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
refactor(share): move the share subsystem into trilium-core
Claude0b6d44c539cf
diff --git a/apps/server/package.json b/apps/server/package.jsonindex 3a74da0938..7ad6096d60 100644--- a/apps/server/package.json+++ b/apps/server/package.json@@ -60,7 +60,6 @@"@types/html": "1.0.4","@types/ini": "4.1.1","@types/multer": "2.2.0",- "@types/safe-compare": "1.1.2","@types/serve-favicon": "2.5.7","@types/serve-static": "2.2.0","@types/supertest": "7.2.1",@@ -105,4 +104,4 @@"vite": "8.3.0","yauzl": "3.4.0"}-}\ No newline at end of file+}diff --git a/apps/server/spec/setup.ts b/apps/server/spec/setup.tsindex 64bdb4cf83..daf21ac000 100644--- a/apps/server/spec/setup.ts+++ b/apps/server/spec/setup.ts@@ -13,6 +13,7 @@ import NodejsInAppHelpProvider from "../src/in_app_help_provider.js";import { initializeTranslationsWithParams } from "../src/services/i18n.js";import ServerLogService from "../src/log_provider.js";import { serverImageProvider } from "../src/services/image_provider.js";+import { registerShareProvider } from "../src/share/share_provider.js";// Initialize environment variables.process.env.TRILIUM_DATA_DIR = join(__dirname, "db");@@ -50,4 +51,7 @@ beforeAll(async () => {log: new ServerLogService(),image: serverImageProvider});++ // The share specs render real share-theme templates, which the provider reads from disk.+ registerShareProvider();});diff --git a/apps/server/src/services/export/zip/share_theme.spec.ts b/apps/server/src/services/export/zip/share_theme.spec.tsindex 00874d3f49..a5f6796e85 100644--- a/apps/server/src/services/export/zip/share_theme.spec.ts+++ b/apps/server/src/services/export/zip/share_theme.spec.ts@@ -19,11 +19,11 @@ const mockAssets = {vi.mock("../../../routes/assets", () => mockAssets);const mockContentRenderer = {- getDefaultTemplatePath: vi.fn((name: string) => `/templates/${name}`),- readTemplate: vi.fn(() => "TEMPLATE"),+ readShareTemplate: vi.fn(() => "TEMPLATE"),renderNoteForExport: vi.fn(() => "<p>rendered</p>")};-vi.mock("../../../share/content_renderer", () => mockContentRenderer);+vi.mock("@triliumnext/core/src/share/index.js", () => mockContentRenderer);+vi.mock("../../../share/share_provider.js", () => ({ registerShareProvider: vi.fn() }));vi.mock("../../resource_dir", () => ({ RESOURCE_DIR: "/resource" }));diff --git a/apps/server/src/services/export/zip/share_theme.ts b/apps/server/src/services/export/zip/share_theme.tsindex f41bd681b4..d2d28fe9b6 100644--- a/apps/server/src/services/export/zip/share_theme.ts+++ b/apps/server/src/services/export/zip/share_theme.ts@@ -6,12 +6,15 @@ import { t } from "i18next";import { join } from "path";import { becca } from "@triliumnext/core";+import { readShareTemplate, renderNoteForExport } from "@triliumnext/core/src/share/index.js";import { getClientDir, getShareThemeAssetDir } from "../../../routes/assets";-import { getDefaultTemplatePath, readTemplate, renderNoteForExport } from "../../../share/content_renderer";+import { registerShareProvider } from "../../../share/share_provider.js";import { getLog } from "@triliumnext/core";import { RESOURCE_DIR } from "../../resource_dir";import { getResourceDir, isDev } from "../../utils";+registerShareProvider();+const shareThemeAssetDir = getShareThemeAssetDir();interface SearchIndexEntry {@@ -181,8 +184,7 @@ export default class ShareThemeExportProvider extends ZipExportProvider {}#save404() {- const templatePath = getDefaultTemplatePath("404");- const content = ejs.render(readTemplate(templatePath), { t });+ const content = ejs.render(readShareTemplate("404"), { t });this.archive.append(content, { name: "404.html" });}diff --git a/apps/server/src/share/routes.spec.ts b/apps/server/src/share/routes.spec.tsindex 97d0ad74ae..5964a17c68 100644--- a/apps/server/src/share/routes.spec.ts+++ b/apps/server/src/share/routes.spec.ts@@ -140,7 +140,7 @@ describe("Share API test", () => {// A note cloned both under the share tree and elsewhere can surface with a// best note path that never passes through the requested ancestor — such a// result must be treated as not visible.- const { isVisibleInShareTree } = await import("./routes.js");+ const { isVisibleInShareTree } = await import("@triliumnext/core/src/share/index.js");expect(isVisibleInShareTree(SHARE_ROOT_ID, ["root", "someUnsharedNote"])).toBe(false);});diff --git a/apps/server/src/share/routes.ts b/apps/server/src/share/routes.tsindex b7d4b83a41..09f0edc2d5 100644--- a/apps/server/src/share/routes.ts+++ b/apps/server/src/share/routes.ts@@ -1,477 +1,48 @@-import { isImageAttachmentRole, isSvgMime, NOTE_TYPE_IMAGE_ATTACHMENTS } from "@triliumnext/commons";-import { search as searchService, SearchContext, utils } from "@triliumnext/core";-import type { NextFunction, Request, Response, Router } from "express";-import safeCompare from "safe-compare";+import { getShareRoutes, handleShareRequest, type ShareReply, type ShareRequest } from "@triliumnext/core/src/share/index.js";+import type { Request, Response, Router } from "express";-import { getDefaultTemplatePath, renderNoteContent } from "./content_renderer.js";-import type SAttachment from "./shaca/entities/sattachment.js";-import type SNote from "./shaca/entities/snote.js";-import shaca from "./shaca/shaca.js";-import shacaLoader from "./shaca/shaca_loader.js";-import { isShareDbReady } from "./sql.js";+import { registerShareProvider } from "./share_provider.js";-function assertShareDbReady(_req: Request, res: Response, next: NextFunction) {- if (!isShareDbReady()) {- res.status(503).send("The application is still initializing. Please try again in a moment.");- return;- }-- next();-}--function addNoIndexHeader(note: SNote, res: Response) {- if (note.isLabelTruthy("shareDisallowRobotIndexing")) {- res.setHeader("X-Robots-Tag", "noindex");- }-}--function requestCredentials(res: Response) {- res.setHeader("WWW-Authenticate", 'Basic realm="User Visible Realm", charset="UTF-8"').sendStatus(401);-}--function checkAttachmentAccess(attachmentId: string, req: Request, res: Response) {- const attachment = shaca.getAttachment(attachmentId);-- if (!attachment) {- res.status(404).json({ message: `Attachment '${attachmentId}' not found.` });-- return false;- }-- const note = checkNoteAccess(attachment.ownerId, req, res);-- if (!note) {- return false;- }-- // Protected notes cannot be shared, and neither can their attachments- // (GHSA-xmv9-3v98-7gq8).- if (rejectProtected(note, res, `Attachment '${attachmentId}' not found.`)) {- return false;- }-- return attachment;-}--function checkNoteAccess(noteId: string, req: Request, res: Response) {- const note = shaca.getNote(noteId);-- if (!note) {- res.status(404).json({ message: `Note '${noteId}' not found.` });-- return false;- }-- if (noteId === "_share" && !shaca.shareIndexEnabled) {- res.status(403).json({ message: `Accessing share index is forbidden.` });-- return false;- }-- if (!hasCredentialAccess(note, req)) {- return false;- }-- return note;-}--// Returns true when the request is allowed to read the given note: either the-// note (including inherited attributes) carries no shareCredentials, or the-// request presents matching HTTP Basic credentials. Pure predicate — does not-// touch the response, so it can also be reused to filter search results.-function hasCredentialAccess(note: SNote, req: Request) {- const credentials = note.getCredentials();-- if (credentials.length === 0) {- return true;- }-- const header = req.header("Authorization");-- if (!header?.startsWith("Basic ")) {- return false;- }-- const base64Str = header.substring("Basic ".length);- const buffer = Buffer.from(base64Str, "base64");- const authString = buffer.toString("utf-8");-- return credentials.some((credentialLabel) => safeCompare(authString, credentialLabel.value));-}--// Returns true when the note reached via `notePathArray` is actually visible in-// the public share tree below `ancestorNoteId`: every hop from the ancestor down-// to the note must be a non-hidden branch whose child note is not-// `shareHiddenFromTree`. Mirrors SNote.getVisibleChildBranches() so that search-// cannot enumerate notes the navigation tree deliberately hides. Exported for-// tests: a clone's best note path can bypass the share subtree entirely, which-// is impractical to stage through the full search stack.-export function isVisibleInShareTree(ancestorNoteId: string, notePathArray: string[]) {- const startIndex = notePathArray.indexOf(ancestorNoteId);-- if (startIndex < 0) {- return false;- }-- for (let i = startIndex + 1; i < notePathArray.length; i++) {- const childNote = shaca.notes[notePathArray[i]];- const branch = shaca.getBranchFromChildAndParent(notePathArray[i], notePathArray[i - 1]);-- if (!childNote || !branch || branch.isHidden || childNote.isLabelTruthy("shareHiddenFromTree")) {- return false;- }- }-- return true;-}--// Like checkNoteAccess, but additionally refuses protected notes. Used by the-// routes that stream a note's raw content/images: a protected note still shows-// up as "[protected]" in the shared tree (handled by content_renderer.ts), but-// its actual bytes must never be served anonymously (GHSA-xmv9-3v98-7gq8).-function checkNoteContentAccess(noteId: string, req: Request, res: Response) {- const note = checkNoteAccess(noteId, req, res);-- if (!note) {- return false;- }+/** Mounts the share routes on the Express router, one adapter per transport-neutral core handler. */+function register(router: Router) {+ registerShareProvider();- if (rejectProtected(note, res, `Note '${noteId}' not found.`)) {- return false;+ for (const route of getShareRoutes()) {+ router.get(route.path, (req, res) => {+ send(res, handleShareRequest(route, toShareRequest(req)));+ });}-- return note;}-// Sends a 404 and returns true when the note is protected, so callers can bail.-function rejectProtected(note: SNote, res: Response, message: string) {- if (!note.isProtected) {- return false;- }-- res.status(404).json({ message });-- return true;+function toShareRequest(req: Request): ShareRequest {+ return {+ path: req.path,+ // Express types a repeated path parameter as an array; the share patterns declare each of+ // theirs once, so every match here is a single segment.+ params: req.params as Record<string, string | undefined>,+ query: req.query as Record<string, string | string[] | undefined>,+ getHeader: (name: string) => req.header(name)+ };}-function renderImageAttachment(image: SNote, res: Response, attachmentName: string) {- let svgString = "<svg/>";- const attachment = image.getAttachmentByTitle(attachmentName);- if (!attachment) {+function send(res: Response, reply: ShareReply) {+ if (reply.redirect) {+ res.redirect(reply.redirect);return;}- const content = attachment.getContent();- if (typeof content === "string") {- svgString = content;- } else {- // backwards compatibility, before attachments, the SVG was stored in the main note content as a separate key- const possibleSvgContent = image.getJsonContentSafely();-- const contentSvg = (typeof possibleSvgContent === "object"- && possibleSvgContent !== null- && "svg" in possibleSvgContent- && typeof possibleSvgContent.svg === "string")- ? possibleSvgContent.svg- : null;- if (contentSvg) {- svgString = contentSvg;- }+ for (const [name, value] of Object.entries(reply.headers)) {+ res.setHeader(name, value);}- const svg = utils.sanitizeSvg(svgString);- res.set("Content-Type", "image/svg+xml");- res.set("Cache-Control", "no-cache, no-store, must-revalidate");- res.set("Content-Security-Policy", utils.SVG_CONTENT_SECURITY_POLICY);- res.set("X-Content-Type-Options", "nosniff");- res.send(svg);-}--function render404(res: Response) {- res.status(404);- const shareThemePath = getDefaultTemplatePath("404");- res.render(shareThemePath);-}--function register(router: Router) {- // Guard: if the share DB is not yet initialized, return 503 for all /share routes.- router.use("/share", assertShareDbReady);-- function renderNote(note: SNote, req: Request, res: Response) {- if (!note) {- console.log("Unable to find note ", note);- res.status(404);- render404(res);- return;- }-- if (!checkNoteAccess(note.noteId, req, res)) {- requestCredentials(res);-- return;- }-- addNoIndexHeader(note, res);-- if (note.isLabelTruthy("shareRaw") || typeof req.query.raw !== "undefined") {- // A protected note is shown as a placeholder by renderNoteContent()- // below, but the raw branch streams note.getContent() directly, so it- // must refuse protected notes (GHSA-xmv9-3v98-7gq8).- if (note.isProtected) {- render404(res);-- return;- }-- // For SVG content, add a restrictive Content-Security-Policy to prevent- // stored XSS via script execution (CWE-79). HTML is intentionally served- // unrestricted here: serving raw HTML requires the `#shareRaw` attribute (or an- // explicit `?raw`), and `#shareRaw` is flagged dangerous (see builtin_attributes.ts),- // so the instance owner is deliberately opting in to serve their own scriptable- // content. Restricting it would break legitimate self-contained HTML pages.- if (isSvgMime(note.mime)) {- res.setHeader("Content-Security-Policy", utils.SVG_CONTENT_SECURITY_POLICY);- res.setHeader("X-Content-Type-Options", "nosniff");- }-- res.setHeader("Content-Type", note.mime).send(note.getContent());+ if (reply.body === undefined) {+ res.sendStatus(reply.status);- return;- }-- res.send(renderNoteContent(note, (includedNote) => hasCredentialAccess(includedNote, req)));+ return;}- router.get("/share/", (req, res) => {- if (req.path.substr(-1) !== "/") {- res.redirect("../share/");- return;- }-- shacaLoader.ensureLoad();-- if (!shaca.shareRootNote) {- res.status(404).json({ message: "Share root note not found" });- return;- }-- renderNote(shaca.shareRootNote, req, res);- });-- router.get("/share/:shareId", (req, res) => {- shacaLoader.ensureLoad();-- const { shareId } = req.params;-- const note = shaca.aliasToNote[shareId] || shaca.notes[shareId];-- renderNote(note, req, res);- });-- router.get("/share/api/notes/:noteId", (req, res) => {- shacaLoader.ensureLoad();- let note: SNote | boolean;-- if (!(note = checkNoteAccess(req.params.noteId, req, res))) {- return;- }-- addNoIndexHeader(note, res);-- res.json(note.getPojo());- });-- router.get("/share/api/notes/:noteId/download", (req, res) => {- shacaLoader.ensureLoad();-- let note: SNote | boolean;-- if (!(note = checkNoteContentAccess(req.params.noteId, req, res))) {- return;- }-- addNoIndexHeader(note, res);-- const filename = utils.formatDownloadTitle(note.title, note.type, note.mime);-- res.setHeader("Content-Disposition", utils.getContentDisposition(filename));-- res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");- res.setHeader("Content-Type", note.mime);-- res.send(note.getContent());- });-- // :filename is not used by trilium, but instead used for "save as" to assign a human-readable filename- router.get("/share/api/images/:noteId/:filename", (req, res) => {- shacaLoader.ensureLoad();-- let image: SNote | boolean;-- if (!(image = checkNoteContentAccess(req.params.noteId, req, res))) {- return;- }-- if (image.type === "image") {- addNoIndexHeader(image, res);- if (isSvgMime(image.mime)) {- // SVG images require sanitization to prevent stored XSS- const content = image.getContent();- const svgContent = typeof content === "string" ? content : new TextDecoder().decode(content ?? new Uint8Array());- const sanitized = utils.sanitizeSvg(svgContent);- res.set("Content-Type", "image/svg+xml");- res.set("Cache-Control", "no-cache, no-store, must-revalidate");- res.set("Content-Security-Policy", utils.SVG_CONTENT_SECURITY_POLICY);- res.set("X-Content-Type-Options", "nosniff");- res.send(sanitized);- } else {- res.set("Content-Type", image.mime);- res.send(image.getContent());- }- } else if (image.type === "canvas") {- renderImageAttachment(image, res, NOTE_TYPE_IMAGE_ATTACHMENTS.canvas);- } else if (image.type === "mermaid") {- renderImageAttachment(image, res, NOTE_TYPE_IMAGE_ATTACHMENTS.mermaid);- } else if (image.type === "mindMap") {- renderImageAttachment(image, res, NOTE_TYPE_IMAGE_ATTACHMENTS.mindMap);- } else {- res.status(400).json({ message: "Requested note is not a shareable image" });- }- });-- // :filename is not used by trilium, but instead used for "save as" to assign a human-readable filename- router.get("/share/api/attachments/:attachmentId/image/:filename", (req, res) => {- shacaLoader.ensureLoad();-- let attachment: SAttachment | boolean;-- if (!(attachment = checkAttachmentAccess(req.params.attachmentId, req, res))) {- return;- }-- if (isImageAttachmentRole(attachment.role)) {- addNoIndexHeader(attachment.note, res);- if (isSvgMime(attachment.mime)) {- // SVG attachments require sanitization to prevent stored XSS- const content = attachment.getContent();- const svgContent = typeof content === "string" ? content : new TextDecoder().decode(content ?? new Uint8Array());- const sanitized = utils.sanitizeSvg(svgContent);- res.set("Content-Type", "image/svg+xml");- res.set("Cache-Control", "no-cache, no-store, must-revalidate");- res.set("Content-Security-Policy", utils.SVG_CONTENT_SECURITY_POLICY);- res.set("X-Content-Type-Options", "nosniff");- res.send(sanitized);- } else {- res.set("Content-Type", attachment.mime);- res.send(attachment.getContent());- }- } else {- res.status(400).json({ message: "Requested attachment is not a shareable image" });- }- });-- router.get("/share/api/attachments/:attachmentId/download", (req, res) => {- shacaLoader.ensureLoad();-- let attachment: SAttachment | boolean;-- if (!(attachment = checkAttachmentAccess(req.params.attachmentId, req, res))) {- return;- }-- addNoIndexHeader(attachment.note, res);-- const filename = utils.formatDownloadTitle(attachment.title, null, attachment.mime);-- res.setHeader("Content-Disposition", utils.getContentDisposition(filename));-- res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");- res.setHeader("Content-Type", attachment.mime);-- res.send(attachment.getContent());- });-- // used for PDF viewing- router.get("/share/api/notes/:noteId/view", (req, res) => {- shacaLoader.ensureLoad();-- let note: SNote | boolean;-- if (!(note = checkNoteContentAccess(req.params.noteId, req, res))) {- return;- }-- addNoIndexHeader(note, res);-- res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");- res.setHeader("Content-Type", note.mime);-- res.send(note.getContent());- });-- // Used for searching, require noteId so we know the subTreeRoot- router.get("/share/api/notes", (req, res) => {- shacaLoader.ensureLoad();-- const ancestorNoteId = req.query.ancestorNoteId ?? "_share";-- if (typeof ancestorNoteId !== "string") {- res.status(400).json({ message: "'ancestorNoteId' parameter is mandatory." });- return;- }-- // This will automatically return if no ancestorNoteId is provided and there is no shareIndex- if (!checkNoteAccess(ancestorNoteId, req, res)) {- return;- }-- const { search } = req.query;-- if (typeof search !== "string" || !search?.trim()) {- res.status(400).json({ message: "'search' parameter is mandatory." });- return;- }-- 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: 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);- });-- // 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);-- const filteredResults = authorizedResults.map((sr) => {- const fullNote = shaca.notes[sr.noteId];- const startIndex = sr.notePathArray.indexOf(ancestorNoteId);- const localPathArray = sr.notePathArray.slice(startIndex + 1).filter((id) => shaca.notes[id]);- const pathTitle = localPathArray.map((id) => shaca.notes[id].title).join(" / ");- return {- id: fullNote.shareId,- title: fullNote.title,- score: sr.score,- path: pathTitle,- // Plain-text fallback and the <b>-highlighted variant from the search service.- snippet: sr.contentSnippet,- highlightedSnippet: sr.highlightedContentSnippet- };- });-- res.json({ results: filteredResults });- });+ res.status(reply.status).send(reply.body instanceof Uint8Array ? Buffer.from(reply.body) : reply.body);}export default {diff --git a/apps/server/src/share/share_provider.ts b/apps/server/src/share/share_provider.tsnew file mode 100644index 0000000000..df13f0d64a--- /dev/null+++ b/apps/server/src/share/share_provider.ts@@ -0,0 +1,49 @@+import { initShare } from "@triliumnext/core/src/share/index.js";+import { readFileSync } from "fs";+import { join } from "path";++import { isScriptingEnabled } from "../services/scripting_guard.js";+import { getResourceDir } from "../services/utils.js";+import sql, { isShareDbReady } from "./sql.js";++const templateCache: Map<string, string> = new Map();+let registered = false;++/**+ * Registers what the share subsystem needs from this platform: rows over the read-only connection+ * `sql.ts` opens beside the main one, and the share theme's templates from disk. Both the share+ * routes and the share-theme export call this, so it runs whichever of them is reached first.+ */+export function registerShareProvider() {+ if (registered) {+ return;+ }++ initShare({+ sql,+ readTemplate,+ isScriptingEnabled,+ isReady: isShareDbReady+ });+ registered = true;+}++function readTemplate(name: string) {+ const path = getDefaultTemplatePath(name);+ const cachedTemplate = templateCache.get(path);++ if (cachedTemplate) {+ return cachedTemplate;+ }++ const templateString = readFileSync(path, "utf-8");+ templateCache.set(path, templateString);++ return templateString;+}++function getDefaultTemplatePath(template: string) {+ return process.env.NODE_ENV === "development"+ ? join(__dirname, `../../../../packages/share-theme/src/templates/${template}.ejs`)+ : join(getResourceDir(), `share-theme/templates/${template}.ejs`);+}diff --git a/apps/server/src/share/sql.ts b/apps/server/src/share/sql.tsindex e14483ec6a..4f4f800480 100644--- a/apps/server/src/share/sql.ts+++ b/apps/server/src/share/sql.ts@@ -56,7 +56,7 @@ function assertDbReady(): void {}}-function getRawRows<T>(query: string, params = []): T[] {+function getRawRows<T>(query: string, params: string[] = []): T[] {assertDbReady();return dbConnection.prepare(query).raw().all(params) as T[];}diff --git a/packages/trilium-core/package.json b/packages/trilium-core/package.jsonindex d7ae72f923..0b15c1c0fc 100644--- a/packages/trilium-core/package.json+++ b/packages/trilium-core/package.json@@ -13,11 +13,13 @@"@ai-sdk/openai": "4.0.67","@braintree/sanitize-url": "7.1.2","@triliumnext/commons": "workspace:*",+ "@triliumnext/highlightjs": "workspace:*","@triliumnext/turndown-plugin-gfm": "workspace:*","ai": "7.0.102","async-mutex": "0.5.0","chardet": "2.2.0","color": "5.0.3",+ "ejs": "6.0.1","escape-html": "1.0.3","i18next": "26.4.2","js-yaml": "5.4.2",@@ -35,9 +37,10 @@"zod": "4.6.5"},"devDependencies": {+ "@types/ejs": "3.1.5","@types/escape-html": "1.0.4","@types/mime-types": "3.0.1","@types/sanitize-html": "2.16.1","@types/xml2js": "0.4.14"}-}\ No newline at end of file+}diff --git a/apps/server/src/share/content_renderer.spec.ts b/packages/trilium-core/src/share/content_renderer.spec.tssimilarity index 98%rename from apps/server/src/share/content_renderer.spec.tsrename to packages/trilium-core/src/share/content_renderer.spec.tsindex 04a4744b7a..299bcdc530 100644--- a/apps/server/src/share/content_renderer.spec.ts+++ b/packages/trilium-core/src/share/content_renderer.spec.ts@@ -1,11 +1,12 @@import { trimIndentation } from "@triliumnext/commons";-import { sanitize, utils } from "@triliumnext/core";import ejs from "ejs";import { parse } from "node-html-parser";import { describe, expect, it, vi } from "vitest";+import * as sanitize from "../services/sanitizer.js";+import * as utils from "../services/utils/index.js";import { buildShareNote, buildShareNotes } from "../test/shaca_mocking.js";-import { getContent, getDefaultTemplatePath, readTemplate, renderCode, renderNoteContent, type Result, shouldSyntaxHighlight } from "./content_renderer.js";+import { getContent, readShareTemplate, renderCode, renderNoteContent, type Result, shouldSyntaxHighlight } from "./content_renderer.js";import type SNote from "./shaca/entities/snote.js";import shaca from "./shaca/shaca.js";import shareRoot from "./share_root.js";@@ -674,7 +675,7 @@ describe("content_renderer", () => {const note = buildShareNote(noteDef);const subRootNote = buildShareNote({ id: `subRoot-${noteDef.id}` });- const html = ejs.render(readTemplate(getDefaultTemplatePath("tree_item")), {+ const html = ejs.render(readShareTemplate("tree_item"), {note,activeNote: subRootNote,subRoot: { note: subRootNote },@@ -719,7 +720,7 @@ describe("content_renderer", () => {const note = shaca.getNote(noteId);const { header, content, isEmpty } = getContent(note);- const html = ejs.render(readTemplate(getDefaultTemplatePath("page")), {+ const html = ejs.render(readShareTemplate("page"), {note,header,content,@@ -743,7 +744,7 @@ describe("content_renderer", () => {iconPackSupportedPrefixes: []}, {includer: (path: string) => ({- template: readTemplate(getDefaultTemplatePath(path))+ template: readShareTemplate(path)})});diff --git a/apps/server/src/share/content_renderer.ts b/packages/trilium-core/src/share/content_renderer.tssimilarity index 95%rename from apps/server/src/share/content_renderer.tsrename to packages/trilium-core/src/share/content_renderer.tsindex 725322bc6e..99309e6a2d 100644--- a/apps/server/src/share/content_renderer.ts+++ b/packages/trilium-core/src/share/content_renderer.ts@@ -1,26 +1,34 @@import { extractYouTubeVideoId, isHttpUrl, safeLinkPreviewHref, safeLinkPreviewImageSrc } from "@triliumnext/commons";import { renderToHtml as renderMarkdownToHtml } from "@triliumnext/commons/src/lib/markdown_renderer.js";import { renderSpreadsheetToHtml } from "@triliumnext/commons/src/lib/spreadsheet/render_to_html.js";-import { type BAttachment, type BBranch, becca, BNote, getLog, icon_packs as iconPackService, options, sanitize, task_states, utils } from "@triliumnext/core";import { highlightAuto } from "@triliumnext/highlightjs";import ejs from "ejs";import escapeHtml from "escape-html";-import { readFileSync } from "fs";import { t } from "i18next";import { HTMLElement, Options, parse, TextNode } from "node-html-parser";-import { join } from "path";-import assetPath, { assetUrlFragment } from "../services/asset_path.js";-import { isScriptingEnabled } from "../services/scripting_guard.js";-import { getResourceDir, isDev } from "../services/utils.js";+import becca from "../becca/becca.js";+import type BAttachment from "../becca/entities/battachment.js";+import type BBranch from "../becca/entities/bbranch.js";+import BNote from "../becca/entities/bnote.js";+import appInfo from "../services/app_info.js";+import * as iconPackService from "../services/icon_packs.js";+import { getLog } from "../services/log.js";+import options from "../services/options.js";+import * as sanitize from "../services/sanitizer.js";+import * as task_states from "../services/task_states.js";+import * as utils from "../services/utils/index.js";+import { getShareProvider } from "./share_provider.js";import SAttachment from "./shaca/entities/sattachment.js";import SBranch from "./shaca/entities/sbranch.js";import type SNote from "./shaca/entities/snote.js";import shaca from "./shaca/shaca.js";import shareRoot from "./share_root.js";-const shareAdjustedAssetPath = isDev ? assetPath : `../${assetPath}`;-const templateCache: Map<string, string> = new Map();+/**+ * The URL prefix the share theme resolves built-in assets against, such as `assets/v1.2.3`.+ */+export const assetUrlFragment = `assets/v${appInfo.appVersion}`;/*** Maximum number of lines a code block may have before server-side syntax highlighting is skipped.@@ -219,11 +227,11 @@ function renderNoteContentInternal(note: SNote | BNote, renderArgs: RenderArgs)header,content,isEmpty,- assetPath: shareAdjustedAssetPath,+ assetPath: getShareAssetPath(),assetUrlFragment,showLoginInShareTheme,t,- isDev,+ isDev: utils.isDev(),utils,sanitizeUrl: sanitize.sanitizeUrl,...renderArgs,@@ -231,7 +239,7 @@ function renderNoteContentInternal(note: SNote | BNote, renderArgs: RenderArgs)// Check if the user has their own template.// Skip user-provided EJS templates when backend scripting is disabled since EJS can execute arbitrary JS.- if (note.hasRelation("shareTemplate") && isScriptingEnabled()) {+ if (note.hasRelation("shareTemplate") && getShareProvider().isScriptingEnabled()) {// Get the template note and contentconst templateId = note.getRelation("shareTemplate")?.value;const templateNote = templateId && shaca.getNote(templateId);@@ -264,31 +272,25 @@ function renderNoteContentInternal(note: SNote | BNote, renderArgs: RenderArgs)}// Render with the default view otherwise.- const templatePath = getDefaultTemplatePath("page");- return ejs.render(readTemplate(templatePath), opts, {- includer: (path) => {- // Path is relative to apps/server/dist/assets/views- return { template: readTemplate(getDefaultTemplatePath(path)) };- }+ return ejs.render(readShareTemplate("page"), opts, {+ includer: (path) => ({ template: readShareTemplate(path) })});}-export function getDefaultTemplatePath(template: string) {- // Path is relative to apps/server/dist/assets/views- return process.env.NODE_ENV === "development"- ? join(__dirname, `../../../../packages/share-theme/src/templates/${template}.ejs`)- : join(getResourceDir(), `share-theme/templates/${template}.ejs`);+/**+ * Returns the share theme's EJS template of that name, such as `page` or `404`. The platform+ * decides where it comes from: the server reads it from disk, the browser build from its bundle.+ */+export function readShareTemplate(name: string) {+ return getShareProvider().readTemplate(name);}-export function readTemplate(path: string) {- const cachedTemplate = templateCache.get(path);- if (cachedTemplate) {- return cachedTemplate;- }-- const templateString = readFileSync(path, "utf-8");- templateCache.set(path, templateString);- return templateString;+/**+ * Returns the prefix the share theme resolves built-in assets against. The share pages live one+ * path segment deeper than the app, so outside dev the prefix climbs back out of `/share/`.+ */+function getShareAssetPath() {+ return utils.isDev() ? `${assetUrlFragment}/src` : `../${assetUrlFragment}`;}/**diff --git a/packages/trilium-core/src/share/handlers.spec.ts b/packages/trilium-core/src/share/handlers.spec.tsnew file mode 100644index 0000000000..5f6a7f2342--- /dev/null+++ b/packages/trilium-core/src/share/handlers.spec.ts@@ -0,0 +1,170 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++import { encodeBase64 } from "../services/utils/binary.js";+import { buildShareNote } from "../test/shaca_mocking.js";+import { getShareRoute, handleShareRequest, type ShareRequest } from "./handlers.js";+import { SHARE_ROUTE_PATHS, type ShareRoutePath } from "./route_paths.js";+import shareRoot from "./share_root.js";+import shaca from "./shaca/shaca.js";++vi.mock("../becca/becca_loader.js", () => ({+ default: {+ load: vi.fn(),+ loaded: Promise.resolve()+ }+}));++describe("share handlers", () => {+ beforeEach(() => {+ shaca.reset();+ // Marked loaded so shacaLoader.ensureLoad() leaves the tree each test builds by hand alone,+ // rather than replacing it with whatever the database holds.+ shaca.loaded = true;+ });++ it("addresses the share root by trailing slash and redirects the bare path to it", () => {+ expect(request("/share/", { path: "/share" })).toMatchObject({ status: 302, redirect: "../share/" });+ expect(request("/share/", { path: "/share/" })).toMatchObject({ status: 404 });++ buildShareTree([ {+ id: "landingNote",+ title: "Landing",+ content: "<p>Landing</p>",+ "#shareRoot": "",+ children: [ { id: "child", title: "Child", content: "<p>Child</p>" } ]+ } ]);+ expect(shaca.shareRootNote?.noteId).toBe("landingNote");++ const reply = request("/share/", { path: "/share/" });+ expect(reply.status).toBe(200);+ expect(String(reply.body)).toContain("Landing");+ });++ it("renders a shared note as HTML and serves its raw content when asked", () => {+ buildShareTree([ { id: "plainNote", title: "Plain", content: "<p>Hello</p>", "#shareAlias": "my-alias" } ]);+ shaca.aliasToNote["my-alias"] = shaca.getNote("plainNote");++ const rendered = request("/share/:shareId", { params: { shareId: "my-alias" } });+ expect(rendered.status).toBe(200);+ expect(rendered.headers["Content-Type"]).toBe("text/html; charset=utf-8");+ expect(String(rendered.body)).toContain("Hello");++ const raw = request("/share/:shareId", { params: { shareId: "plainNote" }, query: { raw: "" } });+ expect(raw.status).toBe(200);+ expect(raw.headers["Content-Type"]).toBe("text/html");+ expect(raw.body).toBe("<p>Hello</p>");+ });++ it("refuses a protected note's bytes on every route that streams them (GHSA-xmv9-3v98-7gq8)", () => {+ buildShareTree([+ { id: "lockedUp", content: "<p>classified body</p>", isProtected: true },+ { id: "openNote", content: "<p>public body</p>" }+ ]);++ for (const path of [+ "/share/api/notes/:noteId/download",+ "/share/api/notes/:noteId/view",+ "/share/api/images/:noteId/:filename"+ ] as const) {+ const refused = request(path, { params: { noteId: "lockedUp", filename: "x.png" } });+ expect(refused.status, path).toBe(404);+ expect(String(refused.body), path).not.toContain("classified");++ // The same route on an unprotected sibling does serve the bytes, so the 404 above is+ // the protection refusing it rather than the route being unreachable. The image route+ // is the exception: a text note is not an image, which it answers 400 to.+ const served = request(path, { params: { noteId: "openNote", filename: "x.png" } });+ expect(served.status, path).toBe(path.includes("/images/") ? 400 : 200);+ if (served.status === 200) {+ expect(String(served.body), path).toContain("public body");+ }+ }++ // `?raw` would otherwise stream the same bytes the routes above refuse.+ const raw = request("/share/:shareId", { params: { shareId: "lockedUp" }, query: { raw: "" } });+ expect(raw.status).toBe(404);+ expect(String(raw.body)).not.toContain("classified");++ expect(request("/share/:shareId", { params: { shareId: "openNote" }, query: { raw: "" } }).body).toBe("<p>public body</p>");+ });++ it("asks for credentials until matching HTTP Basic ones arrive", () => {+ buildShareTree([ { id: "lockedNote", content: "<p>classified</p>", "#shareCredentials": "root:hunter2" } ]);++ const anonymous = request("/share/api/notes/:noteId", { params: { noteId: "lockedNote" } });+ expect(anonymous.status).toBe(401);+ expect(anonymous.headers["WWW-Authenticate"]).toContain("Basic realm=");+ expect(anonymous.body).toBeUndefined();++ const wrong = request("/share/api/notes/:noteId", {+ params: { noteId: "lockedNote" },+ headers: { authorization: `Basic ${encodeBase64("root:nope")}` }+ });+ expect(wrong.status).toBe(401);++ const right = request("/share/api/notes/:noteId", {+ params: { noteId: "lockedNote" },+ headers: { authorization: `Basic ${encodeBase64("root:hunter2")}` }+ });+ expect(right.status).toBe(200);+ expect(JSON.parse(String(right.body)).noteId).toBe("lockedNote");+ });++ it("sanitizes an SVG note and locks it down with a content security policy", () => {+ buildShareTree([ {+ id: "svgNote",+ type: "image",+ mime: "image/svg+xml",+ content: `<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>`+ } ]);++ const reply = request("/share/api/images/:noteId/:filename", { params: { noteId: "svgNote", filename: "x.svg" } });+ expect(reply.status).toBe(200);+ expect(reply.headers["Content-Type"]).toBe("image/svg+xml");+ expect(reply.headers["Content-Security-Policy"]).toContain("default-src 'none'");+ expect(String(reply.body)).not.toContain("<script>");+ });++ it("marks a note that opts out of robot indexing, and only that note", () => {+ buildShareTree([+ { id: "indexedNote", content: "<p>a</p>" },+ { id: "unindexedNote", content: "<p>b</p>", "#shareDisallowRobotIndexing": "true" }+ ]);++ expect(request("/share/:shareId", { params: { shareId: "unindexedNote" } }).headers["X-Robots-Tag"]).toBe("noindex");+ expect(request("/share/:shareId", { params: { shareId: "indexedNote" } }).headers).not.toHaveProperty("X-Robots-Tag");+ });++ it("answers 404 for an unknown note and refuses the share index while it is disabled", () => {+ const missing = request("/share/:shareId", { params: { shareId: "nothingHere" } });+ expect(missing.status).toBe(404);+ expect(String(missing.body)).toContain("<html");++ buildShareTree([]);+ shaca.shareIndexEnabled = false;+ expect(request("/share/api/notes/:noteId", { params: { noteId: shareRoot.SHARE_ROOT_NOTE_ID } }).status).toBe(403);+ });++ it("declares one handler per published route path", () => {+ for (const path of SHARE_ROUTE_PATHS) {+ expect(typeof getShareRoute(path).handle, path).toBe("function");+ }+ });+});++/** Builds the `_share` subtree the renderer walks up to, and returns its root. */+function buildShareTree(children: Parameters<typeof buildShareNote>[0][]) {+ return buildShareNote({ id: shareRoot.SHARE_ROOT_NOTE_ID, title: "Shared Notes", content: "", children });+}++function request(path: ShareRoutePath, overrides: Partial<ShareRequest> & { headers?: Record<string, string> } = {}) {+ const { headers = {}, ...rest } = overrides;++ return handleShareRequest(getShareRoute(path), {+ path: `/share/${path}`,+ params: {},+ query: {},+ getHeader: (name: string) => headers[name.toLowerCase()],+ ...rest+ });+}diff --git a/packages/trilium-core/src/share/handlers.ts b/packages/trilium-core/src/share/handlers.tsnew file mode 100644index 0000000000..8fa836e013--- /dev/null+++ b/packages/trilium-core/src/share/handlers.ts@@ -0,0 +1,495 @@+import { isImageAttachmentRole, isSvgMime, NOTE_TYPE_IMAGE_ATTACHMENTS } from "@triliumnext/commons";+import ejs from "ejs";+import { t } from "i18next";++import { getCrypto } from "../services/encryption/crypto.js";+import searchService from "../services/search/services/search.js";+import SearchContext from "../services/search/search_context.js";+import { decodeBase64, decodeUtf8, encodeUtf8 } from "../services/utils/binary.js";+import * as utils from "../services/utils/index.js";+import { readShareTemplate, renderNoteContent } from "./content_renderer.js";+import { SHARE_ROUTE_PATHS, type ShareRoutePath } from "./route_paths.js";+import { isShareReady } from "./share_provider.js";+import type SAttachment from "./shaca/entities/sattachment.js";+import type SNote from "./shaca/entities/snote.js";+import shaca from "./shaca/shaca.js";+import shacaLoader from "./shaca/shaca_loader.js";++/** A share request, reduced to what the handlers read, so both Express and the browser can supply it. */+export interface ShareRequest {+ /** The full request path, such as `/share/my-alias`. */+ path: string;+ params: Record<string, string | undefined>;+ query: Record<string, string | string[] | undefined>;+ /** Returns the named request header, or `undefined` when the caller did not send it. */+ getHeader(name: string): string | undefined;+}++/** What a handler answers with, for the caller's transport to write out. */+export interface ShareReply {+ status: number;+ headers: Record<string, string>;+ /** Absent on a reply that carries none, such as a redirect. */+ body?: string | Uint8Array;+ /** Where to send the caller, instead of a body. */+ redirect?: string;+}++export interface ShareRoute {+ /** Express-style pattern, such as `/share/api/notes/:noteId`. */+ path: ShareRoutePath;+ handle(req: ShareRequest): ShareReply;+}++/** Returns the share routes, in the order {@link SHARE_ROUTE_PATHS} lays down. */+export function getShareRoutes(): ShareRoute[] {+ return SHARE_ROUTE_PATHS.map((path) => ({ path, handle: HANDLERS[path] }));+}++/** Returns the handler for one share path, for a router that registered the paths on their own. */+export function getShareRoute(path: ShareRoutePath): ShareRoute {+ return { path, handle: HANDLERS[path] };+}++/**+ * Runs a share handler, turning the replies its access checks raise into the handler's own result.+ * Every transport adapter dispatches through this rather than calling {@link ShareRoute.handle}.+ */+export function handleShareRequest(route: ShareRoute, req: ShareRequest): ShareReply {+ if (!isShareReady()) {+ return {+ status: 503,+ headers: { "Content-Type": "text/plain; charset=utf-8" },+ body: "The application is still initializing. Please try again in a moment."+ };+ }++ try {+ shacaLoader.ensureLoad();++ return route.handle(req);+ } catch (e: unknown) {+ if (e instanceof ShareReplyError) {+ return e.reply;+ }++ throw e;+ }+}++const HANDLERS: Record<ShareRoutePath, (req: ShareRequest) => ShareReply> = {+ "/share/api/notes/:noteId/download": downloadNote,+ "/share/api/notes/:noteId/view": viewNote,+ "/share/api/notes/:noteId": getNote,+ "/share/api/notes": searchNotes,+ "/share/api/images/:noteId/:filename": getImage,+ "/share/api/attachments/:attachmentId/image/:filename": getAttachmentImage,+ "/share/api/attachments/:attachmentId/download": downloadAttachment,+ "/share/": getShareRoot,+ "/share/:shareId": getShareNote+};++/** Carries a finished reply out of the access checks, which run several frames below the handler. */+class ShareReplyError extends Error {+ constructor(readonly reply: ShareReply) {+ super(`Share request rejected with ${reply.status}.`);+ }+}++function getShareRoot(req: ShareRequest): ShareReply {+ if (!req.path.endsWith("/")) {+ return { status: 302, headers: {}, redirect: "../share/" };+ }++ if (!shaca.shareRootNote) {+ return jsonReply(404, { message: "Share root note not found" });+ }++ return renderNote(shaca.shareRootNote, req);+}++function getShareNote(req: ShareRequest): ShareReply {+ const shareId = req.params.shareId ?? "";+ const note = shaca.aliasToNote[shareId] || shaca.notes[shareId];++ return renderNote(note, req);+}++function renderNote(note: SNote | undefined, req: ShareRequest): ShareReply {+ if (!note) {+ return render404();+ }++ // Raises the refusal when the caller may not read this note; the note it returns is this one.+ checkNoteAccess(note.noteId, req);++ const headers = noIndexHeaders(note);++ if (note.isLabelTruthy("shareRaw") || typeof req.query.raw !== "undefined") {+ // A protected note is shown as a placeholder by renderNoteContent() below, but the raw+ // branch streams note.getContent() directly, so it must refuse protected notes+ // (GHSA-xmv9-3v98-7gq8).+ if (note.isProtected) {+ return render404();+ }++ // For SVG content, add a restrictive Content-Security-Policy to prevent stored XSS via+ // script execution (CWE-79). HTML is intentionally served unrestricted here: serving raw+ // HTML requires the `#shareRaw` attribute (or an explicit `?raw`), and `#shareRaw` is+ // flagged dangerous (see builtin_attributes.ts), so the instance owner is deliberately+ // opting in to serve their own scriptable content. Restricting it would break legitimate+ // self-contained HTML pages.+ if (isSvgMime(note.mime)) {+ headers["Content-Security-Policy"] = utils.SVG_CONTENT_SECURITY_POLICY;+ headers["X-Content-Type-Options"] = "nosniff";+ }++ headers["Content-Type"] = note.mime;++ return { status: 200, headers, body: note.getContent() };+ }++ headers["Content-Type"] = "text/html; charset=utf-8";++ return {+ status: 200,+ headers,+ body: renderNoteContent(note, (includedNote) => hasCredentialAccess(includedNote, req))+ };+}++function getNote(req: ShareRequest): ShareReply {+ const note = checkNoteAccess(req.params.noteId ?? "", req);++ return jsonReply(200, note.getPojo(), noIndexHeaders(note));+}++function downloadNote(req: ShareRequest): ShareReply {+ const note = checkNoteContentAccess(req.params.noteId ?? "", req);+ const filename = utils.formatDownloadTitle(note.title, note.type, note.mime);++ return {+ status: 200,+ headers: {+ ...noIndexHeaders(note),+ "Content-Disposition": utils.getContentDisposition(filename),+ "Cache-Control": "no-cache, no-store, must-revalidate",+ "Content-Type": note.mime+ },+ body: note.getContent()+ };+}++/** Used for PDF viewing. */+function viewNote(req: ShareRequest): ShareReply {+ const note = checkNoteContentAccess(req.params.noteId ?? "", req);++ return {+ status: 200,+ headers: {+ ...noIndexHeaders(note),+ "Cache-Control": "no-cache, no-store, must-revalidate",+ "Content-Type": note.mime+ },+ body: note.getContent()+ };+}++function getImage(req: ShareRequest): ShareReply {+ const image = checkNoteContentAccess(req.params.noteId ?? "", req);++ switch (image.type) {+ case "image":+ return serveImageBytes(image.getContent(), image.mime, noIndexHeaders(image));+ case "canvas":+ return renderImageAttachment(image, NOTE_TYPE_IMAGE_ATTACHMENTS.canvas);+ case "mermaid":+ return renderImageAttachment(image, NOTE_TYPE_IMAGE_ATTACHMENTS.mermaid);+ case "mindMap":+ return renderImageAttachment(image, NOTE_TYPE_IMAGE_ATTACHMENTS.mindMap);+ default:+ return jsonReply(400, { message: "Requested note is not a shareable image" });+ }+}++function getAttachmentImage(req: ShareRequest): ShareReply {+ const attachment = checkAttachmentAccess(req.params.attachmentId ?? "", req);++ if (!isImageAttachmentRole(attachment.role)) {+ return jsonReply(400, { message: "Requested attachment is not a shareable image" });+ }++ return serveImageBytes(attachment.getContent(), attachment.mime, noIndexHeaders(attachment.note));+}++function downloadAttachment(req: ShareRequest): ShareReply {+ const attachment = checkAttachmentAccess(req.params.attachmentId ?? "", req);+ const filename = utils.formatDownloadTitle(attachment.title, null, attachment.mime);++ return {+ status: 200,+ headers: {+ ...noIndexHeaders(attachment.note),+ "Content-Disposition": utils.getContentDisposition(filename),+ "Cache-Control": "no-cache, no-store, must-revalidate",+ "Content-Type": attachment.mime+ },+ body: attachment.getContent()+ };+}++/** Used for searching; requires a noteId so the subtree root is known. */+function searchNotes(req: ShareRequest): ShareReply {+ const ancestorNoteId = req.query.ancestorNoteId ?? "_share";++ if (typeof ancestorNoteId !== "string") {+ return jsonReply(400, { message: "'ancestorNoteId' parameter is mandatory." });+ }++ // This will automatically return if no ancestorNoteId is provided and there is no shareIndex+ checkNoteAccess(ancestorNoteId, req);++ const { search } = req.query;++ if (typeof search !== "string" || !search.trim()) {+ return jsonReply(400, { message: "'search' parameter is mandatory." });+ }++ 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: 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);+ });++ // 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);++ const filteredResults = authorizedResults.map((sr) => {+ const fullNote = shaca.notes[sr.noteId];+ const startIndex = sr.notePathArray.indexOf(ancestorNoteId);+ const localPathArray = sr.notePathArray.slice(startIndex + 1).filter((id) => shaca.notes[id]);+ const pathTitle = localPathArray.map((id) => shaca.notes[id].title).join(" / ");++ return {+ id: fullNote.shareId,+ title: fullNote.title,+ score: sr.score,+ path: pathTitle,+ // Plain-text fallback and the <b>-highlighted variant from the search service.+ snippet: sr.contentSnippet,+ highlightedSnippet: sr.highlightedContentSnippet+ };+ });++ return jsonReply(200, { results: filteredResults });+}++/**+ * Returns true when the note reached via `notePathArray` is actually visible in the public share+ * tree below `ancestorNoteId`: every hop from the ancestor down to the note must be a non-hidden+ * branch whose child note is not `shareHiddenFromTree`. Mirrors SNote.getVisibleChildBranches() so+ * that search cannot enumerate notes the navigation tree deliberately hides. Exported for tests: a+ * clone's best note path can bypass the share subtree entirely, which is impractical to stage+ * through the full search stack.+ */+export function isVisibleInShareTree(ancestorNoteId: string, notePathArray: string[]) {+ const startIndex = notePathArray.indexOf(ancestorNoteId);++ if (startIndex < 0) {+ return false;+ }++ for (let i = startIndex + 1; i < notePathArray.length; i++) {+ const childNote = shaca.notes[notePathArray[i]];+ const branch = shaca.getBranchFromChildAndParent(notePathArray[i], notePathArray[i - 1]);++ if (!childNote || !branch || branch.isHidden || childNote.isLabelTruthy("shareHiddenFromTree")) {+ return false;+ }+ }++ return true;+}++/** Returns the note, or raises the reply that refuses the caller. */+function checkNoteAccess(noteId: string, req: ShareRequest): SNote {+ const note = shaca.getNote(noteId);++ if (!note) {+ throw new ShareReplyError(jsonReply(404, { message: `Note '${noteId}' not found.` }));+ }++ if (noteId === "_share" && !shaca.shareIndexEnabled) {+ throw new ShareReplyError(jsonReply(403, { message: `Accessing share index is forbidden.` }));+ }++ if (!hasCredentialAccess(note, req)) {+ throw new ShareReplyError(requestCredentials());+ }++ return note;+}++/**+ * Like checkNoteAccess, but additionally refuses protected notes. Used by the routes that stream a+ * note's raw content/images: a protected note still shows up as "[protected]" in the shared tree+ * (handled by content_renderer.ts), but its actual bytes must never be served anonymously+ * (GHSA-xmv9-3v98-7gq8).+ */+function checkNoteContentAccess(noteId: string, req: ShareRequest): SNote {+ const note = checkNoteAccess(noteId, req);++ rejectProtected(note, `Note '${noteId}' not found.`);++ return note;+}++function checkAttachmentAccess(attachmentId: string, req: ShareRequest): SAttachment {+ const attachment = shaca.getAttachment(attachmentId);++ if (!attachment) {+ throw new ShareReplyError(jsonReply(404, { message: `Attachment '${attachmentId}' not found.` }));+ }++ const note = checkNoteAccess(attachment.ownerId, req);++ // Protected notes cannot be shared, and neither can their attachments (GHSA-xmv9-3v98-7gq8).+ rejectProtected(note, `Attachment '${attachmentId}' not found.`);++ return attachment;+}++/** Raises a 404 when the note is protected, so the caller never reaches its bytes. */+function rejectProtected(note: SNote, message: string) {+ if (note.isProtected) {+ throw new ShareReplyError(jsonReply(404, { message }));+ }+}++/**+ * Returns true when the request is allowed to read the given note: either the note (including+ * inherited attributes) carries no shareCredentials, or the request presents matching HTTP Basic+ * credentials. Pure predicate — it raises nothing, so it can also filter search results.+ */+function hasCredentialAccess(note: SNote, req: ShareRequest) {+ const credentials = note.getCredentials();++ if (credentials.length === 0) {+ return true;+ }++ const header = req.getHeader("authorization");++ if (!header?.startsWith("Basic ")) {+ return false;+ }++ let authString: string;++ try {+ authString = decodeUtf8(decodeBase64(header.substring("Basic ".length)));+ } catch {+ return false;+ }++ const given = encodeUtf8(authString);++ return credentials.some((credentialLabel) => getCrypto().constantTimeCompare(given, encodeUtf8(credentialLabel.value)));+}++function requestCredentials(): ShareReply {+ return {+ status: 401,+ headers: { "WWW-Authenticate": 'Basic realm="User Visible Realm", charset="UTF-8"' }+ };+}++/**+ * Serves the rendered SVG a canvas, mermaid or mind map note keeps in a named attachment, falling+ * back to an empty image when neither that attachment nor the note's own content holds one.+ */+function renderImageAttachment(image: SNote, attachmentName: string): ShareReply {+ let svgString = "<svg/>";+ const content = image.getAttachmentByTitle(attachmentName)?.getContent();++ if (typeof content === "string") {+ svgString = content;+ } else {+ // backwards compatibility, before attachments, the SVG was stored in the main note content as a separate key+ const possibleSvgContent = image.getJsonContentSafely();++ const contentSvg = (typeof possibleSvgContent === "object"+ && possibleSvgContent !== null+ && "svg" in possibleSvgContent+ && typeof possibleSvgContent.svg === "string")+ ? possibleSvgContent.svg+ : null;++ if (contentSvg) {+ svgString = contentSvg;+ }+ }++ return svgReply(utils.sanitizeSvg(svgString));+}++/** Serves an image's bytes, sanitizing first when the image is an SVG, which can carry script. */+function serveImageBytes(content: string | Uint8Array | undefined, mime: string, headers: Record<string, string>): ShareReply {+ if (isSvgMime(mime)) {+ const svgContent = typeof content === "string" ? content : decodeUtf8(content ?? new Uint8Array());++ return svgReply(utils.sanitizeSvg(svgContent), headers);+ }++ return {+ status: 200,+ headers: { ...headers, "Content-Type": mime },+ body: content+ };+}++function svgReply(svg: string, headers: Record<string, string> = {}): ShareReply {+ return {+ status: 200,+ headers: {+ ...headers,+ "Content-Type": "image/svg+xml",+ "Cache-Control": "no-cache, no-store, must-revalidate",+ "Content-Security-Policy": utils.SVG_CONTENT_SECURITY_POLICY,+ "X-Content-Type-Options": "nosniff"+ },+ body: svg+ };+}++function render404(): ShareReply {+ return {+ status: 404,+ headers: { "Content-Type": "text/html; charset=utf-8" },+ body: ejs.render(readShareTemplate("404"), { t })+ };+}++function noIndexHeaders(note: SNote): Record<string, string> {+ return note.isLabelTruthy("shareDisallowRobotIndexing") ? { "X-Robots-Tag": "noindex" } : {};+}++function jsonReply(status: number, payload: unknown, headers: Record<string, string> = {}): ShareReply {+ return {+ status,+ headers: { ...headers, "Content-Type": "application/json; charset=utf-8" },+ body: JSON.stringify(payload)+ };+}diff --git a/packages/trilium-core/src/share/index.ts b/packages/trilium-core/src/share/index.tsnew file mode 100644index 0000000000..e6dc6a065c--- /dev/null+++ b/packages/trilium-core/src/share/index.ts@@ -0,0 +1,15 @@+/**+ * The share subsystem: the read-only cache of the `_share` subtree (shaca), the renderer that turns+ * one of its notes into a page, and the transport-neutral route handlers over both.+ *+ * Deliberately kept out of the `@triliumnext/core` barrel: the browser build reaches it through a+ * dynamic import, which only defers its cost — EJS, the share theme and the syntax highlighter —+ * while nothing in the eager graph imports it.+ */+export { assetUrlFragment, readShareTemplate, renderNoteContent, renderNoteForExport } from "./content_renderer.js";+export { getShareRoute, getShareRoutes, handleShareRequest, isVisibleInShareTree, type ShareReply, type ShareRequest, type ShareRoute } from "./handlers.js";+export { SHARE_ROUTE_PATHS, type ShareRoutePath } from "./route_paths.js";+export { initShare, isShareReady, type ShareProvider, type ShareSql } from "./share_provider.js";+export { default as shareRoot } from "./share_root.js";+export { default as shaca } from "./shaca/shaca.js";+export { default as shacaLoader } from "./shaca/shaca_loader.js";diff --git a/packages/trilium-core/src/share/route_paths.ts b/packages/trilium-core/src/share/route_paths.tsnew file mode 100644index 0000000000..cf917697ab--- /dev/null+++ b/packages/trilium-core/src/share/route_paths.ts@@ -0,0 +1,22 @@+/**+ * The share URL patterns, in the order a router must try them: the `/share/api/` routes before the+ * note routes, so a literal segment is never swallowed by `:shareId`, and `/share/` before it so+ * the share root is not read as a note named nothing.+ *+ * Kept in a module of its own, free of imports, so a platform can register its routes without+ * loading the handlers behind them — which carry EJS, the share theme and the syntax highlighter.+ */+export const SHARE_ROUTE_PATHS = [+ "/share/api/notes/:noteId/download",+ "/share/api/notes/:noteId/view",+ "/share/api/notes/:noteId",+ "/share/api/notes",+ // :filename is not used by trilium, but instead used for "save as" to assign a human-readable filename+ "/share/api/images/:noteId/:filename",+ "/share/api/attachments/:attachmentId/image/:filename",+ "/share/api/attachments/:attachmentId/download",+ "/share/",+ "/share/:shareId"+] as const;++export type ShareRoutePath = (typeof SHARE_ROUTE_PATHS)[number];diff --git a/apps/server/src/share/shaca/entities/abstract_shaca_entity.ts b/packages/trilium-core/src/share/shaca/entities/abstract_shaca_entity.tssimilarity index 100%rename from apps/server/src/share/shaca/entities/abstract_shaca_entity.tsrename to packages/trilium-core/src/share/shaca/entities/abstract_shaca_entity.tsdiff --git a/apps/server/src/share/shaca/entities/rows.ts b/packages/trilium-core/src/share/shaca/entities/rows.tssimilarity index 100%rename from apps/server/src/share/shaca/entities/rows.tsrename to packages/trilium-core/src/share/shaca/entities/rows.tsdiff --git a/apps/server/src/share/shaca/entities/sattachment.ts b/packages/trilium-core/src/share/shaca/entities/sattachment.tssimilarity index 89%rename from apps/server/src/share/shaca/entities/sattachment.tsrename to packages/trilium-core/src/share/shaca/entities/sattachment.tsindex 090eaf734c..941b0b0bae 100644--- a/apps/server/src/share/shaca/entities/sattachment.ts+++ b/packages/trilium-core/src/share/shaca/entities/sattachment.ts@@ -1,9 +1,9 @@import { BlobRow } from "@triliumnext/commons";-import { binary_utils } from "@triliumnext/core";+import { decodeUtf8 } from "../../../services/utils/binary.js";-import utils from "../../../services/utils.js";+import { isStringNote } from "../../../services/utils/index.js";import sql from "../../sql.js";import AbstractShacaEntity from "./abstract_shaca_entity.js";import type { SAttachmentRow } from "./rows.js";@@ -52,7 +52,7 @@ class SAttachment extends AbstractShacaEntity {const content = row.content;if (this.hasStringContent()) {- return content === null ? "" : binary_utils.decodeUtf8(content);+ return content === null ? "" : decodeUtf8(content);}return content;@@ -60,7 +60,7 @@ class SAttachment extends AbstractShacaEntity {/** @returns true if the attachment has string content (not binary) */hasStringContent() {- return utils.isStringNote(undefined, this.mime);+ return isStringNote(undefined, this.mime);}getPojo() {diff --git a/apps/server/src/share/shaca/entities/sattribute.ts b/packages/trilium-core/src/share/shaca/entities/sattribute.tssimilarity index 100%rename from apps/server/src/share/shaca/entities/sattribute.tsrename to packages/trilium-core/src/share/shaca/entities/sattribute.tsdiff --git a/apps/server/src/share/shaca/entities/sbranch.ts b/packages/trilium-core/src/share/shaca/entities/sbranch.tssimilarity index 100%rename from apps/server/src/share/shaca/entities/sbranch.tsrename to packages/trilium-core/src/share/shaca/entities/sbranch.tsdiff --git a/apps/server/src/share/shaca/entities/snote.ts b/packages/trilium-core/src/share/shaca/entities/snote.tssimilarity index 98%rename from apps/server/src/share/shaca/entities/snote.tsrename to packages/trilium-core/src/share/shaca/entities/snote.tsindex 790824fd27..6667081509 100644--- a/apps/server/src/share/shaca/entities/snote.ts+++ b/packages/trilium-core/src/share/shaca/entities/snote.ts@@ -1,8 +1,8 @@import { BlobRow, getNoteIcon, NoteType } from "@triliumnext/commons";-import { binary_utils } from "@triliumnext/core";+import { decodeUtf8 } from "../../../services/utils/binary.js";import escape from "escape-html";-import utils from "../../../services/utils.js";+import { isStringNote } from "../../../services/utils/index.js";import sql from "../../sql.js";import AbstractShacaEntity from "./abstract_shaca_entity.js";import type { SNoteRow } from "./rows.js";@@ -107,14 +107,14 @@ class SNote extends AbstractShacaEntity {const content = row.content;if (this.hasStringContent()) {- return content === null ? "" : binary_utils.decodeUtf8(content);+ return content === null ? "" : decodeUtf8(content);}return content;}/** @returns true if the note has string content (not binary) */hasStringContent() {- return utils.isStringNote(this.type, this.mime);+ return isStringNote(this.type, this.mime);}/**diff --git a/apps/server/src/share/shaca/shaca-interface.ts b/packages/trilium-core/src/share/shaca/shaca-interface.tssimilarity index 100%rename from apps/server/src/share/shaca/shaca-interface.tsrename to packages/trilium-core/src/share/shaca/shaca-interface.tsdiff --git a/apps/server/src/share/shaca/shaca.ts b/packages/trilium-core/src/share/shaca/shaca.tssimilarity index 100%rename from apps/server/src/share/shaca/shaca.tsrename to packages/trilium-core/src/share/shaca/shaca.tsdiff --git a/apps/server/src/share/shaca/shaca_loader.ts b/packages/trilium-core/src/share/shaca/shaca_loader.tssimilarity index 96%rename from apps/server/src/share/shaca/shaca_loader.tsrename to packages/trilium-core/src/share/shaca/shaca_loader.tsindex 896be78e3b..aba5b85b21 100644--- a/apps/server/src/share/shaca/shaca_loader.ts+++ b/packages/trilium-core/src/share/shaca/shaca_loader.ts@@ -1,6 +1,5 @@-import { events as eventService } from "@triliumnext/core";--import { getLog } from "@triliumnext/core";+import eventService from "../../services/events.js";+import { getLog } from "../../services/log.js";import shareRoot from "../share_root.js";import sql from "../sql.js";import type { SAttachmentRow, SAttributeRow, SBranchRow, SNoteRow } from "./entities/rows.js";diff --git a/packages/trilium-core/src/share/share_provider.ts b/packages/trilium-core/src/share/share_provider.tsnew file mode 100644index 0000000000..59a3b0a82b--- /dev/null+++ b/packages/trilium-core/src/share/share_provider.ts@@ -0,0 +1,40 @@+/** The raw-row accessors the share cache and its entities read through. */+export interface ShareSql {+ getRawRows<T>(query: string, params?: string[]): T[];+ getRow<T>(query: string, params?: string[]): T;+ getColumn<T>(query: string, params?: string[]): T[];+}++/**+ * What the share subsystem needs from the platform hosting it. The Node server reads rows over a+ * second, read-only connection and loads templates from disk; the browser build shares the one+ * connection it has and carries its templates in the bundle.+ */+export interface ShareProvider {+ sql: ShareSql;+ /** Returns the share theme's EJS template of that name, such as `page` or `404`. */+ readTemplate(name: string): string;+ /** Returns true when a shared note can bring its own EJS template, which runs arbitrary JavaScript. */+ isScriptingEnabled(): boolean;+ /** Returns false while what {@link ShareProvider.sql} reads is still being opened. */+ isReady(): boolean;+}++let provider: ShareProvider | null = null;++export function initShare(shareProvider: ShareProvider) {+ provider = shareProvider;+}++export function getShareProvider(): ShareProvider {+ if (!provider) {+ throw new Error("Share provider has not been initialized. Call initShare() during startup.");+ }++ return provider;+}++/** Returns true when this platform registered a share provider and that provider can be read. */+export function isShareReady(): boolean {+ return !!provider && provider.isReady();+}diff --git a/apps/server/src/share/share_root.ts b/packages/trilium-core/src/share/share_root.tssimilarity index 100%rename from apps/server/src/share/share_root.tsrename to packages/trilium-core/src/share/share_root.tsdiff --git a/packages/trilium-core/src/share/sql.ts b/packages/trilium-core/src/share/sql.tsnew file mode 100644index 0000000000..14e0247c2e--- /dev/null+++ b/packages/trilium-core/src/share/sql.ts@@ -0,0 +1,19 @@+import { getShareProvider } from "./share_provider.js";++function getRawRows<T>(query: string, params: string[] = []): T[] {+ return getShareProvider().sql.getRawRows<T>(query, params);+}++function getRow<T>(query: string, params: string[] = []): T {+ return getShareProvider().sql.getRow<T>(query, params);+}++function getColumn<T>(query: string, params: string[] = []): T[] {+ return getShareProvider().sql.getColumn<T>(query, params);+}++export default {+ getRawRows,+ getRow,+ getColumn+};diff --git a/apps/server/src/test/shaca_mocking.ts b/packages/trilium-core/src/test/shaca_mocking.tssimilarity index 94%rename from apps/server/src/test/shaca_mocking.tsrename to packages/trilium-core/src/test/shaca_mocking.tsindex 8ec3741f59..857ad6470d 100644--- a/apps/server/src/test/shaca_mocking.ts+++ b/packages/trilium-core/src/test/shaca_mocking.ts@@ -1,4 +1,4 @@-import utils from "../services/utils.js";+import { randomString } from "../services/utils/index.js";import SAttachment from "../share/shaca/entities/sattachment.js";import SAttribute from "../share/shaca/entities/sattribute.js";import SBranch from "../share/shaca/entities/sbranch.js";@@ -54,7 +54,7 @@ export function buildShareNotes(notes: NoteDefinition[]) {export function buildShareNote(noteDef: NoteDefinition) {const blobId = "foo";const note = new SNote([- noteDef.id ?? utils.randomString(12),+ noteDef.id ?? randomString(12),noteDef.title ?? "New note",noteDef.type ?? "text",noteDef.mime ?? "text/html",@@ -77,7 +77,7 @@ export function buildShareNote(noteDef: NoteDefinition) {if (noteDef.attachments) {for (const attachmentDef of noteDef.attachments) {new SAttachment([- attachmentDef.id ?? utils.randomString(12),+ attachmentDef.id ?? randomString(12),note.noteId,attachmentDef.role ?? "file",attachmentDef.mime ?? "application/blob",@@ -95,7 +95,7 @@ export function buildShareNote(noteDef: NoteDefinition) {const childNote = buildShareNote(childDef);new SBranch([- utils.randomString(12),+ randomString(12),childNote.noteId,note.noteId,"", // prefix@@ -108,7 +108,7 @@ export function buildShareNote(noteDef: NoteDefinition) {// Handle labels & relationslet position = 0;for (const [ key, value ] of Object.entries(noteDef)) {- const attributeId = utils.randomString(12);+ const attributeId = randomString(12);const name = key.substring(1);let attribute: SAttribute | null = null;diff --git a/packages/trilium-core/tsconfig.lib.json b/packages/trilium-core/tsconfig.lib.jsonindex e0625b3c80..08a9c313e4 100644--- a/packages/trilium-core/tsconfig.lib.json+++ b/packages/trilium-core/tsconfig.lib.json@@ -16,7 +16,11 @@"src/**/*.ts","src/**/*.json"],- "references": [],+ "references": [+ {+ "path": "../highlightjs/tsconfig.lib.json"+ }+ ],"exclude": ["vite.config.ts","vite.config.mts",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex f3da590521..6d3bf782d8 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -688,9 +688,6 @@ importers:'@types/multer':specifier: 2.2.0version: 2.2.0- '@types/safe-compare':- specifier: 1.1.2- version: 1.1.2'@types/serve-favicon':specifier: 2.5.7version: 2.5.7@@ -1407,6 +1404,9 @@ importers:'@triliumnext/commons':specifier: workspace:*version: link:../commons+ '@triliumnext/highlightjs':+ specifier: workspace:*+ version: link:../highlightjs'@triliumnext/turndown-plugin-gfm':specifier: workspace:*version: link:../turndown-plugin-gfm@@ -1422,6 +1422,9 @@ importers:color:specifier: 5.0.3version: 5.0.3+ ejs:+ specifier: 6.0.1+ version: 6.0.1escape-html:specifier: 1.0.3version: 1.0.3@@ -1468,6 +1471,9 @@ importers:specifier: 4.6.5version: 4.6.5devDependencies:+ '@types/ejs':+ specifier: 3.1.5+ version: 3.1.5'@types/escape-html':specifier: 1.0.4version: 1.0.4@@ -4759,9 +4765,6 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-U6wdIeFZPR77zjaZCrFNPzKjjfdFr4Dj0WUAZ+UYgXGjwqYCnjpCngeS0hb+28FLL0QzE9jXBikvB7xxAQi5sg==}- '@types/[email protected]':- resolution: {integrity: sha512-kK/IM1+pvwCMom+Kezt/UlP8LMEwm8rP6UgGbRc6zUnhU/csoBQ5rWgmD2CJuHxiMiX+H1VqPGpo0kDluJGXYA==}-'@types/[email protected]':resolution: {integrity: sha512-n9wjs8bCOTyN/ynwD8s/nTcTreIHB1vf31vhLMGqUPNHaweKC4/fAl4Dj+hUlCTKYgm4P3k83fmiFfzkZ6sgMA==}@@ -15812,8 +15815,6 @@ snapshots:'@types/[email protected]': {}- '@types/[email protected]': {}-'@types/[email protected]':dependencies:htmlparser2: 10.1.0