Skip to content

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

security: harden defaults, viewer CSP, mesh auth, export confinement (#108)

eng1cbaaf4fb445b
diff --git a/README.md b/README.md
index 2e4bd485..45f4de5b 100644
--- a/README.md
+++ b/README.md
@@ -242,6 +242,10 @@ git clone https://github.com/rohitg00/agentmemory.git && cd agentmemory
npm install && npm run build && npm start
```
+This starts agentmemory with a local `iii-engine` if `iii` is already installed, or falls back to Docker Compose if Docker is available. REST, streams, and the viewer bind to `127.0.0.1` by default.
+
+Install `iii-engine` manually with `cargo install iii-engine` or follow [iii.dev docs](https://iii.dev/docs).
+
---
## Why agentmemory
@@ -480,7 +484,7 @@ Auto-starts on port `3113`. Live observation stream, session explorer, memory br
open http://localhost:3113
```
-Protected by `AGENTMEMORY_SECRET` when set. CSP headers on all HTML responses.
+The viewer server binds to `127.0.0.1` by default. The REST-served `/agentmemory/viewer` endpoint follows the normal `AGENTMEMORY_SECRET` bearer-token rules. CSP headers use a per-response script nonce and disable inline handler attributes (`script-src-attr 'none'`).
---
@@ -528,6 +532,7 @@ Create `~/.agentmemory/.env`:
# CONSOLIDATION_ENABLED=true
# LESSON_DECAY_ENABLED=true
# OBSIDIAN_AUTO_EXPORT=false
+# AGENTMEMORY_EXPORT_ROOT=~/.agentmemory
# CLAUDE_MEMORY_BRIDGE=false
# SNAPSHOT_ENABLED=false
@@ -544,7 +549,7 @@ Create `~/.agentmemory/.env`:
## API
-109 endpoints on port `3111`. Protected by `Authorization: Bearer <secret>` when `AGENTMEMORY_SECRET` is set.
+109 endpoints on port `3111`. The REST API binds to `127.0.0.1` by default. Protected endpoints require `Authorization: Bearer <secret>` when `AGENTMEMORY_SECRET` is set, and mesh sync endpoints require `AGENTMEMORY_SECRET` on both peers.
<details>
<summary>Key endpoints</summary>
@@ -601,7 +606,7 @@ npm test # 646 tests (~1.7s)
npm run test:integration # API tests (requires running services)
```
-**Prerequisites:** Node.js >= 20, [iii-engine](https://iii.dev/docs) (auto-installed by `npx @agentmemory/agentmemory`)
+**Prerequisites:** Node.js >= 20, [iii-engine](https://iii.dev/docs) or Docker
## License
diff --git a/docker-compose.yml b/docker-compose.yml
index 101284d6..655deaf6 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -2,13 +2,13 @@ services:
iii-engine:
image: iiidev/iii:latest
ports:
- - "49134:49134"
- - "3111:3111"
- - "3112:3112"
- - "9464:9464"
+ - "127.0.0.1:49134:49134"
+ - "127.0.0.1:3111:3111"
+ - "127.0.0.1:3112:3112"
+ - "127.0.0.1:9464:9464"
volumes:
- iii-data:/data
- - ./iii-config.yaml:/app/config.yaml:ro
+ - ./iii-config.docker.yaml:/app/config.yaml:ro
restart: unless-stopped
volumes:
diff --git a/iii-config.docker.yaml b/iii-config.docker.yaml
new file mode 100644
index 00000000..3aecf8a8
--- /dev/null
+++ b/iii-config.docker.yaml
@@ -0,0 +1,51 @@
+modules:
+ - class: modules::state::StateModule
+ config:
+ adapter:
+ class: modules::state::adapters::KvStore
+ config:
+ store_method: file_based
+ file_path: ./data/state_store.db
+
+ - class: modules::api::RestApiModule
+ config:
+ port: 3111
+ host: 0.0.0.0
+ default_timeout: 180000
+ cors:
+ allowed_origins: ["http://localhost:3111", "http://localhost:3113", "http://127.0.0.1:3111", "http://127.0.0.1:3113"]
+ allowed_methods: [GET, POST, PUT, DELETE, OPTIONS]
+
+ - class: modules::queue::QueueModule
+ config:
+ adapter:
+ class: modules::queue::BuiltinQueueAdapter
+
+ - class: modules::pubsub::PubSubModule
+ config:
+ adapter:
+ class: modules::pubsub::LocalAdapter
+
+ - class: modules::cron::CronModule
+ config:
+ adapter:
+ class: modules::cron::KvCronAdapter
+
+ - class: modules::stream::StreamModule
+ config:
+ port: 3112
+ host: 0.0.0.0
+
+ - class: modules::observability::OtelModule
+ config:
+ enabled: true
+ service_name: agentmemory
+ exporter: memory
+ logs_enabled: true
+
+ - class: modules::shell::ExecModule
+ config:
+ watch:
+ - src/**/*.ts
+ exec:
+ - node dist/index.mjs
diff --git a/iii-config.yaml b/iii-config.yaml
index 3aecf8a8..adb05b5a 100644
--- a/iii-config.yaml
+++ b/iii-config.yaml
@@ -10,7 +10,7 @@ modules:
- class: modules::api::RestApiModule
config:
port: 3111
- host: 0.0.0.0
+ host: 127.0.0.1
default_timeout: 180000
cors:
allowed_origins: ["http://localhost:3111", "http://localhost:3113", "http://127.0.0.1:3111", "http://127.0.0.1:3113"]
@@ -34,7 +34,7 @@ modules:
- class: modules::stream::StreamModule
config:
port: 3112
- host: 0.0.0.0
+ host: 127.0.0.1
- class: modules::observability::OtelModule
config:
diff --git a/package.json b/package.json
index b35f07b7..93a6b771 100644
--- a/package.json
+++ b/package.json
@@ -10,7 +10,7 @@
"agentmemory-mcp": "dist/standalone.mjs"
},
"scripts": {
- "build": "tsdown && (cp iii-config.yaml dist/ 2>/dev/null || true) && (cp docker-compose.yml dist/ 2>/dev/null || true) && mkdir -p dist/viewer && cp src/viewer/index.html dist/viewer/",
+ "build": "tsdown && (cp iii-config.yaml dist/ 2>/dev/null || true) && (cp iii-config.docker.yaml dist/ 2>/dev/null || true) && (cp docker-compose.yml dist/ 2>/dev/null || true) && mkdir -p dist/viewer && cp src/viewer/index.html dist/viewer/",
"dev": "tsx src/index.ts",
"start": "node dist/cli.mjs",
"migrate": "node dist/functions/migrate.js",
diff --git a/src/auth.ts b/src/auth.ts
index 11bba275..95153bad 100644
--- a/src/auth.ts
+++ b/src/auth.ts
@@ -1,6 +1,7 @@
import { timingSafeEqual, createHmac, randomBytes } from "node:crypto";
const hmacKey = randomBytes(32);
+export const VIEWER_NONCE_PLACEHOLDER = "__AGENTMEMORY_VIEWER_NONCE__";
export function timingSafeCompare(a: string, b: string): boolean {
const hmacA = createHmac("sha256", hmacKey).update(a).digest();
@@ -8,5 +9,22 @@ export function timingSafeCompare(a: string, b: string): boolean {
return timingSafeEqual(hmacA, hmacB);
}
-export const VIEWER_CSP =
- "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self' ws://localhost:* wss://localhost:*; img-src 'self'; font-src 'self'";
+export function createViewerNonce(): string {
+ return randomBytes(16).toString("base64url");
+}
+
+export function buildViewerCsp(nonce: string): string {
+ return [
+ "default-src 'none'",
+ "base-uri 'none'",
+ "frame-ancestors 'none'",
+ "object-src 'none'",
+ "form-action 'none'",
+ `script-src 'nonce-${nonce}'`,
+ "script-src-attr 'none'",
+ "style-src 'unsafe-inline'",
+ "connect-src 'self' http://localhost:* http://127.0.0.1:* ws://localhost:* ws://127.0.0.1:* wss://localhost:* wss://127.0.0.1:*",
+ "img-src 'self'",
+ "font-src 'self'",
+ ].join("; ");
+}
diff --git a/src/cli.ts b/src/cli.ts
index 7c908a6a..000621cc 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -1,6 +1,6 @@
#!/usr/bin/env node
-import { spawn, execFileSync, execSync } from "node:child_process";
+import { spawn, execFileSync } from "node:child_process";
import { existsSync } from "node:fs";
import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";
@@ -26,9 +26,9 @@ Options:
--port <N> Override REST port (default: 3111)
Quick start:
- npx @agentmemory/agentmemory # start everything
+ npx @agentmemory/agentmemory # start with local iii-engine or Docker
npx @agentmemory/agentmemory status # check health
- npx agentmemory-mcp # standalone MCP (no engine)
+ npx agentmemory-mcp # standalone MCP server (no engine)
`);
process.exit(0);
}
@@ -81,77 +81,10 @@ function whichBinary(name: string): string | null {
}
}
-async function installIii(): Promise<boolean> {
- if (process.platform === "win32") {
- p.log.warn("Automatic iii-engine install is not supported on Windows.");
- p.log.info("Install manually: https://iii.dev/docs");
- return false;
- }
-
- const curlBin = whichBinary("curl");
- if (!curlBin) {
- p.log.warn("curl not found — cannot auto-install iii-engine.");
- return false;
- }
-
- const shouldInstall = await p.confirm({
- message: "iii-engine is not installed. Install it now?",
- initialValue: true,
- });
-
- if (p.isCancel(shouldInstall) || !shouldInstall) {
- return false;
- }
-
- const s = p.spinner();
- s.start("Installing iii-engine...");
-
- try {
- execSync("curl -fsSL https://install.iii.dev/iii/main/install.sh | sh", {
- stdio: ["pipe", "pipe", "pipe"],
- timeout: 120000,
- });
-
- const installed = whichBinary("iii");
- if (installed) {
- s.stop("iii-engine installed successfully");
- return true;
- }
-
- s.stop("Installation completed but iii not found in PATH");
- p.log.warn("You may need to restart your shell or add iii to your PATH.");
-
- const iiiPaths = [
- join(process.env["HOME"] || "", ".local", "bin", "iii"),
- "/usr/local/bin/iii",
- ];
- for (const iiiPath of iiiPaths) {
- if (existsSync(iiiPath)) {
- p.log.info(`Found iii at: ${iiiPath}`);
- process.env["PATH"] = `${dirname(iiiPath)}:${process.env["PATH"]}`;
- return true;
- }
- }
-
- return false;
- } catch (err) {
- s.stop("Failed to install iii-engine");
- p.log.error(err instanceof Error ? err.message : String(err));
- return false;
- }
-}
-
async function startEngine(): Promise<boolean> {
const configPath = findIiiConfig();
let iiiBin = whichBinary("iii");
- if (!iiiBin) {
- const installed = await installIii();
- if (installed) {
- iiiBin = whichBinary("iii");
- }
- }
-
if (iiiBin && configPath) {
const s = p.spinner();
s.start(`Starting iii-engine: ${iiiBin}`);
@@ -181,6 +114,31 @@ async function startEngine(): Promise<boolean> {
return true;
}
+ const iiiPaths = [
+ join(process.env["HOME"] || "", ".local", "bin", "iii"),
+ "/usr/local/bin/iii",
+ ];
+ for (const iiiPath of iiiPaths) {
+ if (existsSync(iiiPath)) {
+ p.log.info(`Found iii at: ${iiiPath}`);
+ process.env["PATH"] = `${dirname(iiiPath)}:${process.env["PATH"]}`;
+ iiiBin = iiiPath;
+ break;
+ }
+ }
+
+ if (iiiBin && configPath) {
+ const s = p.spinner();
+ s.start(`Starting iii-engine: ${iiiBin}`);
+ const child = spawn(iiiBin, ["--config", configPath], {
+ detached: true,
+ stdio: "ignore",
+ });
+ child.unref();
+ s.stop("iii-engine process started");
+ return true;
+ }
+
return false;
}
@@ -214,8 +172,8 @@ async function main() {
p.note(
[
"Install iii-engine (pick one):",
- " curl -fsSL https://install.iii.dev/iii/main/install.sh | sh",
" cargo install iii-engine",
+ " See: https://iii.dev/docs",
"",
"Or use Docker:",
" docker pull iiidev/iii:latest",
diff --git a/src/functions/mesh.ts b/src/functions/mesh.ts
index 63351765..dd4c670b 100644
--- a/src/functions/mesh.ts
+++ b/src/functions/mesh.ts
@@ -135,7 +135,11 @@ async function lwwMergeGraphNodes(
return count;
}
-export function registerMeshFunction(sdk: ISdk, kv: StateKV): void {
+export function registerMeshFunction(
+ sdk: ISdk,
+ kv: StateKV,
+ meshAuthToken?: string,
+): void {
sdk.registerFunction(
{ id: "mem::mesh-register" },
async (data: {
@@ -183,6 +187,13 @@ export function registerMeshFunction(sdk: ISdk, kv: StateKV): void {
sdk.registerFunction(
{ id: "mem::mesh-sync" },
async (data: { peerId?: string; scopes?: string[]; direction?: "push" | "pull" | "both" }) => {
+ if (!meshAuthToken) {
+ return {
+ success: false,
+ error: "mesh sync requires AGENTMEMORY_SECRET",
+ };
+ }
+
const direction = data.direction || "both";
let peers: MeshPeer[];
@@ -230,7 +241,10 @@ export function registerMeshFunction(sdk: ISdk, kv: StateKV): void {
try {
const response = await fetch(`${peer.url}/agentmemory/mesh/receive`, {
method: "POST",
- headers: { "Content-Type": "application/json" },
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${meshAuthToken}`,
+ },
body: JSON.stringify(pushData),
signal: AbortSignal.timeout(30000),
redirect: "error",
@@ -250,7 +264,13 @@ export function registerMeshFunction(sdk: ISdk, kv: StateKV): void {
try {
const response = await fetch(
`${peer.url}/agentmemory/mesh/export?since=${peer.lastSyncAt || ""}`,
- { signal: AbortSignal.timeout(30000), redirect: "error" },
+ {
+ headers: {
+ Authorization: `Bearer ${meshAuthToken}`,
+ },
+ signal: AbortSignal.timeout(30000),
+ redirect: "error",
+ },
);
if (response.ok) {
const pullData = (await response.json()) as {
diff --git a/src/functions/obsidian-export.ts b/src/functions/obsidian-export.ts
index cb541511..6fabfb6f 100644
--- a/src/functions/obsidian-export.ts
+++ b/src/functions/obsidian-export.ts
@@ -1,5 +1,5 @@
import { mkdir, writeFile } from "node:fs/promises";
-import { join } from "node:path";
+import { join, resolve, sep } from "node:path";
import { homedir } from "node:os";
import type { ISdk } from "iii-sdk";
import type { StateKV } from "../state/kv.js";
@@ -11,8 +11,20 @@ import type {
Session,
} from "../types.js";
import { recordAudit } from "./audit.js";
+const DEFAULT_EXPORT_ROOT = join(homedir(), ".agentmemory");
-const DEFAULT_VAULT = join(homedir(), ".agentmemory", "vault");
+function getExportRoot(): string {
+ return resolve(process.env["AGENTMEMORY_EXPORT_ROOT"] || DEFAULT_EXPORT_ROOT);
+}
+
+function resolveVaultDir(vaultDir?: string): string | null {
+ const root = getExportRoot();
+ const resolved = resolve(vaultDir || join(root, "vault"));
+ if (resolved === root || resolved.startsWith(root + sep)) {
+ return resolved;
+ }
+ return null;
+}
function sanitize(name: string): string {
return name.replace(/[<>:"/\\|?*\x00-\x1f]/g, "_").slice(0, 100);
@@ -188,7 +200,13 @@ export function registerObsidianExportFunction(
sdk.registerFunction(
{ id: "mem::obsidian-export" },
async (data: { vaultDir?: string; types?: string[] }) => {
- const vaultDir = data.vaultDir || DEFAULT_VAULT;
+ const vaultDir = resolveVaultDir(data.vaultDir);
+ if (!vaultDir) {
+ return {
+ success: false,
+ error: `vaultDir must be inside ${getExportRoot()}`,
+ };
+ }
const exportTypes = new Set(
data.types || ["memories", "lessons", "crystals", "sessions"],
);
diff --git a/src/functions/privacy.ts b/src/functions/privacy.ts
index bb67405c..8731cea8 100644
--- a/src/functions/privacy.ts
+++ b/src/functions/privacy.ts
@@ -4,9 +4,11 @@ const PRIVATE_TAG_RE = /<private>[\s\S]*?<\/private>/gi;
const SECRET_PATTERN_SOURCES = [
/(?:api[_-]?key|secret|token|password|credential|auth)[\s]*[=:]\s*["']?[A-Za-z0-9_\-/.+]{20,}["']?/gi,
- /(?:sk|pk|rk|ak)-[A-Za-z0-9]{20,}/g,
+ /Bearer\s+[A-Za-z0-9._\-+/=]{20,}/gi,
+ /sk-proj-[A-Za-z0-9\-_]{20,}/g,
+ /(?:sk|pk|rk|ak)-[A-Za-z0-9][A-Za-z0-9\-_]{19,}/g,
/sk-ant-[A-Za-z0-9\-_]{20,}/g,
- /ghp_[A-Za-z0-9]{36}/g,
+ /gh[pus]_[A-Za-z0-9]{36,}/g,
/github_pat_[A-Za-z0-9_]{22,}/g,
/xoxb-[A-Za-z0-9\-]+/g,
/AKIA[0-9A-Z]{16}/g,
diff --git a/src/index.ts b/src/index.ts
index a0219d0f..288f9400 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -186,7 +186,7 @@ async function main() {
registerRoutinesFunction(sdk, kv);
registerSignalsFunction(sdk, kv);
registerCheckpointsFunction(sdk, kv);
- registerMeshFunction(sdk, kv);
+ registerMeshFunction(sdk, kv, secret);
registerBranchAwareFunction(sdk, kv);
registerFlowCompressFunction(sdk, kv, provider);
registerSentinelsFunction(sdk, kv);
diff --git a/src/triggers/api.ts b/src/triggers/api.ts
index 0c0fb380..428fc0f5 100644
--- a/src/triggers/api.ts
+++ b/src/triggers/api.ts
@@ -2,14 +2,12 @@ import type { ISdk, ApiRequest } from "iii-sdk";
import type { Session, CompressedObservation, HookPayload } from "../types.js";
import { KV } from "../state/schema.js";
import { StateKV } from "../state/kv.js";
-import { readFileSync } from "node:fs";
-import { join, dirname } from "node:path";
-import { fileURLToPath } from "node:url";
import { getLatestHealth } from "../health/monitor.js";
import type { MetricsStore } from "../eval/metrics-store.js";
import type { ResilientProvider } from "../providers/resilient.js";
import { VERSION } from "../version.js";
-import { timingSafeCompare, VIEWER_CSP } from "../auth.js";
+import { timingSafeCompare } from "../auth.js";
+import { renderViewerDocument } from "../viewer/document.js";
type Response = {
status_code: number;
@@ -32,6 +30,17 @@ function checkAuth(
return null;
}
+function requireConfiguredSecret(
+ secret: string | undefined,
+ feature: string,
+): Response | null {
+ if (secret) return null;
+ return {
+ status_code: 503,
+ body: { error: `${feature} requires AGENTMEMORY_SECRET` },
+ };
+}
+
export function registerApiTriggers(
sdk: ISdk,
kv: StateKV,
@@ -1426,6 +1435,8 @@ export function registerApiTriggers(
async (
req: ApiRequest<{ url: string; name: string; sharedScopes?: string[] }>,
): Promise<Response> => {
+ const secretErr = requireConfiguredSecret(secret, "mesh");
+ if (secretErr) return secretErr;
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
if (!req.body?.url || !req.body?.name) {
@@ -1444,6 +1455,8 @@ export function registerApiTriggers(
sdk.registerFunction(
{ id: "api::mesh-list" },
async (req: ApiRequest): Promise<Response> => {
+ const secretErr = requireConfiguredSecret(secret, "mesh");
+ if (secretErr) return secretErr;
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
const result = await sdk.trigger("mem::mesh-list", {});
@@ -1461,6 +1474,8 @@ export function registerApiTriggers(
async (
req: ApiRequest<{ peerId?: string; direction?: string }>,
): Promise<Response> => {
+ const secretErr = requireConfiguredSecret(secret, "mesh");
+ if (secretErr) return secretErr;
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
const result = await sdk.trigger("mem::mesh-sync", req.body || {});
@@ -1476,6 +1491,8 @@ export function registerApiTriggers(
sdk.registerFunction(
{ id: "api::mesh-receive" },
async (req: ApiRequest): Promise<Response> => {
+ const secretErr = requireConfiguredSecret(secret, "mesh");
+ if (secretErr) return secretErr;
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
const result = await sdk.trigger("mem::mesh-receive", req.body || {});
@@ -1491,6 +1508,8 @@ export function registerApiTriggers(
sdk.registerFunction(
{ id: "api::mesh-export" },
async (req: ApiRequest): Promise<Response> => {
+ const secretErr = requireConfiguredSecret(secret, "mesh");
+ if (secretErr) return secretErr;
const authErr = checkAuth(req, secret);
if (authErr) return authErr;
const since = req.query_params?.["since"] as string;
@@ -1612,29 +1631,31 @@ export function registerApiTriggers(
config: { api_path: "/agentmemory/branch/sessions", http_method: "GET" },
});
- sdk.registerFunction({ id: "api::viewer" }, async (): Promise<Response> => {
- const headers = {
- "Content-Type": "text/html",
- "Content-Security-Policy": VIEWER_CSP,
- };
- const base = dirname(fileURLToPath(import.meta.url));
- const candidates = [
- join(base, "..", "viewer", "index.html"),
- join(base, "..", "src", "viewer", "index.html"),
- join(base, "viewer", "index.html"),
- ];
- for (const p of candidates) {
- try {
- const html = readFileSync(p, "utf-8");
- return { status_code: 200, headers, body: html };
- } catch {}
- }
- return {
- status_code: 404,
- headers,
- body: "<!DOCTYPE html><html><body><h1>agentmemory</h1><p>viewer not found</p></body></html>",
- };
- });
+ sdk.registerFunction(
+ { id: "api::viewer" },
+ async (req: ApiRequest): Promise<Response> => {
+ const denied = checkAuth(req, secret);
+ if (denied) return denied;
+ const rendered = renderViewerDocument();
+ if (rendered.found) {
+ return {
+ status_code: 200,
+ headers: {
+ "Content-Type": "text/html",
+ "Content-Security-Policy": rendered.csp,
+ },
+ body: rendered.html,
+ };
+ }
+ return {
+ status_code: 404,
+ headers: {
+ "Content-Type": "text/html",
+ },
+ body: "<!DOCTYPE html><html><body><h1>agentmemory</h1><p>viewer not found</p></body></html>",
+ };
+ },
+ );
sdk.registerTrigger({
type: "http",
function_id: "api::viewer",
diff --git a/src/viewer/document.ts b/src/viewer/document.ts
new file mode 100644
index 00000000..8da3286c
--- /dev/null
+++ b/src/viewer/document.ts
@@ -0,0 +1,39 @@
+import { readFileSync } from "node:fs";
+import { join, dirname } from "node:path";
+import { fileURLToPath } from "node:url";
+import {
+ VIEWER_NONCE_PLACEHOLDER,
+ createViewerNonce,
+ buildViewerCsp,
+} from "../auth.js";
+
+function loadViewerTemplate(): string | null {
+ const base = dirname(fileURLToPath(import.meta.url));
+ const candidates = [
+ join(base, "..", "src", "viewer", "index.html"),
+ join(base, "..", "viewer", "index.html"),
+ join(base, "viewer", "index.html"),
+ ];
+ for (const path of candidates) {
+ try {
+ return readFileSync(path, "utf-8");
+ } catch {}
+ }
+ return null;
+}
+
+export function renderViewerDocument():
+ | { found: true; html: string; csp: string }
+ | { found: false } {
+ const template = loadViewerTemplate();
+ if (!template) {
+ return { found: false };
+ }
+
+ const nonce = createViewerNonce();
+ return {
+ found: true,
+ html: template.replaceAll(VIEWER_NONCE_PLACEHOLDER, nonce),
+ csp: buildViewerCsp(nonce),
+ };
+}
diff --git a/src/viewer/index.html b/src/viewer/index.html
index 9a20ca27..99868dab 100644
--- a/src/viewer/index.html
+++ b/src/viewer/index.html
@@ -765,7 +765,7 @@
</div>
<div class="header-right">
<span class="dateline" id="dateline"></span>
- <button id="theme-toggle" class="btn" style="font-size:9px;padding:3px 10px;letter-spacing:0.1em;margin-right:8px;" onclick="toggleTheme()">DARK</button>
+ <button id="theme-toggle" class="btn" style="font-size:9px;padding:3px 10px;letter-spacing:0.1em;margin-right:8px;" data-action="toggle-theme">DARK</button>
<span id="ws-status" class="ws-status disconnected">live updates off</span>
</div>
</div>
@@ -800,7 +800,7 @@
<div class="modal" id="modal"></div>
</div>
- <script>
+ <script nonce="__AGENTMEMORY_VIEWER_NONCE__">
var params = new URLSearchParams(window.location.search);
var viewerPort = params.get('port') || window.location.port || '3113';
var iiiPort = parseInt(viewerPort);
@@ -1216,7 +1216,7 @@
html += '</div>';
}
- html += '<div style="text-align:center;margin-top:20px;"><button class="btn btn-primary" onclick="refreshDashboard()">Refresh</button>';
+ html += '<div style="text-align:center;margin-top:20px;"><button class="btn btn-primary" data-action="refresh-dashboard">Refresh</button>';
html += '<span style="font-size:10px;color:var(--ink-faint);margin-left:10px;font-family:var(--font-mono);text-transform:uppercase;letter-spacing:0.08em;">Auto-refresh 30s</span></div>';
el.innerHTML = html;
@@ -1238,7 +1238,7 @@
async function loadGraph() {
var el = document.getElementById('view-graph');
- el.innerHTML = '<div class="graph-container"><div class="graph-canvas-wrap"><canvas id="graph-canvas"></canvas><div class="graph-controls"><button title="Zoom In" onclick="zoomGraph(1)">+</button><button title="Zoom Out" onclick="zoomGraph(-1)">&minus;</button><div class="ctrl-divider"></div><button title="Recenter" onclick="recenterGraph()">⌖</button></div><div class="graph-tooltip" id="graph-tooltip"></div></div><div class="graph-sidebar" id="graph-sidebar"></div></div>';
+ el.innerHTML = '<div class="graph-container"><div class="graph-canvas-wrap"><canvas id="graph-canvas"></canvas><div class="graph-controls"><button title="Zoom In" data-action="zoom-graph" data-dir="1">+</button><button title="Zoom Out" data-action="zoom-graph" data-dir="-1">&minus;</button><div class="ctrl-divider"></div><button title="Recenter" data-action="recenter-graph">⌖</button></div><div class="graph-tooltip" id="graph-tooltip"></div></div><div class="graph-sidebar" id="graph-sidebar"></div></div>';
var results = await Promise.all([
apiPost('graph/query', {}),
@@ -1315,7 +1315,7 @@
});
html += '</div>';
- html += '<button class="btn" style="margin-top:14px;width:100%;font-size:11px;padding:8px;letter-spacing:0.06em;transition:all 0.15s ease;" onclick="rebuildGraph()" onmouseover="this.style.background=\'var(--ink)\';this.style.color=\'var(--bg)\'" onmouseout="this.style.background=\'\';this.style.color=\'\'">↻ Rebuild Graph</button>';
+ html += '<button class="btn" style="margin-top:14px;width:100%;font-size:11px;padding:8px;letter-spacing:0.06em;transition:all 0.15s ease;" data-action="rebuild-graph">↻ Rebuild Graph</button>';
html += '<div id="selected-node-panel"></div>';
sb.innerHTML = html;
@@ -1510,7 +1510,7 @@
}
var conns = graphSim.edges.filter(function(e) { return e.sourceNodeId === simNode.id || e.targetNodeId === simNode.id; }).length;
html += '<div class="prop">Connections: ' + conns + '</div>';
- html += '<button class="btn btn-primary" style="margin-top:8px;width:100%;" onclick="expandNode(\'' + esc(simNode.id) + '\')">Expand neighbors</button>';
+ html += '<button class="btn btn-primary" style="margin-top:8px;width:100%;" data-action="expand-node" data-node-id="' + esc(simNode.id) + '">Expand neighbors</button>';
html += '</div>';
panel.innerHTML = html;
}
@@ -1929,7 +1929,7 @@
html += '<td><div class="strength-bar"><div class="fill" style="width:' + strength + '%;background:' + barColor + '"></div></div> <span style="font-size:10px;color:var(--ink-faint);font-family:var(--font-mono);">' + strength + '%</span></td>';
html += '<td style="color:var(--ink-muted);font-family:var(--font-mono);font-size:12px;">v' + (m.version || 1) + '</td>';
html += '<td style="font-size:11px;color:var(--ink-faint);font-family:var(--font-mono);">' + esc(formatTime(m.updatedAt)) + '</td>';
- html += '<td><button class="btn btn-danger" style="font-size:9px;padding:2px 8px;" onclick="deleteMemory(\'' + esc(m.id) + '\',\'' + esc((m.title || '').replace(/'/g, '')) + '\')">Delete</button></td>';
+ html += '<td><button class="btn btn-danger" style="font-size:9px;padding:2px 8px;" data-action="delete-memory" data-memory-id="' + esc(m.id) + '" data-memory-title="' + esc(m.title || '') + '">Delete</button></td>';
html += '</tr>';
});
html += '</table>';
@@ -1956,7 +1956,7 @@
function deleteMemory(id, title) {
var modal = document.getElementById('modal');
var overlay = document.getElementById('modal-overlay');
- modal.innerHTML = '<h3>Delete Memory</h3><p>Are you sure you want to delete "' + esc(title) + '"? This action cannot be undone.</p><div class="modal-actions"><button class="btn" onclick="closeModal()">Cancel</button><button class="btn btn-danger" onclick="confirmDeleteMemory(\'' + esc(id) + '\')">Delete</button></div>';
+ modal.innerHTML = '<h3>Delete Memory</h3><p>Are you sure you want to delete "' + esc(title) + '"? This action cannot be undone.</p><div class="modal-actions"><button class="btn" data-action="close-modal">Cancel</button><button class="btn btn-danger" data-action="confirm-delete-memory" data-memory-id="' + esc(id) + '">Delete</button></div>';
overlay.classList.add('open');
}
@@ -2060,10 +2060,10 @@
var totalPages = Math.ceil(filtered.length / pageSize);
var html = '<div class="type-chips">';
- html += '<span class="type-chip' + (!tlTypeFilter ? ' active' : '') + '" onclick="setTlTypeFilter(\'\')">All (' + obs.length + ')</span>';
+ html += '<span class="type-chip' + (!tlTypeFilter ? ' active' : '') + '" data-action="timeline-filter" data-type-filter="">All (' + obs.length + ')</span>';
typeList.forEach(function(t) {
var color = OBS_TYPE_COLORS[t] || '#666666';
- html += '<span class="type-chip' + (tlTypeFilter === t ? ' active' : '') + '" onclick="setTlTypeFilter(\'' + esc(t) + '\')" style="' + (tlTypeFilter === t ? 'background:' + color + ';border-color:' + color + ';' : 'border-color:' + color + ';color:' + color + ';') + '">' + esc(t.replace(/_/g, ' ')) + ' (' + typeCounts[t] + ')</span>';
+ html += '<span class="type-chip' + (tlTypeFilter === t ? ' active' : '') + '" data-action="timeline-filter" data-type-filter="' + esc(t) + '" style="' + (tlTypeFilter === t ? 'background:' + color + ';border-color:' + color + ';' : 'border-color:' + color + ';color:' + color + ';') + '">' + esc(t.replace(/_/g, ' ')) + ' (' + typeCounts[t] + ')</span>';
});
html += '</div>';
@@ -2175,9 +2175,9 @@
if (totalPages > 1) {
html += '<div class="pagination">';
- if (page > 0) html += '<button class="btn" onclick="tlPage(' + (page - 1) + ')">Prev</button>';
+ if (page > 0) html += '<button class="btn" data-action="timeline-page" data-page="' + (page - 1) + '">Prev</button>';
html += '<span style="color:var(--ink-faint);font-size:12px;padding:6px;font-family:var(--font-mono);">Page ' + (page + 1) + ' of ' + totalPages + ' (' + filtered.length + ' total)</span>';
- if (page < totalPages - 1) html += '<button class="btn" onclick="tlPage(' + (page + 1) + ')">Next</button>';
+ if (page < totalPages - 1) html += '<button class="btn" data-action="timeline-page" data-page="' + (page + 1) + '">Next</button>';
html += '</div>';
}
@@ -2354,7 +2354,7 @@
items.forEach(function(s) {
var statusBadge = s.status === 'active' ? 'badge-green' : s.status === 'completed' ? 'badge-blue' : 'badge-muted';
var selected = state.sessions.selectedId === s.id;
- html += '<div class="session-item' + (selected ? ' selected' : '') + '" onclick="selectSession(\'' + esc(s.id) + '\')">';
+ html += '<div class="session-item' + (selected ? ' selected' : '') + '" data-action="select-session" data-session-id="' + esc(s.id) + '">';
html += '<div class="session-top"><span class="session-project">' + esc(s.project ? s.project.split('/').pop() : 'Unknown') + '</span>';
html += '<span class="badge ' + statusBadge + '">' + esc(s.status) + '</span></div>';
html += '<div class="session-meta">' + esc(s.id.slice(0, 12)) + ' &middot; ' + esc(formatTime(s.startedAt));
@@ -2394,9 +2394,9 @@
html += '<div style="margin-top:16px;display:flex;gap:8px;">';
if (s.status === 'active') {
- html += '<button class="btn btn-danger" onclick="endSession(\'' + esc(s.id) + '\')">End Session</button>';
+ html += '<button class="btn btn-danger" data-action="end-session" data-session-id="' + esc(s.id) + '">End Session</button>';
}
- html += '<button class="btn btn-primary" onclick="summarizeSession(\'' + esc(s.id) + '\')">Summarize</button>';
+ html += '<button class="btn btn-primary" data-action="summarize-session" data-session-id="' + esc(s.id) + '">Summarize</button>';
html += '</div></div>';
panel.innerHTML = html;
}
@@ -2407,8 +2407,8 @@
loadSessions();
}
- async function summarizeSession(id) {
- var btn = event.target;
+ async function summarizeSession(id, btn) {
+ if (!btn) return;
btn.textContent = 'Summarizing...';
btn.disabled = true;
await apiPost('summarize', { sessionId: id });
@@ -2639,7 +2639,7 @@
html += '<span class="badge ' + badgeClass + '">' + esc(a.operation) + '</span>';
html += '<span style="font-size:12px;color:var(--ink-muted);font-family:var(--font-mono);">' + esc(a.functionId || '') + '</span>';
html += '<span style="font-size:10px;color:var(--ink-faint);margin-left:auto;font-family:var(--font-mono);">' + esc(formatTime(a.timestamp)) + '</span>';
- html += '<button class="btn" style="font-size:9px;padding:1px 6px;margin-left:8px;" onclick="toggleAuditDetail(' + idx + ')">&#9660;</button>';
+ html += '<button class="btn" style="font-size:9px;padding:1px 6px;margin-left:8px;" data-action="toggle-audit" data-audit-index="' + idx + '">&#9660;</button>';
html += '</div>';
if (a.targetIds && a.targetIds.length) {
html += '<div style="font-size:10px;color:var(--ink-faint);font-family:var(--font-mono);">' + a.targetIds.length + ' target(s): ' + esc(a.targetIds.slice(0, 3).join(', ')) + (a.targetIds.length > 3 ? '...' : '') + '</div>';
@@ -2876,6 +2876,83 @@
switchTab(e.target.dataset.tab);
}
});
+ document.addEventListener('click', function(e) {
+ if (!(e.target instanceof Element)) return;
+ var target = e.target.closest('[data-action]');
+ if (!target) return;
+ var action = target.getAttribute('data-action');
+ if (!action) return;
+
+ if (action === 'toggle-theme') {
+ toggleTheme();
+ return;
+ }
+ if (action === 'refresh-dashboard') {
+ refreshDashboard();
+ return;
+ }
+ if (action === 'zoom-graph') {
+ zoomGraph(parseInt(target.getAttribute('data-dir') || '0', 10));
+ return;
+ }
+ if (action === 'recenter-graph') {
+ recenterGraph();
+ return;
+ }
+ if (action === 'rebuild-graph') {
+ rebuildGraph();
+ return;
+ }
+ if (action === 'expand-node') {
+ var nodeId = target.getAttribute('data-node-id');
+ if (nodeId) expandNode(nodeId);
+ return;
+ }
+ if (action === 'delete-memory') {
+ deleteMemory(
+ target.getAttribute('data-memory-id') || '',
+ target.getAttribute('data-memory-title') || '',
+ );
+ return;
+ }
+ if (action === 'close-modal') {
+ closeModal();
+ return;
+ }
+ if (action === 'confirm-delete-memory') {
+ var memoryId = target.getAttribute('data-memory-id');
+ if (memoryId) confirmDeleteMemory(memoryId);
+ return;
+ }
+ if (action === 'timeline-filter') {
+ setTlTypeFilter(target.getAttribute('data-type-filter') || '');
+ return;
+ }
+ if (action === 'timeline-page') {
+ var page = parseInt(target.getAttribute('data-page') || '', 10);
+ if (!Number.isNaN(page)) tlPage(page);
+ return;
+ }
+ if (action === 'select-session') {
+ var sessionId = target.getAttribute('data-session-id');
+ if (sessionId) selectSession(sessionId);
+ return;
+ }
+ if (action === 'end-session') {
+ var endSessionId = target.getAttribute('data-session-id');
+ if (endSessionId) endSession(endSessionId);
+ return;
+ }
+ if (action === 'summarize-session') {
+ var summarizeSessionId = target.getAttribute('data-session-id');
+ if (summarizeSessionId) summarizeSession(summarizeSessionId, target);
+ return;
+ }
+ if (action === 'toggle-audit') {
+ var auditIndex = parseInt(target.getAttribute('data-audit-index') || '', 10);
+ if (!Number.isNaN(auditIndex)) toggleAuditDetail(auditIndex);
+ }
+ });
document.getElementById('modal-overlay').addEventListener('click', function(e) {
if (e.target === this) closeModal();
});
diff --git a/src/viewer/server.ts b/src/viewer/server.ts
index 4a6aaba8..1b63d132 100644
--- a/src/viewer/server.ts
+++ b/src/viewer/server.ts
@@ -4,10 +4,7 @@ import {
type IncomingMessage,
type ServerResponse,
} from "node:http";
-import { readFileSync } from "node:fs";
-import { join, dirname } from "node:path";
-import { fileURLToPath } from "node:url";
-import { timingSafeCompare, VIEWER_CSP } from "../auth.js";
+import { renderViewerDocument } from "./document.js";
const ALLOWED_ORIGINS = (
process.env.VIEWER_ALLOWED_ORIGINS ||
@@ -61,14 +58,6 @@ function readBody(req: IncomingMessage): Promise<string> {
});
}
-function checkAuth(req: IncomingMessage, secret: string | undefined): boolean {
- if (!secret) return true;
- const auth = req.headers["authorization"] || "";
- return (
- typeof auth === "string" && timingSafeCompare(auth, `Bearer ${secret}`)
- );
-}
-
export function startViewerServer(
port: number,
_kv: unknown,
@@ -100,36 +89,21 @@ export function startViewerServer(
pathname === "/viewer" ||
pathname === "/agentmemory/viewer")
) {
- const base = dirname(fileURLToPath(import.meta.url));
- const candidates = [
- join(base, "index.html"),
- join(base, "viewer", "index.html"),
- join(base, "..", "viewer", "index.html"),
- join(base, "..", "src", "viewer", "index.html"),
- join(base, "..", "dist", "viewer", "index.html"),
- ];
- for (const p of candidates) {
- try {
- const html = readFileSync(p, "utf-8");
- res.writeHead(200, {
- "Content-Type": "text/html; charset=utf-8",
- "Content-Security-Policy": VIEWER_CSP,
- "Cache-Control": "no-cache",
- });
- res.end(html);
- return;
- } catch {}
+ const rendered = renderViewerDocument();
+ if (rendered.found) {
+ res.writeHead(200, {
+ "Content-Type": "text/html; charset=utf-8",
+ "Content-Security-Policy": rendered.csp,
+ "Cache-Control": "no-cache",
+ });
+ res.end(rendered.html);
+ return;
}
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("viewer not found");
return;
}
- if (!checkAuth(req, secret)) {
- json(res, 401, { error: "unauthorized" }, req);
- return;
- }
-
try {
await proxyToRestApi(resolvedRestPort, pathname, qs, method, req, res, secret);
} catch (err) {
diff --git a/test/integration.test.ts b/test/integration.test.ts
index 9dfbe80f..f224c4a2 100644
--- a/test/integration.test.ts
+++ b/test/integration.test.ts
@@ -226,7 +226,9 @@ describe("agentmemory integration", () => {
describe("viewer", () => {
it("serves the viewer HTML", async () => {
- const res = await fetch(url("/agentmemory/viewer"));
+ const res = await fetch(url("/agentmemory/viewer"), {
+ headers: SECRET ? authHeaders() : undefined,
+ });
expect(res.status).toBe(200);
const body = await res.text();
expect(body).toContain("html");
@@ -260,6 +262,11 @@ describe("agentmemory integration", () => {
});
expect(res.status).toBe(401);
});
+
+ it("rejects unauthenticated viewer requests on the API port", async () => {
+ const res = await fetch(url("/agentmemory/viewer"));
+ expect(res.status).toBe(401);
+ });
}
});
});
diff --git a/test/mesh.test.ts b/test/mesh.test.ts
index 2f65697b..91fc29da 100644
--- a/test/mesh.test.ts
+++ b/test/mesh.test.ts
@@ -180,6 +180,60 @@ describe("Mesh Functions", () => {
});
});
+ describe("mesh-sync", () => {
+ it("requires a configured shared secret", async () => {
+ const regResult = (await sdk.trigger("mem::mesh-register", {
+ url: "https://peer1.example.com",
+ name: "peer-1",
+ })) as { success: boolean; peer: MeshPeer };
+
+ const result = (await sdk.trigger("mem::mesh-sync", {
+ peerId: regResult.peer.id,
+ direction: "push",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("AGENTMEMORY_SECRET");
+ });
+
+ it("sends authorization headers to peers when syncing", async () => {
+ const authedSdk = mockSdk();
+ const authedKv = mockKV();
+ registerMeshFunction(authedSdk as never, authedKv as never, "mesh-secret");
+
+ const fetchMock = vi.fn(async () =>
+ new Response(JSON.stringify({ accepted: 0 }), {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+
+ const regResult = (await authedSdk.trigger("mem::mesh-register", {
+ url: "https://peer2.example.com",
+ name: "peer-2",
+ })) as { success: boolean; peer: MeshPeer };
+
+ const result = (await authedSdk.trigger("mem::mesh-sync", {
+ peerId: regResult.peer.id,
+ direction: "push",
+ })) as { success: boolean; results: Array<{ errors: string[] }> };
+
+ expect(result.success).toBe(true);
+ expect(result.results[0].errors).toEqual([]);
+ expect(fetchMock).toHaveBeenCalledWith(
+ "https://peer2.example.com/agentmemory/mesh/receive",
+ expect.objectContaining({
+ headers: expect.objectContaining({
+ Authorization: "Bearer mesh-secret",
+ }),
+ }),
+ );
+
+ vi.unstubAllGlobals();
+ });
+ });
+
describe("mesh-receive", () => {
it("accepts new memories", async () => {
const mem: Memory = {
diff --git a/test/obsidian-export.test.ts b/test/obsidian-export.test.ts
index 7da338da..fe11caff 100644
--- a/test/obsidian-export.test.ts
+++ b/test/obsidian-export.test.ts
@@ -120,8 +120,10 @@ function makeSession(id: string): Session {
describe("Obsidian Export", () => {
let sdk: ReturnType<typeof mockSdk>;
let kv: ReturnType<typeof mockKV>;
+ const exportRoot = "/tmp/agentmemory-export-root";
beforeEach(() => {
+ process.env.AGENTMEMORY_EXPORT_ROOT = exportRoot;
sdk = mockSdk();
kv = mockKV();
writtenFiles.clear();
@@ -220,15 +222,24 @@ describe("Obsidian Export", () => {
it("respects custom vaultDir", async () => {
await sdk.trigger("mem::obsidian-export", {
- vaultDir: "/tmp/test-vault",
+ vaultDir: "/tmp/agentmemory-export-root/test-vault",
});
const hasCustomPath = [...createdDirs].some((d) =>
- d.startsWith("/tmp/test-vault"),
+ d.startsWith("/tmp/agentmemory-export-root/test-vault"),
);
expect(hasCustomPath).toBe(true);
});
+ it("rejects vaultDir outside the export root", async () => {
+ const result = (await sdk.trigger("mem::obsidian-export", {
+ vaultDir: "/tmp/outside-root",
+ })) as { success: boolean; error: string };
+
+ expect(result.success).toBe(false);
+ expect(result.error).toContain(exportRoot);
+ });
+
it("skips deleted lessons", async () => {
const lesson = makeLesson("lsn_deleted");
(lesson as any).deleted = true;
diff --git a/test/privacy.test.ts b/test/privacy.test.ts
index c3d6e42d..450e2091 100644
--- a/test/privacy.test.ts
+++ b/test/privacy.test.ts
@@ -56,6 +56,26 @@ describe("stripPrivateData", () => {
);
});
+ it("strips OpenAI project keys", () => {
+ expect(
+ stripPrivateData("sk-proj-1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJ"),
+ ).toBe("[REDACTED_SECRET]");
+ });
+
+ it("strips GitHub fine-grained service tokens", () => {
+ expect(
+ stripPrivateData("ghs_1234567890abcdefghijklmnopqrstuvwxyzAB"),
+ ).toBe("[REDACTED_SECRET]");
+ });
+
+ it("strips bearer tokens", () => {
+ expect(
+ stripPrivateData(
+ "Authorization: Bearer sk-proj-1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJ",
+ ),
+ ).toBe("Authorization: [REDACTED_SECRET]");
+ });
+
it("handles multiple secrets in one string", () => {
const input =
"sk-abcdefghijklmnopqrstuv and ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghij";
diff --git a/test/viewer-security.test.ts b/test/viewer-security.test.ts
new file mode 100644
index 00000000..fa0ac4bc
--- /dev/null
+++ b/test/viewer-security.test.ts
@@ -0,0 +1,26 @@
+import { describe, it, expect } from "vitest";
+import { renderViewerDocument } from "../src/viewer/document.js";
+
+describe("viewer document security", () => {
+ it("serves a nonce-backed CSP without unsafe-inline script execution", () => {
+ const rendered = renderViewerDocument();
+ expect(rendered.found).toBe(true);
+ if (!rendered.found) return;
+
+ expect(rendered.csp).toContain("script-src 'nonce-");
+ expect(rendered.csp).toContain("script-src-attr 'none'");
+ expect(rendered.csp).not.toContain("script-src 'unsafe-inline'");
+ expect(rendered.html).toContain("<script nonce=\"");
+ expect(rendered.html).not.toContain("__AGENTMEMORY_VIEWER_NONCE__");
+ });
+
+ it("does not contain inline DOM event handlers", () => {
+ const rendered = renderViewerDocument();
+ expect(rendered.found).toBe(true);
+ if (!rendered.found) return;
+
+ expect(rendered.html).not.toContain("onclick=");
+ expect(rendered.html).not.toContain("onmouseover=");
+ expect(rendered.html).not.toContain("onmouseout=");
+ });
+});