New desktop
Some checks failed
Deploy / deploy-staging (push) Failing after 6s
Deploy / deploy-production (push) Has been skipped

This commit is contained in:
2026-06-06 03:20:50 +02:00
parent 756b4e119b
commit 888981c782
127 changed files with 31275 additions and 0 deletions

View File

@@ -0,0 +1,32 @@
<?php
$file = (string)($_GET['file'] ?? '');
$base = realpath(__DIR__ . '/../assets');
$map = [
'pi_control.css' => $base . '/pi_control.css',
'console.js' => $base . '/console.js',
'hosts.js' => $base . '/hosts.js',
'commands.js' => $base . '/commands.js',
];
if (!isset($map[$file])) {
http_response_code(404);
exit('Not found');
}
$path = $map[$file];
if (!$base || !is_file($path) || !str_starts_with($path, $base)) {
http_response_code(404);
exit('Not found');
}
$ext = pathinfo($path, PATHINFO_EXTENSION);
if ($ext === 'css') {
header('Content-Type: text/css; charset=utf-8');
} elseif ($ext === 'js') {
header('Content-Type: application/javascript; charset=utf-8');
} else {
header('Content-Type: application/octet-stream');
}
readfile($path);
exit;

View File

@@ -0,0 +1,181 @@
<?php
$pdo = module_fn('pi_control', 'pdo');
module_fn('pi_control', 'ensure_schema');
$table = fn(string $name) => module_fn('pi_control', 'table', $name);
$assets = app()->assets();
if ($assets) {
$assets->addStyle('/module/pi_control/asset?file=pi_control.css');
$assets->addScript('/module/pi_control/asset?file=commands.js', 'footer', true);
}
$notice = null;
$error = null;
if (isset($_GET['reorder_json'])) {
require_admin();
$payload = json_decode(file_get_contents('php://input'), true);
$order = is_array($payload['order'] ?? null) ? $payload['order'] : [];
if ($order) {
$stmt = $pdo->prepare('UPDATE ' . $table('commands') . ' SET sort_order = :sort_order WHERE id = :id');
$pos = 1;
foreach ($order as $id) {
$stmt->execute([
'sort_order' => $pos++,
'id' => (int)$id,
]);
}
}
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['ok' => true]);
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
require_admin();
$deleteId = (int)($_POST['delete_id'] ?? 0);
$editId = (int)($_POST['id'] ?? 0);
$label = trim((string)($_POST['label'] ?? ''));
$command = trim((string)($_POST['command'] ?? ''));
$adminOnly = !empty($_POST['admin_only']) ? 1 : 0;
$timeoutSec = (int)($_POST['timeout_sec'] ?? 0);
if ($deleteId > 0) {
$stmt = $pdo->prepare('DELETE FROM ' . $table('commands') . ' WHERE id = :id');
$stmt->execute(['id' => $deleteId]);
$notice = 'Befehl gelöscht.';
} else {
if ($label === '' || $command === '') {
$error = 'Bitte Label und Command angeben.';
} else {
if ($editId > 0) {
$stmt = $pdo->prepare(
'UPDATE ' . $table('commands') . ' SET label = :label, command = :command, admin_only = :admin_only, timeout_sec = :timeout_sec WHERE id = :id'
);
$stmt->execute([
'id' => $editId,
'label' => $label,
'command' => $command,
'admin_only' => $adminOnly,
'timeout_sec' => $timeoutSec > 0 ? $timeoutSec : null,
]);
$notice = 'Befehl aktualisiert.';
} else {
$nextSort = (int)$pdo->query('SELECT COALESCE(MAX(sort_order), 0) + 1 FROM ' . $table('commands'))->fetchColumn();
$stmt = $pdo->prepare(
'INSERT INTO ' . $table('commands') . ' (label, command, admin_only, timeout_sec, sort_order) VALUES (:label, :command, :admin_only, :timeout_sec, :sort_order)'
);
$stmt->execute([
'label' => $label,
'command' => $command,
'admin_only' => $adminOnly,
'timeout_sec' => $timeoutSec > 0 ? $timeoutSec : null,
'sort_order' => $nextSort,
]);
$notice = 'Befehl gespeichert.';
}
}
}
}
$commands = $pdo->query('SELECT * FROM ' . $table('commands') . ' ORDER BY COALESCE(sort_order, id) ASC, id ASC')->fetchAll(PDO::FETCH_ASSOC);
?>
<?= module_shell_header('pi_control', [
'title' => 'Befehle',
]) ?>
<div class="module-flow">
<section class="module-box">
<div class="module-box-head">
<div>
<h2 class="module-box-title">Befehle</h2>
<p>Verwalte vordefinierte SSH-Befehle.</p>
</div>
<button class="module-button module-button--primary" type="button" data-command-new>+ Neuer Befehl</button>
</div>
<?php if ($error): ?>
<div class="setup-db-message setup-db-message--error" style="margin-top:16px;">
<?= e($error) ?>
</div>
<?php elseif ($notice): ?>
<div class="setup-db-message setup-db-message--success" style="margin-top:16px;">
<?= e($notice) ?>
</div>
<?php endif; ?>
<div class="module-box" style="margin-top:16px;">
<strong>Vorhandene Befehle</strong>
<?php if (!$commands): ?>
<div class="muted" style="margin-top:.75rem;">Keine Befehle vorhanden.</div>
<?php else: ?>
<ul class="command-list" data-command-list style="margin-top:.75rem;">
<?php foreach ($commands as $c): ?>
<li class="command-item" draggable="true"
data-command-id="<?= e((string)$c['id']) ?>"
data-label="<?= e((string)($c['label'] ?? '')) ?>"
data-command="<?= e((string)($c['command'] ?? '')) ?>"
data-timeout="<?= e((string)($c['timeout_sec'] ?? '')) ?>"
data-admin="<?= !empty($c['admin_only']) ? '1' : '0' ?>">
<div class="command-drag">⋮⋮</div>
<div class="command-body">
<div class="command-title">
<strong><?= e($c['label'] ?? '') ?></strong>
<?php if (!empty($c['admin_only'])): ?>
<span class="pill">Admin</span>
<?php endif; ?>
</div>
<div class="muted" style="margin-top:4px;">
<code><?= e($c['command'] ?? '') ?></code>
</div>
<div class="muted" style="margin-top:4px;">
Timeout: <?= !empty($c['timeout_sec']) ? e((string)$c['timeout_sec']) . 's' : 'default' ?>
</div>
</div>
<details class="action-menu">
<summary>☰</summary>
<div class="action-menu-panel">
<button class="nav-link" type="button" data-command-edit>Bearbeiten</button>
<form method="post" onsubmit="return confirm('Befehl wirklich löschen?')">
<input type="hidden" name="delete_id" value="<?= e((string)$c['id']) ?>">
<button class="nav-link" type="submit">Löschen</button>
</form>
</div>
</details>
</li>
<?php endforeach; ?>
</ul>
<p class="muted" style="margin-top:.5rem;">Reihenfolge per Drag & Drop ändern.</p>
<?php endif; ?>
</div>
</section>
</div>
<div class="modal" data-command-modal aria-hidden="true">
<div class="modal-card">
<div class="modal-header">
<strong data-command-modal-title>Neuer Befehl</strong>
<button class="icon-button" type="button" data-command-close>×</button>
</div>
<form method="post" class="form-grid" style="margin-top:.75rem;" data-command-form>
<input type="hidden" name="id" value="">
<input type="text" name="label" placeholder="Label" required>
<textarea name="command" rows="4" placeholder="Command" required></textarea>
<input type="number" name="timeout_sec" placeholder="Timeout (Sek., optional)">
<label class="muted" style="display:flex; gap:8px; align-items:center;">
<input type="checkbox" name="admin_only" value="1">
Nur Admin
</label>
<div class="host-unsaved" data-command-unsaved style="display:none;">
<span class="muted">Änderungen nicht gespeichert.</span>
<div style="display:flex; gap:10px; flex-wrap:wrap;">
<button class="cta-button" type="submit" data-command-submit>Speichern</button>
<button class="nav-link" type="button" data-command-discard>Änderungen verwerfen</button>
</div>
</div>
<div style="display:flex; gap:10px; flex-wrap:wrap;">
<button class="cta-button" type="submit" data-command-submit>Speichern</button>
<button class="nav-link" type="button" data-command-cancel>Zurücksetzen</button>
</div>
</form>
</div>
</div>
<?= module_shell_footer() ?>

