From a85b7c0723aab2525825ba405c673a6357926e90 Mon Sep 17 00:00:00 2001 From: dimitri Date: Fri, 13 Nov 2026 10:35:06 -0600 Subject: [PATCH 1/2] fix(mcp): require HTTPS for remote proxy endpoints Signed-off-by: dimitri --- README.md | 2 +- plugin/scripts/_capture.mjs | 2 +- plugin/scripts/plugin-bridge.mjs | 2 +- plugin/scripts/pre-compact.mjs | 2 +- plugin/scripts/pre-tool-use.mjs | 2 +- plugin/scripts/session-start.mjs | 2 +- src/mcp/rest-proxy.ts | 7 ++- src/secret-store.ts | 2 +- test/rest-proxy-credentials.test.ts | 72 +++++++++++++++++++++++++++++ test/secret-store.test.ts | 2 + 10 files changed, 86 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index e12cba755a..90959ed969 100644 --- a/README.md +++ b/README.md @@ -669,7 +669,7 @@ The agentmemory entry is the **same MCP server block** across every host that us | **Aider** | n/a | Use the [authenticated REST examples](#validate-a-fresh-install-and-restart-persistence) to save and search memory from scripts. | | **Supported agents** | Skills only | `npx skills add rohitg00/agentmemory`; choose the skills and agents to install to. | -**Sandboxed MCP clients** (Flatpak / Snap / restrictive containers) that can't reach the host's `localhost`: also set `"AGENTMEMORY_FORCE_PROXY": "1"` in the `env` block, and point `AGENTMEMORY_URL` at a route the sandbox can actually reach (e.g. your LAN IP). +**Sandboxed MCP clients** (Flatpak / Snap / restrictive containers) that can't reach the host's `localhost`: also set `"AGENTMEMORY_FORCE_PROXY": "1"` in the `env` block, and point `AGENTMEMORY_URL` at a route the sandbox can reach. Non-loopback addresses, including LAN IPs, require HTTPS. Alternatively, run a tunnel inside the sandbox and use its loopback address. ### Programmatic access diff --git a/plugin/scripts/_capture.mjs b/plugin/scripts/_capture.mjs index 5e1a91f57a..5ef297f90e 100644 --- a/plugin/scripts/_capture.mjs +++ b/plugin/scripts/_capture.mjs @@ -80,7 +80,7 @@ function isLoopbackUrl(url) { return false; } const bare = hostname.replace(/^\[|\]$/g, ""); - return bare === "localhost" || bare === "::1" || /^127(?:\.\d{1,3}){3}$/.test(bare); + return bare === "localhost" || bare === "localhost." || bare === "::1" || /^127(?:\.\d{1,3}){3}$/.test(bare); } function resolveClientSecret(baseUrl, env = process.env) { const fromEnv = usable(env[SECRET_KEY]); diff --git a/plugin/scripts/plugin-bridge.mjs b/plugin/scripts/plugin-bridge.mjs index f4f8798979..5393cfa602 100644 --- a/plugin/scripts/plugin-bridge.mjs +++ b/plugin/scripts/plugin-bridge.mjs @@ -82,7 +82,7 @@ function isLoopbackUrl(url) { return false; } const bare = hostname.replace(/^\[|\]$/g, ""); - return bare === "localhost" || bare === "::1" || /^127(?:\.\d{1,3}){3}$/.test(bare); + return bare === "localhost" || bare === "localhost." || bare === "::1" || /^127(?:\.\d{1,3}){3}$/.test(bare); } function resolveClientSecret(baseUrl, env = process.env) { const fromEnv = usable(env[SECRET_KEY]); diff --git a/plugin/scripts/pre-compact.mjs b/plugin/scripts/pre-compact.mjs index e44345b36a..0bd1621e7d 100755 --- a/plugin/scripts/pre-compact.mjs +++ b/plugin/scripts/pre-compact.mjs @@ -89,7 +89,7 @@ function isLoopbackUrl(url) { return false; } const bare = hostname.replace(/^\[|\]$/g, ""); - return bare === "localhost" || bare === "::1" || /^127(?:\.\d{1,3}){3}$/.test(bare); + return bare === "localhost" || bare === "localhost." || bare === "::1" || /^127(?:\.\d{1,3}){3}$/.test(bare); } function resolveClientSecret(baseUrl, env = process.env) { const fromEnv = usable(env[SECRET_KEY]); diff --git a/plugin/scripts/pre-tool-use.mjs b/plugin/scripts/pre-tool-use.mjs index 0ec92b7e80..832f848526 100755 --- a/plugin/scripts/pre-tool-use.mjs +++ b/plugin/scripts/pre-tool-use.mjs @@ -80,7 +80,7 @@ function isLoopbackUrl(url) { return false; } const bare = hostname.replace(/^\[|\]$/g, ""); - return bare === "localhost" || bare === "::1" || /^127(?:\.\d{1,3}){3}$/.test(bare); + return bare === "localhost" || bare === "localhost." || bare === "::1" || /^127(?:\.\d{1,3}){3}$/.test(bare); } function resolveClientSecret(baseUrl, env = process.env) { const fromEnv = usable(env[SECRET_KEY]); diff --git a/plugin/scripts/session-start.mjs b/plugin/scripts/session-start.mjs index babd82e795..1b4a05baeb 100755 --- a/plugin/scripts/session-start.mjs +++ b/plugin/scripts/session-start.mjs @@ -80,7 +80,7 @@ function isLoopbackUrl(url) { return false; } const bare = hostname.replace(/^\[|\]$/g, ""); - return bare === "localhost" || bare === "::1" || /^127(?:\.\d{1,3}){3}$/.test(bare); + return bare === "localhost" || bare === "localhost." || bare === "::1" || /^127(?:\.\d{1,3}){3}$/.test(bare); } function resolveClientSecret(baseUrl, env = process.env) { const fromEnv = usable(env[SECRET_KEY]); diff --git a/src/mcp/rest-proxy.ts b/src/mcp/rest-proxy.ts index b2b343afb0..92aef8c6eb 100644 --- a/src/mcp/rest-proxy.ts +++ b/src/mcp/rest-proxy.ts @@ -1,4 +1,4 @@ -import { hookSetting, resolveSettingSecret } from "../hooks/_endpoint.js"; +import { hookSetting, resolveSettingSecret, secretTransportAllowed } from "../hooks/_endpoint.js"; import { readEnvFileValue } from "../secret-store.js"; const DEFAULT_URL = "http://localhost:3111"; const DEFAULT_HEALTH_PROBE_TIMEOUT_MS = 2_000; @@ -73,10 +73,13 @@ function baseUrl(): string { parsed.username || parsed.password || /[?#\s]/.test(value)) { throw new Error(); } - return value.replace(/\/+$/, ""); } catch { throw new Error("AGENTMEMORY_URL must be an HTTP(S) URL without credentials, query, or fragment"); } + if (!secretTransportAllowed(value)) { + throw new Error("AGENTMEMORY_URL must use HTTPS unless it is a loopback address"); + } + return value.replace(/\/+$/, ""); } function authHeader(url: string): Record { diff --git a/src/secret-store.ts b/src/secret-store.ts index 915bb0b0c7..91853484fc 100644 --- a/src/secret-store.ts +++ b/src/secret-store.ts @@ -102,7 +102,7 @@ export function isLoopbackUrl(url: string): boolean { return false; } const bare = hostname.replace(/^\[|\]$/g, ""); - return bare === "localhost" || bare === "::1" || /^127(?:\.\d{1,3}){3}$/.test(bare); + return bare === "localhost" || bare === "localhost." || bare === "::1" || /^127(?:\.\d{1,3}){3}$/.test(bare); } export function resolveClientSecret( diff --git a/test/rest-proxy-credentials.test.ts b/test/rest-proxy-credentials.test.ts index 7761e12d75..5bf50f7a14 100644 --- a/test/rest-proxy-credentials.test.ts +++ b/test/rest-proxy-credentials.test.ts @@ -31,6 +31,78 @@ describe("MCP proxy credential origins", () => { rmSync(home, { recursive: true, force: true }); }); + it.each([ + "http://memory.example.invalid", + "http://192.0.2.10:3111", + "http://[2001:db8::10]:3111", + "http://localhost.example.invalid:3111", + ].flatMap((url) => [false, true].map((forced) => [url, forced] as const)))( + "rejects insecure remote transport %s before sending credentials (forced: %s)", + async (url, forced) => { + vi.stubEnv("AGENTMEMORY_URL", url); + vi.stubEnv("AGENTMEMORY_SECRET", "synthetic-remote-secret"); + vi.stubEnv("AGENTMEMORY_FORCE_PROXY", forced ? "1" : ""); + const fetchMock = vi.fn(async () => new Response("{}")); + vi.stubGlobal("fetch", fetchMock); + const probe = vi.fn(async () => ({ ok: true })); + setLivezProbe(probe); + + await expect(resolveHandle()).rejects.toThrow(/HTTPS.*loopback/i); + expect(probe).not.toHaveBeenCalled(); + expect(fetchMock).not.toHaveBeenCalled(); + }, + ); + + it("rejects insecure remote transport even without a secret", async () => { + vi.stubEnv("AGENTMEMORY_URL", "http://memory.example.invalid"); + const fetchMock = vi.fn(async () => new Response("{}")); + vi.stubGlobal("fetch", fetchMock); + + await expect(resolveHandle()).rejects.toThrow(/HTTPS.*loopback/i); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it.each([ + remote, + "https://memory.example.invalid/prefix", + "http://localhost:3111", + "http://localhost.:3111", + "http://127.0.0.2:3111", + "http://[::1]:3111", + ].flatMap((url) => [false, true].map((forced) => [url, forced] as const)))( + "preserves credentials on secure or loopback transport %s (forced: %s)", + async (url, forced) => { + vi.stubEnv("AGENTMEMORY_URL", url); + vi.stubEnv("AGENTMEMORY_SECRET", "synthetic-remote-secret"); + vi.stubEnv("AGENTMEMORY_FORCE_PROXY", forced ? "1" : ""); + const calls: Array<{ url: string; auth: string | null }> = []; + vi.stubGlobal("fetch", vi.fn(async (target: string, init?: RequestInit) => { + calls.push({ url: target, auth: new Headers(init?.headers).get("authorization") }); + return new Response("{}"); + })); + + const handle = await resolveHandle(); + if (handle.mode !== "proxy") throw new Error("expected proxy mode"); + await handle.call("/agentmemory/sessions"); + const expected = [{ url: `${url}/agentmemory/sessions`, auth: "Bearer synthetic-remote-secret" }]; + if (!forced) expected.unshift({ url: `${url}/agentmemory/livez`, auth: "Bearer synthetic-remote-secret" }); + expect(calls).toEqual(expected); + }, + ); + + it("rejects insecure reconfiguration before reusing or calling a cached handle", async () => { + vi.stubEnv("AGENTMEMORY_SECRET", "synthetic-remote-secret"); + const fetchMock = vi.fn(async () => new Response("{}")); + vi.stubGlobal("fetch", fetchMock); + const handle = await resolveHandle(); + if (handle.mode !== "proxy") throw new Error("expected proxy mode"); + vi.stubEnv("AGENTMEMORY_URL", "http://memory.example.invalid"); + + await expect(resolveHandle()).rejects.toThrow(/HTTPS.*loopback/i); + await expect(handle.call("/agentmemory/sessions")).rejects.toThrow(/HTTPS.*loopback/i); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + it("refuses a stale handle before attaching credentials for a changed endpoint", async () => { const fetchMock = vi.fn(async (_url: string, _init?: RequestInit) => new Response("{}")); vi.stubGlobal("fetch", fetchMock); diff --git a/test/secret-store.test.ts b/test/secret-store.test.ts index ba560fb285..be434bd3fc 100644 --- a/test/secret-store.test.ts +++ b/test/secret-store.test.ts @@ -237,10 +237,12 @@ describe("stored API secret", () => { it("only hands the stored secret to loopback servers", () => { const { secret } = ensureServerSecret(); expect(resolveClientSecret("http://localhost:3111")).toBe(secret); + expect(resolveClientSecret("http://localhost.:3111")).toBe(secret); expect(resolveClientSecret("http://[::1]:3111")).toBe(secret); expect(resolveClientSecret("https://memory.example.com")).toBe(""); expect(isLoopbackUrl("http://127.0.0.2:3111")).toBe(true); expect(isLoopbackUrl("http://localhost.example.com")).toBe(false); + expect(isLoopbackUrl("http://localhost..:3111")).toBe(false); }); it("returns nothing when no secret has been generated yet", () => { From 3cf6f81b54cf07c37a12c9c1aa6fbf18d18486f7 Mon Sep 17 00:00:00 2001 From: dimitri Date: Mon, 16 Nov 2026 12:43:09 -0600 Subject: [PATCH 2/2] fix(mcp): pin localhost alias to loopback Signed-off-by: dimitri --- README.md | 2 ++ plugin/scripts/_capture.mjs | 14 ++++++++++++-- plugin/scripts/plugin-bridge.mjs | 13 ++++++++++++- plugin/scripts/pre-compact.mjs | 14 ++++++++++++-- plugin/scripts/pre-tool-use.mjs | 14 ++++++++++++-- plugin/scripts/session-start.mjs | 14 ++++++++++++-- src/hooks/_endpoint.ts | 13 ++++++++++++- src/mcp/plugin-bridge.ts | 3 ++- src/mcp/rest-proxy.ts | 7 ++++--- src/secret-store.ts | 2 +- test/directory-review-privacy.test.ts | 12 ++++++++++++ test/plugin-bridge-secret.test.ts | 8 ++++++++ test/rest-proxy-credentials.test.ts | 19 ++++++++++++++++++- test/secret-store.test.ts | 7 ++++--- 14 files changed, 123 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 90959ed969..13d189f711 100644 --- a/README.md +++ b/README.md @@ -671,6 +671,8 @@ The agentmemory entry is the **same MCP server block** across every host that us **Sandboxed MCP clients** (Flatpak / Snap / restrictive containers) that can't reach the host's `localhost`: also set `"AGENTMEMORY_FORCE_PROXY": "1"` in the `env` block, and point `AGENTMEMORY_URL` at a route the sandbox can reach. Non-loopback addresses, including LAN IPs, require HTTPS. Alternatively, run a tunnel inside the sandbox and use its loopback address. +The `localhost.` alias is pinned to `127.0.0.1` before MCP and hook requests. Use `[::1]` explicitly for a daemon bound only to IPv6 loopback. + ### Programmatic access Use the [REST API](#api) from any language or the [MCP tools](#mcp-server) from an agent. REST requests use JSON and bearer authentication; see the [save and search example](#validate-a-fresh-install-and-restart-persistence). diff --git a/plugin/scripts/_capture.mjs b/plugin/scripts/_capture.mjs index 5ef297f90e..c65c9afe9d 100644 --- a/plugin/scripts/_capture.mjs +++ b/plugin/scripts/_capture.mjs @@ -80,7 +80,7 @@ function isLoopbackUrl(url) { return false; } const bare = hostname.replace(/^\[|\]$/g, ""); - return bare === "localhost" || bare === "localhost." || bare === "::1" || /^127(?:\.\d{1,3}){3}$/.test(bare); + return bare === "localhost" || bare === "::1" || /^127(?:\.\d{1,3}){3}$/.test(bare); } function resolveClientSecret(baseUrl, env = process.env) { const fromEnv = usable(env[SECRET_KEY]); @@ -122,8 +122,18 @@ function secretTransportAllowed(url) { return false; } } +function pinLoopbackUrl(value) { + try { + const url = new URL(value); + if (url.hostname === "localhost.") { + url.hostname = "127.0.0.1"; + return url.href.replace(/\/$/, ""); + } + } catch {} + return value; +} function resolveHookEndpoint(env = process.env) { - const url = hookSetting("AGENTMEMORY_URL", env) || DEFAULT_URL; + const url = pinLoopbackUrl(hookSetting("AGENTMEMORY_URL", env) || DEFAULT_URL); const secret = resolveSettingSecret(url, env); const blocked = !secretTransportAllowed(url); return { diff --git a/plugin/scripts/plugin-bridge.mjs b/plugin/scripts/plugin-bridge.mjs index 5393cfa602..0281bae3a5 100644 --- a/plugin/scripts/plugin-bridge.mjs +++ b/plugin/scripts/plugin-bridge.mjs @@ -82,7 +82,7 @@ function isLoopbackUrl(url) { return false; } const bare = hostname.replace(/^\[|\]$/g, ""); - return bare === "localhost" || bare === "localhost." || bare === "::1" || /^127(?:\.\d{1,3}){3}$/.test(bare); + return bare === "localhost" || bare === "::1" || /^127(?:\.\d{1,3}){3}$/.test(bare); } function resolveClientSecret(baseUrl, env = process.env) { const fromEnv = usable(env[SECRET_KEY]); @@ -116,6 +116,16 @@ function resolveSettingSecret(url, env = process.env) { else secretEnv["AGENTMEMORY_SECRET"] = explicit; return resolveClientSecret(url, secretEnv); } +function pinLoopbackUrl(value) { + try { + const url = new URL(value); + if (url.hostname === "localhost.") { + url.hostname = "127.0.0.1"; + return url.href.replace(/\/$/, ""); + } + } catch {} + return value; +} //#endregion //#region src/mcp/rest-proxy.ts const DEFAULT_CALL_TIMEOUT_MS = 19e4; @@ -331,6 +341,7 @@ const SETUP = "Start Agent Memory, check `agentmemory status`, and verify AGENTM function createPluginBridge() { const base = new URL(resolveEnvOrEmpty("AGENTMEMORY_URL") || "http://localhost:3111"); if (!["http:", "https:"].includes(base.protocol) || base.username || base.password || base.search || base.hash) throw new Error("AGENTMEMORY_URL must be an HTTP(S) base URL without credentials, query, or fragment."); + base.href = pinLoopbackUrl(base.href); const loopback = [ "localhost", "localhost.", diff --git a/plugin/scripts/pre-compact.mjs b/plugin/scripts/pre-compact.mjs index 0bd1621e7d..13c7f1d487 100755 --- a/plugin/scripts/pre-compact.mjs +++ b/plugin/scripts/pre-compact.mjs @@ -89,7 +89,7 @@ function isLoopbackUrl(url) { return false; } const bare = hostname.replace(/^\[|\]$/g, ""); - return bare === "localhost" || bare === "localhost." || bare === "::1" || /^127(?:\.\d{1,3}){3}$/.test(bare); + return bare === "localhost" || bare === "::1" || /^127(?:\.\d{1,3}){3}$/.test(bare); } function resolveClientSecret(baseUrl, env = process.env) { const fromEnv = usable(env[SECRET_KEY]); @@ -131,8 +131,18 @@ function secretTransportAllowed(url) { return false; } } +function pinLoopbackUrl(value) { + try { + const url = new URL(value); + if (url.hostname === "localhost.") { + url.hostname = "127.0.0.1"; + return url.href.replace(/\/$/, ""); + } + } catch {} + return value; +} function resolveHookEndpoint(env = process.env) { - const url = hookSetting("AGENTMEMORY_URL", env) || DEFAULT_URL; + const url = pinLoopbackUrl(hookSetting("AGENTMEMORY_URL", env) || DEFAULT_URL); const secret = resolveSettingSecret(url, env); const blocked = !secretTransportAllowed(url); return { diff --git a/plugin/scripts/pre-tool-use.mjs b/plugin/scripts/pre-tool-use.mjs index 832f848526..00062a8f9d 100755 --- a/plugin/scripts/pre-tool-use.mjs +++ b/plugin/scripts/pre-tool-use.mjs @@ -80,7 +80,7 @@ function isLoopbackUrl(url) { return false; } const bare = hostname.replace(/^\[|\]$/g, ""); - return bare === "localhost" || bare === "localhost." || bare === "::1" || /^127(?:\.\d{1,3}){3}$/.test(bare); + return bare === "localhost" || bare === "::1" || /^127(?:\.\d{1,3}){3}$/.test(bare); } function resolveClientSecret(baseUrl, env = process.env) { const fromEnv = usable(env[SECRET_KEY]); @@ -122,8 +122,18 @@ function secretTransportAllowed(url) { return false; } } +function pinLoopbackUrl(value) { + try { + const url = new URL(value); + if (url.hostname === "localhost.") { + url.hostname = "127.0.0.1"; + return url.href.replace(/\/$/, ""); + } + } catch {} + return value; +} function resolveHookEndpoint(env = process.env) { - const url = hookSetting("AGENTMEMORY_URL", env) || DEFAULT_URL; + const url = pinLoopbackUrl(hookSetting("AGENTMEMORY_URL", env) || DEFAULT_URL); const secret = resolveSettingSecret(url, env); const blocked = !secretTransportAllowed(url); return { diff --git a/plugin/scripts/session-start.mjs b/plugin/scripts/session-start.mjs index 1b4a05baeb..16903a5b6a 100755 --- a/plugin/scripts/session-start.mjs +++ b/plugin/scripts/session-start.mjs @@ -80,7 +80,7 @@ function isLoopbackUrl(url) { return false; } const bare = hostname.replace(/^\[|\]$/g, ""); - return bare === "localhost" || bare === "localhost." || bare === "::1" || /^127(?:\.\d{1,3}){3}$/.test(bare); + return bare === "localhost" || bare === "::1" || /^127(?:\.\d{1,3}){3}$/.test(bare); } function resolveClientSecret(baseUrl, env = process.env) { const fromEnv = usable(env[SECRET_KEY]); @@ -122,8 +122,18 @@ function secretTransportAllowed(url) { return false; } } +function pinLoopbackUrl(value) { + try { + const url = new URL(value); + if (url.hostname === "localhost.") { + url.hostname = "127.0.0.1"; + return url.href.replace(/\/$/, ""); + } + } catch {} + return value; +} function resolveHookEndpoint(env = process.env) { - const url = hookSetting("AGENTMEMORY_URL", env) || DEFAULT_URL; + const url = pinLoopbackUrl(hookSetting("AGENTMEMORY_URL", env) || DEFAULT_URL); const secret = resolveSettingSecret(url, env); const blocked = !secretTransportAllowed(url); return { diff --git a/src/hooks/_endpoint.ts b/src/hooks/_endpoint.ts index 64ec98f288..e9257c07b0 100644 --- a/src/hooks/_endpoint.ts +++ b/src/hooks/_endpoint.ts @@ -42,8 +42,19 @@ export function secretTransportAllowed(url: string): boolean { } } +export function pinLoopbackUrl(value: string): string { + try { + const url = new URL(value); + if (url.hostname === "localhost.") { + url.hostname = "127.0.0.1"; + return url.href.replace(/\/$/, ""); + } + } catch {} + return value; +} + export function resolveHookEndpoint(env: NodeJS.ProcessEnv = process.env): HookEndpoint { - const url = hookSetting("AGENTMEMORY_URL", env) || DEFAULT_URL; + const url = pinLoopbackUrl(hookSetting("AGENTMEMORY_URL", env) || DEFAULT_URL); const secret = resolveSettingSecret(url, env); const blocked = !secretTransportAllowed(url); return { url, secret: blocked ? "" : secret, blocked }; diff --git a/src/mcp/plugin-bridge.ts b/src/mcp/plugin-bridge.ts index 593e6f9e2a..f37e764d7a 100644 --- a/src/mcp/plugin-bridge.ts +++ b/src/mcp/plugin-bridge.ts @@ -1,7 +1,7 @@ import { pathToFileURL } from "node:url"; import { realpathSync } from "node:fs"; import { VERSION } from "../version.js"; -import { resolveSettingSecret } from "../hooks/_endpoint.js"; +import { pinLoopbackUrl, resolveSettingSecret } from "../hooks/_endpoint.js"; import { callTimeoutMs, resolveEnvOrEmpty } from "./rest-proxy.js"; import { createStdioTransport, JsonRpcError, type RequestHandler } from "./transport.js"; @@ -14,6 +14,7 @@ export function createPluginBridge(): RequestHandler { if (!["http:", "https:"].includes(base.protocol) || base.username || base.password || base.search || base.hash) { throw new Error("AGENTMEMORY_URL must be an HTTP(S) base URL without credentials, query, or fragment."); } + base.href = pinLoopbackUrl(base.href); const loopback = ["localhost", "localhost.", "[::1]"].includes(base.hostname) || /^127(?:\.\d{1,3}){3}$/.test(base.hostname); function resolveSecret(): string { diff --git a/src/mcp/rest-proxy.ts b/src/mcp/rest-proxy.ts index 92aef8c6eb..a4ade0aa70 100644 --- a/src/mcp/rest-proxy.ts +++ b/src/mcp/rest-proxy.ts @@ -1,4 +1,4 @@ -import { hookSetting, resolveSettingSecret, secretTransportAllowed } from "../hooks/_endpoint.js"; +import { hookSetting, pinLoopbackUrl, resolveSettingSecret, secretTransportAllowed } from "../hooks/_endpoint.js"; import { readEnvFileValue } from "../secret-store.js"; const DEFAULT_URL = "http://localhost:3111"; const DEFAULT_HEALTH_PROBE_TIMEOUT_MS = 2_000; @@ -76,10 +76,11 @@ function baseUrl(): string { } catch { throw new Error("AGENTMEMORY_URL must be an HTTP(S) URL without credentials, query, or fragment"); } - if (!secretTransportAllowed(value)) { + const url = pinLoopbackUrl(value); + if (!secretTransportAllowed(url)) { throw new Error("AGENTMEMORY_URL must use HTTPS unless it is a loopback address"); } - return value.replace(/\/+$/, ""); + return url.replace(/\/+$/, ""); } function authHeader(url: string): Record { diff --git a/src/secret-store.ts b/src/secret-store.ts index 91853484fc..915bb0b0c7 100644 --- a/src/secret-store.ts +++ b/src/secret-store.ts @@ -102,7 +102,7 @@ export function isLoopbackUrl(url: string): boolean { return false; } const bare = hostname.replace(/^\[|\]$/g, ""); - return bare === "localhost" || bare === "localhost." || bare === "::1" || /^127(?:\.\d{1,3}){3}$/.test(bare); + return bare === "localhost" || bare === "::1" || /^127(?:\.\d{1,3}){3}$/.test(bare); } export function resolveClientSecret( diff --git a/test/directory-review-privacy.test.ts b/test/directory-review-privacy.test.ts index 011d223344..853bbfa269 100644 --- a/test/directory-review-privacy.test.ts +++ b/test/directory-review-privacy.test.ts @@ -83,6 +83,18 @@ describe("embedding provider opt-in", () => { }); describe("hook token transport", () => { + it.each(["http", "https"])("pins localhost. to IPv4 loopback for %s hook requests", (protocol) => { + const endpoint = resolveHookEndpoint({ + AGENTMEMORY_URL: `${protocol}://LOCALHOST.:3111/prefix`, + AGENTMEMORY_SECRET: "synthetic-local-secret", + }); + expect(endpoint).toEqual({ + url: `${protocol}://127.0.0.1:3111/prefix`, + secret: "synthetic-local-secret", + blocked: false, + }); + }); + it("refuses to send a secret to a remote http URL", () => { const endpoint = resolveHookEndpoint({ AGENTMEMORY_URL: "http://memory.example.com", AGENTMEMORY_SECRET: "s3cret" }); expect(endpoint.blocked).toBe(true); diff --git a/test/plugin-bridge-secret.test.ts b/test/plugin-bridge-secret.test.ts index d398b1baec..aa55cf1aa3 100644 --- a/test/plugin-bridge-secret.test.ts +++ b/test/plugin-bridge-secret.test.ts @@ -33,6 +33,14 @@ function authorization() { } describe("plugin bridge uses the daemon's local credential resolution", () => { + it("pins localhost. to a literal loopback address before sending the local credential", async () => { + store("secret", "generated-test-secret\n"); + vi.stubEnv("AGENTMEMORY_URL", "http://LOCALHOST.:3111/prefix"); + await createPluginBridge()("tools/list", {}); + expect(requestedUrl()).toBe("http://127.0.0.1:3111/prefix/agentmemory/mcp/tools"); + expect(authorization()).toBe("Bearer generated-test-secret"); + }); + it("reads the generated credential without an MCP environment override", async () => { store("secret", "generated-test-secret\n"); await createPluginBridge()("tools/list", {}); diff --git a/test/rest-proxy-credentials.test.ts b/test/rest-proxy-credentials.test.ts index 5bf50f7a14..f5a945b3a8 100644 --- a/test/rest-proxy-credentials.test.ts +++ b/test/rest-proxy-credentials.test.ts @@ -66,7 +66,6 @@ describe("MCP proxy credential origins", () => { remote, "https://memory.example.invalid/prefix", "http://localhost:3111", - "http://localhost.:3111", "http://127.0.0.2:3111", "http://[::1]:3111", ].flatMap((url) => [false, true].map((forced) => [url, forced] as const)))( @@ -90,6 +89,24 @@ describe("MCP proxy credential origins", () => { }, ); + it.each([false, true])("pins localhost. probes and requests to a literal loopback address (forced: %s)", async (forced) => { + vi.stubEnv("AGENTMEMORY_URL", "http://LOCALHOST.:3111/prefix"); + vi.stubEnv("AGENTMEMORY_FORCE_PROXY", forced ? "1" : ""); + const calls: Array<{ url: string; auth: string | null }> = []; + vi.stubGlobal("fetch", vi.fn(async (url: string, init?: RequestInit) => { + calls.push({ url, auth: new Headers(init?.headers).get("authorization") }); + return new Response("{}"); + })); + + const handle = await resolveHandle(); + if (handle.mode !== "proxy") throw new Error("expected proxy mode"); + await handle.call("/agentmemory/sessions"); + expect(calls).toEqual([ + ...(forced ? [] : [{ url: "http://127.0.0.1:3111/prefix/agentmemory/livez", auth: "Bearer synthetic-local-secret" }]), + { url: "http://127.0.0.1:3111/prefix/agentmemory/sessions", auth: "Bearer synthetic-local-secret" }, + ]); + }); + it("rejects insecure reconfiguration before reusing or calling a cached handle", async () => { vi.stubEnv("AGENTMEMORY_SECRET", "synthetic-remote-secret"); const fetchMock = vi.fn(async () => new Response("{}")); diff --git a/test/secret-store.test.ts b/test/secret-store.test.ts index be434bd3fc..1068a1f933 100644 --- a/test/secret-store.test.ts +++ b/test/secret-store.test.ts @@ -237,11 +237,12 @@ describe("stored API secret", () => { it("only hands the stored secret to loopback servers", () => { const { secret } = ensureServerSecret(); expect(resolveClientSecret("http://localhost:3111")).toBe(secret); - expect(resolveClientSecret("http://localhost.:3111")).toBe(secret); + expect(resolveClientSecret("http://localhost.:3111")).toBe(""); expect(resolveClientSecret("http://[::1]:3111")).toBe(secret); expect(resolveClientSecret("https://memory.example.com")).toBe(""); expect(isLoopbackUrl("http://127.0.0.2:3111")).toBe(true); expect(isLoopbackUrl("http://localhost.example.com")).toBe(false); + expect(isLoopbackUrl("http://localhost.:3111")).toBe(false); expect(isLoopbackUrl("http://localhost..:3111")).toBe(false); }); @@ -297,14 +298,14 @@ describe("stored API secret", () => { }); } - it("send the stored secret without any client configuration", async () => { + it.each(["127.0.0.1", "localhost."])("sends the stored secret to %s without any client configuration", async (hostname) => { const { secret } = ensureServerSecret(); const port = (server.address() as AddressInfo).port; const env: NodeJS.ProcessEnv = { PATH: process.env.PATH, HOME: home, USERPROFILE: home, - AGENTMEMORY_URL: `http://127.0.0.1:${port}`, + AGENTMEMORY_URL: `http://${hostname}:${port}`, }; await runHook(join(process.cwd(), "plugin", "scripts", "session-start.mjs"), env); expect(received.length).toBeGreaterThan(0);