Skip to content

Build your personal knowledge base with Trilium Notes

fix(desktop): apply window-open and navigation policy to every WebContents

Elian Doran894019efcd96
diff --git a/apps/desktop/src/services/web_contents_security.spec.ts b/apps/desktop/src/services/web_contents_security.spec.ts
index 61f919a320..7971321142 100644
--- a/apps/desktop/src/services/web_contents_security.spec.ts
+++ b/apps/desktop/src/services/web_contents_security.spec.ts
@@ -32,7 +32,9 @@ const state = vi.hoisted(() => {
errors: [] as string[],
defaultSession: makeFakeSession(),
partitionSessions: new Map<string, ReturnType<typeof makeFakeSession>>(),
- makeFakeSession
+ makeFakeSession,
+ shellOpenExternal: [] as string[],
+ shellOpenExternalThrow: false
};
});
@@ -40,6 +42,13 @@ vi.mock("@triliumnext/core", () => ({
getLog: () => ({ error: (msg: string) => state.errors.push(msg) })
}));
+// shell.ts (imported for validateOpenExternalUrl) transitively pulls in the
+// server's data_dir module, which resolves and creates directories at import
+// time — stub it out to keep this spec free of filesystem side effects.
+vi.mock("@triliumnext/server/src/services/data_dir.js", () => ({
+ default: { TMP_DIR: "/tmp" }
+}));
+
vi.mock("electron", () => ({
default: {
app: {
@@ -58,11 +67,60 @@ vi.mock("electron", () => ({
}
return session;
}
+ },
+ shell: {
+ openExternal: (target: string) => {
+ if (state.shellOpenExternalThrow) {
+ return Promise.reject(new Error("boom"));
+ }
+ state.shellOpenExternal.push(target);
+ return Promise.resolve();
+ }
}
}
}));
-const { hardenWebviewPreferences, isPermissionAllowed, setupWebContentsSecurity } = await import("./web_contents_security.js");
+const { hardenWebviewPreferences, isNavigationAllowed, isPermissionAllowed, setupWebContentsSecurity } = await import("./web_contents_security.js");
+
+interface WindowOpenResult {
+ action: "allow" | "deny";
+}
+
+/**
+ * Simulates the main process creating a WebContents of the given type and
+ * returns the security hooks the global handler installed on it.
+ */
+function createContents(type: "window" | "webview" = "window") {
+ const created = state.appHandlers.get("web-contents-created");
+ if (!created) throw new Error("web-contents-created not registered");
+
+ const handlers = new Map<string, (...args: unknown[]) => unknown>();
+ let windowOpenHandler: ((details: { url: string }) => WindowOpenResult) | undefined;
+ created({}, {
+ getType: () => type,
+ on: (event: string, fn: (...args: unknown[]) => unknown) => handlers.set(event, fn),
+ setWindowOpenHandler: (fn: (details: { url: string }) => WindowOpenResult) => {
+ windowOpenHandler = fn;
+ }
+ });
+
+ return {
+ handlers,
+ openWindow(url: string): WindowOpenResult {
+ if (!windowOpenHandler) throw new Error("window open handler not installed");
+ return windowOpenHandler({ url });
+ }
+ };
+}
+
+function resetState() {
+ state.appHandlers.clear();
+ state.errors.length = 0;
+ state.defaultSession = state.makeFakeSession();
+ state.partitionSessions.clear();
+ state.shellOpenExternal.length = 0;
+ state.shellOpenExternalThrow = false;
+}
describe("hardenWebviewPreferences", () => {
it("reports no violations for a benign attach and forces isolation on", () => {
@@ -151,20 +209,15 @@ describe("setupWebContentsSecurity", () => {
}
beforeEach(() => {
- state.appHandlers.clear();
- state.errors.length = 0;
+ resetState();
setupWebContentsSecurity();
});
/** Simulates a window being created and then a <webview> attaching inside it. */
function attachWebview(prefs: Electron.WebPreferences, src = "https://example.com", partition?: string): 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 { handlers } = createContents();
- const willAttach = contentsHandlers.get("will-attach-webview");
+ const willAttach = handlers.get("will-attach-webview");
if (!willAttach) throw new Error("will-attach-webview not registered");
const preventDefault = vi.fn();
@@ -230,10 +283,7 @@ describe("isPermissionAllowed", () => {
describe("permission handlers", () => {
beforeEach(async () => {
- state.appHandlers.clear();
- state.errors.length = 0;
- state.defaultSession = state.makeFakeSession();
- state.partitionSessions.clear();
+ resetState();
setupWebContentsSecurity();
// Installation is gated on app.whenReady(); flush the microtask queue.
await Promise.resolve();
@@ -286,3 +336,98 @@ describe("permission handlers", () => {
expect(guestCheck({}, "clipboard-sanitized-write")).toBe(false);
});
});
+
+describe("window-open policy", () => {
+ beforeEach(() => {
+ resetState();
+ setupWebContentsSecurity();
+ });
+
+ it("denies the popup and opens allowlisted URLs in the OS browser", async () => {
+ const contents = createContents();
+
+ expect(contents.openWindow("https://example.com")).toEqual({ action: "deny" });
+ await new Promise((r) => setTimeout(r, 0));
+
+ // URL round-trips through the validator, which normalizes it.
+ expect(state.shellOpenExternal).toEqual(["https://example.com/"]);
+ expect(state.errors).toEqual([]);
+ });
+
+ it("refuses to open URLs with blocked schemes externally", async () => {
+ const contents = createContents();
+
+ // Follina-class and credential-leak schemes must not reach the OS
+ // handler via window.open / target=_blank either — same allowlist
+ // as the open-external IPC channel.
+ for (const hostileUrl of ["ms-msdt:/id PCWDiagnostic", "smb://attacker.example/share", "not a url"]) {
+ expect(contents.openWindow(hostileUrl)).toEqual({ action: "deny" });
+ }
+ await new Promise((r) => setTimeout(r, 0));
+
+ expect(state.shellOpenExternal).toEqual([]);
+ expect(state.errors).toHaveLength(3);
+ });
+
+ it("logs when the external open fails", async () => {
+ state.shellOpenExternalThrow = true;
+ const contents = createContents();
+
+ expect(contents.openWindow("https://bad.example")).toEqual({ action: "deny" });
+ await new Promise((r) => setTimeout(r, 0));
+
+ expect(state.errors).toHaveLength(1);
+ expect(state.errors[0]).toContain("https://bad.example");
+ });
+
+ it("denies window.open from webview guests without dispatching to the OS", async () => {
+ const contents = createContents("webview");
+
+ expect(contents.openWindow("https://example.com")).toEqual({ action: "deny" });
+ await new Promise((r) => setTimeout(r, 0));
+
+ expect(state.shellOpenExternal).toEqual([]);
+ expect(state.errors).toHaveLength(1);
+ expect(state.errors[0]).toContain("https://example.com");
+ });
+});
+
+describe("navigation guard", () => {
+ beforeEach(() => {
+ resetState();
+ setupWebContentsSecurity();
+ });
+
+ it("only allows internal root navigation (setup and migration redirects)", () => {
+ expect(isNavigationAllowed("trilium-app://app/")).toBe(true);
+ // Internal host with the root "/?" path is allowed.
+ expect(isNavigationAllowed("trilium-app://app/?")).toBe(true);
+ expect(isNavigationAllowed("http://localhost/")).toBe(true);
+ expect(isNavigationAllowed("http://127.0.0.1/")).toBe(true);
+
+ expect(isNavigationAllowed("https://evil.example/page")).toBe(false);
+ // Internal host but non-root path is blocked.
+ expect(isNavigationAllowed("http://localhost/somewhere")).toBe(false);
+ // URL with no hostname falls back to "" and is blocked.
+ expect(isNavigationAllowed("javascript:void(0)")).toBe(false);
+ });
+
+ it("prevents disallowed navigations on app windows", () => {
+ const { handlers } = createContents();
+ const willNavigate = handlers.get("will-navigate");
+ if (!willNavigate) throw new Error("will-navigate not registered");
+
+ const external = { preventDefault: vi.fn() };
+ willNavigate(external, "https://evil.example/page");
+ expect(external.preventDefault).toHaveBeenCalled();
+
+ const internal = { preventDefault: vi.fn() };
+ willNavigate(internal, "trilium-app://app/");
+ expect(internal.preventDefault).not.toHaveBeenCalled();
+ });
+
+ it("does not install a navigation guard on webview guests", () => {
+ const { handlers } = createContents("webview");
+ expect(handlers.has("will-navigate")).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/services/web_contents_security.ts b/apps/desktop/src/services/web_contents_security.ts
index efb25a7eac..4bf24a95f7 100644
--- a/apps/desktop/src/services/web_contents_security.ts
+++ b/apps/desktop/src/services/web_contents_security.ts
@@ -1,6 +1,9 @@
import { WEBVIEW_SESSION_PARTITION } from "@triliumnext/commons";
import { getLog } from "@triliumnext/core";
import electron from "electron";
+import url from "url";
+
+import { validateOpenExternalUrl } from "./shell.js";
/**
* Security guard for `<webview>` attachment.
@@ -18,10 +21,16 @@ import electron from "electron";
*/
/**
- * 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), and installs deny-by-default permission handlers on
- * both the app session and the dedicated `<webview>` guest session.
+ * Registers a main-process hook that applies a uniform security policy to
+ * every WebContents the app ever creates (main, extra, setup and print
+ * windows as well as `<webview>` guests):
+ *
+ * - vets every `<webview>` before it attaches,
+ * - denies all window-open requests, routing allowlisted URLs to the OS
+ * browser instead,
+ * - blocks navigation away from the app shell,
+ * - installs deny-by-default permission handlers on both the app session and
+ * the dedicated `<webview>` guest session.
*
* Attach attempts that explicitly request a dangerous capability (Node
* integration, a preload script, disabled web security) are denied outright —
@@ -43,6 +52,9 @@ export function setupWebContentsSecurity() {
getLog().error(`Blocked <webview> attach requesting [${violations.join(", ")}] for src: ${params.src}`);
}
});
+
+ installWindowOpenPolicy(webContents);
+ installNavigationGuard(webContents);
});
// Sessions only exist once the app is ready; both handlers below replace
@@ -133,6 +145,71 @@ export function isPermissionAllowed(kind: SessionKind, permission: string): bool
return PERMISSION_ALLOWLIST[kind].has(permission);
}
+/**
+ * Decides whether a renderer-initiated navigation (link click, drag & drop,
+ * meta refresh) may proceed. Only the app shell itself is allowed: the
+ * `trilium-app://` protocol or localhost, and only at the root path —
+ * internal redirects from the setup and migration pages land there. Anything
+ * deeper is in-page SPA routing (which `will-navigate` does not fire for) or
+ * hostile.
+ */
+export function isNavigationAllowed(targetUrl: string): boolean {
+ const parsedUrl = url.parse(targetUrl);
+
+ const isInternal = parsedUrl.protocol === "trilium-app:"
+ || ["localhost", "127.0.0.1"].includes(parsedUrl.hostname || "");
+ return isInternal && (!parsedUrl.path || parsedUrl.path === "/" || parsedUrl.path === "/?");
+}
+
+/**
+ * Denies every window-open request (`window.open`, `target=_blank`). For app
+ * windows the URL is routed to the OS browser instead, after passing the same
+ * scheme allowlist as the open-external IPC channel — a link in note content
+ * is just as attacker-controllable as an IPC payload, so Follina-class
+ * (`ms-msdt:`) and credential-leak (`smb:`) URLs must not bypass it here.
+ *
+ * `<webview>` guests are denied without the external dispatch: the tag never
+ * sets `allowpopups`, so popups are already impossible there — this keeps it
+ * that way even if a future Electron version changes the default, and stops
+ * remote pages from triggering OS protocol handlers.
+ */
+function installWindowOpenPolicy(webContents: Electron.WebContents) {
+ webContents.setWindowOpenHandler((details) => {
+ if (webContents.getType() === "webview") {
+ getLog().error(`Blocked window.open from <webview> guest for URL: ${details.url}`);
+ return { action: "deny" };
+ }
+
+ async function openExternal() {
+ const validated = validateOpenExternalUrl(details.url);
+ await electron.shell.openExternal(validated.toString());
+ }
+
+ openExternal().catch(err => {
+ getLog().error(`Failed to open external URL ${details.url}: ${err}`);
+ });
+ return { action: "deny" };
+ });
+}
+
+/**
+ * Prevents drag & drop, link clicks etc. from navigating an app window away
+ * from Trilium. `<webview>` guests are exempt — they are embedded browsers
+ * the user navigates freely. Main-process `loadURL` calls are unaffected
+ * (`will-navigate` does not fire for them).
+ */
+function installNavigationGuard(webContents: Electron.WebContents) {
+ if (webContents.getType() === "webview") {
+ return;
+ }
+
+ webContents.on("will-navigate", (ev, targetUrl) => {
+ if (!isNavigationAllowed(targetUrl)) {
+ ev.preventDefault();
+ }
+ });
+}
+
function installPermissionPolicy(session: Electron.Session, kind: SessionKind) {
// Asynchronous requests (e.g. getUserMedia prompting for the camera).
session.setPermissionRequestHandler((_webContents, permission, callback, details) => {
diff --git a/apps/desktop/src/services/window.spec.ts b/apps/desktop/src/services/window.spec.ts
index 9758563728..6a0af446fd 100644
--- a/apps/desktop/src/services/window.spec.ts
+++ b/apps/desktop/src/services/window.spec.ts
@@ -47,7 +47,6 @@ class FakeWebContents {
return this;
});
public listeners = new Map<string, Handler[]>();
- public setWindowOpenHandler = vi.fn();
public toggleDevTools = vi.fn();
public cut = vi.fn();
public copy = vi.fn();
@@ -329,7 +328,7 @@ describe("window service", () => {
await windowService.createExtraWindow("#root/abc");
const win = state.windows[state.windows.length - 1];
expect(win.loadURL).toHaveBeenCalledWith("trilium-app://app/?extraWindow=1#root/abc");
- expect(win.webContents.setWindowOpenHandler).toHaveBeenCalled();
+ expect(win.webContents.session.setSpellCheckerLanguages).toHaveBeenCalled();
});
});
@@ -384,71 +383,8 @@ describe("window service", () => {
await windowService.createMainWindow();
});
- it("denies new windows and opens them externally", async () => {
- const wc = state.windows[state.windows.length - 1].webContents;
- const handlerArg = wc.setWindowOpenHandler.mock.calls[0][0] as Handler;
- const result = handlerArg({ url: "https://example.com" });
- expect(result).toEqual({ action: "deny" });
- await new Promise((r) => setTimeout(r, 0));
- // URL round-trips through the validator, which normalizes it.
- expect(fakeShell.openExternal).toHaveBeenCalledWith("https://example.com/");
- });
-
- it("refuses to open URLs with blocked schemes externally", async () => {
- const wc = state.windows[state.windows.length - 1].webContents;
- const handlerArg = wc.setWindowOpenHandler.mock.calls[0][0] as Handler;
-
- // Follina-class and credential-leak schemes must not reach the OS
- // handler via window.open / target=_blank either — same allowlist
- // as the open-external IPC channel.
- for (const hostileUrl of ["ms-msdt:/id PCWDiagnostic", "smb://attacker.example/share", "not a url"]) {
- const result = handlerArg({ url: hostileUrl });
- expect(result).toEqual({ action: "deny" });
- }
- await new Promise((r) => setTimeout(r, 0));
-
- expect(fakeShell.openExternal).not.toHaveBeenCalled();
- expect(state.log.error).toHaveBeenCalledTimes(3);
- });
-
- it("logs when external open fails", async () => {
- // The inner `openExternal()` doesn't await `shell.openExternal`, so only a
- // synchronous throw inside it rejects the wrapper and hits the `.catch`.
- fakeShell.openExternal.mockImplementationOnce(() => {
- throw new Error("boom");
- });
- const wc = state.windows[state.windows.length - 1].webContents;
- const handlerArg = wc.setWindowOpenHandler.mock.calls[0][0] as Handler;
- handlerArg({ url: "https://bad.example" });
- await new Promise((r) => setTimeout(r, 0));
- expect(state.log.error).toHaveBeenCalled();
- });
-
- it("blocks external navigation but allows internal redirects", () => {
- const wc = state.windows[state.windows.length - 1].webContents;
- const external = { preventDefault: vi.fn() };
- wc.fire("will-navigate", external, "https://evil.example/page");
- expect(external.preventDefault).toHaveBeenCalled();
-
- const internal = { preventDefault: vi.fn() };
- wc.fire("will-navigate", internal, "trilium-app://app/");
- expect(internal.preventDefault).not.toHaveBeenCalled();
-
- // internal host but non-root path is blocked
- const internalPath = { preventDefault: vi.fn() };
- wc.fire("will-navigate", internalPath, "http://localhost/somewhere");
- expect(internalPath.preventDefault).toHaveBeenCalled();
-
- // URL with no hostname falls back to "" (covers `hostname || ""`) and is blocked.
- const noHost = { preventDefault: vi.fn() };
- wc.fire("will-navigate", noHost, "javascript:void(0)");
- expect(noHost.preventDefault).toHaveBeenCalled();
-
- // internal host with the root "/?" path is allowed (covers that path comparison).
- const rootQuery = { preventDefault: vi.fn() };
- wc.fire("will-navigate", rootQuery, "trilium-app://app/?");
- expect(rootQuery.preventDefault).not.toHaveBeenCalled();
- });
+ // Window-open and navigation policy is installed globally by
+ // web_contents_security.ts and tested in web_contents_security.spec.ts.
it("forwards full-screen, navigation and context-menu events", () => {
const win = state.windows[state.windows.length - 1];
diff --git a/apps/desktop/src/services/window.ts b/apps/desktop/src/services/window.ts
index 30c3610cd8..16c552c3a0 100644
--- a/apps/desktop/src/services/window.ts
+++ b/apps/desktop/src/services/window.ts
@@ -2,9 +2,6 @@ import { app_info, cls, events, getLog, keyboard_actions as keyboardActionsServi
import { RESOURCE_DIR } from "@triliumnext/server/src/services/resource_dir.js";
import { type BrowserWindow, type BrowserWindowConstructorOptions, default as electron, type Session, type WebContents } from "electron";
import path from "path";
-import url from "url";
-
-import { validateOpenExternalUrl } from "./shell.js";
// Preload bundle path. Two layouts:
// - Dev: this file lives at apps/desktop/src/services/window.ts, and the
@@ -168,34 +165,9 @@ function getWindowExtraOpts() {
}
async function configureWebContents(webContents: WebContents, spellcheckEnabled: boolean) {
- webContents.setWindowOpenHandler((details) => {
- async function openExternal() {
- // A target=_blank link or window.open() from note content is just
- // as attacker-controllable as an IPC payload, so enforce the same
- // scheme allowlist as the open-external IPC channel — otherwise
- // Follina-class (ms-msdt:) and credential-leak (smb:) URLs would
- // bypass it here.
- const validated = validateOpenExternalUrl(details.url);
- (await import("electron")).shell.openExternal(validated.toString());
- }
-
- openExternal().catch(err => {
- getLog().error(`Failed to open external URL ${details.url}: ${err}`);
- });
- return { action: "deny" };
- });
-
- // prevent drag & drop to navigate away from trilium
- webContents.on("will-navigate", (ev, targetUrl) => {
- const parsedUrl = url.parse(targetUrl);
-
- // we still need to allow internal redirects from setup and migration pages
- const isInternal = parsedUrl.protocol === "trilium-app:"
- || ["localhost", "127.0.0.1"].includes(parsedUrl.hostname || "");
- if (!isInternal || (parsedUrl.path && parsedUrl.path !== "/" && parsedUrl.path !== "/?")) {
- ev.preventDefault();
- }
- });
+ // Window-open and navigation policy is NOT applied here: it is installed
+ // globally for every WebContents (including setup and print windows,
+ // which never pass through this function) by web_contents_security.ts.
if (spellcheckEnabled) {
setupSpellcheckForSession(webContents.session);