View File

@@ -0,0 +1,527 @@
<?php
$pdo = module_fn('pi_control', 'pdo');
module_fn('pi_control', 'ensure_schema');
$table = fn(string $name) => module_fn('pi_control', 'table', $name);
$notice = null;
$error = null;
$terminalNotice = null;
$terminalError = null;
$terminalUrl = null;
$terminalToken = null;
$terminalHostLabel = null;
$settings = modules()->settings('pi_control');
$assets = app()->assets();
if ($assets) {
$assets->addStyle('/module/pi_control/asset?file=pi_control.css');
$assets->addScript('/module/pi_control/asset?file=console.js', 'footer', true);
}
$ttydUrl = trim((string)($settings['ttyd_url'] ?? '/ttyd'));
$defaultProvider = 'ttyd';
$defaultTimeout = (int)($settings['exec_default_timeout'] ?? (getenv('PI_CONTROL_EXEC_DEFAULT_TIMEOUT') !== false ? (int)getenv('PI_CONTROL_EXEC_DEFAULT_TIMEOUT') : 300));
$defaultTimeout = $defaultTimeout > 0 ? $defaultTimeout : 300;
$queueName = (string)($settings['redis']['queue'] ?? ($settings['redis.queue'] ?? (getenv('PI_CONTROL_REDIS_QUEUE') ?: 'pi_control:queue')));
$tokenTtl = (int)($settings['terminal_token_ttl'] ?? 10);
$tokenTtl = $tokenTtl > 0 ? $tokenTtl : 10;
$hosts = $pdo->query('SELECT * FROM ' . $table('hosts') . ' ORDER BY name ASC')->fetchAll(PDO::FETCH_ASSOC);
$commands = $pdo->query('SELECT * FROM ' . $table('commands') . ' ORDER BY COALESCE(sort_order, id) ASC, id ASC')->fetchAll(PDO::FETCH_ASSOC);
$renderRuns = function (array $runs): string {
ob_start();
if (!$runs) {
echo '<tr><td colspan="8" class="muted">Noch keine Runs.</td></tr>';
return ob_get_clean();
}
foreach ($runs as $r) {
$out = (string)($r['output'] ?? '');
$err = (string)($r['error'] ?? '');
$snippet = $out !== '' ? $out : $err;
if (strlen($snippet) > 140) {
$snippet = substr($snippet, 0, 140) . '…';
}
echo '<tr>';
echo '<td>' . e((string)$r['id']) . '</td>';
echo '<td>' . e((string)($r['status'] ?? '')) . '</td>';
echo '<td>' . e((string)($r['host_name'] ?? $r['host_addr'] ?? '')) . '</td>';
echo '<td class="muted" style="max-width:360px;"><code>' . e((string)($r['command_text'] ?? '')) . '</code></td>';
echo '<td>' . e((string)($r['created_by'] ?? '')) . '</td>';
echo '<td class="muted" style="max-width:240px;"><code>' . e($snippet) . '</code></td>';
echo '<td>' . (!empty($r['timeout_sec']) ? e((string)$r['timeout_sec']) . 's' : 'default') . '</td>';
$status = (string)($r['status'] ?? '');
echo '<td>';
if ($status === 'queued') {
echo '<button class="nav-link" type="button" data-queue-action="cancel" data-run-id="' . e((string)$r['id']) . '">Stoppen</button>';
echo '<button class="nav-link" type="button" data-queue-action="delete" data-run-id="' . e((string)$r['id']) . '">Löschen</button>';
} elseif ($status === 'running') {
echo '<span class="muted">läuft</span>';
} else {
echo '<button class="nav-link" type="button" data-queue-action="delete" data-run-id="' . e((string)$r['id']) . '">Löschen</button>';
}
echo '</td>';
echo '</tr>';
}
return ob_get_clean();
};
if (isset($_GET['queue_json'])) {
$runs = $pdo->query(
'SELECT r.*, h.name AS host_name, h.host AS host_addr
FROM ' . $table('runs') . ' r
LEFT JOIN ' . $table('hosts') . ' h ON h.id = r.host_id
ORDER BY r.id DESC LIMIT 20'
)->fetchAll(PDO::FETCH_ASSOC);
$count = (int)$pdo->query(
"SELECT COUNT(*) FROM " . $table('runs') . " WHERE status IN ('queued','running','cancel_requested')"
)->fetchColumn();
header('Content-Type: application/json; charset=utf-8');
echo json_encode([
'ok' => true,
'next' => 10,
'count' => $count,
'html' => $renderRuns($runs),
]);
exit;
}
if (isset($_GET['queue_action_json'])) {
$runId = (int)($_POST['run_id'] ?? 0);
$action = (string)($_POST['action'] ?? '');
$error = null;
if ($runId <= 0 || !in_array($action, ['cancel', 'delete'], true)) {
$error = 'Ungültige Anfrage.';
} else {
$stmt = $pdo->prepare('SELECT * FROM ' . $table('runs') . ' WHERE id = :id LIMIT 1');
$stmt->execute(['id' => $runId]);
$run = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$run) {
$error = 'Run nicht gefunden.';
} else {
$status = (string)($run['status'] ?? '');
$driver = (string)$pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
$nowExpr = $driver === 'pgsql' ? 'NOW()' : "DATETIME('now')";
if ($action === 'cancel') {
if ($status !== 'queued') {
$error = 'Nur queued Runs können gestoppt werden.';
} else {
$pdo->exec('UPDATE ' . $table('runs') . ' SET status = \'canceled\', finished_at = ' . $nowExpr . ' WHERE id = ' . (int)$runId);
try {
$redis = module_fn('pi_control', 'redis');
$payload = json_encode(['run_id' => $runId]);
$redis->command(['LREM', $queueName, '0', $payload]);
} catch (\Throwable $e) {
// ignore redis cleanup errors
}
}
} elseif ($action === 'delete') {
if ($status === 'running') {
$error = 'Laufende Runs können nicht gelöscht werden.';
} else {
$pdo->prepare('DELETE FROM ' . $table('runs') . ' WHERE id = :id')->execute(['id' => $runId]);
try {
$redis = module_fn('pi_control', 'redis');
$payload = json_encode(['run_id' => $runId]);
$redis->command(['LREM', $queueName, '0', $payload]);
} catch (\Throwable $e) {
// ignore redis cleanup errors
}
}
}
}
}
header('Content-Type: application/json; charset=utf-8');
echo json_encode([
'ok' => $error === null,
'error' => $error,
]);
exit;
}
if (isset($_GET['open_console_json'])) {
$hostId = (int)($_POST['terminal_host_id'] ?? 0);
$presetId = (int)($_POST['terminal_preset_id'] ?? 0);
$rawCommand = trim((string)($_POST['terminal_command_text'] ?? ''));
$terminalError = null;
$terminalUrl = null;
$terminalToken = null;
$terminalHostLabel = null;
if ($hostId <= 0) {
$terminalError = 'Bitte einen Host wählen.';
} elseif ($ttydUrl === '') {
$terminalError = 'ttyd URL fehlt. Bitte im Setup setzen.';
} else {
$presetCommand = '';
if ($presetId > 0) {
foreach ($commands as $c) {
if ((int)$c['id'] === $presetId) {
if (!auth_is_admin() && !empty($c['admin_only'])) {
$terminalError = 'Diese Vorlage ist nur für Admins.';
} else {
$presetCommand = (string)$c['command'];
}
break;
}
}
}
if (!$terminalError) {
$driver = (string)$pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
$expiresSql = $driver === 'pgsql'
? "NOW() + INTERVAL '{$tokenTtl} minutes'"
: "DATETIME('now', '+{$tokenTtl} minutes')";
$token = bin2hex(random_bytes(24));
$terminalToken = $token;
$stmt = $pdo->prepare(
'INSERT INTO ' . $table('sessions') . ' (token, host_id, provider, command_text, created_by, expires_at)
VALUES (:token, :host_id, :provider, :command_text, :created_by, ' . $expiresSql . ')'
);
$commandToRun = $presetCommand !== '' ? $presetCommand : $rawCommand;
$stmt->execute([
'token' => $token,
'host_id' => $hostId,
'provider' => 'ttyd',
'command_text' => $commandToRun !== '' ? $commandToRun : null,
'created_by' => auth_display_name() ?: null,
]);
$sep = str_contains($ttydUrl, '?') ? '&' : '?';
$terminalUrl = rtrim($ttydUrl, '/') . '/' . $sep . 'arg=' . rawurlencode($token);
foreach ($hosts as $h) {
if ((int)$h['id'] === $hostId) {
$terminalHostLabel = (string)($h['name'] ?? $h['host']);
break;
}
}
}
}
header('Content-Type: application/json; charset=utf-8');
echo json_encode([
'ok' => $terminalError === null,
'error' => $terminalError,
'url' => $terminalUrl,
'token' => $terminalToken,
'host' => $terminalHostLabel,
]);
exit;
}
if (isset($_GET['run_command_json'])) {
$hostId = (int)($_POST['terminal_host_id'] ?? 0);
$commandId = (int)($_POST['terminal_preset_id'] ?? 0);
$rawCommand = trim((string)($_POST['terminal_command_text'] ?? ''));
$timeoutSec = $defaultTimeout;
$error = null;
$notice = null;
if ($hostId <= 0) {
$error = 'Bitte einen Host wählen.';
} elseif ($commandId <= 0 && $rawCommand === '') {
$error = 'Bitte einen Befehl wählen oder einen Befehl eingeben.';
} else {
$selectedCommand = '';
if ($commandId > 0) {
foreach ($commands as $c) {
if ((int)$c['id'] === $commandId) {
if (!auth_is_admin() && !empty($c['admin_only'])) {
$error = 'Dieser Befehl ist nur für Admins.';
} else {
$selectedCommand = (string)$c['command'];
if (!empty($c['timeout_sec'])) {
$timeoutSec = (int)$c['timeout_sec'];
}
}
break;
}
}
}
if (!$error) {
$commandText = $selectedCommand !== '' ? $selectedCommand : $rawCommand;
$driver = (string)$pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
if ($driver === 'pgsql') {
$stmt = $pdo->prepare(
'INSERT INTO ' . $table('runs') . ' (host_id, command_id, command_text, status, timeout_sec, created_by)
VALUES (:host_id, :command_id, :command_text, :status, :timeout_sec, :created_by)
RETURNING id'
);
$stmt->execute([
'host_id' => $hostId,
'command_id' => $commandId > 0 ? $commandId : null,
'command_text' => $commandText,
'status' => 'queued',
'timeout_sec' => $timeoutSec,
'created_by' => auth_display_name() ?: null,
]);
$runId = (int)$stmt->fetchColumn();
} else {
$stmt = $pdo->prepare(
'INSERT INTO ' . $table('runs') . ' (host_id, command_id, command_text, status, timeout_sec, created_by)
VALUES (:host_id, :command_id, :command_text, :status, :timeout_sec, :created_by)'
);
$stmt->execute([
'host_id' => $hostId,
'command_id' => $commandId > 0 ? $commandId : null,
'command_text' => $commandText,
'status' => 'queued',
'timeout_sec' => $timeoutSec,
'created_by' => auth_display_name() ?: null,
]);
$runId = (int)$pdo->lastInsertId();
}
try {
$redis = module_fn('pi_control', 'redis');
$payload = json_encode(['run_id' => $runId], JSON_THROW_ON_ERROR);
$redis->command(['RPUSH', $queueName, $payload]);
$notice = 'Befehl wurde in die Queue gestellt.';
} catch (\Throwable $e) {
$pdo->exec('UPDATE ' . $table('runs') . ' SET status = \'queue_error\' WHERE id = ' . (int)$runId);
$notice = 'Befehl gespeichert, aber Queue nicht erreichbar.';
}
}
}
header('Content-Type: application/json; charset=utf-8');
echo json_encode([
'ok' => $error === null,
'error' => $error,
'notice' => $notice,
]);
exit;
}
if (isset($_GET['send_active_json'])) {
$hostId = (int)($_POST['terminal_host_id'] ?? 0);
$commandId = (int)($_POST['terminal_preset_id'] ?? 0);
$rawCommand = trim((string)($_POST['terminal_command_text'] ?? ''));
$error = null;
$notice = null;
if ($hostId <= 0) {
$error = 'Bitte einen Host wählen.';
} elseif ($commandId <= 0 && $rawCommand === '') {
$error = 'Bitte einen Befehl wählen oder einen Befehl eingeben.';
} else {
$selectedCommand = '';
if ($commandId > 0) {
foreach ($commands as $c) {
if ((int)$c['id'] === $commandId) {
if (!auth_is_admin() && !empty($c['admin_only'])) {
$error = 'Dieser Befehl ist nur für Admins.';
} else {
$selectedCommand = (string)$c['command'];
}
break;
}
}
}
if (!$error) {
$commandText = $selectedCommand !== '' ? $selectedCommand : $rawCommand;
$stmt = $pdo->prepare('SELECT * FROM ' . $table('hosts') . ' WHERE id = :id LIMIT 1');
$stmt->execute(['id' => $hostId]);
$host = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$host) {
$error = 'Host nicht gefunden.';
} else {
$settings = modules()->settings('pi_control');
$strictHostKey = !empty($settings['terminal_strict_hostkey']) || getenv('PI_CONTROL_STRICT_HOSTKEY') === '1';
[$ok, $sendError] = sendToActiveConsole($host, $commandText, $strictHostKey);
if ($ok) {
$notice = 'Befehl wurde in der bestehenden Konsole ausgeführt.';
} else {
$error = $sendError ?: 'Bestehende Konsole nicht verfügbar.';
}
}
}
}
header('Content-Type: application/json; charset=utf-8');
echo json_encode([
'ok' => $error === null,
'error' => $error,
'notice' => $notice,
]);
exit;
}
// Form submits are handled via AJAX to avoid reloads.
$runs = $pdo->query(
'SELECT r.*, h.name AS host_name, h.host AS host_addr
FROM ' . $table('runs') . ' r
LEFT JOIN ' . $table('hosts') . ' h ON h.id = r.host_id
ORDER BY r.id DESC LIMIT 20'
)->fetchAll(PDO::FETCH_ASSOC);
function sendToActiveConsole(array $host, string $command, bool $strictHostKey): array
{
$hostAddr = (string)($host['host'] ?? '');
$user = (string)($host['username'] ?? '');
$port = (int)($host['port'] ?? 22);
$authType = (string)($host['auth_type'] ?? 'key');
$keyPath = (string)($host['key_path'] ?? '');
$password = (string)($host['password'] ?? '');
if ($hostAddr === '' || $user === '') {
return [false, 'Hostdaten unvollständig.'];
}
$opts = $strictHostKey
? '-o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=/root/.ssh/known_hosts'
: '-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null';
$target = escapeshellarg($user . '@' . $hostAddr);
$cmdB64 = base64_encode($command);
$remote = 'CMD_B64="$0"; CMD="$(printf "%s" "$CMD_B64" | base64 -d)"; ' .
'command -v tmux >/dev/null 2>&1 || exit 2; ' .
'tmux has-session -t nexus 2>/dev/null || exit 3; ' .
'tmux send-keys -t nexus "$CMD" C-m';
$cmd = 'ssh ' . $opts . ' -p ' . (int)$port . ' ';
if ($authType === 'key' && $keyPath !== '') {
$cmd .= '-i ' . escapeshellarg($keyPath) . ' ';
}
$cmd .= $target . ' -- /bin/bash -lc ' . escapeshellarg($remote) . ' ' . escapeshellarg($cmdB64);
if ($authType === 'pass' && $password !== '') {
$cmd = 'sshpass -p ' . escapeshellarg($password) . ' ' . $cmd;
}
$descriptors = [
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
];
$process = proc_open($cmd, $descriptors, $pipes);
if (!is_resource($process)) {
return [false, 'proc_open failed'];
}
$out = stream_get_contents($pipes[1]);
$err = stream_get_contents($pipes[2]);
$status = proc_get_status($process);
$exitCode = (int)($status['exitcode'] ?? 1);
proc_close($process);
if ($exitCode === 0) {
return [true, null];
}
if ($exitCode === 2) {
return [false, 'tmux ist auf dem Host nicht installiert.'];
}
if ($exitCode === 3) {
return [false, 'Keine aktive Konsole gefunden.'];
}
$msg = trim($err !== '' ? $err : $out);
return [false, $msg !== '' ? $msg : 'Befehl konnte nicht gesendet werden.'];
}
?>
<?= module_shell_header('pi_control', [
'title' => 'Konsole',
]) ?>
<div class="module-flow">
<section class="module-box">
<div class="module-box-head">
<div>
<h2 class="module-box-title">Konsole</h2>
<p>Wähle einen Host und führe einen Befehl aus.</p>
</div>
</div>
<?php if ($error): ?>
<div class="setup-db-message setup-db-message--error" style="margin-top:16px;">
<?= e($error) ?>
</div>
<?php elseif ($notice): ?>
<div class="setup-db-message setup-db-message--success" style="margin-top:16px;">
<?= e($notice) ?>
</div>
<?php endif; ?>
<div class="module-box" style="margin-top:16px;">
<strong>Live-Konsole</strong>
<div class="setup-db-message setup-db-message--error" style="margin-top:1rem; display:none;" data-console-error></div>
<div class="setup-db-message setup-db-message--success" style="margin-top:1rem; display:none;" data-console-notice></div>
<form method="post" class="form-grid" style="margin-top:.75rem;" data-console-form>
<label class="form-field">
<span class="muted">Host</span>
<select name="terminal_host_id" required title="Pi auswählen, zu dem die Konsole verbindet.">
<option value="">Host wählen</option>
<?php foreach ($hosts as $h): ?>
<option value="<?= e((string)$h['id']) ?>"><?= e($h['name'] ?? $h['host']) ?></option>
<?php endforeach; ?>
</select>
</label>
<label class="form-field">
<span class="muted">Vorlage</span>
<select name="terminal_preset_id" title="Optional: Vorlage direkt in der Konsole ausführen.">
<option value="">Vorlage auswählen (optional)</option>
<?php foreach ($commands as $c): ?>
<?php if (!auth_is_admin() && !empty($c['admin_only'])) { continue; } ?>
<option value="<?= e((string)$c['id']) ?>" data-command="<?= e((string)($c['command'] ?? '')) ?>">
<?= e($c['label'] ?? '') ?>
</option>
<?php endforeach; ?>
</select>
</label>
<label class="form-field">
<span class="muted">Direkter Befehl</span>
<textarea name="terminal_command_text" rows="2" placeholder="Optional: Befehl direkt ausführen"></textarea>
</label>
<div style="display:flex; gap:10px; flex-wrap:wrap;">
<button class="cta-button" type="button" data-open-console>Neue Konsole öffnen</button>
<button class="nav-link" type="button" data-run-command>Im Hintergrund ausführen</button>
<button class="icon-button queue-button" type="button" data-queue-button>
Queue
<span class="queue-badge" data-queue-count>0</span>
</button>
</div>
</form>
<div class="muted" style="margin-top:.5rem;">
Token: <code data-console-token></code>
</div>
<?php if ($terminalUrl): ?>
<div class="console-launch"
data-url="<?= e($terminalUrl) ?>"
data-host="<?= e($terminalHostLabel ?: 'Konsole') ?>"
data-token="<?= e($terminalToken ?: '') ?>"></div>
<?php endif; ?>
</div>
<div class="modal" data-queue-modal aria-hidden="true">
<div class="modal-card">
<div class="modal-header">
<strong>Queue</strong>
<div class="modal-actions">
<span class="muted">Update in <span data-queue-countdown>10</span>s</span>
<button class="icon-button" type="button" data-queue-refresh title="Jetzt aktualisieren">↻</button>
<button class="icon-button" type="button" data-queue-close title="Schließen">×</button>
</div>
</div>
<div style="margin-top:.75rem; overflow:auto;">
<table class="table" style="min-width:720px;">
<thead>
<tr>
<th>ID</th>
<th>Status</th>
<th>Host</th>
<th>Command</th>
<th>Von</th>
<th>Output</th>
<th>Timeout</th>
<th>Aktion</th>
</tr>
</thead>
<tbody data-queue-body>
<?= $renderRuns($runs) ?>
</tbody>
</table>
</div>
</div>
</div>
</section>
</div>
<?= module_shell_footer() ?>

