Skip to content

Build your personal knowledge base with Trilium Notes

test(electron): open note custom

Elian Doran90a2b31106a3
diff --git a/apps/server/src/services/open_custom.spec.ts b/apps/server/src/services/open_custom.spec.ts
new file mode 100644
index 0000000000..c2051c4fd9
--- /dev/null
+++ b/apps/server/src/services/open_custom.spec.ts
@@ -0,0 +1,84 @@
+import fs from "fs";
+import os from "os";
+import path from "path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+
+import { validateOpenCustomPath } from "./open_custom.js";
+
+describe("validateOpenCustomPath", () => {
+ let tmpDir: string;
+ let validFile: string;
+ let hostileFile: string;
+
+ beforeAll(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "trilium-open-custom-"));
+ validFile = path.join(tmpDir, "plain.txt");
+ fs.writeFileSync(validFile, "");
+ // A filename containing `&` is the original command-injection regression:
+ // when the path was interpolated into a cmd.exe string, the `&` chained
+ // arbitrary commands. The validator must ACCEPT this filename — the fix
+ // is to never route through a shell, not to reject the name.
+ hostileFile = path.join(tmpDir, "foo & calc & rem .txt");
+ fs.writeFileSync(hostileFile, "");
+ });
+
+ afterAll(() => {
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+ });
+
+ it("rejects malformed input", () => {
+ expect(() => validateOpenCustomPath(undefined, tmpDir)).toThrow(/invalid filePath/);
+ expect(() => validateOpenCustomPath(null, tmpDir)).toThrow(/invalid filePath/);
+ expect(() => validateOpenCustomPath(123, tmpDir)).toThrow(/invalid filePath/);
+ expect(() => validateOpenCustomPath({}, tmpDir)).toThrow(/invalid filePath/);
+ expect(() => validateOpenCustomPath("", tmpDir)).toThrow(/invalid filePath/);
+ expect(() => validateOpenCustomPath(path.join(tmpDir, "foo\0.txt"), tmpDir))
+ .toThrow(/invalid filePath/);
+ });
+
+ it("rejects paths outside the sandbox", () => {
+ const outside = process.platform === "win32" ? "C:\\Windows\\Temp\\evil.txt" : "/etc/passwd";
+ expect(() => validateOpenCustomPath(outside, tmpDir)).toThrow(/outside tmpdir/);
+
+ // ".." traversal escapes the sandbox after path.resolve normalisation
+ const traversal = path.join(tmpDir, "..", "..", "..", "evil.txt");
+ expect(() => validateOpenCustomPath(traversal, tmpDir)).toThrow(/outside tmpdir/);
+
+ // Relative paths resolve against cwd, not tmpDir
+ expect(() => validateOpenCustomPath("foo.txt", tmpDir)).toThrow(/outside tmpdir/);
+
+ // Near-miss: a sibling directory whose name starts with tmpDir's name
+ // must not satisfy the prefix check.
+ const sibling = tmpDir + "-evil";
+ fs.mkdirSync(sibling);
+ try {
+ const siblingFile = path.join(sibling, "x.txt");
+ fs.writeFileSync(siblingFile, "");
+ expect(() => validateOpenCustomPath(siblingFile, tmpDir)).toThrow(/outside tmpdir/);
+ } finally {
+ fs.rmSync(sibling, { recursive: true, force: true });
+ }
+ });
+
+ it("rejects nonexistent files inside the sandbox", () => {
+ const missing = path.join(tmpDir, "does-not-exist.txt");
+ expect(() => validateOpenCustomPath(missing, tmpDir)).toThrow(/does not exist/);
+ });
+
+ it("accepts valid paths, including filenames with shell metacharacters", () => {
+ expect(validateOpenCustomPath(validFile, tmpDir)).toBe(path.resolve(validFile));
+ // Regression for the original `cmd.exe` injection vulnerability.
+ expect(validateOpenCustomPath(hostileFile, tmpDir)).toBe(path.resolve(hostileFile));
+ });
+
+ it.runIf(process.platform === "win32")(
+ "matches tmpdir case-insensitively on Windows",
+ () => {
+ // Renderer may send the path with different drive-letter / directory casing
+ // than os.tmpdir() reports; Windows paths are case-insensitive so this
+ // must still pass.
+ const mixed = validFile.toUpperCase();
+ expect(validateOpenCustomPath(mixed, tmpDir)).toBe(path.resolve(mixed));
+ }
+ );
+});
diff --git a/apps/server/src/services/open_custom.ts b/apps/server/src/services/open_custom.ts
new file mode 100644
index 0000000000..e8cb99ac73
--- /dev/null
+++ b/apps/server/src/services/open_custom.ts
@@ -0,0 +1,34 @@
+import fs from "fs";
+import path from "path";
+
+/**
+ * Validates a path received from the renderer for the "open-custom" 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 rather than silently doing something unexpected.
+ *
+ * Invariants:
+ * - filePath is a non-empty string with no NUL byte
+ * - resolves strictly under `tmpDir` (no traversal, no arbitrary locations)
+ * - the file actually exists on disk
+ */
+export function validateOpenCustomPath(filePath: unknown, tmpDir: string): string {
+ if (typeof filePath !== "string" || filePath.length === 0 || filePath.includes("\0")) {
+ throw new Error("open-custom: invalid filePath");
+ }
+
+ const resolved = path.resolve(filePath);
+ const tmpRoot = path.resolve(tmpDir) + path.sep;
+ const inTmp = process.platform === "win32"
+ ? resolved.toLowerCase().startsWith(tmpRoot.toLowerCase())
+ : resolved.startsWith(tmpRoot);
+ if (!inTmp) {
+ throw new Error(`open-custom: refusing path outside tmpdir: ${resolved}`);
+ }
+
+ if (!fs.existsSync(resolved)) {
+ throw new Error(`open-custom: file does not exist: ${resolved}`);
+ }
+
+ return resolved;
+}
diff --git a/apps/server/src/services/window.ts b/apps/server/src/services/window.ts
index f137ace95d..b3efe454a6 100644
--- a/apps/server/src/services/window.ts
+++ b/apps/server/src/services/window.ts
@@ -1,6 +1,5 @@
import { execFile } from "child_process";
import { type App, type BrowserWindow, type BrowserWindowConstructorOptions, default as electron, type Session, type WebContents } from "electron";
-import fs from "fs";
import path from "path";
import url from "url";
@@ -10,6 +9,7 @@ import customDictionary from "./custom_dictionary.js";
import dataDirs from "./data_dir.js";
import keyboardActionsService from "./keyboard_actions.js";
import log from "./log.js";
+import { validateOpenCustomPath } from "./open_custom.js";
import optionService from "./options.js";
import { initPrintingHandlers } from "./printing.js";
import { RESOURCE_DIR } from "./resource_dir.js";
@@ -232,25 +232,11 @@ electron.ipcMain.on("download-url", (event, downloadUrl: string) => {
});
electron.ipcMain.on("open-custom", (_event, filePath: string) => {
- if (typeof filePath !== "string" || filePath.length === 0 || filePath.includes("\0")) {
- throw new Error("open-custom: invalid filePath");
- }
-
- // Defense in depth: only allow paths the server itself wrote into Trilium's
- // tmp dir via /api/.../save-to-tmp-dir. Without this, a compromised
- // renderer (e.g. via XSS) could ask us to launch arbitrary local files.
- const resolved = path.resolve(filePath);
- const tmpRoot = path.resolve(dataDirs.TMP_DIR) + path.sep;
- const inTmp = process.platform === "win32"
- ? resolved.toLowerCase().startsWith(tmpRoot.toLowerCase())
- : resolved.startsWith(tmpRoot);
- if (!inTmp) {
- throw new Error(`open-custom: refusing path outside tmpdir: ${resolved}`);
- }
-
- if (!fs.existsSync(resolved)) {
- throw new Error(`open-custom: file does not exist: ${resolved}`);
- }
+ // Defense in depth: validate the path is one the server itself wrote into
+ // Trilium's tmp dir via /api/.../save-to-tmp-dir, and that it exists.
+ // Without this, a compromised renderer (e.g. via XSS) could ask us to
+ // launch arbitrary local files.
+ const resolved = validateOpenCustomPath(filePath, dataDirs.TMP_DIR);
const platform = process.platform;