Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(security): pin PATH in service files and resolve argv binaries at startup
Salman Qureshiae86ef1f4911
diff --git a/src/capabilities/registry.ts b/src/capabilities/registry.tsindex ecc8fb84..fb53b49c 100644--- a/src/capabilities/registry.ts+++ b/src/capabilities/registry.ts@@ -1,4 +1,5 @@import type { Tool } from 'ai';+import { ensurePinnedBinaries } from './shell/argv-lane.js';import { PermissionManager } from './permissions.js';import { createReadFileTool } from './filesystem/read-file.js';import { createWriteFileTool } from './filesystem/write-file.js';@@ -105,6 +106,8 @@ export class CapabilityRegistry {constructor(skillLoader?: SkillLoader, scheduler?: Scheduler, tokenBudget?: TokenBudget, supervisor?: SubAgentSupervisor, userMemory?: UserMemoryStore) {this.permissions = new PermissionManager();+ // Resolve argv-lane binaries once, at startup, from the pinned PATH (#103).+ ensurePinnedBinaries();this.skillLoader = skillLoader;this.scheduler = scheduler;this.tokenBudget = tokenBudget;diff --git a/src/capabilities/shell/argv-lane.ts b/src/capabilities/shell/argv-lane.tsindex fa113faf..cf0aeca8 100644--- a/src/capabilities/shell/argv-lane.ts+++ b/src/capabilities/shell/argv-lane.ts@@ -361,6 +361,11 @@ export function initPinnedBinaries(dirs: readonly string[] = pinnedSearchDirs())return table;}+/** Build the pinned table if it does not exist yet (startup hook; idempotent). */+export function ensurePinnedBinaries(): ReadonlyMap<string, string> {+ return pinnedTable ?? initPinnedBinaries();+}+/** Default resolver: the pinned table built once per process. */export const pinnedBinary: BinaryResolver = (program) => {if (!pinnedTable) initPinnedBinaries();diff --git a/src/cli/service.test.ts b/src/cli/service.test.tsindex 96c822c4..23a483dc 100644--- a/src/cli/service.test.ts+++ b/src/cli/service.test.ts@@ -12,6 +12,8 @@ import {buildWindowsCommandLine,buildWindowsTaskXml,encodeWindowsTaskXml,+ pinnedServicePath,+ serviceFileOptions,quoteWindowsArg,resolveDistPath,runKeyLaunchArgs,@@ -169,3 +171,45 @@ describe('resolveDistPath', () => {expect(guess.endsWith(join('.nvm', 'versions', 'node', 'v20.11.0', 'lib', 'node_modules', '@cosmicstack', 'mercury-agent', 'dist', 'index.js'))).toBe(true);});});++describe('service PATH pinning (ROADMAP P2.2, #103)', () => {+ const nodeDir = '/Users/jane/.nvm/versions/node/v20.11.0/bin';++ it('pins a fixed PATH of system dirs plus the node directory (darwin, linux)', () => {+ expect(pinnedServicePath('darwin', nodeDir)).toBe(`/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/homebrew/bin:${nodeDir}`);+ expect(pinnedServicePath('linux', '/usr/bin')).toBe('/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin');+ // A relative node dir is never written.+ expect(pinnedServicePath('linux', 'node_modules/.bin')).toBe('/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin');+ });++ it('pins Windows to System32, Git and the node directory', () => {+ const p = pinnedServicePath('win32', 'C:\\Program Files\\nodejs', { SystemRoot: 'C:\\Windows', ProgramFiles: 'C:\\Program Files' });+ expect(p.split(';')).toEqual([+ 'C:\\Windows\\System32',+ 'C:\\Windows',+ 'C:\\Windows\\System32\\Wbem',+ 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0',+ 'C:\\Program Files\\Git\\cmd',+ 'C:\\Program Files\\nodejs',+ ]);+ });++ it('generated plist and systemd unit carry the pinned PATH, not the installing shell PATH', () => {+ const original = process.env.PATH;+ process.env.PATH = `/tmp/evil-bin:./node_modules/.bin:${original}`;+ try {+ const opts = serviceFileOptions();+ expect(opts.pathEnv).not.toContain('/tmp/evil-bin');+ expect(opts.pathEnv).not.toContain('node_modules');+ const args = ['/usr/local/bin/node', '/opt/mercury/dist/index.js', 'start', '--daemon'];+ const plist = buildLaunchAgentPlist(args, opts);+ expect(plist).toContain(`<key>PATH</key>\n <string>${opts.pathEnv}</string>`);+ expect(plist).not.toContain('/tmp/evil-bin');+ const unit = buildSystemdUnit(args, opts);+ expect(unit).toContain(`Environment=PATH=${opts.pathEnv}`);+ expect(unit).not.toContain('/tmp/evil-bin');+ } finally {+ process.env.PATH = original;+ }+ });+});diff --git a/src/cli/service.ts b/src/cli/service.tsindex d1f7f654..618565b2 100644--- a/src/cli/service.ts+++ b/src/cli/service.ts@@ -1,5 +1,5 @@import { existsSync, mkdirSync, writeFileSync, unlinkSync, realpathSync } from 'node:fs';-import { join, posix } from 'node:path';+import { dirname, join, posix, win32 } from 'node:path';import { fileURLToPath } from 'node:url';import { homedir } from 'node:os';import chalk from 'chalk';@@ -338,10 +338,41 @@ export interface ServiceFileOptions {mercuryHome: string;/** Account home — WorkingDirectory and HOME for the daemon. */userHome: string;- /** PATH the daemon inherits. */+ /** PATH the daemon inherits — always `pinnedServicePath()`, never the installing shell's PATH. */pathEnv: string;}+/**+ * The fixed PATH written into service files (ROADMAP P2.2, #103): system+ * directories, the standard package-manager prefixes, and the directory of+ * the node binary that runs the daemon (so approval-lane `npm`/`npx`+ * resolve). It is deliberately NOT the PATH of the shell that ran+ * `mercury service install`: a project-local or user-writable entry there+ * (node_modules/.bin, ~/bin, a cwd-relative entry) would otherwise be+ * baked into every command the daemon runs. Argv-lane commands do not use+ * it at all — they resolve binaries from their own pinned table.+ */+export function pinnedServicePath(platform: NodeJS.Platform, nodeBinDir: string, env: NodeJS.ProcessEnv = process.env): string {+ if (platform === 'win32') {+ const systemRoot = env.SystemRoot || env.SYSTEMROOT || 'C:\\Windows';+ const programFiles = env.ProgramFiles || 'C:\\Program Files';+ const dirs = [+ win32.join(systemRoot, 'System32'),+ systemRoot,+ win32.join(systemRoot, 'System32', 'Wbem'),+ win32.join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0'),+ win32.join(programFiles, 'Git', 'cmd'),+ nodeBinDir,+ ];+ return [...new Set(dirs)].join(';');+ }+ const dirs = ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin'];+ if (platform === 'darwin') dirs.push('/opt/homebrew/bin');+ // Only an absolute node directory; never a relative or empty entry.+ if (nodeBinDir.startsWith('/')) dirs.push(nodeBinDir);+ return [...new Set(dirs)].join(':');+}+function xmlEscape(value: string): string {return value.replace(/&/g, '&')@@ -544,14 +575,23 @@ export function runKeyLaunchArgs(serviceLaunchArgs: string[]): string[] {// ─── macOS ───────────────────────────────────────────────────────────────────-function serviceFileOptions(): ServiceFileOptions {+export function serviceFileOptions(): ServiceFileOptions {return {mercuryHome: getMercuryHome(),userHome: homedir(),- pathEnv: process.env.PATH || '/usr/local/bin:/usr/bin:/bin',+ pathEnv: pinnedServicePath(process.platform, dirname(process.execPath)),};}+/**+ * Windows Task Scheduler XML has no environment block, so the daemon pins+ * its own PATH at startup instead (called from runAgent for `--daemon`).+ */+export function pinDaemonPathOnWindows(): void {+ if (process.platform !== 'win32') return;+ process.env.PATH = pinnedServicePath('win32', dirname(process.execPath));+}+function installMac(): void {const plistDir = join(homedir(), 'Library', 'LaunchAgents');const plistPath = join(plistDir, 'com.cosmicstack.mercury.plist');diff --git a/src/index.ts b/src/index.tsindex 23ffd7d7..02face45 100644--- a/src/index.ts+++ b/src/index.ts@@ -77,7 +77,7 @@ import { ask, InputClosedError } from './cli/ask.js';import { startBackground, stopDaemon, showLogs, getDaemonStatus, registerRuntimeProcess, releaseRuntimeProcess, restartDaemon, tryAutoDaemonize, isStandaloneBinary, getForegroundRuntimeStatus, stopForegroundRuntime } from './cli/daemon.js';import { runUninstall } from './cli/uninstall.js';import { runAttach } from './cli/attach.js';-import { installService, uninstallService, showServiceStatus, isServiceInstalled } from './cli/service.js';+import { installService, uninstallService, showServiceStatus, isServiceInstalled, pinDaemonPathOnWindows } from './cli/service.js';import { detectInkPatch, inkPatchFixCommand } from './ui/ink-patch-check.js';import { runWithWatchdog } from './cli/watchdog.js';import { setGitHubToken } from './utils/github.js';@@ -2325,6 +2325,8 @@ function runPlatformDoctor(): void {async function runAgent(isDaemon: boolean = false): Promise<void> {const runtimeMode = isDaemon ? 'daemon' : 'foreground';+ // launchd/systemd units carry a pinned PATH; Task Scheduler cannot.+ if (isDaemon) pinDaemonPathOnWindows();registerRuntimeProcess(runtimeMode);// Crash forensics: V8 fatal errors (heap OOM etc.) print a native stack