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(mcp): run the desktop network gate ahead of the MCP routes
Elian Dorane4f4e36a4bac
diff --git a/apps/server/spec/etapi/mcp.spec.ts b/apps/server/spec/etapi/mcp.spec.tsindex 26dc6a9d40..abd8a4d635 100644--- a/apps/server/spec/etapi/mcp.spec.ts+++ b/apps/server/spec/etapi/mcp.spec.ts@@ -4,6 +4,7 @@ import supertest from "supertest";import { beforeAll, describe, expect, it } from "vitest";import config from "../../src/services/config.js";+import etapiTokenService from "../../src/services/etapi_tokens.js";import { createNote, login } from "./utils.js";let app: Application;@@ -26,17 +27,20 @@ function parseSseResponse(text: string) {return JSON.parse(dataLine.slice("data: ".length));}-function mcpPost(app: Application) {+/** An MCP request carrying no credentials at all. */+function mcpPostAnonymous(app: Application) {return supertest(app).post("/mcp")- // supertest binds to an ephemeral port, so its default Host (127.0.0.1:<random>)- // would be rejected by the DNS-rebinding allow-list. Present a bare loopback Host,- // matching what a real client on a standard port sends..set("Host", "localhost").set("Accept", MCP_ACCEPT).set("Content-Type", "application/json");}+/** An MCP request authenticated with the suite's token — what every real client sends. */+function mcpPost(app: Application) {+ return mcpPostAnonymous(app).set("Authorization", token);+}+function setOption(name: Parameters<typeof optionService.setOption>[0], value: string) {cls.init(() => optionService.setOption(name, value));}@@ -85,7 +89,52 @@ describe("mcp", () => {clientInfo: { name: "test", version: "1.0.0" }}));- expect(response.status).not.toBe(403);+ expect(response.status).toBe(200);+ });+ });++ // Loopback is not a credential: any local process can reach the listener, so a token is+ // required on every request. Without these, the rest of the suite could keep passing+ // while the endpoint silently rejected or silently admitted everyone.+ describe("authentication", () => {+ beforeAll(() => {+ setOption("mcpEnabled", "true");+ });++ it("rejects a request that carries no token", async () => {+ const response = await mcpPostAnonymous(app)+ .send(jsonRpc("initialize"))+ .expect(401);++ expect(response.body.error).toContain("ETAPI token");+ });++ it("rejects a token that was never issued", async () => {+ const response = await mcpPostAnonymous(app)+ .set("Authorization", "Bearer nSFHqNzUUAtCHTIm_not_a_real_token")+ .send(jsonRpc("initialize"))+ .expect(401);++ expect(response.body.error).toContain("ETAPI token");+ });++ it("stops accepting a token once it is revoked", async () => {+ const name = "mcp revocation spec";+ const { authToken } = cls.init(() => etapiTokenService.createToken(name));++ await mcpPostAnonymous(app)+ .set("Authorization", `Bearer ${authToken}`)+ .send(jsonRpc("initialize"))+ .expect(200);++ const issued = becca.getEtapiTokens().find(t => t.name === name);+ expect(issued).toBeDefined();+ cls.init(() => etapiTokenService.deleteToken(issued?.etapiTokenId ?? ""));++ await mcpPostAnonymous(app)+ .set("Authorization", `Bearer ${authToken}`)+ .send(jsonRpc("initialize"))+ .expect(401);});});diff --git a/apps/server/src/app.ts b/apps/server/src/app.tsindex c93c6361af..bc61f1dcf3 100644--- a/apps/server/src/app.ts+++ b/apps/server/src/app.ts@@ -97,17 +97,19 @@ export default async function buildApp() {app.use(express.urlencoded({ extended: false }));app.use(cookieParser());+ // Desktop only: gate web access (SPA/login, /share, /api, static assets) behind+ // the network-access opt-in. Mounted before the static/app/share routes, and before+ // MCP so that the gate's loopback-Host check applies there too — Express dispatches+ // in registration order, so a route registered first would answer before this ever+ // ran. The localhost integrations it exempts 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);+// MCP is registered before session/auth middleware — it authenticates with its own// guard (an ETAPI token, always required) and never uses the Trilium session, which// would make the endpoint CSRF-able.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/routes/transport.spec.ts b/apps/server/src/routes/transport.spec.tsindex 328445a951..8301d41d83 100644--- a/apps/server/src/routes/transport.spec.ts+++ b/apps/server/src/routes/transport.spec.ts@@ -154,6 +154,31 @@ describe("Route transport & middleware", () => {expect(res.headers["www-authenticate"]).toBeUndefined();});+ it("does not accept a logged-in browser session in place of a token", async () => {+ cls.init(() => optionService.setOption("mcpEnabled", "true"));+ // A session of its own: the shared ctx.agent was logged out by an earlier test,+ // and a dead session would make this pass without proving anything.+ const agent = supertest.agent(app);+ await agent.post("/login").send({ password: "demo1234" }).expect(302);+ const csrfToken = (await agent.get("/bootstrap").expect(200)).body.csrfToken;+ await agent.post("/api/tree/load")+ .set("x-csrf-token", csrfToken)+ .send({ noteIds: ["root"] })+ .expect(200);++ // That cookie now demonstrably authenticates the internal API. If it also worked+ // here, /mcp would be CSRF-able by any page the logged-in user visits — with full+ // tool access. Only the Authorization header may authenticate.+ const res = await agent+ .post("/mcp")+ .set("Host", `localhost:${port}`)+ .set("Content-Type", "application/json")+ .set("Accept", "application/json, text/event-stream")+ .send(initializeRequest)+ .expect(401);+ expect(res.body.error).toContain("ETAPI token");+ });+it("rejects a bogus token with 401", async () => {cls.init(() => optionService.setOption("mcpEnabled", "true"));const res = await supertest(app)diff --git a/apps/server/src/services/desktop_network_gate.spec.ts b/apps/server/src/services/desktop_network_gate.spec.tsindex fa11f0bc50..8839ef02bd 100644--- a/apps/server/src/services/desktop_network_gate.spec.ts+++ b/apps/server/src/services/desktop_network_gate.spec.ts@@ -1,12 +1,33 @@-import type { NextFunction, Request, Response } from "express";-import { describe, expect, it, vi } from "vitest";+import { cls, options as optionService } from "@triliumnext/core";+import type { Application, NextFunction, Request, Response } from "express";+import supertest from "supertest";+import { beforeAll, describe, expect, it, vi } from "vitest";++// Simulate the desktop build — the only one where the middleware gates anything.+vi.mock("./utils.js", async (orig) => {+ const actual = await orig<typeof import("./utils.js")>();+ return { ...actual, isElectron: true, default: { ...actual.default, isElectron: true } };+});-// 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 } } }));+// Network access defaults to off (the state that gates anything) but is exposed through a+// getter so a test can flip it after the app has booted — the gate re-reads config on every+// request. The rest of the config stays real so the wiring tests can boot the actual app.+const network = vi.hoisted(() => ({ allowLanAccess: false }));+vi.mock("./config.js", async (orig) => {+ const actual = (await orig<typeof import("./config.js")>()).default;+ return {+ default: {+ ...actual,+ Security: {+ ...actual.Security,+ get allowLanAccess() { return network.allowLanAccess; }+ }+ }+ };+});import { desktopNetworkAccessGate, isLocalIntegrationPath, isLoopbackHost, shouldBlockDesktopWebRequest } from "./desktop_network_gate.js";+import etapiTokenService from "./etapi_tokens.js";function makeRes() {const res = {} as Record<string, unknown>;@@ -110,3 +131,83 @@ describe("desktopNetworkAccessGate (desktop build, network access off)", () => {expect(res.status).not.toHaveBeenCalled();});});++/**+ * The tests above call the middleware directly, so they cannot see whether it is mounted+ * anywhere the paths it names can actually reach it — the gate once sat *after* the MCP+ * routes in app.ts, which meant it never ran for `/mcp` at all. These boot the real app+ * and drive requests through the real middleware chain instead.+ */+describe("desktopNetworkAccessGate wiring (real app)", () => {+ let app: Application;++ const initializeRequest = {+ jsonrpc: "2.0",+ method: "initialize",+ id: 1,+ params: { protocolVersion: "2024-11-05", capabilities: {}, clientInfo: { name: "spec", version: "1" } }+ };++ function mcpPost(host: string, authToken: string) {+ return supertest(app)+ .post("/mcp")+ .set("Host", host)+ .set("Authorization", `Bearer ${authToken}`)+ .set("Content-Type", "application/json")+ .set("Accept", "application/json, text/event-stream")+ .send(initializeRequest);+ }++ function createToken(name: string) {+ cls.init(() => optionService.setOption("mcpEnabled", "true"));+ return cls.init(() => etapiTokenService.createToken(name)).authToken;+ }++ beforeAll(async () => {+ // Built without the usual login handshake: with the gate active, `POST /login` is+ // itself web access and gets refused, which is the behaviour under test.+ app = await (await import("../app.js")).default();+ });++ it("is mounted ahead of the MCP routes", () => {+ const layers = app.router.stack;+ const gateIndex = layers.findIndex((layer) => layer.name === "desktopNetworkAccessGate");+ const mcpIndex = layers.findIndex((layer) => layer.route?.path === "/mcp");++ expect(gateIndex).toBeGreaterThanOrEqual(0);+ expect(mcpIndex).toBeGreaterThanOrEqual(0);+ // Express dispatches in registration order: a route registered first terminates the+ // request before any middleware mounted after it gets a chance to run.+ expect(gateIndex).toBeLessThan(mcpIndex);+ });++ it("refuses a rebound (non-loopback) Host on /mcp even with a valid token", async () => {+ // Enabled + authenticated, so MCP's own guard would answer 200. Anything other than+ // the gate's 403 means the gate never ran.+ const res = await mcpPost("evil.example.com", createToken("mcp gate spec"));++ expect(res.status).toBe(403);+ expect(res.text).toContain("Network access");+ });++ it("still serves a loopback Host on /mcp, so local clients keep working", async () => {+ const res = await mcpPost("localhost:37740", createToken("mcp gate loopback spec"));++ expect(res.status).toBe(200);+ });++ it("serves /mcp on a LAN Host once network access is enabled", async () => {+ const authToken = createToken("mcp gate lan spec");+ // Same request the previous test proves is refused while network access is off, so a+ // 200 here can only come from the opt-in — this is the case the gate must not break+ // now that it sits ahead of the MCP routes.+ expect((await mcpPost("192.168.1.50:37740", authToken)).status).toBe(403);++ network.allowLanAccess = true;+ try {+ expect((await mcpPost("192.168.1.50:37740", authToken)).status).toBe(200);+ } finally {+ network.allowLanAccess = false;+ }+ });+});diff --git a/apps/server/src/services/desktop_network_gate.ts b/apps/server/src/services/desktop_network_gate.tsindex e6db094aee..f0f5a7861d 100644--- a/apps/server/src/services/desktop_network_gate.ts+++ b/apps/server/src/services/desktop_network_gate.ts@@ -9,9 +9,11 @@ import { isElectron } from "./utils.js";* has NOT enabled network access. These are same-machine integrations rather than* the web app:* - `/mcp` — the MCP transport, which requires an ETAPI token on every request- * (see routes/mcp.ts), exactly like `/etapi`. The loopback Host check below still- * applies on top, so on desktop a token alone does not reach the LAN until the user- * opts into network access.+ * (see routes/mcp.ts), exactly like `/etapi`. The loopback Host check below applies on+ * top of that token, which is why this middleware must stay mounted ahead of the MCP+ * routes in app.ts. Note it is the loopback *bind* (see host.ts), not this gate, that+ * keeps MCP off the LAN while network access is off — the check here only refuses a+ * rebound Host on a connection that already reached the loopback listener.* - `/api/clipper` — the web clipper endpoint the browser extension talks to.* - `/etapi` — the token-authenticated External API used by local automation.*