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(desktop): move shell validators from server
Elian Doranb857818ffd51
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex bad10c438c..ce7f2dd8de 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -25,6 +25,7 @@ import IpcMessagingProvider from "./ipc_messaging_provider";import DesktopPlatformProvider from "./platform_provider";import { registerTriliumAppScheme } from "./protocol";import { setupCustomDictionary } from "./services/custom_dictionary";+import { setupShellHandlers } from "./services/shell";import { setupSystemTray } from "./services/tray";async function main() {@@ -93,6 +94,7 @@ async function main() {setupSystemTray();setupCustomDictionary();+ setupShellHandlers();app.on("will-quit", () => {globalShortcut.unregisterAll();diff --git a/apps/server/src/services/shell_validators.spec.ts b/apps/desktop/src/services/shell.spec.tssimilarity index 99%rename from apps/server/src/services/shell_validators.spec.tsrename to apps/desktop/src/services/shell.spec.tsindex ca40c0946c..5eaabd2419 100644--- a/apps/server/src/services/shell_validators.spec.ts+++ b/apps/desktop/src/services/shell.spec.ts@@ -9,7 +9,7 @@ import {validateOpenExternalUrl,validateOpenFileUrl,validateOpenPath-} from "./shell_validators.js";+} from "./shell.js";//#region validateOpenCustomPathdiff --git a/apps/server/src/services/shell_validators.ts b/apps/desktop/src/services/shell.tssimilarity index 59%rename from apps/server/src/services/shell_validators.tsrename to apps/desktop/src/services/shell.tsindex a0da59e455..db7b7363bf 100644--- a/apps/server/src/services/shell_validators.ts+++ b/apps/desktop/src/services/shell.ts@@ -1,16 +1,19 @@+import { SHELL_OPEN_EXTERNAL_PROTOCOLS } from "@triliumnext/commons";+import { utils as coreUtils } from "@triliumnext/core";+import dataDirs from "@triliumnext/server/src/services/data_dir.js";+import log from "@triliumnext/server/src/services/log.js";+import { execFile } from "child_process";+import electron from "electron";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.+ * Handlers for `window.electronApi.shell.*` IPC channels.*- * 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.+ * Each call is gated by an input validator that 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.*///#region Shared helpers@@ -217,3 +220,106 @@ export function validateDownloadUrl(input: unknown, allowedOrigin: string): URL}//#endregion++//#region IPC wiring++/**+ * Registers the IPC handlers that back `window.electronApi.shell.*`.+ *+ * Every channel validates its input (see the per-region docstrings) before+ * calling into `electron.shell` / `WebContents` / `execFile`, so a compromised+ * renderer cannot trick the main process into launching arbitrary paths or+ * URLs.+ */+export function setupShellHandlers() {+ electron.ipcMain.on("open-external", (_event, externalUrl: string) => {+ try {+ const validated = validateOpenExternalUrl(externalUrl);+ electron.shell.openExternal(validated.toString());+ } catch (e) {+ log.error(`open-external failed: ${coreUtils.safeExtractMessageAndStackFromError(e)}`);+ }+ });++ electron.ipcMain.handle("open-path", (_event, filePath: string) => {+ try {+ const resolved = validateOpenPath(filePath, dataDirs.TRILIUM_DATA_DIR, dataDirs.TMP_DIR);+ return electron.shell.openPath(resolved);+ } catch (e) {+ log.error(`open-path failed: ${coreUtils.safeExtractMessageAndStackFromError(e)}`);+ return coreUtils.safeExtractMessageAndStackFromError(e);+ }+ });++ electron.ipcMain.handle("open-file-url", (_event, fileUrl: string) => {+ try {+ const filePath = validateOpenFileUrl(fileUrl);+ return electron.shell.openPath(filePath);+ } catch (e) {+ log.error(`open-file-url failed: ${coreUtils.safeExtractMessageAndStackFromError(e)}`);+ return coreUtils.safeExtractMessageAndStackFromError(e);+ }+ });++ electron.ipcMain.on("download-url", (event, downloadUrl: string) => {+ try {+ const validated = validateDownloadUrl(downloadUrl, event.sender.getURL());+ event.sender.downloadURL(validated.toString());+ } catch (e) {+ log.error(`download-url failed: ${coreUtils.safeExtractMessageAndStackFromError(e)}`);+ }+ });++ electron.ipcMain.on("open-custom", (_event, filePath: string) => {+ // 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;++ if (platform === "linux") {+ const terminals = ["x-terminal-emulator", "gnome-terminal", "konsole", "xterm", "xfce4-terminal", "mate-terminal", "rxvt", "terminator", "terminology"];++ // The terminal's `-e` argument is reparsed by the terminal's own shell,+ // so the path must be POSIX single-quoted before interpolation.+ const sqQuote = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`;+ const innerCommand = `mimeopen -d ${sqQuote(resolved)}`;++ const tryTerminal = (index: number) => {+ if (index >= terminals.length) {+ log.error("open-custom: no terminal emulator found");+ electron.shell.openPath(resolved);+ return;+ }+ const terminal = terminals[index];+ execFile(terminal, ["-e", innerCommand], (err) => {+ if (err) {+ log.info(`open-custom: ${terminal} failed: ${err.message}`);+ tryTerminal(index + 1);+ }+ });+ };+ tryTerminal(0);+ } else if (platform === "win32") {+ const winPath = resolved.replace(/\//g, "\\");+ // OpenAs_RunDLL doesn't strip surrounding quotes from its arg, so we+ // must NOT let Node quote the path on our behalf. windowsVerbatimArguments+ // is safe here: CreateProcess passes the command line to rundll32 without+ // any shell interpretation (so `&` is inert), and the path is validated+ // above to live inside dataDirs.TMP_DIR with a sanitize-filename'd basename+ // (so it cannot contain quotes or other rundll32-confusing characters).+ execFile("rundll32.exe", ["shell32.dll,OpenAs_RunDLL", winPath], { windowsVerbatimArguments: true }, (err) => {+ if (err) {+ log.error(`open-custom: rundll32 failed: ${err.message}`);+ electron.shell.openPath(resolved);+ }+ });+ } else {+ electron.shell.openPath(resolved);+ }+ });+}++//#endregiondiff --git a/apps/server/src/services/window.ts b/apps/server/src/services/window.tsindex e286aa7ec6..31612c3cb9 100644--- a/apps/server/src/services/window.ts+++ b/apps/server/src/services/window.ts@@ -1,25 +1,16 @@-import { execFile } from "child_process";import { type App, type BrowserWindow, type BrowserWindowConstructorOptions, default as electron, type Session, type WebContents } from "electron";import path from "path";import url from "url";import app_info from "./app_info.js";import cls from "./cls.js";-import dataDirs from "./data_dir.js";import keyboardActionsService from "./keyboard_actions.js";import log from "./log.js";import optionService from "./options.js";import { initPrintingHandlers } from "./printing.js";import { RESOURCE_DIR } from "./resource_dir.js";-import {- validateDownloadUrl,- validateOpenCustomPath,- validateOpenExternalUrl,- validateOpenFileUrl,- validateOpenPath-} from "./shell_validators.js";import sqlInit from "./sql_init.js";-import utils, { isDev, isMac, isWindows } from "./utils.js";+import { isDev, isMac, isWindows } from "./utils.js";const PRELOAD_SCRIPT = path.resolve(isDev@@ -214,95 +205,6 @@ electron.ipcMain.on("web-contents-action", (event, action: string, text?: string}});-electron.ipcMain.on("open-external", (_event, url: string) => {- try {- const validated = validateOpenExternalUrl(url);- electron.shell.openExternal(validated.toString());- } catch (e) {- log.error(`open-external failed: ${utils.safeExtractMessageAndStackFromError(e)}`);- }-});--electron.ipcMain.handle("open-path", (_event, filePath: string) => {- try {- const resolved = validateOpenPath(filePath, dataDirs.TRILIUM_DATA_DIR, dataDirs.TMP_DIR);- return electron.shell.openPath(resolved);- } catch (e) {- log.error(`open-path failed: ${utils.safeExtractMessageAndStackFromError(e)}`);- return utils.safeExtractMessageAndStackFromError(e);- }-});--electron.ipcMain.handle("open-file-url", (_event, fileUrl: string) => {- try {- const filePath = validateOpenFileUrl(fileUrl);- return electron.shell.openPath(filePath);- } catch (e) {- log.error(`open-file-url failed: ${utils.safeExtractMessageAndStackFromError(e)}`);- return utils.safeExtractMessageAndStackFromError(e);- }-});--electron.ipcMain.on("download-url", (event, downloadUrl: string) => {- try {- const validated = validateDownloadUrl(downloadUrl, event.sender.getURL());- event.sender.downloadURL(validated.toString());- } catch (e) {- log.error(`download-url failed: ${utils.safeExtractMessageAndStackFromError(e)}`);- }-});--electron.ipcMain.on("open-custom", (_event, filePath: string) => {- // 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;-- if (platform === "linux") {- const terminals = ["x-terminal-emulator", "gnome-terminal", "konsole", "xterm", "xfce4-terminal", "mate-terminal", "rxvt", "terminator", "terminology"];-- // The terminal's `-e` argument is reparsed by the terminal's own shell,- // so the path must be POSIX single-quoted before interpolation.- const sqQuote = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`;- const innerCommand = `mimeopen -d ${sqQuote(resolved)}`;-- const tryTerminal = (index: number) => {- if (index >= terminals.length) {- log.error("open-custom: no terminal emulator found");- electron.shell.openPath(resolved);- return;- }- const terminal = terminals[index];- execFile(terminal, ["-e", innerCommand], (err) => {- if (err) {- log.info(`open-custom: ${terminal} failed: ${err.message}`);- tryTerminal(index + 1);- }- });- };- tryTerminal(0);- } else if (platform === "win32") {- const winPath = resolved.replace(/\//g, "\\");- // OpenAs_RunDLL doesn't strip surrounding quotes from its arg, so we- // must NOT let Node quote the path on our behalf. windowsVerbatimArguments- // is safe here: CreateProcess passes the command line to rundll32 without- // any shell interpretation (so `&` is inert), and the path is validated- // above to live inside dataDirs.TMP_DIR with a sanitize-filename'd basename- // (so it cannot contain quotes or other rundll32-confusing characters).- execFile("rundll32.exe", ["shell32.dll,OpenAs_RunDLL", winPath], { windowsVerbatimArguments: true }, (err) => {- if (err) {- log.error(`open-custom: rundll32 failed: ${err.message}`);- electron.shell.openPath(resolved);- }- });- } else {- electron.shell.openPath(resolved);- }-});-electron.ipcMain.on("navigation-history", (event, method: string) => {const wc = event.sender;switch (method) {