View File

@@ -0,0 +1,479 @@
<?php
$pdo = module_fn('pi_control', 'pdo');
module_fn('pi_control', 'ensure_schema');
$table = fn(string $name) => module_fn('pi_control', 'table', $name);
$assets = app()->assets();
if ($assets) {
$assets->addStyle('/module/pi_control/asset?file=pi_control.css');
$assets->addScript('/module/pi_control/asset?file=hosts.js', 'footer', true);
}
$notice = null;
$error = null;
if (isset($_GET['status_json'])) {
require_admin();
$id = (int)($_GET['id'] ?? 0);
$stmt = $pdo->prepare('SELECT * FROM ' . $table('hosts') . ' WHERE id = :id LIMIT 1');
$stmt->execute(['id' => $id]);
$host = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$host) {
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['ok' => false, 'error' => 'not_found']);
exit;
}
$settings = modules()->settings('pi_control');
$strictHostKey = !empty($settings['terminal_strict_hostkey']);
$reachable = hostReachable((string)($host['host'] ?? ''), (int)($host['port'] ?? 22));
$authOk = $reachable ? hostAuthOk($host, $strictHostKey) : false;
$status = !$reachable ? 'down' : ($authOk ? 'ok' : 'auth');
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['ok' => true, 'status' => $status]);
exit;
}
if (isset($_GET['update_json'])) {
require_admin();
$id = (int)($_GET['id'] ?? 0);
$stmt = $pdo->prepare('SELECT * FROM ' . $table('hosts') . ' WHERE id = :id LIMIT 1');
$stmt->execute(['id' => $id]);
$host = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$host) {
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['ok' => false, 'error' => 'not_found']);
exit;
}
$settings = modules()->settings('pi_control');
$strictHostKey = !empty($settings['terminal_strict_hostkey']);
$updateCmd = <<<'SH'
if ! command -v apt-get >/dev/null 2>&1; then echo "__ERR__NO_APT"; exit 2; fi;
if sudo -n apt update -qq >/dev/null 2>&1; then echo "__APT_UPDATE__=1"; else echo "__APT_UPDATE__=0"; fi;
count=$(apt-get -s dist-upgrade 2>/dev/null | grep -c "^Inst ");
echo "__COUNT__=$count"
SH;
$upgradeCmd = <<<'SH'
id="$(. /etc/os-release 2>/dev/null && echo "${ID:-}")";
current="$(. /etc/os-release 2>/dev/null && echo "${VERSION_CODENAME:-}")";
if [ "$id" != "debian" ] || [ -z "$current" ]; then echo "__UPGRADE__=0"; exit 0; fi;
latest="$( (command -v curl >/dev/null 2>&1 && curl -fsSL https://deb.debian.org/debian/dists/stable/Release) || (command -v wget >/dev/null 2>&1 && wget -qO- https://deb.debian.org/debian/dists/stable/Release) )";
latest="$(printf "%s" "$latest" | awk -F": " "/^Codename:/{print $2}")";
if [ -z "$latest" ]; then echo "__UPGRADE__=0"; echo "__RAW__=NO_FETCH"; exit 0; fi;
if [ "$current" != "$latest" ]; then echo "__UPGRADE__=1"; else echo "__UPGRADE__=0"; fi
SH;
[$updExit, $updOut, $updErr] = runSshCommandCapture($host, $updateCmd, $strictHostKey, 20);
$updOutStr = (string)$updOut;
$updErrStr = (string)$updErr;
$updateCount = null;
$updatePreview = '';
$updateErr = str_contains($updOutStr, '__ERR__NO_APT');
if (preg_match('/^__COUNT__=(\d+)$/m', $updOutStr, $m)) {
$updateCount = (int)$m[1];
}
$updatePreview = trim($updOutStr);
if (strlen($updatePreview) > 1200) {
$updatePreview = substr($updatePreview, 0, 1200);
}
[$upgExit, $upgOut, $upgErr] = runSshCommandCapture($host, $upgradeCmd, $strictHostKey, 25);
$upgOutStr = (string)$upgOut;
$upgErrStr = (string)$upgErr;
$upgradeAvailable = null;
$upgradeErr = str_contains($upgOutStr, '__ERR__');
if ($upgExit === 0 && !$upgradeErr) {
if (preg_match('/^__UPGRADE__=(0|1)$/m', $upgOutStr, $m)) {
$upgradeAvailable = $m[1] === '1';
}
}
$driver = (string)$pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
$nowExpr = $driver === 'pgsql' ? 'NOW()' : "DATETIME('now')";
$updCountVal = $updateCount;
$updErrVal = (!$updateErr && $updateCount !== null) ? null : trim($updErrStr ?: $updOutStr);
$upgAvailVal = $upgradeAvailable;
$upgErrVal = $upgExit === 0 && !$upgradeErr ? null : trim($upgErrStr ?: $upgOutStr);
$stmt = $pdo->prepare(
'UPDATE ' . $table('hosts') . ' SET update_checked_at = ' . $nowExpr . ',
update_count = :update_count,
update_preview = :update_preview,
update_error = :update_error,
upgrade_available = :upgrade_available,
upgrade_raw = :upgrade_raw,
upgrade_error = :upgrade_error
WHERE id = :id'
);
$stmt->execute([
'update_count' => $updCountVal,
'update_preview' => $updatePreview !== '' ? $updatePreview : null,
'update_error' => $updErrVal,
'upgrade_available' => $upgAvailVal === null ? null : ($upgAvailVal ? 1 : 0),
'upgrade_raw' => $upgExit === 0 ? trim($upgOutStr) : null,
'upgrade_error' => $upgErrVal,
'id' => $id,
]);
header('Content-Type: application/json; charset=utf-8');
echo json_encode([
'ok' => true,
'updates' => [
'count' => $updateCount,
'preview' => $updatePreview,
'raw' => $updatePreview,
'error' => (!$updateErr && $updateCount !== null) ? '' : trim($updErrStr ?: $updOutStr),
],
'os' => [
'available' => $upgradeAvailable,
'raw' => $upgExit === 0 ? trim($upgOutStr) : '',
'error' => $upgExit === 0 && !$upgradeErr ? '' : trim($upgErrStr ?: $upgOutStr),
],
'checked_at' => date('c'),
]);
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
require_admin();
$deleteId = (int)($_POST['delete_id'] ?? 0);
$editId = (int)($_POST['id'] ?? 0);
$name = trim((string)($_POST['name'] ?? ''));
$host = trim((string)($_POST['host'] ?? ''));
$port = (int)($_POST['port'] ?? 22);
$username = trim((string)($_POST['username'] ?? ''));
$authType = trim((string)($_POST['auth_type'] ?? 'key'));
$keyPath = trim((string)($_POST['key_path'] ?? ''));
$password = trim((string)($_POST['password'] ?? ''));
$imageUrl = trim((string)($_POST['image_url'] ?? ''));
if ($deleteId > 0) {
$stmt = $pdo->prepare('DELETE FROM ' . $table('hosts') . ' WHERE id = :id');
$stmt->execute(['id' => $deleteId]);
$notice = 'Host gelöscht.';
} else {
if ($name === '' || $host === '' || $username === '') {
$error = 'Bitte Name, Host und Benutzer angeben.';
} else {
if ($editId > 0) {
$stmt = $pdo->prepare('SELECT * FROM ' . $table('hosts') . ' WHERE id = :id LIMIT 1');
$stmt->execute(['id' => $editId]);
$existing = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
$passwordToStore = $password !== '' ? $password : ($existing['password'] ?? null);
$stmt = $pdo->prepare(
'UPDATE ' . $table('hosts') . ' SET name = :name, host = :host, port = :port, username = :username, auth_type = :auth_type, key_path = :key_path, password = :password, image_url = :image_url WHERE id = :id'
);
$stmt->execute([
'id' => $editId,
'name' => $name,
'host' => $host,
'port' => $port > 0 ? $port : 22,
'username' => $username,
'auth_type' => $authType !== '' ? $authType : 'key',
'key_path' => $keyPath !== '' ? $keyPath : null,
'password' => $passwordToStore,
'image_url' => $imageUrl !== '' ? $imageUrl : null,
]);
$notice = 'Host aktualisiert.';
} else {
$stmt = $pdo->prepare(
'INSERT INTO ' . $table('hosts') . ' (name, host, port, username, auth_type, key_path, password, image_url) VALUES (:name, :host, :port, :username, :auth_type, :key_path, :password, :image_url)'
);
$stmt->execute([
'name' => $name,
'host' => $host,
'port' => $port > 0 ? $port : 22,
'username' => $username,
'auth_type' => $authType !== '' ? $authType : 'key',
'key_path' => $keyPath !== '' ? $keyPath : null,
'password' => $password !== '' ? $password : null,
'image_url' => $imageUrl !== '' ? $imageUrl : null,
]);
$notice = 'Host gespeichert.';
}
}
}
}
$hosts = $pdo->query('SELECT * FROM ' . $table('hosts') . ' ORDER BY id DESC')->fetchAll(PDO::FETCH_ASSOC);
$settings = modules()->settings('pi_control');
$strictHostKey = !empty($settings['terminal_strict_hostkey']);
function hostReachable(string $host, int $port): bool
{
$errno = 0;
$errstr = '';
$fp = @fsockopen($host, $port, $errno, $errstr, 1.2);
if ($fp) {
fclose($fp);
return true;
}
return false;
}
function runSshCommand(string $cmd, int $timeoutSec): int
{
$descriptors = [
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
];
$process = proc_open($cmd, $descriptors, $pipes);
if (!is_resource($process)) {
return 255;
}
stream_set_blocking($pipes[1], false);
stream_set_blocking($pipes[2], false);
$start = time();
while (true) {
$status = proc_get_status($process);
if (!$status['running']) {
$code = (int)$status['exitcode'];
proc_close($process);
return $code;
}
if (time() - $start > $timeoutSec) {
proc_terminate($process, 9);
proc_close($process);
return 124;
}
usleep(100000);
}
}
function runSshCommandCapture(array $host, string $command, bool $strictHostKey, int $timeoutSec): array
{
$hostAddr = (string)($host['host'] ?? '');
$user = (string)($host['username'] ?? '');
$port = (int)($host['port'] ?? 22);
$authType = (string)($host['auth_type'] ?? 'key');
$keyPath = (string)($host['key_path'] ?? '');
$password = (string)($host['password'] ?? '');
$opts = $strictHostKey
? '-o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=/root/.ssh/known_hosts'
: '-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null';
$opts .= ' -o ConnectTimeout=6 -o NumberOfPasswordPrompts=1 -o LogLevel=ERROR -o RequestTTY=no';
$target = escapeshellarg($user . '@' . $hostAddr);
$remote = '/bin/sh -c ' . escapeshellarg($command);
$cmd = 'ssh -T ' . $opts . ' -p ' . (int)$port . ' ';
if ($authType === 'key' && $keyPath !== '') {
$cmd .= '-i ' . escapeshellarg($keyPath) . ' -o BatchMode=yes ';
} elseif ($authType === 'key') {
$cmd .= '-o BatchMode=yes ';
}
$cmd .= $target . ' -- ' . $remote;
if ($authType === 'pass' && $password !== '') {
$cmd = 'sshpass -p ' . escapeshellarg($password) . ' ' . $cmd;
}
$descriptors = [
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
];
$process = proc_open($cmd, $descriptors, $pipes);
if (!is_resource($process)) {
return [255, '', 'proc_open failed'];
}
stream_set_blocking($pipes[1], false);
stream_set_blocking($pipes[2], false);
$out = '';
$err = '';
$start = time();
while (true) {
$status = proc_get_status($process);
$out .= stream_get_contents($pipes[1]);
$err .= stream_get_contents($pipes[2]);
if (!$status['running']) {
$exit = (int)$status['exitcode'];
proc_close($process);
return [$exit, $out, $err];
}
if (time() - $start > $timeoutSec) {
proc_terminate($process, 9);
proc_close($process);
return [124, $out, $err];
}
usleep(100000);
}
}
function hostAuthOk(array $host, bool $strictHostKey): bool
{
$hostAddr = (string)($host['host'] ?? '');
$user = (string)($host['username'] ?? '');
$port = (int)($host['port'] ?? 22);
$authType = (string)($host['auth_type'] ?? 'key');
$keyPath = (string)($host['key_path'] ?? '');
$password = (string)($host['password'] ?? '');
if ($hostAddr === '' || $user === '') {
return false;
}
$opts = $strictHostKey
? '-o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=/root/.ssh/known_hosts'
: '-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null';
$opts .= ' -o ConnectTimeout=2 -o NumberOfPasswordPrompts=1';
$target = escapeshellarg($user . '@' . $hostAddr);
$cmd = 'ssh ' . $opts . ' -p ' . (int)$port . ' ';
if ($authType === 'key' && $keyPath !== '') {
$cmd .= '-i ' . escapeshellarg($keyPath) . ' -o BatchMode=yes ';
} elseif ($authType === 'key') {
$cmd .= '-o BatchMode=yes ';
}
$cmd .= $target . ' -- true';
if ($authType === 'pass') {
if ($password === '') {
return false;
}
$cmd = 'sshpass -p ' . escapeshellarg($password) . ' ' . $cmd;
}
$exitCode = runSshCommand($cmd, 3);
return $exitCode === 0;
}
?>
<?= module_shell_header('pi_control', [
'title' => 'Hosts',
]) ?>
<div class="module-flow">
<section class="module-box">
<div class="module-box-head">
<div>
<h2 class="module-box-title">Hosts</h2>
<p>Verwalte die Raspberry Pis, die du steuern möchtest.</p>
</div>
<div style="display:flex; gap:10px; flex-wrap:wrap;">
<button class="module-button module-button--secondary module-button--small" type="button" data-host-check-all>Alle Hosts prüfen</button>
<button class="module-button module-button--primary" type="button" data-host-new>+ Neuer Host</button>
</div>
</div>
<?php if ($error): ?>
<div class="setup-db-message setup-db-message--error" style="margin-top:16px;">
<?= e($error) ?>
</div>
<?php elseif ($notice): ?>
<div class="setup-db-message setup-db-message--success" style="margin-top:16px;">
<?= e($notice) ?>
</div>
<?php endif; ?>
<div class="module-box-grid module-box-grid--panels" style="margin-top:16px;">
<div class="module-box form-card">
<strong>Registrierte Hosts</strong>
<?php if (!$hosts): ?>
<div class="muted" style="margin-top:.75rem;">Keine Hosts vorhanden.</div>
<?php else: ?>
<div class="host-grid" style="margin-top:.75rem;">
<?php foreach ($hosts as $h): ?>
<div class="host-card"
data-host-id="<?= e((string)$h['id']) ?>"
data-name="<?= e((string)($h['name'] ?? '')) ?>"
data-host="<?= e((string)($h['host'] ?? '')) ?>"
data-port="<?= e((string)($h['port'] ?? 22)) ?>"
data-username="<?= e((string)($h['username'] ?? '')) ?>"
data-auth="<?= e((string)($h['auth_type'] ?? 'key')) ?>"
data-key-path="<?= e((string)($h['key_path'] ?? '')) ?>"
data-image-url="<?= e((string)($h['image_url'] ?? '')) ?>"
data-update-checked="<?= e((string)($h['update_checked_at'] ?? '')) ?>"
data-update-count="<?= e((string)($h['update_count'] ?? '')) ?>"
data-update-error="<?= e((string)($h['update_error'] ?? '')) ?>"
data-update-preview="<?= e((string)($h['update_preview'] ?? '')) ?>"
data-upgrade-available="<?= e((string)($h['upgrade_available'] ?? '')) ?>"
data-upgrade-raw="<?= e((string)($h['upgrade_raw'] ?? '')) ?>"
data-upgrade-error="<?= e((string)($h['upgrade_error'] ?? '')) ?>">
<div class="host-card-image"<?= !empty($h['image_url']) ? ' style="background-image:url(' . e((string)$h['image_url']) . ')"' : '' ?>>
<div class="host-card-overlay"></div>
</div>
<div class="host-card-body">
<div class="host-card-header">
<div class="host-card-title">
<span class="status-dot status-auth" data-host-status></span>
<strong><?= e((string)($h['name'] ?? '')) ?></strong>
</div>
<details class="action-menu">
<summary>☰</summary>
<div class="action-menu-panel">
<button class="nav-link" type="button" data-host-edit>Bearbeiten</button>
<form method="post" onsubmit="return confirm('Host wirklich löschen?')">
<input type="hidden" name="delete_id" value="<?= e((string)$h['id']) ?>">
<button class="nav-link" type="submit">Löschen</button>
</form>
</div>
</details>
</div>
<div class="muted"><?= e((string)($h['host'] ?? '')) ?>:<?= e((string)($h['port'] ?? 22)) ?></div>
<div class="muted"><?= e((string)($h['username'] ?? '')) ?> · <?= e((string)($h['auth_type'] ?? '')) ?></div>
<div class="host-update-row">
<span class="update-badge" data-update-badge>Updates: </span>
<span class="update-badge" data-upgrade-badge>OS: </span>
<span class="muted" data-update-time>Nie geprüft</span>
</div>
<pre class="host-debug" data-update-debug>Update Debug: </pre>
<pre class="host-debug" data-upgrade-debug>Upgrade Debug: </pre>
<div style="display:flex; gap:8px; flex-wrap:wrap;">
<button class="nav-link" type="button" data-host-check>Updates prüfen</button>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>
</div>
</div>
</section>
</div>
<div class="modal" data-host-modal aria-hidden="true">
<div class="modal-card">
<div class="modal-header">
<strong data-host-modal-title>Neuer Host</strong>
<button class="icon-button" type="button" data-host-close>×</button>
</div>
<form method="post" class="form-grid" style="margin-top:.75rem;" data-host-form>
<input type="hidden" name="id" value="">
<label class="form-field">
<span class="muted">Name</span>
<input type="text" name="name" placeholder="z.B. Wohnzimmer-Pi" required title="Eindeutiger Anzeigename für diesen Pi.">
</label>
<label class="form-field">
<span class="muted">Host / IP</span>
<input type="text" name="host" placeholder="z.B. 192.168.178.14 oder pi.local" required title="Hostname oder IP im Heimnetzwerk.">
</label>
<label class="form-field">
<span class="muted">SSH Port</span>
<input type="number" name="port" placeholder="22" value="22" title="Standard ist 22.">
</label>
<label class="form-field">
<span class="muted">SSH Benutzer</span>
<input type="text" name="username" placeholder="z.B. pi" required title="Benutzername auf dem Pi.">
</label>
<label class="form-field">
<span class="muted">Auth-Typ</span>
<select name="auth_type" title="key = SSH-Key, password = Passwort">
<option value="key">key (SSH-Key)</option>
<option value="pass">pass (Passwort)</option>
</select>
</label>
<label class="form-field">
<span class="muted">Key-Pfad (optional)</span>
<input type="text" name="key_path" placeholder="/home/app/.ssh/id_rsa" title="Pfad zum Private-Key im Webserver-Container.">
</label>
<label class="form-field">
<span class="muted">Passwort (optional)</span>
<input type="password" name="password" placeholder="SSH-Passwort" title="Nur nutzen, wenn Auth-Typ = pass.">
</label>
<label class="form-field">
<span class="muted">Bild-URL (optional)</span>
<input type="text" name="image_url" placeholder="https://..." title="Optionales Bild für die Host-Karte.">
</label>
<div style="display:flex; gap:10px; flex-wrap:wrap;">
<button class="cta-button" type="submit" data-host-submit>Speichern</button>
<button class="nav-link" type="button" data-host-cancel>Zurücksetzen</button>
</div>
</form>
</div>
</div>
<?= module_shell_footer() ?>

