Skip to content

Build your personal knowledge base with Trilium Notes

fix(desktop): vet <webview> attach attempts in the main process

Elian Doran820bd837ef2c
diff --git a/apps/desktop/src/main.spec.ts b/apps/desktop/src/main.spec.ts
index a859674b03..f13e936a3f 100644
--- a/apps/desktop/src/main.spec.ts
+++ b/apps/desktop/src/main.spec.ts
@@ -176,6 +176,7 @@ vi.mock("./services/custom_dictionary", () => ({ setupCustomDictionary: vi.fn()
vi.mock("./services/printing", () => ({ setupPrintingHandlers: vi.fn() }));
vi.mock("./services/tray", () => ({ setupSystemTray: vi.fn() }));
vi.mock("./services/shell", () => ({ setupShellHandlers: vi.fn() }));
+vi.mock("./services/web_contents_security", () => ({ setupWebContentsSecurity: vi.fn() }));
vi.mock("./services/security_settings", () => ({
getSecuritySettings: () => h.securitySettings,
registerSecurityIpcHandlers: vi.fn()
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index 3bd10426da..66d4cc73fa 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -29,6 +29,7 @@ import { setupPrintingHandlers } from "./services/printing";
import { getSecuritySettings, registerSecurityIpcHandlers } from "./services/security_settings";
import { setupShellHandlers } from "./services/shell";
import { setupSystemTray } from "./services/tray";
+import { setupWebContentsSecurity } from "./services/web_contents_security";
export async function main() {
// Ignore EPIPE errors on stdout/stderr — these occur when the parent process
@@ -103,6 +104,7 @@ export async function main() {
});
setupWindowing();
+ setupWebContentsSecurity();
setupSystemTray();
setupCustomDictionary();
setupShellHandlers();
diff --git a/apps/desktop/src/services/web_contents_security.spec.ts b/apps/desktop/src/services/web_contents_security.spec.ts
new file mode 100644
index 0000000000..ed36a5ea18
--- /dev/null
+++ b/apps/desktop/src/services/web_contents_security.spec.ts
@@ -0,0 +1,138 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+// Captured app event handlers plus logged errors. `electron` is mocked because
+// on CI its entry point throws ("Electron failed to install correctly") when
+// the binary isn't materialized; `getLog` is stubbed because the log service
+// requires `initializeCore`.
+const state = vi.hoisted(() => ({
+ appHandlers: new Map<string, (...args: unknown[]) => unknown>(),
+ errors: [] as string[]
+}));
+
+vi.mock("@triliumnext/core", () => ({
+ getLog: () => ({ error: (msg: string) => state.errors.push(msg) })
+}));
+
+vi.mock("electron", () => ({
+ default: {
+ app: { on: (event: string, fn: (...args: unknown[]) => unknown) => state.appHandlers.set(event, fn) }
+ }
+}));
+
+const { hardenWebviewPreferences, setupWebContentsSecurity } = await import("./web_contents_security.js");
+
+describe("hardenWebviewPreferences", () => {
+ it("reports no violations for a benign attach and forces isolation on", () => {
+ const prefs: Electron.WebPreferences = {};
+
+ const violations = hardenWebviewPreferences(prefs);
+
+ expect(violations).toEqual([]);
+ expect(prefs).toMatchObject({
+ nodeIntegration: false,
+ nodeIntegrationInSubFrames: false,
+ webSecurity: true,
+ allowRunningInsecureContent: false,
+ contextIsolation: true,
+ sandbox: true
+ });
+ });
+
+ it("normalizes explicitly-disabled isolation silently (Electron default plumbing, not hostile markup)", () => {
+ const prefs: Electron.WebPreferences = { contextIsolation: false, sandbox: false };
+
+ const violations = hardenWebviewPreferences(prefs);
+
+ expect(violations).toEqual([]);
+ expect(prefs.contextIsolation).toBe(true);
+ expect(prefs.sandbox).toBe(true);
+ });
+
+ it("strips preload scripts and reports them, including the legacy preloadURL alias", () => {
+ const prefs = { preload: "/evil.js" } as Electron.WebPreferences;
+ const legacyPrefs = { preloadURL: "file:///evil.js" } as Electron.WebPreferences & { preloadURL?: string };
+
+ expect(hardenWebviewPreferences(prefs)).toEqual(["preload script"]);
+ expect(hardenWebviewPreferences(legacyPrefs)).toEqual(["preload script"]);
+ expect("preload" in prefs).toBe(false);
+ expect("preloadURL" in legacyPrefs).toBe(false);
+ });
+
+ it("reports and disables every dangerous capability requested at once", () => {
+ const prefs: Electron.WebPreferences = {
+ nodeIntegration: true,
+ nodeIntegrationInSubFrames: true,
+ webSecurity: false,
+ allowRunningInsecureContent: true
+ };
+
+ const violations = hardenWebviewPreferences(prefs);
+
+ expect(violations).toEqual([
+ "nodeIntegration",
+ "nodeIntegrationInSubFrames",
+ "webSecurity disabled",
+ "allowRunningInsecureContent"
+ ]);
+ expect(prefs).toMatchObject({
+ nodeIntegration: false,
+ nodeIntegrationInSubFrames: false,
+ webSecurity: true,
+ allowRunningInsecureContent: false
+ });
+ });
+});
+
+describe("setupWebContentsSecurity", () => {
+ interface MockAttach {
+ preventDefault: ReturnType<typeof vi.fn>;
+ prefs: Electron.WebPreferences;
+ }
+
+ beforeEach(() => {
+ state.appHandlers.clear();
+ state.errors.length = 0;
+ setupWebContentsSecurity();
+ });
+
+ /** Simulates a window being created and then a <webview> attaching inside it. */
+ function attachWebview(prefs: Electron.WebPreferences, src = "https://example.com"): MockAttach {
+ const created = state.appHandlers.get("web-contents-created");
+ if (!created) throw new Error("web-contents-created not registered");
+
+ const contentsHandlers = new Map<string, (...args: unknown[]) => unknown>();
+ created({}, { on: (event: string, fn: (...args: unknown[]) => unknown) => contentsHandlers.set(event, fn) });
+
+ const willAttach = contentsHandlers.get("will-attach-webview");
+ if (!willAttach) throw new Error("will-attach-webview not registered");
+
+ const preventDefault = vi.fn();
+ willAttach({ preventDefault }, prefs, { src });
+ return { preventDefault, prefs };
+ }
+
+ it("lets a benign webview attach with hardened preferences", () => {
+ const { preventDefault, prefs } = attachWebview({});
+
+ expect(preventDefault).not.toHaveBeenCalled();
+ expect(state.errors).toEqual([]);
+ expect(prefs.nodeIntegration).toBe(false);
+ expect(prefs.contextIsolation).toBe(true);
+ });
+
+ it("denies an attach requesting nodeIntegration and logs the src", () => {
+ const { preventDefault } = attachWebview({ nodeIntegration: true }, "https://evil.example");
+
+ expect(preventDefault).toHaveBeenCalledOnce();
+ expect(state.errors).toHaveLength(1);
+ expect(state.errors[0]).toContain("nodeIntegration");
+ expect(state.errors[0]).toContain("https://evil.example");
+ });
+
+ it("denies an attach requesting a preload script", () => {
+ const { preventDefault } = attachWebview({ preload: "/evil.js" } as Electron.WebPreferences);
+
+ expect(preventDefault).toHaveBeenCalledOnce();
+ expect(state.errors[0]).toContain("preload script");
+ });
+});
diff --git a/apps/desktop/src/services/web_contents_security.ts b/apps/desktop/src/services/web_contents_security.ts
new file mode 100644
index 0000000000..8ff449e415
--- /dev/null
+++ b/apps/desktop/src/services/web_contents_security.ts
@@ -0,0 +1,85 @@
+import { getLog } from "@triliumnext/core";
+import electron from "electron";
+
+/**
+ * Security guard for `<webview>` attachment.
+ *
+ * Main and extra windows are created with `webviewTag: true` so the Web View
+ * note type can embed remote pages. The webview tag is renderer-controlled
+ * markup, which means a single XSS in the renderer could otherwise inject
+ * `<webview nodeintegration src=...>` or attach a `preload` attribute and
+ * regain the full Node.js access that `nodeIntegration: false` +
+ * `contextIsolation: true` were introduced to remove.
+ *
+ * Per the Electron security checklist, `will-attach-webview` fires in the main
+ * process before a guest is created and is the only reliable place to vet the
+ * web preferences the embedder requested.
+ */
+
+/**
+ * Registers a main-process hook that vets every `<webview>` before it
+ * attaches, on every WebContents the app ever creates (main, extra, setup and
+ * print windows alike).
+ *
+ * Attach attempts that explicitly request a dangerous capability (Node
+ * integration, a preload script, disabled web security) are denied outright —
+ * the legitimate Web View note type never requests any of them, so a
+ * violation can only come from injected markup. Benign attaches proceed with
+ * their preferences hardened as defense in depth.
+ *
+ * Call once during startup, before any window is created.
+ */
+export function setupWebContentsSecurity() {
+ electron.app.on("web-contents-created", (_event, webContents) => {
+ webContents.on("will-attach-webview", (attachEvent, webPreferences, params) => {
+ const violations = hardenWebviewPreferences(webPreferences);
+ if (violations.length > 0) {
+ attachEvent.preventDefault();
+ getLog().error(`Blocked <webview> attach requesting [${violations.join(", ")}] for src: ${params.src}`);
+ }
+ });
+ });
+}
+
+/**
+ * Strips dangerous capabilities from the web preferences a `<webview>`
+ * requested and returns the list of explicit violations found (empty for a
+ * benign attach).
+ *
+ * `contextIsolation` and `sandbox` are forced on silently rather than
+ * reported: Electron may legitimately pass them unset for guests, so they are
+ * normalization, not evidence of hostile markup.
+ */
+export function hardenWebviewPreferences(webPreferences: Electron.WebPreferences): string[] {
+ const violations: string[] = [];
+
+ // `preloadURL` is the legacy alias of `preload`; Electron still honours it.
+ const prefs = webPreferences as Electron.WebPreferences & { preloadURL?: string };
+ if (prefs.preload !== undefined || prefs.preloadURL !== undefined) {
+ violations.push("preload script");
+ }
+ delete prefs.preload;
+ delete prefs.preloadURL;
+
+ if (prefs.nodeIntegration) {
+ violations.push("nodeIntegration");
+ }
+ if (prefs.nodeIntegrationInSubFrames) {
+ violations.push("nodeIntegrationInSubFrames");
+ }
+ if (prefs.webSecurity === false) {
+ violations.push("webSecurity disabled");
+ }
+ if (prefs.allowRunningInsecureContent) {
+ violations.push("allowRunningInsecureContent");
+ }
+
+ prefs.nodeIntegration = false;
+ prefs.nodeIntegrationInSubFrames = false;
+ prefs.webSecurity = true;
+ prefs.allowRunningInsecureContent = false;
+ prefs.contextIsolation = true;
+ prefs.sandbox = true;
+
+ return violations;
+}
diff --git a/apps/edit-docs/src/utils.ts b/apps/edit-docs/src/utils.ts
index 07953a9c41..83e91a4c3a 100644
--- a/apps/edit-docs/src/utils.ts
+++ b/apps/edit-docs/src/utils.ts
@@ -5,6 +5,7 @@ import ClsHookedExecutionContext from "@triliumnext/server/src/cls_provider.js";
import NodejsCryptoProvider from "@triliumnext/server/src/crypto_provider.js";
import ServerPlatformProvider from "@triliumnext/server/src/platform_provider.js";
import { serverImageProvider } from "@triliumnext/server/src/services/image_provider.js";
+import { setupWebContentsSecurity } from "@triliumnext/desktop/src/services/web_contents_security.js";
import windowService, { setupWindowing } from "@triliumnext/desktop/src/services/window.js";
import BetterSqlite3Provider from "@triliumnext/server/src/sql_provider.js";
import NodejsZipProvider from "@triliumnext/server/src/zip_provider.js";
@@ -109,6 +110,10 @@ export function startElectron(callback: () => void): DeferredPromise<void> {
// the renderer. Desktop registers these in apps/desktop/src/main.ts.
setupWindowing();
+ // Vet <webview> attach attempts (the windows enable `webviewTag`);
+ // desktop does the same in apps/desktop/src/main.ts.
+ setupWebContentsSecurity();
+
// Create the main window.
await windowService.createMainWindow();