#1 Persistent memory for AI coding agents based on real-world benchmarks
TypeScript agentmemoryagentsaiclaudeclaudecodecodexcopilotcursorgenaiharnesshermesmemoryompopenclawopencodepi
fix(security): reject non-loopback Host headers in viewer server (DNS rebinding) (#294)
@aaronjmars3e7b61efd0d9
diff --git a/src/viewer/server.ts b/src/viewer/server.tsindex 533d4bb4..d488c8c7 100644--- a/src/viewer/server.ts+++ b/src/viewer/server.ts@@ -13,6 +13,55 @@ const ALLOWED_ORIGINS = (.split(",").map((o) => o.trim());+// Hosts the viewer will accept in the Host header. Restricting this is the+// defence against DNS rebinding: a browser visiting `attacker.com` whose+// authoritative DNS rebinds to 127.0.0.1 hits the viewer's listening socket+// directly, the Origin header reads `http://attacker.com` (same-origin from+// the browser's perspective on a same-port attacker page, so no preflight+// fires), and the request body is whatever the page wants. The viewer+// proxies it to the local REST API with the AGENTMEMORY_SECRET bearer+// attached, so the response stream is fully privileged. Rejecting any Host+// not in this allowlist closes that path before the proxy runs.+//+// Explicit override via VIEWER_ALLOWED_HOSTS for the rare case of a+// reverse-proxy in front of the viewer; defaults are computed from the+// listen port at server-create time.+const ALLOWED_HOSTS_OVERRIDE = (process.env.VIEWER_ALLOWED_HOSTS || "")+ .split(",")+ .map((h) => h.trim().toLowerCase())+ .filter(Boolean);++export function buildAllowedHosts(+ origins: string[],+ listenPort: number,+): Set<string> {+ const hosts = new Set<string>();+ for (const o of origins) {+ try {+ const parsed = new URL(o);+ if (parsed.host) hosts.add(parsed.host.toLowerCase());+ } catch {+ // Skip invalid origin entries — the existing CORS path already+ // tolerates them by simply not matching; mirror that here.+ }+ }+ hosts.add(`localhost:${listenPort}`);+ hosts.add(`127.0.0.1:${listenPort}`);+ hosts.add(`[::1]:${listenPort}`);+ for (const h of ALLOWED_HOSTS_OVERRIDE) hosts.add(h);+ return hosts;+}++export function isHostAllowed(+ headerHost: string | string[] | undefined,+ allowed: Set<string>,+): boolean {+ if (typeof headerHost !== "string") return false;+ const lower = headerHost.toLowerCase().trim();+ if (!lower) return false;+ return allowed.has(lower);+}+function corsHeaders(req: IncomingMessage): Record<string, string> {const origin = req.headers.origin || "";const allowed = ALLOWED_ORIGINS.includes(origin)@@ -69,8 +118,26 @@ export function startViewerServer(): Server {const resolvedRestPort = restPort ?? port - 2;const requestedPort = port;+ // Computed lazily on first request — `port` may be 0 here (OS-assigned)+ // or the EADDRINUSE retry loop below may bump us to a different port,+ // so we read the actual bound port from server.address() on first hit.+ let allowedHosts: Set<string> | null = null;const server = createServer(async (req, res) => {+ if (!allowedHosts) {+ const addr = server.address();+ const actualPort =+ addr && typeof addr === "object" && "port" in addr+ ? (addr.port as number)+ : port;+ allowedHosts = buildAllowedHosts(ALLOWED_ORIGINS, actualPort);+ }+ if (!isHostAllowed(req.headers.host, allowedHosts)) {+ res.writeHead(403, { "Content-Type": "text/plain" });+ res.end("forbidden host");+ return;+ }+const raw = req.url || "/";const qIdx = raw.indexOf("?");const pathname = qIdx >= 0 ? raw.slice(0, qIdx) : raw;diff --git a/test/viewer-security.test.ts b/test/viewer-security.test.tsindex fa0ac4bc..1f222227 100644--- a/test/viewer-security.test.ts+++ b/test/viewer-security.test.ts@@ -1,5 +1,12 @@-import { describe, it, expect } from "vitest";+import { describe, it, expect, afterAll } from "vitest";+import type { AddressInfo } from "node:net";+import { request as httpRequest } from "node:http";import { renderViewerDocument } from "../src/viewer/document.js";+import {+ buildAllowedHosts,+ isHostAllowed,+ startViewerServer,+} from "../src/viewer/server.js";describe("viewer document security", () => {it("serves a nonce-backed CSP without unsafe-inline script execution", () => {@@ -24,3 +31,156 @@ describe("viewer document security", () => {expect(rendered.html).not.toContain("onmouseout=");});});++describe("viewer host allowlist (DNS rebinding defence)", () => {+ const DEFAULT_ORIGINS = [+ "http://localhost:3111",+ "http://localhost:3113",+ "http://127.0.0.1:3111",+ "http://127.0.0.1:3113",+ ];++ it("accepts loopback host:port combinations the viewer is reachable at", () => {+ const allowed = buildAllowedHosts(DEFAULT_ORIGINS, 3113);+ expect(isHostAllowed("localhost:3113", allowed)).toBe(true);+ expect(isHostAllowed("127.0.0.1:3113", allowed)).toBe(true);+ expect(isHostAllowed("[::1]:3113", allowed)).toBe(true);+ });++ it("includes the rest-port host so the same origin list works for the REST server", () => {+ const allowed = buildAllowedHosts(DEFAULT_ORIGINS, 3113);+ expect(isHostAllowed("localhost:3111", allowed)).toBe(true);+ expect(isHostAllowed("127.0.0.1:3111", allowed)).toBe(true);+ });++ it("rejects rebound attacker hostnames pointing at loopback", () => {+ const allowed = buildAllowedHosts(DEFAULT_ORIGINS, 3113);+ // Classic DNS-rebinding payload: attacker domain on the viewer port.+ expect(isHostAllowed("attacker.com:3113", allowed)).toBe(false);+ expect(isHostAllowed("evil.example:3113", allowed)).toBe(false);+ // 0.0.0.0 is a routable loopback alias on Linux but not what the+ // viewer prints; reject so an attacker can't substitute it.+ expect(isHostAllowed("0.0.0.0:3113", allowed)).toBe(false);+ });++ it("rejects bare loopback Host headers without the listening port", () => {+ const allowed = buildAllowedHosts(DEFAULT_ORIGINS, 3113);+ // Curl-style `Host: localhost` (no port) does NOT match `localhost:3113`.+ expect(isHostAllowed("localhost", allowed)).toBe(false);+ expect(isHostAllowed("127.0.0.1", allowed)).toBe(false);+ });++ it("rejects missing, empty, or non-string Host headers", () => {+ const allowed = buildAllowedHosts(DEFAULT_ORIGINS, 3113);+ expect(isHostAllowed(undefined, allowed)).toBe(false);+ expect(isHostAllowed("", allowed)).toBe(false);+ expect(isHostAllowed(" ", allowed)).toBe(false);+ // Node sets `host` to a string array only in very unusual setups;+ // treat anything non-string as forbidden.+ expect(isHostAllowed(["localhost:3113"] as unknown as string, allowed))+ .toBe(false);+ });++ it("is case-insensitive on hostname per RFC 3986 §3.2.2", () => {+ const allowed = buildAllowedHosts(DEFAULT_ORIGINS, 3113);+ expect(isHostAllowed("LOCALHOST:3113", allowed)).toBe(true);+ expect(isHostAllowed("LocalHost:3113", allowed)).toBe(true);+ });++ it("honours operator-supplied VIEWER_ALLOWED_ORIGINS on the host check", () => {+ const custom = buildAllowedHosts(+ ["http://memory.internal:8080", "http://localhost:3113"],+ 3113,+ );+ expect(isHostAllowed("memory.internal:8080", custom)).toBe(true);+ expect(isHostAllowed("memory.internal", custom)).toBe(false);+ expect(isHostAllowed("attacker.com:3113", custom)).toBe(false);+ });++ it("ignores malformed origin entries instead of throwing", () => {+ const allowed = buildAllowedHosts(+ ["not-a-url", "", "http://localhost:3113"],+ 3113,+ );+ expect(isHostAllowed("localhost:3113", allowed)).toBe(true);+ });+});++describe("viewer request handler DNS rebinding defence (e2e)", () => {+ const cleanups: Array<() => Promise<void>> = [];+ afterAll(async () => {+ for (const c of cleanups) await c();+ });++ async function spinUpViewer(): Promise<{ port: number }> {+ // Start on port 0 so the OS assigns a free port; passing a real port+ // exercises buildAllowedHosts() with the live listen value.+ const server = startViewerServer(0, {}, {}, undefined, 0);+ await new Promise<void>((resolve) => server.once("listening", () => resolve()));+ const addr = server.address() as AddressInfo;+ cleanups.push(+ () => new Promise<void>((resolve) => server.close(() => resolve())),+ );+ return { port: addr.port };+ }++ // Use node:http directly — the global `fetch` (undici) silently+ // overrides the Host header to the URL authority, so we cannot use it+ // to simulate a DNS-rebinding payload that lands on 127.0.0.1 while+ // carrying `Host: attacker.com`.+ function request(+ port: number,+ hostHeader: string,+ pathname = "/agentmemory/livez",+ ): Promise<{ status: number; body: string }> {+ return new Promise((resolve, reject) => {+ const req = httpRequest(+ {+ host: "127.0.0.1",+ port,+ path: pathname,+ method: "GET",+ headers: { Host: hostHeader },+ },+ (res) => {+ let body = "";+ res.on("data", (chunk: Buffer) => {+ body += chunk.toString();+ });+ res.on("end", () => {+ resolve({ status: res.statusCode ?? 0, body });+ });+ },+ );+ req.on("error", reject);+ req.end();+ });+ }++ it("returns 403 on an attacker-controlled Host header (DNS rebinding payload)", async () => {+ const { port } = await spinUpViewer();+ const res = await request(port, `attacker.com:${port}`);+ expect(res.status).toBe(403);+ expect(res.body).toContain("forbidden host");+ });++ it("returns 403 even on the viewer landing page when Host is not loopback", async () => {+ const { port } = await spinUpViewer();+ const res = await request(port, `evil.example:${port}`, "/");+ expect(res.status).toBe(403);+ expect(res.body).toContain("forbidden host");+ });++ it("accepts loopback Host headers and serves the viewer HTML", async () => {+ const { port } = await spinUpViewer();+ const res = await request(port, `localhost:${port}`, "/");+ // 200 with the viewer HTML when the bundled template is resolvable,+ // or 404 when running from source without `npm run build` having+ // populated dist/viewer/. Either way it's NOT 403 — the host gate+ // passed. The CSP nonce assertion below is the load-bearing check.+ expect(res.status === 200 || res.status === 404).toBe(true);+ if (res.status === 200) {+ expect(res.body).toContain("agentmemory viewer");+ }+ });+});