diff --git a/README.md b/README.md index 3fb4eb6..a0ad18e 100644 --- a/README.md +++ b/README.md @@ -4,10 +4,10 @@ MCP-Server für Unraid: Docker-Container, Netzwerk und System-Tools. Kompiliertes Bun-Binary (TypeScript), läuft als SysVinit-Service auf Unraid. - **MCP-Endpunkt:** `http://UNRAID-IP:3002/mcp` (Streamable HTTP, POST-only, JSON-RPC 2.0) -- **Health-Check:** `http://UNRAID-IP:3002/health` (offen, ohne Auth) +- **Health-Check:** `http://UNRAID-IP:3002/health` (offen; Version/Port nur mit Bearer-Token) - **Config-Server:** `http://127.0.0.1:3013/config` (localhost + separater Admin-Token) - **Auth:** API-Key (Bearer-Token) für `/mcp` -- **Tools:** 47 (Docker, Community Applications, Netzwerk, Unraid-System und optionale Toolbox) +- **Tools:** 48 (Docker, Community Applications, Netzwerk, Unraid-System und optionale Toolbox) --- @@ -90,10 +90,22 @@ Die veröffentlichten r033-/r034-Archive werden nicht überschrieben. - Neuinstallationen starten im Profil **Nur Lesen**. Container-Steuerung, aktive Netzwerktests, Container-Umbauten und die Root-Shell sind aus. -- Für Diagnosen steht `unraid_system_shell_readonly` bereit. Es startet nur - fest freigegebene Leseprogramme als direkte Argumentliste, niemals über - `/bin/sh`; Verkettungen, Pipes, Umleitungen und schreibende Optionen werden - dadurch verhindert. Die freie Root-Shell bleibt separat und kritisch. +- Für Diagnosen steht `unraid_system_shell_readonly` bereit. Es nimmt eine + normale Befehlszeile (`command`, z.B. `ps aux | grep -i plex`, + `df -h; free -m`, `grep -i error /var/log/*.log`) oder `program` + `args`. + MUA zerlegt die Zeile selbst (Quotes, Pipes, `;`/`&&`/`||`, Globs in + absoluten Pfaden) und prüft jedes Programm gegen eine Allowlist mit + Options-Policy je Programm (kombinierte Kurzflags, `--opt=wert`, + GNU-Abkürzungen, `ip` nur mit Leseverben). Umleitungen, Variablen und + `$(…)` gibt es nicht; Pipeline-Stufen bekommen nur vorab geprüfte, + strikt gequotete Literale. Dateien mit Zugangsdaten (`/etc/shadow`, + SSH-Private-Keys, `mua.conf`, `/proc/*/environ`, Docker-`config.v2.json`) + sind gesperrt; in rekursiven Ausgaben werden Passwort-Hashes, + private PEM-Schlüssel und WireGuard-Keys geschwärzt. Die freie Root-Shell + bleibt separat und kritisch. +- MUA-API-Key und Admin-Token erscheinen in keiner Tool-Ausgabe. +- Timeouts beenden die gesamte Prozessgruppe (Shell samt Kindprozessen), + nicht nur den direkten Kindprozess. - `none` bedeutet tatsächlich **keine Tools aktiv**; `all` ist ein expliziter Vollzugriff und wird in der GUI deutlich gewarnt. - Container-Umgebungswerte werden nie ausgegeben, nur ihre Variablennamen. @@ -150,7 +162,9 @@ Der Service startet automatisch bei jedem Boot (SysVinit). ```bash curl http://UNRAID-IP:3002/health -# → {"status":"ok","version":"2026.11.05.r035","auth":"required"} +# → {"status":"ok","server":"mua","auth":"required",...} +curl -H "Authorization: Bearer $MUA_API_KEY" http://UNRAID-IP:3002/health +# → zusätzlich "version" und "port" ``` Bei aktiviertem TLS den zertifizierten Namen mit `https://` und passendem @@ -264,7 +278,7 @@ Zusätzlich kann jedes Werkzeug einzeln nach Risikostufe freigegeben werden: | **Docker (16)** | `unraid_docker_list`, `unraid_docker_inspect`, `unraid_docker_logs`, `unraid_docker_analyze_logs`, `unraid_docker_processes`, `unraid_docker_stats`, `unraid_docker_info`, `unraid_docker_update_status`, `unraid_docker_start`, `unraid_docker_stop`, `unraid_docker_restart`, `unraid_docker_create`, `unraid_docker_modify`, `unraid_docker_update`, `unraid_docker_update_verified_batch`, `unraid_docker_rebuild` | | **Community Applications (3)** | `unraid_ca_search`, `unraid_ca_install_preview`, `unraid_ca_install` | | **Netzwerk (6)** | `unraid_network_inventory`, `unraid_network_list`, `unraid_network_inspect`, `unraid_network_host_state`, `unraid_network_audit_tcp`, `unraid_network_lan_probe` | -| **System (13)** | `unraid_system_health`, `unraid_storage_status`, `unraid_disk_health`, `unraid_notifications_list`, `unraid_shares_list`, `unraid_share_inspect`, `unraid_files_inventory`, `unraid_system_connection_test`, `unraid_system_shell_readonly`, `unraid_system_shell`, `unraid_system_job_start`, `unraid_system_job_status`, `unraid_system_job_cleanup` | +| **System (14)** | `unraid_system_health`, `unraid_storage_status`, `unraid_disk_health`, `unraid_notifications_list`, `unraid_shares_list`, `unraid_share_inspect`, `unraid_files_inventory`, `unraid_system_connection_test`, `unraid_system_shell_readonly`, `unraid_system_shell`, `unraid_system_job_start`, `unraid_system_job_status`, `unraid_system_job_cancel`, `unraid_system_job_cleanup` | Deaktivierte Tools werden vom MCP-Server gefiltert — sie erscheinen nicht in `tools/list` und können nicht aufgerufen werden (→ `ERROR: Tool disabled`). @@ -300,6 +314,9 @@ Administrationsaufträge unmittelbar verwenden und weder den MUA-Quellcode untersuchen noch Befehle über ein lokales Client-Terminal weiterreichen. Das Werkzeug akzeptiert mehrzeilige Skripte bis 256 KiB und Laufzeiten bis 30 Minuten. Nur noch längere Arbeiten gehören in `unraid_system_job_start`. +Jobs laufen in einer eigenen Prozessgruppe, lassen sich mit +`unraid_system_job_cancel` vollständig abbrechen und werden 7 Tage nach +Abschluss automatisch aus `/tmp/mua-jobs` entfernt (`MUA_JOB_RETENTION_DAYS`). --- @@ -424,8 +441,6 @@ Version in **allen** Dateien aktualisieren: - `src/helpers.ts` (`MUA_VERSION`) - `plugin/plugin.json` - `plugin/mua.plg` (Version + txzURL + CHANGES) -- `mcp/server.php` -- `mcp/helpers.php` Nach Build: **SHA256** im `.plg` aktualisieren: ```bash diff --git a/bun.lock b/bun.lock index 54a99ab..c247b87 100644 --- a/bun.lock +++ b/bun.lock @@ -5,7 +5,7 @@ "": { "name": "mua", "devDependencies": { - "@types/bun": "latest", + "@types/bun": "1.3.14", }, }, }, diff --git a/dist/mua-2026.11.20.r036-x86_64-1.txz b/dist/mua-2026.11.20.r036-x86_64-1.txz new file mode 100644 index 0000000..6eb6f8e Binary files /dev/null and b/dist/mua-2026.11.20.r036-x86_64-1.txz differ diff --git a/dist/mua-2026.11.20.r036-x86_64-1.txz.sha256 b/dist/mua-2026.11.20.r036-x86_64-1.txz.sha256 new file mode 100644 index 0000000..3c79012 --- /dev/null +++ b/dist/mua-2026.11.20.r036-x86_64-1.txz.sha256 @@ -0,0 +1 @@ +625e56d3725e40479ec89e38c738728bf7e84724de5404dde8f5a43ebfec157d mua-2026.11.20.r036-x86_64-1.txz diff --git a/mcp/helpers.php b/mcp/helpers.php deleted file mode 100644 index 97c04ed..0000000 --- a/mcp/helpers.php +++ /dev/null @@ -1,510 +0,0 @@ - ['pipe', 'r'], - 1 => ['pipe', 'w'], - 2 => ['pipe', 'w'], - ]; - $proc = proc_open($cmd, $descriptors, $pipes); - if (!is_resource($proc)) { - throw new RuntimeException("proc_open failed for: $label"); - } - fclose($pipes[0]); - stream_set_blocking($pipes[1], false); - stream_set_blocking($pipes[2], false); - - $output = ''; - $error = ''; - $start = microtime(true); - while (true) { - $out = fread($pipes[1], 65536); - $err = fread($pipes[2], 65536); - if ($out !== false && $out !== '') $output .= $out; - if ($err !== false && $err !== '') $error .= $err; - if (feof($pipes[1]) && feof($pipes[2])) break; - if (microtime(true) - $start > $timeout) { - proc_terminate($proc, 9); - fclose($pipes[1]); - fclose($pipes[2]); - proc_close($proc); - throw new RuntimeException("Timeout after {$timeout}s: $label"); - } - usleep(5000); - } - fclose($pipes[1]); - fclose($pipes[2]); - $rc = proc_close($proc); - - $result = trim($output); - if ($result === '' && $error !== '') { - $result = trim($error); - } - return $result; -} - -/** - * Docker-Befehl ausführen (kompakt). - */ -function docker_exec(string $cmd, int $timeout = 60): string { - return run_local('docker', "/usr/bin/docker $cmd 2>&1", $timeout); -} - -/** - * Validiere einen Namen (Container, Network, Host, Template). - * Verhindert Shell-Injection. - * - * @param mixed $value - * @param string $field - * @return string - * @throws InvalidArgumentException - */ -function validate_name($value, string $field): string { - if (!is_string($value) || $value === '') { - throw new InvalidArgumentException("$field is required"); - } - // Erlaubt: Buchstaben, Ziffern, -, _, . - if (!preg_match('/^[a-zA-Z0-9._-]{1,128}$/', $value)) { - throw new InvalidArgumentException("Invalid $field: $value"); - } - return $value; -} - -/** - * JSON-Lines parsen (eine JSON-Objekt pro Zeile). - */ -function json_lines(string $text): array { - $result = []; - foreach (explode("\n", $text) as $line) { - $line = trim($line); - if ($line === '') continue; - $decoded = json_decode($line, true); - if (json_last_error() === JSON_ERROR_NONE) { - $result[] = $decoded; - } - } - return $result; -} - -/** - * Extrahiere Host-Adressen aus `ip -j address show` + `ss`-Output. - * - * @return array{ipv4:string, ipv6:string, public_ipv6:string} - */ -function host_addresses(string $raw): array { - // Robust: JSON parsen statt Regex - $data = json_decode($raw, true); - if (!is_array($data)) { - return ['ipv4' => '', 'ipv6' => '', 'public_ipv6' => '']; - } - - $ipv4 = ''; - $ipv6 = ''; - $public_ipv6 = ''; - - foreach ($data as $iface) { - $ifname = $iface['ifname'] ?? ''; - if ($ifname === 'lo') continue; // Loopback überspringen - - foreach ($iface['addr_info'] ?? [] as $addr) { - $local = $addr['local'] ?? ''; - $family = $addr['family'] ?? ''; - - if ($family === 'inet') { - // IPv4: erste private Adresse - if ($local !== '127.0.0.1' && $local !== '0.0.0.0' && $ipv4 === '') { - $ipv4 = $local; - } - } elseif ($family === 'inet6') { - // IPv6: Link-Local (fe80::) - if (strpos($local, 'fe80') === 0 && $ipv6 === '') { - $ipv6 = $local; - } - // Public IPv6 (global, nicht fe80/fd/fc/::1) - if (strpos($local, 'fe80') !== 0 - && strpos($local, 'fd') !== 0 - && strpos($local, 'fc') !== 0 - && $local !== '::1' - && $public_ipv6 === '') { - $public_ipv6 = $local; - } - } - } - } - - return ['ipv4' => $ipv4, 'ipv6' => $ipv6, 'public_ipv6' => $public_ipv6]; -} - -/** - * TCP-Port probe (IPv4 oder IPv6). - */ -function tcp_probe(string $host, int $port, int $family, float $timeout): array { - if ($host === '') { - return ['reachable' => false, 'error' => 'no host address']; - } - $addr = $family === AF_INET6 ? "[$host]" : $host; - $context = stream_context_create([ - 'tcp' => ['timeout' => $timeout, 'binary_package' => true], - ]); - $start = microtime(true); - $fp = @fsockopen($addr, $port, $errno, $errstr, $timeout, $family === AF_INET6 ? STREAM_CLIENT_IPPROTO_V6 : 0); - $elapsed = (microtime(true) - $start) * 1000; - if ($fp) { - fclose($fp); - return ['reachable' => true, 'latency_ms' => round($elapsed, 1)]; - } - return ['reachable' => false, 'error' => $errstr ?: "errno $errno"]; -} - -/** - * Sanitize Log-Output (entferne Control-Chars, begrenze Länge). - */ -function sanitize_log_output(string $text, int $max_chars = 50000): string { - // Entferne ANSI-Escape-Sequenzen - $text = preg_replace('/\x1b\[[0-9;]*[a-zA-Z]/', '', $text); - // Entferne andere Control-Chars (außer \n, \r, \t) - $text = preg_replace('/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/', '', $text); - // Begrenze Länge - if (strlen($text) > $max_chars) { - $text = '... [truncated] ...' . substr($text, -$max_chars); - } - return $text; -} - -/** - * Kompakte Container-Inspect-Ausgabe. - */ -function compact_container_inspect(string $raw, string $detail = 'summary'): string { - $data = json_decode($raw, true); - if (json_last_error() !== JSON_ERROR_NONE || !is_array($data)) { - return $raw; - } - // Docker inspect gibt ein Array mit einem Element zurück - if (isset($data[0])) { - $data = $data[0]; - } - $compact = [ - 'Id' => substr($data['Id'] ?? '', 0, 12), - 'Name' => $data['Name'] ?? '', - 'State' => [ - 'Status' => $data['State']['Status'] ?? '', - 'Running' => $data['State']['Running'] ?? false, - 'Pid' => $data['State']['Pid'] ?? 0, - 'ExitCode' => $data['State']['ExitCode'] ?? 0, - ], - 'Image' => $data['Config']['Image'] ?? '', - 'NetworkMode' => $data['HostConfig']['NetworkMode'] ?? '', - 'Ports' => $data['NetworkSettings']['Ports'] ?? [], - 'RestartCount' => $data['RestartCount'] ?? 0, - 'Created' => $data['Created'] ?? '', - ]; - if ($detail === 'full') { - $compact['Env'] = array_map(function ($entry) { - if (!is_string($entry) || !str_contains($entry, '=')) return $entry; - [$name, $value] = explode('=', $entry, 2); - if (preg_match('/(KEY|TOKEN|SECRET|PASS|AUTH|COOKIE|ARL)/i', $name)) { - return $name . '='; - } - return $name . '=' . $value; - }, $data['Config']['Env'] ?? []); - $compact['Mounts'] = array_map(function ($m) { - return [ - 'Type' => $m['Type'] ?? '', - 'Source' => $m['Source'] ?? '', - 'Destination' => $m['Destination'] ?? '', - ]; - }, $data['Mounts'] ?? []); - } - return json_encode($compact, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); -} - -/** - * Container-Runtime-Zusammenfassung (docker ps + docker stats). - */ -function container_runtime_summary(array $args = []): string { - $state_filter = $args['state'] ?? 'all'; - $include_stats = ($args['include_stats'] ?? false) === true; - $detail = $args['detail'] ?? 'compact'; - $allowed_states = ['all', 'running', 'stopped', 'created', 'exited']; - if (!in_array($state_filter, $allowed_states, true)) { - throw new InvalidArgumentException('state must be one of: ' . implode(', ', $allowed_states)); - } - if (!in_array($detail, ['compact', 'full'], true)) { - throw new InvalidArgumentException('detail must be compact or full'); - } - $ps = docker_exec("ps -a --format '{{json .}}'"); - $containers = json_lines($ps); - - // docker stats für laufende Container - $running_ids = array_filter(array_map(function ($c) { - return (($c['State'] ?? '') === 'running') ? ($c['ID'] ?? '') : ''; - }, $containers)); - - $stats = []; - if ($include_stats && !empty($running_ids)) { - $stats_raw = docker_exec("stats --no-stream --format '{{json .}}'"); - foreach (json_lines($stats_raw) as $s) { - $stats[$s['ID'] ?? ''] = $s; - } - } - - $state_counts = []; - foreach ($containers as $c) { - $state = (string)($c['State'] ?? 'unknown'); - $state_counts[$state] = ($state_counts[$state] ?? 0) + 1; - } - - $result = []; - foreach ($containers as $c) { - $state = (string)($c['State'] ?? ''); - $matches = $state_filter === 'all' - || ($state_filter === 'stopped' && $state !== 'running') - || $state === $state_filter; - if (!$matches) continue; - - $id = $c['ID'] ?? ''; - $entry = [ - 'name' => $c['Names'] ?? '', - 'status' => $c['Status'] ?? '', - 'state' => $c['State'] ?? '', - ]; - if ($detail === 'full') { - $entry['id'] = substr($id, 0, 12); - $entry['image'] = $c['Image'] ?? ''; - $entry['ports'] = $c['Ports'] ?? ''; - } - if ($include_stats && isset($stats[$id])) { - $entry['cpu_percent'] = $stats[$id]['CPUPerc'] ?? ''; - $entry['mem_usage'] = $stats[$id]['MemUsage'] ?? ''; - $entry['mem_percent'] = $stats[$id]['MemPerc'] ?? ''; - $entry['net_io'] = $stats[$id]['NetIO'] ?? ''; - $entry['block_io'] = $stats[$id]['BlockIO'] ?? ''; - } - $result[] = $entry; - } - - return json_encode([ - 'schema_version' => '1.1', - 'container_count' => count($result), - 'returned_count' => count($result), - 'total_count' => count($containers), - 'running_count' => $state_counts['running'] ?? 0, - 'stopped_count' => count($containers) - ($state_counts['running'] ?? 0), - 'state_counts' => $state_counts, - 'filter' => ['state' => $state_filter, 'include_stats' => $include_stats, 'detail' => $detail], - 'containers' => $result, - ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); -} - -/** - * Kompakte Netzwerk-Inventur. - */ -function compact_network_inventory(array $args): string { - $networks_raw = docker_exec("network ls --no-trunc --format '{{json .}}'"); - $networks = json_lines($networks_raw); - - $result = []; - foreach ($networks as $n) { - $entry = [ - 'name' => $n['Name'] ?? '', - 'id' => substr($n['ID'] ?? '', 0, 12), - 'driver' => $n['Driver'] ?? '', - 'scope' => $n['Scope'] ?? '', - ]; - // Container-Count via inspect - $inspect = docker_exec("network inspect --format '{{len .Containers}}' {$n['Name']}"); - $entry['container_count'] = (int)trim($inspect); - $result[] = $entry; - } - - return json_encode([ - 'schema_version' => '1.0', - 'network_count' => count($result), - 'networks' => $result, - ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); -} - -/** - * Container-Logs analysieren (server-seitig). - */ -function analyze_container_logs(?string $severity, ?string $container, string $since, int $scan_tail, int $max_results): string { - $severity_levels = [ - 'error' => ['error', 'fatal', 'panic', 'exception', 'traceback', 'critical'], - 'warn' => ['warn', 'warning', 'deprecated'], - 'info' => ['info', 'started', 'listening', 'ready'], - ]; - - $patterns = $severity_levels[$severity] ?? $severity_levels['error']; - $regex = '/(' . implode('|', array_map('preg_quote', $patterns)) . ')/i'; - - // Hole Logs - $log_cmd = "logs --timestamps --since $since --tail $scan_tail"; - if ($container) { - $log_cmd .= " $container"; - } - $raw = docker_exec($log_cmd); - $lines = explode("\n", $raw); - - $matches = []; - $counts = []; - foreach ($lines as $line) { - if (preg_match($regex, $line, $m)) { - $key = strtolower($m[1]); - $counts[$key] = ($counts[$key] ?? 0) + 1; - if (count($matches) < $max_results) { - $matches[] = [ - 'pattern' => $m[1], - 'line' => mb_substr(trim($line), 0, 300), - ]; - } - } - } - - return json_encode([ - 'schema_version' => '1.0', - 'severity' => $severity, - 'container' => $container, - 'since' => $since, - 'scan_tail' => $scan_tail, - 'total_matches' => array_sum($counts), - 'pattern_counts' => $counts, - 'sample_matches' => $matches, - ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); -} - -/** - * Dualstack-LAN-Probe. - */ -function probe_dualstack(string $host, int $port, float $timeout): string { - $ipv4 = tcp_probe($host, $port, AF_INET, $timeout); - $ipv6 = tcp_probe($host, $port, AF_INET6, $timeout); - return json_encode([ - 'host' => $host, - 'port' => $port, - 'ipv4' => $ipv4, - 'ipv6' => $ipv6, - ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); -} - -/** - * Alle TCP-Endpunkte auditieren (komplexes Tool). - */ -function audit_all_tcp_endpoints(float $timeout, bool $include_all_endpoints = false): string { - // Container-Inventur - $inventory_cmd = "ids=\$(docker ps -aq); [ -z \"\$ids\" ] || docker inspect --type container --format '{\"ID\":{{json .Id}},\"Name\":{{json .Name}},\"Image\":{{json .Config.Image}},\"Status\":{{json .State.Status}},\"Running\":{{json .State.Running}},\"Health\":{{json (index .State \"Health\")}},\"NetworkMode\":{{json .HostConfig.NetworkMode}},\"ExposedPorts\":{{json (index .Config \"ExposedPorts\")}},\"Ports\":{{json .NetworkSettings.Ports}}}' \$ids"; - $containers = json_lines(run_local('audit', $inventory_cmd)); - - // Host-Netzwerk - $host_cmd = "printf '%s\\n' '--- IPv4/IPv6 addresses ---'; ip -j address show; printf '%s\\n' '--- Listening sockets ---'; ss -H -lntup"; - $host_raw = run_local('audit', $host_cmd); - $addrs = host_addresses($host_raw); - - $by_id = []; - foreach ($containers as $item) { - $by_id[$item['ID'] ?? ''] = $item; - } - - $endpoints = []; - $inactive = []; - $no_tcp = []; - $udp = []; - $endpoint_keys = []; - - foreach ($containers as $item) { - $name = ltrim($item['Name'] ?? '', '/'); - if (!($item['Running'] ?? false)) { - $inactive[] = ['container' => $name, 'status' => $item['Status'] ?? '']; - continue; - } - $mode = $item['NetworkMode'] ?? 'unknown'; - $found_tcp = false; - foreach (($item['Ports'] ?? []) as $container_port => $bindings) { - $protocol = substr($container_port, strrpos($container_port, '/') + 1); - if ($protocol === 'udp' && $bindings) { - $udp[] = ['container' => $name, 'container_port' => $container_port]; - continue; - } - if ($protocol !== 'tcp' || !$bindings) continue; - foreach ($bindings as $binding) { - if (!empty($binding['HostPort'])) { - $key = "$name:{$binding['HostPort']}:$container_port"; - if (!isset($endpoint_keys[$key])) { - $endpoint_keys[$key] = true; - $endpoints[] = [ - 'container' => $name, - 'mode' => $mode, - 'container_port' => $container_port, - 'host_port' => (int)$binding['HostPort'], - ]; - } - $found_tcp = true; - } - } - } - if ($mode !== 'host' && !$found_tcp) { - $no_tcp[] = ['container' => $name, 'mode' => $mode]; - } - } - - // Probes - $classifications = ['dualstack' => 0, 'ipv4-only' => 0, 'ipv6-only' => 0, 'unreachable' => 0]; - foreach ($endpoints as &$ep) { - $v4 = tcp_probe($addrs['ipv4'], $ep['host_port'], AF_INET, $timeout); - $v6 = tcp_probe($addrs['ipv6'], $ep['host_port'], AF_INET6, $timeout); - $ep['ipv4_reachable'] = $v4['reachable']; - $ep['ipv6_reachable'] = $v6['reachable']; - $ep['classification'] = ($v4['reachable'] && $v6['reachable']) ? 'dualstack' - : ($v4['reachable'] ? 'ipv4-only' : ($v6['reachable'] ? 'ipv6-only' : 'unreachable')); - $classifications[$ep['classification']]++; - } - unset($ep); - - $issue_endpoints = array_filter($endpoints, function ($e) { - return $e['classification'] !== 'dualstack'; - }); - - $result = [ - 'schema_version' => '2.0', - 'targets' => ['ipv4' => $addrs['ipv4'], 'lan_ipv6' => $addrs['ipv6']], - 'counts' => [ - 'containers_total' => count($containers), - 'tcp_endpoints_total' => count($endpoints), - 'tcp_dualstack' => $classifications['dualstack'], - 'tcp_ipv4_only' => $classifications['ipv4-only'], - 'tcp_ipv6_only' => $classifications['ipv6-only'], - 'tcp_unreachable' => $classifications['unreachable'], - 'tcp_problem_endpoints' => count($issue_endpoints), - ], - 'problem_endpoints_only' => array_values($issue_endpoints), - 'inactive_containers' => $inactive, - 'running_without_published_tcp' => $no_tcp, - 'task_complete' => true, - ]; - if ($include_all_endpoints) { - $result['all_tcp_endpoints'] = $endpoints; - } - return json_encode($result, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); -} diff --git a/mcp/selftest.php b/mcp/selftest.php deleted file mode 100644 index 91e261a..0000000 --- a/mcp/selftest.php +++ /dev/null @@ -1,137 +0,0 @@ - $name, "detail" => $detail]; - echo " ✓ $name" . ($detail ? " ($detail)" : '') . "\n"; - } else { - $failed++; - $results[] = ["FAIL" => $name, "detail" => $detail]; - echo " ✗ $name" . ($detail ? " ($detail)" : '') . "\n"; - } -} - -echo "=== MUA Selftest ===\n\n"; - -// ── 1. Tools-Definition ────────────────────────────────────────────────── -echo "[1] Tools-Definition\n"; -$tools = mua_tools(); -check('21 Tools definiert', count($tools) === 21, count($tools) . ' Tools'); - -$names = array_column($tools, 'name'); -$expected = [ - 'unraid_docker_list', 'unraid_docker_inspect', 'unraid_docker_logs', - 'unraid_docker_analyze_logs', 'unraid_docker_processes', 'unraid_docker_stats', - 'unraid_docker_info', 'unraid_docker_start', 'unraid_docker_stop', - 'unraid_docker_restart', 'unraid_docker_create', 'unraid_docker_modify', - 'unraid_docker_update', 'unraid_docker_rebuild', - 'unraid_network_inventory', 'unraid_network_list', 'unraid_network_inspect', - 'unraid_network_host_state', 'unraid_network_audit_tcp', 'unraid_network_lan_probe', - 'unraid_system_connection_test', -]; -$missing = array_diff($expected, $names); -check('Alle erwarteten Tools vorhanden', empty($missing), empty($missing) ? '' : 'Fehlt: ' . implode(', ', $missing)); - -// ── 2. Docker-Verbindung ───────────────────────────────────────────────── -echo "\n[2] Docker-Verbindung\n"; -try { - $info = docker_exec("info --format '{{.ServerVersion}}'"); - check('Docker erreichbar', $info !== '', 'Version: ' . trim($info)); -} catch (Exception $e) { - check('Docker erreichbar', false, $e->getMessage()); -} - -// ── 3. Container-Liste ─────────────────────────────────────────────────── -echo "\n[3] Container-Liste\n"; -try { - $summary = container_runtime_summary(); - $decoded = json_decode($summary, true); - check('container_runtime_summary() funktioniert', is_array($decoded) && isset($decoded['container_count'])); - check('Container-Count > 0', ($decoded['container_count'] ?? 0) > 0, $decoded['container_count'] . ' Container'); -} catch (Exception $e) { - check('container_runtime_summary() funktioniert', false, $e->getMessage()); -} - -// ── 3b. Kompakte Inspect-Ausgabe ───────────────────────────────────────── -$fixture = json_encode([[ - 'Id' => str_repeat('a', 64), - 'Name' => '/test', - 'State' => ['Status' => 'running', 'Running' => true, 'Pid' => 42, 'ExitCode' => 0], - 'Config' => ['Image' => 'example:latest', 'Env' => ['SECRET=value']], - 'HostConfig' => ['NetworkMode' => 'bridge'], - 'NetworkSettings' => ['Ports' => []], - 'Mounts' => [['Type' => 'bind', 'Source' => '/secret', 'Destination' => '/data']], - 'RestartCount' => 0, - 'Created' => 'now', -]]); -$summaryInspect = json_decode(compact_container_inspect($fixture), true); -$fullInspect = json_decode(compact_container_inspect($fixture, 'full'), true); -check('Inspect summary laesst Env aus', !isset($summaryInspect['Env']) && !isset($summaryInspect['Mounts'])); -check('Inspect full enthaelt Env und Mounts', isset($fullInspect['Env']) && isset($fullInspect['Mounts'])); -check('Inspect full maskiert Secrets', ($fullInspect['Env'][0] ?? '') === 'SECRET='); - -// ── 4. Netzwerk-Inventur ───────────────────────────────────────────────── -echo "\n[4] Netzwerk-Inventur\n"; -try { - $inventory = compact_network_inventory([]); - $decoded = json_decode($inventory, true); - check('compact_network_inventory() funktioniert', is_array($decoded) && isset($decoded['network_count'])); - check('Netzwerk-Count > 0', ($decoded['network_count'] ?? 0) > 0, $decoded['network_count'] . ' Netzwerke'); -} catch (Exception $e) { - check('compact_network_inventory() funktioniert', false, $e->getMessage()); -} - -// ── 5. Host-Adressen ───────────────────────────────────────────────────── -echo "\n[5] Host-Adressen\n"; -try { - $raw = run_local('test', "ip -j address show"); - $addrs = host_addresses($raw); - check('IPv4-Adresse gefunden', $addrs['ipv4'] !== '', $addrs['ipv4']); - check('IPv6-Adresse gefunden', $addrs['ipv6'] !== '', $addrs['ipv6']); -} catch (Exception $e) { - check('Host-Adressen', false, $e->getMessage()); -} - -// ── 6. Validate-Name ───────────────────────────────────────────────────── -echo "\n[6] Validate-Name\n"; -try { - validate_name('test-container', 'container'); - check('Gültiger Name akzeptiert', true); -} catch (Exception $e) { - check('Gültiger Name akzeptiert', false, $e->getMessage()); -} -try { - validate_name('bad;name', 'container'); - check('Ungültiger Name abgelehnt', false, 'Sollte Exception werfen'); -} catch (Exception $e) { - check('Ungültiger Name abgelehnt', true); -} - -// ── 7. PHP-Helper vorhanden ────────────────────────────────────────────── -echo "\n[7] PHP-Helper\n"; -$helper = '/usr/local/bin/unraid-docker-mcp-helper.php'; -check('PHP-Helper vorhanden', file_exists($helper), $helper); - -// ── Zusammenfassung ────────────────────────────────────────────────────── -echo "\n=== Zusammenfassung ===\n"; -echo " Bestanden: $passed\n"; -echo " Fehlgeschlagen: $failed\n"; -echo " Gesamt: " . ($passed + $failed) . "\n"; - -exit($failed > 0 ? 1 : 0); diff --git a/mcp/server.php b/mcp/server.php deleted file mode 100644 index 436d192..0000000 --- a/mcp/server.php +++ /dev/null @@ -1,382 +0,0 @@ - ['created' => time, 'initialized' => bool] - -function session_create(): string { - global $sessions; - $id = bin2hex(random_bytes(16)); - $sessions[$id] = ['created' => time(), 'initialized' => false]; - return $id; -} - -function session_get(?string $id): ?array { - global $sessions; - if ($id === null || !isset($sessions[$id])) return null; - // TTL-Check - if (time() - $sessions[$id]['created'] > MUA_SESSION_TTL) { - unset($sessions[$id]); - return null; - } - return $sessions[$id]; -} - -function session_delete(?string $id): void { - global $sessions; - if ($id !== null) unset($sessions[$id]); -} - -// ── HTTP-Response-Helfer ───────────────────────────────────────────────── -function http_response(int $code, string $body, array $headers = []): void { - http_response_code($code); - foreach ($headers as $k => $v) { - header("$k: $v"); - } - echo $body; - exit; -} - -function json_response(int $code, array $data, array $extra_headers = []): void { - $headers = ['Content-Type' => 'application/json']; - $headers = array_merge($headers, $extra_headers); - http_response($code, json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), $headers); -} - -function sse_response(array $data, array $extra_headers = []): void { - $headers = [ - 'Content-Type' => 'text/event-stream', - 'Cache-Control' => 'no-cache', - 'Connection' => 'keep-alive', - ]; - $headers = array_merge($headers, $extra_headers); - http_response(200, "data: " . json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "\n\n", $headers); -} - -// ── JSON-RPC-Response ──────────────────────────────────────────────────── -function rpc_result($id, $result): array { - return ['jsonrpc' => '2.0', 'id' => $id, 'result' => $result]; -} - -function rpc_error($id, int $code, string $message, $data = null): array { - $err = ['code' => $code, 'message' => $message]; - if ($data !== null) $err['data'] = $data; - return ['jsonrpc' => '2.0', 'id' => $id, 'error' => $err]; -} - -// ── Tool-Dispatch ──────────────────────────────────────────────────────── -function call_tool(string $name, array $args): string { - switch ($name) { - // ── Docker ────────────────────────────────────────────────────── - case 'unraid_docker_list': - return container_runtime_summary($args); - - case 'unraid_docker_inspect': - $container = validate_name($args['container'] ?? null, 'container'); - $detail = $args['detail'] ?? 'summary'; - if (!in_array($detail, ['summary', 'full'], true)) { - throw new InvalidArgumentException('detail must be summary or full'); - } - $raw = docker_exec("inspect --type container -- $container"); - return compact_container_inspect($raw, $detail); - - case 'unraid_docker_logs': - $container = validate_name($args['container'] ?? null, 'container'); - $tail = (int)($args['tail'] ?? 200); - if ($tail < 1 || $tail > 2000) throw new InvalidArgumentException('tail must be between 1 and 2000'); - $raw = docker_exec("logs --timestamps --tail $tail $container"); - return sanitize_log_output($raw); - - case 'unraid_docker_analyze_logs': - $severity = $args['severity'] ?? 'error'; - $container = $args['container'] ?? null; - if ($container !== null && !is_string($container)) throw new InvalidArgumentException('container must be a string'); - $since = $args['since'] ?? '24h'; - $scan_tail = (int)($args['scan_tail'] ?? 1000); - $max_results = (int)($args['max_results'] ?? 50); - return analyze_container_logs($severity, $container, $since, $scan_tail, $max_results); - - case 'unraid_docker_processes': - $container = validate_name($args['container'] ?? null, 'container'); - return docker_exec("top $container -eo pid,ppid,user,stat,lstart,etime,args"); - - case 'unraid_docker_stats': - return docker_exec("stats --no-stream --format '{{json .}}'"); - - case 'unraid_docker_info': - return docker_exec("info --format '{{json .}}'"); - - case 'unraid_docker_start': - $container = validate_name($args['container'] ?? null, 'container'); - return docker_exec("start $container"); - - case 'unraid_docker_stop': - $container = validate_name($args['container'] ?? null, 'container'); - return docker_exec("stop $container"); - - case 'unraid_docker_restart': - $container = validate_name($args['container'] ?? null, 'container'); - return docker_exec("restart $container"); - - case 'unraid_docker_create': - $template = validate_name($args['template_name'] ?? null, 'template_name'); - return run_php_helper('create', $template); - - case 'unraid_docker_modify': - $container = validate_name($args['container'] ?? null, 'container'); - $field = $args['field'] ?? ''; - $value = $args['value'] ?? ''; - if (!in_array($field, ['port', 'env', 'volume', 'network', 'privileged'])) { - throw new InvalidArgumentException('field must be one of: port, env, volume, network, privileged'); - } - return run_php_helper('modify', $container, $field, $value); - - case 'unraid_docker_update': - $container = validate_name($args['container'] ?? null, 'container'); - return run_php_helper('update', $container); - - case 'unraid_docker_rebuild': - $container = validate_name($args['container'] ?? null, 'container'); - return run_php_helper('rebuild', $container); - - // ── Netzwerk ──────────────────────────────────────────────────── - case 'unraid_network_inventory': - return compact_network_inventory($args); - - case 'unraid_network_list': - return docker_exec("network ls --no-trunc --format '{{json .}}'"); - - case 'unraid_network_inspect': - $network = validate_name($args['network'] ?? null, 'network'); - return docker_exec("network inspect -- $network"); - - case 'unraid_network_host_state': - return run_local('host_state', "printf '%s\\n' '--- IPv4/IPv6 addresses ---'; ip -j address show; printf '%s\\n' '--- IPv4 routes ---'; ip -j -4 route show; printf '%s\\n' '--- IPv6 routes ---'; ip -j -6 route show; printf '%s\\n' '--- Listening sockets ---'; ss -H -lntup"); - - case 'unraid_network_audit_tcp': - $timeout = (float)($args['timeout_seconds'] ?? 2); - if ($timeout < 0.2 || $timeout > 10) throw new InvalidArgumentException('timeout_seconds must be between 0.2 and 10'); - $include_all = (bool)($args['include_all_endpoints'] ?? false); - return audit_all_tcp_endpoints($timeout, $include_all); - - case 'unraid_network_lan_probe': - $host = validate_name($args['host'] ?? null, 'host'); - $port = (int)($args['port'] ?? 0); - $timeout = (float)($args['timeout_seconds'] ?? 3); - if ($port < 1 || $port > 65535 || $timeout < 0.2 || $timeout > 10) { - throw new InvalidArgumentException('Invalid port or timeout'); - } - return probe_dualstack($host, $port, $timeout); - - // ── System ────────────────────────────────────────────────────── - case 'unraid_system_connection_test': - return run_local('connection_test', "id; printf 'hostname='; hostname; printf 'kernel='; uname -sr; printf 'unraid='; cat /etc/unraid-version"); - - default: - throw new InvalidArgumentException("Unknown tool: $name"); - } -} - -/** - * PHP-Helper für Write-Operationen aufrufen. - * Der Helper liegt in /usr/local/bin/unraid-docker-mcp-helper.php - * (wird vom Plugin installiert). - */ -function run_php_helper(string $action, ...$args): string { - $helper = '/usr/local/bin/unraid-docker-mcp-helper.php'; - if (!file_exists($helper)) { - throw new RuntimeException("PHP helper not found: $helper"); - } - $cmd = escapeshellarg('/usr/bin/php') . ' ' . escapeshellarg($helper) . ' ' . escapeshellarg($action); - foreach ($args as $arg) { - $cmd .= ' ' . escapeshellarg($arg); - } - return run_local("php_helper:$action", $cmd, 300); -} - -// ── MCP-Methoden-Handler ───────────────────────────────────────────────── -function handle_mcp_request(array $message, ?string $session_id): array { - global $_SERVER; - $method = $message['method'] ?? ''; - $id = $message['id'] ?? null; - $params = $message['params'] ?? []; - - // ── initialize ────────────────────────────────────────────────────── - if ($method === 'initialize') { - $protocol_version = $params['protocolVersion'] ?? '2024-11-05'; - // Session erstellen (oder bestehende übernehmen) - if ($session_id === null) { - $session_id = session_create(); - } else { - // Bestehende Session als initialisiert markieren - global $sessions; - if (isset($sessions[$session_id])) { - $sessions[$session_id]['initialized'] = true; - } else { - $session_id = session_create(); - } - } - // Session-ID muss im Response-Header zurückgegeben werden - $_SERVER['MUA_SESSION_ID'] = $session_id; - return rpc_result($id, [ - 'protocolVersion' => $protocol_version, - 'capabilities' => ['tools' => ['listChanged' => false]], - 'serverInfo' => ['name' => MUA_SERVER_NAME, 'version' => MUA_VERSION], - ]); - } - - // ── notifications/initialized (kein Response nötig) ───────────────── - if ($method === 'notifications/initialized') { - return null; // Notification, kein Response - } - - // ── Session-Check für alle anderen Methoden ───────────────────────── - if ($session_id === null) { - return rpc_error($id, -32000, 'Missing Mcp-Session-Id header'); - } - $session = session_get($session_id); - if ($session === null) { - return rpc_error($id, -32000, 'Invalid or expired session'); - } - if (!$session['initialized'] && $method !== 'initialize') { - return rpc_error($id, -32000, 'Not initialized: send initialize first'); - } - - // ── tools/list ────────────────────────────────────────────────────── - if ($method === 'tools/list') { - return rpc_result($id, ['tools' => mua_tools()]); - } - - // ── tools/call ────────────────────────────────────────────────────── - if ($method === 'tools/call') { - $tool_name = $params['name'] ?? ''; - $tool_args = $params['arguments'] ?? []; - try { - $text = call_tool($tool_name, $tool_args); - $result = [ - 'content' => [['type' => 'text', 'text' => $text]], - 'isError' => false, - ]; - // structuredContent für JSON-Tools - if (in_array($tool_name, [ - 'unraid_docker_list', 'unraid_network_inventory', - 'unraid_docker_analyze_logs', 'unraid_network_audit_tcp', - ])) { - $decoded = json_decode($text, true); - if (json_last_error() === JSON_ERROR_NONE) { - $result['structuredContent'] = $decoded; - } - } - return rpc_result($id, $result); - } catch (Exception $e) { - return rpc_result($id, [ - 'content' => [['type' => 'text', 'text' => 'ERROR: ' . $e->getMessage()]], - 'isError' => true, - ]); - } - } - - // ── ping ──────────────────────────────────────────────────────────── - if ($method === 'ping') { - return rpc_result($id, new stdClass()); - } - - // ── Unknown method ────────────────────────────────────────────────── - if ($id !== null) { - return rpc_error($id, -32601, "Method not found: $method"); - } - return null; -} - -// ── HTTP-Router ────────────────────────────────────────────────────────── -$method = $_SERVER['REQUEST_METHOD'] ?? 'GET'; -$path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/'; -$session_header = $_SERVER['HTTP_MCP_SESSION_ID'] ?? null; - -// CORS für lokale Nutzung -header('Access-Control-Allow-Origin: *'); -header('Access-Control-Allow-Methods: GET, POST, DELETE, OPTIONS'); -header('Access-Control-Allow-Headers: Content-Type, Mcp-Session-Id'); - -if ($method === 'OPTIONS') { - http_response(204, ''); -} - -// ── Health-Check ───────────────────────────────────────────────────────── -if ($path === '/health') { - json_response(200, [ - 'status' => 'ok', - 'server' => MUA_SERVER_NAME, - 'version' => MUA_VERSION, - 'port' => MUA_PORT, - 'time' => date('c'), - ]); -} - -// ── MCP-Endpunkt ───────────────────────────────────────────────────────── -if ($path === '/mcp' || $path === '/') { - - // ── POST: JSON-RPC Request ────────────────────────────────────────── - if ($method === 'POST') { - $body = file_get_contents('php://input'); - $message = json_decode($body, true); - if (!is_array($message)) { - json_response(400, rpc_error(null, -32700, 'Parse error')); - } - - $response = handle_mcp_request($message, $session_header); - - // Notification (kein Response nötig) - if ($response === null) { - http_response(202, '', [ - 'Mcp-Session-Id' => $_SERVER['MUA_SESSION_ID'] ?? ($session_header ?? ''), - ]); - } - - $headers = []; - if (!empty($_SERVER['MUA_SESSION_ID'])) { - $headers['Mcp-Session-Id'] = $_SERVER['MUA_SESSION_ID']; - } - json_response(200, $response, $headers); - } - - // ── GET: SSE-Stream (nicht implementiert) ─────────────────────────── - // Laut MCP-Streamable-HTTP-Spec ist die SSE-GET-Endpunkt optional. - // Wir nutzen POST-only (request/response). 405 = spec-konform. - if ($method === 'GET') { - http_response(405, json_encode(['error' => 'SSE not supported. Use POST /mcp for JSON-RPC requests.']), [ - 'Content-Type' => 'application/json', - ]); - } - - // ── DELETE: Session-End ───────────────────────────────────────────── - if ($method === 'DELETE') { - session_delete($session_header); - http_response(200, ''); - } -} - -// ── 404 ────────────────────────────────────────────────────────────────── -json_response(404, ['error' => 'Not found. Use /mcp or /health']); diff --git a/mcp/tools.php b/mcp/tools.php deleted file mode 100644 index 9e6d037..0000000 --- a/mcp/tools.php +++ /dev/null @@ -1,228 +0,0 @@ -_ - * Kategorien: docker (14), network (6), system (1) - * - * Identisch zu /opt/mike-ai/unraid-agent/unraid_mcp.py (Python). - */ - -function mua_tools(): array { - return [ - // ── Docker (14) ────────────────────────────────────────────────── - [ - 'name' => 'unraid_docker_list', - 'description' => "List Docker containers with authoritative server-side counts. For active containers always use state='running'. Stats are optional to keep output compact.", - 'inputSchema' => [ - 'type' => 'object', - 'properties' => [ - 'state' => ['type' => 'string', 'enum' => ['all', 'running', 'stopped', 'created', 'exited'], 'description' => "Use 'running' for active containers. Default: all."], - 'include_stats' => ['type' => 'boolean', 'description' => 'Include live CPU, RAM and I/O statistics. Default: false.'], - 'detail' => ['type' => 'string', 'enum' => ['compact', 'full'], 'description' => 'compact returns name/status/state; full also returns ID/image/ports.'], - ], - 'additionalProperties' => false, - ], - ], - [ - 'name' => 'unraid_docker_inspect', - 'description' => "Inspect one known Docker container directly. Default summary returns state, image, network mode and ports only; request detail='full' only when environment variables or mounts are required.", - 'inputSchema' => [ - 'type' => 'object', - 'properties' => [ - 'container' => ['type' => 'string', 'description' => 'Container name or ID'], - 'detail' => ['type' => 'string', 'enum' => ['summary', 'full'], 'description' => "Use 'summary' by default. 'full' additionally returns redacted environment and mounts."], - ], - 'required' => ['container'], - 'additionalProperties' => false, - ], - ], - [ - 'name' => 'unraid_docker_logs', - 'description' => 'Get recent logs from a Docker container (with timestamps).', - 'inputSchema' => [ - 'type' => 'object', - 'properties' => [ - 'container' => ['type' => 'string', 'description' => 'Container name or ID'], - 'tail' => ['type' => 'integer', 'description' => 'Number of lines (1-2000, default 200)'], - ], - 'required' => ['container'], - ], - ], - [ - 'name' => 'unraid_docker_analyze_logs', - 'description' => 'Analyze container logs server-side for errors/warnings. Returns pattern counts and sample matches.', - 'inputSchema' => [ - 'type' => 'object', - 'properties' => [ - 'severity' => ['type' => 'string', 'enum' => ['error', 'warn', 'info'], 'description' => 'Log severity to scan for'], - 'container' => ['type' => 'string', 'description' => 'Container name (optional, scans all if omitted)'], - 'since' => ['type' => 'string', 'description' => 'Time filter (default 24h)'], - 'scan_tail' => ['type' => 'integer', 'description' => 'Max lines to scan (default 1000)'], - 'max_results' => ['type' => 'integer', 'description' => 'Max sample matches (default 50)'], - ], - 'required' => ['severity'], - ], - ], - [ - 'name' => 'unraid_docker_processes', - 'description' => 'List processes running inside a Docker container (docker top).', - 'inputSchema' => [ - 'type' => 'object', - 'properties' => [ - 'container' => ['type' => 'string', 'description' => 'Container name or ID'], - ], - 'required' => ['container'], - ], - ], - [ - 'name' => 'unraid_docker_stats', - 'description' => 'Get live CPU/memory/network/block I/O stats for all running containers.', - 'inputSchema' => ['type' => 'object', 'properties' => new stdClass(), 'additionalProperties' => false], - ], - [ - 'name' => 'unraid_docker_info', - 'description' => 'Get Docker daemon information (version, storage driver, container counts, etc.).', - 'inputSchema' => ['type' => 'object', 'properties' => new stdClass(), 'additionalProperties' => false], - ], - [ - 'name' => 'unraid_docker_start', - 'description' => 'Start a Docker container.', - 'inputSchema' => [ - 'type' => 'object', - 'properties' => [ - 'container' => ['type' => 'string', 'description' => 'Container name or ID'], - ], - 'required' => ['container'], - ], - ], - [ - 'name' => 'unraid_docker_stop', - 'description' => 'Stop a Docker container.', - 'inputSchema' => [ - 'type' => 'object', - 'properties' => [ - 'container' => ['type' => 'string', 'description' => 'Container name or ID'], - ], - 'required' => ['container'], - ], - ], - [ - 'name' => 'unraid_docker_restart', - 'description' => 'Restart a Docker container.', - 'inputSchema' => [ - 'type' => 'object', - 'properties' => [ - 'container' => ['type' => 'string', 'description' => 'Container name or ID'], - ], - 'required' => ['container'], - ], - ], - [ - 'name' => 'unraid_docker_create', - 'description' => 'Create a Docker container from a template (pulls image, creates container).', - 'inputSchema' => [ - 'type' => 'object', - 'properties' => [ - 'template_name' => ['type' => 'string', 'description' => 'Template name (e.g. "linuxserver/sonarr")'], - ], - 'required' => ['template_name'], - ], - ], - [ - 'name' => 'unraid_docker_modify', - 'description' => 'Modify a container template (port, env, volume, network, privileged) and rebuild.', - 'inputSchema' => [ - 'type' => 'object', - 'properties' => [ - 'container' => ['type' => 'string', 'description' => 'Container/template name'], - 'field' => ['type' => 'string', 'enum' => ['port', 'env', 'volume', 'network', 'privileged']], - 'value' => ['type' => 'string', 'description' => 'New value (format depends on field)'], - ], - 'required' => ['container', 'field', 'value'], - ], - ], - [ - 'name' => 'unraid_docker_update', - 'description' => 'Update a container (pull latest image, rebuild).', - 'inputSchema' => [ - 'type' => 'object', - 'properties' => [ - 'container' => ['type' => 'string', 'description' => 'Container/template name'], - ], - 'required' => ['container'], - ], - ], - [ - 'name' => 'unraid_docker_rebuild', - 'description' => 'Rebuild a container from its template (without pulling new image).', - 'inputSchema' => [ - 'type' => 'object', - 'properties' => [ - 'container' => ['type' => 'string', 'description' => 'Container/template name'], - ], - 'required' => ['container'], - ], - ], - - // ── Netzwerk (6) ───────────────────────────────────────────────── - [ - 'name' => 'unraid_network_inventory', - 'description' => 'Compact Docker network inventory (all networks with container counts).', - 'inputSchema' => ['type' => 'object', 'properties' => new stdClass(), 'additionalProperties' => false], - ], - [ - 'name' => 'unraid_network_list', - 'description' => 'List all Docker networks.', - 'inputSchema' => ['type' => 'object', 'properties' => new stdClass(), 'additionalProperties' => false], - ], - [ - 'name' => 'unraid_network_inspect', - 'description' => 'Inspect a Docker network in detail.', - 'inputSchema' => [ - 'type' => 'object', - 'properties' => [ - 'network' => ['type' => 'string', 'description' => 'Network name or ID'], - ], - 'required' => ['network'], - ], - ], - [ - 'name' => 'unraid_network_host_state', - 'description' => 'Get host network state (IPv4/IPv6 addresses, routes, listening sockets).', - 'inputSchema' => ['type' => 'object', 'properties' => new stdClass(), 'additionalProperties' => false], - ], - [ - 'name' => 'unraid_network_audit_tcp', - 'description' => 'Audit all TCP endpoints: probe IPv4/IPv6 reachability for every published port. Returns classification (dualstack/ipv4-only/ipv6-only/unreachable).', - 'inputSchema' => [ - 'type' => 'object', - 'properties' => [ - 'timeout_seconds' => ['type' => 'number', 'description' => 'Probe timeout (0.2-10, default 2)'], - 'include_all_endpoints' => ['type' => 'boolean', 'description' => 'Include all endpoints (default false, only problems)'], - ], - ], - ], - [ - 'name' => 'unraid_network_lan_probe', - 'description' => 'Probe a specific host:port for IPv4 and IPv6 reachability (dualstack test).', - 'inputSchema' => [ - 'type' => 'object', - 'properties' => [ - 'host' => ['type' => 'string', 'description' => 'Hostname or IP'], - 'port' => ['type' => 'integer', 'description' => 'Port (1-65535)'], - 'timeout_seconds' => ['type' => 'number', 'description' => 'Timeout (0.2-10, default 3)'], - ], - 'required' => ['host', 'port'], - ], - ], - - // ── System (1) ─────────────────────────────────────────────────── - [ - 'name' => 'unraid_system_connection_test', - 'description' => 'Test connection to the Unraid host (hostname, kernel, Unraid version).', - 'inputSchema' => ['type' => 'object', 'properties' => new stdClass(), 'additionalProperties' => false], - ], - ]; -} diff --git a/package.json b/package.json index 78d39ac..db64a29 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "mua", - "version": "2026.11.05.r035", + "version": "2026.11.20.r036", "description": "Mikes Unraid Agent - MCP over HTTP(S) (Streamable HTTP) for Unraid", "type": "module", "main": "src/index.ts", @@ -11,6 +11,6 @@ "selftest": "bun test" }, "devDependencies": { - "@types/bun": "latest" + "@types/bun": "1.3.14" } } diff --git a/plugin/mua.plg b/plugin/mua.plg index 2bbcd5d..f409579 100644 --- a/plugin/mua.plg +++ b/plugin/mua.plg @@ -2,13 +2,13 @@ - + - - + + ]> +### 2026.11.20.r036 +- Readonly-Shell versteht jetzt eine normale Befehlszeile (`command`): Quotes, Pipes zwischen erlaubten Programmen, `;`/`&&`/`||`, Globs in absoluten Pfaden; `2>&1` wird toleriert. Kleine Modelle kommen so in einem Aufruf zum Ergebnis. +- Schließt Umgehungen der Readonly-Shell: `ip`-Abkürzungen (`ip a a`, `ip r d`, `ip link s`), `dmesg -c`/`-Tc`/`--console-level=`, `ss -tK`/`-D`, `date`-Operanden, `sort -o`, `uniq` mit Ausgabedatei, `file -C`. Optionen werden je Programm inkl. kombinierter Kurzflags und GNU-Abkürzungen geprüft. +- Dateien mit Zugangsdaten (`/etc/shadow`, SSH-Private-Keys, `mua.conf`, Admin-Token, `/proc/*/environ`, Docker-`config.v2.json`) sind in der Readonly-Shell gesperrt; Passwort-Hashes, private PEM-Schlüssel und WireGuard-Keys werden in Ausgaben geschwärzt. MUA-API-Key und Admin-Token erscheinen in keiner Tool-Ausgabe. +- Mehr Diagnoseprogramme: echo, printf, sort, uniq, cut, tr, tac, nl, strings, md5sum, which, basename, dirname, nproc, lscpu, lsusb, sensors, findmnt, zpool/zfs (nur Lesebefehle), `mdcmd status`. `grep` ohne Treffer gilt nicht mehr als Fehler. +- Timeouts beenden die ganze Prozessgruppe statt nur der Shell; der harte MCP-Timeout beendet gezielt die Prozesse des betroffenen Aufrufs. +- Async-Jobs: `exit` im Skript verliert den Exit-Code nicht mehr; neues Werkzeug `unraid_system_job_cancel`; abgeschlossene Jobs werden nach 7 Tagen aus `/tmp/mua-jobs` entfernt. +- Toolbox-Erkennung wird kurz gecacht (weniger `docker ps` pro Aufruf); Session-IDs werden validiert und begrenzt; `/health` zeigt Version/Port nur mit Token; automatisch ergänzte Freigaben werden geloggt und in der WebGUI angezeigt. +- Alter PHP-Server (`mcp/`) entfernt; alte Pakete aus `dist/` entfernt. + ### 2026.11.05.r035 - Neuer expliziter Modus „Unraid-WebGUI-Zertifikat verwenden“: keine manuellen Zertifikatspfade nötig; bisherige Pfade bleiben als Expertenoption erhalten. - Leitet verwendete Bundles aus der erzeugten nginx-Konfiguration und Management-Laufzeitdaten ab, nicht aus beliebigen PEM-Dateien oder Änderungszeiten. @@ -212,7 +222,7 @@ Das .txz enthält: install/doinst.sh (läuft nach Installation) =========================================== --> - + &txzURL; &txzSHA256; diff --git a/plugin/plugin.json b/plugin/plugin.json index 71e22a9..35d59bc 100644 --- a/plugin/plugin.json +++ b/plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "mua", "author": "Michael", - "version": "2026.11.05.r035", + "version": "2026.11.20.r036", "minver": "7.0.0", "pluginDirectory": "/usr/local/emhttp/plugins/mua", "configDirectory": "/boot/config/plugins/mua", diff --git a/scripts/mua.page b/scripts/mua.page index 8d61250..213bb7c 100644 --- a/scripts/mua.page +++ b/scripts/mua.page @@ -141,6 +141,7 @@ $tls_locked = !$config_ok || !empty($transport['envOverride']); $enabled_tools = $config['enabledTools'] ?? []; $all_tools_enabled = (bool)($config['allToolsEnabled'] ?? false); $all_tools = $config['allTools'] ?? []; +$auto_granted = is_array($config['autoGrantedTools'] ?? null) ? $config['autoGrantedTools'] : []; $toolbox = is_array($config['toolbox'] ?? null) ? $config['toolbox'] : []; $toolbox_available = (bool)($toolbox['available'] ?? false); $toolbox_enabled = (bool)($toolbox['enabled'] ?? false); @@ -220,7 +221,9 @@ $active_count = $all_tools_enabled ? count($all_tools) : count($enabled_tools);
">
-

Werkzeuge im Detail

+

Werkzeuge im Detail

+
Automatisch ergänzt (durch bestehende, gleich starke Freigaben gedeckt): . Sie folgen ihrer Hauptfreigabe (z.B. Root-Shell → Async-Jobs) und entfallen mit ihr.
+
$tools): $meta=$risk_labels[$risk]; ?>

diff --git a/scripts/test-release.py b/scripts/test-release.py index 6bc4b9b..ea8c6f5 100644 --- a/scripts/test-release.py +++ b/scripts/test-release.py @@ -41,7 +41,7 @@ class ReleaseTests(unittest.TestCase): self.assertRegex(current, r"^\d{4}\.\d{2}\.\d{2}\.r\d{3}$") self.assertEqual(manifest().attrib["version"], current) self.assertEqual(json.loads((ROOT / "plugin/plugin.json").read_text())["version"], current) - for path in ("src/helpers.ts", "mcp/server.php", "mcp/helpers.php"): + for path in ("src/helpers.ts",): with self.subTest(path=path): declared = re.search(r'MUA_VERSION\s*=\s*[\'\"]([^\'\"]+)', (ROOT / path).read_text()) self.assertIsNotNone(declared) @@ -107,15 +107,17 @@ class ReleaseTests(unittest.TestCase): result = subprocess.run(["bash", "-n"], input=node.text, text=True, capture_output=True) self.assertEqual(result.returncode, 0, result.stderr) - def test_r033_archive_is_not_overwritten(self): - archive = ROOT / "dist/mua-2026.11.01.r033-x86_64-1.txz" - self.assertEqual(hashlib.sha256(archive.read_bytes()).hexdigest(), - "ee85aa33230dbb6fe561f8c0000cb854bd542b0da5ad6c1a9100320fc2d5267f") - - def test_r034_archive_is_not_overwritten(self): - archive = ROOT / "dist/mua-2026.11.05.r034-x86_64-1.txz" - self.assertEqual(hashlib.sha256(archive.read_bytes()).hexdigest(), - "ed6f1f52474711ac87aba9dd53d3f920c9701373bafc7eeff868ef9a839100ed") + def test_dist_holds_only_the_current_release(self): + # Older packages stay available in git history; keeping only the + # current one in the tree keeps checkouts small (each is ~24 MB). + tracked = subprocess.run(["git", "ls-files", "dist"], cwd=ROOT, text=True, + capture_output=True, check=True).stdout.split() + name = f"dist/mua-{version()}-x86_64-1.txz" + self.assertEqual(sorted(tracked), [name, name + ".sha256"]) + payload = next(node for node in manifest().findall("FILE") if node.find("URL") is not None) + digest = hashlib.sha256((ROOT / name).read_bytes()).hexdigest() + self.assertEqual(digest, payload.findtext("SHA256")) + self.assertEqual((ROOT / (name + ".sha256")).read_text().split()[0], digest) @unittest.skipUnless(os.environ.get("MUA_RELEASE_ARCHIVE"), "set MUA_RELEASE_ARCHIVE after building") def test_built_archive_matches_manifest_and_expected_files(self): diff --git a/src/admin.test.ts b/src/admin.test.ts index 0bd173b..2cc1268 100644 --- a/src/admin.test.ts +++ b/src/admin.test.ts @@ -62,7 +62,7 @@ test("actual MCP transport advertises new tools and marks failed commands as err return await r.json() as any; }; const init = await rpc("initialize", { protocolVersion: "2025-03-26", capabilities: {}, clientInfo: { name: "isolated-test", version: "1" } }); - expect(init.result.serverInfo.version).toBe("2026.11.05.r035"); + expect(init.result.serverInfo.version).toBe(JSON.parse(await Bun.file(new URL("../package.json", import.meta.url)).text()).version); const list = await rpc("tools/list", {}); expect(list.result.tools.some((t: { name: string }) => t.name === "unraid_share_apply")).toBe(true); const fail = await rpc("tools/call", { name: "unraid_system_shell", arguments: { command: "exit 17" } }); diff --git a/src/auth.ts b/src/auth.ts index 3a96d90..39a26a0 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -21,7 +21,8 @@ */ import { readFileSync, writeFileSync, mkdirSync, chmodSync } from "node:fs"; -import { randomBytes } from "node:crypto"; +import { randomBytes, timingSafeEqual } from "node:crypto"; +import { forgetSecret, registerSecret } from "./redact"; const CONFIG_DIR = process.env["MUA_CONFIG_DIR"] ?? "/boot/config/plugins/mua"; const CONFIG_FILE = `${CONFIG_DIR}/mua.conf`; @@ -32,6 +33,12 @@ export interface MUAConfig { enabledTools: string[]; allToolsEnabled: boolean; toolboxEnabled: boolean; + /** + * Tools, die beim Laden aus Kompatibilitätsgründen automatisch ergänzt + * wurden (nicht in der Datei, aber durch eine bereits erteilte, gleich + * starke Freigabe gedeckt). Wird geloggt und in der WebGUI angezeigt. + */ + autoGranted?: string[]; } // Sichere Grundeinstellung für Neuinstallationen. Schreibzugriffe, aktive @@ -71,6 +78,12 @@ export function parseConfig(content: string): MUAConfig { allToolsEnabled: false, toolboxEnabled: false, }; + const grant = (name: string) => { + if (!cfg.enabledTools.includes(name)) { + cfg.enabledTools.push(name); + (cfg.autoGranted ??= []).push(name); + } + }; for (const line of content.split("\n")) { const trimmed = line.trim(); if (trimmed.startsWith("#") || trimmed === "") continue; @@ -102,23 +115,15 @@ export function parseConfig(content: string): MUAConfig { // batch variant. If an administrator already enabled the older update // capability, expose the safer equivalent automatically; this does not // grant a new class of operation. - if ( - !cfg.allToolsEnabled - && cfg.enabledTools.includes("unraid_docker_update") - && !cfg.enabledTools.includes("unraid_docker_update_verified_batch") - ) { - cfg.enabledTools.push("unraid_docker_update_verified_batch"); + if (!cfg.allToolsEnabled && cfg.enabledTools.includes("unraid_docker_update")) { + grant("unraid_docker_update_verified_batch"); } // r020 adds a bounded metadata-only filesystem inventory. It is strictly // less powerful than the already-enabled read-only shell and avoids many // repeated ls/find calls, so existing read-only installations may receive // it without granting a new write capability. - if ( - !cfg.allToolsEnabled - && cfg.enabledTools.includes("unraid_system_shell_readonly") - && !cfg.enabledTools.includes("unraid_files_inventory") - ) { - cfg.enabledTools.push("unraid_files_inventory"); + if (!cfg.allToolsEnabled && cfg.enabledTools.includes("unraid_system_shell_readonly")) { + grant("unraid_files_inventory"); } // Async jobs are the bounded long-running equivalent of the already // unrestricted root shell. Existing administrators who explicitly enabled @@ -127,9 +132,10 @@ export function parseConfig(content: string): MUAConfig { for (const name of [ "unraid_system_job_start", "unraid_system_job_status", + "unraid_system_job_cancel", "unraid_system_job_cleanup", ]) { - if (!cfg.enabledTools.includes(name)) cfg.enabledTools.push(name); + grant(name); } } return cfg; @@ -137,6 +143,15 @@ export function parseConfig(content: string): MUAConfig { function loadConfig(): MUAConfig { if (cachedConfig) return cachedConfig; + const cfg = loadConfigUncached(); + registerSecret(cfg.apiKey); + if (cfg.autoGranted?.length) { + console.log(`[MUA] Kompatibilität: automatisch freigegeben (durch bestehende Freigaben gedeckt): ${cfg.autoGranted.join(", ")}`); + } + return cfg; +} + +function loadConfigUncached(): MUAConfig { // 1. Env-Override (für Testing / Docker) const envToken = process.env["MUA_API_KEY"]; @@ -207,7 +222,15 @@ function writeConfigFile(cfg: MUAConfig): void { export function saveConfig(cfg: MUAConfig): void { cachedConfig = cfg; + registerSecret(cfg.apiKey); writeConfigFile(cfg); + // Nach dem Speichern stehen alle Tools explizit in der Datei. + cfg.autoGranted = undefined; +} + +/** Automatisch ergänzte Tools der aktuell geladenen Konfiguration. */ +export function getAutoGrantedTools(): string[] { + return [...(loadConfig().autoGranted ?? [])]; } // ── API-Key ───────────────────────────────────────────────────────────── @@ -217,6 +240,7 @@ export function getApiKey(): string { export function setApiKey(newKey: string): void { const cfg = loadConfig(); + forgetSecret(cfg.apiKey); cfg.apiKey = newKey; saveConfig(cfg); } @@ -288,11 +312,15 @@ export function checkAuth(req: Request): boolean { return false; } - let diff = 0; - for (let i = 0; i < token.length; i++) { - diff |= token.charCodeAt(i) ^ provided.charCodeAt(i); - } - return diff === 0; + return safeEqual(provided, token); +} + +/** Zeitkonstanter Vergleich gleich langer Strings. */ +export function safeEqual(provided: string, expected: string): boolean { + if (expected.length === 0) return false; + const a = Buffer.from(provided); + const b = Buffer.from(expected); + return a.length === b.length && timingSafeEqual(a, b); } export function getMaskedApiKey(): string { diff --git a/src/helpers.ts b/src/helpers.ts index 63433f6..99bf036 100644 --- a/src/helpers.ts +++ b/src/helpers.ts @@ -8,16 +8,18 @@ * PHP-Klassen (DockerClient) benötigen. */ -import { spawn } from "bun"; import { createConnection, type Socket } from "net"; import { hostname } from "node:os"; import { createHash, randomUUID } from "node:crypto"; -import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs"; import { readProcessOutput } from "./process-output"; +import { killProcessGroup, spawnGroup } from "./process-group"; +import { runReadOnly } from "./readonly"; +import { redactKnownSecrets } from "./redact"; // ── Konstanten ────────────────────────────────────────────────────────── export const MUA_SERVER_NAME = "mua"; -export const MUA_VERSION = "2026.11.05.r035"; +export const MUA_VERSION = "2026.11.20.r036"; export const MUA_PROTOCOL_VERSION = "2025-03-26"; export const PHP_HELPER = "/usr/local/bin/unraid-docker-mcp-helper.php"; export const STATUS_HELPER = "/usr/local/bin/unraid-mcp-status-helper.php"; @@ -30,7 +32,7 @@ export interface CmdResult { } async function awaitProcess( - proc: { kill: () => void; exited: Promise }, + proc: { pid: number; kill: () => void; exited: Promise }, stdout: Promise, stderr: Promise, timeoutSec: number, @@ -45,12 +47,10 @@ async function awaitProcess( let timer: ReturnType | undefined; const timeout = new Promise((_, reject) => { timer = setTimeout(() => { - try { - proc.kill(); - } catch { - // The process may already have exited; timeout rejection still frees - // the caller and its concurrency lease. - } + // Kill the whole process group (shell plus every descendant), not only + // the direct child. Otherwise e.g. a `docker pull` keeps running after + // the timeout has already released its concurrency slot. + killProcessGroup(proc.pid); reject(new Error(`${label} timed out after ${timeoutSec} seconds`)); }, timeoutSec * 1000); }); @@ -93,7 +93,7 @@ export async function runLocal( ): Promise { let phase = "spawn"; try { - const proc = spawn(["/bin/sh", "-c", cmd], { + const proc = spawnGroup(["/bin/sh", "-c", cmd], { stdout: "pipe", stderr: "pipe", cwd: "/", @@ -128,7 +128,7 @@ export async function runLocal( export async function runShell(cmd: string, timeoutSec = 60): Promise { let phase = "spawn"; try { - const proc = spawn(["/bin/sh", "-c", cmd], { + const proc = spawnGroup(["/bin/sh", "-c", cmd], { stdout: "pipe", stderr: "pipe", cwd: "/", @@ -157,12 +157,14 @@ export async function runShell(cmd: string, timeoutSec = 60): Promise { } } -const ASYNC_JOB_ROOT = "/tmp/mua-jobs"; +function jobRoot(): string { + return process.env["MUA_JOB_ROOT"] ?? "/tmp/mua-jobs"; +} const JOB_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; function jobPath(jobId: string): string { if (!JOB_ID_PATTERN.test(jobId)) throw new Error("invalid job_id"); - return `${ASYNC_JOB_ROOT}/${jobId}`; + return `${jobRoot()}/${jobId}`; } async function tailJobFile(path: string, maxBytes = 12_000): Promise { @@ -175,69 +177,125 @@ async function tailJobFile(path: string, maxBytes = 12_000): Promise { /** Start arbitrary, explicitly authorized host work without tying up MCP HTTP. */ export async function startShellJob(cmd: string): Promise { if (cmd.trim() === "") throw new Error("command is required"); - mkdirSync(ASYNC_JOB_ROOT, { recursive: true, mode: 0o700 }); + mkdirSync(jobRoot(), { recursive: true, mode: 0o700 }); const jobId = randomUUID(); const dir = jobPath(jobId); mkdirSync(dir, { mode: 0o700 }); - const script = `${dir}/run.sh`; // The unrestricted command is already a critical/admin-only capability. // Keep it out of status output and audit responses because it may contain // credentials supplied by the operator. + // + // The user command lives in its own file and runs in a child shell, so an + // `exit`/`exec` inside it cannot skip writing exit_code (previously the job + // then stayed "unknown" forever). + writeFileSync(`${dir}/command.sh`, cmd.endsWith("\n") ? cmd : `${cmd}\n`, { mode: 0o600 }); + const script = `${dir}/run.sh`; writeFileSync( script, - `#!/bin/sh\n${cmd}\ncode=$?\nprintf '%s\\n' "$code" > '${dir}/exit_code'\nexit "$code"\n`, + `#!/bin/sh\n/bin/sh '${dir}/command.sh'\ncode=$?\nprintf '%s\\n' "$code" > '${dir}/exit_code.tmp' && mv '${dir}/exit_code.tmp' '${dir}/exit_code'\nexit "$code"\n`, { mode: 0o700 }, ); - const proc = spawn(["/bin/sh", script], { + // Own process group: survives the MCP call, can be cancelled as a whole. + const proc = spawnGroup(["/bin/sh", script], { cwd: "/", stdin: "ignore", stdout: Bun.file(`${dir}/stdout.log`), stderr: Bun.file(`${dir}/stderr.log`), - }); + }, { background: true }); proc.unref(); writeFileSync( `${dir}/meta.json`, - JSON.stringify({ job_id: jobId, pid: proc.pid, started_at: new Date().toISOString() }), + JSON.stringify({ job_id: jobId, pid: proc.pid, pgid: proc.pid, started_at: new Date().toISOString() }), { mode: 0o600 }, ); - return JSON.stringify({ job_id: jobId, state: "running", pid: proc.pid }); + return JSON.stringify({ job_id: jobId, state: "running", pid: proc.pid, + next: "Poll with unraid_system_job_status; stop with unraid_system_job_cancel." }); +} + +function readJobMeta(jobId: string): { pid: number; pgid?: number; started_at: string; cancelled_at?: string } { + const dir = jobPath(jobId); + if (!existsSync(`${dir}/meta.json`)) throw new Error("job not found"); + return JSON.parse(readFileSync(`${dir}/meta.json`, "utf-8")); +} + +function jobIsRunning(dir: string, pid: number): boolean { + if (existsSync(`${dir}/exit_code`)) return false; + try { + process.kill(Number(pid), 0); + return true; + } catch { + return false; + } } /** Poll a job with compact tail output; works across independent MCP calls. */ export async function shellJobStatus(jobId: string): Promise { const dir = jobPath(jobId); - if (!existsSync(`${dir}/meta.json`)) throw new Error("job not found"); - const meta = JSON.parse(readFileSync(`${dir}/meta.json`, "utf-8")); - let running = false; - if (!existsSync(`${dir}/exit_code`)) { - try { - process.kill(Number(meta.pid), 0); - running = true; - } catch { - running = false; - } - } + const meta = readJobMeta(jobId); + const running = jobIsRunning(dir, meta.pid); const exitCode = existsSync(`${dir}/exit_code`) ? Number(readFileSync(`${dir}/exit_code`, "utf-8").trim()) : null; + const state = running ? "running" : exitCode !== null ? "finished" : meta.cancelled_at ? "cancelled" : "unknown"; return JSON.stringify({ job_id: jobId, - state: running ? "running" : exitCode === null ? "unknown" : "finished", + state, exit_code: exitCode, started_at: meta.started_at, + ...(meta.cancelled_at ? { cancelled_at: meta.cancelled_at } : {}), stdout_tail: await tailJobFile(`${dir}/stdout.log`), stderr_tail: await tailJobFile(`${dir}/stderr.log`), }); } +/** Stop a running job including all processes it started. */ +export async function cancelShellJob(jobId: string): Promise { + const dir = jobPath(jobId); + const meta = readJobMeta(jobId); + if (!jobIsRunning(dir, meta.pid)) { + return JSON.stringify({ job_id: jobId, cancelled: false, note: "Job is not running; nothing to cancel." }); + } + const pgid = meta.pgid ?? meta.pid; + killProcessGroup(pgid, "SIGTERM"); + for (let i = 0; i < 20 && jobIsRunning(dir, meta.pid); i++) await Bun.sleep(100); + if (jobIsRunning(dir, meta.pid)) killProcessGroup(pgid, "SIGKILL"); + meta.cancelled_at = new Date().toISOString(); + writeFileSync(`${dir}/meta.json`, JSON.stringify(meta), { mode: 0o600 }); + return JSON.stringify({ job_id: jobId, cancelled: true }); +} + /** Remove only one completed MUA job directory. */ export async function cleanupShellJob(jobId: string): Promise { const status = JSON.parse(await shellJobStatus(jobId)); - if (status.state === "running") throw new Error("cannot clean up a running job"); + if (status.state === "running") throw new Error("cannot clean up a running job; cancel it first with unraid_system_job_cancel"); rmSync(jobPath(jobId), { recursive: true, force: false }); return JSON.stringify({ job_id: jobId, cleaned: true, previous_state: status.state }); } +/** + * /tmp liegt auf Unraid im RAM. Abgeschlossene Jobs nach `maxAgeMs` + * (Standard 7 Tage) automatisch entfernen; laufende Jobs bleiben. + */ +export function pruneFinishedJobs(maxAgeMs = 7 * 24 * 60 * 60 * 1000, now = Date.now()): number { + if (!existsSync(jobRoot())) return 0; + let removed = 0; + for (const entry of readdirSync(jobRoot())) { + if (!JOB_ID_PATTERN.test(entry)) continue; + const dir = `${jobRoot()}/${entry}`; + try { + const meta = JSON.parse(readFileSync(`${dir}/meta.json`, "utf-8")); + if (jobIsRunning(dir, meta.pid)) continue; + const finishedAt = existsSync(`${dir}/exit_code`) ? statSync(`${dir}/exit_code`).mtimeMs : statSync(`${dir}/meta.json`).mtimeMs; + if (now - finishedAt < maxAgeMs) continue; + rmSync(dir, { recursive: true, force: true }); + removed += 1; + } catch { + // Unreadable/partial job directory: leave it for manual inspection. + } + } + return removed; +} + async function runArgv( label: string, argv: string[], @@ -246,7 +304,7 @@ async function runArgv( maxStderr = 20_000, ): Promise { try { - const proc = spawn(argv, { stdout: "pipe", stderr: "pipe", cwd: "/" }); + const proc = spawnGroup(argv, { stdout: "pipe", stderr: "pipe", cwd: "/" }); const outputAbort = new AbortController(); const stdoutPromise = readProcessOutput(proc.stdout, maxStdout, { signal: outputAbort.signal }); const stderrPromise = readProcessOutput(proc.stderr, maxStderr, { signal: outputAbort.signal }); @@ -269,30 +327,18 @@ async function runArgv( } } -const READ_ONLY_PROGRAMS = new Set([ - "cat", "date", "df", "dmesg", "du", "file", "find", "free", "grep", - "head", "hostname", "id", "ip", "lsof", "ls", "lsblk", "lspci", "mount", - "ps", "readlink", "realpath", "sha256sum", "ss", "stat", "tail", "uname", - "uptime", "wc", "whoami", -]); - function stopProcessWhenTruncated( - proc: { kill: () => void }, + proc: { pid: number }, output: Promise<{ text: string; truncated: boolean }>, ): void { void output.then((result) => { - if (!result.truncated) return; - try { - proc.kill(); - } catch { - // The process may already have exited after its pipe was closed. - } + if (result.truncated) killProcessGroup(proc.pid); }).catch(() => {}); } /** - * Führt ausschließlich freigegebene Leseprogramme direkt als argv aus. - * Kein /bin/sh, keine Pipes, Umleitungen, Substitutionen oder Verkettungen. + * Readonly-Diagnose ohne /bin/sh (Details in readonly.ts). + * Akzeptiert `program` + `args` oder eine komplette Befehlszeile `command`. */ export async function runReadOnlyCommand( program: string, @@ -300,82 +346,18 @@ export async function runReadOnlyCommand( timeoutSec = 30, maxOutputChars = 12_000, ): Promise { - if (!READ_ONLY_PROGRAMS.has(program)) { - throw new Error(`Program is not allowed in read-only mode: ${program}`); - } - if (args.length > 64 || args.some((arg) => typeof arg !== "string" || arg.length > 4096)) { - throw new Error("Invalid or excessive arguments"); - } + return runReadOnlyInput({ program, args }, timeoutSec, maxOutputChars); +} + +export async function runReadOnlyInput( + input: { command?: unknown; program?: unknown; args?: unknown }, + timeoutSec = 30, + maxOutputChars = 12_000, +): Promise { if (!Number.isInteger(maxOutputChars) || maxOutputChars < 1_000 || maxOutputChars > 30_000) { throw new Error("maxOutputChars must be between 1000 and 30000"); } - - const lowered = args.map((arg) => arg.toLowerCase()); - const reject = (message: string) => { throw new Error(message); }; - if (["hostname", "whoami", "uptime"].includes(program) && args.length > 0) { - reject(`${program} does not accept arguments in read-only mode`); - } - if (program === "date") { - const safeDateFlags = new Set(["-u", "--utc", "-r", "--reference", "--rfc-email", "-d", "--date"]); - for (let i = 0; i < args.length; i++) { - const arg = lowered[i]; - if (i > 0 && ["-d", "--date", "-r", "--reference"].includes(lowered[i - 1])) continue; - if (arg.startsWith("+") || safeDateFlags.has(arg) || arg.startsWith("--date=") || - arg.startsWith("--iso-8601") || arg.startsWith("--rfc-3339")) continue; - reject("Only date display and parsing options are allowed"); - } - } - if (program === "dmesg" && args.some((a) => - ["-C", "-D", "-E", "-n"].includes(a) || - ["--clear", "--read-clear", "--console-off", "--console-on", "--console-level"].includes(a.toLowerCase()) - )) { - reject("Changing or clearing the kernel log is not allowed"); - } - if (program === "ss" && lowered.some((a) => a === "-k" || a === "--kill")) { - reject("Killing sockets is not allowed"); - } - if (program === "mount" && args.length > 0) { - reject("mount is display-only and accepts no arguments in read-only mode"); - } - if (program === "ip") { - const safeObjects = new Set(["address", "addr", "route", "link", "neigh", "neighbor"]); - const mutating = new Set(["add", "append", "change", "delete", "del", "flush", "replace", "set"]); - if (args.length === 0 || !safeObjects.has(lowered[0]) || lowered.some((a) => mutating.has(a))) { - reject("Only read-only ip objects and show/list operations are allowed"); - } - } - if (program === "find") { - const mutatingFind = ["-delete", "-exec", "-execdir", "-ok", "-okdir", "-fprint", "-fprintf", "-fls"]; - if (lowered.some((a) => mutatingFind.some((blocked) => a === blocked || a.startsWith(blocked)))) { - reject("Mutating find actions are not allowed"); - } - } - - try { - const proc = spawn([program, ...args], { stdout: "pipe", stderr: "pipe", cwd: "/" }); - const outputAbort = new AbortController(); - const stdoutPromise = readProcessOutput(proc.stdout, maxOutputChars, { signal: outputAbort.signal }); - const stderrPromise = readProcessOutput(proc.stderr, Math.min(8_000, maxOutputChars), { signal: outputAbort.signal }); - stopProcessWhenTruncated(proc, stdoutPromise); - stopProcessWhenTruncated(proc, stderrPromise); - const [stdout, stderr, code] = await awaitProcess( - proc, - stdoutPromise, - stderrPromise, - timeoutSec, - `read-only ${program}`, - outputAbort, - ); - return JSON.stringify({ - exit_code: code, - stdout: sanitizeLogOutput(stdout.text.trim(), maxOutputChars), - stderr: sanitizeLogOutput(stderr.text.trim(), Math.min(8_000, maxOutputChars)), - truncated: stdout.truncated || stderr.truncated, - mode: "read-only", - }); - } catch (e) { - throw new Error(`read-only command failed: ${String(e)}`); - } + return runReadOnly(input, timeoutSec, maxOutputChars, sanitizeLogOutput); } /** @@ -392,8 +374,36 @@ export interface ToolboxContainer { status: string; } +// tools/list und jeder tools/call fragen den Toolbox-Zustand ab. Ohne Cache +// kostet das pro Aufruf einen `docker ps` (spürbare Latenz). Kurzer Cache, +// laufende Abfragen werden geteilt; Fehler werden nicht gecacht. +const TOOLBOX_CACHE_MS = Number(process.env["MUA_TOOLBOX_CACHE_MS"] ?? 15_000); +let toolboxCache: { at: number; value: ToolboxContainer[] } | null = null; +let toolboxInflight: Promise | null = null; + +export function invalidateToolboxCache(): void { + toolboxCache = null; +} + /** Find self-declared agent toolboxes without relying on a container name. */ -export async function discoverToolboxContainers(): Promise { +export async function discoverToolboxContainers( + { fresh = false }: { fresh?: boolean } = {}, +): Promise { + const now = Date.now(); + if (!fresh && toolboxCache && now - toolboxCache.at < TOOLBOX_CACHE_MS) return toolboxCache.value; + if (!fresh && toolboxInflight) return toolboxInflight; + const pending = queryToolboxContainers(); + toolboxInflight = pending; + try { + const value = await pending; + toolboxCache = { at: Date.now(), value }; + return value; + } finally { + if (toolboxInflight === pending) toolboxInflight = null; + } +} + +async function queryToolboxContainers(): Promise { const raw = await dockerExec( "ps -a --filter 'label=mike.ai.role=toolbox' --format '{{json .}}'", 30, @@ -446,7 +456,7 @@ export async function toolboxStatus(programs: string[] = []): Promise { throw new Error(`Invalid program name: ${program}`); } } - const containers = await discoverToolboxContainers(); + const containers = await discoverToolboxContainers({ fresh: true }); const running = containers.filter((container) => container.state === "running"); const result: Record = { label: "mike.ai.role=toolbox", @@ -492,9 +502,9 @@ export async function toolboxExec( timeoutSec = 300, requestedName?: string, ): Promise { - const selected = selectRunningToolbox(await discoverToolboxContainers(), requestedName); + const selected = selectRunningToolbox(await discoverToolboxContainers({ fresh: true }), requestedName); try { - const proc = spawn( + const proc = spawnGroup( ["/usr/bin/docker", "exec", selected.name, "/bin/sh", "-lc", command], { stdout: "pipe", stderr: "pipe", cwd: "/" }, ); @@ -661,8 +671,10 @@ export function tcpProbe( // ── Log Sanitize ──────────────────────────────────────────────────────── export function sanitizeLogOutput(text: string, maxChars = 50000): string { + // Konkrete MUA-Zugangsdaten (API-Key, Admin-Token) niemals ausgeben. + let result = redactKnownSecrets(text); // Entferne ANSI-Escape-Sequenzen - let result = text.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, ""); + result = result.replace(/\x1b\[[0-9;]*[a-zA-Z]/g, ""); // Entferne andere Control-Chars (außer \n, \r, \t) result = result.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, ""); // Häufige Secret-Formate redigieren. Das ist bewusst nur eine zusätzliche diff --git a/src/index.ts b/src/index.ts index 0fc3add..6a97be5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -18,7 +18,11 @@ import { MUA_VERSION, MUA_PROTOCOL_VERSION, discoverToolboxContainers, + invalidateToolboxCache, + pruneFinishedJobs, } from "./helpers"; +import { killForegroundGroups, runInProcessScope } from "./process-group"; +import { registerSecret } from "./redact"; import { TOOLS, toolByName, getToolRisk } from "./tools"; import { checkAuth, @@ -30,6 +34,8 @@ import { setEnabledTools, getToolboxEnabled, setToolboxEnabled, + getAutoGrantedTools, + safeEqual, } from "./auth"; import { randomBytes } from "node:crypto"; import { spawn } from "node:child_process"; @@ -110,6 +116,15 @@ function rpcError(id: number | string | null, code: number, message: string) { } // ── Session Management ────────────────────────────────────────────────── +// Sessions: Neue IDs entstehen nur bei `initialize`. Eine unbekannte, aber +// formal gültige ID (UUID) wird bewusst übernommen statt mit 404 abgelehnt: +// MUA startet sich bei Binary-Updates selbst neu und verliert dabei alle +// Sessions. Viele MCP-Clients (auch Hermes) initialisieren nach 404 nicht +// automatisch neu und wären bis zum Client-Neustart unbenutzbar. Die +// Sicherheit hängt ausschließlich am Bearer-Token, nicht an der Session-ID. +// Ungültige IDs werden mit 400 abgelehnt; die Map ist in der Größe begrenzt. +const MAX_SESSIONS = 1000; +const SESSION_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; const sessions = new Map(); const rateLimits = new Map(); const toolCallGate = new ToolCallGate(MAX_CONCURRENT_TOOL_CALLS); @@ -150,11 +165,19 @@ function newSessionId(): string { } function touchSession(id: string) { const now = Date.now(); - if (sessions.has(id)) { - sessions.get(id)!.lastActivity = now; - } else { - sessions.set(id, { createdAt: now, lastActivity: now }); + const existing = sessions.get(id); + if (existing) { + existing.lastActivity = now; + return; } + if (sessions.size >= MAX_SESSIONS) { + // Älteste (am längsten inaktive) Session verdrängen. + let oldestId = ""; + let oldest = Infinity; + for (const [sid, s] of sessions) if (s.lastActivity < oldest) { oldest = s.lastActivity; oldestId = sid; } + sessions.delete(oldestId); + } + sessions.set(id, { createdAt: now, lastActivity: now }); } function deleteSession(id: string | null) { if (id) sessions.delete(id); @@ -247,10 +270,19 @@ async function handleMcpRequest( }; } const startedAt = Date.now(); + // Alle Prozesse dieses Aufrufs werden in einem Scope erfasst. Greift der + // harte Timeout, wird genau dieser Prozessbaum beendet, statt im + // Hintergrund weiterzulaufen, während der Slot schon wieder frei ist. + const scope = runInProcessScope(() => tool.handler(args)); try { - const text = await withHardTimeout(tool.handler(args), timeoutMs, `MCP tool '${toolName}'`); + const text = await withHardTimeout(scope.promise, timeoutMs, `MCP tool '${toolName}'`) + .catch((error) => { scope.killAll(); throw error; }); let failed = false; - try { const v = JSON.parse(text); failed = v?.ok === false || (typeof v?.exit_code === "number" && v.exit_code !== 0); } catch { /* textual success */ } + try { + const v = JSON.parse(text); + failed = v?.ok === false + || (typeof v?.exit_code === "number" && v.exit_code !== 0 && v?.no_match !== true); + } catch { /* textual success */ } auditTool(toolName, !failed, Date.now() - startedAt); const result: Record = { content: [{ type: "text", text }], @@ -271,7 +303,7 @@ async function handleMcpRequest( auditTool(toolName, false, Date.now() - startedAt); return { response: rpcResult(id, { - content: [{ type: "text", text: `ERROR: ${String(e)}` }], + content: [{ type: "text", text: `ERROR: ${e instanceof Error ? e.message : String(e)}` }], isError: true, }), sessionId: sessionId ?? "", @@ -340,12 +372,13 @@ try { // ── Health-Check (ohne Auth) ──────────────────────────────────────── if (path === "/health") { const toolCalls = toolCallGate.snapshot(); + // Ohne Auth nur der Zustand; Version/Port nur mit gültigem Bearer-Token. + const authed = checkAuth(req); return Response.json( { status: "ok", server: MUA_SERVER_NAME, - version: MUA_VERSION, - port: PORT, + ...(authed ? { version: MUA_VERSION, port: PORT } : {}), auth: "required", tool_calls: { active: toolCalls.active, @@ -386,6 +419,10 @@ try { } // ── MCP-Endpunkt ──────────────────────────────────────────────────── + if ((path === "/mcp" || path === "/") && sessionHeader !== null && sessionHeader !== "" + && !SESSION_ID_PATTERN.test(sessionHeader)) { + return Response.json(rpcError(null, -32600, "Invalid Mcp-Session-Id"), { status: 400, headers: corsHeaders }); + } if (path === "/mcp" || path === "/") { // POST: JSON-RPC Request if (method === "POST") { @@ -493,6 +530,7 @@ function transportStatus(forGUI = false) { const CONFIG_PORT = Number(process.env["MUA_CONFIG_PORT"] ?? 3013); const ADMIN_TOKEN_FILE = process.env["MUA_ADMIN_TOKEN_FILE"] ?? "/var/run/mua-admin.token"; const adminToken = randomBytes(32).toString("hex"); +registerSecret(adminToken); try { writeFileSync(ADMIN_TOKEN_FILE, adminToken + "\n", { mode: 0o600 }); chmodSync(ADMIN_TOKEN_FILE, 0o600); @@ -515,7 +553,7 @@ try { return Response.json({ error: "Not found" }, { status: 404 }); } - if (req.headers.get("x-mua-admin-token") !== adminToken) { + if (!safeEqual(req.headers.get("x-mua-admin-token") ?? "", adminToken)) { return Response.json({ error: "Unauthorized" }, { status: 401 }); } @@ -553,6 +591,7 @@ try { transport: transportStatus(true), enabledTools: getEnabledTools(), allToolsEnabled: getAllToolsEnabled(), + autoGrantedTools: getAutoGrantedTools(), allTools: TOOLS.filter((t) => !TOOLBOX_TOOL_NAMES.has(t.name)).map((t) => ({ name: t.name, description: t.description, @@ -601,6 +640,7 @@ try { setEnabledTools(tools, body["allToolsEnabled"] === true); } if (typeof body["toolboxEnabled"] === "boolean") { + invalidateToolboxCache(); const toolbox = await toolboxGuidance(); setToolboxEnabled(body["toolboxEnabled"] === true && toolbox.available); } @@ -694,14 +734,24 @@ const housekeepingInterval = setInterval(() => { }, 5 * 60 * 1000); housekeepingInterval.unref(); +// Abgeschlossene Async-Jobs (/tmp = RAM auf Unraid) nach 7 Tagen entfernen. +const JOB_RETENTION_MS = Number(process.env["MUA_JOB_RETENTION_DAYS"] ?? 7) * 24 * 60 * 60 * 1000; +try { pruneFinishedJobs(JOB_RETENTION_MS); } catch { /* best effort */ } +const jobPruneInterval = setInterval(() => { + try { pruneFinishedJobs(JOB_RETENTION_MS); } catch { /* best effort */ } +}, 60 * 60 * 1000); +jobPruneInterval.unref(); + // Graceful shutdown process.on("SIGTERM", () => { console.log("[MUA] SIGTERM received, shutting down"); + killForegroundGroups(); server.stop(true); process.exit(0); }); process.on("SIGINT", () => { console.log("[MUA] SIGINT received, shutting down"); + killForegroundGroups(); server.stop(true); process.exit(0); }); diff --git a/src/process-group.ts b/src/process-group.ts new file mode 100644 index 0000000..61085bc --- /dev/null +++ b/src/process-group.ts @@ -0,0 +1,97 @@ +/** + * MUA — Mikes Unraid Agent + * process-group.ts — Kindprozesse in eigenen Prozessgruppen starten und + * bei Timeouts vollständig (inklusive Enkelprozessen) beenden. + * + * Hintergrund: `proc.kill()` trifft nur den direkten Kindprozess, z.B. die + * `/bin/sh`. Ein darin gestartetes `docker pull` oder eine Schleife lief nach + * einem Timeout weiter, obwohl der Tool-Slot bereits wieder frei war. + * + * Jeder Prozess wird deshalb `detached` (setsid → eigene Prozessgruppe, PGID + * = PID) gestartet. Ein Kill trifft mit `kill(-pgid)` die gesamte Gruppe. + * + * Zusätzlich merkt sich ein AsyncLocalStorage-Scope pro MCP-Tool-Aufruf alle + * gestarteten Gruppen. Greift der harte Timeout in index.ts, werden genau die + * Prozesse dieses Aufrufs beendet — nicht die anderer, parallel laufender + * Aufrufe. Bei normalem Ende wird nichts beendet: absichtlich mit `nohup … &` + * gestartete Hintergrundprozesse der Root-Shell bleiben erhalten. + */ + +import { spawn } from "bun"; +import { AsyncLocalStorage } from "node:async_hooks"; + +type SpawnOptions = NonNullable[1]>; +export type GroupProcess = ReturnType; + +const scopeStorage = new AsyncLocalStorage>(); +/** Alle laufenden, an einen MCP-Aufruf gebundenen Gruppen (für SIGTERM). */ +const foregroundGroups = new Set(); + +/** Sendet ein Signal an die ganze Prozessgruppe; fällt auf die PID zurück. */ +export function killProcessGroup(pid: number | undefined, signal: NodeJS.Signals = "SIGKILL"): boolean { + if (!pid || pid <= 1) return false; + try { + process.kill(-pid, signal); + return true; + } catch { + try { + process.kill(pid, signal); + return true; + } catch { + return false; // Bereits beendet. + } + } +} + +/** + * Startet einen Prozess in eigener Prozessgruppe. + * `background: true` = langlebiger Job, der nicht an den aktuellen + * Tool-Aufruf oder den MUA-Shutdown gebunden ist. + */ +export function spawnGroup( + argv: string[], + options: SpawnOptions = {}, + { background = false }: { background?: boolean } = {}, +): GroupProcess { + const proc = spawn(argv, { cwd: "/", ...options, detached: true } as SpawnOptions); + const pid = proc.pid; + if (!background && pid) { + foregroundGroups.add(pid); + const scope = scopeStorage.getStore(); + scope?.add(pid); + void proc.exited.finally(() => { + foregroundGroups.delete(pid); + // Absichtlich NICHT aus dem Scope entfernen: Die Gruppe kann nach Ende + // des Leaders weiterleben (Enkel halten Pipes offen). Ein Kill auf eine + // leere Gruppe ist harmlos (ESRCH). + }).catch(() => {}); + } + return proc; +} + +export interface ProcessScope { + promise: Promise; + /** Beendet alle in diesem Scope gestarteten Prozessgruppen. */ + killAll: () => number; +} + +/** Führt `work` in einem eigenen Scope aus, dessen Prozesse gezielt beendbar sind. */ +export function runInProcessScope(work: () => Promise): ProcessScope { + const groups = new Set(); + const promise = scopeStorage.run(groups, work); + return { + promise, + killAll: () => { + let killed = 0; + for (const pid of groups) if (killProcessGroup(pid)) killed += 1; + groups.clear(); + return killed; + }, + }; +} + +/** Beim MUA-Shutdown laufende Vordergrund-Prozessgruppen mitnehmen. */ +export function killForegroundGroups(): void { + for (const pid of foregroundGroups) killProcessGroup(pid); + foregroundGroups.clear(); +} diff --git a/src/readonly.test.ts b/src/readonly.test.ts new file mode 100644 index 0000000..6f7bd53 --- /dev/null +++ b/src/readonly.test.ts @@ -0,0 +1,289 @@ +import { afterAll, describe, expect, test } from "bun:test"; +import { mkdtempSync, mkdirSync, rmSync, symlinkSync, utimesSync, writeFileSync, existsSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +// Vor dem Import der Module setzen (Job-Root wird lazy gelesen). +const sandbox = mkdtempSync(join(tmpdir(), "mua-r036-")); +process.env["MUA_JOB_ROOT"] = join(sandbox, "jobs"); + +import { parseCommandLine, planReadOnly } from "./readonly"; +import { + cancelShellJob, pruneFinishedJobs, runReadOnlyInput, runShell, sanitizeLogOutput, + shellJobStatus, startShellJob, +} from "./helpers"; +import { parseConfig, safeEqual } from "./auth"; +import { registerSecret, redactCredentialFormats } from "./redact"; +import { runInProcessScope } from "./process-group"; +import { withHardTimeout } from "./concurrency"; +import { getToolRisk, toolByName } from "./tools"; + +afterAll(() => rmSync(sandbox, { recursive: true, force: true })); + +const run = async (input: Record, timeout = 10, max = 12_000) => + JSON.parse(await runReadOnlyInput(input, timeout, max)); +const rejects = (command: string) => expect(() => planReadOnly({ command })).toThrow(); +const accepts = (command: string) => expect(() => planReadOnly({ command })).not.toThrow(); + +function processAlive(marker: string): boolean { + const out = Bun.spawnSync(["ps", "-axo", "command"]).stdout.toString(); + return out.split("\n").some((line) => line.includes(marker) && !line.includes("ps -axo")); +} + +describe("read-only: previously possible bypasses are rejected", () => { + test("ip: abbreviated mutating verbs and batch mode", () => { + rejects("ip a a 10.0.0.5/24 dev lo"); // address add + rejects("ip r d default"); // route delete + rejects("ip link s lo down"); // link set + rejects("ip addr flush dev eth0"); + rejects("ip -b /tmp/cmds"); + rejects("ip -force -batch /tmp/cmds"); + rejects("ip netns exec x id"); + rejects("ip monitor"); + }); + + test("dmesg: clear/console options incl. combined flags and abbreviations", () => { + for (const cmd of ["dmesg -c", "dmesg -Tc", "dmesg -C", "dmesg -n1", "dmesg -n 1", "dmesg --read-c", + "dmesg --cle", "dmesg --console-level=1", "dmesg -D", "dmesg -E", "dmesg -w", "dmesg --follow"]) rejects(cmd); + }); + + test("ss, date, tail, sort, uniq, file, find, mount, hostname, storage", () => { + for (const cmd of [ + "ss -tK dst 1.2.3.4", "ss --kill", "ss -D /tmp/dump", "ss --diag=/tmp/x", + "date -s 2020-01-01", "date --set=2020-01-01", "date 010112002020", "date -us now", + "tail -f /var/log/syslog", "tail -fn 5 /var/log/syslog", "tail --follow=name x", + "sort -o /etc/passwd x", "sort --output=/x y", "sort --compress-program=sh x", "uniq a b", + "file -C -m /tmp/x", "file -zC x", "find / -fprint0 /tmp/x", "find /tmp -execdir id ;", + "mount /dev/sda1 /mnt", "hostname evil", "hostname -F /tmp/x", "uptime now", + "zpool destroy tank", "zfs destroy tank/x", "mdcmd stop", "sensors -s", + ]) rejects(cmd); + }); + + test("shell features are refused with guidance", () => { + expect(() => planReadOnly({ command: "cat /etc/passwd > /tmp/x" })).toThrow(/redirection/); + expect(() => planReadOnly({ command: "echo $(id)" })).toThrow(/\$\(\.\.\.\)/); + expect(() => planReadOnly({ command: "echo `id`" })).toThrow(/substitution/); + expect(() => planReadOnly({ command: 'echo "$HOME"' })).toThrow(); + expect(() => planReadOnly({ command: "sleep 1 &" })).toThrow(/Background/); + expect(() => planReadOnly({ command: "sh -c id" })).toThrow(/not allowed/); + expect(() => planReadOnly({ command: "rm -rf /" })).toThrow(/Allowed:/); + }); +}); + +describe("read-only: flexible input for small models", () => { + test("legit read-only forms stay allowed", () => { + for (const cmd of [ + "ip -br a", "ip -4 addr show dev eth0", "ip route get 1.1.1.1", "ip -j link show", "ip neigh", "ip r", + "dmesg -T --level=err,warn", "dmesg --color=never -l err", "date +%s", "date -d '2024-01-01' +%s", + "date -u -Iseconds", "tail -n 50 /var/log/syslog", "tail -50 /var/log/syslog", "head -c 100 /etc/passwd", + "sort -k2 -t: /etc/passwd", "uniq -c /etc/passwd", "mount", "mount -t xfs", "hostname -I", "uptime -p", + "zpool status", "zfs list -o name,used", "mdcmd status", "find /var/log -name '*.log' -mmin -60", + "ss -tulpn", "ps aux", "lsof -nP -i :3002", "df -h", "free -m", "grep -ri 'error|warn' /var/log", + "/usr/bin/tail -n 5 /etc/hosts", "sudo tail -n 5 /etc/hosts", + ]) accepts(cmd); + }); + + test("tokenizer handles quotes, escapes, ~, comments and tolerated stderr redirects", () => { + const steps = parseCommandLine(`grep -E "a|b" 'x y' a\\ b ~/f # comment`); + expect(steps[0].pipeline[0].map((w) => w.value)).toEqual(["grep", "-E", "a|b", "x y", "a b", "/root/f"]); + expect(parseCommandLine("grep x /f 2>&1 | head -n 1")[0].pipeline.length).toBe(2); + expect(parseCommandLine("grep x /f 2>/dev/null")[0].pipeline[0].map((w) => w.value)).toEqual(["grep", "x", "/f"]); + expect(parseCommandLine("df -h; free -m && uptime || id\nwc -l /x").map((s) => s.connector)) + .toEqual([";", ";", "&&", "||", ";"]); + }); + + test("pipelines, sequences and connectors execute correctly", async () => { + const piped = await run({ command: "printf 'a\\nb\\nc\\n' | grep -v b | wc -l" }); + expect(piped.stdout.trim()).toBe("2"); + expect(piped.ran).toBe("printf 'a\\nb\\nc\\n' | grep -v b | wc -l"); + const seq = await run({ command: "echo one; echo two && echo three || echo never" }); + expect(seq.stdout).toContain("$ echo one\none"); + expect(seq.stdout).toContain("three"); + expect(seq.stdout).not.toContain("never"); + expect(seq.steps.length).toBe(3); + const fallback = await run({ command: "grep zzz-not-there /etc/hosts || echo fallback" }); + expect(fallback.stdout).toContain("fallback"); + }); + + test("program may carry the whole command line and args may be a string", async () => { + expect((await run({ program: "echo hello world" })).stdout).toBe("hello world"); + expect((await run({ program: "echo", args: "hi there" })).stdout).toBe("hi there"); + expect((await run({ program: "echo", args: ["a|b", "$X"] })).stdout).toBe("a|b $X"); + }); + + test("globs in absolute paths are expanded without a shell", async () => { + const dir = join(sandbox, "glob"); + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, "one.log"), "1\n"); + writeFileSync(join(dir, "two.log"), "2\n"); + writeFileSync(join(dir, "skip.txt"), "x\n"); + const result = await run({ command: `cat ${dir}/*.log` }); + expect(result.stdout).toBe("1\n2"); + const literal = await run({ command: `ls '${dir}/*.log'` }); + expect(literal.exit_code).not.toBe(0); // gequotet = kein Glob, wie in bash + }); + + test("grep without matches is reported as no_match, not as failure", async () => { + const result = await run({ command: "grep definitely-not-present /etc/hosts" }); + expect(result.exit_code).toBe(1); + expect(result.no_match).toBe(true); + }); + + test("output limit still bounds pipelines and reports truncation", async () => { + const result = await run({ command: "cat /dev/zero | tr '\\0' a" }, 5, 1000); + expect(result.truncated).toBe(true); + expect(result.stdout.length).toBeLessThanOrEqual(1000 + 30); + }); + + test("timeouts return partial output and kill the pipeline", async () => { + const result = await run({ command: "find / -name zzz-mua-never-exists-r036" }, 1); + expect(result.timed_out).toBe(true); + expect(result.exit_code).toBe(124); + await Bun.sleep(300); + expect(processAlive("zzz-mua-never-exists-r036")).toBe(false); + }); + + test("tool definition exposes command, program and args", () => { + const tool = toolByName("unraid_system_shell_readonly")!; + const props = (tool.inputSchema as any).properties; + expect(Object.keys(props)).toEqual(["command", "program", "args", "timeout_seconds", "max_output_chars"]); + expect(tool.description).toContain("tail -n 100"); + }); +}); + +describe("read-only: credentials", () => { + test("direct access to credential files is blocked, also via relative, attached and symlinked paths", () => { + const blocked = [ + "cat /etc/shadow", "cat etc/shadow", "cat /etc/../etc/gshadow", "grep -f/etc/shadow x", + "grep --file=/etc/shadow x", "cat /boot/config/shadow", "cat /boot/config/smbpasswd", + "cat /root/.ssh/id_ed25519", "cat /boot/config/ssh/ssh_host_rsa_key", "cat /proc/self/environ", + "cat /proc/1/environ", "cat /var/lib/docker/containers/abc/config.v2.json", + ]; + for (const cmd of blocked) expect(() => planReadOnly({ command: cmd })).toThrow(/blocked/); + accepts("cat /root/.ssh/id_ed25519.pub"); + accepts("cat /root/.ssh/authorized_keys"); + accepts("cat /etc/passwd"); + }); + + test("MUA config and admin token are blocked, including via symlink", () => { + const cfgDir = join(sandbox, "cfg"); + mkdirSync(cfgDir, { recursive: true }); + writeFileSync(join(cfgDir, "mua.conf"), "MUA_API_KEY=x\n"); + symlinkSync(join(cfgDir, "mua.conf"), join(sandbox, "innocent-link")); + const previous = process.env["MUA_CONFIG_DIR"]; + process.env["MUA_CONFIG_DIR"] = cfgDir; + try { + expect(() => planReadOnly({ command: `cat ${cfgDir}/mua.conf` })).toThrow(/MUA credentials/); + expect(() => planReadOnly({ command: `cat ${sandbox}/innocent-link` })).toThrow(/MUA credentials/); + expect(() => planReadOnly({ command: "cat /var/run/mua-admin.token" })).toThrow(/MUA credentials/); + } finally { + if (previous === undefined) delete process.env["MUA_CONFIG_DIR"]; else process.env["MUA_CONFIG_DIR"] = previous; + } + }); + + test("credential formats are redacted in recursive read-only output", async () => { + const dir = join(sandbox, "creds"); + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, "copy-of-shadow"), "root:$6$saltsalt$abcdefghijklmnopqrstuvwxyz0123456789:19000:0:99999:7:::\n"); + writeFileSync(join(dir, "wg0.conf"), "[Interface]\nPrivateKey = aGVsbG8gd29ybGQgc2VjcmV0IGtleQ==\nAddress = 10.0.0.1/24\n"); + writeFileSync(join(dir, "server.pem"), "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBg\n-----END PRIVATE KEY-----\n-----BEGIN CERTIFICATE-----\nMIIBpublic\n-----END CERTIFICATE-----\n"); + const result = await run({ command: `grep -r . ${dir}` }); + expect(result.stdout).not.toContain("$6$saltsalt"); + expect(result.stdout).not.toContain("aGVsbG8gd29ybGQgc2VjcmV0IGtleQ=="); + expect(result.stdout).toContain("Address = 10.0.0.1/24"); + const pem = await run({ command: `cat ${dir}/server.pem` }); + expect(pem.stdout).not.toContain("MIIEvQIBADANBg"); + expect(pem.stdout).toContain("MIIBpublic"); // öffentliche Zertifikate bleiben lesbar + }); + + test("registered MUA secrets never appear in any sanitized output", () => { + const secret = "f".repeat(20) + "0123456789abcdef0123456789abcdef"; + registerSecret(secret); + expect(sanitizeLogOutput(`key is ${secret}!`)).toBe("key is [REDACTED:mua-secret]!"); + expect(redactCredentialFormats("PresharedKey=abc")).toBe("PresharedKey=[REDACTED]"); + }); +}); + +describe("process groups", () => { + test("a shell timeout kills background grandchildren too", async () => { + const result = runShell("sleep 61.0360 & sleep 61.0361; echo done", 1); + await expect(result).rejects.toThrow(); + await Bun.sleep(300); + expect(processAlive("sleep 61.0360")).toBe(false); + expect(processAlive("sleep 61.0361")).toBe(false); + }); + + test("the MCP hard timeout kills the processes of exactly that call", async () => { + const scope = runInProcessScope(() => runShell("sleep 62.0362", 120)); + await expect(withHardTimeout(scope.promise, 400, "test").catch((e) => { scope.killAll(); throw e; })).rejects.toThrow(/hard timeout/); + await Bun.sleep(300); + expect(processAlive("sleep 62.0362")).toBe(false); + }); + + test("normal completion keeps intentionally detached background processes", async () => { + const out = JSON.parse(await runShell("nohup sleep 63.0363 >/dev/null 2>&1 & echo started", 10)); + expect(out.stdout).toBe("started"); + await Bun.sleep(200); + expect(processAlive("sleep 63.0363")).toBe(true); + Bun.spawnSync(["pkill", "-f", "sleep 63.0363"]); + }); +}); + +describe("async jobs", () => { + async function waitState(id: string, wanted: string) { + for (let i = 0; i < 50; i++) { + const status = JSON.parse(await shellJobStatus(id)); + if (status.state === wanted) return status; + await Bun.sleep(100); + } + return JSON.parse(await shellJobStatus(id)); + } + + test("exit inside the command still records the exit code", async () => { + const { job_id } = JSON.parse(await startShellJob("echo hi\nexit 3\necho never")); + const status = await waitState(job_id, "finished"); + expect(status.state).toBe("finished"); + expect(status.exit_code).toBe(3); + expect(status.stdout_tail).toContain("hi"); + expect(status.stdout_tail).not.toContain("never"); + }); + + test("cancel stops the job and all of its processes", async () => { + const { job_id } = JSON.parse(await startShellJob("sleep 64.0364 & sleep 64.0365; wait")); + await Bun.sleep(300); + expect(processAlive("sleep 64.0364")).toBe(true); + const cancelled = JSON.parse(await cancelShellJob(job_id)); + expect(cancelled.cancelled).toBe(true); + await Bun.sleep(300); + expect(processAlive("sleep 64.0364")).toBe(false); + expect(processAlive("sleep 64.0365")).toBe(false); + expect(JSON.parse(await shellJobStatus(job_id)).state).not.toBe("running"); + }); + + test("old finished jobs are pruned, recent ones are kept", async () => { + const { job_id } = JSON.parse(await startShellJob("true")); + await waitState(job_id, "finished"); + const dir = join(process.env["MUA_JOB_ROOT"]!, job_id); + expect(pruneFinishedJobs(60_000)).toBe(0); + const old = new Date(Date.now() - 8 * 24 * 3600 * 1000); + utimesSync(join(dir, "exit_code"), old, old); + expect(pruneFinishedJobs(7 * 24 * 3600 * 1000)).toBe(1); + expect(existsSync(dir)).toBe(false); + }); + + test("job_cancel is critical and granted together with the root shell", () => { + expect(getToolRisk("unraid_system_job_cancel")).toBe("critical"); + const cfg = parseConfig("MUA_API_KEY=t\nMUA_ENABLED_TOOLS=unraid_system_shell\n"); + expect(cfg.enabledTools).toContain("unraid_system_job_cancel"); + expect(cfg.autoGranted).toContain("unraid_system_job_cancel"); + expect(parseConfig("MUA_API_KEY=t\nMUA_ENABLED_TOOLS=unraid_system_shell_readonly\n").enabledTools) + .not.toContain("unraid_system_job_cancel"); + }); +}); + +test("safeEqual compares in constant time and rejects empty secrets", () => { + expect(safeEqual("abc", "abc")).toBe(true); + expect(safeEqual("abd", "abc")).toBe(false); + expect(safeEqual("ab", "abc")).toBe(false); + expect(safeEqual("", "")).toBe(false); +}); diff --git a/src/readonly.ts b/src/readonly.ts new file mode 100644 index 0000000..2a6646b --- /dev/null +++ b/src/readonly.ts @@ -0,0 +1,680 @@ +/** + * MUA — Mikes Unraid Agent + * readonly.ts — Readonly-Diagnose-Shell ohne /bin/sh. + * + * Ziel: Auch kleine Modelle sollen in EINEM Aufruf korrekte Ergebnisse + * bekommen. Deshalb wird eine normale Befehlszeile akzeptiert + * ("ps aux | grep plex", "df -h; free -m", "tail -n 50 /var/log/syslog") + * und hier selbst — ohne Shell-Interpreter — zerlegt, geprüft und + * ausgeführt: + * + * - Quotes ('…', "…"), Backslash-Escapes, ~ → /root + * - Pipes zwischen erlaubten Programmen (max. 4 Stufen) + * - Sequenzen mit ; && || und Zeilenumbrüchen (max. 8 Befehle) + * - Globs in absoluten Pfaden (/var/log/*.log) werden selbst expandiert + * - 2>&1 und 2>/dev/null werden toleriert (stderr kommt ohnehin separat) + * + * Nicht möglich: Umleitungen in Dateien, $VAR, $(…), Backticks, &. + * + * Sicherheit: + * - Feste Programm-Allowlist; je Programm eine Options-Policy, die + * kombinierte Kurzflags (-Tc), --opt=wert und GNU-Abkürzungen (--cle) + * korrekt erkennt. + * - `ip` nur mit Positivliste für Objekt UND Verb (iproute2 akzeptiert + * Abkürzungen wie "ip a a" = address add). + * - Direkter Zugriff auf Dateien mit Zugangsdaten wird abgelehnt; in + * rekursiven Ausgaben (grep -r /etc) werden Zugangsdaten geschwärzt. + */ + +import { existsSync, realpathSync } from "node:fs"; +import { basename, resolve as resolvePath } from "node:path"; +import { readProcessOutput } from "./process-output"; +import { killProcessGroup, spawnGroup, type GroupProcess } from "./process-group"; +import { redactCredentialFormats } from "./redact"; + +export class ReadOnlyError extends Error {} +const fail = (message: string): never => { throw new ReadOnlyError(message); }; + +// ── Programme und Policies ─────────────────────────────────────────────── + +interface Policy { + /** Kurzoptionen, die einen Wert verlangen (Rest des Clusters oder nächstes Token). */ + valueShort?: string; + /** Kurzoptionen mit optionalem, nur angehängtem Wert (z.B. date -Iseconds). */ + optionalValueShort?: string; + /** Langoptionen, deren Wert als nächstes Token folgen darf. */ + valueLong?: string[]; + denyShort?: Record; + denyLong?: Record; + /** Maximale Zahl von Operanden (Nicht-Optionen). */ + maxOperands?: number; + /** Nur diese Options-Tokens sind erlaubt (exakt). */ + onlyOptions?: string[]; + /** Zusätzliche Prüfung auf den geparsten Operanden. */ + operands?: (operands: string[]) => void; + /** Vollständig eigene Prüfung (ersetzt den generischen Parser). */ + custom?: (args: string[]) => void; +} + +const FOLLOW = "Follow/watch mode never ends in a bounded tool. Drop it and read a fixed amount instead (e.g. tail -n 200 FILE)."; + +const POLICIES: Record = { + // Dateien & Text + cat: {}, head: { valueShort: "cn", valueLong: ["bytes", "lines"] }, + tail: { + valueShort: "cns", valueLong: ["bytes", "lines", "sleep-interval", "pid", "max-unchanged-stats"], + denyShort: { f: FOLLOW, F: FOLLOW }, denyLong: { follow: FOLLOW }, + }, + grep: {}, wc: {}, echo: {}, printf: {}, tac: {}, nl: {}, cut: {}, tr: {}, strings: {}, + sort: { + valueShort: "kStT", valueLong: ["key", "buffer-size", "temporary-directory", "field-separator", "parallel", "files0-from", "random-source", "batch-size"], + denyShort: { o: "sort -o writes a file. Output is returned directly; omit -o." }, + denyLong: { + output: "sort --output writes a file. Output is returned directly; omit it.", + "compress-program": "sort --compress-program executes a program and is not allowed.", + }, + }, + uniq: { valueShort: "fsw", valueLong: ["skip-fields", "skip-chars", "check-chars"], maxOperands: 1 }, + ls: {}, stat: {}, file: { + valueShort: "efFmP", valueLong: ["exclude", "exclude-quiet", "files-from", "separator", "magic-file", "parameter"], + denyShort: { C: "file -C writes a compiled magic file and is not allowed." }, + denyLong: { compile: "file --compile writes a compiled magic file and is not allowed." }, + }, + find: { custom: checkFind }, + du: {}, df: {}, readlink: {}, realpath: {}, basename: {}, dirname: {}, which: {}, + sha256sum: {}, md5sum: {}, + // System + date: { + valueShort: "dfr", optionalValueShort: "I", valueLong: ["date", "file", "reference"], + denyShort: { s: "Setting the clock is not allowed." }, + denyLong: { set: "Setting the clock is not allowed." }, + operands: (ops) => { + if (ops.some((op) => !op.startsWith("+"))) { + fail("date only accepts +FORMAT operands; other operands would set the clock. Use date -d 'STRING' to parse a date."); + } + }, + }, + dmesg: { + valueShort: "flsF", valueLong: ["facility", "level", "buffer-size", "file", "since", "until", "time-format"], + denyShort: { + c: "dmesg -c clears the kernel log. Use dmesg (optionally with -T or --level) instead.", + C: "dmesg -C clears the kernel log and is not allowed.", + D: "Changing console logging is not allowed.", E: "Changing console logging is not allowed.", + n: "Changing the console log level is not allowed.", + w: FOLLOW, W: FOLLOW, + }, + denyLong: { + clear: "Clearing the kernel log is not allowed.", "read-clear": "Clearing the kernel log is not allowed.", + "console-off": "Changing console logging is not allowed.", "console-on": "Changing console logging is not allowed.", + "console-level": "Changing the console log level is not allowed.", + follow: FOLLOW, "follow-new": FOLLOW, + }, + maxOperands: 0, + }, + free: {}, uname: {}, id: {}, nproc: {}, lscpu: {}, lsblk: {}, lspci: {}, lsusb: {}, + hostname: { onlyOptions: ["-i", "-I", "-f", "-s", "-d", "-A", "-a", "-y", "--fqdn", "--long", "--short", "--domain", "--ip-address", "--all-ip-addresses", "--all-fqdns", "--alias"], maxOperands: 0 }, + whoami: { onlyOptions: [], maxOperands: 0 }, + uptime: { onlyOptions: ["-p", "-s", "--pretty", "--since"], maxOperands: 0 }, + mount: { custom: checkMount }, + findmnt: { denyShort: { p: FOLLOW }, denyLong: { poll: FOLLOW }, valueShort: "oOtSTFNwdM", valueLong: ["output", "options", "types", "source", "target", "tab-file", "task", "timeout", "direction", "mountpoint"] }, + ps: {}, lsof: {}, + sensors: { denyShort: { s: "sensors -s writes chip settings and is not allowed." }, denyLong: { set: "sensors --set writes chip settings and is not allowed." } }, + // Netzwerk + ip: { custom: checkIp }, + ss: { + valueShort: "fAFN", valueLong: ["family", "query", "socket", "filter", "net"], + denyShort: { K: "Killing sockets is not allowed.", D: "ss -D writes a dump file and is not allowed." }, + denyLong: { kill: "Killing sockets is not allowed.", diag: "ss --diag writes a dump file and is not allowed." }, + }, + // Storage + zpool: { custom: subcommandOnly("zpool", ["status", "list", "get", "iostat", "history", "version"]) }, + zfs: { custom: subcommandOnly("zfs", ["list", "get", "version"]) }, + mdcmd: { custom: (args) => { if (args.length !== 1 || args[0] !== "status") fail("mdcmd only supports: mdcmd status"); } }, +}; + +export const READ_ONLY_PROGRAMS = Object.keys(POLICIES).sort(); + +const PROGRAM_DIRS = ["/bin", "/sbin", "/usr/bin", "/usr/sbin", "/usr/local/bin", "/usr/local/sbin"]; + +function normalizeProgram(raw: string): string { + const slash = raw.lastIndexOf("/"); + if (slash >= 0 && PROGRAM_DIRS.includes(raw.slice(0, slash))) return raw.slice(slash + 1); + return raw; +} + +// ── Generischer Options-Parser ─────────────────────────────────────────── + +function checkWithPolicy(program: string, args: string[], policy: Policy): void { + if (policy.custom) return policy.custom(args); + const operands: string[] = []; + const valueShort = policy.valueShort ?? ""; + const optionalValueShort = policy.optionalValueShort ?? ""; + const valueLong = new Set(policy.valueLong ?? []); + const denyShort = policy.denyShort ?? {}; + const denyLong = policy.denyLong ?? {}; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === "--") { operands.push(...args.slice(i + 1)); break; } + if (policy.onlyOptions && arg.startsWith("-") && arg !== "-") { + if (!policy.onlyOptions.includes(arg)) { + fail(policy.onlyOptions.length === 0 + ? `${program} accepts no arguments here.` + : `${program} option not allowed: ${arg}. Allowed: ${policy.onlyOptions.join(" ")}`); + } + continue; + } + if (arg.startsWith("--")) { + const eq = arg.indexOf("="); + const name = (eq >= 0 ? arg.slice(2, eq) : arg.slice(2)).toLowerCase(); + for (const [denied, message] of Object.entries(denyLong)) { + // GNU getopt_long akzeptiert eindeutige Präfixe: --cle == --clear + if (denied === name || (name.length > 0 && denied.startsWith(name))) fail(message); + } + if (eq < 0 && valueLong.has(name)) i += 1; + continue; + } + if (arg.startsWith("-") && arg.length > 1) { + for (let c = 1; c < arg.length; c++) { + const ch = arg[c]; + if (Object.prototype.hasOwnProperty.call(denyShort, ch)) fail(denyShort[ch]); + if (optionalValueShort.includes(ch)) break; + if (valueShort.includes(ch)) { + if (c === arg.length - 1) i += 1; // Wert ist das nächste Token + break; + } + } + continue; + } + operands.push(arg); + } + if (policy.maxOperands !== undefined && operands.length > policy.maxOperands) { + fail(policy.maxOperands === 0 + ? `${program} accepts no operands here (got: ${operands.join(" ")}).` + : program === "uniq" + ? "uniq treats a second operand as OUTPUT file. Pass at most one input file." + : `${program} accepts at most ${policy.maxOperands} operand(s).`); + } + policy.operands?.(operands); +} + +function checkFind(args: string[]): void { + const blocked = ["-delete", "-exec", "-execdir", "-ok", "-okdir", "-fprint", "-fprint0", "-fprintf", "-fls"]; + for (const arg of args) { + const lowered = arg.toLowerCase(); + if (blocked.some((b) => lowered === b || lowered.startsWith(b))) { + fail(`find action not allowed: ${arg}. Use -print/-printf/-ls; to act on files use unraid_system_shell.`); + } + } +} + +function checkMount(args: string[]): void { + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (arg === "-l" || arg === "--show-labels") continue; + if ((arg === "-t" || arg === "--types") && i + 1 < args.length) { i += 1; continue; } + if (arg.startsWith("--types=") || (arg.startsWith("-t") && arg.length > 2)) continue; + fail("mount is display-only here: use 'mount', 'mount -l' or 'mount -t TYPE'. For details use findmnt."); + } +} + +// iproute2: Objekte in der Reihenfolge, in der ip(8) Präfixe auflöst. +const IP_OBJECTS = ["address", "route", "rule", "neighbor", "neighbour", "link"]; +const IP_VERBS = new Set(["show", "list", "lst", "ls", "get", "help"]); +const IP_GLOBAL_OPTIONS = new Set([ + "-4", "-6", "-0", "-br", "-brief", "-j", "-json", "-p", "-pretty", "-s", "-stats", "-statistics", + "-d", "-details", "-c", "-color", "-o", "-oneline", "-h", "-human", "-human-readable", "-r", "-resolve", + "-a", "-all", "-t", "-timestamp", "-ts", "-tshort", +]); +function checkIp(args: string[]): void { + let i = 0; + while (i < args.length && args[i].startsWith("-")) { + const opt = args[i].toLowerCase().replace(/^--/, "-"); + const bare = opt.split("=")[0]; + if (!IP_GLOBAL_OPTIONS.has(bare) && !bare.startsWith("-color")) { + fail(`ip option not allowed: ${args[i]}. Allowed e.g.: -4 -6 -br -j -s -d -c`); + } + i += 1; + } + const rawObject = (args[i] ?? "").toLowerCase(); + const object = rawObject ? IP_OBJECTS.find((o) => o.startsWith(rawObject)) : undefined; + if (!object) fail("ip: use one of: ip addr | ip route | ip link | ip neigh | ip rule (optionally with show/list/get)."); + const verb = args[i + 1]; + if (verb === undefined || verb.startsWith("-")) return; + if (!IP_VERBS.has(verb.toLowerCase())) { + // "ip addr eth0" ist ungültig; "ip link s" wäre "set". Nur volle Leseverben. + fail(`ip ${object}: only read verbs are allowed (show, list, get); got "${verb}". Example: ip ${object} show`); + } +} + +function subcommandOnly(program: string, allowed: string[]) { + return (args: string[]) => { + const sub = args[0]; + if (!sub || !allowed.includes(sub)) { + fail(`${program}: allowed subcommands: ${allowed.join(", ")} (e.g. ${program} ${allowed[0]})`); + } + }; +} + +// ── Pfade mit Zugangsdaten ─────────────────────────────────────────────── + +function configFile(): string { + return `${process.env["MUA_CONFIG_DIR"] ?? "/boot/config/plugins/mua"}/mua.conf`; +} +function adminTokenFile(): string { + return process.env["MUA_ADMIN_TOKEN_FILE"] ?? "/var/run/mua-admin.token"; +} + +interface DenyRule { test: (path: string) => boolean; reason: string } +const DENY_RULES: DenyRule[] = [ + { test: (p) => /^\/etc\/g?shadow-?$/.test(p) || p === "/boot/config/shadow", + reason: "contains password hashes. For user info read /etc/passwd or /etc/group." }, + { test: (p) => p === "/boot/config/smbpasswd" || p.startsWith("/var/lib/samba/private/"), + reason: "contains Samba password hashes. Use unraid_share_inspect for SMB settings." }, + { test: (p) => /^(id_[a-z0-9_]+|ssh_host_[a-z0-9_]+_key)$/i.test(basename(p)), + reason: "is an SSH private key. Public keys (*.pub) and authorized_keys are readable." }, + { test: (p) => p === configFile() || p === adminTokenFile() + || p === resolveCandidate(configFile()) || p === resolveCandidate(adminTokenFile()), + reason: "holds MUA credentials." }, + { test: (p) => /^\/proc\/(?:\d+|self|thread-self)(?:\/task\/\d+)?\/(?:environ|mem)$/.test(p) || p === "/proc/kcore", + reason: "exposes process memory/environment (often secrets). Use unraid_docker_inspect for container settings (redacted)." }, + { test: (p) => /^\/var\/lib\/docker\/containers\/[^/]+\/config\.v2\.json$/.test(p), + reason: "contains container environment variables in plaintext. Use unraid_docker_inspect (secrets redacted)." }, +]; + +function resolveCandidate(raw: string): string { + const absolute = raw.startsWith("/") ? raw : resolvePath("/", raw); + try { + if (existsSync(absolute)) return realpathSync.native(absolute); + } catch { /* fall through */ } + return resolvePath(absolute); +} + +function pathCandidates(arg: string): string[] { + const out: string[] = []; + if (arg === "" || arg === "-") return out; + if (arg.startsWith("-")) { + const eq = arg.indexOf("="); + if (eq >= 0 && arg.length > eq + 1) out.push(arg.slice(eq + 1)); + const slash = arg.indexOf("/"); + if (slash > 0) out.push(arg.slice(slash)); + return out; + } + out.push(arg); + return out; +} + +export function checkSensitivePaths(args: string[]): void { + for (const arg of args) { + for (const candidate of pathCandidates(arg)) { + if (!candidate.includes("/") && !existsSync(resolvePath("/", candidate))) continue; + const resolved = resolveCandidate(candidate); + const rule = DENY_RULES.find((r) => r.test(resolved)); + if (rule) fail(`Access to ${resolved} is blocked: it ${rule.reason}`); + } + } +} + +// ── Tokenizer für Befehlszeilen ────────────────────────────────────────── + +interface Word { value: string; glob: boolean } +type Connector = ";" | "&&" | "||"; +export interface CommandSpec { program: string; args: string[] } +interface Step { connector: Connector; pipeline: CommandSpec[] } + +const MAX_COMMANDS = 8; +const MAX_PIPELINE = 4; +const MAX_COMMAND_LINE = 8192; + +/** Zerlegt eine Befehlszeile in Schritte und Pipelines (ohne Shell). */ +export function parseCommandLine(line: string): { connector: Connector; pipeline: Word[][] }[] { + if (line.length > MAX_COMMAND_LINE) fail(`command must not exceed ${MAX_COMMAND_LINE} characters`); + const steps: { connector: Connector; pipeline: Word[][] }[] = []; + let pipeline: Word[][] = []; + let words: Word[] = []; + let current = ""; + let inWord = false; + let glob = false; + let quotedAny = false; + let connector: Connector = ";"; + + const endWord = () => { + if (inWord) { + if (!quotedAny && current.startsWith("~") && (current.length === 1 || current[1] === "/")) { + current = "/root" + current.slice(1); + } + words.push({ value: current, glob }); + } + current = ""; inWord = false; glob = false; quotedAny = false; + }; + const endCommand = () => { + endWord(); + if (words.length > 0) pipeline.push(words); + words = []; + }; + const endStep = (next: Connector) => { + endCommand(); + if (pipeline.length > 0) steps.push({ connector, pipeline }); + pipeline = []; + connector = next; + }; + const noShell = (what: string) => fail( + `Not supported here: ${what} (no shell interpreter). Use program options instead, or unraid_system_shell for real shell scripts.`, + ); + + for (let i = 0; i < line.length; i++) { + const ch = line[i]; + if (ch === "\\") { + if (i + 1 < line.length) { + if (line[i + 1] === "\n") { i += 1; continue; } + current += line[++i]; inWord = true; + } + continue; + } + if (ch === "'") { + const end = line.indexOf("'", i + 1); + if (end < 0) fail("Unterminated single quote"); + current += line.slice(i + 1, end); inWord = true; quotedAny = true; i = end; + continue; + } + if (ch === '"') { + let j = i + 1; + for (; j < line.length && line[j] !== '"'; j++) { + const c = line[j]; + if (c === "\\" && j + 1 < line.length && '"\\$`'.includes(line[j + 1])) { current += line[++j]; continue; } + if (c === "`") noShell("Command substitution (`...`)"); + if (c === "$" && /[({A-Za-z_0-9@*#?$!-]/.test(line[j + 1] ?? "")) noShell("Variables and $(...)"); + current += c; + } + if (j >= line.length) fail("Unterminated double quote"); + inWord = true; quotedAny = true; i = j; + continue; + } + if (ch === " " || ch === "\t") { endWord(); continue; } + if (ch === "\n" || ch === "\r") { endStep(";"); continue; } + if (ch === "#" && !inWord) break; // Kommentar + if (ch === "`") noShell("Command substitution (`...`)"); + if (ch === "$" && /[({A-Za-z_0-9@*#?$!-]/.test(line[i + 1] ?? "")) noShell("Variables and $(...)"); + if (ch === ";") { endStep(";"); continue; } + if (ch === "&") { + if (line[i + 1] === "&") { endStep("&&"); i += 1; continue; } + noShell("Background execution (&)"); + } + if (ch === "|") { + if (line[i + 1] === "|") { endStep("||"); i += 1; continue; } + endCommand(); + if (pipeline.length === 0) fail("Pipe without a command before it"); + continue; + } + if (ch === ">" || ch === "<") { + // Nur "2>&1" und "2>/dev/null" werden toleriert und ignoriert. + const fd = inWord && /^\d+$/.test(current) && !quotedAny ? current : ""; + let j = i + 1; + if (line[j] === ">") j += 1; + while (line[j] === " ") j += 1; + let target = ""; + if (line[j] === "&") target += line[j++]; + while (j < line.length && !" \t\n;|&".includes(line[j])) target += line[j++]; + if (ch === ">" && fd === "2" && (target === "&1" || target === "/dev/null")) { + current = ""; inWord = false; glob = false; quotedAny = false; + i = j - 1; + continue; + } + noShell(ch === ">" ? "Output redirection (>)" : "Input redirection (<); pass the file as an argument"); + } + if (ch === "*" || ch === "?" || ch === "[") glob = true; + current += ch; inWord = true; + } + endStep(";"); + return steps; +} + +// ── Glob-Expansion für absolute Pfade ──────────────────────────────────── + +const MAX_GLOB_MATCHES = 500; + +function expandGlob(pattern: string): string[] { + const parts = pattern.split("/"); + const firstGlob = parts.findIndex((p) => /[*?[]/.test(p)); + if (firstGlob < 0) return [pattern]; + const base = parts.slice(0, firstGlob).join("/") || "/"; + const rest = parts.slice(firstGlob).join("/"); + if (!rest || !existsSync(base)) return [pattern]; + const matches: string[] = []; + try { + for (const match of new Bun.Glob(rest).scanSync({ cwd: base, absolute: true, onlyFiles: false, followSymlinks: false })) { + matches.push(match); + if (matches.length > MAX_GLOB_MATCHES) { + fail(`Glob ${pattern} matches more than ${MAX_GLOB_MATCHES} paths; narrow it down.`); + } + } + } catch (error) { + if (error instanceof ReadOnlyError) throw error; + return [pattern]; + } + // Wie bash ohne nullglob: kein Treffer → Muster unverändert lassen. + return matches.length > 0 ? matches.sort() : [pattern]; +} + +function expandArgs(words: Word[]): string[] { + const out: string[] = []; + for (const w of words) { + if (w.glob && w.value.startsWith("/")) out.push(...expandGlob(w.value)); + else out.push(w.value); + } + return out; +} + +// ── Plan erstellen ─────────────────────────────────────────────────────── + +export interface ReadOnlyInput { + command?: unknown; + program?: unknown; + args?: unknown; +} + +function validateCommand(spec: CommandSpec): CommandSpec { + let program = normalizeProgram(spec.program); + let args = spec.args; + if (program === "sudo") { + // MUA läuft bereits als root. + if (args.length === 0) fail("sudo without a command"); + program = normalizeProgram(args[0]); + args = args.slice(1); + } + const policy = POLICIES[program]; + if (!policy) { + fail(`Program not allowed in read-only mode: ${program}. Allowed: ${READ_ONLY_PROGRAMS.join(", ")}. ` + + "For anything else use unraid_system_shell (if enabled)."); + } + if (args.length > 256 || args.some((a) => typeof a !== "string" || a.length > 4096)) { + fail("Invalid or excessive arguments (max 256 arguments, 4096 characters each)"); + } + checkWithPolicy(program, args, policy); + checkSensitivePaths(args); + return { program, args }; +} + +function stringArgs(raw: unknown): Word[] | null { + if (raw === undefined || raw === null) return []; + if (typeof raw === "string") return null; // als Befehlszeile behandeln + if (!Array.isArray(raw) || raw.some((a) => typeof a !== "string")) fail("args must be an array of strings (or one string)"); + return (raw as string[]).map((value) => ({ value, glob: /[*?[]/.test(value) })); +} + +/** Wandelt die flexible Tool-Eingabe in einen geprüften Ausführungsplan um. */ +export function planReadOnly(input: ReadOnlyInput): { steps: Step[]; display: string } { + const command = typeof input.command === "string" ? input.command.trim() : ""; + const program = typeof input.program === "string" ? input.program.trim() : ""; + let line = ""; + let direct: Word[] | null = null; + + if (command) { + line = command; + } else if (program) { + const argWords = stringArgs(input.args); + if (argWords === null) line = `${program} ${String(input.args)}`; + else if (/[\s|;&<>]/.test(program)) line = argWords.length ? `${program} ${argWords.map((w) => shellQuote(w.value)).join(" ")}` : program; + else direct = [{ value: program, glob: false }, ...argWords]; + } else { + fail("Provide `command` (e.g. \"tail -n 50 /var/log/syslog\") or `program` with optional `args`."); + } + + const rawSteps = direct ? [{ connector: ";" as Connector, pipeline: [direct] }] : parseCommandLine(line); + if (rawSteps.length === 0) fail("Empty command"); + let total = 0; + const steps: Step[] = rawSteps.map((step) => { + if (step.pipeline.length > MAX_PIPELINE) fail(`At most ${MAX_PIPELINE} commands per pipeline`); + const pipeline = step.pipeline.map((words) => { + total += 1; + const expanded = expandArgs(words); + return validateCommand({ program: expanded[0], args: expanded.slice(1) }); + }); + return { connector: step.connector, pipeline }; + }); + if (total > MAX_COMMANDS) fail(`At most ${MAX_COMMANDS} commands per call`); + return { steps, display: direct ? displayCommand(steps[0].pipeline) : line }; +} + +function shellQuote(value: string): string { + return /^[A-Za-z0-9_./:=,+@%-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`; +} +function displayCommand(pipeline: CommandSpec[]): string { + return pipeline.map((c) => [c.program, ...c.args].map(shellQuote).join(" ")).join(" | "); +} + +// ── Ausführung ─────────────────────────────────────────────────────────── + +interface PipelineResult { + exitCode: number; + stdout: string; + stderr: string; + truncated: boolean; + timedOut: boolean; +} + +/** Single-Quote-Escaping: Innerhalb von '…' expandiert /bin/sh nichts. */ +function strictQuote(value: string): string { + return `'${value.replace(/'/g, `'\\''`)}'`; +} + +async function runPipeline( + pipeline: CommandSpec[], + deadline: number, + maxStdout: number, + maxStderr: number, +): Promise { + // Einzelbefehl: direkt als argv. Pipeline: echte OS-Pipes über /bin/sh, + // wobei JEDES Token vorher geprüft und strikt single-quoted ist. Die Shell + // sieht damit nur Literale und `|` — keine Expansion, keine Umleitung. + // (JS-Streams zwischen Prozessen führen bei frühem Ende, z.B. `head`, zu + // unbehandeltem EPIPE in Bun.) + const argv = pipeline.length === 1 + ? [pipeline[0].program, ...pipeline[0].args] + : ["/bin/sh", "-c", pipeline.map((c) => [c.program, ...c.args].map(strictQuote).join(" ")).join(" | ")]; + let proc: GroupProcess; + try { + proc = spawnGroup(argv, { stdin: "ignore", stdout: "pipe", stderr: "pipe" }); + } catch { + return fail(`${pipeline[0].program} is not installed on this host.`); + } + const kill = () => killProcessGroup(proc.pid); + const abort = new AbortController(); + const stdoutPromise = readProcessOutput(proc.stdout as ReadableStream, maxStdout, { signal: abort.signal }); + const stderrPromise = readProcessOutput(proc.stderr as ReadableStream, maxStderr, { signal: abort.signal }) + .catch(() => ({ text: "", truncated: false, bytesRead: 0 })); + // Ausgabe-Limit erreicht → Prozessgruppe beenden (wie bisher). + void stdoutPromise.then((r) => { if (r.truncated) kill(); }).catch(() => {}); + + let timedOut = false; + const timer = setTimeout(() => { timedOut = true; kill(); }, Math.max(1, deadline - Date.now())); + try { + const exit = await proc.exited; + // Nach Prozessende nur kurz auf noch offene Pipes (Enkel) warten. + const grace = setTimeout(() => { kill(); abort.abort(); }, 2000); + const [out, err] = await Promise.all([ + stdoutPromise.catch(() => ({ text: "", truncated: true, bytesRead: 0 })), + stderrPromise, + ]); + clearTimeout(grace); + let stderr = err.text.trim(); + if (pipeline.length > 1 && exit === 127 && /not found/.test(stderr)) { + stderr = `A program in this pipeline is not installed on this host. ${stderr}`; + } + return { + exitCode: timedOut ? 124 : typeof exit === "number" ? exit : 137, + stdout: out.text, + stderr, + truncated: out.truncated || err.truncated, + timedOut, + }; + } finally { + clearTimeout(timer); + abort.abort(); + } +} + +export function redactReadOnlyOutput(text: string): string { + return redactCredentialFormats(text); +} + +/** + * Führt einen Readonly-Plan aus. + * `sanitize` = sanitizeLogOutput aus helpers (ANSI, Secrets, Längenlimit). + */ +export async function runReadOnly( + input: ReadOnlyInput, + timeoutSec: number, + maxOutputChars: number, + sanitize: (text: string, max: number) => string, +): Promise { + const { steps, display } = planReadOnly(input); + const deadline = Date.now() + timeoutSec * 1000; + const maxStderr = Math.min(8_000, maxOutputChars); + const multi = steps.length > 1; + const results: { command: string; exit_code: number }[] = []; + let stdout = ""; + let stderr = ""; + let truncated = false; + let timedOut = false; + let exitCode = 0; + let ran = 0; + + for (const step of steps) { + if (ran > 0 && ((step.connector === "&&" && exitCode !== 0) || (step.connector === "||" && exitCode === 0))) continue; + if (Date.now() >= deadline) { timedOut = true; break; } + const budget = Math.max(1_000, maxOutputChars - stdout.length); + const result = await runPipeline(step.pipeline, deadline, budget, maxStderr); + ran += 1; + exitCode = result.exitCode; + const label = displayCommand(step.pipeline); + results.push({ command: label, exit_code: result.exitCode }); + const text = result.stdout.replace(/\s+$/, ""); + stdout += multi ? `$ ${label}\n${text}${text ? "\n" : ""}` : text; + if (result.stderr) stderr += (stderr ? "\n" : "") + (multi ? `[${label}] ${result.stderr}` : result.stderr); + truncated ||= result.truncated; + if (result.timedOut) { timedOut = true; break; } + if (stdout.length >= maxOutputChars) { truncated = true; break; } + } + + const clean = (text: string, max: number) => sanitize(redactReadOnlyOutput(text.trim()), max); + const lastProgram = steps[steps.length - 1]?.pipeline.at(-1)?.program; + const noMatch = !timedOut && exitCode === 1 && lastProgram === "grep" && stdout.trim() === "" && stderr.trim() === ""; + const response: Record = { + exit_code: exitCode, + stdout: clean(stdout, maxOutputChars), + stderr: clean(stderr, maxStderr), + truncated, + mode: "read-only", + }; + if (input.command !== undefined || multi || steps[0].pipeline.length > 1) response["ran"] = display; + if (multi) response["steps"] = results; + if (noMatch) { response["no_match"] = true; response["note"] = "grep found no matches (exit 1 is not an error)."; } + if (timedOut) { + response["timed_out"] = true; + response["note"] = `Stopped after ${timeoutSec}s; output above is partial. Narrow the command or raise timeout_seconds (max 120).`; + } + if (truncated && !timedOut) { + response["note"] = "Output was cut at the limit. Narrow it (grep, head -n, tail -n) or raise max_output_chars (max 30000)."; + } + return JSON.stringify(response); +} diff --git a/src/redact.ts b/src/redact.ts new file mode 100644 index 0000000..ab2d03e --- /dev/null +++ b/src/redact.ts @@ -0,0 +1,47 @@ +/** + * MUA — Mikes Unraid Agent + * redact.ts — Schwärzen von Zugangsdaten in Tool-Ausgaben. + * + * Zwei Stufen: + * - redactKnownSecrets: Die konkreten Werte von MUA-API-Key und Admin-Token + * tauchen in KEINER Tool-Ausgabe auf (auch nicht in der Root-Shell). + * - redactCredentialFormats: Format-basierte Schwärzung für die Readonly- + * Werkzeuge (private PEM-Schlüssel, Passwort-Hashes, WireGuard-Keys, + * Samba-Hashes). Die Root-Shell bleibt bewusst ungefiltert, damit echte + * Administration (z.B. Zertifikate erzeugen/kopieren) nicht behindert wird. + */ + +const knownSecrets = new Set(); + +/** Registriert einen Wert, der niemals in Ausgaben erscheinen darf. */ +export function registerSecret(value: string | undefined | null): void { + if (typeof value === "string" && value.length >= 16) knownSecrets.add(value); +} + +export function forgetSecret(value: string | undefined | null): void { + if (typeof value === "string") knownSecrets.delete(value); +} + +export function redactKnownSecrets(text: string): string { + let result = text; + for (const secret of knownSecrets) { + if (result.includes(secret)) result = result.split(secret).join("[REDACTED:mua-secret]"); + } + return result; +} + +const PEM_PRIVATE_KEY = + /-----BEGIN ((?:RSA |EC |DSA |OPENSSH |ENCRYPTED )?PRIVATE KEY)-----[\s\S]*?(?:-----END \1-----|$)/g; +// crypt(3)-Hashes: $1$ (MD5), $2a/b/y$ (bcrypt), $5$/$6$ (SHA), $y$/$gy$ (yescrypt), $7$ (scrypt) +const CRYPT_HASH = /\$(?:1|2[abxy]?|5|6|7|y|gy)\$[./A-Za-z0-9$=,+-]{8,}/g; +const WIREGUARD_KEY = /\b((?:PrivateKey|PresharedKey)\s*=\s*)\S+/gi; +// smbpasswd: user:uid:LMHASH:NTHASH:... +const SMB_HASH = /(:)[0-9A-F]{32}(?=:)/g; + +export function redactCredentialFormats(text: string): string { + return text + .replace(PEM_PRIVATE_KEY, (_m, kind: string) => `-----BEGIN ${kind}----- [REDACTED] -----END ${kind}-----`) + .replace(CRYPT_HASH, "[REDACTED:hash]") + .replace(WIREGUARD_KEY, "$1[REDACTED]") + .replace(SMB_HASH, "$1[REDACTED]"); +} diff --git a/src/tls.test.ts b/src/tls.test.ts index bf07021..e380517 100644 --- a/src/tls.test.ts +++ b/src/tls.test.ts @@ -53,7 +53,8 @@ test("Unraid source can be saved without manual paths and starts real verified H } finally { await app.stop(); } const secure = await start(saved, { MUA_UNRAID_ROOT: layout }); try { - expect((await bundleRequest(secure.port, "/health", fixture.publicCert)).data.version).toBe(expectedVersion); + expect((await bundleRequest(secure.port, "/health", fixture.publicCert)).data.version).toBeUndefined(); + expect((await bundleRequest(secure.port, "/health", fixture.publicCert, undefined, testToken)).data.version).toBe(expectedVersion); const initialized = await bundleRequest(secure.port, "/mcp", fixture.publicCert, { jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-03-26", capabilities: {}, clientInfo: { name: "unraid-mode", version: "1" } } }, testToken); expect(initialized.status).toBe(200); @@ -184,7 +185,9 @@ for (const keyFirst of [true, false]) { try { const health = await bundleRequest(app.port, "/health", fixture.publicCert); expect(health.status).toBe(200); - expect(health.data.version).toBe(expectedVersion); + expect(health.data.status).toBe("ok"); + expect(health.data.version).toBeUndefined(); + expect((await bundleRequest(app.port, "/health", fixture.publicCert, undefined, testToken)).data.version).toBe(expectedVersion); const rpc = async (id: number, method: string, params: unknown = {}) => bundleRequest(app.port, "/mcp", fixture.publicCert, { jsonrpc: "2.0", id, method, params }, testToken); const initialized = await rpc(1, "initialize", { protocolVersion: "2025-03-26", capabilities: {}, diff --git a/src/tools.ts b/src/tools.ts index 1289120..e789195 100644 --- a/src/tools.ts +++ b/src/tools.ts @@ -24,7 +24,8 @@ import { startShellJob, shellJobStatus, cleanupShellJob, - runReadOnlyCommand, + cancelShellJob, + runReadOnlyInput, runStatusHelper, searchCommunityApps, previewCommunityAppInstall, @@ -32,6 +33,7 @@ import { toolboxStatus, toolboxExec, } from "./helpers"; +import { READ_ONLY_PROGRAMS } from "./readonly"; export interface ToolDef { name: string; @@ -51,6 +53,7 @@ const CRITICAL_TOOLS = new Set([ "unraid_system_shell", "unraid_toolbox_exec", "unraid_system_job_start", + "unraid_system_job_cancel", "unraid_system_job_cleanup", "unraid_ca_install", "unraid_share_apply", @@ -665,47 +668,42 @@ export const TOOLS: ToolDef[] = [ { name: "unraid_system_shell_readonly", description: - "Run one strictly allowlisted read-only command without a shell interpreter. Use it as a bounded diagnostic fallback, not for broad inventories: start from a concrete notification or failing component, locate the newest exact artifact, then use grep/tail/stat on that file. Prefer tail/grep over cat, and targeted paths over recursive find or large ls output. Never read a complete configuration or directory tree unless the user explicitly needs it. Output defaults to 12000 characters and is always server-side bounded. Pipes, redirects, command chaining and mutating options are impossible or rejected.", + "Run read-only diagnostic commands on the Unraid host (safe, no root shell). " + + "Simplest: pass one command line in `command`, e.g. \"tail -n 100 /var/log/syslog\", " + + "\"ps aux | grep -i plex\", \"df -h; free -m\", \"grep -i error /var/log/*.log\". " + + "Supports quotes, pipes between allowed programs, ; && || and globs in absolute paths. " + + "No redirects, variables or $(). Prefer targeted reads (grep, tail -n) over whole files. " + + `Allowed programs: ${READ_ONLY_PROGRAMS.join(" ")}.`, inputSchema: { type: "object", properties: { - program: { - type: "string", - enum: [ - "cat", "date", "df", "dmesg", "du", "file", "find", "free", "grep", - "head", "hostname", "id", "ip", "lsof", "ls", "lsblk", "lspci", "mount", - "ps", "readlink", "realpath", "sha256sum", "ss", "stat", "tail", "uname", - "uptime", "wc", "whoami", - ], - description: "Allowlisted read-only program", - }, + command: str("Full command line, e.g. \"tail -n 50 /var/log/syslog | grep -i error\". Use this OR program+args."), + program: str("Single program name (alternative to command), e.g. \"tail\""), args: { type: "array", items: { type: "string", maxLength: 4096 }, - maxItems: 64, - description: "Argument vector; passed directly without /bin/sh", + maxItems: 256, + description: "Arguments for program, passed literally (no shell)", }, timeout_seconds: int("Timeout in seconds (1-120, default 30)"), - max_output_chars: int("Maximum combined diagnostic output retained server-side (1000-30000, default 12000). Keep the default or lower it for routine diagnosis; raise it only when the user explicitly needs a larger bounded result."), + max_output_chars: int("Output limit (1000-30000, default 12000). Raise only if really needed."), }, - required: ["program"], additionalProperties: false, }, handler: (a) => { - const program = (a["program"] as string) ?? ""; - const rawArgs = a["args"] ?? []; - if (!Array.isArray(rawArgs) || rawArgs.some((arg) => typeof arg !== "string")) { - throw new Error("args must be an array of strings"); - } const timeout = Number(a["timeout_seconds"] ?? 30); - if (timeout < 1 || timeout > 120) { + if (!Number.isFinite(timeout) || timeout < 1 || timeout > 120) { throw new Error("timeout_seconds must be between 1 and 120"); } const maxOutputChars = Number(a["max_output_chars"] ?? 12_000); if (!Number.isInteger(maxOutputChars) || maxOutputChars < 1_000 || maxOutputChars > 30_000) { throw new Error("max_output_chars must be between 1000 and 30000"); } - return runReadOnlyCommand(program, rawArgs as string[], timeout, maxOutputChars); + return runReadOnlyInput( + { command: a["command"], program: a["program"], args: a["args"] }, + timeout, + maxOutputChars, + ); }, }, { @@ -758,6 +756,18 @@ export const TOOLS: ToolDef[] = [ }, handler: (a) => shellJobStatus(String(a["job_id"] ?? "")), }, + { + name: "unraid_system_job_cancel", + description: + "CRITICAL: Stop a running asynchronous Unraid shell job by job_id, including every process it started. Use it when a job hangs or was started by mistake.", + inputSchema: { + type: "object", + properties: { job_id: str("Job identifier returned by unraid_system_job_start") }, + required: ["job_id"], + additionalProperties: false, + }, + handler: (a) => cancelShellJob(String(a["job_id"] ?? "")), + }, { name: "unraid_system_job_cleanup", description: