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(standardize): contain model-authored plan fields before they reach the repository

Adam Eivy4f8c639a6899
diff --git a/server/services/pm2Standardizer.js b/server/services/pm2Standardizer.js
index ebcd48d5d6..c56410bfee 100644
--- a/server/services/pm2Standardizer.js
+++ b/server/services/pm2Standardizer.js
@@ -14,6 +14,11 @@ import { isStandardizable } from './streamingDetect.js';
import { getListeningPorts } from '../lib/platform.js';
import { isBrowserUnsafePort } from '../lib/browserUnsafePorts.js';
import { DEFAULT_PORT_RANGE_START } from './ports.js';
+import { isPathInsideDir } from '../lib/pathSafety.js';
+
+// Mirrors standardizePlanStrayPortSchema (lib/validation.js): the sink re-checks
+// because the socket flow applies the model's plan without the HTTP route's schema.
+const STRAY_VARIABLE_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
const execAsync = promisify(exec);
const DEFAULT_PM2_AI_TIMEOUT_MS = 180000;
@@ -428,7 +433,7 @@ function parseAnalysisResponse(response, promptToStrip = '') {
/**
* Generate ecosystem.config.cjs content from processes
*/
-function generateEcosystemContent(processes, appName) {
+export function generateEcosystemContent(processes, appName) {
const apps = processes.map(proc => {
const config = {
name: proc.name,
@@ -458,15 +463,13 @@ function generateEcosystemContent(processes, appName) {
return config;
});
- // Generate formatted JavaScript
- const configStr = JSON.stringify({ apps }, null, 2)
- .replace(/"([^"]+)":/g, '$1:') // Remove quotes from keys
- .replace(/"/g, "'"); // Use single quotes for strings
-
+ // Plain JSON is a valid JS object literal and PM2 `require()`s this file.
+ // Every process field is model output steered by the scanned repository, so
+ // the old quote rewrite (which left `'` unescaped) could turn a value into code.
return `// PM2 Ecosystem Configuration
// ${PORTOS_ECOSYSTEM_MARKER}
-module.exports = ${configStr};
+module.exports = ${JSON.stringify({ apps }, null, 2)};
`;
}
@@ -648,7 +651,14 @@ export async function applyStandardization(
for (const stray of preserveEcosystem ? [] : plan.proposedChanges.strayPorts || []) {
if (stray.action !== 'remove') continue;
- const filePath = join(repoPath, stray.file);
+ // Contain both model-chosen fields at the sink: the file must resolve
+ // inside the repository and the variable must be a bare identifier before
+ // it becomes a RegExp.
+ const filePath = join(repoPath, String(stray.file ?? ''));
+ if (!isPathInsideDir(repoPath, filePath) || !STRAY_VARIABLE_RE.test(String(stray.variable ?? ''))) {
+ console.warn(`⚠️ PM2 standardizer skipped a stray-port edit outside the plan contract: ${stray.file} / ${stray.variable}`);
+ continue;
+ }
if (!existsSync(filePath)) continue;
const content = await tryReadFile(filePath);
diff --git a/server/services/pm2Standardizer.test.js b/server/services/pm2Standardizer.test.js
index 6c27bcfb9a..661f74ee6b 100644
--- a/server/services/pm2Standardizer.test.js
+++ b/server/services/pm2Standardizer.test.js
@@ -1,3 +1,7 @@
+import { generateEcosystemContent as buildEcosystemContent } from './pm2Standardizer.js';
+import { mkdtempSync as makeTempDir, writeFileSync as writeFixture, readFileSync as readFixture, rmSync as removeFixture } from 'fs';
+import { join as joinPath, relative as relativePath } from 'path';
+import { tmpdir as osTmpDir } from 'os';
import { describe, it, expect, vi, afterEach } from 'vitest';
import { mkdtempSync, writeFileSync, readFileSync, existsSync, rmSync } from 'fs';
import { tmpdir } from 'os';
@@ -391,3 +395,45 @@ describe('applyStandardization — preserve existing ecosystem.config.cjs', () =
expect(readFileSync(join(dir, '.env'), 'utf-8')).not.toContain('PORT=5261');
});
});
+
+describe('model-authored plan fields at the apply sink', () => {
+ it('emits an ecosystem file PM2 can load even when a model string carries quotes', () => {
+ const hostile = "x' + require('child_process').execSync('id') + '";
+ const content = buildEcosystemContent([{ name: "it's", cwd: '.', script: 'x.js', env: { HOSTILE: hostile, 'key"name': 1 } }], 'app');
+ expect(content).toContain(PORTOS_ECOSYSTEM_MARKER);
+ const module = { exports: {} };
+ new Function('module', content)(module);
+ expect(module.exports.apps[0].env.HOSTILE).toBe(hostile);
+ expect(module.exports.apps[0].env['key"name']).toBe(1);
+ expect(module.exports.apps[0].name).toBe("it's");
+ });
+
+ it('refuses stray-port edits that leave the repository or carry a non-identifier variable', async () => {
+ const repo = makeTempDir(joinPath(osTmpDir(), 'stray-repo-'));
+ const outside = makeTempDir(joinPath(osTmpDir(), 'stray-outside-'));
+ try {
+ writeFixture(joinPath(repo, '.env'), 'PORT=3000\nKEEP=1\n');
+ writeFixture(joinPath(outside, '.env'), 'PORT=3000\nSECRET=1\n');
+ const escape = relativePath(repo, joinPath(outside, '.env'));
+ const plan = {
+ currentState: { hasGit: false },
+ proposedChanges: {
+ ecosystemContent: `// ${PORTOS_ECOSYSTEM_MARKER}\nmodule.exports = { apps: [] };\n`,
+ createEcosystem: true,
+ strayPorts: [
+ { file: escape, variable: 'PORT', action: 'remove' },
+ { file: '.env', variable: '|', action: 'remove' },
+ { file: '.env', variable: 'PORT', action: 'remove' },
+ ],
+ },
+ };
+ const result = await applyStandardization(repo, plan, { skipBackup: true });
+ expect(readFixture(joinPath(outside, '.env'), 'utf-8')).toBe('PORT=3000\nSECRET=1\n');
+ expect(readFixture(joinPath(repo, '.env'), 'utf-8')).toBe('KEEP=1\n');
+ expect(result.filesModified).toEqual(['ecosystem.config.cjs', '.env (removed PORT)']);
+ } finally {
+ removeFixture(repo, { recursive: true, force: true });
+ removeFixture(outside, { recursive: true, force: true });
+ }
+ });
+});