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
feat(electron): harden open path
Elian Doran4be95dee1744
diff --git a/apps/server/src/services/open_path.spec.ts b/apps/server/src/services/open_path.spec.tsnew file mode 100644index 0000000000..ec1ec5e7f9--- /dev/null+++ b/apps/server/src/services/open_path.spec.ts@@ -0,0 +1,119 @@+import fs from "fs";+import os from "os";+import path from "path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";++import { validateOpenPath } from "./open_path.js";++describe("validateOpenPath", () => {+ let dataDir: string;+ let tmpDir: string;+ let separateTmpDir: string;+ let dataFile: string;+ let tmpFile: string;+ let separateTmpFile: string;++ beforeAll(() => {+ // Simulate the default layout: TMP_DIR is a subdirectory of DATA_DIR.+ dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "trilium-open-path-data-"));+ tmpDir = path.join(dataDir, "tmp");+ fs.mkdirSync(tmpDir);++ // Also simulate the TRILIUM_TMP_DIR-outside-of-data-dir configuration.+ separateTmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "trilium-open-path-tmp-"));++ dataFile = path.join(dataDir, "config.ini");+ fs.writeFileSync(dataFile, "");+ tmpFile = path.join(tmpDir, "attachment.txt");+ fs.writeFileSync(tmpFile, "");+ separateTmpFile = path.join(separateTmpDir, "attachment.txt");+ fs.writeFileSync(separateTmpFile, "");+ });++ afterAll(() => {+ fs.rmSync(dataDir, { recursive: true, force: true });+ fs.rmSync(separateTmpDir, { recursive: true, force: true });+ });++ it("rejects malformed input", () => {+ expect(() => validateOpenPath(undefined, dataDir, tmpDir)).toThrow(/invalid filePath/);+ expect(() => validateOpenPath(null, dataDir, tmpDir)).toThrow(/invalid filePath/);+ expect(() => validateOpenPath(123, dataDir, tmpDir)).toThrow(/invalid filePath/);+ expect(() => validateOpenPath({}, dataDir, tmpDir)).toThrow(/invalid filePath/);+ expect(() => validateOpenPath("", dataDir, tmpDir)).toThrow(/invalid filePath/);+ expect(() => validateOpenPath(path.join(dataDir, "foo\0.txt"), dataDir, tmpDir))+ .toThrow(/invalid filePath/);+ });++ it("rejects paths outside the sandbox", () => {+ // Absolute path elsewhere on disk+ const outside = process.platform === "win32" ? "C:\\Windows\\Temp\\evil.txt" : "/etc/passwd";+ expect(() => validateOpenPath(outside, dataDir, tmpDir))+ .toThrow(/outside data dir/);++ // ".." traversal escapes the sandbox after path.resolve normalisation+ const traversal = path.join(dataDir, "..", "..", "..", "evil.txt");+ expect(() => validateOpenPath(traversal, dataDir, tmpDir))+ .toThrow(/outside data dir/);++ // Relative paths resolve against cwd, not the data dir+ expect(() => validateOpenPath("foo.txt", dataDir, tmpDir))+ .toThrow(/outside data dir/);++ // Near-miss: sibling directory whose name starts with dataDir's name+ // must not satisfy the prefix check.+ const sibling = dataDir + "-evil";+ fs.mkdirSync(sibling);+ try {+ const siblingFile = path.join(sibling, "x.txt");+ fs.writeFileSync(siblingFile, "");+ expect(() => validateOpenPath(siblingFile, dataDir, tmpDir))+ .toThrow(/outside data dir/);+ } finally {+ fs.rmSync(sibling, { recursive: true, force: true });+ }+ });++ it("rejects UNC paths (the NTLM-credential-theft vector)", () => {+ // UNC paths can never resolve under the data dir, so they're blocked+ // by the sandbox check rather than a dedicated UNC rule.+ if (process.platform === "win32") {+ expect(() => validateOpenPath("\\\\attacker.example\\share\\x", dataDir, tmpDir))+ .toThrow(/outside data dir/);+ }+ });++ it("rejects nonexistent files inside the sandbox", () => {+ const missing = path.join(dataDir, "does-not-exist.txt");+ expect(() => validateOpenPath(missing, dataDir, tmpDir))+ .toThrow(/does not exist/);+ });++ it("accepts the data directory itself (About-dialog 'open data directory' case)", () => {+ expect(validateOpenPath(dataDir, dataDir, tmpDir)).toBe(path.resolve(dataDir));+ });++ it("accepts files under the data directory", () => {+ expect(validateOpenPath(dataFile, dataDir, tmpDir)).toBe(path.resolve(dataFile));+ });++ it("accepts files under the tmp dir (default 'TMP_DIR-is-a-subdir' layout)", () => {+ expect(validateOpenPath(tmpFile, dataDir, tmpDir)).toBe(path.resolve(tmpFile));+ });++ it("accepts files under a TRILIUM_TMP_DIR configured outside the data dir", () => {+ // This is the only reason both dataDir and tmpDir are passed in: when+ // the user sets TRILIUM_TMP_DIR to a custom location, files there+ // would otherwise fail the data-dir sandbox check.+ expect(validateOpenPath(separateTmpFile, dataDir, separateTmpDir))+ .toBe(path.resolve(separateTmpFile));+ });++ it.runIf(process.platform === "win32")(+ "matches sandbox roots case-insensitively on Windows",+ () => {+ expect(validateOpenPath(dataFile.toUpperCase(), dataDir, tmpDir))+ .toBe(path.resolve(dataFile.toUpperCase()));+ }+ );+});diff --git a/apps/server/src/services/open_path.ts b/apps/server/src/services/open_path.tsnew file mode 100644index 0000000000..ead42664b4--- /dev/null+++ b/apps/server/src/services/open_path.ts@@ -0,0 +1,41 @@+import fs from "fs";+import path from "path";++/**+ * Validates a path received from the renderer for the "open-path" IPC+ * channel. Returns the resolved absolute path on success; throws on any+ * invariant violation so a hostile or buggy caller surfaces loudly in the+ * main-process log.+ *+ * The two legitimate callers (Open Note/Attachment Externally, and the+ * "open data directory" link in the About dialog) only ever pass paths the+ * server itself produced — either inside Trilium's tmp dir or equal to the+ * data dir. Locking the IPC channel to that surface blocks the otherwise-+ * generic "open any file on disk" primitive (including UNC paths, which+ * resolve via SMB on Windows and leak the user's NTLM hash).+ */+export function validateOpenPath(input: unknown, dataDir: string, tmpDir: string): string {+ if (typeof input !== "string" || input.length === 0 || input.includes("\0")) {+ throw new Error("open-path: invalid filePath");+ }++ const resolved = path.resolve(input);+ const isWin = process.platform === "win32";+ const norm = (s: string) => isWin ? s.toLowerCase() : s;++ const isUnderOrEquals = (root: string) => {+ const r = path.resolve(root);+ return norm(resolved) === norm(r)+ || norm(resolved).startsWith(norm(r) + path.sep);+ };++ if (!isUnderOrEquals(dataDir) && !isUnderOrEquals(tmpDir)) {+ throw new Error(`open-path: refusing path outside data dir: ${resolved}`);+ }++ if (!fs.existsSync(resolved)) {+ throw new Error(`open-path: file does not exist: ${resolved}`);+ }++ return resolved;+}diff --git a/apps/server/src/services/window.ts b/apps/server/src/services/window.tsindex 40462c3145..27b7e18ff2 100644--- a/apps/server/src/services/window.ts+++ b/apps/server/src/services/window.ts@@ -13,6 +13,7 @@ import log from "./log.js";import { validateOpenCustomPath } from "./open_custom.js";import { validateOpenExternalUrl } from "./open_external.js";import { validateOpenFileUrl } from "./open_file_url.js";+import { validateOpenPath } from "./open_path.js";import optionService from "./options.js";import { initPrintingHandlers } from "./printing.js";import { RESOURCE_DIR } from "./resource_dir.js";@@ -223,7 +224,8 @@ electron.ipcMain.on("open-external", (_event, url: string) => {});electron.ipcMain.handle("open-path", (_event, filePath: string) => {- return electron.shell.openPath(filePath);+ const resolved = validateOpenPath(filePath, dataDirs.TRILIUM_DATA_DIR, dataDirs.TMP_DIR);+ return electron.shell.openPath(resolved);});electron.ipcMain.handle("open-file-url", (_event, fileUrl: string) => {