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
refactor(electron): group validators into one module
Elian Doran9bbfaae288db
diff --git a/apps/server/src/services/download_url.spec.ts b/apps/server/src/services/download_url.spec.tsdeleted file mode 100644index 2c800e42e6..0000000000--- a/apps/server/src/services/download_url.spec.ts+++ /dev/null@@ -1,87 +0,0 @@-import { describe, expect, it } from "vitest";--import { validateDownloadUrl } from "./download_url.js";--// Trilium's desktop renderer is served via a custom protocol whose origin is-// opaque per the WHATWG URL spec; this is the realistic page URL in production.-const DESKTOP_PAGE_URL = "trilium-app://app/";-// The web variant uses a plain HTTP origin.-const HTTP_PAGE_URL = "http://localhost:8080/index.html";--describe("validateDownloadUrl", () => {- it("rejects malformed input", () => {- expect(() => validateDownloadUrl(undefined, DESKTOP_PAGE_URL)).toThrow(/invalid URL/);- expect(() => validateDownloadUrl(null, DESKTOP_PAGE_URL)).toThrow(/invalid URL/);- expect(() => validateDownloadUrl(123, DESKTOP_PAGE_URL)).toThrow(/invalid URL/);- expect(() => validateDownloadUrl("", DESKTOP_PAGE_URL)).toThrow(/invalid URL/);- });-- it("rejects strings that don't parse as URLs", () => {- expect(() => validateDownloadUrl("not a url", DESKTOP_PAGE_URL)).toThrow(/not a valid URL/);- expect(() => validateDownloadUrl("example.com", DESKTOP_PAGE_URL)).toThrow(/not a valid URL/);- expect(() => validateDownloadUrl("/relative/path", DESKTOP_PAGE_URL))- .toThrow(/not a valid URL/);- });-- it("rejects cross-origin downloads (HTTP renderer)", () => {- // Different host- expect(() => validateDownloadUrl("https://attacker.example/malware.exe", HTTP_PAGE_URL))- .toThrow(/cross-origin download blocked/);- // Same host, different port- expect(() => validateDownloadUrl("http://localhost:9090/foo", HTTP_PAGE_URL))- .toThrow(/cross-origin download blocked/);- // Same host, different scheme- expect(() => validateDownloadUrl("https://localhost:8080/foo", HTTP_PAGE_URL))- .toThrow(/cross-origin download blocked/);- });-- it("rejects cross-origin downloads (custom-protocol renderer)", () => {- // Different scheme — common XSS attempt- expect(() => validateDownloadUrl("https://attacker.example/malware.exe", DESKTOP_PAGE_URL))- .toThrow(/cross-origin download blocked/);- // Same scheme, different host- expect(() => validateDownloadUrl("trilium-app://attacker/x", DESKTOP_PAGE_URL))- .toThrow(/cross-origin download blocked/);- });-- it("rejects URLs without a usable host on either side", () => {- // data:, file:///, about:, blob: all parse but have empty hostname.- // We refuse them because two such URLs would naively compare as- // same-origin (both have hostname === "") even when they shouldn't.- expect(() => validateDownloadUrl("data:text/plain,hello", DESKTOP_PAGE_URL))- .toThrow(/hostless URL not allowed/);- expect(() => validateDownloadUrl("file:///C:/Windows/System32/calc.exe", DESKTOP_PAGE_URL))- .toThrow(/hostless URL not allowed/);- expect(() => validateDownloadUrl("about:blank", DESKTOP_PAGE_URL))- .toThrow(/not a valid URL|hostless URL not allowed/);- // Same shape, but the allowed origin (the renderer itself) is hostless- expect(() => validateDownloadUrl("file:///C:/foo", "file:///C:/index.html"))- .toThrow(/hostless URL not allowed/);- });-- it("rejects when the allowed origin itself is malformed", () => {- expect(() => validateDownloadUrl(`${HTTP_PAGE_URL}`, "not a url"))- .toThrow(/invalid allowed origin/);- expect(() => validateDownloadUrl(`${HTTP_PAGE_URL}`, ""))- .toThrow(/invalid allowed origin/);- });-- it("accepts same-origin downloads via the trilium-app:// custom protocol", () => {- // The real production scenario. getUrlForDownload() in open.ts builds- // URLs of this shape from window.location.- expect(validateDownloadUrl("trilium-app://app/api/notes/abc/download", DESKTOP_PAGE_URL).toString())- .toBe("trilium-app://app/api/notes/abc/download");- expect(validateDownloadUrl("trilium-app://app/api/attachments/xyz/download?123", DESKTOP_PAGE_URL).toString())- .toBe("trilium-app://app/api/attachments/xyz/download?123");- expect(validateDownloadUrl("trilium-app://app/api/revisions/r1/download", DESKTOP_PAGE_URL).toString())- .toBe("trilium-app://app/api/revisions/r1/download");- expect(validateDownloadUrl("trilium-app://app/api/branches/b1/export/subtree/html/1/t1", DESKTOP_PAGE_URL).toString())- .toBe("trilium-app://app/api/branches/b1/export/subtree/html/1/t1");- });-- it("accepts same-origin downloads via plain HTTP", () => {- // Equivalent to the web variant or to alternate Electron configurations.- expect(validateDownloadUrl("http://localhost:8080/api/notes/abc/download", HTTP_PAGE_URL).toString())- .toBe("http://localhost:8080/api/notes/abc/download");- });-});diff --git a/apps/server/src/services/download_url.ts b/apps/server/src/services/download_url.tsdeleted file mode 100644index b7da10eb1b..0000000000--- a/apps/server/src/services/download_url.ts+++ /dev/null@@ -1,55 +0,0 @@-/**- * Validates a URL received from the renderer for the "download-url" IPC- * channel. Returns the parsed URL on success; throws on any invariant- * violation so a hostile or buggy caller surfaces loudly in the main-process- * log rather than silently triggering a download.- *- * The handler this gates (event.sender.downloadURL) writes a file straight- * to the user's Downloads folder with no save dialog. An unconstrained- * channel lets a compromised renderer (e.g. via XSS) pre-position malware- * disguised as a legitimate download for later execution. Locking it to the- * renderer's own origin closes the cross-origin abuse path while preserving- * the legitimate same-origin attachment / revision / export downloads.- */-export function validateDownloadUrl(input: unknown, allowedOrigin: string): URL {- if (typeof input !== "string" || input.length === 0) {- throw new Error("download-url: invalid URL");- }-- let parsed: URL;- try {- parsed = new URL(input);- } catch {- throw new Error(`download-url: not a valid URL: ${input}`);- }-- let allowed: URL;- try {- allowed = new URL(allowedOrigin);- } catch {- throw new Error(`download-url: invalid allowed origin: ${allowedOrigin}`);- }-- // We can't use URL.origin for the comparison because Electron serves the- // renderer via a custom protocol (trilium-app://app/) which the WHATWG URL- // spec treats as opaque-origin (.origin === "null"). Two opaque-origin URLs- // would always string-compare as equal even across different schemes/hosts.- //- // Instead, require both sides to have a non-empty hostname (rules out- // data:, file:///, about:, blob:) and compare scheme + hostname + port- // component-by-component.- if (allowed.hostname === "" || parsed.hostname === "") {- throw new Error("download-url: hostless URL not allowed");- }-- const sameOrigin = parsed.protocol === allowed.protocol- && parsed.hostname === allowed.hostname- && parsed.port === allowed.port;- if (!sameOrigin) {- throw new Error(- `download-url: cross-origin download blocked: ${parsed.protocol}//${parsed.host} (allowed: ${allowed.protocol}//${allowed.host})`- );- }-- return parsed;-}diff --git a/apps/server/src/services/open_custom.spec.ts b/apps/server/src/services/open_custom.spec.tsdeleted file mode 100644index c2051c4fd9..0000000000--- a/apps/server/src/services/open_custom.spec.ts+++ /dev/null@@ -1,84 +0,0 @@-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.tsdeleted file mode 100644index e8cb99ac73..0000000000--- a/apps/server/src/services/open_custom.ts+++ /dev/null@@ -1,34 +0,0 @@-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/open_external.spec.ts b/apps/server/src/services/open_external.spec.tsdeleted file mode 100644index ce9618e914..0000000000--- a/apps/server/src/services/open_external.spec.ts+++ /dev/null@@ -1,77 +0,0 @@-import { describe, expect, it } from "vitest";--import { validateOpenExternalUrl } from "./open_external.js";--describe("validateOpenExternalUrl", () => {- it("rejects malformed input", () => {- expect(() => validateOpenExternalUrl(undefined)).toThrow(/invalid URL/);- expect(() => validateOpenExternalUrl(null)).toThrow(/invalid URL/);- expect(() => validateOpenExternalUrl(123)).toThrow(/invalid URL/);- expect(() => validateOpenExternalUrl("")).toThrow(/invalid URL/);- });-- it("rejects strings that don't parse as URLs", () => {- expect(() => validateOpenExternalUrl("not a url")).toThrow(/not a valid URL/);- expect(() => validateOpenExternalUrl("example.com")).toThrow(/not a valid URL/);- expect(() => validateOpenExternalUrl("/relative/path")).toThrow(/not a valid URL/);- });-- it("rejects known-dangerous OS protocol-handler schemes", () => {- // Follina (CVE-2022-30190) and friends- expect(() => validateOpenExternalUrl("ms-msdt:/id PCWDiagnostic"))- .toThrow(/blocked scheme 'ms-msdt'/);- expect(() => validateOpenExternalUrl("search-ms:query=x&crumb=location:\\\\evil.example\\share"))- .toThrow(/blocked scheme 'search-ms'/);- expect(() => validateOpenExternalUrl("ms-officecmd:%7B%22LocalProviders%22:..."))- .toThrow(/blocked scheme 'ms-officecmd'/);-- // Script execution- expect(() => validateOpenExternalUrl("javascript:alert(1)"))- .toThrow(/blocked scheme 'javascript'/);- expect(() => validateOpenExternalUrl("vbscript:msgbox(1)"))- .toThrow(/blocked scheme 'vbscript'/);- });-- it("rejects schemes explicitly dropped from the openExternal allowlist", () => {- // local-file launcher (must go through openFileUrl instead)- expect(() => validateOpenExternalUrl("file:///C:/Windows/System32/calc.exe"))- .toThrow(/blocked scheme 'file'/);- // phishing surface- expect(() => validateOpenExternalUrl("data:text/html,<script>alert(1)</script>"))- .toThrow(/blocked scheme 'data'/);- // NTLM credential theft / SMB relay- expect(() => validateOpenExternalUrl("smb://attacker.example/share/file"))- .toThrow(/blocked scheme 'smb'/);- // NTLM relay / JNDI lookup- expect(() => validateOpenExternalUrl("ldap://attacker.example/dc=x"))- .toThrow(/blocked scheme 'ldap'/);- expect(() => validateOpenExternalUrl("ldaps://attacker.example/dc=x"))- .toThrow(/blocked scheme 'ldaps'/);- });-- it("accepts standard web and communication schemes", () => {- expect(validateOpenExternalUrl("https://example.com/path").toString())- .toBe("https://example.com/path");- expect(validateOpenExternalUrl("http://example.com/").toString())- .toBe("http://example.com/");- expect(validateOpenExternalUrl("mailto:[email protected]").toString())- .toBe("mailto:[email protected]");- expect(validateOpenExternalUrl("tel:+15551234").toString())- .toBe("tel:+15551234");- });-- it("accepts the note-app integration schemes (zotero/obsidian/etc.)", () => {- expect(() => validateOpenExternalUrl("zotero://select/items/0_ABC")).not.toThrow();- expect(() => validateOpenExternalUrl("obsidian://open?vault=Notes")).not.toThrow();- expect(() => validateOpenExternalUrl("logseq://x-callback-url/foo")).not.toThrow();- expect(() => validateOpenExternalUrl("evernote://x")).not.toThrow();- expect(() => validateOpenExternalUrl("onenote://x")).not.toThrow();- });-- it("matches the scheme case-insensitively", () => {- // URL.protocol returns lowercase, so HTTPS:// becomes "https:".- expect(() => validateOpenExternalUrl("HTTPS://example.com")).not.toThrow();- expect(() => validateOpenExternalUrl("MS-MSDT:/id x"))- .toThrow(/blocked scheme 'ms-msdt'/);- });-});diff --git a/apps/server/src/services/open_external.ts b/apps/server/src/services/open_external.tsdeleted file mode 100644index 6f87f99799..0000000000--- a/apps/server/src/services/open_external.ts+++ /dev/null@@ -1,33 +0,0 @@-import { SHELL_OPEN_EXTERNAL_PROTOCOLS } from "@triliumnext/commons";--/**- * Validates a URL received from the renderer for the "open-external" IPC- * channel. Returns the parsed URL on success; throws on any invariant- * violation so a hostile or buggy caller surfaces loudly in the main-process- * log rather than silently dispatching to an OS protocol handler.- *- * The handler this gates (electron.shell.openExternal) historically has been- * a Follina-class RCE primitive on Windows (ms-msdt:, search-ms:, etc.) and a- * credential-leak primitive (smb:, ldap:). Allowlisting the scheme is the- * only reliable defence.- */-export function validateOpenExternalUrl(input: unknown): URL {- if (typeof input !== "string" || input.length === 0) {- throw new Error("open-external: invalid URL");- }-- let parsed: URL;- try {- parsed = new URL(input);- } catch {- throw new Error(`open-external: not a valid URL: ${input}`);- }-- // URL.protocol returns "http:" — strip the trailing colon for comparison.- const scheme = parsed.protocol.replace(/:$/, "").toLowerCase();- if (!SHELL_OPEN_EXTERNAL_PROTOCOLS.includes(scheme)) {- throw new Error(`open-external: blocked scheme '${scheme}'`);- }-- return parsed;-}diff --git a/apps/server/src/services/open_file_url.spec.ts b/apps/server/src/services/open_file_url.spec.tsdeleted file mode 100644index d99093eeb5..0000000000--- a/apps/server/src/services/open_file_url.spec.ts+++ /dev/null@@ -1,54 +0,0 @@-import path from "path";-import { describe, expect, it } from "vitest";--import { validateOpenFileUrl } from "./open_file_url.js";--describe("validateOpenFileUrl", () => {- it("rejects malformed input", () => {- expect(() => validateOpenFileUrl(undefined)).toThrow(/invalid URL/);- expect(() => validateOpenFileUrl(null)).toThrow(/invalid URL/);- expect(() => validateOpenFileUrl(123)).toThrow(/invalid URL/);- expect(() => validateOpenFileUrl("")).toThrow(/invalid URL/);- });-- it("rejects strings that don't parse as URLs", () => {- expect(() => validateOpenFileUrl("not a url")).toThrow(/not a valid URL/);- expect(() => validateOpenFileUrl("/some/path")).toThrow(/not a valid URL/);- });-- it("rejects non-file: schemes", () => {- expect(() => validateOpenFileUrl("https://example.com/foo")).toThrow(/not a file: URL/);- expect(() => validateOpenFileUrl("smb://attacker.example/share/x"))- .toThrow(/not a file: URL/);- });-- it("rejects UNC paths (the NTLM-credential-theft vector)", () => {- // Classic UNC: file: URL with a non-empty hostname resolves to- // \\host\share\x on Windows, triggering SMB auth and leaking NTLM hash.- expect(() => validateOpenFileUrl("file://attacker.example/share/x"))- .toThrow(/UNC path blocked: attacker\.example/);- expect(() => validateOpenFileUrl("file://192.168.1.1/c$/Windows"))- .toThrow(/UNC path blocked: 192\.168\.1\.1/);- });-- it.runIf(process.platform === "win32")(- "accepts and resolves normal Windows file: URLs",- () => {- expect(validateOpenFileUrl("file:///C:/Windows/notepad.exe"))- .toBe(path.win32.normalize("C:\\Windows\\notepad.exe"));- // Malformed form some sources emit: file://C:/path (drive letter as host).- // The validator normalises this before the empty-host check.- expect(validateOpenFileUrl("file://C:/Windows/notepad.exe"))- .toBe(path.win32.normalize("C:\\Windows\\notepad.exe"));- }- );-- it.runIf(process.platform !== "win32")(- "accepts and resolves normal POSIX file: URLs",- () => {- expect(validateOpenFileUrl("file:///etc/hosts")).toBe("/etc/hosts");- expect(validateOpenFileUrl("file:///tmp/foo bar"))- .toBe("/tmp/foo bar");- }- );-});diff --git a/apps/server/src/services/open_file_url.ts b/apps/server/src/services/open_file_url.tsdeleted file mode 100644index 47e120e712..0000000000--- a/apps/server/src/services/open_file_url.ts+++ /dev/null@@ -1,40 +0,0 @@-import url from "url";--/**- * Validates a URL received from the renderer for the "open-file-url" IPC- * channel and returns the resolved filesystem path. Throws on any invariant- * violation so a hostile caller surfaces loudly in the main-process log.- *- * The specific threat blocked here is UNC paths: a file: URL with a non-empty- * hostname (file://attacker.example/share/x) resolves on Windows to- * \\attacker.example\share\x, which triggers SMB authentication and leaks the- * logged-in user's NTLM hash to the attacker — the same primitive blocked for- * smb:// URLs in the openExternal allowlist.- */-export function validateOpenFileUrl(input: unknown): string {- if (typeof input !== "string" || input.length === 0) {- throw new Error("open-file-url: invalid URL");- }-- // Some sources produce malformed file URLs that look like file://C:/path- // (drive letter parsed as the host). Insert the missing slash so the URL- // parser sees file:///C:/path with an empty host.- const normalized = input.replace(/^file:\/\/(?=[a-zA-Z]:)/i, "file:///");-- let parsed: URL;- try {- parsed = new URL(normalized);- } catch {- throw new Error(`open-file-url: not a valid URL: ${input}`);- }-- if (parsed.protocol !== "file:") {- throw new Error(`open-file-url: not a file: URL: ${input}`);- }-- if (parsed.hostname !== "") {- throw new Error(`open-file-url: UNC path blocked: ${parsed.hostname}`);- }-- return url.fileURLToPath(parsed);-}diff --git a/apps/server/src/services/open_path.spec.ts b/apps/server/src/services/open_path.spec.tsdeleted file mode 100644index ec1ec5e7f9..0000000000--- a/apps/server/src/services/open_path.spec.ts+++ /dev/null@@ -1,119 +0,0 @@-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.tsdeleted file mode 100644index ead42664b4..0000000000--- a/apps/server/src/services/open_path.ts+++ /dev/null@@ -1,41 +0,0 @@-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/shell_validators.spec.ts b/apps/server/src/services/shell_validators.spec.tsnew file mode 100644index 0000000000..d73ae2dea7--- /dev/null+++ b/apps/server/src/services/shell_validators.spec.ts@@ -0,0 +1,390 @@+import fs from "fs";+import os from "os";+import path from "path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";++import {+ validateDownloadUrl,+ validateOpenCustomPath,+ validateOpenExternalUrl,+ validateOpenFileUrl,+ validateOpenPath+} from "./shell_validators.js";++// ============================================================================+// validateOpenCustomPath+// ============================================================================++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/);++ const traversal = path.join(tmpDir, "..", "..", "..", "evil.txt");+ expect(() => validateOpenCustomPath(traversal, tmpDir)).toThrow(/outside tmpdir/);++ expect(() => validateOpenCustomPath("foo.txt", tmpDir)).toThrow(/outside tmpdir/);++ // Sibling-prefix near-miss+ 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",+ () => {+ const mixed = validFile.toUpperCase();+ expect(validateOpenCustomPath(mixed, tmpDir)).toBe(path.resolve(mixed));+ }+ );+});++// ============================================================================+// validateOpenPath+// ============================================================================++describe("validateOpenPath", () => {+ let dataDir: string;+ let tmpDir: string;+ let separateTmpDir: string;+ let dataFile: string;+ let tmpFile: string;+ let separateTmpFile: string;++ beforeAll(() => {+ // 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", () => {+ const outside = process.platform === "win32" ? "C:\\Windows\\Temp\\evil.txt" : "/etc/passwd";+ expect(() => validateOpenPath(outside, dataDir, tmpDir)).toThrow(/outside data dir/);++ const traversal = path.join(dataDir, "..", "..", "..", "evil.txt");+ expect(() => validateOpenPath(traversal, dataDir, tmpDir)).toThrow(/outside data dir/);++ expect(() => validateOpenPath("foo.txt", dataDir, tmpDir)).toThrow(/outside data dir/);++ 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)", () => {+ 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", () => {+ 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()));+ }+ );+});++// ============================================================================+// validateOpenExternalUrl+// ============================================================================++describe("validateOpenExternalUrl", () => {+ it("rejects malformed input", () => {+ expect(() => validateOpenExternalUrl(undefined)).toThrow(/invalid URL/);+ expect(() => validateOpenExternalUrl(null)).toThrow(/invalid URL/);+ expect(() => validateOpenExternalUrl(123)).toThrow(/invalid URL/);+ expect(() => validateOpenExternalUrl("")).toThrow(/invalid URL/);+ });++ it("rejects strings that don't parse as URLs", () => {+ expect(() => validateOpenExternalUrl("not a url")).toThrow(/not a valid URL/);+ expect(() => validateOpenExternalUrl("example.com")).toThrow(/not a valid URL/);+ expect(() => validateOpenExternalUrl("/relative/path")).toThrow(/not a valid URL/);+ });++ it("rejects known-dangerous OS protocol-handler schemes", () => {+ // Follina (CVE-2022-30190) and friends+ expect(() => validateOpenExternalUrl("ms-msdt:/id PCWDiagnostic"))+ .toThrow(/blocked scheme 'ms-msdt'/);+ expect(() => validateOpenExternalUrl("search-ms:query=x&crumb=location:\\\\evil.example\\share"))+ .toThrow(/blocked scheme 'search-ms'/);+ expect(() => validateOpenExternalUrl("ms-officecmd:%7B%22LocalProviders%22:..."))+ .toThrow(/blocked scheme 'ms-officecmd'/);++ // Script execution+ expect(() => validateOpenExternalUrl("javascript:alert(1)"))+ .toThrow(/blocked scheme 'javascript'/);+ expect(() => validateOpenExternalUrl("vbscript:msgbox(1)"))+ .toThrow(/blocked scheme 'vbscript'/);+ });++ it("rejects schemes explicitly dropped from the openExternal allowlist", () => {+ expect(() => validateOpenExternalUrl("file:///C:/Windows/System32/calc.exe"))+ .toThrow(/blocked scheme 'file'/);+ expect(() => validateOpenExternalUrl("data:text/html,<script>alert(1)</script>"))+ .toThrow(/blocked scheme 'data'/);+ expect(() => validateOpenExternalUrl("smb://attacker.example/share/file"))+ .toThrow(/blocked scheme 'smb'/);+ expect(() => validateOpenExternalUrl("ldap://attacker.example/dc=x"))+ .toThrow(/blocked scheme 'ldap'/);+ expect(() => validateOpenExternalUrl("ldaps://attacker.example/dc=x"))+ .toThrow(/blocked scheme 'ldaps'/);+ });++ it("accepts standard web and communication schemes", () => {+ expect(validateOpenExternalUrl("https://example.com/path").toString())+ .toBe("https://example.com/path");+ expect(validateOpenExternalUrl("http://example.com/").toString())+ .toBe("http://example.com/");+ expect(validateOpenExternalUrl("mailto:[email protected]").toString())+ .toBe("mailto:[email protected]");+ expect(validateOpenExternalUrl("tel:+15551234").toString())+ .toBe("tel:+15551234");+ });++ it("accepts the note-app integration schemes (zotero/obsidian/etc.)", () => {+ expect(() => validateOpenExternalUrl("zotero://select/items/0_ABC")).not.toThrow();+ expect(() => validateOpenExternalUrl("obsidian://open?vault=Notes")).not.toThrow();+ expect(() => validateOpenExternalUrl("logseq://x-callback-url/foo")).not.toThrow();+ expect(() => validateOpenExternalUrl("evernote://x")).not.toThrow();+ expect(() => validateOpenExternalUrl("onenote://x")).not.toThrow();+ });++ it("matches the scheme case-insensitively", () => {+ expect(() => validateOpenExternalUrl("HTTPS://example.com")).not.toThrow();+ expect(() => validateOpenExternalUrl("MS-MSDT:/id x"))+ .toThrow(/blocked scheme 'ms-msdt'/);+ });+});++// ============================================================================+// validateOpenFileUrl+// ============================================================================++describe("validateOpenFileUrl", () => {+ it("rejects malformed input", () => {+ expect(() => validateOpenFileUrl(undefined)).toThrow(/invalid URL/);+ expect(() => validateOpenFileUrl(null)).toThrow(/invalid URL/);+ expect(() => validateOpenFileUrl(123)).toThrow(/invalid URL/);+ expect(() => validateOpenFileUrl("")).toThrow(/invalid URL/);+ });++ it("rejects strings that don't parse as URLs", () => {+ expect(() => validateOpenFileUrl("not a url")).toThrow(/not a valid URL/);+ expect(() => validateOpenFileUrl("/some/path")).toThrow(/not a valid URL/);+ });++ it("rejects non-file: schemes", () => {+ expect(() => validateOpenFileUrl("https://example.com/foo")).toThrow(/not a file: URL/);+ expect(() => validateOpenFileUrl("smb://attacker.example/share/x"))+ .toThrow(/not a file: URL/);+ });++ it("rejects UNC paths (the NTLM-credential-theft vector)", () => {+ expect(() => validateOpenFileUrl("file://attacker.example/share/x"))+ .toThrow(/UNC path blocked: attacker\.example/);+ expect(() => validateOpenFileUrl("file://192.168.1.1/c$/Windows"))+ .toThrow(/UNC path blocked: 192\.168\.1\.1/);+ });++ it.runIf(process.platform === "win32")(+ "accepts and resolves normal Windows file: URLs",+ () => {+ expect(validateOpenFileUrl("file:///C:/Windows/notepad.exe"))+ .toBe(path.win32.normalize("C:\\Windows\\notepad.exe"));+ // Malformed form some sources emit: file://C:/path (drive letter as host).+ expect(validateOpenFileUrl("file://C:/Windows/notepad.exe"))+ .toBe(path.win32.normalize("C:\\Windows\\notepad.exe"));+ }+ );++ it.runIf(process.platform !== "win32")(+ "accepts and resolves normal POSIX file: URLs",+ () => {+ expect(validateOpenFileUrl("file:///etc/hosts")).toBe("/etc/hosts");+ expect(validateOpenFileUrl("file:///tmp/foo bar")).toBe("/tmp/foo bar");+ }+ );+});++// ============================================================================+// validateDownloadUrl+// ============================================================================++// Trilium's desktop renderer is served via a custom protocol whose origin is+// opaque per the WHATWG URL spec; this is the realistic page URL in production.+const DESKTOP_PAGE_URL = "trilium-app://app/";+// The web variant uses a plain HTTP origin.+const HTTP_PAGE_URL = "http://localhost:8080/index.html";++describe("validateDownloadUrl", () => {+ it("rejects malformed input", () => {+ expect(() => validateDownloadUrl(undefined, DESKTOP_PAGE_URL)).toThrow(/invalid URL/);+ expect(() => validateDownloadUrl(null, DESKTOP_PAGE_URL)).toThrow(/invalid URL/);+ expect(() => validateDownloadUrl(123, DESKTOP_PAGE_URL)).toThrow(/invalid URL/);+ expect(() => validateDownloadUrl("", DESKTOP_PAGE_URL)).toThrow(/invalid URL/);+ });++ it("rejects strings that don't parse as URLs", () => {+ expect(() => validateDownloadUrl("not a url", DESKTOP_PAGE_URL)).toThrow(/not a valid URL/);+ expect(() => validateDownloadUrl("example.com", DESKTOP_PAGE_URL)).toThrow(/not a valid URL/);+ expect(() => validateDownloadUrl("/relative/path", DESKTOP_PAGE_URL))+ .toThrow(/not a valid URL/);+ });++ it("rejects cross-origin downloads (HTTP renderer)", () => {+ expect(() => validateDownloadUrl("https://attacker.example/malware.exe", HTTP_PAGE_URL))+ .toThrow(/cross-origin download blocked/);+ expect(() => validateDownloadUrl("http://localhost:9090/foo", HTTP_PAGE_URL))+ .toThrow(/cross-origin download blocked/);+ expect(() => validateDownloadUrl("https://localhost:8080/foo", HTTP_PAGE_URL))+ .toThrow(/cross-origin download blocked/);+ });++ it("rejects cross-origin downloads (custom-protocol renderer)", () => {+ expect(() => validateDownloadUrl("https://attacker.example/malware.exe", DESKTOP_PAGE_URL))+ .toThrow(/cross-origin download blocked/);+ expect(() => validateDownloadUrl("trilium-app://attacker/x", DESKTOP_PAGE_URL))+ .toThrow(/cross-origin download blocked/);+ });++ it("rejects URLs without a usable host on either side", () => {+ // data:, file:///, about:, blob: all parse but have empty hostname.+ expect(() => validateDownloadUrl("data:text/plain,hello", DESKTOP_PAGE_URL))+ .toThrow(/hostless URL not allowed/);+ expect(() => validateDownloadUrl("file:///C:/Windows/System32/calc.exe", DESKTOP_PAGE_URL))+ .toThrow(/hostless URL not allowed/);+ expect(() => validateDownloadUrl("about:blank", DESKTOP_PAGE_URL))+ .toThrow(/not a valid URL|hostless URL not allowed/);+ expect(() => validateDownloadUrl("file:///C:/foo", "file:///C:/index.html"))+ .toThrow(/hostless URL not allowed/);+ });++ it("rejects when the allowed origin itself is malformed", () => {+ expect(() => validateDownloadUrl(`${HTTP_PAGE_URL}`, "not a url"))+ .toThrow(/invalid allowed origin/);+ expect(() => validateDownloadUrl(`${HTTP_PAGE_URL}`, ""))+ .toThrow(/invalid allowed origin/);+ });++ it("accepts same-origin downloads via the trilium-app:// custom protocol", () => {+ expect(validateDownloadUrl("trilium-app://app/api/notes/abc/download", DESKTOP_PAGE_URL).toString())+ .toBe("trilium-app://app/api/notes/abc/download");+ expect(validateDownloadUrl("trilium-app://app/api/attachments/xyz/download?123", DESKTOP_PAGE_URL).toString())+ .toBe("trilium-app://app/api/attachments/xyz/download?123");+ expect(validateDownloadUrl("trilium-app://app/api/revisions/r1/download", DESKTOP_PAGE_URL).toString())+ .toBe("trilium-app://app/api/revisions/r1/download");+ expect(validateDownloadUrl("trilium-app://app/api/branches/b1/export/subtree/html/1/t1", DESKTOP_PAGE_URL).toString())+ .toBe("trilium-app://app/api/branches/b1/export/subtree/html/1/t1");+ });++ it("accepts same-origin downloads via plain HTTP", () => {+ expect(validateDownloadUrl("http://localhost:8080/api/notes/abc/download", HTTP_PAGE_URL).toString())+ .toBe("http://localhost:8080/api/notes/abc/download");+ });+});diff --git a/apps/server/src/services/shell_validators.ts b/apps/server/src/services/shell_validators.tsnew file mode 100644index 0000000000..c47142322c--- /dev/null+++ b/apps/server/src/services/shell_validators.ts@@ -0,0 +1,219 @@+import fs from "fs";+import path from "path";+import url from "url";++import { SHELL_OPEN_EXTERNAL_PROTOCOLS } from "@triliumnext/commons";++/**+ * Input validators for every IPC channel under window.electronApi.shell.+ *+ * Each validator throws on any invariant violation so a hostile or buggy+ * caller surfaces loudly in the main-process log rather than silently+ * triggering an OS-level action. The handlers in window.ts delegate to these+ * functions before invoking the underlying electron.shell / WebContents APIs.+ */++// ============================================================================+// Shared helpers+// ============================================================================++/** Windows filesystems are case-insensitive, POSIX are case-sensitive. */+function normalizeForCompare(p: string): string {+ return process.platform === "win32" ? p.toLowerCase() : p;+}++/** True if `resolved` is a strict descendant of `root` (not `root` itself). */+function isStrictlyUnder(resolved: string, root: string): boolean {+ const prefix = path.resolve(root) + path.sep;+ return normalizeForCompare(resolved).startsWith(normalizeForCompare(prefix));+}++/** True if `resolved` equals `root` or is a descendant. */+function isUnderOrEquals(resolved: string, root: string): boolean {+ return normalizeForCompare(resolved) === normalizeForCompare(path.resolve(root))+ || isStrictlyUnder(resolved, root);+}++// ============================================================================+// open-custom — sandbox to Trilium's tmp dir + existence check+// ============================================================================++/**+ * Validates a path for the "open-custom" IPC channel (renderer asks the main+ * process to invoke Windows' "Open With…" dialog or the Linux mimeopen flow).+ * The legit caller always passes a path freshly written by saveToTmpDir, so+ * the path must live under that dir and the file must exist 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);+ if (!isStrictlyUnder(resolved, tmpDir)) {+ 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;+}++// ============================================================================+// open-path — sandbox to Trilium's data dir ∪ tmp dir + existence check+// ============================================================================++/**+ * Validates a path for the "open-path" IPC channel (Open Note Externally,+ * Open Attachment Externally, and the "open data directory" link in the+ * About dialog). The legit callers only ever pass server-generated paths+ * either inside the tmp dir or equal to the data dir itself.+ *+ * UNC paths are blocked implicitly — they cannot normalise to a descendant+ * of the data/tmp dirs, so the sandbox check rejects them. This closes the+ * NTLM-hash-leak vector that affects file:// and smb:// URLs.+ */+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);+ if (!isUnderOrEquals(resolved, dataDir) && !isUnderOrEquals(resolved, 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;+}++// ============================================================================+// open-external — scheme allowlist+// ============================================================================++/**+ * Validates a URL for the "open-external" IPC channel (electron.shell.openExternal,+ * which hands the URL to the OS protocol handler). Historically this is a+ * Follina-class RCE primitive on Windows (ms-msdt:, search-ms:, ms-officecmd:)+ * and a credential-leak primitive (smb:, ldap:). Allowlisting the scheme is+ * the only reliable defence — see SHELL_OPEN_EXTERNAL_PROTOCOLS in commons.+ */+export function validateOpenExternalUrl(input: unknown): URL {+ if (typeof input !== "string" || input.length === 0) {+ throw new Error("open-external: invalid URL");+ }++ let parsed: URL;+ try {+ parsed = new URL(input);+ } catch {+ throw new Error(`open-external: not a valid URL: ${input}`);+ }++ // URL.protocol returns "http:" — strip the trailing colon for comparison.+ const scheme = parsed.protocol.replace(/:$/, "").toLowerCase();+ if (!SHELL_OPEN_EXTERNAL_PROTOCOLS.includes(scheme)) {+ throw new Error(`open-external: blocked scheme '${scheme}'`);+ }++ return parsed;+}++// ============================================================================+// open-file-url — block UNC paths+// ============================================================================++/**+ * Validates a URL for the "open-file-url" IPC channel and returns the+ * resolved filesystem path. The specific threat blocked here is UNC paths:+ * a file: URL with a non-empty hostname (file://attacker.example/share/x)+ * resolves on Windows to \\attacker.example\share\x, which triggers SMB+ * authentication and leaks the user's NTLM hash to the attacker.+ */+export function validateOpenFileUrl(input: unknown): string {+ if (typeof input !== "string" || input.length === 0) {+ throw new Error("open-file-url: invalid URL");+ }++ // Some sources produce malformed file URLs that look like file://C:/path+ // (drive letter parsed as the host). Insert the missing slash so the URL+ // parser sees file:///C:/path with an empty host.+ const normalized = input.replace(/^file:\/\/(?=[a-zA-Z]:)/i, "file:///");++ let parsed: URL;+ try {+ parsed = new URL(normalized);+ } catch {+ throw new Error(`open-file-url: not a valid URL: ${input}`);+ }++ if (parsed.protocol !== "file:") {+ throw new Error(`open-file-url: not a file: URL: ${input}`);+ }++ if (parsed.hostname !== "") {+ throw new Error(`open-file-url: UNC path blocked: ${parsed.hostname}`);+ }++ return url.fileURLToPath(parsed);+}++// ============================================================================+// download-url — same-origin lock+// ============================================================================++/**+ * Validates a URL for the "download-url" IPC channel (WebContents.downloadURL,+ * which writes the response straight to the user's Downloads folder).+ * Locking it to the renderer's own origin closes the cross-origin abuse path+ * (a compromised renderer pre-positioning a malicious file disguised as a+ * legitimate download) while preserving the legitimate same-origin+ * attachment / revision / export downloads.+ */+export function validateDownloadUrl(input: unknown, allowedOrigin: string): URL {+ if (typeof input !== "string" || input.length === 0) {+ throw new Error("download-url: invalid URL");+ }++ let parsed: URL;+ try {+ parsed = new URL(input);+ } catch {+ throw new Error(`download-url: not a valid URL: ${input}`);+ }++ let allowed: URL;+ try {+ allowed = new URL(allowedOrigin);+ } catch {+ throw new Error(`download-url: invalid allowed origin: ${allowedOrigin}`);+ }++ // We can't use URL.origin for the comparison because Electron serves the+ // renderer via a custom protocol (trilium-app://app/) which the WHATWG URL+ // spec treats as opaque-origin (.origin === "null"). Two opaque-origin URLs+ // would always string-compare as equal even across different schemes/hosts.+ //+ // Instead, require both sides to have a non-empty hostname (rules out+ // data:, file:///, about:, blob:) and compare scheme + hostname + port+ // component-by-component.+ if (allowed.hostname === "" || parsed.hostname === "") {+ throw new Error("download-url: hostless URL not allowed");+ }++ const sameOrigin = parsed.protocol === allowed.protocol+ && parsed.hostname === allowed.hostname+ && parsed.port === allowed.port;+ if (!sameOrigin) {+ throw new Error(+ `download-url: cross-origin download blocked: ${parsed.protocol}//${parsed.host} (allowed: ${allowed.protocol}//${allowed.host})`+ );+ }++ return parsed;+}diff --git a/apps/server/src/services/window.ts b/apps/server/src/services/window.tsindex 27b7e18ff2..3f7c370132 100644--- a/apps/server/src/services/window.ts+++ b/apps/server/src/services/window.ts@@ -7,14 +7,16 @@ import app_info from "./app_info.js";import cls from "./cls.js";import customDictionary from "./custom_dictionary.js";import dataDirs from "./data_dir.js";-import { validateDownloadUrl } from "./download_url.js";import keyboardActionsService from "./keyboard_actions.js";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 {+ validateDownloadUrl,+ validateOpenCustomPath,+ validateOpenExternalUrl,+ validateOpenFileUrl,+ validateOpenPath+} from "./shell_validators.js";import { initPrintingHandlers } from "./printing.js";import { RESOURCE_DIR } from "./resource_dir.js";import sqlInit from "./sql_init.js";