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(core): improve coverage for services
Elian Doran92af46ba32d3
diff --git a/packages/trilium-core/src/services/in_app_help.spec.ts b/packages/trilium-core/src/services/in_app_help.spec.tsnew file mode 100644index 0000000000..88164b9721--- /dev/null+++ b/packages/trilium-core/src/services/in_app_help.spec.ts@@ -0,0 +1,103 @@+import { beforeAll, describe, expect, it } from "vitest";++import type { HiddenSubtreeItem } from "@triliumnext/commons";+import becca from "../becca/becca.js";+import { getContext } from "./context.js";+import {+ cleanUpHelp,+ getHelpHiddenSubtreeData,+ InAppHelpProvider,+ initInAppHelp+} from "./in_app_help.js";++function withContext<T>(fn: () => T): T {+ return getContext().init(fn);+}++/** Minimal concrete provider so the abstract `cleanUpHelp` logic can be exercised. */+class TestHelpProvider extends InAppHelpProvider {++ constructor(private data: HiddenSubtreeItem[]) {+ super();+ }+ getHelpHiddenSubtreeData(): HiddenSubtreeItem[] {+ return this.data;+ }++}++const noteService = (await import("./notes.js")).default;++/** Creates a note with a forced id under the given parent within the help subtree. */+function createHelpNote(noteId: string, parentNoteId: string) {+ return withContext(+ () =>+ noteService.createNewNote({+ noteId,+ parentNoteId,+ title: noteId,+ content: "help content",+ type: "text",+ // The help subtree (`_help*`) is a forbidden parent by default.+ ignoreForbiddenParents: true+ }).note+ );+}++describe("in_app_help - module accessors", () => {+ it("delegates getHelpHiddenSubtreeData to the registered provider", () => {+ // The server suite registers a real provider during initializeCore;+ // override it with a deterministic stub for this isolated fork.+ const data: HiddenSubtreeItem[] = [+ { id: "_helpFoo", title: "Foo", type: "text" }+ ];+ initInAppHelp(new TestHelpProvider(data));+ expect(getHelpHiddenSubtreeData()).toBe(data);+ });+});++describe("in_app_help - cleanUpHelp", () => {+ beforeAll(() => {+ // `_help` already exists in the fixture (empty). Build a subtree under it:+ // _help+ // ├── _helpKeep+ // │ └── _helpKeepChild+ // └── _helpStale+ createHelpNote("_helpKeep", "_help");+ createHelpNote("_helpKeepChild", "_helpKeep");+ createHelpNote("_helpStale", "_help");+ });++ it("deletes notes absent from the definition and preserves the rest", () => {+ // Definition keeps _helpKeep (and its child) but omits _helpStale.+ const definition: HiddenSubtreeItem[] = [+ {+ id: "_help",+ title: "Help",+ type: "text",+ children: [+ {+ id: "_helpKeep",+ title: "Keep",+ type: "text",+ children: [+ {+ id: "_helpKeepChild",+ title: "Keep child",+ type: "text"+ }+ ]+ }+ ]+ }+ ];++ withContext(() => cleanUpHelp(definition));++ // The stale note is gone; the kept notes (incl. nested child and root) survive.+ expect(becca.getNote("_helpStale")?.isDeleted ?? true).toBe(true);+ expect(becca.getNote("_helpKeep")?.isDeleted).toBe(false);+ expect(becca.getNote("_helpKeepChild")?.isDeleted).toBe(false);+ expect(becca.getNote("_help")?.isDeleted).toBe(false);+ });+});diff --git a/packages/trilium-core/src/services/safe_template.spec.ts b/packages/trilium-core/src/services/safe_template.spec.tsnew file mode 100644index 0000000000..e255e129e9--- /dev/null+++ b/packages/trilium-core/src/services/safe_template.spec.ts@@ -0,0 +1,200 @@+import { describe, expect, it, vi } from "vitest";+import { getLog } from "./log.js";+import { evaluateTemplate, evaluateTemplateSafe } from "./safe_template.js";++/**+ * A stand-in for the note-like objects passed into template evaluation. Only the+ * whitelisted properties/methods are exercised; method calls record their args so+ * we can assert the single string literal is forwarded verbatim.+ */+function fakeNote(overrides: Record<string, unknown> = {}) {+ return {+ title: "My Note",+ type: "text",+ noteId: "abc123",+ getLabelValue: (name: string) => `label:${name}`,+ getRelationValue: (name: string) => `relation:${name}`,+ format: (fmt: string) => `formatted(${fmt})`,+ ...overrides+ };+}++describe("safe_template - evaluateTemplate", () => {+ it("returns literal text unchanged when there are no expressions", () => {+ expect(evaluateTemplate("just text", {})).toBe("just text");+ });++ it("resolves a bare variable reference", () => {+ expect(evaluateTemplate("${note}", { note: "value" })).toBe("value");+ });++ it("resolves a single-level property access", () => {+ expect(evaluateTemplate("${note.title}", { note: fakeNote() })).toBe(+ "My Note"+ );+ });++ it("resolves a multi-level property chain (both segments whitelisted)", () => {+ // `content` and `title` are both whitelisted, so a two-hop chain resolves.+ const note = fakeNote({ content: { title: "inner" } });+ expect(evaluateTemplate("${note.content.title}", { note })).toBe(+ "inner"+ );+ });++ it("interpolates multiple expressions mixed with literal text", () => {+ const note = fakeNote();+ expect(evaluateTemplate("[${note.type}] ${note.title}", { note })).toBe(+ "[text] My Note"+ );+ });++ it("calls a whitelisted method with a single-quoted string argument", () => {+ const note = fakeNote();+ expect(+ evaluateTemplate("${note.getLabelValue('authorName')}", { note })+ ).toBe("label:authorName");+ });++ it("calls a whitelisted method with a double-quoted string argument", () => {+ const note = fakeNote();+ expect(evaluateTemplate('${note.format("YYYY-MM-DD")}', { note })).toBe(+ "formatted(YYYY-MM-DD)"+ );+ });++ it("calls a whitelisted method through a property chain", () => {+ const note = fakeNote({+ dateCreatedObj: { format: (f: string) => `date(${f})` }+ });+ expect(+ evaluateTemplate("${note.dateCreatedObj.format('MM-DD')}", {+ note+ })+ ).toBe("date(MM-DD)");+ });++ it("calls a whitelisted no-arg method", () => {+ const note = fakeNote({ getLabelValue: () => "no-arg-value" });+ expect(evaluateTemplate("${note.getLabelValue()}", { note })).toBe(+ "no-arg-value"+ );+ });++ it("renders null/undefined results as an empty string", () => {+ expect(+ evaluateTemplate("[${note.title}]", {+ note: fakeNote({ title: null })+ })+ ).toBe("[]");+ expect(+ evaluateTemplate("[${note.title}]", {+ note: fakeNote({ title: undefined })+ })+ ).toBe("[]");+ });++ it("returns empty string when a method target along the chain is null", () => {+ // resolvePropertyChain yields null because the root variable itself is null.+ expect(+ evaluateTemplate("${note.getLabelValue('x')}", { note: null })+ ).toBe("");+ });++ it("returns null (rendered empty) when a property on a null intermediate is accessed", () => {+ expect(evaluateTemplate("[${note.title}]", { note: null })).toBe("[]");+ });++ it("treats an empty string argument as a valid method argument", () => {+ const note = fakeNote({ getLabelValue: (name: string) => `[${name}]` });+ expect(evaluateTemplate("${note.getLabelValue('')}", { note })).toBe(+ "[]"+ );+ });+});++describe("safe_template - rejected expressions", () => {+ it("throws for an unknown root variable", () => {+ expect(() => evaluateTemplate("${missing.title}", {})).toThrow(+ /Unknown variable 'missing'/+ );+ });++ it("throws for a non-whitelisted property", () => {+ const note = fakeNote({ constructor: "evil" });+ expect(() => evaluateTemplate("${note.constructor}", { note })).toThrow(+ /Property 'constructor' is not allowed/+ );+ });++ it("throws for a non-whitelisted method", () => {+ const note = fakeNote({ toString: () => "boom" });+ expect(() => evaluateTemplate("${note.toString()}", { note })).toThrow(+ /Method 'toString' is not allowed/+ );+ });++ it("throws for a non-whitelisted method with an argument", () => {+ const note = fakeNote({ eval: (s: string) => s });+ expect(() => evaluateTemplate("${note.eval('1+1')}", { note })).toThrow(+ /Method 'eval' is not allowed/+ );+ });++ it("throws when a whitelisted method name resolves to a non-function", () => {+ // `format` is whitelisted but here it is a plain string, not callable.+ const note = fakeNote({ format: "not a function" });+ expect(() => evaluateTemplate("${note.format('x')}", { note })).toThrow(+ /'format' is not a function/+ );+ });++ it("throws when a whitelisted no-arg method name resolves to a non-function", () => {+ const note = fakeNote({ getLabelValue: 42 });+ expect(() =>+ evaluateTemplate("${note.getLabelValue()}", { note })+ ).toThrow(/'getLabelValue' is not a function/);+ });++ it("throws for syntactically unsupported expressions", () => {+ expect(() => evaluateTemplate("${1 + 1}", {})).toThrow(+ /is not a supported expression/+ );+ expect(() =>+ evaluateTemplate("${note['title']}", { note: fakeNote() })+ ).toThrow(/is not a supported expression/);+ expect(() =>+ evaluateTemplate("${note.method(unquotedArg)}", {+ note: fakeNote()+ })+ ).toThrow(/is not a supported expression/);+ });+});++describe("safe_template - evaluateTemplateSafe", () => {+ it("returns the interpolated value on success", () => {+ const note = fakeNote();+ expect(+ evaluateTemplateSafe("${note.title}", { note }, "fallback", "test")+ ).toBe("My Note");+ });++ it("returns the fallback and logs when evaluation throws", () => {+ const errorSpy = vi+ .spyOn(getLog(), "error")+ .mockImplementation(() => {});+ try {+ const result = evaluateTemplateSafe(+ "${missing.title}",+ {},+ "the-fallback",+ "my context"+ );+ expect(result).toBe("the-fallback");+ expect(errorSpy).toHaveBeenCalledOnce();+ expect(errorSpy.mock.calls[0]?.[0]).toContain("my context");+ } finally {+ errorSpy.mockRestore();+ }+ });+});diff --git a/packages/trilium-core/src/services/scripting_guard.spec.ts b/packages/trilium-core/src/services/scripting_guard.spec.tsnew file mode 100644index 0000000000..5f1900cd16--- /dev/null+++ b/packages/trilium-core/src/services/scripting_guard.spec.ts@@ -0,0 +1,51 @@+import { afterEach, describe, expect, it } from "vitest";+import { type CoreConfig, getConfig, initConfig } from "./config.js";+import {+ assertScriptingEnabled,+ assertSqlConsoleEnabled,+ isScriptingEnabled+} from "./scripting_guard.js";++const original = getConfig();++/** Restore whatever config the test harness injected so sibling specs are unaffected. */+afterEach(() => initConfig(original));++function withSecurity(security: Partial<CoreConfig["Security"]>) {+ initConfig({+ ...original,+ Security: {+ backendScriptingEnabled: false,+ sqlConsoleEnabled: false,+ ...security+ }+ });+}++describe("scripting_guard", () => {+ it("assertScriptingEnabled passes when backend scripting is enabled", () => {+ withSecurity({ backendScriptingEnabled: true });+ expect(() => assertScriptingEnabled()).not.toThrow();+ expect(isScriptingEnabled()).toBe(true);+ });++ it("assertScriptingEnabled throws when backend scripting is disabled", () => {+ withSecurity({ backendScriptingEnabled: false });+ expect(() => assertScriptingEnabled()).toThrow(+ /Backend script execution is disabled/+ );+ expect(isScriptingEnabled()).toBe(false);+ });++ it("assertSqlConsoleEnabled passes when the SQL console is enabled", () => {+ withSecurity({ sqlConsoleEnabled: true });+ expect(() => assertSqlConsoleEnabled()).not.toThrow();+ });++ it("assertSqlConsoleEnabled throws when the SQL console is disabled", () => {+ withSecurity({ sqlConsoleEnabled: false });+ expect(() => assertSqlConsoleEnabled()).toThrow(+ /SQL console is disabled/+ );+ });+});