Skip to content

Local-first 🧠 memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.

TypeScript
13.3 KB
Raw Blame
/**
 * Path-safety helpers shared by every module that writes into the vault.
 *
 * Centralises the "is this path inside the vault?" check and a reusable
 * vault-relative path renderer. Every module that constructs a path to
 * write must funnel through `ensureInsideVault` so a malicious or buggy
 * input (e.g. a slug with `..`, an absolute symlink target) cannot land a
 * file outside the vault root.
 */

import { existsSync, realpathSync, statSync } from "node:fs";
import {
  basename,
  dirname,
  join,
  posix as pathPosix,
  relative,
  resolve,
  sep,
  win32 as pathWin32,
} from "node:path";

/** The `code` a {@link VaultEscapeError} carries, beside the errno codes of fs errors. */
export const VAULT_ESCAPE_CODE = "ESCAPE";

/**
 * A path that leaves the vault, lexically or through a symlink. It carries
 * a `code` the way a Node fs error does, so a reader that reports a failed
 * read by its code names this one too rather than the bare class.
 */
export class VaultEscapeError extends Error {
  readonly code = VAULT_ESCAPE_CODE;
  constructor(message: string) {
    super(message);
    this.name = "VaultEscapeError";
  }
}

/**
 * Throw if `target` is not the vault root or a descendant of it.
 *
 * The check is twofold:
 *
 *   1. `path.resolve` normalises `..` so a slug like `../outside`
 *      cannot pretend to be inside the vault. The platform path
 *      separator (`/` or `\`) is used for the prefix check so siblings
 *      that share a name prefix (`/v` vs `/v-evil`) are rejected.
 *   2. `fs.realpathSync` follows symlinks for the deepest existing
 *      ancestor of the target, then re-runs the prefix check on the
 *      resolved real paths. This blocks the case where a directory
 *      *inside* the vault is itself a symlink to somewhere outside it
 *      (`<vault>/Brain/payments/escape -> /tmp/outside`) — without
 *      realpath, the lexical check would happily admit the path.
 *
 * Returns the resolved (lexical) absolute path of `target`. Callers that
 * need the realpath should call `realpathSync` themselves on the result;
 * we deliberately return the lexical form so wikilinks rendered from it
 * keep matching what the user sees in Obsidian.
 */
export function ensureInsideVault(target: string, vault: string): string {
  const resolvedTarget = resolve(target);
  const resolvedVault = resolve(vault);

  if (!isLexicallyInsideHost(resolvedTarget, resolvedVault)) {
    throw new VaultEscapeError(`path escapes vault: ${target}`);
  }

  // Realpath protection only matters when the vault actually exists on
  // disk — otherwise there is no symlink to follow. Pure-lexical inputs
  // (used by unit tests) skip this branch and rely on step 1 above.
  if (existsSync(resolvedVault) && !realpathInsideVault(resolvedTarget, resolvedVault)) {
    throw new VaultEscapeError(`path escapes vault via symlink: ${target}`);
  }

  return resolvedTarget;
}

/**
 * Step 2 of {@link ensureInsideVault} as a non-throwing predicate: does
 * `target`'s realpath (following symlinks for its deepest existing
 * ancestor) resolve inside `vault`? Returns true when the vault does not
 * exist on disk (no symlink to follow). Shared with the doctor's
 * `symlink-escape` lint so the two-step check lives in exactly one place.
 */
export function realpathInsideVault(target: string, vault: string): boolean {
  const resolvedVault = resolve(vault);
  if (!existsSync(resolvedVault)) return true;
  const realVault = safeRealpath(resolvedVault);
  const realAncestor = safeRealpath(deepestExistingAncestor(resolve(target)));
  return isLexicallyInsideHost(realAncestor, realVault);
}

/**
 * Step 1 of {@link ensureInsideVault} as a non-throwing predicate: does
 * `target` resolve, lexically, to `root` or a descendant of it?
 *
 * Exported for the callers that need the ANSWER rather than the refusal -
 * the ownership statement has to say where the search index actually
 * landed, and a `try`/`catch` around a thrower would collapse "outside the
 * vault" and "the check could not run" into one arm.
 */
export function pathIsInside(target: string, root: string): boolean {
  return pathIsInsideOn(hostPlatform(), target, root);
}

