Skip to content

Build your personal knowledge base with Trilium Notes

feat(desktop): gate web/share access behind the network-access opt-in (#10589)

Elian Doranad2ee729ba69
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index dd920af36a..b6c4636bad 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -1835,9 +1835,9 @@
"sql_console_label": "SQL console",
"sql_console_description": "Allow execution of queries in the SQL console.",
"lan_access_title": "Network access",
- "lan_access_section_description": "By default the desktop app only accepts connections from this computer. Allow access from your local network so other devices can connect to it — for example to sync from another device. Only enable this on networks you trust.",
- "lan_access_label": "Allow connections from other devices",
- "lan_access_description": "Bind the server to all network interfaces instead of localhost only.",
+ "lan_access_section_description": "By default the desktop app is self-contained: the app and your shared notes aren't served over the network, and only local integrations (web clipper, MCP, ETAPI) can reach it from this computer. Enable this to open the app and shared notes in a browser, and to let other devices connect — for example, to sync. Only enable this on networks you trust.",
+ "lan_access_label": "Allow web and network access",
+ "lan_access_description": "Serves the app, shared notes and live updates over HTTP — reachable from a browser on this computer and from other devices on your network. When off, only local integrations (web clipper, MCP, ETAPI) remain reachable.",
"how_to_enable": "How to enable",
"server_config_hint": "Add the following to your config.ini file:",
"server_env_hint": "Or set the following environment variable:",
diff --git a/apps/server/src/app.ts b/apps/server/src/app.ts
index 47bd71395e..c6ee5c457d 100644
--- a/apps/server/src/app.ts
+++ b/apps/server/src/app.ts
@@ -18,6 +18,7 @@ import mcpRoutes from "./routes/mcp.js";
import routes from "./routes/routes.js";
import config from "./services/config.js";
import { getLog } from "@triliumnext/core";
+import { desktopNetworkAccessGate } from "./services/desktop_network_gate.js";
import { createReactiveOidcMiddleware } from "./services/open_id.js";
import { RESOURCE_DIR } from "./services/resource_dir.js";
import utils, { getResourceDir, isDev } from "./services/utils.js";
@@ -100,6 +101,12 @@ export default async function buildApp() {
// localhost-only guard and does not require Trilium authentication.
mcpRoutes.register(app);
+ // Desktop only: gate web access (SPA/login, /share, /api, static assets) behind
+ // the network-access opt-in. Mounted after MCP and before the static/app/share
+ // routes so those local integrations stay reachable on loopback while the web app
+ // does not, unless the user enables network access. No-op on the server build.
+ app.use(desktopNetworkAccessGate);
+
app.use(express.static(path.join(publicDir, "root"), STATIC_OPTIONS));
app.use(`/manifest.webmanifest`, express.static(path.join(publicAssetsDir, "manifest.webmanifest"), STATIC_OPTIONS));
app.use(`/robots.txt`, express.static(path.join(publicAssetsDir, "robots.txt"), STATIC_OPTIONS));
diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.json
index ce1af2f5ca..b305db1c82 100644
--- a/apps/server/src/assets/translations/en/server.json
+++ b/apps/server/src/assets/translations/en/server.json
@@ -460,6 +460,6 @@
"sql-console": "SQL console",
"sql-console-warning": "The SQL console allows executing arbitrary SQL queries against the database.",
"lan-access": "network access",
- "lan-access-warning": "Other devices on your local network will be able to connect to this Trilium instance."
+ "lan-access-warning": "The app and your shared notes will be served over the network — reachable from a browser on this computer and from other devices on your local network."
}
}
diff --git a/apps/server/src/services/desktop_network_gate.spec.ts b/apps/server/src/services/desktop_network_gate.spec.ts
new file mode 100644
index 0000000000..0db2aacc0f
--- /dev/null
+++ b/apps/server/src/services/desktop_network_gate.spec.ts
@@ -0,0 +1,89 @@
+import type { NextFunction, Request, Response } from "express";
+import { describe, expect, it, vi } from "vitest";
+
+// Simulate the desktop build with network access off — the only configuration in
+// which the middleware actually gates anything.
+vi.mock("./utils.js", async (orig) => ({ ...(await orig<typeof import("./utils.js")>()), isElectron: true }));
+vi.mock("./config.js", () => ({ default: { Security: { allowLanAccess: false } } }));
+
+import { desktopNetworkAccessGate, isLocalIntegrationPath, shouldBlockDesktopWebRequest } from "./desktop_network_gate.js";
+
+function makeRes() {
+ const res = {} as Record<string, unknown>;
+ res.status = vi.fn(() => res);
+ res.type = vi.fn(() => res);
+ res.send = vi.fn(() => res);
+ return res as unknown as Response & { status: ReturnType<typeof vi.fn>; send: ReturnType<typeof vi.fn> };
+}
+
+describe("isLocalIntegrationPath", () => {
+ it("matches the MCP and clipper endpoints (and only those)", () => {
+ expect(isLocalIntegrationPath("/mcp")).toBe(true);
+ expect(isLocalIntegrationPath("/mcp/messages")).toBe(true);
+ expect(isLocalIntegrationPath("/api/clipper")).toBe(true);
+ expect(isLocalIntegrationPath("/api/clipper/handshake")).toBe(true);
+ expect(isLocalIntegrationPath("/etapi")).toBe(true);
+ expect(isLocalIntegrationPath("/etapi/notes")).toBe(true);
+
+ expect(isLocalIntegrationPath("/")).toBe(false);
+ expect(isLocalIntegrationPath("/bootstrap")).toBe(false);
+ expect(isLocalIntegrationPath("/api/tree")).toBe(false);
+ expect(isLocalIntegrationPath("/share/abc")).toBe(false);
+ // Must not be fooled by a prefix that isn't a path segment boundary.
+ expect(isLocalIntegrationPath("/mcp-evil")).toBe(false);
+ expect(isLocalIntegrationPath("/api/clipperx")).toBe(false);
+ });
+});
+
+describe("shouldBlockDesktopWebRequest", () => {
+ const base = { isElectron: true, allowLanAccess: false, isInternal: false, path: "/" };
+
+ it("never blocks on the server build", () => {
+ expect(shouldBlockDesktopWebRequest({ ...base, isElectron: false })).toBe(false);
+ expect(shouldBlockDesktopWebRequest({ ...base, isElectron: false, path: "/share/x" })).toBe(false);
+ });
+
+ it("serves everything once network access is enabled", () => {
+ expect(shouldBlockDesktopWebRequest({ ...base, allowLanAccess: true })).toBe(false);
+ expect(shouldBlockDesktopWebRequest({ ...base, allowLanAccess: true, path: "/share/x" })).toBe(false);
+ });
+
+ it("never blocks the trusted renderer (internal trilium-app:// request)", () => {
+ expect(shouldBlockDesktopWebRequest({ ...base, isInternal: true })).toBe(false);
+ expect(shouldBlockDesktopWebRequest({ ...base, isInternal: true, path: "/share/x" })).toBe(false);
+ });
+
+ it("blocks the web app and share for external requests when network access is off", () => {
+ expect(shouldBlockDesktopWebRequest({ ...base, path: "/" })).toBe(true);
+ expect(shouldBlockDesktopWebRequest({ ...base, path: "/bootstrap" })).toBe(true);
+ expect(shouldBlockDesktopWebRequest({ ...base, path: "/api/tree" })).toBe(true);
+ expect(shouldBlockDesktopWebRequest({ ...base, path: "/share/abc" })).toBe(true);
+ });
+
+ it("still allows the localhost integrations (MCP, clipper) when network access is off", () => {
+ expect(shouldBlockDesktopWebRequest({ ...base, path: "/mcp" })).toBe(false);
+ expect(shouldBlockDesktopWebRequest({ ...base, path: "/api/clipper/handshake" })).toBe(false);
+ expect(shouldBlockDesktopWebRequest({ ...base, path: "/etapi/notes" })).toBe(false);
+ });
+});
+
+describe("desktopNetworkAccessGate (desktop build, network access off)", () => {
+ it("responds 403 to an external web request and does not continue", () => {
+ const res = makeRes();
+ const next = vi.fn() as unknown as NextFunction;
+ // A plain object carries no internal-electron marker → treated as external/TCP.
+ desktopNetworkAccessGate({ path: "/" } as Request, res, next);
+
+ expect(res.status).toHaveBeenCalledWith(403);
+ expect(next).not.toHaveBeenCalled();
+ });
+
+ it("passes localhost-integration requests through to the next handler", () => {
+ const res = makeRes();
+ const next = vi.fn() as unknown as NextFunction;
+ desktopNetworkAccessGate({ path: "/api/clipper/handshake" } as Request, res, next);
+
+ expect(next).toHaveBeenCalled();
+ expect(res.status).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/desktop_network_gate.ts b/apps/server/src/services/desktop_network_gate.ts
new file mode 100644
index 0000000000..4b33aa0e77
--- /dev/null
+++ b/apps/server/src/services/desktop_network_gate.ts
@@ -0,0 +1,75 @@
+import type { NextFunction, Request, Response } from "express";
+
+import config from "./config.js";
+import { isInternalElectronRequest } from "./electron_request.js";
+import { isElectron } from "./utils.js";
+
+/**
+ * Paths that stay reachable on the desktop's loopback listener even when the user
+ * has NOT enabled network access. These are same-machine integrations rather than
+ * the web app:
+ * - `/mcp` — the MCP transport, which additionally self-restricts to loopback with
+ * DNS-rebinding protection (see routes/mcp.ts), so it never reaches the LAN.
+ * - `/api/clipper` — the web clipper endpoint the browser extension talks to.
+ * - `/etapi` — the token-authenticated External API used by local automation.
+ *
+ * Everything else (the SPA + login, `/share`, the authenticated `/api`, static
+ * assets) is "web access to the desktop instance" and is served only once the user
+ * opts into network access.
+ */
+const LOCAL_INTEGRATION_PREFIXES = ["/mcp", "/api/clipper", "/etapi"];
+
+export function isLocalIntegrationPath(path: string): boolean {
+ return LOCAL_INTEGRATION_PREFIXES.some((prefix) => path === prefix || path.startsWith(`${prefix}/`));
+}
+
+/**
+ * Pure decision for {@link desktopNetworkAccessGate}, extracted so the branching is
+ * unit-testable without a live Electron build (isElectron is a process constant).
+ *
+ * Blocks a request only when ALL hold: it's the desktop build, the user hasn't
+ * enabled network access, it arrived over TCP (not from our own trilium-app://
+ * renderer), and it targets something other than a localhost integration.
+ */
+export function shouldBlockDesktopWebRequest(opts: {
+ isElectron: boolean;
+ allowLanAccess: boolean;
+ isInternal: boolean;
+ path: string;
+}): boolean {
+ if (!opts.isElectron) {
+ return false; // server build — web access is the whole point
+ }
+ if (opts.allowLanAccess) {
+ return false; // opted into network access — serve everything
+ }
+ if (opts.isInternal) {
+ return false; // our own renderer, dispatched in-process — never gated
+ }
+ return !isLocalIntegrationPath(opts.path);
+}
+
+/**
+ * Gates web access to a desktop instance behind the network-access opt-in
+ * (`allowLanAccess`). With it off, a browser (or any TCP client) reaching the
+ * loopback listener can still use the localhost integrations but not the app or
+ * shared notes. Mounted before the static/app/share routes; the renderer bypasses
+ * it via the internal-electron marker.
+ */
+export function desktopNetworkAccessGate(req: Request, res: Response, next: NextFunction): void {
+ const blocked = shouldBlockDesktopWebRequest({
+ isElectron,
+ allowLanAccess: config.Security?.allowLanAccess === true,
+ isInternal: isInternalElectronRequest(req),
+ path: req.path
+ });
+
+ if (blocked) {
+ res.status(403).type("text/plain").send(
+ 'Web access to this Trilium desktop instance is disabled. Enable "Network access" in Settings → Security to reach it from a browser.'
+ );
+ return;
+ }
+
+ next();
+}