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: close credential gaps in managed process launches

[._.]/ Adam Eivy7d97191f27a9
diff --git a/server/lib/processEnv.js b/server/lib/processEnv.js
index 08bdb248b0..bdba7bd1b7 100644
--- a/server/lib/processEnv.js
+++ b/server/lib/processEnv.js
@@ -138,12 +138,14 @@ export function buildSafeCliBaseEnv(env = process.env, provider = null) {
// server state.
const SERVER_SECRET_ENV_KEYS = new Set([
'PRIVACY_VAULT_KEY',
+ 'FAL_KEY', 'RUNWAYML_API_SECRET', 'REACTOR_API_KEY', 'ARTIFICIAL_ANALYSIS_API_KEY',
+ 'HUGGINGFACE_TOKEN', 'HUGGINGFACE_HUB_TOKEN', 'HUGGINGFACEHUB_API_TOKEN', 'HUGGING_FACE_HUB_TOKEN',
...Object.values(CLI_PROVIDER_AUTH_RULES).flatMap((rule) => rule.keys),
]);
const SERVER_SECRET_ENV_PATTERNS = [
/^PG[A-Z]+$/,
/^PORTOS_[A-Z_]*(TOKEN|KEY|PASSWORD|SECRET)$/,
- /^(ANTHROPIC|OPENAI|GEMINI|XAI|GROK|KIMI|MOONSHOT|CURSOR|NVIDIA|OPENROUTER|CIVITAI|HF)_[A-Z_]*(API_KEY|AUTH_TOKEN|TOKEN)$/,
+ /^(ANTHROPIC|CLAUDE|OPENAI|GEMINI|XAI|GROK|KIMI|MOONSHOT|CURSOR|NVIDIA|OPENROUTER|CIVITAI|HF)_[A-Z_]*(API_KEY|AUTH_TOKEN|TOKEN)$/,
];
// Matched case-insensitively: Windows treats `PgPassword` as `PGPASSWORD`.
diff --git a/server/lib/processEnv.test.js b/server/lib/processEnv.test.js
index e23f60d584..0bfcef6653 100644
--- a/server/lib/processEnv.test.js
+++ b/server/lib/processEnv.test.js
@@ -210,6 +210,10 @@ describe('withoutServerSecretsEnv', () => {
PATH: '/usr/bin', HOME: '/home/example', NODE_ENV: 'production', PORT: '5555',
PRIVACY_VAULT_KEY: 'k', PGPASSWORD: 'p', PGHOST: 'h', PGDATABASE: 'd',
PORTOS_API_TOKEN: 't', ANTHROPIC_API_KEY: 'a', OPENAI_API_KEY: 'o', GEMINI_API_KEY: 'g',
+ CLAUDE_CODE_OAUTH_TOKEN: 'claude-session', Claude_Code_OAuth_Token: 'mixed-case-session',
+ GEMINI_CLI_AUTH_TOKEN: 'gemini-session',
+ FAL_KEY: 'fal', RUNWAYML_API_SECRET: 'runway', REACTOR_API_KEY: 'reactor', ARTIFICIAL_ANALYSIS_API_KEY: 'catalog',
+ HUGGINGFACE_TOKEN: 'hf', HUGGINGFACE_HUB_TOKEN: 'hf', HUGGINGFACEHUB_API_TOKEN: 'hf', HUGGING_FACE_HUB_TOKEN: 'hf',
PgPassword: 'mixed-case', DATABASE_URL: 'app-owned', STRIPE_KEY: 'app-owned', PGP_NOTE: 'not a libpq var',
};
diff --git a/server/services/eidoverse.js b/server/services/eidoverse.js
index b7d1e34111..7e2dd6b267 100644
--- a/server/services/eidoverse.js
+++ b/server/services/eidoverse.js
@@ -157,7 +157,8 @@ const bunRuntimeEnv = (bunExecutable) => {
};
async function resolveBunRuntime() {
- if (await commandExists('bun')) return { command: 'bun', env: withoutServerSecretsEnv(process.env) };
+ const ambientEnv = withoutServerSecretsEnv(process.env);
+ if (await commandExists('bun', ['--version'], { env: ambientEnv })) return { command: 'bun', env: ambientEnv };
const command = getBunExecutable();
const env = bunRuntimeEnv(command);
diff --git a/server/services/eidoverse.test.js b/server/services/eidoverse.test.js
index 7e09ba1670..47d07af99b 100644
--- a/server/services/eidoverse.test.js
+++ b/server/services/eidoverse.test.js
@@ -3,6 +3,7 @@ import { join } from 'path';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { execFileSync } from 'node:child_process';
+import { commandExists } from '../lib/commandExists.js';
const mock = vi.hoisted(() => ({
existing: new Set(),
@@ -131,6 +132,10 @@ describe('Eidoverse managed-app installer', () => {
const installEnv = mock.spawn.mock.calls.find(([, args]) => args[0] === 'install')[2].env;
expect(installEnv).not.toHaveProperty('PRIVACY_VAULT_KEY');
expect(installEnv).not.toHaveProperty('PGPASSWORD');
+ for (const [, , options] of vi.mocked(commandExists).mock.calls) {
+ expect(options.env).not.toHaveProperty('PRIVACY_VAULT_KEY');
+ expect(options.env).not.toHaveProperty('PGPASSWORD');
+ }
vi.unstubAllEnvs();
expect(mock.cloneRepo).toHaveBeenCalledWith(SELECTED_WORLDS_REPO, { branch: '' });
diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.js
index 0141849796..ee6914ca69 100644
--- a/server/services/imageGen/codex.js
+++ b/server/services/imageGen/codex.js
@@ -165,7 +165,9 @@ export async function checkConnection({ codexPath } = {}) {
// "yes the binary exists and is reachable".
const bin = codexPath || DEFAULT_BIN;
const prepared = prepareCliSpawn(bin, ['--version']);
- const result = await bufferedSpawn(prepared.command, prepared.args, { timeoutMs: 15_000, shell: false });
+ const result = await bufferedSpawn(prepared.command, prepared.args, {
+ timeoutMs: 15_000, shell: false, env: withoutServerSecretsEnv(process.env, { keep: CODEX_AUTH_ENV_KEYS }),
+ });
if (result.error) {
return { connected: false, mode: IMAGE_GEN_MODE.CODEX, reason: `Codex CLI not found (${result.error.message})` };
}
diff --git a/server/services/imageGen/codex.test.js b/server/services/imageGen/codex.test.js
index e8f1fe9c09..9a41bdac8a 100644
--- a/server/services/imageGen/codex.test.js
+++ b/server/services/imageGen/codex.test.js
@@ -123,6 +123,21 @@ afterEach(async () => {
});
describe('codex provider — checkConnection', () => {
+ it('uses the same credential boundary for the version probe as rendering', async () => {
+ vi.stubEnv('PRIVACY_VAULT_KEY', 'vault');
+ vi.stubEnv('CLAUDE_CODE_OAUTH_TOKEN', 'claude');
+ vi.stubEnv('FAL_KEY', 'fal');
+ vi.stubEnv('OPENAI_API_KEY', 'codex-own');
+ const result = codex.checkConnection();
+ await flush();
+ const call = spawnCalls[0];
+ expect(call.options.env).not.toHaveProperty('PRIVACY_VAULT_KEY');
+ expect(call.options.env).not.toHaveProperty('CLAUDE_CODE_OAUTH_TOKEN');
+ expect(call.options.env).not.toHaveProperty('FAL_KEY');
+ expect(call.options.env.OPENAI_API_KEY).toBe('codex-own');
+ call.child.emit('close', 0);
+ expect((await result).connected).toBe(true);
+ });
it.each([
['stdout', 'codex-cli 1.2.3', 'codex-cli 1.2.3'],
['stderr', 'Codex version 2.3.4', 'codex-cli 2.3.4'],
diff --git a/server/services/pm2.ecosystemEnv.test.js b/server/services/pm2.ecosystemEnv.test.js
new file mode 100644
index 0000000000..762f162595
--- /dev/null
+++ b/server/services/pm2.ecosystemEnv.test.js
@@ -0,0 +1,66 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { mkdtemp, readdir, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { execFile } from 'node:child_process';
+import { promisify } from 'node:util';
+import { EventEmitter } from 'node:events';
+import { pinPlatform } from '../lib/testHelper.js';
+
+vi.mock('pm2', () => ({ default: {} }));
+const mockSpawn = vi.hoisted(() => vi.fn());
+vi.mock('../lib/childProcess.js', async original => ({ ...(await original()), spawn: mockSpawn }));
+const execFileAsync = promisify(execFile);
+let root;
+afterEach(async () => {
+ vi.unstubAllEnvs();
+ vi.clearAllMocks();
+ if (root) await rm(root, { recursive: true, force: true });
+});
+
+describe('ecosystem launch credential boundary', () => {
+ it.each([['linux', false], ['win32', false], ['win32', true]])('evaluates %s configs safely and removes its wrapper (configThrows=%s)', async (platform, configThrows) => {
+ root = await mkdtemp(join(tmpdir(), 'portos-ecosystem-env-'));
+ await writeFile(join(root, 'relative.cjs'), 'module.exports = "relative-import";');
+ await writeFile(join(root, 'ecosystem.config.cjs'), configThrows ? 'throw new Error("fixture config rejected");' : `module.exports = { apps: [{
+ name: 'example-app', script: 'npm', env: {
+ PGPASSWORD: 'app-owned', relative: require('./relative.cjs'),
+ leaked: process.env.PRIVACY_VAULT_KEY || process.env.CLAUDE_CODE_OAUTH_TOKEN || process.env.FAL_KEY || null
+ }
+ }] };`);
+ vi.stubEnv('PRIVACY_VAULT_KEY', 'vault');
+ vi.stubEnv('CLAUDE_CODE_OAUTH_TOKEN', 'claude');
+ vi.stubEnv('FAL_KEY', 'fal');
+ vi.stubEnv('PGPASSWORD', 'server-database');
+ const restore = pinPlatform(platform);
+ let service;
+ try { vi.resetModules(); service = await import('./pm2.js'); }
+ finally { restore(); }
+ let evaluated;
+ mockSpawn.mockImplementation((_bin, argv, options) => {
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ // Evaluate precisely what the PM2 CLI would require, with its supplied
+ // environment, without contacting or starting any PM2 daemon.
+ const config = join(root, argv[2]);
+ void execFileAsync(process.execPath, ['-e', 'process.stdout.write(JSON.stringify(require(process.argv[1])))', config], {
+ cwd: options.cwd, env: options.env,
+ }).then(({ stdout }) => {
+ evaluated = JSON.parse(stdout);
+ child.emit('close', 0);
+ }, error => child.emit('error', error));
+ return child;
+ });
+ const launch = service.startFromEcosystem(root, ['example-app'], join(root, 'pm2'));
+ if (configThrows) await expect(launch).rejects.toThrow('fixture config rejected');
+ else {
+ await launch;
+ expect(evaluated.apps[0].env).toEqual({ PGPASSWORD: 'app-owned', relative: 'relative-import', leaked: null });
+ if (platform === 'win32') expect(evaluated.apps[0]).toMatchObject({ interpreter: 'none', windowsHide: true, max_restarts: 10 });
+ }
+ expect((await readdir(root)).filter(name => name.startsWith('_portos_pm2_'))).toEqual([]);
+ expect(process.env.PRIVACY_VAULT_KEY).toBe('vault');
+ expect(process.env.PGPASSWORD).toBe('server-database');
+ });
+});
diff --git a/server/services/pm2.js b/server/services/pm2.js
index 055bd80e05..d1d7ecacfb 100644
--- a/server/services/pm2.js
+++ b/server/services/pm2.js
@@ -4,8 +4,9 @@ import { existsSync } from 'fs';
import { writeFile, unlink } from 'fs/promises';
import { join, dirname } from 'path';
import { createRequire } from 'module';
+import { randomUUID } from 'crypto';
import { homedir } from 'os';
-import { atomicWrite, safeJSONParse, sleep, tryReadFile } from '../lib/fileUtils.js';
+import { atomicWrite, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';
import { parseCommandArgs } from '../lib/commandSecurity.js';
import { parsePm2JlistStdout } from '../lib/pm2Jlist.js';
import { PATHS } from '../lib/paths.js';
@@ -725,7 +726,7 @@ async function spawnPm2StartCommand(name, cwd, script, args, { autorestart, maxR
async function spawnPm2StartEcosystem(cwd, ecosystemFile, processNames, pm2Home) {
const args = ['start', ecosystemFile];
if (processNames.length > 0) args.push('--only', processNames.join(','));
- const { stdout } = await execPm2(args, { cwd, env: buildEnv(pm2Home) });
+ const { stdout } = await execPm2(args, { cwd, env: buildStartEnv(pm2Home) });
clearJlistCache(pm2Home);
return { success: true, output: stdout };
}
@@ -839,73 +840,29 @@ export async function startFromEcosystem(cwd, processNames = [], pm2Home = null)
}
/**
- * Windows-specific ecosystem start: loads config, patches non-JS scripts
- * with interpreter:'none' so PM2 spawns them instead of forking (which would
- * try to require() .cmd batch files as JavaScript).
+ * Evaluate the app's config inside the sanitized PM2 child, never in the
+ * server: a config can copy process.env into an app-specific key before the
+ * CLI's inheritance filter runs. Requiring the original file preserves its
+ * relative imports and __dirname while this wrapper patches Windows launchers.
*/
async function startFromEcosystemWindows(cwd, ecosystemFile, processNames, pm2Home) {
- // Each file name is a module-level literal joined at its own require() so the
- // test memo can key every tracked ecosystem file (scripts/lib/testMemo.js).
- const configPath = ecosystemFile === ECOSYSTEM_FILE ? join(cwd, ECOSYSTEM_FILE) : join(cwd, LEGACY_ECOSYSTEM_FILE);
-
- // Try to load and patch the config
- let config;
- try {
- // Clear module cache to get fresh config on repeated starts
- try { delete require.cache[require.resolve(configPath)]; } catch {}
- config = ecosystemFile === ECOSYSTEM_FILE ? require(join(cwd, ECOSYSTEM_FILE)) : require(join(cwd, LEGACY_ECOSYSTEM_FILE));
- } catch (err) {
- // If we can't load the config (syntax error, missing deps, etc.),
- // fall back to unpatched start — PM2 may still handle it
- console.log(`⚠️ Could not load ${ecosystemFile} for Windows patching: ${err.message}`);
- return spawnPm2StartEcosystem(cwd, ecosystemFile, processNames, pm2Home);
- }
-
- const apps = config.apps || [];
- let needsPatch = false;
-
- for (const app of apps) {
- // Skip apps not in our target list
- if (processNames.length > 0 && !processNames.includes(app.name)) continue;
-
- // Patch non-JS scripts to use interpreter:'none' (spawn instead of fork)
- if (app.script && !isJsScript(app.script) && app.interpreter !== 'none') {
- app.interpreter = 'none';
- needsPatch = true;
- }
-
- // Ensure windowsHide and restart safety on all apps
- if (!app.windowsHide) {
- app.windowsHide = true;
- needsPatch = true;
- }
- if (app.autorestart !== false && !app.max_restarts) {
- app.max_restarts = 10;
- needsPatch = true;
- }
- }
-
- if (!needsPatch) {
- // No modifications needed — use original config as-is
- return spawnPm2StartEcosystem(cwd, ecosystemFile, processNames, pm2Home);
- }
-
- // Write patched config to a temp file.
- // JSON.stringify is safe here because require() already executed the CJS module,
- // resolving all dynamic expressions (__dirname, path.join, process.env) to plain
- // string/number/boolean values. The resulting apps array has no functions or symbols.
- const tempFile = `_portos_pm2_${process.pid}_${Date.now()}.config.cjs`;
+ const tempFile = `_portos_pm2_${randomUUID()}.config.cjs`;
const tempPath = join(cwd, tempFile);
-
+ const content = `const config = require(${JSON.stringify(`./${ecosystemFile}`)});
+const selected = ${JSON.stringify(processNames)};
+for (const app of config.apps || []) {
+ if (selected.length && !selected.includes(app.name)) continue;
+ if (app.script && !/\\.(?:js|mjs|cjs|ts)$/i.test(app.script) && app.interpreter !== 'none') app.interpreter = 'none';
+ if (!app.windowsHide) app.windowsHide = true;
+ if (app.autorestart !== false && !app.max_restarts) app.max_restarts = 10;
+}
+module.exports = config;
+`;
+ await writeFile(tempPath, content, { flag: 'wx', mode: 0o600 });
try {
- const content = `module.exports = ${JSON.stringify({ apps }, null, 2)};\n`;
- await writeFile(tempPath, content);
- console.log(`🔧 Patched ${ecosystemFile} for Windows → ${tempFile}`);
return await spawnPm2StartEcosystem(cwd, tempFile, processNames, pm2Home);
} finally {
- // spawnPm2StartEcosystem resolves on child 'close' (PM2 CLI has exited, config already loaded).
- // Small delay as extra safety before removing the temp file.
- await sleep(500);
+ // The CLI has closed, so it has finished evaluating this invocation's file.
await unlink(tempPath).catch(() => {});
}
}