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

fix: parse quoted .env settings identically in PM2 and setup (#9471)

Adam Eivy2c432c4d6b6c
diff --git a/ecosystem.config.cjs b/ecosystem.config.cjs
index d0fd70997b..a3b15fd8de 100644
--- a/ecosystem.config.cjs
+++ b/ecosystem.config.cjs
@@ -19,28 +19,20 @@ const BASE_ENV = {
// running server instead of silently falling back to the `portos` defaults
// while setup provisioned something else (#8447). An explicit process.env wins
// over the .env file so a one-off shell override still works.
-const fs = require('fs');
const envFile = path.join(__dirname, '.env');
-const readEnvValue = (content, key) => content.match(new RegExp(`^${key}=(\\S+)`, 'm'))?.[1] ?? null;
-let pgMode = 'docker';
-let envServerMaxMemory = null;
-let envPgPassword = null;
-let envPgUser = null;
-let envPgDatabase = null;
-let envPgHost = null;
-let envPgPort = null;
-let envPgPortDocker = null;
-try {
- const envContent = fs.readFileSync(envFile, 'utf8');
- pgMode = readEnvValue(envContent, 'PGMODE') || pgMode;
- envServerMaxMemory = readEnvValue(envContent, 'PORTOS_SERVER_MAX_MEMORY');
- envPgPassword = readEnvValue(envContent, 'PGPASSWORD');
- envPgUser = readEnvValue(envContent, 'PGUSER');
- envPgDatabase = readEnvValue(envContent, 'PGDATABASE');
- envPgHost = readEnvValue(envContent, 'PGHOST');
- envPgPort = readEnvValue(envContent, 'PGPORT');
- envPgPortDocker = readEnvValue(envContent, 'PGPORT_DOCKER');
-} catch { /* no .env file — default to docker */ }
+// Parsed by the same dependency-free grammar setup uses (scripts/lib/envFile.cjs),
+// so quoted values resolve identically here and in setup (#9471).
+const { parseEnvFile } = require('./scripts/lib/envFile.cjs');
+const dotenv = parseEnvFile(envFile); // {} when .env is missing
+const envValue = (key) => dotenv[key] || null;
+const pgMode = envValue('PGMODE') || 'docker';
+const envServerMaxMemory = envValue('PORTOS_SERVER_MAX_MEMORY');
+const envPgPassword = envValue('PGPASSWORD');
+const envPgUser = envValue('PGUSER');
+const envPgDatabase = envValue('PGDATABASE');
+const envPgHost = envValue('PGHOST');
+const envPgPort = envValue('PGPORT');
+const envPgPortDocker = envValue('PGPORT_DOCKER');
// Same precedence as scripts/setup-db.js: process.env → .env → default. Keep the
// 'portos' password fallback (AGENTS.md: intentional backward-compatible
diff --git a/scripts/ecosystemEnv.test.js b/scripts/ecosystemEnv.test.js
index 3653c2df17..cf06fca57d 100644
--- a/scripts/ecosystemEnv.test.js
+++ b/scripts/ecosystemEnv.test.js
@@ -16,14 +16,17 @@
*/
import { describe, it, expect, afterEach } from 'vitest';
import { createRequire } from 'module';
-import { mkdtempSync, rmSync, readFileSync, writeFileSync } from 'fs';
+import { mkdirSync, mkdtempSync, rmSync, readFileSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
+import { parseEnvFile } from './lib/envFile.js';
const require = createRequire(import.meta.url);
const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
const CONFIG_SOURCE = readFileSync(join(REPO_ROOT, 'ecosystem.config.cjs'), 'utf8');
+// The config require()s this dependency-free parser (#9471), so each temp copy needs it too.
+const PARSER_SOURCE = readFileSync(join(REPO_ROOT, 'scripts', 'lib', 'envFile.cjs'), 'utf8');
let tmpDirs = [];
@@ -40,10 +43,16 @@ afterEach(() => {
* duration of the load only.
*/
function loadConfig(envContent, overrideEnv = {}) {
+ return loadConfigIn(envContent, overrideEnv).config;
+}
+
+function loadConfigIn(envContent, overrideEnv = {}) {
const dir = mkdtempSync(join(tmpdir(), 'portos-ecosystem-env-'));
tmpDirs.push(dir);
const configPath = join(dir, 'ecosystem.config.cjs');
writeFileSync(configPath, CONFIG_SOURCE);
+ mkdirSync(join(dir, 'scripts', 'lib'), { recursive: true });
+ writeFileSync(join(dir, 'scripts', 'lib', 'envFile.cjs'), PARSER_SOURCE);
if (envContent !== null) writeFileSync(join(dir, '.env'), envContent);
const savedEnv = {};
@@ -54,7 +63,7 @@ function loadConfig(envContent, overrideEnv = {}) {
}
try {
delete require.cache[configPath];
- return require(configPath);
+ return { config: require(configPath), dir };
} finally {
for (const key of Object.keys(savedEnv)) {
if (savedEnv[key] === undefined) delete process.env[key];
@@ -141,3 +150,56 @@ describe('ecosystem.config.cjs PostgreSQL env', () => {
}
});
});
+
+describe('ecosystem.config.cjs parses .env with the setup grammar (#9471)', () => {
+ const server = (config) => config.apps.find((a) => a.name === 'portos-server');
+
+ it.each([
+ ['double', (v) => `"${v}"`],
+ ['single', (v) => `'${v}'`],
+ ])('resolves %s-quoted native mode and port to the endpoint setup resolves', (_label, quote) => {
+ const env = `PGMODE=${quote('native')}\nPGPORT=${quote('5433')}\n`;
+ const { config, dir } = loadConfigIn(env, clearedPgEnv);
+ const setup = parseEnvFile(join(dir, '.env'));
+ expect(setup).toMatchObject({ PGMODE: 'native', PGPORT: '5433' });
+ expect(config.DATABASE_MODE).toBe('native');
+ expect(config.DATABASE_ENDPOINTS.native.port).toBe(5433);
+ expect(server(config).env.PGPORT).toBe(5433);
+ });
+
+ it('resolves a quoted native port under an unquoted mode to a finite endpoint', () => {
+ const config = loadConfig('PGMODE=native\nPGPORT="5433"\n', clearedPgEnv);
+ expect(config.DATABASE_ENDPOINTS.native.port).toBe(5433);
+ });
+
+ it('preserves a quoted password with spaces exactly, for server and CoS, and still lets the shell win', () => {
+ const env = 'PGPASSWORD="example secret pass"\n';
+ const { config, dir } = loadConfigIn(env, clearedPgEnv);
+ expect(parseEnvFile(join(dir, '.env')).PGPASSWORD).toBe('example secret pass');
+ expect(server(config).env.PGPASSWORD).toBe('example secret pass');
+ expect(config.apps.find((a) => a.name === 'portos-cos').env.PGPASSWORD).toBe('example secret pass');
+
+ const overridden = loadConfig(env, { ...clearedPgEnv, PGPASSWORD: 'from-shell' });
+ expect(server(overridden).env.PGPASSWORD).toBe('from-shell');
+ });
+
+ it('reads quoted user/database/host/memory settings, with whitespace around the assignment', () => {
+ const env = `PGUSER = "example user"\nPGDATABASE='example db'\nPGHOST = "db.example.com"\nPORTOS_SERVER_MAX_MEMORY = "6G"\n`;
+ const config = loadConfig(env, { ...clearedPgEnv, PORTOS_SERVER_MAX_MEMORY: undefined });
+ expect(server(config).env).toMatchObject({ PGUSER: 'example user', PGDATABASE: 'example db', PGHOST: 'db.example.com' });
+ expect(server(config).max_memory_restart).toBe('6G');
+ });
+
+ it('still keeps a quoted PGPASSWORD out of the non-DB apps', () => {
+ const { apps } = loadConfig('PGPASSWORD="example secret pass"\n', clearedPgEnv);
+ for (const name of ['portos-ui', 'portos-autofixer', 'portos-autofixer-ui', 'portos-browser']) {
+ expect(apps.find((a) => a.name === name).env.PGPASSWORD).toBeUndefined();
+ }
+ });
+
+ it('keeps the docker defaults when .env is missing', () => {
+ const config = loadConfig(null, clearedPgEnv);
+ expect(config.DATABASE_MODE).toBe('docker');
+ expect(server(config).env.PGPORT).toBe(5561);
+ });
+});
diff --git a/scripts/lib/envFile.cjs b/scripts/lib/envFile.cjs
new file mode 100644
index 0000000000..87bb17973e
--- /dev/null
+++ b/scripts/lib/envFile.cjs
@@ -0,0 +1,53 @@
+/**
+ * Dependency-free `.env` parser — the single owner of PortOS's pre-install
+ * `.env` grammar, shared by setup (`scripts/lib/envFile.js`, ESM) and the PM2
+ * config (`ecosystem.config.cjs`, CJS).
+ *
+ * ZERO external dependencies and no imports from server/ — both consumers run
+ * before/around `npm install`. CommonJS so `require()` works on every supported
+ * Node version and from the PM2 config, while ESM callers import it by default.
+ */
+'use strict';
+
+const { readFileSync } = require('fs');
+
+/**
+ * Parse `.env` text into a key/value map.
+ * Tolerates blank lines, # comments, whitespace around keys, `=` and values,
+ * CRLF line endings, and optional surrounding single/double quotes around values
+ * (quotes are removed; spaces inside them are preserved).
+ *
+ * @param {string} content
+ * @returns {Record<string, string>}
+ */
+function parseEnvContent(content) {
+ const result = {};
+ for (const line of String(content).split('\n')) {
+ const trimmed = line.trim();
+ if (!trimmed || trimmed.startsWith('#')) continue;
+ const idx = trimmed.indexOf('=');
+ if (idx === -1) continue;
+ const key = trimmed.slice(0, idx).trim();
+ let value = trimmed.slice(idx + 1).trim();
+ if ((value.startsWith('"') && value.endsWith('"')) ||
+ (value.startsWith("'") && value.endsWith("'"))) {
+ value = value.slice(1, -1);
+ }
+ result[key] = value;
+ }
+ return result;
+}
+
+/**
+ * Parse a .env file. Returns {} when the file is missing or unreadable.
+ *
+ * @param {string} filePath - absolute path to the .env file
+ * @returns {Record<string, string>}
+ */
+function parseEnvFile(filePath) {
+ let content = '';
+ try { content = readFileSync(filePath, 'utf8'); } catch { return {}; }
+ return parseEnvContent(content);
+}
+
+module.exports = { parseEnvContent, parseEnvFile };
diff --git a/scripts/lib/envFile.js b/scripts/lib/envFile.js
index c89d7b2f9e..53905766ae 100644
--- a/scripts/lib/envFile.js
+++ b/scripts/lib/envFile.js
@@ -6,34 +6,11 @@
*/
import { readFileSync, writeFileSync } from 'fs';
+import envFileParser from './envFile.cjs';
-/**
- * Parse a .env file into a key/value map.
- * Tolerates blank lines, # comments, and optional surrounding single/double
- * quotes around values. Returns {} when the file is missing or unreadable.
- *
- * @param {string} filePath - absolute path to the .env file
- * @returns {Record<string, string>}
- */
-export function parseEnvFile(filePath) {
- const result = {};
- let content = '';
- try { content = readFileSync(filePath, 'utf8'); } catch { return result; }
- for (const line of content.split('\n')) {
- const trimmed = line.trim();
- if (!trimmed || trimmed.startsWith('#')) continue;
- const idx = trimmed.indexOf('=');
- if (idx === -1) continue;
- const key = trimmed.slice(0, idx).trim();
- let value = trimmed.slice(idx + 1).trim();
- if ((value.startsWith('"') && value.endsWith('"')) ||
- (value.startsWith("'") && value.endsWith("'"))) {
- value = value.slice(1, -1);
- }
- result[key] = value;
- }
- return result;
-}
+// The grammar lives in envFile.cjs so ecosystem.config.cjs (PM2) parses `.env`
+// exactly as setup does; see that file for the supported syntax.
+export const { parseEnvContent, parseEnvFile } = envFileParser;
/**
* Set (or add) a single key in a .env file without touching other lines.
diff --git a/scripts/lib/envFile.test.js b/scripts/lib/envFile.test.js
index 6928c01964..c918d02d76 100644
--- a/scripts/lib/envFile.test.js
+++ b/scripts/lib/envFile.test.js
@@ -64,6 +64,15 @@ describe('parseEnvFile', () => {
});
});
+describe('pre-install module boundary', () => {
+ it('loads the CommonJS parser without any installed dependency', async () => {
+ const { createRequire } = await import('module');
+ const cjs = createRequire(import.meta.url)('./envFile.cjs');
+ expect(Object.keys(cjs).sort()).toEqual(['parseEnvContent', 'parseEnvFile']);
+ expect(cjs.parseEnvContent('A = "x y"\r\nB=\'z\'\n')).toEqual({ A: 'x y', B: 'z' });
+ });
+});
+
describe('upsertEnvKey', () => {
it('creates .env with the key when file is missing', () => {
upsertEnvKey(envPath, 'PGMODE', 'docker');
diff --git a/server/lib/databaseMaintenanceJournal.test.js b/server/lib/databaseMaintenanceJournal.test.js
index bc4da95945..2ba0875f3c 100644
--- a/server/lib/databaseMaintenanceJournal.test.js
+++ b/server/lib/databaseMaintenanceJournal.test.js
@@ -1,10 +1,11 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { spawn, spawnSync } from 'node:child_process';
-import { copyFileSync, mkdtempSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
+import { mkdtempSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { createDatabaseMaintenanceJournal } from './databaseMaintenanceJournal.js';
+import { copyEcosystemConfig } from '../test/fixtures/ecosystemConfigCopy.js';
// Pass-through fs whose readFileSync can run one hook before or after it: the
// only way to land a concurrent fence move deterministically between read()'s
@@ -350,7 +351,7 @@ describe('persistent database maintenance boundary', () => {
});
it('drives the operator CLI against disposable saved configuration without touching PostgreSQL', () => {
- copyFileSync(new URL('../../ecosystem.config.cjs', import.meta.url), join(root, 'ecosystem.config.cjs'));
+ copyEcosystemConfig(root);
const config = 'PGMODE=native\nPGPORT=6543\nPGPORT_DOCKER=6544\n';
writeFileSync(join(root, '.env'), config);
const cli = new URL('../../scripts/database-maintenance.mjs', import.meta.url);
@@ -391,7 +392,7 @@ describe('persistent database maintenance boundary', () => {
});
it('keeps maintenance direction when invoked by a Docker-managed process', () => {
- copyFileSync(new URL('../../ecosystem.config.cjs', import.meta.url), join(root, 'ecosystem.config.cjs'));
+ copyEcosystemConfig(root);
writeFileSync(join(root, '.env'), 'PGMODE=docker\nPGPORT=6543\nPGPORT_DOCKER=6544\n');
const cli = fileURLToPath(new URL('../../scripts/database-maintenance.mjs', import.meta.url));
const env = { ...childEnv, PORTOS_DATA_ROOT: root, PGPORT: '6544',
diff --git a/server/routes/databasePreflight.test.js b/server/routes/databasePreflight.test.js
index 20067ccbbe..9785770f68 100644
--- a/server/routes/databasePreflight.test.js
+++ b/server/routes/databasePreflight.test.js
@@ -1,8 +1,9 @@
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import express from 'express';
-import { copyFileSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { request } from '../lib/testHelper.js';
+import { copyEcosystemConfig } from '../test/fixtures/ecosystemConfigCopy.js';
vi.mock('../lib/paths.js', async importOriginal => {
const { makePathsProxy, lazyTempDataRoot } = await import('../lib/mockPathsDataRoot.js');
@@ -56,7 +57,7 @@ beforeEach(() => {
vi.clearAllMocks();
for (const [key, value] of Object.entries({ PGHOST: 'localhost', PGPORT: '5432', PORTOS_NATIVE_PGPORT: '5432', PGPORT_DOCKER: '5561', PGUSER: 'example_role', PGDATABASE: 'example_test', PGPASSWORD: 'example-only' })) vi.stubEnv(key, value);
Object.assign(POOL_CONFIG, { host: 'localhost', port: 5432, user: 'example_role', database: 'example_test' });
- copyFileSync(new URL('../../ecosystem.config.cjs', import.meta.url), join(PATHS.installRoot, 'ecosystem.config.cjs'));
+ copyEcosystemConfig(PATHS.installRoot);
saveMode('native');
getSystemActivity.mockResolvedValue(idle());
countActiveCosAgents.mockResolvedValue(0);
diff --git a/server/test/fixtures/databaseCutoverStubs.js b/server/test/fixtures/databaseCutoverStubs.js
index 08008be0a6..131df2d7f4 100644
--- a/server/test/fixtures/databaseCutoverStubs.js
+++ b/server/test/fixtures/databaseCutoverStubs.js
@@ -11,17 +11,18 @@
// databaseCutoverHandshake + databaseBootFence against a pool configured
// from its environment, then records `server booted` (or `server refused`).
// Its stderr is kept in `surrogate-stderr.log` as failure evidence.
-import { appendFileSync, chmodSync, closeSync, copyFileSync, existsSync, openSync, readFileSync, writeFileSync } from 'node:fs';
+import { appendFileSync, chmodSync, closeSync, existsSync, openSync, readFileSync, writeFileSync } from 'node:fs';
import { spawn } from '../../lib/childProcess.js';
import { join } from 'node:path';
import { pathToFileURL } from 'node:url';
+import { copyEcosystemConfig } from './ecosystemConfigCopy.js';
const handshakeUrl = new URL('../../services/databaseCutoverHandshake.js', import.meta.url).href;
const bootFenceUrl = new URL('../../services/databaseBootFence.js', import.meta.url).href;
export function installCutoverStubs(root, dir, { source, target }) {
writeFileSync(join(dir, 'endpoints.json'), JSON.stringify({ [source.mode]: source, [target.mode]: target }));
- copyFileSync(new URL('../../../ecosystem.config.cjs', import.meta.url), join(root, 'ecosystem.config.cjs'));
+ copyEcosystemConfig(root);
const pgStub = join(dir, 'pg-stub.mjs');
writeFileSync(pgStub, `import { existsSync, readFileSync } from 'node:fs';
diff --git a/server/test/fixtures/ecosystemConfigCopy.js b/server/test/fixtures/ecosystemConfigCopy.js
new file mode 100644
index 0000000000..dd32c84045
--- /dev/null
+++ b/server/test/fixtures/ecosystemConfigCopy.js
@@ -0,0 +1,15 @@
+import { copyFileSync, mkdirSync } from 'node:fs';
+import { join } from 'node:path';
+
+const repoFile = (rel) => new URL(`../../../${rel}`, import.meta.url);
+
+/**
+ * Copy the REAL `ecosystem.config.cjs` into a disposable install root, with the
+ * dependency-free `.env` parser it `require()`s (#9471) — a bare config copy
+ * would throw MODULE_NOT_FOUND when loaded from the temp root.
+ */
+export function copyEcosystemConfig(root) {
+ mkdirSync(join(root, 'scripts', 'lib'), { recursive: true });
+ copyFileSync(repoFile('ecosystem.config.cjs'), join(root, 'ecosystem.config.cjs'));
+ copyFileSync(repoFile('scripts/lib/envFile.cjs'), join(root, 'scripts', 'lib', 'envFile.cjs'));
+}