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
6.7 KB
Raw Blame
/**
 * Secret-custody crypto kernel (write-time-integrity-governance).
 *
 * The 32-byte key lives in a 0600 keyfile beside the ciphertext store (an
 * owner-only ACL on Windows, see `owner-acl.ts`); both stay under the
 * vault-local state dir, which is excluded from git by a marker file and
 * must be excluded from a file syncer by the operator (see
 * `SYNC_EXCLUSION_CONTENT` below). Values themselves are sealed through
 * the shared per-value cipher in the leaf `value-cipher.ts`, re-exported
 * below so every custody consumer keeps one import path.
 *
 * Honest threat model (documented, not implied): this protects
 * against secret values entering an agent's context, against vault
 * sync/export leakage, and against casual reads of vault markdown.
 * It does NOT protect against root or same-user processes on the
 * host - there is no daemon and no TPM in this design.
 */

import { randomBytes } from "node:crypto";
import {
  chmodSync,
  closeSync,
  existsSync,
  mkdirSync,
  openSync,
  readFileSync,
  writeFileSync,
  writeSync,
} from "node:fs";
import { dirname, join } from "node:path";

import { heldKeyOrRefusal, isEnvelopeBytes } from "./envelope.ts";
import { restrictToOwner } from "./owner-acl.ts";

/**
 * The per-value cipher is re-exported from the leaf `value-cipher.ts` so
 * the custody store and the export bundle keep importing it from this
 * module, and the envelope wraps the keyfile's DEK through the same leaf
 * instead of importing this kernel back (a two-module cycle).
 */
export { decryptValue, encryptValue } from "./value-cipher.ts";
export type { EncryptedValue } from "./value-cipher.ts";

const KEY_BYTES = 32;

/**
 * The git-exclusion marker this directory carries: a vault that is a git
 * repository does not ignore dot-directories by default, so without it
 * the keyfile and the ciphertext would ride the next commit. `*` excludes
 * everything; `!.gitignore` keeps the marker itself under version control
 * so the exclusion survives a clone.
 *
 * It covers GIT ONLY. Syncthing never reads a `.gitignore`: its one
 * exclusion list is the `.stignore` at the synced folder's root, which is
 * the operator's file and is not edited here. `./sync-exposure.ts`
 * detects a vault inside a Syncthing folder whose `.stignore` does not
 * cover this directory, and the doctor and `secret set` name the line to
 * add. Other file syncers have their own rules and are not covered.
 */
const SYNC_EXCLUSION_CONTENT = "*\n!.gitignore\n";

/**
 * Drop the exclusion marker into `dir`, once, best-effort. Beside the
 * vault root, the only `.gitignore` writers in src are this marker and
 * the vault-level managed block seeded by `ensureVaultGitignoreEntries`
 * in `../gitignore-guard.ts` - both deliberate and named here so the
 * guarantee cannot silently rot: this marker stays separate because the
 * secrets directory can pre-date brain init (an operator may store a
 * secret long before the first `o2b brain init`). One further writer
 * exists by design outside that pair: `ensureBackupRootIgnored` in
 * `../../trust.ts` writes its own `.gitignore` into the `.o2b-backups/`
 * root, covering the backups it owns, not Brain state. This marker and
 * that seeder are the whole guarantee that the keyfile and the
 * ciphertext do not ride a git commit to another machine; every other
 * reference in the tree is a reader.
 */
function ensureSyncExclusionMarker(dir: string): void {
  const marker = join(dir, ".gitignore");
  if (existsSync(marker)) return;
  try {
    writeFileSync(marker, SYNC_EXCLUSION_CONTENT, { encoding: "utf8", flag: "wx", mode: 0o600 });
  } catch (err) {
    if ((err as NodeJS.ErrnoException).code !== "EEXIST") {
      process.stderr.write(
        `warning: could not write the sync-exclusion marker for the secrets directory: ` +
          `${marker}: ${err instanceof Error ? err.message : String(err)}\n`,
      );
    }
  }
}

/** Load the keyfile, creating it 0600 with 32 random bytes on first use. */
export function loadOrCreateKey(keyPath: string): Buffer {
  const keyDir = dirname(keyPath);
  if (existsSync(keyPath)) {
    // On Windows the owner-only ACL is (re)applied on load too, not only
    // at creation: a secrets directory that came in with a copied or
    // restored vault carries whatever ACL it inherited at its new place.
    // `restrictToOwner` is idempotent and runs once per path per process.
    restrictToOwner(keyDir, "directory");
    restrictToOwner(keyPath, "file");
    // The POSIX mirror of that re-application: mode bits are set only at
    // creation, so a keyfile that arrived with a copy or a tar restore
    // keeps whatever mode the copy gave it - 0644 included - forever,
    // because `restrictToOwner` is a no-op here. Warn-and-continue, like
    // the Windows path: the key is already on disk, and refusing to read
    // it would break every secret operation over a repairable bit.
    if (process.platform !== "win32") {
      try {
        chmodSync(keyDir, 0o700);
        chmodSync(keyPath, 0o600);
      } catch (err) {
        process.stderr.write(
          `warning: could not re-apply owner-only modes to the secrets keyfile: ` +
            `${keyPath}: ${err instanceof Error ? err.message : String(err)}\n`,
        );
      }
    }
    ensureSyncExclusionMarker(keyDir);
    const key = readFileSync(keyPath);
    // The passphrase-wrapped envelope replaces the raw file at the SAME
    // path and carries the same ACL discipline (all of the above applies
    // to it unchanged). There is nothing to create and nothing to mint:
    // the key comes from this process's unlock holder, and an empty
    // holder is the named locked-store refusal - never a fresh random
    // key, which would silently orphan every stored value.
    if (isEnvelopeBytes(key)) return heldKeyOrRefusal(keyPath);
    if (key.length !== KEY_BYTES) {
      throw new Error(`secrets keyfile is corrupt (expected ${KEY_BYTES} bytes): ${keyPath}`);
    }
    return key;
  }
  // The `0700` mode takes effect on POSIX only for a directory this call
  // creates. Windows ignores the mode; `restrictToOwner` sets the
  // equivalent ACL there, whoever created the directory.
  mkdirSync(keyDir, { recursive: true, mode: 0o700 });
  restrictToOwner(keyDir, "directory");
  ensureSyncExclusionMarker(keyDir);
  const key = randomBytes(KEY_BYTES);
  // Exclusive create: two concurrent first-writers cannot truncate
  // each other's key; the loser re-reads the winner's file.
  let fd: number;
  try {
    fd = openSync(keyPath, "wx", 0o600);
  } catch (exc) {
    if ((exc as NodeJS.ErrnoException).code === "EEXIST") return loadOrCreateKey(keyPath);
    throw exc;
  }
  try {
    writeSync(fd, key);
  } finally {
    closeSync(fd);
  }
  restrictToOwner(keyPath, "file");
  return key;
}