Skip to content

Build your personal knowledge base with Trilium Notes

fix(desktop): deny-by-default permission policy for renderer and webview sessions

Elian Doran953ba5df8a2e
diff --git a/apps/desktop/src/services/web_contents_security.spec.ts b/apps/desktop/src/services/web_contents_security.spec.ts
index e77d4e394c..f73416b76c 100644
--- a/apps/desktop/src/services/web_contents_security.spec.ts
+++ b/apps/desktop/src/services/web_contents_security.spec.ts
@@ -4,10 +4,37 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
// 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[]
-}));
+const state = vi.hoisted(() => {
+ type PermissionRequestHandler = (
+ webContents: unknown,
+ permission: string,
+ callback: (granted: boolean) => void,
+ details: { requestingUrl: string }
+ ) => void;
+ type PermissionCheckHandler = (webContents: unknown, permission: string) => boolean;
+
+ /** Fake Electron session capturing the permission handlers installed on it. */
+ function makeFakeSession() {
+ return {
+ requestHandler: undefined as PermissionRequestHandler | undefined,
+ checkHandler: undefined as PermissionCheckHandler | undefined,
+ setPermissionRequestHandler(fn: PermissionRequestHandler) {
+ this.requestHandler = fn;
+ },
+ setPermissionCheckHandler(fn: PermissionCheckHandler) {
+ this.checkHandler = fn;
+ }
+ };
+ }
+
+ return {
+ appHandlers: new Map<string, (...args: unknown[]) => unknown>(),
+ errors: [] as string[],
+ defaultSession: makeFakeSession(),
+ partitionSessions: new Map<string, ReturnType<typeof makeFakeSession>>(),
+ makeFakeSession
+ };
+});
vi.mock("@triliumnext/core", () => ({
getLog: () => ({ error: (msg: string) => state.errors.push(msg) })
@@ -15,11 +42,27 @@ vi.mock("@triliumnext/core", () => ({
vi.mock("electron", () => ({
default: {
- app: { on: (event: string, fn: (...args: unknown[]) => unknown) => state.appHandlers.set(event, fn) }
+ app: {
+ on: (event: string, fn: (...args: unknown[]) => unknown) => state.appHandlers.set(event, fn),
+ whenReady: () => Promise.resolve()
+ },
+ session: {
+ get defaultSession() {
+ return state.defaultSession;
+ },
+ fromPartition: (partition: string) => {
+ let session = state.partitionSessions.get(partition);
+ if (!session) {
+ session = state.makeFakeSession();
+ state.partitionSessions.set(partition, session);
+ }
+ return session;
+ }
+ }
}
}));
-const { hardenWebviewPreferences, setupWebContentsSecurity } = await import("./web_contents_security.js");
+const { hardenWebviewPreferences, isPermissionAllowed, setupWebContentsSecurity } = await import("./web_contents_security.js");
describe("hardenWebviewPreferences", () => {
it("reports no violations for a benign attach and forces isolation on", () => {
@@ -162,3 +205,80 @@ describe("setupWebContentsSecurity", () => {
expect(state.errors[0]).toContain("preload script");
});
});
+
+describe("isPermissionAllowed", () => {
+ it("implements the per-session allowlist matrix", () => {
+ // App session: the renderer copies note content and toggles fullscreen.
+ expect(isPermissionAllowed("app", "clipboard-sanitized-write")).toBe(true);
+ expect(isPermissionAllowed("app", "fullscreen")).toBe(true);
+
+ // Guest session: only fullscreen (embedded video players).
+ expect(isPermissionAllowed("guest", "fullscreen")).toBe(true);
+ expect(isPermissionAllowed("guest", "clipboard-sanitized-write")).toBe(false);
+
+ // Everything else is denied everywhere.
+ for (const permission of ["media", "geolocation", "notifications", "midi", "hid", "serial", "usb", "pointerLock", "clipboard-read", "openExternal"]) {
+ expect(isPermissionAllowed("app", permission)).toBe(false);
+ expect(isPermissionAllowed("guest", permission)).toBe(false);
+ }
+ });
+});
+
+describe("permission handlers", () => {
+ beforeEach(async () => {
+ state.appHandlers.clear();
+ state.errors.length = 0;
+ state.defaultSession = state.makeFakeSession();
+ state.partitionSessions.clear();
+ setupWebContentsSecurity();
+ // Installation is gated on app.whenReady(); flush the microtask queue.
+ await Promise.resolve();
+ });
+
+ it("installs request and check handlers on both the default and the webview partition session", () => {
+ expect(state.defaultSession.requestHandler).toBeDefined();
+ expect(state.defaultSession.checkHandler).toBeDefined();
+
+ const guestSession = state.partitionSessions.get("persist:webview");
+ expect(guestSession?.requestHandler).toBeDefined();
+ expect(guestSession?.checkHandler).toBeDefined();
+ expect(state.partitionSessions.size).toBe(1);
+ });
+
+ it("grants allowlisted permission requests without logging", () => {
+ const handler = state.defaultSession.requestHandler;
+ if (!handler) throw new Error("request handler not installed");
+
+ const callback = vi.fn();
+ handler({}, "fullscreen", callback, { requestingUrl: "trilium-app://main/" });
+
+ expect(callback).toHaveBeenCalledWith(true);
+ expect(state.errors).toEqual([]);
+ });
+
+ it("denies non-allowlisted permission requests and logs the requesting URL", () => {
+ const guestSession = state.partitionSessions.get("persist:webview");
+ const handler = guestSession?.requestHandler;
+ if (!handler) throw new Error("request handler not installed");
+
+ const callback = vi.fn();
+ handler({}, "media", callback, { requestingUrl: "https://evil.example/" });
+
+ expect(callback).toHaveBeenCalledWith(false);
+ expect(state.errors).toHaveLength(1);
+ expect(state.errors[0]).toContain("media");
+ expect(state.errors[0]).toContain("https://evil.example/");
+ expect(state.errors[0]).toContain("guest");
+ });
+
+ it("mirrors the policy in the synchronous check handler", () => {
+ const appCheck = state.defaultSession.checkHandler;
+ const guestCheck = state.partitionSessions.get("persist:webview")?.checkHandler;
+ if (!appCheck || !guestCheck) throw new Error("check handlers not installed");
+
+ expect(appCheck({}, "clipboard-sanitized-write")).toBe(true);
+ expect(appCheck({}, "geolocation")).toBe(false);
+ expect(guestCheck({}, "fullscreen")).toBe(true);
+ expect(guestCheck({}, "clipboard-sanitized-write")).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/services/web_contents_security.ts b/apps/desktop/src/services/web_contents_security.ts
index 0d405318ca..369b5097fe 100644
--- a/apps/desktop/src/services/web_contents_security.ts
+++ b/apps/desktop/src/services/web_contents_security.ts
@@ -20,7 +20,8 @@ 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).
+ * print windows alike), and 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 +44,13 @@ export function setupWebContentsSecurity() {
}
});
});
+
+ // Sessions only exist once the app is ready; both handlers below replace
+ // Electron's default behaviour of granting every permission request.
+ electron.app.whenReady().then(() => {
+ installPermissionPolicy(electron.session.defaultSession, "app");
+ installPermissionPolicy(electron.session.fromPartition(WEBVIEW_SESSION_PARTITION), "guest");
+ });
}
/**
@@ -97,3 +105,41 @@ export function hardenWebviewPreferences(webPreferences: Electron.WebPreferences
return violations;
}
+
+/**
+ * Permission allowlists per session kind. Unset handlers make Electron GRANT
+ * every request, so anything not listed here (camera, microphone, geolocation,
+ * notifications, MIDI, HID, serial, USB, pointer lock, clipboard read, …) is
+ * denied.
+ *
+ * - `app`: the default session — the Trilium renderer itself. It legitimately
+ * writes to the clipboard (copy note content/links) and toggles fullscreen
+ * (e.g. presentations, zen mode), nothing else.
+ * - `guest`: the `<webview>` partition hosting arbitrary remote pages from
+ * Web View notes. Fullscreen only (embedded video players).
+ */
+const PERMISSION_ALLOWLIST = {
+ app: new Set(["clipboard-sanitized-write", "fullscreen"]),
+ guest: new Set(["fullscreen"])
+} as const;
+
+export type SessionKind = keyof typeof PERMISSION_ALLOWLIST;
+
+/** Pure policy check: is `permission` allowed for the given session kind? */
+export function isPermissionAllowed(kind: SessionKind, permission: string): boolean {
+ return PERMISSION_ALLOWLIST[kind].has(permission);
+}
+
+function installPermissionPolicy(session: Electron.Session, kind: SessionKind) {
+ // Asynchronous requests (e.g. getUserMedia prompting for the camera).
+ session.setPermissionRequestHandler((_webContents, permission, callback, details) => {
+ const allowed = isPermissionAllowed(kind, permission);
+ if (!allowed) {
+ getLog().error(`Denied '${permission}' permission request from ${details.requestingUrl} (${kind} session)`);
+ }
+ callback(allowed);
+ });
+ // Synchronous checks (e.g. navigator.permissions.query, push subscription
+ // state) — without this handler Electron reports everything as granted.
+ session.setPermissionCheckHandler((_webContents, permission) => isPermissionAllowed(kind, permission));
+}