diff --git a/src/cli/service-cli.ts b/src/cli/service-cli.ts new file mode 100644 index 0000000..f620637 --- /dev/null +++ b/src/cli/service-cli.ts @@ -0,0 +1,171 @@ +/** + * `code-executor-mcp service ` — manage the + * resident launchd service that runs the single shared HTTP MCP endpoint. + * + * This is the minimal, local-plist lifecycle (PR2): enough to install a working + * resident service and point a host at it. Homebrew / `brew services` wrapping, + * host-config rewiring (`configure-hosts`), and token rotation are later PRs. + */ + +import * as path from 'node:path'; +import * as os from 'node:os'; +import { LaunchdService } from '../service/launchd-service.js'; +import { ensureHttpToken, getHttpTokenPath } from '../service/http-token.js'; +import { getHttpPort, getHttpHost } from '../config/loader.js'; + +const USAGE = + 'Usage: code-executor-mcp service ' + + '[--port N] [--config PATH] [--binary PATH] [--no-auth]'; + +interface ServiceFlags { + port?: number; + config?: string; + binary?: string; + auth: boolean; // default: true (auth on) +} + +/** Parse the flag subset the service command accepts. Throws on anything else. */ +function parseFlags(args: string[]): ServiceFlags { + const flags: ServiceFlags = { auth: true }; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + switch (arg) { + case '--port': + flags.port = parseInt(args[++i] ?? '', 10); + break; + case '--config': + flags.config = args[++i]; + break; + case '--binary': + flags.binary = args[++i]; + break; + case '--no-auth': + flags.auth = false; + break; + default: + throw new Error(`Unknown flag: ${arg}\n${USAGE}`); + } + } + if (flags.port !== undefined && (isNaN(flags.port) || flags.port < 1024 || flags.port > 65535)) { + throw new Error('--port must be an integer between 1024 and 65535'); + } + return flags; +} + +/** Build the launchd EnvironmentVariables and install + load the service. */ +async function doInstall(service: LaunchdService, flags: ServiceFlags): Promise { + // The compiled binary invoking this command is exactly what launchd should run. + const programPath = path.resolve(flags.binary ?? process.execPath); + const port = flags.port ?? getHttpPort(); + const host = getHttpHost(); + const logDir = path.join(os.homedir(), 'Library', 'Logs'); + + const env: Record = { + CODE_EXECUTOR_ROLE: 'http', + CODE_EXECUTOR_HTTP_PORT: String(port), + // The single-instance model structurally prevents the fork-bomb the ancestry + // guard defends against, and launchd (not a parent code-executor) launches + // this process — so allow it to build the downstream pool. + CODE_EXECUTOR_ALLOW_NESTED: '1', + }; + + const configPath = flags.config ?? process.env.MCP_CONFIG_PATH; + if (configPath) { + env.MCP_CONFIG_PATH = path.resolve(configPath); + } + + let token: string | undefined; + if (flags.auth) { + token = await ensureHttpToken(); + env.CODE_EXECUTOR_HTTP_TOKEN = token; + } else { + env.CODE_EXECUTOR_HTTP_AUTH = 'off'; + } + + await service.install({ + programPath, + env, + stdoutPath: path.join(logDir, 'code-executor-mcp.log'), + stderrPath: path.join(logDir, 'code-executor-mcp.error.log'), + }); + + console.log(`✅ Installed and loaded launchd service "${service.serviceLabel}"`); + console.log(` Binary : ${programPath}`); + console.log(` Endpoint: http://${host}:${port}/mcp`); + if (configPath) { + console.log(` Config : ${env.MCP_CONFIG_PATH}`); + } + if (token) { + console.log(` Auth : Bearer token (stored 0600 at ${getHttpTokenPath()})`); + console.log(''); + console.log(' Point an MCP host at it with:'); + console.log(` url : http://${host}:${port}/mcp`); + console.log(` header : Authorization: Bearer ${token}`); + } else { + console.log(' Auth : OFF (CODE_EXECUTOR_HTTP_AUTH=off)'); + } +} + +/** Print installed / loaded / health status. */ +async function doStatus(service: LaunchdService): Promise { + const plistPresent = await service.plistExists(); + const loaded = await service.isLoaded(); + const host = getHttpHost(); + const port = getHttpPort(); + + console.log(`Service : ${service.serviceLabel}`); + console.log(`Plist : ${plistPresent ? service.plistFilePath : '(not installed)'}`); + console.log(`Loaded : ${loaded ? 'yes' : 'no'}`); + + // Best-effort readiness probe against the default/env port (the installed + // plist may use a different port; this reports what is reachable now). + try { + const res = await fetch(`http://${host}:${port}/health`); + if (res.ok) { + const body = (await res.json()) as { sessions?: number; version?: string }; + console.log(`Health : ok (sessions: ${body.sessions ?? '?'}, v${body.version ?? '?'})`); + } else { + console.log(`Health : HTTP ${res.status}`); + } + } catch { + console.log(`Health : unreachable at http://${host}:${port}/health`); + } +} + +/** + * Entry point for the `service` subcommand. Handles its own process exit so the + * caller (src/index.ts) does not need to. + */ +export async function runServiceCli(args: string[]): Promise { + const sub = args[0]; + const rest = args.slice(1); + const service = new LaunchdService(); + + try { + switch (sub) { + case 'install': + await doInstall(service, parseFlags(rest)); + break; + case 'uninstall': + await service.uninstall(); + console.log(`✅ Uninstalled launchd service "${service.serviceLabel}"`); + break; + case 'restart': + await service.restart(); + console.log(`✅ Restarted launchd service "${service.serviceLabel}"`); + break; + case 'status': + await doStatus(service); + break; + default: + console.error(USAGE); + process.exit(2); + } + process.exit(0); + } catch (error) { + console.error( + `❌ service ${sub ?? ''} failed: ${error instanceof Error ? error.message : String(error)}` + ); + process.exit(1); + } +} diff --git a/src/config/loader.ts b/src/config/loader.ts index 21b1261..df8349a 100644 --- a/src/config/loader.ts +++ b/src/config/loader.ts @@ -591,3 +591,33 @@ export function getHttpAuthToken(): string | undefined { const token = process.env.CODE_EXECUTOR_HTTP_TOKEN; return token && token.length > 0 ? token : undefined; } + +/** + * Idle-teardown window (ms) for the shared downstream MCP pool. + * + * `0` (the default) means DISABLED — the pool is built eagerly at startup and + * kept warm for the process lifetime (today's behavior, and the stdio default). + * When `> 0`, the resident HTTP service builds the pool LAZILY on the first tool + * call and tears it down after this many ms with zero connected sessions, so an + * idle resident service reclaims its ~15 downstream children; the next tool call + * rebuilds the pool. Set via `CODE_EXECUTOR_POOL_IDLE_MS`. + * + * **WHY clamp/disable instead of throw:** this governs a RESIDENT service's + * startup. A throw on a bad value would crash the service (mirroring the + * shutdown-knob rationale in {@link getBoundedEnvMs}), so a non-numeric or + * non-positive value falls back to disabled (eager) and an out-of-range value is + * clamped — never fatal. + */ +export const DEFAULT_POOL_IDLE_MS = 0; // disabled → eager pool +const MIN_POOL_IDLE_MS = 1_000; // 1s floor when enabled +const MAX_POOL_IDLE_MS = 24 * 60 * 60 * 1_000; // 24h ceiling + +export function getPoolIdleMs(): number { + const raw = process.env.CODE_EXECUTOR_POOL_IDLE_MS; + if (!raw) return DEFAULT_POOL_IDLE_MS; + const parsed = parseInt(raw, 10); + if (isNaN(parsed) || parsed <= 0) return DEFAULT_POOL_IDLE_MS; // 0/invalid → disabled + if (parsed < MIN_POOL_IDLE_MS) return MIN_POOL_IDLE_MS; + if (parsed > MAX_POOL_IDLE_MS) return MAX_POOL_IDLE_MS; + return parsed; +} diff --git a/src/core/shared-core.ts b/src/core/shared-core.ts index 2d04387..7f3b93a 100644 --- a/src/core/shared-core.ts +++ b/src/core/shared-core.ts @@ -66,19 +66,33 @@ export class SharedCore { rateLimiter: RateLimiter | null = null; denoAvailable = false; // Resolves when the downstream MCP client pool has finished initializing. - // The pool is initialized in the BACKGROUND (see startBackgroundServices) so - // the upstream MCP handshake is never blocked by slow/unreachable downstream - // servers. Tool handlers await this before executing so downstream tools are - // ready (or have been determined unavailable) by the time code runs. + // The pool is initialized in the BACKGROUND (see startBackgroundServices / + // ensurePoolReady) so the upstream MCP handshake is never blocked by slow/ + // unreachable downstream servers. Tool handlers call ensurePoolReady() and + // await this before executing so downstream tools are ready (or have been + // determined unavailable) by the time code runs. poolReady: Promise = Promise.resolve(); private healthCheckServer: HealthCheckServer | null = null; private shutdownInProgress = false; // P1: Prevent concurrent shutdown attempts - constructor() { + // Lazy/idle downstream pool (resident HTTP mode). When idleMs === 0 the pool is + // eager and kept warm for the process lifetime (stdio default, unchanged). When + // idleMs > 0 it is built on the first tool call (see ensurePoolReady) and torn + // down after idleMs with zero active sessions, then rebuilt on demand. + private poolInitStarted = false; + private idleMs = 0; + private activeSessions = 0; + private idleTimer: ReturnType | null = null; + + /** + * @param deps - Optional injected collaborators (tests). Production callers + * pass nothing, so the pool/connection-pool are built here as before. + */ + constructor(deps?: { mcpClientPool?: MCPClientPool; connectionPool?: ConnectionPool }) { // Initialize components - this.mcpClientPool = new MCPClientPool(); + this.mcpClientPool = deps?.mcpClientPool ?? new MCPClientPool(); this.securityValidator = new SecurityValidator(); - this.connectionPool = new ConnectionPool(100); // Max 100 concurrent executions + this.connectionPool = deps?.connectionPool ?? new ConnectionPool(100); // Max 100 concurrent executions } /** @@ -118,25 +132,30 @@ export class SharedCore { /** * Post-transport background services: kick off the downstream MCP client pool - * (in the background — not awaited) and start the optional health-check server. + * (eager mode — in the background, not awaited) and start the optional + * health-check server. + * + * @param options.poolIdleMs - Idle-teardown window. `0`/omitted keeps the pool + * eager (built now, warm for the process lifetime — stdio default). `> 0` + * defers the build to the first tool call and tears the pool down after this + * many ms with no sessions (resident HTTP mode; see {@link getPoolIdleMs}). */ - async startBackgroundServices(): Promise { - // Initialize MCP client pool in the background. Tool handlers await - // `poolReady` before executing (see registerTools). Failures are logged but - // never crash the server — code-executor keeps serving whatever connected. - console.error('Initializing MCP client pool...'); - this.poolReady = this.mcpClientPool - .initialize() - .then(() => { - const tools = this.mcpClientPool.listAllTools(); - console.error(`Connected to ${tools.length} MCP tools across multiple servers`); - }) - .catch((error) => { - const message = error instanceof Error ? error.message : String(error); - console.error( - `MCP client pool initialization failed — continuing without downstream tools: ${message}` - ); - }); + async startBackgroundServices(options?: { poolIdleMs?: number }): Promise { + this.idleMs = options?.poolIdleMs && options.poolIdleMs > 0 ? options.poolIdleMs : 0; + + if (this.idleMs === 0) { + // Eager: initialize the downstream pool now, in the background. Tool + // handlers await ensurePoolReady() (which returns this same promise) + // before executing. Failures are logged but never crash the server. + this.ensurePoolReady(); + } else { + // Lazy: defer the build to the first tool call so a resident service with + // no connected host stays lightweight; it is torn down after idleMs with + // no sessions and rebuilt on demand. + console.error( + `Lazy downstream pool: build on first tool call, tear down after ${this.idleMs}ms idle` + ); + } // Initialize health check server (optional, enabled via env var) const enableHealthCheck = process.env.ENABLE_HEALTH_CHECK !== 'false'; @@ -158,6 +177,102 @@ export class SharedCore { } } + /** + * Ensure the downstream MCP client pool is initializing (or already + * initialized) and return a promise that resolves when it is ready. + * + * Idempotent: `poolInitStarted` is flipped synchronously (single-threaded + * event loop), so concurrent callers share one in-flight initialization — no + * lock needed. In eager mode {@link startBackgroundServices} calls this once + * at startup; tool handlers then await an already-started init. In lazy mode + * the FIRST tool call triggers the build, and after an idle teardown the flag + * is reset so the next call rebuilds the pool. + * + * Failures are logged but never rejected — code-executor keeps serving with + * whatever downstream tools connected (or none). + */ + ensurePoolReady(): Promise { + if (!this.poolInitStarted) { + this.poolInitStarted = true; + console.error('Initializing MCP client pool...'); + this.poolReady = this.mcpClientPool + .initialize() + .then(() => { + const tools = this.mcpClientPool.listAllTools(); + console.error(`Connected to ${tools.length} MCP tools across multiple servers`); + }) + .catch((error) => { + const message = error instanceof Error ? error.message : String(error); + console.error( + `MCP client pool initialization failed — continuing without downstream tools: ${message}` + ); + }); + } + return this.poolReady; + } + + /** + * Record that a host session connected (HTTP transport). Cancels any pending + * idle teardown so the pool stays warm while at least one host is connected. + */ + onSessionOpen(): void { + this.activeSessions++; + this.cancelIdleTimer(); + } + + /** + * Record that a host session closed. When the LAST session closes (and idle + * teardown is enabled), arm the timer that reclaims the downstream pool. + */ + onSessionClose(): void { + this.activeSessions = Math.max(0, this.activeSessions - 1); + if (this.idleMs > 0 && this.activeSessions === 0) { + this.armIdleTimer(); + } + } + + private armIdleTimer(): void { + this.cancelIdleTimer(); + this.idleTimer = setTimeout(() => { + this.idleTimer = null; + void this.teardownIdlePool(); + }, this.idleMs); + // Do not keep the event loop alive solely for this timer. + this.idleTimer.unref?.(); + } + + private cancelIdleTimer(): void { + if (this.idleTimer) { + clearTimeout(this.idleTimer); + this.idleTimer = null; + } + } + + /** + * Tear down the downstream pool after an idle period with no sessions, so a + * resident service reclaims its ~15 downstream children when nobody is using + * it. Re-checked at fire time: a reconnected session or an in-flight execution + * defers teardown (the timer is re-armed in the latter case). After teardown + * `poolInitStarted` resets so the next tool call rebuilds the pool via + * {@link ensurePoolReady}. + */ + private async teardownIdlePool(): Promise { + if (this.activeSessions > 0) return; // a session reconnected during the window + if (!this.poolInitStarted) return; // nothing was built + if (this.connectionPool.getStats().active > 0) { + this.armIdleTimer(); // an execution is in flight — retry after another window + return; + } + console.error(`Downstream pool idle for ${this.idleMs}ms with no sessions — tearing down`); + try { + await this.mcpClientPool.disconnect(); + } catch (error) { + console.error('Error tearing down idle downstream pool:', error); + } + this.poolInitStarted = false; + this.poolReady = Promise.resolve(); + } + /** * Graceful shutdown with request draining * @@ -182,6 +297,7 @@ export class SharedCore { return; } this.shutdownInProgress = true; + this.cancelIdleTimer(); // no idle teardown once a full shutdown is underway const shutdownStart = Date.now(); @@ -442,10 +558,11 @@ Example: }; } - // Ensure the downstream MCP pool has finished initializing (it is set - // up in the background at startup) so callMCPTool/discovery see the - // connected servers. Bounded by per-server connect timeouts. - await core.poolReady; + // Ensure the downstream MCP pool is ready so callMCPTool/discovery see + // the connected servers. Eager mode: this awaits the startup build; + // lazy mode: the first call triggers (and later calls rebuild) it. + // Bounded by per-server connect timeouts. + await core.ensurePoolReady(); // Execute code with connection pooling const result = await core.connectionPool.execute(async () => { @@ -705,9 +822,10 @@ Example: }; } - // Ensure the downstream MCP pool has finished initializing (background - // startup) before executing. Bounded by per-server connect timeouts. - await core.poolReady; + // Ensure the downstream MCP pool is ready before executing. Eager mode: + // awaits the startup build; lazy mode: the first call triggers (and + // later calls rebuild) it. Bounded by per-server connect timeouts. + await core.ensurePoolReady(); // Execute code with connection pooling // Use Pyodide (secure) when PYTHON_SANDBOX_READY, otherwise native (insecure) diff --git a/src/http/http-server.ts b/src/http/http-server.ts index cf791ee..540bf9c 100644 --- a/src/http/http-server.ts +++ b/src/http/http-server.ts @@ -33,6 +33,7 @@ import { getHttpHost, isHttpAuthEnabled, getHttpAuthToken, + getPoolIdleMs, } from '../config/loader.js'; import { VERSION } from '../version.js'; @@ -92,7 +93,10 @@ export async function runHttpServer(): Promise { // then kick off the downstream pool + health server. All sessions share it. const core = new SharedCore(); await core.initialize(); - await core.startBackgroundServices(); + // In HTTP mode the pool may be built lazily and torn down when idle so a + // resident service reclaims its downstream children between uses (0 = eager). + const poolIdleMs = getPoolIdleMs(); + await core.startBackgroundServices({ poolIdleMs }); const port = getHttpPort(); const host = getHttpHost(); @@ -101,6 +105,18 @@ export async function runHttpServer(): Promise { // One transport (+ its own McpServer) per live MCP session, keyed by session id. const sessions = new Map(); + /** + * Forget a session exactly once and notify the core's idle accounting. Both + * `onsessionclosed` and `transport.onclose` can fire for the same session, so + * the decrement is gated on the Map actually having held the id. + */ + function closeSession(id: string | undefined): void { + if (id && sessions.delete(id)) { + core.onSessionClose(); + console.error(`MCP session closed: ${id} (active: ${sessions.size})`); + } + } + /** Create a fresh per-session transport + McpServer sharing the one core. */ async function openSession(): Promise { // Pre-generate the session id so it can scope this session's audit-log @@ -113,18 +129,12 @@ export async function runHttpServer(): Promise { allowedHosts, onsessioninitialized: (id) => { sessions.set(id, transport); + core.onSessionOpen(); console.error(`MCP session opened: ${id} (active: ${sessions.size})`); }, - onsessionclosed: (id) => { - sessions.delete(id); - console.error(`MCP session closed: ${id} (active: ${sessions.size})`); - }, + onsessionclosed: (id) => closeSession(id), }); - transport.onclose = () => { - if (transport.sessionId) { - sessions.delete(transport.sessionId); - } - }; + transport.onclose = () => closeSession(transport.sessionId); const server = new McpServer({ name: 'code-executor-mcp-server', version: VERSION }); registerTools(core, server, sessionId); diff --git a/src/index.ts b/src/index.ts index be1290b..b94665e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -190,6 +190,17 @@ if (command === 'setup') { console.error('❌ Wrapper sync failed:', error); process.exit(1); }); +} else if (command === 'service') { + // Manage the resident launchd service that runs the single shared HTTP MCP + // endpoint (macOS): install | uninstall | status | restart. Argv-dispatched + // like `setup`/`sync-wrappers`; the resident server itself is selected by env + // (CODE_EXECUTOR_ROLE=http), which launchd sets via the plist. + import('./cli/service-cli.js') + .then((m) => m.runServiceCli(args.slice(1))) + .catch((error) => { + console.error('❌ service command failed:', error); + process.exit(1); + }); } else { // Server startup flow. // diff --git a/src/service/http-token.ts b/src/service/http-token.ts new file mode 100644 index 0000000..9a0aa94 --- /dev/null +++ b/src/service/http-token.ts @@ -0,0 +1,62 @@ +/** + * Bearer-token bootstrap for the single-instance HTTP MCP endpoint. + * + * The resident service requires a bearer token (auth is on by default — a + * code-execution endpoint on a loopback TCP port is reachable by any local + * process and, via DNS-rebinding, by browsers). This persists a random token + * under `~/.code-executor/http-token` with `0600` permissions so `service + * install` can bake its value into the launchd plist and, later (PR4), inject + * the SAME value into each host config. Idempotent: an existing non-empty token + * file is reused rather than rotated. + */ + +import { promises as fs } from 'node:fs'; +import { randomBytes } from 'node:crypto'; +import * as path from 'node:path'; +import * as os from 'node:os'; + +const TOKEN_FILENAME = 'http-token'; + +/** The `~/.code-executor` state directory (shared with wrappers, audit logs). */ +export function getCodeExecutorDir(): string { + return path.join(os.homedir(), '.code-executor'); +} + +/** Absolute path of the persisted bearer-token file. */ +export function getHttpTokenPath(): string { + return path.join(getCodeExecutorDir(), TOKEN_FILENAME); +} + +/** Generate a fresh 256-bit token as a 64-character hex string (XML/URL safe). */ +export function generateToken(): string { + return randomBytes(32).toString('hex'); +} + +/** + * Return the persisted HTTP bearer token, generating and storing one (`0600`) + * if the file is absent or empty. + * + * @param dir - Storage directory override (tests). Defaults to `~/.code-executor`. + */ +export async function ensureHttpToken(dir: string = getCodeExecutorDir()): Promise { + const tokenPath = path.join(dir, TOKEN_FILENAME); + + try { + const existing = (await fs.readFile(tokenPath, 'utf-8')).trim(); + if (existing.length > 0) { + return existing; + } + } catch { + // Not present (or unreadable) — generate a new one below. + } + + const token = generateToken(); + await fs.mkdir(dir, { recursive: true }); + await fs.writeFile(tokenPath, token, { mode: 0o600 }); + // Enforce 0600 even if the file pre-existed (empty) with looser permissions; + // writeFile's mode is not applied to an already-existing file. + await fs.chmod(tokenPath, 0o600).catch(() => { + // Best effort — a filesystem that cannot chmod is not a reason to fail. + }); + return token; +} diff --git a/src/service/launchd-service.ts b/src/service/launchd-service.ts new file mode 100644 index 0000000..512cc28 --- /dev/null +++ b/src/service/launchd-service.ts @@ -0,0 +1,288 @@ +/** + * Resident launchd service manager (macOS). + * + * WHY: in HTTP mode a single code-executor process must already be running + * before any host connects — an HTTP MCP client cannot spawn its own server the + * way a stdio host does. launchd is the macOS way to keep such a user service + * resident: `RunAtLoad` starts it at login and `KeepAlive` restarts it on crash. + * + * This is DISTINCT from {@link ../cli/schedulers/launchd-scheduler} (a + * `StartCalendarInterval` timer for the daily wrapper sync): here the plist + * declares a long-running background daemon, not a scheduled one-shot. + * + * Security: + * - The plist is written `0600` — it carries the bearer token in + * `EnvironmentVariables`. + * - Every interpolated value is XML-escaped (paths, env keys/values). + * - The label is validated to a safe charset so it can never traverse out of + * `~/Library/LaunchAgents`. + * - launchd runs `ProgramArguments` directly (no shell), so there is no shell + * metacharacter injection surface. + */ + +import { promises as fs } from 'node:fs'; +import { spawn } from 'node:child_process'; +import * as path from 'node:path'; +import * as os from 'node:os'; + +/** Default reverse-DNS launchd label for the resident service. */ +export const DEFAULT_SERVICE_LABEL = 'com.codeexecutor.mcp'; + +/** Everything needed to render the resident-service plist. */ +export interface ResidentServiceSpec { + /** Absolute path to the executable launchd should run (the compiled binary). */ + programPath: string; + /** Environment variables baked into the plist (role, port, token, config…). */ + env: Record; + /** Absolute path for the service's stdout log. */ + stdoutPath: string; + /** Absolute path for the service's stderr log. */ + stderrPath: string; +} + +/** Runs `launchctl `, resolving on exit 0 and rejecting otherwise. */ +export type LaunchctlRunner = (args: string[]) => Promise; + +export interface LaunchdServiceOptions { + /** launchd label (also the plist basename). Default {@link DEFAULT_SERVICE_LABEL}. */ + label?: string; + /** LaunchAgents directory. Default `~/Library/LaunchAgents` (override in tests). */ + launchAgentsDir?: string; + /** GUI domain uid for `launchctl`. Default the current user's uid. */ + uid?: number; + /** Host platform. Default `process.platform` (override in tests). */ + platform?: NodeJS.Platform; + /** launchctl runner. Default spawns the real `launchctl` (override in tests). */ + runLaunchctl?: LaunchctlRunner; +} + +/** Escape a string for safe inclusion in a plist XML text node. */ +export function escapeXml(value: string): string { + return value + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + +export class LaunchdService { + private readonly label: string; + private readonly launchAgentsDir: string; + private readonly plistPath: string; + private readonly uid: number; + private readonly platform: NodeJS.Platform; + private readonly runLaunchctl: LaunchctlRunner; + + constructor(options: LaunchdServiceOptions = {}) { + this.label = options.label ?? DEFAULT_SERVICE_LABEL; + + // Restrict the label to a safe charset (reverse-DNS style). This also makes + // path traversal in the plist path impossible — no `/`, so no `../`. + if (!/^[a-zA-Z0-9_.-]+$/.test(this.label)) { + throw new Error( + 'Service label must contain only alphanumerics, hyphens, underscores, and dots' + ); + } + + this.launchAgentsDir = + options.launchAgentsDir ?? path.join(os.homedir(), 'Library', 'LaunchAgents'); + this.plistPath = path.join(this.launchAgentsDir, `${this.label}.plist`); + + // Defense-in-depth: the plist must stay inside the LaunchAgents directory. + if (!this.plistPath.startsWith(this.launchAgentsDir + path.sep)) { + throw new Error('Path traversal detected in service label'); + } + + this.uid = options.uid ?? os.userInfo().uid; + this.platform = options.platform ?? process.platform; + this.runLaunchctl = options.runLaunchctl ?? ((args) => this.defaultRunLaunchctl(args)); + } + + /** The launchd label / plist basename. */ + get serviceLabel(): string { + return this.label; + } + + /** Absolute path of the managed plist. */ + get plistFilePath(): string { + return this.plistPath; + } + + /** The `gui/` service-target domain used by modern launchctl verbs. */ + private get domainTarget(): string { + return `gui/${this.uid}`; + } + + /** The `gui//