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, ]); exit;