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(server): increase ETAPI coverage
Elian Doranbe206feceea3
diff --git a/apps/server/spec/etapi/attachment-content.spec.ts b/apps/server/spec/etapi/attachment-content.spec.tsindex 12c90c1551..5fc9e41657 100644--- a/apps/server/spec/etapi/attachment-content.spec.ts+++ b/apps/server/spec/etapi/attachment-content.spec.ts@@ -1,8 +1,10 @@+import { cls } from "@triliumnext/core";import { Application } from "express";import { beforeAll, describe, expect, it } from "vitest";import supertest from "supertest";import { createNote, login } from "./utils.js";import config from "../../src/services/config.js";+import sql from "../../src/services/sql.js";let app: Application;let token: string;@@ -61,4 +63,25 @@ describe("etapi/attachment-content", () => {.expect(204);});+ it("refuses to read and write a protected attachment's content", async () => {+ cls.init(() => sql.execute("UPDATE attachments SET isProtected = 1 WHERE attachmentId = ?", [createdAttachmentId]));+ try {+ const get = await supertest(app)+ .get(`/etapi/attachments/${createdAttachmentId}/content`)+ .auth(USER, token, { "type": "basic"})+ .expect(400);+ expect(get.body.code).toStrictEqual("ATTACHMENT_IS_PROTECTED");++ const put = await supertest(app)+ .put(`/etapi/attachments/${createdAttachmentId}/content`)+ .auth(USER, token, { "type": "basic"})+ .set("Content-Type", "text/plain")+ .send("data")+ .expect(400);+ expect(put.body.code).toStrictEqual("ATTACHMENT_IS_PROTECTED");+ } finally {+ cls.init(() => sql.execute("UPDATE attachments SET isProtected = 0 WHERE attachmentId = ?", [createdAttachmentId]));+ }+ });+});diff --git a/apps/server/spec/etapi/auth-login.spec.ts b/apps/server/spec/etapi/auth-login.spec.tsindex 6213ede085..b5f43054a1 100644--- a/apps/server/spec/etapi/auth-login.spec.ts+++ b/apps/server/spec/etapi/auth-login.spec.ts@@ -45,6 +45,14 @@ describe("etapi/auth/login", () => {expect(response.body.authToken).toBeUndefined();});+ it("reports a 500 when the password is missing and cannot be verified", async () => {+ // No password field → verifyPassword throws → caught by the middleware.+ await supertest(app)+ .post(LOGIN_URL)+ .send({ tokenName: "test" })+ .expect(500);+ });+// A token must never be issued from a failed login, and even if one were, it must not// grant access to data.it("does not grant data access from a wrong-password login attempt", async () => {diff --git a/apps/server/spec/etapi/create-backup.spec.ts b/apps/server/spec/etapi/create-backup.spec.tsindex 00c8751aa4..6e0d640fa7 100644--- a/apps/server/spec/etapi/create-backup.spec.ts+++ b/apps/server/spec/etapi/create-backup.spec.ts@@ -1,5 +1,6 @@+import { getBackup } from "@triliumnext/core";import { Application } from "express";-import { beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import supertest from "supertest";import { login } from "./utils.js";import config from "../../src/services/config.js";@@ -18,9 +19,21 @@ describe("etapi/backup", () => {});it("backup works", async () => {- const response = await supertest(app)+ await supertest(app).put("/etapi/backup/etapi_test").auth(USER, token, { "type": "basic"}).expect(204);});++ it("reports a 500 when the backup fails", async () => {+ vi.spyOn(getBackup(), "backupNow").mockRejectedValue(new Error("boom"));+ try {+ await supertest(app)+ .put("/etapi/backup/etapi_fail")+ .auth(USER, token, { "type": "basic"})+ .expect(500);+ } finally {+ vi.restoreAllMocks();+ }+ });});diff --git a/apps/server/spec/etapi/create-entities.spec.ts b/apps/server/spec/etapi/create-entities.spec.tsindex 25dab1d458..ddf98c522a 100644--- a/apps/server/spec/etapi/create-entities.spec.ts+++ b/apps/server/spec/etapi/create-entities.spec.ts@@ -1,5 +1,6 @@+import { BBranch, note_service as noteService } from "@triliumnext/core";import { Application } from "express";-import { beforeAll, describe, expect, it } from "vitest";+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";import supertest from "supertest";import { login } from "./utils.js";import config from "../../src/services/config.js";@@ -95,6 +96,63 @@ describe("etapi/create-entities", () => {title: "my attachment"});});++ describe("error and edge cases", () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it("rejects creating an image note with a non-image MIME", async () => {+ const response = await supertest(app)+ .post("/etapi/create-note")+ .auth(USER, token, { "type": "basic"})+ .send({ parentNoteId: "root", title: "img", type: "image", mime: "text/plain" })+ .expect(400);+ expect(response.body.code).toStrictEqual("INVALID_MIME_FOR_IMAGE");+ });++ it("reports a 500 when note creation throws", async () => {+ vi.spyOn(noteService, "createNewNote").mockImplementation(() => {+ throw new Error("boom");+ });+ const response = await supertest(app)+ .post("/etapi/create-note")+ .auth(USER, token, { "type": "basic"})+ .send({ parentNoteId: "root", title: "x", type: "text", content: "x" })+ .expect(500);+ expect(response.body.code).toStrictEqual("GENERIC");+ });++ it("creates a relation attribute, validating the target note", async () => {+ const response = await supertest(app)+ .post("/etapi/attributes")+ .auth(USER, token, { "type": "basic"})+ .send({ noteId: createdNoteId, type: "relation", name: "myrelation", value: "root" })+ .expect(201);+ expect(response.body.type).toStrictEqual("relation");+ });++ it("reports a 400 when branch creation throws", async () => {+ // A fresh note with no existing branch under _hidden, so the route takes the+ // "new BBranch().save()" path (the try/catch) rather than updating an existing one.+ const noteResp = await supertest(app)+ .post("/etapi/create-note")+ .auth(USER, token, { "type": "basic"})+ .send({ parentNoteId: "root", title: "branch-fail", type: "text", content: "x" })+ .expect(201);+ const noteId = noteResp.body.note.noteId;++ vi.spyOn(BBranch.prototype, "save").mockImplementation(() => {+ throw new Error("boom");+ });+ const response = await supertest(app)+ .post("/etapi/branches")+ .auth(USER, token, { "type": "basic"})+ .send({ noteId, parentNoteId: "_hidden" })+ .expect(400);+ expect(response.body.code).toStrictEqual("GENERIC");+ });+ });});async function createNote() {diff --git a/apps/server/spec/etapi/get-date-notes.spec.ts b/apps/server/spec/etapi/get-date-notes.spec.tsindex 2f7eb2ecb6..e3257f1bd1 100644--- a/apps/server/spec/etapi/get-date-notes.spec.ts+++ b/apps/server/spec/etapi/get-date-notes.spec.ts@@ -26,6 +26,40 @@ describe("etapi/get-date-notes", () => {.expect(200);});+ it("rejects an invalid inbox date", async () => {+ const response = await supertest(app)+ .get("/etapi/inbox/not-a-date")+ .auth(USER, token, { "type": "basic"})+ .expect(400);+ expect(response.body.code).toStrictEqual("DATE_INVALID");+ });++ describe("week-first-day", () => {+ it("obtains the week's first day note", async () => {+ await supertest(app)+ .get("/etapi/calendar/week-first-day/2022-01-01")+ .auth(USER, token, { "type": "basic"})+ .expect(200);+ });++ it("detects invalid date", async () => {+ const response = await supertest(app)+ .get("/etapi/calendar/week-first-day/not-a-date")+ .auth(USER, token, { "type": "basic"})+ .expect(400);+ expect(response.body.code).toStrictEqual("DATE_INVALID");+ });+ });++ // Runs before the "weeks" suite below enables week notes, so the lookup misses.+ it("returns 404 for a well-formed week when week notes are disabled", async () => {+ const response = await supertest(app)+ .get("/etapi/calendar/weeks/2022-W01")+ .auth(USER, token, { "type": "basic"})+ .expect(404);+ expect(response.body.code).toStrictEqual("WEEK_NOT_FOUND");+ });+describe("days", () => {it("obtains day from calendar", async () => {await supertest(app)diff --git a/apps/server/spec/etapi/get-revision.spec.ts b/apps/server/spec/etapi/get-revision.spec.tsindex 641f5255a7..0f77ce5b2c 100644--- a/apps/server/spec/etapi/get-revision.spec.ts+++ b/apps/server/spec/etapi/get-revision.spec.ts@@ -1,8 +1,10 @@+import { cls } from "@triliumnext/core";import { Application } from "express";import { beforeAll, describe, expect, it } from "vitest";import supertest from "supertest";import { createNote, login } from "./utils.js";import config from "../../src/services/config.js";+import sql from "../../src/services/sql.js";let app: Application;let token: string;@@ -68,4 +70,17 @@ describe("etapi/get-revision", () => {expect(response.body.code).toStrictEqual("REVISION_NOT_FOUND");});++ it("refuses to read a protected revision", async () => {+ cls.init(() => sql.execute("UPDATE revisions SET isProtected = 1 WHERE revisionId = ?", [revisionId]));+ try {+ const response = await supertest(app)+ .get(`/etapi/revisions/${revisionId}`)+ .auth(USER, token, { "type": "basic" })+ .expect(400);+ expect(response.body.code).toStrictEqual("REVISION_IS_PROTECTED");+ } finally {+ cls.init(() => sql.execute("UPDATE revisions SET isProtected = 0 WHERE revisionId = ?", [revisionId]));+ }+ });});diff --git a/apps/server/spec/etapi/metrics-format.spec.ts b/apps/server/spec/etapi/metrics-format.spec.tsnew file mode 100644index 0000000000..e4ce8476b7--- /dev/null+++ b/apps/server/spec/etapi/metrics-format.spec.ts@@ -0,0 +1,90 @@+import { describe, expect, it } from "vitest";++import metrics from "../../src/etapi/metrics.js";++// `collectMetrics` is exercised end-to-end by etapi-metrics.spec.ts; here we lock down+// `formatPrometheusMetrics`, whose null-handling branches the live DB never produces+// (it always has notes, dates and a measurable size).+describe("etapi/metrics formatPrometheusMetrics", () => {+ const baseVersion = {+ app: "1.0.0",+ db: 228,+ node: undefined,+ sync: 1,+ buildDate: "2026-01-01",+ buildRevision: "abc123"+ };++ it("skips metrics whose value is null and statistics that are absent", () => {+ const text = metrics.formatPrometheusMetrics({+ version: baseVersion,+ database: {+ // a null count must be omitted entirely+ totalNotes: null as unknown as number,+ deletedNotes: 0,+ activeNotes: 0,+ protectedNotes: 0,+ totalAttachments: 0,+ deletedAttachments: 0,+ activeAttachments: 0,+ totalRevisions: 0,+ totalBranches: 0,+ totalAttributes: 0,+ totalBlobs: 0,+ totalEtapiTokens: 0,+ totalRecentNotes: 0+ },+ noteTypes: {},+ attachmentTypes: {},+ statistics: {+ oldestNote: null,+ newestNote: null,+ lastModified: null,+ databaseSizeBytes: null+ },+ timestamp: "2026-01-01T00:00:00.000Z"+ });++ expect(text).not.toContain("trilium_notes_total");+ expect(text).not.toContain("trilium_database_size_bytes");+ expect(text).not.toContain("trilium_oldest_note_timestamp");+ expect(text).toContain("trilium_info");+ });++ it("emits type/mime breakdowns and timestamped statistics when present", () => {+ const text = metrics.formatPrometheusMetrics({+ version: { ...baseVersion, node: "20.0.0" },+ database: {+ totalNotes: 10,+ deletedNotes: 1,+ activeNotes: 9,+ protectedNotes: 2,+ totalAttachments: 3,+ deletedAttachments: 0,+ activeAttachments: 3,+ totalRevisions: 4,+ totalBranches: 9,+ totalAttributes: 5,+ totalBlobs: 6,+ totalEtapiTokens: 1,+ totalRecentNotes: 7+ },+ noteTypes: { text: 8, code: 1 },+ attachmentTypes: { "image/png": 3 },+ statistics: {+ oldestNote: "2026-01-01T00:00:00.000Z",+ newestNote: "2026-02-01T00:00:00.000Z",+ lastModified: "2026-03-01T00:00:00.000Z",+ databaseSizeBytes: 4096+ },+ timestamp: "2026-01-01T00:00:00.000Z"+ });++ expect(text).toContain("trilium_notes_total 10");+ expect(text).toContain('trilium_notes_by_type{type="text"} 8');+ expect(text).toContain('trilium_attachments_by_type{mime_type="image/png"} 3');+ expect(text).toContain("trilium_database_size_bytes 4096");+ expect(text).toContain("trilium_oldest_note_timestamp");+ expect(text).toContain("trilium_last_modified_timestamp");+ });+});diff --git a/apps/server/spec/etapi/no-auth-logout.spec.ts b/apps/server/spec/etapi/no-auth-logout.spec.tsnew file mode 100644index 0000000000..34eb189556--- /dev/null+++ b/apps/server/spec/etapi/no-auth-logout.spec.ts@@ -0,0 +1,26 @@+import { Application } from "express";+import supertest from "supertest";+import { afterAll, beforeAll, describe, expect, it } from "vitest";++import config from "../../src/services/config.js";++let app: Application;++// `noAuthentication` is captured at module load in etapi_utils.ts, so it must be set+// before the app (and its ETAPI router) is first imported in this isolated fork.+describe("etapi with noAuthentication enabled", () => {+ beforeAll(async () => {+ config.General.noAuthentication = true;+ const buildApp = (await import("../../src/app.js")).default;+ app = await buildApp();+ });++ afterAll(() => {+ config.General.noAuthentication = false;+ });++ it("rejects logout when the request carries no usable token", async () => {+ const response = await supertest(app).post("/etapi/auth/logout").expect(400);+ expect(response.body.code).toStrictEqual("GENERIC");+ });+});diff --git a/apps/server/spec/etapi/note-content.spec.ts b/apps/server/spec/etapi/note-content.spec.tsindex 5b7fdcba82..6d6adac16b 100644--- a/apps/server/spec/etapi/note-content.spec.ts+++ b/apps/server/spec/etapi/note-content.spec.ts@@ -1,3 +1,4 @@+import { becca } from "@triliumnext/core";import { Application } from "express";import { beforeAll, describe, expect, it } from "vitest";import supertest from "supertest";@@ -63,6 +64,29 @@ describe("etapi/note-content", () => {.expect(204);});+ it("refuses to read and write a protected note's content", async () => {+ const noteId = await createNote(app, token);+ const note = becca.getNoteOrThrow(noteId);+ note.isProtected = true;+ try {+ const get = await supertest(app)+ .get(`/etapi/notes/${noteId}/content`)+ .auth(USER, token, { "type": "basic"})+ .expect(400);+ expect(get.body.code).toStrictEqual("NOTE_IS_PROTECTED");++ const put = await supertest(app)+ .put(`/etapi/notes/${noteId}/content`)+ .auth(USER, token, { "type": "basic"})+ .set("Content-Type", "text/plain")+ .send("data")+ .expect(400);+ expect(put.body.code).toStrictEqual("NOTE_IS_PROTECTED");+ } finally {+ note.isProtected = false;+ }+ });+function getContentResponse() {return supertest(app).get(`/etapi/notes/${createdNoteId}/content`)diff --git a/apps/server/spec/etapi/note-history.spec.ts b/apps/server/spec/etapi/note-history.spec.tsindex 7696c00516..0abeb1dd11 100644--- a/apps/server/spec/etapi/note-history.spec.ts+++ b/apps/server/spec/etapi/note-history.spec.ts@@ -1,8 +1,10 @@+import { cls, password_encryption, protected_session } from "@triliumnext/core";import { Application } from "express";import { beforeAll, describe, expect, it } from "vitest";import supertest from "supertest";import { createNote, login } from "./utils.js";import config from "../../src/services/config.js";+import sql from "../../src/services/sql.js";let app: Application;let token: string;@@ -91,4 +93,49 @@ describe("etapi/note-history", () => {expect(deletedEntry).toHaveProperty("canBeUndeleted");}});++ it("masks protected entries when no protected session is active", async () => {+ protected_session.resetDataKey();+ const noteId = await createNote(app, token);++ try {+ cls.init(() => sql.execute("UPDATE notes SET isProtected = 1 WHERE noteId = ?", [noteId]));++ const response = await supertest(app)+ .get("/etapi/notes/history")+ .auth(USER, token, { "type": "basic" })+ .expect(200);+ const change = response.body.find((c: { noteId: string }) => c.noteId === noteId);+ expect(change?.title).toStrictEqual("[protected]");+ } finally {+ cls.init(() => sql.execute("UPDATE notes SET isProtected = 0 WHERE noteId = ?", [noteId]));+ }+ });++ it("decrypts protected entries when a protected session is active", async () => {+ const dataKey = await password_encryption.getDataKey("demo1234");+ if (!(dataKey instanceof Uint8Array)) {+ throw new Error("Expected a data key from the fixture password.");+ }+ const noteId = await createNote(app, token);++ try {+ protected_session.default.setDataKey(dataKey);+ const encryptedTitle = protected_session.default.encrypt("secret title");+ cls.init(() => sql.execute(+ "UPDATE notes SET isProtected = 1, title = ? WHERE noteId = ?",+ [encryptedTitle, noteId]+ ));++ const response = await supertest(app)+ .get("/etapi/notes/history")+ .auth(USER, token, { "type": "basic" })+ .expect(200);+ const change = response.body.find((c: { noteId: string }) => c.noteId === noteId);+ expect(change?.title).toStrictEqual("secret title");+ } finally {+ protected_session.resetDataKey();+ cls.init(() => sql.execute("UPDATE notes SET isProtected = 0 WHERE noteId = ?", [noteId]));+ }+ });});diff --git a/apps/server/spec/etapi/openapi-spec.spec.ts b/apps/server/spec/etapi/openapi-spec.spec.tsnew file mode 100644index 0000000000..63c3b0db09--- /dev/null+++ b/apps/server/spec/etapi/openapi-spec.spec.ts@@ -0,0 +1,25 @@+import { Application } from "express";+import { beforeAll, describe, expect, it } from "vitest";+import supertest from "supertest";++import config from "../../src/services/config.js";++let app: Application;++describe("etapi/etapi.openapi.yaml", () => {+ beforeAll(async () => {+ config.General.noAuthentication = false;+ const buildApp = (await import("../../src/app.js")).default;+ app = await buildApp();+ });++ it("serves the OpenAPI specification (and the cached copy on repeat)", async () => {+ const response = await supertest(app).get("/etapi/etapi.openapi.yaml").expect(200);+ expect(response.headers["content-type"]).toContain("text/plain");+ expect(response.text).toContain("openapi");++ // Second request is served from the in-memory cache.+ const cached = await supertest(app).get("/etapi/etapi.openapi.yaml").expect(200);+ expect(cached.text).toStrictEqual(response.text);+ });+});diff --git a/apps/server/spec/etapi/patch-attachment.spec.ts b/apps/server/spec/etapi/patch-attachment.spec.tsindex 706ac7fbbc..482de5ab5f 100644--- a/apps/server/spec/etapi/patch-attachment.spec.ts+++ b/apps/server/spec/etapi/patch-attachment.spec.ts@@ -1,8 +1,10 @@+import { cls } from "@triliumnext/core";import { Application } from "express";import { beforeAll, describe, expect, it } from "vitest";import supertest from "supertest";import { createNote, login } from "./utils.js";import config from "../../src/services/config.js";+import sql from "../../src/services/sql.js";let app: Application;let token: string;@@ -75,4 +77,27 @@ describe("etapi/attachment-content", () => {expect(response.body.code).toStrictEqual("PROPERTY_VALIDATION_ERROR");});+ it("reports a 500 when creating an attachment without an owner", async () => {+ const response = await supertest(app)+ .post("/etapi/attachments")+ .auth(USER, token, { "type": "basic"})+ .send({ role: "file", mime: "text/plain", title: "orphan" })+ .expect(500);+ expect(response.body.code).toStrictEqual("GENERIC");+ });++ it("refuses to patch a protected attachment", async () => {+ cls.init(() => sql.execute("UPDATE attachments SET isProtected = 1 WHERE attachmentId = ?", [createdAttachmentId]));+ try {+ const response = await supertest(app)+ .patch(`/etapi/attachments/${createdAttachmentId}`)+ .auth(USER, token, { "type": "basic"})+ .send({ title: "x" })+ .expect(400);+ expect(response.body.code).toStrictEqual("ATTACHMENT_IS_PROTECTED");+ } finally {+ cls.init(() => sql.execute("UPDATE attachments SET isProtected = 0 WHERE attachmentId = ?", [createdAttachmentId]));+ }+ });+});diff --git a/apps/server/spec/etapi/patch-attribute.spec.ts b/apps/server/spec/etapi/patch-attribute.spec.tsindex 821a4e3dba..1ebbee9162 100644--- a/apps/server/spec/etapi/patch-attribute.spec.ts+++ b/apps/server/spec/etapi/patch-attribute.spec.ts@@ -1,5 +1,6 @@+import { attributes as attributeService } from "@triliumnext/core";import { Application } from "express";-import { beforeAll, describe, expect, it } from "vitest";+import { beforeAll, describe, expect, it, vi } from "vitest";import supertest from "supertest";import { createNote, login } from "./utils.js";import config from "../../src/services/config.js";@@ -74,4 +75,45 @@ describe("etapi/patch-attribute", () => {expect(response.body.code).toStrictEqual("PROPERTY_VALIDATION_ERROR");});+ it("patches a relation's position and rejects changing its target", async () => {+ const created = await supertest(app)+ .post("/etapi/attributes")+ .auth(USER, token, { "type": "basic"})+ .send({ noteId: createdNoteId, type: "relation", name: "myrelation", value: "root" })+ .expect(201);+ const attributeId = created.body.attributeId;++ // Goes through the relation branch (target validation + patch).+ const patched = await supertest(app)+ .patch(`/etapi/attributes/${attributeId}`)+ .auth(USER, token, { "type": "basic"})+ .send({ position: 5 })+ .expect(200);+ expect(patched.body.position).toStrictEqual(5);++ // `value` (the relation target) is not a patchable property.+ const notAllowed = await supertest(app)+ .patch(`/etapi/attributes/${attributeId}`)+ .auth(USER, token, { "type": "basic"})+ .send({ value: "root" })+ .expect(400);+ expect(notAllowed.body.code).toStrictEqual("PROPERTY_NOT_ALLOWED");+ });++ it("reports a 500 when attribute creation throws", async () => {+ vi.spyOn(attributeService, "createAttribute").mockImplementation(() => {+ throw new Error("boom");+ });+ try {+ const response = await supertest(app)+ .post("/etapi/attributes")+ .auth(USER, token, { "type": "basic"})+ .send({ noteId: createdNoteId, type: "label", name: "boom", value: "x" })+ .expect(500);+ expect(response.body.code).toStrictEqual("GENERIC");+ } finally {+ vi.restoreAllMocks();+ }+ });+});diff --git a/apps/server/spec/etapi/patch-note.spec.ts b/apps/server/spec/etapi/patch-note.spec.tsindex 3d6a9cd598..4e726916ae 100644--- a/apps/server/spec/etapi/patch-note.spec.ts+++ b/apps/server/spec/etapi/patch-note.spec.ts@@ -1,7 +1,8 @@+import { becca } from "@triliumnext/core";import { Application } from "express";import { beforeAll, describe, expect, it } from "vitest";import supertest from "supertest";-import { login } from "./utils.js";+import { createNote, login } from "./utils.js";import config from "../../src/services/config.js";let app: Application;@@ -79,6 +80,31 @@ describe("etapi/patch-note", () => {expect(response.body.code).toStrictEqual("PROPERTY_VALIDATION_ERROR");});+ it("rejects turning a note into an image with a non-image MIME", async () => {+ const response = await supertest(app)+ .patch(`/etapi/notes/${createdNoteId}`)+ .auth("etapi", token, { "type": "basic"})+ .send({ type: "image", mime: "text/plain" })+ .expect(400);+ expect(response.body.code).toStrictEqual("INVALID_MIME_FOR_IMAGE");+ });++ it("refuses to patch a protected note", async () => {+ const noteId = await createNote(app, token);+ const note = becca.getNoteOrThrow(noteId);+ note.isProtected = true;+ try {+ const response = await supertest(app)+ .patch(`/etapi/notes/${noteId}`)+ .auth("etapi", token, { "type": "basic"})+ .send({ title: "x" })+ .expect(400);+ expect(response.body.code).toStrictEqual("NOTE_IS_PROTECTED");+ } finally {+ note.isProtected = false;+ }+ });+async function expectNoteToMatch(state: object) {const response = await supertest(app).get(`/etapi/notes/${createdNoteId}`)diff --git a/apps/server/spec/etapi/post-revision.spec.ts b/apps/server/spec/etapi/post-revision.spec.tsindex 6c17c88384..72cf60b25b 100644--- a/apps/server/spec/etapi/post-revision.spec.ts+++ b/apps/server/spec/etapi/post-revision.spec.ts@@ -26,4 +26,12 @@ describe("etapi/post-revision", () => {.send("Changed content").expect(204);});++ it("posts a note revision with a custom description", async () => {+ await supertest(app)+ .post(`/etapi/notes/${createdNoteId}/revision`)+ .auth(USER, token, { "type": "basic"})+ .send({ description: "manual snapshot" })+ .expect(204);+ });});diff --git a/apps/server/spec/etapi/revision-content.spec.ts b/apps/server/spec/etapi/revision-content.spec.tsindex 5d7d5e558a..e91f4816fe 100644--- a/apps/server/spec/etapi/revision-content.spec.ts+++ b/apps/server/spec/etapi/revision-content.spec.ts@@ -1,8 +1,10 @@+import { cls } from "@triliumnext/core";import { Application } from "express";import { beforeAll, describe, expect, it } from "vitest";import supertest from "supertest";import { createNote, login } from "./utils.js";import config from "../../src/services/config.js";+import sql from "../../src/services/sql.js";let app: Application;let token: string;@@ -61,4 +63,17 @@ describe("etapi/revision-content", () => {expect(response.body.code).toStrictEqual("REVISION_NOT_FOUND");});++ it("refuses to read a protected revision's content", async () => {+ cls.init(() => sql.execute("UPDATE revisions SET isProtected = 1 WHERE revisionId = ?", [revisionId]));+ try {+ const response = await supertest(app)+ .get(`/etapi/revisions/${revisionId}/content`)+ .auth(USER, token, { "type": "basic" })+ .expect(400);+ expect(response.body.code).toStrictEqual("REVISION_IS_PROTECTED");+ } finally {+ cls.init(() => sql.execute("UPDATE revisions SET isProtected = 0 WHERE revisionId = ?", [revisionId]));+ }+ });});diff --git a/apps/server/spec/etapi/search.spec.ts b/apps/server/spec/etapi/search.spec.tsindex bfd14e7400..72beed25a5 100644--- a/apps/server/spec/etapi/search.spec.ts+++ b/apps/server/spec/etapi/search.spec.ts@@ -1,5 +1,6 @@+import { search as searchService } from "@triliumnext/core";import { Application } from "express";-import { beforeAll, describe, expect, it } from "vitest";+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";import supertest from "supertest";import { createNote, login } from "./utils.js";import config from "../../src/services/config.js";@@ -37,4 +38,60 @@ describe("etapi/search", () => {.expect(200);expect(response.body.results).toHaveLength(0);});++ describe("query parameter handling", () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it("rejects a missing search query parameter", async () => {+ const response = await supertest(app)+ .get("/etapi/notes")+ .auth(USER, token, { "type": "basic"})+ .expect(400);+ expect(response.body.code).toStrictEqual("SEARCH_QUERY_PARAM_MANDATORY");+ });++ it("accepts string, order and integer parameters", async () => {+ await supertest(app)+ .get("/etapi/notes?search=root&ancestorNoteId=root&orderBy=title&orderDirection=asc&limit=5&includeArchivedNotes=true")+ .auth(USER, token, { "type": "basic"})+ .expect(200);+ });++ it("rejects a non-boolean flag", async () => {+ const response = await supertest(app)+ .get("/etapi/notes?search=root&fastSearch=maybe")+ .auth(USER, token, { "type": "basic"})+ .expect(400);+ expect(response.body.code).toStrictEqual("SEARCH_PARAM_VALIDATION_ERROR");+ });++ it("rejects an invalid order direction", async () => {+ const response = await supertest(app)+ .get("/etapi/notes?search=root&orderDirection=sideways")+ .auth(USER, token, { "type": "basic"})+ .expect(400);+ expect(response.body.code).toStrictEqual("SEARCH_PARAM_VALIDATION_ERROR");+ });++ it("rejects a non-integer limit", async () => {+ const response = await supertest(app)+ .get("/etapi/notes?search=root&limit=lots")+ .auth(USER, token, { "type": "basic"})+ .expect(400);+ expect(response.body.code).toStrictEqual("SEARCH_PARAM_VALIDATION_ERROR");+ });++ it("reports a generic 500 when the search service throws", async () => {+ vi.spyOn(searchService, "findResultsWithQuery").mockImplementation(() => {+ throw new Error("boom");+ });+ const response = await supertest(app)+ .get("/etapi/notes?search=root")+ .auth(USER, token, { "type": "basic"})+ .expect(500);+ expect(response.body.code).toStrictEqual("GENERIC");+ });+ });});diff --git a/apps/server/spec/etapi/undelete-note.spec.ts b/apps/server/spec/etapi/undelete-note.spec.tsindex 236539f4a1..1a6a214122 100644--- a/apps/server/spec/etapi/undelete-note.spec.ts+++ b/apps/server/spec/etapi/undelete-note.spec.ts@@ -100,4 +100,34 @@ describe("etapi/undelete-note", () => {expect(response.body.code).toStrictEqual("NOTE_NOT_DELETED");});++ it("returns 400 when there is no undeleted parent to restore under", async () => {+ // Create a parent with a child, then delete the parent so the child is+ // deleted with no undeletable parent branch.+ const parentId = `parent${randomInt(10000)}`;+ await supertest(app)+ .post("/etapi/create-note")+ .auth(USER, token, { "type": "basic" })+ .send({ noteId: parentId, parentNoteId: "root", title: "Parent", type: "text", content: "x" })+ .expect(201);++ const childResp = await supertest(app)+ .post("/etapi/create-note")+ .auth(USER, token, { "type": "basic" })+ .send({ parentNoteId: parentId, title: "Child", type: "text", content: "x" })+ .expect(201);+ const childId = childResp.body.note.noteId;++ await supertest(app)+ .delete(`/etapi/notes/${parentId}`)+ .auth(USER, token, { "type": "basic" })+ .expect(204);++ const response = await supertest(app)+ .post(`/etapi/notes/${childId}/undelete`)+ .auth(USER, token, { "type": "basic" })+ .expect(400);++ expect(response.body.code).toStrictEqual("CANNOT_UNDELETE");+ });});diff --git a/apps/server/spec/etapi/validators.spec.ts b/apps/server/spec/etapi/validators.spec.tsnew file mode 100644index 0000000000..d6c8a11ce3--- /dev/null+++ b/apps/server/spec/etapi/validators.spec.ts@@ -0,0 +1,71 @@+import { describe, expect, it } from "vitest";++import v from "../../src/etapi/validators.js";++// The in-memory fixture booted by spec/setup.ts initialises becca and the note-type+// service, so the becca-/service-backed validators (isNoteId, isNoteType) work directly.+describe("etapi/validators", () => {+ it("mandatory rejects undefined, accepts anything else", () => {+ expect(v.mandatory(undefined)).toBeTruthy();+ expect(v.mandatory(null)).toBeUndefined();+ expect(v.mandatory("x")).toBeUndefined();+ });++ it("notNull rejects null only", () => {+ expect(v.notNull(null)).toBeTruthy();+ expect(v.notNull(undefined)).toBeUndefined();+ expect(v.notNull("x")).toBeUndefined();+ });++ it("isString skips nullish, rejects non-strings", () => {+ expect(v.isString(undefined)).toBeUndefined();+ expect(v.isString(null)).toBeUndefined();+ expect(v.isString("x")).toBeUndefined();+ expect(v.isString(5)).toBeTruthy();+ });++ it("isLocalDateTime / isUtcDateTime skip non-strings", () => {+ expect(v.isLocalDateTime(5)).toBeUndefined();+ expect(v.isUtcDateTime(5)).toBeUndefined();+ expect(v.isLocalDateTime("2023-08-21 23:38:51.123+0200")).toBeUndefined();+ expect(v.isUtcDateTime("2023-08-21 23:38:51.123Z")).toBeUndefined();+ });++ it("isBoolean skips nullish, rejects non-booleans", () => {+ expect(v.isBoolean(undefined)).toBeUndefined();+ expect(v.isBoolean(true)).toBeUndefined();+ expect(v.isBoolean("nope")).toBeTruthy();+ });++ it("isInteger skips nullish, rejects non-integers", () => {+ expect(v.isInteger(undefined)).toBeUndefined();+ expect(v.isInteger(5)).toBeUndefined();+ expect(v.isInteger(1.5)).toBeTruthy();+ });++ it("isNoteId skips nullish, rejects non-strings and unknown ids", () => {+ expect(v.isNoteId(undefined)).toBeUndefined();+ expect(v.isNoteId("root")).toBeUndefined();+ expect(v.isNoteId(5)).toBeTruthy();+ expect(v.isNoteId("doesNotExist123")).toBeTruthy();+ });++ it("isNoteType skips nullish, rejects unknown types", () => {+ expect(v.isNoteType(undefined)).toBeUndefined();+ expect(v.isNoteType("text")).toBeUndefined();+ expect(v.isNoteType("notARealType")).toBeTruthy();+ });++ it("isAttributeType skips nullish, accepts label/relation, rejects others", () => {+ expect(v.isAttributeType(undefined)).toBeUndefined();+ expect(v.isAttributeType("label")).toBeUndefined();+ expect(v.isAttributeType("relation")).toBeUndefined();+ expect(v.isAttributeType("banana")).toBeTruthy();+ });++ it("isValidEntityId skips nullish, rejects malformed ids", () => {+ expect(v.isValidEntityId(undefined)).toBeUndefined();+ expect(v.isValidEntityId("abcd")).toBeUndefined();+ expect(v.isValidEntityId("!!")).toBeTruthy();+ });+});