Skip to content

#1 Persistent memory for AI coding agents based on real-world benchmarks

fix(integrations): warn when bearer auth crosses plaintext HTTP to non-loopback (#315)

Matt Van Horn1a706ca2d6f3
diff --git a/.gitignore b/.gitignore
index 506de84c..9a9260b8 100644
--- a/.gitignore
+++ b/.gitignore
@@ -19,3 +19,4 @@ data/
package-lock.json
pnpm-lock.yaml
yarn.lock
+integrations/hermes/__pycache__/
diff --git a/integrations/hermes/README.md b/integrations/hermes/README.md
index 73ffc506..ba06c105 100644
--- a/integrations/hermes/README.md
+++ b/integrations/hermes/README.md
@@ -105,6 +105,7 @@ The plugin auto-detects the running server and hooks into the Hermes agent loop.
|---|---|---|
| `AGENTMEMORY_URL` | `http://localhost:3111` | agentmemory server URL |
| `AGENTMEMORY_SECRET` | (none) | Auth token for protected instances |
+| `AGENTMEMORY_REQUIRE_HTTPS` | (off) | When set to `1`, refuse to send the bearer token over plaintext HTTP to a non-loopback host. Sends only when `AGENTMEMORY_URL` is `https://...` or points at `localhost`/`127.0.0.1`/`::1`. With this off, the plugin warns once on stderr but still sends. |
The plugin reads `~/.agentmemory/.env` (or `$XDG_CONFIG_HOME/agentmemory/.env`) at import time and populates any missing values into the process environment via `os.environ.setdefault`. Anything you set in the shell takes precedence; the file is only used to fill gaps. This means `hermes memory status` reports the plugin as available even when the agentmemory service is launched by systemd or another process manager that loads `~/.agentmemory/.env` directly without exporting it to the Hermes CLI shell (#250).
diff --git a/integrations/hermes/__init__.py b/integrations/hermes/__init__.py
index fdffc17b..7f17d98a 100644
--- a/integrations/hermes/__init__.py
+++ b/integrations/hermes/__init__.py
@@ -11,10 +11,12 @@ from __future__ import annotations
import json
import os
+import sys
import threading
import time
from pathlib import Path
-from typing import Any
+from typing import Any, Callable
+from urllib.parse import urlparse
from urllib.request import Request, urlopen
from urllib.error import URLError
@@ -49,6 +51,8 @@ except ImportError:
DEFAULT_BASE_URL = "http://localhost:3111"
TIMEOUT = 5
+LOOPBACK_HOSTS = {"localhost", "127.0.0.1", "::1"}
+_plaintext_bearer_warned = False
# agentmemory's documented runtime config lives at ~/.agentmemory/.env.
# When agentmemory is launched as a systemd user service (or any other
@@ -92,17 +96,53 @@ _preload_agentmemory_dotenv()
def _validate_url(base: str) -> bool:
- from urllib.parse import urlparse
parsed = urlparse(base)
return parsed.scheme in ("http", "https")
+def _uses_plaintext_bearer_auth(base: str, secret: str = "") -> bool:
+ if not secret:
+ return False
+ parsed = urlparse(base)
+ return parsed.scheme == "http" and (parsed.hostname or "").lower() not in LOOPBACK_HOSTS
+
+
+def _plaintext_bearer_auth_message(base: str) -> str:
+ return f"agentmemory: AGENTMEMORY_SECRET is configured for plaintext HTTP to {base}. Bearer tokens and memory payloads can be observed on the network; use HTTPS or an SSH tunnel."
+
+
+def _warn_plaintext_bearer_auth(message: str) -> None:
+ print(message, file=sys.stderr)
+
+
+def _check_plaintext_bearer_guard(
+ base: str,
+ secret: str = "",
+ warn: Callable[[str], None] | None = None,
+) -> None:
+ global _plaintext_bearer_warned
+ if not _uses_plaintext_bearer_auth(base, secret):
+ return
+ message = _plaintext_bearer_auth_message(base)
+ if os.environ.get("AGENTMEMORY_REQUIRE_HTTPS") == "1":
+ raise RuntimeError(message)
+ if not _plaintext_bearer_warned:
+ _plaintext_bearer_warned = True
+ (warn or _warn_plaintext_bearer_auth)(message)
+
+
+def _reset_plaintext_bearer_guard_for_tests() -> None:
+ global _plaintext_bearer_warned
+ _plaintext_bearer_warned = False
+
+
def _api(base: str, path: str, body: dict | None = None, method: str = "POST", secret: str = "") -> dict | None:
if not _validate_url(base):
return None
url = f"{base}/agentmemory/{path}"
headers = {"Content-Type": "application/json"}
auth = secret or os.environ.get("AGENTMEMORY_SECRET", "")
+ _check_plaintext_bearer_guard(base, auth)
if auth:
headers["Authorization"] = f"Bearer {auth}"
@@ -141,6 +181,8 @@ class AgentMemoryProvider(MemoryProvider):
self._base = os.environ.get("AGENTMEMORY_URL", DEFAULT_BASE_URL)
self._session_id = session_id
self._project = kwargs.get("cwd", os.getcwd())
+ if os.environ.get("AGENTMEMORY_REQUIRE_HTTPS") == "1":
+ _check_plaintext_bearer_guard(self._base, os.environ.get("AGENTMEMORY_SECRET", ""))
_api(self._base, "session/start", {
"sessionId": session_id,
diff --git a/integrations/openclaw/plugin.mjs b/integrations/openclaw/plugin.mjs
index 7579a9d8..332189d7 100644
--- a/integrations/openclaw/plugin.mjs
+++ b/integrations/openclaw/plugin.mjs
@@ -12,6 +12,7 @@
const DEFAULT_BASE_URL = "http://localhost:3111";
const DEFAULT_TIMEOUT_MS = 5000;
+const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "::1"]);
const configSchema = {
type: "object",
@@ -73,13 +74,51 @@ function formatResults(results) {
.join("\n");
}
+function normalizedHostname(hostname) {
+ return hostname.replace(/^\[|\]$/g, "").toLowerCase();
+}
+
+function usesPlaintextBearerAuth(baseUrl, secret) {
+ if (!secret) return false;
+ try {
+ const parsed = new URL(baseUrl);
+ return parsed.protocol === "http:" && !LOOPBACK_HOSTS.has(normalizedHostname(parsed.hostname));
+ } catch {
+ return false;
+ }
+}
+
+function plaintextBearerAuthMessage(baseUrl) {
+ return `agentmemory: AGENTMEMORY_SECRET is configured for plaintext HTTP to ${baseUrl}. Bearer tokens and memory payloads can be observed on the network; use HTTPS or an SSH tunnel.`;
+}
+
+export function createPlaintextBearerAuthGuard(warn, env) {
+ let warned = false;
+ return function guardPlaintextBearerAuth(baseUrl, secret) {
+ if (!usesPlaintextBearerAuth(baseUrl, secret)) return;
+ const message = plaintextBearerAuthMessage(baseUrl);
+ if ((env || process.env).AGENTMEMORY_REQUIRE_HTTPS === "1") throw new Error(message);
+ if (!warned) {
+ warned = true;
+ warn(message);
+ }
+ };
+}
+
function createClient(cfg, api) {
const baseUrl = String(cfg.base_url || DEFAULT_BASE_URL).replace(/\/+$/, "");
const timeoutMs = Number(cfg.timeout_ms || DEFAULT_TIMEOUT_MS);
const fallbackOnError = cfg.fallback_on_error !== false;
const secret = process.env.AGENTMEMORY_SECRET;
+ const guardPlaintextBearerAuth = createPlaintextBearerAuthGuard(
+ (message) => api.logger.warn?.(message),
+ );
+ if (process.env.AGENTMEMORY_REQUIRE_HTTPS === "1") {
+ guardPlaintextBearerAuth(baseUrl, secret);
+ }
async function postJson(path, payload) {
+ guardPlaintextBearerAuth(baseUrl, secret);
const headers = { "Content-Type": "application/json" };
if (secret) headers.Authorization = `Bearer ${secret}`;
try {
diff --git a/integrations/pi/README.md b/integrations/pi/README.md
index cdc613cc..85a2758e 100644
--- a/integrations/pi/README.md
+++ b/integrations/pi/README.md
@@ -53,6 +53,7 @@ If you place it under `~/.pi/agent/extensions/agentmemory/`, pi will also auto-d
|---|---|---|
| `AGENTMEMORY_URL` | `http://localhost:3111` | agentmemory server URL |
| `AGENTMEMORY_SECRET` | (none) | Bearer token for protected instances |
+| `AGENTMEMORY_REQUIRE_HTTPS` | (off) | When set to `1`, refuse to send a bearer token over plaintext HTTP to a non-loopback host. Sends the token only when `AGENTMEMORY_URL` is `https://...` or points at `localhost`/`127.0.0.1`/`::1`. With this off, the plugin warns once but still sends. |
## Smoke test
diff --git a/integrations/pi/index.ts b/integrations/pi/index.ts
index f2bafc0a..dee703f8 100644
--- a/integrations/pi/index.ts
+++ b/integrations/pi/index.ts
@@ -2,6 +2,7 @@ import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
import { Type } from "typebox";
import path from "node:path";
import crypto from "node:crypto";
+import { createPlaintextBearerAuthGuard } from "./security.js";
type TextBlock = { type?: string; text?: string };
type AssistantMessage = { role?: string; content?: unknown };
@@ -29,6 +30,7 @@ type HealthResponse = {
};
const DEFAULT_URL = process.env.AGENTMEMORY_URL || "http://localhost:3111";
+const guardPlaintextBearerAuth = createPlaintextBearerAuthGuard();
const TOOL_GUIDANCE = [
"agentmemory is available for cross-session memory.",
"Use memory_search to recall prior decisions, preferences, bugs, and workflows.",
@@ -92,8 +94,10 @@ async function callAgentMemory<T>(
const method = options?.method || "POST";
const url = `${baseUrl}/agentmemory/${pathname.replace(/^\/+/, "")}`;
const headers: Record<string, string> = {};
+ const secret = process.env.AGENTMEMORY_SECRET;
+ guardPlaintextBearerAuth(baseUrl, secret);
if (options?.body !== undefined) headers["Content-Type"] = "application/json";
- if (process.env.AGENTMEMORY_SECRET) headers.Authorization = `Bearer ${process.env.AGENTMEMORY_SECRET}`;
+ if (secret) headers.Authorization = `Bearer ${secret}`;
try {
const response = await fetch(url, {
@@ -109,6 +113,12 @@ async function callAgentMemory<T>(
}
export default function agentmemoryExtension(pi: ExtensionAPI) {
+ if (process.env.AGENTMEMORY_REQUIRE_HTTPS === "1") {
+ guardPlaintextBearerAuth(
+ normalizeBaseUrl(process.env.AGENTMEMORY_URL || DEFAULT_URL),
+ process.env.AGENTMEMORY_SECRET,
+ );
+ }
let sessionId = `ephemeral-${crypto.randomUUID().slice(0, 8)}`;
let currentProject = process.cwd();
let lastPrompt = "";
diff --git a/integrations/pi/security.ts b/integrations/pi/security.ts
new file mode 100644
index 00000000..4db0e529
--- /dev/null
+++ b/integrations/pi/security.ts
@@ -0,0 +1,35 @@
+const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "::1"]);
+
+function normalizedHostname(hostname: string): string {
+ return hostname.replace(/^\[|\]$/g, "").toLowerCase();
+}
+
+export function usesPlaintextBearerAuth(baseUrl: string, secret?: string): boolean {
+ if (!secret) return false;
+ try {
+ const parsed = new URL(baseUrl);
+ return parsed.protocol === "http:" && !LOOPBACK_HOSTS.has(normalizedHostname(parsed.hostname));
+ } catch {
+ return false;
+ }
+}
+
+export function plaintextBearerAuthMessage(baseUrl: string): string {
+ return `agentmemory: AGENTMEMORY_SECRET is configured for plaintext HTTP to ${baseUrl}. Bearer tokens and memory payloads can be observed on the network; use HTTPS or an SSH tunnel.`;
+}
+
+export function createPlaintextBearerAuthGuard(
+ warn: (message: string) => void = (message) => console.warn(message),
+ env?: { AGENTMEMORY_REQUIRE_HTTPS?: string },
+): (baseUrl: string, secret?: string) => void {
+ let warned = false;
+ return (baseUrl, secret) => {
+ if (!usesPlaintextBearerAuth(baseUrl, secret)) return;
+ const message = plaintextBearerAuthMessage(baseUrl);
+ if ((env || process.env).AGENTMEMORY_REQUIRE_HTTPS === "1") throw new Error(message);
+ if (!warned) {
+ warned = true;
+ warn(message);
+ }
+ };
+}
diff --git a/test/integration-plaintext-http.test.ts b/test/integration-plaintext-http.test.ts
new file mode 100644
index 00000000..70ef689f
--- /dev/null
+++ b/test/integration-plaintext-http.test.ts
@@ -0,0 +1,210 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { spawnSync } from "node:child_process";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import openclawPlugin from "../integrations/openclaw/plugin.mjs";
+import { createPlaintextBearerAuthGuard } from "../integrations/pi/security.ts";
+
+type OpenClawHandler = (event: Record<string, unknown>) => Promise<unknown>;
+
+function mockFetch(): ReturnType<typeof vi.fn> {
+ const fetchMock = vi.fn(async () =>
+ new Response(JSON.stringify({ results: [] }), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ }),
+ );
+ (globalThis as { fetch: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
+ return fetchMock;
+}
+
+function registerOpenClaw(baseUrl: string) {
+ const handlers = new Map<string, OpenClawHandler>();
+ const warn = vi.fn();
+ openclawPlugin.register({
+ pluginConfig: { base_url: baseUrl },
+ logger: { warn },
+ on(event: string, handler: OpenClawHandler) {
+ handlers.set(event, handler);
+ },
+ });
+ return { handlers, warn };
+}
+
+describe("OpenClaw plaintext bearer guard", () => {
+ const originalFetch = globalThis.fetch;
+ const originalEnv = { ...process.env };
+
+ beforeEach(() => {
+ process.env = { ...originalEnv, AGENTMEMORY_SECRET: "secret" };
+ delete process.env["AGENTMEMORY_REQUIRE_HTTPS"];
+ mockFetch();
+ });
+
+ afterEach(() => {
+ globalThis.fetch = originalFetch;
+ process.env = { ...originalEnv };
+ });
+
+ it("keeps loopback HTTP silent", async () => {
+ const { handlers, warn } = registerOpenClaw("http://localhost:3111");
+ await handlers.get("before_agent_start")?.({ prompt: "recall auth work" });
+ expect(warn).not.toHaveBeenCalled();
+ });
+
+ it("warns once for non-loopback HTTP with a bearer secret", async () => {
+ const { handlers, warn } = registerOpenClaw("http://remote.example:3111");
+ await handlers.get("before_agent_start")?.({ prompt: "first" });
+ await handlers.get("before_agent_start")?.({ prompt: "second" });
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(warn.mock.calls[0][0]).toContain("plaintext HTTP to http://remote.example:3111");
+ });
+
+ it("keeps HTTPS with a bearer secret silent", async () => {
+ const { handlers, warn } = registerOpenClaw("https://remote.example");
+ await handlers.get("before_agent_start")?.({ prompt: "recall auth work" });
+ expect(warn).not.toHaveBeenCalled();
+ });
+
+ it("fails before any request when HTTPS is required", () => {
+ process.env["AGENTMEMORY_REQUIRE_HTTPS"] = "1";
+ const fetchMock = mockFetch();
+ expect(() => registerOpenClaw("http://remote.example:3111")).toThrow(
+ /plaintext HTTP to http:\/\/remote\.example:3111/,
+ );
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
+
+describe("pi plaintext bearer guard", () => {
+ it("keeps loopback HTTP silent", () => {
+ const warn = vi.fn();
+ const guard = createPlaintextBearerAuthGuard(warn, {});
+ guard("http://127.0.0.1:3111", "secret");
+ expect(warn).not.toHaveBeenCalled();
+ });
+
+ it("warns once for non-loopback HTTP with a bearer secret", () => {
+ const warn = vi.fn();
+ const guard = createPlaintextBearerAuthGuard(warn, {});
+ guard("http://remote.example:3111", "secret");
+ guard("http://remote.example:3111", "secret");
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(warn.mock.calls[0][0]).toContain("plaintext HTTP to http://remote.example:3111");
+ });
+
+ it("keeps HTTPS with a bearer secret silent", () => {
+ const warn = vi.fn();
+ const guard = createPlaintextBearerAuthGuard(warn, {});
+ guard("https://remote.example", "secret");
+ expect(warn).not.toHaveBeenCalled();
+ });
+
+ it("fails before callers can issue a request when HTTPS is required", () => {
+ const warn = vi.fn();
+ const guard = createPlaintextBearerAuthGuard(warn, {
+ AGENTMEMORY_REQUIRE_HTTPS: "1",
+ });
+ expect(() => guard("http://remote.example:3111", "secret")).toThrow(
+ /plaintext HTTP to http:\/\/remote\.example:3111/,
+ );
+ expect(warn).not.toHaveBeenCalled();
+ });
+
+ it("treats IPv6 loopback ([::1]) as loopback (URL parser strips brackets)", () => {
+ const warn = vi.fn();
+ const guard = createPlaintextBearerAuthGuard(warn, {});
+ guard("http://[::1]:3111", "secret");
+ expect(warn).not.toHaveBeenCalled();
+ });
+
+ it("warns for private LAN IPs — RFC1918 ranges are NOT loopback", () => {
+ const warn = vi.fn();
+ const guard = createPlaintextBearerAuthGuard(warn, {});
+ guard("http://192.168.1.50:3111", "secret");
+ guard("http://10.0.0.42:3111", "secret");
+ expect(warn).toHaveBeenCalledTimes(1); // warn-once
+ expect(warn.mock.calls[0][0]).toContain("plaintext HTTP to http://192.168.1.50:3111");
+ });
+
+ it("does not warn when no secret is set — guard only fires when a bearer would actually be sent", () => {
+ const warn = vi.fn();
+ const guard = createPlaintextBearerAuthGuard(warn, {});
+ guard("http://remote.example:3111", "");
+ guard("http://remote.example:3111", undefined);
+ expect(warn).not.toHaveBeenCalled();
+ });
+
+ it("treats hostnames that LOOK loopback but aren't (localhost.evil.com) as remote", () => {
+ const warn = vi.fn();
+ const guard = createPlaintextBearerAuthGuard(warn, {});
+ guard("http://localhost.evil.com:3111", "secret");
+ expect(warn).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("Hermes plaintext bearer guard", () => {
+ let home: string;
+
+ beforeEach(() => {
+ home = mkdtempSync(join(tmpdir(), "agentmemory-hermes-test-"));
+ });
+
+ afterEach(() => {
+ rmSync(home, { recursive: true, force: true });
+ });
+
+ it("covers loopback, remote HTTP, HTTPS, and require-HTTPS behavior", () => {
+ const script = String.raw`
+import importlib.util
+import os
+import sys
+
+spec = importlib.util.spec_from_file_location("agentmemory_hermes", "integrations/hermes/__init__.py")
+mod = importlib.util.module_from_spec(spec)
+assert spec.loader is not None
+spec.loader.exec_module(mod)
+
+for key in ("AGENTMEMORY_SECRET", "AGENTMEMORY_URL", "AGENTMEMORY_REQUIRE_HTTPS"):
+ os.environ.pop(key, None)
+
+warnings = []
+mod._reset_plaintext_bearer_guard_for_tests()
+mod._check_plaintext_bearer_guard("http://localhost:3111", "secret", warnings.append)
+assert warnings == [], warnings
+
+mod._reset_plaintext_bearer_guard_for_tests()
+mod._check_plaintext_bearer_guard("http://remote.example:3111", "secret", warnings.append)
+mod._check_plaintext_bearer_guard("http://remote.example:3111", "secret", warnings.append)
+assert len(warnings) == 1, warnings
+assert "plaintext HTTP to http://remote.example:3111" in warnings[0], warnings
+
+warnings = []
+mod._reset_plaintext_bearer_guard_for_tests()
+mod._check_plaintext_bearer_guard("https://remote.example", "secret", warnings.append)
+assert warnings == [], warnings
+
+calls = []
+def fake_urlopen(req, timeout=0):
+ calls.append(req)
+ raise AssertionError("request should not be sent")
+
+mod.urlopen = fake_urlopen
+os.environ["AGENTMEMORY_REQUIRE_HTTPS"] = "1"
+try:
+ mod._api("http://remote.example:3111", "health", method="GET", secret="secret")
+except RuntimeError as exc:
+ assert "plaintext HTTP to http://remote.example:3111" in str(exc), exc
+else:
+ raise AssertionError("expected RuntimeError")
+assert calls == [], calls
+`;
+ const result = spawnSync("python3", ["-c", script], {
+ cwd: process.cwd(),
+ env: { ...process.env, HOME: home },
+ encoding: "utf8",
+ });
+ expect(result.status, result.stderr || result.stdout).toBe(0);
+ });
+});