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
test(share): cover the share cache and the share handlers fully
Elian Doranbd5137c5f132
diff --git a/packages/trilium-core/src/share/handlers.spec.ts b/packages/trilium-core/src/share/handlers.spec.tsindex 4714b4688e..443a1a8420 100644--- a/packages/trilium-core/src/share/handlers.spec.ts+++ b/packages/trilium-core/src/share/handlers.spec.ts@@ -1,9 +1,16 @@-import { beforeEach, describe, expect, it, vi } from "vitest";+import { NOTE_TYPE_IMAGE_ATTACHMENTS } from "@triliumnext/commons";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { encodeBase64 } from "../services/utils/binary.js";+import { getCrypto } from "../services/encryption/crypto.js";+import SearchResult from "../services/search/search_result.js";+import searchService from "../services/search/services/search.js";+import { encodeBase64, encodeUtf8 } from "../services/utils/binary.js";import { buildShareNote } from "../test/shaca_mocking.js";-import { getShareRoute, handleShareRequest, type ShareRequest } from "./handlers.js";+import {+ getShareRoute, getShareRoutes, handleShareRequest, type ShareReply, type ShareRequest+} from "./handlers.js";import { SHARE_ROUTE_PATHS, type ShareRoutePath } from "./route_paths.js";+import { getShareProvider } from "./share_provider.js";import shareRoot from "./share_root.js";import shaca from "./shaca/shaca.js";@@ -22,6 +29,10 @@ describe("share handlers", () => {shaca.loaded = true;});+ afterEach(() => {+ vi.restoreAllMocks();+ });+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 });@@ -164,22 +175,335 @@ describe("share handlers", () => {for (const path of SHARE_ROUTE_PATHS) {expect(typeof getShareRoute(path).handle, path).toBe("function");}++ const routes = getShareRoutes();+ expect(routes.map((route) => route.path)).toEqual([ ...SHARE_ROUTE_PATHS ]);+ for (const route of routes) {+ expect(route.handle, route.path).toBe(getShareRoute(route.path).handle);+ }+ });++ it("answers 503 until the share provider is ready and lets unexpected errors through", () => {+ buildShareTree([ { id: "readyNote", content: "<p>Ready</p>" } ]);+ const isReady = vi.spyOn(getShareProvider(), "isReady").mockReturnValue(false);+ const reply = request("/share/:shareId", { params: { shareId: "readyNote" } });+ expect(reply.status).toBe(503);+ expect(String(reply.body)).toContain("still initializing");+ isReady.mockRestore();+ expect(request("/share/:shareId", { params: { shareId: "readyNote" } }).status).toBe(200);++ const failing = {+ path: "/share/" as const,+ handle: (): ShareReply => {+ throw new Error("unexpected failure");+ }+ };+ expect(() => handleShareRequest(failing, buildRequest("/share/"))).toThrow("unexpected failure");+ });++ it("answers 404 when a route's id parameter is missing", () => {+ buildShareTree([]);++ expect(String(request("/share/:shareId").body)).toContain("<html");+ for (const path of [+ "/share/:shareId",+ "/share/api/notes/:noteId",+ "/share/api/notes/:noteId/download",+ "/share/api/notes/:noteId/view",+ "/share/api/images/:noteId/:filename",+ "/share/api/attachments/:attachmentId/image/:filename",+ "/share/api/attachments/:attachmentId/download"+ ] as const) {+ expect(request(path).status, path).toBe(404);+ }+ });++ it("locks a raw SVG note down with a content security policy, but not raw HTML", () => {+ buildShareTree([+ { id: "rawSvg", type: "image", mime: "image/svg+xml", content: "<svg/>", "#shareRaw": "" },+ { id: "rawHtml", content: "<p>Raw</p>", "#shareRaw": "" }+ ]);++ const svg = request("/share/:shareId", { params: { shareId: "rawSvg" } });+ expect(svg.headers).toMatchObject({+ "Content-Type": "image/svg+xml",+ "X-Content-Type-Options": "nosniff"+ });+ expect(svg.headers["Content-Security-Policy"]).toContain("default-src 'none'");+ expect(svg.body).toBe("<svg/>");++ const html = request("/share/:shareId", { params: { shareId: "rawHtml" } });+ expect(html.headers["Content-Type"]).toBe("text/html");+ expect(html.headers).not.toHaveProperty("Content-Security-Policy");+ expect(html.body).toBe("<p>Raw</p>");+ });++ it("withholds an included note behind credentials until the request presents them", () => {+ buildShareTree([+ {+ id: "hostNote",+ content: `<section class="include-note" data-note-id="lockedEmbed"> </section>`+ },+ { "id": "lockedEmbed", "content": "<p>embedded secret</p>", "#shareCredentials": "root:hunter2" }+ ]);++ const anonymous = String(request("/share/:shareId", { params: { shareId: "hostNote" } }).body);+ expect(anonymous).toContain("include-note-forbidden");+ expect(anonymous).not.toContain("embedded secret");++ const authorized = String(request("/share/:shareId", {+ params: { shareId: "hostNote" },+ headers: { authorization: `Basic ${encodeBase64("root:hunter2")}` }+ }).body);+ expect(authorized).toContain("embedded secret");+ expect(authorized).not.toContain("include-note-forbidden");+ });++ it("refuses credentials that are not Basic or that the decoder rejects", () => {+ buildShareTree([+ { "id": "lockedNote", "content": "<p>classified</p>", "#shareCredentials": "root:hunter2" }+ ]);+ const valid = `Basic ${encodeBase64("root:hunter2")}`;+ const fetchNote = (authorization: string) => request("/share/api/notes/:noteId", {+ params: { noteId: "lockedNote" },+ headers: { authorization }+ }).status;++ expect(fetchNote(`Bearer ${encodeBase64("root:hunter2")}`)).toBe(401);++ vi.spyOn(getCrypto(), "base64Decode").mockImplementationOnce(() => {+ throw new Error("invalid base64");+ });+ expect(fetchNote(valid)).toBe(401);+ expect(fetchNote(valid)).toBe(200);+ });++ it("serves the SVG a canvas, mermaid or mind map note renders to, sanitized", () => {+ buildShareTree([+ {+ id: "canvasNote",+ type: "canvas",+ mime: "application/json",+ content: "{}",+ attachments: [+ { id: "canvasExport", title: NOTE_TYPE_IMAGE_ATTACHMENTS.canvas, mime: "image/svg+xml" }+ ]+ },+ {+ id: "mermaidNote",+ type: "mermaid",+ mime: "text/mermaid",+ content: JSON.stringify({ svg: `<svg id="legacy"><script>alert(1)</script></svg>` })+ },+ { id: "mindMapNote", type: "mindMap", mime: "application/json", content: "not json" },+ {+ id: "binaryExport",+ type: "canvas",+ mime: "application/json",+ content: JSON.stringify({ svg: `<svg id="fallback"/>` }),+ attachments: [ { id: "binaryAttachment", title: NOTE_TYPE_IMAGE_ATTACHMENTS.canvas } ]+ }+ ]);+ stubAttachmentContent("canvasExport", `<svg id="export" onload="alert(1)"/>`);+ stubAttachmentContent("binaryAttachment", encodeUtf8("<svg id=\"binary\"/>"));+ const image = (noteId: string) => request("/share/api/images/:noteId/:filename", {+ params: { noteId, filename: "x.svg" }+ });++ const canvas = image("canvasNote");+ expect(canvas.status).toBe(200);+ expect(canvas.headers).toMatchObject({+ "Content-Type": "image/svg+xml",+ "X-Content-Type-Options": "nosniff"+ });+ expect(canvas.headers["Content-Security-Policy"]).toContain("default-src 'none'");+ expect(canvas.body).toBe(`<svg id="export"/>`);++ // Before attachments existed, the SVG lived under the `svg` key of the note's own JSON.+ expect(image("mermaidNote").body).toBe(`<svg id="legacy"></svg>`);+ expect(image("binaryExport").body).toBe(`<svg id="fallback"/>`);+ expect(image("mindMapNote").body).toBe("<svg/>");++ for (const content of [ "", "5", "{}", "{\"svg\":1}", "{\"svg\":\"\"}" ]) {+ const legacyNote = shaca.getNote("mindMapNote");+ legacyNote.getContent = () => content;+ expect(image("mindMapNote").body, content).toBe("<svg/>");+ }+ });++ it("serves an image attachment and downloads any attachment, behind its owner's checks", () => {+ buildShareTree([+ {+ "id": "attachmentOwner",+ "content": "<p>Owner</p>",+ "#shareDisallowRobotIndexing": "true",+ "attachments": [+ { id: "pngAttachment", role: "image", mime: "image/png", title: "picture.png" },+ { id: "svgAttachment", role: "image", mime: "image/svg+xml", title: "drawing.svg" },+ { id: "fileAttachment", role: "file", mime: "application/pdf", title: "report.pdf" }+ ]+ },+ {+ id: "protectedOwner",+ content: "<p>Secret</p>",+ isProtected: true,+ attachments: [ { id: "protectedAttachment", role: "image", mime: "image/png" } ]+ },+ {+ "id": "lockedOwner",+ "content": "<p>Locked</p>",+ "#shareCredentials": "root:hunter2",+ "attachments": [ { id: "lockedAttachment", role: "image", mime: "image/png" } ]+ }+ ]);+ const pngBytes = new Uint8Array([ 0x89, 0x50, 0x4e, 0x47 ]);+ stubAttachmentContent("pngAttachment", pngBytes);+ stubAttachmentContent("svgAttachment", encodeUtf8(`<svg><script>alert(1)</script></svg>`));+ stubAttachmentContent("fileAttachment", "%PDF");+ for (const attachmentId of [ "protectedAttachment", "lockedAttachment" ]) {+ stubAttachmentContent(attachmentId, "attachment bytes");+ }+ const image = (attachmentId: string) => request(+ "/share/api/attachments/:attachmentId/image/:filename",+ { params: { attachmentId, filename: "x" } }+ );+ const download = (attachmentId: string) => request(+ "/share/api/attachments/:attachmentId/download",+ { params: { attachmentId } }+ );++ const png = image("pngAttachment");+ expect(png).toMatchObject({ status: 200, body: pngBytes });+ expect(png.headers).toEqual({ "X-Robots-Tag": "noindex", "Content-Type": "image/png" });++ const svg = image("svgAttachment");+ expect(svg.body).toBe("<svg></svg>");+ expect(svg.headers).toMatchObject({ "X-Robots-Tag": "noindex", "Content-Type": "image/svg+xml" });+ expect(svg.headers["Content-Security-Policy"]).toContain("default-src 'none'");++ stubAttachmentContent("svgAttachment", undefined);+ expect(image("svgAttachment")).toMatchObject({ status: 200, body: "" });++ expect(image("fileAttachment").status).toBe(400);+ const pdf = download("fileAttachment");+ expect(pdf).toMatchObject({ status: 200, body: "%PDF" });+ expect(pdf.headers).toMatchObject({+ "X-Robots-Tag": "noindex",+ "Content-Type": "application/pdf",+ "Cache-Control": "no-cache, no-store, must-revalidate"+ });+ expect(pdf.headers["Content-Disposition"]).toContain("report.pdf");++ for (const route of [ image, download ]) {+ const missing = route("noSuchAttachment");+ expect(missing.status).toBe(404);+ expect(String(missing.body)).toContain("noSuchAttachment");++ const protectedReply = route("protectedAttachment");+ expect(protectedReply.status).toBe(404);+ expect(String(protectedReply.body)).not.toContain("attachment bytes");++ expect(route("lockedAttachment").status).toBe(401);+ }+ });++ it("searches the share tree and returns only the results the caller can see", () => {+ buildShareTree([+ {+ id: "docs",+ title: "Docs",+ content: "",+ children: [+ { id: "visible", title: "Visible", content: "" },+ { "id": "labelHidden", "title": "Label hidden", "content": "", "#shareHiddenFromTree": "" },+ { id: "branchHidden", title: "Branch hidden", content: "" },+ { "id": "locked", "title": "Locked", "content": "", "#shareCredentials": "root:hunter2" },+ { id: "protectedNote", title: "Protected", content: "", isProtected: true }+ ]+ },+ { id: "outside", title: "Outside", content: "" }+ ]);+ shaca.shareIndexEnabled = true;+ shaca.getBranchFromChildAndParent("branchHidden", "docs").isHidden = true;++ const visible = new SearchResult([ "root", "_share", "docs", "visible" ]);+ visible.score = 7;+ visible.contentSnippet = "plain snippet";+ visible.highlightedContentSnippet = "<b>plain</b> snippet";+ const results = [+ visible,+ ...[ "labelHidden", "branchHidden", "locked", "protectedNote" ]+ .map((noteId) => new SearchResult([ "root", "_share", "docs", noteId ])),+ new SearchResult([ "root", "notShared" ]),+ new SearchResult([ "root", "outside" ]),+ new SearchResult([ "root", "_share", "visible" ]),+ new SearchResult([ "root", "_share", "notShared", "visible" ])+ ];+ // The spies replace the search service on its shared default export, which handlers.ts+ // already holds; a vi.mock() of the module would not reach that instance.+ const findResults = vi.spyOn(searchService, "findResultsWithQuery").mockReturnValue(results);+ const buildDetails = vi.spyOn(searchService, "buildSearchResultDetails").mockReturnValue([]);+ const search = (query: ShareRequest["query"], authorization?: string) => request(+ "/share/api/notes",+ { query, headers: authorization ? { authorization } : {} }+ );+ const titles = (reply: ShareReply) => {+ const { results: found } = JSON.parse(String(reply.body)) as { results: { title: string }[] };+ return found.map((result) => result.title);+ };++ const anonymous = search({ search: "anything" });+ expect(anonymous.status).toBe(200);+ expect(JSON.parse(String(anonymous.body))).toEqual({+ results: [ {+ id: "visible",+ title: "Visible",+ score: 7,+ path: "Docs / Visible",+ snippet: "plain snippet",+ highlightedSnippet: "<b>plain</b> snippet"+ } ]+ });+ expect(findResults.mock.lastCall?.[1].ancestorNoteId).toBe("_share");+ expect(buildDetails.mock.lastCall?.[0]).toEqual([ visible ]);++ const authorized = search({ search: "anything" }, `Basic ${encodeBase64("root:hunter2")}`);+ expect(titles(authorized)).toEqual([ "Visible", "Locked" ]);++ const scoped = JSON.parse(String(search({ search: "anything", ancestorNoteId: "docs" }).body));+ expect(scoped.results[0].path).toBe("Visible");++ expect(search({ search: "anything", ancestorNoteId: [ "docs", "outside" ] }).status).toBe(400);+ expect(search({}).status).toBe(400);+ expect(search({ search: " " }).status).toBe(400);+ expect(search({ search: [ "a", "b" ] }).status).toBe(400);});});+function stubAttachmentContent(attachmentId: string, content: string | Uint8Array | undefined) {+ const attachment = shaca.getAttachment(attachmentId);+ attachment.getContent = () => content;+}+/** 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> } = {}) {+function request(path: ShareRoutePath, overrides: RequestOverrides = {}) {+ return handleShareRequest(getShareRoute(path), buildRequest(path, overrides));+}++type RequestOverrides = Partial<ShareRequest> & { headers?: Record<string, string> };++function buildRequest(path: ShareRoutePath, overrides: RequestOverrides = {}): ShareRequest {const { headers = {}, ...rest } = overrides;- return handleShareRequest(getShareRoute(path), {+ return {path: `/share/${path}`,params: {},query: {},getHeader: (name: string) => headers[name.toLowerCase()],...rest- });+ };}diff --git a/packages/trilium-core/src/share/shaca/entities/sattachment.spec.ts b/packages/trilium-core/src/share/shaca/entities/sattachment.spec.tsnew file mode 100644index 0000000000..6f32cf7a2f--- /dev/null+++ b/packages/trilium-core/src/share/shaca/entities/sattachment.spec.ts@@ -0,0 +1,66 @@+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { encodeUtf8 } from "../../../services/utils/binary.js";+import { buildShareNote, stubShareSql } from "../../../test/shaca_mocking.js";+import shaca from "../shaca.js";+import SAttachment from "./sattachment.js";++const PNG_BYTES = new Uint8Array([ 0x89, 0x50, 0x4e, 0x47 ]);+const BLOBS: Record<string, { content: string | Uint8Array | null }> = {+ textBlob: { content: encodeUtf8("plain text") },+ emptyBlob: { content: null },+ imageBlob: { content: PNG_BYTES }+};++describe("SAttachment", () => {+ let restore: () => void;++ beforeEach(() => {+ shaca.reset();+ restore = stubShareSql({ getRow: (_query, [ blobId ]) => BLOBS[blobId] });+ });++ afterEach(() => {+ restore();+ });++ it("registers itself on its owner and describes itself", () => {+ const owner = buildShareNote({ id: "owner" });+ const attachment = new SAttachment([+ "att1", "owner", "image", "image/png", "Picture", "imageBlob", "2025-01-01"+ ]);++ expect(attachment.note).toBe(owner);+ expect(owner.getAttachments()).toEqual([ attachment ]);+ expect(shaca.getAttachment("att1")).toBe(attachment);+ expect(attachment.getPojo()).toEqual({+ attachmentId: "att1",+ role: "image",+ mime: "image/png",+ title: "Picture",+ blobId: "imageBlob",+ utcDateModified: "2025-01-01"+ });+ });++ it("reads text blobs as strings, binary blobs as bytes, and reports a missing blob", () => {+ buildShareNote({ id: "owner" });+ const attach = (id: string, mime: string, blobId: string) =>+ new SAttachment([ id, "owner", "file", mime, id, blobId, "2025-01-01" ]);++ const text = attach("text", "text/plain", "textBlob");+ expect(text.hasStringContent()).toBe(true);+ expect(text.getContent()).toBe("plain text");+ expect(attach("empty", "text/plain", "emptyBlob").getContent()).toBe("");++ const image = attach("image", "image/png", "imageBlob");+ expect(image.hasStringContent()).toBe(false);+ expect(image.getContent()).toBe(PNG_BYTES);++ const missing = attach("missing", "text/plain", "noSuchBlob");+ expect(missing.getContent(true)).toBeUndefined();+ expect(() => missing.getContent()).toThrow(+ "Cannot find blob for attachment 'missing', blob 'noSuchBlob'"+ );+ });+});diff --git a/packages/trilium-core/src/share/shaca/entities/sattribute.spec.ts b/packages/trilium-core/src/share/shaca/entities/sattribute.spec.tsnew file mode 100644index 0000000000..d90bc6d09d--- /dev/null+++ b/packages/trilium-core/src/share/shaca/entities/sattribute.spec.ts@@ -0,0 +1,80 @@+import { beforeEach, describe, expect, it } from "vitest";++import { buildShareNote } from "../../../test/shaca_mocking.js";+import shaca from "../shaca.js";+import SAttribute from "./sattribute.js";++describe("SAttribute", () => {+ beforeEach(() => {+ shaca.reset();+ });++ it("registers itself on its note, its target and the share-wide labels", () => {+ const owner = buildShareNote({+ id: "owner",+ children: [ { id: "image" }, { id: "visible" } ]+ });+ const target = buildShareNote({ id: "target" });+ const add = (id: string, type: string, name: string, value: string) =>+ new SAttribute([ id, "owner", type, name, value, false, 0 ]);++ const relation = add("rel", "relation", "related", "target");+ expect(owner.ownedAttributes).toContain(relation);+ expect(shaca.getAttribute("rel")).toBe(relation);+ expect(target.getTargetRelations()).toEqual([ relation ]);++ add("img", "relation", "imageLink", "image");+ add("ext", "relation", "imageLink", "target");+ expect(owner.getVisibleChildNotes().map((note) => note.noteId)).toEqual([ "visible" ]);++ add("blankAlias", "label", "shareAlias", " ");+ expect(shaca.aliasToNote).toEqual({});+ add("alias", "label", "shareAlias", " my-alias ");+ expect(shaca.aliasToNote).toEqual({ "my-alias": owner });++ expect(shaca.shareRootNote).toBeNull();+ expect(shaca.shareIndexEnabled).toBe(false);+ add("root", "label", "shareRoot", "");+ add("index", "label", "shareIndex", "");+ expect(shaca.shareRootNote).toBe(owner);+ expect(shaca.shareIndexEnabled).toBe(true);+ });++ it("tells relations from labels and resolves their notes", () => {+ const owner = buildShareNote({ id: "owner" });+ const target = buildShareNote({ id: "target" });+ const add = (type: string, name: string, value: string, isInheritable = false) =>+ new SAttribute([ `${type}-${name}`, "owner", type, name, value, isInheritable, 3 ]);++ const label = add("label", "color", "red");+ const inheritable = add("label", "cssClass", "x", true);+ const template = add("relation", "template", "target");+ const internalLink = add("relation", "internalLink", "target");+ const empty = add("relation", "related", "");++ expect([ label, inheritable, template, internalLink ].map((a) => a.isAffectingSubtree))+ .toEqual([ false, true, true, false ]);+ expect([ label, template, internalLink ].map((a) => a.isAutoLink()))+ .toEqual([ false, false, true ]);++ expect(label.targetNoteId).toBeUndefined();+ expect(label.targetNote).toBeUndefined();+ expect(() => label.getTargetNote()).toThrow("Attribute 'label-color' is not relation");+ expect(template.targetNoteId).toBe("target");+ expect(template.targetNote).toBe(target);+ expect(template.getTargetNote()).toBe(target);+ expect(empty.getTargetNote()).toBeNull();++ expect(label.note).toBe(owner);+ expect(label.getNote()).toBe(owner);+ expect(inheritable.getPojo()).toEqual({+ attributeId: "label-cssClass",+ noteId: "owner",+ type: "label",+ name: "cssClass",+ position: 3,+ value: "x",+ isInheritable: true+ });+ });+});diff --git a/packages/trilium-core/src/share/shaca/entities/sbranch.spec.ts b/packages/trilium-core/src/share/shaca/entities/sbranch.spec.tsnew file mode 100644index 0000000000..f68c89c2a7--- /dev/null+++ b/packages/trilium-core/src/share/shaca/entities/sbranch.spec.ts@@ -0,0 +1,30 @@+import { beforeEach, describe, expect, it } from "vitest";++import { buildShareNote } from "../../../test/shaca_mocking.js";+import shaca from "../shaca.js";+import SBranch from "./sbranch.js";++describe("SBranch", () => {+ beforeEach(() => {+ shaca.reset();+ });++ it("links its notes once, however many branches join them", () => {+ const parent = buildShareNote({ id: "parent" });+ const child = buildShareNote({ id: "child" });++ const first = new SBranch([ "first", "child", "parent", "", "", false ]);+ const second = new SBranch([ "second", "child", "parent", "prefix", "1", false ]);++ expect(first.getNote()).toBe(child);+ expect(first.childNote).toBe(child);+ expect(first.getParentNote()).toBe(parent);+ expect(first.parentNote).toBe(parent);+ expect(child.getParentNotes()).toEqual([ parent ]);+ expect(parent.getChildNotes()).toEqual([ child ]);+ expect(child.getParentBranches()).toEqual([ first, second ]);+ expect(child.getBranches()).toEqual([ first, second ]);+ expect(shaca.getBranch("first")).toBe(first);+ expect(shaca.getBranchFromChildAndParent("child", "parent")).toBe(second);+ });+});diff --git a/packages/trilium-core/src/share/shaca/entities/sbranch.ts b/packages/trilium-core/src/share/shaca/entities/sbranch.tsindex a1bd6ee53d..d06aaf39cd 100644--- a/packages/trilium-core/src/share/shaca/entities/sbranch.ts+++ b/packages/trilium-core/src/share/shaca/entities/sbranch.ts@@ -29,9 +29,7 @@ class SBranch extends AbstractShacaEntity {childNote.parents.push(parentNote);}- if (!childNote.parentBranches.includes(this)) {- childNote.parentBranches.push(this);- }+ childNote.parentBranches.push(this);if (!parentNote.children.includes(childNote)) {parentNote.children.push(childNote);diff --git a/packages/trilium-core/src/share/shaca/entities/snote.spec.ts b/packages/trilium-core/src/share/shaca/entities/snote.spec.tsnew file mode 100644index 0000000000..85c3d78873--- /dev/null+++ b/packages/trilium-core/src/share/shaca/entities/snote.spec.ts@@ -0,0 +1,229 @@+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { encodeUtf8 } from "../../../services/utils/binary.js";+import { buildShareNote, stubShareSql } from "../../../test/shaca_mocking.js";+import shaca from "../shaca.js";+import SAttribute from "./sattribute.js";+import SBranch from "./sbranch.js";+import SNote from "./snote.js";++const PNG_BYTES = new Uint8Array([ 0x89, 0x50, 0x4e, 0x47 ]);+const BLOBS: Record<string, { content: string | Uint8Array | null }> = {+ json: { content: encodeUtf8("{ \"a\": 1 }") },+ invalidJson: { content: "{ nope" },+ blank: { content: " " },+ empty: { content: null },+ image: { content: PNG_BYTES }+};++describe("SNote", () => {+ let restore: () => void;++ beforeEach(() => {+ shaca.reset();+ restore = stubShareSql({ getRow: (_query, [ blobId ]) => BLOBS[blobId] });+ });++ afterEach(() => {+ restore();+ });++ it("reads its content as text, bytes or JSON", () => {+ const note = (id: string, type: string, mime: string, blobId = id) =>+ new SNote([ id, id, type, mime, blobId, "2025-01-01", false ]);++ const json = note("json", "code", "application/json");+ expect(json.hasStringContent()).toBe(true);+ expect(json.getContent()).toBe("{ \"a\": 1 }");+ expect(json.getJsonContent()).toEqual({ a: 1 });+ expect(json.getJsonContentSafely()).toEqual({ a: 1 });++ const invalid = note("invalidJson", "code", "application/json");+ expect(() => invalid.getJsonContent()).toThrow(SyntaxError);+ expect(invalid.getJsonContentSafely()).toBeNull();++ const empty = note("empty", "code", "application/json");+ expect(empty.getContent()).toBe("");+ expect(empty.getJsonContent()).toBeNull();+ expect(note("blank", "code", "application/json").getJsonContent()).toBeNull();++ const image = note("image", "image", "image/png");+ expect(image.hasStringContent()).toBe(false);+ expect(image.getContent()).toBe(PNG_BYTES);+ expect(image.getJsonContent()).toBeNull();++ const missing = note("missing", "text", "text/html", "noSuchBlob");+ expect(missing.getContent(true)).toBeUndefined();+ expect(() => missing.getContent()).toThrow(+ "Cannot find note content for note 'missing', blob 'noSuchBlob'"+ );+ });++ it("lists its children, hiding those marked hidden from the tree", () => {+ const parent = buildShareNote({+ id: "parent",+ children: [ { id: "shown" }, { id: "hidden", "#shareHiddenFromTree": "" } ]+ });+ const lonely = buildShareNote({+ id: "lonely",+ children: [ { id: "secret", "#shareHiddenFromTree": "" } ]+ });+ const leaf = buildShareNote({ id: "leaf" });++ expect(parent.getChildNotes().map((note) => note.noteId)).toEqual([ "shown", "hidden" ]);+ expect(parent.getVisibleChildNotes().map((note) => note.noteId)).toEqual([ "shown" ]);+ expect([ parent, lonely, leaf ].map((note) => note.hasChildren()))+ .toEqual([ true, true, false ]);+ expect([ parent, lonely, leaf ].map((note) => note.hasVisibleChildren()))+ .toEqual([ true, false, false ]);+ expect([ parent, leaf ].map((note) => note.isFolder())).toEqual([ true, false ]);+ });++ it("inherits attributes from parents and templates, once each and without looping", () => {+ const parent = buildShareNote({ id: "parent", children: [ { id: "child" } ] });+ const template = buildShareNote({ id: "template" });+ const child = shaca.getNote("child");++ addAttribute("fromTemplate", "template", "label", "fromTemplate", "yes");+ addAttribute("inherited", "parent", "label", "inherited", "1", true);+ addAttribute("notInherited", "parent", "label", "notInherited", "1");+ addAttribute("toTemplate", "child", "relation", "template", "template");+ addAttribute("toParent", "child", "relation", "inherit", "parent");+ addAttribute("toMissing", "child", "relation", "template", "missing");+ addAttribute("toSelf", "template", "relation", "template", "template");+ // A parent-child cycle: the child is also the parent's parent.+ new SBranch([ "cycle", "parent", "child", "", "", false ]);++ expect(child.getAttributes().map((attr) => attr.attributeId)).toEqual([+ "toTemplate", "toParent", "toMissing", "inherited",+ "fromTemplate", "toSelf", "notInherited"+ ]);+ expect(child.getLabelValue("inherited")).toBe("1");+ expect(child.getLabelValue("fromTemplate")).toBe("yes");+ expect(child.isInherited()).toBe(false);+ expect(template.isInherited()).toBe(true);+ expect(parent.isInherited()).toBe(true);+ expect(template.getTargetRelations().map((rel) => rel.attributeId))+ .toEqual([ "toTemplate", "toSelf" ]);+ });++ it("does not let the root note inherit from a parent", () => {+ const root = buildShareNote({ id: "root" });+ const above = buildShareNote({ id: "above" });+ new SAttribute([ "fromAbove", "above", "label", "fromAbove", "", true, 0 ]);+ new SBranch([ "rootUnderAbove", "root", "above", "", "", false ]);++ expect(root.getParentNotes()).toEqual([ above ]);+ expect(root.hasLabel("fromAbove")).toBe(false);+ });++ it("finds attributes by type and name, owned or inherited, and keeps credentials apart", () => {+ const parent = buildShareNote({ id: "parent", children: [ { id: "note" } ] });+ const target = buildShareNote({ id: "target" });+ const note = shaca.getNote("note");++ const color = addAttribute("color", "note", "label", "color", "red");+ const color2 = addAttribute("color2", "note", "label", "color", "blue");+ const archived = addAttribute("archived", "parent", "label", "archived", "", true);+ const enabled = addAttribute("enabled", "note", "label", "enabled", "false");+ const related = addAttribute("related", "note", "relation", "related", "target");+ const credentials =+ addAttribute("credentials", "note", "label", "shareCredentials", "user:pass");++ expect(note.getAttributes()).toEqual([ color, color2, enabled, related, archived ]);+ expect(note.getAttributes("label")).toEqual([ color, color2, enabled, archived ]);+ expect(note.getAttributes(undefined, "color")).toEqual([ color, color2 ]);+ expect(note.getAttributes("label", "shareCredentials")).toEqual([]);+ expect(note.getCredentials()).toEqual([ credentials ]);++ expect(note.hasLabel("archived")).toBe(true);+ expect(note.hasOwnedLabel("archived")).toBe(false);+ expect(note.isArchived).toBe(true);+ expect(parent.isArchived).toBe(true);+ expect(target.isArchived).toBe(false);+ expect([ "color", "enabled", "missing" ].map((name) => note.isLabelTruthy(name)))+ .toEqual([ true, false, false ]);++ expect(note.getLabel("color")).toBe(color);+ expect(note.getOwnedLabel("color")).toBe(color);+ expect(note.getOwnedLabel("missing")).toBeNull();+ expect(note.getLabelValue("missing")).toBeNull();+ expect(note.getOwnedLabelValue("color")).toBe("red");+ expect(note.getOwnedLabelValue("missing")).toBeNull();+ expect(note.getLabels("color")).toEqual([ color, color2 ]);+ expect(note.getLabelValues("color")).toEqual([ "red", "blue" ]);+ expect(note.getOwnedLabels("archived")).toEqual([]);+ expect(note.getOwnedLabelValues("color")).toEqual([ "red", "blue" ]);++ expect(note.hasRelation("related")).toBe(true);+ expect(note.hasOwnedRelation("related")).toBe(true);+ expect(note.hasOwnedRelation("color")).toBe(false);+ expect(note.getRelation("related")).toBe(related);+ expect(note.getOwnedRelation("related")).toBe(related);+ expect(note.getRelations("related")).toEqual([ related ]);+ expect(note.getOwnedRelations("related")).toEqual([ related ]);+ expect(note.getRelationValue("related")).toBe("target");+ expect(note.getOwnedRelationValue("related")).toBe("target");+ expect(note.getRelationTarget("related")).toBe(target);+ expect(note.getRelationTarget("missing")).toBeNull();++ expect(note.getOwnedAttributes("label", "#color")).toEqual([ color, color2 ]);+ expect(note.getOwnedAttributes("relation", "~related")).toEqual([ related ]);+ expect(note.getOwnedAttributes("relation", "")).toEqual([ related ]);+ expect(note.getOwnedAttributes("", "color")).toEqual([ color, color2 ]);+ expect(note.getOwnedAttributes("", "")).toEqual(note.ownedAttributes);+ expect(note.getOwnedAttributes("", "")).not.toBe(note.ownedAttributes);+ expect(note.getOwnedAttribute("label", "missing")).toBeNull();+ expect(note.hasOwnedAttribute("label", "enabled")).toBe(true);+ expect(note.getAttributeValue("relation", "missing")).toBeNull();+ expect(note.getOwnedAttributeValue("label", "missing")).toBeNull();+ });++ it("describes itself for the share page and its API", () => {+ const parent = buildShareNote({+ id: "parent",+ title: "Tom & Jerry",+ "#iconClass": "bx bx-star",+ "~related": "parent",+ attachments: [ { id: "att", title: "Diagram", mime: "image/png", role: "image" } ],+ children: [ { id: "child" }, { id: "hidden", "#shareHiddenFromTree": "" } ]+ });+ new SAttribute([ "otherIcon", "parent", "label", "iconClass", "tn-icon-x", false, 9 ]);+ const aliased = buildShareNote({ id: "aliased", "#shareAlias": "my-alias" });+ const root = buildShareNote({ id: "rootNote", "#shareRoot": "" });++ expect([ parent, aliased, root ].map((note) => note.shareId))+ .toEqual([ "parent", "my-alias", "" ]);+ expect(parent.escapedTitle).toBe("Tom & Jerry");+ expect(parent.encodedTitle).toBe("Tom%20%26%20Jerry");+ expect(parent.getAttachmentByTitle("Diagram")?.getPojo().attachmentId).toBe("att");+ expect(parent.getAttachmentByTitle("Missing")).toBeUndefined();+ expect(parent.getIcon()).toBe("tn-icon bx bx-star");+ expect(parent.getIcon([ "tn-icon" ])).toBe("tn-icon tn-icon-x");++ const pojo = parent.getPojo();+ expect(pojo).toMatchObject({+ noteId: "parent",+ title: "Tom & Jerry",+ type: "text",+ mime: "text/html",+ parentNoteIds: [],+ childNoteIds: [ "child" ]+ });+ expect(pojo.attributes.map((attr) => attr.name)).toEqual([ "iconClass", "iconClass" ]);+ expect(pojo.attachments.map((attachment) => attachment.attachmentId)).toEqual([ "att" ]);+ expect(shaca.getNote("child").getPojo().parentNoteIds).toEqual([ "parent" ]);+ });++ it("hides a protected note's title", () => {+ const note = buildShareNote({ id: "locked", title: "Secret plans", isProtected: true });++ expect(note.title).toBe("[protected]");+ expect(note.isProtected).toBe(true);+ });+});++function addAttribute(id: string, noteId: string, type: string, name: string, value: string,+ isInheritable = false) {+ return new SAttribute([ id, noteId, type, name, value, isInheritable, 0 ]);+}diff --git a/packages/trilium-core/src/share/shaca/entities/snote.ts b/packages/trilium-core/src/share/shaca/entities/snote.tsindex 979120f543..08b256f206 100644--- a/packages/trilium-core/src/share/shaca/entities/snote.ts+++ b/packages/trilium-core/src/share/shaca/entities/snote.ts@@ -29,7 +29,6 @@ class SNote extends AbstractShacaEntity {children: SNote[];ownedAttributes: SAttribute[];private __attributeCache: SAttribute[] | null;- private __inheritableAttributeCache: SAttribute[] | null;targetRelations: SAttribute[];attachments: SAttachment[];@@ -50,7 +49,6 @@ class SNote extends AbstractShacaEntity {this.ownedAttributes = [];this.__attributeCache = null;- this.__inheritableAttributeCache = null;this.targetRelations = [];this.attachments = [];@@ -87,7 +85,7 @@ class SNote extends AbstractShacaEntity {}hasChildren() {- return this.children && this.children.length > 0;+ return this.children.length > 0;}hasVisibleChildren() {@@ -181,14 +179,6 @@ class SNote extends AbstractShacaEntity {this.__attributeCache.push(attr);}}-- this.__inheritableAttributeCache = [];-- for (const attr of this.__attributeCache) {- if (attr.isInheritable) {- this.__inheritableAttributeCache.push(attr);- }- }}return this.__attributeCache;@@ -199,11 +189,7 @@ class SNote extends AbstractShacaEntity {return [];}- if (!this.__inheritableAttributeCache) {- this.__getAttributes(path); // will refresh also this.__inheritableAttributeCache- }-- return this.__inheritableAttributeCache || [];+ return this.__getAttributes(path).filter((attr) => attr.isInheritable);}/**diff --git a/packages/trilium-core/src/share/shaca/shaca.spec.ts b/packages/trilium-core/src/share/shaca/shaca.spec.tsnew file mode 100644index 0000000000..d8bc34e505--- /dev/null+++ b/packages/trilium-core/src/share/shaca/shaca.spec.ts@@ -0,0 +1,47 @@+import { beforeEach, describe, expect, it } from "vitest";++import { buildShareNote } from "../../test/shaca_mocking.js";+import shaca from "./shaca.js";++describe("shaca", () => {+ beforeEach(() => {+ shaca.reset();+ });++ it("looks up notes by ID, failing on a missing one unless told to skip it", () => {+ const first = buildShareNote({ id: "first" });+ const second = buildShareNote({ id: "second" });++ expect(shaca.hasNote("first")).toBe(true);+ expect(shaca.hasNote("missing")).toBe(false);+ expect(shaca.getNotes([ "second", "first" ])).toEqual([ second, first ]);+ expect(shaca.getNotes([ "first", "missing", "second" ], true)).toEqual([ first, second ]);+ expect(() => shaca.getNotes([ "first", "missing" ])).toThrow(+ "Note 'missing' was not found in shaca."+ );+ });++ it("looks up branches, attributes and attachments by ID and by entity name", () => {+ const parent = buildShareNote({+ id: "parent",+ "#color": "red",+ attachments: [ { id: "attachment", title: "Attachment" } ],+ children: [ { id: "child" } ]+ });+ const branch = shaca.getBranchFromChildAndParent("child", "parent");+ const [ label ] = parent.getOwnedLabels("color");+ const [ attachment ] = parent.getAttachments();++ expect(branch.getParentNote()).toBe(parent);+ expect(Object.keys(shaca.branches)).toHaveLength(1);+ expect(shaca.getBranch(Object.keys(shaca.branches)[0])).toBe(branch);+ expect(shaca.getAttribute(label.attributeId)).toBe(label);+ expect(shaca.getAttachment("attachment")).toBe(attachment);++ expect(shaca.getEntity("notes", "parent")).toBe(parent);+ expect(shaca.getEntity("attributes", label.attributeId)).toBe(label);+ expect(shaca.getEntity("child_parent_to_branch", "child-parent")).toBe(branch);+ expect(shaca.getEntity("", "parent")).toBeNull();+ expect(shaca.getEntity("notes", "")).toBeNull();+ });+});diff --git a/packages/trilium-core/src/share/shaca/shaca_loader.spec.ts b/packages/trilium-core/src/share/shaca/shaca_loader.spec.tsnew file mode 100644index 0000000000..dc59b22147--- /dev/null+++ b/packages/trilium-core/src/share/shaca/shaca_loader.spec.ts@@ -0,0 +1,72 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { stubShareSql } from "../../test/shaca_mocking.js";+import shaca from "./shaca.js";+import shacaLoader from "./shaca_loader.js";++const ROWS: Record<string, unknown[][]> = {+ notes: [+ [ "_share", "Shared", "text", "text/html", "blob1", "2025-01-01", false ],+ [ "open", "Open", "text", "text/html", "blob2", "2025-01-01", false ],+ [ "locked", "Secret", "text", "text/html", "blob3", "2025-01-01", true ]+ ],+ branches: [+ [ "_share_open", "open", "_share", "", false, "2025-01-01" ],+ [ "_share_locked", "locked", "_share", "", false, "2025-01-01" ]+ ],+ attributes: [+ [ "attr1", "_share", "label", "shareIndex", "", false, 10 ]+ ],+ attachments: [+ [ "openAttachment", "open", "file", "text/plain", "Notes", "blob4", "2025-01-01" ],+ [ "lockedAttachment", "locked", "file", "text/plain", "Keys", "blob5", "2025-01-01" ]+ ]+};++describe("shaca loader", () => {+ const getColumn = vi.fn(() => [ "_share", "open", "locked" ]);+ const getRawRows = vi.fn((query: string) => ROWS[/FROM (\w+)/.exec(query)?.[1] ?? ""]);+ let restore: () => void;++ beforeEach(() => {+ shaca.reset();+ getColumn.mockClear();+ getRawRows.mockClear();+ restore = stubShareSql({ getColumn, getRawRows });+ });++ afterEach(() => {+ restore();+ shaca.reset();+ });++ it("loads the share subtree and leaves protected notes' attachments out", () => {+ shacaLoader.load();++ expect(getColumn)+ .toHaveBeenCalledWith(expect.stringContaining("WITH RECURSIVE"), [ "_share" ]);+ for (const [ query ] of getRawRows.mock.calls) {+ expect(query).toContain("('_share','open','locked')");+ }+ expect(shaca.loaded).toBe(true);+ expect(Object.keys(shaca.notes)).toEqual([ "_share", "open", "locked" ]);+ expect(shaca.getNote("_share").getChildNotes().map((note) => note.noteId))+ .toEqual([ "open", "locked" ]);+ expect(shaca.getNote("locked").title).toBe("[protected]");+ expect(shaca.shareIndexEnabled).toBe(true);+ expect(Object.keys(shaca.attachments)).toEqual([ "openAttachment" ]);+ expect(shaca.getNote("open").getAttachments().map((a) => a.title)).toEqual([ "Notes" ]);+ expect(shaca.getNote("locked").getAttachments()).toEqual([]);+ });++ it("loads only while the cache is empty", () => {+ shacaLoader.ensureLoad();+ shacaLoader.ensureLoad();+ expect(getColumn).toHaveBeenCalledTimes(1);++ shaca.reset();+ shacaLoader.ensureLoad();+ expect(getColumn).toHaveBeenCalledTimes(2);+ expect(shaca.hasNote("open")).toBe(true);+ });+});diff --git a/packages/trilium-core/src/share/shaca/shaca_loader.ts b/packages/trilium-core/src/share/shaca/shaca_loader.tsindex aba5b85b21..5becd65afd 100644--- a/packages/trilium-core/src/share/shaca/shaca_loader.ts+++ b/packages/trilium-core/src/share/shaca/shaca_loader.ts@@ -29,12 +29,6 @@ function load() {[shareRoot.SHARE_ROOT_NOTE_ID]);- if (noteIds.length === 0) {- shaca.loaded = true;-- return;- }-const noteIdStr = noteIds.map((noteId) => `'${noteId}'`).join(",");const rawNoteRows = sql.getRawRows<SNoteRow>(`@@ -79,7 +73,7 @@ function load() {// shared, so their attachments must never enter the share cache. The// note was loaded above (attachments are scoped to the same subtree).const [, ownerId] = row;- if (shaca.notes[ownerId]?.isProtected) {+ if (shaca.notes[ownerId].isProtected) {continue;}diff --git a/packages/trilium-core/src/share/share_provider.spec.ts b/packages/trilium-core/src/share/share_provider.spec.tsnew file mode 100644index 0000000000..2589f1f1b3--- /dev/null+++ b/packages/trilium-core/src/share/share_provider.spec.ts@@ -0,0 +1,47 @@+import { describe, expect, it, vi } from "vitest";++import { stubShareSql } from "../test/shaca_mocking.js";+import sql from "./sql.js";++describe("share provider", () => {+ it("refuses to be read before a platform registers it, then answers through it", async () => {+ // A fresh module instance holds no provider, unlike the one the test setup registered.+ vi.resetModules();+ const { getShareProvider, initShare, isShareReady } = await import("./share_provider.js");++ expect(() => getShareProvider()).toThrow("Share provider has not been initialized");+ expect(isShareReady()).toBe(false);++ let ready = false;+ const provider = {+ sql: { getRawRows: vi.fn(), getRow: vi.fn(), getColumn: vi.fn() },+ readTemplate: vi.fn(),+ isScriptingEnabled: () => false,+ isReady: () => ready+ };+ initShare(provider);++ expect(getShareProvider()).toBe(provider);+ expect(isShareReady()).toBe(false);+ ready = true;+ expect(isShareReady()).toBe(true);+ });++ it("forwards the share cache's queries to the provider, with no parameters by default", () => {+ const getRawRows = vi.fn(() => [ [ "a" ] ]);+ const getRow = vi.fn(() => ({ content: "x" }));+ const getColumn = vi.fn(() => [ "b" ]);+ const restore = stubShareSql({ getRawRows, getRow, getColumn });++ try {+ expect(sql.getRawRows("rows")).toEqual([ [ "a" ] ]);+ expect(sql.getRow("row", [ "1" ])).toEqual({ content: "x" });+ expect(sql.getColumn("column")).toEqual([ "b" ]);+ expect(getRawRows).toHaveBeenCalledWith("rows", []);+ expect(getRow).toHaveBeenCalledWith("row", [ "1" ]);+ expect(getColumn).toHaveBeenCalledWith("column", []);+ } finally {+ restore();+ }+ });+});diff --git a/packages/trilium-core/src/test/shaca_mocking.ts b/packages/trilium-core/src/test/shaca_mocking.tsindex 857ad6470d..516271ba5a 100644--- a/packages/trilium-core/src/test/shaca_mocking.ts+++ b/packages/trilium-core/src/test/shaca_mocking.ts@@ -4,9 +4,11 @@ import SAttribute from "../share/shaca/entities/sattribute.js";import SBranch from "../share/shaca/entities/sbranch.js";import SNote from "../share/shaca/entities/snote.js";import shaca from "../share/shaca/shaca.js";+import { getShareProvider, initShare, type ShareSql } from "../share/share_provider.js";type AttributeDefinitions = { [key in `#${string}`]: string; };type RelationDefinitions = { [key in `~${string}`]: string; };+type ShareSqlStub = { [key in keyof ShareSql]?: (query: string, params: string[]) => unknown; };interface AttachementDefinition {id?: string;@@ -145,3 +147,16 @@ export function buildShareNote(noteDef: NoteDefinition) {}return note;}++/**+ * Registers a share provider whose `sql` answers with the given accessors and keeps the rest of the+ * registered provider.+ *+ * @returns a function that registers the previous provider again.+ */+export function stubShareSql(sql: ShareSqlStub) {+ const original = getShareProvider();+ initShare({ ...original, sql: { ...original.sql, ...sql } as ShareSql });++ return () => initShare(original);+}