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
fix(server): explain an unusable data directory without a stack trace
Elian Dorand425f83f3be4
diff --git a/apps/server/src/services/data_dir.spec.ts b/apps/server/src/services/data_dir.spec.tsindex e4066eda46..989823bf3d 100644--- a/apps/server/src/services/data_dir.spec.ts+++ b/apps/server/src/services/data_dir.spec.ts@@ -8,6 +8,7 @@ describe("data_dir.ts unit tests", () => {let getDataDirs: typeof getDataDirsType;const mockFn = {+ accessSyncMock: vi.fn(),existsSyncMock: vi.fn(),mkdirSyncMock: vi.fn(),statSyncMock: vi.fn(),@@ -28,6 +29,8 @@ describe("data_dir.ts unit tests", () => {vi.doMock("node:fs", () => {return {default: {+ accessSync: mockFn.accessSyncMock,+ constants: { X_OK: 1 },existsSync: mockFn.existsSyncMock,mkdirSync: mockFn.mkdirSyncMock,statSync: mockFn.statSyncMock@@ -44,8 +47,10 @@ describe("data_dir.ts unit tests", () => {};});+ const { dirname } = await vi.importActual<typeof import("node:path")>("node:path");vi.doMock("node:path", () => {return {+ dirname,join: mockFn.pathJoinMock};});@@ -381,23 +386,33 @@ describe("data_dir.ts unit tests", () => {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.+ // Runs getTriliumDataDir with process.exit stubbed and returns what was printed.+ const runUntilExit = () => {+ const exit = vi.spyOn(process, "exit").mockImplementation(() => {+ throw new Error("process.exit");+ });+ expect(() => getTriliumDataDir("trilium-data")).toThrow("process.exit");+ expect(exit).toHaveBeenCalledWith(1);+ expect(console.error).toHaveBeenCalledTimes(1);+ return String(vi.mocked(console.error).mock.calls[0][0]);+ };++ it("EACCES – prints why the directory cannot be created and exits", () => {+ mkdirThrows("EACCES");mockFn.statSyncMock.mockImplementation(() => ({ uid: 1000, gid: 1000, mode: 0o755 }));- // Provide getuid/getgid (absent on Windows) so the UID:GID branch runs.+ // Provide getuid/getgid (absent on Windows) so the UID:GID line is printed.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(mockFn.statSyncMock).toHaveBeenCalledTimes(1);- // Confirm the owner/permissions diagnostics branch actually ran.- expect(console.error).toHaveBeenCalledWith("Process running as UID:GID = 1000:1000");- expect(console.error).toHaveBeenCalledWith(" Owner UID:GID = 1000:1000");- expect(console.error).toHaveBeenCalledWith(" Permissions = 755 (octal)");+ const message = runUntilExit();+ expect(message).toContain("Trilium cannot start: permission denied while creating /home/mock/trilium-data-ERR.");+ expect(message).toContain("Running as UID:GID 1000:1000.");+ expect(message).toContain("/home/mock is owned by UID:GID 1000:1000 with permissions 755.");+ expect(message).toContain("in Docker, set USER_UID and USER_GID to the owner of the mounted directory");+ expect(mockFn.statSyncMock).toHaveBeenCalledWith("/home/mock");} finally {if (!hadGetuid) {delete proc.getuid;@@ -406,15 +421,47 @@ describe("data_dir.ts unit tests", () => {}});- it("EACCES – handles an inaccessible parent dir (stat throws) and rethrows", () => {- const err = mkdirThrows("EACCES");+ it("EACCES – names the ancestor that cannot be entered and exits", () => {+ mkdirThrows("EACCES");+ mockFn.accessSyncMock.mockImplementation((path: string) => {+ if (path === "/home/mock") {+ throw new Error("EACCES");+ }+ });+ mockFn.statSyncMock.mockImplementation(() => ({ uid: 1000, gid: 1000, mode: 0o700 }));++ const message = runUntilExit();+ expect(message).toContain("Trilium cannot start: /home/mock/trilium-data-ERR cannot be reached.");+ expect(message).toContain("/home/mock cannot be entered; it is owned by UID:GID 1000:1000 with permissions 700.");+ });++ it("EACCES – reports a parent that cannot be inspected and exits", () => {+ mkdirThrows("EACCES");mockFn.statSyncMock.mockImplementation(() => { throw new Error("no access"); });- expect(() => getTriliumDataDir("trilium-data")).toThrow(err);- // The inaccessible-parent branch (not the owner/permissions one) ran.- expect(console.error).toHaveBeenCalledWith(- expect.stringContaining("is not accessible")- );+ expect(runUntilExit()).toContain("/home/mock cannot be inspected.");+ });++ it("EACCES under Electron – throws the explanation for the main-process error dialog", () => {+ const err = mkdirThrows("EACCES");+ mockFn.statSyncMock.mockImplementation(() => ({ uid: 1000, gid: 1000, mode: 0o755 }));+ const exit = vi.spyOn(process, "exit");+ Object.defineProperty(process.versions, "electron", { value: "1.0.0", configurable: true });++ try {+ let thrown: unknown;+ try {+ getTriliumDataDir("trilium-data");+ } catch (e) {+ thrown = e;+ }+ expect(thrown).toBeInstanceOf(Error);+ expect((thrown as Error).message).toContain("Trilium cannot start: permission denied while creating /home/mock/trilium-data-ERR.");+ expect((thrown as Error).cause).toBe(err);+ expect(exit).not.toHaveBeenCalled();+ } finally {+ delete (process.versions as Record<string, string | undefined>).electron;+ }});it("EEXIST but target is not a directory – rethrows", () => {diff --git a/apps/server/src/services/data_dir.ts b/apps/server/src/services/data_dir.tsindex a3ed9f2bae..66f1a968b7 100644--- a/apps/server/src/services/data_dir.ts+++ b/apps/server/src/services/data_dir.ts@@ -8,7 +8,7 @@import fs from "node:fs";import os from "node:os";-import { join as pathJoin } from "node:path";+import { dirname, join as pathJoin } from "node:path";const DIR_NAME = "trilium-data";const FOLDER_PERMISSIONS = 0o700;@@ -74,33 +74,73 @@ export function getPlatformAppDataDir(platform: ReturnType<typeof os.platform>,}}-function outputPermissionDiagnostics(targetPath: fs.PathLike) {- const pathStr = targetPath.toString();- const parentDir = pathJoin(pathStr, "..");-- console.error("\n========== PERMISSION ERROR DIAGNOSTICS ==========");- console.error(`Failed to create directory: ${pathStr}`);+/**+ * Stops startup with an explanation of why `targetPath` cannot be created. The server prints it+ * and exits, since a stack trace adds nothing. Electron shows an uncaught main-process error in a+ * dialog, which is the only place a desktop user sees it, so there the explanation is thrown.+ */+function failWithPermissionError(targetPath: fs.PathLike, cause: unknown): never {+ const message = describePermissionError(targetPath.toString());+ if (process.versions.electron) {+ throw new Error(message, { cause });+ }+ console.error(`\n${message}\n`);+ process.exit(1);+}- // Output current process UID:GID (Unix only)- if (typeof process.getuid === "function" && typeof process.getgid === "function") {- console.error(`Process running as UID:GID = ${process.getuid()}:${process.getgid()}`);+function describePermissionError(path: string) {+ const blockedDir = findUnreachableAncestor(dirname(path));+ const shownDir = blockedDir ?? dirname(path);+ const lines = [+ blockedDir+ ? `Trilium cannot start: ${path} cannot be reached.`+ : `Trilium cannot start: permission denied while creating ${path}.`,+ ""+ ];++ // process.getuid() and process.getgid() do not exist on Windows.+ if (process.getuid && process.getgid) {+ lines.push(`Running as UID:GID ${process.getuid()}:${process.getgid()}.`);}- // Try to get parent directory statstry {- const stats = fs.statSync(parentDir);- console.error(`Parent directory: ${parentDir}`);- console.error(` Owner UID:GID = ${stats.uid}:${stats.gid}`);- console.error(` Permissions = ${(stats.mode & 0o777).toString(8)} (octal)`);+ const stats = fs.statSync(shownDir);+ const ownership = `owned by UID:GID ${stats.uid}:${stats.gid} with permissions ${(stats.mode & 0o777).toString(8)}`;+ lines.push(blockedDir+ ? `${shownDir} cannot be entered; it is ${ownership}.`+ : `${shownDir} is ${ownership}.`);} catch {- console.error(`Parent directory ${parentDir} is not accessible`);+ lines.push(`${shownDir} cannot be inspected.`);}- console.error("\nTo fix this issue:");- console.error(" - Ensure the data directory is owned by the user running Trilium");- console.error(" - Or set USER_UID and USER_GID environment variables to match the directory owner");- console.error(" - Example: docker run -e USER_UID=$(id -u) -e USER_GID=$(id -g) ...");- console.error("====================================================\n");+ lines.push(+ "",+ "To fix this, either:",+ " - make sure the user running Trilium can enter every directory above the data directory",+ " and write to the data directory itself",+ " - set TRILIUM_DATA_DIR to a directory owned by that user",+ " - in Docker, set USER_UID and USER_GID to the owner of the mounted directory, or, if the",+ " container runs with --user, give the mounted directory to that user"+ );+ return lines.join("\n");+}++/**+ * Returns the highest directory on the way to `dir` that the process cannot enter. Every+ * directory below it fails the same check, so it is the one whose permissions need fixing.+ */+function findUnreachableAncestor(dir: string) {+ let blocked: string | undefined;+ for (let current = dir; ; current = dirname(current)) {+ try {+ fs.accessSync(current, fs.constants.X_OK);+ } catch {+ blocked = current;+ }+ if (dirname(current) === current) {+ return blocked;+ }+ }}function createDirIfNotExisting(path: fs.PathLike, permissionMode: fs.Mode = FOLDER_PERMISSIONS) {@@ -111,7 +151,7 @@ function createDirIfNotExisting(path: fs.PathLike, permissionMode: fs.Mode = FOLconst code = (err as { code: string }).code;if (code === "EACCES") {- outputPermissionDiagnostics(path);+ failWithPermissionError(path, err);} else if (code === "EEXIST") {// Directory already exists - verify it's actually a directorytry {