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
fix(desktop): gate trilium-app dispatch by requesting frame, not Origin header
Elian Doranc1517c97b256
diff --git a/apps/desktop/src/protocol.spec.ts b/apps/desktop/src/protocol.spec.tsindex af9e38f90e..ea5052e75b 100644--- a/apps/desktop/src/protocol.spec.ts+++ b/apps/desktop/src/protocol.spec.ts@@ -4,18 +4,20 @@ import { describe, expect, it, vi } from "vitest";const electronMock = vi.hoisted(() => ({registerSchemesAsPrivileged: vi.fn(),- handle: vi.fn()+ handle: vi.fn(),+ onBeforeRequest: vi.fn()}));vi.mock("electron", () => ({default: {app: { whenReady: () => Promise.resolve() },- protocol: { handle: electronMock.handle }+ protocol: { handle: electronMock.handle },+ session: { defaultSession: { webRequest: { onBeforeRequest: electronMock.onBeforeRequest } } }},protocol: { registerSchemesAsPrivileged: electronMock.registerSchemesAsPrivileged }}));-const { dispatch, isDispatchOriginAllowed, registerTriliumAppScheme, setupTriliumAppProtocol } = await import("./protocol.js");+const { dispatch, isDispatchOriginAllowed, isRequestorChainTrusted, registerTriliumAppScheme, setupTriliumAppProtocol } = await import("./protocol.js");const { isInternalElectronRequest } = await import("@triliumnext/server/src/services/electron_request.js");function buildTestApp() {@@ -420,9 +422,11 @@ describe("trilium-app protocol dispatcher", () => {});// Every dispatched request gets the auth/CSRF-bypassing internal marker,- // so the protocol handler must refuse requests that Chromium attests came- // from a foreign origin (`Origin` is a forbidden header — page JS cannot- // forge it) before they ever reach `dispatch`.+ // so requests must be vetted before they ever reach `dispatch`. The+ // primary gate is the webRequest frame-origin guard (headers cannot+ // distinguish friend from foe on a custom scheme — see protocol.ts);+ // the Origin check on the handler itself is the secondary layer for+ // navigation-style requests, the only ones that carry an Origin.describe("origin gate", () => {async function installHandler(app: Parameters<typeof setupTriliumAppProtocol>[0]) {electronMock.handle.mockReset();@@ -445,32 +449,23 @@ describe("trilium-app protocol dispatcher", () => {} as unknown as Request;}- it("isDispatchOriginAllowed implements the three-rule policy", () => {- // Rule 3: Origin-less GET / HEAD — top-level navigations- // (main-process loadURL, print window) and same-origin- // subresource loads legitimately carry no Origin.- expect(isDispatchOriginAllowed("GET", null)).toBe(true);- expect(isDispatchOriginAllowed("HEAD", null)).toBe(true);-- // Rule 2: Origin-less writes are anomalous — Chromium always- // attaches Origin to state-changing requests.- for (const method of ["POST", "PUT", "PATCH", "DELETE", "OPTIONS"]) {- expect(isDispatchOriginAllowed(method, null)).toBe(false);- }-- // Rule 1: foreign origins are rejected regardless of method,- // including the opaque "null" origin of sandboxed frames and- // other hosts under our own scheme — `trilium-app://app` is the- // only origin the app ever loads.- expect(isDispatchOriginAllowed("GET", "https://evil.example")).toBe(false);- expect(isDispatchOriginAllowed("POST", "https://evil.example")).toBe(false);- expect(isDispatchOriginAllowed("POST", "null")).toBe(false);- expect(isDispatchOriginAllowed("POST", "trilium-app://evil")).toBe(false);- expect(isDispatchOriginAllowed("POST", "trilium-app://app.evil.example")).toBe(false);-- // The app's own exact origin passes for both reads and writes.- expect(isDispatchOriginAllowed("GET", "trilium-app://app")).toBe(true);- expect(isDispatchOriginAllowed("POST", "trilium-app://app")).toBe(true);+ it("isDispatchOriginAllowed only rejects positively-attested foreign origins", () => {+ // Foreign origins are rejected, including the opaque "null"+ // origin of sandboxed frames and other hosts under our own+ // scheme — `trilium-app://app` is the only origin the app ever+ // loads.+ expect(isDispatchOriginAllowed("https://evil.example")).toBe(false);+ expect(isDispatchOriginAllowed("null")).toBe(false);+ expect(isDispatchOriginAllowed("trilium-app://evil")).toBe(false);+ expect(isDispatchOriginAllowed("trilium-app://app.evil.example")).toBe(false);++ // The app's own exact origin passes.+ expect(isDispatchOriginAllowed("trilium-app://app")).toBe(true);++ // No Origin proves nothing on a custom scheme: Chromium omits it+ // even on the renderer's own POST/PUT requests, so absence must+ // be allowed through (the frame guard already vetted the source).+ expect(isDispatchOriginAllowed(null)).toBe(true);});it("returns 403 without invoking the Express app for a foreign-origin request", async () => {@@ -490,17 +485,20 @@ describe("trilium-app protocol dispatcher", () => {expect(appInvoked).toBe(false);});- it("returns 403 for an Origin-less state-changing request", async () => {- const handler = await installHandler(express());+ // Regression test: same-origin renderer writes (tree/load,+ // recent-notes, ...) arrive with NO Origin header on the custom+ // scheme and must not be rejected.+ it("dispatches Origin-less writes (the renderer's own API calls)", async () => {+ const app = express();+ app.post("/probe", (_req, res) => res.send("written"));+ const handler = await installHandler(app);- const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});const response = await handler(fakeRequest("POST"));- errorSpy.mockRestore();-- expect(response.status).toBe(403);+ expect(response.status).toBe(200);+ expect(await response.text()).toBe("written");});- it("dispatches same-origin requests carrying a trilium-app Origin", async () => {+ it("dispatches writes carrying the exact trilium-app Origin", async () => {const app = express();app.post("/probe", (_req, res) => res.send("written"));const handler = await installHandler(app);@@ -521,6 +519,110 @@ describe("trilium-app protocol dispatcher", () => {});});+ // The primary gate: a webRequest hook cancels any trilium-app:// request+ // whose requesting frame chain is not exclusively the app shell. Frame+ // URLs are main-process-side state that renderer content cannot forge,+ // unlike every header on this scheme.+ describe("frame origin guard", () => {+ type OnBeforeRequestListener = (+ details: {+ method: string;+ url: string;+ resourceType: string;+ frame?: { url: string; parent: unknown } | null;+ },+ callback: (response: { cancel: boolean }) => void+ ) => void;++ async function installGuard() {+ electronMock.onBeforeRequest.mockReset();+ setupTriliumAppProtocol(express());+ await Promise.resolve(); // let whenReady().then(...) run+ const [filter, listener] = electronMock.onBeforeRequest.mock.calls[0] as [+ { urls: string[] },+ OnBeforeRequestListener+ ];+ return { filter, listener };+ }++ function frameChain(...urls: string[]) {+ return urls.reduceRight<{ url: string; parent: unknown } | null>(+ (parent, url) => ({ url, parent }),+ null+ );+ }++ function decide(listener: OnBeforeRequestListener, resourceType: string, frame: { url: string; parent: unknown } | null | undefined) {+ let cancelled: boolean | undefined;+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ listener(+ { method: "POST", url: "trilium-app://app/api/probe", resourceType, frame },+ ({ cancel }) => { cancelled = cancel; }+ );+ errorSpy.mockRestore();+ return cancelled;+ }++ it("isRequestorChainTrusted implements the frame-chain policy", () => {+ // Top-level navigations come from main-process loadURL calls or+ // are vetted by the will-navigate guard — always allowed.+ expect(isRequestorChainTrusted("mainFrame", [""])).toBe(true);++ // The renderer's own fetch/XHR.+ expect(isRequestorChainTrusted("xhr", ["trilium-app://app/"])).toBe(true);+ // ... including from same-origin iframes (pdfjs viewer, print).+ expect(isRequestorChainTrusted("xhr", ["trilium-app://app/pdfjs/web/viewer.html", "trilium-app://app/"])).toBe(true);+ // Subframe navigation of a legit app iframe: the navigated frame+ // reports its uncommitted URL; the app-shell parent attests it.+ expect(isRequestorChainTrusted("subFrame", ["", "trilium-app://app/"])).toBe(true);+ expect(isRequestorChainTrusted("subFrame", ["about:blank", "trilium-app://app/"])).toBe(true);+ // DevTools fetching source maps for trilium-app:// scripts.+ expect(isRequestorChainTrusted("xhr", ["devtools://devtools/bundled/devtools_app.html"])).toBe(true);++ // A foreign window's fetch.+ expect(isRequestorChainTrusted("xhr", ["http://127.0.0.1:8080/"])).toBe(false);+ // A foreign iframe embedded in the app window — the app-shell+ // ancestor does not launder the hostile requesting frame.+ expect(isRequestorChainTrusted("xhr", ["http://evil.example/", "trilium-app://app/"])).toBe(false);+ // A hostile form POST targeting an iframe, from a foreign window+ // or nested inside the app window.+ expect(isRequestorChainTrusted("subFrame", ["about:blank", "http://evil.example/"])).toBe(false);+ expect(isRequestorChainTrusted("subFrame", ["about:blank", "http://evil.example/", "trilium-app://app/"])).toBe(false);+ // Lookalike hosts under our own or other schemes.+ expect(isRequestorChainTrusted("xhr", ["trilium-app://app.evil.example/"])).toBe(false);+ expect(isRequestorChainTrusted("xhr", ["trilium-app://evil/"])).toBe(false);+ // Chains with no committed frame at all attest nothing.+ expect(isRequestorChainTrusted("xhr", ["about:blank"])).toBe(false);+ expect(isRequestorChainTrusted("xhr", [])).toBe(false);+ // Unparseable frame URLs.+ expect(isRequestorChainTrusted("xhr", ["<disposed frame>"])).toBe(false);+ });++ it("registers for trilium-app URLs and cancels based on the frame chain", async () => {+ const { filter, listener } = await installGuard();+ expect(filter).toEqual({ urls: ["trilium-app://*/*"] });++ expect(decide(listener, "xhr", frameChain("trilium-app://app/"))).toBe(false);+ expect(decide(listener, "xhr", frameChain("http://evil.example/", "trilium-app://app/"))).toBe(true);+ expect(decide(listener, "mainFrame", frameChain(""))).toBe(false);+ });++ it("denies subresource requests with no frame attached", async () => {+ const { listener } = await installGuard();+ expect(decide(listener, "xhr", null)).toBe(true);+ expect(decide(listener, "xhr", undefined)).toBe(true);+ });++ it("denies when reading the frame chain throws (disposed frame)", async () => {+ const { listener } = await installGuard();+ const disposed = {+ get url(): string { throw new Error("Render frame was disposed"); },+ parent: null+ };+ expect(decide(listener, "xhr", disposed)).toBe(true);+ });+ });+it("does NOT tag plain Express requests with the internal-electron marker", () => {// Anything that didn't come through `dispatch()` — i.e. a real HTTP// request to the TCP listener, or an arbitrary attacker-controlleddiff --git a/apps/desktop/src/protocol.ts b/apps/desktop/src/protocol.tsindex 5b19501238..44882ba6a2 100644--- a/apps/desktop/src/protocol.ts+++ b/apps/desktop/src/protocol.ts@@ -48,9 +48,10 @@ export function registerTriliumAppScheme() {*/export function setupTriliumAppProtocol(app: Application) {electron.app.whenReady().then(() => {+ installFrameOriginGuard();electron.protocol.handle("trilium-app", async (request) => {const origin = request.headers.get("origin");- if (!isDispatchOriginAllowed(request.method, origin)) {+ if (!isDispatchOriginAllowed(origin)) {console.error(`[trilium-app] blocked ${request.method} ${request.url} from origin '${origin}'`);return new Response("Forbidden", { status: 403 });}@@ -65,36 +66,99 @@ export function setupTriliumAppProtocol(app: Application) {}/**- * Origin gate in front of `dispatch`. Every dispatched request is tagged with- * `markAsInternalElectronRequest`, which bypasses auth and CSRF — so before- * dispatching we require Chromium's attestation that the request actually- * originates from our own scheme.+ * The primary gate in front of `dispatch`. Every dispatched request is tagged+ * with `markAsInternalElectronRequest`, which bypasses auth and CSRF — so a+ * request may only reach `dispatch` if it comes from the app shell itself.*- * `Origin` is a forbidden header name: page JavaScript cannot set or override- * it, Chromium stamps the requesting frame's true origin. And since- * `trilium-app://` is not a network listener — it only exists in this- * process's protocol registry — every request seen here comes from a Chromium- * frame whose Origin header (when present) is trustworthy.+ * Request headers cannot make that distinction. Empirically (Electron 41, and+ * contrary to how http(s) origins behave) Chromium stamps **no** identifying+ * headers on requests to a privileged custom scheme: same-origin renderer+ * requests carry no `Origin` even on POST/PUT, cross-origin `fetch()` calls+ * from foreign http(s) or sandboxed frames *also* arrive without `Origin`,+ * and no `Sec-Fetch-*` or `Referer` headers exist at all. Worse, `corsEnabled`+ * is not actually enforced for reads — a foreign frame can both send and read+ * responses. Only navigation-style requests (e.g. `<form>` POSTs) get an+ * `Origin` stamped. Custom marker headers are no help either: foreign frames+ * can attach them without triggering a CORS preflight.*- * Policy:- * 1. `Origin` present but not exactly `trilium-app://app` (the sole origin- * the app ever loads — see the loadURL call sites) → reject. Catches- * foreign http(s) frames, the opaque `"null"` origin of sandboxed frames,- * and any other host under our own scheme.- * 2. No `Origin` on a state-changing method → reject. Chromium always- * attaches Origin to cross-origin and non-GET/HEAD requests, so a write- * without one is anomalous by construction.- * 3. No `Origin` on GET / HEAD → allow. Legitimate for top-level navigations- * (main-process `loadURL`, the print window) and same-origin subresource- * loads. Foreign-frame GETs can't read responses anyway: `corsEnabled` on- * the scheme means CORS applies and no `Access-Control-Allow-Origin` is- * ever returned.+ * What Chromium *does* expose truthfully is the requesting frame, via+ * `webRequest` — `details.frame` and its `parent` chain are main-process-side+ * state that renderer content cannot forge. So the policy is enforced in+ * `onBeforeRequest`, before the protocol handler ever runs:+ *+ * - Top-level navigations are allowed: they originate from main-process+ * `loadURL` calls (main / extra / setup / print windows) or are already+ * vetted by the `will-navigate` guard in `web_contents_security.ts`.+ * - Every other request — subframe navigations, fetch/XHR, scripts, images —+ * must come from a frame chain consisting solely of the app shell+ * (`trilium-app://app`, the sole origin ever loaded — see the loadURL call+ * sites). Uncommitted frames (`about:blank` / `about:srcdoc` / empty URL)+ * inherit their embedder's trust, mirroring Chromium's own origin+ * inheritance; the chain still has to contain at least one committed app+ * frame. This denies requests from foreign frames anywhere in the chain —+ * e.g. a remote page loaded into an iframe — including frames *nested+ * inside* such content.+ * - DevTools frames are allowed so source-map fetches for `trilium-app://`+ * scripts keep working; page content can never navigate a frame to the+ * privileged `devtools://` scheme.+ *+ * `<webview>` guests are out of scope by construction: they live in a+ * dedicated session partition where the `trilium-app://` handler is not even+ * registered, so the scheme does not resolve there at all.*/-export function isDispatchOriginAllowed(method: string, origin: string | null): boolean {- if (origin !== null) {- return origin === "trilium-app://app";+function installFrameOriginGuard() {+ electron.session.defaultSession.webRequest.onBeforeRequest({ urls: ["trilium-app://*/*"] }, (details, callback) => {+ let frameUrls: string[];+ try {+ frameUrls = [];+ for (let frame = details.frame; frame; frame = frame.parent) {+ frameUrls.push(frame.url);+ }+ } catch {+ // Accessing a disposed frame throws; with no attestation left the+ // requester is gone anyway, so deny.+ frameUrls = ["<disposed frame>"];+ }++ const allowed = isRequestorChainTrusted(details.resourceType, frameUrls);+ if (!allowed) {+ console.error(`[trilium-app] blocked ${details.method} ${details.url} from frame chain [${frameUrls.join(" ← ")}]`);+ }+ callback({ cancel: !allowed });+ });+}++/** Pure policy behind {@link installFrameOriginGuard}; exported for tests. */+export function isRequestorChainTrusted(resourceType: string, frameUrls: string[]): boolean {+ if (resourceType === "mainFrame") {+ return true;+ }+ const committed = frameUrls.filter((frameUrl) => frameUrl !== "" && frameUrl !== "about:blank" && frameUrl !== "about:srcdoc");+ if (committed.length === 0) {+ return false;+ }+ return committed.every(isTrustedFrameUrl);+}++function isTrustedFrameUrl(frameUrl: string): boolean {+ try {+ const parsed = new URL(frameUrl);+ return (parsed.protocol === "trilium-app:" && parsed.host === "app") || parsed.protocol === "devtools:";+ } catch {+ return false;}- return method === "GET" || method === "HEAD";+}++/**+ * Second, weaker layer behind the frame-origin guard: rejects any request+ * that *positively* attests a foreign origin. As described above, the only+ * requests that carry an `Origin` on this scheme are navigation-style ones+ * (e.g. a hostile `<form method=POST>` targeting `trilium-app://`); the app's+ * own traffic and — unfortunately — foreign `fetch()` calls carry none, so+ * the absence of the header proves nothing and must be allowed through.+ */+export function isDispatchOriginAllowed(origin: string | null): boolean {+ return origin === null || origin === "trilium-app://app";}export async function dispatch(app: Application, request: Request): Promise<Response> {