Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

address review (claude): vault key must survive restarts, worktree boots, and invalid .env lines

Adam Eivya2d32cf280bb
diff --git a/server/lib/README.md b/server/lib/README.md
index 1a682f244f..01032a800c 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -221,7 +221,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `planIds.js` | Utilities for PLAN.md `[slug]` IDs. |
| `renderSlot.js` | Render-slot helpers for `(proof\|final)Image` per stage. |
| `telegramClient.js` | Telegram bot client. |
-| `vaultCrypto.js` | Privacy Center PII Vault field-level encryption (issue #2140). AES-256-GCM `encryptValue`/`decryptValue` (`v1:<iv>:<tag>:<ct>` format, per-value 12-byte IV), `ensureVaultKey()` self-heal (generates `PRIVACY_VAULT_KEY` into `.env` on first write, never logs the value), `isVaultKeyConfigured()`, and the per-type `maskValue(type, plaintext)` display masking (last-4 / domain-visible / street-masked). Plaintext must never be logged by callers. |
+| `vaultCrypto.js` | Privacy Center PII Vault field-level encryption (issue #2140). AES-256-GCM `encryptValue`/`decryptValue` (`v1:<iv>:<tag>:<ct>` format, per-value 12-byte IV), `ensureVaultKey()` self-heal (generates `PRIVACY_VAULT_KEY` into the install root's `.env` on first write, replacing any invalid line; never logs the value), key resolution that falls back to reading `.env` so decrypt/status survive a server restart, `isVaultKeyConfigured()`, and the per-type `maskValue(type, plaintext)` display masking (last-4 / domain-visible / street-masked). Plaintext must never be logged by callers. |
## Model & config
diff --git a/server/lib/vaultCrypto.js b/server/lib/vaultCrypto.js
index 3251467caf..7957e23529 100644
--- a/server/lib/vaultCrypto.js
+++ b/server/lib/vaultCrypto.js
@@ -18,6 +18,7 @@
*/
import { randomBytes, createCipheriv, createDecipheriv } from 'crypto';
+import { readFileSync } from 'fs';
import { join } from 'path';
import { PATHS, tryReadFile, atomicWrite } from './fileUtils.js';
@@ -26,7 +27,30 @@ const IV_BYTES = 12;
const KEY_BYTES = 32;
const FORMAT_VERSION = 'v1';
-const DEFAULT_ENV_PATH = join(PATHS.root, '.env');
+// Anchor to the INSTALL root, not the code root: the encrypted rows live in
+// the ONE install-shared Postgres, so the key must live next to that data. A
+// server booted from a CoS git worktree (PORTOS_DATA_ROOT pinned, #1947) has
+// no .env in its checkout — anchoring to PATHS.root there would mint a
+// throwaway key in the worktree, encrypt shared rows with it, and destroy the
+// key when the worktree is pruned (irreversible PII loss).
+const DEFAULT_ENV_PATH = join(PATHS.installRoot, '.env');
+
+// Test hook: unit tests point this at a temp .env so the read-path fallback
+// below never touches (or is satisfied by) the real install's key.
+let envPathOverride = null;
+export function __setVaultEnvPathForTests(path) { envPathOverride = path; }
+const resolveEnvPath = () => envPathOverride ?? DEFAULT_ENV_PATH;
+
+/** First VALID key among all PRIVACY_VAULT_KEY= lines in the .env file. */
+function readKeyFromEnvFile(envPath) {
+ let content = '';
+ try { content = readFileSync(envPath, 'utf8'); } catch { return null; }
+ for (const match of content.matchAll(/^PRIVACY_VAULT_KEY=(.*)$/gm)) {
+ const raw = match[1].trim();
+ if (parseKey(raw)) return raw;
+ }
+ return null;
+}
/** Parse a hex- or base64-encoded 32-byte key; null when absent/invalid. */
function parseKey(raw) {
@@ -41,8 +65,23 @@ function parseKey(raw) {
return null;
}
+/**
+ * Resolve the vault key: `process.env` first, then the `.env` file. The file
+ * fallback is what makes READS survive a server restart — nothing loads `.env`
+ * into `process.env` at boot (PortOS has no dotenv), so without it every
+ * decrypt/status call would fail after `pm2 restart` until the next WRITE
+ * happened to run `ensureVaultKey()`. A key found in the file is adopted into
+ * `process.env` so subsequent calls take the fast path.
+ */
function getVaultKey() {
- return parseKey(process.env.PRIVACY_VAULT_KEY);
+ const fromEnv = parseKey(process.env.PRIVACY_VAULT_KEY);
+ if (fromEnv) return fromEnv;
+ const fromFile = readKeyFromEnvFile(resolveEnvPath());
+ if (fromFile) {
+ process.env.PRIVACY_VAULT_KEY = fromFile;
+ return parseKey(fromFile);
+ }
+ return null;
}
/** True when PRIVACY_VAULT_KEY holds a valid 32-byte key. */
@@ -51,27 +90,33 @@ export function isVaultKeyConfigured() {
}
/**
- * Self-heal a missing vault key: when `PRIVACY_VAULT_KEY` is unset or invalid,
- * generate 32 random bytes, append the hex form to `.env` (created if absent),
- * and set `process.env` so the running server picks it up immediately. Reads
- * the `.env` file first so a key added after boot is adopted rather than
- * duplicated. Returns `{ generated }`. Never logs the key value.
+ * Self-heal a missing vault key: when `PRIVACY_VAULT_KEY` is unset or invalid
+ * in both `process.env` and the `.env` file, generate 32 random bytes, write
+ * the hex form to `.env` (created if absent), and set `process.env` so the
+ * running server picks it up immediately. Any existing INVALID
+ * `PRIVACY_VAULT_KEY=` lines (e.g. an uncommented `.env.example` placeholder)
+ * are REPLACED, not appended-around — appending would leave the invalid first
+ * line winning future reads and silently re-rotate the key on every restart,
+ * orphaning previously encrypted rows. Returns `{ generated }`. Never logs
+ * the key value.
*/
-export async function ensureVaultKey({ envPath = DEFAULT_ENV_PATH } = {}) {
- if (isVaultKeyConfigured()) return { generated: false };
+export async function ensureVaultKey({ envPath = resolveEnvPath() } = {}) {
+ if (parseKey(process.env.PRIVACY_VAULT_KEY)) return { generated: false };
- const content = (await tryReadFile(envPath)) ?? '';
- const existing = content.match(/^PRIVACY_VAULT_KEY=(.*)$/m);
- if (existing && parseKey(existing[1])) {
- process.env.PRIVACY_VAULT_KEY = existing[1].trim();
+ const fromFile = readKeyFromEnvFile(envPath);
+ if (fromFile) {
+ process.env.PRIVACY_VAULT_KEY = fromFile;
return { generated: false };
}
const key = randomBytes(KEY_BYTES).toString('hex');
- const separator = content && !content.endsWith('\n') ? '\n' : '';
- await atomicWrite(envPath, `${content}${separator}PRIVACY_VAULT_KEY=${key}\n`);
+ const content = (await tryReadFile(envPath)) ?? '';
+ // Drop any invalid PRIVACY_VAULT_KEY lines (none are valid — checked above).
+ const cleaned = content.replace(/^PRIVACY_VAULT_KEY=.*(\r?\n|$)/gm, '');
+ const separator = cleaned && !cleaned.endsWith('\n') ? '\n' : '';
+ await atomicWrite(envPath, `${cleaned}${separator}PRIVACY_VAULT_KEY=${key}\n`);
process.env.PRIVACY_VAULT_KEY = key;
- console.log('🔐 Generated PRIVACY_VAULT_KEY and appended it to .env (vault encryption engaged)');
+ console.log('🔐 Generated PRIVACY_VAULT_KEY and wrote it to .env (vault encryption engaged)');
return { generated: true };
}
@@ -142,9 +187,13 @@ export function maskValue(type, plaintext) {
return `${value[0]}•••@${value.slice(at + 1)}`;
}
case 'address': {
- const comma = value.indexOf(',');
- if (comma === -1) return '•••';
- return `•••${value.slice(comma)}`;
+ // Keep only the trailing city/state segments visible. Masking just the
+ // FIRST comma segment would leak the street whenever the value starts
+ // with a non-street segment ("c/o Adam Eivy, 123 Main St, ...").
+ const parts = value.split(',').map((p) => p.trim()).filter(Boolean);
+ if (parts.length < 2) return '•••';
+ const visible = parts.slice(parts.length >= 3 ? -2 : -1);
+ return `•••, ${visible.join(', ')}`;
}
default:
return `${value[0]}•••`;
diff --git a/server/lib/vaultCrypto.test.js b/server/lib/vaultCrypto.test.js
index 3e3ea7bc44..4323472e0d 100644
--- a/server/lib/vaultCrypto.test.js
+++ b/server/lib/vaultCrypto.test.js
@@ -4,19 +4,27 @@
* against a temp .env, and the per-type display masking.
*/
-import { describe, it, expect, beforeEach, afterAll } from 'vitest';
+import { describe, it, expect, beforeEach, beforeAll, afterAll } from 'vitest';
import { mkdtempSync, rmSync, readFileSync, writeFileSync, existsSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import {
encryptValue, decryptValue, ensureVaultKey, isVaultKeyConfigured, maskValue,
+ __setVaultEnvPathForTests,
} from './vaultCrypto.js';
// Fixed 32-byte test key (hex). Never a real key.
const HEX_KEY = 'a'.repeat(64);
const originalKey = process.env.PRIVACY_VAULT_KEY;
+// Point the module's .env fallback at a nonexistent file so "key not
+// configured" tests can't be satisfied by (or write into) the real install's
+// .env. Individual tests re-point it at their own temp files.
+const NO_ENV = join(tmpdir(), 'vault-crypto-no-such-dir', '.env');
+beforeAll(() => __setVaultEnvPathForTests(NO_ENV));
+
afterAll(() => {
+ __setVaultEnvPathForTests(null);
if (originalKey === undefined) delete process.env.PRIVACY_VAULT_KEY;
else process.env.PRIVACY_VAULT_KEY = originalKey;
});
@@ -83,6 +91,40 @@ describe('encryptValue / decryptValue', () => {
});
});
+describe('key resolution survives a restart (read-path .env fallback)', () => {
+ let dir;
+ let envPath;
+
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'vault-restart-'));
+ envPath = join(dir, '.env');
+ __setVaultEnvPathForTests(envPath);
+ delete process.env.PRIVACY_VAULT_KEY;
+ });
+
+ afterEach(() => {
+ __setVaultEnvPathForTests(NO_ENV);
+ rmSync(dir, { recursive: true, force: true });
+ });
+
+ it('reads decrypt/status from .env when process.env is empty (post-restart)', () => {
+ // Simulate: key generated pre-restart lives in .env; process.env is fresh.
+ writeFileSync(envPath, `PRIVACY_VAULT_KEY=${HEX_KEY}\n`);
+ process.env.PRIVACY_VAULT_KEY = HEX_KEY;
+ const ct = encryptValue('survives restart');
+ delete process.env.PRIVACY_VAULT_KEY; // the "restart"
+ expect(isVaultKeyConfigured()).toBe(true); // status stays truthful
+ expect(decryptValue(ct)).toBe('survives restart'); // reveal works without a prior write
+ expect(process.env.PRIVACY_VAULT_KEY).toBe(HEX_KEY); // adopted for the fast path
+ });
+
+ it('ignores invalid PRIVACY_VAULT_KEY lines and adopts the first valid one', () => {
+ writeFileSync(envPath, `PRIVACY_VAULT_KEY=not-a-key\nPRIVACY_VAULT_KEY=${HEX_KEY}\n`);
+ expect(isVaultKeyConfigured()).toBe(true);
+ expect(process.env.PRIVACY_VAULT_KEY).toBe(HEX_KEY);
+ });
+});
+
describe('ensureVaultKey', () => {
let dir;
let envPath;
@@ -127,6 +169,24 @@ describe('ensureVaultKey', () => {
expect(isVaultKeyConfigured()).toBe(true);
});
+ it('REPLACES an invalid PRIVACY_VAULT_KEY line instead of appending a duplicate', async () => {
+ // e.g. the user uncommented the .env.example placeholder. Appending around
+ // it would let the invalid first line win future reads → silent key
+ // rotation on every restart, orphaning previously encrypted rows.
+ writeFileSync(envPath, 'OTHER_VAR=1\nPRIVACY_VAULT_KEY=<64 hex chars>\nLAST_VAR=2\n');
+ expect(await ensureVaultKey({ envPath })).toEqual({ generated: true });
+ const content = readFileSync(envPath, 'utf8');
+ expect(content.match(/^PRIVACY_VAULT_KEY=/gm)).toHaveLength(1);
+ expect(content).toMatch(/^PRIVACY_VAULT_KEY=[0-9a-f]{64}$/m);
+ expect(content).toContain('OTHER_VAR=1');
+ expect(content).toContain('LAST_VAR=2');
+ // Idempotent across the next "restart": the same key is adopted, not rotated.
+ const adopted = process.env.PRIVACY_VAULT_KEY;
+ delete process.env.PRIVACY_VAULT_KEY;
+ expect(await ensureVaultKey({ envPath })).toEqual({ generated: false });
+ expect(process.env.PRIVACY_VAULT_KEY).toBe(adopted);
+ });
+
afterEach(() => rmSync(dir, { recursive: true, force: true }));
});
@@ -151,6 +211,10 @@ describe('maskValue', () => {
it('masks the street segment of an address', () => {
expect(maskValue('address', '123 Main St, Portland, OR 97201')).toBe('•••, Portland, OR 97201');
expect(maskValue('address', '123 Main St')).toBe('•••');
+ // A leading non-street segment must not shift the street into view.
+ expect(maskValue('address', 'c/o Adam Eivy, 123 Main St, Portland, OR 97201')).toBe('•••, Portland, OR 97201');
+ // Two segments: only the last is visible (both would disclose the street).
+ expect(maskValue('address', '123 Main St, Portland')).toBe('•••, Portland');
});
it('falls back to first-char masking for other types', () => {