Skip to content

Build your personal knowledge base with Trilium Notes

test(server): increase coverage of routes

Elian Doran058247ae1a59
diff --git a/apps/server/src/routes/api/clipper.spec.ts b/apps/server/src/routes/api/clipper.spec.ts
index d95570117b..02ffa68ee6 100644
--- a/apps/server/src/routes/api/clipper.spec.ts
+++ b/apps/server/src/routes/api/clipper.spec.ts
@@ -1,8 +1,8 @@
-import { becca_easy_mocking, BNote } from "@triliumnext/core";
+import { becca_easy_mocking, BNote, cls } from "@triliumnext/core";
+import type { Request } from "express";
import { beforeAll, describe, expect, it, vi } from "vitest";
-import { cls } from "@triliumnext/core";
-import { processContent } from "./clipper";
+import clipperRoute, { processContent } from "./clipper";
const { buildNote } = becca_easy_mocking;
@@ -54,3 +54,58 @@ describe("processContent", () => {
}
});
});
+
+// These exercise the route handlers against the real in-memory DB.
+describe("clipper route handlers", () => {
+ it("returns the handshake metadata", () => {
+ const result = clipperRoute.handshake();
+ expect(result.appName).toBe("trilium");
+ expect(result.protocolVersion).toBeTruthy();
+ });
+
+ it("reports open-in-browser when not running under Electron", () => {
+ const req = { params: { noteId: "root" } } as unknown as Request<{ noteId: string }>;
+ expect(clipperRoute.openNote(req)).toEqual({ result: "open-in-browser" });
+ });
+
+ it("creates a clipping note, then appends to it when clipped from the same URL", async () => {
+ const pageUrl = "https://example.com/article";
+ const first = await cls.init(() => clipperRoute.addClipping({
+ body: { title: "Article", content: "<p>first</p>", images: [], pageUrl }
+ } as unknown as Request));
+ expect(first.noteId).toBeTruthy();
+
+ const second = await cls.init(() => clipperRoute.addClipping({
+ body: { title: "Article", content: "<p>second</p>", images: [], pageUrl }
+ } as unknown as Request));
+ // Same pageUrl → appends to the existing clipping note.
+ expect(second.noteId).toBe(first.noteId);
+
+ const found = await cls.init(() => clipperRoute.findNotesByUrl({ params: { noteUrl: pageUrl } } as unknown as Request<{ noteUrl: string }>));
+ expect(found.noteId).toBe(first.noteId);
+ });
+
+ it("creates a standalone note with labels", async () => {
+ const result = await cls.init(() => clipperRoute.createNote({
+ body: {
+ title: "Clipped",
+ content: "<p>body</p>",
+ images: [],
+ clipType: "note",
+ pageUrl: "https://example.com/page",
+ labels: { source: "web" }
+ }
+ } as unknown as Request));
+ expect(result.noteId).toBeTruthy();
+ });
+
+ it("returns a null noteId when no clipping matches the URL", async () => {
+ const found = await cls.init(() => clipperRoute.findNotesByUrl({ params: { noteUrl: "https://nope.example/none" } } as unknown as Request<{ noteUrl: string }>));
+ expect(found.noteId).toBeNull();
+ });
+
+ it("returns a null noteId for an empty URL", async () => {
+ const found = await cls.init(() => clipperRoute.findNotesByUrl({ params: { noteUrl: "" } } as unknown as Request<{ noteUrl: string }>));
+ expect(found.noteId).toBeNull();
+ });
+});
diff --git a/apps/server/src/routes/api/database.spec.ts b/apps/server/src/routes/api/database.spec.ts
new file mode 100644
index 0000000000..df6de2cd82
--- /dev/null
+++ b/apps/server/src/routes/api/database.spec.ts
@@ -0,0 +1,96 @@
+import { getBackup, ValidationError } from "@triliumnext/core";
+import type { Request, Response } from "express";
+import fs from "fs";
+import path from "path";
+import { describe, expect, it, vi } from "vitest";
+
+import anonymizationService from "../../services/anonymization.js";
+import dataDir from "../../services/data_dir.js";
+import databaseRoute from "./database.js";
+
+function fakeRes() {
+ const calls: { status?: number; body?: unknown; download?: unknown[] } = {};
+ const res = {
+ status(code: number) { calls.status = code; return this; },
+ send(body: unknown) { calls.body = body; return this; },
+ download(...args: unknown[]) { calls.download = args; return this; }
+ } as unknown as Response;
+ return { res, calls };
+}
+
+describe("Database API", () => {
+ it("returns existing backups and anonymized databases", async () => {
+ expect(Array.isArray(await databaseRoute.getExistingBackups())).toBe(true);
+ expect(Array.isArray(databaseRoute.getExistingAnonymizedDatabases())).toBe(true);
+ });
+
+ it("runs an integrity check that reports 'ok'", () => {
+ const result = databaseRoute.checkIntegrity();
+ expect(result.results[0].integrity_check).toBe("ok");
+ });
+
+ it("vacuums the database without throwing", () => {
+ expect(() => databaseRoute.vacuumDatabase()).not.toThrow();
+ });
+
+ it("kicks off on-demand consistency checks", () => {
+ expect(() => databaseRoute.findAndFixConsistencyIssues()).not.toThrow();
+ });
+
+ it("backs up the database (provider mocked — fixture isn't a real file DB)", async () => {
+ const spy = vi.spyOn(getBackup(), "backupNow").mockResolvedValue("now-backup");
+ const result = await databaseRoute.backupDatabase();
+ expect(result).toEqual({ backupFile: "now-backup" });
+ spy.mockRestore();
+ });
+
+ it("rejects an unknown anonymization type", async () => {
+ const req = { params: { type: "bogus" } } as unknown as Request;
+ await expect(databaseRoute.anonymize(req)).rejects.toBeInstanceOf(ValidationError);
+ });
+
+ it("anonymizes with a valid type (service mocked)", async () => {
+ const spy = vi.spyOn(anonymizationService, "createAnonymizedCopy")
+ .mockResolvedValue({ success: true, anonymizedFilePath: "/tmp/x.db" });
+ const req = { params: { type: "light" } } as unknown as Request;
+ const result = await databaseRoute.anonymize(req);
+ expect(result).toEqual({ success: true, anonymizedFilePath: "/tmp/x.db" });
+ spy.mockRestore();
+ });
+
+ describe("downloadBackup error handling", () => {
+ it("returns 400 when filePath is missing", () => {
+ const { res, calls } = fakeRes();
+ databaseRoute.downloadBackup({ query: {} } as unknown as Request, res);
+ expect(calls.status).toBe(400);
+ });
+
+ it("returns 403 for a path outside the backup directory", () => {
+ const { res, calls } = fakeRes();
+ databaseRoute.downloadBackup({ query: { filePath: "/etc/passwd" } } as unknown as Request, res);
+ expect(calls.status).toBe(403);
+ });
+
+ it("returns 404 for a non-existent file inside the backup directory", () => {
+ const { res, calls } = fakeRes();
+ const filePath = path.join(dataDir.BACKUP_DIR, "missing-backup.db");
+ databaseRoute.downloadBackup({ query: { filePath } } as unknown as Request, res);
+ expect(calls.status).toBe(404);
+ });
+
+ it("streams an existing backup file via res.download", () => {
+ const filePath = path.join(dataDir.BACKUP_DIR, "spec-backup.db");
+ fs.writeFileSync(filePath, "backup-bytes");
+ try {
+ const { res, calls } = fakeRes();
+ databaseRoute.downloadBackup({ query: { filePath } } as unknown as Request, res);
+ expect(calls.download).toBeDefined();
+ expect(calls.download![0]).toBe(path.resolve(filePath));
+ // A timestamped download filename is generated from the file mtime.
+ expect(String(calls.download![1])).toMatch(/spec-backup_.*\.db/);
+ } finally {
+ fs.rmSync(filePath, { force: true });
+ }
+ });
+ });
+});
diff --git a/apps/server/src/routes/api/etapi_tokens.spec.ts b/apps/server/src/routes/api/etapi_tokens.spec.ts
new file mode 100644
index 0000000000..059776fed4
--- /dev/null
+++ b/apps/server/src/routes/api/etapi_tokens.spec.ts
@@ -0,0 +1,39 @@
+import { cls } from "@triliumnext/core";
+import type { Request } from "express";
+import { describe, expect, it } from "vitest";
+
+import etapiTokensRoute from "./etapi_tokens.js";
+
+function req(body: Record<string, unknown> = {}, params: Record<string, string> = {}) {
+ return { body, params } as unknown as Request<{ etapiTokenId: string }>;
+}
+
+describe("ETAPI tokens API", () => {
+ it("creates, lists, renames and deletes a token", () => {
+ const created = cls.init(() => etapiTokensRoute.createToken(req({ tokenName: "spec-token" })));
+ expect(created.authToken).toBeTruthy();
+
+ const etapiTokenId = cls.init(() =>
+ etapiTokensRoute.getTokens().find(t => t.name === "spec-token")!.etapiTokenId
+ );
+ expect(etapiTokenId).toBeTruthy();
+
+ cls.init(() => etapiTokensRoute.patchToken(req({ name: "renamed" }, { etapiTokenId })));
+ const renamed = cls.init(() => etapiTokensRoute.getTokens().find(t => t.etapiTokenId === etapiTokenId));
+ expect(renamed?.name).toBe("renamed");
+
+ cls.init(() => etapiTokensRoute.deleteToken(req({}, { etapiTokenId })));
+ const afterDelete = cls.init(() => etapiTokensRoute.getTokens().find(t => t.etapiTokenId === etapiTokenId));
+ expect(afterDelete).toBeUndefined();
+ });
+
+ it("returns tokens sorted by creation date", () => {
+ cls.init(() => etapiTokensRoute.createToken(req({ tokenName: "a" })));
+ cls.init(() => etapiTokensRoute.createToken(req({ tokenName: "b" })));
+
+ const tokens = cls.init(() => etapiTokensRoute.getTokens());
+ for (let i = 1; i < tokens.length; i++) {
+ expect(tokens[i - 1].utcDateCreated <= tokens[i].utcDateCreated).toBe(true);
+ }
+ });
+});
diff --git a/apps/server/src/routes/api/files.spec.ts b/apps/server/src/routes/api/files.spec.ts
new file mode 100644
index 0000000000..2839fc9c4d
--- /dev/null
+++ b/apps/server/src/routes/api/files.spec.ts
@@ -0,0 +1,109 @@
+import { becca, cls, note_service as noteService, ValidationError } from "@triliumnext/core";
+import type { Request } from "express";
+import fs from "fs";
+import { Readable } from "stream";
+import { beforeAll, describe, expect, it } from "vitest";
+
+import filesRoute from "./files.js";
+
+let noteId: string;
+let attachmentId: string;
+
+function fileReq(params: Record<string, string>, file?: unknown, query: Record<string, string> = {}, body: Record<string, unknown> = {}) {
+ return { params, file, query, body } as unknown as Request<{ noteId: string }>;
+}
+
+async function streamToString(stream: Readable) {
+ const chunks: Buffer[] = [];
+ for await (const chunk of stream) chunks.push(Buffer.from(chunk));
+ return Buffer.concat(chunks).toString("utf8");
+}
+
+describe("Files API", () => {
+ beforeAll(() => {
+ cls.init(() => {
+ const { note } = noteService.createNewNote({
+ parentNoteId: "root", title: "File note", type: "file", mime: "text/plain", content: "original"
+ });
+ noteId = note.noteId;
+ const attachment = note.saveAttachment({ role: "file", mime: "text/plain", title: "att.txt", content: "att-data" });
+ attachmentId = attachment.attachmentId;
+ });
+ });
+
+ describe("updateFile", () => {
+ it("reports a missing file", () => {
+ expect(cls.init(() => filesRoute.updateFile(fileReq({ noteId })))).toEqual({ uploaded: false, message: "Missing file." });
+ });
+
+ it("replaces note content without a revision when replace=1", () => {
+ const file = { buffer: Buffer.from("replaced"), mimetype: "TEXT/Plain", originalname: "new.txt" };
+ const result = cls.init(() => filesRoute.updateFile(fileReq({ noteId }, file, { replace: "1" })));
+ expect(result).toEqual({ uploaded: true });
+ expect(becca.getNote(noteId)!.mime).toBe("text/plain");
+ });
+
+ it("saves a revision when not replacing", () => {
+ const file = { buffer: Buffer.from("v2"), mimetype: "text/plain", originalname: "v2.txt" };
+ expect(cls.init(() => filesRoute.updateFile(fileReq({ noteId }, file)))).toEqual({ uploaded: true });
+ });
+ });
+
+ describe("updateAttachment", () => {
+ it("reports a missing file", () => {
+ const req = fileReq({ attachmentId } as Record<string, string>) as unknown as Request<{ attachmentId: string }>;
+ expect(cls.init(() => filesRoute.updateAttachment(req))).toEqual({ uploaded: false, message: "Missing file." });
+ });
+
+ it("updates attachment content", () => {
+ const file = { buffer: Buffer.from("new-att"), mimetype: "text/plain", originalname: "a.txt" };
+ const req = fileReq({ attachmentId } as Record<string, string>, file) as unknown as Request<{ attachmentId: string }>;
+ expect(cls.init(() => filesRoute.updateAttachment(req))).toEqual({ uploaded: true });
+ });
+ });
+
+ describe("content providers", () => {
+ it("streams full and ranged note content", async () => {
+ const current = becca.getNote(noteId)!.getContent() as string;
+ const provider = await filesRoute.fileContentProvider(fileReq({ noteId }));
+ expect(provider.totalSize).toBe(Buffer.byteLength(current));
+ expect(await streamToString(provider.getStream(undefined as never))).toBe(current);
+ expect(await streamToString(provider.getStream({ start: 0, end: 0 }))).toBe(current.slice(0, 1));
+ });
+
+ it("streams attachment content", async () => {
+ const req = fileReq({ attachmentId } as Record<string, string>) as unknown as Request<{ attachmentId: string }>;
+ const provider = await filesRoute.attachmentContentProvider(req);
+ expect(provider.mimeType).toBe("text/plain");
+ expect(await streamToString(provider.getStream(undefined as never))).toBe("new-att");
+ });
+ });
+
+ describe("temp-dir round trip", () => {
+ it("saves a note to a temp file then uploads the modified content back", () => {
+ const { tmpFilePath } = cls.init(() => filesRoute.saveNoteToTmpDir(fileReq({ noteId })));
+ expect(fs.existsSync(tmpFilePath)).toBe(true);
+
+ fs.writeFileSync(tmpFilePath, "edited-on-disk");
+ cls.init(() => filesRoute.uploadModifiedFileToNote(fileReq({ noteId }, undefined, {}, { filePath: tmpFilePath })));
+ expect(becca.getNote(noteId)!.getContent()).toBe("edited-on-disk");
+ });
+
+ it("saves an attachment to a temp file then uploads it back", () => {
+ const req = fileReq({ attachmentId } as Record<string, string>) as unknown as Request<{ attachmentId: string }>;
+ const { tmpFilePath } = cls.init(() => filesRoute.saveAttachmentToTmpDir(req));
+ fs.writeFileSync(tmpFilePath, "edited-att");
+ const uploadReq = fileReq({ attachmentId } as Record<string, string>, undefined, {}, { filePath: tmpFilePath }) as unknown as Request<{ attachmentId: string }>;
+ cls.init(() => filesRoute.uploadModifiedFileToAttachment(uploadReq));
+ expect(becca.getAttachment(attachmentId)!.getContent()).toBe("edited-att");
+ });
+
+ it("rejects uploading from an unknown temp path", () => {
+ expect(() => cls.init(() => filesRoute.uploadModifiedFileToNote(
+ fileReq({ noteId }, undefined, {}, { filePath: "/not/a/temp/file" })
+ ))).toThrow(ValidationError);
+ const req = fileReq({ attachmentId } as Record<string, string>, undefined, {}, { filePath: "/nope" }) as unknown as Request<{ attachmentId: string }>;
+ expect(() => cls.init(() => filesRoute.uploadModifiedFileToAttachment(req))).toThrow(ValidationError);
+ });
+ });
+});
diff --git a/apps/server/src/routes/api/fonts.spec.ts b/apps/server/src/routes/api/fonts.spec.ts
new file mode 100644
index 0000000000..891534e9d9
--- /dev/null
+++ b/apps/server/src/routes/api/fonts.spec.ts
@@ -0,0 +1,70 @@
+import { cls, options as optionService } from "@triliumnext/core";
+import type { Request, Response } from "express";
+import { beforeEach, describe, expect, it } from "vitest";
+
+import fontsRoute from "./fonts.js";
+
+function fakeRes() {
+ const headers: Record<string, string> = {};
+ let body = "";
+ const res = {
+ setHeader(name: string, value: string) { headers[name] = value; },
+ send(content: string) { body = content; }
+ } as unknown as Response;
+ return { res, headers, getBody: () => body };
+}
+
+function getCss(): { headers: Record<string, string>; body: string } {
+ const { res, headers, getBody } = fakeRes();
+ fontsRoute.getFontCss({} as Request, res);
+ return { headers, body: getBody() };
+}
+
+describe("Fonts API", () => {
+ beforeEach(() => {
+ cls.init(() => optionService.setOption("overrideThemeFonts", "false"));
+ });
+
+ it("always sets a CSS content type", () => {
+ const { headers } = getCss();
+ expect(headers["Content-Type"]).toBe("text/css");
+ });
+
+ it("returns empty CSS when font override is disabled", () => {
+ expect(getCss().body).toBe("");
+ });
+
+ it("emits font-size variables and resolves 'system' / 'theme' families", () => {
+ cls.init(() => {
+ optionService.setOption("overrideThemeFonts", "true");
+ optionService.setOption("mainFontFamily", "system");
+ optionService.setOption("treeFontFamily", "theme");
+ optionService.setOption("detailFontFamily", "Arial");
+ optionService.setOption("monospaceFontFamily", "system");
+ });
+
+ const { body } = getCss();
+ expect(body).toContain("--main-font-size:");
+ expect(body).toContain("--tree-font-size:");
+ // 'system' is expanded to a font stack, 'theme' is omitted entirely
+ expect(body).toContain("--main-font-family:");
+ expect(body).not.toContain("--tree-font-family:");
+ expect(body).toContain("--detail-font-family: Arial;");
+ expect(body).toContain("--monospace-font-family:");
+ });
+
+ it("expands every family when all are set to 'system'", () => {
+ cls.init(() => {
+ optionService.setOption("overrideThemeFonts", "true");
+ optionService.setOption("mainFontFamily", "system");
+ optionService.setOption("treeFontFamily", "system");
+ optionService.setOption("detailFontFamily", "system");
+ optionService.setOption("monospaceFontFamily", "system");
+ });
+
+ const { body } = getCss();
+ for (const v of ["--main-font-family:", "--tree-font-family:", "--detail-font-family:", "--monospace-font-family:"]) {
+ expect(body).toContain(v);
+ }
+ });
+});
diff --git a/apps/server/src/routes/api/link_embed.spec.ts b/apps/server/src/routes/api/link_embed.spec.ts
index adee0ea0b9..0da62864e4 100644
--- a/apps/server/src/routes/api/link_embed.spec.ts
+++ b/apps/server/src/routes/api/link_embed.spec.ts
@@ -1,26 +1,128 @@
-import { describe, expect, it } from "vitest";
-
import { extractYouTubeVideoId } from "@triliumnext/commons";
+import { ValidationError } from "@triliumnext/core";
+import type { Request } from "express";
+import { describe, expect, it, vi } from "vitest";
+
+const safeFetch = vi.hoisted(() => vi.fn());
+
+vi.mock("../../services/safe_fetch.js", () => ({
+ // Bypass SSRF/DNS checks in tests — just parse the URL.
+ validateUrl: (u: string) => new URL(u),
+ safeFetch: (...args: unknown[]) => safeFetch(...args)
+}));
+
+import linkEmbedRoute from "./link_embed.js";
+
+function oneShotReader(bytes: Buffer) {
+ let sent = false;
+ return {
+ async read() {
+ if (sent) return { done: true, value: undefined };
+ sent = true;
+ return { done: false, value: new Uint8Array(bytes) };
+ },
+ async cancel() {}
+ };
+}
+
+function fakeResponse(payload: string | Buffer, opts: { ok?: boolean; contentType?: string; json?: unknown } = {}) {
+ const buf = Buffer.isBuffer(payload) ? payload : Buffer.from(payload);
+ const headers: Record<string, string | null> = {
+ "content-type": opts.contentType ?? "text/html",
+ "content-length": String(buf.byteLength)
+ };
+ return {
+ ok: opts.ok ?? true,
+ status: opts.ok === false ? 500 : 200,
+ headers: { get: (h: string) => headers[h.toLowerCase()] ?? null },
+ body: { getReader: () => oneShotReader(buf) },
+ json: async () => opts.json
+ };
+}
describe("extractYouTubeVideoId", () => {
- it("extracts ID from standard watch URL", () => {
+ it("extracts ids and rejects non-YouTube URLs", () => {
expect(extractYouTubeVideoId("https://www.youtube.com/watch?v=dQw4w9WgXcQ")).toBe("dQw4w9WgXcQ");
+ expect(extractYouTubeVideoId("https://youtu.be/dQw4w9WgXcQ")).toBe("dQw4w9WgXcQ");
+ expect(extractYouTubeVideoId("https://example.com")).toBeNull();
});
+});
- it("extracts ID from short URL", () => {
- expect(extractYouTubeVideoId("https://youtu.be/dQw4w9WgXcQ")).toBe("dQw4w9WgXcQ");
+describe("link-embed getMetadata", () => {
+ function req(url?: unknown) { return { query: { url } } as unknown as Request; }
+
+ it("requires a url query parameter", async () => {
+ await expect(linkEmbedRoute.getMetadata(req())).rejects.toBeInstanceOf(ValidationError);
});
- it("extracts ID from embed URL", () => {
- expect(extractYouTubeVideoId("https://www.youtube.com/embed/dQw4w9WgXcQ")).toBe("dQw4w9WgXcQ");
+ it("returns YouTube metadata via the oEmbed endpoint", async () => {
+ safeFetch.mockImplementation(async (url: string) => {
+ if (url.includes("favicon")) return fakeResponse(Buffer.from([1, 2, 3]), { contentType: "image/x-icon" });
+ return fakeResponse("", { json: { title: "Cool Video", author_name: "Channel", thumbnail_url: "https://img/thumb.jpg" } });
+ });
+
+ const result = await linkEmbedRoute.getMetadata(req("https://www.youtube.com/watch?v=dQw4w9WgXcQ"));
+ expect(result.embedType).toBe("youtube");
+ expect(result.title).toBe("Cool Video");
+ expect(result.description).toBe("Channel");
+ expect(result.favicon).toMatch(/^data:image\//);
});
- it("extracts ID from shorts URL", () => {
- expect(extractYouTubeVideoId("https://www.youtube.com/shorts/dQw4w9WgXcQ")).toBe("dQw4w9WgXcQ");
+ it("parses OpenGraph metadata from an HTML page", async () => {
+ const html = `<html><head>
+ <meta property="og:title" content="OG Title">
+ <meta property="og:description" content="OG Desc">
+ <meta property="og:image" content="https://site/img.png">
+ <meta property="og:site_name" content="Example">
+ <link rel="icon" href="/fav.ico">
+ </head></html>`;
+ safeFetch.mockImplementation(async (url: string) => {
+ if (url.includes("fav.ico")) return fakeResponse(Buffer.from([9, 9]), { contentType: "image/x-icon" });
+ return fakeResponse(html, { contentType: "text/html" });
+ });
+
+ const result = await linkEmbedRoute.getMetadata(req("https://example.com/page"));
+ expect(result.embedType).toBe("opengraph");
+ expect(result.title).toBe("OG Title");
+ expect(result.description).toBe("OG Desc");
+ expect(result.siteName).toBe("Example");
});
- it("returns null for non-YouTube URLs", () => {
- expect(extractYouTubeVideoId("https://example.com")).toBeNull();
- expect(extractYouTubeVideoId("https://vimeo.com/12345")).toBeNull();
+ it("falls back to the hostname when the fetch fails", async () => {
+ safeFetch.mockResolvedValue(fakeResponse("", { ok: false }));
+ const result = await linkEmbedRoute.getMetadata(req("https://broken.example.com/x"));
+ expect(result).toEqual({ url: "https://broken.example.com/x", title: "broken.example.com", embedType: "opengraph" });
+ });
+
+ it("uses a generic YouTube title when oEmbed is unavailable", async () => {
+ safeFetch.mockImplementation(async (url: string) => {
+ if (url.includes("favicon")) return fakeResponse(Buffer.from([1]), { contentType: "image/x-icon" });
+ return fakeResponse("", { ok: false }); // oembed fails
+ });
+ const result = await linkEmbedRoute.getMetadata(req("https://youtu.be/dQw4w9WgXcQ"));
+ expect(result.embedType).toBe("youtube");
+ expect(result.title).toBe("YouTube Video");
+ });
+
+ it("falls back when the page is not HTML", async () => {
+ safeFetch.mockResolvedValue(fakeResponse("not html", { contentType: "application/json" }));
+ const result = await linkEmbedRoute.getMetadata(req("https://example.com/data.json"));
+ expect(result).toEqual({ url: "https://example.com/data.json", title: "example.com", embedType: "opengraph" });
+ });
+
+ it("ignores a favicon that advertises a size over the limit", async () => {
+ const html = `<html><head><title>Plain</title><link rel="icon" href="/big.ico"></head></html>`;
+ safeFetch.mockImplementation(async (url: string) => {
+ if (url.includes("big.ico")) {
+ const big = fakeResponse(Buffer.from([1, 2, 3]), { contentType: "image/x-icon" });
+ (big.headers as { get: (h: string) => string | null }).get = (h: string) =>
+ h.toLowerCase() === "content-length" ? String(1024 * 1024) : "image/x-icon";
+ return big;
+ }
+ return fakeResponse(html, { contentType: "text/html" });
+ });
+ const result = await linkEmbedRoute.getMetadata(req("https://example.com/page"));
+ expect(result.title).toBe("Plain");
+ expect(result.favicon).toBeUndefined();
});
});
diff --git a/apps/server/src/routes/api/llm_chat.spec.ts b/apps/server/src/routes/api/llm_chat.spec.ts
new file mode 100644
index 0000000000..87609a0101
--- /dev/null
+++ b/apps/server/src/routes/api/llm_chat.spec.ts
@@ -0,0 +1,111 @@
+import type { Request, Response } from "express";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+const state = vi.hoisted(() => ({
+ configured: true,
+ models: [] as unknown[],
+ chunks: [] as unknown[],
+ availableModels: [{ id: "m1", name: "Model One", isDefault: true }] as { id: string; name: string; isDefault?: boolean }[],
+ chatThrows: false
+}));
+
+vi.mock("../../services/llm/index.js", () => ({
+ hasConfiguredProviders: () => state.configured,
+ getAllModels: () => state.models,
+ getProviderByType: () => ({
+ chat: () => { if (state.chatThrows) throw new Error("provider exploded"); return {}; },
+ getAvailableModels: () => state.availableModels,
+ getModelPricing: () => ({ input: 0, output: 0 })
+ })
+}));
+
+vi.mock("../../services/llm/stream.js", () => ({
+ async *streamToChunks () { for (const c of state.chunks) yield c; }
+}));
+
+const generateChatTitle = vi.fn(async () => {});
+vi.mock("../../services/llm/chat_title.js", () => ({ generateChatTitle: (...args: unknown[]) => generateChatTitle(...args) }));
+
+import llmChatRoute from "./llm_chat.js";
+
+function fakeRes() {
+ const writes: string[] = [];
+ const headers: Record<string, string> = {};
+ let statusCode = 200;
+ let jsonBody: unknown;
+ let ended = false;
+ const res = {
+ setHeader(k: string, v: string) { headers[k] = v; },
+ flushHeaders() {},
+ write(chunk: string) { writes.push(chunk); return true; },
+ end() { ended = true; },
+ status(code: number) { statusCode = code; return this; },
+ json(body: unknown) { jsonBody = body; return this; }
+ } as unknown as Response;
+ return { res, writes, headers, get statusCode() { return statusCode; }, get jsonBody() { return jsonBody; }, get ended() { return ended; } };
+}
+
+describe("LLM chat API", () => {
+ afterEach(() => {
+ Object.assign(state, { configured: true, models: [], chunks: [], availableModels: [{ id: "m1", name: "Model One", isDefault: true }], chatThrows: false });
+ generateChatTitle.mockClear();
+ });
+
+ describe("getModels", () => {
+ it("returns no models when no provider is configured", () => {
+ state.configured = false;
+ expect(llmChatRoute.getModels({} as Request, {} as Response)).toEqual({ models: [] });
+ });
+
+ it("returns all models when configured", () => {
+ state.models = [{ id: "m1" }];
+ expect(llmChatRoute.getModels({} as Request, {} as Response)).toEqual({ models: [{ id: "m1" }] });
+ });
+ });
+
+ describe("streamChat", () => {
+ function req(body: unknown) { return { body } as unknown as Request; }
+
+ it("returns 400 for an empty messages array", async () => {
+ const r = fakeRes();
+ await llmChatRoute.streamChat(req({ messages: [] }), r.res);
+ expect(r.statusCode).toBe(400);
+ expect(r.jsonBody).toEqual({ error: "messages array is required" });
+ });
+
+ it("emits an SSE error when no providers are configured", async () => {
+ state.configured = false;
+ const r = fakeRes();
+ await llmChatRoute.streamChat(req({ messages: [{ role: "user", content: "hi" }] }), r.res);
+ expect(r.writes.join("")).toContain("No LLM providers configured");
+ expect(r.ended).toBe(true);
+ });
+
+ it("emits an SSE error when no model can be resolved", async () => {
+ state.availableModels = [];
+ const r = fakeRes();
+ await llmChatRoute.streamChat(req({ messages: [{ role: "user", content: "hi" }], config: {} }), r.res);
+ expect(r.writes.join("")).toContain("No model specified");
+ });
+
+ it("streams chunks, logs errors, ends the response and generates a title", async () => {
+ state.chunks = [{ type: "text", content: "Hi" }, { type: "error", error: "boom" }, { type: "done" }];
+ const r = fakeRes();
+ await llmChatRoute.streamChat(req({ messages: [{ role: "user", content: "hello" }], config: { chatNoteId: "abc" } }), r.res);
+ const body = r.writes.join("");
+ expect(body).toContain('"type":"text"');
+ expect(body).toContain('"type":"done"');
+ expect(r.ended).toBe(true);
+ expect(generateChatTitle).toHaveBeenCalledWith("abc", "hello");
+ expect(r.headers["Content-Type"]).toBe("text/event-stream");
+ });
+
+ it("writes an SSE error when the provider throws", async () => {
+ state.chatThrows = true;
+ const r = fakeRes();
+ await llmChatRoute.streamChat(req({ messages: [{ role: "user", content: "hi" }], config: {} }), r.res);
+ expect(r.writes.join("")).toContain("provider exploded");
+ expect(r.ended).toBe(true);
+ });
+ });
+});
diff --git a/apps/server/src/routes/api/llm_special_notes.spec.ts b/apps/server/src/routes/api/llm_special_notes.spec.ts
new file mode 100644
index 0000000000..bd5f321d5e
--- /dev/null
+++ b/apps/server/src/routes/api/llm_special_notes.spec.ts
@@ -0,0 +1,41 @@
+import { cls } from "@triliumnext/core";
+import type { Request } from "express";
+import { describe, expect, it } from "vitest";
+
+import llmSpecialNotesRoute from "./llm_special_notes.js";
+
+describe("LLM special notes API", () => {
+ it("creates an LLM chat note", () => {
+ const chat = cls.init(() => llmSpecialNotesRoute.createLlmChat());
+ expect(chat.id ?? chat.noteId).toBeTruthy();
+ });
+
+ it("gets or creates, then returns it as the most recent chat", () => {
+ const created = cls.init(() => llmSpecialNotesRoute.getOrCreateLlmChat());
+ expect(created).toBeTruthy();
+
+ const recent = cls.init(() => llmSpecialNotesRoute.getMostRecentLlmChat());
+ expect(recent).not.toBeNull();
+ });
+
+ it("lists recent chats honouring the limit query param", () => {
+ const req = { query: { limit: "1" } } as unknown as Request;
+ const chats = cls.init(() => llmSpecialNotesRoute.getRecentLlmChats(req));
+ expect(Array.isArray(chats)).toBe(true);
+ expect(chats.length).toBeLessThanOrEqual(1);
+ });
+
+ it("defaults the limit when not a number", () => {
+ const req = { query: {} } as unknown as Request;
+ const chats = cls.init(() => llmSpecialNotesRoute.getRecentLlmChats(req));
+ expect(Array.isArray(chats)).toBe(true);
+ });
+
+ it("saves a chat by note id", () => {
+ const created = cls.init(() => llmSpecialNotesRoute.createLlmChat());
+ const noteId = (created.id ?? created.noteId) as string;
+ const req = { body: { llmChatNoteId: noteId } } as unknown as Request<{ llmChatNoteId: string }>;
+ const saved = cls.init(() => llmSpecialNotesRoute.saveLlmChat(req));
+ expect(saved).toBeTruthy();
+ });
+});
diff --git a/apps/server/src/routes/api/login.spec.ts b/apps/server/src/routes/api/login.spec.ts
new file mode 100644
index 0000000000..2a176490d2
--- /dev/null
+++ b/apps/server/src/routes/api/login.spec.ts
@@ -0,0 +1,66 @@
+import { app_info as appInfo, cls, date_utils as dateUtils, options, options as optionService } from "@triliumnext/core";
+import type { Request } from "express";
+import { describe, expect, it } from "vitest";
+
+import totpService from "../../services/totp.js";
+import utils from "../../services/utils.js";
+import loginApiRoute from "./login.js";
+
+function syncReq(body: Record<string, unknown>) {
+ return { body, session: {} } as unknown as Request;
+}
+
+describe("Login (sync) API", () => {
+ it("rejects a timestamp that is out of sync", () => {
+ const stale = dateUtils.utcDateTimeStr(new Date(Date.now() - 10 * 60 * 1000));
+ const result = loginApiRoute.loginSync(syncReq({ timestamp: stale, syncVersion: appInfo.syncVersion }));
+ expect(result[0]).toBe(401);
+ });
+
+ it("rejects a non-matching sync version", () => {
+ const now = dateUtils.utcNowDateTime();
+ const result = loginApiRoute.loginSync(syncReq({ timestamp: now, syncVersion: appInfo.syncVersion + 1 }));
+ expect(result[0]).toBe(400);
+ expect((result[1] as { message: string }).message).toContain("Non-matching sync versions");
+ });
+
+ it("rejects an incorrect hash", () => {
+ const now = dateUtils.utcNowDateTime();
+ const result = loginApiRoute.loginSync(syncReq({ timestamp: now, syncVersion: appInfo.syncVersion, hash: "wrong" }));
+ expect(result[0]).toBe(400);
+ expect((result[1] as { message: string }).message).toContain("Sync login credentials are incorrect");
+ });
+
+ it("logs in with a correct HMAC of the document secret", () => {
+ const now = dateUtils.utcNowDateTime();
+ const documentSecret = options.getOption("documentSecret");
+ const hash = utils.hmac(documentSecret, now);
+ const req = syncReq({ timestamp: now, syncVersion: appInfo.syncVersion, hash });
+ const result = loginApiRoute.loginSync(req) as { instanceId: string; maxEntityChangeId: number };
+ expect(result.instanceId).toBeTruthy();
+ expect(req.session.loggedIn).toBe(true);
+ });
+});
+
+describe("Login (token) API", () => {
+ it("rejects an incorrect password", async () => {
+ const req = { body: { password: "wrongpassword" } } as unknown as Request;
+ expect(await loginApiRoute.token(req)).toEqual([401, "Incorrect credential"]);
+ });
+
+ it("issues an ETAPI token for the correct password", async () => {
+ const req = { body: { password: "demo1234", tokenName: "spec-sender" } } as unknown as Request;
+ const result = await cls.init(() => loginApiRoute.token(req)) as { token: string };
+ expect(result.token).toBeTruthy();
+ });
+
+ it("rejects login when TOTP is enabled and the submitted token is wrong", async () => {
+ cls.init(() => {
+ optionService.setOption("mfaEnabled", "true");
+ totpService.createSecret(); // stores a secret so TOTP counts as enabled
+ });
+
+ const req = { body: { password: "demo1234", totpToken: "000000" } } as unknown as Request;
+ expect(await cls.init(() => loginApiRoute.token(req))).toEqual([401, "Incorrect credential"]);
+ });
+});
diff --git a/apps/server/src/routes/api/ocr.spec.ts b/apps/server/src/routes/api/ocr.spec.ts
index b778e100c4..71d5717531 100644
--- a/apps/server/src/routes/api/ocr.spec.ts
+++ b/apps/server/src/routes/api/ocr.spec.ts
@@ -1,56 +1,107 @@
-import { describe, expect, it, vi, beforeEach } from "vitest";
-import ocrRoutes from "./ocr.js";
+import { becca, cls, getSql, note_service as noteService } from "@triliumnext/core";
+import type { Request } from "express";
+import { beforeAll, describe, expect, it, vi } from "vitest";
+
+// Only the OCR engine is mocked — becca/sql run against the real in-memory DB.
+const ocrState = vi.hoisted(() => ({
+ noteResult: null as unknown,
+ attachmentResult: null as unknown,
+ batchResult: { success: true } as { success: boolean; message?: string }
+}));
-// Mock the OCR service
vi.mock("../../services/ocr/ocr_service.js", () => ({
default: {
- startBatchProcessing: vi.fn(() => Promise.resolve({ success: true })),
+ processNoteOCR: vi.fn(async () => ocrState.noteResult),
+ processAttachmentOCR: vi.fn(async () => ocrState.attachmentResult),
+ startBatchProcessing: vi.fn(async () => ocrState.batchResult),
getBatchProgress: vi.fn(() => ({ inProgress: false, total: 0, processed: 0 }))
}
}));
-// Mock becca
-vi.mock("../../becca/becca.js", () => ({
- default: {}
-}));
-
-// Mock sql
-vi.mock("../../services/sql.js", () => ({
- default: {
- getRow: vi.fn()
- }
-}));
+import ocrRoutes from "./ocr.js";
-// Mock log
-vi.mock("../../services/log.js", () => ({
- default: {
- error: vi.fn()
- }
-}));
+let noteId: string;
+let attachmentId: string;
describe("OCR API", () => {
- beforeEach(() => {
- vi.clearAllMocks();
+ beforeAll(() => {
+ cls.init(() => {
+ const { note } = noteService.createNewNote({ parentNoteId: "root", title: "OCR note", type: "text", content: "hi" });
+ noteId = note.noteId;
+ attachmentId = note.saveAttachment({ role: "image", mime: "image/png", title: "img", content: "x" }).attachmentId;
+ });
+ });
+
+ describe("processNoteOCR", () => {
+ it("returns 404 for a missing note", async () => {
+ const result = await ocrRoutes.processNoteOCR({ params: { noteId: "missing" }, body: {} } as unknown as Request<{ noteId: string }>);
+ expect(result).toEqual([404, { success: false, message: "Note not found" }]);
+ });
+
+ it("returns 400 when the note is not a supported image", async () => {
+ ocrState.noteResult = null;
+ const result = await ocrRoutes.processNoteOCR({ params: { noteId }, body: {} } as unknown as Request<{ noteId: string }>);
+ expect(result).toEqual([400, { success: false, message: "Note is not an image or has unsupported format" }]);
+ });
+
+ it("returns the OCR result on success", async () => {
+ ocrState.noteResult = { text: "hello" };
+ const result = await ocrRoutes.processNoteOCR({ params: { noteId }, body: { language: "eng" } } as unknown as Request<{ noteId: string }>);
+ expect(result).toMatchObject({ success: true, result: { text: "hello" } });
+ });
});
- it("should return success for batch processing", async () => {
- const result = await ocrRoutes.batchProcessOCR();
- expect(result).toEqual({ success: true });
+ describe("processAttachmentOCR", () => {
+ it("returns 404 for a missing attachment", async () => {
+ const result = await ocrRoutes.processAttachmentOCR({ params: { attachmentId: "missing" }, body: {} } as unknown as Request<{ attachmentId: string }>);
+ expect(result).toEqual([404, { success: false, message: "Attachment not found" }]);
+ });
+
+ it("returns 400 then success depending on the engine result", async () => {
+ ocrState.attachmentResult = null;
+ expect(await ocrRoutes.processAttachmentOCR({ params: { attachmentId }, body: {} } as unknown as Request<{ attachmentId: string }>))
+ .toEqual([400, { success: false, message: "Attachment is not an image or has unsupported format" }]);
+
+ ocrState.attachmentResult = { text: "ocr" };
+ expect(await ocrRoutes.processAttachmentOCR({ params: { attachmentId }, body: {} } as unknown as Request<{ attachmentId: string }>))
+ .toMatchObject({ success: true });
+ });
});
- it("should return batch progress", async () => {
- const result = await ocrRoutes.getBatchProgress();
- expect(result).toEqual({ inProgress: false, total: 0, processed: 0 });
+ describe("batch processing", () => {
+ it("returns the result on success", async () => {
+ ocrState.batchResult = { success: true };
+ expect(await ocrRoutes.batchProcessOCR()).toEqual({ success: true });
+ });
+
+ it("returns 400 when batch processing fails", async () => {
+ ocrState.batchResult = { success: false, message: "No images found that need OCR processing" };
+ expect(await ocrRoutes.batchProcessOCR()).toEqual([400, { success: false, message: "No images found that need OCR processing" }]);
+ });
+
+ it("returns batch progress", async () => {
+ expect(await ocrRoutes.getBatchProgress()).toEqual({ inProgress: false, total: 0, processed: 0 });
+ });
});
- it("should return 400 when batch processing fails", async () => {
- const ocrService = await import("../../services/ocr/ocr_service.js");
- vi.mocked(ocrService.default.startBatchProcessing).mockResolvedValueOnce({
- success: false,
- message: "No images found that need OCR processing"
+ describe("OCR text retrieval", () => {
+ it("returns 404 for a missing note / attachment", async () => {
+ expect(await ocrRoutes.getNoteOCRText({ params: { noteId: "missing" } } as unknown as Request<{ noteId: string }>))
+ .toEqual([404, { success: false, message: "Note not found" }]);
+ expect(await ocrRoutes.getAttachmentOCRText({ params: { attachmentId: "missing" } } as unknown as Request<{ attachmentId: string }>))
+ .toEqual([404, { success: false, message: "Attachment not found" }]);
+ });
+
+ it("reports no OCR text when none is stored", async () => {
+ const result = await ocrRoutes.getNoteOCRText({ params: { noteId } } as unknown as Request<{ noteId: string }>);
+ expect(result).toEqual({ success: true, text: "", hasOcr: false });
});
- const result = await ocrRoutes.batchProcessOCR();
- expect(result).toEqual([400, { success: false, message: "No images found that need OCR processing" }]);
+ it("returns stored OCR text from the blob", async () => {
+ const blobId = becca.getNote(noteId)!.blobId;
+ cls.init(() => getSql().execute("UPDATE blobs SET textRepresentation = ? WHERE blobId = ?", ["scanned text", blobId]));
+ const result = await ocrRoutes.getNoteOCRText({ params: { noteId } } as unknown as Request<{ noteId: string }>);
+ expect(result).toEqual({ success: true, text: "scanned text", hasOcr: true });
+ });
});
});
diff --git a/apps/server/src/routes/api/recovery_codes.spec.ts b/apps/server/src/routes/api/recovery_codes.spec.ts
new file mode 100644
index 0000000000..5cc9f14159
--- /dev/null
+++ b/apps/server/src/routes/api/recovery_codes.spec.ts
@@ -0,0 +1,42 @@
+import { cls } from "@triliumnext/core";
+import type { Request } from "express";
+import { describe, expect, it } from "vitest";
+
+import recoveryCodesRoute from "./recovery_codes.js";
+
+describe("Recovery codes API", () => {
+ it("reports no keys before any are set", () => {
+ // Runs first within this fork's fresh DB copy.
+ const result = recoveryCodesRoute.checkForRecoveryKeys();
+ expect(result).toEqual({ success: true, keysExist: false });
+ expect(recoveryCodesRoute.getUsedRecoveryCodes()).toEqual([]);
+ });
+
+ it("generates codes, then verifies and marks one as used", () => {
+ const generated = cls.init(() => recoveryCodesRoute.generateRecoveryCodes());
+ expect(generated.success).toBe(true);
+ expect(generated.recoveryCodes).toHaveLength(8);
+
+ expect(recoveryCodesRoute.checkForRecoveryKeys()).toEqual({ success: true, keysExist: true });
+
+ const guess = generated.recoveryCodes[0];
+ const verifyReq = { body: { recovery_code_guess: guess } } as unknown as Request;
+ expect(cls.init(() => recoveryCodesRoute.verifyRecoveryCode(verifyReq))).toEqual({ success: true });
+
+ // A wrong guess fails.
+ const wrongReq = { body: { recovery_code_guess: "not-a-valid-code" } } as unknown as Request;
+ expect(cls.init(() => recoveryCodesRoute.verifyRecoveryCode(wrongReq))).toEqual({ success: false });
+
+ const used = recoveryCodesRoute.getUsedRecoveryCodes() as { success: boolean; usedRecoveryCodes: string[] };
+ expect(used.success).toBe(true);
+ // The used code is replaced by an ISO-ish timestamp; the rest stay as indices.
+ expect(used.usedRecoveryCodes.some(c => /T/.test(c))).toBe(true);
+ });
+
+ it("sets recovery codes from an explicit list", () => {
+ const codes = Array.from({ length: 3 }, (_, i) => `code-${i}`);
+ const req = { body: { recoveryCodes: codes } } as unknown as Request;
+ const result = cls.init(() => recoveryCodesRoute.setRecoveryCodes(req));
+ expect(result.message).toBe("Recovery codes set!");
+ });
+});
diff --git a/apps/server/src/routes/api/sender.spec.ts b/apps/server/src/routes/api/sender.spec.ts
new file mode 100644
index 0000000000..f409858117
--- /dev/null
+++ b/apps/server/src/routes/api/sender.spec.ts
@@ -0,0 +1,68 @@
+import { cls } from "@triliumnext/core";
+import type { Request } from "express";
+import { describe, expect, it } from "vitest";
+
+import senderRoute from "./sender.js";
+
+// A real 9x16 PNG so image-type / sharp accept it.
+const PNG = Buffer.from(
+ "iVBORw0KGgoAAAANSUhEUgAAAAkAAAAQCAYAAADESFVDAAAAF0lEQVQoU2P8DwQMBADjqKLRIGAgKggAzHs/0SoYCGwAAAAASUVORK5CYII=",
+ "base64"
+);
+
+function imageReq(opts: { file?: unknown; headers?: Record<string, string> } = {}) {
+ return { file: opts.file, headers: opts.headers ?? {} } as unknown as Request;
+}
+
+describe("Sender API", () => {
+ describe("uploadImage validation", () => {
+ it("reports missing image data", async () => {
+ expect(await senderRoute.uploadImage(imageReq())).toEqual({ uploaded: false, message: "Missing image data." });
+ });
+
+ it("rejects an unsupported mime type", async () => {
+ const result = await senderRoute.uploadImage(imageReq({ file: { mimetype: "application/pdf", buffer: PNG } }));
+ expect(result).toEqual([400, "Unknown image type: application/pdf"]);
+ });
+
+ it("rejects a string buffer", async () => {
+ const result = await senderRoute.uploadImage(imageReq({ file: { mimetype: "image/png", buffer: "notabuffer" } }));
+ expect(result).toEqual([400, "Invalid image content type."]);
+ });
+
+ it("rejects bytes that aren't a real image", async () => {
+ const result = await senderRoute.uploadImage(imageReq({ file: { mimetype: "image/png", buffer: Buffer.from("nope") } }));
+ expect(result).toEqual([400, "Unable to determine image type."]);
+ });
+
+ it("requires the x-local-date header", async () => {
+ const result = await senderRoute.uploadImage(imageReq({ file: { mimetype: "image/png", buffer: PNG } }));
+ expect(result).toEqual([400, "Invalid local date"]);
+ });
+ });
+
+ it("uploads an image into the inbox with labels", async () => {
+ const result = await cls.init(() => senderRoute.uploadImage(imageReq({
+ file: { mimetype: "image/png", buffer: PNG },
+ headers: { "x-local-date": "2025-01-01", "x-labels": JSON.stringify([{ name: "src", value: "phone" }]) }
+ })));
+ expect((result as { noteId: string }).noteId).toBeTruthy();
+ });
+
+ describe("saveNote", () => {
+ it("requires a valid x-local-date header", async () => {
+ const req = { headers: {}, body: {} } as unknown as Request;
+ expect(await senderRoute.saveNote(req)).toEqual([400, "Invalid local date"]);
+ });
+
+ it("creates a note in the inbox with labels", async () => {
+ const req = {
+ headers: { "x-local-date": "2025-01-01" },
+ body: { title: "From phone", content: "<p>hi</p>", labels: [{ name: "src", value: "phone" }] }
+ } as unknown as Request;
+ const result = await cls.init(() => senderRoute.saveNote(req)) as { noteId: string; branchId: string };
+ expect(result.noteId).toBeTruthy();
+ expect(result.branchId).toBeTruthy();
+ });
+ });
+});
diff --git a/apps/server/src/routes/api/system_info.spec.ts b/apps/server/src/routes/api/system_info.spec.ts
new file mode 100644
index 0000000000..faad54aa4e
--- /dev/null
+++ b/apps/server/src/routes/api/system_info.spec.ts
@@ -0,0 +1,65 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+const state = vi.hoisted(() => ({
+ isMac: false,
+ isWindows: false,
+ arch: "x64",
+ cpuModel: "Intel",
+ execResult: "0",
+ execThrows: false
+}));
+
+vi.mock("../../services/utils", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../services/utils.js")>()),
+ get isMac() { return state.isMac; },
+ get isWindows() { return state.isWindows; }
+}));
+
+vi.mock("child_process", () => ({
+ execSync: () => {
+ if (state.execThrows) throw new Error("sysctl missing");
+ return state.execResult;
+ }
+}));
+
+vi.mock("os", () => ({
+ arch: () => state.arch,
+ cpus: () => [{ model: state.cpuModel }]
+}));
+
+import systemInfoRoute, { isCpuArchMismatch } from "./system_info.js";
+
+describe("System info API", () => {
+ afterEach(() => {
+ Object.assign(state, { isMac: false, isWindows: false, arch: "x64", cpuModel: "Intel", execResult: "0", execThrows: false });
+ });
+
+ it("reports no mismatch on a native (non-mac, non-windows) platform", () => {
+ expect(systemInfoRoute.systemChecks()).toEqual({ isCpuArchMismatch: false });
+ });
+
+ it("detects Rosetta 2 translation on macOS", () => {
+ state.isMac = true;
+ state.execResult = "1";
+ expect(isCpuArchMismatch()).toBe(true);
+
+ state.execResult = "0";
+ expect(isCpuArchMismatch()).toBe(false);
+ });
+
+ it("treats a failing sysctl on macOS as native", () => {
+ state.isMac = true;
+ state.execThrows = true;
+ expect(isCpuArchMismatch()).toBe(false);
+ });
+
+ it("detects ARM emulation on Windows x64", () => {
+ state.isWindows = true;
+ state.arch = "x64";
+ state.cpuModel = "Snapdragon (TM) 8cx";
+ expect(isCpuArchMismatch()).toBe(true);
+
+ state.cpuModel = "Intel";
+ expect(isCpuArchMismatch()).toBe(false);
+ });
+});
diff --git a/apps/server/src/routes/api/totp.spec.ts b/apps/server/src/routes/api/totp.spec.ts
new file mode 100644
index 0000000000..696fee65ee
--- /dev/null
+++ b/apps/server/src/routes/api/totp.spec.ts
@@ -0,0 +1,26 @@
+import { cls } from "@triliumnext/core";
+import { describe, expect, it } from "vitest";
+
+import totpRoute from "./totp.js";
+
+// totp is disabled by default in the test fixture (no mfaEnabled option),
+// so these assert the disabled-state shape plus that a fresh secret is generated.
+describe("TOTP API", () => {
+ it("generates and stores a base32 secret", () => {
+ const result = cls.init(() => totpRoute.generateSecret());
+ expect(result.success).toBe(true);
+ expect(result.message).toMatch(/^[A-Z2-7]+$/);
+ });
+
+ it("reports the TOTP status", () => {
+ const status = totpRoute.getTOTPStatus();
+ expect(status.success).toBe(true);
+ expect(typeof status.message).toBe("boolean");
+ expect(typeof status.set).toBe("boolean");
+ });
+
+ it("exposes the configured secret (empty when none is set)", () => {
+ const result = totpRoute.getSecret();
+ expect(result).toBeDefined();
+ });
+});
diff --git a/apps/server/src/routes/assets.spec.ts b/apps/server/src/routes/assets.spec.ts
new file mode 100644
index 0000000000..e5febebec1
--- /dev/null
+++ b/apps/server/src/routes/assets.spec.ts
@@ -0,0 +1,24 @@
+import { afterEach, describe, expect, it } from "vitest";
+
+import { getClientDir, getPdfjsAssetDir, getShareThemeAssetDir } from "./assets.js";
+
+// The test runner sets NODE_ENV=development, which exercises the dev branch of
+// these path helpers. Toggle to production to cover the resource-dir branch too.
+describe("assets path helpers", () => {
+ const original = process.env.NODE_ENV;
+ afterEach(() => { process.env.NODE_ENV = original; });
+
+ it("resolves dev paths under development", () => {
+ process.env.NODE_ENV = "development";
+ expect(getShareThemeAssetDir()).toContain("share-theme");
+ expect(getPdfjsAssetDir()).toContain("pdfjs-viewer");
+ expect(getClientDir()).toContain("client");
+ });
+
+ it("resolves resource-dir paths under production", () => {
+ process.env.NODE_ENV = "production";
+ expect(getShareThemeAssetDir()).toContain("share-theme");
+ expect(getPdfjsAssetDir()).toContain("pdfjs-viewer");
+ expect(typeof getClientDir()).toBe("string");
+ });
+});
diff --git a/apps/server/src/routes/custom.spec.ts b/apps/server/src/routes/custom.spec.ts
new file mode 100644
index 0000000000..7456dc21a0
--- /dev/null
+++ b/apps/server/src/routes/custom.spec.ts
@@ -0,0 +1,70 @@
+import { cls, note_service as noteService } from "@triliumnext/core";
+import type { Application } from "express";
+import supertest from "supertest";
+import { beforeAll, describe, expect, it } from "vitest";
+
+let app: Application;
+
+describe("Custom request/resource handlers", () => {
+ beforeAll(async () => {
+ app = await (await import("../app.js")).default();
+
+ cls.init(() => {
+ // A backend script note that handles a custom request.
+ const handler = noteService.createNewNote({
+ parentNoteId: "root",
+ title: "Custom handler",
+ type: "code",
+ mime: "application/javascript;env=backend",
+ content: `api.res.status(200).send("handled:" + api.pathParams[0]);`
+ }).note;
+ handler.setLabel("customRequestHandler", "greet/([a-z]+)");
+
+ // A script note that throws, to exercise the error branch.
+ const thrower = noteService.createNewNote({
+ parentNoteId: "root",
+ title: "Throwing handler",
+ type: "code",
+ mime: "application/javascript;env=backend",
+ content: `throw new Error("boom in handler");`
+ }).note;
+ thrower.setLabel("customRequestHandler", "explode");
+
+ // A resource note served directly.
+ const resource = noteService.createNewNote({
+ parentNoteId: "root",
+ title: "Custom resource",
+ type: "text",
+ content: "<p>resource body</p>"
+ }).note;
+ resource.setLabel("customResourceProvider", "resource");
+
+ // Empty value → skipped; invalid regex → caught and skipped. Both are
+ // exercised by the "no handler matches" request below.
+ noteService.createNewNote({ parentNoteId: "root", title: "Empty handler", type: "text", content: "x" })
+ .note.setLabel("customRequestHandler", " ");
+ noteService.createNewNote({ parentNoteId: "root", title: "Bad regex handler", type: "text", content: "x" })
+ .note.setLabel("customRequestHandler", "([unclosed");
+ });
+ });
+
+ it("runs a custom request handler with captured path params", async () => {
+ const res = await supertest(app).get("/custom/greet/world").expect(200);
+ expect(res.text).toBe("handled:world");
+ });
+
+ it("returns 500 when the custom handler throws", async () => {
+ const res = await supertest(app).get("/custom/explode").expect(500);
+ expect(res.text).toContain("boom in handler");
+ });
+
+ it("serves a custom resource provider note", async () => {
+ const res = await supertest(app).get("/custom/resource").expect(200);
+ expect(res.text).toContain("resource body");
+ });
+
+ it("returns 404 when no handler matches", async () => {
+ const res = await supertest(app).get("/custom/no-such-path").expect(404);
+ expect(res.text).toContain("No handler matched");
+ });
+});
diff --git a/apps/server/src/routes/session_parser.spec.ts b/apps/server/src/routes/session_parser.spec.ts
new file mode 100644
index 0000000000..ac12a9415f
--- /dev/null
+++ b/apps/server/src/routes/session_parser.spec.ts
@@ -0,0 +1,63 @@
+import { cls } from "@triliumnext/core";
+import type { SessionData } from "express-session";
+import { describe, expect, it } from "vitest";
+
+import { SQLiteSessionStore } from "./session_parser.js";
+
+const store = new SQLiteSessionStore();
+
+function get(sid: string) {
+ return new Promise<SessionData | null | undefined>((resolve, reject) =>
+ store.get(sid, (err, session) => (err ? reject(err) : resolve(session))));
+}
+
+function set(sid: string, session: SessionData) {
+ return new Promise<void>((resolve, reject) =>
+ cls.init(() => store.set(sid, session, err => (err ? reject(err) : resolve()))));
+}
+
+function destroy(sid: string) {
+ return new Promise<void>((resolve, reject) =>
+ cls.init(() => store.destroy(sid, err => (err ? reject(err) : resolve()))));
+}
+
+function touch(sid: string, session: SessionData) {
+ return new Promise<void>((resolve, reject) =>
+ cls.init(() => store.touch(sid, session, err => (err ? reject(err) : resolve()))));
+}
+
+const baseSession = (expires?: Date) => ({ cookie: expires ? { expires } : {}, loggedIn: true }) as unknown as SessionData;
+
+describe("SQLiteSessionStore", () => {
+ it("stores, reads and removes a session", async () => {
+ await set("sess-1", baseSession());
+ expect((await get("sess-1"))?.loggedIn).toBe(true);
+ expect(store.getSessionExpiry("sess-1")).toBeInstanceOf(Date);
+
+ await destroy("sess-1");
+ expect(await get("sess-1")).toBeNull();
+ });
+
+ it("returns null for an unknown session and its expiry", async () => {
+ expect(await get("does-not-exist")).toBeNull();
+ expect(store.getSessionExpiry("does-not-exist")).toBeNull();
+ });
+
+ it("uses the cookie expiry when one is provided", async () => {
+ const expires = new Date(Date.now() + 5 * 60 * 1000);
+ await set("sess-2", baseSession(expires));
+ expect(store.getSessionExpiry("sess-2")?.getTime()).toBe(expires.getTime());
+ });
+
+ it("touch renews a non-persistent session but leaves a persistent one untouched", async () => {
+ await set("sess-3", baseSession());
+ const before = store.getSessionExpiry("sess-3")!.getTime();
+ // No cookie.expires → touch pushes the expiry forward.
+ await touch("sess-3", baseSession());
+ expect(store.getSessionExpiry("sess-3")!.getTime()).toBeGreaterThanOrEqual(before);
+
+ // cookie.expires present → touch is a no-op (early return).
+ await touch("sess-3", baseSession(new Date(Date.now() + 60_000)));
+ expect(store.getSessionExpiry("sess-3")).toBeInstanceOf(Date);
+ });
+});
diff --git a/apps/server/src/routes/session_parser_errors.spec.ts b/apps/server/src/routes/session_parser_errors.spec.ts
new file mode 100644
index 0000000000..e2d2526dc0
--- /dev/null
+++ b/apps/server/src/routes/session_parser_errors.spec.ts
@@ -0,0 +1,62 @@
+import type { SessionData } from "express-session";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+// This spec drives the defensive branches of the session store: the
+// "DB not initialized" early returns and the SQL error catch paths. It mocks
+// sql/sql_init wholesale, so it lives apart from the happy-path store spec.
+const mockState = vi.hoisted(() => ({ initialized: true, throws: false }));
+
+vi.mock("../services/sql_init.js", () => ({
+ default: { isDbInitialized: () => mockState.initialized }
+}));
+
+vi.mock("../services/sql.js", () => ({
+ default: {
+ getValue: () => { if (mockState.throws) throw new Error("sql down"); return undefined; },
+ upsert: () => { if (mockState.throws) throw new Error("sql down"); },
+ execute: () => { if (mockState.throws) throw new Error("sql down"); return { changes: 0 }; }
+ }
+}));
+
+import { SQLiteSessionStore } from "./session_parser.js";
+
+const store = new SQLiteSessionStore();
+const session = { cookie: {}, loggedIn: true } as unknown as SessionData;
+
+describe("SQLiteSessionStore defensive branches", () => {
+ afterEach(() => { mockState.initialized = true; mockState.throws = false; });
+
+ it("short-circuits every operation when the DB is not initialized", () => {
+ mockState.initialized = false;
+ const cbs = { get: vi.fn(), set: vi.fn(), destroy: vi.fn(), touch: vi.fn() };
+ store.get("x", cbs.get);
+ store.set("x", session, cbs.set);
+ store.destroy("x", cbs.destroy);
+ store.touch("x", session, cbs.touch);
+ expect(cbs.get).toHaveBeenCalledWith(null, null);
+ expect(cbs.set).toHaveBeenCalled();
+ expect(cbs.destroy).toHaveBeenCalled();
+ expect(cbs.touch).toHaveBeenCalled();
+ });
+
+ it("propagates SQL errors through callbacks and returns null expiry", () => {
+ mockState.throws = true;
+ const getCb = vi.fn();
+ store.get("x", getCb);
+ expect(getCb.mock.calls[0][0]).toBeInstanceOf(Error);
+
+ const setCb = vi.fn();
+ store.set("x", session, setCb);
+ expect(setCb.mock.calls[0][0]).toBeInstanceOf(Error);
+
+ const destroyCb = vi.fn();
+ store.destroy("x", destroyCb);
+ expect(destroyCb.mock.calls[0][0]).toBeInstanceOf(Error);
+
+ const touchCb = vi.fn();
+ store.touch("x", session, touchCb);
+ expect(touchCb.mock.calls[0][0]).toBeInstanceOf(Error);
+
+ expect(store.getSessionExpiry("x")).toBeNull();
+ });
+});
diff --git a/apps/server/src/routes/transport.spec.ts b/apps/server/src/routes/transport.spec.ts
new file mode 100644
index 0000000000..1eea4d3e3d
--- /dev/null
+++ b/apps/server/src/routes/transport.spec.ts
@@ -0,0 +1,108 @@
+import { cls, options as optionService } from "@triliumnext/core";
+import type { Application } from "express";
+import supertest from "supertest";
+import { beforeAll, describe, expect, it } from "vitest";
+
+import { type ApiTestContext, bootLoggedInApp, createTextNote } from "../../spec/support/internal_api.js";
+
+let ctx: ApiTestContext;
+let app: Application;
+
+describe("Route transport & middleware", () => {
+ beforeAll(async () => {
+ ctx = await bootLoggedInApp();
+ app = ctx.app;
+ });
+
+ describe("bootstrap view detection", () => {
+ it("returns the print view when ?print is present", async () => {
+ const res = await supertest(app).get("/bootstrap?print").expect(200);
+ expect(res.body.device).toBe("print");
+ });
+
+ it("returns the mobile view via query, cookie and user-agent", async () => {
+ expect((await supertest(app).get("/bootstrap?mobile").expect(200)).body.device).toBe("mobile");
+ expect((await supertest(app).get("/bootstrap?desktop").expect(200)).body.device).toBe("desktop");
+
+ const byCookie = await supertest(app).get("/bootstrap").set("Cookie", "trilium-device=mobile").expect(200);
+ expect(byCookie.body.device).toBe("mobile");
+
+ const byUa = await supertest(app).get("/bootstrap")
+ .set("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X)").expect(200);
+ expect(byUa.body.device).toBe("mobile");
+ });
+
+ it("treats ?extraWindow as a non-main window", async () => {
+ const res = await supertest(app).get("/bootstrap?extraWindow=1").expect(200);
+ expect(res.body.isMainWindow).toBe(false);
+ });
+ });
+
+ describe("CSRF & error handling", () => {
+ it("rejects a mutating request carrying a bogus CSRF token (403)", async () => {
+ await ctx.agent.post("/api/tree/load")
+ .set("x-csrf-token", "bogustoken1234567890")
+ .send({ noteIds: ["root"] })
+ .expect(403);
+ });
+
+ it("returns a 404 body for an unknown route", async () => {
+ const res = await supertest(app).get("/this-route-does-not-exist").expect(404);
+ expect(res.body.message).toBeTruthy();
+ });
+
+ it("serves a [statusCode, string] handler result as plain text", async () => {
+ // /api/login/token returns [401, "Incorrect credential"] on a bad
+ // password — exercising apiResultHandler's array form and send()'s
+ // text-error branch.
+ const res = await supertest(app).post("/api/login/token").send({ password: "wrong" }).expect(401);
+ expect(res.headers["content-type"]).toContain("text/plain");
+ expect(res.text).toBe("Incorrect credential");
+ });
+
+ it("maps a thrown ValidationError to a 400 JSON body", async () => {
+ const res = await ctx.agent.post("/api/database/anonymize/bogus")
+ .set("x-csrf-token", ctx.csrfToken)
+ .send({})
+ .expect(400);
+ expect(res.body.message).toContain("Invalid type");
+ });
+
+ it("handles a multipart file upload through the upload middleware", async () => {
+ const { noteId } = await createTextNote(ctx, { title: "Upload target" });
+ const res = await ctx.agent.put(`/api/notes/${noteId}/file`)
+ .set("x-csrf-token", ctx.csrfToken)
+ .attach("upload", Buffer.from("uploaded bytes"), { filename: "doc.txt", contentType: "text/plain" })
+ .expect(200);
+ expect(res.body.uploaded).toBe(true);
+ });
+ });
+
+ it("redirects /setup to the app when the DB is already initialized", async () => {
+ await supertest(app).get("/setup").expect(302);
+ });
+
+ it("logs out an authenticated session", async () => {
+ await ctx.agent.post("/logout").set("x-csrf-token", ctx.csrfToken).expect(302);
+ });
+
+ describe("MCP endpoint", () => {
+ it("returns 403 when MCP is disabled", async () => {
+ const res = await supertest(app).post("/mcp").send({ jsonrpc: "2.0", method: "ping", id: 1 }).expect(403);
+ expect(res.body.error).toContain("disabled");
+ });
+
+ it("reaches the MCP transport over loopback once enabled", async () => {
+ cls.init(() => optionService.setOption("mcpEnabled", "true"));
+ // supertest connects over loopback, so the guard passes and the
+ // request is handed to the streamable transport (any status is fine —
+ // we only need the handler code to execute).
+ const res = await supertest(app)
+ .post("/mcp")
+ .set("Content-Type", "application/json")
+ .set("Accept", "application/json, text/event-stream")
+ .send({ jsonrpc: "2.0", method: "initialize", id: 1, params: { protocolVersion: "2024-11-05", capabilities: {}, clientInfo: { name: "spec", version: "1" } } });
+ expect(res.status).toBeGreaterThanOrEqual(200);
+ });
+ });
+});