/**
 * Does `target` resolve, under `platform`'s own path rules, to `root` or a
 * descendant of it? The pure judgment behind {@link pathIsInside},
 * parameterized by platform so the Windows rules can be exercised from a
 * POSIX test process.
 *
 * Both sides go through the SAME named platform's `path` module, whose
 * whole surface is string work: `path.win32.resolve` treats `\` and `/`
 * alike as separators, returns a backslash-separated absolute path, and
 * collapses `..` lexically - it never touches the filesystem, so an 8.3
 * short spelling (`RUNNER~1`) stays exactly as spelled on both sides.
 * That symmetry is what makes the check fail-closed under spelling
 * divergence: a short-vs-long mismatch can only make the prefix
 * MISmatch, which refuses an actually-inside path, never admits an
 * actually-escaped one.
 */
export function pathIsInsideOn(platform: "win32" | "posix", target: string, root: string): boolean {
  const pathImpl = platform === "win32" ? pathWin32 : pathPosix;
  return isLexicallyInside(platform, pathImpl.resolve(target), pathImpl.resolve(root));
}

function isLexicallyInside(platform: "win32" | "posix", target: string, root: string): boolean {
  // Windows file paths are case-insensitive at the filesystem level —
  // `C:\Vault\x.md` and `c:\vault\x.md` resolve to the same inode. Doing
  // a case-sensitive string compare on Windows would falsely reject a
  // user's lower-cased argument against a vault stored with the canonical
  // capitalisation. POSIX stays case-sensitive. The separator is the named
  // platform's own, so a win32 judgment keeps working from a POSIX host.
  const fold = platform === "win32";
  const sepChar = fold ? pathWin32.sep : pathPosix.sep;
  const t = fold ? target.toLowerCase() : target;
  const r = fold ? root.toLowerCase() : root;
  return t === r || t.startsWith(r + sepChar);
}

/** This host's path-rules name, narrowed to the two `node:path` flavors. */
function hostPlatform(): "win32" | "posix" {
  return process.platform === "win32" ? "win32" : "posix";
}

/** The lexical answer for THIS host, over paths its own `path` module resolved. */
function isLexicallyInsideHost(target: string, root: string): boolean {
  return isLexicallyInside(hostPlatform(), target, root);
}

function deepestExistingAncestor(target: string): string {
  let cur = target;
  // Walk up until we hit a path that exists. `dirname` of a top-level
  // path returns itself; the loop terminates either at the first existing
  // ancestor (the common case — vault root exists) or at the root.
  while (!existsSync(cur)) {
    const parent = dirname(cur);
    if (parent === cur) return cur;
    cur = parent;
  }
  return cur;
}

function safeRealpath(p: string): string {
  // realpath throws on non-existent paths and on permission failure.
  // For non-existent we fall back to the lexical form (the
  // `deepestExistingAncestor` walk above tries to avoid this case);
  // for permission failure we surface the error so the caller learns
  // about it instead of silently disabling symlink protection.
  try {
    return realpathSync(p);
  } catch (err) {
    if ((err as NodeJS.ErrnoException)?.code === "ENOENT") return p;
    throw err;
  }
}

/**
 * The realpath of `target`, resolving every symlink in the components
 * that exist and re-appending the components that do not yet.
 *
 * A write target is normally the LAST component and does not exist yet,
 * so `realpathSync` on it alone would only ever raise; what matters is
 * the directory chain above it, which does exist and is where a symlink
 * redirects the write. ENOENT walks one level up; any other errno is
 * raised, because a directory we cannot examine is not a directory we
 * know to be safe.
 */
function realpathOfDeepestExisting(target: string): string {
  try {
    return realpathSync(target);
  } catch (err) {
    if ((err as NodeJS.ErrnoException)?.code !== "ENOENT") throw err;
    const parent = dirname(target);
    if (parent === target) return target;
    const realParent = realpathOfDeepestExisting(parent);
    assertNotAFile(realParent);
    return join(realParent, basename(target));
  }
}

/**
 * Refuse to append a component below an existing non-directory.
 *
 * POSIX `realpath` answers `ENOTDIR` for `note.md/child.md` when `note.md`
 * is a file, but Windows answers `ENOENT`, which the walk above reads as
 * "not created yet" and would resolve to a path no write can ever create.
 * Raising the POSIX errno here gives both platforms the same answer.
 */
function assertNotAFile(path: string): void {
  const stat = statSync(path, { throwIfNoEntry: false });
  if (stat === undefined || stat.isDirectory()) return;
  const err: NodeJS.ErrnoException = new Error(`ENOTDIR: not a directory, '${path}'`);
  err.code = "ENOTDIR";
  err.path = path;
  throw err;
}

