Skip to content

A self-organizing Obsidian vault that gives AI coding agents persistent memory.

fix: never-expose withheld only the spelling you typed (#185)

Brenno Ferrari633c36fe60b0
diff --git a/.claude/scripts/lib/mcp-exposure.ts b/.claude/scripts/lib/mcp-exposure.ts
index 1e289f2..fc5d15a 100644
--- a/.claude/scripts/lib/mcp-exposure.ts
+++ b/.claude/scripts/lib/mcp-exposure.ts
@@ -95,6 +95,39 @@ function cleanRoots(value: unknown): string[] {
return [...new Set(out)];
}
+/**
+ * Is this path's filename withheld by name, whatever folder it sits in?
+ *
+ * Compares case-insensitively on BOTH sides, and does so here rather than
+ * relying on the set having been lowercased when it was built. That
+ * distinction is the whole fix: the admit side (`isExposedPath`,
+ * `matchedRoot`) has always lowercased, the withhold side was exact-case, and
+ * on any case-insensitive filesystem the asymmetry served the file. With
+ * `mcp_never_expose: ["SOUL.md"]`, `brain/SOUL.md` was refused and
+ * `brain/soul.md` returned 44KB — the listing withheld it while the reader
+ * served it, which is the two-surfaces-disagree defect this module exists to
+ * prevent, inverted. `realpathSync` on Windows does not canonicalise case, so
+ * the post-realpath re-check saw the caller's spelling too.
+ *
+ * Normalising only in `resolveExposure` would leave a policy built any other
+ * way failing OPEN — and every test builds one by hand. A guard whose
+ * correctness depends on its constructor is the same split invariant in a new
+ * place, so the comparison owns it. The set holds at most a handful of names,
+ * so the scan is free.
+ *
+ * Separators are normalised before the basename is taken: a URI or marker can
+ * arrive with backslashes, and `basename("brain\\SOUL.md")` on POSIX returns
+ * the whole string rather than the filename.
+ */
+export function isNeverExposed(policy: ExposurePolicy, path: string): boolean {
+ const name = basename(String(path).replace(/\\/g, "/")).toLowerCase();
+ if (!name) return false;
+ for (const entry of policy.neverExpose) {
+ if (entry.toLowerCase() === name) return true;
+ }
+ return false;
+}
+
/**
* Memories are never served as ordinary notes, whatever the config says. They
* carry their own declared scope, evaluated per caller; reaching them through
@@ -130,9 +163,12 @@ export function resolveExposure(
memoryRoot = "memories",
): ExposurePolicy {
// Filenames, not folder names — spaces and dots are legitimate here.
+ // Lowercased on the way in as well, though `isNeverExposed` no longer relies
+ // on it: the comparison owns the case rule, so a policy built any other way
+ // cannot fail open. See that function for what the asymmetry cost.
const never = new Set(
Array.isArray(manifest?.mcp_never_expose)
- ? manifest.mcp_never_expose.filter((s): s is string => typeof s === "string")
+ ? manifest.mcp_never_expose.filter((s): s is string => typeof s === "string").map((s) => s.toLowerCase())
: [],
);
@@ -265,7 +301,7 @@ export function visibleFiles(vaultRoot: string, policy: ExposurePolicy): Visible
continue;
}
if (!f.endsWith(".md")) continue;
- if (policy.neverExpose.has(f)) continue;
+ if (isNeverExposed(policy, f)) continue;
if (isPrivate(full)) continue;
files.push({ full, label: basename(f, ".md"), scope });
}
@@ -340,27 +376,24 @@ export function vaultRelKeyRaw(vaultRoot: string, full: string): string {
* as not-found — to this server a URI it does not serve is simply not a
* resource.
*
- * `collection` is optional, and exists because a path a caller reads out of a
- * `search` result is not a path this resolver would otherwise accept. qmd reports
- * paths **prefixed with the collection name** and with **spaces replaced by
- * dashes**, in directory names as well as filenames. So a note at
- * `projects/notes/2026-01-02 Some Title.md` comes back as
- * `myvault/projects/notes/2026-01-02-Some-Title.md`, and pasting that into a
- * resource URI produced a bare not-found the caller had no way to diagnose.
- * `expand` already tolerated the prefix, which left this the only surface
- * rejecting the form the server's own search hands out.
- *
- * Three tiers, each ending in the same strict resolver, so exposure, traversal,
- * extension, never-expose and realpath containment are re-run on whatever comes
- * out. Nothing is loosened; only the spelling is repaired.
+ * `collection` is optional and exists for one measured reason: `search` reports
+ * qmd's COLLECTION-PREFIXED paths (`vigil-mind/projects/x.md`), so a caller that
+ * pastes one straight into a resource URI gets a not-found it cannot diagnose.
+ * That happened on vigia's first session, which burned a round trip guessing the
+ * right form. `expand` already tolerated the prefix, leaving this the only
+ * surface that rejected what the server's own search hands out. When supplied,
+ * an exactly-matching leading segment is dropped and resolution is retried ONCE
+ * against the remainder — which then runs every check below unchanged, so
+ * exposure, traversal, extension, never-expose and realpath containment all
+ * still apply. Nothing is loosened.
*
* RETURNS A REALPATH. Every other path in this module is built by joining the
* unresolved vault root, so a caller stripping a vault-root prefix from THIS
* return value must strip with the RESOLVED root. On macOS `/var` is
* `/private/var`, the prefix does not match, and `vaultRelKeyRaw` hands back an
- * absolute filesystem path rather than a relative one — which is how a local
- * path reached a `vault://note/...` URI during this change. Caught by macOS CI;
- * it cannot reproduce on Windows or Linux.
+ * absolute filesystem path instead of a relative one — which is how a local path
+ * reached a `vault://note/...` URI. Found by macOS CI; it cannot reproduce on
+ * Windows or Linux.
*/
export function resolveResourceUri(
vaultRoot: string,
@@ -382,7 +415,9 @@ export function resolveResourceUri(
}
}
- // Tier 3: de-slugify against the real tree.
+ // Tier 3: de-slugify. qmd reports paths with spaces replaced by dashes, in
+ // directory names as well as filenames, so a path copied from a search result
+ // names a file that does not exist. Map it back by walking the real tree.
const m = bare.match(/^vault:\/\/note\/(.+)$/);
if (!m?.[1]) return null;
let slug: string;
@@ -398,21 +433,19 @@ export function resolveResourceUri(
const real = unslugPath(vaultRoot, slug);
if (!real) return null;
- return resolveExactResourceUri(
- vaultRoot,
- policy,
- `vault://note/${real.split("/").map(encodeURIComponent).join("/")}`,
- );
+ // Re-enter the strict resolver so the recovered path is policy-checked like
+ // any other. Nothing here grants access; it only repairs the spelling.
+ return resolveExactResourceUri(vaultRoot, policy, `vault://note/${real.split("/").map(encodeURIComponent).join("/")}`);
}
/**
- * Walk `slug` against the real tree, accepting a segment whose spaces became
- * dashes. Returns the true vault-relative path, or null.
+ * Walk `slug` against the real tree, accepting a segment whose spaces were
+ * replaced by dashes. Returns the true vault-relative path, or null.
*
- * Refuses when a segment is AMBIGUOUS. If both `A B.md` and `A-B.md` exist, the
+ * Refuses when a segment is AMBIGUOUS — if both `A B.md` and `A-B.md` exist, the
* slug `A-B.md` cannot say which was meant, and guessing would silently serve
- * the wrong note — worse than a not-found. Bounded work: one `readdir` per
- * segment, and only after exact resolution has already failed.
+ * the wrong note. Bounded: one readdir per segment, and it only runs after exact
+ * resolution has already failed.
*/
function unslugPath(vaultRoot: string, slug: string): string | null {
const parts = slug.split("/").filter(Boolean);
@@ -433,7 +466,7 @@ function unslugPath(vaultRoot: string, slug: string): string | null {
return acc;
}
-/** The strict resolver. `resolveResourceUri` is this plus two repair attempts. */
+/** The strict resolver. `resolveResourceUri` is this plus one prefix retry. */
function resolveExactResourceUri(vaultRoot: string, policy: ExposurePolicy, uri: string): string | null {
const m = String(uri).match(/^vault:\/\/note\/(.+)$/);
if (!m?.[1]) return null;
@@ -452,7 +485,9 @@ function resolveExactResourceUri(vaultRoot: string, policy: ExposurePolicy, uri:
if (rel.includes("..") || rel.startsWith("/") || /^[A-Za-z]:/.test(rel)) return null;
if (!rel.toLowerCase().endsWith(".md")) return null;
if (!isExposedPath(policy, rel)) return null;
- if (policy.neverExpose.has(basename(rel))) return null;
+ // Separators normalised before taking the basename: `brain\SOUL.md` must
+ // yield `soul.md`, not the whole string.
+ if (isNeverExposed(policy, rel)) return null;
// Containment must survive SYMLINKS, not just `..`. `resolve` collapses dot
// segments but happily returns a path whose real target is outside the vault,
@@ -473,7 +508,7 @@ function resolveExactResourceUri(vaultRoot: string, policy: ExposurePolicy, uri:
return null; // missing, or a broken link
}
if (full !== rootReal && !full.startsWith(rootReal + sep)) return null;
- if (policy.neverExpose.has(basename(full))) return null;
+ if (isNeverExposed(policy, full)) return null;
if (isPrivate(full)) return null;
return full;
}
diff --git a/.claude/scripts/tests/mcp-exposure.test.ts b/.claude/scripts/tests/mcp-exposure.test.ts
index 2e232f3..5f52726 100644
--- a/.claude/scripts/tests/mcp-exposure.test.ts
+++ b/.claude/scripts/tests/mcp-exposure.test.ts
@@ -26,7 +26,9 @@ import {
listResources,
resolveResourceUri,
vaultRelKeyRaw,
+ isNeverExposed,
} from "../lib/mcp-exposure.ts";
+import type { ExposurePolicy } from "../lib/mcp-exposure.ts";
import { vaultRelKey } from "../lib/mcp-qmd-client.ts";
const NOTE = (desc = "a note") => `---\ndate: 2026-07-26\ndescription: "${desc}"\n---\n\n# n\n\nbody\n`;
@@ -161,8 +163,70 @@ describe("resolving the policy", () => {
test("never-expose keeps filenames with spaces and dots, which the root rule would reject", () => {
withVault((dir) => {
const p = resolveExposure(dir, { mcp_never_expose: ["North Star.md", "SOUL.md"] });
- assert.ok(p.neverExpose.has("North Star.md"));
- assert.ok(p.neverExpose.has("SOUL.md"));
+ // Asserted through the predicate rather than on the set's own spelling:
+ // the set's internal case is an implementation detail, and a test that
+ // pins it breaks on the very normalisation that closes the bypass below.
+ assert.ok(isNeverExposed(p, "brain/North Star.md"));
+ assert.ok(isNeverExposed(p, "brain/SOUL.md"));
+ });
+ });
+
+ /**
+ * The bypass, and the shape of it.
+ *
+ * The admit side has always compared case-insensitively; the withhold side
+ * was exact-case. On any case-insensitive filesystem that asymmetry served
+ * the file: `mcp_never_expose: ["SOUL.md"]` refused `brain/SOUL.md` and
+ * returned 44KB for `brain/soul.md`. The listing withheld it while the reader
+ * served it — the two-surfaces-disagree defect, inverted — and `realpathSync`
+ * on Windows does not canonicalise case, so the post-realpath re-check saw
+ * the caller's spelling too.
+ */
+ test("never-expose withholds every case spelling, not the one that was typed", () => {
+ withVault((dir) => {
+ const p = resolveExposure(dir, { mcp_never_expose: ["SOUL.md"] });
+ for (const spelling of ["SOUL.md", "soul.md", "Soul.md", "SoUl.MD", "sOuL.Md"]) {
+ assert.ok(isNeverExposed(p, `brain/${spelling}`), spelling);
+ }
+ });
+ });
+
+ test("never-expose does not depend on how the policy was constructed", () => {
+ // Every test — and any caller assembling one by hand — builds a policy
+ // literal. Normalising only in `resolveExposure` would leave those failing
+ // OPEN, which is the same split invariant the bypass came from.
+ const handBuilt: ExposurePolicy = {
+ roots: ["brain"],
+ neverExpose: new Set(["SOUL.md"]),
+ source: "manifest",
+ memoryRoot: "memories",
+ };
+ assert.ok(isNeverExposed(handBuilt, "brain/soul.md"));
+ assert.ok(isNeverExposed(handBuilt, "brain/SOUL.md"));
+ });
+
+ /**
+ * PLATFORM-DEPENDENT, and worth saying so rather than letting it read as
+ * universal coverage. On Windows `path.basename` is the win32 implementation
+ * and already splits backslashes, so this assertion passes with or without
+ * the normalisation — mutation-checked, and the mutant survives here. It has
+ * teeth only on POSIX, where a backslash is an ordinary filename character
+ * and `basename("brain\\SOUL.md")` returns the whole string. Linux CI is what
+ * enforces it.
+ */
+ test("never-expose normalises separators before taking the basename", () => {
+ withVault((dir) => {
+ const p = resolveExposure(dir, { mcp_never_expose: ["SOUL.md"] });
+ assert.ok(isNeverExposed(p, String.raw`brain\SOUL.md`), "a backslash path must still yield the filename");
+ });
+ });
+
+ test("a path that is not withheld stays servable", () => {
+ withVault((dir) => {
+ const p = resolveExposure(dir, { mcp_never_expose: ["SOUL.md"] });
+ assert.ok(!isNeverExposed(p, "brain/Gotchas.md"));
+ assert.ok(!isNeverExposed(p, "brain/SOULFUL.md"), "a prefix is not a match");
+ assert.ok(!isNeverExposed(p, ""));
});
});
@@ -404,13 +468,18 @@ describe("resolving a resource URI", () => {
});
});
- // qmd reports paths PREFIXED with the collection name and with spaces replaced
- // by dashes, in directory names as well as filenames. So a path read out of a
- // `search` result names a file that does not exist, and pasting it into a
- // resource URI produced a bare not-found. Both repairs re-enter the strict
- // resolver, so these also pin that nothing was loosened.
+ test("a URI naming an out-of-scope note is refused even though it is well-formed", () => {
+ withVault((dir) => {
+ stocked(dir);
+ const policy = resolveExposure(dir, { mcp_exposed_roots: ["brain"] });
+ assert.equal(resolveResourceUri(dir, policy, "vault://note/work/1-1/Sarah.md"), null);
+ });
+ });
- test("a collection-prefixed URI resolves once the collection is known", () => {
+ // `search` reports qmd's collection-prefixed paths, so a caller that pastes one
+ // into a resource URI used to get an undiagnosable not-found. Observed for real
+ // on vigia's first session, which burned a round trip guessing the right form.
+ test("a collection-prefixed URI resolves when the collection is supplied", () => {
withVault((dir) => {
stocked(dir);
const policy = resolveExposure(dir, { mcp_exposed_roots: ["brain"] });
@@ -421,20 +490,24 @@ describe("resolving a resource URI", () => {
assert.equal(
resolveResourceUri(dir, policy, prefixed, "myvault"),
resolveResourceUri(dir, policy, uri),
- "same file once the collection is known",
+ "resolves to the same file once the collection is known",
);
});
});
- test("a slugified path resolves back to the real file, directory names included", () => {
+ // The prefix was only half of it. qmd replaces spaces with dashes in directory
+ // names as well as filenames, so a path copied out of a search result names a
+ // file that does not exist. This is what actually denied vigia's first read.
+ test("a slugified path resolves back to the real file, directories included", () => {
withVault((dir) => {
stocked(dir);
- put(dir, "reference/Deep Folder/A Long Note.md", NOTE("the real one"));
+ put(dir, "reference/Deep Folder/A Long Note.md", NOTE("real one"));
const policy = resolveExposure(dir, { mcp_exposed_roots: ["brain", "reference"] });
const truth = resolveResourceUri(dir, policy, "vault://note/reference/Deep Folder/A Long Note.md");
assert.ok(truth, "sanity: the true path resolves");
+ // Slug in the filename, slug in the directory, and both behind the prefix.
for (const uri of [
"vault://note/reference/Deep Folder/A-Long-Note.md",
"vault://note/reference/Deep-Folder/A-Long-Note.md",
@@ -447,12 +520,13 @@ describe("resolving a resource URI", () => {
test("an ambiguous slug is refused rather than guessed", () => {
withVault((dir) => {
- // Two sibling directories that slugify to the same thing, with the note in
- // only one. The exact path cannot resolve, so repair runs and finds the
- // segment matches both. Serving a note from a directory the caller did not
- // name would be worse than a not-found.
+ // Two sibling directories that slugify to the same thing, with the note
+ // present in only one. The exact path cannot resolve (the file is not in
+ // `Deep-Folder`), so repair runs and finds the segment matches both.
+ // Guessing would silently serve a note from a directory the caller did
+ // not name, so it refuses.
put(dir, "reference/Deep Folder/A Long Note.md", NOTE("the real one"));
- put(dir, "reference/Deep-Folder/Other Note.md", NOTE("a decoy"));
+ put(dir, "reference/Deep-Folder/Something Else.md", NOTE("a decoy"));
const policy = resolveExposure(dir, { mcp_exposed_roots: ["reference"] });
assert.equal(
@@ -460,47 +534,51 @@ describe("resolving a resource URI", () => {
null,
"ambiguous directory segment must not be guessed",
);
+ // Unambiguous still works, so the guard has not disabled repair.
assert.ok(
resolveResourceUri(dir, policy, "vault://note/reference/Deep Folder/A-Long-Note.md", "myvault"),
- "unambiguous repair still works",
);
});
});
- test("repair loosens nothing: scope, traversal and never-expose still decide", () => {
+ test("de-slugging loosens nothing: an out-of-scope note stays out of scope", () => {
withVault((dir) => {
stocked(dir);
- put(dir, "work/1-1/Some Person.md", NOTE("a 1:1 note"));
+ put(dir, "work/1-1/Sarah Jones.md", NOTE("a 1:1 note"));
const policy = resolveExposure(dir, { mcp_exposed_roots: ["brain"] });
-
for (const uri of [
- // out of scope, reached by slug and by prefix
- "vault://note/work/1-1/Some-Person.md",
- "vault://note/myvault/work/1-1/Some-Person.md",
- "vault://note/myvault/work/1-1/Some Person.md",
- // traversal, behind both repairs
- "vault://note/myvault/brain/../work/1-1/Some-Person.md",
- // only the exact collection name is stripped, and only once
- "vault://note/other/brain/Gotchas.md",
- "vault://note/myvault/myvault/brain/Gotchas.md",
+ "vault://note/work/1-1/Sarah-Jones.md",
+ "vault://note/myvault/work/1-1/Sarah-Jones.md",
+ "vault://note/myvault/brain/../work/1-1/Sarah-Jones.md",
]) {
assert.equal(resolveResourceUri(dir, policy, uri, "myvault"), null, uri);
}
-
- // A never-expose note stays refused when reached by its slug.
- assert.equal(
- resolveResourceUri(dir, policy, "vault://note/brain/Private-Thing.md", "myvault"),
- null,
- "private note refused via slug",
- );
+ // A never-expose note is still refused when reached by its slug.
+ assert.equal(resolveResourceUri(dir, policy, "vault://note/brain/Private-Thing.md", "myvault"), null);
});
});
- test("a URI naming an out-of-scope note is refused even though it is well-formed", () => {
+ test("the prefix retry loosens nothing: policy still decides after stripping", () => {
withVault((dir) => {
stocked(dir);
const policy = resolveExposure(dir, { mcp_exposed_roots: ["brain"] });
- assert.equal(resolveResourceUri(dir, policy, "vault://note/work/1-1/Sarah.md"), null);
+
+ // Out of scope stays out of scope, prefixed or not.
+ assert.equal(
+ resolveResourceUri(dir, policy, "vault://note/myvault/work/1-1/Sarah.md", "myvault"),
+ null,
+ );
+ // Traversal is still refused when it arrives behind the prefix.
+ assert.equal(
+ resolveResourceUri(dir, policy, "vault://note/myvault/brain/../work/1-1/Sarah.md", "myvault"),
+ null,
+ );
+ // Only the exact collection name is stripped, and only once.
+ assert.equal(resolveResourceUri(dir, policy, "vault://note/other/brain/Gotchas.md", "myvault"), null);
+ assert.equal(
+ resolveResourceUri(dir, policy, "vault://note/myvault/myvault/brain/Gotchas.md", "myvault"),
+ null,
+ );
});
});