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

fix(config): derive vault store reference from a keyed installation secret (#140)

Sol Aitken61e93d249cfa
diff --git a/src/core/config.ts b/src/core/config.ts
index 8f2103b2..ec8057f6 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -8,7 +8,7 @@
*/
import { mkdirSync, readFileSync } from "node:fs";
-import { createHash, randomBytes } from "node:crypto";
+import { createHmac, randomBytes } from "node:crypto";
import { homedir } from "node:os";
import { dirname, isAbsolute, join, resolve } from "node:path";
@@ -273,22 +273,95 @@ export function resolveExposeHostPaths(configPath?: string): boolean {
return resolveConfigFlag("OPEN_SECOND_BRAIN_EXPOSE_HOST_PATHS", "expose_host_paths", configPath);
}
+/**
+ * Device-local installation secret that keys {@link vaultStoreReference}.
+ *
+ * Sixteen random bytes (128-bit) rendered as 32 lowercase hex, generated
+ * once and persisted beside `device_id` in the same device-local config.
+ * Three properties make the store reference unguessable offline:
+ *
+ * - it is NEVER synced (device-local config, like `device_id`);
+ * - it is NEVER derived from `device_id`, so the `O2B_DEVICE_ID=""`
+ * sharding opt-out (which makes the device id empty and predictable)
+ * cannot weaken it;
+ * - it has NO empty/predictable escape hatch: the only env override
+ * ({@link INSTALLATION_SECRET_ENV_KEY}, for deterministic tests) is
+ * honoured solely when it is itself a full 32-hex key.
+ *
+ * A missing or corrupt persisted value self-heals to a fresh key under the
+ * same directory lock `resolveDeviceId` uses, so a concurrent first use
+ * cannot split into two keys.
+ */
+export const INSTALLATION_SECRET_CONFIG_KEY = "installation_secret";
+/** Test-only env override; honoured ONLY when it is a full 32-hex key. */
+export const INSTALLATION_SECRET_ENV_KEY = "O2B_INSTALLATION_SECRET";
+/** Strict shape: 32 lowercase hex = 16 bytes = a 128-bit key. */
+export const INSTALLATION_SECRET_RE = /^[0-9a-f]{32}$/;
+
+export function isValidInstallationSecret(value: string): boolean {
+ return INSTALLATION_SECRET_RE.test(value);
+}
+
+export function resolveInstallationSecret(configPath?: string): string {
+ // Env override exists for deterministic tests only, and is accepted solely
+ // as a full 32-hex key so it can never make the secret empty or guessable.
+ const env = process.env[INSTALLATION_SECRET_ENV_KEY];
+ if (env !== undefined && isValidInstallationSecret(env)) return env;
+ const resolved = configPath ?? defaultConfigPath();
+
+ const read = (): string | null => {
+ const value = discoverConfig(resolved).data[INSTALLATION_SECRET_CONFIG_KEY];
+ return value && isValidInstallationSecret(value) ? value : null;
+ };
+
+ const existing = read();
+ if (existing !== null) return existing;
+
+ // First-use generation under a directory lock, mirroring resolveDeviceId:
+ // a lock failure falls through to the unlocked path so secret resolution
+ // never fails outright.
+ const dir = dirname(resolved);
+ mkdirSync(dir, { recursive: true });
+ let release: (() => void) | undefined;
+ try {
+ for (let attempt = 0; attempt < 10; attempt++) {
+ try {
+ release = lockfile.lockSync(dir, { stale: 10_000, realpath: false });
+ break;
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== "ELOCKED") break;
+ Bun.sleepSync(50);
+ }
+ }
+ const won = read();
+ if (won !== null) return won;
+ const generated = randomBytes(16).toString("hex");
+ setConfigValue(INSTALLATION_SECRET_CONFIG_KEY, generated, resolved);
+ return generated;
+ } finally {
+ release?.();
+ }
+}
+
/** Prefix of the opaque store reference emitted in place of a host path. */
export const VAULT_STORE_REF_PREFIX = "vault://";
-/** Hex length of the store-reference digest. */
-const VAULT_STORE_REF_HEX_LEN = 8;
+/** Hex length of the store-reference digest (128 bits of HMAC-SHA256). */
+const VAULT_STORE_REF_HEX_LEN = 32;
/**
- * Stable opaque reference for a vault, of the form `vault://<8-hex>`.
- * Derived from the device-id primitive plus a hash of the vault path, so
- * it is stable across calls on the same install (agents correlate by it)
- * and does not leak the absolute host path. Returned by MCP tools in
- * place of the raw path unless {@link resolveExposeHostPaths} is on.
+ * Stable opaque reference for a vault, of the form `vault://<32-hex>`.
+ * Computed as HMAC-SHA256, keyed by the device-local
+ * {@link resolveInstallationSecret}, over the ABSOLUTE vault path. The key
+ * makes the reference unguessable offline (a plain hash of a common host
+ * path is trivially reversible), and truncating to 128 bits keeps collisions
+ * negligible. It is stable across calls on the same install (agents correlate
+ * by it) and never leaks the raw path. Returned by MCP tools in place of the
+ * absolute path unless {@link resolveExposeHostPaths} is on.
*/
export function vaultStoreReference(vaultPath: string, configPath?: string): string {
- const deviceId = resolveDeviceId(configPath);
- const digest = createHash("sha256")
- .update(`${deviceId}\0${vaultPath}`)
+ const key = resolveInstallationSecret(configPath);
+ const digest = createHmac("sha256", key)
+ .update(resolve(vaultPath))
.digest("hex")
.slice(0, VAULT_STORE_REF_HEX_LEN);
return `${VAULT_STORE_REF_PREFIX}${digest}`;
diff --git a/tests/core/config.installation-secret.test.ts b/tests/core/config.installation-secret.test.ts
new file mode 100644
index 00000000..42ae586a
--- /dev/null
+++ b/tests/core/config.installation-secret.test.ts
@@ -0,0 +1,131 @@
+/**
+ * Device-local installation secret (D2 hardening, PR #139 review).
+ *
+ * The installation secret keys `vaultStoreReference`'s HMAC so the opaque
+ * `vault://` reference cannot be reconstructed offline from a guessable host
+ * path. Unlike the device id it has NO empty/predictable escape hatch: the
+ * only env override (for deterministic tests) is honoured solely when it is a
+ * full 32-hex key, so it can never weaken the secret. It lives in the
+ * device-local config, is generated once, and self-heals when corrupt.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ INSTALLATION_SECRET_ENV_KEY,
+ isValidInstallationSecret,
+ resolveInstallationSecret,
+ vaultStoreReference,
+ VAULT_STORE_REF_PREFIX,
+} from "../../src/core/config.ts";
+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+
+const HEX32 = /^[0-9a-f]{32}$/;
+
+let configHome: string;
+let configPath: string;
+let savedSecret: string | undefined;
+let savedDeviceId: string | undefined;
+
+beforeEach(() => {
+ configHome = mkdtempSync(join(tmpdir(), "o2b-install-secret-"));
+ configPath = join(configHome, "config.yaml");
+ savedSecret = process.env[INSTALLATION_SECRET_ENV_KEY];
+ savedDeviceId = process.env["O2B_DEVICE_ID"];
+ delete process.env[INSTALLATION_SECRET_ENV_KEY];
+});
+
+afterEach(() => {
+ rmSync(configHome, { recursive: true, force: true });
+ if (savedSecret === undefined) delete process.env[INSTALLATION_SECRET_ENV_KEY];
+ else process.env[INSTALLATION_SECRET_ENV_KEY] = savedSecret;
+ if (savedDeviceId === undefined) delete process.env["O2B_DEVICE_ID"];
+ else process.env["O2B_DEVICE_ID"] = savedDeviceId;
+});
+
+describe("resolveInstallationSecret", () => {
+ test("generates a non-empty 32-hex secret on first use and persists it", () => {
+ const secret = resolveInstallationSecret(configPath);
+ expect(secret).not.toBe("");
+ expect(secret).toMatch(HEX32);
+ expect(readFileSync(configPath, "utf8")).toContain(`installation_secret: "${secret}"`);
+ });
+
+ test("returns the same secret on every subsequent call (stable)", () => {
+ const first = resolveInstallationSecret(configPath);
+ const second = resolveInstallationSecret(configPath);
+ expect(second).toBe(first);
+ });
+
+ test("regenerates when the stored value is corrupt or the wrong shape", () => {
+ atomicWriteFileSync(configPath, 'installation_secret: "not-a-valid-secret"\n');
+ const secret = resolveInstallationSecret(configPath);
+ expect(secret).toMatch(HEX32);
+ expect(readFileSync(configPath, "utf8")).toContain(`installation_secret: "${secret}"`);
+ });
+
+ test("honours the env override only when it is a full 32-hex key", () => {
+ process.env[INSTALLATION_SECRET_ENV_KEY] = "0123456789abcdef0123456789abcdef";
+ expect(resolveInstallationSecret(configPath)).toBe("0123456789abcdef0123456789abcdef");
+ });
+
+ test("ignores an empty or predictable env override and generates a real key", () => {
+ process.env[INSTALLATION_SECRET_ENV_KEY] = "";
+ const empty = resolveInstallationSecret(configPath);
+ expect(empty).not.toBe("");
+ expect(empty).toMatch(HEX32);
+
+ rmSync(configPath, { force: true });
+ process.env[INSTALLATION_SECRET_ENV_KEY] = "short";
+ const short = resolveInstallationSecret(configPath);
+ expect(short).not.toBe("short");
+ expect(short).toMatch(HEX32);
+ });
+
+ test("isValidInstallationSecret accepts 32-hex only", () => {
+ expect(isValidInstallationSecret("0123456789abcdef0123456789abcdef")).toBe(true);
+ expect(isValidInstallationSecret("")).toBe(false);
+ expect(isValidInstallationSecret("short")).toBe(false);
+ expect(isValidInstallationSecret("0123456789ABCDEF0123456789ABCDEF")).toBe(false); // uppercase
+ expect(isValidInstallationSecret("0123456789abcdef0123456789abcdefff")).toBe(false); // too long
+ });
+});
+
+describe("vaultStoreReference (keyed HMAC)", () => {
+ test("emits vault:// plus 32 hex chars (128 bits)", () => {
+ atomicWriteFileSync(configPath, "vault_path: /tmp/vault\n");
+ const ref = vaultStoreReference("/some/vault", configPath);
+ expect(ref.startsWith(VAULT_STORE_REF_PREFIX)).toBe(true);
+ expect(ref).toMatch(/^vault:\/\/[0-9a-f]{32}$/);
+ });
+
+ test("is stable for the same vault and differs across vaults", () => {
+ atomicWriteFileSync(configPath, "vault_path: /tmp/vault\n");
+ expect(vaultStoreReference("/a/vault", configPath)).toBe(
+ vaultStoreReference("/a/vault", configPath),
+ );
+ expect(vaultStoreReference("/a/vault", configPath)).not.toBe(
+ vaultStoreReference("/b/vault", configPath),
+ );
+ });
+
+ test("known-answer: HMAC-SHA256(secret, abs path) with an injected key", () => {
+ process.env[INSTALLATION_SECRET_ENV_KEY] = "0123456789abcdef0123456789abcdef";
+ expect(vaultStoreReference("/tmp/vault-kat", configPath)).toBe(
+ "vault://c8bef611f8e689165309bdecffb0f292",
+ );
+ });
+
+ test("reference does not depend on device id (device_id opt-out cannot weaken it)", () => {
+ process.env[INSTALLATION_SECRET_ENV_KEY] = "0123456789abcdef0123456789abcdef";
+ process.env["O2B_DEVICE_ID"] = "";
+ const withEmptyDevice = vaultStoreReference("/tmp/vault-kat", configPath);
+ process.env["O2B_DEVICE_ID"] = "abcd1234";
+ const withRealDevice = vaultStoreReference("/tmp/vault-kat", configPath);
+ expect(withEmptyDevice).toBe(withRealDevice);
+ expect(withEmptyDevice).toBe("vault://c8bef611f8e689165309bdecffb0f292");
+ });
+});
diff --git a/tests/core/config.test.ts b/tests/core/config.test.ts
index 6c9cb840..189715c5 100644
--- a/tests/core/config.test.ts
+++ b/tests/core/config.test.ts
@@ -438,12 +438,12 @@ describe("resolveExposeHostPaths", () => {
});
describe("vaultStoreReference", () => {
- test("has the vault:// prefix and 8 hex chars", () => {
+ test("has the vault:// prefix and 32 hex chars (128-bit keyed digest)", () => {
const cfg = join(tmp, "config.yaml");
writeFileSync(cfg, "vault_path: /tmp/vault\n");
const ref = vaultStoreReference("/some/vault", cfg);
expect(ref.startsWith(VAULT_STORE_REF_PREFIX)).toBe(true);
- expect(ref).toMatch(/^vault:\/\/[0-9a-f]{8}$/);
+ expect(ref).toMatch(/^vault:\/\/[0-9a-f]{32}$/);
});
test("is stable for the same vault and differs across vaults", () => {
diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.ts
index dbab8d01..61bb73f7 100644
--- a/tests/mcp/mcp.test.ts
+++ b/tests/mcp/mcp.test.ts
@@ -332,7 +332,7 @@ describe("tool calls", () => {
const s = r.result.structuredContent;
// Default (expose_host_paths unset): the absolute host path is redacted
// to a stable opaque reference, never the raw path.
- expect(s.vault_path).toMatch(/^vault:\/\/[0-9a-f]{8}$/);
+ expect(s.vault_path).toMatch(/^vault:\/\/[0-9a-f]{32}$/);
expect(s.vault_path).not.toBe(vault);
// The raw host path must not leak through any field, including nested
// ones like config.vault_path.