Skip to content

Self-hosted MCP server + dashboard giving Claude Code, Cursor & Hermes agents shared long-term memory over a git-backed markdown vault. Agent-native, Obsidian-compatible second brain — markdown RAG, no vector DB.

fix(security): a read-only token could read any file on the host (#6)

Ronalds Palacisfeb62a0c3f87
diff --git a/README.md b/README.md
index afb0e11..61975ee 100644
--- a/README.md
+++ b/README.md
@@ -14,6 +14,10 @@
<p align="center"><sub><a href="https://github.com/rwnalds/engram/blob/main/assets/demo.mp4">▶ Watch the full-length video</a> (real-time, full quality)</sub></p>
+<p align="center">
+ <a href="https://www.producthunt.com/products/engram-3?embed=true&amp;utm_source=badge-featured&amp;utm_medium=badge&amp;utm_campaign=badge-engram-4cb7e488-c380-4fa7-a2c7-0129b971c90e" target="_blank" rel="noopener noreferrer"><img alt="Engram - Agent memory that knows what's still true | Product Hunt" width="250" height="54" src="https://api.producthunt.com/widgets/embed-image/v1/featured.svg?post_id=1202294&amp;theme=light&amp;t=1784627191540"></a>
+</p>
+
---
Engram is a self-hosted **MCP server + dashboard** that gives Claude Code, Cursor, Hermes, and any
diff --git a/bun.lock b/bun.lock
index 893d583..9818824 100644
--- a/bun.lock
+++ b/bun.lock
@@ -24,6 +24,7 @@
"react-dom": "19.2.4",
"react-markdown": "^9.0.1",
"rehype-raw": "^7.0.0",
+ "rehype-sanitize": "^6.0.0",
"remark-gfm": "^4.0.0",
"shadcn": "^4.10.0",
"simple-git": "^3.27.0",
@@ -965,6 +966,8 @@
"hast-util-raw": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "@ungap/structured-clone": "^1.0.0", "hast-util-from-parse5": "^8.0.0", "hast-util-to-parse5": "^8.0.0", "html-void-elements": "^3.0.0", "mdast-util-to-hast": "^13.0.0", "parse5": "^7.0.0", "unist-util-position": "^5.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0", "web-namespaces": "^2.0.0", "zwitch": "^2.0.0" } }, "sha512-Y8/SBAHkZGoNkpzqqfCldijcuUKh7/su31kEBp67cFY09Wy0mTRgtsLYsiIxMJxlu0f6AA5SUTbDR8K0rxnbUw=="],
+ "hast-util-sanitize": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "@ungap/structured-clone": "^1.0.0", "unist-util-position": "^5.0.0" } }, "sha512-3yTWghByc50aGS7JlGhk61SPenfE/p1oaFeNwkOOyrscaOkMGrcW9+Cy/QAIOBpZxP1yqDIzFMR0+Np0i0+usg=="],
+
"hast-util-to-jsx-runtime": ["[email protected]", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "comma-separated-tokens": "^2.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "hast-util-whitespace": "^3.0.0", "mdast-util-mdx-expression": "^2.0.0", "mdast-util-mdx-jsx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "style-to-js": "^1.0.0", "unist-util-position": "^5.0.0", "vfile-message": "^4.0.0" } }, "sha512-zl6s8LwNyo1P9uw+XJGvZtdFF1GdAkOg8ujOw+4Pyb76874fLps4ueHXDhXWdk6YHQ6OgUtinliG7RsYvCbbBg=="],
"hast-util-to-parse5": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "comma-separated-tokens": "^2.0.0", "devlop": "^1.0.0", "property-information": "^7.0.0", "space-separated-tokens": "^2.0.0", "web-namespaces": "^2.0.0", "zwitch": "^2.0.0" } }, "sha512-MlWT6Pjt4CG9lFCjiz4BH7l9wmrMkfkJYCxFwKQic8+RTZgWPuWxwAfjJElsXkex7DJjfSJsQIt931ilUgmwdA=="],
@@ -1439,6 +1442,8 @@
"rehype-raw": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-raw": "^9.0.0", "vfile": "^6.0.0" } }, "sha512-/aE8hCfKlQeA8LmyeyQvQF3eBiLRGNlfBJEvWH7ivp9sBqs7TNqBL5X3v157rM4IFETqDnIOO+z5M/biZbo9Ww=="],
+ "rehype-sanitize": ["[email protected]", "", { "dependencies": { "@types/hast": "^3.0.0", "hast-util-sanitize": "^5.0.0" } }, "sha512-CsnhKNsyI8Tub6L4sm5ZFsme4puGfc6pYylvXo1AeqaGbjOYyzNv3qZPwvs0oMJ39eryyeOdmxwUIo94IpEhqg=="],
+
"remark-gfm": ["[email protected]", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-gfm": "^3.0.0", "micromark-extension-gfm": "^3.0.0", "remark-parse": "^11.0.0", "remark-stringify": "^11.0.0", "unified": "^11.0.0" } }, "sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg=="],
"remark-parse": ["[email protected]", "", { "dependencies": { "@types/mdast": "^4.0.0", "mdast-util-from-markdown": "^2.0.0", "micromark-util-types": "^2.0.0", "unified": "^11.0.0" } }, "sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA=="],
diff --git a/components/markdown.tsx b/components/markdown.tsx
index 09e827d..6de8951 100644
--- a/components/markdown.tsx
+++ b/components/markdown.tsx
@@ -1,11 +1,54 @@
"use client";
-import ReactMarkdown from "react-markdown";
+import ReactMarkdown, { defaultUrlTransform } from "react-markdown";
import remarkGfm from "remark-gfm";
import rehypeRaw from "rehype-raw";
+import rehypeSanitize, { defaultSchema } from "rehype-sanitize";
import { useRouter } from "next/navigation";
import { preprocessWikilinks, remarkCallouts, wikilinkStem } from "@/lib/markdown";
+/**
+ * Note bodies are rendered with rehypeRaw so Obsidian notes keep their inline HTML. That means
+ * whatever is in a note reaches the DOM — and notes are written by agents and teammates, not
+ * only by you. Without a sanitizer, anyone who can write a note can land `<script>` or
+ * `<img onerror=...>` in every reader's browser. Stored XSS, delivered by your own vault.
+ *
+ * So: rehypeRaw parses the HTML, then rehypeSanitize strips anything dangerous. Order matters —
+ * sanitize has to run after raw, or it inspects a tree that doesn't contain the HTML yet.
+ *
+ * The schema is the library default plus exactly what this renderer needs:
+ * - `className` / `data-callout` on the elements remarkCallouts emits, so callouts still style
+ * - the `wikilink:` href protocol, which the custom `a` component below resolves
+ */
+const schema = {
+ ...defaultSchema,
+ attributes: {
+ ...defaultSchema.attributes,
+ div: [...(defaultSchema.attributes?.div ?? []), "className", "dataCallout"],
+ blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "className", "dataCallout"],
+ span: [...(defaultSchema.attributes?.span ?? []), "className"],
+ p: [...(defaultSchema.attributes?.p ?? []), "className"],
+ a: [...(defaultSchema.attributes?.a ?? []), "className"],
+ code: [...(defaultSchema.attributes?.code ?? []), "className"],
+ },
+ protocols: {
+ ...defaultSchema.protocols,
+ href: [...(defaultSchema.protocols?.href ?? []), "wikilink"],
+ },
+};
+
+/**
+ * Let `wikilink:` through; defer to react-markdown for everything else.
+ *
+ * react-markdown's defaultUrlTransform blanks any scheme outside http/https/mailto/tel, which
+ * silently emptied every `[[wikilink]]` href — the `.wikilink` styles and the click-to-navigate
+ * branch below had never actually run. Keeping the default for all other URLs means the
+ * javascript:/data: protections stay exactly as they were.
+ */
+function urlTransform(url: string): string {
+ return url.startsWith("wikilink:") ? url : defaultUrlTransform(url);
+}
+
export function Markdown({
content,
resolve,
@@ -20,7 +63,8 @@ export function Markdown({
<div className="prose">
<ReactMarkdown
remarkPlugins={[remarkGfm, remarkCallouts]}
- rehypePlugins={[rehypeRaw]}
+ rehypePlugins={[rehypeRaw, [rehypeSanitize, schema]]}
+ urlTransform={urlTransform}
components={{
a({ href, children, ...props }) {
if (href?.startsWith("wikilink:")) {
diff --git a/lib/vault/paths.test.ts b/lib/vault/paths.test.ts
new file mode 100644
index 0000000..7f31ed8
--- /dev/null
+++ b/lib/vault/paths.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, test } from "bun:test";
+import path from "node:path";
+import { resolveInVault, tryResolveInVault } from "./paths";
+
+/**
+ * Regression tests for the read-path traversal.
+ *
+ * `getNote` joined the caller's path onto the vault dir with no escape check, and `brain_read`
+ * passes its argument straight through — so a READ-scoped token could read any file the process
+ * could, including /proc/self/environ. These pin the guard that closed it.
+ */
+
+const VAULT = "/srv/vault";
+
+describe("resolveInVault", () => {
+ test("resolves an ordinary note", () => {
+ expect(resolveInVault(VAULT, "docs/pricing.md")).toBe(path.join(VAULT, "docs/pricing.md"));
+ });
+
+ test("allows the vault root itself", () => {
+ expect(resolveInVault(VAULT, ".")).toBe(VAULT);
+ });
+
+ test("refuses a parent-directory escape", () => {
+ expect(() => resolveInVault(VAULT, "../secrets.txt")).toThrow(/escapes the vault/);
+ });
+
+ test("refuses a deep escape — the /etc/passwd case", () => {
+ expect(() => resolveInVault(VAULT, "../../../../../../etc/passwd")).toThrow(/escapes the vault/);
+ });
+
+ test("refuses an escape hidden mid-path", () => {
+ expect(() => resolveInVault(VAULT, "docs/../../etc/passwd")).toThrow(/escapes the vault/);
+ });
+
+ test("refuses /proc/self/environ — the credential-leak path", () => {
+ expect(() => resolveInVault(VAULT, "../../../proc/self/environ")).toThrow(/escapes the vault/);
+ });
+
+ test("refuses a sibling directory that merely shares a name prefix", () => {
+ // /srv/vault-backup must not pass a naive startsWith(root) check.
+ expect(() => resolveInVault(VAULT, "../vault-backup/notes.md")).toThrow(/escapes the vault/);
+ });
+
+ test("an absolute path is contained, not honoured", () => {
+ // path.resolve would escape on a truly absolute arg, so the guard has to catch it.
+ expect(() => resolveInVault(VAULT, "/etc/passwd")).toThrow(/escapes the vault/);
+ });
+
+ test("a note whose name merely contains dots is fine", () => {
+ expect(resolveInVault(VAULT, "docs/v1.2.3-notes.md")).toBe(path.join(VAULT, "docs/v1.2.3-notes.md"));
+ });
+});
+
+describe("tryResolveInVault", () => {
+ test("returns the path when safe", () => {
+ expect(tryResolveInVault(VAULT, "a.md")).toBe(path.join(VAULT, "a.md"));
+ });
+
+ test("returns null instead of throwing on an escape", () => {
+ expect(tryResolveInVault(VAULT, "../../etc/passwd")).toBeNull();
+ });
+});
diff --git a/lib/vault/paths.ts b/lib/vault/paths.ts
new file mode 100644
index 0000000..2025755
--- /dev/null
+++ b/lib/vault/paths.ts
@@ -0,0 +1,34 @@
+import path from "node:path";
+
+/**
+ * Resolve a vault-relative path to an absolute one, refusing anything that escapes the vault.
+ *
+ * The write path has always had this guard. The read path did not, and `getNote` takes its
+ * argument straight from `brain_read` — so `brain_read({ path: "../../../../etc/passwd" })`
+ * read whatever the process could read. `brain_read` is a READ-scoped tool, which made this
+ * reachable with a read-only token: the exact token you hand an agent you don't fully trust,
+ * and the one the README promises is safe. On a deployed instance the reachable set included
+ * /proc/self/environ (AUTH_SECRET, OAuth client secrets, the Anthropic key) and the token
+ * hashes under ENGRAM_DATA_DIR.
+ *
+ * Every filesystem access derived from caller input goes through here. `path.resolve` collapses
+ * `..` before the check, so no traversal survives it, and the prefix test uses path.sep to avoid
+ * matching a sibling directory that merely shares a name prefix (`/vault-backup` vs `/vault`).
+ */
+export function resolveInVault(vaultDir: string, relPath: string): string {
+ const root = path.resolve(vaultDir);
+ const abs = path.resolve(root, relPath);
+ if (abs !== root && !abs.startsWith(root + path.sep)) {
+ throw new Error(`path escapes the vault: ${relPath}`);
+ }
+ return abs;
+}
+
+/** Non-throwing variant for read paths that already return null on a miss. */
+export function tryResolveInVault(vaultDir: string, relPath: string): string | null {
+ try {
+ return resolveInVault(vaultDir, relPath);
+ } catch {
+ return null;
+ }
+}
diff --git a/lib/vault/store.ts b/lib/vault/store.ts
index b55b01b..42a4f5f 100644
--- a/lib/vault/store.ts
+++ b/lib/vault/store.ts
@@ -7,6 +7,7 @@ import { activeVaultDir } from "@/lib/repos";
import { scanVault } from "./scan";
import { parseNote, stemOf } from "./parse";
import { authorityOf, authorityRules, isArchivedPath, isUnrecognizedStatus, overlayValidity, weightOf, type Authority } from "./authority";
+import { tryResolveInVault } from "./paths";
import type { Graph, GraphEdge, GraphNode, Note, NoteMeta, TreeNode } from "./types";
interface IndexDoc {
@@ -294,7 +295,9 @@ export function listRecent(sinceMs?: number, limit = 20): NoteMeta[] {
export function getNote(relPath: string): Note | null {
const s = ensure();
- const abs = path.join(s.dir, relPath);
+ // Caller-controlled (brain_read, the dashboard note route) — must not escape the vault.
+ const abs = tryResolveInVault(s.dir, relPath);
+ if (!abs) return null;
let raw: string;
try {
raw = fs.readFileSync(abs, "utf8");
@@ -578,7 +581,9 @@ export function getTree(): TreeNode {
/** Read a top-level meta file (SCHEMA.md / INDEX.md) from the active vault, or null. */
export function readVaultFile(name: string): string | null {
try {
- return fs.readFileSync(path.join(activeVaultDir(), name), "utf8");
+ const abs = tryResolveInVault(activeVaultDir(), name);
+ if (!abs) return null;
+ return fs.readFileSync(abs, "utf8");
} catch {
return null;
}
diff --git a/lib/vault/write.ts b/lib/vault/write.ts
index 2157563..0180a8a 100644
--- a/lib/vault/write.ts
+++ b/lib/vault/write.ts
@@ -6,15 +6,13 @@ import { refreshPaths, getNote } from "./store";
import { humanize, stemOf } from "./parse";
import { checkFrontmatter, frontmatterErrorMessage } from "./validate";
import { guardConflict } from "./conflict";
+import { resolveInVault } from "./paths";
import { requestSync } from "@/lib/git";
import { currentActor } from "@/lib/actor";
/** Resolve a vault-relative path to an absolute path in the active vault, refusing escapes. */
function safeAbs(relPath: string): string {
- const root = path.resolve(activeVaultDir());
- const abs = path.resolve(root, relPath);
- if (abs !== root && !abs.startsWith(root + path.sep)) throw new Error("path escapes the vault");
- return abs;
+ return resolveInVault(activeVaultDir(), relPath);
}
export function normalizeNotePath(relPath: string): string {
diff --git a/package.json b/package.json
index 5d79a5e..f362998 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "engram",
- "version": "0.1.1",
+ "version": "0.1.2",
"private": true,
"author": "rwnalds",
"homepage": "https://github.com/rwnalds/engram#readme",
@@ -64,6 +64,7 @@
"react-dom": "19.2.4",
"react-markdown": "^9.0.1",
"rehype-raw": "^7.0.0",
+ "rehype-sanitize": "^6.0.0",
"remark-gfm": "^4.0.0",
"shadcn": "^4.10.0",
"simple-git": "^3.27.0",
diff --git a/server.json b/server.json
index 4613086..f3f16af 100644
--- a/server.json
+++ b/server.json
@@ -3,7 +3,7 @@
"name": "io.github.rwnalds/engram",
"title": "Engram",
"description": "Git-backed markdown memory for AI agents; search hides superseded and archived notes.",
- "version": "0.1.1",
+ "version": "0.1.2",
"repository": {
"url": "https://github.com/rwnalds/engram",
"source": "github"
@@ -12,7 +12,7 @@
"packages": [
{
"registryType": "oci",
- "identifier": "ghcr.io/rwnalds/engram:0.1.1",
+ "identifier": "ghcr.io/rwnalds/engram:0.1.2",
"transport": {
"type": "stdio"
},