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
feat(server): prevent unauthenticated access over Electron
Elian Doran7008f6a2945a
diff --git a/apps/server/src/routes/csrf_protection.ts b/apps/server/src/routes/csrf_protection.tsindex 450b8089e8..8b153909be 100644--- a/apps/server/src/routes/csrf_protection.ts+++ b/apps/server/src/routes/csrf_protection.ts@@ -1,8 +1,8 @@import { doubleCsrf } from "csrf-csrf";import type { NextFunction, Request, Response } from "express";+import { isInternalElectronRequest } from "../services/electron_request.js";import sessionSecret from "../services/session_secret.js";-import { isElectron } from "../services/utils.js";export const CSRF_COOKIE_NAME = "trilium-csrf";@@ -20,13 +20,15 @@ const doubleCsrfUtilities = doubleCsrf({export const { generateCsrfToken } = doubleCsrfUtilities;-// Skip CSRF validation under Electron. The desktop renderer is our own UI,-// requests arrive through the `trilium-app://` custom protocol, and Express-// sessions don't round-trip through that path — so the HMAC double-submit-// check has nothing meaningful to validate against. Auth is similarly-// bypassed for Electron in `services/auth.ts`.+// Skip CSRF validation only for requests dispatched via the `trilium-app://`+// custom protocol from our own renderer — Express sessions don't round-trip+// through that path, so the HMAC double-submit check has nothing meaningful+// to validate against. Keying off the per-request marker (rather than the+// process-wide `isElectron` flag) means TCP requests to the desktop's HTTP+// listener still get the full CSRF check. Auth is similarly gated in+// `services/auth.ts`.export function doubleCsrfProtection(req: Request, res: Response, next: NextFunction) {- if (isElectron) {+ if (isInternalElectronRequest(req)) {return next();}return doubleCsrfUtilities.doubleCsrfProtection(req, res, next);diff --git a/apps/server/src/routes/electron.spec.ts b/apps/server/src/routes/electron.spec.tsindex 0761dad0b6..c348a474b6 100644--- a/apps/server/src/routes/electron.spec.ts+++ b/apps/server/src/routes/electron.spec.ts@@ -10,6 +10,7 @@ vi.mock("electron", () => ({}));const { dispatch } = await import("./electron.js");+const { isInternalElectronRequest } = await import("../services/electron_request.js");function buildTestApp() {const app = express();@@ -63,4 +64,40 @@ describe("electron protocol dispatcher", () => {expect(response.status).toBe(200);expect(await response.json()).toEqual({ echo: { hello: "world" } });});++ // Auth + CSRF middleware rely on this marker to distinguish a+ // renderer→main protocol dispatch from a public-HTTP request hitting the+ // desktop's TCP listener. Regression for the auth bypass that used to+ // key off the process-wide `isElectron` flag.+ it("tags dispatched requests with the internal-electron marker", async () => {+ const app = express();+ let markedOnHandler: boolean | undefined;+ app.get("/probe", (req, res) => {+ markedOnHandler = isInternalElectronRequest(req);+ res.status(200).send("");+ });++ await dispatch(app, new Request("trilium-app://app/probe"));++ expect(markedOnHandler).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-controlled+ // payload — must register as untagged.+ const plainReq = {} as object;+ expect(isInternalElectronRequest(plainReq)).toBe(false);++ // An attacker can't forge the marker via HTTP headers / body fields+ // because the marker is keyed by a non-exported Symbol. Header maps+ // and JSON-decoded bodies that mention the string "trilium-electron-+ // internal-request" can't reach the Symbol-keyed slot.+ const headerForgery = { headers: { "trilium-electron-internal-request": "true" } };+ const bodyForgery = { body: { "trilium-electron-internal-request": true } };+ const stringKeyForgery: Record<string, unknown> = { "trilium-electron-internal-request": true };+ expect(isInternalElectronRequest(headerForgery)).toBe(false);+ expect(isInternalElectronRequest(bodyForgery)).toBe(false);+ expect(isInternalElectronRequest(stringKeyForgery)).toBe(false);+ });});diff --git a/apps/server/src/routes/electron.ts b/apps/server/src/routes/electron.tsindex c2368591ae..d115a0c548 100644--- a/apps/server/src/routes/electron.ts+++ b/apps/server/src/routes/electron.ts@@ -4,6 +4,8 @@ import type { Application } from "express";import { createResponse } from "node-mocks-http";import { Readable } from "node:stream";+import { markAsInternalElectronRequest } from "../services/electron_request.js";+/*** Bridges renderer-process requests on the `trilium-app://app/...` custom* protocol into the Express application running in the main process.@@ -140,7 +142,7 @@ function buildIncomingRequest(opts: BuildRequestOpts): object {const socket = { remoteAddress: "127.0.0.1", encrypted: false, readable: true, destroy() {}, end() {}, on() {}, removeListener() {} };- return Object.assign(stream, {+ const req = Object.assign(stream, {method: opts.method,url: opts.url,headers: opts.headers,@@ -157,6 +159,15 @@ function buildIncomingRequest(opts: BuildRequestOpts): object {connection: socket,ip: "127.0.0.1"});++ // Tag the request so auth/CSRF middleware can distinguish a renderer→main+ // protocol dispatch from a public-HTTP request. Without this they would+ // have to fall back to the process-wide `isElectron` flag, which would+ // also bypass the bypass for LAN-reachable TCP requests on the desktop's+ // HTTP listener.+ markAsInternalElectronRequest(req);++ return req;}// Headers that either describe HTTP transport framing or assume an httpsdiff --git a/apps/server/src/services/auth.ts b/apps/server/src/services/auth.tsindex 63b6a5a66b..1b620973d4 100644--- a/apps/server/src/services/auth.ts+++ b/apps/server/src/services/auth.ts@@ -2,6 +2,7 @@ import etapiTokenService from "./etapi_tokens.js";import log from "./log.js";import sqlInit from "./sql_init.js";import { isElectron } from "./utils.js";+import { isInternalElectronRequest } from "./electron_request.js";import passwordEncryptionService from "./encryption/password_encryption.js";import config from "./config.js";import passwordService from "./encryption/password.js";@@ -25,7 +26,7 @@ function checkAuth(req: Request, res: Response, next: NextFunction) {const currentSsoStatus = openID.isOpenIDEnabled();const lastAuthState = req.session.lastAuthState || { totpEnabled: false, ssoEnabled: false };- if (isElectron || noAuthentication) {+ if (isInternalElectronRequest(req) || noAuthentication) {next();return;} else if (!req.session.loggedIn && !noAuthentication) {@@ -79,7 +80,7 @@ function checkApiAuthOrElectron(req: Request, res: Response, next: NextFunction)return next();}- if (!req.session.loggedIn && !isElectron && !noAuthentication) {+ if (!req.session.loggedIn && !isInternalElectronRequest(req) && !noAuthentication) {console.warn(`Missing session with ID '${req.sessionID}'.`);reject(req, res, "Logged in session not found");} else {@@ -94,8 +95,11 @@ function checkApiAuth(req: Request, res: Response, next: NextFunction) {// The desktop renderer is trusted (it's our own UI). API requests come in// via the `trilium-app://` custom protocol where Express sessions don't- // round-trip, so we bypass auth here the same way `checkAuth` does.- if (isElectron || noAuthentication) {+ // round-trip — those carry the internal-electron marker and bypass auth.+ // Requests that arrive over the desktop's TCP HTTP listener (LAN, DNS-+ // rebound browser, co-resident process) do NOT carry the marker and go+ // through the normal session check.+ if (isInternalElectronRequest(req) || noAuthentication) {return next();}diff --git a/apps/server/src/services/electron_request.ts b/apps/server/src/services/electron_request.tsnew file mode 100644index 0000000000..ddd4692ab0--- /dev/null+++ b/apps/server/src/services/electron_request.ts@@ -0,0 +1,26 @@+/**+ * Per-request marker for the Electron `trilium-app://` custom-protocol path.+ *+ * The desktop build runs the full Express stack inside the Electron main+ * process. The renderer makes API calls via the custom protocol (see+ * `apps/server/src/routes/electron.ts`), which dispatches a synthesised+ * request through the same Express app instance as the public HTTP listener.+ *+ * Auth and CSRF middleware historically bypassed on the process-wide+ * `isElectron` flag, which meant any TCP request to the desktop's listener+ * (LAN, DNS-rebound browser, co-resident process) shared the bypass.+ * Instead, the dispatcher tags only its own requests with this marker, and+ * middleware checks the marker — so TCP traffic is treated like any other+ * external request.+ *+ * Symbol-keyed so attacker-supplied JSON / headers cannot collide.+ */+const ELECTRON_INTERNAL_REQUEST = Symbol("trilium-electron-internal-request");++export function markAsInternalElectronRequest(req: object): void {+ (req as Record<symbol, unknown>)[ELECTRON_INTERNAL_REQUEST] = true;+}++export function isInternalElectronRequest(req: object): boolean {+ return (req as Record<symbol, unknown>)[ELECTRON_INTERNAL_REQUEST] === true;+}diff --git a/apps/server/src/services/host.ts b/apps/server/src/services/host.tsindex eee470e084..fbe9f18ad2 100644--- a/apps/server/src/services/host.ts+++ b/apps/server/src/services/host.ts@@ -7,7 +7,18 @@ function getHost() {return envHost;}- return config["Network"]["host"] || "0.0.0.0";+ const configHost = config["Network"]["host"];+ if (configHost) {+ return configHost;+ }++ // The desktop renderer talks to the server via the `trilium-app://`+ // custom protocol (in-process); the TCP listener only needs to serve+ // same-host traffic (the renderer's WebSocket). Binding loopback by+ // default keeps the local port off the LAN — defense in depth on top+ // of the per-request auth marker. A user who wants LAN access can still+ // set `[Network] host=` in config.ini.+ return isElectron ? "127.0.0.1" : "0.0.0.0";}export default getHost();