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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: never rewrite .env after a failed read
Adam Eivy541740026fba
diff --git a/server/lib/portosEnv.js b/server/lib/portosEnv.jsindex 5ea1ead762..4a1778fa50 100644--- a/server/lib/portosEnv.js+++ b/server/lib/portosEnv.js@@ -143,8 +143,11 @@ export async function upsertPortosEnvLine(key, value, envPath) {let contents = '';try {contents = readFileSync(path, 'utf8');- } catch {- // no .env yet+ } catch (err) {+ // Only a missing file is an empty start. Any other read failure (EACCES,+ // EMFILE, EIO) would otherwise rewrite .env as this one line, dropping+ // PGPASSWORD, PRIVACY_VAULT_KEY and every other recorded value.+ if (err.code !== 'ENOENT') throw err;}const next = upsertEnvLine(contents, key, value);await atomicWrite(path, next);diff --git a/server/lib/vaultCrypto.js b/server/lib/vaultCrypto.jsindex 02048065f9..c6f86708cc 100644--- a/server/lib/vaultCrypto.js+++ b/server/lib/vaultCrypto.js@@ -20,7 +20,7 @@import { randomBytes, createCipheriv, createDecipheriv } from 'crypto';import { readFileSync } from 'fs';import { chmod } from 'fs/promises';-import { tryReadFile, atomicWrite } from './fileUtils.js';+import { tryReadFileStrict, atomicWrite } from './fileUtils.js';import { createSingleFlight } from './singleFlight.js';import { PORTOS_ENV_PATH } from './portosEnv.js';@@ -44,10 +44,8 @@ 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; }+/** First VALID key among all PRIVACY_VAULT_KEY= lines in `.env` content. */+function findKeyInEnvContent(content) {for (const match of content.matchAll(/^PRIVACY_VAULT_KEY=(.*)$/gm)) {const raw = match[1].trim();if (parseKey(raw)) return raw;@@ -55,6 +53,13 @@ function readKeyFromEnvFile(envPath) {return null;}+/** Read-path lookup: an unreadable .env reads as "no key" (decrypt then refuses). */+function readKeyFromEnvFile(envPath) {+ let content = '';+ try { content = readFileSync(envPath, 'utf8'); } catch { return null; }+ return findKeyInEnvContent(content);+}+/** Parse a hex- or base64-encoded 32-byte key; null when absent/invalid. */function parseKey(raw) {if (typeof raw !== 'string') return null;@@ -118,15 +123,19 @@ async function provisionVaultKey(envPath) {// (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);+ // One strict read decides both "is there a key" and the content to rewrite.+ // Only a missing .env proves there is no key: generating after any other read+ // failure would strip the live key line below and orphan every encrypted row.+ const { ok, value: existing } = await tryReadFileStrict(envPath);+ if (!ok) throw new Error('Cannot provision PRIVACY_VAULT_KEY: .env exists but could not be read');+ const content = existing ?? '';+ const fromFile = findKeyInEnvContent(content);if (fromFile) {process.env.PRIVACY_VAULT_KEY = fromFile;return { generated: false };}const key = randomBytes(KEY_BYTES).toString('hex');- 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' : '';diff --git a/server/lib/vaultCrypto.test.js b/server/lib/vaultCrypto.test.jsindex f324b1e4e6..2b47a65c59 100644--- a/server/lib/vaultCrypto.test.js+++ b/server/lib/vaultCrypto.test.js@@ -5,7 +5,7 @@*/import { describe, it, expect, beforeEach, afterEach, beforeAll, afterAll } from 'vitest';-import { mkdtempSync, rmSync, readFileSync, writeFileSync, existsSync, statSync } from 'fs';+import { mkdtempSync, rmSync, readFileSync, writeFileSync, existsSync, statSync, chmodSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';import {@@ -214,6 +214,21 @@ describe('ensureVaultKey', () => {expect(process.env.PRIVACY_VAULT_KEY).toBe(adopted);});+ // An unreadable .env is not proof that no key exists: generating here used to+ // strip the live key line and orphan every row encrypted under it.+ it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)('refuses to generate a key when .env exists but cannot be read', async () => {+ const original = `OTHER_VAR=1\nPRIVACY_VAULT_KEY=${HEX_KEY}\n`;+ writeFileSync(envPath, original);+ chmodSync(envPath, 0o000);+ try {+ await expect(ensureVaultKey({ envPath })).rejects.toThrow(/could not be read/);+ } finally {+ chmodSync(envPath, 0o600);+ }+ expect(readFileSync(envPath, 'utf8')).toBe(original);+ expect(process.env.PRIVACY_VAULT_KEY).toBeUndefined();+ });+afterEach(() => rmSync(dir, { recursive: true, force: true }));});diff --git a/server/lib/vllmQwenProject.test.js b/server/lib/vllmQwenProject.test.jsindex f61a8503f8..de0a979a47 100644--- a/server/lib/vllmQwenProject.test.js+++ b/server/lib/vllmQwenProject.test.js@@ -1,5 +1,5 @@import { describe, it, expect, beforeEach, afterEach } from 'vitest';-import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs';+import { chmodSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';@@ -79,6 +79,19 @@ describe('resolveVllmProjectDir', () => {expect(contents).toContain('PGPASSWORD=portos\n');});+ // Only a missing .env is an empty start; rewriting after a failed read used to+ // replace the whole file with the one recorded line.+ it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)('refuses to rewrite a .env it cannot read', async () => {+ writeFileSync(envPath(), 'PGPASSWORD=portos\n');+ chmodSync(envPath(), 0o000);+ try {+ await expect(recordVllmProjectDir('/srv/first', envPath())).rejects.toMatchObject({ code: 'EACCES' });+ } finally {+ chmodSync(envPath(), 0o600);+ }+ expect(readFileSync(envPath(), 'utf8')).toBe('PGPASSWORD=portos\n');+ });+it('reports nothing settled until something answers', async () => {const bare = { HOME: '/home/example', USERPROFILE: '/home/example' };expect(vllmProjectDirIsSettled(bare, envPath())).toBe(false);