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: keep server secrets out of managed-app, deploy and install child environments (#12497)
[._.]/ Adam Eivy426b477b907f
diff --git a/server/lib/README.md b/server/lib/README.mdindex 72b7268a28..aec05dfb29 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -469,7 +469,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `glabArgs.js` | `GLAB_JSON_ARGS`, `withGlabJson(args)` — pure `glab` argv conventions. The JSON output flag is `--output json`, NOT `-F json`: on `glab issue list` (and only there) `-F` is `--output-format` (details/ids/urls), so `-F json` is accepted, ignored, and answers with the human table at exit 0. Shared by all three `glab` runners so the spelling has one definition; guarded tree-wide by `services/gitlab.glabFlags.test.js`. || `killWithEscalation.js` | `killWithEscalation(proc, {label, stillRunning, delayMs=8000})` — shared SIGTERM→grace→SIGKILL cancel-escalation for spawn-based media jobs. Sends SIGTERM, then escalates to SIGKILL after `delayMs` only when `stillRunning()` holds and the child hasn't exited (`exitCode===null && signalCode===null`). The timer is unref'd and the callback is try/catch-wrapped (runs outside the request lifecycle). Converges musicVideo/render, videoTimeline, imageGen local+codex, videoGen, loraTraining, and the yt-dlp track import cancel paths. || `npmGlobalBin.js` | `adoptNpmGlobalBinDir()` — puts the directory `npm install --global` actually writes to onto `process.env.PATH`, from one cached `npm prefix -g`. npm resolves its prefix through a config cascade (cli flags, `npm_config_*`, project/user/global npmrc, a builtin npmrc that interpolates env vars), so guessing it from `%APPDATA%`/`$HOME` reproduces the bug on the next host — only npm can answer. Exists because a host whose npm prefix is NOT the directory its Node installer put on PATH (a machine-wide Windows prefix vs the per-user `%APPDATA%\npm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and then reported it unrunnable, advising a restart that inherits the same PATH. Called at boot in BOTH processes that spawn provider CLIs (`services/bootstrap.js`, `cos-runner/index.js`) and again from `providerRuntimeInstaller.js`'s probe, because on a first install the prefix directory did not exist when boot looked. |-| `processEnv.js` | `stripDebugMallocEnv(env)` / `safeChildProcessEnv(extra)` — drop macOS `Malloc*` debug env vars before spawning a child. `safeChildProcessOptions(options)` adds that sanitized environment plus `windowsHide: true`, preventing detached PM2 subprocesses from opening transient Windows console UI; `buildSafeCliBaseEnv(env, provider)` allowlists runtime/delivery essentials and only the selected CLI's ambient provider auth before an AI CLI inherits the server environment. Route Node→Python and other background CLI spawns through the process helpers. Also `whichFirst(name)` — first-hit `which`/`where` PATH probe (safe options, 5s timeout, direct PATH fallback on probe failure) returning the absolute binary path or `null`; `whichFirstSync(name)` provides the same contract without the await; `findCommandOnPath(name, { env, cwd })` resolves an executable from the exact child environment without needing `which` itself on that PATH. `adoptPathDirs(dirs)` appends the ones that exist and are not already there to THIS process's `process.env.PATH` (case-insensitively on Windows), which fixes this process AND every child, since the env builders above derive from `process.env` — the only fix that reaches a CLI launched by BARE NAME through node-pty. Shared by `npmGlobalBin.js` and `services/llamaServerManager.js`'s winget-shim adoption. `windowsPowerShell51Path(env)` is the fixed Windows PowerShell 5.1 location under `SystemRoot`, shared by `interactiveShellResolver.js` and `nativeTrash.js`. |+| `processEnv.js` | `withoutServerSecretsEnv(env, { keep })` / `serverSecretEnvKeys(env)` — copy of an env minus the vault key, `PG*`, PortOS tokens and provider credentials, for non-AI-CLI children (managed apps, deploy scripts, third-party installs); `keep` exempts names a child needs by design. `stripDebugMallocEnv(env)` / `safeChildProcessEnv(extra)` — drop macOS `Malloc*` debug env vars before spawning a child. `safeChildProcessOptions(options)` adds that sanitized environment plus `windowsHide: true`, preventing detached PM2 subprocesses from opening transient Windows console UI; `buildSafeCliBaseEnv(env, provider)` allowlists runtime/delivery essentials and only the selected CLI's ambient provider auth before an AI CLI inherits the server environment. Route Node→Python and other background CLI spawns through the process helpers. Also `whichFirst(name)` — first-hit `which`/`where` PATH probe (safe options, 5s timeout, direct PATH fallback on probe failure) returning the absolute binary path or `null`; `whichFirstSync(name)` provides the same contract without the await; `findCommandOnPath(name, { env, cwd })` resolves an executable from the exact child environment without needing `which` itself on that PATH. `adoptPathDirs(dirs)` appends the ones that exist and are not already there to THIS process's `process.env.PATH` (case-insensitively on Windows), which fixes this process AND every child, since the env builders above derive from `process.env` — the only fix that reaches a CLI launched by BARE NAME through node-pty. Shared by `npmGlobalBin.js` and `services/llamaServerManager.js`'s winget-shim adoption. `windowsPowerShell51Path(env)` is the fixed Windows PowerShell 5.1 location under `SystemRoot`, shared by `interactiveShellResolver.js` and `nativeTrash.js`. || `branchUpstreamGuard.js` | `enforceSafeBranchUpstream(repo, branch)` / `readBranchUpstream` / `isSafeBranchUpstream` — the agent-branch upstream invariant (#4172): a branch handed to a CoS agent tracks either NOTHING or its OWN ref, never `refs/heads/main`. `git worktree add -b <b> <path> origin/main` does not leave the branch untracked — `branch.autoSetupMerge` records `merge=refs/heads/main` — and `/do:pr` derives its push destination from that config (`git push <remote> HEAD:<merge>`), so the agent's work lands straight on the default branch with no PR. Prevention is `--no-track` at the `worktreeManager.js` creation sites; this is the backstop that also REPAIRS branches created before the fix (drops the bogus upstream, logs it) and throws only if the repair doesn't take. Fails CLOSED: `readBranchUpstream` returns `null` for could-not-read (distinct from `''` = genuinely unset), and an unverifiable upstream is refused rather than waved through — `worktreeManager.js` undoes the `worktree add` on refusal so the throw can't strand a tree. Pairs with `primaryCheckoutGuard.js`, which catches the other way agent work reaches `main`. || `primaryCheckoutGuard.js` | `capturePrimaryCheckoutState(path)` / `detectPrimaryCheckoutDrift(baseline, {agentBranch})` + `PRIMARY_CHECKOUT_MUTATED_REASON`/`_CATEGORY` — the branch-jack detector (#3680): stamps the PRIMARY checkout's branch + HEAD onto a worktree agent's metadata at spawn (`agentLifecycle.js`) and re-reads it in the shared finalize path (`agentFinalization.js`), so a worktree-isolated agent that commits to the primary is recorded as a FAILURE naming the drifted branch, the commit count, and the `git reset --hard` recovery — instead of a silent "completed". Detect-and-report only: the reset discards commits, so it stays a human decision. Non-throwing (runs outside the request lifecycle); an unreadable checkout reports no drift rather than inventing one. `resolveRemoteDefaultRef(path)` resolves local origin/HEAD, origin/main, then origin/master to `{ref, sha}` or null without fetching; also used by run-window diffs. || `ptySpawnDiagnostics.js` | `diagnosePtySpawnFailure(err, {cwd, probeCwd, runtimeProbe})` + `probePtyRuntime(pty, cwd)` and the `PTY_UNAVAILABLE_PREFIX` / `PTY_WORKSPACE_MISSING_PREFIX` markers — turns node-pty’s one opaque `posix_spawn failed: No such file or directory` into a named fault. The executable is already cleared upstream (PATH resolve + `--version` probe), so a throw is either a `cwd` that vanished (cheap `existsSync`) or a PTY layer that cannot fork AT ALL — proven by re-forking a known-good command in a known-good directory; `diagnosed: false` means neither matched, and the caller re-throws rather than inventing a cause. **Retry policy is the caller’s and the two faults differ:** `agentTuiSpawning.js` matches only the PTY-layer prefix, mapping it to the actionable `runner-pty-unavailable` so the task blocks once with the repair, while a reaped workspace falls through to the retrying `spawn-rejected` because the next attempt provisions a fresh worktree. The motivating outage: an `npm ci` inside a CoS worktree emptied the primary checkout’s `server/node_modules` through a symlink, deleting the `spawn-helper` binary node-pty execs on every fork, while the already-loaded binding left the runner process itself looking healthy. |diff --git a/server/lib/processEnv.js b/server/lib/processEnv.jsindex ed4baa9d11..a1773fd82f 100644--- a/server/lib/processEnv.js+++ b/server/lib/processEnv.js@@ -131,6 +131,40 @@ export function buildSafeCliBaseEnv(env = process.env, provider = null) {);}+// Server-held secrets a non-agent child (managed app, deploy.sh, third-party+// install script) must not inherit: the vault key, database credentials, PortOS+// session tokens and AI provider credentials. Managed apps receive their own+// configured variables through explicit env overlays, not through ambient+// server state.+const SERVER_SECRET_ENV_KEYS = new Set([+ 'PRIVACY_VAULT_KEY',+ ...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)$/,+];++const isServerSecretEnvKey = (key, keep) => !keep.includes(key)+ && (SERVER_SECRET_ENV_KEYS.has(key) || SERVER_SECRET_ENV_PATTERNS.some((pattern) => pattern.test(key)));++/** Names present in `env` that `withoutServerSecretsEnv` would remove. */+export function serverSecretEnvKeys(env = process.env, { keep = [] } = {}) {+ return Object.keys(env || {}).filter((key) => isServerSecretEnvKey(key, keep));+}++/**+ * Copy of `env` minus server-held secrets, for children that are not AI CLIs+ * (those use `buildSafeCliBaseEnv`). `keep` exempts names the child needs by+ * design, such as the Codex image agent's own provider key.+ */+export function withoutServerSecretsEnv(env = process.env, { keep = [] } = {}) {+ return Object.fromEntries(+ Object.entries(env || {}).filter(([key]) => !isServerSecretEnvKey(key, keep)),+ );+}+// Resolve the first PATH hit for a binary via `which` (POSIX) / `where`// (Windows) — the "is this system tool installed, and where?" probe copied// inline across ytdlp/ffmpeg/pythonSetup/voice discovery. Returns the absolutediff --git a/server/lib/processEnv.test.js b/server/lib/processEnv.test.jsindex 4aabbd010d..ced8027141 100644--- a/server/lib/processEnv.test.js+++ b/server/lib/processEnv.test.js@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, it, expect } from 'vitest';import { mkdtempSync, rmSync } from 'fs';import { tmpdir } from 'os';import { basename, delimiter, dirname, join } from 'path';-import { adoptPathDirs, buildSafeCliBaseEnv, findCommandOnPath, safeChildProcessEnv, stripDebugMallocEnv, whichFirst } from './processEnv.js';+import { adoptPathDirs, buildSafeCliBaseEnv, serverSecretEnvKeys, withoutServerSecretsEnv, findCommandOnPath, safeChildProcessEnv, stripDebugMallocEnv, whichFirst } from './processEnv.js';describe('stripDebugMallocEnv', () => {it('drops every key that starts with "Malloc"', () => {@@ -204,3 +204,26 @@ describe('adoptPathDirs', () => {expect(process.env.PATH).toBe(before);});});++describe('withoutServerSecretsEnv', () => {+ const env = {+ 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',+ DATABASE_URL: 'app-owned', STRIPE_KEY: 'app-owned', PGP_NOTE: 'not a libpq var',+ };++ it('drops the vault key, PG*, PortOS tokens and provider keys but keeps ordinary variables', () => {+ expect(withoutServerSecretsEnv(env)).toEqual({+ PATH: '/usr/bin', HOME: '/home/example', NODE_ENV: 'production', PORT: '5555',+ DATABASE_URL: 'app-owned', STRIPE_KEY: 'app-owned', PGP_NOTE: 'not a libpq var',+ });+ });++ it('lets a child keep the credentials it needs by design', () => {+ const out = withoutServerSecretsEnv(env, { keep: ['OPENAI_API_KEY'] });+ expect(out.OPENAI_API_KEY).toBe('o');+ expect(out).not.toHaveProperty('ANTHROPIC_API_KEY');+ expect(serverSecretEnvKeys(env, { keep: ['OPENAI_API_KEY'] })).not.toContain('OPENAI_API_KEY');+ });+});diff --git a/server/services/appDeployer.js b/server/services/appDeployer.jsindex a3b8a5b60f..03fe92b346 100644--- a/server/services/appDeployer.js+++ b/server/services/appDeployer.js@@ -4,6 +4,7 @@ import { join } from 'path';import { NON_PM2_TYPES } from './appProcessTypes.js';import { getAppById } from './apps.js';import { resolveBashBinary } from '../lib/bashResolver.js';+import { withoutServerSecretsEnv } from '../lib/processEnv.js';import { DEPLOY_FLAGS } from '../lib/appDeployFlags.js';export { DEPLOY_FLAGS };@@ -70,7 +71,7 @@ export function deployApp(app, flags, emit) {const child = spawn(resolveBashBinary(), ['deploy.sh', ...safeFlags], {cwd: dir,shell: false,- env: { ...process.env, FORCE_COLOR: '0' }+ env: { ...withoutServerSecretsEnv(process.env), FORCE_COLOR: '0' }});// Guard against a hung deploy.sh holding the lock forever.diff --git a/server/services/appDeployer.test.js b/server/services/appDeployer.test.jsindex 01333f3636..dbc2e84f0d 100644--- a/server/services/appDeployer.test.js+++ b/server/services/appDeployer.test.js@@ -1,6 +1,38 @@+import { EventEmitter } from 'events';import { describe, it, expect, vi } from 'vitest';import { DEPLOY_FLAGS as sharedDeployFlags } from '../lib/appDeployFlags.js';-import { DEPLOY_FLAGS, runDeployFlow } from './appDeployer.js';++const mockSpawn = vi.hoisted(() => vi.fn());+vi.mock('../lib/childProcess.js', async (importOriginal) => ({+ ...(await importOriginal()),+ spawn: mockSpawn,+}));++import { DEPLOY_FLAGS, deployApp, runDeployFlow } from './appDeployer.js';++describe('deployApp environment', () => {+ it('does not hand server secrets to deploy.sh', async () => {+ vi.stubEnv('PRIVACY_VAULT_KEY', 'vault');+ vi.stubEnv('PGPASSWORD', 'db');+ vi.stubEnv('PORTOS_DEPLOY_PROBE', 'kept');+ mockSpawn.mockImplementation(() => {+ const child = new EventEmitter();+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ queueMicrotask(() => child.emit('close', 0));+ return child;+ });++ await deployApp({ repoPath: '/repo/example-ios' }, [], () => {});++ const { env } = mockSpawn.mock.calls[0][2];+ expect(env).not.toHaveProperty('PRIVACY_VAULT_KEY');+ expect(env).not.toHaveProperty('PGPASSWORD');+ expect(env.PORTOS_DEPLOY_PROBE).toBe('kept');+ expect(env.FORCE_COLOR).toBe('0');+ vi.unstubAllEnvs();+ });+});describe('deploy flag contract', () => {it('preserves the service export as the shared lib allowlist', () => {diff --git a/server/services/eidoverse.js b/server/services/eidoverse.jsindex f2b545be2c..b7d1e34111 100644--- a/server/services/eidoverse.js+++ b/server/services/eidoverse.js@@ -3,6 +3,7 @@ import { homedir } from 'os';import { ServerError } from '../lib/errorHandler.js';import { bufferedSpawnOrThrow } from '../lib/bufferedSpawn.js';import { commandExists } from '../lib/commandExists.js';+import { withoutServerSecretsEnv } from '../lib/processEnv.js';import { execGit } from '../lib/execGit.js';import { atomicWrite, ensureDir, pathExists, PATHS } from '../lib/fileUtils.js';import { parseGitHubUrl } from '../lib/repoUrl.js';@@ -143,7 +144,7 @@ async function registerManagedApp(paths, bunCommand) {const bunRuntimeEnv = (bunExecutable) => {const binDirectory = dirname(bunExecutable);- const env = { ...process.env };+ const env = withoutServerSecretsEnv(process.env);const inheritedPath = env.PATH || env.Path || '';for (const key of Object.keys(env)) {if (key.toLowerCase() === 'path') delete env[key];@@ -156,7 +157,7 @@ const bunRuntimeEnv = (bunExecutable) => {};async function resolveBunRuntime() {- if (await commandExists('bun')) return { command: 'bun', env: process.env };+ if (await commandExists('bun')) return { command: 'bun', env: withoutServerSecretsEnv(process.env) };const command = getBunExecutable();const env = bunRuntimeEnv(command);diff --git a/server/services/eidoverse.test.js b/server/services/eidoverse.test.jsindex ccd2228508..7e09ba1670 100644--- a/server/services/eidoverse.test.js+++ b/server/services/eidoverse.test.js@@ -125,7 +125,13 @@ describe('Eidoverse managed-app installer', () => {});it('clones separate licensed repos, installs Bun dependencies, and registers Worlds', async () => {+ vi.stubEnv('PRIVACY_VAULT_KEY', 'vault');+ vi.stubEnv('PGPASSWORD', 'db');const status = await installEidoverse({ worldsRepoUrl: SELECTED_WORLDS_REPO });+ 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');+ vi.unstubAllEnvs();expect(mock.cloneRepo).toHaveBeenCalledWith(SELECTED_WORLDS_REPO, { branch: '' });expect(mock.cloneRepo).toHaveBeenCalledWith(EIDOVERSE_VIDEO_REPO);diff --git a/server/services/imageGen/codex.js b/server/services/imageGen/codex.jsindex 98d709e071..0141849796 100644--- a/server/services/imageGen/codex.js+++ b/server/services/imageGen/codex.js@@ -35,6 +35,10 @@ import { basename, join, isAbsolute, resolve, sep } from 'path';import { tmpdir } from 'os';import { codexHomeDir } from '../../lib/codexUserConfig.js';import { withSpawnCwdEnv } from '../../lib/spawnCwd.js';+import { withoutServerSecretsEnv } from '../../lib/processEnv.js';++// Codex's own ambient credentials; everything else server-held is withheld.+const CODEX_AUTH_ENV_KEYS = ['OPENAI_API_KEY', 'OPENAI_BASE_URL', 'OPENAI_API_BASE'];import { maintenance } from '../../lib/maintenanceAdmission.js';import { noFabricationClause } from './fabricationGuard.js';import { randomUUID } from 'crypto';@@ -416,7 +420,8 @@ function runCodex(job, jobId, bin, args, outputPath, filename, meta, { cleanC2PAtry {const resolvedBin = !isAbsolute(bin) && (bin.includes('/') || bin.includes(sep)) ? resolve(bin) : bin;const prepared = prepareCliSpawn(resolvedBin, args);- const env = process.env.CODEX_HOME ? { ...process.env, CODEX_HOME: resolve(process.env.CODEX_HOME) } : process.env;+ const baseEnv = withoutServerSecretsEnv(process.env, { keep: CODEX_AUTH_ENV_KEYS });+ const env = process.env.CODEX_HOME ? { ...baseEnv, CODEX_HOME: resolve(process.env.CODEX_HOME) } : baseEnv;proc = spawn(prepared.command, prepared.args, { cwd: scratchDir, env: withSpawnCwdEnv(env, scratchDir), shell: false, stdio: ['ignore', 'pipe', 'pipe'] });} catch (err) {void removeScratch();diff --git a/server/services/imageGen/codex.test.js b/server/services/imageGen/codex.test.jsindex 1318379361..e8f1fe9c09 100644--- a/server/services/imageGen/codex.test.js+++ b/server/services/imageGen/codex.test.js@@ -1067,6 +1067,20 @@ describe('Codex cached defaults and isolated workspace', () => {await finish(call);});+ it('withholds server secrets but keeps the Codex provider key', async () => {+ vi.stubEnv('PRIVACY_VAULT_KEY', 'vault');+ vi.stubEnv('PGPASSWORD', 'db');+ vi.stubEnv('ANTHROPIC_API_KEY', 'other-provider');+ vi.stubEnv('OPENAI_API_KEY', 'codex-key');+ await codex.generateImage({ prompt: 'synthetic' });+ const { env } = spawnCalls[0].options;+ expect(env).not.toHaveProperty('PRIVACY_VAULT_KEY');+ expect(env).not.toHaveProperty('PGPASSWORD');+ expect(env).not.toHaveProperty('ANTHROPIC_API_KEY');+ expect(env.OPENAI_API_KEY).toBe('codex-key');+ await finish(spawnCalls[0]);+ });+it('cleans scratch after a spawn error with no physical child', async () => {await codex.generateImage({ prompt: 'synthetic' });const call = spawnCalls[0];diff --git a/server/services/pm2.js b/server/services/pm2.jsindex 54a2db0d84..055bd80e05 100644--- a/server/services/pm2.js+++ b/server/services/pm2.js@@ -9,6 +9,7 @@ import { atomicWrite, safeJSONParse, sleep, tryReadFile } from '../lib/fileUtilsimport { parseCommandArgs } from '../lib/commandSecurity.js';import { parsePm2JlistStdout } from '../lib/pm2Jlist.js';import { PATHS } from '../lib/paths.js';+import { serverSecretEnvKeys, withoutServerSecretsEnv } from '../lib/processEnv.js';// The leaf, not readinessNotify.js: its observer's lazy imports would join// pm2.js's ~280 suites to the CoS cluster's CI selection (#12285).import { noteReadinessChanged } from './readinessSignal.js';@@ -253,6 +254,16 @@ export function buildEnv(pm2Home) {return env;}+// Env for a CLI `pm2 start` of a managed app: buildEnv() minus server secrets.+function buildStartEnv(pm2Home) {+ return withoutServerSecretsEnv(buildEnv(pm2Home));+}++// The Node API merges process.env into the child; its `filter_env` option (an+// array of names) is the only way to drop inherited keys. Explicit `env`+// entries are applied after the filter, so configured variables still arrive.+const serverSecretFilterEnv = () => serverSecretEnvKeys(process.env);+/*** Spawn a PM2 CLI command with optional custom PM2_HOME* @param {string} action PM2 action (stop, restart, delete)@@ -329,6 +340,7 @@ export async function startApp(name, options = {}) {args: options.args || 'run dev',cwd: options.cwd,env: options.env || {},+ filter_env: serverSecretFilterEnv(),watch: false,autorestart: true,max_restarts: 10,@@ -662,6 +674,7 @@ export async function startWithCommand(name, cwd, command, options = {}) {// also overrides the app's env file — they agree by construction, since// PortOS generates that file from the same port it records....(port ? { env: { PORT: String(port) } } : {}),+ filter_env: serverSecretFilterEnv(),windowsHide: IS_WIN};@@ -695,7 +708,7 @@ async function spawnPm2StartCommand(name, cwd, script, args, { autorestart, maxRcliArgs.push('--no-autorestart');}if (args.length > 0) cliArgs.push('--', ...args);- const env = buildEnv(pm2Home);+ const env = buildStartEnv(pm2Home);if (port) env.PORT = String(port);await execPm2(cliArgs, { env });clearJlistCache(pm2Home);diff --git a/server/services/pm2.launch.test.js b/server/services/pm2.launch.test.jsindex c483e3e0ed..41207f1a9a 100644--- a/server/services/pm2.launch.test.js+++ b/server/services/pm2.launch.test.js@@ -117,6 +117,36 @@ describe('PM2 command launch interpreters', () => {});});+ describe('server secrets in the environment', () => {+ afterEach(() => {+ vi.unstubAllEnvs();+ });++ it('filters them from the Node API start while keeping the app-configured env', async () => {+ vi.stubEnv('PRIVACY_VAULT_KEY', 'vault');+ vi.stubEnv('PGPASSWORD', 'db');+ await startWithCommand('worlds', '/repo/worlds', 'bun server/server.ts', { port: 8940 });+ await startApp('tooling-app', { script: 'npm', env: { PGPASSWORD: 'app-own' } });++ const [command] = mockPm2.start.mock.calls[0];+ expect(command.filter_env).toEqual(expect.arrayContaining(['PRIVACY_VAULT_KEY', 'PGPASSWORD']));+ const [configured] = mockPm2.start.mock.calls[1];+ expect(configured.filter_env).toContain('PGPASSWORD');+ expect(configured.env).toEqual({ PGPASSWORD: 'app-own' });+ });++ it('omits them from the CLI start environment', async () => {+ vi.stubEnv('PRIVACY_VAULT_KEY', 'vault');+ vi.stubEnv('PGPASSWORD', 'db');+ await startWithCommand('worlds', '/repo/worlds', 'bun server/server.ts', { pm2Home: '/tmp/example-pm2' });++ const [, , spawnOpts] = mockSpawn.mock.calls[0];+ expect(spawnOpts.env).not.toHaveProperty('PRIVACY_VAULT_KEY');+ expect(spawnOpts.env).not.toHaveProperty('PGPASSWORD');+ expect(spawnOpts.env.PM2_HOME).toBe('/tmp/example-pm2');+ });+ });+// Sibling of the leak above, on the app-facing side: PM2 copies the launching// process's environment into the child, so portos-server's own PORT reached// every managed app it started. An app's env file cannot undo that — neither