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: stop PortOS's own PORT leaking into managed apps and crashlooping the server
Adam Eivy1e54db930abf
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex 2aca6f732f..21cc0a3e71 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -1266,7 +1266,7 @@"sources": [{"source": "server/routes/apps/lifecycle.js",- "line": 251+ "line": 262}]},@@ -1376,7 +1376,7 @@"sources": [{"source": "server/routes/apps/lifecycle.js",- "line": 299+ "line": 310}]},@@ -1475,7 +1475,7 @@"sources": [{"source": "server/routes/apps/lifecycle.js",- "line": 315+ "line": 326}]},@@ -1486,7 +1486,7 @@"sources": [{"source": "server/routes/apps/lifecycle.js",- "line": 190+ "line": 201}]},@@ -1519,7 +1519,7 @@"sources": [{"source": "server/routes/apps/lifecycle.js",- "line": 280+ "line": 291}]},@@ -1530,7 +1530,7 @@"sources": [{"source": "server/routes/apps/lifecycle.js",- "line": 167+ "line": 178}]},@@ -1585,7 +1585,7 @@"sources": [{"source": "server/routes/apps/lifecycle.js",- "line": 228+ "line": 239}]},diff --git a/server/routes/apps/lifecycle.js b/server/routes/apps/lifecycle.jsindex c2a57a8f08..5709cbaf20 100644--- a/server/routes/apps/lifecycle.js+++ b/server/routes/apps/lifecycle.js@@ -143,6 +143,14 @@ router.post('/:id/start', loadApp, asyncHandler(async (req, res) => {} else {// Fallback to command-based start for apps without ecosystem configconst commands = app.startCommands || ['npm run dev'];+ // Pin the app's own port so PortOS's PORT can't leak in through the+ // inherited environment (see startWithCommand). Only a single-process app+ // has an unambiguous port — for a multi-process app the recorded ports+ // can't be mapped to process names here, and handing every process the+ // same PORT would collide them against each other.+ const singleProcessPort = processNames.length === 1+ ? (app.apiPort || app.uiPort || null)+ : null;for (let i = 0; i < processNames.length; i++) {const name = processNames[i];const command = commands[i] || commands[0];@@ -150,7 +158,10 @@ router.post('/:id/start', loadApp, asyncHandler(async (req, res) => {results[name] = await launchDesktopProcess(app, name, command);continue;}- const result = await pm2Service.startWithCommand(name, app.repoPath, command, { pm2Home: app.pm2Home })+ const result = await pm2Service.startWithCommand(name, app.repoPath, command, {+ pm2Home: app.pm2Home,+ port: singleProcessPort+ }).catch(err => ({ success: false, error: err.message }));results[name] = result;}diff --git a/server/routes/apps/lifecycle.test.js b/server/routes/apps/lifecycle.test.jsindex 1f178f25cc..011f0c34a8 100644--- a/server/routes/apps/lifecycle.test.js+++ b/server/routes/apps/lifecycle.test.js@@ -218,10 +218,61 @@ describe('Apps Lifecycle Routes', () => {expect(response.status).toBe(200);expect(pm2Service.startWithCommand).toHaveBeenCalledWith(- 'test-app', '/path/to/repo', 'npm run dev', { pm2Home: join(REAL_DIR, 'example-pm2') }+ 'test-app', '/path/to/repo', 'npm run dev', { pm2Home: join(REAL_DIR, 'example-pm2'), port: null });});+ // PM2 copies the launching process's env into the child, so PortOS's own+ // PORT reached managed apps and won over their env file (neither Bun's+ // --env-file nor dotenv overrides an already-set variable). A managed app+ // then bound PortOS's port and crashlooped the server on EADDRINUSE.+ it('pins a single-process app to its own recorded port, not PortOS\'s', async () => {+ const mockApp = {+ id: 'app-001',+ name: 'Worlds',+ repoPath: '/path/to/repo',+ uiPort: 8940,+ apiPort: 8940,+ pm2ProcessNames: ['worlds'],+ startCommands: ['bun --env-file=.env.portos server/server.ts']+ };+ appsService.getAppById.mockResolvedValue(mockApp);+ pm2Service.startWithCommand.mockResolvedValue({ success: true });+ history.logAction.mockResolvedValue();++ const response = await request(app).post('/api/apps/app-001/start');++ expect(response.status).toBe(200);+ expect(pm2Service.startWithCommand).toHaveBeenCalledWith(+ 'worlds', '/path/to/repo', 'bun --env-file=.env.portos server/server.ts',+ expect.objectContaining({ port: 8940 })+ );+ });++ // Multi-process apps have no port-to-process mapping here, so handing every+ // process the same PORT would collide them against each other.+ it('does not pin a port when starting several processes', async () => {+ const mockApp = {+ id: 'app-001',+ name: 'Two Part App',+ repoPath: '/path/to/repo',+ uiPort: 8940,+ apiPort: 8941,+ pm2ProcessNames: ['two-part-server', 'two-part-ui'],+ startCommands: ['npm run server', 'npm run ui']+ };+ appsService.getAppById.mockResolvedValue(mockApp);+ pm2Service.startWithCommand.mockResolvedValue({ success: true });+ history.logAction.mockResolvedValue();++ const response = await request(app).post('/api/apps/app-001/start');++ expect(response.status).toBe(200);+ for (const call of pm2Service.startWithCommand.mock.calls) {+ expect(call[3].port).toBeNull();+ }+ });+it('launches a desktop app from its startCommands with autorestart OFF (#2991)', async () => {const mockApp = {id: 'game-001',diff --git a/server/services/pm2.js b/server/services/pm2.jsindex 94d4db1ae8..3eaf5fbe17 100644--- a/server/services/pm2.js+++ b/server/services/pm2.js@@ -550,16 +550,20 @@ export async function getLogs(name, lines = 100, pm2Home = null) {* CLI (like deleteApp/getAppStatus) instead of the default-daemon Node API —* otherwise the process would launch under PortOS's own PM2 daemon and be* invisible to every subsequent status/log/delete call that targets pm2Home.+ * @param {number} [options.port=null] The app's own port, pinned as PORT in the+ * child's environment so PortOS's inherited PORT cannot reach it. Pass null+ * when no single port applies (a portless app, or several processes sharing+ * one start call) — see the EADDRINUSE note at the env assignment below.*/export async function startWithCommand(name, cwd, command, options = {}) {- const { autorestart = true, maxRestarts = 10, pm2Home = null } = options;+ const { autorestart = true, maxRestarts = 10, pm2Home = null, port = null } = options;// Parse with quote-awareness so `node --opt "arg with spaces"` survives;// a bare split(' ') would shred quoted segments. PM2 accepts `args` as an// array, which avoids re-joining and re-splitting on the way through.const [script, ...args] = parseCommandArgs(command);if (pm2Home) {- return spawnPm2StartCommand(name, cwd, script, args, { autorestart, maxRestarts, pm2Home });+ return spawnPm2StartCommand(name, cwd, script, args, { autorestart, maxRestarts, pm2Home, port });}return connectAndRun((pm2) => {@@ -580,6 +584,17 @@ export async function startWithCommand(name, cwd, command, options = {}) {...(autorestart? { max_restarts: maxRestarts, min_uptime: '10s', restart_delay: 5000, max_memory_restart: '500M' }: {}),+ // PM2 snapshots the launching process's environment into the child, so+ // PortOS's own PORT would otherwise reach a managed app and win: both+ // Bun's `--env-file` and dotenv yield to an already-set variable, so the+ // app's env file cannot rescue it. The app then binds PortOS's port and+ // whichever process loses the boot race crashloops on EADDRINUSE.+ // buildEnv() strips PORT/HOST on the CLI path below; the Node API has no+ // way to *unset* an inherited key (it merges `env` over process.env), so+ // pin the app's own recorded port instead. Last writer wins, so this+ // 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) } } : {}),windowsHide: IS_WIN};@@ -603,7 +618,7 @@ export async function startWithCommand(name, cwd, command, options = {}) {* tunes the autorestart=true nursing behavior, which no current caller uses* together with a custom pm2Home.*/-function spawnPm2StartCommand(name, cwd, script, args, { autorestart, maxRestarts, pm2Home }) {+function spawnPm2StartCommand(name, cwd, script, args, { autorestart, maxRestarts, pm2Home, port = null }) {return new Promise((resolve, reject) => {const cliArgs = ['start', script, '--name', name, '--cwd', cwd];if (!isJsScript(script)) cliArgs.push('--interpreter', 'none');@@ -614,7 +629,12 @@ function spawnPm2StartCommand(name, cwd, script, args, { autorestart, maxRestart}if (args.length > 0) cliArgs.push('--', ...args);- const child = spawnPm2(cliArgs, { env: buildEnv(pm2Home) });+ // buildEnv drops the inherited PortOS PORT/HOST; put the app's own port+ // back so this path pins the same value the Node API path above does.+ const env = buildEnv(pm2Home);+ if (port) env.PORT = String(port);++ const child = spawnPm2(cliArgs, { env });let stderr = '';child.stderr.on('data', (data) => { stderr += data.toString(); });child.on('close', (code) => {diff --git a/server/services/pm2.launch.test.js b/server/services/pm2.launch.test.jsindex 3247f92ff7..58c63f087e 100644--- a/server/services/pm2.launch.test.js+++ b/server/services/pm2.launch.test.js@@ -108,6 +108,60 @@ describe('PM2 command launch interpreters', () => {});});+ // 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+ // Bun's `--env-file` nor dotenv overrides an already-set variable — so the app+ // bound PortOS's port and whichever process lost the boot race crashlooped on+ // EADDRINUSE.+ describe('inherited PORT in the environment', () => {+ it('pins the app\'s own port over the inherited one on the Node API path', async () => {+ vi.stubEnv('PORT', '5555');++ await startWithCommand('worlds', '/repo/worlds', 'bun server/server.ts', { port: 8940 });++ const [options] = mockPm2.start.mock.calls[0];+ expect(options.env).toEqual({ PORT: '8940' });+ vi.unstubAllEnvs();+ });++ it('pins the app\'s own port over the inherited one on the CLI path', async () => {+ vi.stubEnv('PORT', '5555');++ await startWithCommand('worlds', '/repo/worlds', 'bun server/server.ts', {+ port: 8940,+ pm2Home: '/tmp/example-pm2'+ });++ const [, , spawnOpts] = mockSpawn.mock.calls[0];+ expect(spawnOpts.env.PORT).toBe('8940');+ vi.unstubAllEnvs();+ });++ // No recorded port means no correct value to pin, so the Node API path must+ // not invent one — PM2 merges `env` over process.env and cannot unset a key.+ it('sets no env override when the caller gives no port', async () => {+ await startWithCommand('worlds', '/repo/worlds', 'bun server/server.ts');++ const [options] = mockPm2.start.mock.calls[0];+ expect(options).not.toHaveProperty('env');+ });++ // buildEnv drops the inherited PORT/HOST on this path, so a port-less app+ // gets a clean environment rather than PortOS's.+ it('leaves no inherited PORT behind on the CLI path when given no port', async () => {+ vi.stubEnv('PORT', '5555');++ await startWithCommand('worlds', '/repo/worlds', 'bun server/server.ts', {+ pm2Home: '/tmp/example-pm2'+ });++ const [, , spawnOpts] = mockSpawn.mock.calls[0];+ expect(spawnOpts.env).not.toHaveProperty('PORT');+ vi.unstubAllEnvs();+ });+ });+describe('with a custom pm2Home', () => {it('starts via the PM2 CLI (not the default-daemon Node API) so the process is visible to CLI-based status/log/delete calls targeting the same home', async () => {const result = await startWithCommand(