diff --git a/README.md b/README.md index 9bd40ee..a571999 100644 --- a/README.md +++ b/README.md @@ -99,10 +99,10 @@ Oder manuell: ```bash # .txz von Gitea laden -curl -O https://git.casaderoll.de/michael/MUA-Mikes-Unraid-Agent/raw/branch/main/dist/mua-2026.10.11.r030-x86_64-1.txz +curl -O https://git.casaderoll.de/michael/MUA-Mikes-Unraid-Agent/raw/branch/main/dist/mua-2026.10.12.r031-x86_64-1.txz # Installieren -upgradepkg --install-new mua-2026.10.11.r030-x86_64-1.txz +upgradepkg --install-new mua-2026.10.12.r031-x86_64-1.txz ``` ### 2. Service starten @@ -380,3 +380,9 @@ shasum -a 256 dist/mua-*.txz 6. `xmllint --noout plugin/mua.plg` 7. `git add -A && git commit -m "rNNN: ..." && git push` 8. Auf Unraid: **Plugins → MUA → Update** + +## Shell-Ausführungsort und Dateitransfer + +[r031-Fix, Prüfungen, Installation/Restore und Transfergrenzen](docs/SHELL-CWD-FIX.md). +MUA läuft direkt auf dem Unraid-Host. Verbindungstest trennt MCP-Transport/Auth-Dispatch +von lokalem Prozessstart; Shell und Dienststart verwenden das stabile cwd `/`. diff --git a/docs/SHELL-CWD-FIX.md b/docs/SHELL-CWD-FIX.md new file mode 100644 index 0000000..7f917d9 --- /dev/null +++ b/docs/SHELL-CWD-FIX.md @@ -0,0 +1,67 @@ +# r031: shell spawn and connection diagnostics + +Confirmed on 2026-10-12 before any change: +- MUA r030 is `/usr/local/bin/mua`, host plugin, process root `/`, not a container. +- `/proc//cwd` = `/tmp/mua-storage-units-check (deleted)`. +- `/proc//root/bin/sh` exists, symlink to bash. +- Authenticated MCP: shell and connection-test reproduce ENOENT posix_spawn /bin/sh; + read-only hostname succeeds on HomeServer. + +Cause: r030 was started from the temporary installation directory, which was +later removed. runLocal/runShell inherited this deleted cwd, causing Bun's spawn +to fail before launching the existing interpreter. runReadOnlyCommand already +used explicit cwd `/`. This is not missing shell, container/SSH misrouting or +failed host connectivity. Local subprocess regression reproduces the same ENOENT. + +Minimal fix: +- runLocal/runShell set cwd `/`, like the read-only executor. +- rc.mua starts daemon from `/`, independent of install/update caller directory. +- shell response adds execution metadata (local process host, Unraid marker, + stable cwd/interpreter). Exit code/stdout/stderr remain present. +- controlled error JSON reports spawn/execution phase, system error code or + timeout, interpreter existence and host, omitting command and raw exception + text. Local process failures explicitly are not connection failures. +- connection test now returns structured JSON with transport arrival, + authentication-before-dispatch (SSH login not applicable), and command-execution + result separately. Handler arrival is not a new network probe from the client. + Transport/auth errors before dispatch remain HTTP/network errors; the tool + cannot diagnose an HTTP request which never reaches it. + +No new permissions, mount, socket, transport, SSH setup or enabled tools. +Command validation, API auth, risk classes and timeout checks retained. +Read-only shell unchanged. No foreign containers restarted. + +## File transfer: existing abilities and limits + +Actual tool list has unraid_files_inventory, which lists names only; no dedicated +upload/download/copy tool. Read-only shell cannot copy files. The unrestricted +shell can perform explicitly authorized host copies using existing host access: +Open-Terminal `/home/user/` is already bind-mounted from +`/mnt/nvme-storage/appdata/Open-Terminal/workspace/`. +A file there can be copied to the existing `/mnt/user/Musik/` after +checking source/destination and overwrite policy. No copy was performed in tests. +This mapping does not cover arbitrary terminal paths: files elsewhere inside the +container would need an explicitly authorized host `docker cp` or a different +existing mapping. No direct access to the MCP client's local files, no generic +remote SSH/SFTP upload bridge. Paths/data must never be invented or passed through +model context unnecessarily. Existing root-shell permission required and unchanged. + +## Validation, installation and restore + +23 Bun tests (82 assertions), including inherited-deleted-cwd reproduction and +successful fixed execution, spawn error diagnostics/secret omission, command error +versus transport, existing safety/concurrency tests. TypeScript and rc.mua syntax +checks. Live `scripts/verify-live-shell.php`: exclusively hostname and existence +of `/mnt/user/Musik`, connection identity, existing read-only hostname, unauthenticated +401 versus authenticated transport, and daemon cwd `/`. + +Package release r031; SHA256 and plugin manifest validation. Install only MUA +when health tool_calls.active is zero; start service from `/`. Configuration, +API key and tool permissions retained. Remove temporary installation artifacts +only after live acceptance. Host/media/share data untouched. + +Restore: existing r030 package remains in dist and on Unraid. After confirming +no active MUA calls, run `cd /` then upgradepkg with the prior package and restart +rc.mua from `/`. Restore the matching prior plugin manifest from Git. Restoring +r030 removes the new diagnostics; shell calls can fail again if a future daemon +start inherits a deleted directory. No configuration/credential rollback needed. diff --git a/mcp/helpers.php b/mcp/helpers.php index 0f4dd69..b0e5afc 100644 --- a/mcp/helpers.php +++ b/mcp/helpers.php @@ -10,7 +10,7 @@ error_reporting(E_ALL); ini_set('display_errors', 0); // Fehler werden als JSON-RPC-Error zurückgegeben, nicht als HTML -const MUA_VERSION = '2026.10.11.r030'; +const MUA_VERSION = '2026.10.12.r031'; const MUA_SERVER_NAME = 'mua'; /** diff --git a/mcp/server.php b/mcp/server.php index 6b40e25..150fe20 100644 --- a/mcp/server.php +++ b/mcp/server.php @@ -21,7 +21,7 @@ const MUA_PORT = 3002; const MUA_BIND = '0.0.0.0'; const MUA_SESSION_TTL = 3600; // Sekunden const MUA_SERVER_NAME = 'mua'; -const MUA_VERSION = '2026.10.11.r030'; +const MUA_VERSION = '2026.10.12.r031'; // ── Session-Management (in-memory) ─────────────────────────────────────── $sessions = []; // session_id => ['created' => time, 'initialized' => bool] diff --git a/package.json b/package.json index ea9536f..91a4e24 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "mua", - "version": "2026.10.11.r030", + "version": "2026.10.12.r031", "description": "Mikes Unraid Agent - MCP over HTTP (Streamable HTTP) for Unraid", "type": "module", "main": "src/index.ts", diff --git a/plugin/mua.plg b/plugin/mua.plg index 96ae12f..50f97a2 100644 --- a/plugin/mua.plg +++ b/plugin/mua.plg @@ -2,13 +2,13 @@ - + - - + + ]> +### 2026.10.12.r031 +- Setzt Shell-Prozesse und Dienststart auf das stabile Arbeitsverzeichnis /; behebt ENOENT bei gelöschtem Installationsordner. +- Verbindungstest trennt MCP-Transport/Auth-Dispatch von lokaler Befehlsausführung; Fehler nennen Ort, Phase und kontrollierte Ursache ohne Befehle oder Secrets. +- Ergänzt Regressionstests für gelöschtes cwd und getrennte Prozessfehler. + ### 2026.10.11.r030 - Konvertiert disks.ini-Kapazität, belegt und frei gezielt von KiB in Bytes. RAM und bereits bytebasierte Quellen bleiben unverändert. - Regressionstest und Live-Abgleich mit df -B1 und blockdev dokumentiert. @@ -181,7 +186,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 39062e0..ba7fd80 100644 --- a/plugin/plugin.json +++ b/plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "mua", "author": "Michael", - "version": "2026.10.11.r030", + "version": "2026.10.12.r031", "minver": "7.0.0", "pluginDirectory": "/usr/local/emhttp/plugins/mua", "configDirectory": "/boot/config/plugins/mua", diff --git a/scripts/rc.mua b/scripts/rc.mua index 39a93fb..6ac30a9 100644 --- a/scripts/rc.mua +++ b/scripts/rc.mua @@ -24,7 +24,7 @@ start() { # Config-Verzeichnis sicherstellen (für API-Key) mkdir -p /boot/config/plugins/mua # Server starten (detached) - MUA_PORT=$PORT nohup "$DAEMON" >> "$LOGFILE" 2>&1 & + (cd / && exec env MUA_PORT="$PORT" nohup "$DAEMON") >> "$LOGFILE" 2>&1 & echo $! > "$PIDFILE" sleep 1 if kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then diff --git a/scripts/verify-live-shell.php b/scripts/verify-live-shell.php new file mode 100644 index 0000000..df8f5ce --- /dev/null +++ b/scripts/verify-live-shell.php @@ -0,0 +1,15 @@ +true,CURLOPT_POST=>true,CURLOPT_HTTPHEADER=>$headers,CURLOPT_POSTFIELDS=>json_encode(['jsonrpc'=>'2.0','id'=>1,'method'=>$method,'params'=>$params]),CURLOPT_TIMEOUT=>30]);$body=curl_exec($c);$code=curl_getinfo($c,CURLINFO_HTTP_CODE);$errno=curl_errno($c);curl_close($c);need($errno===0,'Local test transport failed');return [$code,json_decode($body,true)];} +function rpc($method,$params){[$code,$r]=request($method,$params);need($code===200&&isset($r['result'])&&empty($r['result']['isError']),'Authenticated MCP request failed');return $r['result'];} +[$unauth]=request('initialize',(object)[],false);need($unauth===401,'Unauthenticated request must be rejected'); +$i=rpc('initialize',['protocolVersion'=>'2025-03-26','capabilities'=>(object)[],'clientInfo'=>['name'=>'read-only-shell-acceptance','version'=>'1']]);need($i['serverInfo']['version']==='2026.10.12.r031','Expected loaded r031'); +$list=rpc('tools/list',(object)[]);$names=array_column($list['tools'],'name');foreach(['unraid_system_shell','unraid_system_shell_readonly','unraid_system_connection_test'] as $name)need(in_array($name,$names,true),'Required tool disabled; do not change permission'); +function tool($name,$args){$r=rpc('tools/call',['name'=>$name,'arguments'=>$args]);return json_decode($r['content'][0]['text'],true);} +$host=trim(shell_exec('hostname'));$readonly=tool('unraid_system_shell_readonly',['program'=>'hostname']);need($readonly['exit_code']===0&&$readonly['stdout']===$host,'Read-only host differs'); +$shell=tool('unraid_system_shell',['command'=>'hostname; if test -d /mnt/user/Musik; then printf "Musik_exists\n"; else exit 3; fi','timeout_seconds'=>15]);need($shell['exit_code']===0&&$shell['stdout']===$host."\nMusik_exists",'Host command or Musik existence failed');need($shell['execution']['host']===$host&&$shell['execution']['unraid_host_confirmed']&&$shell['execution']['cwd']==='/','Wrong execution context'); +$connection=tool('unraid_system_connection_test',(object)[]);need($connection['ok']===true&&$connection['command_execution']['exit_code']===0&&$connection['execution']['host']===$host,'Connection/host command check failed');need($connection['phases']['authentication']['ssh_login']==='not_applicable','Unexpected SSH transport'); +$p=(int)trim(file_get_contents('/var/run/mua.pid'));need(readlink('/proc/'.$p.'/cwd')==='/','Daemon cwd not stable'); +echo json_encode(['version'=>$i['serverInfo']['version'],'host'=>$host,'executionLocation'=>'Unraid host plugin, no SSH','daemonCwd'=>'/','transport'=>'HTTP request succeeds','authentication'=>'unauthenticated 401; authenticated initialize/list/tool calls succeed','shell'=>'hostname and existing /mnt/user/Musik verified','readonly'=>'same host confirmed','connectionTest'=>'all phases verified','mutationsExecuted'=>0,'fileRelatedToolNames'=>array_values(array_filter($names,fn($n)=>preg_match('/file|upload|download|transfer|copy/',$n)))],JSON_PRETTY_PRINT).PHP_EOL; diff --git a/src/helpers.ts b/src/helpers.ts index 2bbc08d..69f3713 100644 --- a/src/helpers.ts +++ b/src/helpers.ts @@ -10,12 +10,13 @@ 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"; // ── Konstanten ────────────────────────────────────────────────────────── export const MUA_SERVER_NAME = "mua"; -export const MUA_VERSION = "2026.10.11.r030"; +export const MUA_VERSION = "2026.10.12.r031"; 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"; @@ -59,6 +60,21 @@ async function awaitProcess( } } +export function localExecutionContext() { + return { location: "mua_local_process", host: hostname(), transport: "direct_host_plugin_no_ssh", + unraid_host_confirmed: existsSync("/etc/unraid-version"), cwd: "/", interpreter: "/bin/sh", + interpreter_exists: existsSync("/bin/sh") }; +} + +export function executionFailure(error: unknown, phase: string, timeoutSec: number) { + const code = typeof error === "object" && error !== null && "code" in error ? String(error.code) : "PROCESS_ERROR"; + const timedOut = phase === "execution" && error instanceof Error && error.message.includes("timed out after"); + return { error: "local_process_failure", execution: localExecutionContext(), phase, + cause: timedOut ? `timed out after ${timeoutSec} seconds` : code, + connection_failure: false, + explanation: "Local process error; not evidence of a failed host connection or login. No command or credentials included." }; +} + /** * Führe einen lokalen Shell-Befehl aus (via /bin/sh -c). * Timeout in Sekunden. @@ -68,11 +84,14 @@ export async function runLocal( cmd: string, timeoutSec = 60, ): Promise { + let phase = "spawn"; try { const proc = spawn(["/bin/sh", "-c", cmd], { stdout: "pipe", stderr: "pipe", + cwd: "/", }); + phase = "execution"; const [stdout, stderr, code] = await awaitProcess( proc, new Response(proc.stdout).text(), @@ -84,7 +103,7 @@ export async function runLocal( if (result === "" && stderr.trim() !== "") result = stderr.trim(); return result; } catch (e) { - throw new Error(`run_local failed for ${label}: ${String(e)}`); + throw new Error(JSON.stringify(executionFailure(e, phase, timeoutSec))); } } @@ -94,11 +113,14 @@ export async function runLocal( * Liefert JSON, damit der Agent Exit-Code und beides Streams sieht. */ export async function runShell(cmd: string, timeoutSec = 60): Promise { + let phase = "spawn"; try { const proc = spawn(["/bin/sh", "-c", cmd], { stdout: "pipe", stderr: "pipe", + cwd: "/", }); + phase = "execution"; const [stdout, stderr, code] = await awaitProcess( proc, new Response(proc.stdout).text(), @@ -108,11 +130,12 @@ export async function runShell(cmd: string, timeoutSec = 60): Promise { ); return JSON.stringify({ exit_code: code, + execution: localExecutionContext(), stdout: sanitizeLogOutput(stdout.trim(), 100000), stderr: sanitizeLogOutput(stderr.trim(), 20000), }); } catch (e) { - throw new Error(`run_shell failed: ${String(e)}`); + throw new Error(JSON.stringify(executionFailure(e, phase, timeoutSec))); } } @@ -1037,12 +1060,25 @@ export async function hostState(): Promise { } // ── Connection Test ───────────────────────────────────────────────────── -export async function connectionTest(): Promise { - return runLocal( - "connection_test", - "id; printf 'hostname='; hostname; printf 'kernel='; uname -sr; printf 'unraid='; cat /etc/unraid-version", - 15, - ); +export async function connectionTest(execute: typeof runShell = runShell): Promise { + // Reaching this MCP handler proves request transport/auth dispatch; there is no SSH login. + // This is a local host process test, not a network probe from the caller's machine. + const phases = { + transport: { status: "request_reached_handler", mode: "direct_mcp_http", scope: "current tool invocation; not an outbound network probe" }, + authentication: { status: "checked_by_mcp_before_dispatch", ssh_login: "not_applicable" }, + }; + try { + const result = JSON.parse(await execute("set -e; id; printf 'hostname='; hostname; printf 'kernel='; uname -sr; printf 'unraid='; cat /etc/unraid-version", 15)); + return JSON.stringify({ ok: result.exit_code === 0, phases, execution: result.execution, + command_execution: { status: result.exit_code === 0 ? "ok" : "command_failed", phase: "execution", + exit_code: result.exit_code, stdout: result.stdout, stderr: result.stderr } }); + } catch (error) { + // runShell emits only controlled diagnostic fields, never the supplied command. + let failure; + try { failure = JSON.parse((error as Error).message); } + catch { failure = executionFailure(error, "spawn", 15); } + return JSON.stringify({ ok: false, phases, command_execution: { status: "local_process_failed", ...failure } }); + } } // ── Community Applications ───────────────────────────────────────────── diff --git a/src/security.test.ts b/src/security.test.ts index f9dc4bf..a42fcdb 100644 --- a/src/security.test.ts +++ b/src/security.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "bun:test"; import { parseConfig, SAFE_DEFAULT_TOOLS } from "./auth"; -import { installCommunityApp, runReadOnlyCommand, sanitizeLogOutput } from "./helpers"; +import { connectionTest, executionFailure, installCommunityApp, runReadOnlyCommand, sanitizeLogOutput } from "./helpers"; import { getToolRisk, toolByName } from "./tools"; import { ToolCallGate, withHardTimeout } from "./concurrency"; @@ -184,3 +184,45 @@ describe("Community Applications approval", () => { ).rejects.toThrow("Approval ticket missing"); }); }); + + +describe("deleted working directory regression", () => { + test("inherited deleted cwd reproduces ENOENT but explicit host cwd works", async () => { + const helperPath = new URL("./helpers.ts", import.meta.url).pathname; + const source = ` + import { mkdtempSync, rmSync } from 'node:fs'; + import { tmpdir } from 'node:os'; + import { runLocal, runShell } from ${JSON.stringify(helperPath)}; + const path=mkdtempSync(tmpdir()+'/mua-cwd-test-'); + process.chdir(path);rmSync(path,{recursive:true}); + let reproduced=false; + try { const p=Bun.spawn(['/bin/sh','-c','printf before']);await p.exited; } + catch(e){ reproduced=e.code==='ENOENT'; } + if(!reproduced)throw new Error('Expected original ENOENT'); + const shell=JSON.parse(await runShell('printf after',5)); + if(shell.exit_code!==0||shell.stdout!=='after'||shell.execution.cwd!=='/')throw new Error('Shell fix failed'); + if(await runLocal('test','printf local',5)!=='local')throw new Error('Connection helper spawn path failed'); + console.log('deleted-cwd-reproduced-and-fixed'); + `; + const child=Bun.spawn([process.execPath,'-e',source],{cwd:'/',stdout:'pipe',stderr:'pipe'}); + const [stdout,stderr,code]=await Promise.all([new Response(child.stdout).text(),new Response(child.stderr).text(),child.exited]); + expect(stderr).toBe('');expect(code).toBe(0);expect(stdout.trim()).toBe('deleted-cwd-reproduced-and-fixed'); + }); + test("spawn errors expose phase/location and omit command secrets", async () => { + const error=Object.assign(new Error('password=do-not-disclose'),{code:'ENOENT'}); + const failure=executionFailure(error,'spawn',15); + expect(failure.phase).toBe('spawn');expect(failure.cause).toBe('ENOENT'); + expect(failure.connection_failure).toBe(false);expect(failure.execution.cwd).toBe('/'); + expect(JSON.stringify(failure)).not.toContain('do-not-disclose'); + const result=JSON.parse(await connectionTest(async()=>{throw new Error(JSON.stringify(failure));})); + expect(result.ok).toBe(false);expect(result.command_execution.status).toBe('local_process_failed'); + expect(result.phases.transport.status).toBe('request_reached_handler'); + expect(result.phases.authentication.ssh_login).toBe('not_applicable'); + }); + test("failed command is distinct from transport and spawn failure", async () => { + const result=JSON.parse(await connectionTest(async()=>JSON.stringify({exit_code:3,stdout:'',stderr:'missing version',execution:{cwd:'/',location:'mua_local_process'}}))); + expect(result.ok).toBe(false);expect(result.command_execution.status).toBe('command_failed'); + expect(result.command_execution.phase).toBe('execution');expect(result.command_execution.exit_code).toBe(3); + expect(result.phases.transport.status).toBe('request_reached_handler'); + }); +}); diff --git a/src/tools.ts b/src/tools.ts index 935c2c0..39cff47 100644 --- a/src/tools.ts +++ b/src/tools.ts @@ -652,7 +652,7 @@ export const TOOLS: ToolDef[] = [ { name: "unraid_system_connection_test", description: - "Test connection to the Unraid host (hostname, kernel, Unraid version).", + "Diagnose this authenticated MCP invocation and local command execution on the Unraid host. Reports transport arrival, authentication dispatch and command execution separately. MUA runs as a host plugin, without SSH; a local spawn/interpreter error is not a failed host connection. Includes hostname, kernel, Unraid version and execution location.", inputSchema: empty, handler: () => connectionTest(), },