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 PM2 global options before daemon protection

Adam Eivye8fa68d894a0
diff --git a/server/lib/agentGuard/bin/pm2 b/server/lib/agentGuard/bin/pm2
index 0ccfcb36a9..b44ee1eeb3 100755
--- a/server/lib/agentGuard/bin/pm2
+++ b/server/lib/agentGuard/bin/pm2
@@ -9,36 +9,13 @@
# would take down the SHARED PM2 daemon — and therefore every other app on the
# machine, including PortOS itself — then exec the real pm2 for everything else.
#
-# This list is mirrored in server/lib/commandSecurity.js (validatePm2Command).
-# Keep the two in sync.
-#
-# Note: this is defense-in-depth against a *confused* agent, not a sandbox. An
-# agent that calls pm2 by absolute path bypasses the shim — acceptable for
-# PortOS's single-user, private-network trust model.
-
-sub="$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')"
-
-block() {
- printf '🛑 PortOS agent guard: `pm2 %s` is blocked — it would disrupt the shared PM2 daemon or other apps on this server (including PortOS itself). Restart only your own app with `pm2 restart <your-process-name>`.\n' "$*" >&2
- exit 1
-}
-
-case "$sub" in
- kill|startup|unstartup) block "$@" ;;
-esac
-
-case "$sub" in
- stop|delete|del|restart|reload|gracefulreload|scale)
- for arg in "${@:2}"; do
- lower="$(printf '%s' "$arg" | tr '[:upper:]' '[:lower:]')"
- [ "$lower" = "all" ] && block "$@"
- done
- ;;
-esac
+# This is a confused-agent guard, not a sandbox: absolute binary paths bypass it.
+# Share the option-aware policy with PortOS's command runner.
+self_dir="$(cd "$(dirname "$0")" && pwd)"
+node "$self_dir/../validatePm2.js" "$@" || exit $?
# Resolve the real pm2. PortOS sets PORTOS_REAL_PM2 to the Node-resolved binary;
# fall back to the first pm2 on PATH that is NOT this shim's own directory.
-self_dir="$(cd "$(dirname "$0")" && pwd)"
real="$PORTOS_REAL_PM2"
if [ -z "$real" ] || [ ! -x "$real" ]; then
real=""
diff --git a/server/lib/agentGuard/index.test.js b/server/lib/agentGuard/index.test.js
index a8871c5695..7d5ef0dfc7 100644
--- a/server/lib/agentGuard/index.test.js
+++ b/server/lib/agentGuard/index.test.js
@@ -87,7 +87,8 @@ describeShim('pm2 guard shim (bin/pm2)', () => {
// of depending on whether the host's /usr/bin happens to contain pm2.
cleanBin = join(workDir, 'cleanbin');
mkdirSync(cleanBin);
- for (const tool of ['tr', 'dirname']) {
+ symlinkSync(process.execPath, join(cleanBin, 'node'));
+ for (const tool of ['dirname']) {
const src = [`/usr/bin/${tool}`, `/bin/${tool}`].find((p) => existsSync(p));
if (src) symlinkSync(src, join(cleanBin, tool));
}
@@ -149,6 +150,26 @@ describeShim('pm2 guard shim (bin/pm2)', () => {
expect(execedArgs).toBeNull();
});
+ it.each([
+ ['--name', '--watch', 'kill'], ['--name', '--watch', 'delete', 'all'],
+ ['--silent', 'kill'], ['-s', 'delete', 'all'],
+ ['--name', 'example', '--silent', 'kill'], ['--name=example', 'restart', 'all'],
+ ['-sf', 'reload', 'all'], ['--', 'kill'],
+ ])('blocks option-prefixed disruption (%j)', (...args) => {
+ const result = runShim(args);
+ expect(result.code).toBe(1);
+ expect(result.execedArgs).toBeNull();
+ });
+
+ it.each([
+ ['--silent', 'restart', 'my-app'], ['--name', 'kill', 'start', 'app.js'],
+ ['restart', 'my-app', '--name', 'all'], ['-sf', 'start', 'app.js'],
+ ])('preserves scoped commands and option values (%j)', (...args) => {
+ const result = runShim(args);
+ expect(result.code).toBe(0);
+ expect(result.execedArgs).toBe(args.join(' '));
+ });
+
it('passes a scoped `pm2 restart <name>` through to the real pm2', () => {
const { code, execedArgs } = runShim(['restart', 'my-app']);
expect(code).toBe(0);
diff --git a/server/lib/agentGuard/validatePm2.js b/server/lib/agentGuard/validatePm2.js
new file mode 100644
index 0000000000..52162e82b3
--- /dev/null
+++ b/server/lib/agentGuard/validatePm2.js
@@ -0,0 +1,7 @@
+import { validatePm2Command } from '../commandSecurity.js';
+
+const result = validatePm2Command(process.argv.slice(2));
+if (!result.valid) {
+ console.error(`🛑 PortOS agent guard: ${result.error}`);
+ process.exitCode = 1;
+}
diff --git a/server/lib/commandSecurity.js b/server/lib/commandSecurity.js
index 65b4f78112..2a4dd80bf6 100644
--- a/server/lib/commandSecurity.js
+++ b/server/lib/commandSecurity.js
@@ -86,17 +86,69 @@ export const PM2_ALL_TARGET_VERBS = new Set([
'stop', 'delete', 'del', 'restart', 'reload', 'gracefulreload', 'scale',
]);
+// Mirror the argument grammar of PM2's Commander CLI before applying policy.
+// Required values consume even a flag-shaped token; optional values do not.
+const PM2_REQUIRED_OPTIONS = new Set([
+ '--ext', '--name', '--interpreter', '--interpreter-args', '--node-args',
+ '--output', '--error', '--log-type', '--log-date-format', '--env', '--instances',
+ '--parallel', '--pid', '--kill-timeout', '--listen-timeout', '--max-memory-restart',
+ '--restart-delay', '--exp-backoff-restart-delay', '--user', '--uid', '--gid',
+ '--namespace', '--cwd', '--hp', '--service-name', '--cron', '--cron-restart',
+ '--only', '--ignore-watch', '--watch-delay', '--stop-exit-codes', '--sort',
+ '-n', '-o', '-e', '-i', '-p', '-k', '-u', '-c',
+]);
+const PM2_OPTIONAL_OPTIONS = new Set(['--log', '-l', '--filter-env', '--max-restarts', '--watch']);
+const PM2_BOOLEAN_OPTIONS = new Set([
+ '-v', '--version', '-s', '--silent', '-m', '--mini-list', '--time', '--disable-logs',
+ '-a', '--update-env', '-f', '--force', '--shutdown-with-message', '-x', '--execute-command',
+ '--wait-ip', '-w', '--write', '--no-daemon', '--source-map-support',
+ '--disable-source-map-support', '--wait-ready', '--merge-logs', '--no-color',
+ '--no-vizion', '--no-autostart', '--no-autorestart', '--no-treekill', '--no-pmx',
+ '--no-automation', '--trace', '--disable-trace', '--attach', '--v8',
+ '--event-loop-inspector', '--deep-monitoring', '-h', '--help',
+]);
+
+function pm2Positionals(args) {
+ const normalized = [];
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i];
+ if (arg === '--') { normalized.push(...args.slice(i)); break; }
+ if (PM2_REQUIRED_OPTIONS.has(args[i - 1])) normalized.push(arg);
+ else if (/^-[^-]/.test(arg)) normalized.push(...arg.slice(1).split('').map(c => `-${c}`));
+ else if (arg.startsWith('--') && arg.includes('=')) {
+ const split = arg.indexOf('=');
+ normalized.push(arg.slice(0, split), arg.slice(split + 1));
+ } else normalized.push(arg);
+ }
+ const positionals = [];
+ for (let i = 0; i < normalized.length; i++) {
+ const arg = normalized[i];
+ if (arg === '--') return [...positionals, ...normalized.slice(i + 1)];
+ if (PM2_REQUIRED_OPTIONS.has(arg)) i++;
+ else if (PM2_BOOLEAN_OPTIONS.has(arg)) continue;
+ else if (PM2_OPTIONAL_OPTIONS.has(arg)) {
+ const next = normalized[i + 1];
+ if (next != null && (!next.startsWith('-') || next === '-')) i++;
+ } else if (arg.length > 1 && arg.startsWith('-')) {
+ // Commander retains unknown options separately, consuming a plain value.
+ if (normalized[i + 1] != null && !normalized[i + 1].startsWith('-')) i++;
+ } else positionals.push(arg);
+ }
+ return positionals;
+}
+
/**
* Reject pm2 invocations that would disrupt the shared PM2 daemon or other apps.
* `args` is everything after the `pm2` base command.
* Returns { valid, error? }.
*/
export function validatePm2Command(args) {
- const sub = (args[0] || '').toLowerCase();
+ const positionals = pm2Positionals(args);
+ const sub = (positionals[0] || '').toLowerCase();
if (PM2_BLOCKED_SUBCOMMANDS.has(sub)) {
return { valid: false, error: `'pm2 ${sub}' is blocked — it would take down the shared PM2 daemon or every app on this machine (including PortOS). Use a scoped command like 'pm2 restart <process-name>'.` };
}
- if (PM2_ALL_TARGET_VERBS.has(sub) && args.slice(1).some(a => a.toLowerCase() === 'all')) {
+ if (PM2_ALL_TARGET_VERBS.has(sub) && positionals.slice(1).some(a => a.toLowerCase() === 'all')) {
return { valid: false, error: `'pm2 ${sub} all' is blocked — it affects every app on this shared server. Target a specific process by name instead.` };
}
return { valid: true };
diff --git a/server/lib/commandSecurity.test.js b/server/lib/commandSecurity.test.js
index 2f926b6cd6..b75a157997 100644
--- a/server/lib/commandSecurity.test.js
+++ b/server/lib/commandSecurity.test.js
@@ -1,3 +1,5 @@
+import { createRequire } from 'node:module'
+import { readFileSync } from 'node:fs'
import { describe, it, expect } from 'vitest'
import {
ALLOWED_COMMANDS,
@@ -252,6 +254,9 @@ describe('commandSecurity', () => {
// The shared pm2 daemon runs every app on the machine. These must never reach
// the shell — `pm2 kill` once took the whole server (incl. PortOS) down.
it.each([
+ 'pm2 --silent kill',
+ 'pm2 --name example --silent delete all',
+ 'pm2 -sf restart all',
'pm2 kill',
'pm2 startup',
'pm2 unstartup',
@@ -270,6 +275,9 @@ describe('commandSecurity', () => {
})
it.each([
+ 'pm2 --silent restart my-app',
+ 'pm2 --name kill start app.js',
+ 'pm2 restart my-app --name all',
'pm2 list',
'pm2 jlist',
'pm2 logs my-app',
@@ -282,6 +290,38 @@ describe('commandSecurity', () => {
expect(validateCommand(cmd).valid).toBe(true)
})
+ it('matches installed PM2 option parsing before applying the disruption policy', () => {
+ // Load only Commander and declarative flag strings, never PM2's CLI.
+ const require = createRequire(import.meta.url)
+ const pm2Require = createRequire(require.resolve('pm2'))
+ const { Command } = pm2Require('commander')
+ const source = readFileSync(require.resolve('pm2/lib/binaries/CLI.js'), 'utf8')
+ const flags = [...source.matchAll(/\.option\('([^']+)'/g)].map(match => match[1])
+ const globalFlags = flags.slice(0, flags.indexOf('--deep-monitoring') + 1)
+ expect(globalFlags.length).toBeGreaterThan(50)
+ const parser = new Command()
+ for (const flag of globalFlags) parser.option(flag)
+ const cases = [
+ ['--name', '--watch', 'kill'], ['--name', '--watch', 'delete', 'all'],
+ ['-snexample', 'restart', 'all'], ['--', 'kill'],
+ ['--unknown', 'start', 'kill'], ['--name=kill', 'start', 'app.js'],
+ ]
+ for (const flag of globalFlags) {
+ const name = flag.match(/--[\w-]+/)[0]
+ for (const tail of [['kill'], ['delete', 'all'], ['restart', 'my-app']]) {
+ cases.push([name, ...(flag.includes('<') || flag.includes('[') ? ['example'] : []), ...tail])
+ if (flag.includes('<')) cases.push([name, '--watch', ...tail])
+ }
+ }
+ for (const args of cases) {
+ const parsed = parser.parseOptions(parser.normalize(args)).args
+ const verb = (parsed[0] || '').toLowerCase()
+ const blocked = ['kill', 'startup', 'unstartup'].includes(verb) ||
+ (['stop', 'delete', 'del', 'restart', 'reload', 'gracefulreload', 'scale'].includes(verb) && parsed.slice(1).some(arg => arg.toLowerCase() === 'all'))
+ expect(validatePm2Command(args).valid, JSON.stringify(args)).toBe(!blocked)
+ }
+ })
+
it('validatePm2Command is callable directly with arg arrays', () => {
expect(validatePm2Command(['kill']).valid).toBe(false)
expect(validatePm2Command(['restart', 'my-app']).valid).toBe(true)