Skip to content

Build your personal knowledge base with Trilium Notes

fix(desktop): address review — session flush + DNS-rebind guard (#10589)

Elian Doran6d39a9e00738
diff --git a/apps/server/src/services/auth.spec.ts b/apps/server/src/services/auth.spec.ts
index 8d336a15fa..c7a1247d44 100644
--- a/apps/server/src/services/auth.spec.ts
+++ b/apps/server/src/services/auth.spec.ts
@@ -244,7 +244,9 @@ describe("Auth", () => {
const res = makeRes();
const next = vi.fn();
- const session = { loggedIn: true, lastAuthState: { totpEnabled: false, ssoEnabled: true } };
+ // save() flushes the loggedIn:false flip before handoff; invoke its callback so next() runs.
+ const save = vi.fn((cb: (err?: unknown) => void) => cb());
+ const session = { loggedIn: true, lastAuthState: { totpEnabled: false, ssoEnabled: true }, save };
auth.checkAuth(
makeReq({ session, oidc: { isAuthenticated: () => false } }),
res as never,
@@ -255,8 +257,9 @@ describe("Auth", () => {
expect(res.redirectedTo).not.toBe("login");
// Instead fall through so the SPA renders the login screen in place.
expect(next).toHaveBeenCalled();
- // And the stale flag is cleared so subsequent requests take the plain logged-out path.
+ // And the stale flag is cleared (and persisted) so subsequent requests take the logged-out path.
expect(session.loggedIn).toBe(false);
+ expect(save).toHaveBeenCalled();
});
it("checkAuth falls through to next on the normal logged-in path", () => {
diff --git a/apps/server/src/services/auth.ts b/apps/server/src/services/auth.ts
index 3eba834d25..5cd4d8333a 100644
--- a/apps/server/src/services/auth.ts
+++ b/apps/server/src/services/auth.ts
@@ -75,8 +75,17 @@ function checkAuth(req: Request, res: Response, next: NextFunction) {
// which lands right back in this branch (#10589 follow-up). Treat the session as logged
// out and serve the SPA, which renders the login screen from the bootstrap
// loggedIn:false payload. The API stays protected separately via checkApiAuth.
+ //
+ // Persist the flip explicitly before handing off: express-session's implicit save
+ // only runs on res.end(), so with an async store the SPA's immediately-following
+ // /bootstrap sub-request could otherwise read the still-loggedIn session and bounce
+ // back through this branch instead of seeing loggedIn:false.
req.session.loggedIn = false;
- return next();
+ req.session.save((err) => {
+ if (err) console.error("Error saving session after OIDC session lapse:", err);
+ next();
+ });
+ return;
} else {
next();
}
diff --git a/apps/server/src/services/desktop_network_gate.spec.ts b/apps/server/src/services/desktop_network_gate.spec.ts
index 0db2aacc0f..75c5d696b9 100644
--- a/apps/server/src/services/desktop_network_gate.spec.ts
+++ b/apps/server/src/services/desktop_network_gate.spec.ts
@@ -6,7 +6,7 @@ import { describe, expect, it, vi } from "vitest";
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";
+import { desktopNetworkAccessGate, isLocalIntegrationPath, isLoopbackHost, shouldBlockDesktopWebRequest } from "./desktop_network_gate.js";
function makeRes() {
const res = {} as Record<string, unknown>;
@@ -35,8 +35,19 @@ describe("isLocalIntegrationPath", () => {
});
});
+describe("isLoopbackHost", () => {
+ it("accepts loopback host headers (with or without port / brackets) and rejects the rest", () => {
+ for (const host of ["localhost", "localhost:37742", "127.0.0.1", "127.0.0.1:37742", "127.5.5.5", "[::1]", "[::1]:37742"]) {
+ expect(isLoopbackHost(host)).toBe(true);
+ }
+ for (const host of [undefined, "", "evil.example.com", "evil.example.com:37742", "192.168.1.9:37742", "localhost.evil.com"]) {
+ expect(isLoopbackHost(host)).toBe(false);
+ }
+ });
+});
+
describe("shouldBlockDesktopWebRequest", () => {
- const base = { isElectron: true, allowLanAccess: false, isInternal: false, path: "/" };
+ const base = { isElectron: true, allowLanAccess: false, isInternal: false, path: "/", host: "localhost:37742" };
it("never blocks on the server build", () => {
expect(shouldBlockDesktopWebRequest({ ...base, isElectron: false })).toBe(false);
@@ -60,11 +71,17 @@ describe("shouldBlockDesktopWebRequest", () => {
expect(shouldBlockDesktopWebRequest({ ...base, path: "/share/abc" })).toBe(true);
});
- it("still allows the localhost integrations (MCP, clipper) when network access is off", () => {
+ it("still allows the localhost integrations (MCP, clipper, ETAPI) from a loopback host", () => {
expect(shouldBlockDesktopWebRequest({ ...base, path: "/mcp" })).toBe(false);
expect(shouldBlockDesktopWebRequest({ ...base, path: "/api/clipper/handshake" })).toBe(false);
expect(shouldBlockDesktopWebRequest({ ...base, path: "/etapi/notes" })).toBe(false);
});
+
+ it("blocks the localhost integrations when the Host header is non-loopback (DNS rebinding)", () => {
+ expect(shouldBlockDesktopWebRequest({ ...base, path: "/api/clipper/handshake", host: "evil.example.com" })).toBe(true);
+ expect(shouldBlockDesktopWebRequest({ ...base, path: "/etapi/notes", host: "evil.example.com:37742" })).toBe(true);
+ expect(shouldBlockDesktopWebRequest({ ...base, path: "/mcp", host: undefined })).toBe(true);
+ });
});
describe("desktopNetworkAccessGate (desktop build, network access off)", () => {
@@ -72,7 +89,7 @@ describe("desktopNetworkAccessGate (desktop build, network access off)", () => {
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);
+ desktopNetworkAccessGate({ path: "/", headers: { host: "localhost:37742" } } as unknown as Request, res, next);
expect(res.status).toHaveBeenCalledWith(403);
expect(next).not.toHaveBeenCalled();
@@ -81,7 +98,7 @@ describe("desktopNetworkAccessGate (desktop build, network access off)", () => {
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);
+ desktopNetworkAccessGate({ path: "/api/clipper/handshake", headers: { host: "localhost:37742" } } as unknown 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
index 4b33aa0e77..0a2f38b343 100644
--- a/apps/server/src/services/desktop_network_gate.ts
+++ b/apps/server/src/services/desktop_network_gate.ts
@@ -23,6 +23,23 @@ export function isLocalIntegrationPath(path: string): boolean {
return LOCAL_INTEGRATION_PREFIXES.some((prefix) => path === prefix || path.startsWith(`${prefix}/`));
}
+/**
+ * Whether an HTTP `Host` header names a loopback address. Used to keep the local
+ * integrations reachable only from genuine same-machine clients: a page that has
+ * DNS-rebound its own domain to 127.0.0.1 still connects from loopback (so an IP
+ * check passes) but sends its original host, so the Host header is what exposes it
+ * — the same defence MCP applies (see routes/mcp.ts). Guards the unauthenticated
+ * web-clipper endpoint in particular.
+ */
+export function isLoopbackHost(host: string | undefined): boolean {
+ if (!host) {
+ return false;
+ }
+ // Strip any :port and IPv6 brackets: "127.0.0.1:37742" → "127.0.0.1", "[::1]:37742" → "::1".
+ const hostname = host.replace(/:\d+$/, "").replace(/^\[|\]$/g, "");
+ return hostname === "localhost" || hostname === "::1" || hostname.startsWith("127.");
+}
+
/**
* Pure decision for {@link desktopNetworkAccessGate}, extracted so the branching is
* unit-testable without a live Electron build (isElectron is a process constant).
@@ -36,17 +53,23 @@ export function shouldBlockDesktopWebRequest(opts: {
allowLanAccess: boolean;
isInternal: boolean;
path: string;
+ host: string | undefined;
}): 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
+ return false; // opted into network access — serve everything (LAN clients included)
}
if (opts.isInternal) {
return false; // our own renderer, dispatched in-process — never gated
}
- return !isLocalIntegrationPath(opts.path);
+ if (!isLocalIntegrationPath(opts.path)) {
+ return true; // the web app / share — gated behind the network-access opt-in
+ }
+ // A local integration on the loopback-only listener: additionally require a loopback
+ // Host header so a DNS-rebound attacker domain can't drive the unauthenticated clipper.
+ return !isLoopbackHost(opts.host);
}
/**
@@ -61,7 +84,8 @@ export function desktopNetworkAccessGate(req: Request, res: Response, next: Next
isElectron,
allowLanAccess: config.Security?.allowLanAccess === true,
isInternal: isInternalElectronRequest(req),
- path: req.path
+ path: req.path,
+ host: req.headers.host
});
if (blocked) {