View File

@@ -0,0 +1,41 @@
<?php
$pdo = module_fn('pi_control', 'pdo');
module_fn('pi_control', 'ensure_schema');
$table = fn(string $name) => module_fn('pi_control', 'table', $name);
$hostCount = (int)$pdo->query('SELECT COUNT(*) FROM ' . $table('hosts'))->fetchColumn();
$cmdCount = (int)$pdo->query('SELECT COUNT(*) FROM ' . $table('commands'))->fetchColumn();
$runCount = (int)$pdo->query('SELECT COUNT(*) FROM ' . $table('runs'))->fetchColumn();
?>
<?= module_shell_header('pi_control', [
'title' => 'Raspberry Pi Steuerung',
]) ?>
<div class="module-flow">
<section class="module-box">
<div class="module-box-head">
<div>
<h2 class="module-box-title">Raspberry Pi Steuerung</h2>
<p>SSH Hosts verwalten, Befehle definieren und Aktionen ausführen.</p>
</div>
</div>
</section>
<div class="module-box-grid module-box-grid--stats">
<div class="module-box-soft">
<strong>Hosts</strong>
<div class="muted" style="margin-top:.35rem;">Registriert: <?= e((string)$hostCount) ?></div>
<div style="margin-top:.75rem;"><a class="module-button module-button--secondary module-button--small" href="/module/pi_control/hosts">Hosts verwalten</a></div>
</div>
<div class="module-box-soft">
<strong>Befehle</strong>
<div class="muted" style="margin-top:.35rem;">Presets: <?= e((string)$cmdCount) ?></div>
<div style="margin-top:.75rem;"><a class="module-button module-button--secondary module-button--small" href="/module/pi_control/commands">Befehle verwalten</a></div>
</div>
<div class="module-box-soft">
<strong>Konsole</strong>
<div class="muted" style="margin-top:.35rem;">Runs: <?= e((string)$runCount) ?></div>
<div style="margin-top:.75rem;"><a class="module-button module-button--secondary module-button--small" href="/module/pi_control/console">Konsole öffnen</a></div>
</div>
</div>
</div>
<?= module_shell_footer() ?>

