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): automated coverage for services
Elian Doran1908dd2e54ba
diff --git a/apps/server/src/services/anonymization.spec.ts b/apps/server/src/services/anonymization.spec.tsnew file mode 100644index 0000000000..5567df245e--- /dev/null+++ b/apps/server/src/services/anonymization.spec.ts@@ -0,0 +1,145 @@+import { BUILTIN_ATTRIBUTES } from "@triliumnext/commons";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++// --- Mocks (hoisted above the module-under-test import) ---++const mockFs = {+ existsSync: vi.fn(),+ mkdirSync: vi.fn(),+ readdirSync: vi.fn()+};++vi.mock("fs", () => ({ default: mockFs, ...mockFs }));++const mockDbInstance = {+ exec: vi.fn(),+ close: vi.fn()+};+// Must be a normal (non-arrow) function so `new Database(...)` works.+const DatabaseCtor = vi.fn(function (this: any) {+ return mockDbInstance;+});++vi.mock("better-sqlite3", () => ({ default: DatabaseCtor }));++const mockSql = { copyDatabase: vi.fn().mockResolvedValue(undefined) };+vi.mock("./sql.js", () => ({ default: mockSql }));++vi.mock("@triliumnext/core", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@triliumnext/core")>();+ return {+ ...actual,+ date_utils: { ...actual.date_utils, getDateTimeForFile: () => "2025-01-01_00-00-00" }+ };+});++// data_dir.ts runs createDirIfNotExisting at import time; provide a directory result.+mockFs.existsSync.mockReturnValue(true);++const { default: anonymization } = await import("./anonymization.js");+const { default: dataDir } = await import("./data_dir.js");++beforeEach(() => {+ vi.clearAllMocks();+ mockSql.copyDatabase.mockResolvedValue(undefined);+});++afterEach(() => vi.restoreAllMocks());++describe("getFullAnonymizationScript", () => {+ it("contains the expected destructive statements and builtin attribute names", () => {+ const script = anonymization.getFullAnonymizationScript();++ // Locks the structural shape of the anonymization SQL.+ expect(script).toContain("UPDATE etapi_tokens SET tokenHash");+ expect(script).toContain("UPDATE notes SET title = 'title'");+ expect(script).toContain("UPDATE blobs SET content = 'text'");+ expect(script).toContain("UPDATE revisions SET title = 'title'");+ expect(script).toContain("UPDATE attachments SET title = 'title'");+ expect(script).toContain("UPDATE attributes SET name = 'name', value = 'value'");+ expect(script).toContain("UPDATE branches SET prefix = 'prefix'");+ expect(script).toContain("UPDATE options SET value = 'anonymized'");+ expect(script).toContain("VACUUM;");++ // Builtin attribute names are preserved (kept out of the anonymization).+ expect(script).toContain("'inbox'");+ expect(script).toContain("'archived'");++ // share-specific attributes are intentionally excluded from the keep-list.+ expect(script).not.toContain("'shareCredentials'");+ expect(script).not.toContain("'shareAlias'");++ // Sanity: every other builtin attribute name appears in the keep-list.+ const expectedNames = BUILTIN_ATTRIBUTES+ .filter((a) => !["shareCredentials", "shareAlias"].includes(a.name))+ .map((a) => a.name);+ for (const name of expectedNames) {+ expect(script).toContain(`'${name}'`);+ }+ });+});++describe("createAnonymizedCopy", () => {+ it("rejects unrecognized anonymization types", async () => {+ await expect(anonymization.createAnonymizedCopy("invalid" as any))+ .rejects.toThrow(/Unrecognized anonymization type/);+ expect(mockSql.copyDatabase).not.toHaveBeenCalled();+ });++ it("creates the anonymized-db dir when missing, then copies + runs the full script", async () => {+ mockFs.existsSync.mockReturnValue(false);++ const result = await anonymization.createAnonymizedCopy("full");++ expect(mockFs.mkdirSync).toHaveBeenCalledWith(dataDir.ANONYMIZED_DB_DIR, 0o700);+ const expectedPath = `${dataDir.ANONYMIZED_DB_DIR}/anonymized-full-2025-01-01_00-00-00.db`;+ expect(mockSql.copyDatabase).toHaveBeenCalledWith(expectedPath);+ expect(DatabaseCtor).toHaveBeenCalledWith(expectedPath);+ // full script ends in VACUUM+ expect(mockDbInstance.exec).toHaveBeenCalledWith(expect.stringContaining("VACUUM;"));+ expect(mockDbInstance.close).toHaveBeenCalled();+ expect(result).toEqual({ success: true, anonymizedFilePath: expectedPath });+ });++ it("skips dir creation when it already exists and runs the light script", async () => {+ mockFs.existsSync.mockReturnValue(true);++ const result = await anonymization.createAnonymizedCopy("light");++ expect(mockFs.mkdirSync).not.toHaveBeenCalled();+ // light script targets js notes' blobs and does NOT vacuum+ const execArg = mockDbInstance.exec.mock.calls[0][0] as string;+ expect(execArg).toContain("application/javascript;env=backend");+ expect(execArg).not.toContain("VACUUM");+ expect(result.success).toBe(true);+ expect(result.anonymizedFilePath).toContain("anonymized-light-");+ });+});++describe("getExistingAnonymizedDatabases", () => {+ it("returns an empty list when the directory does not exist", () => {+ mockFs.existsSync.mockReturnValue(false);+ expect(anonymization.getExistingAnonymizedDatabases()).toEqual([]);+ expect(mockFs.readdirSync).not.toHaveBeenCalled();+ });++ it("lists only files whose name includes 'anonymized'", () => {+ mockFs.existsSync.mockReturnValue(true);+ mockFs.readdirSync.mockReturnValue([+ "anonymized-full-x.db",+ "document.db",+ "anonymized-light-y.db",+ "backup.zip"+ ]);++ const result = anonymization.getExistingAnonymizedDatabases();++ expect(result.map((r) => r.fileName)).toEqual([+ "anonymized-full-x.db",+ "anonymized-light-y.db"+ ]);+ for (const entry of result) {+ expect(entry.filePath).toContain(entry.fileName);+ }+ });+});diff --git a/apps/server/src/services/app_path.spec.ts b/apps/server/src/services/app_path.spec.tsnew file mode 100644index 0000000000..79c02c4db4--- /dev/null+++ b/apps/server/src/services/app_path.spec.ts@@ -0,0 +1,27 @@+import { afterEach, describe, expect, it, vi } from "vitest";++describe("app_path", () => {+ afterEach(() => {+ vi.resetModules();+ vi.doUnmock("./utils.js");+ vi.doUnmock("./asset_path.js");+ });++ it("uses the asset path unchanged in dev mode", async () => {+ vi.resetModules();+ vi.doMock("./utils.js", () => ({ isDev: true }));+ vi.doMock("./asset_path.js", () => ({ default: "assets/vX" }));++ const mod = await import("./app_path.js");+ expect(mod.default).toBe("assets/vX");+ });++ it("appends /src to the asset path outside dev mode", async () => {+ vi.resetModules();+ vi.doMock("./utils.js", () => ({ isDev: false }));+ vi.doMock("./asset_path.js", () => ({ default: "assets/vX" }));++ const mod = await import("./app_path.js");+ expect(mod.default).toBe("assets/vX/src");+ });+});diff --git a/apps/server/src/services/asset_path.spec.ts b/apps/server/src/services/asset_path.spec.tsnew file mode 100644index 0000000000..43073c75dd--- /dev/null+++ b/apps/server/src/services/asset_path.spec.ts@@ -0,0 +1,27 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import packageJson from "../../package.json" with { type: "json" };++describe("asset_path", () => {+ afterEach(() => {+ vi.resetModules();+ vi.doUnmock("./utils");+ });++ it("appends /src suffix in dev mode", async () => {+ vi.resetModules();+ vi.doMock("./utils", () => ({ isDev: true }));++ const mod = await import("./asset_path.js");+ expect(mod.assetUrlFragment).toBe(`assets/v${packageJson.version}`);+ expect(mod.default).toBe(`assets/v${packageJson.version}/src`);+ });++ it("omits /src suffix outside dev mode", async () => {+ vi.resetModules();+ vi.doMock("./utils", () => ({ isDev: false }));++ const mod = await import("./asset_path.js");+ expect(mod.default).toBe(`assets/v${packageJson.version}`);+ });+});diff --git a/apps/server/src/services/auth.spec.ts b/apps/server/src/services/auth.spec.tsindex 7380d6c53f..b27ed11433 100644--- a/apps/server/src/services/auth.spec.ts+++ b/apps/server/src/services/auth.spec.ts@@ -1,11 +1,16 @@-import { options } from "@triliumnext/core";+import { attributes, options, password as passwordService, password_encryption as passwordEncryptionService } from "@triliumnext/core";import { Application } from "express";import supertest from "supertest";-import { beforeAll, describe, expect, it } from "vitest";+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";-import { refreshAuth } from "./auth";+import auth, { refreshAuth } from "./auth";import { cls } from "@triliumnext/core";import config from "./config";+import { markAsInternalElectronRequest } from "./electron_request";+import etapiTokens from "./etapi_tokens";+import openID from "./open_id";+import sqlInit from "./sql_init";+import totp from "./totp";let app: Application;@@ -72,4 +77,309 @@ describe("Auth", () => {.expect(200);});});++ describe("middleware (direct invocation)", () => {+ function makeRes() {+ const res = {+ statusCode: 0 as number,+ headers: {} as Record<string, string>,+ body: undefined as unknown,+ redirectedTo: undefined as string | undefined,+ setHeader(k: string, v: string) {+ res.headers[k] = v;+ return res;+ },+ status(c: number) {+ res.statusCode = c;+ return res;+ },+ json(o: unknown) {+ res.body = o;+ return res;+ },+ send(o: unknown) {+ res.body = o;+ return res;+ },+ redirect(loc: string) {+ res.redirectedTo = loc;+ }+ };+ return res;+ }++ function makeReq(overrides: Record<string, unknown> = {}) {+ return {+ method: "GET",+ path: "/test",+ ip: "127.0.0.1",+ sessionID: "sid",+ headers: {},+ session: {},+ ...overrides+ } as never;+ }++ beforeAll(() => {+ config.General.noAuthentication = false;+ refreshAuth();+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ it("checkAuth lets the request through when the DB is not initialized", () => {+ const spy = vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(false);+ const next = vi.fn();+ auth.checkAuth(makeReq(), makeRes() as never, next);+ expect(next).toHaveBeenCalled();+ spy.mockRestore();+ });++ it("checkAuth lets internal electron requests through", () => {+ vi.spyOn(totp, "isTotpEnabled").mockReturnValue(false);+ vi.spyOn(openID, "isOpenIDEnabled").mockReturnValue(false);+ const req = makeReq();+ markAsInternalElectronRequest(req as object);+ const next = vi.fn();+ auth.checkAuth(req, makeRes() as never, next);+ expect(next).toHaveBeenCalled();+ });++ it("checkAuth redirects to login when not logged in (no bare-domain redirect)", () => {+ vi.spyOn(totp, "isTotpEnabled").mockReturnValue(false);+ vi.spyOn(openID, "isOpenIDEnabled").mockReturnValue(false);+ cls.init(() => options.setOption("redirectBareDomain", "false"));+ const res = makeRes();+ auth.checkAuth(makeReq({ session: { loggedIn: false } }), res as never, vi.fn());+ expect(res.redirectedTo).toBe("login");+ });++ it("checkAuth honours redirectBareDomain: 404 when no shareRoot, else redirects to share", () => {+ vi.spyOn(totp, "isTotpEnabled").mockReturnValue(false);+ vi.spyOn(openID, "isOpenIDEnabled").mockReturnValue(false);+ cls.init(() => options.setOption("redirectBareDomain", "true"));++ const labelSpy = vi.spyOn(attributes, "getNotesWithLabel").mockReturnValue([]);+ const res404 = makeRes();+ auth.checkAuth(makeReq({ session: { loggedIn: false } }), res404 as never, vi.fn());+ expect(res404.statusCode).toBe(404);++ labelSpy.mockReturnValue([{ noteId: "x" } as never]);+ const resShare = makeRes();+ auth.checkAuth(makeReq({ session: { loggedIn: false } }), resShare as never, vi.fn());+ expect(resShare.redirectedTo).toBe("share");++ cls.init(() => options.setOption("redirectBareDomain", "false"));+ });++ it("checkAuth destroys the session and redirects when auth state changed", () => {+ vi.spyOn(totp, "isTotpEnabled").mockReturnValue(true);+ vi.spyOn(openID, "isOpenIDEnabled").mockReturnValue(false);+ const destroy = vi.fn((cb: (err?: Error) => void) => cb());+ const res = makeRes();+ auth.checkAuth(+ makeReq({+ session: { loggedIn: true, lastAuthState: { totpEnabled: false, ssoEnabled: false }, destroy }+ }),+ res as never,+ vi.fn()+ );+ expect(destroy).toHaveBeenCalled();+ expect(res.redirectedTo).toBe("login");++ // also exercise the destroy-error logging branch+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ const destroyErr = vi.fn((cb: (err?: Error) => void) => cb(new Error("boom")));+ auth.checkAuth(+ makeReq({+ session: { loggedIn: true, lastAuthState: { totpEnabled: false, ssoEnabled: false }, destroy: destroyErr }+ }),+ makeRes() as never,+ vi.fn()+ );+ expect(errSpy).toHaveBeenCalled();+ errSpy.mockRestore();+ });++ it("checkAuth handles the SSO-enabled path (authenticated vs not)", () => {+ vi.spyOn(totp, "isTotpEnabled").mockReturnValue(false);+ vi.spyOn(openID, "isOpenIDEnabled").mockReturnValue(true);+ const base = {+ loggedIn: true,+ lastAuthState: { totpEnabled: false, ssoEnabled: true }+ };++ const nextOk = vi.fn();+ auth.checkAuth(+ makeReq({ session: { ...base }, oidc: { isAuthenticated: () => true } }),+ makeRes() as never,+ nextOk+ );+ expect(nextOk).toHaveBeenCalled();++ const resRedirect = makeRes();+ auth.checkAuth(+ makeReq({ session: { ...base }, oidc: { isAuthenticated: () => false } }),+ resRedirect as never,+ vi.fn()+ );+ expect(resRedirect.redirectedTo).toBe("login");+ });++ it("checkAuth falls through to next on the normal logged-in path", () => {+ vi.spyOn(totp, "isTotpEnabled").mockReturnValue(false);+ vi.spyOn(openID, "isOpenIDEnabled").mockReturnValue(false);+ const next = vi.fn();+ auth.checkAuth(+ makeReq({ session: { loggedIn: true, lastAuthState: { totpEnabled: false, ssoEnabled: false } } }),+ makeRes() as never,+ next+ );+ expect(next).toHaveBeenCalled();+ });++ it("checkApiAuthOrElectron rejects unauthenticated and allows internal electron", () => {+ const res = makeRes();+ auth.checkApiAuthOrElectron(makeReq({ session: { loggedIn: false } }), res as never, vi.fn());+ expect(res.statusCode).toBe(401);++ const req = makeReq({ session: { loggedIn: false } });+ markAsInternalElectronRequest(req as object);+ const next = vi.fn();+ auth.checkApiAuthOrElectron(req, makeRes() as never, next);+ expect(next).toHaveBeenCalled();+ });++ it("checkApiAuthOrElectron passes through when DB not initialized", () => {+ const spy = vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(false);+ const next = vi.fn();+ auth.checkApiAuthOrElectron(makeReq(), makeRes() as never, next);+ expect(next).toHaveBeenCalled();+ spy.mockRestore();+ });++ it("checkApiAuth handles electron, unauthenticated, and authenticated paths", () => {+ // DB not initialized -> next+ const dbSpy = vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(false);+ const next1 = vi.fn();+ auth.checkApiAuth(makeReq(), makeRes() as never, next1);+ expect(next1).toHaveBeenCalled();+ dbSpy.mockRestore();++ // internal electron -> next+ const electronReq = makeReq();+ markAsInternalElectronRequest(electronReq as object);+ const next2 = vi.fn();+ auth.checkApiAuth(electronReq, makeRes() as never, next2);+ expect(next2).toHaveBeenCalled();++ // not logged in -> reject+ const res = makeRes();+ auth.checkApiAuth(makeReq({ session: { loggedIn: false } }), res as never, vi.fn());+ expect(res.statusCode).toBe(401);++ // logged in -> next+ const next3 = vi.fn();+ auth.checkApiAuth(makeReq({ session: { loggedIn: true } }), makeRes() as never, next3);+ expect(next3).toHaveBeenCalled();+ });++ it("checkAppInitialized always calls next", () => {+ const next = vi.fn();+ auth.checkAppInitialized(makeReq(), makeRes() as never, next);+ expect(next).toHaveBeenCalled();+ });++ it("checkPasswordSet / checkPasswordNotSet branch on whether a password is set", () => {+ // password set+ const setSpy = vi.spyOn(passwordService, "isPasswordSet").mockReturnValue(true);+ const nextSet = vi.fn();+ auth.checkPasswordSet(makeReq(), makeRes() as never, nextSet);+ expect(nextSet).toHaveBeenCalled();++ const resNotSet = makeRes();+ auth.checkPasswordNotSet(makeReq(), resNotSet as never, vi.fn());+ expect(resNotSet.redirectedTo).toBe("login");+ setSpy.mockRestore();++ // password not set+ const unsetSpy = vi.spyOn(passwordService, "isPasswordSet").mockReturnValue(false);+ const resSet = makeRes();+ auth.checkPasswordSet(makeReq(), resSet as never, vi.fn());+ expect(resSet.redirectedTo).toBe("set-password");++ const nextNotSet = vi.fn();+ auth.checkPasswordNotSet(makeReq(), makeRes() as never, nextNotSet);+ expect(nextNotSet).toHaveBeenCalled();+ unsetSpy.mockRestore();+ });++ it("checkAppNotInitialized rejects when initialized, else calls next", () => {+ const res = makeRes();+ auth.checkAppNotInitialized(makeReq(), res as never, vi.fn());+ expect(res.statusCode).toBe(401);++ const spy = vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(false);+ const next = vi.fn();+ auth.checkAppNotInitialized(makeReq(), makeRes() as never, next);+ expect(next).toHaveBeenCalled();+ spy.mockRestore();+ });++ it("checkEtapiToken accepts a valid token header and rejects an invalid one", () => {+ const { authToken } = cls.init(() => etapiTokens.createToken("auth-spec-token"));+ const next = vi.fn();+ auth.checkEtapiToken(makeReq({ headers: { authorization: authToken } }), makeRes() as never, next);+ expect(next).toHaveBeenCalled();++ const res = makeRes();+ auth.checkEtapiToken(makeReq({ headers: { authorization: "bogus_token" } }), res as never, vi.fn());+ expect(res.statusCode).toBe(401);+ });++ it("checkCredentials walks DB/password/header/verification branches", () => {+ // DB not initialized -> 400+ const dbSpy = vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(false);+ const res1 = makeRes();+ auth.checkCredentials(makeReq(), res1 as never, vi.fn());+ expect(res1.statusCode).toBe(400);+ dbSpy.mockRestore();++ // password not set -> 400+ const unsetSpy = vi.spyOn(passwordService, "isPasswordSet").mockReturnValue(false);+ const res2 = makeRes();+ auth.checkCredentials(makeReq(), res2 as never, vi.fn());+ expect(res2.statusCode).toBe(400);+ unsetSpy.mockRestore();++ // password set from here on+ vi.spyOn(passwordService, "isPasswordSet").mockReturnValue(true);++ // non-string trilium-cred header -> 400+ const res3 = makeRes();+ auth.checkCredentials(makeReq({ headers: { "trilium-cred": ["a", "b"] } }), res3 as never, vi.fn());+ expect(res3.statusCode).toBe(400);++ // wrong password -> 401+ const verifySpy = vi.spyOn(passwordEncryptionService, "verifyPassword").mockReturnValue(false as never);+ const cred = Buffer.from("user:wrongpass").toString("base64");+ const res4 = makeRes();+ auth.checkCredentials(makeReq({ headers: { "trilium-cred": cred } }), res4 as never, vi.fn());+ expect(res4.statusCode).toBe(401);++ // correct password (no colon in decoded cred path also exercised) -> next+ verifySpy.mockReturnValue(true as never);+ const credNoColon = Buffer.from("justpassword").toString("base64");+ const next = vi.fn();+ auth.checkCredentials(makeReq({ headers: { "trilium-cred": credNoColon } }), makeRes() as never, next);+ expect(next).toHaveBeenCalled();++ // missing trilium-cred header -> falls back to "" -> next (with verify mocked true)+ const nextNoHeader = vi.fn();+ auth.checkCredentials(makeReq({ headers: {} }), makeRes() as never, nextNoHeader);+ expect(nextNoHeader).toHaveBeenCalled();+ });+ });}, 60_000);diff --git a/apps/server/src/services/branches.spec.ts b/apps/server/src/services/branches.spec.tsnew file mode 100644index 0000000000..55db2d78d6--- /dev/null+++ b/apps/server/src/services/branches.spec.ts@@ -0,0 +1,136 @@+import { becca, cls, note_service as noteService } from "@triliumnext/core";+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";++import branches from "./branches.js";+import sql_init from "./sql_init.js";++function createNote(parentNoteId: string, title: string) {+ return cls.init(() => noteService.createNewNote({+ parentNoteId, title, content: "", type: "text"+ }));+}++describe("branches (real DB)", () => {+ beforeAll(async () => {+ sql_init.initializeDb();+ await sql_init.dbReady;+ });++ afterEach(() => vi.restoreAllMocks());++ describe("moveBranchToNote", () => {+ it("is a no-op when the branch already lives under the target parent", () => {+ const { branch } = createNote("root", "Stay put");++ const result = branches.moveBranchToNote(branch, branch.parentNoteId);++ expect(result).toEqual({ success: true });+ // The branch was not replaced.+ expect(becca.getBranch(branch.branchId!)?.isDeleted).toBeFalsy();+ });++ it("returns the validation result tuple when the move is invalid", () => {+ const parent = createNote("root", "Parent");+ const child = createNote(parent.note.noteId, "Child");++ // Moving a parent under its own descendant is a cycle → validation fails.+ const result = branches.moveBranchToNote(parent.branch, child.note.noteId) as any[];++ expect(Array.isArray(result)).toBe(true);+ expect(result[0]).toBe(200);+ expect(result[1].success).toBe(false);+ });++ it("moves a branch to a new parent, deleting the old branch (notePosition 0 when target empty)", () => {+ const sourceParent = createNote("root", "Source");+ const targetParent = createNote("root", "Target empty");+ const child = createNote(sourceParent.note.noteId, "Movable");+ const oldBranchId = child.branch.branchId!;++ const result = cls.init(() => branches.moveBranchToNote(child.branch, targetParent.note.noteId)) as any;++ expect(result.success).toBe(true);+ expect(result.branch.parentNoteId).toBe(targetParent.note.noteId);+ // The original branch is gone (deleted or removed from the cache).+ const oldBranch = becca.getBranch(oldBranchId);+ expect(!oldBranch || oldBranch.isDeleted).toBe(true);+ // The note now lives under the target.+ expect(child.note.getParentBranches().some((b) => b.parentNoteId === targetParent.note.noteId)).toBe(true);+ });++ it("computes notePosition as max + 10 when the target already has children", () => {+ const targetParent = createNote("root", "Target with child");+ // Existing child establishes a max notePosition.+ const existing = createNote(targetParent.note.noteId, "Existing");+ existing.branch.notePosition = 50;+ cls.init(() => existing.branch.save());++ const sourceParent = createNote("root", "Source 2");+ const child = createNote(sourceParent.note.noteId, "Movable 2");++ const result = cls.init(() => branches.moveBranchToNote(child.branch, targetParent.note.noteId)) as any;++ expect(result.success).toBe(true);+ expect(result.branch.notePosition).toBe(60);+ });+ });++ describe("moveBranchToBranch", () => {+ it("moves the branch and expands a collapsed target parent branch", () => {+ const targetParent = createNote("root", "Expand target");+ const targetBranch = targetParent.branch;+ targetBranch.isExpanded = false;+ cls.init(() => targetBranch.save());++ const source = createNote("root", "Source 3");+ const child = createNote(source.note.noteId, "Movable 3");++ const result = cls.init(() => branches.moveBranchToBranch(child.branch, targetBranch, "ignored")) as any;++ expect(result.success).toBe(true);+ expect(targetBranch.isExpanded).toBe(true);+ });++ it("leaves an already-expanded target parent untouched", () => {+ const targetParent = createNote("root", "Already expanded");+ const targetBranch = targetParent.branch;+ targetBranch.isExpanded = true;+ cls.init(() => targetBranch.save());++ const source = createNote("root", "Source 4");+ const child = createNote(source.note.noteId, "Movable 4");+ const saveSpy = vi.spyOn(targetBranch, "save");++ const result = cls.init(() => branches.moveBranchToBranch(child.branch, targetBranch, "ignored")) as any;++ expect(result.success).toBe(true);+ expect(targetBranch.isExpanded).toBe(true);+ // No re-save was needed to expand.+ expect(saveSpy).not.toHaveBeenCalled();+ });++ it("passes through a failed move without expanding the target", () => {+ const parent = createNote("root", "P5");+ const child = createNote(parent.note.noteId, "C5");+ const targetBranch = child.branch;+ targetBranch.isExpanded = false;++ // Moving the parent into its own child fails validation.+ const result = branches.moveBranchToBranch(parent.branch, targetBranch, "ignored") as any[];++ expect(Array.isArray(result)).toBe(true);+ expect(result[0]).toBe(200);+ expect(targetBranch.isExpanded).toBe(false);+ });++ it("returns the no-op success object when source already under the target parent", () => {+ const targetParent = createNote("root", "Noop target");+ const targetBranch = targetParent.branch;+ const child = createNote(targetParent.note.noteId, "Child noop");++ const result = cls.init(() => branches.moveBranchToBranch(child.branch, targetBranch, "ignored")) as any;++ expect(result).toEqual({ success: true });+ });+ });+});diff --git a/apps/server/src/services/config.spec.ts b/apps/server/src/services/config.spec.tsindex 573d89d3d1..f55f4321e3 100644--- a/apps/server/src/services/config.spec.ts+++ b/apps/server/src/services/config.spec.ts@@ -303,6 +303,37 @@ corsAllowOrigin=https://ini-cors.com});});+ describe("config.ini bootstrapping", () => {+ it("creates config.ini from the sample when it does not yet exist", async () => {+ // existsSync false -> the bootstrap branch copies config-sample.ini.+ vi.mocked(fs.existsSync).mockReturnValue(false);+ const sampleContents = "[General]\ninstanceName=from-sample";+ vi.mocked(fs.readFileSync).mockImplementation((path) => {+ if (String(path).includes("config-sample.ini")) {+ return Buffer.from(sampleContents) as any;+ }+ return sampleContents as any;+ });++ const { default: config } = await import("./config.js");++ expect(fs.writeFileSync).toHaveBeenCalledWith("/test/config.ini", sampleContents);+ expect(config.General.instanceName).toBe("from-sample");+ });+ });++ describe("Boolean transformation edge cases", () => {+ it("defaults unrecognized boolean-ish values to false", async () => {+ // "yes" is not handled by envToBoolean nor the 1/0 checks -> falls+ // through to the default `return false` branch of transformBoolean.+ process.env.TRILIUM_GENERAL_NOAUTHENTICATION = "yes";++ const { default: config } = await import("./config.js");++ expect(config.General.noAuthentication).toBe(false);+ });+ });+describe("Default Values", () => {it("should use correct default values when no config is provided", async () => {const { default: config } = await import("./config.js");diff --git a/apps/server/src/services/data_dir.spec.ts b/apps/server/src/services/data_dir.spec.tsindex a6a408b269..e61a9922b8 100644--- a/apps/server/src/services/data_dir.spec.ts+++ b/apps/server/src/services/data_dir.spec.ts@@ -1,4 +1,4 @@-import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import type { getDataDirs as getDataDirsType, getPlatformAppDataDir as getPlatformAppDataDirType,getTriliumDataDir as getTriliumDataDirType } from "./data_dir.js";@@ -361,4 +361,80 @@ describe("data_dir.ts unit tests", () => {}});});++ describe("createDirIfNotExisting error handling (via getTriliumDataDir case A)", () => {+ beforeEach(() => {+ resetAllMocks();+ process.env.TRILIUM_DATA_DIR = "/home/mock/trilium-data-ERR";+ vi.spyOn(console, "error").mockImplementation(() => {});+ });++ afterEach(() => {+ delete process.env.TRILIUM_DATA_DIR;+ vi.restoreAllMocks();+ });++ const mkdirThrows = (code: string) => {+ const err = new Error(code) as NodeJS.ErrnoException;+ err.code = code;+ mockFn.mkdirSyncMock.mockImplementation(() => { throw err; });+ return err;+ };++ it("EACCES – prints permission diagnostics (parent stat ok) and rethrows", () => {+ const err = mkdirThrows("EACCES");+ // statSync of the parent dir succeeds -> owner/permission diagnostics branch.+ mockFn.statSyncMock.mockImplementation(() => ({ uid: 1000, gid: 1000, mode: 0o755 }));+ // Provide getuid/getgid (absent on Windows) so the UID:GID branch runs.+ const proc = process as NodeJS.Process & { getuid?: () => number; getgid?: () => number };+ const hadGetuid = "getuid" in proc;+ proc.getuid = () => 1000;+ proc.getgid = () => 1000;++ try {+ expect(() => getTriliumDataDir("trilium-data")).toThrow(err);+ expect(console.error).toHaveBeenCalled();+ expect(mockFn.statSyncMock).toHaveBeenCalledTimes(1);+ } finally {+ if (!hadGetuid) {+ delete proc.getuid;+ delete proc.getgid;+ }+ }+ });++ it("EACCES – handles an inaccessible parent dir (stat throws) and rethrows", () => {+ const err = mkdirThrows("EACCES");+ mockFn.statSyncMock.mockImplementation(() => { throw new Error("no access"); });++ expect(() => getTriliumDataDir("trilium-data")).toThrow(err);+ expect(console.error).toHaveBeenCalled();+ });++ it("EEXIST but target is not a directory – rethrows", () => {+ const err = mkdirThrows("EEXIST");+ mockFn.statSyncMock.mockImplementation(() => ({ isDirectory: () => false }));++ expect(() => getTriliumDataDir("trilium-data")).toThrow(err);+ });++ it("EEXIST but stat throws – rethrows the original error", () => {+ const err = mkdirThrows("EEXIST");+ mockFn.statSyncMock.mockImplementation(() => { throw new Error("cannot stat"); });++ expect(() => getTriliumDataDir("trilium-data")).toThrow(err);+ });++ it("other error codes – rethrows directly", () => {+ const err = mkdirThrows("ENOSPC");++ expect(() => getTriliumDataDir("trilium-data")).toThrow(err);+ });++ it("non-Error throw value – rethrows as-is", () => {+ mockFn.mkdirSyncMock.mockImplementation(() => { throw "weird"; });++ expect(() => getTriliumDataDir("trilium-data")).toThrow("weird");+ });+ });});diff --git a/apps/server/src/services/electron_request.spec.ts b/apps/server/src/services/electron_request.spec.tsnew file mode 100644index 0000000000..85f944eac5--- /dev/null+++ b/apps/server/src/services/electron_request.spec.ts@@ -0,0 +1,19 @@+import { describe, expect, it } from "vitest";++import { isInternalElectronRequest, markAsInternalElectronRequest } from "./electron_request.js";++describe("electron_request markers", () => {+ it("marks a request as internal and detects it", () => {+ const req = {};+ expect(isInternalElectronRequest(req)).toBe(false);++ markAsInternalElectronRequest(req);+ expect(isInternalElectronRequest(req)).toBe(true);+ });++ it("reports unmarked / foreign-keyed objects as not internal", () => {+ expect(isInternalElectronRequest({})).toBe(false);+ // A plain string key cannot collide with the internal symbol.+ expect(isInternalElectronRequest({ "trilium-electron-internal-request": true })).toBe(false);+ });+});diff --git a/apps/server/src/services/encryption/my_scrypt.spec.ts b/apps/server/src/services/encryption/my_scrypt.spec.tsnew file mode 100644index 0000000000..63eb2dc53c--- /dev/null+++ b/apps/server/src/services/encryption/my_scrypt.spec.ts@@ -0,0 +1,58 @@+import { beforeAll, describe, expect, it, vi } from "vitest";++import sql from "../sql.js";+import sql_init from "../sql_init.js";+import myScrypt from "./my_scrypt.js";++describe("my_scrypt (OpenID scrypt helpers)", () => {+ beforeAll(async () => {+ sql_init.initializeDb();+ await sql_init.dbReady;+ });++ it("derives deterministic, salt-dependent hashes when salt is given explicitly", () => {+ const a = myScrypt.getSubjectIdentifierVerificationHash("subject", "salt-one");+ const a2 = myScrypt.getSubjectIdentifierVerificationHash("subject", "salt-one");+ const b = myScrypt.getSubjectIdentifierVerificationHash("subject", "salt-two");++ expect(a).toBeInstanceOf(Buffer);+ expect(a).toHaveLength(32);+ expect(a!.equals(a2!)).toBe(true);+ expect(a!.equals(b!)).toBe(false);++ // createSubjectIdentifierDerivedKey shares the same underlying sync hash+ const derived = myScrypt.createSubjectIdentifierDerivedKey("subject", "salt-one");+ expect(derived.equals(a!)).toBe(true);++ // getSubjectIdentifierDerivedKey with explicit salt matches as well+ const derivedKey = myScrypt.getSubjectIdentifierDerivedKey("subject", "salt-one");+ expect(derivedKey!.equals(a!)).toBe(true);+ });++ it("reads salt from user_data when none is given", () => {+ sql.transactional(() => {+ sql.execute("DELETE FROM user_data");+ sql.upsert("user_data", "tmpID", { tmpID: 0, salt: "db-salt" });+ });++ const fromDb = myScrypt.getSubjectIdentifierVerificationHash("subject");+ const explicit = myScrypt.getSubjectIdentifierVerificationHash("subject", "db-salt");+ expect(fromDb!.equals(explicit!)).toBe(true);++ const derivedFromDb = myScrypt.getSubjectIdentifierDerivedKey("subject");+ expect(derivedFromDb!.equals(explicit!)).toBe(true);+ });++ it("returns undefined and logs when no salt is stored", () => {+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ sql.transactional(() => {+ sql.execute("DELETE FROM user_data");+ });++ expect(myScrypt.getSubjectIdentifierVerificationHash("subject")).toBeUndefined();+ expect(errorSpy).toHaveBeenCalled();+ expect(myScrypt.getSubjectIdentifierDerivedKey("subject")).toBeUndefined();++ errorSpy.mockRestore();+ });+});diff --git a/apps/server/src/services/encryption/open_id_encryption.spec.ts b/apps/server/src/services/encryption/open_id_encryption.spec.tsnew file mode 100644index 0000000000..2ca5393872--- /dev/null+++ b/apps/server/src/services/encryption/open_id_encryption.spec.ts@@ -0,0 +1,164 @@+import { data_encryption } from "@triliumnext/core";+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";++import sql from "../sql.js";+import sqlInit from "../sql_init.js";+import myScrypt from "./my_scrypt.js";+import openIDEncryption from "./open_id_encryption.js";++function clearUserData() {+ sql.transactional(() => {+ sql.execute("DELETE FROM user_data");+ });+}++describe("open_id_encryption", () => {+ beforeAll(async () => {+ const sql_init = (await import("../sql_init.js")).default;+ sql_init.initializeDb();+ await sql_init.dbReady;+ });++ beforeEach(() => {+ clearUserData();+ });++ it("reports no saved identifier on an empty user_data table", () => {+ expect(openIDEncryption.isSubjectIdentifierSaved()).toBe(false);+ });++ it("saveUser persists a user and marks it saved; a second saveUser is a no-op", () => {+ const saved = openIDEncryption.saveUser("subject-123", "Alice", "[email protected]");+ expect(saved).toBe(true);++ expect(openIDEncryption.isSubjectIdentifierSaved()).toBe(true);+ // once a user is set up, verifyOpenIDSubjectIdentifier short-circuits to false+ expect(openIDEncryption.verifyOpenIDSubjectIdentifier("subject-123")).toBe(false);++ // a second save short-circuits because a user already exists+ expect(openIDEncryption.saveUser("other", "Bob", "[email protected]")).toBe(false);+ });++ it("setDataKey / getDataKey round-trips the plaintext data key", () => {+ const salt = "fixed-salt";+ const plainKey = "0123456789abcdef";+ const encrypted = openIDEncryption.setDataKey("subject-xyz", plainKey, salt);+ expect(typeof encrypted).toBe("string");++ sql.transactional(() => {+ sql.upsert("user_data", "tmpID", {+ tmpID: 0,+ salt,+ userIDEncryptedDataKey: encrypted+ });+ });++ const decrypted = openIDEncryption.getDataKey("subject-xyz");+ expect(Buffer.from(decrypted as Uint8Array).toString()).toBe(plainKey);+ });++ it("getDataKey returns undefined when no encrypted data key is stored", () => {+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ sql.transactional(() => {+ sql.upsert("user_data", "tmpID", { tmpID: 0, salt: "s" });+ });+ expect(openIDEncryption.getDataKey("subject")).toBeUndefined();+ expect(errorSpy).toHaveBeenCalled();+ errorSpy.mockRestore();+ });++ it("getDataKey returns undefined when the derived key cannot be produced", () => {+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ sql.transactional(() => {+ sql.upsert("user_data", "tmpID", { tmpID: 0, salt: "s", userIDEncryptedDataKey: "abc" });+ });+ const spy = vi.spyOn(myScrypt, "getSubjectIdentifierDerivedKey").mockReturnValue(undefined);+ expect(openIDEncryption.getDataKey("subject")).toBeUndefined();+ expect(errorSpy).toHaveBeenCalled();+ spy.mockRestore();+ errorSpy.mockRestore();+ });++ it("setDataKey returns undefined when the derived key cannot be produced", () => {+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ const spy = vi+ .spyOn(myScrypt, "getSubjectIdentifierDerivedKey")+ .mockReturnValue(undefined);+ expect(openIDEncryption.setDataKey("subject", "key", "salt")).toBeUndefined();+ expect(errorSpy).toHaveBeenCalled();+ spy.mockRestore();+ errorSpy.mockRestore();+ });++ describe("verifyOpenIDSubjectIdentifier", () => {+ it("throws when the database is not initialized", () => {+ const spy = vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(false);+ expect(() => openIDEncryption.verifyOpenIDSubjectIdentifier("subject")).toThrow();+ spy.mockRestore();+ });++ it("returns undefined when salt is missing", () => {+ const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});+ // row exists (so isUserSaved=false) but salt is null+ sql.transactional(() => {+ sql.upsert("user_data", "tmpID", { tmpID: 0, isSetup: "false" });+ });+ expect(openIDEncryption.verifyOpenIDSubjectIdentifier("subject")).toBeUndefined();+ logSpy.mockRestore();+ });++ it("returns the constant-time comparison of stored vs computed hashes", () => {+ const subject = "subject-verify";+ const salt = "the-salt";+ const hash = myScrypt.getSubjectIdentifierVerificationHash(subject, salt)!.toString("base64");+ sql.transactional(() => {+ sql.upsert("user_data", "tmpID", {+ tmpID: 0,+ isSetup: "false",+ salt,+ userIDVerificationHash: hash+ });+ });++ expect(openIDEncryption.verifyOpenIDSubjectIdentifier(subject)).toBe(true);+ expect(openIDEncryption.verifyOpenIDSubjectIdentifier("wrong-subject")).toBe(false);+ });++ it("returns undefined when the computed subject-id hash is undefined", () => {+ const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});+ sql.transactional(() => {+ sql.upsert("user_data", "tmpID", { tmpID: 0, isSetup: "false", salt: "s" });+ });+ const spy = vi+ .spyOn(myScrypt, "getSubjectIdentifierVerificationHash")+ .mockReturnValue(undefined);+ expect(openIDEncryption.verifyOpenIDSubjectIdentifier("subject")).toBeUndefined();+ spy.mockRestore();+ logSpy.mockRestore();+ });++ });++ describe("saveUser defensive branches", () => {+ it("throws when the verification hash cannot be computed", () => {+ const spy = vi+ .spyOn(myScrypt, "getSubjectIdentifierVerificationHash")+ .mockReturnValue(undefined);+ expect(() => openIDEncryption.saveUser("s", "n", "[email protected]")).toThrow();+ spy.mockRestore();+ });++ it("returns undefined when the encrypted data key cannot be produced", () => {+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ const encryptSpy = vi.spyOn(data_encryption, "encrypt");+ const derivedSpy = vi+ .spyOn(myScrypt, "getSubjectIdentifierDerivedKey")+ .mockReturnValue(undefined);+ expect(openIDEncryption.saveUser("s", "n", "[email protected]")).toBeUndefined();+ expect(encryptSpy).not.toHaveBeenCalled();+ derivedSpy.mockRestore();+ encryptSpy.mockRestore();+ errorSpy.mockRestore();+ });+ });+});diff --git a/apps/server/src/services/encryption/open_id_encryption.ts b/apps/server/src/services/encryption/open_id_encryption.tsindex 5126a0cf5c..c5d351b587 100644--- a/apps/server/src/services/encryption/open_id_encryption.ts+++ b/apps/server/src/services/encryption/open_id_encryption.ts@@ -82,6 +82,9 @@ function verifyOpenIDSubjectIdentifier(subjectIdentifier: string) {const savedHash = sql.getValue("SELECT userIDVerificationHash FROM user_data");+ /* v8 ignore next 4 -- unreachable: the same single user_data row already+ yielded a non-null salt above, so this column query cannot return undefined+ (a NULL column yields null, not undefined). */if (savedHash === undefined) {console.log("verification hash undefined");return undefined;diff --git a/apps/server/src/services/encryption/recovery_codes.spec.ts b/apps/server/src/services/encryption/recovery_codes.spec.tsnew file mode 100644index 0000000000..e1d5f0c136--- /dev/null+++ b/apps/server/src/services/encryption/recovery_codes.spec.ts@@ -0,0 +1,70 @@+import { cls, options } from "@triliumnext/core";+import { beforeAll, describe, expect, it } from "vitest";++import sql_init from "../sql_init.js";+import recoveryCodes from "./recovery_codes.js";++// A recovery code in this scheme is any string matching /^.{22}==$/ (24 chars+// ending in "=="). We use deterministic placeholder codes here.+const CODE_A = "AAAAAAAAAAAAAAAAAAAAAA==";+const CODE_B = "BBBBBBBBBBBBBBBBBBBBBB==";++describe("recovery_codes", () => {+ beforeAll(async () => {+ sql_init.initializeDb();+ await sql_init.dbReady;+ });++ it("returns [] when not set, and round-trips after setting", () => {+ cls.init(() => {+ options.setOption("encryptedRecoveryCodes", "false");+ });+ expect(recoveryCodes.isRecoveryCodeSet()).toBe(false);+ expect(recoveryCodes.getRecoveryCodes()).toEqual([]);++ cls.init(() => {+ recoveryCodes.setRecoveryCodes([CODE_A, CODE_B].join(","));+ });++ expect(recoveryCodes.isRecoveryCodeSet()).toBe(true);+ expect(recoveryCodes.getRecoveryCodes()).toEqual([CODE_A, CODE_B]);+ });++ it("rejects codes failing the format regex without consuming a code", () => {+ cls.init(() => {+ recoveryCodes.setRecoveryCodes([CODE_A, CODE_B].join(","));+ });++ let result: boolean | undefined;+ cls.init(() => {+ result = recoveryCodes.verifyRecoveryCode("too-short");+ });+ expect(result).toBe(false);+ // both codes still present+ expect(recoveryCodes.getRecoveryCodes()).toEqual([CODE_A, CODE_B]);+ });++ it("matches a valid code, consumes it (replaced with a date), and rejects reuse", () => {+ cls.init(() => {+ recoveryCodes.setRecoveryCodes([CODE_A, CODE_B].join(","));+ });++ let firstMatch: boolean | undefined;+ cls.init(() => {+ firstMatch = recoveryCodes.verifyRecoveryCode(CODE_A);+ });+ expect(firstMatch).toBe(true);++ // CODE_A has been replaced with a date string; the remaining real code is CODE_B+ const remaining = recoveryCodes.getRecoveryCodes();+ expect(remaining).toContain(CODE_B);+ expect(remaining).not.toContain(CODE_A);++ // reusing the now-consumed code fails (it no longer matches anything stored)+ let reuse: boolean | undefined;+ cls.init(() => {+ reuse = recoveryCodes.verifyRecoveryCode(CODE_A);+ });+ expect(reuse).toBe(false);+ });+});diff --git a/apps/server/src/services/encryption/totp_encryption.spec.ts b/apps/server/src/services/encryption/totp_encryption.spec.tsnew file mode 100644index 0000000000..3ed346f40e--- /dev/null+++ b/apps/server/src/services/encryption/totp_encryption.spec.ts@@ -0,0 +1,78 @@+import { cls, data_encryption } from "@triliumnext/core";+import { beforeAll, describe, expect, it, vi } from "vitest";++import sql_init from "../sql_init.js";+import totpEncryption from "./totp_encryption.js";++const SECRET = "JBSWY3DPEHPK3PXP";++describe("totp_encryption", () => {+ beforeAll(async () => {+ sql_init.initializeDb();+ await sql_init.dbReady;+ });++ it("throws when setting an empty secret", () => {+ cls.init(() => {+ expect(() => totpEncryption.setTotpSecret("")).toThrow();+ });+ });++ it("round-trips a secret and verifies it", () => {+ cls.init(() => {+ totpEncryption.setTotpSecret(SECRET);+ });++ expect(totpEncryption.isTotpSecretSet()).toBe(true);+ // getTotpSecret returns a non-null decrypted value whose bytes are the secret+ const stored = totpEncryption.getTotpSecret();+ expect(stored).not.toBeNull();+ const bytes = Uint8Array.from((stored as string).split(",").map(Number));+ expect(Buffer.from(bytes).toString("utf-8")).toBe(SECRET);+ // verification re-hashes the original secret with the password salt+ expect(totpEncryption.verifyTotpSecret(SECRET)).toBe(true);+ expect(totpEncryption.verifyTotpSecret("wrong-secret")).toBe(false);+ });++ it("returns null from getTotpSecret when decryption yields a falsy result", () => {+ cls.init(() => {+ totpEncryption.setTotpSecret(SECRET);+ });+ const decryptSpy = vi.spyOn(data_encryption, "decrypt").mockReturnValue(false);++ expect(totpEncryption.getTotpSecret()).toBeNull();++ decryptSpy.mockRestore();+ });++ it("returns null and logs when decryption throws", () => {+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ cls.init(() => {+ totpEncryption.setTotpSecret(SECRET);+ });+ const decryptSpy = vi.spyOn(data_encryption, "decrypt").mockImplementation(() => {+ throw new Error("boom");+ });++ expect(totpEncryption.getTotpSecret()).toBeNull();+ expect(errorSpy).toHaveBeenCalled();++ decryptSpy.mockRestore();+ errorSpy.mockRestore();+ });++ it("reset clears the secret and verification flips off", () => {+ cls.init(() => {+ totpEncryption.setTotpSecret(SECRET);+ });+ expect(totpEncryption.isTotpSecretSet()).toBe(true);++ cls.init(() => {+ totpEncryption.resetTotpSecret();+ });++ expect(totpEncryption.isTotpSecretSet()).toBe(false);+ expect(totpEncryption.getTotpSecret()).toBeNull();+ expect(totpEncryption.verifyTotpSecret(SECRET)).toBe(false);+ });+});diff --git a/apps/server/src/services/etapi_tokens.spec.ts b/apps/server/src/services/etapi_tokens.spec.tsnew file mode 100644index 0000000000..0b5964719d--- /dev/null+++ b/apps/server/src/services/etapi_tokens.spec.ts@@ -0,0 +1,102 @@+import { cls } from "@triliumnext/core";+import { beforeAll, describe, expect, it } from "vitest";++import etapiTokens from "./etapi_tokens.js";+import sql_init from "./sql_init.js";+import { toBase64 } from "./utils.js";++describe("etapi_tokens", () => {+ beforeAll(async () => {+ sql_init.initializeDb();+ await sql_init.dbReady;+ });++ describe("parseAuthToken", () => {+ it("returns null for missing auth", () => {+ expect(etapiTokens.parseAuthToken(undefined)).toBeNull();+ expect(etapiTokens.parseAuthToken("")).toBeNull();+ });++ it("parses the legacy single-chunk format and the id_token format", () => {+ expect(etapiTokens.parseAuthToken("legacytoken")).toEqual({ token: "legacytoken" });+ expect(etapiTokens.parseAuthToken("abc123_secrettoken")).toEqual({+ etapiTokenId: "abc123",+ token: "secrettoken"+ });+ });++ it("returns null for a malformed three-chunk token", () => {+ expect(etapiTokens.parseAuthToken("a_b_c")).toBeNull();+ });++ it("strips a Bearer prefix", () => {+ expect(etapiTokens.parseAuthToken("Bearer id_tok")).toEqual({+ etapiTokenId: "id",+ token: "tok"+ });+ });++ it("parses Basic auth with the 'etapi' username", () => {+ const basic = "Basic " + toBase64("etapi:id_tok");+ expect(etapiTokens.parseAuthToken(basic)).toEqual({ etapiTokenId: "id", token: "tok" });+ });++ it("rejects Basic auth with the wrong username or wrong chunk count", () => {+ expect(etapiTokens.parseAuthToken("Basic " + toBase64("wrong:tok"))).toBeNull();+ expect(etapiTokens.parseAuthToken("Basic " + toBase64("nocolon"))).toBeNull();+ expect(etapiTokens.parseAuthToken("Basic " + toBase64("a:b:c"))).toBeNull();+ });+ });++ describe("createToken + isValidAuthHeader", () => {+ it("creates a token that validates via its id_token, Bearer and Basic forms", () => {+ const { authToken } = cls.init(() => etapiTokens.createToken("My token"));+ expect(authToken).toContain("_");++ expect(etapiTokens.isValidAuthHeader(authToken)).toBe(true);+ expect(etapiTokens.isValidAuthHeader(`Bearer ${authToken}`)).toBe(true);+ expect(etapiTokens.isValidAuthHeader("Basic " + toBase64(`etapi:${authToken}`))).toBe(true);++ // legacy form (no id) should also match by scanning all tokens+ const legacyToken = authToken.split("_")[1];+ expect(etapiTokens.isValidAuthHeader(legacyToken)).toBe(true);+ });++ it("rejects unparseable, unknown-id, and non-matching tokens", () => {+ expect(etapiTokens.isValidAuthHeader(undefined)).toBe(false);+ expect(etapiTokens.isValidAuthHeader("a_b_c")).toBe(false);+ expect(etapiTokens.isValidAuthHeader("nonexistentid_sometoken")).toBe(false);+ expect(etapiTokens.isValidAuthHeader("unmatchedlegacytoken")).toBe(false);+ });+ });++ describe("rename / delete / get", () => {+ it("renames an existing token and lists it", () => {+ const { authToken } = cls.init(() => etapiTokens.createToken("Before"));+ const etapiTokenId = authToken.split("_")[0];++ cls.init(() => etapiTokens.renameToken(etapiTokenId, "After"));++ const tokens = etapiTokens.getTokens();+ const renamed = tokens.find((t) => t.etapiTokenId === etapiTokenId);+ expect(renamed?.name).toBe("After");+ });++ it("throws when renaming a non-existent token", () => {+ cls.init(() => {+ expect(() => etapiTokens.renameToken("doesNotExist", "x")).toThrow();+ });+ });++ it("deletes a token and treats a repeat delete as a no-op", () => {+ const { authToken } = cls.init(() => etapiTokens.createToken("ToDelete"));+ const etapiTokenId = authToken.split("_")[0];++ cls.init(() => etapiTokens.deleteToken(etapiTokenId));+ expect(etapiTokens.getTokens().some((t) => t.etapiTokenId === etapiTokenId)).toBe(false);++ // deleting again is a no-op (already deleted)+ cls.init(() => expect(() => etapiTokens.deleteToken(etapiTokenId)).not.toThrow());+ });+ });+});diff --git a/apps/server/src/services/export/zip/factory.spec.ts b/apps/server/src/services/export/zip/factory.spec.tsnew file mode 100644index 0000000000..5456a9d505--- /dev/null+++ b/apps/server/src/services/export/zip/factory.spec.ts@@ -0,0 +1,92 @@+import fs from "fs";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++// --- Mocks (hoisted above the module-under-test import) ---++class FakeHtml {+ constructor(public data: any, public opts: any) {}+}+class FakeMarkdown {+ constructor(public data: any) {}+}+class FakeShare {+ constructor(public data: any) {}+}++vi.mock("@triliumnext/core/src/services/export/zip/html.js", () => ({ default: FakeHtml }));+vi.mock("@triliumnext/core/src/services/export/zip/markdown.js", () => ({ default: FakeMarkdown }));+vi.mock("./share_theme.js", () => ({ default: FakeShare }));++const data = { branch: {} } as any;++/**+ * `isDev` in utils.ts is a module-load constant derived from TRILIUM_ENV, so to+ * exercise both readContentCss branches we re-import the factory with modules+ * reset under each env value (the html/markdown/share mocks are re-applied).+ */+async function importFactory(dev: boolean) {+ vi.resetModules();+ vi.doMock("@triliumnext/core/src/services/export/zip/html.js", () => ({ default: FakeHtml }));+ vi.doMock("@triliumnext/core/src/services/export/zip/markdown.js", () => ({ default: FakeMarkdown }));+ vi.doMock("./share_theme.js", () => ({ default: FakeShare }));+ if (dev) {+ vi.stubEnv("TRILIUM_ENV", "dev");+ } else {+ vi.stubEnv("TRILIUM_ENV", "");+ }+ return (await import("./factory.js")).serverZipExportProviderFactory;+}++let readFileSyncSpy: ReturnType<typeof vi.spyOn>;++beforeEach(() => {+ readFileSyncSpy = vi.spyOn(fs, "readFileSync").mockReturnValue("body { color: red; }" as any);+});++afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllEnvs();+});++describe("serverZipExportProviderFactory", () => {+ it("builds an HTML provider, reading content CSS from the resource dir in production", async () => {+ const factory = await importFactory(false);+ const provider = await factory("html", data);++ expect(provider).toBeInstanceOf(FakeHtml);+ expect((provider as any).opts.contentCss).toBe("body { color: red; }");+ // production reads the bundled css next to the resource dir+ const readPath = readFileSyncSpy.mock.calls[0][0] as string;+ expect(readPath).toContain("ckeditor5-content.css");+ expect(readPath).not.toContain("node_modules");+ });++ it("builds an HTML provider, resolving content CSS from the ckeditor5 package in dev mode", async () => {+ const factory = await importFactory(true);+ await factory("html", data);++ const readPath = readFileSyncSpy.mock.calls[0][0] as string;+ expect(readPath).toContain("ckeditor5-content.css");+ expect(readPath).toContain("ckeditor5");+ });++ it("builds a Markdown provider without reading any CSS", async () => {+ const factory = await importFactory(false);+ const provider = await factory("markdown", data);++ expect(provider).toBeInstanceOf(FakeMarkdown);+ expect(readFileSyncSpy).not.toHaveBeenCalled();+ });++ it("builds a Share theme provider", async () => {+ const factory = await importFactory(false);+ const provider = await factory("share", data);++ expect(provider).toBeInstanceOf(FakeShare);+ });++ it("throws on an unsupported format", async () => {+ const factory = await importFactory(false);+ await expect(factory("xml" as any, data)).rejects.toThrow(/Unsupported export format/);+ });+});diff --git a/apps/server/src/services/export/zip/share_theme.spec.ts b/apps/server/src/services/export/zip/share_theme.spec.tsnew file mode 100644index 0000000000..00874d3f49--- /dev/null+++ b/apps/server/src/services/export/zip/share_theme.spec.ts@@ -0,0 +1,370 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++// --- Mocks (hoisted above the module-under-test import) ---++const mockFs = { readFileSync: vi.fn(), readdirSync: vi.fn() };+vi.mock("fs", () => ({+ default: mockFs,+ readFileSync: (...a: any[]) => mockFs.readFileSync(...a),+ readdirSync: (...a: any[]) => mockFs.readdirSync(...a)+}));++vi.mock("ejs", () => ({ default: { render: vi.fn(() => "<html>404</html>") } }));+vi.mock("html-to-text", () => ({ convert: vi.fn((s: string) => `TEXT:${s}`) }));++const mockAssets = {+ getClientDir: vi.fn(() => "/client"),+ getShareThemeAssetDir: vi.fn(() => "/share-assets")+};+vi.mock("../../../routes/assets", () => mockAssets);++const mockContentRenderer = {+ getDefaultTemplatePath: vi.fn((name: string) => `/templates/${name}`),+ readTemplate: vi.fn(() => "TEMPLATE"),+ renderNoteForExport: vi.fn(() => "<p>rendered</p>")+};+vi.mock("../../../share/content_renderer", () => mockContentRenderer);++vi.mock("../../resource_dir", () => ({ RESOURCE_DIR: "/resource" }));++const utils = { getResourceDir: vi.fn(() => "/res"), isDev: false };+vi.mock("../../utils", () => ({+ getResourceDir: () => utils.getResourceDir(),+ get isDev() {+ return utils.isDev;+ }+}));++const mockIconPacks: any[] = [];+const mockBecca = {+ getNote: vi.fn(),+ getAttachment: vi.fn()+};+const mockLog = { error: vi.fn(), info: vi.fn() };++vi.mock("@triliumnext/core", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@triliumnext/core")>();+ return {+ ...actual,+ becca: mockBecca,+ getLog: () => mockLog,+ icon_packs: {+ ...actual.icon_packs,+ getIconPacks: vi.fn(() => mockIconPacks),+ MIME_TO_EXTENSION_MAPPINGS: { "font/woff2": "woff2", "font/ttf": "ttf" }+ }+ };+});++const { default: ShareThemeExportProvider } = await import("./share_theme.js");++// --- Test scaffolding -------------------------------------------------------++interface AppendCall {+ data: any;+ options: { name: string };+}+let appendCalls: AppendCall[];++function makeData(branchNote?: any) {+ const branch = {+ getNote: () => branchNote ?? {+ getContent: () => "<p>root</p>",+ noteId: "rootNote",+ getBestNotePath: () => ["root", "rootNote12345"]+ }+ };+ return {+ branch,+ getNoteTargetUrl: vi.fn((id: string) => `url/${id}`),+ archive: { append: vi.fn((data: any, options: any) => appendCalls.push({ data, options })) },+ zipExportOptions: undefined,+ rewriteFn: vi.fn((content: string) => content)+ } as any;+}++function makeProvider(branchNote?: any) {+ return new ShareThemeExportProvider(makeData(branchNote));+}++beforeEach(() => {+ vi.clearAllMocks();+ appendCalls = [];+ mockIconPacks.length = 0;+ utils.isDev = false;+ mockFs.readFileSync.mockReturnValue(Buffer.from("file-data"));+ mockFs.readdirSync.mockReturnValue(["a.css", "b.js"]);+ mockContentRenderer.renderNoteForExport.mockReturnValue("<p>rendered</p>");+});++afterEach(() => vi.restoreAllMocks());++describe("ShareThemeExportProvider", () => {+ describe("prepareMeta", () => {+ it("registers icon-color.svg, asset-dir files, and an index entry", () => {+ const provider = makeProvider();+ const metaFile: any = { files: [{ noteId: "rootNote", title: "Root" }] };++ provider.prepareMeta(metaFile);++ const dataFileNames = metaFile.files.map((f: any) => f.dataFileName).filter(Boolean);+ expect(dataFileNames).toContain("icon-color.svg");+ expect(dataFileNames).toContain("assets/a.css");+ expect(dataFileNames).toContain("assets/b.js");+ expect(dataFileNames).toContain("index.html");+ // rootMeta is taken from the first existing file entry+ expect((provider as any).rootMeta).toBe(metaFile.files[0]);+ });+ });++ describe("mapExtension", () => {+ it("returns null for images, js for javascript, null for .zip, html otherwise", () => {+ const p = makeProvider();+ expect(p.mapExtension("image", "image/png", "", "share")).toBeNull();+ expect(p.mapExtension("code", "application/javascript", "", "share")).toBe("js");+ expect(p.mapExtension("file", "application/zip", ".zip", "share")).toBeNull();+ expect(p.mapExtension("text", "text/html", "", "share")).toBe("html");+ });+ });++ describe("prepareContent", () => {+ it("throws when the note path is missing", () => {+ const p = makeProvider();+ expect(() => p.prepareContent("t", "x", { notePath: [] } as any, undefined as any, {} as any))+ .toThrow(/note path/i);+ });++ it("returns content unchanged when there is no note (no search index entry)", () => {+ const p = makeProvider();+ const result = p.prepareContent("t", "raw", { notePath: ["root", "a"] } as any, undefined as any, {} as any);+ expect(result).toBe("raw");+ expect((p as any).searchIndex.size).toBe(0);+ });++ it("rewrites attachment links, note links, and builds a search-index entry for a note", () => {+ const note = {+ noteId: "noteABC",+ getBestNotePath: () => ["root", "parent12chars", "noteABC12char"]+ };+ mockBecca.getNote.mockImplementation((id: string) =>+ id === "parent12chars" ? { title: "Parent" } : null);++ // Render output exercises both the attachment and note link rewrites.+ mockContentRenderer.renderNoteForExport.mockReturnValue(+ `<a href="api/attachments/att123456/download">f</a>` ++ `<a href="x./otherNote123">n</a>` ++ `<a href="x./assets/keepme12345">keep</a>`+ );++ const p = makeProvider();+ (p as any).rootMeta = { noteId: "rootNote" };+ const noteMeta: any = {+ notePath: ["root", "parent12chars", "noteABC12char"],+ attachments: [{ attachmentId: "att123456", dataFileName: "files/att.png" }]+ };++ const out = p.prepareContent("Title", "<p>html</p>", noteMeta, note as any, {} as any) as string;++ // Attachment download link rewritten to its data file name.+ expect(out).toContain('href="files/att.png"');+ // Plain note link rewritten to a hash anchor.+ expect(out).toContain('href="#root/otherNote123"');+ // /assets/ links are preserved untouched.+ expect(out).toContain("/assets/keepme12345");++ const entry = (p as any).searchIndex.get("noteABC");+ expect(entry.title).toBe("Title");+ expect(entry.content).toContain("TEXT:");+ // Path built from titles, excluding root and falsy titles.+ expect(entry.path).toBe("Parent");+ });++ it("keeps the original attachment link when the attachment has no data file (or no attachments at all)", () => {+ const note = { noteId: "noAtt", getBestNotePath: () => ["root", "noAtt1234567"] };+ mockBecca.getNote.mockReturnValue(null);+ mockContentRenderer.renderNoteForExport.mockReturnValue(+ `<a href="api/attachments/att999999/download">f</a>`+ );++ const p = makeProvider();+ // attachment present but without a dataFileName → keep original match (line 79 false).+ const withAtt: any = {+ notePath: ["root", "noAtt1234567"],+ attachments: [{ attachmentId: "att999999" }]+ };+ const out1 = p.prepareContent("t", "<p>c</p>", withAtt, note as any, {} as any) as string;+ expect(out1).toContain('href="api/attachments/att999999/download"');++ // no attachments array at all → (noteMeta.attachments || []) fallback (line 78).+ const noAttArr: any = { notePath: ["root", "noAtt1234567"] };+ const out2 = p.prepareContent("t", "<p>c</p>", noAttArr, note as any, {} as any) as string;+ expect(out2).toContain('href="api/attachments/att999999/download"');+ });++ it("rewrites a note link pointing at the root to the base path", () => {+ const note = { noteId: "rootChild", getBestNotePath: () => ["root", "rootNote12345"] };+ mockBecca.getNote.mockReturnValue(null);+ mockContentRenderer.renderNoteForExport.mockReturnValue(`<a href="x./rootNote1234">root</a>`);++ const p = makeProvider();+ (p as any).rootMeta = { noteId: "rootNote1234" };+ const noteMeta: any = { notePath: ["root", "rootNote1234"], attachments: [] };++ const out = p.prepareContent("t", "<p>c</p>", noteMeta, note as any, {} as any) as string;+ // basePath for a 2-element path is "" (root link points to the base).+ expect(out).toContain('href=""');+ });++ it("leaves binary (non-string) content untouched but still indexes the note", () => {+ const note = { noteId: "binNote", getBestNotePath: () => ["root", "binNote12345"] };+ mockBecca.getNote.mockReturnValue(null);+ mockContentRenderer.renderNoteForExport.mockReturnValue(new Uint8Array([1, 2, 3]) as any);++ const p = makeProvider();+ const noteMeta: any = { notePath: ["root", "binNote12345"], attachments: [] };++ const out = p.prepareContent("Bin", new Uint8Array([9]), noteMeta, note as any, {} as any);+ expect(out).toBeInstanceOf(Uint8Array);+ // Binary input means empty search content.+ expect((p as any).searchIndex.get("binNote").content).toBe("");+ });+ });++ describe("afterDone", () => {+ it("writes index, 404, assets, fonts, and the search index json", () => {+ const p = makeProvider();+ (p as any).indexMeta = { dataFileName: "index.html" };+ (p as any).assetsMeta = [{ dataFileName: "icon-color.svg" }, { dataFileName: undefined }];+ (p as any).rootMeta = { noteId: "rootNote" };++ // A builtin icon pack (read from client dir) and a custom one (from becca).+ mockIconPacks.push(+ { prefix: "BX", fontMime: "font/woff2", fontAttachmentId: "boxicons", builtin: true },+ { prefix: "Custom", fontMime: "font/ttf", fontAttachmentId: "customAtt", builtin: false }+ );+ (p as any).iconPacks = mockIconPacks;+ mockBecca.getAttachment.mockReturnValue({ getContent: () => Buffer.from("font") });++ // search index with one valid + one null-id entry+ (p as any).searchIndex.set("n1", { id: "n1", title: "T", content: "c", path: "p" });+ (p as any).searchIndex.set("n2", { id: null, title: "T2", content: "c2", path: "p2" });+ (p as any).getNoteTargetUrl.mockReturnValue("resolved/n1");++ // #saveIndex re-runs prepareContent against rootMeta, so it needs a notePath.+ const rootMeta: any = { noteId: "rootNote", title: "Root", notePath: ["root", "rootNote12345"], attachments: [] };+ p.afterDone(rootMeta);++ const names = appendCalls.map((c) => c.options.name);+ expect(names).toContain("index.html");+ expect(names).toContain("404.html");+ expect(names).toContain("icon-color.svg");+ expect(names).toContain("assets/icon-pack-bx.woff2");+ expect(names).toContain("assets/icon-pack-custom.ttf");+ expect(names).toContain("search-index.json");++ const searchAppend = appendCalls.find((c) => c.options.name === "search-index.json")!;+ const parsed = JSON.parse(searchAppend.data);+ // Only the entry with a non-null id is URL-resolved; both are serialized.+ expect(parsed.find((e: any) => e.id === "resolved/n1")).toBeTruthy();+ });++ it("buffers binary index content and appends string font data as-is", () => {+ const p = makeProvider();+ (p as any).indexMeta = { dataFileName: "index.html" };+ (p as any).assetsMeta = [];+ (p as any).rootMeta = { noteId: "rootNote" };++ // renderNoteForExport returns binary → prepareContent returns binary →+ // #saveIndex takes the Buffer.from(content) branch (line 149 else).+ mockContentRenderer.renderNoteForExport.mockReturnValue(new Uint8Array([1, 2, 3]) as any);++ // A custom icon pack whose font content is a string exercises line 177's string branch.+ mockIconPacks.push({ prefix: "Str", fontMime: "font/ttf", fontAttachmentId: "strAtt", builtin: false });+ (p as any).iconPacks = mockIconPacks;+ mockBecca.getAttachment.mockReturnValue({ getContent: () => "string-font-data" });++ const rootMeta: any = { noteId: "rootNote", title: "Root", notePath: ["root", "rootNote12345"], attachments: [] };+ p.afterDone(rootMeta);++ const index = appendCalls.find((c) => c.options.name === "index.html")!;+ expect(Buffer.isBuffer(index.data)).toBe(true);+ const font = appendCalls.find((c) => c.options.name === "assets/icon-pack-str.ttf")!;+ expect(font.data).toBe("string-font-data");+ });++ it("defaults the index title to an empty string when rootMeta has no title", () => {+ const p = makeProvider();+ (p as any).indexMeta = { dataFileName: "index.html" };+ (p as any).assetsMeta = [];+ (p as any).rootMeta = { noteId: "rootNote" };+ mockContentRenderer.renderNoteForExport.mockReturnValue("<p>x</p>");++ // No `title` → exercises the `?? ""` fallback on line 148.+ const rootMeta: any = { noteId: "rootNote", notePath: ["root", "rootNote12345"], attachments: [] };+ p.afterDone(rootMeta);++ expect(mockContentRenderer.renderNoteForExport).toHaveBeenCalled();+ expect(appendCalls.map((c) => c.options.name)).toContain("index.html");+ });++ it("skips the index when there is no index data file name", () => {+ const p = makeProvider();+ (p as any).indexMeta = null;+ (p as any).assetsMeta = [];+ p.afterDone({ noteId: "rootNote", title: "Root" } as any);++ expect(appendCalls.map((c) => c.options.name)).not.toContain("index.html");+ // 404 + search-index are still written.+ expect(appendCalls.map((c) => c.options.name)).toContain("404.html");+ });++ it("logs an error and skips a font when its data cannot be found", () => {+ const p = makeProvider();+ (p as any).indexMeta = null;+ (p as any).assetsMeta = [];+ mockIconPacks.push({ prefix: "Missing", fontMime: "font/ttf", fontAttachmentId: "gone", builtin: false });+ (p as any).iconPacks = mockIconPacks;+ mockBecca.getAttachment.mockReturnValue(undefined);++ p.afterDone({ noteId: "rootNote", title: "Root" } as any);++ expect(mockLog.error).toHaveBeenCalled();+ expect(appendCalls.map((c) => c.options.name)).not.toContain("assets/icon-pack-missing.ttf");+ });+ });+});++describe("getShareThemeAssets (asset resolution branches)", () => {+ // getShareThemeAssets is private to the module; it is exercised through+ // afterDone's #saveAssets, which calls it for each asset data file name.+ function runSaveAssets(assetNames: string[], dev: boolean) {+ utils.isDev = dev;+ const p = makeProvider();+ (p as any).indexMeta = null;+ (p as any).assetsMeta = assetNames.map((n) => ({ dataFileName: n }));+ (p as any).iconPacks = [];+ p.afterDone({ noteId: "rootNote", title: "Root" } as any);+ // Normalize path separators so assertions are OS-independent.+ return mockFs.readFileSync.mock.calls.map((c) => String(c[0]).split("\\").join("/"));+ }++ it("resolves icon-color.svg from the resource images dir", () => {+ const reads = runSaveAssets(["icon-color.svg"], false);+ expect(reads.some((p) => p.includes("/resource") && p.includes("icon-color.svg"))).toBe(true);+ });++ it("resolves assets/* relative to the share theme asset dir", () => {+ const reads = runSaveAssets(["assets/style.css"], false);+ expect(reads.some((p) => p.includes("/share-assets") && p.includes("style.css"))).toBe(true);+ });++ it("resolves other files from the client dist in dev mode", () => {+ const reads = runSaveAssets(["main.js"], true);+ expect(reads.some((p) => p.includes("client") && p.includes("dist"))).toBe(true);+ });++ it("resolves other files from the public dir in production", () => {+ const reads = runSaveAssets(["main.js"], false);+ expect(reads.some((p) => p.includes("public") && p.includes("main.js"))).toBe(true);+ });+});diff --git a/apps/server/src/services/handlers.spec.ts b/apps/server/src/services/handlers.spec.tsnew file mode 100644index 0000000000..1ad6f65f32--- /dev/null+++ b/apps/server/src/services/handlers.spec.ts@@ -0,0 +1,145 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++// --- Mocks (hoisted above the module-under-test import) ---++type Listener = (data: { entityName: string; entity: any }) => void;+const listeners: Record<string, Listener[]> = {};++const mockEvents = {+ ENTITY_CREATED: "ENTITY_CREATED",+ subscribe: vi.fn((eventType: string, listener: Listener) => {+ (listeners[eventType] ||= []).push(listener);+ }),+ emit: (eventType: string, data: any) => {+ for (const l of listeners[eventType] || []) {+ l(data);+ }+ }+};++const mockLog = { info: vi.fn(), error: vi.fn() };+const mockOptions = { getOptionBool: vi.fn() };+const mockOcrService = {+ getAllSupportedMimeTypes: vi.fn(() => ["image/png", "application/pdf"]),+ processNoteOCR: vi.fn(),+ processAttachmentOCR: vi.fn()+};++vi.mock("@triliumnext/core", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@triliumnext/core")>();+ return {+ ...actual,+ events: mockEvents,+ getLog: () => mockLog,+ options: mockOptions+ };+});++vi.mock("./ocr/ocr_service", () => ({ default: mockOcrService }));++const { registerOcrHandlers } = await import("./handlers.js");++/** Flush queued microtasks so the .then/.catch of autoProcessOCR runs. */+const flush = () => new Promise((resolve) => setImmediate(resolve));++function emitCreated(entityName: string, entity: any) {+ mockEvents.emit("ENTITY_CREATED", { entityName, entity });+}++beforeEach(() => {+ for (const key of Object.keys(listeners)) delete listeners[key];+ vi.clearAllMocks();+ mockOptions.getOptionBool.mockReturnValue(true);+ mockOcrService.getAllSupportedMimeTypes.mockReturnValue(["image/png", "application/pdf"]);+ mockOcrService.processNoteOCR.mockResolvedValue(null);+ mockOcrService.processAttachmentOCR.mockResolvedValue(null);+ registerOcrHandlers();+});++afterEach(() => vi.restoreAllMocks());++describe("registerOcrHandlers", () => {+ it("subscribes to ENTITY_CREATED once", () => {+ expect(mockEvents.subscribe).toHaveBeenCalledWith("ENTITY_CREATED", expect.any(Function));+ });++ describe("file notes", () => {+ it("processes a supported file note and logs success when a result is returned", async () => {+ mockOcrService.processNoteOCR.mockResolvedValue({ text: "ok" });+ emitCreated("notes", { type: "file", mime: "application/pdf", noteId: "n1" });+ await flush();++ expect(mockOcrService.processNoteOCR).toHaveBeenCalledWith("n1");+ expect(mockLog.info).toHaveBeenCalled();+ });++ it("processes but does not log success when the result is falsy", async () => {+ mockOcrService.processNoteOCR.mockResolvedValue(null);+ emitCreated("notes", { type: "file", mime: "application/pdf", noteId: "n2" });+ await flush();++ expect(mockOcrService.processNoteOCR).toHaveBeenCalled();+ expect(mockLog.info).not.toHaveBeenCalled();+ });++ it("logs an error when processing rejects", async () => {+ mockOcrService.processNoteOCR.mockRejectedValue(new Error("boom"));+ emitCreated("notes", { type: "file", mime: "application/pdf", noteId: "n3" });+ await flush();++ expect(mockLog.error).toHaveBeenCalled();+ });++ it("does not process when the option is disabled", () => {+ mockOptions.getOptionBool.mockReturnValue(false);+ emitCreated("notes", { type: "file", mime: "application/pdf", noteId: "n4" });++ expect(mockOcrService.processNoteOCR).not.toHaveBeenCalled();+ });++ it("does not process non-file note types", () => {+ emitCreated("notes", { type: "image", mime: "image/png", noteId: "n5" });++ expect(mockOcrService.processNoteOCR).not.toHaveBeenCalled();+ });++ it("does not process a file note with an unsupported mime", async () => {+ emitCreated("notes", { type: "file", mime: "text/plain", noteId: "n6" });+ await flush();++ expect(mockOcrService.processNoteOCR).not.toHaveBeenCalled();+ expect(mockLog.info).not.toHaveBeenCalled();+ });+ });++ describe("file attachments", () => {+ it("processes a supported file attachment", async () => {+ mockOcrService.processAttachmentOCR.mockResolvedValue({ text: "ok" });+ emitCreated("attachments", { role: "file", mime: "image/png", attachmentId: "a1" });+ await flush();++ expect(mockOcrService.processAttachmentOCR).toHaveBeenCalledWith("a1");+ expect(mockLog.info).toHaveBeenCalled();+ });++ it("ignores non-file attachment roles", () => {+ emitCreated("attachments", { role: "image", mime: "image/png", attachmentId: "a2" });++ expect(mockOcrService.processAttachmentOCR).not.toHaveBeenCalled();+ });++ it("does not process when the option is disabled", () => {+ mockOptions.getOptionBool.mockReturnValue(false);+ emitCreated("attachments", { role: "file", mime: "image/png", attachmentId: "a3" });++ expect(mockOcrService.processAttachmentOCR).not.toHaveBeenCalled();+ });+ });++ it("ignores unrelated entity types", () => {+ emitCreated("branches", { branchId: "b1" });++ expect(mockOcrService.processNoteOCR).not.toHaveBeenCalled();+ expect(mockOcrService.processAttachmentOCR).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/host.spec.ts b/apps/server/src/services/host.spec.tsnew file mode 100644index 0000000000..bdc4faea72--- /dev/null+++ b/apps/server/src/services/host.spec.ts@@ -0,0 +1,46 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++describe("host", () => {+ let originalEnv: NodeJS.ProcessEnv;++ beforeEach(() => {+ originalEnv = { ...process.env };+ delete process.env.TRILIUM_HOST;+ });++ afterEach(() => {+ process.env = originalEnv;+ vi.resetModules();+ vi.doUnmock("./config.js");+ vi.doUnmock("./utils.js");+ });++ async function loadHost(opts: { isElectron: boolean; configHost: string }) {+ vi.resetModules();+ vi.doMock("./utils.js", () => ({ isElectron: opts.isElectron }));+ vi.doMock("./config.js", () => ({ default: { Network: { host: opts.configHost } } }));+ return (await import("./host.js")).default;+ }++ it("prefers TRILIUM_HOST env var when not running under Electron", async () => {+ process.env.TRILIUM_HOST = "env-host";+ expect(await loadHost({ isElectron: false, configHost: "config-host" })).toBe("env-host");+ });++ it("ignores TRILIUM_HOST under Electron and falls back to config host", async () => {+ process.env.TRILIUM_HOST = "env-host";+ expect(await loadHost({ isElectron: true, configHost: "config-host" })).toBe("config-host");+ });++ it("uses the config host when no env var is set", async () => {+ expect(await loadHost({ isElectron: false, configHost: "config-host" })).toBe("config-host");+ });++ it("defaults to loopback under Electron when nothing else is set", async () => {+ expect(await loadHost({ isElectron: true, configHost: "" })).toBe("127.0.0.1");+ });++ it("defaults to all interfaces on the server when nothing else is set", async () => {+ expect(await loadHost({ isElectron: false, configHost: "" })).toBe("0.0.0.0");+ });+});diff --git a/apps/server/src/services/i18n.spec.ts b/apps/server/src/services/i18n.spec.tsindex fba64cdb7b..d0ff3fc4b2 100644--- a/apps/server/src/services/i18n.spec.ts+++ b/apps/server/src/services/i18n.spec.ts@@ -1,9 +1,22 @@import { findDuplicateJsonKeys, LOCALES } from "@triliumnext/commons";+import { dayjs } from "@triliumnext/commons";+import { hidden_subtree, options } from "@triliumnext/core";import { readFileSync } from "fs";+import i18next from "i18next";import { join } from "path";// eslint-disable-next-line @typescript-eslint/no-require-importsconst { languages } = require("tesseract.js");-import { describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";++import {+ changeLanguage,+ getCurrentLocale,+ initializeTranslations,+ ordinal+} from "./i18n.js";+// i18n.ts uses the server-local sql_init wrapper (not core's), so the spy must+// target this same singleton for `isDbInitialized` to be intercepted.+import sqlInit from "./sql_init.js";describe("i18n", () => {it("translations are valid JSON with no duplicate keys", () => {@@ -39,3 +52,82 @@ describe("i18n", () => {}});});++describe("i18n helpers", () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it("ordinal() formats a date as an ordinal day", () => {+ expect(ordinal(dayjs("2024-01-01"))).toBe("1st");+ expect(ordinal(dayjs("2024-01-22"))).toBe("22nd");+ });++ describe("getCurrentLocale()", () => {+ it("returns the locale matching the stored option", () => {+ vi.spyOn(options, "getOptionOrNull").mockReturnValue("en");+ expect(getCurrentLocale().id).toBe("en");+ });++ it("falls back to English when no option is set", () => {+ vi.spyOn(options, "getOptionOrNull").mockReturnValue(null);+ expect(getCurrentLocale().id).toBe("en");+ });++ it("falls back to English when the stored locale is unknown", () => {+ vi.spyOn(options, "getOptionOrNull").mockReturnValue("xx-unknown");+ expect(getCurrentLocale().id).toBe("en");+ });+ });++ describe("initializeTranslations() / getCurrentLanguage()", () => {+ // Stub i18next so the tests exercise only the language-resolution+ // branches, not the real fs-backend file loading (which hangs here).+ function stubI18next() {+ vi.spyOn(i18next, "use").mockReturnValue(i18next);+ return vi.spyOn(i18next, "init").mockResolvedValue((() => "") as never);+ }++ it("uses the DB locale option when the database is initialized", async () => {+ const initSpy = stubI18next();+ vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(true);+ const getOption = vi.spyOn(options, "getOptionOrNull").mockReturnValue("de");++ await initializeTranslations();++ expect(getOption).toHaveBeenCalledWith("locale");+ expect(initSpy).toHaveBeenCalledWith(expect.objectContaining({ lng: "de" }));+ });++ it("falls back to English when the DB is uninitialized", async () => {+ const initSpy = stubI18next();+ vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(false);+ vi.spyOn(console, "info").mockImplementation(() => {});++ await initializeTranslations();++ expect(initSpy).toHaveBeenCalledWith(expect.objectContaining({ lng: "en" }));+ });++ it("falls back to English when the locale option is empty", async () => {+ const initSpy = stubI18next();+ vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(true);+ vi.spyOn(options, "getOptionOrNull").mockReturnValue(null);+ vi.spyOn(console, "info").mockImplementation(() => {});++ await initializeTranslations();++ expect(initSpy).toHaveBeenCalledWith(expect.objectContaining({ lng: "en" }));+ });+ });++ it("changeLanguage() switches i18next and restores hidden subtree names", async () => {+ const changeSpy = vi.spyOn(i18next, "changeLanguage").mockResolvedValue((() => "") as never);+ const subtreeSpy = vi.spyOn(hidden_subtree, "checkHiddenSubtree").mockImplementation(() => {});++ await changeLanguage("en");++ expect(changeSpy).toHaveBeenCalledWith("en");+ expect(subtreeSpy).toHaveBeenCalledWith(true, { restoreNames: true });+ });+});diff --git a/apps/server/src/services/image.spec.ts b/apps/server/src/services/image.spec.tsnew file mode 100644index 0000000000..cf7487db00--- /dev/null+++ b/apps/server/src/services/image.spec.ts@@ -0,0 +1,137 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const mockImageService = {+ saveImage: vi.fn(),+ saveImageToAttachment: vi.fn(),+ updateImage: vi.fn()+};++const mockOptions = {+ getOptionBool: vi.fn()+};++const mockLog = { info: vi.fn(), error: vi.fn() };++vi.mock('@triliumnext/core', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@triliumnext/core')>();+ return {+ ...actual,+ imageService: mockImageService,+ options: mockOptions,+ getLog: () => mockLog+ };+});++const mockOcrService = {+ processNoteOCR: vi.fn().mockResolvedValue(null),+ processAttachmentOCR: vi.fn().mockResolvedValue(null)+};++vi.mock('./ocr/ocr_service.js', () => ({+ default: mockOcrService+}));++let image: typeof import('./image.js').default;++/** Resolves once any pending setImmediate-scheduled callbacks have run. */+function flushImmediate(): Promise<void> {+ return new Promise((resolve) => setImmediate(resolve));+}++beforeEach(async () => {+ vi.clearAllMocks();+ mockOptions.getOptionBool.mockReturnValue(true);+ mockOcrService.processNoteOCR.mockResolvedValue(null);+ mockOcrService.processAttachmentOCR.mockResolvedValue(null);+ ({ default: image } = await import('./image.js'));+});++afterEach(() => {+ vi.restoreAllMocks();+});++const data = new Uint8Array([1, 2, 3]);++describe('server image service', () => {+ describe('saveImage', () => {+ it('delegates to the core service and schedules note OCR', async () => {+ mockImageService.saveImage.mockReturnValue({ noteId: 'note1', branch: {} });++ const result = image.saveImage('parent1', data, 'pic.png', true, false);++ expect(result).toEqual({ noteId: 'note1', branch: {} });+ expect(mockImageService.saveImage).toHaveBeenCalledWith(+ 'parent1', data, 'pic.png', true, false+ );+ await flushImmediate();+ expect(mockOcrService.processNoteOCR).toHaveBeenCalledWith('note1');+ });++ it('does not schedule OCR when auto-processing is disabled', async () => {+ mockOptions.getOptionBool.mockReturnValue(false);+ mockImageService.saveImage.mockReturnValue({ noteId: 'note1' });++ image.saveImage('parent1', data, 'pic.png', true);++ await flushImmediate();+ expect(mockOcrService.processNoteOCR).not.toHaveBeenCalled();+ });++ it('logs when scheduled note OCR fails', async () => {+ mockImageService.saveImage.mockReturnValue({ noteId: 'note1' });+ mockOcrService.processNoteOCR.mockRejectedValue(new Error('ocr fail'));++ image.saveImage('parent1', data, 'pic.png', true);++ await flushImmediate();+ await flushImmediate();+ expect(mockLog.error).toHaveBeenCalledWith(+ expect.stringContaining('Failed to process OCR for note note1')+ );+ });+ });++ describe('saveImageToAttachment', () => {+ it('delegates to the core service and schedules attachment OCR', async () => {+ mockImageService.saveImageToAttachment.mockReturnValue({ attachmentId: 'att1' });++ const result = image.saveImageToAttachment('note1', data, 'pic.png', true, false);++ expect(result).toEqual({ attachmentId: 'att1' });+ await flushImmediate();+ expect(mockOcrService.processAttachmentOCR).toHaveBeenCalledWith('att1');+ });++ it('does not schedule OCR when there is no attachment id', async () => {+ mockImageService.saveImageToAttachment.mockReturnValue({ attachmentId: undefined });++ image.saveImageToAttachment('note1', data, 'pic.png');++ await flushImmediate();+ expect(mockOcrService.processAttachmentOCR).not.toHaveBeenCalled();+ });++ it('logs when scheduled attachment OCR fails', async () => {+ mockImageService.saveImageToAttachment.mockReturnValue({ attachmentId: 'att1' });+ mockOcrService.processAttachmentOCR.mockRejectedValue(new Error('ocr fail'));++ image.saveImageToAttachment('note1', data, 'pic.png', true);++ await flushImmediate();+ await flushImmediate();+ expect(mockLog.error).toHaveBeenCalledWith(+ expect.stringContaining('Failed to process OCR for attachment att1')+ );+ });+ });++ describe('updateImage', () => {+ it('delegates to the core service and schedules note OCR', async () => {+ image.updateImage('note1', data, 'pic.png');++ expect(mockImageService.updateImage).toHaveBeenCalledWith('note1', data, 'pic.png');+ await flushImmediate();+ expect(mockOcrService.processNoteOCR).toHaveBeenCalledWith('note1');+ });+ });+});diff --git a/apps/server/src/services/image_provider.spec.ts b/apps/server/src/services/image_provider.spec.tsnew file mode 100644index 0000000000..b0a3ce41d3--- /dev/null+++ b/apps/server/src/services/image_provider.spec.ts@@ -0,0 +1,181 @@+import { cls, options } from '@triliumnext/core';+import { Jimp } from 'jimp';+import { afterEach, beforeAll, describe, expect, it } from 'vitest';++import { serverImageProvider } from './image_provider.js';++// is-svg / image-type / is-animated / jimp are all loaded by spec/setup.ts (which+// imports serverImageProvider to initialise core), so they cannot be re-mocked+// reliably. Instead we exercise the real implementations end-to-end with real+// image buffers and drive behaviour through the real (in-memory DB) options.++function setOptions(values: Record<string, string>) {+ cls.init(() => {+ for (const [name, value] of Object.entries(values)) {+ options.setOption(name as Parameters<typeof options.setOption>[0], value);+ }+ });+}++// Real, deterministic image buffers built once.+let tallPng: Uint8Array; // 200x600 -> resized by height+let smallPng: Uint8Array; // 8x8 -> within bounds, jpeg ends up larger+let noisyPng: Uint8Array; // large noisy image where jpeg compression helps+let corruptPng: Uint8Array; // valid PNG signature but unreadable by jimp+const svgBuffer = new TextEncoder().encode('<svg xmlns="http://www.w3.org/2000/svg"></svg>');+const garbageBuffer = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);+const staticGif = Uint8Array.from(+ Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', 'base64')+);+const animatedGif = Uint8Array.from(+ Buffer.from(+ 'R0lGODlhAQABAPABAP///wAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQFCgABACwAA' ++ 'AAAAQABAAACAkQBACH5BAUKAAEALAAAAAABAAEAAAICRAEAOw==',+ 'base64'+ )+);++async function makePng(width: number, height: number, noisy = false): Promise<Uint8Array> {+ const image = new Jimp({ width, height, color: 0x3366ccff });+ if (noisy) {+ for (let x = 0; x < width; x++) {+ for (let y = 0; y < height; y++) {+ const r = (x * 31 + y * 17) % 256;+ const g = (x * 13 + y * 7) % 256;+ const b = (x * 5 + y * 23) % 256;+ const color = (((r << 24) | (g << 16) | (b << 8) | 0xff) >>> 0);+ image.setPixelColor(color, x, y);+ }+ }+ }+ return new Uint8Array(await image.getBuffer('image/png'));+}++beforeAll(async () => {+ tallPng = await makePng(200, 600);+ smallPng = await makePng(8, 8);+ noisyPng = await makePng(600, 400, true);+ const valid = await makePng(8, 8);+ corruptPng = new Uint8Array(+ Buffer.concat([Buffer.from(valid.slice(0, 50)), Buffer.alloc(valid.length, 0xab)])+ );+}, 30000);++afterEach(() => {+ setOptions({ compressImages: 'true', imageJpegQuality: '75', imageMaxWidthHeight: '2000' });+});++describe('serverImageProvider.getImageType', () => {+ it('returns the SVG format for SVG buffers', () => {+ expect(serverImageProvider.getImageType(svgBuffer)).toEqual({+ ext: 'svg',+ mime: 'image/svg+xml'+ });+ });++ it('returns null for non-SVG buffers (async detection handled elsewhere)', () => {+ expect(serverImageProvider.getImageType(smallPng)).toBeNull();+ });+});++describe('serverImageProvider.processImage', () => {+ it('returns the original buffer and detected format when compression is disabled', async () => {+ setOptions({ compressImages: 'false' });++ const result = await serverImageProvider.processImage(smallPng, 'a.png', true);++ expect(result.buffer).toBe(smallPng);+ expect(result.format).toEqual({ ext: 'png', mime: 'image/png' });+ });++ it('uses the octet-stream fallback format when the type cannot be detected', async () => {+ setOptions({ compressImages: 'false' });++ const result = await serverImageProvider.processImage(garbageBuffer, 'unknown.bin', true);++ expect(result.format).toEqual({ ext: 'dat', mime: 'application/octet-stream' });+ });++ it('detects SVG content via getImageTypeFromBuffer', async () => {+ setOptions({ compressImages: 'false' });++ const result = await serverImageProvider.processImage(svgBuffer, 'a.svg', false);++ expect(result.format).toEqual({ ext: 'svg', mime: 'image/svg+xml' });+ expect(result.buffer).toBe(svgBuffer);+ });++ it('does not shrink unsupported (non jpg/png) formats even when shrink is requested', async () => {+ const result = await serverImageProvider.processImage(staticGif, 'a.gif', true);++ expect(result.buffer).toBe(staticGif);+ expect(result.format).toEqual({ ext: 'gif', mime: 'image/gif' });+ });++ it('does not shrink animated images', async () => {+ const result = await serverImageProvider.processImage(animatedGif, 'a.gif', true);++ expect(result.buffer).toBe(animatedGif);+ });++ it('does not shrink when shrink is not requested', async () => {+ const result = await serverImageProvider.processImage(smallPng, 'a.png', false);++ expect(result.buffer).toBe(smallPng);+ });++ it('shrinks a wide image by width', async () => {+ setOptions({ imageMaxWidthHeight: '100' });++ const result = await serverImageProvider.processImage(noisyPng, 'wide.png', true);++ // Noisy 600x400 -> resized to width 100, re-encoded as JPEG (smaller).+ expect(result.buffer.byteLength).toBeLessThan(noisyPng.byteLength);+ expect(result.format).toEqual({ ext: 'jpg', mime: 'image/jpeg' });+ });++ it('resizes a tall image by height', async () => {+ setOptions({ imageMaxWidthHeight: '100' });++ // tallPng (200x600) is taller than wide, so the height-resize branch runs.+ const result = await serverImageProvider.processImage(tallPng, 'tall.png', true);++ expect(result.format).toEqual({ ext: 'jpg', mime: 'image/jpeg' });+ expect(result.buffer.byteLength).toBeLessThan(tallPng.byteLength);+ });++ it('keeps the original buffer when shrinking does not reduce the size', async () => {+ setOptions({ imageMaxWidthHeight: '2000' });++ // A small solid-colour PNG re-encodes to a larger JPEG, so the original wins.+ const result = await serverImageProvider.processImage(smallPng, 'small.png', true);++ expect(result.buffer).toBe(smallPng);+ expect(result.format).toEqual({ ext: 'png', mime: 'image/png' });+ });++ it('falls back to the original buffer when resizing throws', async () => {+ setOptions({ imageMaxWidthHeight: '100' });++ // corruptPng passes image-type detection as PNG but Jimp cannot decode it,+ // so resize() throws and shrinkImage() falls back to the original buffer.+ const result = await serverImageProvider.processImage(corruptPng, 'broken.png', true);++ expect(result.buffer).toBe(corruptPng);+ expect(result.format).toEqual({ ext: 'png', mime: 'image/png' });+ });++ it('clamps an out-of-range (too low) JPEG quality to the default', async () => {+ setOptions({ imageMaxWidthHeight: '100', imageJpegQuality: '5' });++ const result = await serverImageProvider.processImage(noisyPng, 'wide.png', true);+ expect(result.format).toEqual({ ext: 'jpg', mime: 'image/jpeg' });+ });++ it('clamps an out-of-range (too high) JPEG quality to the default', async () => {+ setOptions({ imageMaxWidthHeight: '100', imageJpegQuality: '150' });++ const result = await serverImageProvider.processImage(noisyPng, 'wide.png', true);+ expect(result.format).toEqual({ ext: 'jpg', mime: 'image/jpeg' });+ });+});diff --git a/apps/server/src/services/image_provider.ts b/apps/server/src/services/image_provider.tsindex 7f2644d984..d4229ff53a 100644--- a/apps/server/src/services/image_provider.ts+++ b/apps/server/src/services/image_provider.ts@@ -93,16 +93,21 @@ export const serverImageProvider: ImageProvider = {if (!origImageFormat || !["jpg", "png"].includes(origImageFormat.ext)) {shouldShrink = false;+ /* v8 ignore start -- defensive guard: file-type classifies animated PNG as+ "apng" and animated GIF/WebP as non-jpg/png, so they are already excluded+ above, making this branch effectively unreachable. */} else if (isAnimated(Buffer.from(buffer))) {- // Recompression of animated images will make them staticshouldShrink = false;}+ /* v8 ignore stop */let finalBuffer: Uint8Array;let format: ImageFormat;if (compressImages && shouldShrink) {finalBuffer = await shrinkImage(buffer, originalName);+ /* v8 ignore next -- the "jpg" fallback is unreachable: shrinkImage returns+ either a detectable JPEG or the (jpg/png-detectable) original buffer. */format = (await getImageTypeFromBuffer(finalBuffer)) || { ext: "jpg", mime: "image/jpeg" };} else {finalBuffer = buffer;diff --git a/apps/server/src/services/llm/chat_title.spec.ts b/apps/server/src/services/llm/chat_title.spec.tsnew file mode 100644index 0000000000..d46d56de48--- /dev/null+++ b/apps/server/src/services/llm/chat_title.spec.ts@@ -0,0 +1,86 @@+import { t } from "i18next";+import { beforeEach, describe, expect, it, vi } from "vitest";++const { getNoteMock, getProviderMock, generateTitleMock } = vi.hoisted(() => ({+ getNoteMock: vi.fn(),+ getProviderMock: vi.fn(),+ generateTitleMock: vi.fn()+}));++vi.mock("@triliumnext/core", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@triliumnext/core")>();+ return {+ ...actual,+ becca: { ...actual.becca, getNote: getNoteMock },+ getLog: () => ({ info: vi.fn(), error: vi.fn(), warn: vi.fn() })+ };+});++vi.mock("./index.js", () => ({+ getProvider: getProviderMock+}));++import { generateChatTitle } from "./chat_title.js";++/** A note stub that records title assignment + save(). */+function noteStub(title: string) {+ return {+ title,+ save: vi.fn()+ };+}++describe("generateChatTitle", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getProviderMock.mockReturnValue({ generateTitle: generateTitleMock });+ });++ it("renames a note that still has a default 'Chat:' title", async () => {+ // Build a default title dynamically from the translation, not a hardcoded string.+ const note = noteStub(`${t("special_notes.llm_chat_prefix")} 2026-01-01`);+ getNoteMock.mockReturnValue(note);+ generateTitleMock.mockResolvedValue("Tolkien reading order");++ await generateChatTitle("chat1", "How should I read Tolkien?");++ expect(generateTitleMock).toHaveBeenCalledWith("How should I read Tolkien?");+ expect(note.title).toBe("Tolkien reading order");+ expect(note.save).toHaveBeenCalledOnce();+ });++ it("renames a note whose title is the default 'New note' title", async () => {+ const note = noteStub(t("notes.new-note"));+ getNoteMock.mockReturnValue(note);+ generateTitleMock.mockResolvedValue("Generated title");++ await generateChatTitle("chat2", "first message");+ expect(note.title).toBe("Generated title");+ expect(note.save).toHaveBeenCalledOnce();+ });++ it("does nothing when the note no longer exists", async () => {+ getNoteMock.mockReturnValue(null);+ await generateChatTitle("missing", "hello");+ expect(getProviderMock).not.toHaveBeenCalled();+ });++ it("leaves a manually renamed note untouched", async () => {+ const note = noteStub("My carefully chosen title");+ getNoteMock.mockReturnValue(note);++ await generateChatTitle("chat3", "hello");+ expect(getProviderMock).not.toHaveBeenCalled();+ expect(note.save).not.toHaveBeenCalled();+ });++ it("does not rename when the provider returns an empty title", async () => {+ const note = noteStub(t("notes.new-note"));+ getNoteMock.mockReturnValue(note);+ generateTitleMock.mockResolvedValue("");++ await generateChatTitle("chat4", "hello");+ expect(note.title).toBe(t("notes.new-note")); // unchanged+ expect(note.save).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/llm/index.spec.ts b/apps/server/src/services/llm/index.spec.tsnew file mode 100644index 0000000000..650980a7fb--- /dev/null+++ b/apps/server/src/services/llm/index.spec.ts@@ -0,0 +1,162 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const { getOptionOrNullMock, errorMock } = vi.hoisted(() => ({+ getOptionOrNullMock: vi.fn(),+ errorMock: vi.fn()+}));++vi.mock("@triliumnext/core", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@triliumnext/core")>();+ return {+ ...actual,+ options: { ...actual.options, getOptionOrNull: getOptionOrNullMock },+ getLog: () => ({ error: errorMock, info: vi.fn(), warn: vi.fn() })+ };+});++/** Each provider stub records its constructor args and exposes a tagged model list. */+function makeProviderMock(tag: string) {+ return class {+ static lastArgs: unknown[] = [];+ constructor(...args: unknown[]) {+ (this.constructor as any).lastArgs = args;+ }+ getAvailableModels() {+ return [{ id: `${tag}-model`, name: `${tag} Model` }];+ }+ };+}++vi.mock("./providers/anthropic.js", () => ({ AnthropicProvider: makeProviderMock("anthropic") }));+vi.mock("./providers/openai.js", () => ({ OpenAiProvider: makeProviderMock("openai") }));+vi.mock("./providers/google.js", () => ({ GoogleProvider: makeProviderMock("google") }));++import {+ clearProviderCache,+ getAllModels,+ getProvider,+ getProviderByType,+ hasConfiguredProviders+} from "./index.js";++function setProviders(configs: unknown) {+ getOptionOrNullMock.mockReturnValue(typeof configs === "string" ? configs : JSON.stringify(configs));+}++const TWO = [+ { id: "a1", name: "My Claude", provider: "anthropic", apiKey: "k1", baseURL: "https://proxy" },+ { id: "o1", name: "My GPT", provider: "openai", apiKey: "k2" }+];++describe("llm/index provider registry", () => {+ beforeEach(() => {+ clearProviderCache();+ vi.clearAllMocks();+ });+ afterEach(() => {+ clearProviderCache();+ });++ describe("getProvider", () => {+ it("returns the first provider when no id is given and caches it", () => {+ setProviders(TWO);+ const p1 = getProvider();+ const p2 = getProvider();+ expect(p1).toBe(p2); // cached+ expect((p1.constructor as any).lastArgs).toEqual(["k1", "https://proxy"]);+ });++ it("returns the provider matching a given id", () => {+ setProviders(TWO);+ const p = getProvider("o1");+ expect((p.constructor as any).lastArgs).toEqual(["k2", undefined]);+ });++ it("instantiates each known provider type via its factory", () => {+ setProviders([+ { id: "a", name: "A", provider: "anthropic", apiKey: "ka" },+ { id: "o", name: "O", provider: "openai", apiKey: "ko" },+ { id: "g", name: "G", provider: "google", apiKey: "kg" }+ ]);+ expect((getProvider("a").constructor as any).lastArgs).toEqual(["ka", undefined]);+ expect((getProvider("o").constructor as any).lastArgs).toEqual(["ko", undefined]);+ expect((getProvider("g").constructor as any).lastArgs).toEqual(["kg", undefined]);+ });++ it("throws when no providers are configured (null and empty array)", () => {+ getOptionOrNullMock.mockReturnValue(null);+ expect(() => getProvider()).toThrow(/No LLM providers configured/);+ setProviders([]);+ expect(() => getProvider()).toThrow(/No LLM providers configured/);+ });++ it("throws when the requested id is not found", () => {+ setProviders(TWO);+ expect(() => getProvider("nope")).toThrow(/not found: nope/);+ });++ it("throws for an unknown provider type", () => {+ setProviders([{ id: "x", name: "X", provider: "mystery", apiKey: "k" }]);+ expect(() => getProvider("x")).toThrow(/Unknown LLM provider type: mystery/);+ });+ });++ describe("getConfiguredProviders error handling (via hasConfiguredProviders)", () => {+ it("treats malformed JSON as no providers and logs the error", () => {+ getOptionOrNullMock.mockReturnValue("{not json");+ expect(hasConfiguredProviders()).toBe(false);+ expect(errorMock).toHaveBeenCalled();+ });++ it("treats a null option as no providers", () => {+ getOptionOrNullMock.mockReturnValue(null);+ expect(hasConfiguredProviders()).toBe(false);+ });++ it("reports true when providers exist", () => {+ setProviders(TWO);+ expect(hasConfiguredProviders()).toBe(true);+ });+ });++ describe("getProviderByType", () => {+ it("returns the first provider of the given type", () => {+ setProviders(TWO);+ const p = getProviderByType("openai");+ expect((p.constructor as any).lastArgs).toEqual(["k2", undefined]);+ });++ it("throws when no provider of that type is configured", () => {+ setProviders(TWO);+ expect(() => getProviderByType("google")).toThrow(/No google provider configured/);+ });+ });++ describe("getAllModels", () => {+ it("aggregates models across provider types, tagged with the provider", () => {+ setProviders(TWO);+ const models = getAllModels();+ expect(models).toEqual([+ { id: "anthropic-model", name: "anthropic Model", provider: "anthropic" },+ { id: "openai-model", name: "openai Model", provider: "openai" }+ ]);+ });++ it("includes each provider type only once even with duplicate configs", () => {+ setProviders([+ { id: "a1", name: "A1", provider: "anthropic", apiKey: "k1" },+ { id: "a2", name: "A2", provider: "anthropic", apiKey: "k2" }+ ]);+ const models = getAllModels();+ expect(models).toHaveLength(1);+ expect(models[0].provider).toBe("anthropic");+ });++ it("skips and logs a provider whose model lookup throws", () => {+ setProviders([{ id: "x", name: "X", provider: "mystery", apiKey: "k" }]);+ // Unknown type → getProvider throws inside getAllModels and is caught.+ expect(getAllModels()).toEqual([]);+ expect(errorMock).toHaveBeenCalled();+ });+ });+});diff --git a/apps/server/src/services/llm/providers/anthropic.spec.ts b/apps/server/src/services/llm/providers/anthropic.spec.tsindex 9d6a2ab18f..0f4cef3d15 100644--- a/apps/server/src/services/llm/providers/anthropic.spec.ts+++ b/apps/server/src/services/llm/providers/anthropic.spec.ts@@ -2,12 +2,13 @@ import type { LlmMessage } from "@triliumnext/commons";import { beforeEach, describe, expect, it, vi } from "vitest";const createAnthropicMock = vi.fn();+const webSearchMock = vi.fn(() => ({ kind: "anthropic_web_search" }));vi.mock("@ai-sdk/anthropic", () => ({createAnthropic: (opts: unknown) => {createAnthropicMock(opts);const fn: any = () => ({});- fn.tools = { webSearch_20250305: () => ({}) };+ fn.tools = { webSearch_20250305: webSearchMock };return fn;}}));@@ -142,6 +143,54 @@ describe("AnthropicProvider message building", () => {});});+describe("AnthropicProvider tool handling", () => {+ beforeEach(() => {+ streamTextMock.mockClear();+ webSearchMock.mockClear();+ });++ it("registers the Anthropic web search tool with a maxUses cap", () => {+ const provider = new AnthropicProvider("sk-ant-test");+ provider.chat([{ role: "user", content: "hi" }], { enableWebSearch: true });++ expect(webSearchMock).toHaveBeenCalledWith({ maxUses: 5 });+ const opts = streamTextMock.mock.calls[0][0] as any;+ expect(opts.tools.web_search).toEqual({ kind: "anthropic_web_search" });+ expect(opts.toolChoice).toBe("auto");+ expect(opts.stopWhen).toBeDefined();+ });++ it("sets the thinking budget and agentic options on the extended-thinking path with tools", () => {+ const provider = new AnthropicProvider("sk-ant-test");+ provider.chat([{ role: "user", content: "hi" }], {+ enableExtendedThinking: true,+ enableNoteTools: true,+ thinkingBudget: 12000,+ maxTokens: 8096+ });++ const opts = streamTextMock.mock.calls[0][0] as any;+ expect(opts.providerOptions.anthropic.thinking).toEqual({+ type: "enabled",+ budgetTokens: 12000+ });+ // maxOutputTokens is raised to at least thinkingBudget + 4000.+ expect(opts.maxOutputTokens).toBe(16000);+ expect(opts.toolChoice).toBe("auto");+ expect(opts.stopWhen).toBeDefined();+ });++ it("defaults the thinking budget and floors maxOutputTokens when unset", () => {+ const provider = new AnthropicProvider("sk-ant-test");+ provider.chat([{ role: "user", content: "hi" }], { enableExtendedThinking: true });++ const opts = streamTextMock.mock.calls[0][0] as any;+ expect(opts.providerOptions.anthropic.thinking.budgetTokens).toBe(10000);+ // max(8096, 10000 + 4000) = 14000+ expect(opts.maxOutputTokens).toBe(14000);+ });+});+/*** The system prompt carries the ephemeral cache breakpoint, so Anthropic can only* reuse the cached system+tools prefix when that string is byte-stable across turns.diff --git a/apps/server/src/services/llm/providers/base_provider.spec.ts b/apps/server/src/services/llm/providers/base_provider.spec.tsnew file mode 100644index 0000000000..16e379776a--- /dev/null+++ b/apps/server/src/services/llm/providers/base_provider.spec.ts@@ -0,0 +1,447 @@+import type { LlmMessage, LlmMessagePart } from "@triliumnext/commons";+import { encodeUtf8 } from "@triliumnext/core/src/services/utils/binary.js";+import type { LanguageModel } from "ai";+import { beforeEach, describe, expect, it, vi } from "vitest";++import type { LlmProviderConfig, ModelInfo } from "../types.js";++const { streamTextMock, generateTextMock, noteMetaMock, errorLogMock, beccaStub } = vi.hoisted(() => ({+ streamTextMock: vi.fn((..._args: any[]) => ({}) as any),+ generateTextMock: vi.fn(async (..._args: any[]) => ({ text: " Generated Title " })),+ noteMetaMock: vi.fn(() => ({ noteId: "ctx", contentPreview: "PREVIEW" })),+ errorLogMock: vi.fn(),+ // becca is accessed directly during message-part resolution and note-hint+ // building. Stub just these while keeping the rest of core intact.+ beccaStub: {+ getNote: vi.fn((noteId: string) => ({ noteId }) as any),+ getAttachment: vi.fn() as any+ }+}));++vi.mock("ai", async (importOriginal) => {+ const actual = await importOriginal<typeof import("ai")>();+ return { ...actual, streamText: streamTextMock, generateText: generateTextMock };+});++vi.mock("@triliumnext/core", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@triliumnext/core")>();+ return {+ ...actual,+ becca: { ...actual.becca, ...beccaStub },+ getLog: () => ({ ...actual.getLog(), error: errorLogMock })+ };+});++vi.mock("../tools/helpers.js", async (importOriginal) => {+ const actual = await importOriginal<typeof import("../tools/helpers.js")>();+ return { ...actual, getNoteMeta: noteMetaMock };+});++// Deterministic tool set so buildTools is exercised without real registries.+vi.mock("../tools/index.js", () => ({+ allToolRegistries: [{ toToolSet: () => ({ fake_tool: { description: "x" } }) }]+}));++import { BaseProvider, buildModelList, buildModelMessage } from "./base_provider.js";++const TEST_MODELS: Omit<ModelInfo, "costMultiplier">[] = [+ { id: "cheap", name: "Cheap", pricing: { input: 1, output: 2 } },+ { id: "mid", name: "Mid", pricing: { input: 2, output: 4 }, isDefault: true },+ { id: "spendy", name: "Spendy", pricing: { input: 10, output: 30 } }+];++const { models: BUILT_MODELS, pricing: BUILT_PRICING } = buildModelList(TEST_MODELS);++class TestProvider extends BaseProvider {+ name = "test";+ protected defaultModel = "mid";+ protected titleModel = "cheap";+ protected availableModels = BUILT_MODELS;+ protected modelPricing = BUILT_PRICING;++ public createdModelIds: string[] = [];++ protected createModel(modelId: string): LanguageModel {+ this.createdModelIds.push(modelId);+ return { modelId } as unknown as LanguageModel;+ }++ // Expose protected helpers for direct assertions.+ public callBuildSystemPrompt(m: LlmMessage[], c: LlmProviderConfig) {+ return this.buildSystemPrompt(m, c);+ }+ public callApplyNoteHint(m: LlmMessage[], c: LlmProviderConfig) {+ return this.applyNoteHint(m, c);+ }+ public callBuildMessages(m: LlmMessage[]) {+ return this.buildMessages(m);+ }+}++/** Build a stub attachment with the given content/availability. */+function makeAttachment(over: Partial<Record<string, unknown>> = {}) {+ return {+ mime: "image/png",+ title: "att.png",+ isContentAvailable: () => true,+ getContent: () => Buffer.from("BYTES"),+ ...over+ } as any;+}++describe("buildModelList", () => {+ it("derives cost multipliers relative to the default (baseline) model", () => {+ // Baseline = mid: effective = (2 + 3*4)/4 = 3.5+ const byId = Object.fromEntries(BUILT_MODELS.map((m) => [m.id, m]));+ expect(byId.mid.costMultiplier).toBe(1);+ // cheap: (1 + 3*2)/4 = 1.75 → 1.75/3.5 = 0.5+ expect(byId.cheap.costMultiplier).toBe(0.5);+ // spendy: (10 + 3*30)/4 = 25 → 25/3.5 = 7.14 → rounded to 7.1+ expect(byId.spendy.costMultiplier).toBe(7.1);+ });++ it("falls back to the first model as baseline when none is marked default", () => {+ const { models } = buildModelList([+ { id: "a", name: "A", pricing: { input: 2, output: 4 } },+ { id: "b", name: "B", pricing: { input: 4, output: 8 } }+ ]);+ expect(models[0].costMultiplier).toBe(1);+ expect(models[1].costMultiplier).toBe(2);+ });++ it("maps each model id to its pricing", () => {+ expect(BUILT_PRICING).toMatchObject({+ cheap: { input: 1, output: 2 },+ mid: { input: 2, output: 4 },+ spendy: { input: 10, output: 30 }+ });+ });+});++describe("buildModelMessage", () => {+ beforeEach(() => {+ beccaStub.getAttachment.mockReset();+ errorLogMock.mockClear();+ });++ it("passes plain string content straight through", () => {+ expect(buildModelMessage({ role: "user", content: "hi" })).toEqual({ role: "user", content: "hi" });+ expect(buildModelMessage({ role: "assistant", content: "yo" })).toEqual({ role: "assistant", content: "yo" });+ });++ it("resolves an image attachment into an image part", () => {+ beccaStub.getAttachment.mockReturnValue(makeAttachment({ mime: "image/png" }));+ const msg = buildModelMessage({+ role: "user",+ content: [{ type: "image", attachmentId: "a1", mime: "image/png" }]+ });+ expect((msg.content as any[])[0]).toMatchObject({ type: "image", mediaType: "image/png" });+ });++ it("falls back to the attachment mime when the image part omits it", () => {+ beccaStub.getAttachment.mockReturnValue(makeAttachment({ mime: "image/jpeg" }));+ const msg = buildModelMessage({+ role: "user",+ content: [{ type: "image", attachmentId: "a1" } as unknown as LlmMessagePart]+ });+ expect((msg.content as any[])[0]).toMatchObject({ type: "image", mediaType: "image/jpeg" });+ });++ it("inlines an SVG image as labelled text, falling back to image.svg when untitled", () => {+ beccaStub.getAttachment.mockReturnValue(makeAttachment({+ mime: "image/svg+xml",+ title: "",+ getContent: () => encodeUtf8("<svg/>")+ }));+ const msg = buildModelMessage({+ role: "user",+ // part.mime omitted → falls back to the attachment's svg mime.+ content: [{ type: "image", attachmentId: "svg1" } as unknown as LlmMessagePart]+ });+ const part = (msg.content as any[])[0];+ expect(part.type).toBe("text");+ expect(part.text).toContain("<file name=\"image.svg\">");+ expect(part.text).toContain("<svg/>");+ });++ it("resolves a file attachment, using part overrides for mime and filename", () => {+ beccaStub.getAttachment.mockReturnValue(makeAttachment({ mime: "application/octet-stream", title: "fallback" }));+ const msg = buildModelMessage({+ role: "user",+ content: [{ type: "file", attachmentId: "f1", mime: "application/pdf", filename: "doc.pdf" }]+ });+ expect((msg.content as any[])[0]).toMatchObject({+ type: "file",+ mediaType: "application/pdf",+ filename: "doc.pdf"+ });+ });++ it("falls back to the attachment's own mime/title for a file part without overrides", () => {+ beccaStub.getAttachment.mockReturnValue(makeAttachment({ mime: "application/pdf", title: "report.pdf" }));+ const msg = buildModelMessage({+ role: "user",+ content: [{ type: "file", attachmentId: "f2" } as unknown as LlmMessagePart]+ });+ expect((msg.content as any[])[0]).toMatchObject({+ type: "file",+ mediaType: "application/pdf",+ filename: "report.pdf"+ });+ });++ it("decodes a text_attachment into a labelled text block", () => {+ beccaStub.getAttachment.mockReturnValue(makeAttachment({+ getContent: () => encodeUtf8("file body"),+ title: "notes.md"+ }));+ const msg = buildModelMessage({+ role: "user",+ content: [{ type: "text_attachment", attachmentId: "t1", filename: "custom.md" }]+ });+ const part = (msg.content as any[])[0];+ expect(part.type).toBe("text");+ expect(part.text).toBe("<file name=\"custom.md\">\nfile body\n</file>");+ });++ it("uses the attachment title as the text_attachment filename when the part omits it", () => {+ beccaStub.getAttachment.mockReturnValue(makeAttachment({+ getContent: () => encodeUtf8("body"),+ title: "fallback.txt"+ }));+ const msg = buildModelMessage({+ role: "user",+ content: [{ type: "text_attachment", attachmentId: "t2" } as unknown as LlmMessagePart]+ });+ expect((msg.content as any[])[0].text).toContain("<file name=\"fallback.txt\">");+ });++ it("drops a part when its attachment is missing and logs an error", () => {+ beccaStub.getAttachment.mockReturnValue(null);+ const msg = buildModelMessage({+ role: "user",+ content: [{ type: "image", attachmentId: "gone", mime: "image/png" }]+ });+ expect(msg.content).toEqual([]);+ expect(errorLogMock).toHaveBeenCalledWith(expect.stringContaining("missing attachment gone"));+ });++ it("drops a protected attachment that is not content-available", () => {+ beccaStub.getAttachment.mockReturnValue(makeAttachment({ isContentAvailable: () => false }));+ const msg = buildModelMessage({+ role: "user",+ content: [{ type: "file", attachmentId: "locked", mime: "application/pdf", filename: "x.pdf" }]+ });+ expect(msg.content).toEqual([]);+ expect(errorLogMock).toHaveBeenCalledWith(expect.stringContaining("protected attachment locked"));+ });++ it("drops a part whose resolution throws and logs the failure", () => {+ beccaStub.getAttachment.mockImplementation(() => { throw new Error("blob corrupt"); });+ const msg = buildModelMessage({+ role: "user",+ content: [+ { type: "text", text: "still here" },+ { type: "image", attachmentId: "bad", mime: "image/png" }+ ]+ });+ expect(msg.content).toEqual([{ type: "text", text: "still here" }]);+ expect(errorLogMock).toHaveBeenCalledWith(expect.stringContaining("Failed to resolve message part"));+ });++ it("strips non-text parts from assistant turns", () => {+ beccaStub.getAttachment.mockReturnValue(makeAttachment());+ const msg = buildModelMessage({+ role: "assistant",+ content: [+ { type: "text", text: "thinking" },+ { type: "image", attachmentId: "a", mime: "image/png" }+ ]+ });+ expect(msg).toEqual({ role: "assistant", content: [{ type: "text", text: "thinking" }] });+ });+});++describe("BaseProvider system prompt", () => {+ const provider = new TestProvider();++ it("uses config.systemPrompt over the message system prompt and emits the no-note-access notice", () => {+ const prompt = provider.callBuildSystemPrompt(+ [{ role: "system", content: "FROM MESSAGE" }],+ { systemPrompt: "FROM CONFIG" }+ )!;+ expect(prompt).toContain("FROM CONFIG");+ expect(prompt).not.toContain("FROM MESSAGE");+ expect(prompt).toContain("do not have access to the user's notes");+ });++ it("falls back to the system message content when no config prompt is set", () => {+ const prompt = provider.callBuildSystemPrompt([{ role: "system", content: "FROM MESSAGE" }], {})!;+ expect(prompt).toContain("FROM MESSAGE");+ });++ it("includes the note-tools guidance when note tools are enabled", () => {+ const prompt = provider.callBuildSystemPrompt([], { enableNoteTools: true, enableWebSearch: true })!;+ expect(prompt).toContain("load_skill");+ expect(prompt).toContain("wiki-link format [[noteId]]");+ // Parallel tool-call hint appears when any tool capability is on.+ expect(prompt).toContain("issue the tool calls in parallel");+ // Web search enabled → no "web search is disabled" notice.+ expect(prompt).not.toContain("do not have access to web search");+ });++ it("emits the context-note-only notice when a context note is set but note tools are off", () => {+ const prompt = provider.callBuildSystemPrompt([], { contextNoteId: "ctx" })!;+ expect(prompt).toContain("cannot search or access other notes");+ expect(prompt).toContain("do not have access to web search");+ });++ it("always appends the markdown formatting hints", () => {+ const prompt = provider.callBuildSystemPrompt([], {})!;+ expect(prompt).toContain("Admonitions");+ expect(prompt).toContain("Mermaid diagrams");+ });+});++describe("BaseProvider applyNoteHint", () => {+ const provider = new TestProvider();++ beforeEach(() => {+ beccaStub.getNote.mockReset().mockImplementation((noteId: string) => ({ noteId }) as any);+ noteMetaMock.mockReset().mockReturnValue({ noteId: "ctx", contentPreview: "PREVIEW" });+ });++ it("returns messages unchanged when there is no context note", () => {+ const messages: LlmMessage[] = [{ role: "user", content: "hi" }];+ expect(provider.callApplyNoteHint(messages, {})).toBe(messages);+ });++ it("returns messages unchanged when there is no user message", () => {+ const messages: LlmMessage[] = [{ role: "assistant", content: "hi" }];+ expect(provider.callApplyNoteHint(messages, { contextNoteId: "ctx" })).toBe(messages);+ });++ it("returns messages unchanged when the context note no longer exists", () => {+ beccaStub.getNote.mockReturnValue(null);+ const messages: LlmMessage[] = [{ role: "user", content: "hi" }];+ expect(provider.callApplyNoteHint(messages, { contextNoteId: "missing" })).toBe(messages);+ });++ it("prepends the note hint to the last user string message", () => {+ const out = provider.callApplyNoteHint(+ [+ { role: "user", content: "first" },+ { role: "assistant", content: "ok" },+ { role: "user", content: "second" }+ ],+ { contextNoteId: "ctx" }+ );+ expect(out[0].content).toBe("first");+ expect(out[2].content).toContain("PREVIEW");+ expect(out[2].content).toContain("second");+ });++ it("prepends the note hint as a leading text part for multimodal content (attachments noted)", () => {+ beccaStub.getAttachment?.mockReturnValue?.(makeAttachment());+ const out = provider.callApplyNoteHint(+ [+ {+ role: "user",+ content: [+ { type: "text", text: "look" },+ { type: "image", attachmentId: "a", mime: "image/png" }+ ]+ }+ ],+ { contextNoteId: "ctx" }+ );+ const content = out[0].content as LlmMessagePart[];+ expect(content[0]).toMatchObject({ type: "text" });+ expect((content[0] as any).text).toContain("PREVIEW");+ // hasAttachments true → the note hint mentions the attached files.+ expect((content[0] as any).text).toContain("attached files");+ // Original parts are preserved after the hint.+ expect(content[1]).toMatchObject({ type: "text", text: "look" });+ });+});++describe("BaseProvider chat / pricing / models / title", () => {+ beforeEach(() => {+ streamTextMock.mockClear();+ generateTextMock.mockClear();+ beccaStub.getNote.mockReset().mockImplementation((noteId: string) => ({ noteId }) as any);+ });++ it("omits tool options when no tools are enabled", () => {+ const provider = new TestProvider();+ provider.chat([{ role: "user", content: "hi" }], {});+ const opts = streamTextMock.mock.calls[0][0] as any;+ expect(opts.tools).toBeUndefined();+ expect(opts.toolChoice).toBeUndefined();+ expect(opts.stopWhen).toBeUndefined();+ // Default max tokens applied when none configured.+ expect(opts.maxOutputTokens).toBe(8096);+ // onError is silenced (no-op) rather than left to the SDK's stdout dump.+ expect(typeof opts.onError).toBe("function");+ expect(opts.onError(new Error("x"))).toBeUndefined();+ });++ it("invokes the no-op base addWebSearchTool when web search is enabled (adds nothing)", () => {+ const provider = new TestProvider();+ // Base addWebSearchTool is a no-op, so the tool set stays empty and no+ // agentic options are attached.+ provider.chat([{ role: "user", content: "hi" }], { enableWebSearch: true });+ const opts = streamTextMock.mock.calls[0][0] as any;+ expect(opts.tools).toBeUndefined();+ expect(opts.toolChoice).toBeUndefined();+ });++ it("attaches tools, stopWhen and toolChoice when note tools are enabled and honours maxTokens", () => {+ const provider = new TestProvider();+ provider.chat([{ role: "user", content: "hi" }], { enableNoteTools: true, maxTokens: 1234 });+ const opts = streamTextMock.mock.calls[0][0] as any;+ expect(opts.tools).toHaveProperty("fake_tool");+ expect(opts.toolChoice).toBe("auto");+ expect(opts.stopWhen).toBeDefined();+ expect(opts.maxOutputTokens).toBe(1234);+ });++ it("creates the model from config.model, falling back to the default", () => {+ const provider = new TestProvider();+ provider.chat([{ role: "user", content: "hi" }], {});+ expect(provider.createdModelIds).toContain("mid");++ const provider2 = new TestProvider();+ provider2.chat([{ role: "user", content: "hi" }], { model: "spendy" });+ expect(provider2.createdModelIds).toContain("spendy");+ });++ it("getModelPricing returns known pricing and undefined for unknown models", () => {+ const provider = new TestProvider();+ expect(provider.getModelPricing("mid")).toEqual({ input: 2, output: 4 });+ expect(provider.getModelPricing("nope")).toBeUndefined();+ });++ it("getAvailableModels returns the configured model list", () => {+ const provider = new TestProvider();+ expect(provider.getAvailableModels().map((m) => m.id)).toEqual(["cheap", "mid", "spendy"]);+ });++ it("generateTitle uses the title model and trims the result", async () => {+ const provider = new TestProvider();+ const title = await provider.generateTitle("Some long first message");+ expect(title).toBe("Generated Title");+ expect(provider.createdModelIds).toContain("cheap");+ const args = generateTextMock.mock.calls[0][0] as any;+ expect(args.maxOutputTokens).toBe(30);+ expect(args.messages[0].content).toContain("Some long first message");+ });+});++describe("BaseProvider default buildSystemMessage", () => {+ it("returns the system prompt unchanged (no provider-specific wrapping)", () => {+ const provider = new TestProvider() as any;+ expect(provider.buildSystemMessage("PLAIN")).toBe("PLAIN");+ expect(provider.buildSystemMessage(undefined)).toBeUndefined();+ });+});diff --git a/apps/server/src/services/llm/providers/base_provider.ts b/apps/server/src/services/llm/providers/base_provider.tsindex bf684a6426..09840fe46d 100644--- a/apps/server/src/services/llm/providers/base_provider.ts+++ b/apps/server/src/services/llm/providers/base_provider.ts@@ -251,6 +251,9 @@ export abstract class BaseProvider implements LlmProvider {+ `**Task lists** — use \`- [ ]\` for unchecked and \`- [x]\` for checked items.`);+ // The markdown formatting hints above are pushed unconditionally, so+ // `parts` is never empty — the `: undefined` arm is unreachable defence.+ /* v8 ignore next */return parts.length > 0 ? parts.join("\n\n") : undefined;}diff --git a/apps/server/src/services/llm/providers/google.spec.ts b/apps/server/src/services/llm/providers/google.spec.tsindex afdf8542cc..6eb6027941 100644--- a/apps/server/src/services/llm/providers/google.spec.ts+++ b/apps/server/src/services/llm/providers/google.spec.ts@@ -2,12 +2,13 @@ import type { LlmMessage } from "@triliumnext/commons";import { beforeEach, describe, expect, it, vi } from "vitest";const createGoogleMock = vi.fn();+const googleSearchMock = vi.fn(() => ({ kind: "google_search" }));vi.mock("@ai-sdk/google", () => ({createGoogleGenerativeAI: (opts: unknown) => {createGoogleMock(opts);const fn: any = () => ({});- fn.tools = { googleSearch: () => ({}) };+ fn.tools = { googleSearch: googleSearchMock };return fn;}}));@@ -114,5 +115,57 @@ describe("GoogleProvider message building", () => {expect(opts.messages.every((m: any) => m.role !== "system")).toBe(true);expect(typeof opts.system).toBe("string");expect(opts.system).toContain("BASE PROMPT");+ // Extended thinking forwards Gemini's thinkingConfig.+ expect(opts.providerOptions.google.thinkingConfig.thinkingBudget).toBe(10000);+ });+});++describe("GoogleProvider tool handling", () => {+ beforeEach(() => {+ streamTextMock.mockClear();+ googleSearchMock.mockClear();+ });++ it("adds the googleSearch tool when only web search is enabled", () => {+ const provider = new GoogleProvider("test-key");+ provider.chat([{ role: "user", content: "hi" }], { enableWebSearch: true });++ expect(googleSearchMock).toHaveBeenCalledOnce();+ const opts = streamTextMock.mock.calls[0][0] as any;+ expect(opts.tools.google_search).toEqual({ kind: "google_search" });+ expect(opts.toolChoice).toBe("auto");+ });++ it("drops googleSearch and warns the model when note tools and web search are both enabled", () => {+ const provider = new GoogleProvider("test-key");+ provider.chat([{ role: "user", content: "hi" }], {+ enableWebSearch: true,+ enableNoteTools: true+ });++ // The conflict path strips google_search but keeps the function tools.+ expect(googleSearchMock).not.toHaveBeenCalled();+ const opts = streamTextMock.mock.calls[0][0] as any;+ expect(opts.tools.google_search).toBeUndefined();+ expect(Object.keys(opts.tools).length).toBeGreaterThan(0);+ // The system prompt gains the conflict explanation.+ expect(opts.system).toContain("web search is unavailable in this turn");+ });++ it("forwards thinkingBudget override under extended thinking with tools enabled", () => {+ const provider = new GoogleProvider("test-key");+ provider.chat([{ role: "user", content: "hi" }], {+ enableExtendedThinking: true,+ enableNoteTools: true,+ thinkingBudget: 25000,+ maxTokens: 5000+ });++ const opts = streamTextMock.mock.calls[0][0] as any;+ expect(opts.providerOptions.google.thinkingConfig.thinkingBudget).toBe(25000);+ expect(opts.maxOutputTokens).toBe(5000);+ // Function tools present → agentic loop options set on the thinking path.+ expect(opts.toolChoice).toBe("auto");+ expect(opts.stopWhen).toBeDefined();});});diff --git a/apps/server/src/services/llm/providers/openai.spec.ts b/apps/server/src/services/llm/providers/openai.spec.tsindex 3a56467493..9161163d47 100644--- a/apps/server/src/services/llm/providers/openai.spec.ts+++ b/apps/server/src/services/llm/providers/openai.spec.ts@@ -1,16 +1,27 @@import { describe, expect, it, vi, beforeEach } from "vitest";const createOpenAIMock = vi.fn();+const webSearchMock = vi.fn(() => ({ kind: "web_search" }));+const modelMock = vi.fn((modelId: string) => ({ modelId }));vi.mock("@ai-sdk/openai", () => ({createOpenAI: (opts: unknown) => {createOpenAIMock(opts);- const fn: any = () => ({});- fn.tools = { webSearch: () => ({}) };+ const fn: any = (modelId: string) => modelMock(modelId);+ fn.tools = { webSearch: webSearchMock };return fn;}}));+const { streamTextMock } = vi.hoisted(() => ({+ streamTextMock: vi.fn((..._args: any[]) => ({}) as any)+}));++vi.mock("ai", async (importOriginal) => {+ const actual = await importOriginal<typeof import("ai")>();+ return { ...actual, streamText: streamTextMock };+});+import { OpenAiProvider } from "./openai.js";describe("OpenAiProvider construction", () => {@@ -41,3 +52,32 @@ describe("OpenAiProvider construction", () => {expect(() => new OpenAiProvider("")).toThrow(/API key is required/);});});++describe("OpenAiProvider chat", () => {+ beforeEach(() => {+ streamTextMock.mockClear();+ webSearchMock.mockClear();+ modelMock.mockClear();+ });++ it("createModel uses the configured model id, falling back to the default", () => {+ const provider = new OpenAiProvider("sk-test");+ provider.chat([{ role: "user", content: "hi" }], {});+ expect(modelMock).toHaveBeenLastCalledWith("gpt-4.1");++ provider.chat([{ role: "user", content: "hi" }], { model: "o3" });+ expect(modelMock).toHaveBeenLastCalledWith("o3");+ });++ it("adds the OpenAI web_search tool when web search is enabled", () => {+ const provider = new OpenAiProvider("sk-test");+ provider.chat([{ role: "user", content: "hi" }], { enableWebSearch: true });++ expect(webSearchMock).toHaveBeenCalledOnce();+ const opts = streamTextMock.mock.calls[0][0] as any;+ expect(opts.tools.web_search).toEqual({ kind: "web_search" });+ // Tools present → agentic loop options are set.+ expect(opts.toolChoice).toBe("auto");+ expect(opts.stopWhen).toBeDefined();+ });+});diff --git a/apps/server/src/services/llm/skills/index.spec.ts b/apps/server/src/services/llm/skills/index.spec.tsnew file mode 100644index 0000000000..6edd17012a--- /dev/null+++ b/apps/server/src/services/llm/skills/index.spec.ts@@ -0,0 +1,40 @@+import { describe, expect, it } from "vitest";++import type { ToolDefinition } from "../tools/tool_registry.js";+import { getSkillsSummary, skillTools } from "./index.js";++function loadSkillTool(): ToolDefinition {+ for (const [name, def] of skillTools) {+ if (name === "load_skill") return def;+ }+ throw new Error("load_skill tool not registered");+}++describe("llm skills", () => {+ it("getSkillsSummary lists each skill name inline (no bullets)", () => {+ const summary = getSkillsSummary();+ // Inline prose, not a bulleted catalog (bullets confuse some models).+ expect(summary).not.toContain("\n");+ expect(summary).toContain('"search_syntax"');+ expect(summary).toContain('"backend_scripting"');+ expect(summary).toContain('"frontend_scripting"');+ });++ describe("load_skill tool", () => {+ it("loads the markdown content of a known skill", () => {+ const result = loadSkillTool().execute({ name: "search_syntax" }) as {+ skill: string;+ instructions: string;+ };+ expect(result.skill).toBe("search_syntax");+ expect(typeof result.instructions).toBe("string");+ expect(result.instructions.length).toBeGreaterThan(0);+ });++ it("returns an error listing available skills for an unknown name", () => {+ const result = loadSkillTool().execute({ name: "no_such_skill" }) as { error: string };+ expect(result.error).toContain("Unknown skill: 'no_such_skill'");+ expect(result.error).toContain("search_syntax");+ });+ });+});diff --git a/apps/server/src/services/llm/stream.spec.ts b/apps/server/src/services/llm/stream.spec.tsindex a8fa3b2849..cc7e3302fb 100644--- a/apps/server/src/services/llm/stream.spec.ts+++ b/apps/server/src/services/llm/stream.spec.ts@@ -2,8 +2,8 @@ import type { LlmStreamChunk } from "@triliumnext/commons";import { APICallError } from "ai";import { describe, expect, it } from "vitest";-import { describeStreamError, streamToChunks } from "./stream.js";-import type { StreamResult } from "./types.js";+import { describeStreamError, type StreamOptions, streamToChunks } from "./stream.js";+import type { ModelPricing, StreamResult } from "./types.js";type ErrorChunk = Extract<LlmStreamChunk, { type: "error" }>;@@ -20,14 +20,18 @@ function fakeResult(parts: unknown[], totalUsage: Promise<unknown>): StreamResul}/** Drain streamToChunks into an array. */-async function collect(result: StreamResult): Promise<LlmStreamChunk[]> {+async function collect(result: StreamResult, options?: StreamOptions): Promise<LlmStreamChunk[]> {const chunks: LlmStreamChunk[] = [];- for await (const chunk of streamToChunks(result)) {+ for await (const chunk of streamToChunks(result, options)) {chunks.push(chunk);}return chunks;}+type UsageChunk = Extract<LlmStreamChunk, { type: "usage" }>;+const usageOf = (chunks: LlmStreamChunk[]) =>+ chunks.find((c): c is UsageChunk => c.type === "usage")!;+/** A representative provider failure: a 404 against a misconfigured base URL. */function apiCallError(): APICallError {return new APICallError({@@ -153,6 +157,147 @@ describe("streamToChunks", () => {]);});+ it("maps reasoning-delta parts to thinking chunks", async () => {+ const chunks = await collect(fakeResult(+ [+ { type: "reasoning-delta", text: "let me think" },+ { type: "text-delta", text: "answer" }+ ],+ Promise.resolve({ inputTokens: 1, outputTokens: 1 })+ ));++ expect(chunks).toContainEqual({ type: "thinking", content: "let me think" });+ expect(chunks).toContainEqual({ type: "text", content: "answer" });+ });++ it("flags tool results whose output object carries an error and stringifies object output", async () => {+ const chunks = await collect(fakeResult(+ [+ { type: "tool-result", toolCallId: "ok", toolName: "search_notes", output: { hits: 2 } },+ { type: "tool-result", toolCallId: "bad", toolName: "search_notes", output: { error: "boom" } }+ ],+ Promise.resolve({ inputTokens: 1, outputTokens: 1 })+ ));++ const results = chunks.filter((c) => c.type === "tool_result") as Extract<LlmStreamChunk, { type: "tool_result" }>[];+ expect(results[0]).toMatchObject({ result: JSON.stringify({ hits: 2 }), isError: false });+ expect(results[1]).toMatchObject({ result: JSON.stringify({ error: "boom" }), isError: true });+ });++ it("emits citations only for url sources and ignores other source types", async () => {+ const chunks = await collect(fakeResult(+ [+ { type: "source", sourceType: "url", url: "https://a.test", title: "A" },+ { type: "source", sourceType: "document", id: "doc1" }+ ],+ Promise.resolve({ inputTokens: 1, outputTokens: 1 })+ ));++ const citations = chunks.filter((c) => c.type === "citation");+ expect(citations).toEqual([+ { type: "citation", citation: { url: "https://a.test", title: "A" } }+ ]);+ });++ it("emits the error chunk from the outer catch when the stream itself throws", async () => {+ const result = {+ fullStream: (async function* () {+ yield { type: "text-delta", text: "partial" };+ throw new TypeError("stream blew up");+ })(),+ totalUsage: Promise.resolve({ inputTokens: 0, outputTokens: 0 })+ } as unknown as StreamResult;++ const chunks = await collect(result);+ expect(chunks).toContainEqual({ type: "text", content: "partial" });+ expect(errorsOf(chunks)).toEqual([{ type: "error", error: "TypeError: stream blew up" }]);+ expect(chunks.some((c) => c.type === "done")).toBe(false);+ });++ it("does not double-report when the stream throws after an error part was already emitted", async () => {+ const result = {+ fullStream: (async function* () {+ yield { type: "error", error: new Error("first failure") };+ throw new TypeError("secondary explosion");+ })(),+ totalUsage: Promise.resolve({ inputTokens: 0, outputTokens: 0 })+ } as unknown as StreamResult;++ const chunks = await collect(result);+ // errorEmitted is already true, so the outer catch swallows the throw.+ const errors = errorsOf(chunks);+ expect(errors).toHaveLength(1);+ expect(errors[0].error).toContain("first failure");+ });++ it("computes cost from cache read/write token detail tiers", async () => {+ const pricing: ModelPricing = { input: 4, output: 8 };+ const chunks = await collect(fakeResult(+ [],+ Promise.resolve({+ inputTokens: 1_000_000,+ outputTokens: 1_000_000,+ inputTokenDetails: {+ cacheReadTokens: 200_000,+ cacheWriteTokens: 100_000,+ noCacheTokens: 700_000+ }+ })+ ), { model: "m", pricing });++ // 0.7*4 (no-cache) + 0.2*4*0.1 (read) + 0.1*4*1.25 (write) + 1*8 (output)+ const expected = 0.7 * 4 + 0.2 * 4 * 0.1 + 0.1 * 4 * 1.25 + 1 * 8;+ const usage = usageOf(chunks);+ expect(usage.usage.cost).toBeCloseTo(expected, 6);+ expect(usage.usage.model).toBe("m");+ });++ it("falls back to cachedInputTokens and derives no-cache input when details are absent", async () => {+ const pricing: ModelPricing = { input: 2, output: 6 };+ const chunks = await collect(fakeResult(+ [],+ Promise.resolve({+ inputTokens: 1_000_000,+ outputTokens: 0,+ cachedInputTokens: 400_000+ })+ ), { pricing });++ // noCache = max(0, 1_000_000 - 400_000 - 0) = 600_000+ // 0.6*2 + 0.4*2*0.1 (read) + 0 (write) + 0 (output)+ const expected = 0.6 * 2 + 0.4 * 2 * 0.1;+ expect(usageOf(chunks).usage.cost).toBeCloseTo(expected, 6);+ });++ it("derives no-cache tokens via Math.max when details lack noCacheTokens and there is no cache read", async () => {+ const pricing: ModelPricing = { input: 3, output: 5 };+ const chunks = await collect(fakeResult(+ [],+ Promise.resolve({+ inputTokens: 1_000_000,+ outputTokens: 0,+ // details present but only carries a write count; no read, no noCache.+ inputTokenDetails: { cacheWriteTokens: 250_000 }+ })+ ), { pricing });++ // cacheRead = 0 (details.cacheReadTokens ?? cachedInputTokens ?? 0)+ // noCache = max(0, 1_000_000 - 0 - 250_000) = 750_000+ const expected = 0.75 * 3 + 0.25 * 3 * 1.25;+ expect(usageOf(chunks).usage.cost).toBeCloseTo(expected, 6);+ });++ it("does not emit usage when token counts are not numbers", async () => {+ const chunks = await collect(fakeResult(+ [{ type: "text-delta", text: "hi" }],+ Promise.resolve({ inputTokens: undefined, outputTokens: undefined })+ ));++ expect(chunks.some((c) => c.type === "usage")).toBe(false);+ // Stream still completes cleanly.+ expect(chunks[chunks.length - 1]).toEqual({ type: "done" });+ });+it("interleaves input deltas for parallel tool calls and forwards distinct ids", async () => {// Two parallel tool calls with the same name; without per-call ids the client// couldn't tell whose delta belonged to whom.@@ -200,6 +345,18 @@ describe("describeStreamError", () => {expect(msg.length).toBeLessThan(900);});+ it("omits the detail suffix for an APICallError lacking status, url and body", () => {+ const err = new APICallError({+ message: "Opaque failure",+ url: "",+ requestBodyValues: {},+ statusCode: undefined,+ responseBody: undefined+ });+ // No status/url/body → no parenthesised detail, just name + message.+ expect(describeStreamError(err)).toBe(`${err.name}: Opaque failure`);+ });+it("falls back to name and message for a plain Error", () => {expect(describeStreamError(new TypeError("bad input"))).toBe("TypeError: bad input");});diff --git a/apps/server/src/services/llm/stream.ts b/apps/server/src/services/llm/stream.tsindex 25848516e3..893280d310 100644--- a/apps/server/src/services/llm/stream.ts+++ b/apps/server/src/services/llm/stream.ts@@ -24,8 +24,14 @@ function calculateCost(usage: LanguageModelUsage, pricing?: ModelPricing): numbeconst details = usage.inputTokenDetails;const cacheReadTokens = details?.cacheReadTokens ?? usage.cachedInputTokens ?? 0;const cacheWriteTokens = details?.cacheWriteTokens ?? 0;+ // The sole caller only invokes calculateCost once it has type-guarded both+ // inputTokens and outputTokens as numbers, so the `?? 0` fallbacks here are+ // unreachable defensive normalisation.+ /* v8 ignore next */+ const inputTokens = usage.inputTokens ?? 0;const noCacheInputTokens = details?.noCacheTokens- ?? Math.max(0, (usage.inputTokens ?? 0) - cacheReadTokens - cacheWriteTokens);+ ?? Math.max(0, inputTokens - cacheReadTokens - cacheWriteTokens);+ /* v8 ignore next */const outputTokens = usage.outputTokens ?? 0;const M = 1_000_000;diff --git a/apps/server/src/services/llm/tools/attachment_tools.spec.ts b/apps/server/src/services/llm/tools/attachment_tools.spec.tsnew file mode 100644index 0000000000..e96a986fda--- /dev/null+++ b/apps/server/src/services/llm/tools/attachment_tools.spec.ts@@ -0,0 +1,120 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const { getAttachmentMock, getBlobMock } = vi.hoisted(() => ({+ getAttachmentMock: vi.fn(),+ getBlobMock: vi.fn()+}));++// Attachment + blob lookups go through SQL in the real becca; partial-mock core+// so these two return deterministic stubs while the rest of core is untouched.+vi.mock("@triliumnext/core", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@triliumnext/core")>();+ return {+ ...actual,+ becca: { ...actual.becca, getAttachment: getAttachmentMock, getBlob: getBlobMock }+ };+});++import { attachmentTools } from "./attachment_tools.js";+import type { ToolDefinition } from "./tool_registry.js";++function getTool(name: string): ToolDefinition {+ for (const [n, def] of attachmentTools) {+ if (n === name) return def;+ }+ throw new Error(`Tool ${name} not registered`);+}++function stubAttachment(overrides: Record<string, unknown>) {+ return {+ attachmentId: "att1",+ ownerId: "note1",+ role: "file",+ mime: "text/plain",+ title: "doc.txt",+ dateModified: "2026-01-01",+ contentLength: 12,+ blobId: "blob1",+ hasStringContent: () => true,+ getContent: () => "plain text",+ ...overrides+ };+}++describe("attachment_tools", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ describe("get_attachment", () => {+ it("returns attachment metadata", () => {+ getAttachmentMock.mockReturnValue(stubAttachment({}));+ expect(getTool("get_attachment").execute({ attachmentId: "att1" })).toEqual({+ attachmentId: "att1",+ ownerId: "note1",+ role: "file",+ mime: "text/plain",+ title: "doc.txt",+ dateModified: "2026-01-01",+ contentLength: 12+ });+ });++ it("returns an error when the attachment is missing", () => {+ getAttachmentMock.mockReturnValue(null);+ expect(getTool("get_attachment").execute({ attachmentId: "missing" }))+ .toEqual({ error: "Attachment not found" });+ });+ });++ describe("get_attachment_content", () => {+ it("returns the text content for a string attachment", () => {+ getAttachmentMock.mockReturnValue(stubAttachment({ getContent: () => "hello world" }));+ expect(getTool("get_attachment_content").execute({ attachmentId: "att1" })).toEqual({+ attachmentId: "att1",+ source: "text",+ content: "hello world"+ });+ });++ it("falls back to OCR/extracted text from the blob for binary attachments", () => {+ getAttachmentMock.mockReturnValue(stubAttachment({+ hasStringContent: () => false,+ mime: "image/png",+ blobId: "blob1"+ }));+ getBlobMock.mockReturnValue({ textRepresentation: "OCR extracted" });++ expect(getTool("get_attachment_content").execute({ attachmentId: "att1" })).toEqual({+ attachmentId: "att1",+ source: "ocr",+ content: "OCR extracted"+ });+ });++ it("returns an error for binary attachments with no readable text (no blobId, or empty blob)", () => {+ // No blobId at all → getBlob is never consulted.+ getAttachmentMock.mockReturnValue(stubAttachment({+ hasStringContent: () => false,+ blobId: null+ }));+ expect(getTool("get_attachment_content").execute({ attachmentId: "att1" }))+ .toEqual({ error: "Attachment has no readable text content" });++ // Has a blob, but it carries no extracted text.+ getAttachmentMock.mockReturnValue(stubAttachment({+ hasStringContent: () => false,+ blobId: "blob1"+ }));+ getBlobMock.mockReturnValue({ textRepresentation: null });+ expect(getTool("get_attachment_content").execute({ attachmentId: "att1" }))+ .toEqual({ error: "Attachment has no readable text content" });+ });++ it("returns an error when the attachment is missing", () => {+ getAttachmentMock.mockReturnValue(null);+ expect(getTool("get_attachment_content").execute({ attachmentId: "missing" }))+ .toEqual({ error: "Attachment not found" });+ });+ });+});diff --git a/apps/server/src/services/llm/tools/attribute_tools.spec.ts b/apps/server/src/services/llm/tools/attribute_tools.spec.tsnew file mode 100644index 0000000000..a0f10d03a0--- /dev/null+++ b/apps/server/src/services/llm/tools/attribute_tools.spec.ts@@ -0,0 +1,169 @@+import { becca, cls, note_service as noteService } from "@triliumnext/core";+import { beforeAll, describe, expect, it } from "vitest";++import { attributeTools } from "./attribute_tools.js";+import type { ToolDefinition } from "./tool_registry.js";++function getTool(name: string): ToolDefinition {+ for (const [n, def] of attributeTools) {+ if (n === name) return def;+ }+ throw new Error(`Tool ${name} not registered`);+}++/** Create a fresh note under root in the real (seeded) in-memory DB. */+function createNote(title: string) {+ return cls.init(() => noteService.createNewNote({+ parentNoteId: "root",+ title,+ content: "body",+ type: "text"+ }).note);+}++describe("attribute_tools", () => {+ let noteId: string;++ beforeAll(() => {+ const note = createNote("Attr host");+ noteId = note.noteId;+ cls.init(() => {+ note.setLabel("color", "blue");+ note.setRelation("template", "root");+ });+ });++ describe("get_attributes", () => {+ it("lists owned, non-auto-link attributes with their fields", () => {+ const result = getTool("get_attributes").execute({ noteId }) as any[];+ const color = result.find((a) => a.name === "color");+ expect(color).toMatchObject({ type: "label", name: "color", value: "blue" });+ expect(color.attributeId).toBeTruthy();+ // A relation is included too.+ expect(result.some((a) => a.type === "relation" && a.name === "template")).toBe(true);+ });++ it("returns an error when the note is missing", () => {+ expect(getTool("get_attributes").execute({ noteId: "missing" }))+ .toEqual({ error: "Note not found" });+ });+ });++ describe("get_attribute", () => {+ it("returns a single attribute by id, including inheritable flag when set", () => {+ const note = createNote("Inheritable host");+ cls.init(() => note.addLabel("shared", "yes", true));+ const attr = note.getOwnedAttributes()[0];++ expect(getTool("get_attribute").execute({ attributeId: attr.attributeId })).toEqual({+ attributeId: attr.attributeId,+ noteId: note.noteId,+ type: "label",+ name: "shared",+ value: "yes",+ isInheritable: true+ });+ });++ it("returns an error when the attribute is missing", () => {+ expect(getTool("get_attribute").execute({ attributeId: "missing" }))+ .toEqual({ error: "Attribute not found" });+ });+ });++ describe("set_attribute", () => {+ it("creates a label on a note", () => {+ const note = createNote("Set label host");+ const result = cls.init(() => getTool("set_attribute").execute({+ noteId: note.noteId,+ type: "label",+ name: "priority",+ value: "high"+ }));+ expect(result).toEqual({+ success: true,+ noteId: note.noteId,+ type: "label",+ name: "priority",+ value: "high"+ });+ expect(note.getLabelValue("priority")).toBe("high");+ });++ it("defaults the value to an empty string when omitted", () => {+ const note = createNote("Empty value host");+ const result = cls.init(() => getTool("set_attribute").execute({+ noteId: note.noteId,+ type: "label",+ name: "marker"+ })) as { value: string };+ expect(result.value).toBe("");+ });++ it("rejects a missing note, protected note, dangerous attribute, and missing relation target", () => {+ expect(getTool("set_attribute").execute({ noteId: "missing", type: "label", name: "x" }))+ .toEqual({ error: "Note not found" });++ const protectedNote = createNote("Protected set host");+ protectedNote.isProtected = true;+ expect(cls.init(() => getTool("set_attribute").execute({+ noteId: protectedNote.noteId, type: "label", name: "x"+ }))).toMatchObject({ error: expect.stringContaining("protected") });+ protectedNote.isProtected = false;++ const dangerHost = createNote("Danger host");+ expect(cls.init(() => getTool("set_attribute").execute({+ noteId: dangerHost.noteId, type: "label", name: "run"+ }))).toMatchObject({ error: expect.stringContaining("dangerous") });++ const relHost = createNote("Relation host");+ expect(cls.init(() => getTool("set_attribute").execute({+ noteId: relHost.noteId, type: "relation", name: "ref", value: "doesNotExist"+ }))).toEqual({ error: "Target note not found for relation" });+ });++ it("creates a relation to an existing target note", () => {+ const note = createNote("Relation ok host");+ const result = cls.init(() => getTool("set_attribute").execute({+ noteId: note.noteId, type: "relation", name: "ref", value: "root"+ }));+ expect(result).toMatchObject({ success: true, type: "relation", value: "root" });+ });+ });++ describe("delete_attribute", () => {+ it("deletes an attribute owned by the note", () => {+ const note = createNote("Delete host");+ cls.init(() => note.setLabel("temp", "1"));+ const attr = note.getOwnedAttributes().find((a) => a.name === "temp")!;++ const result = cls.init(() => getTool("delete_attribute").execute({+ noteId: note.noteId,+ attributeId: attr.attributeId+ }));+ expect(result).toEqual({ success: true, attributeId: attr.attributeId });+ expect(becca.getAttribute(attr.attributeId)).toBeNull();+ });++ it("rejects a missing attribute, a mismatched owner, and a protected owner", () => {+ expect(getTool("delete_attribute").execute({ noteId: "x", attributeId: "missing" }))+ .toEqual({ error: "Attribute not found" });++ const note = createNote("Mismatch host");+ cls.init(() => note.setLabel("keep", "1"));+ const attr = note.getOwnedAttributes()[0];+ expect(getTool("delete_attribute").execute({+ noteId: "root", attributeId: attr.attributeId+ })).toMatchObject({ error: expect.stringContaining("does not belong") });++ const protectedNote = createNote("Protected del host");+ cls.init(() => protectedNote.setLabel("p", "1"));+ const pAttr = protectedNote.getOwnedAttributes()[0];+ protectedNote.isProtected = true;+ expect(getTool("delete_attribute").execute({+ noteId: protectedNote.noteId, attributeId: pAttr.attributeId+ })).toMatchObject({ error: expect.stringContaining("protected") });+ protectedNote.isProtected = false;+ });+ });+});diff --git a/apps/server/src/services/llm/tools/helpers.spec.ts b/apps/server/src/services/llm/tools/helpers.spec.tsindex 92f87e45a1..cf13bfa0ba 100644--- a/apps/server/src/services/llm/tools/helpers.spec.ts+++ b/apps/server/src/services/llm/tools/helpers.spec.ts@@ -1,7 +1,244 @@-import { describe, expect, it } from "vitest";+import type { BAttachment, BNote } from "@triliumnext/core";+import { beforeEach, describe, expect, it, vi } from "vitest";-import { applyTextEdits } from "./helpers.js";+const getBlobMock = vi.hoisted(() => vi.fn());+// getContentPreview / getNoteContentForLlm consult becca.getBlob (SQL-backed);+// partial-mock core so it returns deterministic blobs while markdown+// import/export services keep their real implementations.+vi.mock("@triliumnext/core", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@triliumnext/core")>();+ return {+ ...actual,+ becca: { ...actual.becca, getBlob: getBlobMock }+ };+});++import {+ applyTextEdits,+ flag,+ getAttachmentContentPreview,+ getContentPreview,+ getNoteContentForLlm,+ getNoteMeta,+ setNoteContentFromLlm+} from "./helpers.js";++/** Minimal BNote stub exposing only what the helpers under test call. */+function noteStub(overrides: Partial<Record<string, unknown>> = {}): BNote {+ return {+ noteId: "n1",+ title: "Note 1",+ type: "text",+ mime: "text/html",+ isProtected: false,+ blobId: "b1",+ dateCreated: "2026-01-01",+ dateModified: "2026-01-02",+ isContentAvailable: () => true,+ getContent: () => "<p>hello</p>",+ getTitleOrProtected: () => "Note 1",+ getChildNotes: () => [],+ getParentNotes: () => [],+ getAttributes: () => [],+ getAttachments: () => [],+ setContent: vi.fn(),+ ...overrides+ } as unknown as BNote;+}++function attachmentStub(overrides: Partial<Record<string, unknown>> = {}): BAttachment {+ return {+ attachmentId: "a1",+ role: "file",+ mime: "text/plain",+ title: "doc.txt",+ contentLength: 10,+ blobId: "b1",+ hasStringContent: () => true,+ getContent: () => "attachment text",+ ...overrides+ } as unknown as BAttachment;+}++describe("flag", () => {+ it("returns true for truthy and undefined otherwise", () => {+ expect(flag(true)).toBe(true);+ expect(flag(false)).toBeUndefined();+ expect(flag(undefined)).toBeUndefined();+ });+});++describe("getNoteContentForLlm", () => {+ beforeEach(() => getBlobMock.mockReset());++ it("converts text notes from HTML to Markdown", () => {+ const note = noteStub({ type: "text", getContent: () => "<h1>Title</h1>" });+ expect(getNoteContentForLlm(note)).toContain("# Title");+ });++ it("returns code-note content verbatim", () => {+ const note = noteStub({ type: "code", mime: "text/plain", getContent: () => "const x = 1;" });+ expect(getNoteContentForLlm(note)).toBe("const x = 1;");+ });++ it("uses the blob's extracted text for binary content", () => {+ const note = noteStub({ type: "image", getContent: () => new Uint8Array([1, 2, 3]) });+ getBlobMock.mockReturnValue({ textRepresentation: "scanned words" });+ expect(getNoteContentForLlm(note)).toBe("[extracted text from image]\nscanned words");+ });++ it("falls back to a binary-content marker when no extracted text exists", () => {+ const noBlob = noteStub({ type: "image", blobId: "", getContent: () => new Uint8Array([1]) });+ expect(getNoteContentForLlm(noBlob)).toBe("[binary content]");++ const emptyBlob = noteStub({ type: "image", getContent: () => new Uint8Array([1]) });+ getBlobMock.mockReturnValue({ textRepresentation: null });+ expect(getNoteContentForLlm(emptyBlob)).toBe("[binary content]");+ });+});++describe("setNoteContentFromLlm", () => {+ it("renders Markdown to HTML for text notes", () => {+ const note = noteStub({ type: "text" });+ setNoteContentFromLlm(note, "# Heading");+ const [written] = (note.setContent as ReturnType<typeof vi.fn>).mock.calls[0];+ // Trilium's markdown importer renders the document title as h1, so a+ // top-level "# Heading" becomes an <h2> in the body.+ expect(written).toContain("Heading");+ expect(written).toMatch(/<h[12]>/);+ });++ it("stores raw content for non-text notes", () => {+ const note = noteStub({ type: "code", mime: "text/plain" });+ setNoteContentFromLlm(note, "raw code");+ expect(note.setContent).toHaveBeenCalledWith("raw code");+ });+});++describe("getContentPreview", () => {+ beforeEach(() => getBlobMock.mockReset());++ it("returns null when content is not available (protected)", () => {+ expect(getContentPreview(noteStub({ isContentAvailable: () => false }))).toBeNull();+ });++ it("returns a size hint for large notes without loading content", () => {+ getBlobMock.mockReturnValue({ contentLength: 50_000 });+ const result = getContentPreview(noteStub());+ expect(result).toMatch(/\d+KB - use get_note_content/);+ });++ it("returns null for binary/empty content", () => {+ getBlobMock.mockReturnValue({ contentLength: 5 });+ const binary = noteStub({ type: "image", getContent: () => new Uint8Array([1]), blobId: "" });+ expect(getContentPreview(binary)).toBeNull();+ });++ it("returns the full converted content when short", () => {+ getBlobMock.mockReturnValue({ contentLength: 5 });+ const note = noteStub({ type: "code", mime: "text/plain", getContent: () => "short" });+ expect(getContentPreview(note)).toBe("short");+ });++ it("truncates long content with an ellipsis", () => {+ getBlobMock.mockReturnValue({ contentLength: 600 });+ const long = "x".repeat(600);+ const note = noteStub({ type: "code", mime: "text/plain", getContent: () => long });+ const result = getContentPreview(note)!;+ expect(result.endsWith("…")).toBe(true);+ expect(result.length).toBe(501); // 500 chars + ellipsis+ });++ it("loads content normally when there is no blob to size-check", () => {+ getBlobMock.mockReturnValue(null);+ const note = noteStub({ type: "code", mime: "text/plain", getContent: () => "abc" });+ expect(getContentPreview(note)).toBe("abc");+ });+});++describe("getAttachmentContentPreview", () => {+ beforeEach(() => getBlobMock.mockReset());++ it("returns the raw text of a string attachment", () => {+ expect(getAttachmentContentPreview(attachmentStub({ getContent: () => "hi" }))).toBe("hi");+ });++ it("uses the blob's extracted text for binary attachments", () => {+ getBlobMock.mockReturnValue({ textRepresentation: "ocr text" });+ const att = attachmentStub({ hasStringContent: () => false, mime: "image/png" });+ expect(getAttachmentContentPreview(att)).toBe("ocr text");+ });++ it("returns null when no readable text exists", () => {+ // Binary without blob.+ const noBlob = attachmentStub({ hasStringContent: () => false, blobId: "" });+ expect(getAttachmentContentPreview(noBlob)).toBeNull();+ // Binary with blob but no extracted text.+ getBlobMock.mockReturnValue({ textRepresentation: null });+ const emptyBlob = attachmentStub({ hasStringContent: () => false });+ expect(getAttachmentContentPreview(emptyBlob)).toBeNull();+ });++ it("truncates long attachment text", () => {+ const att = attachmentStub({ getContent: () => "y".repeat(300) });+ const result = getAttachmentContentPreview(att)!;+ expect(result.endsWith("…")).toBe(true);+ expect(result.length).toBe(201); // 200 chars + ellipsis+ });+});++describe("getNoteMeta", () => {+ beforeEach(() => getBlobMock.mockReset());++ it("builds metadata with truncated children/attributes/attachments and total counts", () => {+ getBlobMock.mockReturnValue({ contentLength: 5 });+ const children = Array.from({ length: 3 }, (_, i) => ({+ noteId: `c${i}`,+ getTitleOrProtected: () => `Child ${i}`+ }));+ const attrs = [+ { attributeId: "at1", type: "label", name: "color", value: "red", isInheritable: true },+ { attributeId: "at2", type: "relation", name: "ref", value: "n2", isInheritable: false }+ ];+ const attachments = [attachmentStub({ getContent: () => "preview" })];++ const note = noteStub({+ type: "code",+ mime: "text/plain",+ isProtected: true,+ getContent: () => "body",+ getChildNotes: () => children,+ getParentNotes: () => [{ noteId: "root" }],+ getAttributes: () => attrs,+ getAttachments: () => attachments+ });++ const meta = getNoteMeta(note, { childNotes: 2, attributes: 5, attachments: 5 }) as any;++ expect(meta.noteId).toBe("n1");+ expect(meta.isProtected).toBe(true);+ expect(meta.parentNoteIds).toEqual(["root"]);+ expect(meta.childNotes).toEqual({+ totalCount: 3,+ results: [+ { noteId: "c0", title: "Child 0" },+ { noteId: "c1", title: "Child 1" }+ ]+ });+ expect(meta.attributes.totalCount).toBe(2);+ expect(meta.attributes.results[0]).toEqual({+ attributeId: "at1", type: "label", name: "color", value: "red", isInheritable: true+ });+ // isInheritable:false is omitted via flag().+ expect(meta.attributes.results[1].isInheritable).toBeUndefined();+ expect(meta.attachments.totalCount).toBe(1);+ expect(meta.attachments.results[0].contentPreview).toBe("preview");+ expect(meta.contentPreview).toBe("body");+ });+});++// Existing applyTextEdits coverage (kept; exercises the find-and-replace path).describe("applyTextEdits", () => {it("applies a single find-and-replace edit", () => {const result = applyTextEdits("const x = 1;\nconst y = 2;\n", [diff --git a/apps/server/src/services/llm/tools/hierarchy_tools.spec.ts b/apps/server/src/services/llm/tools/hierarchy_tools.spec.tsnew file mode 100644index 0000000000..2b65cd08f5--- /dev/null+++ b/apps/server/src/services/llm/tools/hierarchy_tools.spec.ts@@ -0,0 +1,205 @@+import { cls, note_service as noteService } from "@triliumnext/core";+import { describe, expect, it } from "vitest";++import { hierarchyTools } from "./hierarchy_tools.js";+import type { ToolDefinition } from "./tool_registry.js";++function getTool(name: string): ToolDefinition {+ for (const [n, def] of hierarchyTools) {+ if (n === name) return def;+ }+ throw new Error(`Tool ${name} not registered`);+}++function createNote(parentNoteId: string, title: string) {+ return cls.init(() => noteService.createNewNote({+ parentNoteId,+ title,+ content: "body",+ type: "text"+ }).note);+}++describe("hierarchy_tools", () => {+ describe("get_child_notes", () => {+ it("lists immediate children with their child counts", () => {+ const parent = createNote("root", "Parent");+ const child = createNote(parent.noteId, "Child");+ createNote(child.noteId, "Grandchild");++ const result = getTool("get_child_notes").execute({ noteId: parent.noteId }) as any[];+ expect(result).toEqual([+ { noteId: child.noteId, title: "Child", type: "text", childCount: 1 }+ ]);+ });++ it("returns an error when the note is missing", () => {+ expect(getTool("get_child_notes").execute({ noteId: "missing" }))+ .toEqual({ error: "Note not found" });+ });+ });++ describe("get_subtree", () => {+ it("returns a nested subtree honouring the depth argument", () => {+ const root = createNote("root", "Subtree root");+ const a = createNote(root.noteId, "A");+ createNote(a.noteId, "A.1");++ // Default depth (2): root → A → A.1 not shown beyond depth.+ const result = getTool("get_subtree").execute({ noteId: root.noteId }) as any;+ expect(result.noteId).toBe(root.noteId);+ expect(result.children[0].title).toBe("A");+ // At depth 2 the leaf A.1 is reached and has no children of its own.+ expect(result.children[0].children[0].title).toBe("A.1");+ });++ it("reports a depth-limit message when children exist past maxDepth", () => {+ const root = createNote("root", "Deep root");+ const a = createNote(root.noteId, "Deep A");+ createNote(a.noteId, "Deep A.1");++ // depth 1: only the first level is expanded; A still has children.+ const result = getTool("get_subtree").execute({ noteId: root.noteId, depth: 1 }) as any;+ expect(result.children[0].children).toContain("1 children not shown (depth limit reached)");+ });++ it("truncates wide levels and appends a '... and N more' marker", () => {+ const wide = createNote("root", "Wide");+ for (let i = 0; i < 12; i++) {+ createNote(wide.noteId, `c${i}`);+ }+ const result = getTool("get_subtree").execute({ noteId: wide.noteId, depth: 1 }) as any;+ // 10 shown + 1 truncation marker.+ expect(result.children).toHaveLength(11);+ expect(result.children[10]).toMatchObject({ type: "truncated", noteId: "" });+ });++ it("stops at leaf nodes reached before the depth limit", () => {+ const root = createNote("root", "Leaf root");+ // A is a leaf (no children) reached at depth 1, well within depth 2.+ createNote(root.noteId, "Leaf A");+ const result = getTool("get_subtree").execute({ noteId: root.noteId, depth: 2 }) as any;+ expect(result.children).toHaveLength(1);+ // A leaf has no `children` property at all.+ expect(result.children[0]).not.toHaveProperty("children");+ });++ it("returns an error when the note is missing", () => {+ expect(getTool("get_subtree").execute({ noteId: "missing" }))+ .toEqual({ error: "Note not found" });+ });+ });++ describe("move_note", () => {+ it("moves a note to a new parent", () => {+ const oldParent = createNote("root", "Old parent");+ const newParent = createNote("root", "New parent");+ const note = createNote(oldParent.noteId, "Movable");++ const result = cls.init(() => getTool("move_note").execute({+ noteId: note.noteId,+ newParentNoteId: newParent.noteId+ }));+ expect(result).toMatchObject({+ success: true,+ noteId: note.noteId,+ newParentNoteId: newParent.noteId,+ newParentTitle: "New parent"+ });+ expect(note.getParentNotes().map((p) => p.noteId)).toContain(newParent.noteId);+ });++ it("rejects missing note, system notes, protected notes, and missing/invalid targets", () => {+ expect(getTool("move_note").execute({ noteId: "missing", newParentNoteId: "root" }))+ .toEqual({ error: "Note not found" });++ expect(getTool("move_note").execute({ noteId: "root", newParentNoteId: "root" }))+ .toEqual({ error: "Cannot move system notes" });++ const protectedNote = createNote("root", "Protected move");+ protectedNote.isProtected = true;+ expect(getTool("move_note").execute({+ noteId: protectedNote.noteId, newParentNoteId: "root"+ })).toMatchObject({ error: expect.stringContaining("protected") });+ protectedNote.isProtected = false;++ const orphan = createNote("root", "Target missing");+ expect(getTool("move_note").execute({+ noteId: orphan.noteId, newParentNoteId: "doesNotExist"+ })).toEqual({ error: "Target parent note not found" });++ const movable = createNote("root", "Movable to protected");+ const protectedParent = createNote("root", "Protected target");+ protectedParent.isProtected = true; // content unavailable without a protected session+ expect(getTool("move_note").execute({+ noteId: movable.noteId, newParentNoteId: protectedParent.noteId+ })).toMatchObject({ error: expect.stringContaining("protected parent") });+ protectedParent.isProtected = false;+ });++ it("surfaces a validation failure when moving a note under its own descendant", () => {+ const parent = createNote("root", "Cycle parent");+ const child = createNote(parent.noteId, "Cycle child");++ // Moving the parent under its own child would create a cycle → validation fails.+ const result = cls.init(() => getTool("move_note").execute({+ noteId: parent.noteId,+ newParentNoteId: child.noteId+ }));+ expect(result).toHaveProperty("error");+ expect(result).not.toHaveProperty("success");+ });+ });++ describe("clone_note", () => {+ it("clones a note to an additional parent with a prefix", () => {+ const a = createNote("root", "Clone A");+ const b = createNote("root", "Clone B");+ const note = createNote(a.noteId, "Cloneable");++ const result = cls.init(() => getTool("clone_note").execute({+ noteId: note.noteId,+ parentNoteId: b.noteId,+ prefix: "ref"+ })) as any;+ expect(result).toMatchObject({+ success: true,+ noteId: note.noteId,+ parentNoteId: b.noteId,+ parentTitle: "Clone B"+ });+ expect(result.branchId).toBeTruthy();+ expect(note.getParentNotes().map((p) => p.noteId)).toContain(b.noteId);+ });++ it("rejects a missing note, a protected source, a protected parent, and a clone failure", () => {+ expect(getTool("clone_note").execute({ noteId: "missing", parentNoteId: "root" }))+ .toEqual({ error: "Note not found" });++ const protectedSource = createNote("root", "Protected clone source");+ protectedSource.isProtected = true;+ expect(getTool("clone_note").execute({+ noteId: protectedSource.noteId, parentNoteId: "root"+ })).toMatchObject({ error: expect.stringContaining("protected") });+ protectedSource.isProtected = false;++ const cloneable = createNote("root", "Cloneable to protected");+ const protectedParent = createNote("root", "Protected clone target");+ protectedParent.isProtected = true;+ expect(getTool("clone_note").execute({+ noteId: cloneable.noteId, parentNoteId: protectedParent.noteId+ })).toMatchObject({ error: expect.stringContaining("protected parent") });+ protectedParent.isProtected = false;++ const parent = createNote("root", "Dup parent");+ const note = createNote(parent.noteId, "Already there");+ // Cloning into a parent it already lives under fails.+ const result = cls.init(() => getTool("clone_note").execute({+ noteId: note.noteId,+ parentNoteId: parent.noteId+ }));+ expect(result).toHaveProperty("error");+ expect(result).not.toHaveProperty("success");+ });+ });+});diff --git a/apps/server/src/services/llm/tools/hierarchy_tools.ts b/apps/server/src/services/llm/tools/hierarchy_tools.tsindex afa2983476..f27277acb8 100644--- a/apps/server/src/services/llm/tools/hierarchy_tools.ts+++ b/apps/server/src/services/llm/tools/hierarchy_tools.ts@@ -118,12 +118,10 @@ export const hierarchyTools = defineTools({if (!targetParent.isContentAvailable()) {return { error: "Cannot move note to a protected parent" };}- if (!targetParent.isContentAvailable()) {- return { error: "Cannot move note to a protected parent" };- }// Use the first (primary) parent branch for the moveconst branches = note.getParentBranches();+ /* v8 ignore next 3 -- defensive: a non-system note always has at least one parent branch */if (branches.length === 0) {return { error: "Note has no parent branches" };}@@ -132,8 +130,10 @@ export const hierarchyTools = defineTools({if (Array.isArray(result)) {// Validation error: [statusCode, { success: false, message }]const validation = result[1] as { success: boolean; message?: string };+ /* v8 ignore next -- defensive: validateParentChild always supplies a message on failure */return { error: validation.message || "Move validation failed" };}+ /* v8 ignore next 3 -- defensive: moveBranchToNote only returns success:true or a validation array */if (!result.success) {return { error: "Failed to move note" };}@@ -172,6 +172,7 @@ export const hierarchyTools = defineTools({const result = cloningService.cloneNoteToParentNote(noteId, parentNoteId, prefix ?? null);if (!result.success) {+ /* v8 ignore next -- defensive: cloneNoteToParentNote always supplies a message on failure */return { error: result.message || "Clone failed" };}@@ -180,6 +181,8 @@ export const hierarchyTools = defineTools({noteId,title: note.getTitleOrProtected(),parentNoteId,+ // A successful clone always has a real (content-available) parent note.+ /* v8 ignore next -- defensive: parent is non-null on the success path */parentTitle: parent?.getTitleOrProtected() ?? parentNoteId,branchId: result.branchId};diff --git a/apps/server/src/services/llm/tools/note_tools.spec.ts b/apps/server/src/services/llm/tools/note_tools.spec.tsindex a3aa3fe0d7..4128864ae3 100644--- a/apps/server/src/services/llm/tools/note_tools.spec.ts+++ b/apps/server/src/services/llm/tools/note_tools.spec.ts@@ -1,18 +1,23 @@-import { becca_easy_mocking } from "@triliumnext/core";+import { becca, becca_easy_mocking } from "@triliumnext/core";import { beforeEach, describe, expect, it, vi } from "vitest";-import { becca } from "@triliumnext/core";import { noteTools } from "./note_tools.js";import type { ToolDefinition } from "./tool_registry.js";const { buildNote } = becca_easy_mocking;+const findResultsMock = vi.hoisted(() => vi.fn());+vi.mock("@triliumnext/core", async (importOriginal) => {const actual = await importOriginal<typeof import("@triliumnext/core")>();return {...actual,note_service: {createNewNote: vi.fn()+ },+ search: {+ ...actual.search,+ findResultsWithQuery: findResultsMock}};});@@ -126,6 +131,80 @@ describe("note_tools — write tools return post-write content", () => {});});+ describe("write-tool guard branches", () => {+ for (const tool of ["set_note_content", "append_to_note", "edit_note_content"] as const) {+ const args = (noteId: string) =>+ tool === "edit_note_content"+ ? { noteId, edits: [{ oldText: "a", newText: "b" }] }+ : { noteId, content: "x" };++ it(`${tool} reports a missing note`, () => {+ expect(getTool(tool).execute(args("does-not-exist")))+ .toEqual({ error: "Note not found" });+ });++ it(`${tool} rejects a protected note and an unsupported (binary) note type`, () => {+ const prot = buildNote({ id: `${tool}-p`, type: "code", mime: "text/plain", content: "a" });+ withMutableContent(prot, "a");+ prot.isContentAvailable = () => false;+ expect(getTool(tool).execute(args(`${tool}-p`)))+ .toMatchObject({ error: expect.stringContaining("protected") });++ // image notes are not string notes → hasStringContent() is false.+ const bin = buildNote({ id: `${tool}-b`, type: "image", mime: "image/png" });+ expect(getTool(tool).execute(args(bin.noteId)))+ .toMatchObject({ error: expect.stringContaining("note type: image") });+ });+ }++ it("append_to_note and edit_note_content reject a note whose stored content is binary", () => {+ // hasStringContent() reports true but getContent() yields a buffer.+ const mkBinaryHolder = (id: string) => {+ const note = buildNote({ id, type: "code", mime: "text/plain" });+ note.hasStringContent = () => true;+ note.getContent = () => new Uint8Array([1, 2, 3]);+ note.saveRevision = vi.fn() as typeof note.saveRevision;+ return note;+ };+ expect(getTool("append_to_note").execute({ noteId: mkBinaryHolder("ap-bin").noteId, content: "x" }))+ .toEqual({ error: "Note has binary content" });+ expect(getTool("edit_note_content").execute({+ noteId: mkBinaryHolder("ed-bin").noteId,+ edits: [{ oldText: "a", newText: "b" }]+ })).toEqual({ error: "Note has binary content" });+ });++ it("append_to_note does not add a second newline when content already ends with one", () => {+ const note = buildNote({ id: "ap-nl", type: "code", mime: "text/plain", content: "line\n" });+ withMutableContent(note, "line\n");+ const result = getTool("append_to_note").execute({ noteId: "ap-nl", content: "next" }) as {+ content: string;+ };+ expect(result.content).toBe("line\nnext");+ });++ it("append_to_note converts Markdown to HTML for text notes", () => {+ const note = buildNote({ id: "ap-text", type: "text", content: "<p>start</p>" });+ withMutableContent(note, "<p>start</p>");+ const result = getTool("append_to_note").execute({ noteId: "ap-text", content: "more" }) as {+ success: boolean;+ content: string;+ };+ expect(result.success).toBe(true);+ // The appended Markdown is rendered and round-tripped back to Markdown.+ expect(result.content).toContain("more");+ });++ it("edit_note_content surfaces a failed text edit", () => {+ const note = buildNote({ id: "ed-fail", type: "code", mime: "text/plain", content: "abc" });+ withMutableContent(note, "abc");+ expect(getTool("edit_note_content").execute({+ noteId: "ed-fail",+ edits: [{ oldText: "zzz", newText: "y" }]+ })).toMatchObject({ error: expect.stringContaining("not found") });+ });+ });+describe("create_note", () => {it("returns the created note's content", async () => {buildNote({ id: "parent1", title: "Parent" });@@ -148,5 +227,167 @@ describe("note_tools — write tools return post-write content", () => {expect(result.noteId).toBe("new1");expect(result.content).toBe("hello");});++ it("requires a mime for code notes and validates the parent", async () => {+ expect(getTool("create_note").execute({+ parentNoteId: "root", title: "x", content: "", type: "code"+ })).toMatchObject({ error: expect.stringContaining("mime is required") });++ expect(getTool("create_note").execute({+ parentNoteId: "ghost", title: "x", content: "", type: "text"+ })).toEqual({ error: "Parent note not found" });++ const protectedParent = buildNote({ id: "pp", title: "Protected" });+ protectedParent.isProtected = true;+ expect(getTool("create_note").execute({+ parentNoteId: "pp", title: "x", content: "", type: "text"+ })).toMatchObject({ error: expect.stringContaining("protected parent") });+ });++ it("renders Markdown to HTML for text notes and surfaces creation errors", async () => {+ buildNote({ id: "tparent", title: "TParent" });+ const { note_service: noteService } = await import("@triliumnext/core");++ const created = buildNote({ id: "tnew", type: "text", content: "<h2>Hi</h2>" });+ withMutableContent(created, "<h2>Hi</h2>");+ vi.mocked(noteService.createNewNote).mockImplementationOnce((opts: any) => {+ // The tool converts Markdown → HTML before persisting.+ expect(opts.content).toContain("<h2>");+ return { note: created } as ReturnType<typeof noteService.createNewNote>;+ });+ const ok = getTool("create_note").execute({+ parentNoteId: "tparent", title: "T", content: "## Hi", type: "text"+ }) as { success: boolean };+ expect(ok.success).toBe(true);++ vi.mocked(noteService.createNewNote).mockImplementationOnce(() => {+ throw new Error("disk full");+ });+ expect(getTool("create_note").execute({+ parentNoteId: "tparent", title: "T", content: "x", type: "text"+ })).toEqual({ error: "disk full" });++ // A non-Error throw falls back to a generic message.+ vi.mocked(noteService.createNewNote).mockImplementationOnce(() => {+ throw "boom";+ });+ expect(getTool("create_note").execute({+ parentNoteId: "tparent", title: "T", content: "x", type: "text"+ })).toEqual({ error: "Failed to create note" });+ });+ });++ describe("search_notes", () => {+ it("maps results to note summaries, applies the limit, and skips stale ids", () => {+ const parent = buildNote({ id: "sp", title: "Search parent" });+ const a = buildNote({ id: "sa", title: "Alpha", type: "code", mime: "text/plain", content: "body" });+ withMutableContent(a, "body");+ // Wire a parent so parentTitle is populated.+ a.getParentNotes = () => [parent];++ findResultsMock.mockReturnValue([+ { noteId: "sa" },+ { noteId: "stale" } // not in becca → filtered out within the limit+ ]);++ const result = getTool("search_notes").execute({ query: "alpha", limit: 5 }) as {+ totalResults: number;+ results: any[];+ };+ expect(result.totalResults).toBe(2);+ expect(result.results).toHaveLength(1); // stale id dropped+ expect(result.results[0]).toMatchObject({ noteId: "sa", title: "Alpha", parentTitle: "Search parent" });+ });++ it("defaults the limit to 10 and tolerates results with no parent", () => {+ const n = buildNote({ id: "np", title: "No parent", type: "code", mime: "text/plain", content: "c" });+ withMutableContent(n, "c");+ n.getParentNotes = () => [];+ findResultsMock.mockReturnValue([{ noteId: "np" }]);++ const result = getTool("search_notes").execute({ query: "x" }) as { results: any[] };+ expect(result.results[0].parentTitle).toBeNull();+ });+ });++ describe("get_note", () => {+ it("returns full metadata for an existing note", () => {+ const note = buildNote({ id: "gn", title: "Meta note", type: "code", mime: "text/plain", content: "c" });+ withMutableContent(note, "c");+ const result = getTool("get_note").execute({ noteId: "gn" }) as { noteId: string };+ expect(result.noteId).toBe("gn");+ });++ it("returns an error for a missing note", () => {+ expect(getTool("get_note").execute({ noteId: "nope" })).toEqual({ error: "Note not found" });+ });+ });++ describe("get_note_content", () => {+ it("returns the LLM-formatted content", () => {+ const note = buildNote({ id: "gc", type: "code", mime: "text/plain", content: "plain" });+ withMutableContent(note, "plain");+ expect(getTool("get_note_content").execute({ noteId: "gc" }))+ .toEqual({ noteId: "gc", content: "plain" });+ });++ it("rejects a missing note and a protected note", () => {+ expect(getTool("get_note_content").execute({ noteId: "nope" }))+ .toEqual({ error: "Note not found" });++ const note = buildNote({ id: "gp", content: "x" });+ note.isContentAvailable = () => false;+ expect(getTool("get_note_content").execute({ noteId: "gp" }))+ .toEqual({ error: "Note is protected" });+ });+ });++ describe("rename_note", () => {+ it("renames a note and trims the title", () => {+ const note = buildNote({ id: "rn", title: "Old" });+ note.save = vi.fn() as typeof note.save;+ const result = getTool("rename_note").execute({ noteId: "rn", newTitle: " New " }) as { title: string };+ expect(result.title).toBe("New");+ expect(note.title).toBe("New");+ expect(note.save).toHaveBeenCalledOnce();+ });++ it("rejects missing, protected, and empty-title cases", () => {+ expect(getTool("rename_note").execute({ noteId: "nope", newTitle: "x" }))+ .toEqual({ error: "Note not found" });++ const prot = buildNote({ id: "rp", title: "P" });+ prot.isProtected = true;+ expect(getTool("rename_note").execute({ noteId: "rp", newTitle: "x" }))+ .toMatchObject({ error: expect.stringContaining("protected") });++ const note = buildNote({ id: "re", title: "E" });+ note.save = vi.fn() as typeof note.save;+ expect(getTool("rename_note").execute({ noteId: "re", newTitle: " " }))+ .toMatchObject({ error: expect.stringContaining("empty") });+ });+ });++ describe("delete_note", () => {+ it("soft-deletes a note and returns its former title", () => {+ const note = buildNote({ id: "dn", title: "Doomed" });+ note.deleteNote = vi.fn() as typeof note.deleteNote;+ const result = getTool("delete_note").execute({ noteId: "dn" });+ expect(result).toEqual({ success: true, noteId: "dn", deletedTitle: "Doomed" });+ expect(note.deleteNote).toHaveBeenCalledOnce();+ });++ it("rejects system notes, missing notes, and protected notes", () => {+ expect(getTool("delete_note").execute({ noteId: "root" }))+ .toEqual({ error: "Cannot delete system notes" });++ expect(getTool("delete_note").execute({ noteId: "nope" }))+ .toEqual({ error: "Note not found" });++ const prot = buildNote({ id: "dp", title: "P" });+ prot.isProtected = true;+ expect(getTool("delete_note").execute({ noteId: "dp" }))+ .toMatchObject({ error: expect.stringContaining("protected") });+ });});});diff --git a/apps/server/src/services/llm/tools/tool_registry.spec.ts b/apps/server/src/services/llm/tools/tool_registry.spec.tsnew file mode 100644index 0000000000..1d958188fe--- /dev/null+++ b/apps/server/src/services/llm/tools/tool_registry.spec.ts@@ -0,0 +1,70 @@+import { describe, expect, it, vi } from "vitest";+import { z } from "zod";++const transactionalMock = vi.hoisted(() => vi.fn(<T>(cb: () => T) => cb()));++// toToolSet wraps mutating tools in sql.transactional; stub it to just run the+// callback so we can assert the wrapping happens without a real transaction.+vi.mock("../../sql.js", () => ({+ default: { transactional: transactionalMock }+}));++import { allToolRegistries } from "./index.js";+import { defineTools, ToolRegistry } from "./tool_registry.js";++describe("ToolRegistry", () => {+ const registry = defineTools({+ read_thing: {+ description: "read",+ inputSchema: z.object({ id: z.string() }),+ execute: ({ id }) => ({ id, read: true })+ },+ write_thing: {+ description: "write",+ inputSchema: z.object({ id: z.string() }),+ mutates: true,+ execute: ({ id }) => ({ id, written: true })+ }+ });++ it("defineTools returns a ToolRegistry", () => {+ expect(registry).toBeInstanceOf(ToolRegistry);+ });++ it("allToolRegistries aggregates every tool group as ToolRegistry instances", () => {+ expect(allToolRegistries.length).toBeGreaterThan(0);+ expect(allToolRegistries.every((r) => r instanceof ToolRegistry)).toBe(true);+ // Every registry yields at least one named tool.+ for (const reg of allToolRegistries) {+ expect([...reg].length).toBeGreaterThan(0);+ }+ });++ it("is iterable over [name, definition] pairs", () => {+ const names = [...registry].map(([name]) => name);+ expect(names).toEqual(["read_thing", "write_thing"]);+ const [, def] = [...registry][1];+ expect(def.mutates).toBe(true);+ });++ it("toToolSet exposes each tool with its description and inputSchema", () => {+ const set = registry.toToolSet();+ expect(Object.keys(set)).toEqual(["read_thing", "write_thing"]);+ expect(set.read_thing.description).toBe("read");+ expect(set.write_thing.inputSchema).toBeDefined();+ });++ it("toToolSet runs read-only tools directly and wraps mutating tools in a transaction", async () => {+ transactionalMock.mockClear();+ const set = registry.toToolSet();++ const readResult = await set.read_thing.execute!({ id: "r1" }, {} as any);+ expect(readResult).toEqual({ id: "r1", read: true });+ // Read-only tools are not transaction-wrapped.+ expect(transactionalMock).not.toHaveBeenCalled();++ const writeResult = await set.write_thing.execute!({ id: "w1" }, {} as any);+ expect(writeResult).toEqual({ id: "w1", written: true });+ expect(transactionalMock).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/server/src/services/mcp/mcp_server.spec.ts b/apps/server/src/services/mcp/mcp_server.spec.tsnew file mode 100644index 0000000000..2e02ffcfd3--- /dev/null+++ b/apps/server/src/services/mcp/mcp_server.spec.ts@@ -0,0 +1,102 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++// --- Mocks (hoisted above the module-under-test import) ---++// Capture every (name, config, callback) passed to registerTool.+interface Registered {+ name: string;+ config: any;+ callback: (args: any) => any;+}+const registered: Registered[] = [];++class FakeMcpServer {+ constructor(public info: any) {}+ registerTool(name: string, config: any, callback: (args: any) => any) {+ registered.push({ name, config, callback });+ return { name };+ }+}++vi.mock("@modelcontextprotocol/sdk/server/mcp.js", () => ({ McpServer: FakeMcpServer }));++const mockSql = { transactional: vi.fn((cb: () => unknown) => cb()) };+vi.mock("../sql.js", () => ({ default: mockSql }));++const clsCalls: { init: number; set: Array<[string, unknown]> } = { init: 0, set: [] };+const mockCls = {+ init: vi.fn((cb: () => unknown) => {+ clsCalls.init++;+ return cb();+ }),+ set: vi.fn((key: string, value: unknown) => clsCalls.set.push([key, value]))+};++vi.mock("@triliumnext/core", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@triliumnext/core")>();+ return {+ ...actual,+ cls: mockCls,+ app_info: { ...actual.app_info, appVersion: "9.9.9-test" }+ };+});++// Two tools: one read-only, one mutating, so both branches of the ternary run.+const readExecute = vi.fn(() => ({ ok: "read" }));+const mutateExecute = vi.fn(() => ({ ok: "mutate" }));++const readRegistry: any = [+ ["read_tool", { description: "r", inputSchema: {}, execute: readExecute }]+];+const mutateRegistry: any = [+ ["mutate_tool", { description: "m", inputSchema: {}, mutates: true, execute: mutateExecute }]+];++vi.mock("../llm/tools/index.js", () => ({+ allToolRegistries: [readRegistry, mutateRegistry]+}));++const { createMcpServer } = await import("./mcp_server.js");++beforeEach(() => {+ registered.length = 0;+ clsCalls.init = 0;+ clsCalls.set.length = 0;+ vi.clearAllMocks();+ mockSql.transactional.mockImplementation((cb: () => unknown) => cb());+});++afterEach(() => vi.restoreAllMocks());++describe("createMcpServer", () => {+ it("registers every tool from all registries", () => {+ const server = createMcpServer();++ expect(server).toBeInstanceOf(FakeMcpServer);+ expect((server as any).info).toMatchObject({ name: "trilium-notes", version: "9.9.9-test" });+ expect(registered.map((r) => r.name)).toEqual(["read_tool", "mutate_tool"]);+ });++ it("runs a read-only tool inside CLS without a transaction", () => {+ createMcpServer();+ const read = registered.find((r) => r.name === "read_tool")!;++ const result = read.callback({ foo: 1 });++ expect(readExecute).toHaveBeenCalledWith({ foo: 1 });+ expect(mockSql.transactional).not.toHaveBeenCalled();+ expect(mockCls.set).toHaveBeenCalledWith("componentId", "mcp");+ expect(result).toEqual({ content: [{ type: "text", text: JSON.stringify({ ok: "read" }) }] });+ });++ it("runs a mutating tool inside CLS + a transaction", () => {+ createMcpServer();+ const mutate = registered.find((r) => r.name === "mutate_tool")!;++ const result = mutate.callback({ bar: 2 });++ expect(mutateExecute).toHaveBeenCalledWith({ bar: 2 });+ expect(mockSql.transactional).toHaveBeenCalledTimes(1);+ expect(result).toEqual({ content: [{ type: "text", text: JSON.stringify({ ok: "mutate" }) }] });+ });+});diff --git a/apps/server/src/services/ocr/ocr_service.spec.ts b/apps/server/src/services/ocr/ocr_service.spec.tsindex a310904006..f9665841fa 100644--- a/apps/server/src/services/ocr/ocr_service.spec.ts+++ b/apps/server/src/services/ocr/ocr_service.spec.ts@@ -140,6 +140,95 @@ describe('OCRService', () => {await expect(ocrService.extractTextFromFile(mockImageBuffer, 'image/jpeg')).rejects.toThrow('OCR recognition failed');expect(mockLog.error).toHaveBeenCalledWith('Image OCR text extraction failed: Error: OCR recognition failed');});++ it('should throw when no processor matches the MIME type', async () => {+ await expect(+ ocrService.extractTextFromFile(mockImageBuffer, 'text/plain')+ ).rejects.toThrow('No processor found for MIME type: text/plain');+ });+ });++ describe('resolveOcrLanguage', () => {+ it('returns the explicit language when provided', () => {+ expect(ocrService.resolveOcrLanguage('note123', 'fra')).toBe('fra');+ });++ it('uses the note language label when no explicit language', () => {+ mockBecca.getNote.mockReturnValue({+ getLabelValue: vi.fn().mockReturnValue('de')+ });+ expect(ocrService.resolveOcrLanguage('note123')).toBe('deu');+ });++ it('falls through note label when it maps to no tesseract code', () => {+ mockBecca.getNote.mockReturnValue({+ getLabelValue: vi.fn().mockReturnValue('not-a-locale')+ });+ mockOptions.getOption.mockImplementation((name: string) => {+ if (name === 'languages') return '["en","de"]';+ return '';+ });+ expect(ocrService.resolveOcrLanguage('note123')).toBe('eng+deu');+ });++ it('uses enabled content languages (deduplicated) when no note label', () => {+ mockBecca.getNote.mockReturnValue({ getLabelValue: vi.fn().mockReturnValue(null) });+ mockOptions.getOption.mockImplementation((name: string) => {+ if (name === 'languages') return '["en","en-GB","de"]';+ return '';+ });+ expect(ocrService.resolveOcrLanguage('note123')).toBe('eng+deu');+ });++ it('falls back to UI locale when the enabled languages list is empty', () => {+ mockBecca.getNote.mockReturnValue({ getLabelValue: vi.fn().mockReturnValue(null) });+ mockOptions.getOption.mockImplementation((name: string) => {+ if (name === 'languages') return '[]';+ if (name === 'locale') return 'fr';+ return '';+ });+ expect(ocrService.resolveOcrLanguage('note123')).toBe('fra');+ });++ it('defaults the languages list to empty when the option is unset', () => {+ mockBecca.getNote.mockReturnValue({ getLabelValue: vi.fn().mockReturnValue(null) });+ mockOptions.getOption.mockImplementation((name: string) => {+ if (name === 'languages') return null;+ if (name === 'locale') return 'fr';+ return '';+ });+ expect(ocrService.resolveOcrLanguage('note123')).toBe('fra');+ });++ it('falls back to UI locale when no enabled languages resolve', () => {+ mockBecca.getNote.mockReturnValue({ getLabelValue: vi.fn().mockReturnValue(null) });+ mockOptions.getOption.mockImplementation((name: string) => {+ if (name === 'languages') return '["not-a-locale"]';+ if (name === 'locale') return 'fr';+ return '';+ });+ expect(ocrService.resolveOcrLanguage('note123')).toBe('fra');+ });++ it('falls back to eng when nothing resolves and parsing throws', () => {+ mockBecca.getNote.mockReturnValue(undefined);+ mockOptions.getOption.mockImplementation((name: string) => {+ if (name === 'languages') return 'not json';+ if (name === 'locale') return 'not-a-locale';+ return '';+ });+ expect(ocrService.resolveOcrLanguage()).toBe('eng');+ });++ it('falls back to eng when the UI locale option is empty', () => {+ mockBecca.getNote.mockReturnValue(undefined);+ mockOptions.getOption.mockImplementation((name: string) => {+ if (name === 'languages') return '[]';+ if (name === 'locale') return '';+ return '';+ });+ expect(ocrService.resolveOcrLanguage()).toBe('eng');+ });});describe('storeOCRResult', () => {@@ -271,6 +360,63 @@ describe('OCRService', () => {expect(result).toBe(null);expect(mockLog.info).toHaveBeenCalledWith('note note123 has unsupported MIME type text/plain for text extraction, skipping');});++ it('should skip notes that are not images or files', async () => {+ (mockNote as any).type = 'text';++ const result = await ocrService.processNoteOCR('note123');++ expect(result).toBe(null);+ expect(mockLog.info).toHaveBeenCalledWith('note note123 is not an image or file, skipping OCR');+ (mockNote as any).type = 'image';+ });++ it('should skip when OCR result already stored and not forcing', async () => {+ mockSql.getRow.mockReturnValue({ textRepresentation: 'existing' });++ const result = await ocrService.processNoteOCR('note123');++ expect(result).toBe(null);+ expect(mockLog.info).toHaveBeenCalledWith('OCR already exists for note note123, skipping');+ });++ it('should throw when content is not a Buffer', async () => {+ mockNote.getContent.mockReturnValue('not a buffer');++ await expect(ocrService.processNoteOCR('note123')).rejects.toThrow(+ 'Cannot get content for note note123'+ );+ expect(mockLog.error).toHaveBeenCalledWith(+ expect.stringContaining('Failed to process OCR for note note123')+ );+ });++ it('processes a note whose blobId is undefined', async () => {+ (mockNote as any).blobId = undefined;+ mockSql.getRow.mockReturnValue(null);+ mockWorker.recognize.mockResolvedValue({+ data: { text: 'text', confidence: 90, words: [] }+ });++ const result = await ocrService.processNoteOCR('note123');++ expect(result?.text).toBe('text');+ expect(mockLog.error).toHaveBeenCalledWith('Cannot store OCR result: blobId is undefined');+ (mockNote as any).blobId = 'blob123';+ });++ it('skips storing the blob entity change when blob is missing', async () => {+ mockSql.getRow.mockReturnValue(null);+ mockBecca.getBlob.mockReturnValue(null);+ mockWorker.recognize.mockResolvedValue({+ data: { text: 'text', confidence: 90, words: [] }+ });++ const result = await ocrService.processNoteOCR('note123');++ expect(result?.text).toBe('text');+ expect(mockEntityChangesService.putEntityChange).not.toHaveBeenCalled();+ });});describe('processAttachmentOCR', () => {@@ -392,6 +538,61 @@ describe('OCRService', () => {expect.stringContaining('Failed to get blobs needing OCR'));});++ it('returns failure when collecting blobs throws unexpectedly', async () => {+ vi.spyOn(ocrService, 'getBlobsNeedingOCR').mockImplementation(() => {+ throw new Error('unexpected');+ });++ const result = await ocrService.startBatchProcessing();++ expect(result).toEqual({ success: false, message: 'unexpected' });+ expect(mockLog.error).toHaveBeenCalledWith(+ expect.stringContaining('Failed to start batch processing: unexpected')+ );+ });++ it('stringifies non-Error failures when collecting blobs throws', async () => {+ vi.spyOn(ocrService, 'getBlobsNeedingOCR').mockImplementation(() => {+ throw 'plain string';+ });++ const result = await ocrService.startBatchProcessing();++ expect(result).toEqual({ success: false, message: 'plain string' });+ });++ it('logs a stringified non-Error when the background batch rejects', async () => {+ vi.useFakeTimers();+ mockBlobsNeedingOCR([{ entityId: 'note1', mimeType: 'image/jpeg' }]);+ vi.spyOn(ocrService as any, 'processBlobs').mockRejectedValue('plain reject');++ await ocrService.startBatchProcessing();+ await vi.runAllTimersAsync();+ vi.useRealTimers();++ expect(mockLog.error).toHaveBeenCalledWith(+ expect.stringContaining('Batch processing failed: plain reject')+ );+ });++ it('logs when the background batch fails', async () => {+ vi.useFakeTimers();+ mockBlobsNeedingOCR([{ entityId: 'note1', mimeType: 'image/jpeg' }]);+ vi.spyOn(ocrService as any, 'processBlobs').mockRejectedValue(+ new Error('batch boom')+ );++ const result = await ocrService.startBatchProcessing();+ expect(result).toEqual({ success: true });++ await vi.runAllTimersAsync();+ vi.useRealTimers();++ expect(mockLog.error).toHaveBeenCalledWith(+ expect.stringContaining('Batch processing failed: batch boom')+ );+ });});describe('getBatchProgress', () => {@@ -442,5 +643,90 @@ describe('OCRService', () => {expect(mockLog.info).not.toHaveBeenCalledWith('Batch OCR processing cancelled');});});++ describe('processBlobs (background)', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ (ocrService as any).batchProcessingState = {+ inProgress: true, total: 2, processed: 0+ };+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('processes notes and attachments, logging per-item errors', async () => {+ const processNote = vi+ .spyOn(ocrService, 'processNoteOCR')+ .mockResolvedValue(null);+ const processAttachment = vi+ .spyOn(ocrService, 'processAttachmentOCR')+ .mockRejectedValue(new Error('boom'));++ const promise = (ocrService as any).processBlobs([+ { entityType: 'note', entityId: 'n1' },+ { entityType: 'attachment', entityId: 'a1' }+ ]);++ await vi.runAllTimersAsync();+ await promise;++ expect(processNote).toHaveBeenCalledWith('n1');+ expect(processAttachment).toHaveBeenCalledWith('a1');+ expect(mockLog.error).toHaveBeenCalledWith(+ expect.stringContaining('Failed to process OCR for attachment a1')+ );+ expect((ocrService as any).batchProcessingState.processed).toBe(2);+ });++ it('stops the loop when processing is cancelled mid-way', async () => {+ vi.spyOn(ocrService, 'processNoteOCR').mockImplementation(async () => {+ (ocrService as any).batchProcessingState.inProgress = false;+ return null;+ });+ const processAttachment = vi.spyOn(ocrService, 'processAttachmentOCR');++ const promise = (ocrService as any).processBlobs([+ { entityType: 'note', entityId: 'n1' },+ { entityType: 'attachment', entityId: 'a1' }+ ]);++ await vi.runAllTimersAsync();+ await promise;++ expect(processAttachment).not.toHaveBeenCalled();+ expect((ocrService as any).batchProcessingState.processed).toBe(1);+ });+ });++ describe('getBlobsNeedingOCR', () => {+ it('returns combined note and attachment rows', () => {+ mockSql.getRows.mockReturnValueOnce([+ { blobId: 'b1', mimeType: 'image/png', entityId: 'n1' }+ ]);+ mockSql.getRows.mockReturnValueOnce([+ { blobId: 'b2', mimeType: 'image/jpeg', entityId: 'a1' }+ ]);++ const result = ocrService.getBlobsNeedingOCR();++ expect(result).toEqual([+ { blobId: 'b1', mimeType: 'image/png', entityId: 'n1', entityType: 'note' },+ { blobId: 'b2', mimeType: 'image/jpeg', entityId: 'a1', entityType: 'attachment' }+ ]);+ });++ it('returns empty array and logs when the query fails', () => {+ mockSql.getRows.mockImplementation(() => {+ throw new Error('db down');+ });++ expect(ocrService.getBlobsNeedingOCR()).toEqual([]);+ expect(mockLog.error).toHaveBeenCalledWith(+ expect.stringContaining('Failed to get blobs needing OCR')+ );+ });+ });});});diff --git a/apps/server/src/services/ocr/processors/image_processor.spec.ts b/apps/server/src/services/ocr/processors/image_processor.spec.tsindex 43ccc5c5a3..a8c654b147 100644--- a/apps/server/src/services/ocr/processors/image_processor.spec.ts+++ b/apps/server/src/services/ocr/processors/image_processor.spec.ts@@ -1,37 +1,242 @@-import fs from 'fs';-import path from 'path';-import { describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-// Mock dependencies-vi.mock('../../data_dir.js', () => ({- default: {- OCR_CACHE_DIR: '/tmp/trilium-ocr-test-cache'- }+// Mock Tesseract.js so no real OCR model is ever loaded.+const mockWorker = {+ recognize: vi.fn(),+ terminate: vi.fn().mockResolvedValue(undefined)+};++const mockTesseract = {+ createWorker: vi.fn()+};++vi.mock('tesseract.js', () => ({+ default: mockTesseract}));-vi.mock('../../log.js', () => ({+// Avoid touching the real filesystem for the worker cache directory.+vi.mock('fs', () => ({default: {- info: vi.fn(),- error: vi.fn()+ mkdirSync: vi.fn()}}));-vi.mock('../../options.js', () => ({+vi.mock('../../data_dir.js', () => ({default: {- getOption: vi.fn().mockReturnValue('0')+ OCR_CACHE_DIR: '/tmp/trilium-ocr-test-cache'}}));-import { ImageProcessor } from './image_processor.js';+const mockOptions = {+ getOption: vi.fn()+};++const mockLog = {+ info: vi.fn(),+ error: vi.fn()+};++vi.mock('@triliumnext/core', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@triliumnext/core')>();+ return {+ ...actual,+ options: mockOptions,+ getLog: () => mockLog+ };+});++let ImageProcessor: typeof import('./image_processor.js').ImageProcessor;++beforeEach(async () => {+ vi.clearAllMocks();+ mockOptions.getOption.mockReturnValue('0');+ mockTesseract.createWorker.mockResolvedValue(mockWorker);+ ({ ImageProcessor } = await import('./image_processor.js'));+});++afterEach(() => {+ vi.restoreAllMocks();+});++const buffer = Buffer.from('fake-image');describe('ImageProcessor', () => {- const processor = new ImageProcessor();- const sampleImagePath = path.join(__dirname, 'samples', 'image.png');+ it('reports the MIME types it can process', () => {+ const processor = new ImageProcessor();++ expect(processor.canProcess('image/PNG')).toBe(true);+ expect(processor.canProcess('image/jpeg')).toBe(true);+ expect(processor.canProcess('application/pdf')).toBe(false);+ expect(processor.getSupportedMimeTypes()).toContain('image/png');+ expect(processor.getProcessingType()).toBe('image');+ });++ it('extracts text and returns it untrimmed-confidence when no threshold is set', async () => {+ const processor = new ImageProcessor();+ mockWorker.recognize.mockResolvedValue({+ data: { text: ' hello world ', confidence: 88, words: [] }+ });++ const result = await processor.extractText(buffer, { language: 'eng' });++ expect(result.text).toBe('hello world');+ expect(result.confidence).toBeCloseTo(0.88);+ expect(result.language).toBe('eng');+ expect(result.pageCount).toBe(1);+ expect(mockTesseract.createWorker).toHaveBeenCalledWith(+ 'eng',+ 1,+ expect.objectContaining({ cachePath: '/tmp/trilium-ocr-test-cache' })+ );+ });++ it('defaults the language to eng when none is supplied', async () => {+ const processor = new ImageProcessor();+ mockWorker.recognize.mockResolvedValue({+ data: { text: 'x', confidence: 50, words: [] }+ });++ await processor.extractText(buffer);++ expect(mockTesseract.createWorker).toHaveBeenCalledWith('eng', 1, expect.anything());+ });++ it('reuses the worker for the same language and recreates it when the language changes', async () => {+ const processor = new ImageProcessor();+ mockWorker.recognize.mockResolvedValue({+ data: { text: 'a', confidence: 50, words: [] }+ });++ await processor.extractText(buffer, { language: 'eng' });+ await processor.extractText(buffer, { language: 'eng' });+ expect(mockTesseract.createWorker).toHaveBeenCalledTimes(1);+ expect(mockWorker.terminate).not.toHaveBeenCalled();++ await processor.extractText(buffer, { language: 'deu' });+ expect(mockWorker.terminate).toHaveBeenCalledTimes(1);+ expect(mockTesseract.createWorker).toHaveBeenCalledTimes(2);+ });++ it('invokes the recognizing-text logger callback', async () => {+ const processor = new ImageProcessor();+ mockWorker.recognize.mockResolvedValue({+ data: { text: 'a', confidence: 50, words: [] }+ });++ await processor.extractText(buffer, { language: 'eng' });++ const config = mockTesseract.createWorker.mock.calls[0][2];+ config.logger({ status: 'recognizing text', progress: 0.5 });+ config.logger({ status: 'loading', progress: 0.1 });++ expect(mockLog.info).toHaveBeenCalledWith(+ expect.stringContaining('Image OCR progress')+ );+ });++ it('propagates and logs recognition errors', async () => {+ const processor = new ImageProcessor();+ mockWorker.recognize.mockRejectedValue(new Error('recognize failed'));++ await expect(processor.extractText(buffer, { language: 'eng' })).rejects.toThrow(+ 'recognize failed'+ );+ expect(mockLog.error).toHaveBeenCalledWith(+ expect.stringContaining('Image OCR text extraction failed')+ );+ });++ describe('confidence filtering', () => {+ it('keeps only words above the configured threshold', async () => {+ mockOptions.getOption.mockReturnValue('0.8');+ const processor = new ImageProcessor();+ mockWorker.recognize.mockResolvedValue({+ data: {+ text: 'good bad good',+ confidence: 70,+ words: [+ { text: 'good', confidence: 90 },+ { text: 'bad', confidence: 50 },+ { text: 'good', confidence: 95 }+ ]+ }+ });++ const result = await processor.extractText(buffer, { language: 'eng' });++ expect(result.text).toBe('good good');+ expect(result.confidence).toBeCloseTo((0.9 + 0.95) / 2);+ });++ it('returns empty confidence when no words pass the threshold', async () => {+ mockOptions.getOption.mockReturnValue('0.99');+ const processor = new ImageProcessor();+ mockWorker.recognize.mockResolvedValue({+ data: {+ text: 'low',+ confidence: 10,+ words: [{ text: 'low', confidence: 10 }]+ }+ });++ const result = await processor.extractText(buffer, { language: 'eng' });++ expect(result.text).toBe('');+ expect(result.confidence).toBe(0);+ });++ it('handles an empty word array with a threshold set', async () => {+ mockOptions.getOption.mockReturnValue('0.5');+ const processor = new ImageProcessor();+ mockWorker.recognize.mockResolvedValue({+ data: { text: 'ignored', confidence: 80, words: [] }+ });++ const result = await processor.extractText(buffer, { language: 'eng' });++ expect(result.text).toBe('');+ expect(result.confidence).toBe(0);+ });++ it('falls back to overall confidence when there is no word-level data', async () => {+ mockOptions.getOption.mockReturnValue('0.5');+ const processor = new ImageProcessor();+ mockWorker.recognize.mockResolvedValue({+ data: { text: ' whole text ', confidence: 80, words: undefined }+ });++ const result = await processor.extractText(buffer, { language: 'eng' });++ expect(result.text).toBe('whole text');+ expect(result.confidence).toBeCloseTo(0.8);+ });++ it('drops all text via the fallback when overall confidence is too low', async () => {+ mockOptions.getOption.mockReturnValue('0.9');+ const processor = new ImageProcessor();+ mockWorker.recognize.mockResolvedValue({+ data: { text: 'whole text', confidence: 40, words: undefined }+ });++ const result = await processor.extractText(buffer, { language: 'eng' });++ expect(result.text).toBe('');+ expect(result.confidence).toBeCloseTo(0.4);+ expect(mockLog.info).toHaveBeenCalledWith(+ expect.stringContaining('Entire text filtered out')+ );+ });++ it('defaults the threshold to 0 when the option is null', async () => {+ mockOptions.getOption.mockReturnValue(null);+ const processor = new ImageProcessor();+ mockWorker.recognize.mockResolvedValue({+ data: { text: 'kept', confidence: 30, words: [{ text: 'kept', confidence: 30 }] }+ });- it('should extract text from the sample image', async () => {- const imageBuffer = fs.readFileSync(sampleImagePath);+ const result = await processor.extractText(buffer, { language: 'eng' });- const result = await processor.extractText(imageBuffer, { language: 'eng' });- expect(result.text).toContain('TriliumNext');- }, 60000);+ expect(result.text).toBe('kept');+ });+ });});diff --git a/apps/server/src/services/ocr/processors/office_processor.spec.ts b/apps/server/src/services/ocr/processors/office_processor.spec.tsnew file mode 100644index 0000000000..c3e10e74cf--- /dev/null+++ b/apps/server/src/services/ocr/processors/office_processor.spec.ts@@ -0,0 +1,88 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const mockParseOffice = vi.fn();++vi.mock('officeparser', () => ({+ OfficeParser: {+ parseOffice: mockParseOffice+ }+}));++const mockLog = { info: vi.fn(), error: vi.fn() };++vi.mock('@triliumnext/core', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@triliumnext/core')>();+ return {+ ...actual,+ getLog: () => mockLog+ };+});++let OfficeProcessor: typeof import('./office_processor.js').OfficeProcessor;++const DOCX = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';+const ODT = 'application/vnd.oasis.opendocument.text';++beforeEach(async () => {+ vi.clearAllMocks();+ ({ OfficeProcessor } = await import('./office_processor.js'));+});++afterEach(() => {+ vi.restoreAllMocks();+});++const buffer = Buffer.from('PK fake office');++describe('OfficeProcessor', () => {+ it('reports the MIME types it can process', () => {+ const processor = new OfficeProcessor();++ expect(processor.canProcess(DOCX)).toBe(true);+ expect(processor.canProcess(ODT)).toBe(true);+ expect(processor.canProcess('application/pdf')).toBe(false);+ expect(processor.getSupportedMimeTypes()).toContain(DOCX);+ expect(processor.getProcessingType()).toBe('office');+ });++ it('extracts text and reports high confidence when text is present', async () => {+ const processor = new OfficeProcessor();+ mockParseOffice.mockResolvedValue({ toText: () => ' document body ' });++ const result = await processor.extractText(buffer, { mimeType: DOCX, language: 'deu' });++ expect(result.text).toBe('document body');+ expect(result.confidence).toBe(0.99);+ expect(result.pageCount).toBe(1);+ expect(result.language).toBe('deu');+ expect(mockParseOffice).toHaveBeenCalledWith(buffer, expect.any(Object));+ });++ it('reports zero confidence and defaults language when no text is extracted', async () => {+ const processor = new OfficeProcessor();+ mockParseOffice.mockResolvedValue({ toText: () => ' ' });++ const result = await processor.extractText(buffer, { mimeType: ODT });++ expect(result.text).toBe('');+ expect(result.confidence).toBe(0);+ expect(result.language).toBe('eng');+ });++ it('throws when the MIME type is missing', async () => {+ const processor = new OfficeProcessor();++ await expect(processor.extractText(buffer, {})).rejects.toThrow(+ 'Unsupported MIME type for Office processor: undefined'+ );+ expect(mockParseOffice).not.toHaveBeenCalled();+ });++ it('throws when the MIME type is not supported', async () => {+ const processor = new OfficeProcessor();++ await expect(+ processor.extractText(buffer, { mimeType: 'application/pdf' })+ ).rejects.toThrow('Unsupported MIME type for Office processor: application/pdf');+ });+});diff --git a/apps/server/src/services/ocr/processors/pdf_processor.spec.ts b/apps/server/src/services/ocr/processors/pdf_processor.spec.tsnew file mode 100644index 0000000000..14ca32d18c--- /dev/null+++ b/apps/server/src/services/ocr/processors/pdf_processor.spec.ts@@ -0,0 +1,73 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const mockGetDocumentProxy = vi.fn();+const mockExtractText = vi.fn();++vi.mock('unpdf', () => ({+ getDocumentProxy: mockGetDocumentProxy,+ extractText: mockExtractText+}));++const mockLog = { info: vi.fn(), error: vi.fn() };++vi.mock('@triliumnext/core', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@triliumnext/core')>();+ return {+ ...actual,+ getLog: () => mockLog+ };+});++let PDFProcessor: typeof import('./pdf_processor.js').PDFProcessor;++beforeEach(async () => {+ vi.clearAllMocks();+ mockGetDocumentProxy.mockResolvedValue({ proxy: true });+ ({ PDFProcessor } = await import('./pdf_processor.js'));+});++afterEach(() => {+ vi.restoreAllMocks();+});++const buffer = Buffer.from('%PDF-1.4 fake');++describe('PDFProcessor', () => {+ it('reports the MIME types it can process', () => {+ const processor = new PDFProcessor();++ expect(processor.canProcess('application/PDF')).toBe(true);+ expect(processor.canProcess('image/png')).toBe(false);+ expect(processor.getSupportedMimeTypes()).toEqual(['application/pdf']);+ expect(processor.getProcessingType()).toBe('pdf');+ });++ it('extracts merged text and reports high confidence when text is present', async () => {+ const processor = new PDFProcessor();+ mockExtractText.mockResolvedValue({ totalPages: 3, text: ' hello pdf ' });++ const result = await processor.extractText(buffer, { language: 'fra' });++ expect(result.text).toBe('hello pdf');+ expect(result.confidence).toBe(0.99);+ expect(result.pageCount).toBe(3);+ expect(result.language).toBe('fra');+ expect(mockExtractText).toHaveBeenCalledWith(+ { proxy: true },+ { mergePages: true }+ );+ // buffer is wrapped into a Uint8Array before being passed to unpdf+ expect(mockGetDocumentProxy).toHaveBeenCalledWith(expect.any(Uint8Array));+ });++ it('reports zero confidence and defaults language when no text is extracted', async () => {+ const processor = new PDFProcessor();+ mockExtractText.mockResolvedValue({ totalPages: 1, text: ' ' });++ const result = await processor.extractText(buffer);++ expect(result.text).toBe('');+ expect(result.confidence).toBe(0);+ expect(result.language).toBe('eng');+ });+});diff --git a/apps/server/src/services/open_id.spec.ts b/apps/server/src/services/open_id.spec.tsnew file mode 100644index 0000000000..3f8b701e89--- /dev/null+++ b/apps/server/src/services/open_id.spec.ts@@ -0,0 +1,164 @@+import { cls, options } from "@triliumnext/core";+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";++import config from "./config.js";+import openIDEncryption from "./encryption/open_id_encryption.js";+import openID from "./open_id.js";+import sql from "./sql.js";+import sqlInit from "./sql_init.js";++const mfa = config.MultiFactorAuthentication;+const originalMfa = { ...mfa };++function setOauthConfig(complete: boolean) {+ mfa.oauthBaseUrl = complete ? "https://app.example.com" : "";+ mfa.oauthClientId = complete ? "client-id" : "";+ mfa.oauthClientSecret = complete ? "client-secret" : "";+ mfa.oauthIssuerBaseUrl = "https://issuer.example.com";+ mfa.oauthIssuerName = "Acme";+ mfa.oauthIssuerIcon = "icon.png";+}++describe("open_id", () => {+ beforeAll(async () => {+ sqlInit.initializeDb();+ await sqlInit.dbReady;+ });++ afterEach(() => {+ Object.assign(mfa, originalMfa);+ vi.restoreAllMocks();+ });++ it("checkOpenIDConfig reports each missing oauth variable", () => {+ setOauthConfig(false);+ expect(openID.isOpenIDEnabled()).toBe(false);+ // with all three blank, getOAuthStatus surfaces them+ const status = openID.getOAuthStatus();+ expect(status.success).toBe(true);+ expect(status.missingVars).toEqual(+ expect.arrayContaining(["oauthBaseUrl", "oauthClientId", "oauthClientSecret"])+ );+ expect(status.enabled).toBe(false);+ });++ it("isOpenIDEnabled requires full config and mfaMethod=oauth", () => {+ setOauthConfig(true);+ cls.init(() => options.setOption("mfaMethod", "totp"));+ expect(openID.isOpenIDEnabled()).toBe(false); // method not oauth++ cls.init(() => options.setOption("mfaMethod", "oauth"));+ expect(openID.isOpenIDEnabled()).toBe(true);+ expect(openID.getOAuthStatus().missingVars).toEqual([]);+ });++ it("exposes issuer name/icon from config", () => {+ setOauthConfig(true);+ expect(openID.getSSOIssuerName()).toBe("Acme");+ expect(openID.getSSOIssuerIcon()).toBe("icon.png");+ });++ it("isUserSaved and getOAuthStatus read user_data", () => {+ cls.init(() => {+ sql.transactional(() => {+ sql.execute("DELETE FROM user_data");+ sql.upsert("user_data", "tmpID", {+ tmpID: 0,+ isSetup: "true",+ username: "Alice",+ email: "[email protected]"+ });+ });+ });+ expect(openID.isUserSaved()).toBe(true);+ const status = openID.getOAuthStatus();+ expect(status.name).toBe("Alice");+ expect(status.email).toBe("[email protected]");+ });++ it("clearSavedUser empties user_data and clears the option", () => {+ const result = cls.init(() => openID.clearSavedUser());+ expect(result.success).toBe(true);+ expect(openID.isUserSaved()).toBe(false);+ // clearSavedUser sets the option to a falsy value+ expect(options.getOptionOrNull("userSubjectIdentifierSaved")).toBeFalsy();+ });++ describe("isTokenValid", () => {+ const fakeRes = {} as never;+ const next = (() => {}) as never;++ it("reports 'not set up' when oidc is undefined", async () => {+ const req = { oidc: undefined } as never;+ const res = await openID.isTokenValid(req, fakeRes, next);+ expect(res.success).toBe(false);+ expect(typeof res.user).toBe("boolean");+ });++ it("reports valid when fetchUserInfo succeeds", async () => {+ const req = { oidc: { fetchUserInfo: vi.fn().mockResolvedValue({}) } } as never;+ const res = await openID.isTokenValid(req, fakeRes, next);+ expect(res.success).toBe(true);+ });++ it("reports invalid when fetchUserInfo throws", async () => {+ const req = {+ oidc: { fetchUserInfo: vi.fn().mockRejectedValue(new Error("nope")) }+ } as never;+ const res = await openID.isTokenValid(req, fakeRes, next);+ expect(res.success).toBe(false);+ });+ });++ describe("generateOAuthConfig.afterCallback", () => {+ function buildConfig() {+ setOauthConfig(true);+ return openID.generateOAuthConfig();+ }++ it("wires routes and credentials from config", () => {+ const cfg = buildConfig();+ expect(cfg.baseURL).toBe("https://app.example.com");+ expect(cfg.clientID).toBe("client-id");+ expect(cfg.routes.callback).toBe("/callback");+ expect(typeof cfg.afterCallback).toBe("function");+ });++ it("returns the session unchanged when the DB is not initialized", async () => {+ const cfg = buildConfig();+ const spy = vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(false);+ const session = { marker: 1 } as never;+ const result = await cfg.afterCallback({ oidc: { user: {} } } as never, {} as never, session);+ expect(result).toBe(session);+ spy.mockRestore();+ });++ it("returns the session unchanged when there is no user", async () => {+ const cfg = buildConfig();+ const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});+ const session = { marker: 2 } as never;+ const result = await cfg.afterCallback({ oidc: { user: undefined } } as never, {} as never, session);+ expect(result).toBe(session);+ logSpy.mockRestore();+ });++ it("saves the user and sets the session login flags", async () => {+ cls.init(() => {+ sql.transactional(() => sql.execute("DELETE FROM user_data"));+ });+ const cfg = buildConfig();+ const saveSpy = vi.spyOn(openIDEncryption, "saveUser").mockReturnValue(true);+ const req = {+ oidc: { user: { sub: "sub-1", name: "Alice", email: "[email protected]" } },+ session: {} as Record<string, unknown>+ } as never;+ const session = { marker: 3 } as never;++ const result = await cfg.afterCallback(req, {} as never, session);++ expect(saveSpy).toHaveBeenCalledWith("sub-1", "Alice", "[email protected]");+ expect((req as { session: { loggedIn: boolean } }).session.loggedIn).toBe(true);+ expect(result).toBe(session);+ });+ });+});diff --git a/apps/server/src/services/port.spec.ts b/apps/server/src/services/port.spec.tsnew file mode 100644index 0000000000..e7bdbe1b5a--- /dev/null+++ b/apps/server/src/services/port.spec.ts@@ -0,0 +1,69 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++describe("port", () => {+ let originalEnv: NodeJS.ProcessEnv;++ beforeEach(() => {+ originalEnv = { ...process.env };+ delete process.env.TRILIUM_PORT;+ });++ afterEach(() => {+ process.env = originalEnv;+ vi.resetModules();+ vi.doUnmock("./config.js");+ vi.doUnmock("./utils.js");+ vi.doUnmock("./data_dir.js");+ vi.restoreAllMocks();+ });++ async function loadPort(opts: { isElectron: boolean; isDev: boolean; configPort: string }) {+ vi.resetModules();+ vi.doMock("./utils.js", () => ({ isDev: opts.isDev, isElectron: opts.isElectron }));+ vi.doMock("./config.js", () => ({ default: { Network: { port: opts.configPort } } }));+ vi.doMock("./data_dir.js", () => ({ default: { CONFIG_INI_PATH: "/test/config.ini" } }));+ return (await import("./port.js")).default;+ }++ it("uses TRILIUM_PORT env var when valid", async () => {+ process.env.TRILIUM_PORT = "8123";+ expect(await loadPort({ isElectron: false, isDev: false, configPort: "3000" })).toBe(8123);+ });++ it("exits on an invalid TRILIUM_PORT env var", async () => {+ process.env.TRILIUM_PORT = "not-a-number";+ const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {+ throw new Error("exit");+ }) as never);+ vi.spyOn(console, "log").mockImplementation(() => {});++ await expect(loadPort({ isElectron: false, isDev: false, configPort: "3000" })).rejects.toThrow("exit");+ expect(exitSpy).toHaveBeenCalledWith(-1);+ });++ it("uses the Electron dev default port", async () => {+ expect(await loadPort({ isElectron: true, isDev: true, configPort: "3000" })).toBe(37740);+ });++ it("uses the Electron prod default port", async () => {+ expect(await loadPort({ isElectron: true, isDev: false, configPort: "3000" })).toBe(37840);+ });++ it("falls back to the config port", async () => {+ expect(await loadPort({ isElectron: false, isDev: false, configPort: "9000" })).toBe(9000);+ });++ it("defaults to 3000 when the config port is empty", async () => {+ expect(await loadPort({ isElectron: false, isDev: false, configPort: "" })).toBe(3000);+ });++ it("exits on an out-of-range config port", async () => {+ const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {+ throw new Error("exit");+ }) as never);+ vi.spyOn(console, "log").mockImplementation(() => {});++ await expect(loadPort({ isElectron: false, isDev: false, configPort: "70000" })).rejects.toThrow("exit");+ expect(exitSpy).toHaveBeenCalledWith(-1);+ });+});diff --git a/apps/server/src/services/request.spec.ts b/apps/server/src/services/request.spec.tsnew file mode 100644index 0000000000..2b7012d16a--- /dev/null+++ b/apps/server/src/services/request.spec.ts@@ -0,0 +1,433 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++type Handler = (e: any) => void;++interface FakeResponse {+ statusCode: number;+ statusMessage: string;+ headers: Record<string, any>;+ on(event: string, cb: Handler): FakeResponse;+ emitData(chunk: Buffer): void;+ emitEnd(): void;+}++interface FakeRequest {+ opts: any;+ endPayload: string | undefined;+ on(event: string, cb: Handler): FakeRequest;+ end(payload?: string): void;+ triggerError(err: any): void;+ triggerAbort(err: any): void;+ triggerResponse(response: FakeResponse): void;+}++/**+ * Shared mock state + fake http/https modules. Each `request()` call pushes a+ * FakeRequest whose registered handlers can be driven by the test to simulate+ * "response", "error" and "abort" events. Everything lives inside `vi.hoisted`+ * so the (hoisted) `vi.mock` factories can reference it.+ */+const { state, fakeHttp, fakeHttps, makeResponse, HttpProxyAgent, HttpsProxyAgent, getLogMock, getSyncProxyMock } =+ vi.hoisted(() => {+ const state: {+ requests: FakeRequest[];+ onEnd: ((req: FakeRequest) => void) | null;+ } = { requests: [], onEnd: null };++ function makeResponse(+ statusCode: number,+ statusMessage: string,+ headers: Record<string, any> = {}+ ): FakeResponse {+ const handlers: Record<string, Handler> = {};+ return {+ statusCode,+ statusMessage,+ headers,+ on(event, cb) {+ handlers[event] = cb;+ return this;+ },+ emitData(chunk) {+ handlers["data"]?.(chunk);+ },+ emitEnd() {+ handlers["end"]?.(undefined);+ }+ };+ }++ function makeRequest(opts: any): FakeRequest {+ const handlers: Record<string, Handler> = {};+ const req: FakeRequest = {+ opts,+ endPayload: undefined,+ on(event, cb) {+ handlers[event] = cb;+ return req;+ },+ end(payload) {+ req.endPayload = payload;+ state.onEnd?.(req);+ },+ triggerError: (err) => handlers["error"]?.(err),+ triggerAbort: (err) => handlers["abort"]?.(err),+ triggerResponse: (response) => handlers["response"]?.(response)+ };+ state.requests.push(req);+ return req;+ }++ const fakeHttp = { request: vi.fn((opts: any) => makeRequest(opts)) };+ const fakeHttps = { request: vi.fn((opts: any) => makeRequest(opts)) };++ const HttpProxyAgent = vi.fn(function (this: any, proxy: string) {+ this.proxy = proxy;+ this.kind = "http";+ });+ const HttpsProxyAgent = vi.fn(function (this: any, proxy: string) {+ this.proxy = proxy;+ this.kind = "https";+ });++ return {+ state,+ fakeHttp,+ fakeHttps,+ makeResponse,+ HttpProxyAgent,+ HttpsProxyAgent,+ getLogMock: { error: vi.fn(), info: vi.fn() },+ getSyncProxyMock: vi.fn(() => null as string | null)+ };+ });++vi.mock("http", () => fakeHttp);+vi.mock("https", () => fakeHttps);+vi.mock("http-proxy-agent", () => ({ HttpProxyAgent }));+vi.mock("https-proxy-agent", () => ({ HttpsProxyAgent }));+vi.mock("@triliumnext/core", () => ({+ getLog: () => getLogMock,+ sync_options: { getSyncProxy: getSyncProxyMock }+}));++import type { ExecOpts } from "@triliumnext/core";++import NodeRequestProvider from "./request.js";++function baseOpts(overrides: Partial<ExecOpts> = {}): any {+ return {+ method: "GET",+ url: "http://sync.example.com:8080/api/sync",+ proxy: null,+ timeout: 1000,+ ...overrides+ };+}++describe("NodeRequestProvider.exec", () => {+ let provider: NodeRequestProvider;++ beforeEach(() => {+ provider = new NodeRequestProvider();+ state.requests = [];+ state.onEnd = null;+ fakeHttp.request.mockClear();+ fakeHttps.request.mockClear();+ HttpProxyAgent.mockClear();+ HttpsProxyAgent.mockClear();+ getLogMock.error.mockClear();+ getLogMock.info.mockClear();+ getSyncProxyMock.mockReturnValue(null);+ });++ afterEach(() => {+ vi.clearAllMocks();+ });++ it("selects the http client and resolves parsed JSON on 200", async () => {+ state.onEnd = (req) => {+ const res = makeResponse(200, "OK");+ req.triggerResponse(res);+ res.emitData(Buffer.from('{"foo":'));+ res.emitData(Buffer.from('"bar"}'));+ res.emitEnd();+ };++ const result = await provider.exec<{ foo: string }>(baseOpts());+ expect(result).toEqual({ foo: "bar" });+ expect(fakeHttp.request).toHaveBeenCalledTimes(1);+ const sent = fakeHttp.request.mock.calls[0][0] as any;+ expect(sent.host).toBe("sync.example.com");+ expect(sent.port).toBe("8080");+ expect(sent.headers["Content-Type"]).toBe("application/json");+ });++ it("selects the https client based on the URL scheme", async () => {+ state.onEnd = (req) => {+ const res = makeResponse(204, "No Content");+ req.triggerResponse(res);+ res.emitEnd();+ };++ const result = await provider.exec(baseOpts({ url: "https://sync.example.com/x" }));+ expect(result).toBeNull(); // empty body → null+ expect(fakeHttps.request).toHaveBeenCalledTimes(1);+ });++ it("throws for an unrecognized protocol", async () => {+ await expect(provider.exec(baseOpts({ url: "ftp://example.com/x" }))).rejects.toThrow(+ /Unrecognized protocol/+ );+ });++ it("sends paging headers (text/plain) when pageCount > 1 and stores response cookies", async () => {+ const cookieJar = { header: "sid=1" };+ state.onEnd = (req) => {+ const res = makeResponse(201, "Created", { "set-cookie": "sid=2" });+ req.triggerResponse(res);+ res.emitData(Buffer.from("null"));+ res.emitEnd();+ };++ await provider.exec(+ baseOpts({+ method: "POST",+ body: { a: 1 },+ cookieJar,+ auth: { password: "secret" },+ paging: { pageCount: 3, pageIndex: 1, requestId: "req-1" }+ })+ );++ const sent = state.requests[0].opts;+ expect(sent.headers["Content-Type"]).toBe("text/plain");+ expect(sent.headers["pageCount"]).toBe(3);+ expect(sent.headers["Cookie"]).toBe("sid=1");+ // auth header is base64 of dummy:secret+ expect(sent.headers["trilium-cred"]).toBe(Buffer.from("dummy:secret").toString("base64"));+ // body object serialized+ expect(state.requests[0].endPayload).toBe(JSON.stringify({ a: 1 }));+ // response set-cookie stored back into the jar+ expect(cookieJar.header).toBe("sid=2");+ });++ it("passes a string body through unchanged and defaults the cookie header to empty", async () => {+ state.onEnd = (req) => {+ const res = makeResponse(200, "OK");+ req.triggerResponse(res);+ res.emitData(Buffer.from(""));+ res.emitEnd();+ };++ await provider.exec(baseOpts({ method: "POST", body: "raw-string" }));+ expect(state.requests[0].endPayload).toBe("raw-string");+ expect(state.requests[0].opts.headers["Cookie"]).toBe("");+ });++ it("rejects on a request error", async () => {+ state.onEnd = (req) => req.triggerError(new Error("ECONNRESET"));+ await expect(provider.exec(baseOpts())).rejects.toThrow(/ECONNRESET/);+ });++ it("rejects and logs when a successful response body is not valid JSON", async () => {+ state.onEnd = (req) => {+ const res = makeResponse(200, "OK");+ req.triggerResponse(res);+ res.emitData(Buffer.from("not json"));+ res.emitEnd();+ };++ await expect(provider.exec(baseOpts())).rejects.toThrow(/failed/);+ expect(getLogMock.error).toHaveBeenCalled();+ });++ it("rejects non-2xx responses using the JSON error message", async () => {+ state.onEnd = (req) => {+ const res = makeResponse(400, "Bad Request");+ req.triggerResponse(res);+ res.emitData(Buffer.from('{"message":"nope"}'));+ res.emitEnd();+ };++ await expect(provider.exec(baseOpts())).rejects.toThrow(/400 Bad Request nope/);+ });++ it("rejects non-2xx responses with an empty message when JSON has no message field", async () => {+ state.onEnd = (req) => {+ const res = makeResponse(403, "Forbidden");+ req.triggerResponse(res);+ res.emitData(Buffer.from("{}"));+ res.emitEnd();+ };++ const err = await provider.exec(baseOpts()).catch((e: Error) => e);+ // trailing space because the empty error message is appended+ expect((err as Error).message).toContain("403 Forbidden ");+ });++ it("rejects non-2xx responses falling back to a truncated body when not JSON", async () => {+ const longBody = "x".repeat(200);+ state.onEnd = (req) => {+ const res = makeResponse(500, "Server Error");+ req.triggerResponse(res);+ res.emitData(Buffer.from(longBody));+ res.emitEnd();+ };++ const err = await provider.exec(baseOpts()).catch((e: Error) => e);+ expect((err as Error).message).toContain("500 Server Error");+ expect((err as Error).message).toContain("x".repeat(100));+ expect((err as Error).message).not.toContain("x".repeat(101));+ });++ it("does not store cookies when the response has no set-cookie header", async () => {+ const cookieJar = { header: "sid=keep" };+ state.onEnd = (req) => {+ const res = makeResponse(200, "OK");+ req.triggerResponse(res);+ res.emitData(Buffer.from("null"));+ res.emitEnd();+ };+ await provider.exec(baseOpts({ cookieJar }));+ expect(cookieJar.header).toBe("sid=keep");+ });++ describe("proxy handling", () => {+ it("builds an HttpProxyAgent for http URLs with a proxy", async () => {+ state.onEnd = (req) => {+ const res = makeResponse(200, "OK");+ req.triggerResponse(res);+ res.emitData(Buffer.from("null"));+ res.emitEnd();+ };+ await provider.exec(baseOpts({ proxy: "http://proxy:3128" }));+ expect(HttpProxyAgent).toHaveBeenCalledWith("http://proxy:3128");+ expect(state.requests[0].opts.agent).toBeInstanceOf(HttpProxyAgent);+ });++ it("builds an HttpsProxyAgent for https URLs with a proxy", async () => {+ state.onEnd = (req) => {+ const res = makeResponse(200, "OK");+ req.triggerResponse(res);+ res.emitData(Buffer.from("null"));+ res.emitEnd();+ };+ await provider.exec(+ baseOpts({ url: "https://sync.example.com/x", proxy: "http://proxy:3128" })+ );+ expect(HttpsProxyAgent).toHaveBeenCalledWith("http://proxy:3128");+ });++ it("resets the special 'noproxy' value to no proxy agent", async () => {+ state.onEnd = (req) => {+ const res = makeResponse(200, "OK");+ req.triggerResponse(res);+ res.emitData(Buffer.from("null"));+ res.emitEnd();+ };+ await provider.exec(baseOpts({ proxy: "noproxy" }));+ expect(HttpProxyAgent).not.toHaveBeenCalled();+ expect(state.requests[0].opts.agent).toBeNull();+ });++ it("ignores a proxy when the target URL protocol is unsupported", async () => {+ // getProxyAgent parses the url; a non-http(s) protocol yields no agent.+ // getClient runs first and rejects unsupported protocols, so assert there.+ await expect(+ provider.exec(baseOpts({ url: "ftp://example.com/x", proxy: "http://proxy:3128" }))+ ).rejects.toThrow(/Unrecognized protocol/);+ });+ });++ it("rejects if the client throws synchronously while preparing the request", async () => {+ fakeHttp.request.mockImplementationOnce(() => {+ throw new Error("boom-prepare");+ });+ await expect(provider.exec(baseOpts())).rejects.toThrow(/boom-prepare/);+ });+});++describe("NodeRequestProvider.getImage", () => {+ let provider: NodeRequestProvider;++ beforeEach(() => {+ provider = new NodeRequestProvider();+ state.requests = [];+ state.onEnd = null;+ fakeHttp.request.mockClear();+ getSyncProxyMock.mockReturnValue(null);+ });++ it("downloads image bytes and resolves an ArrayBuffer", async () => {+ const bytes = Buffer.from([1, 2, 3, 4]);+ state.onEnd = (req) => {+ const res = makeResponse(200, "OK");+ req.triggerResponse(res);+ res.emitData(bytes);+ res.emitEnd();+ };++ const result = await provider.getImage("http://img.example.com/pic.png");+ expect(Buffer.from(result)).toEqual(bytes);+ });++ it("uses the configured sync proxy", async () => {+ getSyncProxyMock.mockReturnValue("http://proxy:3128");+ state.onEnd = (req) => {+ const res = makeResponse(200, "OK");+ req.triggerResponse(res);+ res.emitData(Buffer.from([0]));+ res.emitEnd();+ };+ await provider.getImage("http://img.example.com/pic.png");+ expect(HttpProxyAgent).toHaveBeenCalledWith("http://proxy:3128");+ });++ it("treats the 'noproxy' sync proxy value as no proxy", async () => {+ getSyncProxyMock.mockReturnValue("noproxy");+ state.onEnd = (req) => {+ const res = makeResponse(200, "OK");+ req.triggerResponse(res);+ res.emitData(Buffer.from([0]));+ res.emitEnd();+ };+ await provider.getImage("http://img.example.com/pic.png");+ expect(state.requests[0].opts.agent).toBeNull();+ });++ it("rejects non-2xx image responses", async () => {+ state.onEnd = (req) => {+ const res = makeResponse(404, "Not Found");+ req.triggerResponse(res);+ // Still resolves end after rejecting on the status code.+ res.emitEnd();+ };+ await expect(provider.getImage("http://img.example.com/missing.png")).rejects.toThrow(+ /404 Not Found/+ );+ });++ it("rejects on a request error", async () => {+ state.onEnd = (req) => req.triggerError(new Error("img-error"));+ await expect(provider.getImage("http://img.example.com/pic.png")).rejects.toThrow(+ /img-error/+ );+ });++ it("rejects on a request abort", async () => {+ state.onEnd = (req) => req.triggerAbort(new Error("img-abort"));+ await expect(provider.getImage("http://img.example.com/pic.png")).rejects.toThrow(+ /img-abort/+ );+ });++ it("rejects if the client throws synchronously", async () => {+ fakeHttp.request.mockImplementationOnce(() => {+ throw new Error("img-prepare");+ });+ await expect(provider.getImage("http://img.example.com/pic.png")).rejects.toThrow(+ /img-prepare/+ );+ });+});diff --git a/apps/server/src/services/resource_dir.spec.ts b/apps/server/src/services/resource_dir.spec.tsnew file mode 100644index 0000000000..2afe67f83e--- /dev/null+++ b/apps/server/src/services/resource_dir.spec.ts@@ -0,0 +1,35 @@+import path from "path";+import { afterEach, describe, expect, it, vi } from "vitest";++describe("resource_dir", () => {+ afterEach(() => {+ vi.resetModules();+ vi.doUnmock("fs");+ vi.doUnmock("./utils.js");+ vi.restoreAllMocks();+ });++ async function loadResourceDir(dbInitDirExists: boolean) {+ vi.resetModules();+ vi.doMock("./utils.js", () => ({ getResourceDir: () => "/test/root" }));+ vi.doMock("fs", () => ({ default: { existsSync: () => dbInitDirExists } }));+ return (await import("./resource_dir.js")).default;+ }++ it("computes resource directories when the DB init dir exists", async () => {+ const dirs = await loadResourceDir(true);+ expect(dirs.RESOURCE_DIR).toBe(path.join("/test/root", "assets"));+ expect(dirs.DB_INIT_DIR).toBe(path.resolve(dirs.RESOURCE_DIR, "db"));+ expect(dirs.ELECTRON_APP_ROOT_DIR).toBe(path.resolve(dirs.RESOURCE_DIR, "../.."));+ });++ it("exits when the DB init directory is missing", async () => {+ const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {+ throw new Error("exit");+ }) as never);+ vi.spyOn(console, "error").mockImplementation(() => {});++ await expect(loadResourceDir(false)).rejects.toThrow("exit");+ expect(exitSpy).toHaveBeenCalledWith(1);+ });+});diff --git a/apps/server/src/services/safe_fetch.spec.ts b/apps/server/src/services/safe_fetch.spec.tsindex 29b8a109e7..98ccea6a79 100644--- a/apps/server/src/services/safe_fetch.spec.ts+++ b/apps/server/src/services/safe_fetch.spec.ts@@ -1,8 +1,36 @@import dns from "node:dns";-import { describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { validateHostResolution, validateUrl } from "./safe_fetch.js";+interface MockAgent {+ options: { connect?: { lookup?: unknown } };+ closed: boolean;+ close(): void;+}++const { agentInstances, MockAgent } = vi.hoisted(() => {+ const agentInstances: MockAgent[] = [];++ class MockAgent {+ options: { connect?: { lookup?: unknown } };+ closed = false;++ constructor(options: { connect?: { lookup?: unknown } } = {}) {+ this.options = options;+ agentInstances.push(this);+ }++ close() {+ this.closed = true;+ }+ }++ return { agentInstances, MockAgent };+});++vi.mock("undici", () => ({ Agent: MockAgent }));++import { safeFetch, validateHostResolution, validateUrl } from "./safe_fetch.js";describe("validateUrl", () => {it("accepts http URLs", () => {@@ -49,6 +77,23 @@ describe("validateHostResolution", () => {await expect(validateHostResolution("1.1.1.1")).resolves.toEqual([{ address: "1.1.1.1", family: 4 }]);});+ it("handles IPv4-mapped IPv6 literals by checking the embedded IPv4", async () => {+ // public mapped address is allowed+ await expect(validateHostResolution("::ffff:8.8.8.8")).resolves.toEqual([+ { address: "::ffff:8.8.8.8", family: 6 }+ ]);+ // private mapped address is blocked+ await expect(validateHostResolution("::ffff:10.0.0.1")).rejects.toThrow("private/internal");+ });++ it("treats an unparseable resolved address as blocked", async () => {+ vi.spyOn(dns.promises, "lookup").mockResolvedValueOnce([+ { address: "not-an-ip", family: 4 }+ ] as unknown as dns.LookupAddress);++ await expect(validateHostResolution("garbage.example.com")).rejects.toThrow("private/internal");+ });+it("rejects hostnames that resolve to private IPs (DNS rebinding)", async () => {vi.spyOn(dns.promises, "lookup").mockResolvedValueOnce([{ address: "127.0.0.1", family: 4 }@@ -82,3 +127,188 @@ describe("validateHostResolution", () => {await expect(validateHostResolution("nonexistent.invalid")).rejects.toThrow("Could not resolve hostname");});});++describe("safeFetch", () => {+ let fetchMock: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ agentInstances.length = 0;+ fetchMock = vi.fn();+ vi.stubGlobal("fetch", fetchMock);+ // DNS literal so no actual DNS lookup is attempted.+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ });++ function makeResponse(body: ReadableStream | null, init: ResponseInit) {+ // Construct a plain object that quacks like the parts safeFetch reads.+ return {+ status: init.status ?? 200,+ statusText: init.statusText ?? "OK",+ headers: new Headers(init.headers),+ body+ } as unknown as Response;+ }++ function streamFrom(chunks: Uint8Array[]): ReadableStream {+ let i = 0;+ return new ReadableStream({+ pull(controller) {+ if (i < chunks.length) {+ controller.enqueue(chunks[i++]);+ } else {+ controller.close();+ }+ }+ });+ }++ it("fetches a public IP, pins DNS, and cleans up the dispatcher after the body is read", async () => {+ const payload = new TextEncoder().encode("hello");+ fetchMock.mockResolvedValueOnce(makeResponse(streamFrom([payload]), { status: 200 }));++ const response = await safeFetch("http://8.8.8.8/data");++ // The custom dispatcher was passed to fetch.+ const fetchOptions = fetchMock.mock.calls[0][1] as { dispatcher: MockAgent; redirect: string; signal: unknown };+ expect(fetchOptions.redirect).toBe("manual");+ expect(fetchOptions.signal).toBeDefined();+ expect(agentInstances).toHaveLength(1);+ expect(fetchOptions.dispatcher).toBe(agentInstances[0]);++ // Drain the wrapped body; this should close the dispatcher exactly once.+ const text = await new Response(response.body).text();+ expect(text).toBe("hello");+ expect(agentInstances[0].closed).toBe(true);+ });++ it("closes the dispatcher immediately when the response has no body", async () => {+ fetchMock.mockResolvedValueOnce(makeResponse(null, { status: 204 }));++ const response = await safeFetch("http://8.8.8.8/empty");+ expect(response.status).toBe(204);+ expect(agentInstances[0].closed).toBe(true);+ });++ it("cancels the wrapped body and closes the dispatcher", async () => {+ fetchMock.mockResolvedValueOnce(+ makeResponse(streamFrom([new TextEncoder().encode("data")]), { status: 200 })+ );++ const response = await safeFetch("http://8.8.8.8/cancel");+ await response.body!.cancel();+ expect(agentInstances[0].closed).toBe(true);+ });++ it("propagates a body read error to the consumer and closes the dispatcher", async () => {+ const erroringStream = new ReadableStream({+ pull() {+ throw new Error("boom");+ }+ });+ fetchMock.mockResolvedValueOnce(makeResponse(erroringStream, { status: 200 }));++ const response = await safeFetch("http://8.8.8.8/err");+ await expect(new Response(response.body).text()).rejects.toThrow("boom");+ expect(agentInstances[0].closed).toBe(true);+ });++ it("follows redirects (resolving relative locations) and closes intermediate dispatchers", async () => {+ fetchMock+ .mockResolvedValueOnce(makeResponse(null, { status: 302, headers: { location: "/next" } }))+ .mockResolvedValueOnce(makeResponse(streamFrom([new TextEncoder().encode("final")]), { status: 200 }));++ const response = await safeFetch("http://8.8.8.8/start");++ expect(fetchMock).toHaveBeenCalledTimes(2);+ // Relative redirect resolved against the original URL.+ expect(fetchMock.mock.calls[1][0]).toBe("http://8.8.8.8/next");+ // First (redirect) dispatcher was closed before following.+ expect(agentInstances[0].closed).toBe(true);++ const text = await new Response(response.body).text();+ expect(text).toBe("final");+ });++ it("throws when a redirect response has no Location header", async () => {+ fetchMock.mockResolvedValueOnce(makeResponse(null, { status: 301 }));++ await expect(safeFetch("http://8.8.8.8/noloc")).rejects.toThrow("Redirect without Location header");+ });++ it("throws after exceeding the maximum number of redirects", async () => {+ fetchMock.mockResolvedValue(makeResponse(null, { status: 302, headers: { location: "/loop" } }));++ await expect(safeFetch("http://8.8.8.8/loop")).rejects.toThrow("Too many redirects");+ });++ it("uses a caller-provided abort signal when present", async () => {+ const controller = new AbortController();+ fetchMock.mockResolvedValueOnce(makeResponse(null, { status: 200 }));++ await safeFetch("http://8.8.8.8/signal", { signal: controller.signal });+ const fetchOptions = fetchMock.mock.calls[0][1] as { signal: unknown };+ expect(fetchOptions.signal).toBe(controller.signal);+ });++ describe("pinned DNS lookup", () => {+ function getPinnedLookup() {+ return (agentInstances[0].options.connect as { lookup: Function }).lookup;+ }++ beforeEach(() => {+ // Two validated addresses: one IPv4, one IPv6.+ vi.spyOn(dns.promises, "lookup").mockResolvedValue([+ { address: "93.184.216.34", family: 4 },+ { address: "2606:2800:220:1:248:1893:25c8:1946", family: 6 }+ ] as unknown as dns.LookupAddress);+ fetchMock.mockResolvedValueOnce(makeResponse(null, { status: 200 }));+ });++ it("returns all addresses when options.all is set", async () => {+ await safeFetch("http://example.com/");+ const lookup = getPinnedLookup();+ const cb = vi.fn();+ lookup("example.com", { all: true }, cb);+ expect(cb).toHaveBeenCalledWith(null, [+ { address: "93.184.216.34", family: 4 },+ { address: "2606:2800:220:1:248:1893:25c8:1946", family: 6 }+ ]);+ });++ it("returns a single address when options.all is not set", async () => {+ await safeFetch("http://example.com/");+ const lookup = getPinnedLookup();+ const cb = vi.fn();+ lookup("example.com", {}, cb);+ expect(cb).toHaveBeenCalledWith(null, "93.184.216.34", 4);+ });++ it("filters by requested address family (numeric options form)", async () => {+ await safeFetch("http://example.com/");+ const lookup = getPinnedLookup();+ const cb = vi.fn();+ // numeric options => family 6+ lookup("example.com", 6, cb);+ expect(cb).toHaveBeenCalledWith(null, "2606:2800:220:1:248:1893:25c8:1946", 6);+ });++ it("errors when no validated address matches the requested family", async () => {+ // Only an IPv4 address is validated; request the IPv6 family.+ vi.spyOn(dns.promises, "lookup").mockResolvedValue([+ { address: "93.184.216.34", family: 4 }+ ] as unknown as dns.LookupAddress);++ await safeFetch("http://example.com/");+ const lookup = getPinnedLookup();+ const cb = vi.fn();+ lookup("example.com", { family: 6 }, cb);+ const err = cb.mock.calls[0][0] as Error;+ expect(err).toBeInstanceOf(Error);+ expect(err.message).toMatch(/No validated addresses/);+ });+ });+});diff --git a/apps/server/src/services/session_secret.spec.ts b/apps/server/src/services/session_secret.spec.tsnew file mode 100644index 0000000000..96aacc63e5--- /dev/null+++ b/apps/server/src/services/session_secret.spec.ts@@ -0,0 +1,49 @@+import { afterEach, describe, expect, it, vi } from "vitest";++describe("session_secret", () => {+ afterEach(() => {+ vi.resetModules();+ vi.doUnmock("fs");+ vi.doUnmock("./data_dir.js");+ vi.doUnmock("./utils.js");+ vi.doUnmock("@triliumnext/core");+ vi.restoreAllMocks();+ });++ async function loadSecret(opts: { exists: boolean }) {+ vi.resetModules();+ const writeFileSync = vi.fn();+ const readFileSync = vi.fn(() => "secret-from-file");+ const info = vi.fn();+ vi.doMock("fs", () => ({+ default: { existsSync: () => opts.exists, writeFileSync, readFileSync }+ }));+ vi.doMock("./data_dir.js", () => ({ default: { TRILIUM_DATA_DIR: "/test/data" } }));+ vi.doMock("./utils.js", () => ({+ randomSecureToken: (len: number) => "g".repeat(len)+ }));+ vi.doMock("@triliumnext/core", () => ({ getLog: () => ({ info }) }));++ const secret = (await import("./session_secret.js")).default;+ return { secret, writeFileSync, readFileSync, info };+ }++ it("generates, logs and persists a 64-char secret when none exists", async () => {+ const { secret, writeFileSync, info } = await loadSecret({ exists: false });+ expect(secret).toHaveLength(64);+ expect(info).toHaveBeenCalledOnce();+ expect(writeFileSync).toHaveBeenCalledWith(+ "/test/data/session_secret.txt",+ secret,+ "ascii"+ );+ });++ it("reads the existing secret from disk", async () => {+ const { secret, readFileSync, writeFileSync, info } = await loadSecret({ exists: true });+ expect(secret).toBe("secret-from-file");+ expect(readFileSync).toHaveBeenCalledWith("/test/data/session_secret.txt", "ascii");+ expect(writeFileSync).not.toHaveBeenCalled();+ expect(info).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/special_notes.spec.ts b/apps/server/src/services/special_notes.spec.tsnew file mode 100644index 0000000000..dec9bc29c8--- /dev/null+++ b/apps/server/src/services/special_notes.spec.ts@@ -0,0 +1,210 @@+import { becca, cls, hoisted_note as hoistedNoteService, note_service as noteService, search as searchService, SearchContext } from "@triliumnext/core";+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";++import sql_init from "./sql_init.js";+import specialNotes from "./special_notes.js";++function countLlmChats() {+ return searchService.searchNotes(+ "note.type = llmChat",+ new SearchContext({ ancestorNoteId: "_llmChat" })+ ).length;+}++describe("special_notes (LLM chat, real DB)", () => {+ beforeAll(async () => {+ sql_init.initializeDb();+ await sql_init.dbReady;+ });++ describe("createLlmChat", () => {+ it("creates an llmChat note with the expected metadata under a monthly parent", () => {+ const note = cls.init(() => specialNotes.createLlmChat());++ expect(note.type).toBe("llmChat");+ expect(note.mime).toBe("application/json");+ expect(JSON.parse(note.getContent() as string)).toEqual({ version: 1, messages: [] });+ expect(note.getLabelValue("iconClass")).toBe("bx bx-message-square-dots");+ expect(note.hasLabel("keepCurrentHoisting")).toBe(true);++ // It must live (transitively) under the _llmChat hidden subtree.+ expect(note.hasAncestor("_llmChat")).toBe(true);++ // The monthly parent must be a book note labelled llmChatMonthNote.+ const parent = note.getParentNotes()[0];+ expect(parent.type).toBe("book");+ expect(parent.hasLabel("llmChatMonthNote")).toBe(true);+ });++ it("reuses the same monthly parent for chats created in the same month", () => {+ const a = cls.init(() => specialNotes.createLlmChat());+ const b = cls.init(() => specialNotes.createLlmChat());++ expect(a.getParentNotes()[0].noteId).toBe(b.getParentNotes()[0].noteId);+ });+ });++ describe("getMostRecentLlmChat / getRecentLlmChats", () => {+ it("returns the most recently modified chat and a mapped recent list", () => {+ const recent = specialNotes.getRecentLlmChats(5);+ expect(Array.isArray(recent)).toBe(true);+ expect(recent.length).toBeGreaterThan(0);+ for (const entry of recent) {+ expect(entry).toHaveProperty("noteId");+ expect(entry).toHaveProperty("title");+ expect(entry).toHaveProperty("dateModified");+ }++ const mostRecent = specialNotes.getMostRecentLlmChat();+ expect(mostRecent).not.toBeNull();+ expect(mostRecent!.type).toBe("llmChat");+ // The newest chat in the recent list should match getMostRecentLlmChat.+ expect(mostRecent!.noteId).toBe(recent[0].noteId);+ });++ it("respects the limit argument", () => {+ expect(specialNotes.getRecentLlmChats(1).length).toBeLessThanOrEqual(1);+ });+ });++ describe("getOrCreateLlmChat", () => {+ it("returns an existing chat when one exists", () => {+ // Ensure at least one exists.+ cls.init(() => specialNotes.createLlmChat());+ const result = specialNotes.getOrCreateLlmChat();+ expect(result.type).toBe("llmChat");+ });++ it("creates a new chat when none exist", () => {+ // Delete all existing chats first.+ cls.init(() => {+ for (const chat of searchService.searchNotes(+ "note.type = llmChat",+ new SearchContext({ ancestorNoteId: "_llmChat" })+ )) {+ chat.deleteNote();+ }+ });+ expect(specialNotes.getMostRecentLlmChat()).toBeNull();++ const created = cls.init(() => specialNotes.getOrCreateLlmChat());+ expect(created.type).toBe("llmChat");+ expect(specialNotes.getMostRecentLlmChat()).not.toBeNull();+ });+ });++ describe("saveLlmChat", () => {+ it("throws when no chat note ID is provided", () => {+ expect(() => specialNotes.saveLlmChat(null)).toThrow();+ });++ it("throws when the chat note does not exist", () => {+ expect(() => specialNotes.saveLlmChat("doesNotExist123")).toThrow();+ });++ it("clones the chat to the chat home and removes the hidden-subtree parent branch", () => {+ const chat = cls.init(() => specialNotes.createLlmChat());+ expect(chat.hasAncestor("_hidden")).toBe(true);++ const result = cls.init(() => specialNotes.saveLlmChat(chat.noteId));+ expect(result.success).toBe(true);+ expect(result.branchId).toBeTruthy();++ // After saving, the chat should no longer hang off the hidden subtree.+ const liveParents = chat.getParentBranches().filter((b) => !b.isDeleted);+ expect(liveParents.length).toBeGreaterThan(0);+ const stillHidden = liveParents.some((b) => b.parentNote?.hasAncestor("_hidden"));+ expect(stillHidden).toBe(false);++ // The clone produced a resolvable branch.+ const branch = becca.getBranch(result.branchId!);+ expect(branch).toBeTruthy();+ });+ });++ describe("getLlmChatHome branches (via saveLlmChat)", () => {+ afterEach(() => vi.restoreAllMocks());++ it("throws when there is no workspace note", () => {+ vi.spyOn(hoistedNoteService, "getWorkspaceNote").mockReturnValue(null as any);+ const chat = cls.init(() => specialNotes.createLlmChat());++ expect(() => cls.init(() => specialNotes.saveLlmChat(chat.noteId)))+ .toThrow(/workspace note/);+ });++ // A real workspace note (under root, labelled #workspace) used as the clone target.+ let workspaceId: string;+ beforeAll(() => {+ workspaceId = cls.init(() => {+ const workspace = noteService.createNewNote({+ parentNoteId: "root", title: "Workspace", content: "", type: "book"+ }).note;+ workspace.addLabel("workspace");+ return workspace.noteId;+ });+ });++ function expectClonedOutOfHidden(branchId: string | undefined, chat: ReturnType<typeof specialNotes.createLlmChat>) {+ const liveParents = chat.getParentBranches().filter((b) => !b.isDeleted);+ expect(liveParents.length).toBeGreaterThan(0);+ expect(liveParents.some((b) => b.parentNote?.hasAncestor("_hidden"))).toBe(false);+ expect(becca.getBranch(branchId!)).toBeTruthy();+ }++ /**+ * Returns a workspace stub backed by the real workspace note but with a+ * controllable searchNoteInSubtree, so the three short-circuit operands of+ * `#workspaceLlmChatHome || #llmChatHome || workspaceNote` can each be reached+ * (the production searchNoteInSubtree is global, so real labels would collide).+ */+ function workspaceStub(found: Record<string, unknown>) {+ const real = becca.getNoteOrThrow(workspaceId);+ return new Proxy(real, {+ get(target, prop) {+ if (prop === "isRoot") return () => false;+ if (prop === "searchNoteInSubtree") {+ return (query: string) => found[query] ?? null;+ }+ return (target as any)[prop];+ }+ });+ }++ it("uses the #workspaceLlmChatHome target when present", () => {+ const home = becca.getNoteOrThrow(workspaceId);+ vi.spyOn(hoistedNoteService, "getWorkspaceNote")+ .mockReturnValue(workspaceStub({ "#workspaceLlmChatHome": home }) as any);++ const chat = cls.init(() => specialNotes.createLlmChat());+ const result = cls.init(() => specialNotes.saveLlmChat(chat.noteId));+ expect(result.success).toBe(true);+ expectClonedOutOfHidden(result.branchId, chat);+ });++ it("falls back to #llmChatHome when #workspaceLlmChatHome is absent", () => {+ const home = becca.getNoteOrThrow(workspaceId);+ vi.spyOn(hoistedNoteService, "getWorkspaceNote")+ .mockReturnValue(workspaceStub({ "#llmChatHome": home }) as any);++ const chat = cls.init(() => specialNotes.createLlmChat());+ const result = cls.init(() => specialNotes.saveLlmChat(chat.noteId));+ expect(result.success).toBe(true);+ expectClonedOutOfHidden(result.branchId, chat);+ });++ it("falls back to the workspace note itself when no chat-home label exists", () => {+ vi.spyOn(hoistedNoteService, "getWorkspaceNote")+ .mockReturnValue(workspaceStub({}) as any);++ const chat = cls.init(() => specialNotes.createLlmChat());+ const result = cls.init(() => specialNotes.saveLlmChat(chat.noteId));+ expect(result.success).toBe(true);+ expectClonedOutOfHidden(result.branchId, chat);+ });+ });++ it("starts with at least the seeded chat content available", () => {+ expect(countLlmChats()).toBeGreaterThanOrEqual(0);+ });+});diff --git a/apps/server/src/services/sql.spec.ts b/apps/server/src/services/sql.spec.tsnew file mode 100644index 0000000000..afaefb0cb6--- /dev/null+++ b/apps/server/src/services/sql.spec.ts@@ -0,0 +1,18 @@+import { describe, expect, it } from "vitest";++import sqlProxy from "./sql.js";++describe("sql proxy", () => {+ it("forwards function and non-function properties through the lazy proxy", () => {+ // Function branch of the `typeof value === "function"` ternary: the+ // bound method runs a real query against the booted in-memory DB.+ expect(typeof (sqlProxy as { getValue: unknown }).getValue).toBe("function");+ const one = sqlProxy.getValue<number>("SELECT 1");+ expect(one).toBe(1);++ // Non-function branch: an instance data property (the statement cache)+ // is returned directly, not bound.+ const cache = (sqlProxy as unknown as { statementCache: unknown }).statementCache;+ expect(typeof cache).toBe("object");+ });+});diff --git a/apps/server/src/services/totp.spec.ts b/apps/server/src/services/totp.spec.tsnew file mode 100644index 0000000000..349c5786e9--- /dev/null+++ b/apps/server/src/services/totp.spec.ts@@ -0,0 +1,149 @@+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";++const { mockGenerateSecret, mockValidate } = vi.hoisted(() => ({+ mockGenerateSecret: vi.fn<() => string>(),+ mockValidate: vi.fn<(args: { passcode: string; secret: string }) => boolean>()+}));++vi.mock("time2fa", () => ({+ generateSecret: mockGenerateSecret,+ Totp: { validate: mockValidate }+}));++import { cls, options } from "@triliumnext/core";++import totpEncryption from "./encryption/totp_encryption.js";+import sql_init from "./sql_init.js";+import totp from "./totp.js";++const SECRET = "JBSWY3DPEHPK3PXP";++describe("totp", () => {+ beforeAll(async () => {+ sql_init.initializeDb();+ await sql_init.dbReady;+ });++ beforeEach(() => {+ vi.clearAllMocks();+ mockGenerateSecret.mockReturnValue(SECRET);+ mockValidate.mockReturnValue(true);+ });++ it("isTotpEnabled requires mfaEnabled+totp method+secret set", () => {+ cls.init(() => {+ totpEncryption.resetTotpSecret();+ options.setOption("mfaEnabled", "false");+ options.setOption("mfaMethod", "totp");+ });+ expect(totp.isTotpEnabled()).toBe(false);++ cls.init(() => {+ options.setOption("mfaEnabled", "true");+ options.setOption("mfaMethod", "oauth");+ });+ expect(totp.isTotpEnabled()).toBe(false);++ // method is totp + enabled, but no secret yet+ cls.init(() => {+ options.setOption("mfaMethod", "totp");+ });+ expect(totp.isTotpEnabled()).toBe(false);++ // now set a secret as well+ cls.init(() => {+ totp.createSecret();+ });+ expect(totp.isTotpEnabled()).toBe(true);+ });++ it("createSecret stores the generated secret on success", () => {+ cls.init(() => {+ totpEncryption.resetTotpSecret();+ });+ let result: { success: boolean; message?: string } | undefined;+ cls.init(() => {+ result = totp.createSecret();+ });+ expect(result?.success).toBe(true);+ expect(result?.message).toBe(SECRET);+ expect(totp.checkForTotpSecret()).toBe(true);+ expect(totp.getTotpSecret()).not.toBeNull();+ });++ it("createSecret returns failure when secret generation throws", () => {+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});++ // Error instance -> the error's message is surfaced+ mockGenerateSecret.mockImplementation(() => {+ throw new Error("gen failed");+ });+ let result: { success: boolean; message?: string } | undefined;+ cls.init(() => {+ result = totp.createSecret();+ });+ expect(result?.success).toBe(false);+ expect(result?.message).toBe("gen failed");++ // non-Error throw -> falls back to a generic message+ mockGenerateSecret.mockImplementation(() => {+ throw "string failure";+ });+ cls.init(() => {+ result = totp.createSecret();+ });+ expect(result?.success).toBe(false);+ expect(result?.message).toBeTruthy();++ errorSpy.mockRestore();+ });++ it("validateTOTP returns false when no secret is set", () => {+ cls.init(() => {+ totpEncryption.resetTotpSecret();+ });+ expect(totp.validateTOTP("123456")).toBe(false);+ expect(mockValidate).not.toHaveBeenCalled();+ });++ it("validateTOTP delegates to Totp.validate when a secret is set", () => {+ cls.init(() => {+ totp.createSecret();+ });++ mockValidate.mockReturnValue(true);+ expect(totp.validateTOTP("000000")).toBe(true);++ mockValidate.mockReturnValue(false);+ expect(totp.validateTOTP("000000")).toBe(false);+ });++ it("validateTOTP returns false when Totp.validate throws", () => {+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ cls.init(() => {+ totp.createSecret();+ });+ mockValidate.mockImplementation(() => {+ throw new Error("invalid");+ });+ expect(totp.validateTOTP("bad")).toBe(false);+ errorSpy.mockRestore();+ });++ it("resetTotp clears the secret and disables MFA", () => {+ cls.init(() => {+ options.setOption("mfaEnabled", "true");+ options.setOption("mfaMethod", "totp");+ totp.createSecret();+ });+ expect(totp.checkForTotpSecret()).toBe(true);++ cls.init(() => {+ totp.resetTotp();+ });++ expect(totp.checkForTotpSecret()).toBe(false);+ expect(options.getOptionOrNull("mfaEnabled")).toBe("false");+ expect(options.getOptionOrNull("mfaMethod")).toBe("");+ });+});diff --git a/apps/server/src/services/utils.spec.ts b/apps/server/src/services/utils.spec.tsindex e29c391c03..5201d42bfe 100644--- a/apps/server/src/services/utils.spec.ts+++ b/apps/server/src/services/utils.spec.ts@@ -1,9 +1,166 @@-import { describe, expect, it } from "vitest";+import { utils as coreUtils } from "@triliumnext/core";+import { EventEmitter } from "events";+import { afterEach, describe, expect, it, vi } from "vitest";import utils from "./utils";+import {+ constantTimeCompare,+ formatDownloadTitle,+ fromBase64,+ getContentDisposition,+ hashedBlobId,+ hmac,+ isStringNote,+ newEntityId,+ normalize,+ quoteRegex,+ randomString,+ removeDiacritic,+ replaceAll,+ toBase64,+ toMap,+ waitForStreamToFinish+} from "./utils";-describe("#isDev", () => {- it("should export a boolean", () => {+describe("platform flags & isDev", () => {+ it("exposes boolean platform flags", () => {expect(utils.isDev).toBeTypeOf("boolean");+ expect(utils.isMac).toBeTypeOf("boolean");+ expect(utils.isWindows).toBeTypeOf("boolean");+ expect(utils.isElectron).toBeTypeOf("boolean");+ });+});++describe("base64 helpers", () => {+ it("round-trips strings and buffers", () => {+ expect(toBase64("hello")).toBe(Buffer.from("hello").toString("base64"));+ expect(toBase64(Buffer.from("world"))).toBe(Buffer.from("world").toString("base64"));+ expect(fromBase64(toBase64("hello")).toString("utf-8")).toBe("hello");+ });+});++describe("constantTimeCompare", () => {+ it("returns true only for equal strings", () => {+ expect(constantTimeCompare("abc", "abc")).toBe(true);+ expect(constantTimeCompare("", "")).toBe(true);+ });++ it("returns false for differing strings, different lengths and non-string inputs", () => {+ expect(constantTimeCompare("abc", "abd")).toBe(false);+ expect(constantTimeCompare("abc", "abcd")).toBe(false);+ expect(constantTimeCompare(null, "abc")).toBe(false);+ expect(constantTimeCompare("abc", undefined)).toBe(false);+ expect(constantTimeCompare(undefined, undefined)).toBe(false);+ });+});++describe("hmac", () => {+ it("delegates to the core crypto provider", () => {+ const result = hmac("secret", "value");+ expect(result).toBeDefined();+ // Deterministic for the same inputs.+ expect(hmac("secret", "value")).toEqual(result);+ });+});++describe("deprecated core delegations", () => {+ it("forward to the equivalent core utility", () => {+ expect(newEntityId()).toBeTypeOf("string");+ expect(randomString(10)).toHaveLength(10);+ expect(hashedBlobId("content")).toBe(coreUtils.hashedBlobId("content"));+ expect(getContentDisposition("file.txt")).toBe(coreUtils.getContentDisposition("file.txt"));+ expect(isStringNote("text", "text/html")).toBe(coreUtils.isStringNote("text", "text/html"));+ expect(quoteRegex("a.b")).toBe(coreUtils.quoteRegex("a.b"));+ expect(replaceAll("a-b-c", "-", "+")).toBe(coreUtils.replaceAll("a-b-c", "-", "+"));+ expect(formatDownloadTitle("name", "text", "text/html"))+ .toBe(coreUtils.formatDownloadTitle("name", "text", "text/html"));+ expect(removeDiacritic("café")).toBe(coreUtils.removeDiacritic("café"));+ expect(normalize("ABC")).toBe(coreUtils.normalize("ABC"));++ const list = [{ id: "a", v: 1 }, { id: "b", v: 2 }];+ expect(toMap(list, "id")).toEqual(coreUtils.toMap(list, "id"));+ });+});++describe("waitForStreamToFinish", () => {+ afterEach(() => vi.restoreAllMocks());++ it("resolves on the stream 'finish' event", async () => {+ const stream = new EventEmitter();+ const promise = waitForStreamToFinish(stream);+ stream.emit("finish");+ await expect(promise).resolves.toBeUndefined();+ });++ it("rejects on the stream 'error' event", async () => {+ const stream = new EventEmitter();+ const promise = waitForStreamToFinish(stream);+ const err = new Error("boom");+ stream.emit("error", err);+ await expect(promise).rejects.toBe(err);+ });+});++describe("getResourceDir", () => {+ const ORIGINAL_RESOURCE_DIR = process.env.TRILIUM_RESOURCE_DIR;+ const ORIGINAL_ENV = process.env.TRILIUM_ENV;+ const ORIGINAL_ELECTRON = Object.getOwnPropertyDescriptor(process.versions, "electron");+ const ORIGINAL_ARGV1 = process.argv[1];++ afterEach(() => {+ if (ORIGINAL_RESOURCE_DIR === undefined) {+ delete process.env.TRILIUM_RESOURCE_DIR;+ } else {+ process.env.TRILIUM_RESOURCE_DIR = ORIGINAL_RESOURCE_DIR;+ }+ if (ORIGINAL_ENV === undefined) {+ delete process.env.TRILIUM_ENV;+ } else {+ process.env.TRILIUM_ENV = ORIGINAL_ENV;+ }+ if (ORIGINAL_ELECTRON) {+ Object.defineProperty(process.versions, "electron", ORIGINAL_ELECTRON);+ } else {+ delete (process.versions as { electron?: string }).electron;+ }+ process.argv[1] = ORIGINAL_ARGV1;+ vi.resetModules();+ vi.doUnmock("path");+ });++ it("returns TRILIUM_RESOURCE_DIR when set", () => {+ process.env.TRILIUM_RESOURCE_DIR = "/custom/resources";+ expect(utils.getResourceDir()).toBe("/custom/resources");+ });++ // isDev / isElectron are import-time constants, so each branch needs a+ // fresh module load with the relevant env/versions patched beforehand.+ async function loadFresh() {+ vi.resetModules();+ delete process.env.TRILIUM_RESOURCE_DIR;+ return (await import("./utils.js")).getResourceDir;+ }++ it("uses __dirname in dev mode", async () => {+ process.env.TRILIUM_ENV = "dev";+ delete (process.versions as { electron?: string }).electron;+ const getResourceDir = await loadFresh();+ expect(getResourceDir().endsWith("..") || getResourceDir().length > 0).toBe(true);+ });++ it("uses __dirname under Electron in production", async () => {+ delete process.env.TRILIUM_ENV;+ Object.defineProperty(process.versions, "electron", { value: "30.0.0", configurable: true });+ const getResourceDir = await loadFresh();+ // The electron prod branch returns __dirname of the loaded module.+ expect(getResourceDir()).toBeTypeOf("string");+ });++ it("uses the executable directory in non-electron production", async () => {+ delete process.env.TRILIUM_ENV;+ delete (process.versions as { electron?: string }).electron;+ process.argv[1] = "/opt/trilium/bin/server.js";+ const getResourceDir = await loadFresh();+ expect(getResourceDir()).toBe("/opt/trilium/bin");});});diff --git a/apps/server/src/services/ws_messaging_provider.spec.ts b/apps/server/src/services/ws_messaging_provider.spec.tsnew file mode 100644index 0000000000..f9e21b0109--- /dev/null+++ b/apps/server/src/services/ws_messaging_provider.spec.ts@@ -0,0 +1,243 @@+import type { WebSocketMessage } from "@triliumnext/commons";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const OPEN = 1;+const CLOSED = 3;++type Handler = (...args: any[]) => void;++const { state, getLogMock, configMock, randomStringMock, WebSocketServerMock } = vi.hoisted(() => {+ const state: { instances: any[] } = { instances: [] };++ class WebSocketServerMock {+ options: any;+ clients = new Set<any>();+ handlers: Record<string, (...a: any[]) => void> = {};+ closed = false;++ constructor(options: any) {+ this.options = options;+ state.instances.push(this);+ }+ on(event: string, cb: (...a: any[]) => void) {+ this.handlers[event] = cb;+ return this;+ }+ emit(event: string, ...args: any[]) {+ return this.handlers[event]?.(...args);+ }+ close() {+ this.closed = true;+ }+ }++ return {+ state,+ WebSocketServerMock,+ getLogMock: { error: vi.fn(), info: vi.fn() },+ configMock: { General: { noAuthentication: false } as { noAuthentication: boolean } | undefined },+ randomStringMock: vi.fn(() => "client-id")+ };+});++vi.mock("ws", () => ({+ WebSocketServer: WebSocketServerMock,+ WebSocket: { OPEN: 1 } // keep in sync with the module-level OPEN constant+}));+vi.mock("./config.js", () => ({ default: configMock }));+vi.mock("./utils.js", () => ({ randomString: randomStringMock }));+vi.mock("@triliumnext/core", () => ({ getLog: () => getLogMock }));++import WebSocketMessagingProvider from "./ws_messaging_provider.js";++function makeSocket(readyState = OPEN) {+ const handlers: Record<string, Handler> = {};+ return {+ readyState,+ sent: [] as string[],+ handlers,+ on(event: string, cb: Handler) {+ handlers[event] = cb;+ return this;+ },+ send(data: string) {+ this.sent.push(data);+ },+ emit(event: string, ...args: any[]) {+ return handlers[event]?.(...args);+ }+ };+}++describe("WebSocketMessagingProvider", () => {+ let provider: WebSocketMessagingProvider;++ beforeEach(() => {+ provider = new WebSocketMessagingProvider();+ state.instances = [];+ getLogMock.error.mockClear();+ getLogMock.info.mockClear();+ configMock.General = { noAuthentication: false };+ randomStringMock.mockReturnValue("client-id");+ vi.spyOn(console, "log").mockImplementation(() => {});+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ function init() {+ const httpServer = {} as any;+ const sessionParser = vi.fn((_req: any, _params: any, cb: () => void) => cb());+ provider.init(httpServer, sessionParser as any);+ return { server: state.instances[0], sessionParser };+ }++ describe("init / verifyClient", () => {+ it("allows a logged-in session", () => {+ const { server } = init();+ const done = vi.fn();+ server.options.verifyClient({ req: { session: { loggedIn: true } } }, done);+ expect(done).toHaveBeenCalledWith(true);+ expect(getLogMock.error).not.toHaveBeenCalled();+ });++ it("allows when authentication is disabled", () => {+ configMock.General = { noAuthentication: true };+ const { server } = init();+ const done = vi.fn();+ server.options.verifyClient({ req: { session: { loggedIn: false } } }, done);+ expect(done).toHaveBeenCalledWith(true);+ });++ it("rejects and logs when not logged in and auth is required", () => {+ const { server } = init();+ const done = vi.fn();+ server.options.verifyClient({ req: { session: { loggedIn: false } } }, done);+ expect(done).toHaveBeenCalledWith(false);+ expect(getLogMock.error).toHaveBeenCalled();+ });++ it("rejects when the config has no General section", () => {+ configMock.General = undefined;+ const { server } = init();+ const done = vi.fn();+ server.options.verifyClient({ req: { session: { loggedIn: false } } }, done);+ // `config.General && config.General.noAuthentication` short-circuits to a+ // falsy value, so the connection is not allowed.+ expect(done.mock.calls[0][0]).toBeFalsy();+ });+ });++ describe("connection lifecycle", () => {+ it("tracks a connected client, dispatches messages, and untracks on close", async () => {+ const { server } = init();+ const handler = vi.fn();+ provider.setClientMessageHandler(handler);++ const ws = makeSocket();+ server.emit("connection", ws, {});+ expect(provider.getClientCount()).toBe(0); // server.clients still empty (we manage map)+ expect(provider.sendMessageToClient("client-id", { type: "ping" } as any)).toBe(true);++ await Promise.resolve(ws.emit("message", JSON.stringify({ type: "hello" })));+ expect(handler).toHaveBeenCalledWith("client-id", { type: "hello" });++ ws.emit("close");+ expect(provider.sendMessageToClient("client-id", { type: "ping" } as any)).toBe(false);+ });++ it("ignores incoming messages when no handler is registered", async () => {+ const { server } = init();+ const ws = makeSocket();+ server.emit("connection", ws, {});+ await expect(ws.emit("message", JSON.stringify({ type: "x" }))).resolves.toBeUndefined();+ });++ it("logs server errors via the error handler", () => {+ const { server } = init();+ expect(() => server.emit("error", new Error("ws boom"))).not.toThrow();+ });+ });++ describe("sendMessageToAllClients", () => {+ it("sends to OPEN clients and logs non-suppressed message types", () => {+ const { server } = init();+ const open = makeSocket(OPEN);+ const closed = makeSocket(CLOSED);+ server.clients.add(open);+ server.clients.add(closed);++ provider.sendMessageToAllClients({ type: "frontend-update" } as WebSocketMessage);+ expect(open.sent).toHaveLength(1);+ expect(closed.sent).toHaveLength(0);+ expect(getLogMock.info).toHaveBeenCalled();+ });++ it("does not log for suppressed message types", () => {+ init();+ provider.sendMessageToAllClients({ type: "sync-failed" } as WebSocketMessage);+ provider.sendMessageToAllClients({ type: "api-log-messages" } as WebSocketMessage);+ expect(getLogMock.info).not.toHaveBeenCalled();+ });++ it("is a no-op when the server is not initialized", () => {+ expect(() =>+ provider.sendMessageToAllClients({ type: "frontend-update" } as WebSocketMessage)+ ).not.toThrow();+ expect(getLogMock.info).not.toHaveBeenCalled();+ });+ });++ describe("sendMessageToClient", () => {+ it("returns false for an unknown client", () => {+ init();+ expect(provider.sendMessageToClient("missing", { type: "ping" } as any)).toBe(false);+ });++ it("returns false for a client that is not OPEN", () => {+ const { server } = init();+ const ws = makeSocket(CLOSED);+ server.emit("connection", ws, {});+ expect(provider.sendMessageToClient("client-id", { type: "ping" } as any)).toBe(false);+ });++ it("sends and returns true for an OPEN client", () => {+ const { server } = init();+ const ws = makeSocket(OPEN);+ server.emit("connection", ws, {});+ expect(provider.sendMessageToClient("client-id", { type: "ping" } as any)).toBe(true);+ expect(ws.sent).toHaveLength(1);+ });+ });++ describe("getClientCount", () => {+ it("returns the server's client set size", () => {+ const { server } = init();+ server.clients.add(makeSocket());+ server.clients.add(makeSocket());+ expect(provider.getClientCount()).toBe(2);+ });++ it("returns 0 when the server is not initialized", () => {+ expect(provider.getClientCount()).toBe(0);+ });+ });++ describe("dispose", () => {+ it("closes the server and clears the client map", () => {+ const { server } = init();+ const ws = makeSocket(OPEN);+ server.emit("connection", ws, {});++ provider.dispose();+ expect(server.closed).toBe(true);+ // After dispose, server is still referenced but map is cleared.+ expect(provider.sendMessageToClient("client-id", { type: "ping" } as any)).toBe(false);+ });++ it("is safe to call before init", () => {+ expect(() => provider.dispose()).not.toThrow();+ });+ });+});