/**
 * Where `relPath` actually lands, as a vault-relative POSIX path, or
 * `null` when it lands outside the vault altogether.
 */
export function realVaultRelative(vault: string, relPath: string): string | null {
  const realVault = realpathOfDeepestExisting(resolve(vault));
  const realTarget = realpathOfDeepestExisting(resolve(join(vault, relPath)));
  const rel = relative(realVault, realTarget);
  // `relative` emits the platform separator, so the "climbs out of the
  // root" test uses it too. An empty result means the target IS the
  // vault root, which is not a place a note can be written either.
  if (rel === "" || rel === ".." || rel.startsWith(".." + sep)) return null;
  return toPosix(rel);
}

/**
 * Convert an OS-native path to POSIX form (forward slashes).
 *
 * Returns the input unchanged on POSIX hosts (`sep === "/"`); on
 * Windows, replaces every `\\` separator with `/`. Used by the
 * vault walkers when they project absolute or vault-relative OS
 * paths into the POSIX form that the vault-scope matcher and Obsidian
 * wikilinks both expect.
 */
export function toPosix(p: string): string {
  return sep === "/" ? p : p.split(sep).join("/");
}

/**
 * Fold Windows separators in a vault-relative rel to forward slashes,
 * exactly where the platform separator is not already `/`.
 *
 * `toPosix` above renders an OS-native path for display and is a no-op
 * where the platform separator is already `/`; boundaries that KEY or
 * PROBE by a vault-relative rel follow the same platform condition. On
 * Windows a `\` in a rel is a separator artifact - Windows cannot create
 * a file whose name carries one - so folding unifies `notes\page.md`
 * and `notes/page.md` into one logical page: one cache entry, one
 * probe, one read. On POSIX hosts the fold is the identity, because a
 * `\` byte there is a LEGAL filename character: the walkers preserve it,
 * and folding it would misprobe a genuinely backslash-named file as its
 * slash-named neighbour.
 */
export function posixRel(p: string): string {
  return sep === "/" ? p : p.replaceAll("\\", "/");
}

/**
 * Canonical vault-relative note identity: forward-slash POSIX form plus
 * Unicode NFC.
 *
 * The same note has byte-different vault-relative paths across devices:
 * macOS (APFS/HFS+) stores filenames decomposed (NFD), while Linux and
 * Android store them precomposed (NFC). On a Syncthing peer set that
 * splits one note into two identities, defeating incremental-index
 * change detection (constant re-index churn) and surfacing phantom
 * cross-device duplicates. Funnelling every path that keys a note's
 * identity (the index change-detection key, provenance stamping)
 * through this helper collapses both forms to one NFC identity.
 *
 * Idempotent: an already-POSIX, already-NFC path - the Linux common
 * case - returns byte-identical, so the normalisation is invisible on
 * the dominant platform and only the macOS NFD path actually converges.
 */
export function canonicalNotePath(p: string): string {
  return toPosix(p).normalize("NFC");
}

/**
 * A URI scheme per RFC 3986 §3.1: an ASCII letter followed by letters,
 * digits, `+`, `-` and `.`, terminated by a colon. Structural - never a
 * list of known scheme names, which could not be complete.
 */
const URI_SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i;

/**
 * Does `target` name a location somewhere other than inside this vault -
 * either by carrying a URI scheme (`https:`, `mailto:`, `obsidian:`) or by
 * being protocol-relative (`//host/x`)?
 *
 * This is the boundary between "a path in the vault" and "an address
 * elsewhere", and both readings of that boundary want the same answer: a
 * markdown link target with a scheme is an external link rather than a note
 * reference, and a source identity with one entered the vault from outside
 * it. One predicate, so the two cannot drift apart.
 */
export function hasUriScheme(target: string): boolean {
  return URI_SCHEME_RE.test(target) || target.startsWith("//");
}

/**
 * Vault-relative path with forward slashes.
 *
 * Markdown rendering and Obsidian wikilinks both want forward slashes
 * regardless of host OS, so we collapse Windows-style backslashes to
 * `/`. Returns the input unchanged if it is not inside the vault — that
 * guards `ensureInsideVault` callers that want to display the rejected
 * path back to the user without crashing.
 */
export function vaultRelative(target: string, vault: string): string {
  const rel = relative(resolve(vault), resolve(target));
  return rel
    .split(/[\\/]/)
    .filter((p) => p.length > 0)
    .join(pathPosix.sep);
}