diff --git a/README.md b/README.md index e12cba755a..13d189f711 100644 --- a/README.md +++ b/README.md @@ -669,7 +669,9 @@ 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. + +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 diff --git a/plugin/scripts/_capture.mjs b/plugin/scripts/_capture.mjs index 5e1a91f57a..c65c9afe9d 100644 --- a/plugin/scripts/_capture.mjs +++ b/plugin/scripts/_capture.mjs @@ -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 f4f8798979..0281bae3a5 100644 --- a/plugin/scripts/plugin-bridge.mjs +++ b/plugin/scripts/plugin-bridge.mjs @@ -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 e44345b36a..13c7f1d487 100755 --- a/plugin/scripts/pre-compact.mjs +++ b/plugin/scripts/pre-compact.mjs @@ -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 0ec92b7e80..00062a8f9d 100755 --- a/plugin/scripts/pre-tool-use.mjs +++ b/plugin/scripts/pre-tool-use.mjs @@ -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 babd82e795..16903a5b6a 100755 --- a/plugin/scripts/session-start.mjs +++ b/plugin/scripts/session-start.mjs @@ -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 b2b343afb0..a4ade0aa70 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, 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; @@ -73,10 +73,14 @@ 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"); } + const url = pinLoopbackUrl(value); + if (!secretTransportAllowed(url)) { + throw new Error("AGENTMEMORY_URL must use HTTPS unless it is a loopback address"); + } + return url.replace(/\/+$/, ""); } function authHeader(url: string): Record { 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 7761e12d75..f5a945b3a8 100644 --- a/test/rest-proxy-credentials.test.ts +++ b/test/rest-proxy-credentials.test.ts @@ -31,6 +31,95 @@ 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://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.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("{}")); + 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..1068a1f933 100644 --- a/test/secret-store.test.ts +++ b/test/secret-store.test.ts @@ -237,10 +237,13 @@ 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(""); 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); }); it("returns nothing when no secret has been generated yet", () => { @@ -295,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);