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 (codex): single-flight vault key provisioning; 0600 perms on new .env

Adam Eivyb06b2a7cdd83
diff --git a/server/lib/vaultCrypto.js b/server/lib/vaultCrypto.js
index 7957e23529..c46d46b34e 100644
--- a/server/lib/vaultCrypto.js
+++ b/server/lib/vaultCrypto.js
@@ -19,8 +19,10 @@
import { randomBytes, createCipheriv, createDecipheriv } from 'crypto';
import { readFileSync } from 'fs';
+import { chmod } from 'fs/promises';
import { join } from 'path';
import { PATHS, tryReadFile, atomicWrite } from './fileUtils.js';
+import { createSingleFlight } from './singleFlight.js';
const CIPHER = 'aes-256-gcm';
const IV_BYTES = 12;
@@ -100,7 +102,19 @@ export function isVaultKeyConfigured() {
* orphaning previously encrypted rows. Returns `{ generated }`. Never logs
* the key value.
*/
-export async function ensureVaultKey({ envPath = resolveEnvPath() } = {}) {
+const keyProvisioning = createSingleFlight();
+
+export function ensureVaultKey({ envPath = resolveEnvPath() } = {}) {
+ if (parseKey(process.env.PRIVACY_VAULT_KEY)) return Promise.resolve({ generated: false });
+ // Single-flight per env path: two concurrent first writes must share ONE
+ // generation — otherwise each mints its own key, one wins the .env write,
+ // and the loser's freshly encrypted row is unrecoverable after restart.
+ return keyProvisioning.run(envPath, () => provisionVaultKey(envPath));
+}
+
+async function provisionVaultKey(envPath) {
+ // Re-check inside the flight: a caller that raced in behind an adopt/generate
+ // (or a fresh call after the slot cleared) must not rotate an existing key.
if (parseKey(process.env.PRIVACY_VAULT_KEY)) return { generated: false };
const fromFile = readKeyFromEnvFile(envPath);
@@ -110,11 +124,17 @@ export async function ensureVaultKey({ envPath = resolveEnvPath() } = {}) {
}
const key = randomBytes(KEY_BYTES).toString('hex');
- const content = (await tryReadFile(envPath)) ?? '';
+ const existing = await tryReadFile(envPath);
+ const content = existing ?? '';
// 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`);
+ // A brand-new .env holding a key that decrypts every vault record must not
+ // be world-readable (atomicWrite gives new files the umask default, commonly
+ // 0644). An EXISTING .env keeps whatever mode the user chose — atomicWrite
+ // already preserves it, and silently re-chmodding a user's file is worse.
+ if (existing === null) await chmod(envPath, 0o600);
process.env.PRIVACY_VAULT_KEY = key;
console.log('🔐 Generated PRIVACY_VAULT_KEY and wrote it to .env (vault encryption engaged)');
return { generated: true };
diff --git a/server/lib/vaultCrypto.test.js b/server/lib/vaultCrypto.test.js
index 4323472e0d..8ee407a47d 100644
--- a/server/lib/vaultCrypto.test.js
+++ b/server/lib/vaultCrypto.test.js
@@ -5,7 +5,7 @@
*/
import { describe, it, expect, beforeEach, beforeAll, afterAll } from 'vitest';
-import { mkdtempSync, rmSync, readFileSync, writeFileSync, existsSync } from 'fs';
+import { mkdtempSync, rmSync, readFileSync, writeFileSync, existsSync, statSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import {
@@ -169,6 +169,33 @@ describe('ensureVaultKey', () => {
expect(isVaultKeyConfigured()).toBe(true);
});
+ it('coalesces concurrent first writes into ONE generated key (no rotation race)', async () => {
+ // Two racing first vault writes must not each mint a key — the loser's
+ // rows would be encrypted under a key the winner's .env write discards.
+ const [a, b] = await Promise.all([
+ ensureVaultKey({ envPath }),
+ ensureVaultKey({ envPath }),
+ ]);
+ expect(a).toEqual({ generated: true });
+ expect(b).toEqual({ generated: true }); // shared flight → same result object
+ const content = readFileSync(envPath, 'utf8');
+ expect(content.match(/^PRIVACY_VAULT_KEY=/gm)).toHaveLength(1);
+ expect(content).toContain(`PRIVACY_VAULT_KEY=${process.env.PRIVACY_VAULT_KEY}`);
+ // A later call adopts, never rotates.
+ expect(await ensureVaultKey({ envPath })).toEqual({ generated: false });
+ });
+
+ it.skipIf(process.platform === 'win32')('creates a NEW .env with 0600 permissions', async () => {
+ await ensureVaultKey({ envPath });
+ expect(statSync(envPath).mode & 0o777).toBe(0o600);
+ });
+
+ it.skipIf(process.platform === 'win32')('preserves an EXISTING .env file mode', async () => {
+ writeFileSync(envPath, 'OTHER_VAR=1\n', { mode: 0o644 });
+ await ensureVaultKey({ envPath });
+ expect(statSync(envPath).mode & 0o777).toBe(0o644);
+ });
+
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