View File

@@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
$pdo = module_fn('pi_control', 'pdo');
module_fn('pi_control', 'ensure_schema');
$table = fn(string $name) => module_fn('pi_control', 'table', $name);
header('Content-Type: application/json; charset=utf-8');
$settings = modules()->settings('pi_control');
$sharedSecret = trim((string)($settings['terminal_shared_secret'] ?? ''));
if ($sharedSecret !== '') {
$provided = trim((string)($_SERVER['HTTP_X_TERMINAL_SECRET'] ?? ''));
if (!hash_equals($sharedSecret, $provided)) {
http_response_code(401);
echo json_encode(['ok' => false, 'error' => 'unauthorized']);
exit;
}
}
$token = '';
if (!empty($_GET['token'])) {
$token = trim((string)$_GET['token']);
} elseif (!empty($_SERVER['HTTP_X_TERMINAL_TOKEN'])) {
$token = trim((string)$_SERVER['HTTP_X_TERMINAL_TOKEN']);
}
if ($token === '') {
http_response_code(400);
echo json_encode(['ok' => false, 'error' => 'missing_token']);
exit;
}
$driver = (string)$pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
$nowSql = $driver === 'pgsql' ? 'NOW()' : "DATETIME('now')";
$sessionStmt = $pdo->prepare(
'SELECT * FROM ' . $table('sessions') . ' WHERE token = :token AND expires_at > ' . $nowSql . ' LIMIT 1'
);
$sessionStmt->execute(['token' => $token]);
$session = $sessionStmt->fetch(PDO::FETCH_ASSOC);
if (!$session) {
http_response_code(404);
echo json_encode(['ok' => false, 'error' => 'invalid_or_expired']);
exit;
}
$hostStmt = $pdo->prepare('SELECT * FROM ' . $table('hosts') . ' WHERE id = :id LIMIT 1');
$hostStmt->execute(['id' => (int)$session['host_id']]);
$host = $hostStmt->fetch(PDO::FETCH_ASSOC);
if (!$host) {
http_response_code(404);
echo json_encode(['ok' => false, 'error' => 'host_not_found']);
exit;
}
$pdo->prepare('UPDATE ' . $table('sessions') . ' SET last_used_at = ' . $nowSql . ' WHERE id = :id')
->execute(['id' => (int)$session['id']]);
$commandText = (string)($session['command_text'] ?? '');
if ($commandText !== '') {
$pdo->prepare('UPDATE ' . $table('sessions') . ' SET command_text = NULL WHERE id = :id')
->execute(['id' => (int)$session['id']]);
}
echo json_encode([
'ok' => true,
'host' => [
'name' => (string)($host['name'] ?? ''),
'host' => (string)($host['host'] ?? ''),
'port' => (int)($host['port'] ?? 22),
'username' => (string)($host['username'] ?? ''),
'auth_type' => (string)($host['auth_type'] ?? 'key'),
'key_path' => (string)($host['key_path'] ?? ''),
'password' => (string)($host['password'] ?? ''),
],
'command' => $commandText,
'strict_hostkey' => !empty($settings['terminal_strict_hostkey']),
'tmux_session' => (string)($settings['terminal_tmux_session'] ?? ''),
]);
exit;