From f8b876b2d5eda57eb066fbee0e630b91e28102cb Mon Sep 17 00:00:00 2001 From: Dev-lib4n Date: Wed, 18 Nov 2026 15:03:28 -0300 Subject: [PATCH 1/5] feat(network): add probe, wifi, reset, ssl, lan scan, and public IP commands --- app/Commands/Network/LanScanCommand.php | 75 ++++ app/Commands/Network/NetResetCommand.php | 63 ++++ app/Commands/Network/ProbeCommand.php | 114 ++++++ app/Commands/Network/PublicIpCommand.php | 48 +++ app/Commands/Network/SslCheckCommand.php | 63 ++++ app/Commands/Network/WifiCommand.php | 55 +++ app/Commands/ToolboxMenuCommand.php | 6 + app/Contracts/SystemDriverInterface.php | 48 +++ .../Concerns/InteractsWithNetworkSockets.php | 326 ++++++++++++++++++ app/Drivers/LinuxDriver.php | 209 +++++++++++ app/Drivers/WindowsDriver.php | 159 +++++++++ lang/en/messages.php | 70 ++++ lang/pt_BR/messages.php | 70 ++++ tests/Feature/ReportExporterTest.php | 30 ++ tests/Unit/HealthCheckServiceTest.php | 30 ++ tests/Unit/LinuxDriverTest.php | 62 ++++ tests/Unit/WindowsDriverTest.php | 78 +++++ 17 files changed, 1506 insertions(+) create mode 100644 app/Commands/Network/LanScanCommand.php create mode 100644 app/Commands/Network/NetResetCommand.php create mode 100644 app/Commands/Network/ProbeCommand.php create mode 100644 app/Commands/Network/PublicIpCommand.php create mode 100644 app/Commands/Network/SslCheckCommand.php create mode 100644 app/Commands/Network/WifiCommand.php create mode 100644 app/Drivers/Concerns/InteractsWithNetworkSockets.php diff --git a/app/Commands/Network/LanScanCommand.php b/app/Commands/Network/LanScanCommand.php new file mode 100644 index 0000000..e59736a --- /dev/null +++ b/app/Commands/Network/LanScanCommand.php @@ -0,0 +1,75 @@ +resolveLocale(); + + info((string) __('messages.network.scan_section')); + + /** @var array $devices */ + $devices = spin( + callback: fn (): array => $driver->scanLanDevices(), + message: (string) __('messages.spinners.network_scan'), + ); + + if ($devices === []) { + warning((string) __('messages.network.no_lan_devices')); + + return self::SUCCESS; + } + + table( + headers: [ + (string) __('messages.network.scan_headers.ip'), + (string) __('messages.network.scan_headers.mac'), + (string) __('messages.network.scan_headers.status'), + (string) __('messages.network.scan_headers.interface'), + ], + rows: array_map( + fn (array $device): array => [ + $device['ip'] ?? '-', + $device['mac'] ?? '-', + $device['status'] ?? '-', + $device['interface'] ?? '-', + ], + $devices + ), + ); + + return self::SUCCESS; + } +} diff --git a/app/Commands/Network/NetResetCommand.php b/app/Commands/Network/NetResetCommand.php new file mode 100644 index 0000000..afe4a51 --- /dev/null +++ b/app/Commands/Network/NetResetCommand.php @@ -0,0 +1,63 @@ +resolveLocale(); + + info((string) __('messages.network.reset_section')); + + if (! $this->option('force') && ! confirm( + label: (string) __('messages.network.confirm_reset'), + default: false, + yes: (string) __('messages.common.yes'), + no: (string) __('messages.common.no'), + )) { + warning((string) __('messages.common.cancelled')); + + return self::SUCCESS; + } + + $result = spin( + callback: fn () => $driver->resetNetworkStack(), + message: (string) __('messages.spinners.network_reset'), + ); + + return $this->renderActionResult($result); + } +} diff --git a/app/Commands/Network/ProbeCommand.php b/app/Commands/Network/ProbeCommand.php new file mode 100644 index 0000000..5ea4c00 --- /dev/null +++ b/app/Commands/Network/ProbeCommand.php @@ -0,0 +1,114 @@ +resolveLocale(); + + info((string) __('messages.network.probe_section')); + + $hostArg = $this->argument('host'); + $host = is_string($hostArg) && trim($hostArg) !== '' + ? trim($hostArg) + : text( + label: (string) __('messages.network.probe_host_prompt'), + default: '1.1.1.1', + required: true, + ); + + $portArg = $this->argument('port'); + $portStr = is_string($portArg) && trim($portArg) !== '' + ? trim($portArg) + : text( + label: (string) __('messages.network.probe_port_prompt'), + default: '443', + required: true, + validate: fn (string $val): ?string => (is_numeric($val) && (int) $val >= 1 && (int) $val <= 65535) + ? null + : (string) __('messages.network.probe_invalid_port'), + ); + + $port = max(1, min(65535, (int) $portStr)); + $timeout = max(1, (int) $this->option('timeout')); + + $result = spin( + callback: fn (): array => $driver->probePort($host, $port, $timeout), + message: (string) __('messages.spinners.network_probe', ['host' => $host, 'port' => $port]), + ); + + table( + headers: [ + (string) __('messages.network.probe_headers.host'), + (string) __('messages.network.probe_headers.port'), + (string) __('messages.network.probe_headers.status'), + (string) __('messages.network.probe_headers.latency'), + (string) __('messages.network.probe_headers.details'), + ], + rows: [ + [ + $result['host'], + (string) $result['port'], + $result['status'], + $result['latency'], + $result['error'], + ], + ], + ); + + if ($result['status'] === 'OPEN') { + info((string) __('messages.network.probe_open_success', [ + 'host' => $result['host'], + 'port' => $result['port'], + 'latency' => $result['latency'], + ])); + + return self::SUCCESS; + } + + error((string) __('messages.network.probe_failed', [ + 'host' => $result['host'], + 'port' => $result['port'], + 'status' => $result['status'], + ])); + + return self::FAILURE; + } +} diff --git a/app/Commands/Network/PublicIpCommand.php b/app/Commands/Network/PublicIpCommand.php new file mode 100644 index 0000000..8af796b --- /dev/null +++ b/app/Commands/Network/PublicIpCommand.php @@ -0,0 +1,48 @@ +resolveLocale(); + + info((string) __('messages.network.public_section')); + + $result = spin( + callback: fn () => $driver->getPublicIpInfo(), + message: (string) __('messages.spinners.network_public'), + ); + + return $this->renderActionResult($result); + } +} diff --git a/app/Commands/Network/SslCheckCommand.php b/app/Commands/Network/SslCheckCommand.php new file mode 100644 index 0000000..f7a0daf --- /dev/null +++ b/app/Commands/Network/SslCheckCommand.php @@ -0,0 +1,63 @@ +resolveLocale(); + + info((string) __('messages.network.ssl_section')); + + $domainArg = $this->argument('domain'); + $domain = is_string($domainArg) && trim($domainArg) !== '' + ? trim($domainArg) + : text( + label: (string) __('messages.network.ssl_domain_prompt'), + default: 'google.com', + required: true, + ); + + $port = max(1, min(65535, (int) $this->option('port'))); + + $result = spin( + callback: fn () => $driver->checkSslCertificate($domain, $port), + message: (string) __('messages.spinners.network_ssl', ['domain' => $domain]), + ); + + return $this->renderActionResult($result); + } +} diff --git a/app/Commands/Network/WifiCommand.php b/app/Commands/Network/WifiCommand.php new file mode 100644 index 0000000..45d29e7 --- /dev/null +++ b/app/Commands/Network/WifiCommand.php @@ -0,0 +1,55 @@ +resolveLocale(); + + info((string) __('messages.network.wifi_section')); + + $result = spin( + callback: fn () => $driver->getWifiInfo(), + message: (string) __('messages.spinners.network_wifi'), + ); + + if (! $result->success) { + warning((string) __($result->message)); + + return self::SUCCESS; + } + + return $this->renderActionResult($result); + } +} diff --git a/app/Commands/ToolboxMenuCommand.php b/app/Commands/ToolboxMenuCommand.php index 912bc32..078bd04 100644 --- a/app/Commands/ToolboxMenuCommand.php +++ b/app/Commands/ToolboxMenuCommand.php @@ -169,6 +169,12 @@ protected function handleCategorySubmenu(string $category, string $locale): void '1' => ['label' => (string) __('messages.menu.actions.network_check'), 'command' => 'network:check'], '2' => ['label' => (string) __('messages.menu.actions.network_flush'), 'command' => 'network:flush'], '3' => ['label' => (string) __('messages.menu.actions.network_ports'), 'command' => 'network:ports'], + '4' => ['label' => (string) __('messages.menu.actions.network_probe'), 'command' => 'network:probe'], + '5' => ['label' => (string) __('messages.menu.actions.network_wifi'), 'command' => 'network:wifi'], + '6' => ['label' => (string) __('messages.menu.actions.network_reset'), 'command' => 'network:reset'], + '7' => ['label' => (string) __('messages.menu.actions.network_ssl'), 'command' => 'network:ssl'], + '8' => ['label' => (string) __('messages.menu.actions.network_scan'), 'command' => 'network:scan'], + '9' => ['label' => (string) __('messages.menu.actions.network_public'), 'command' => 'network:public'], ], 'maintenance' => [ '1' => ['label' => (string) __('messages.menu.actions.clean_temp'), 'command' => 'clean:temp'], diff --git a/app/Contracts/SystemDriverInterface.php b/app/Contracts/SystemDriverInterface.php index d74c41a..c16e1d7 100644 --- a/app/Contracts/SystemDriverInterface.php +++ b/app/Contracts/SystemDriverInterface.php @@ -95,6 +95,54 @@ public function flushDnsAndRenew(): ActionResult; */ public function getListeningPorts(): array; + /** + * Probe a remote TCP host and port and measure connection latency in milliseconds. + * + * @param string $host + * @param int $port + * @param int $timeout + * @return array{host: string, port: int, status: string, latency: string, error: string} + */ + public function probePort(string $host, int $port, int $timeout = 3): array; + + /** + * Retrieve wireless (Wi-Fi) adapter connection metrics (SSID, BSSID, Signal, Channel, Band, Rates). + * + * @return ActionResult + */ + public function getWifiInfo(): ActionResult; + + /** + * Perform a complete network stack reset (Winsock/IP reset on Windows; NetworkManager/DHCP on Linux). + * + * @return ActionResult + */ + public function resetNetworkStack(): ActionResult; + + /** + * Inspect an HTTPS domain's SSL/TLS certificate (CN, Issuer, Validity dates, Days remaining, SANs). + * + * @param string $domain + * @param int $port + * @param int $timeout + * @return ActionResult + */ + public function checkSslCertificate(string $domain, int $port = 443, int $timeout = 5): ActionResult; + + /** + * Discover active devices on the local area network (ARP cache + local subnet discovery). + * + * @return array + */ + public function scanLanDevices(): array; + + /** + * Retrieve external public IP address, geolocation, ISP/ASN, and reverse hostname. + * + * @return ActionResult + */ + public function getPublicIpInfo(): ActionResult; + /** * Clean system and user temporary directories safely. * diff --git a/app/Drivers/Concerns/InteractsWithNetworkSockets.php b/app/Drivers/Concerns/InteractsWithNetworkSockets.php new file mode 100644 index 0000000..413dd39 --- /dev/null +++ b/app/Drivers/Concerns/InteractsWithNetworkSockets.php @@ -0,0 +1,326 @@ +sanitizeHost($host); + $safePort = max(1, min(65535, $port)); + $safeTimeout = max(1, $timeout); + + $errno = 0; + $errstr = ''; + $startNs = hrtime(true); + + $socket = @stream_socket_client( + sprintf('tcp://%s:%d', $cleanHost, $safePort), + $errno, + $errstr, + $safeTimeout, + STREAM_CLIENT_CONNECT + ); + + $elapsedMs = round((hrtime(true) - $startNs) / 1_000_000, 2); + + if (is_resource($socket)) { + @fclose($socket); + + return [ + 'host' => $cleanHost, + 'port' => $safePort, + 'status' => 'OPEN', + 'latency' => sprintf('%.2f ms', $elapsedMs), + 'error' => '-', + ]; + } + + $lowerErr = strtolower($errstr); + $isTimeout = $errno === 110 + || $errno === 10060 + || str_contains($lowerErr, 'timed out') + || str_contains($lowerErr, 'timeout'); + + return [ + 'host' => $cleanHost, + 'port' => $safePort, + 'status' => $isTimeout ? 'TIMEOUT' : 'CLOSED', + 'latency' => '-', + 'error' => $errstr !== '' ? trim($errstr) : ($isTimeout ? 'Connection timed out' : 'Connection refused'), + ]; + } + + /** + * Inspect an HTTPS domain's SSL/TLS certificate (CN, Issuer, Validity dates, Days remaining, SANs). + */ + public function checkSslCertificate(string $domain, int $port = 443, int $timeout = 5): ActionResult + { + $cleanDomain = $this->sanitizeHost($domain); + $safePort = max(1, min(65535, $port)); + $safeTimeout = max(1, $timeout); + + $context = stream_context_create([ + 'ssl' => [ + 'capture_peer_cert' => true, + 'verify_peer' => false, + 'verify_peer_name' => false, + 'SNI_enabled' => true, + 'peer_name' => $cleanDomain, + ], + ]); + + $errno = 0; + $errstr = ''; + $client = @stream_socket_client( + sprintf('ssl://%s:%d', $cleanDomain, $safePort), + $errno, + $errstr, + $safeTimeout, + STREAM_CLIENT_CONNECT, + $context + ); + + if (! is_resource($client)) { + return new ActionResult( + success: false, + message: 'messages.network.ssl_connect_failed', + details: [ + 'domain' => $cleanDomain, + 'port' => $safePort, + 'error' => $errstr !== '' ? trim($errstr) : 'TLS handshake failed', + ], + ); + } + + $params = stream_context_get_params($client); + @fclose($client); + + $certResource = $params['options']['ssl']['peer_certificate'] ?? null; + if ($certResource === null) { + return new ActionResult( + success: false, + message: 'messages.network.ssl_connect_failed', + details: [ + 'domain' => $cleanDomain, + 'port' => $safePort, + 'error' => 'No peer certificate returned by server.', + ], + ); + } + + $parsed = @openssl_x509_parse($certResource); + if (! is_array($parsed)) { + return new ActionResult( + success: false, + message: 'messages.network.ssl_connect_failed', + details: [ + 'domain' => $cleanDomain, + 'port' => $safePort, + 'error' => 'Failed to parse X.509 certificate structure.', + ], + ); + } + + return $this->formatParsedSslCertificate($cleanDomain, $safePort, $parsed); + } + + /** + * Format a parsed openssl_x509_parse() array into a standardized ActionResult. + * + * @param array $parsed + */ + protected function formatParsedSslCertificate(string $domain, int $port, array $parsed): ActionResult + { + $subjectCn = (string) ($parsed['subject']['CN'] ?? $domain); + $issuerOrg = (string) ($parsed['issuer']['O'] ?? $parsed['issuer']['CN'] ?? 'Unknown Issuer'); + $issuerCn = (string) ($parsed['issuer']['CN'] ?? ''); + $issuer = ($issuerCn !== '' && $issuerCn !== $issuerOrg) + ? sprintf('%s (%s)', $issuerOrg, $issuerCn) + : $issuerOrg; + + $validFromTs = (int) ($parsed['validFrom_time_t'] ?? 0); + $validToTs = (int) ($parsed['validTo_time_t'] ?? 0); + + $validFrom = $validFromTs > 0 ? gmdate('Y-m-d H:i:s \U\T\C', $validFromTs) : 'N/A'; + $validTo = $validToTs > 0 ? gmdate('Y-m-d H:i:s \U\T\C', $validToTs) : 'N/A'; + + $daysRemaining = (int) floor(($validToTs - time()) / 86400); + if ($daysRemaining < 0) { + $daysLabel = sprintf('❌ %d (%s)', $daysRemaining, (string) __('messages.network.ssl_expired')); + } elseif ($daysRemaining < 30) { + $daysLabel = sprintf('⚠️ %d (%s)', $daysRemaining, (string) __('messages.network.ssl_expiring_soon')); + } else { + $daysLabel = sprintf('✅ %d', $daysRemaining); + } + + $rawSans = (string) ($parsed['extensions']['subjectAltName'] ?? ''); + $sansList = []; + foreach (explode(',', $rawSans) as $part) { + $part = trim($part); + if (str_starts_with($part, 'DNS:')) { + $sansList[] = substr($part, 4); + } + } + $sansFormatted = $sansList !== [] ? implode(', ', array_slice($sansList, 0, 8)) : $subjectCn; + + return new ActionResult( + success: true, + message: 'messages.network.ssl_valid_success', + details: [ + 'domain' => sprintf('%s:%d', $domain, $port), + 'subject_cn' => $subjectCn, + 'issuer' => $issuer, + 'valid_from' => $validFrom, + 'valid_to' => $validTo, + 'days_remaining' => $daysLabel, + 'sans' => $sansFormatted, + ], + ); + } + + /** + * Retrieve external public IP address, geolocation, ISP/ASN, and reverse hostname. + */ + public function getPublicIpInfo(): ActionResult + { + $endpoints = [ + 'https://ipinfo.io/json', + 'https://api.ipify.org?format=json', + ]; + + foreach ($endpoints as $url) { + $raw = $this->fetchPublicEndpoint($url, 4); + if ($raw === null || $raw === '') { + continue; + } + + $decoded = json_decode($raw, true); + if (! is_array($decoded) || empty($decoded['ip'])) { + continue; + } + + return $this->formatPublicIpPayload($decoded); + } + + return new ActionResult( + success: false, + message: 'messages.network.public_ip_failed', + details: [], + ); + } + + /** + * Format decoded JSON from ipinfo.io or ipify into a standardized ActionResult. + * + * @param array $decoded + */ + protected function formatPublicIpPayload(array $decoded): ActionResult + { + $ip = trim((string) ($decoded['ip'] ?? '-')); + $locationParts = array_filter([ + trim((string) ($decoded['city'] ?? '')), + trim((string) ($decoded['region'] ?? '')), + trim((string) ($decoded['country'] ?? '')), + ], fn (string $val): bool => $val !== ''); + + $location = $locationParts !== [] ? implode(', ', $locationParts) : 'N/A'; + $isp = trim((string) ($decoded['org'] ?? '')) ?: 'N/A'; + $hostname = trim((string) ($decoded['hostname'] ?? '')); + + if ($hostname === '' && filter_var($ip, FILTER_VALIDATE_IP) !== false) { + $resolved = @gethostbyaddr($ip); + $hostname = ($resolved !== false && $resolved !== $ip) ? $resolved : 'N/A'; + } + + return new ActionResult( + success: true, + message: 'messages.network.public_ip_success', + details: [ + 'public_ip' => $ip, + 'location' => $location, + 'isp' => $isp, + 'reverse_hostname' => $hostname !== '' ? $hostname : 'N/A', + ], + ); + } + + /** + * Perform a fast HTTPS GET request with a 4-second timeout. + */ + protected function fetchPublicEndpoint(string $url, int $timeout = 4): ?string + { + $context = stream_context_create([ + 'http' => [ + 'method' => 'GET', + 'header' => "User-Agent: it-toolbox-cli\r\nAccept: application/json\r\n", + 'timeout' => $timeout, + 'follow_location' => 1, + ], + 'ssl' => [ + 'verify_peer' => true, + 'verify_peer_name' => true, + ], + ]); + + try { + $result = @file_get_contents($url, false, $context); + + return $result === false ? null : $result; + } catch (Throwable) { + return null; + } + } + + /** + * Strip scheme, path, and port suffixes from a hostname or IP string. + */ + protected function sanitizeHost(string $host): string + { + $clean = trim($host); + $clean = (string) preg_replace('#^https?://#i', '', $clean); + $clean = explode('/', $clean)[0]; + + if (substr_count($clean, ':') === 1 && ! str_starts_with($clean, '[')) { + $clean = explode(':', $clean)[0]; + } + + return trim($clean, " \t\n\r\0\x0B[]"); + } + + /** + * Determine whether an IPv4 and MAC pair represents a real unicast LAN neighbor (excluding multicast/broadcast). + */ + protected function isUnicastLanNeighbor(string $ip, string $mac): bool + { + if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) { + return false; + } + + if (str_starts_with($ip, '127.') || str_ends_with($ip, '.255') || $ip === '255.255.255.255') { + return false; + } + + $firstOctet = (int) explode('.', $ip)[0]; + if ($firstOctet >= 224 && $firstOctet <= 239) { + return false; + } + + $normalizedMac = strtolower(str_replace('-', ':', trim($mac))); + if ($normalizedMac === '' || $normalizedMac === 'ff:ff:ff:ff:ff:ff' || $normalizedMac === '00:00:00:00:00:00' || str_starts_with($normalizedMac, '01:00:5e')) { + return false; + } + + return true; + } +} diff --git a/app/Drivers/LinuxDriver.php b/app/Drivers/LinuxDriver.php index 88ae3ec..5cc2d4f 100644 --- a/app/Drivers/LinuxDriver.php +++ b/app/Drivers/LinuxDriver.php @@ -6,6 +6,7 @@ use App\Contracts\ProcessExecutorInterface; use App\Contracts\SystemDriverInterface; +use App\Drivers\Concerns\InteractsWithNetworkSockets; use App\DTOs\ActionResult; use App\Services\SymfonyProcessExecutor; use Closure; @@ -15,6 +16,7 @@ class LinuxDriver implements SystemDriverInterface { + use InteractsWithNetworkSockets; /** * Real block/disk filesystem types to include in storage health checks. * @@ -677,6 +679,213 @@ public function getListeningPorts(): array return []; } + /** + * {@inheritDoc} + */ + public function getWifiInfo(): ActionResult + { + $nmcliResult = $this->processRunner->run([ + 'nmcli', + '-t', + '-f', + 'ACTIVE,SSID,BSSID,CHAN,FREQ,RATE,SIGNAL', + 'dev', + 'wifi', + ]); + + if ($nmcliResult->successful && $nmcliResult->output !== '') { + $lines = preg_split('/\r\n|\r|\n/', trim($nmcliResult->output)) ?: []; + foreach ($lines as $line) { + $line = trim($line); + if ($line === '') { + continue; + } + + // Split on unescaped colons (nmcli escapes colons inside BSSID as \:) + $parts = preg_split('/(? 'wlan0 (nmcli)', + 'state' => 'Connected', + 'ssid' => $ssid !== '' ? $ssid : '-', + 'bssid' => $bssid !== '' ? $bssid : '-', + 'signal' => $signal !== '' && ! str_ends_with($signal, '%') ? $signal . '%' : ($signal ?: '-'), + 'channel' => $chan !== '' ? $chan : '-', + 'band' => $freq !== '' ? $freq : '-', + 'rx_rate' => $rate !== '' ? $rate : '-', + 'tx_rate' => $rate !== '' ? $rate : '-', + 'driver' => 'Linux', + ], + ); + } + } + + // Fallback to `iw dev` + $iwResult = $this->processRunner->run(['iw', 'dev']); + if ($iwResult->successful && $iwResult->output !== '') { + if (preg_match('/Interface\s+(\S+)/', $iwResult->output, $ifaceMatch) === 1) { + $iface = $ifaceMatch[1]; + $ssid = preg_match('/ssid\s+(.+)$/m', $iwResult->output, $ssidMatch) === 1 ? trim($ssidMatch[1]) : '-'; + $chan = preg_match('/channel\s+(\d+)\s+\(([^)]+)\)/', $iwResult->output, $chanMatch) === 1 + ? $chanMatch[1] + : '-'; + $freq = isset($chanMatch[2]) ? trim($chanMatch[2]) : '-'; + + return new ActionResult( + success: true, + message: 'messages.network.wifi_fetched_success', + details: [ + 'interface' => $iface, + 'state' => $ssid !== '-' ? 'Connected' : 'Disconnected', + 'ssid' => $ssid, + 'bssid' => '-', + 'signal' => '-', + 'channel' => $chan, + 'band' => $freq, + 'rx_rate' => '-', + 'tx_rate' => '-', + 'driver' => 'Linux', + ], + ); + } + } + + return new ActionResult( + success: false, + message: 'messages.network.no_wifi', + details: ['driver' => 'Linux'], + ); + } + + /** + * {@inheritDoc} + */ + public function resetNetworkStack(): ActionResult + { + if (! $this->isRoot()) { + return new ActionResult( + success: false, + message: 'messages.common.permission_denied', + details: ['driver' => 'Linux'], + ); + } + + $executed = []; + + $nmRestart = $this->processRunner->run(['systemctl', 'restart', 'NetworkManager']); + if ($nmRestart->successful) { + $executed[] = 'systemctl restart NetworkManager'; + } else { + $networkdRestart = $this->processRunner->run(['systemctl', 'restart', 'systemd-networkd']); + if ($networkdRestart->successful) { + $executed[] = 'systemctl restart systemd-networkd'; + } + } + + if ($this->commandExists('dhclient')) { + $this->processRunner->run(['dhclient', '-r']); + $this->processRunner->run(['dhclient']); + $executed[] = 'dhclient -r && dhclient'; + } + + if ($executed === []) { + return new ActionResult( + success: false, + message: 'messages.network.reset_failed', + details: ['driver' => 'Linux'], + ); + } + + return new ActionResult( + success: true, + message: 'messages.network.reset_success', + details: [ + 'commands_executed' => $executed, + 'driver' => 'Linux', + ], + ); + } + + /** + * {@inheritDoc} + */ + public function scanLanDevices(): array + { + $neighResult = $this->processRunner->run(['ip', 'neigh', 'show']); + if ($neighResult->successful && $neighResult->output !== '') { + $devices = []; + $lines = preg_split('/\r\n|\r|\n/', trim($neighResult->output)) ?: []; + foreach ($lines as $line) { + $line = trim($line); + if (preg_match('/^([0-9]{1,3}(?:\.[0-9]{1,3}){3})\s+dev\s+(\S+)\s+lladdr\s+([0-9a-fA-F:]{17})\s+(\S+)/', $line, $m) === 1) { + $ip = $m[1]; + $iface = $m[2]; + $mac = strtoupper($m[3]); + $state = strtoupper($m[4]); + + if (! $this->isUnicastLanNeighbor($ip, $mac)) { + continue; + } + + $devices[] = [ + 'ip' => $ip, + 'mac' => $mac, + 'status' => $state, + 'interface' => $iface, + ]; + } + } + + return $devices; + } + + $arpResult = $this->processRunner->run(['arp', '-n']); + if ($arpResult->successful && $arpResult->output !== '') { + $devices = []; + $lines = preg_split('/\r\n|\r|\n/', trim($arpResult->output)) ?: []; + foreach ($lines as $line) { + if (preg_match('/^([0-9]{1,3}(?:\.[0-9]{1,3}){3})\s+\S+\s+([0-9a-fA-F:]{17})\s+\S+\s+(\S+)/', trim($line), $m) === 1) { + $ip = $m[1]; + $mac = strtoupper($m[2]); + $iface = $m[3]; + + if (! $this->isUnicastLanNeighbor($ip, $mac)) { + continue; + } + + $devices[] = [ + 'ip' => $ip, + 'mac' => $mac, + 'status' => 'REACHABLE', + 'interface' => $iface, + ]; + } + } + + return $devices; + } + + return []; + } + /** * {@inheritDoc} */ diff --git a/app/Drivers/WindowsDriver.php b/app/Drivers/WindowsDriver.php index 96eb920..f6a6a0d 100644 --- a/app/Drivers/WindowsDriver.php +++ b/app/Drivers/WindowsDriver.php @@ -6,12 +6,15 @@ use App\Contracts\ProcessExecutorInterface; use App\Contracts\SystemDriverInterface; +use App\Drivers\Concerns\InteractsWithNetworkSockets; use App\DTOs\ActionResult; use App\DTOs\ProcessResult; use App\Services\SymfonyProcessExecutor; class WindowsDriver implements SystemDriverInterface { + use InteractsWithNetworkSockets; + private const UTF8_PREAMBLE = '[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; $OutputEncoding = [System.Text.Encoding]::UTF8; '; public function __construct( @@ -683,6 +686,162 @@ public function getListeningPorts(): array return $ports; } + /** + * {@inheritDoc} + */ + public function getWifiInfo(): ActionResult + { + $result = $this->runPowerShell('netsh wlan show interfaces'); + $output = trim($result->output); + + if (! $result->successful || $output === '') { + return new ActionResult( + success: false, + message: 'messages.network.no_wifi', + details: ['driver' => 'Windows'], + ); + } + + $lower = strtolower($output); + if (str_contains($lower, 'no wireless interface') + || str_contains($lower, 'não há interface sem fio') + || str_contains($lower, 'is not running') + || str_contains($lower, 'não está em execução')) { + return new ActionResult( + success: false, + message: 'messages.network.no_wifi', + details: ['driver' => 'Windows'], + ); + } + + $fields = []; + $lines = preg_split('/\r\n|\r|\n/', $output) ?: []; + foreach ($lines as $line) { + if (preg_match('/^\s*([^:]+?)\s*:\s*(.+)$/', $line, $matches) === 1) { + $key = strtolower(trim($matches[1])); + $val = trim($matches[2]); + $fields[$key] = $val; + } + } + + $ssid = $fields['ssid'] ?? ''; + $interface = $fields['name'] ?? $fields['nome'] ?? 'Wi-Fi'; + $state = $fields['state'] ?? $fields['estado'] ?? 'disconnected'; + + if ($ssid === '' && ! isset($fields['name']) && ! isset($fields['nome'])) { + return new ActionResult( + success: false, + message: 'messages.network.no_wifi', + details: ['driver' => 'Windows'], + ); + } + + $rxRate = $fields['receive rate (mbps)'] ?? $fields['taxa de recepção (mbps)'] ?? '-'; + $txRate = $fields['transmit rate (mbps)'] ?? $fields['taxa de transmissão (mbps)'] ?? '-'; + + return new ActionResult( + success: true, + message: 'messages.network.wifi_fetched_success', + details: [ + 'interface' => $interface, + 'state' => $state, + 'ssid' => $ssid !== '' ? $ssid : '-', + 'bssid' => $fields['bssid'] ?? '-', + 'signal' => $fields['signal'] ?? $fields['sinal'] ?? '-', + 'channel' => $fields['channel'] ?? $fields['canal'] ?? '-', + 'band' => $fields['band'] ?? $fields['banda'] ?? $fields['radio type'] ?? $fields['tipo de rádio'] ?? '-', + 'rx_rate' => $rxRate !== '-' && ! str_contains(strtolower($rxRate), 'mbps') ? $rxRate . ' Mbps' : $rxRate, + 'tx_rate' => $txRate !== '-' && ! str_contains(strtolower($txRate), 'mbps') ? $txRate . ' Mbps' : $txRate, + 'driver' => 'Windows', + ], + ); + } + + /** + * {@inheritDoc} + */ + public function resetNetworkStack(): ActionResult + { + $adminCheck = $this->processRunner->run(['net', 'session'], 5); + if (! $adminCheck->successful) { + return new ActionResult( + success: false, + message: 'messages.common.permission_denied', + details: ['driver' => 'Windows'], + ); + } + + $steps = [ + ['cmd' => ['ipconfig', '/release'], 'label' => 'ipconfig /release'], + ['cmd' => ['ipconfig', '/flushdns'], 'label' => 'ipconfig /flushdns'], + ['cmd' => ['netsh', 'winsock', 'reset'], 'label' => 'netsh winsock reset'], + ['cmd' => ['netsh', 'int', 'ip', 'reset'], 'label' => 'netsh int ip reset'], + ['cmd' => ['ipconfig', '/renew'], 'label' => 'ipconfig /renew'], + ]; + + $executed = []; + foreach ($steps as $step) { + $this->processRunner->run($step['cmd'], 30); + $executed[] = $step['label']; + } + + return new ActionResult( + success: true, + message: 'messages.network.reset_success', + details: [ + 'commands_executed' => $executed, + 'driver' => 'Windows', + ], + ); + } + + /** + * {@inheritDoc} + */ + public function scanLanDevices(): array + { + $arpResult = $this->processRunner->run(['arp', '-a']); + if (! $arpResult->successful || $arpResult->output === '') { + return []; + } + + $devices = []; + $currentInterface = 'LAN'; + $lines = preg_split('/\r\n|\r|\n/', $arpResult->output) ?: []; + + foreach ($lines as $line) { + $line = trim($line); + if ($line === '') { + continue; + } + + if (preg_match('/^Interface:\s+([0-9.]+)/i', $line, $ifaceMatch) === 1) { + $currentInterface = $ifaceMatch[1]; + + continue; + } + + if (preg_match('/^([0-9]{1,3}(?:\.[0-9]{1,3}){3})\s+([0-9a-fA-F:-]{17})\s+(\S+)/', $line, $entryMatch) === 1) { + $ip = $entryMatch[1]; + $mac = strtoupper(str_replace('-', ':', $entryMatch[2])); + $type = ucfirst(strtolower($entryMatch[3])); + + if (! $this->isUnicastLanNeighbor($ip, $mac)) { + continue; + } + + $devices[] = [ + 'ip' => $ip, + 'mac' => $mac, + 'status' => $type, + 'interface' => $currentInterface, + ]; + } + } + + return $devices; + } + /** * {@inheritDoc} */ diff --git a/lang/en/messages.php b/lang/en/messages.php index c4377d3..7d62332 100644 --- a/lang/en/messages.php +++ b/lang/en/messages.php @@ -48,6 +48,12 @@ 'network_check' => 'Interfaces & Connectivity Health Check (network:check)', 'network_flush' => 'Flush DNS Cache & Renew IP Lease (network:flush)', 'network_ports' => 'Inspect Open Listening Ports (network:ports)', + 'network_probe' => 'Test Remote TCP Port & Measure Latency (network:probe)', + 'network_wifi' => 'Inspect Wi-Fi Signal, SSID, Channel & Speed (network:wifi)', + 'network_reset' => 'Full Network Stack Reset — Winsock/IP/DHCP (network:reset)', + 'network_ssl' => 'Inspect HTTPS SSL/TLS Certificate & Expiration (network:ssl)', + 'network_scan' => 'Discover Active Devices on Local Network (network:scan)', + 'network_public' => 'View External Public IP, Geolocation & ISP (network:public)', 'clean_temp' => 'Clean System & User Temporary Files (clean:temp)', 'report_export' => 'Export Full System Diagnostic Report (report:export)', ], @@ -76,6 +82,12 @@ 'network_check' => 'Inspecting network interfaces and testing connectivity...', 'network_flush' => 'Flushing DNS resolver cache and renewing network lease...', 'network_ports' => 'Scanning active listening TCP/UDP ports...', + 'network_probe' => 'Probing TCP connection to :host::port...', + 'network_wifi' => 'Querying wireless adapter signal and radio metrics...', + 'network_reset' => 'Resetting network stack, Winsock/IP configuration, and renewing DHCP lease...', + 'network_ssl' => 'Inspecting SSL/TLS certificate for :domain...', + 'network_scan' => 'Scanning local network ARP cache and active neighbors...', + 'network_public' => 'Querying external public IP address and ISP geolocation...', 'clean_temp' => 'Scanning and removing temporary files safely...', 'report_export' => 'Generating full diagnostic report...', 'self_update_check' => 'Checking GitHub Releases for newer versions...', @@ -230,6 +242,43 @@ 'confirm_flush' => 'This will flush the DNS cache and renew network configuration (may briefly interrupt active connections). Proceed?', 'flush_success' => 'DNS cache flushed and network configuration renewed successfully.', 'flush_failed' => 'Failed to flush DNS or renew network configuration.', + 'probe_section' => 'Remote TCP Port Probe & Latency Test', + 'probe_host_prompt' => 'Enter target hostname or IP address:', + 'probe_port_prompt' => 'Enter target TCP port (1-65535):', + 'probe_invalid_port' => 'Please enter a valid TCP port number between 1 and 65535.', + 'probe_headers' => [ + 'host' => 'Target Host', + 'port' => 'TCP Port', + 'status' => 'State', + 'latency' => 'Response Time', + 'details' => 'Details', + ], + 'probe_open_success' => 'TCP port :port on :host is OPEN (Latency: :latency).', + 'probe_failed' => 'TCP port :port on :host is :status.', + 'wifi_section' => 'Wireless (Wi-Fi) Adapter Diagnostics', + 'wifi_fetched_success' => 'Wireless adapter metrics retrieved successfully.', + 'no_wifi' => 'No active wireless (Wi-Fi) interface detected on this machine.', + 'reset_section' => 'Full Network Stack Reset', + 'confirm_reset' => 'WARNING: This will reset Winsock/IP stack and renew DHCP leases, temporarily disconnecting active network sessions. Proceed?', + 'reset_success' => 'Network stack reset and IP configuration renewed successfully. A system reboot is recommended on Windows.', + 'reset_failed' => 'Failed to reset the network stack. Verify administrator/sudo privileges.', + 'ssl_section' => 'HTTPS SSL/TLS Certificate Inspector', + 'ssl_domain_prompt' => 'Enter target HTTPS domain (e.g. google.com):', + 'ssl_valid_success' => 'SSL/TLS certificate retrieved and parsed successfully.', + 'ssl_connect_failed' => 'Failed to establish TLS connection or retrieve SSL certificate.', + 'ssl_expiring_soon' => 'EXPIRING SOON (< 30 days)', + 'ssl_expired' => 'EXPIRED', + 'scan_section' => 'Local Network (LAN) Active Devices Discovery', + 'no_lan_devices' => 'No active LAN neighbor devices found in the ARP table.', + 'scan_headers' => [ + 'ip' => 'IPv4 Address', + 'mac' => 'MAC Address', + 'status' => 'State / Type', + 'interface' => 'Interface', + ], + 'public_section' => 'External Public IP & ISP Geolocation', + 'public_ip_success' => 'External public IP information retrieved successfully.', + 'public_ip_failed' => 'Unable to query external public IP address. Check internet connectivity.', ], 'maintenance' => [ @@ -255,6 +304,27 @@ 'asset_name' => 'Release Artifact', 'download_url' => 'Download URL', 'count' => 'Event Count', + 'interface' => 'Interface', + 'state' => 'Connection State', + 'ssid' => 'Network SSID', + 'bssid' => 'Access Point BSSID', + 'signal' => 'Signal Quality', + 'channel' => 'Radio Channel', + 'band' => 'Frequency / Radio Band', + 'rx_rate' => 'Receive Rate (RX)', + 'tx_rate' => 'Transmit Rate (TX)', + 'domain' => 'Target Domain', + 'port' => 'Port', + 'subject_cn' => 'Subject (Common Name)', + 'issuer' => 'Certificate Issuer', + 'valid_from' => 'Issued On', + 'valid_to' => 'Expires On', + 'days_remaining' => 'Days Remaining', + 'sans' => 'Subject Alt Names (SANs)', + 'public_ip' => 'Public IP Address', + 'location' => 'City / Region / Country', + 'isp' => 'ISP / Organization (ASN)', + 'reverse_hostname' => 'Reverse Hostname', ], ], diff --git a/lang/pt_BR/messages.php b/lang/pt_BR/messages.php index 648a732..bc557b4 100644 --- a/lang/pt_BR/messages.php +++ b/lang/pt_BR/messages.php @@ -48,6 +48,12 @@ 'network_check' => 'Interfaces e Teste de Saúde de Conectividade (network:check)', 'network_flush' => 'Limpar Cache DNS e Renovar Concessão de IP (network:flush)', 'network_ports' => 'Inspecionar Portas Abertas em Escuta (network:ports)', + 'network_probe' => 'Testar Porta TCP Remota e Medir Latência (network:probe)', + 'network_wifi' => 'Diagnóstico de Wi-Fi — Sinal, SSID, Canal e Velocidade (network:wifi)', + 'network_reset' => 'Reset Completo da Pilha de Rede — Winsock/IP/DHCP (network:reset)', + 'network_ssl' => 'Inspecionar Certificado SSL/TLS HTTPS e Validade (network:ssl)', + 'network_scan' => 'Descobrir Dispositivos Ativos na Rede Local (network:scan)', + 'network_public' => 'Consultar IP Público Externo, Geolocalização e Provedor (network:public)', 'clean_temp' => 'Limpar Arquivos Temporários do Sistema e Usuário (clean:temp)', 'report_export' => 'Exportar Relatório Completo de Diagnóstico (report:export)', ], @@ -76,6 +82,12 @@ 'network_check' => 'Inspecionando interfaces de rede e testando conectividade...', 'network_flush' => 'Limpando cache de resolução DNS e renovando IP...', 'network_ports' => 'Escaneando portas TCP/UDP ativas em escuta...', + 'network_probe' => 'Testando conexão TCP em :host::port...', + 'network_wifi' => 'Consultando métricas do adaptador Wi-Fi e qualidade de sinal...', + 'network_reset' => 'Resetando pilha de rede, Winsock/IP e renovando concessão DHCP...', + 'network_ssl' => 'Inspecionando certificado SSL/TLS de :domain...', + 'network_scan' => 'Escaneando tabela ARP e dispositivos ativos na rede local...', + 'network_public' => 'Consultando endereço IP público externo e provedor (ISP)...', 'clean_temp' => 'Analisando e removendo arquivos temporários com segurança...', 'report_export' => 'Gerando relatório completo de diagnóstico...', 'self_update_check' => 'Consultando GitHub Releases por novas versões...', @@ -230,6 +242,43 @@ 'confirm_flush' => 'Isto limpará o cache DNS e renovará a configuração de rede (pode interromper conexões brevemente). Prosseguir?', 'flush_success' => 'Cache DNS limpo e configuração de rede renovada com sucesso.', 'flush_failed' => 'Falha ao limpar o DNS ou renovar a configuração de rede.', + 'probe_section' => 'Teste de Porta TCP Remota & Latência', + 'probe_host_prompt' => 'Informe o host ou endereço IP alvo:', + 'probe_port_prompt' => 'Informe a porta TCP alvo (1-65535):', + 'probe_invalid_port' => 'Informe um número de porta TCP válido entre 1 e 65535.', + 'probe_headers' => [ + 'host' => 'Host Alvo', + 'port' => 'Porta TCP', + 'status' => 'Estado', + 'latency' => 'Tempo de Resposta', + 'details' => 'Detalhes', + ], + 'probe_open_success' => 'A porta TCP :port em :host está ABERTA (Latência: :latency).', + 'probe_failed' => 'A porta TCP :port em :host retornou status :status.', + 'wifi_section' => 'Diagnóstico de Adaptador Sem Fio (Wi-Fi)', + 'wifi_fetched_success' => 'Métricas do adaptador Wi-Fi coletadas com sucesso.', + 'no_wifi' => 'Nenhuma interface sem fio (Wi-Fi) ativa detectada nesta máquina.', + 'reset_section' => 'Reset Completo da Pilha de Rede', + 'confirm_reset' => 'ATENÇÃO: Isto redefinirá a pilha Winsock/IP e renovará o DHCP, desconectando temporariamente as sessões de rede. Deseja prosseguir?', + 'reset_success' => 'Pilha de rede redefinida e configuração de IP renovada com sucesso. Recomenda-se reiniciar o sistema no Windows.', + 'reset_failed' => 'Falha ao redefinir a pilha de rede. Verifique privilégios de Administrador/sudo.', + 'ssl_section' => 'Inspetor de Certificado SSL/TLS HTTPS', + 'ssl_domain_prompt' => 'Informe o domínio HTTPS alvo (ex: google.com):', + 'ssl_valid_success' => 'Certificado SSL/TLS coletado e analisado com sucesso.', + 'ssl_connect_failed' => 'Falha ao estabelecer conexão TLS ou obter o certificado SSL.', + 'ssl_expiring_soon' => 'EXPIRA EM BREVE (< 30 dias)', + 'ssl_expired' => 'EXPIRADO', + 'scan_section' => 'Descoberta de Dispositivos Ativos na Rede Local (LAN)', + 'no_lan_devices' => 'Nenhum dispositivo vizinho ativo encontrado na tabela ARP.', + 'scan_headers' => [ + 'ip' => 'Endereço IPv4', + 'mac' => 'Endereço MAC', + 'status' => 'Estado / Tipo', + 'interface' => 'Interface', + ], + 'public_section' => 'IP Público Externo & Geolocalização do Provedor (ISP)', + 'public_ip_success' => 'Informações de IP público externo obtidas com sucesso.', + 'public_ip_failed' => 'Não foi possível consultar o IP público externo. Verifique a conexão com a internet.', ], 'maintenance' => [ @@ -255,6 +304,27 @@ 'asset_name' => 'Artefato da Release', 'download_url' => 'URL de Download', 'count' => 'Total de Eventos', + 'interface' => 'Interface', + 'state' => 'Estado da Conexão', + 'ssid' => 'SSID da Rede', + 'bssid' => 'BSSID do Ponto de Acesso', + 'signal' => 'Qualidade do Sinal', + 'channel' => 'Canal de Rádio', + 'band' => 'Frequência / Banda', + 'rx_rate' => 'Taxa de Recepção (RX)', + 'tx_rate' => 'Taxa de Transmissão (TX)', + 'domain' => 'Domínio Alvo', + 'port' => 'Porta', + 'subject_cn' => 'Sujeito (Common Name)', + 'issuer' => 'Emissor do Certificado', + 'valid_from' => 'Data de Emissão', + 'valid_to' => 'Data de Expiração', + 'days_remaining' => 'Dias Restantes', + 'sans' => 'Nomes Alternativos (SANs)', + 'public_ip' => 'Endereço IP Público', + 'location' => 'Cidade / Região / País', + 'isp' => 'Provedor / Organização (ASN)', + 'reverse_hostname' => 'Hostname Reverso', ], ], diff --git a/tests/Feature/ReportExporterTest.php b/tests/Feature/ReportExporterTest.php index f716249..cdc7ebc 100644 --- a/tests/Feature/ReportExporterTest.php +++ b/tests/Feature/ReportExporterTest.php @@ -117,6 +117,36 @@ public function getListeningPorts(): array return []; } + public function probePort(string $host, int $port, int $timeout = 3): array + { + return ['host' => $host, 'port' => $port, 'status' => 'OPEN', 'latency' => '1.00 ms', 'error' => '-']; + } + + public function getWifiInfo(): ActionResult + { + return new ActionResult(false, 'messages.network.no_wifi'); + } + + public function resetNetworkStack(): ActionResult + { + return new ActionResult(true, 'messages.network.reset_success'); + } + + public function checkSslCertificate(string $domain, int $port = 443, int $timeout = 5): ActionResult + { + return new ActionResult(true, 'messages.network.ssl_valid_success'); + } + + public function scanLanDevices(): array + { + return []; + } + + public function getPublicIpInfo(): ActionResult + { + return new ActionResult(true, 'messages.network.public_ip_success'); + } + public function cleanTempFiles(): ActionResult { return new ActionResult(true, 'messages.maintenance.clean_success'); diff --git a/tests/Unit/HealthCheckServiceTest.php b/tests/Unit/HealthCheckServiceTest.php index 67e2c25..fdc2676 100644 --- a/tests/Unit/HealthCheckServiceTest.php +++ b/tests/Unit/HealthCheckServiceTest.php @@ -109,6 +109,36 @@ public function getListeningPorts(): array return []; } + public function probePort(string $host, int $port, int $timeout = 3): array + { + return ['host' => $host, 'port' => $port, 'status' => 'OPEN', 'latency' => '1.00 ms', 'error' => '-']; + } + + public function getWifiInfo(): ActionResult + { + return new ActionResult(false, 'messages.network.no_wifi'); + } + + public function resetNetworkStack(): ActionResult + { + return new ActionResult(true, 'messages.network.reset_success'); + } + + public function checkSslCertificate(string $domain, int $port = 443, int $timeout = 5): ActionResult + { + return new ActionResult(true, 'messages.network.ssl_valid_success'); + } + + public function scanLanDevices(): array + { + return []; + } + + public function getPublicIpInfo(): ActionResult + { + return new ActionResult(true, 'messages.network.public_ip_success'); + } + public function cleanTempFiles(): ActionResult { return new ActionResult(true, 'ok'); diff --git a/tests/Unit/LinuxDriverTest.php b/tests/Unit/LinuxDriverTest.php index 3ab8db8..7732dc7 100644 --- a/tests/Unit/LinuxDriverTest.php +++ b/tests/Unit/LinuxDriverTest.php @@ -144,3 +144,65 @@ public function getEffectiveUid(): int ->and($emptyResult->details['count'])->toBe(0) ->and($emptyResult->details['events'])->toBeEmpty(); }); + +it('parses Linux nmcli Wi-Fi metrics, ip neigh LAN devices, and executes network stack reset as root', function (): void { + $executor = new class implements ProcessExecutorInterface + { + public int $uid = 0; + + public function run(array $command, int $timeout = 30): ProcessResult + { + return match ($command) { + ['nmcli', '-t', '-f', 'ACTIVE,SSID,BSSID,CHAN,FREQ,RATE,SIGNAL', 'dev', 'wifi'] => new ProcessResult( + 0, + "no:GuestNet:11\\:22\\:33\\:44\\:55\\:66:6:2437 MHz:130 Mbit/s:55\nyes:Office-WiFi6:AA\\:BB\\:CC\\:DD\\:EE\\:FF:44:5220 MHz:540 Mbit/s:88" + ), + ['systemctl', 'restart', 'NetworkManager'] => new ProcessResult(0, ''), + ['which', 'dhclient'] => new ProcessResult(0, '/usr/sbin/dhclient'), + ['dhclient', '-r'] => new ProcessResult(0, ''), + ['dhclient'] => new ProcessResult(0, ''), + ['ip', 'neigh', 'show'] => new ProcessResult(0, implode("\n", [ + '192.168.1.1 dev eth0 lladdr 00:1a:2b:3c:4d:5e REACHABLE', + '192.168.1.25 dev eth0 lladdr 10:20:30:40:50:60 STALE', + '192.168.1.99 dev eth0 FAILED', + ])), + default => new ProcessResult(1, '', 'Command failed', false), + }; + } + + public function readFile(string $path): ?string + { + return null; + } + + public function getEffectiveUid(): int + { + return $this->uid; + } + }; + + $driver = new LinuxDriver($executor); + + $wifi = $driver->getWifiInfo(); + expect($wifi->success)->toBeTrue() + ->and($wifi->details['ssid'])->toBe('Office-WiFi6') + ->and($wifi->details['bssid'])->toBe('AA:BB:CC:DD:EE:FF') + ->and($wifi->details['signal'])->toBe('88%') + ->and($wifi->details['channel'])->toBe('44'); + + $resetRoot = $driver->resetNetworkStack(); + expect($resetRoot->success)->toBeTrue() + ->and($resetRoot->details['commands_executed'])->toContain('systemctl restart NetworkManager', 'dhclient -r && dhclient'); + + $executor->uid = 1000; + $resetNonRoot = $driver->resetNetworkStack(); + expect($resetNonRoot->success)->toBeFalse() + ->and($resetNonRoot->message)->toBe('messages.common.permission_denied'); + + $neighbors = $driver->scanLanDevices(); + expect($neighbors)->toHaveCount(2) + ->and($neighbors[0]['ip'])->toBe('192.168.1.1') + ->and($neighbors[0]['mac'])->toBe('00:1A:2B:3C:4D:5E') + ->and($neighbors[0]['status'])->toBe('REACHABLE') + ->and($neighbors[1]['ip'])->toBe('192.168.1.25'); +}); diff --git a/tests/Unit/WindowsDriverTest.php b/tests/Unit/WindowsDriverTest.php index 35aafcb..b7a0f92 100644 --- a/tests/Unit/WindowsDriverTest.php +++ b/tests/Unit/WindowsDriverTest.php @@ -217,3 +217,81 @@ public function getEffectiveUid(): int ->and($emptyResult->details['count'])->toBe(0) ->and($emptyResult->details['events'])->toBeEmpty(); }); + +it('parses Windows Wi-Fi metrics, ARP LAN devices, and executes network stack reset with Admin check', function (): void { + $executor = new class implements ProcessExecutorInterface + { + public int $callIndex = 0; + + public function run(array $command, int $timeout = 30): ProcessResult + { + $this->callIndex++; + + return match ($this->callIndex) { + 1 => new ProcessResult(0, implode("\r\n", [ + ' Name : Wi-Fi', + ' State : connected', + ' SSID : CorpNet-5G', + ' BSSID : aa:bb:cc:dd:ee:ff', + ' Radio type : 802.11ax', + ' Channel : 36', + ' Receive rate (Mbps) : 866.7', + ' Transmit rate (Mbps) : 866.7', + ' Signal : 92%', + ])), + 2 => new ProcessResult(0, 'There is no wireless interface on the system.'), + 3 => new ProcessResult(1, '', 'Access is denied.', false), // net session not admin + 4 => new ProcessResult(0, 'The command completed successfully.'), // net session admin + 5, 6, 7, 8, 9 => new ProcessResult(0, 'OK'), + 10 => new ProcessResult(0, implode("\r\n", [ + 'Interface: 192.168.1.105 --- 0xc', + ' Internet Address Physical Address Type', + ' 192.168.1.1 00-1a-2b-3c-4d-5e dynamic', + ' 192.168.1.50 11-22-33-44-55-66 dynamic', + ' 224.0.0.22 01-00-5e-00-00-16 static', + ' 255.255.255.255 ff-ff-ff-ff-ff-ff static', + ])), + default => new ProcessResult(0, ''), + }; + } + + public function readFile(string $path): ?string + { + return null; + } + + public function getEffectiveUid(): int + { + return 0; + } + }; + + $driver = new WindowsDriver($executor); + + $wifi = $driver->getWifiInfo(); + expect($wifi->success)->toBeTrue() + ->and($wifi->details['ssid'])->toBe('CorpNet-5G') + ->and($wifi->details['bssid'])->toBe('aa:bb:cc:dd:ee:ff') + ->and($wifi->details['signal'])->toBe('92%') + ->and($wifi->details['channel'])->toBe('36') + ->and($wifi->details['rx_rate'])->toBe('866.7 Mbps'); + + $noWifi = $driver->getWifiInfo(); + expect($noWifi->success)->toBeFalse() + ->and($noWifi->message)->toBe('messages.network.no_wifi'); + + $deniedReset = $driver->resetNetworkStack(); + expect($deniedReset->success)->toBeFalse() + ->and($deniedReset->message)->toBe('messages.common.permission_denied'); + + $adminReset = $driver->resetNetworkStack(); + expect($adminReset->success)->toBeTrue() + ->and($adminReset->message)->toBe('messages.network.reset_success') + ->and($adminReset->details['commands_executed'])->toHaveCount(5); + + $lanDevices = $driver->scanLanDevices(); + expect($lanDevices)->toHaveCount(2) + ->and($lanDevices[0]['ip'])->toBe('192.168.1.1') + ->and($lanDevices[0]['mac'])->toBe('00:1A:2B:3C:4D:5E') + ->and($lanDevices[1]['ip'])->toBe('192.168.1.50'); +}); From 0c40398eab025c2284f89973feb9c47b0716cafb Mon Sep 17 00:00:00 2001 From: Dev-lib4n Date: Wed, 18 Nov 2026 15:20:14 -0300 Subject: [PATCH 2/5] feat(system): add services, battery, startup, usb, env, and kill commands --- app/Commands/System/BatteryCommand.php | 55 ++++ app/Commands/System/EnvInspectorCommand.php | 93 ++++++ app/Commands/System/KillProcessCommand.php | 181 +++++++++++ app/Commands/System/ServicesCommand.php | 133 ++++++++ app/Commands/System/StartupCommand.php | 75 +++++ app/Commands/System/UsbDevicesCommand.php | 75 +++++ app/Commands/ToolboxMenuCommand.php | 6 + app/Contracts/SystemDriverInterface.php | 56 ++++ .../Concerns/InteractsWithNetworkSockets.php | 79 +++++ app/Drivers/LinuxDriver.php | 305 ++++++++++++++++++ app/Drivers/WindowsDriver.php | 272 ++++++++++++++++ lang/en/messages.php | 65 ++++ lang/pt_BR/messages.php | 65 ++++ tests/Feature/ReportExporterTest.php | 35 ++ tests/Unit/HealthCheckServiceTest.php | 35 ++ tests/Unit/LinuxDriverTest.php | 90 ++++++ tests/Unit/WindowsDriverTest.php | 103 ++++++ 17 files changed, 1723 insertions(+) create mode 100644 app/Commands/System/BatteryCommand.php create mode 100644 app/Commands/System/EnvInspectorCommand.php create mode 100644 app/Commands/System/KillProcessCommand.php create mode 100644 app/Commands/System/ServicesCommand.php create mode 100644 app/Commands/System/StartupCommand.php create mode 100644 app/Commands/System/UsbDevicesCommand.php diff --git a/app/Commands/System/BatteryCommand.php b/app/Commands/System/BatteryCommand.php new file mode 100644 index 0000000..d8647f2 --- /dev/null +++ b/app/Commands/System/BatteryCommand.php @@ -0,0 +1,55 @@ +resolveLocale(); + + info((string) __('messages.system.battery_section')); + + $result = spin( + callback: fn () => $driver->getBatteryHealth(), + message: (string) __('messages.spinners.system_battery'), + ); + + if (! $result->success) { + warning((string) __($result->message)); + + return self::SUCCESS; + } + + return $this->renderActionResult($result); + } +} diff --git a/app/Commands/System/EnvInspectorCommand.php b/app/Commands/System/EnvInspectorCommand.php new file mode 100644 index 0000000..a42ce75 --- /dev/null +++ b/app/Commands/System/EnvInspectorCommand.php @@ -0,0 +1,93 @@ +resolveLocale(); + + $audit = spin( + callback: fn (): array => $driver->auditEnvironmentPath(), + message: (string) __('messages.spinners.system_env'), + ); + + info((string) __('messages.system.env_section')); + + $varRows = []; + foreach ($audit['variables'] as $key => $val) { + $varRows[] = [$key, $val]; + } + + table( + headers: [ + (string) __('messages.common.metric'), + (string) __('messages.common.value'), + ], + rows: $varRows, + ); + + info((string) __('messages.system.path_audit_section')); + + $statusLabels = [ + 'VALID' => (string) __('messages.system.path_states.valid'), + 'BROKEN' => (string) __('messages.system.path_states.broken'), + 'DUPLICATE' => (string) __('messages.system.path_states.duplicate'), + ]; + + table( + headers: [ + '#', + (string) __('messages.system.path_headers.directory'), + (string) __('messages.system.path_headers.status'), + ], + rows: array_map( + fn (array $entry): array => [ + (string) $entry['index'], + $entry['path'], + sprintf('%s %s', $entry['icon'], $statusLabels[$entry['status']] ?? $entry['status']), + ], + $audit['path_entries'] + ), + ); + + note((string) __('messages.system.path_summary', [ + 'valid' => $audit['summary']['valid'], + 'broken' => $audit['summary']['broken'], + 'duplicate' => $audit['summary']['duplicate'], + ])); + + return self::SUCCESS; + } +} diff --git a/app/Commands/System/KillProcessCommand.php b/app/Commands/System/KillProcessCommand.php new file mode 100644 index 0000000..f6648f7 --- /dev/null +++ b/app/Commands/System/KillProcessCommand.php @@ -0,0 +1,181 @@ +resolveLocale(); + + info((string) __('messages.system.kill_section')); + + $targetArg = $this->argument('target'); + if (is_string($targetArg) && trim($targetArg) !== '') { + return $this->terminateDirectTarget($driver, trim($targetArg)); + } + + /** @var array $processes */ + $processes = spin( + callback: fn (): array => $driver->getTopProcesses(10), + message: (string) __('messages.spinners.system_top'), + ); + + if ($processes === []) { + warning((string) __('messages.system.no_processes')); + + return self::SUCCESS; + } + + $rows = []; + $indexedProcesses = []; + $menuOptions = []; + + foreach (array_values($processes) as $idx => $proc) { + $num = (string) ($idx + 1); + $indexedProcesses[$num] = $proc; + $menuOptions[$num] = sprintf('%s (PID %d | RAM: %s)', $proc['name'], $proc['pid'], $proc['memory']); + + $rows[] = [ + sprintf('[%s]', $num), + (string) $proc['pid'], + $proc['name'], + $proc['cpu'], + $proc['memory'], + ]; + } + + table( + headers: [ + '#', + (string) __('messages.system.process_headers.pid'), + (string) __('messages.system.process_headers.name'), + (string) __('messages.system.process_headers.cpu'), + (string) __('messages.system.process_headers.memory'), + ], + rows: $rows, + ); + + if (! $this->input->isInteractive()) { + return self::SUCCESS; + } + + $menuOptions['0'] = (string) __('messages.common.cancelled'); + + $choice = $this->promptNumericMenu( + promptLabel: (string) __('messages.system.select_process_prompt'), + options: $menuOptions, + defaultKey: '0', + ); + + if ($choice === '0' || ! isset($indexedProcesses[$choice])) { + warning((string) __('messages.common.cancelled')); + + return self::SUCCESS; + } + + $selected = $indexedProcesses[$choice]; + $pid = (int) $selected['pid']; + $name = (string) $selected['name']; + + if (! $this->option('force') && ! confirm( + label: (string) __('messages.system.confirm_kill', ['pid' => $pid, 'name' => $name]), + default: false, + yes: (string) __('messages.common.yes'), + no: (string) __('messages.common.no'), + )) { + warning((string) __('messages.common.cancelled')); + + return self::SUCCESS; + } + + $result = spin( + callback: fn () => $driver->killProcess($pid), + message: (string) __('messages.spinners.killing_process', ['pid' => $pid]), + ); + + return $this->renderActionResult($result); + } + + /** + * Terminate a process directly by numeric PID or process name. + */ + protected function terminateDirectTarget(SystemDriverInterface $driver, string $target): int + { + if (ctype_digit($target)) { + $pid = (int) $target; + + if (! $this->option('force') && ! confirm( + label: (string) __('messages.system.confirm_kill', ['pid' => $pid, 'name' => 'PID ' . $pid]), + default: false, + yes: (string) __('messages.common.yes'), + no: (string) __('messages.common.no'), + )) { + warning((string) __('messages.common.cancelled')); + + return self::SUCCESS; + } + + $result = spin( + callback: fn () => $driver->killProcess($pid), + message: (string) __('messages.spinners.killing_process', ['pid' => $pid]), + ); + + return $this->renderActionResult($result); + } + + if (! $this->option('force') && ! confirm( + label: (string) __('messages.system.confirm_kill_name', ['name' => $target]), + default: false, + yes: (string) __('messages.common.yes'), + no: (string) __('messages.common.no'), + )) { + warning((string) __('messages.common.cancelled')); + + return self::SUCCESS; + } + + $result = spin( + callback: fn () => $driver->killProcessByName($target), + message: (string) __('messages.spinners.killing_process', ['pid' => $target]), + ); + + return $this->renderActionResult($result); + } +} diff --git a/app/Commands/System/ServicesCommand.php b/app/Commands/System/ServicesCommand.php new file mode 100644 index 0000000..badeff2 --- /dev/null +++ b/app/Commands/System/ServicesCommand.php @@ -0,0 +1,133 @@ +resolveLocale(); + + info((string) __('messages.system.services_section')); + + $restartTarget = $this->option('restart'); + if (is_string($restartTarget) && trim($restartTarget) !== '') { + $target = trim($restartTarget); + $result = spin( + callback: fn () => $driver->restartService($target), + message: (string) __('messages.spinners.restarting_service', ['service' => $target]), + ); + + return $this->renderActionResult($result); + } + + /** @var array $services */ + $services = spin( + callback: fn (): array => $driver->getCriticalServices(), + message: (string) __('messages.spinners.system_services'), + ); + + if ($services === []) { + warning((string) __('messages.system.no_services')); + + return self::SUCCESS; + } + + $rows = []; + $indexedMap = []; + foreach (array_values($services) as $idx => $svc) { + $num = (string) ($idx + 1); + $indexedMap[$num] = $svc['name']; + $statusBadge = strtolower($svc['status']) === 'running' + ? '✅ ' . $svc['status'] + : '⚠️ ' . $svc['status']; + + $rows[] = [ + sprintf('[%s]', $num), + $svc['name'], + $svc['display_name'], + $statusBadge, + $svc['start_type'], + ]; + } + + table( + headers: [ + '#', + (string) __('messages.system.service_headers.name'), + (string) __('messages.system.service_headers.display_name'), + (string) __('messages.system.service_headers.status'), + (string) __('messages.system.service_headers.start_type'), + ], + rows: $rows, + ); + + if ($this->input->isInteractive() && confirm( + label: (string) __('messages.system.ask_restart_service'), + default: false, + yes: (string) __('messages.common.yes'), + no: (string) __('messages.common.no'), + )) { + $menuOptions = []; + foreach ($indexedMap as $num => $name) { + $menuOptions[$num] = $name; + } + $menuOptions['0'] = (string) __('messages.common.cancelled'); + + $choice = $this->promptNumericMenu( + promptLabel: (string) __('messages.system.select_service_prompt'), + options: $menuOptions, + defaultKey: '1', + ); + + if ($choice === '0' || ! isset($indexedMap[$choice])) { + return self::SUCCESS; + } + + $selectedService = $indexedMap[$choice]; + $result = spin( + callback: fn () => $driver->restartService($selectedService), + message: (string) __('messages.spinners.restarting_service', ['service' => $selectedService]), + ); + + return $this->renderActionResult($result); + } + + return self::SUCCESS; + } +} diff --git a/app/Commands/System/StartupCommand.php b/app/Commands/System/StartupCommand.php new file mode 100644 index 0000000..771bb8e --- /dev/null +++ b/app/Commands/System/StartupCommand.php @@ -0,0 +1,75 @@ +resolveLocale(); + + info((string) __('messages.system.startup_section')); + + /** @var array $entries */ + $entries = spin( + callback: fn (): array => $driver->getStartupPrograms(), + message: (string) __('messages.spinners.system_startup'), + ); + + if ($entries === []) { + warning((string) __('messages.system.no_startup_items')); + + return self::SUCCESS; + } + + table( + headers: [ + (string) __('messages.system.startup_headers.name'), + (string) __('messages.system.startup_headers.command'), + (string) __('messages.system.startup_headers.location'), + (string) __('messages.system.startup_headers.user'), + ], + rows: array_map( + fn (array $item): array => [ + $item['name'] ?? '-', + $item['command'] ?? '-', + $item['location'] ?? '-', + $item['user'] ?? '-', + ], + $entries + ), + ); + + return self::SUCCESS; + } +} diff --git a/app/Commands/System/UsbDevicesCommand.php b/app/Commands/System/UsbDevicesCommand.php new file mode 100644 index 0000000..d2f180c --- /dev/null +++ b/app/Commands/System/UsbDevicesCommand.php @@ -0,0 +1,75 @@ +resolveLocale(); + + info((string) __('messages.system.usb_section')); + + /** @var array $devices */ + $devices = spin( + callback: fn (): array => $driver->getUsbDevices(), + message: (string) __('messages.spinners.system_usb'), + ); + + if ($devices === []) { + warning((string) __('messages.system.no_usb_devices')); + + return self::SUCCESS; + } + + table( + headers: [ + (string) __('messages.system.usb_headers.name'), + (string) __('messages.system.usb_headers.manufacturer'), + (string) __('messages.system.usb_headers.status'), + (string) __('messages.system.usb_headers.device_id'), + ], + rows: array_map( + fn (array $dev): array => [ + $dev['name'] ?? '-', + $dev['manufacturer'] ?? '-', + $dev['status'] ?? 'OK', + $dev['device_id'] ?? '-', + ], + $devices + ), + ); + + return self::SUCCESS; + } +} diff --git a/app/Commands/ToolboxMenuCommand.php b/app/Commands/ToolboxMenuCommand.php index 078bd04..9a0f94c 100644 --- a/app/Commands/ToolboxMenuCommand.php +++ b/app/Commands/ToolboxMenuCommand.php @@ -160,6 +160,12 @@ protected function handleCategorySubmenu(string $category, string $locale): void '1' => ['label' => (string) __('messages.menu.actions.system_info'), 'command' => 'system:info'], '2' => ['label' => (string) __('messages.menu.actions.system_top'), 'command' => 'system:top'], '3' => ['label' => (string) __('messages.menu.actions.system_logs'), 'command' => 'system:logs'], + '4' => ['label' => (string) __('messages.menu.actions.system_services'), 'command' => 'system:services'], + '5' => ['label' => (string) __('messages.menu.actions.system_battery'), 'command' => 'system:battery'], + '6' => ['label' => (string) __('messages.menu.actions.system_startup'), 'command' => 'system:startup'], + '7' => ['label' => (string) __('messages.menu.actions.system_usb'), 'command' => 'system:usb'], + '8' => ['label' => (string) __('messages.menu.actions.system_env'), 'command' => 'system:env'], + '9' => ['label' => (string) __('messages.menu.actions.system_kill'), 'command' => 'system:kill'], ], 'printers' => [ '1' => ['label' => (string) __('messages.menu.actions.printer_list'), 'command' => 'printer:list'], diff --git a/app/Contracts/SystemDriverInterface.php b/app/Contracts/SystemDriverInterface.php index c16e1d7..f9bfc03 100644 --- a/app/Contracts/SystemDriverInterface.php +++ b/app/Contracts/SystemDriverInterface.php @@ -45,6 +45,14 @@ public function getTopProcesses(int $limit = 10): array; */ public function killProcess(int $pid): ActionResult; + /** + * Terminate running process(es) by process name. + * + * @param string $processName + * @return ActionResult + */ + public function killProcessByName(string $processName): ActionResult; + /** * Retrieve recent critical and error events from the OS event log / journal (last 24 hours). * @@ -53,6 +61,54 @@ public function killProcess(int $pid): ActionResult; */ public function getCriticalLogs(int $limit = 15): ActionResult; + /** + * Retrieve status of critical IT support system services. + * + * @return array + */ + public function getCriticalServices(): array; + + /** + * Restart a system service by its service identifier. + * + * @param string $serviceName + * @return ActionResult + */ + public function restartService(string $serviceName): ActionResult; + + /** + * Retrieve battery health, charge level, design vs full capacity, wear percentage, and cycles. + * + * @return ActionResult + */ + public function getBatteryHealth(): ActionResult; + + /** + * Retrieve programs and services configured to run at system startup / login. + * + * @return array + */ + public function getStartupPrograms(): array; + + /** + * Retrieve connected USB and peripheral devices. + * + * @return array + */ + public function getUsbDevices(): array; + + /** + * Audit key environment variables and inspect every directory entry in the system PATH. + * + * @param string|null $customPathString Optional custom PATH string for testing. + * @return array{ + * variables: array, + * path_entries: array, + * summary: array{valid: int, broken: int, duplicate: int} + * } + */ + public function auditEnvironmentPath(?string $customPathString = null): array; + /** * List installed printers, their current status, and pending print jobs. * diff --git a/app/Drivers/Concerns/InteractsWithNetworkSockets.php b/app/Drivers/Concerns/InteractsWithNetworkSockets.php index 413dd39..08a2689 100644 --- a/app/Drivers/Concerns/InteractsWithNetworkSockets.php +++ b/app/Drivers/Concerns/InteractsWithNetworkSockets.php @@ -323,4 +323,83 @@ protected function isUnicastLanNeighbor(string $ip, string $mac): bool return true; } + + /** + * Audit key environment variables and inspect every directory entry in the system PATH. + * + * @return array{ + * variables: array, + * path_entries: array, + * summary: array{valid: int, broken: int, duplicate: int} + * } + */ + public function auditEnvironmentPath(?string $customPathString = null): array + { + $rawPath = $customPathString ?? (string) (getenv('PATH') ?: ($_SERVER['PATH'] ?? '')); + $separator = str_contains($rawPath, ';') && ! str_contains($rawPath, ':') + ? ';' + : (PHP_OS_FAMILY === 'Windows' && $customPathString === null ? ';' : PATH_SEPARATOR); + + $rawEntries = $rawPath !== '' ? explode($separator, $rawPath) : []; + + $seen = []; + $entries = []; + $validCount = 0; + $brokenCount = 0; + $duplicateCount = 0; + $index = 1; + + foreach ($rawEntries as $entry) { + $cleanPath = trim($entry, " \t\n\r\0\x0B\"'"); + if ($cleanPath === '') { + continue; + } + + $normalizedKey = PHP_OS_FAMILY === 'Windows' + ? strtolower(rtrim($cleanPath, '\\/')) + : rtrim($cleanPath, '/'); + + if (isset($seen[$normalizedKey])) { + $status = 'DUPLICATE'; + $icon = '⚠️'; + $duplicateCount++; + } elseif (is_dir($cleanPath)) { + $status = 'VALID'; + $icon = '✅'; + $validCount++; + $seen[$normalizedKey] = true; + } else { + $status = 'BROKEN'; + $icon = '❌'; + $brokenCount++; + $seen[$normalizedKey] = true; + } + + $entries[] = [ + 'index' => $index++, + 'path' => $cleanPath, + 'status' => $status, + 'icon' => $icon, + ]; + } + + $variables = [ + 'OS_FAMILY' => PHP_OS_FAMILY, + 'USER' => (string) (getenv('USERNAME') ?: getenv('USER') ?: get_current_user() ?: '-'), + 'HOME' => (string) (getenv('USERPROFILE') ?: getenv('HOME') ?: '-'), + 'SHELL' => (string) (getenv('SHELL') ?: getenv('ComSpec') ?: '-'), + 'TEMP' => sys_get_temp_dir(), + 'PHP_VERSION' => PHP_VERSION, + ]; + + return [ + 'variables' => $variables, + 'path_entries' => $entries, + 'summary' => [ + 'valid' => $validCount, + 'broken' => $brokenCount, + 'duplicate' => $duplicateCount, + ], + ]; + } } diff --git a/app/Drivers/LinuxDriver.php b/app/Drivers/LinuxDriver.php index 5cc2d4f..a622bd4 100644 --- a/app/Drivers/LinuxDriver.php +++ b/app/Drivers/LinuxDriver.php @@ -331,6 +331,70 @@ public function killProcess(int $pid): ActionResult ); } + /** + * {@inheritDoc} + */ + public function killProcessByName(string $processName): ActionResult + { + $cleanName = preg_replace('/[^A-Za-z0-9_.-]/', '', trim($processName)) ?? ''; + if ($cleanName === '') { + return new ActionResult( + success: false, + message: 'messages.system.process_killed_failed', + details: ['process_name' => $processName, 'driver' => 'Linux'], + ); + } + + $result = $this->processRunner->run(['pkill', '-15', '-x', $cleanName]); + if ($result->successful) { + return new ActionResult( + success: true, + message: 'messages.system.process_killed_success', + details: [ + 'process_name' => $cleanName, + 'signal' => 'SIGTERM', + 'driver' => 'Linux', + ], + ); + } + + $err = $result->errorOutput !== '' ? $result->errorOutput : $result->output; + if ($this->isPermissionDeniedError($err)) { + return new ActionResult( + success: false, + message: 'messages.common.permission_denied', + details: [ + 'process_name' => $cleanName, + 'error' => $err, + 'driver' => 'Linux', + ], + ); + } + + $forceResult = $this->processRunner->run(['pkill', '-9', '-x', $cleanName]); + if ($forceResult->successful) { + return new ActionResult( + success: true, + message: 'messages.system.process_killed_success', + details: [ + 'process_name' => $cleanName, + 'signal' => 'SIGKILL', + 'driver' => 'Linux', + ], + ); + } + + return new ActionResult( + success: false, + message: 'messages.system.process_killed_failed', + details: [ + 'process_name' => $cleanName, + 'error' => $forceResult->errorOutput ?: ($err ?: 'Process not found'), + 'driver' => 'Linux', + ], + ); + } + /** * {@inheritDoc} */ @@ -374,6 +438,247 @@ public function getCriticalLogs(int $limit = 15): ActionResult ); } + /** + * {@inheritDoc} + */ + public function getCriticalServices(): array + { + $candidates = [ + 'cups' => 'CUPS Print Spooler', + 'ssh' => 'OpenSSH Server (ssh)', + 'sshd' => 'OpenSSH Daemon (sshd)', + 'docker' => 'Docker Engine', + 'nginx' => 'Nginx Web Server', + 'NetworkManager' => 'NetworkManager', + 'cron' => 'Cron Daemon', + ]; + + $result = $this->processRunner->run([ + 'systemctl', + 'show', + '--property=Id,Description,ActiveState,UnitFileState,LoadState', + '--', + 'cups.service', + 'ssh.service', + 'sshd.service', + 'docker.service', + 'nginx.service', + 'NetworkManager.service', + 'cron.service', + ]); + + if (! $result->successful || $result->output === '') { + return []; + } + + $services = []; + $blocks = preg_split('/\r?\n\r?\n/', trim($result->output)) ?: []; + + foreach ($blocks as $block) { + $props = []; + foreach (preg_split('/\r\n|\r|\n/', trim($block)) ?: [] as $line) { + if (str_contains($line, '=')) { + [$k, $v] = explode('=', $line, 2); + $props[trim($k)] = trim($v); + } + } + + $loadState = strtolower($props['LoadState'] ?? ''); + if ($loadState === 'not-found' || empty($props['Id'])) { + continue; + } + + $unitName = (string) preg_replace('/\.service$/', '', $props['Id']); + $activeState = strtolower($props['ActiveState'] ?? 'inactive'); + $status = $activeState === 'active' ? 'Running' : 'Stopped'; + + $services[] = [ + 'name' => $unitName, + 'display_name' => $props['Description'] ?? ($candidates[$unitName] ?? $unitName), + 'status' => $status, + 'start_type' => $props['UnitFileState'] ?? 'enabled', + ]; + } + + return $services; + } + + /** + * {@inheritDoc} + */ + public function restartService(string $serviceName): ActionResult + { + if (! $this->isRoot()) { + return new ActionResult( + success: false, + message: 'messages.common.permission_denied', + details: ['service' => $serviceName, 'driver' => 'Linux'], + ); + } + + $cleanName = preg_replace('/[^A-Za-z0-9_.-]/', '', trim($serviceName)) ?? ''; + if ($cleanName === '') { + return new ActionResult( + success: false, + message: 'messages.system.service_restarted_failed', + details: ['service' => $serviceName, 'driver' => 'Linux'], + ); + } + + $result = $this->processRunner->run(['systemctl', 'restart', $cleanName]); + if ($result->successful) { + return new ActionResult( + success: true, + message: 'messages.system.service_restarted_success', + details: [ + 'service' => $cleanName, + 'driver' => 'Linux', + ], + ); + } + + $fallback = $this->processRunner->run(['service', $cleanName, 'restart']); + if ($fallback->successful) { + return new ActionResult( + success: true, + message: 'messages.system.service_restarted_success', + details: [ + 'service' => $cleanName, + 'driver' => 'Linux', + ], + ); + } + + return new ActionResult( + success: false, + message: 'messages.system.service_restarted_failed', + details: [ + 'service' => $cleanName, + 'error' => $result->errorOutput ?: ($fallback->errorOutput ?: 'Failed to restart service'), + 'driver' => 'Linux', + ], + ); + } + + /** + * {@inheritDoc} + */ + public function getBatteryHealth(): ActionResult + { + $batBase = null; + foreach (['/sys/class/power_supply/BAT0', '/sys/class/power_supply/BAT1'] as $candidate) { + if ($this->readFile($candidate . '/status') !== null) { + $batBase = $candidate; + break; + } + } + + if ($batBase === null) { + return new ActionResult( + success: false, + message: 'messages.system.no_battery', + details: ['driver' => 'Linux'], + ); + } + + $status = trim((string) ($this->readFile($batBase . '/status') ?? 'Unknown')); + $capacity = (int) trim((string) ($this->readFile($batBase . '/capacity') ?? '0')); + $designRaw = $this->readFile($batBase . '/energy_full_design') ?? $this->readFile($batBase . '/charge_full_design'); + $fullRaw = $this->readFile($batBase . '/energy_full') ?? $this->readFile($batBase . '/charge_full'); + $cyclesRaw = $this->readFile($batBase . '/cycle_count'); + + // /sys/class/power_supply reports energy in microWatt-hours (uWh) -> divide by 1000 for mWh + $designMwh = ($designRaw !== null && is_numeric(trim($designRaw))) ? ((float) trim($designRaw)) / 1000.0 : 0.0; + $fullMwh = ($fullRaw !== null && is_numeric(trim($fullRaw))) ? ((float) trim($fullRaw)) / 1000.0 : 0.0; + $cycles = ($cyclesRaw !== null && is_numeric(trim($cyclesRaw))) ? (int) trim($cyclesRaw) : 0; + + $healthPercent = ($designMwh > 0.0 && $fullMwh > 0.0) + ? min(100.0, round(($fullMwh / $designMwh) * 100.0, 1)) + : 100.0; + $wearPercent = max(0.0, round(100.0 - $healthPercent, 1)); + + return new ActionResult( + success: true, + message: 'messages.system.battery_fetched_success', + details: [ + 'battery_status' => $status, + 'charge_percent' => sprintf('%d%%', $capacity), + 'design_capacity' => $designMwh > 0.0 ? sprintf('%.0f mWh', $designMwh) : 'N/A', + 'full_charge_capacity' => $fullMwh > 0.0 ? sprintf('%.0f mWh', $fullMwh) : 'N/A', + 'battery_health' => sprintf('%.1f%% (Wear: %.1f%%)', $healthPercent, $wearPercent), + 'cycle_count' => $cycles > 0 ? (string) $cycles : 'N/A', + 'driver' => 'Linux', + ], + ); + } + + /** + * {@inheritDoc} + */ + public function getStartupPrograms(): array + { + $result = $this->processRunner->run([ + 'systemctl', + 'list-unit-files', + '--state=enabled', + '--type=service', + '--no-pager', + '--no-legend', + ]); + + $entries = []; + if ($result->successful && $result->output !== '') { + $lines = preg_split('/\r\n|\r|\n/', trim($result->output)) ?: []; + foreach (array_slice($lines, 0, 30) as $line) { + $parts = preg_split('/\s+/', trim($line)); + if (is_array($parts) && count($parts) >= 2) { + $unit = $parts[0]; + $state = $parts[1]; + $entries[] = [ + 'name' => (string) preg_replace('/\.service$/', '', $unit), + 'command' => $unit, + 'location' => 'systemd (' . $state . ')', + 'user' => 'root', + ]; + } + } + } + + return $entries; + } + + /** + * {@inheritDoc} + */ + public function getUsbDevices(): array + { + $result = $this->processRunner->run(['lsusb']); + if (! $result->successful || $result->output === '') { + return []; + } + + $devices = []; + $lines = preg_split('/\r\n|\r|\n/', trim($result->output)) ?: []; + + foreach ($lines as $line) { + $line = trim($line); + if (preg_match('/^Bus\s+(\d+)\s+Device\s+(\d+):\s+ID\s+([0-9a-fA-F]{4}:[0-9a-fA-F]{4})\s*(.*)$/', $line, $m) === 1) { + $busDev = sprintf('Bus %s Dev %s', $m[1], $m[2]); + $vendorProd = $m[3]; + $desc = trim($m[4]) !== '' ? trim($m[4]) : 'USB Device'; + + $devices[] = [ + 'name' => $desc, + 'manufacturer' => 'ID ' . $vendorProd, + 'status' => 'OK', + 'device_id' => $busDev, + ]; + } + } + + return $devices; + } + /** * {@inheritDoc} */ diff --git a/app/Drivers/WindowsDriver.php b/app/Drivers/WindowsDriver.php index f6a6a0d..6447bac 100644 --- a/app/Drivers/WindowsDriver.php +++ b/app/Drivers/WindowsDriver.php @@ -267,6 +267,52 @@ public function killProcess(int $pid): ActionResult ); } + /** + * {@inheritDoc} + */ + public function killProcessByName(string $processName): ActionResult + { + $cleanName = preg_replace('/\.exe$/i', '', trim($processName)) ?? ''; + $cleanName = preg_replace('/[^A-Za-z0-9_.-]/', '', $cleanName) ?? ''; + + if ($cleanName === '') { + return new ActionResult( + success: false, + message: 'messages.system.process_killed_failed', + details: ['process_name' => $processName, 'driver' => 'Windows'], + ); + } + + $script = sprintf("Stop-Process -Name '%s' -Force -ErrorAction Stop", $cleanName); + $result = $this->runPowerShell($script); + + if ($result->successful) { + return new ActionResult( + success: true, + message: 'messages.system.process_killed_success', + details: [ + 'process_name' => $cleanName, + 'driver' => 'Windows', + ], + ); + } + + $errorMessage = $result->errorOutput !== '' ? $result->errorOutput : $result->output; + $isPermissionDenied = $this->isPermissionDeniedError($errorMessage); + + return new ActionResult( + success: false, + message: $isPermissionDenied + ? 'messages.common.permission_denied' + : 'messages.system.process_killed_failed', + details: [ + 'process_name' => $cleanName, + 'error' => $errorMessage !== '' ? $errorMessage : 'Stop-Process failed', + 'driver' => 'Windows', + ], + ); + } + /** * {@inheritDoc} */ @@ -334,6 +380,232 @@ public function getCriticalLogs(int $limit = 15): ActionResult ); } + /** + * {@inheritDoc} + */ + public function getCriticalServices(): array + { + $script = <<<'PS' +$ErrorActionPreference = 'SilentlyContinue'; +$names = @('Spooler','wuauserv','BITS','Dnscache','TermService','AnyDesk','TeamViewer'); +@(Get-Service -Name $names -ErrorAction SilentlyContinue | ForEach-Object { + [PSCustomObject]@{ + Name = [string]$_.Name; + DisplayName = [string]$_.DisplayName; + Status = [string]$_.Status; + StartType = [string]$_.StartType + } +}) | ConvertTo-Json -Compress +PS; + + $items = $this->normalizeJsonList($this->runPowerShellJson($script)); + + $services = []; + foreach ($items as $item) { + if (! is_array($item) || empty($item['Name'])) { + continue; + } + + $rawStatus = trim((string) ($item['Status'] ?? 'Stopped')); + $status = match ($rawStatus) { + '4', 'Running' => 'Running', + '1', 'Stopped' => 'Stopped', + default => $rawStatus, + }; + + $services[] = [ + 'name' => trim((string) $item['Name']), + 'display_name' => trim((string) ($item['DisplayName'] ?? $item['Name'])), + 'status' => $status, + 'start_type' => trim((string) ($item['StartType'] ?? 'Automatic')), + ]; + } + + return $services; + } + + /** + * {@inheritDoc} + */ + public function restartService(string $serviceName): ActionResult + { + $cleanName = preg_replace('/[^A-Za-z0-9_.-]/', '', trim($serviceName)) ?? ''; + if ($cleanName === '') { + return new ActionResult( + success: false, + message: 'messages.system.service_restarted_failed', + details: ['service' => $serviceName, 'driver' => 'Windows'], + ); + } + + $script = sprintf("Restart-Service -Name '%s' -Force -ErrorAction Stop", $cleanName); + $result = $this->runPowerShell($script); + + if ($result->successful) { + return new ActionResult( + success: true, + message: 'messages.system.service_restarted_success', + details: [ + 'service' => $cleanName, + 'driver' => 'Windows', + ], + ); + } + + $errorMessage = $result->errorOutput !== '' ? $result->errorOutput : $result->output; + $isPermissionDenied = $this->isPermissionDeniedError($errorMessage); + + return new ActionResult( + success: false, + message: $isPermissionDenied + ? 'messages.common.permission_denied' + : 'messages.system.service_restarted_failed', + details: [ + 'service' => $cleanName, + 'error' => $errorMessage !== '' ? $errorMessage : 'Restart-Service failed', + 'driver' => 'Windows', + ], + ); + } + + /** + * {@inheritDoc} + */ + public function getBatteryHealth(): ActionResult + { + $script = <<<'PS' +$ErrorActionPreference = 'SilentlyContinue'; +$bat = Get-CimInstance -ClassName Win32_Battery -ErrorAction SilentlyContinue | Select-Object -First 1; +if ($null -eq $bat) { + [PSCustomObject]@{ HasBattery = $false } | ConvertTo-Json -Compress; + exit 0; +} +$static = Get-CimInstance -Namespace 'root\WMI' -ClassName BatteryStaticData -ErrorAction SilentlyContinue | Select-Object -First 1; +$full = Get-CimInstance -Namespace 'root\WMI' -ClassName BatteryFullChargedCapacity -ErrorAction SilentlyContinue | Select-Object -First 1; +$cycle = Get-CimInstance -Namespace 'root\WMI' -ClassName BatteryCycleCount -ErrorAction SilentlyContinue | Select-Object -First 1; +[PSCustomObject]@{ + HasBattery = $true; + Name = [string]$bat.Name; + BatteryStatus = [int]$bat.BatteryStatus; + ChargePercent = [int]$bat.EstimatedChargeRemaining; + DesignCapacity = [double]($static.DesignedCapacity -as [double]); + FullChargedCapacity = [double]($full.FullChargedCapacity -as [double]); + CycleCount = [int]($cycle.CycleCount -as [int]) +} | ConvertTo-Json -Compress +PS; + + $data = $this->runPowerShellJson($script); + + if ($data === [] || ($data['HasBattery'] ?? false) === false) { + return new ActionResult( + success: false, + message: 'messages.system.no_battery', + details: ['driver' => 'Windows'], + ); + } + + $statusInt = (int) ($data['BatteryStatus'] ?? 1); + $statusLabel = match ($statusInt) { + 2, 6, 7, 8, 9 => 'Charging / AC Power', + 1, 4, 5 => 'Discharging (On Battery)', + 3 => 'Fully Charged', + default => 'Unknown', + }; + + $designCap = (float) ($data['DesignCapacity'] ?? 0.0); + $fullCap = (float) ($data['FullChargedCapacity'] ?? 0.0); + $healthPercent = ($designCap > 0.0 && $fullCap > 0.0) + ? min(100.0, round(($fullCap / $designCap) * 100.0, 1)) + : 100.0; + $wearPercent = max(0.0, round(100.0 - $healthPercent, 1)); + + return new ActionResult( + success: true, + message: 'messages.system.battery_fetched_success', + details: [ + 'battery_status' => $statusLabel, + 'charge_percent' => sprintf('%d%%', (int) ($data['ChargePercent'] ?? 0)), + 'design_capacity' => $designCap > 0.0 ? sprintf('%.0f mWh', $designCap) : 'N/A', + 'full_charge_capacity' => $fullCap > 0.0 ? sprintf('%.0f mWh', $fullCap) : 'N/A', + 'battery_health' => sprintf('%.1f%% (Wear: %.1f%%)', $healthPercent, $wearPercent), + 'cycle_count' => (int) ($data['CycleCount'] ?? 0) > 0 ? (string) ((int) $data['CycleCount']) : 'N/A', + 'driver' => 'Windows', + ], + ); + } + + /** + * {@inheritDoc} + */ + public function getStartupPrograms(): array + { + $script = <<<'PS' +$ErrorActionPreference = 'SilentlyContinue'; +@(Get-CimInstance -ClassName Win32_StartupCommand -ErrorAction SilentlyContinue | ForEach-Object { + [PSCustomObject]@{ + Name = [string]$_.Name; + Command = [string]$_.Command; + Location = [string]$_.Location; + User = [string]$_.User + } +}) | ConvertTo-Json -Compress +PS; + + $items = $this->normalizeJsonList($this->runPowerShellJson($script)); + + $entries = []; + foreach ($items as $item) { + if (! is_array($item) || empty($item['Name'])) { + continue; + } + + $entries[] = [ + 'name' => trim((string) $item['Name']), + 'command' => $this->truncateLogMessage((string) ($item['Command'] ?? '-'), 65), + 'location' => trim((string) ($item['Location'] ?? 'Registry')), + 'user' => trim((string) ($item['User'] ?? 'System')), + ]; + } + + return $entries; + } + + /** + * {@inheritDoc} + */ + public function getUsbDevices(): array + { + $script = <<<'PS' +$ErrorActionPreference = 'SilentlyContinue'; +@(Get-PnpDevice -Class USB,HIDClass,Printer,Image -PresentOnly -ErrorAction SilentlyContinue | Select-Object -First 40 | ForEach-Object { + [PSCustomObject]@{ + FriendlyName = [string]$_.FriendlyName; + Manufacturer = [string]$_.Manufacturer; + Status = [string]$_.Status; + InstanceId = [string]$_.InstanceId + } +}) | ConvertTo-Json -Compress +PS; + + $items = $this->normalizeJsonList($this->runPowerShellJson($script)); + + $devices = []; + foreach ($items as $item) { + if (! is_array($item) || empty($item['FriendlyName'])) { + continue; + } + + $devices[] = [ + 'name' => trim((string) $item['FriendlyName']), + 'manufacturer' => trim((string) ($item['Manufacturer'] ?? '-')) ?: '-', + 'status' => trim((string) ($item['Status'] ?? 'OK')) ?: 'OK', + 'device_id' => $this->truncateLogMessage((string) ($item['InstanceId'] ?? '-'), 55), + ]; + } + + return $devices; + } + /** * {@inheritDoc} */ diff --git a/lang/en/messages.php b/lang/en/messages.php index 7d62332..16d8146 100644 --- a/lang/en/messages.php +++ b/lang/en/messages.php @@ -43,6 +43,12 @@ 'system_info' => 'View OS, CPU, RAM & Storage Health (system:info)', 'system_top' => 'Inspect Top Processes & Kill Frozen Tasks (system:top)', 'system_logs' => 'Inspect Critical OS Logs & Recent Errors (system:logs)', + 'system_services' => 'Manage & Restart Critical Support Services (system:services)', + 'system_battery' => 'Inspect Laptop Battery Health, Capacity & Wear (system:battery)', + 'system_startup' => 'Inspect Boot & Login Startup Programs (system:startup)', + 'system_usb' => 'List Connected USB Controllers & Peripherals (system:usb)', + 'system_env' => 'Audit Environment Variables & Broken PATH Entries (system:env)', + 'system_kill' => 'Force-Kill Frozen Process by PID, Name or List (system:kill)', 'printer_list' => 'List Installed Printers & Status (printer:list)', 'printer_clear' => 'Restart Spooler & Clear Print Queue (printer:clear)', 'network_check' => 'Interfaces & Connectivity Health Check (network:check)', @@ -76,6 +82,12 @@ 'system_info' => 'Collecting OS, hardware, and storage metrics...', 'system_top' => 'Querying top resource-consuming processes...', 'system_logs' => 'Scanning OS event logs for critical errors in the last 24 hours...', + 'system_services' => 'Querying status of critical IT support services...', + 'restarting_service' => 'Restarting system service ":service"...', + 'system_battery' => 'Querying battery hardware telemetry and wear metrics...', + 'system_startup' => 'Scanning startup registry keys, autostart entries, and boot services...', + 'system_usb' => 'Enumerating connected USB controllers and peripheral devices...', + 'system_env' => 'Auditing environment variables and system PATH directories...', 'killing_process' => 'Terminating process PID :pid...', 'printer_list' => 'Querying installed printers and spooler status...', 'printer_clear' => 'Stopping spooler, purging queue, and restarting service...', @@ -131,8 +143,53 @@ 'ask_kill_prompt' => 'Would you like to terminate one of these processes?', 'select_process_prompt' => 'Select the process to terminate:', 'confirm_kill' => 'Are you sure you want to force-terminate PID :pid (:name)?', + 'confirm_kill_name' => 'Are you sure you want to force-terminate all processes matching ":name"?', 'process_killed_success' => 'Process terminated successfully.', 'process_killed_failed' => 'Failed to terminate the selected process.', + 'kill_section' => 'Process Termination Utility', + 'services_section' => 'Critical System & IT Support Services', + 'no_services' => 'No matching support services found on this system.', + 'service_headers' => [ + 'name' => 'Service ID', + 'display_name' => 'Display Name', + 'status' => 'State', + 'start_type' => 'Startup Type', + ], + 'ask_restart_service' => 'Would you like to restart one of these services now?', + 'select_service_prompt' => 'Select the service number to restart:', + 'service_restarted_success' => 'System service restarted successfully.', + 'service_restarted_failed' => 'Failed to restart the system service. Check administrator/sudo privileges.', + 'battery_section' => 'Laptop Battery Health & Capacity Diagnostics', + 'battery_fetched_success' => 'Battery health and capacity metrics retrieved successfully.', + 'no_battery' => 'No battery detected on this system (Desktop workstation or AC-only device).', + 'startup_section' => 'System Boot & User Login Startup Items', + 'no_startup_items' => 'No startup programs or enabled boot services found.', + 'startup_headers' => [ + 'name' => 'Name / Service', + 'command' => 'Command / Unit', + 'location' => 'Source / Location', + 'user' => 'Account', + ], + 'usb_section' => 'Connected USB Controllers & Peripheral Devices', + 'no_usb_devices' => 'No connected USB peripheral devices detected.', + 'usb_headers' => [ + 'name' => 'Device Name / Description', + 'manufacturer' => 'Manufacturer / Vendor ID', + 'status' => 'Status', + 'device_id' => 'Instance / Bus ID', + ], + 'env_section' => 'Core System Environment Variables', + 'path_audit_section' => 'System PATH Directory Audit', + 'path_headers' => [ + 'directory' => 'Directory Path', + 'status' => 'Audit Result', + ], + 'path_states' => [ + 'valid' => 'Valid', + 'broken' => 'Missing / Broken', + 'duplicate' => 'Duplicate', + ], + 'path_summary' => 'PATH Audit Summary -> ✅ Valid: :valid | ❌ Missing/Broken: :broken | ⚠️ Duplicate: :duplicate', ], 'logs' => [ @@ -325,6 +382,14 @@ 'location' => 'City / Region / Country', 'isp' => 'ISP / Organization (ASN)', 'reverse_hostname' => 'Reverse Hostname', + 'process_name' => 'Process Name', + 'signal' => 'Signal / Quality', + 'battery_status' => 'Power / Charging State', + 'charge_percent' => 'Current Charge (%)', + 'design_capacity' => 'Design Capacity', + 'full_charge_capacity' => 'Full Charge Capacity', + 'battery_health' => 'Battery Health & Wear', + 'cycle_count' => 'Charge Cycle Count', ], ], diff --git a/lang/pt_BR/messages.php b/lang/pt_BR/messages.php index bc557b4..7c6313e 100644 --- a/lang/pt_BR/messages.php +++ b/lang/pt_BR/messages.php @@ -43,6 +43,12 @@ 'system_info' => 'Exibir SO, CPU, RAM e Saúde de Discos (system:info)', 'system_top' => 'Inspecionar Processos e Encerrar Tarefas Travadas (system:top)', 'system_logs' => 'Logs Críticos do SO & Erros Recentes (system:logs)', + 'system_services' => 'Gerenciar e Reiniciar Serviços Críticos de Suporte (system:services)', + 'system_battery' => 'Saúde da Bateria, Capacidade e Desgaste (system:battery)', + 'system_startup' => 'Inspecionar Programas e Serviços de Inicialização (system:startup)', + 'system_usb' => 'Listar Controladores e Dispositivos USB Conectados (system:usb)', + 'system_env' => 'Auditar Variáveis de Ambiente e Diretórios do PATH (system:env)', + 'system_kill' => 'Encerrar Processo Travado por PID, Nome ou Lista (system:kill)', 'printer_list' => 'Listar Impressoras Instaladas e Status (printer:list)', 'printer_clear' => 'Reiniciar Spooler e Limpar Fila de Impressão (printer:clear)', 'network_check' => 'Interfaces e Teste de Saúde de Conectividade (network:check)', @@ -76,6 +82,12 @@ 'system_info' => 'Coletando métricas de SO, hardware e armazenamento...', 'system_top' => 'Consultando processos com maior consumo de recursos...', 'system_logs' => 'Analisando logs do SO em busca de erros críticos nas últimas 24h...', + 'system_services' => 'Consultando status dos serviços críticos de suporte...', + 'restarting_service' => 'Reiniciando serviço do sistema ":service"...', + 'system_battery' => 'Consultando telemetria de hardware e desgaste da bateria...', + 'system_startup' => 'Analisando chaves de inicialização, autostart e serviços de boot...', + 'system_usb' => 'Enumerando controladores e periféricos USB conectados...', + 'system_env' => 'Auditando variáveis de ambiente e diretórios do PATH...', 'killing_process' => 'Encerrando processo PID :pid...', 'printer_list' => 'Consultando impressoras instaladas e status do spooler...', 'printer_clear' => 'Parando spooler, limpando fila e reiniciando serviço...', @@ -131,8 +143,53 @@ 'ask_kill_prompt' => 'Deseja encerrar algum destes processos?', 'select_process_prompt' => 'Selecione o processo que deseja encerrar:', 'confirm_kill' => 'Tem certeza de que deseja forçar o encerramento do PID :pid (:name)?', + 'confirm_kill_name' => 'Tem certeza de que deseja forçar o encerramento de todos os processos ":name"?', 'process_killed_success' => 'Processo encerrado com sucesso.', 'process_killed_failed' => 'Falha ao encerrar o processo selecionado.', + 'kill_section' => 'Utilitário de Encerramento de Processos', + 'services_section' => 'Serviços Críticos do Sistema & Suporte de TI', + 'no_services' => 'Nenhum serviço de suporte correspondente encontrado neste sistema.', + 'service_headers' => [ + 'name' => 'ID do Serviço', + 'display_name' => 'Nome de Exibição', + 'status' => 'Estado', + 'start_type' => 'Tipo de Inicialização', + ], + 'ask_restart_service' => 'Deseja reiniciar algum destes serviços agora?', + 'select_service_prompt' => 'Selecione o número do serviço que deseja reiniciar:', + 'service_restarted_success' => 'Serviço do sistema reiniciado com sucesso.', + 'service_restarted_failed' => 'Falha ao reiniciar o serviço. Verifique privilégios de Administrador/sudo.', + 'battery_section' => 'Diagnóstico de Saúde e Capacidade da Bateria', + 'battery_fetched_success' => 'Métricas de saúde e capacidade da bateria coletadas com sucesso.', + 'no_battery' => 'Nenhuma bateria detectada neste sistema (Desktop ou equipamento sem bateria).', + 'startup_section' => 'Programas e Serviços de Inicialização (Boot / Login)', + 'no_startup_items' => 'Nenhum programa de inicialização ou serviço de boot habilitado encontrado.', + 'startup_headers' => [ + 'name' => 'Nome / Serviço', + 'command' => 'Comando / Unidade', + 'location' => 'Origem / Local', + 'user' => 'Conta', + ], + 'usb_section' => 'Controladores e Dispositivos Periféricos USB Conectados', + 'no_usb_devices' => 'Nenhum dispositivo periférico USB conectado foi detectado.', + 'usb_headers' => [ + 'name' => 'Nome / Descrição do Dispositivo', + 'manufacturer' => 'Fabricante / Vendor ID', + 'status' => 'Status', + 'device_id' => 'Instance / Bus ID', + ], + 'env_section' => 'Principais Variáveis de Ambiente do Sistema', + 'path_audit_section' => 'Auditoria de Diretórios da Variável PATH', + 'path_headers' => [ + 'directory' => 'Diretório no PATH', + 'status' => 'Resultado da Auditoria', + ], + 'path_states' => [ + 'valid' => 'Válido', + 'broken' => 'Inexistente / Quebrado', + 'duplicate' => 'Duplicado', + ], + 'path_summary' => 'Resumo do PATH -> ✅ Válidos: :valid | ❌ Inexistentes/Quebrados: :broken | ⚠️ Duplicados: :duplicate', ], 'logs' => [ @@ -325,6 +382,14 @@ 'location' => 'Cidade / Região / País', 'isp' => 'Provedor / Organização (ASN)', 'reverse_hostname' => 'Hostname Reverso', + 'process_name' => 'Nome do Processo', + 'signal' => 'Sinal / Qualidade', + 'battery_status' => 'Estado de Energia / Carga', + 'charge_percent' => 'Carga Atual (%)', + 'design_capacity' => 'Capacidade Projetada', + 'full_charge_capacity' => 'Capacidade Total Atual', + 'battery_health' => 'Saúde e Desgaste da Bateria', + 'cycle_count' => 'Contagem de Ciclos', ], ], diff --git a/tests/Feature/ReportExporterTest.php b/tests/Feature/ReportExporterTest.php index cdc7ebc..ad51d93 100644 --- a/tests/Feature/ReportExporterTest.php +++ b/tests/Feature/ReportExporterTest.php @@ -57,11 +57,46 @@ public function killProcess(int $pid): ActionResult return new ActionResult(true, 'messages.system.process_killed_success'); } + public function killProcessByName(string $processName): ActionResult + { + return new ActionResult(true, 'messages.system.process_killed_success'); + } + public function getCriticalLogs(int $limit = 15): ActionResult { return new ActionResult(true, 'messages.logs.no_logs', ['events' => [], 'count' => 0]); } + public function getCriticalServices(): array + { + return []; + } + + public function restartService(string $serviceName): ActionResult + { + return new ActionResult(true, 'messages.system.service_restarted_success'); + } + + public function getBatteryHealth(): ActionResult + { + return new ActionResult(false, 'messages.system.no_battery'); + } + + public function getStartupPrograms(): array + { + return []; + } + + public function getUsbDevices(): array + { + return []; + } + + public function auditEnvironmentPath(?string $customPathString = null): array + { + return ['variables' => [], 'path_entries' => [], 'summary' => ['valid' => 0, 'broken' => 0, 'duplicate' => 0]]; + } + public function listPrinters(): array { return [ diff --git a/tests/Unit/HealthCheckServiceTest.php b/tests/Unit/HealthCheckServiceTest.php index fdc2676..b03e74c 100644 --- a/tests/Unit/HealthCheckServiceTest.php +++ b/tests/Unit/HealthCheckServiceTest.php @@ -67,6 +67,11 @@ public function killProcess(int $pid): ActionResult return new ActionResult(true, 'ok'); } + public function killProcessByName(string $processName): ActionResult + { + return new ActionResult(true, 'ok'); + } + public function getCriticalLogs(int $limit = 15): ActionResult { $events = array_fill(0, $this->criticalLogCount, [ @@ -79,6 +84,36 @@ public function getCriticalLogs(int $limit = 15): ActionResult return new ActionResult(true, 'ok', ['events' => $events, 'count' => count($events)]); } + public function getCriticalServices(): array + { + return []; + } + + public function restartService(string $serviceName): ActionResult + { + return new ActionResult(true, 'ok'); + } + + public function getBatteryHealth(): ActionResult + { + return new ActionResult(false, 'messages.system.no_battery'); + } + + public function getStartupPrograms(): array + { + return []; + } + + public function getUsbDevices(): array + { + return []; + } + + public function auditEnvironmentPath(?string $customPathString = null): array + { + return ['variables' => [], 'path_entries' => [], 'summary' => ['valid' => 0, 'broken' => 0, 'duplicate' => 0]]; + } + public function listPrinters(): array { return $this->printers; diff --git a/tests/Unit/LinuxDriverTest.php b/tests/Unit/LinuxDriverTest.php index 7732dc7..f34d8d2 100644 --- a/tests/Unit/LinuxDriverTest.php +++ b/tests/Unit/LinuxDriverTest.php @@ -206,3 +206,93 @@ public function getEffectiveUid(): int ->and($neighbors[0]['status'])->toBe('REACHABLE') ->and($neighbors[1]['ip'])->toBe('192.168.1.25'); }); + +it('parses Linux critical services, /sys battery telemetry, systemd startup units, lsusb devices, and killProcessByName', function (): void { + $executor = new class implements ProcessExecutorInterface + { + /** @var array */ + public array $files = [ + '/sys/class/power_supply/BAT0/status' => "Discharging\n", + '/sys/class/power_supply/BAT0/capacity' => "76\n", + '/sys/class/power_supply/BAT0/energy_full_design' => "60000000\n", // 60,000 mWh + '/sys/class/power_supply/BAT0/energy_full' => "51000000\n", // 51,000 mWh (85% health, 15% wear) + '/sys/class/power_supply/BAT0/cycle_count' => "215\n", + ]; + + public function run(array $command, int $timeout = 30): ProcessResult + { + if ($command[0] === 'systemctl' && ($command[1] ?? '') === 'show') { + return new ProcessResult(0, implode("\n", [ + 'Id=cups.service', + 'Description=CUPS Scheduler', + 'LoadState=loaded', + 'ActiveState=active', + 'UnitFileState=enabled', + '', + 'Id=nginx.service', + 'Description=A high performance web server', + 'LoadState=loaded', + 'ActiveState=inactive', + 'UnitFileState=disabled', + ])); + } + + return match ($command) { + ['systemctl', 'restart', 'cups'] => new ProcessResult(0, ''), + ['systemctl', 'list-unit-files', '--state=enabled', '--type=service', '--no-pager', '--no-legend'] => new ProcessResult( + 0, + "cups.service enabled enabled\nssh.service enabled enabled\n" + ), + ['lsusb'] => new ProcessResult( + 0, + "Bus 001 Device 002: ID 046d:c52b Logitech, Inc. Unifying Receiver\nBus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub\n" + ), + ['pkill', '-15', '-x', 'firefox'] => new ProcessResult(0, ''), + default => new ProcessResult(1, '', 'Failed', false), + }; + } + + public function readFile(string $path): ?string + { + return $this->files[$path] ?? null; + } + + public function getEffectiveUid(): int + { + return 0; + } + }; + + $driver = new LinuxDriver($executor); + + $services = $driver->getCriticalServices(); + expect($services)->toHaveCount(2) + ->and($services[0]['name'])->toBe('cups') + ->and($services[0]['status'])->toBe('Running') + ->and($services[1]['name'])->toBe('nginx') + ->and($services[1]['status'])->toBe('Stopped'); + + $restart = $driver->restartService('cups'); + expect($restart->success)->toBeTrue() + ->and($restart->message)->toBe('messages.system.service_restarted_success'); + + $battery = $driver->getBatteryHealth(); + expect($battery->success)->toBeTrue() + ->and($battery->details['charge_percent'])->toBe('76%') + ->and($battery->details['battery_health'])->toBe('85.0% (Wear: 15.0%)') + ->and($battery->details['cycle_count'])->toBe('215'); + + $startup = $driver->getStartupPrograms(); + expect($startup)->toHaveCount(2) + ->and($startup[0]['name'])->toBe('cups') + ->and($startup[1]['name'])->toBe('ssh'); + + $usb = $driver->getUsbDevices(); + expect($usb)->toHaveCount(2) + ->and($usb[0]['name'])->toBe('Logitech, Inc. Unifying Receiver') + ->and($usb[0]['manufacturer'])->toBe('ID 046d:c52b'); + + $killByName = $driver->killProcessByName('firefox'); + expect($killByName->success)->toBeTrue() + ->and($killByName->details['process_name'])->toBe('firefox'); +}); diff --git a/tests/Unit/WindowsDriverTest.php b/tests/Unit/WindowsDriverTest.php index b7a0f92..2094c0f 100644 --- a/tests/Unit/WindowsDriverTest.php +++ b/tests/Unit/WindowsDriverTest.php @@ -295,3 +295,106 @@ public function getEffectiveUid(): int ->and($lanDevices[0]['mac'])->toBe('00:1A:2B:3C:4D:5E') ->and($lanDevices[1]['ip'])->toBe('192.168.1.50'); }); + +it('parses Windows critical services, battery health, startup items, USB devices, PATH audit, and killProcessByName', function (): void { + $executor = new class implements ProcessExecutorInterface + { + public int $callIndex = 0; + + public function run(array $command, int $timeout = 30): ProcessResult + { + $this->callIndex++; + + return match ($this->callIndex) { + 1 => new ProcessResult(0, (string) json_encode([ + [ + 'Name' => 'Spooler', + 'DisplayName' => 'Print Spooler', + 'Status' => 'Running', + 'StartType' => 'Automatic', + ], + ])), + 2 => new ProcessResult(0, ''), // Restart-Service Spooler + 3 => new ProcessResult(0, (string) json_encode([ + 'HasBattery' => true, + 'Name' => 'DELL 0V9H2', + 'BatteryStatus' => 2, + 'ChargePercent' => 84, + 'DesignCapacity' => 50000, + 'FullChargedCapacity' => 45000, + 'CycleCount' => 120, + ])), + 4 => new ProcessResult(0, (string) json_encode([ + 'HasBattery' => false, + ])), + 5 => new ProcessResult(0, (string) json_encode([ + [ + 'Name' => 'OneDrive', + 'Command' => 'C:\\Program Files\\Microsoft OneDrive\\OneDrive.exe /background', + 'Location' => 'HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run', + 'User' => 'CORP\\User', + ], + ])), + 6 => new ProcessResult(0, (string) json_encode([ + [ + 'FriendlyName' => 'USB Root Hub (USB 3.0)', + 'Manufacturer' => '(Standard USB HUBs)', + 'Status' => 'OK', + 'InstanceId' => 'USB\\ROOT_HUB30\\4&1A2B3C', + ], + ])), + 7 => new ProcessResult(0, ''), // Stop-Process -Name 'notepad' + default => new ProcessResult(0, '[]'), + }; + } + + public function readFile(string $path): ?string + { + return null; + } + + public function getEffectiveUid(): int + { + return 0; + } + }; + + $driver = new WindowsDriver($executor); + + $services = $driver->getCriticalServices(); + expect($services)->toHaveCount(1) + ->and($services[0]['name'])->toBe('Spooler') + ->and($services[0]['status'])->toBe('Running'); + + $restart = $driver->restartService('Spooler'); + expect($restart->success)->toBeTrue() + ->and($restart->message)->toBe('messages.system.service_restarted_success'); + + $battery = $driver->getBatteryHealth(); + expect($battery->success)->toBeTrue() + ->and($battery->details['charge_percent'])->toBe('84%') + ->and($battery->details['battery_health'])->toBe('90.0% (Wear: 10.0%)') + ->and($battery->details['cycle_count'])->toBe('120'); + + $noBattery = $driver->getBatteryHealth(); + expect($noBattery->success)->toBeFalse() + ->and($noBattery->message)->toBe('messages.system.no_battery'); + + $startup = $driver->getStartupPrograms(); + expect($startup)->toHaveCount(1) + ->and($startup[0]['name'])->toBe('OneDrive'); + + $usb = $driver->getUsbDevices(); + expect($usb)->toHaveCount(1) + ->and($usb[0]['name'])->toBe('USB Root Hub (USB 3.0)'); + + $killByName = $driver->killProcessByName('notepad.exe'); + expect($killByName->success)->toBeTrue() + ->and($killByName->details['process_name'])->toBe('notepad'); + + $validDir = sys_get_temp_dir(); + $pathAudit = $driver->auditEnvironmentPath($validDir . ';C:\\NonExistent_Toolbox_Dir_999;' . $validDir); + expect($pathAudit['summary']['valid'])->toBe(1) + ->and($pathAudit['summary']['broken'])->toBe(1) + ->and($pathAudit['summary']['duplicate'])->toBe(1); +}); From dd7fbb007ae3ad7c09b9f7684f86ef0f984f589b Mon Sep 17 00:00:00 2001 From: Dev-lib4n Date: Wed, 18 Nov 2026 15:23:55 -0300 Subject: [PATCH 3/5] fix(windows-driver): use explicit semicolon separator in auditEnvironmentPath for cross-OS test compatibility --- .../Concerns/InteractsWithNetworkSockets.php | 14 ++++++++++---- app/Drivers/LinuxDriver.php | 8 ++++++++ app/Drivers/WindowsDriver.php | 8 ++++++++ 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/app/Drivers/Concerns/InteractsWithNetworkSockets.php b/app/Drivers/Concerns/InteractsWithNetworkSockets.php index 08a2689..90ac6ea 100644 --- a/app/Drivers/Concerns/InteractsWithNetworkSockets.php +++ b/app/Drivers/Concerns/InteractsWithNetworkSockets.php @@ -336,9 +336,7 @@ protected function isUnicastLanNeighbor(string $ip, string $mac): bool public function auditEnvironmentPath(?string $customPathString = null): array { $rawPath = $customPathString ?? (string) (getenv('PATH') ?: ($_SERVER['PATH'] ?? '')); - $separator = str_contains($rawPath, ';') && ! str_contains($rawPath, ':') - ? ';' - : (PHP_OS_FAMILY === 'Windows' && $customPathString === null ? ';' : PATH_SEPARATOR); + $separator = $this->getEnvPathSeparator(); $rawEntries = $rawPath !== '' ? explode($separator, $rawPath) : []; @@ -355,7 +353,7 @@ public function auditEnvironmentPath(?string $customPathString = null): array continue; } - $normalizedKey = PHP_OS_FAMILY === 'Windows' + $normalizedKey = $separator === ';' ? strtolower(rtrim($cleanPath, '\\/')) : rtrim($cleanPath, '/'); @@ -402,4 +400,12 @@ public function auditEnvironmentPath(?string $customPathString = null): array ], ]; } + + /** + * Return the OS-specific PATH entry separator (';' on Windows, ':' on Linux). + */ + protected function getEnvPathSeparator(): string + { + return PATH_SEPARATOR; + } } diff --git a/app/Drivers/LinuxDriver.php b/app/Drivers/LinuxDriver.php index a622bd4..759dc0a 100644 --- a/app/Drivers/LinuxDriver.php +++ b/app/Drivers/LinuxDriver.php @@ -2083,4 +2083,12 @@ protected function truncateLogMessage(string $message, int $maxLength = 90): str return rtrim(mb_substr($clean, 0, $maxLength - 3)) . '...'; } + + /** + * Linux always uses ':' as the PATH directory separator. + */ + protected function getEnvPathSeparator(): string + { + return ':'; + } } diff --git a/app/Drivers/WindowsDriver.php b/app/Drivers/WindowsDriver.php index 6447bac..15f5791 100644 --- a/app/Drivers/WindowsDriver.php +++ b/app/Drivers/WindowsDriver.php @@ -1316,4 +1316,12 @@ protected function truncateLogMessage(string $message, int $maxLength = 90): str return rtrim(mb_substr($clean, 0, $maxLength - 3)) . '...'; } + + /** + * Windows always uses ';' as the PATH directory separator. + */ + protected function getEnvPathSeparator(): string + { + return ';'; + } } From ba83dfa4897f36ef1506168d1c962e6f5c5f5a72 Mon Sep 17 00:00:00 2001 From: Dev-lib4n Date: Wed, 18 Nov 2026 15:40:49 -0300 Subject: [PATCH 4/5] feat(maintenance,security): add OS repair, large files, browser cache, updates, scheduler, and security audit suite --- .../Maintenance/CleanBrowsersCommand.php | 63 +++ .../Maintenance/LargeFilesCommand.php | 83 ++++ app/Commands/Maintenance/OsRepairCommand.php | 63 +++ app/Commands/Maintenance/OsUpdatesCommand.php | 74 +++ app/Commands/Maintenance/SchedulerCommand.php | 75 +++ app/Commands/Security/HostsFileCommand.php | 78 ++++ .../Security/SecurityAuditCommand.php | 66 +++ app/Commands/Security/SharesCommand.php | 74 +++ app/Commands/Security/UsersAuditCommand.php | 75 +++ app/Commands/ToolboxMenuCommand.php | 25 +- app/Contracts/SystemDriverInterface.php | 67 +++ .../InteractsWithMaintenanceAndSecurity.php | 320 +++++++++++++ app/Drivers/LinuxDriver.php | 441 ++++++++++++++++++ app/Drivers/WindowsDriver.php | 314 +++++++++++++ lang/en/messages.php | 90 +++- lang/pt_BR/messages.php | 90 +++- tests/Feature/ReportExporterTest.php | 45 ++ tests/Unit/HealthCheckServiceTest.php | 45 ++ tests/Unit/LinuxDriverTest.php | 83 ++++ tests/Unit/WindowsDriverTest.php | 127 +++++ 20 files changed, 2288 insertions(+), 10 deletions(-) create mode 100644 app/Commands/Maintenance/CleanBrowsersCommand.php create mode 100644 app/Commands/Maintenance/LargeFilesCommand.php create mode 100644 app/Commands/Maintenance/OsRepairCommand.php create mode 100644 app/Commands/Maintenance/OsUpdatesCommand.php create mode 100644 app/Commands/Maintenance/SchedulerCommand.php create mode 100644 app/Commands/Security/HostsFileCommand.php create mode 100644 app/Commands/Security/SecurityAuditCommand.php create mode 100644 app/Commands/Security/SharesCommand.php create mode 100644 app/Commands/Security/UsersAuditCommand.php create mode 100644 app/Drivers/Concerns/InteractsWithMaintenanceAndSecurity.php diff --git a/app/Commands/Maintenance/CleanBrowsersCommand.php b/app/Commands/Maintenance/CleanBrowsersCommand.php new file mode 100644 index 0000000..7f59a18 --- /dev/null +++ b/app/Commands/Maintenance/CleanBrowsersCommand.php @@ -0,0 +1,63 @@ +resolveLocale(); + + info((string) __('messages.maintenance.browsers_section')); + + if (! $this->option('force') && ! confirm( + label: (string) __('messages.maintenance.confirm_browsers_clean'), + default: true, + yes: (string) __('messages.common.yes'), + no: (string) __('messages.common.no'), + )) { + warning((string) __('messages.common.cancelled')); + + return self::SUCCESS; + } + + $result = spin( + callback: fn () => $driver->cleanBrowserCaches(), + message: (string) __('messages.spinners.maintenance_browsers'), + ); + + return $this->renderActionResult($result); + } +} diff --git a/app/Commands/Maintenance/LargeFilesCommand.php b/app/Commands/Maintenance/LargeFilesCommand.php new file mode 100644 index 0000000..c014c13 --- /dev/null +++ b/app/Commands/Maintenance/LargeFilesCommand.php @@ -0,0 +1,83 @@ +resolveLocale(); + + info((string) __('messages.maintenance.large_files_section')); + + $pathArg = $this->argument('path'); + $targetPath = is_string($pathArg) && trim($pathArg) !== '' ? trim($pathArg) : null; + $limit = max(1, (int) $this->option('limit')); + + /** @var array $files */ + $files = spin( + callback: fn (): array => $driver->findLargeFiles($targetPath, $limit), + message: (string) __('messages.spinners.maintenance_large_files'), + ); + + if ($files === []) { + warning((string) __('messages.maintenance.no_large_files')); + + return self::SUCCESS; + } + + table( + headers: [ + '#', + (string) __('messages.maintenance.large_files_headers.size'), + (string) __('messages.maintenance.large_files_headers.modified'), + (string) __('messages.maintenance.large_files_headers.path'), + ], + rows: array_map( + fn (array $file, int $idx): array => [ + (string) ($idx + 1), + $file['size_formatted'], + $file['modified_at'], + $file['path'], + ], + $files, + array_keys($files) + ), + ); + + return self::SUCCESS; + } +} diff --git a/app/Commands/Maintenance/OsRepairCommand.php b/app/Commands/Maintenance/OsRepairCommand.php new file mode 100644 index 0000000..15b065d --- /dev/null +++ b/app/Commands/Maintenance/OsRepairCommand.php @@ -0,0 +1,63 @@ +resolveLocale(); + + info((string) __('messages.maintenance.repair_section')); + + if (! $this->option('force') && ! confirm( + label: (string) __('messages.maintenance.confirm_repair'), + default: false, + yes: (string) __('messages.common.yes'), + no: (string) __('messages.common.no'), + )) { + warning((string) __('messages.common.cancelled')); + + return self::SUCCESS; + } + + $result = spin( + callback: fn () => $driver->repairOsIntegrity(), + message: (string) __('messages.spinners.maintenance_repair'), + ); + + return $this->renderActionResult($result); + } +} diff --git a/app/Commands/Maintenance/OsUpdatesCommand.php b/app/Commands/Maintenance/OsUpdatesCommand.php new file mode 100644 index 0000000..4c36f8f --- /dev/null +++ b/app/Commands/Maintenance/OsUpdatesCommand.php @@ -0,0 +1,74 @@ +resolveLocale(); + + info((string) __('messages.maintenance.updates_section')); + + /** @var array $updates */ + $updates = spin( + callback: fn (): array => $driver->getPendingUpdates(), + message: (string) __('messages.spinners.maintenance_updates'), + ); + + if ($updates === []) { + info((string) __('messages.maintenance.no_pending_updates')); + + return self::SUCCESS; + } + + table( + headers: [ + (string) __('messages.maintenance.updates_headers.package'), + (string) __('messages.maintenance.updates_headers.version'), + (string) __('messages.maintenance.updates_headers.source'), + (string) __('messages.maintenance.updates_headers.status'), + ], + rows: array_map( + fn (array $upd): array => [ + $upd['package'] ?? '-', + $upd['version'] ?? '-', + $upd['source'] ?? '-', + $upd['status'] ?? '-', + ], + $updates + ), + ); + + return self::SUCCESS; + } +} diff --git a/app/Commands/Maintenance/SchedulerCommand.php b/app/Commands/Maintenance/SchedulerCommand.php new file mode 100644 index 0000000..d59d8f7 --- /dev/null +++ b/app/Commands/Maintenance/SchedulerCommand.php @@ -0,0 +1,75 @@ +resolveLocale(); + + info((string) __('messages.maintenance.scheduler_section')); + + /** @var array $tasks */ + $tasks = spin( + callback: fn (): array => $driver->getScheduledTasks(), + message: (string) __('messages.spinners.maintenance_scheduler'), + ); + + if ($tasks === []) { + warning((string) __('messages.maintenance.no_scheduled_tasks')); + + return self::SUCCESS; + } + + table( + headers: [ + (string) __('messages.maintenance.scheduler_headers.name'), + (string) __('messages.maintenance.scheduler_headers.schedule'), + (string) __('messages.maintenance.scheduler_headers.next_run'), + (string) __('messages.maintenance.scheduler_headers.status'), + ], + rows: array_map( + fn (array $task): array => [ + $task['name'] ?? '-', + $task['schedule'] ?? '-', + $task['next_run'] ?? '-', + $task['status'] ?? '-', + ], + $tasks + ), + ); + + return self::SUCCESS; + } +} diff --git a/app/Commands/Security/HostsFileCommand.php b/app/Commands/Security/HostsFileCommand.php new file mode 100644 index 0000000..0f2fee2 --- /dev/null +++ b/app/Commands/Security/HostsFileCommand.php @@ -0,0 +1,78 @@ +resolveLocale(); + + info((string) __('messages.security.hosts_section')); + + /** @var array $entries */ + $entries = spin( + callback: fn (): array => $driver->inspectHostsFile(), + message: (string) __('messages.spinners.security_hosts'), + ); + + if ($entries === []) { + info((string) __('messages.security.no_hosts_entries')); + + return self::SUCCESS; + } + + $statusLabels = [ + 'STANDARD' => (string) __('messages.security.hosts_states.standard'), + 'CUSTOM_LOCAL' => (string) __('messages.security.hosts_states.custom_local'), + 'EXTERNAL_REDIRECT' => (string) __('messages.security.hosts_states.external_redirect'), + ]; + + table( + headers: [ + (string) __('messages.security.hosts_headers.ip'), + (string) __('messages.security.hosts_headers.host'), + (string) __('messages.security.hosts_headers.status'), + ], + rows: array_map( + fn (array $item): array => [ + $item['ip'] ?? '-', + $item['host'] ?? '-', + sprintf('%s %s', $item['icon'] ?? '', $statusLabels[$item['status']] ?? $item['status']), + ], + $entries + ), + ); + + return self::SUCCESS; + } +} diff --git a/app/Commands/Security/SecurityAuditCommand.php b/app/Commands/Security/SecurityAuditCommand.php new file mode 100644 index 0000000..f70cf55 --- /dev/null +++ b/app/Commands/Security/SecurityAuditCommand.php @@ -0,0 +1,66 @@ +resolveLocale(); + + info((string) __('messages.security.audit_section')); + + /** @var array $checks */ + $checks = spin( + callback: fn (): array => $driver->runSecurityAudit(), + message: (string) __('messages.spinners.security_audit'), + ); + + table( + headers: [ + (string) __('messages.security.audit_headers.component'), + (string) __('messages.security.audit_headers.status'), + (string) __('messages.security.audit_headers.details'), + ], + rows: array_map( + fn (array $item): array => [ + $item['component'] ?? '-', + sprintf('%s %s', $item['icon'] ?? '', $item['status'] ?? '-'), + $item['details'] ?? '-', + ], + $checks + ), + ); + + return self::SUCCESS; + } +} diff --git a/app/Commands/Security/SharesCommand.php b/app/Commands/Security/SharesCommand.php new file mode 100644 index 0000000..1f3f2e2 --- /dev/null +++ b/app/Commands/Security/SharesCommand.php @@ -0,0 +1,74 @@ +resolveLocale(); + + info((string) __('messages.security.shares_section')); + + /** @var array $shares */ + $shares = spin( + callback: fn (): array => $driver->getNetworkShares(), + message: (string) __('messages.spinners.security_shares'), + ); + + if ($shares === []) { + info((string) __('messages.security.no_shares_found')); + + return self::SUCCESS; + } + + table( + headers: [ + (string) __('messages.security.shares_headers.name'), + (string) __('messages.security.shares_headers.path'), + (string) __('messages.security.shares_headers.type'), + (string) __('messages.security.shares_headers.description'), + ], + rows: array_map( + fn (array $share): array => [ + $share['name'] ?? '-', + $share['path'] ?? '-', + $share['type'] ?? '-', + $share['description'] ?? '-', + ], + $shares + ), + ); + + return self::SUCCESS; + } +} diff --git a/app/Commands/Security/UsersAuditCommand.php b/app/Commands/Security/UsersAuditCommand.php new file mode 100644 index 0000000..806b084 --- /dev/null +++ b/app/Commands/Security/UsersAuditCommand.php @@ -0,0 +1,75 @@ +resolveLocale(); + + info((string) __('messages.security.users_section')); + + /** @var array $users */ + $users = spin( + callback: fn (): array => $driver->getLocalUsersAudit(), + message: (string) __('messages.spinners.security_users'), + ); + + if ($users === []) { + warning((string) __('messages.security.no_users_found')); + + return self::SUCCESS; + } + + table( + headers: [ + (string) __('messages.security.users_headers.username'), + (string) __('messages.security.users_headers.status'), + (string) __('messages.security.users_headers.is_admin'), + (string) __('messages.security.users_headers.last_logon'), + ], + rows: array_map( + fn (array $user): array => [ + $user['username'] ?? '-', + $user['status'] ?? '-', + $user['is_admin'] ?? 'No', + $user['last_logon'] ?? '-', + ], + $users + ), + ); + + return self::SUCCESS; + } +} diff --git a/app/Commands/ToolboxMenuCommand.php b/app/Commands/ToolboxMenuCommand.php index 9a0f94c..8bb361c 100644 --- a/app/Commands/ToolboxMenuCommand.php +++ b/app/Commands/ToolboxMenuCommand.php @@ -50,9 +50,10 @@ public function handle(): int '3' => (string) __('messages.menu.categories.printers'), '4' => (string) __('messages.menu.categories.network'), '5' => (string) __('messages.menu.categories.maintenance'), - '6' => (string) __('messages.menu.categories.reports'), - '7' => (string) __('messages.menu.categories.self_update'), - '8' => (string) __('messages.menu.categories.language'), + '6' => (string) __('messages.menu.categories.security'), + '7' => (string) __('messages.menu.categories.reports'), + '8' => (string) __('messages.menu.categories.self_update'), + '9' => (string) __('messages.menu.categories.language'), '0' => (string) __('messages.menu.exit'), ], defaultKey: '1', @@ -67,11 +68,11 @@ public function handle(): int if ($choice === '1') { $this->executeSubcommand('health:check', $locale); - } elseif ($choice === '6') { - $this->executeSubcommand('report:export', $locale); } elseif ($choice === '7') { - $this->executeSubcommand('self:update', $locale); + $this->executeSubcommand('report:export', $locale); } elseif ($choice === '8') { + $this->executeSubcommand('self:update', $locale); + } elseif ($choice === '9') { $locale = $this->promptNumericLanguageSwitch($locale); } else { $category = match ($choice) { @@ -79,6 +80,7 @@ public function handle(): int '3' => 'printers', '4' => 'network', '5' => 'maintenance', + '6' => 'security', default => 'system', }; @@ -184,6 +186,17 @@ protected function handleCategorySubmenu(string $category, string $locale): void ], 'maintenance' => [ '1' => ['label' => (string) __('messages.menu.actions.clean_temp'), 'command' => 'clean:temp'], + '2' => ['label' => (string) __('messages.menu.actions.maintenance_browsers'), 'command' => 'maintenance:browsers'], + '3' => ['label' => (string) __('messages.menu.actions.maintenance_large_files'), 'command' => 'maintenance:large-files'], + '4' => ['label' => (string) __('messages.menu.actions.maintenance_repair'), 'command' => 'maintenance:repair'], + '5' => ['label' => (string) __('messages.menu.actions.maintenance_updates'), 'command' => 'maintenance:updates'], + '6' => ['label' => (string) __('messages.menu.actions.maintenance_scheduler'), 'command' => 'maintenance:scheduler'], + ], + 'security' => [ + '1' => ['label' => (string) __('messages.menu.actions.security_audit'), 'command' => 'security:audit'], + '2' => ['label' => (string) __('messages.menu.actions.security_users'), 'command' => 'security:users'], + '3' => ['label' => (string) __('messages.menu.actions.security_shares'), 'command' => 'security:shares'], + '4' => ['label' => (string) __('messages.menu.actions.security_hosts'), 'command' => 'security:hosts'], ], default => [], }; diff --git a/app/Contracts/SystemDriverInterface.php b/app/Contracts/SystemDriverInterface.php index f9bfc03..3fc6522 100644 --- a/app/Contracts/SystemDriverInterface.php +++ b/app/Contracts/SystemDriverInterface.php @@ -205,4 +205,71 @@ public function getPublicIpInfo(): ActionResult; * @return ActionResult */ public function cleanTempFiles(): ActionResult; + + /** + * Run OS image and package integrity verification / repair (SFC & DISM on Windows; dpkg/apt/rpm/pacman audit on Linux). + * + * @return ActionResult + */ + public function repairOsIntegrity(): ActionResult; + + /** + * Scan a target directory recursively and return the largest files sorted by size descending. + * + * @param string|null $directory + * @param int $limit + * @return array + */ + public function findLargeFiles(?string $directory = null, int $limit = 15): array; + + /** + * Safely clean browser cache directories (Chrome, Edge, Firefox) without touching passwords, cookies, or history. + * + * @param array|null $customCachePaths Optional map of browser label => cache path for testing. + * @return ActionResult + */ + public function cleanBrowserCaches(?array $customCachePaths = null): ActionResult; + + /** + * Retrieve pending OS and package updates. + * + * @return array + */ + public function getPendingUpdates(): array; + + /** + * Retrieve active non-system scheduled tasks, cron jobs, and systemd timers. + * + * @return array + */ + public function getScheduledTasks(): array; + + /** + * Run a unified security posture audit (Firewall, Antivirus/Defender/MAC, and UAC/Sudo/SSH policy). + * + * @return array + */ + public function runSecurityAudit(): array; + + /** + * Audit local user accounts, active status, last logon, and Administrative / sudo membership. + * + * @return array + */ + public function getLocalUsersAudit(): array; + + /** + * Retrieve active SMB / Samba / NFS network shares. + * + * @return array + */ + public function getNetworkShares(): array; + + /** + * Inspect the system hosts file and highlight custom or suspicious domain redirections. + * + * @param string|null $customContent Optional raw hosts file content for testing. + * @return array + */ + public function inspectHostsFile(?string $customContent = null): array; } diff --git a/app/Drivers/Concerns/InteractsWithMaintenanceAndSecurity.php b/app/Drivers/Concerns/InteractsWithMaintenanceAndSecurity.php new file mode 100644 index 0000000..7b80bf4 --- /dev/null +++ b/app/Drivers/Concerns/InteractsWithMaintenanceAndSecurity.php @@ -0,0 +1,320 @@ + + */ + private const STANDARD_LOCAL_HOSTS = [ + 'localhost', + 'localhost.localdomain', + 'local', + 'ip6-localhost', + 'ip6-loopback', + 'ip6-localnet', + 'ip6-mcastprefix', + 'ip6-allnodes', + 'ip6-allrouters', + 'ip6-allhosts', + 'broadcasthost', + ]; + + /** + * Ignored virtual/system directory names when scanning for large files. + * + * @var array + */ + private const IGNORED_SCAN_DIRS = [ + 'proc', 'sys', 'dev', 'run', 'snap', 'winsxs', 'system volume information', '$recycle.bin', '.git', 'node_modules', + ]; + + /** + * Scan a target directory recursively and return the largest files sorted by size descending. + * + * @return array + */ + public function findLargeFiles(?string $directory = null, int $limit = 15): array + { + $safeLimit = max(1, $limit); + $targetDir = $directory !== null && trim($directory) !== '' + ? trim($directory) + : (string) (getenv('USERPROFILE') ?: getenv('HOME') ?: (getcwd() ?: base_path())); + + if (! is_dir($targetDir) || ! is_readable($targetDir)) { + return []; + } + + $collected = []; + + try { + $dirIterator = new RecursiveDirectoryIterator( + $targetDir, + FilesystemIterator::SKIP_DOTS | FilesystemIterator::CURRENT_AS_FILEINFO + ); + + $filterIterator = new \RecursiveCallbackFilterIterator( + $dirIterator, + function (SplFileInfo $current): bool { + if ($current->isLink()) { + return false; + } + if ($current->isDir()) { + $lowerName = strtolower($current->getFilename()); + + return ! in_array($lowerName, self::IGNORED_SCAN_DIRS, true); + } + + return true; + } + ); + + $iterator = new RecursiveIteratorIterator( + $filterIterator, + RecursiveIteratorIterator::LEAVES_ONLY, + RecursiveIteratorIterator::CATCH_GET_CHILD + ); + + /** @var SplFileInfo $file */ + foreach ($iterator as $file) { + if (! $file->isFile() || $file->isLink()) { + continue; + } + + $size = @$file->getSize(); + if ($size === false || $size <= 0) { + continue; + } + + $mtime = @$file->getMTime(); + $collected[] = [ + 'path' => $file->getPathname(), + 'size_bytes' => (float) $size, + 'size_formatted' => $this->formatBytes((float) $size), + 'modified_at' => $mtime !== false ? date('Y-m-d H:i', $mtime) : '-', + ]; + } + } catch (Throwable) { + // Ignore unreadable permission boundaries + } + + usort( + $collected, + fn (array $a, array $b): int => $b['size_bytes'] <=> $a['size_bytes'] + ); + + return array_slice($collected, 0, $safeLimit); + } + + /** + * Safely clean browser cache directories (Chrome, Edge, Firefox) without touching passwords, cookies, or history. + * + * @param array|null $customCachePaths + */ + public function cleanBrowserCaches(?array $customCachePaths = null): ActionResult + { + $targets = $customCachePaths ?? $this->getDefaultBrowserCachePaths(); + + $deletedFiles = 0; + $skippedFiles = 0; + $freedBytes = 0.0; + $cleanedBrowsers = []; + + foreach ($targets as $browserLabel => $cacheDir) { + if ($cacheDir === '' || ! is_dir($cacheDir) || ! is_readable($cacheDir)) { + continue; + } + + $browserFreed = 0.0; + try { + $iterator = new FilesystemIterator($cacheDir, FilesystemIterator::SKIP_DOTS); + /** @var SplFileInfo $entry */ + foreach ($iterator as $entry) { + $path = $entry->getPathname(); + $entrySize = $this->calculateCacheEntrySize($path); + + if ($this->deleteCacheEntrySafely($path)) { + $deletedFiles++; + $freedBytes += $entrySize; + $browserFreed += $entrySize; + } else { + $skippedFiles++; + } + } + } catch (Throwable) { + $skippedFiles++; + } + + if ($browserFreed > 0.0 || ! in_array($browserLabel, $cleanedBrowsers, true)) { + $cleanedBrowsers[] = (string) $browserLabel; + } + } + + return new ActionResult( + success: true, + message: 'messages.maintenance.browsers_clean_success', + details: [ + 'browsers_cleaned' => $cleanedBrowsers !== [] ? $cleanedBrowsers : ['None Detected'], + 'deleted_files' => $deletedFiles, + 'skipped_locked_files' => $skippedFiles, + 'freed_space' => $this->formatBytes($freedBytes), + 'driver' => $this->getDriverLabel(), + ], + ); + } + + /** + * Inspect the system hosts file and highlight custom or suspicious domain redirections. + * + * @return array + */ + public function inspectHostsFile(?string $customContent = null): array + { + $raw = $customContent ?? $this->readHostsFileContent(); + if ($raw === null || trim($raw) === '') { + return []; + } + + $entries = []; + $lines = preg_split('/\r\n|\r|\n/', $raw) ?: []; + $localHostname = strtolower((string) (gethostname() ?: '')); + + foreach ($lines as $line) { + // Strip inline comments + if (str_contains($line, '#')) { + $line = explode('#', $line, 2)[0]; + } + + $line = trim($line); + if ($line === '') { + continue; + } + + $parts = preg_split('/\s+/', $line); + if (! is_array($parts) || count($parts) < 2) { + continue; + } + + $ip = array_shift($parts); + $isLoopbackIp = in_array($ip, ['127.0.0.1', '127.0.1.1', '::1', '0.0.0.0', 'fe00::0', 'ff00::0', 'ff02::1', 'ff02::2', 'ff02::3'], true); + + foreach ($parts as $host) { + $lowerHost = strtolower(trim($host)); + if ($lowerHost === '') { + continue; + } + + $isStandardHost = in_array($lowerHost, self::STANDARD_LOCAL_HOSTS, true) + || ($localHostname !== '' && $lowerHost === $localHostname); + + if ($isLoopbackIp && $isStandardHost) { + $status = 'STANDARD'; + $icon = '✅'; + } elseif ($isLoopbackIp) { + $status = 'CUSTOM_LOCAL'; + $icon = '⚠️'; + } else { + $status = 'EXTERNAL_REDIRECT'; + $icon = '❌'; + } + + $entries[] = [ + 'ip' => $ip, + 'host' => $host, + 'status' => $status, + 'icon' => $icon, + ]; + } + } + + return $entries; + } + + /** + * Calculate byte size of a cache file or directory tree safely. + */ + protected function calculateCacheEntrySize(string $path): float + { + if (is_link($path)) { + return 0.0; + } + + if (is_file($path)) { + $size = @filesize($path); + + return $size !== false ? (float) $size : 0.0; + } + + if (! is_dir($path) || ! is_readable($path)) { + return 0.0; + } + + $total = 0.0; + try { + $iterator = new FilesystemIterator($path, FilesystemIterator::SKIP_DOTS); + /** @var SplFileInfo $item */ + foreach ($iterator as $item) { + $total += $this->calculateCacheEntrySize($item->getPathname()); + } + } catch (Throwable) { + // Ignore unreadable subtrees + } + + return $total; + } + + /** + * Delete a cache file or subdirectory safely. + */ + protected function deleteCacheEntrySafely(string $path): bool + { + if (is_link($path) || is_file($path)) { + return @unlink($path); + } + + if (! is_dir($path)) { + return false; + } + + try { + $iterator = new FilesystemIterator($path, FilesystemIterator::SKIP_DOTS); + /** @var SplFileInfo $item */ + foreach ($iterator as $item) { + $this->deleteCacheEntrySafely($item->getPathname()); + } + } catch (Throwable) { + return false; + } + + return @rmdir($path); + } + + /** + * Return default browser cache directories for the active OS driver. + * + * @return array + */ + abstract protected function getDefaultBrowserCachePaths(): array; + + /** + * Read the raw content of the system hosts file. + */ + abstract protected function readHostsFileContent(): ?string; + + /** + * Return the driver identifier ('Windows' or 'Linux'). + */ + abstract protected function getDriverLabel(): string; +} diff --git a/app/Drivers/LinuxDriver.php b/app/Drivers/LinuxDriver.php index 759dc0a..d700962 100644 --- a/app/Drivers/LinuxDriver.php +++ b/app/Drivers/LinuxDriver.php @@ -6,6 +6,7 @@ use App\Contracts\ProcessExecutorInterface; use App\Contracts\SystemDriverInterface; +use App\Drivers\Concerns\InteractsWithMaintenanceAndSecurity; use App\Drivers\Concerns\InteractsWithNetworkSockets; use App\DTOs\ActionResult; use App\Services\SymfonyProcessExecutor; @@ -16,6 +17,7 @@ class LinuxDriver implements SystemDriverInterface { + use InteractsWithMaintenanceAndSecurity; use InteractsWithNetworkSockets; /** * Real block/disk filesystem types to include in storage health checks. @@ -1272,6 +1274,445 @@ public function cleanTempFiles(): ActionResult ); } + /** + * {@inheritDoc} + */ + public function repairOsIntegrity(): ActionResult + { + $executed = []; + $outputs = []; + + if ($this->commandExists('dpkg')) { + $res = $this->processRunner->run(['dpkg', '--audit']); + $executed[] = 'dpkg --audit'; + $outputs[] = $res->output !== '' ? $res->output : 'dpkg: no broken packages found'; + } + + if ($this->commandExists('apt-get') && $this->isRoot()) { + $res = $this->processRunner->run(['apt-get', 'check']); + $executed[] = 'apt-get check'; + if ($res->output !== '') { + $outputs[] = $res->output; + } + } + + if ($executed === [] && $this->commandExists('rpm')) { + $res = $this->processRunner->run(['rpm', '-Va', '--nofiles', '--nodigest']); + $executed[] = 'rpm -Va --nofiles --nodigest'; + $outputs[] = $res->output !== '' ? $res->output : 'rpm: package database verified'; + } + + if ($executed === [] && $this->commandExists('pacman')) { + $res = $this->processRunner->run(['pacman', '-Qk']); + $executed[] = 'pacman -Qk'; + $outputs[] = $res->output !== '' ? $res->output : 'pacman: all packages intact'; + } + + if ($executed === []) { + return new ActionResult( + success: false, + message: 'messages.maintenance.repair_failed', + details: ['driver' => 'Linux'], + ); + } + + $summaryOutput = $this->truncateLogMessage(implode(' | ', $outputs), 110); + + return new ActionResult( + success: true, + message: 'messages.maintenance.repair_success', + details: [ + 'commands_executed' => $executed, + 'output' => $summaryOutput, + 'driver' => 'Linux', + ], + ); + } + + /** + * {@inheritDoc} + */ + public function getPendingUpdates(): array + { + $updates = []; + + if ($this->commandExists('apt')) { + $res = $this->processRunner->run(['apt', 'list', '--upgradable']); + if ($res->successful && $res->output !== '') { + $lines = preg_split('/\r\n|\r|\n/', trim($res->output)) ?: []; + foreach ($lines as $line) { + $line = trim($line); + if ($line === '' || str_starts_with(strtolower($line), 'listing')) { + continue; + } + // Format: "curl/noble-updates 8.5.0-2ubuntu10.4 amd64 [upgradable from: 8.5.0-2ubuntu10.1]" + if (preg_match('/^([^\/\s]+)\/(\S+)\s+(\S+)\s+\S+/', $line, $m) === 1) { + $updates[] = [ + 'package' => $m[1], + 'version' => $m[3], + 'source' => 'APT (' . $m[2] . ')', + 'status' => 'Upgradable', + ]; + } + } + + return array_slice($updates, 0, 30); + } + } + + if ($this->commandExists('dnf')) { + $res = $this->processRunner->run(['dnf', 'check-update', '--quiet']); + if ($res->output !== '') { + $lines = preg_split('/\r\n|\r|\n/', trim($res->output)) ?: []; + foreach ($lines as $line) { + $parts = preg_split('/\s+/', trim($line)); + if (is_array($parts) && count($parts) >= 3) { + $updates[] = [ + 'package' => $parts[0], + 'version' => $parts[1], + 'source' => 'DNF (' . $parts[2] . ')', + 'status' => 'Upgradable', + ]; + } + } + + return array_slice($updates, 0, 30); + } + } + + if ($this->commandExists('pacman')) { + $res = $this->processRunner->run(['pacman', '-Qu']); + if ($res->successful && $res->output !== '') { + $lines = preg_split('/\r\n|\r|\n/', trim($res->output)) ?: []; + foreach ($lines as $line) { + if (preg_match('/^(\S+)\s+(\S+)\s+->\s+(\S+)/', trim($line), $m) === 1) { + $updates[] = [ + 'package' => $m[1], + 'version' => $m[3], + 'source' => 'Pacman', + 'status' => 'Upgradable (from ' . $m[2] . ')', + ]; + } + } + } + } + + return array_slice($updates, 0, 30); + } + + /** + * {@inheritDoc} + */ + public function getScheduledTasks(): array + { + $tasks = []; + + $crontabRaw = $this->readFile('/etc/crontab') ?? ''; + if ($crontabRaw !== '') { + $lines = preg_split('/\r\n|\r|\n/', $crontabRaw) ?: []; + foreach ($lines as $line) { + $line = trim($line); + if ($line === '' || str_starts_with($line, '#') || preg_match('/^[A-Z_]+=/', $line) === 1) { + continue; + } + + $parts = preg_split('/\s+/', $line, 7); + if (is_array($parts) && count($parts) === 7) { + $scheduleExpr = implode(' ', array_slice($parts, 0, 5)); + $user = $parts[5]; + $command = $this->truncateLogMessage($parts[6], 55); + + $tasks[] = [ + 'name' => $command, + 'schedule' => 'cron (' . $scheduleExpr . ')', + 'next_run' => 'User: ' . $user, + 'status' => 'Active', + ]; + } + } + } + + $timersResult = $this->processRunner->run(['systemctl', 'list-timers', '--no-pager', '--no-legend']); + if ($timersResult->successful && $timersResult->output !== '') { + $lines = preg_split('/\r\n|\r|\n/', trim($timersResult->output)) ?: []; + foreach (array_slice($lines, 0, 20) as $line) { + $line = trim($line); + if ($line === '') { + continue; + } + if (preg_match('/^(.+?)\s+([A-Za-z0-9_.-]+\.timer)\s+([A-Za-z0-9_.-]+\.service)$/i', $line, $m) === 1) { + $tasks[] = [ + 'name' => $m[2], + 'schedule' => 'systemd timer -> ' . $m[3], + 'next_run' => $this->truncateLogMessage(trim($m[1]), 35), + 'status' => 'Active', + ]; + } + } + } + + return $tasks; + } + + /** + * {@inheritDoc} + */ + public function runSecurityAudit(): array + { + $audit = []; + + // 1. Firewall check (UFW / firewalld / nftables) + $fwActive = false; + $fwDetails = 'No active firewall service detected (ufw / firewalld / nftables)'; + + if ($this->commandExists('ufw')) { + $ufwRes = $this->processRunner->run(['ufw', 'status']); + if ($ufwRes->successful && str_contains(strtolower($ufwRes->output), 'status: active')) { + $fwActive = true; + $fwDetails = 'UFW Firewall is active'; + } + } + + if (! $fwActive) { + foreach (['firewalld', 'nftables'] as $fwDaemon) { + $res = $this->processRunner->run(['systemctl', 'is-active', $fwDaemon]); + if ($res->successful && trim($res->output) === 'active') { + $fwActive = true; + $fwDetails = $fwDaemon . ' daemon is active'; + break; + } + } + } + + $audit[] = [ + 'component' => 'Linux Host Firewall', + 'status' => $fwActive ? 'ENABLED' : 'WARNING', + 'icon' => $fwActive ? '✅' : '⚠️', + 'details' => $fwDetails, + ]; + + // 2. MAC / Antivirus check (AppArmor / SELinux / ClamAV) + $macActive = false; + $macDetails = []; + + $appArmorParam = trim((string) ($this->readFile('/sys/module/apparmor/parameters/enabled') ?? '')); + if (strtoupper($appArmorParam) === 'Y') { + $macActive = true; + $macDetails[] = 'AppArmor: Enabled'; + } + + if ($this->commandExists('getenforce')) { + $seRes = $this->processRunner->run(['getenforce']); + $seMode = trim($seRes->output); + if (in_array(strtolower($seMode), ['enforcing', 'permissive'], true)) { + $macActive = true; + $macDetails[] = 'SELinux: ' . $seMode; + } + } + + $audit[] = [ + 'component' => 'Mandatory Access Control (AppArmor / SELinux)', + 'status' => $macActive ? 'PROTECTED' : 'WARNING', + 'icon' => $macActive ? '✅' : '⚠️', + 'details' => $macDetails !== [] ? implode(' | ', $macDetails) : 'Neither AppArmor nor SELinux reported active', + ]; + + // 3. SSH Root Login & Sudo Policy + $sshdConfig = $this->readFile('/etc/ssh/sshd_config') ?? ''; + $rootLoginPermitted = preg_match('/^\s*PermitRootLogin\s+yes\b/im', $sshdConfig) === 1; + + $audit[] = [ + 'component' => 'SSH & Root Privilege Policy', + 'status' => $rootLoginPermitted ? 'WARNING' : 'HARDENED', + 'icon' => $rootLoginPermitted ? '⚠️' : '✅', + 'details' => $rootLoginPermitted + ? 'PermitRootLogin is set to "yes" in /etc/ssh/sshd_config' + : 'Direct SSH PermitRootLogin is restricted or disabled', + ]; + + return $audit; + } + + /** + * {@inheritDoc} + */ + public function getLocalUsersAudit(): array + { + $passwdRaw = $this->readFile('/etc/passwd') ?? ''; + $groupRaw = $this->readFile('/etc/group') ?? ''; + + if ($passwdRaw === '') { + return []; + } + + $adminUsers = ['root' => true]; + foreach (preg_split('/\r\n|\r|\n/', $groupRaw) ?: [] as $gLine) { + $gParts = explode(':', trim($gLine)); + if (count($gParts) >= 4 && in_array($gParts[0], ['sudo', 'wheel', 'admin', 'root'], true)) { + foreach (explode(',', $gParts[3]) as $member) { + $member = trim($member); + if ($member !== '') { + $adminUsers[$member] = true; + } + } + } + } + + $users = []; + foreach (preg_split('/\r\n|\r|\n/', $passwdRaw) ?: [] as $pLine) { + $pLine = trim($pLine); + if ($pLine === '' || str_starts_with($pLine, '#')) { + continue; + } + + $parts = explode(':', $pLine); + if (count($parts) < 7) { + continue; + } + + $username = $parts[0]; + $uid = (int) $parts[2]; + $shell = $parts[6]; + + $isLoginShell = ! str_ends_with($shell, 'nologin') && ! str_ends_with($shell, '/false') && ! str_ends_with($shell, '/sync'); + if ($uid !== 0 && $uid < 1000 && ! $isLoginShell) { + continue; + } + + $isAdmin = $uid === 0 || isset($adminUsers[$username]); + + $users[] = [ + 'username' => sprintf('%s (UID %d)', $username, $uid), + 'status' => $isLoginShell ? '✅ Active (' . basename($shell) . ')' : '⚪ System/Locked', + 'is_admin' => $isAdmin ? '⚠️ YES (sudo/root)' : 'No', + 'last_logon' => $shell, + ]; + } + + return $users; + } + + /** + * {@inheritDoc} + */ + public function getNetworkShares(): array + { + $shares = []; + + $smbConf = $this->readFile('/etc/samba/smb.conf') ?? ''; + if ($smbConf !== '') { + $currentSection = null; + $currentPath = '-'; + $currentComment = '-'; + + $lines = preg_split('/\r\n|\r|\n/', $smbConf) ?: []; + foreach ($lines as $line) { + $line = trim($line); + if ($line === '' || str_starts_with($line, '#') || str_starts_with($line, ';')) { + continue; + } + + if (preg_match('/^\[([^\]]+)\]$/', $line, $secMatch) === 1) { + if ($currentSection !== null && strtolower($currentSection) !== 'global') { + $shares[] = [ + 'name' => $currentSection, + 'path' => $currentPath, + 'type' => 'Samba (SMB)', + 'description' => $currentComment, + ]; + } + $currentSection = trim($secMatch[1]); + $currentPath = '-'; + $currentComment = '-'; + + continue; + } + + if ($currentSection !== null && str_contains($line, '=')) { + [$k, $v] = array_map('trim', explode('=', $line, 2)); + if (strtolower($k) === 'path') { + $currentPath = $v; + } elseif (strtolower($k) === 'comment') { + $currentComment = $v; + } + } + } + + if ($currentSection !== null && strtolower($currentSection) !== 'global') { + $shares[] = [ + 'name' => $currentSection, + 'path' => $currentPath, + 'type' => 'Samba (SMB)', + 'description' => $currentComment, + ]; + } + } + + $exportsRaw = $this->readFile('/etc/exports') ?? ''; + if ($exportsRaw !== '') { + $lines = preg_split('/\r\n|\r|\n/', $exportsRaw) ?: []; + foreach ($lines as $line) { + $line = trim($line); + if ($line === '' || str_starts_with($line, '#')) { + continue; + } + + $parts = preg_split('/\s+/', $line, 2); + if (is_array($parts) && count($parts) === 2) { + $shares[] = [ + 'name' => basename($parts[0]) ?: $parts[0], + 'path' => $parts[0], + 'type' => 'NFS Export', + 'description' => $this->truncateLogMessage($parts[1], 55), + ]; + } + } + } + + return $shares; + } + + /** + * {@inheritDoc} + */ + protected function getDefaultBrowserCachePaths(): array + { + $home = (string) (getenv('HOME') ?: '/root'); + $cacheRoot = $home . '/.cache'; + + $paths = [ + 'Google Chrome (Cache)' => $cacheRoot . '/google-chrome/Default/Cache', + 'Google Chrome (Code Cache)' => $cacheRoot . '/google-chrome/Default/Code Cache', + 'Microsoft Edge (Cache)' => $cacheRoot . '/microsoft-edge/Default/Cache', + 'Microsoft Edge (Code Cache)' => $cacheRoot . '/microsoft-edge/Default/Code Cache', + ]; + + $firefoxCache = $cacheRoot . '/mozilla/firefox'; + if (is_dir($firefoxCache) && is_readable($firefoxCache)) { + foreach (glob($firefoxCache . '/*/cache2/entries') ?: [] as $idx => $ffDir) { + $paths['Mozilla Firefox (Profile ' . ($idx + 1) . ')'] = $ffDir; + } + } + + return $paths; + } + + /** + * {@inheritDoc} + */ + protected function readHostsFileContent(): ?string + { + return $this->readFile('/etc/hosts'); + } + + /** + * {@inheritDoc} + */ + protected function getDriverLabel(): string + { + return 'Linux'; + } + /** * Read a file from the filesystem or injected ProcessExecutorInterface / test reader. */ diff --git a/app/Drivers/WindowsDriver.php b/app/Drivers/WindowsDriver.php index 15f5791..73d5c6f 100644 --- a/app/Drivers/WindowsDriver.php +++ b/app/Drivers/WindowsDriver.php @@ -6,6 +6,7 @@ use App\Contracts\ProcessExecutorInterface; use App\Contracts\SystemDriverInterface; +use App\Drivers\Concerns\InteractsWithMaintenanceAndSecurity; use App\Drivers\Concerns\InteractsWithNetworkSockets; use App\DTOs\ActionResult; use App\DTOs\ProcessResult; @@ -13,6 +14,7 @@ class WindowsDriver implements SystemDriverInterface { + use InteractsWithMaintenanceAndSecurity; use InteractsWithNetworkSockets; private const UTF8_PREAMBLE = '[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; $OutputEncoding = [System.Text.Encoding]::UTF8; '; @@ -1186,6 +1188,318 @@ public function cleanTempFiles(): ActionResult ); } + /** + * {@inheritDoc} + */ + public function repairOsIntegrity(): ActionResult + { + $adminCheck = $this->processRunner->run(['net', 'session'], 5); + if (! $adminCheck->successful) { + return new ActionResult( + success: false, + message: 'messages.common.permission_denied', + details: ['driver' => 'Windows'], + ); + } + + $sfcResult = $this->processRunner->run(['sfc', '/scannow'], 300); + $dismResult = $this->processRunner->run(['DISM', '/Online', '/Cleanup-Image', '/RestoreHealth'], 300); + + $combinedOutput = $this->normalizeConsoleOutput($sfcResult->output . ' ' . $dismResult->output); + $succeeded = $sfcResult->successful && $dismResult->successful; + + return new ActionResult( + success: $succeeded, + message: $succeeded ? 'messages.maintenance.repair_success' : 'messages.maintenance.repair_failed', + details: [ + 'commands_executed' => [ + 'sfc /scannow', + 'DISM /Online /Cleanup-Image /RestoreHealth', + ], + 'output' => $combinedOutput !== '' ? $this->truncateLogMessage($combinedOutput, 110) : 'Completed', + 'driver' => 'Windows', + ], + ); + } + + /** + * {@inheritDoc} + */ + public function getPendingUpdates(): array + { + $script = <<<'PS' +$ErrorActionPreference = 'SilentlyContinue'; +$results = @(); +try { + $session = New-Object -ComObject Microsoft.Update.Session; + $searcher = $session.CreateUpdateSearcher(); + $searchResult = $searcher.Search("IsInstalled=0 and Type='Software'"); + foreach ($upd in $searchResult.Updates) { + $kb = if ($upd.KBArticleIDs.Count -gt 0) { "KB" + ($upd.KBArticleIDs | Select-Object -First 1) } else { "Update" }; + $results += [PSCustomObject]@{ + Package = [string]$upd.Title; + Version = [string]$kb; + Source = 'Windows Update'; + Status = if ($upd.IsDownloaded) { 'Downloaded (Pending Install)' } else { 'Available' } + }; + } +} catch {} + +if ($results.Count -eq 0) { + $hotfixes = @(Get-HotFix | Sort-Object InstalledOn -Descending | Select-Object -First 5); + foreach ($hf in $hotfixes) { + $installedDate = if ($hf.InstalledOn -is [DateTime]) { $hf.InstalledOn.ToString('yyyy-MM-dd') } else { 'Installed' }; + $results += [PSCustomObject]@{ + Package = [string]($hf.Description + ' (' + $hf.HotFixID + ')'); + Version = [string]$hf.HotFixID; + Source = 'Get-HotFix'; + Status = "Installed ($installedDate)" + }; + } +} +$results | ConvertTo-Json -Compress +PS; + + $items = $this->normalizeJsonList($this->runPowerShellJson($script, 45)); + + $updates = []; + foreach ($items as $item) { + if (! is_array($item) || empty($item['Package'])) { + continue; + } + + $updates[] = [ + 'package' => $this->truncateLogMessage((string) $item['Package'], 65), + 'version' => trim((string) ($item['Version'] ?? '-')), + 'source' => trim((string) ($item['Source'] ?? 'Windows Update')), + 'status' => trim((string) ($item['Status'] ?? 'Available')), + ]; + } + + return $updates; + } + + /** + * {@inheritDoc} + */ + public function getScheduledTasks(): array + { + $script = <<<'PS' +$ErrorActionPreference = 'SilentlyContinue'; +@(Get-ScheduledTask | Where-Object { $_.State -ne 'Disabled' -and $_.TaskPath -notlike '\Microsoft\*' } | Select-Object -First 25 | ForEach-Object { + $info = Get-ScheduledTaskInfo -TaskName $_.TaskName -TaskPath $_.TaskPath -ErrorAction SilentlyContinue; + $nextRun = if ($null -ne $info -and $info.NextRunTime -is [DateTime] -and $info.NextRunTime.Year -gt 2000) { $info.NextRunTime.ToString('yyyy-MM-dd HH:mm') } else { '-' }; + [PSCustomObject]@{ + TaskName = [string]$_.TaskName; + TaskPath = [string]$_.TaskPath; + NextRun = [string]$nextRun; + State = [string]$_.State + } +}) | ConvertTo-Json -Compress +PS; + + $items = $this->normalizeJsonList($this->runPowerShellJson($script)); + + $tasks = []; + foreach ($items as $item) { + if (! is_array($item) || empty($item['TaskName'])) { + continue; + } + + $tasks[] = [ + 'name' => trim((string) $item['TaskName']), + 'schedule' => trim((string) ($item['TaskPath'] ?? '\\')), + 'next_run' => trim((string) ($item['NextRun'] ?? '-')), + 'status' => trim((string) ($item['State'] ?? 'Ready')), + ]; + } + + return $tasks; + } + + /** + * {@inheritDoc} + */ + public function runSecurityAudit(): array + { + $script = <<<'PS' +$ErrorActionPreference = 'SilentlyContinue'; +$fw = @(Get-NetFirewallProfile -ErrorAction SilentlyContinue | ForEach-Object { + "$($_.Name): " + ($(if ($_.Enabled) { 'ON' } else { 'OFF' })) +}); +$fwAllOn = @(Get-NetFirewallProfile -ErrorAction SilentlyContinue | Where-Object { -not $_.Enabled }).Count -eq 0 -and $fw.Count -gt 0; + +$mp = Get-MpComputerStatus -ErrorAction SilentlyContinue; +$avEnabled = if ($null -ne $mp) { [bool]$mp.AntivirusEnabled } else { $false }; +$rtpEnabled = if ($null -ne $mp) { [bool]$mp.RealTimeProtectionEnabled } else { $false }; + +$uac = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System' -Name 'EnableLUA' -ErrorAction SilentlyContinue).EnableLUA; +$uacEnabled = ($uac -eq 1); + +[PSCustomObject]@{ + FirewallAllOn = [bool]$fwAllOn; + FirewallSummary = [string]($fw -join ', '); + AvEnabled = [bool]$avEnabled; + RtpEnabled = [bool]$rtpEnabled; + UacEnabled = [bool]$uacEnabled +} | ConvertTo-Json -Compress +PS; + + $data = $this->runPowerShellJson($script); + + $fwOn = (bool) ($data['FirewallAllOn'] ?? false); + $avOn = (bool) ($data['AvEnabled'] ?? false) && (bool) ($data['RtpEnabled'] ?? false); + $uacOn = (bool) ($data['UacEnabled'] ?? false); + + return [ + [ + 'component' => 'Windows Defender Firewall', + 'status' => $fwOn ? 'ENABLED' : 'WARNING', + 'icon' => $fwOn ? '✅' : '⚠️', + 'details' => trim((string) ($data['FirewallSummary'] ?? '')) ?: ($fwOn ? 'All profiles active' : 'One or more profiles disabled'), + ], + [ + 'component' => 'Microsoft Defender Antivirus', + 'status' => $avOn ? 'PROTECTED' : 'WARNING', + 'icon' => $avOn ? '✅' : '⚠️', + 'details' => sprintf( + 'AV: %s | Real-Time Protection: %s', + ! empty($data['AvEnabled']) ? 'ON' : 'OFF', + ! empty($data['RtpEnabled']) ? 'ON' : 'OFF' + ), + ], + [ + 'component' => 'User Account Control (UAC)', + 'status' => $uacOn ? 'ENABLED' : 'DISABLED', + 'icon' => $uacOn ? '✅' : '❌', + 'details' => $uacOn ? 'EnableLUA = 1 (Active)' : 'EnableLUA = 0 (Disabled)', + ], + ]; + } + + /** + * {@inheritDoc} + */ + public function getLocalUsersAudit(): array + { + $script = <<<'PS' +$ErrorActionPreference = 'SilentlyContinue'; +$admins = @(Get-LocalGroupMember -SID 'S-1-5-32-544' -ErrorAction SilentlyContinue | ForEach-Object { + ($_.Name -split '\\')[-1].ToLower() +}); +@(Get-LocalUser -ErrorAction SilentlyContinue | ForEach-Object { + $isAdm = $admins -contains $_.Name.ToLower(); + $lastLogon = if ($_.LastLogon -is [DateTime] -and $_.LastLogon.Year -gt 2000) { $_.LastLogon.ToString('yyyy-MM-dd HH:mm') } else { 'Never' }; + [PSCustomObject]@{ + Name = [string]$_.Name; + Enabled = [bool]$_.Enabled; + IsAdmin = [bool]$isAdm; + LastLogon = [string]$lastLogon + } +}) | ConvertTo-Json -Compress +PS; + + $items = $this->normalizeJsonList($this->runPowerShellJson($script)); + + $users = []; + foreach ($items as $item) { + if (! is_array($item) || empty($item['Name'])) { + continue; + } + + $enabled = ! empty($item['Enabled']); + $isAdmin = ! empty($item['IsAdmin']); + + $users[] = [ + 'username' => trim((string) $item['Name']), + 'status' => $enabled ? '✅ Enabled' : '⚪ Disabled', + 'is_admin' => $isAdmin ? '⚠️ YES (Administrator)' : 'No', + 'last_logon' => trim((string) ($item['LastLogon'] ?? '-')), + ]; + } + + return $users; + } + + /** + * {@inheritDoc} + */ + public function getNetworkShares(): array + { + $script = <<<'PS' +$ErrorActionPreference = 'SilentlyContinue'; +@(Get-SmbShare -ErrorAction SilentlyContinue | ForEach-Object { + [PSCustomObject]@{ + Name = [string]$_.Name; + Path = [string]$_.Path; + ShareType = [string]$_.ShareType; + Description = [string]$_.Description + } +}) | ConvertTo-Json -Compress +PS; + + $items = $this->normalizeJsonList($this->runPowerShellJson($script)); + + $shares = []; + foreach ($items as $item) { + if (! is_array($item) || empty($item['Name'])) { + continue; + } + + $shares[] = [ + 'name' => trim((string) $item['Name']), + 'path' => trim((string) ($item['Path'] ?? '-')) ?: '-', + 'type' => 'SMB (' . (trim((string) ($item['ShareType'] ?? 'FileSystemVolume')) ?: 'Disk') . ')', + 'description' => trim((string) ($item['Description'] ?? '-')) ?: '-', + ]; + } + + return $shares; + } + + /** + * {@inheritDoc} + */ + protected function getDefaultBrowserCachePaths(): array + { + $localAppData = (string) (getenv('LOCALAPPDATA') ?: ((getenv('USERPROFILE') ?: 'C:\\Users\\Default') . '\\AppData\\Local')); + + $paths = [ + 'Google Chrome (Cache)' => $localAppData . '\\Google\\Chrome\\User Data\\Default\\Cache\\Cache_Data', + 'Google Chrome (Code Cache)' => $localAppData . '\\Google\\Chrome\\User Data\\Default\\Code Cache', + 'Microsoft Edge (Cache)' => $localAppData . '\\Microsoft\\Edge\\User Data\\Default\\Cache\\Cache_Data', + 'Microsoft Edge (Code Cache)' => $localAppData . '\\Microsoft\\Edge\\User Data\\Default\\Code Cache', + ]; + + $firefoxProfilesDir = $localAppData . '\\Mozilla\\Firefox\\Profiles'; + if (is_dir($firefoxProfilesDir) && is_readable($firefoxProfilesDir)) { + foreach (glob($firefoxProfilesDir . '\\*\\cache2\\entries') ?: [] as $idx => $ffCache) { + $paths['Mozilla Firefox (Profile ' . ($idx + 1) . ')'] = $ffCache; + } + } + + return $paths; + } + + /** + * {@inheritDoc} + */ + protected function readHostsFileContent(): ?string + { + $systemRoot = (string) (getenv('SystemRoot') ?: 'C:\\Windows'); + $hostsPath = $systemRoot . '\\System32\\drivers\\etc\\hosts'; + + return $this->processRunner->readFile($hostsPath); + } + + /** + * {@inheritDoc} + */ + protected function getDriverLabel(): string + { + return 'Windows'; + } + /** * Execute a PowerShell script safely with UTF-8 output encoding. */ diff --git a/lang/en/messages.php b/lang/en/messages.php index 16d8146..1901db8 100644 --- a/lang/en/messages.php +++ b/lang/en/messages.php @@ -35,6 +35,7 @@ 'printers' => '🖨 Printers & Spooler Management', 'network' => '🌐 Network & Connectivity Diagnostics', 'maintenance' => '🧹 System Maintenance & Cleanup', + 'security' => '🛡 Security & Access Auditing', 'reports' => '📄 Export Diagnostic Report', 'self_update' => '⬆️ Check for Updates (self:update)', 'language' => '🌍 Switch Language (EN / PT-BR)', @@ -61,6 +62,15 @@ 'network_scan' => 'Discover Active Devices on Local Network (network:scan)', 'network_public' => 'View External Public IP, Geolocation & ISP (network:public)', 'clean_temp' => 'Clean System & User Temporary Files (clean:temp)', + 'maintenance_browsers' => 'Clean Browser Caches — Chrome, Edge & Firefox (maintenance:browsers)', + 'maintenance_large_files' => 'Find Top 15 Largest Files on Disk (maintenance:large-files)', + 'maintenance_repair' => 'Verify & Repair OS System Integrity — SFC/DISM/Packages (maintenance:repair)', + 'maintenance_updates' => 'Inspect Pending OS Patches & Package Updates (maintenance:updates)', + 'maintenance_scheduler' => 'Inspect Active Scheduled Tasks, Cron & Timers (maintenance:scheduler)', + 'security_audit' => 'Unified Security Posture Audit — Firewall, AV & UAC/SSH (security:audit)', + 'security_users' => 'Audit Local User Accounts & Admin/Sudo Privileges (security:users)', + 'security_shares' => 'Inspect Active Network Shares — SMB, Samba & NFS (security:shares)', + 'security_hosts' => 'Audit System Hosts File & Custom Domain Redirects (security:hosts)', 'report_export' => 'Export Full System Diagnostic Report (report:export)', ], ], @@ -101,6 +111,15 @@ 'network_scan' => 'Scanning local network ARP cache and active neighbors...', 'network_public' => 'Querying external public IP address and ISP geolocation...', 'clean_temp' => 'Scanning and removing temporary files safely...', + 'maintenance_repair' => 'Running OS integrity verification and repair (this may take several minutes)...', + 'maintenance_large_files' => 'Scanning directory tree for the largest files...', + 'maintenance_browsers' => 'Cleaning Chrome, Edge, and Firefox cache directories safely...', + 'maintenance_updates' => 'Querying pending OS patches and package updates...', + 'maintenance_scheduler' => 'Enumerating active scheduled tasks, cron jobs, and systemd timers...', + 'security_audit' => 'Evaluating firewall, antivirus/MAC, and privilege elevation policies...', + 'security_users' => 'Auditing local user accounts and Administrator/sudo memberships...', + 'security_shares' => 'Querying active SMB, Samba, and NFS network shares...', + 'security_hosts' => 'Inspecting system hosts file for custom domain mappings...', 'report_export' => 'Generating full diagnostic report...', 'self_update_check' => 'Checking GitHub Releases for newer versions...', 'self_update_download' => 'Downloading and installing update v:version...', @@ -343,6 +362,36 @@ 'confirm_clean' => 'Are you sure you want to clean temporary directories (%TEMP%, /tmp, caches)? Locked files in use will be skipped.', 'clean_success' => 'Temporary directories cleaned and DNS cache flushed successfully.', 'clean_failed' => 'Failed to complete temporary files cleanup.', + 'repair_section' => 'OS System Files & Package Integrity Verification', + 'confirm_repair' => 'This will run OS integrity checks (SFC & DISM on Windows; dpkg/rpm/pacman audit on Linux). Proceed?', + 'repair_success' => 'OS integrity verification and package audit completed successfully.', + 'repair_failed' => 'OS integrity repair encountered errors or requires elevated privileges.', + 'large_files_section' => 'Top Largest Files Disk Space Analyzer', + 'no_large_files' => 'No readable files found in the target directory.', + 'large_files_headers' => [ + 'size' => 'File Size', + 'modified' => 'Last Modified', + 'path' => 'Full File Path', + ], + 'browsers_section' => 'Web Browser Cache Cleanup (Chrome, Edge, Firefox)', + 'confirm_browsers_clean' => 'This will clean ONLY temporary browser cache files (passwords, history, cookies, and bookmarks are preserved). Proceed?', + 'browsers_clean_success' => 'Browser cache directories cleaned safely.', + 'updates_section' => 'Pending OS & Package Updates', + 'no_pending_updates' => 'System is up to date. No pending updates found.', + 'updates_headers' => [ + 'package' => 'Package / Update Title', + 'version' => 'Version / KB', + 'source' => 'Provider / Repo', + 'status' => 'State', + ], + 'scheduler_section' => 'Active Scheduled Tasks, Cron Jobs & Systemd Timers', + 'no_scheduled_tasks' => 'No active non-system scheduled tasks or timers found.', + 'scheduler_headers' => [ + 'name' => 'Task / Timer Name', + 'schedule' => 'Trigger / Path', + 'next_run' => 'Next Run / Account', + 'status' => 'State', + ], 'details_labels' => [ 'deleted_files' => 'Deleted Items', 'skipped_locked_files' => 'Skipped (In Use / Locked)', @@ -365,7 +414,7 @@ 'state' => 'Connection State', 'ssid' => 'Network SSID', 'bssid' => 'Access Point BSSID', - 'signal' => 'Signal Quality', + 'signal' => 'Signal / Quality', 'channel' => 'Radio Channel', 'band' => 'Frequency / Radio Band', 'rx_rate' => 'Receive Rate (RX)', @@ -383,13 +432,50 @@ 'isp' => 'ISP / Organization (ASN)', 'reverse_hostname' => 'Reverse Hostname', 'process_name' => 'Process Name', - 'signal' => 'Signal / Quality', 'battery_status' => 'Power / Charging State', 'charge_percent' => 'Current Charge (%)', 'design_capacity' => 'Design Capacity', 'full_charge_capacity' => 'Full Charge Capacity', 'battery_health' => 'Battery Health & Wear', 'cycle_count' => 'Charge Cycle Count', + 'browsers_cleaned' => 'Browsers Processed', + ], + ], + + 'security' => [ + 'audit_section' => 'Unified Security Posture Audit (Firewall, Antivirus/MAC & Privilege Policy)', + 'audit_headers' => [ + 'component' => 'Security Component', + 'status' => 'Posture', + 'details' => 'Configuration Details', + ], + 'users_section' => 'Local User Accounts & Administrative Privilege Audit', + 'no_users_found' => 'No local user accounts returned by the system driver.', + 'users_headers' => [ + 'username' => 'Account / UID', + 'status' => 'Account State', + 'is_admin' => 'Admin / Sudoer', + 'last_logon' => 'Last Logon / Shell', + ], + 'shares_section' => 'Active Network Shares (SMB / Samba / NFS)', + 'no_shares_found' => 'No active network shares exposed on this system.', + 'shares_headers' => [ + 'name' => 'Share Name', + 'path' => 'Local Path', + 'type' => 'Protocol', + 'description' => 'Permissions / Comment', + ], + 'hosts_section' => 'System Hosts File Inspector (/etc/hosts)', + 'no_hosts_entries' => 'No active host mappings found in the system hosts file.', + 'hosts_headers' => [ + 'ip' => 'Target IP Address', + 'host' => 'Mapped Domain / Hostname', + 'status' => 'Classification', + ], + 'hosts_states' => [ + 'standard' => 'Standard Loopback', + 'custom_local' => 'Custom Local Override', + 'external_redirect' => 'Alert: Non-Standard External Redirect', ], ], diff --git a/lang/pt_BR/messages.php b/lang/pt_BR/messages.php index 7c6313e..84176b8 100644 --- a/lang/pt_BR/messages.php +++ b/lang/pt_BR/messages.php @@ -35,6 +35,7 @@ 'printers' => '🖨 Impressoras & Spooler', 'network' => '🌐 Rede & Conectividade', 'maintenance' => '🧹 Limpeza & Manutenção', + 'security' => '🛡 Segurança & Auditoria de Acesso', 'reports' => '📄 Exportar Relatório de Atendimento', 'self_update' => '⬆️ Verificar Atualizações (self:update)', 'language' => '🌍 Alterar Idioma (EN / PT-BR)', @@ -61,6 +62,15 @@ 'network_scan' => 'Descobrir Dispositivos Ativos na Rede Local (network:scan)', 'network_public' => 'Consultar IP Público Externo, Geolocalização e Provedor (network:public)', 'clean_temp' => 'Limpar Arquivos Temporários do Sistema e Usuário (clean:temp)', + 'maintenance_browsers' => 'Limpar Cache de Navegadores — Chrome, Edge e Firefox (maintenance:browsers)', + 'maintenance_large_files' => 'Localizar os 15 Maiores Arquivos no Disco (maintenance:large-files)', + 'maintenance_repair' => 'Verificar e Reparar Integridade do SO — SFC/DISM/Pacotes (maintenance:repair)', + 'maintenance_updates' => 'Inspecionar Atualizações Pendentes do SO e Pacotes (maintenance:updates)', + 'maintenance_scheduler' => 'Inspecionar Tarefas Agendadas, Cron e Timers (maintenance:scheduler)', + 'security_audit' => 'Auditoria Unificada de Segurança — Firewall, AV e UAC/SSH (security:audit)', + 'security_users' => 'Auditar Usuários Locais e Privilégios Admin/Sudo (security:users)', + 'security_shares' => 'Inspecionar Compartilhamentos Ativos — SMB, Samba e NFS (security:shares)', + 'security_hosts' => 'Auditar Arquivo Hosts e Redirecionamentos de Domínio (security:hosts)', 'report_export' => 'Exportar Relatório Completo de Diagnóstico (report:export)', ], ], @@ -101,6 +111,15 @@ 'network_scan' => 'Escaneando tabela ARP e dispositivos ativos na rede local...', 'network_public' => 'Consultando endereço IP público externo e provedor (ISP)...', 'clean_temp' => 'Analisando e removendo arquivos temporários com segurança...', + 'maintenance_repair' => 'Executando verificação e reparo de integridade do SO (pode levar alguns minutos)...', + 'maintenance_large_files' => 'Varrendo árvore de diretórios em busca dos maiores arquivos...', + 'maintenance_browsers' => 'Limpando diretórios de cache do Chrome, Edge e Firefox com segurança...', + 'maintenance_updates' => 'Consultando atualizações pendentes do SO e pacotes...', + 'maintenance_scheduler' => 'Enumerando tarefas agendadas ativas, cron jobs e systemd timers...', + 'security_audit' => 'Avaliando políticas de firewall, antivírus/MAC e elevação de privilégios...', + 'security_users' => 'Auditando contas de usuários locais e grupos Administradores/sudo...', + 'security_shares' => 'Consultando compartilhamentos de rede SMB, Samba e NFS ativos...', + 'security_hosts' => 'Inspecionando arquivo hosts do sistema por mapeamentos customizados...', 'report_export' => 'Gerando relatório completo de diagnóstico...', 'self_update_check' => 'Consultando GitHub Releases por novas versões...', 'self_update_download' => 'Baixando e instalando atualização v:version...', @@ -343,6 +362,36 @@ 'confirm_clean' => 'Tem certeza de que deseja limpar os diretórios temporários (%TEMP%, /tmp, caches)? Arquivos em uso serão ignorados com segurança.', 'clean_success' => 'Diretórios temporários limpos e cache DNS atualizado com sucesso.', 'clean_failed' => 'Falha ao concluir a limpeza de arquivos temporários.', + 'repair_section' => 'Verificação de Integridade de Arquivos e Pacotes do SO', + 'confirm_repair' => 'Isto executará verificações de integridade do SO (SFC & DISM no Windows; auditoria dpkg/rpm/pacman no Linux). Deseja prosseguir?', + 'repair_success' => 'Verificação de integridade do SO e auditoria de pacotes concluídas com sucesso.', + 'repair_failed' => 'O reparo de integridade encontrou erros ou requer privilégios elevados.', + 'large_files_section' => 'Analisador de Espaço dos Maiores Arquivos em Disco', + 'no_large_files' => 'Nenhum arquivo legível encontrado no diretório informado.', + 'large_files_headers' => [ + 'size' => 'Tamanho', + 'modified' => 'Última Modificação', + 'path' => 'Caminho Completo do Arquivo', + ], + 'browsers_section' => 'Limpeza de Cache de Navegadores Web (Chrome, Edge, Firefox)', + 'confirm_browsers_clean' => 'Isto limpará APENAS arquivos temporários de cache dos navegadores (senhas, histórico, cookies e favoritos serão preservados). Deseja prosseguir?', + 'browsers_clean_success' => 'Diretórios de cache dos navegadores limpos com segurança.', + 'updates_section' => 'Atualizações Pendentes do SO e Pacotes', + 'no_pending_updates' => 'O sistema está atualizado. Nenhuma atualização pendente encontrada.', + 'updates_headers' => [ + 'package' => 'Pacote / Atualização', + 'version' => 'Versão / KB', + 'source' => 'Origem / Repositório', + 'status' => 'Estado', + ], + 'scheduler_section' => 'Tarefas Agendadas Ativas, Cron Jobs & Systemd Timers', + 'no_scheduled_tasks' => 'Nenhuma tarefa agendada não-sistema ou timer ativo encontrado.', + 'scheduler_headers' => [ + 'name' => 'Nome da Tarefa / Timer', + 'schedule' => 'Gatilho / Caminho', + 'next_run' => 'Próxima Execução / Conta', + 'status' => 'Estado', + ], 'details_labels' => [ 'deleted_files' => 'Itens Removidos', 'skipped_locked_files' => 'Ignorados (Em Uso / Bloqueados)', @@ -365,7 +414,7 @@ 'state' => 'Estado da Conexão', 'ssid' => 'SSID da Rede', 'bssid' => 'BSSID do Ponto de Acesso', - 'signal' => 'Qualidade do Sinal', + 'signal' => 'Sinal / Qualidade', 'channel' => 'Canal de Rádio', 'band' => 'Frequência / Banda', 'rx_rate' => 'Taxa de Recepção (RX)', @@ -383,13 +432,50 @@ 'isp' => 'Provedor / Organização (ASN)', 'reverse_hostname' => 'Hostname Reverso', 'process_name' => 'Nome do Processo', - 'signal' => 'Sinal / Qualidade', 'battery_status' => 'Estado de Energia / Carga', 'charge_percent' => 'Carga Atual (%)', 'design_capacity' => 'Capacidade Projetada', 'full_charge_capacity' => 'Capacidade Total Atual', 'battery_health' => 'Saúde e Desgaste da Bateria', 'cycle_count' => 'Contagem de Ciclos', + 'browsers_cleaned' => 'Navegadores Processados', + ], + ], + + 'security' => [ + 'audit_section' => 'Auditoria Unificada de Segurança (Firewall, Antivírus/MAC & Política de Privilégios)', + 'audit_headers' => [ + 'component' => 'Componente de Segurança', + 'status' => 'Postura', + 'details' => 'Detalhes da Configuração', + ], + 'users_section' => 'Auditoria de Contas de Usuários Locais & Privilégios Administrativos', + 'no_users_found' => 'Nenhuma conta de usuário local retornada pelo driver do sistema.', + 'users_headers' => [ + 'username' => 'Conta / UID', + 'status' => 'Estado da Conta', + 'is_admin' => 'Admin / Sudoer', + 'last_logon' => 'Último Logon / Shell', + ], + 'shares_section' => 'Compartilhamentos de Rede Ativos (SMB / Samba / NFS)', + 'no_shares_found' => 'Nenhum compartilhamento de rede ativo exposto neste sistema.', + 'shares_headers' => [ + 'name' => 'Nome do Compartilhamento', + 'path' => 'Caminho Local', + 'type' => 'Protocolo', + 'description' => 'Permissões / Comentário', + ], + 'hosts_section' => 'Inspetor do Arquivo Hosts do Sistema (/etc/hosts)', + 'no_hosts_entries' => 'Nenhum mapeamento de host ativo encontrado no arquivo hosts.', + 'hosts_headers' => [ + 'ip' => 'Endereço IP Alvo', + 'host' => 'Domínio / Hostname Mapeado', + 'status' => 'Classificação', + ], + 'hosts_states' => [ + 'standard' => 'Loopback Padrão', + 'custom_local' => 'Redirecionamento Local Customizado', + 'external_redirect' => 'Alerta: Redirecionamento Externo Não-Padrão', ], ], diff --git a/tests/Feature/ReportExporterTest.php b/tests/Feature/ReportExporterTest.php index ad51d93..18805bd 100644 --- a/tests/Feature/ReportExporterTest.php +++ b/tests/Feature/ReportExporterTest.php @@ -186,6 +186,51 @@ public function cleanTempFiles(): ActionResult { return new ActionResult(true, 'messages.maintenance.clean_success'); } + + public function repairOsIntegrity(): ActionResult + { + return new ActionResult(true, 'messages.maintenance.repair_success'); + } + + public function findLargeFiles(?string $directory = null, int $limit = 15): array + { + return []; + } + + public function cleanBrowserCaches(?array $customCachePaths = null): ActionResult + { + return new ActionResult(true, 'messages.maintenance.browsers_clean_success'); + } + + public function getPendingUpdates(): array + { + return []; + } + + public function getScheduledTasks(): array + { + return []; + } + + public function runSecurityAudit(): array + { + return []; + } + + public function getLocalUsersAudit(): array + { + return []; + } + + public function getNetworkShares(): array + { + return []; + } + + public function inspectHostsFile(?string $customContent = null): array + { + return []; + } }; $tempDir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'it_toolbox_test_' . uniqid(); diff --git a/tests/Unit/HealthCheckServiceTest.php b/tests/Unit/HealthCheckServiceTest.php index b03e74c..45012dd 100644 --- a/tests/Unit/HealthCheckServiceTest.php +++ b/tests/Unit/HealthCheckServiceTest.php @@ -178,6 +178,51 @@ public function cleanTempFiles(): ActionResult { return new ActionResult(true, 'ok'); } + + public function repairOsIntegrity(): ActionResult + { + return new ActionResult(true, 'ok'); + } + + public function findLargeFiles(?string $directory = null, int $limit = 15): array + { + return []; + } + + public function cleanBrowserCaches(?array $customCachePaths = null): ActionResult + { + return new ActionResult(true, 'ok'); + } + + public function getPendingUpdates(): array + { + return []; + } + + public function getScheduledTasks(): array + { + return []; + } + + public function runSecurityAudit(): array + { + return []; + } + + public function getLocalUsersAudit(): array + { + return []; + } + + public function getNetworkShares(): array + { + return []; + } + + public function inspectHostsFile(?string $customContent = null): array + { + return []; + } }; } diff --git a/tests/Unit/LinuxDriverTest.php b/tests/Unit/LinuxDriverTest.php index f34d8d2..a492779 100644 --- a/tests/Unit/LinuxDriverTest.php +++ b/tests/Unit/LinuxDriverTest.php @@ -296,3 +296,86 @@ public function getEffectiveUid(): int expect($killByName->success)->toBeTrue() ->and($killByName->details['process_name'])->toBe('firefox'); }); + +it('executes Linux package integrity audit, pending APT updates, cron/systemd scheduler, security posture audit, local users, and Samba/NFS shares', function (): void { + $executor = new class implements ProcessExecutorInterface + { + /** @var array */ + public array $files = [ + '/etc/crontab' => "0 3 * * * root /usr/local/bin/backup.sh\n", + '/sys/module/apparmor/parameters/enabled' => "Y\n", + '/etc/ssh/sshd_config' => "PermitRootLogin no\n", + '/etc/passwd' => "root:x:0:0:root:/root:/bin/bash\nadminuser:x:1000:1000:Admin:/home/adminuser:/bin/bash\nwww-data:x:33:33:www-data:/var/www:/usr/sbin/nologin\n", + '/etc/group' => "sudo:x:27:adminuser\n", + '/etc/samba/smb.conf' => "[global]\nworkgroup = WORKGROUP\n[ projects ]\npath = /srv/samba/projects\ncomment = Engineering Files\n", + '/etc/exports' => "/srv/nfs/backups 192.168.1.0/24(rw,sync,no_subtree_check)\n", + ]; + + public function run(array $command, int $timeout = 30): ProcessResult + { + return match ($command) { + ['which', 'dpkg'] => new ProcessResult(0, '/usr/bin/dpkg'), + ['dpkg', '--audit'] => new ProcessResult(0, ''), + ['which', 'apt-get'] => new ProcessResult(0, '/usr/bin/apt-get'), + ['apt-get', 'check'] => new ProcessResult(0, ''), + ['which', 'apt'] => new ProcessResult(0, '/usr/bin/apt'), + ['apt', 'list', '--upgradable'] => new ProcessResult( + 0, + "Listing... Done\nopenssl/noble-security 3.0.13-0ubuntu3.4 amd64 [upgradable from: 3.0.13-0ubuntu3.1]\n" + ), + ['systemctl', 'list-timers', '--no-pager', '--no-legend'] => new ProcessResult( + 0, + "Thu 2026-11-19 06:00:00 UTC 14h left apt-daily.timer apt-daily.service\n" + ), + ['which', 'ufw'] => new ProcessResult(0, '/usr/sbin/ufw'), + ['ufw', 'status'] => new ProcessResult(0, "Status: active\n"), + ['which', 'getenforce'] => new ProcessResult(1, '', '', false), + default => new ProcessResult(1, '', '', false), + }; + } + + public function readFile(string $path): ?string + { + return $this->files[$path] ?? null; + } + + public function getEffectiveUid(): int + { + return 0; + } + }; + + $driver = new LinuxDriver($executor); + + $repair = $driver->repairOsIntegrity(); + expect($repair->success)->toBeTrue() + ->and($repair->details['commands_executed'])->toContain('dpkg --audit', 'apt-get check'); + + $updates = $driver->getPendingUpdates(); + expect($updates)->toHaveCount(1) + ->and($updates[0]['package'])->toBe('openssl') + ->and($updates[0]['version'])->toBe('3.0.13-0ubuntu3.4'); + + $tasks = $driver->getScheduledTasks(); + expect($tasks)->toHaveCount(2) + ->and($tasks[0]['name'])->toBe('/usr/local/bin/backup.sh') + ->and($tasks[1]['name'])->toBe('apt-daily.timer'); + + $security = $driver->runSecurityAudit(); + expect($security)->toHaveCount(3) + ->and($security[0]['status'])->toBe('ENABLED') + ->and($security[1]['status'])->toBe('PROTECTED') + ->and($security[2]['status'])->toBe('HARDENED'); + + $users = $driver->getLocalUsersAudit(); + expect($users)->toHaveCount(2) + ->and($users[0]['username'])->toContain('root') + ->and($users[1]['username'])->toContain('adminuser') + ->and($users[1]['is_admin'])->toContain('YES'); + + $shares = $driver->getNetworkShares(); + expect($shares)->toHaveCount(2) + ->and($shares[0]['name'])->toBe('projects') + ->and($shares[0]['type'])->toBe('Samba (SMB)') + ->and($shares[1]['type'])->toBe('NFS Export'); +}); diff --git a/tests/Unit/WindowsDriverTest.php b/tests/Unit/WindowsDriverTest.php index 2094c0f..cf61795 100644 --- a/tests/Unit/WindowsDriverTest.php +++ b/tests/Unit/WindowsDriverTest.php @@ -398,3 +398,130 @@ public function getEffectiveUid(): int ->and($pathAudit['summary']['broken'])->toBe(1) ->and($pathAudit['summary']['duplicate'])->toBe(1); }); + +it('executes Windows OS repair, pending updates, scheduled tasks, security audit, users audit, SMB shares, large files, browser cache cleanup, and hosts inspection', function (): void { + $executor = new class implements ProcessExecutorInterface + { + public int $callIndex = 0; + + public function run(array $command, int $timeout = 30): ProcessResult + { + $this->callIndex++; + + return match ($this->callIndex) { + 1 => new ProcessResult(0, 'Admin OK'), // net session + 2 => new ProcessResult(0, 'Windows Resource Protection did not find any integrity violations.'), // sfc + 3 => new ProcessResult(0, 'The restore operation completed successfully.'), // DISM + 4 => new ProcessResult(0, (string) json_encode([ + [ + 'Package' => '2026-11 Cumulative Update for Windows 11 (KB5046617)', + 'Version' => 'KB5046617', + 'Source' => 'Windows Update', + 'Status' => 'Available', + ], + ])), + 5 => new ProcessResult(0, (string) json_encode([ + [ + 'TaskName' => 'GoogleUpdateTaskMachineCore', + 'TaskPath' => '\\GoogleSystem\\GoogleUpdater\\', + 'NextRun' => '2026-11-19 08:00', + 'State' => 'Ready', + ], + ])), + 6 => new ProcessResult(0, (string) json_encode([ + 'FirewallAllOn' => true, + 'FirewallSummary' => 'Domain: ON, Private: ON, Public: ON', + 'AvEnabled' => true, + 'RtpEnabled' => true, + 'UacEnabled' => true, + ])), + 7 => new ProcessResult(0, (string) json_encode([ + [ + 'Name' => 'Administrator', + 'Enabled' => true, + 'IsAdmin' => true, + 'LastLogon' => '2026-11-18 09:00', + ], + ])), + 8 => new ProcessResult(0, (string) json_encode([ + [ + 'Name' => 'PublicDocs', + 'Path' => 'C:\\Users\\Public\\Documents', + 'ShareType' => 'FileSystemVolume', + 'Description' => 'Shared Documents', + ], + ])), + default => new ProcessResult(0, '[]'), + }; + } + + public function readFile(string $path): ?string + { + return null; + } + + public function getEffectiveUid(): int + { + return 0; + } + }; + + $driver = new WindowsDriver($executor); + + $repair = $driver->repairOsIntegrity(); + expect($repair->success)->toBeTrue() + ->and($repair->details['commands_executed'])->toContain('sfc /scannow', 'DISM /Online /Cleanup-Image /RestoreHealth'); + + $updates = $driver->getPendingUpdates(); + expect($updates)->toHaveCount(1) + ->and($updates[0]['version'])->toBe('KB5046617'); + + $tasks = $driver->getScheduledTasks(); + expect($tasks)->toHaveCount(1) + ->and($tasks[0]['name'])->toBe('GoogleUpdateTaskMachineCore'); + + $security = $driver->runSecurityAudit(); + expect($security)->toHaveCount(3) + ->and($security[0]['status'])->toBe('ENABLED') + ->and($security[1]['status'])->toBe('PROTECTED') + ->and($security[2]['status'])->toBe('ENABLED'); + + $users = $driver->getLocalUsersAudit(); + expect($users)->toHaveCount(1) + ->and($users[0]['username'])->toBe('Administrator') + ->and($users[0]['is_admin'])->toContain('YES'); + + $shares = $driver->getNetworkShares(); + expect($shares)->toHaveCount(1) + ->and($shares[0]['name'])->toBe('PublicDocs'); + + $hosts = $driver->inspectHostsFile("# Comment line\n127.0.0.1 localhost\n127.0.0.1 myapp.local\n203.0.113.55 login.bank.com\n"); + expect($hosts)->toHaveCount(3) + ->and($hosts[0]['status'])->toBe('STANDARD') + ->and($hosts[1]['status'])->toBe('CUSTOM_LOCAL') + ->and($hosts[2]['status'])->toBe('EXTERNAL_REDIRECT'); + + $tempDir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'it_toolbox_maint_' . uniqid(); + $cacheDir = $tempDir . DIRECTORY_SEPARATOR . 'chrome_cache'; + mkdir($cacheDir, 0777, true); + file_put_contents($tempDir . DIRECTORY_SEPARATOR . 'small.bin', str_repeat('A', 128)); + file_put_contents($tempDir . DIRECTORY_SEPARATOR . 'large.bin', str_repeat('B', 2048)); + file_put_contents($cacheDir . DIRECTORY_SEPARATOR . 'data_1', str_repeat('C', 1024)); + + try { + $largeFiles = $driver->findLargeFiles($tempDir, 5); + expect($largeFiles)->not->toBeEmpty() + ->and(basename($largeFiles[0]['path']))->toBe('large.bin'); + + $browserClean = $driver->cleanBrowserCaches(['Google Chrome' => $cacheDir]); + expect($browserClean->success)->toBeTrue() + ->and($browserClean->details['deleted_files'])->toBe(1) + ->and($browserClean->details['freed_space'])->toBe('1.00 KB'); + } finally { + @unlink($tempDir . DIRECTORY_SEPARATOR . 'small.bin'); + @unlink($tempDir . DIRECTORY_SEPARATOR . 'large.bin'); + @unlink($cacheDir . DIRECTORY_SEPARATOR . 'data_1'); + @rmdir($cacheDir); + @rmdir($tempDir); + } +}); From 7def2fa7af74e79279f83b094588850b2d6bdaf8 Mon Sep 17 00:00:00 2001 From: Dev-lib4n Date: Wed, 18 Nov 2026 16:00:23 -0300 Subject: [PATCH 5/5] feat(v2.0.0): add printer test/default, CPU/disk benchmark, hardware inventory, and complete v2.0.0 docs --- .gitignore | 2 + README.md | 148 ++++++++----- README.pt-BR.md | 154 ++++++++----- app/Commands/Printer/PrintTestPageCommand.php | 94 ++++++++ .../Printer/SetDefaultPrinterCommand.php | 94 ++++++++ app/Commands/System/BenchmarkCommand.php | 48 +++++ app/Commands/System/InventoryCommand.php | 203 ++++++++++++++++++ app/Commands/ToolboxMenuCommand.php | 10 +- app/Contracts/SystemDriverInterface.php | 37 ++++ .../InteractsWithMaintenanceAndSecurity.php | 82 +++++++ app/Drivers/LinuxDriver.php | 172 +++++++++++++++ app/Drivers/WindowsDriver.php | 190 ++++++++++++++++ config/app.php | 2 +- lang/en/messages.php | 54 ++++- lang/pt_BR/messages.php | 54 ++++- tests/Feature/ReportExporterTest.php | 25 +++ tests/Unit/HealthCheckServiceTest.php | 25 +++ tests/Unit/LinuxDriverTest.php | 81 +++++++ tests/Unit/WindowsDriverTest.php | 86 ++++++++ 19 files changed, 1447 insertions(+), 114 deletions(-) create mode 100644 app/Commands/Printer/PrintTestPageCommand.php create mode 100644 app/Commands/Printer/SetDefaultPrinterCommand.php create mode 100644 app/Commands/System/BenchmarkCommand.php create mode 100644 app/Commands/System/InventoryCommand.php diff --git a/.gitignore b/.gitignore index ce38f3b..fd73a93 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,8 @@ composer.lock it-toolbox-report-*.txt it-toolbox-report-*.md it-toolbox-report-*.json +it-toolbox-inventory-*.md +it-toolbox-inventory-*.json .DS_Store Thumbs.db .env diff --git a/README.md b/README.md index 6d3bd39..47b1ab5 100644 --- a/README.md +++ b/README.md @@ -11,58 +11,75 @@ ## Overview -**IT Toolbox CLI (`it-toolbox`)** is a cross-platform, interactive terminal utility (TUI/CLI) built with **PHP 8.3+**, **Laravel Zero**, and **Laravel Prompts**. Designed for **IT Support Technicians, Help Desk Engineers, and System Administrators**, it unifies daily troubleshooting, hardware/OS diagnostics, print spooler recovery, network health checks, and safe temporary file cleanup across both **Windows** and **Linux** (distribution-agnostic) environments from a single portable binary. +**IT Toolbox CLI (`it-toolbox`)** is a cross-platform, interactive terminal utility (TUI/CLI) built with **PHP 8.3+**, **Laravel Zero**, and **Laravel Prompts**. Designed for **IT Support Technicians, Help Desk Engineers, and System Administrators**, it unifies **35+ diagnostic, maintenance, security, printer, network, and asset inventory tools** across both **Windows** and **Linux** (distribution-agnostic) environments from a single zero-dependency standalone binary. --- -## Features +## Features (`v2.0.0`) - **🩺 Full Machine Health Check & Score (`health:check`):** - Calculates an objective **0–100 Health Score** across RAM usage, disk storage, internet/DNS connectivity, print queue state, and critical OS logs, classifying the workstation into **Healthy (`80–100`)**, **Warning (`50–79`)**, or **Critical (`0–49`)** with visual progress bar, checklist (`✅` / `⚠️` / `❌`), and actionable remediation recommendations. -- **🖥 System & Hardware Diagnostics (`system`):** - - Inspect OS metadata, kernel version, architecture, hostname, and system uptime. - - Real-time CPU model, core/thread count, load percentage, and physical RAM usage. - - Storage volume capacity, used/free space, and usage percentages across NTFS/ext4/btrfs/xfs filesystems. - - Top resource-consuming processes viewer with interactive frozen process termination (`PID` kill). - - **Critical OS Logs & Recent Errors (`system:logs`):** Inspect critical and error events recorded in the last 24 hours (`Get-WinEvent` on Windows / `journalctl -p err` & `/var/log/syslog` on Linux). +- **🖥 System, Hardware & Services (`system`):** + - `system:info`: OS metadata, kernel/build, CPU model/load, physical RAM, and disk usage alerts (`> 85%`). + - `system:top` & `system:kill`: Top resource-consuming processes viewer and force-termination by PID, name, or interactive selection. + - `system:logs`: Critical & error OS event logs from the last 24h (`Get-WinEvent` / `journalctl -p err` / `/var/log/syslog`). + - `system:services`: Status and one-click restart for critical support services (`Spooler`, `wuauserv`, `BITS`, `Dnscache`, `AnyDesk`, `TeamViewer`, `cups`, `ssh`, `docker`, `nginx`, `NetworkManager`). + - `system:battery`: Laptop battery charge, design vs full capacity (mWh), wear percentage, and cycle count. + - `system:startup`: Boot & login startup programs (`Win32_StartupCommand` / `systemctl list-unit-files --state=enabled`). + - `system:usb`: Connected USB controllers and peripherals (`Get-PnpDevice` / `lsusb`). + - `system:env`: Environment variable inspector and `PATH` directory auditor (`✅ Valid`, `❌ Missing/Broken`, `⚠️ Duplicate`). - **🖨 Printers & Spooler Management (`printer`):** - - List installed printers, driver details, ports/URIs, default status, and queue states (`PowerShell Get-Printer` on Windows / `CUPS lpstat` on Linux). - - One-step print queue purge and spooler service restart (`net stop/start spooler` & `PRINTERS` cleanup on Windows / `cancel -a` & `systemctl restart cups` on Linux). -- **🌐 Network & Connectivity Diagnostics (`network`):** - - Active network interface inspection (`IPv4`, `IPv6`, `MAC`, link status). - - Automated connectivity health check (Default Gateway ping, external ICMP latency to `8.8.8.8` / `1.1.1.1`, and DNS resolution verification). - - One-click DNS cache flush and DHCP IP lease renewal. - - Active listening `TCP`/`UDP` ports and owning processes scanner (`Get-NetTCPConnection` / `ss -tulnp`). + - `printer:list` & `printer:clear`: List installed printers, drivers, ports/URIs, pending jobs, and restart Print Spooler / CUPS purging stuck queues. + - `printer:test-page` & `printer:default`: Send a diagnostic test page (`Win32_Printer.PrintTestPage` / `lp -d`) and switch the system default printer (`SetDefaultPrinter` / `lpoptions -d`). +- **🌐 Advanced Network & Connectivity (`network`):** + - `network:check`, `network:flush` & `network:ports`: Interfaces (IPv4/IPv6/Gateway/DNS/MAC), cascade connectivity test, DNS flush, and active listening ports (`Get-NetTCPConnection` / `ss -tulnp`). + - `network:probe`: Native TCP port connection probe with millisecond latency measurement (`OPEN` / `CLOSED` / `TIMEOUT`). + - `network:wifi`: Wireless signal strength (`%`), SSID, BSSID, channel, band, and RX/TX link speeds (`netsh wlan` / `nmcli` / `iw`). + - `network:reset`: Full network stack & DHCP reset (`ipconfig /release`, `netsh winsock reset`, `netsh int ip reset`, `ipconfig /renew` / `NetworkManager` & `dhclient`). + - `network:ssl`: Live HTTPS SSL/TLS certificate inspector (CN, Issuer, expiration date, `< 30` days warning, SANs). + - `network:scan`: Local Area Network (LAN) active devices discovery via ARP & neighbor cache. + - `network:public`: External Public IP, City/Region/Country, ISP/ASN, and reverse hostname lookup. - **🧹 System Maintenance & Cleanup (`maintenance`):** - - Safe cleanup of user and system temporary directories (`%TEMP%`, `C:\Windows\Temp`, `/tmp`, `/var/tmp`, `~/.cache/thumbnails`), gracefully skipping locked/in-use files and reporting freed disk space. -- **📄 Diagnostic Reports & Export (`report`):** - - Export complete hardware, OS, printer, and network diagnostic snapshots to structured `.md` and `.json` files for ticketing systems and audit logs. -- **⬆️ Over-the-Air Self-Update (`self:update`):** - - Automatically queries GitHub Releases for newer versions and atomically updates the running standalone binary (`.exe`, Linux ELF, or `.phar`) in-place. -- **🌍 Native Bilingual Interface (`i18n`):** - - Full support for **English (`en`)** and **Brazilian Portuguese (`pt_BR`)**, selectable via `--lang=` flag or dynamically inside the interactive numeric TUI menu. + - `clean:temp`: Safe cleanup of user/system temp directories (`%TEMP%`, `C:\Windows\Temp`, `/tmp`, `/var/tmp`) + DNS flush / `journalctl --vacuum-time=3d`. + - `maintenance:browsers`: Cleans **only** cache directories for Chrome, Edge, and Firefox (preserving passwords, history, cookies, and bookmarks). + - `maintenance:large-files`: Recursive scanner locating the largest disk-consuming files cleanly. + - `maintenance:repair`: OS image & package integrity verification (`sfc /scannow` + `DISM` / `dpkg --audit` / `apt-get check` / `rpm -Va` / `pacman -Qk`). + - `maintenance:updates` & `maintenance:scheduler`: Pending OS/package updates (`Microsoft.Update.Session` / `apt` / `dnf` / `pacman`) and active non-system scheduled tasks, cron jobs & systemd timers. +- **🛡 Security & Access Auditing (`security`):** + - `security:audit`: Unified posture check for Firewall (`Windows Defender Firewall` / `ufw` / `firewalld` / `nftables`), Antivirus/MAC (`Microsoft Defender` / `AppArmor` / `SELinux`), and Elevation Policy (`UAC` / `SSH PermitRootLogin`). + - `security:users`: Local accounts audit highlighting `Administrators` / `sudo` / `wheel` / `root` members. + - `security:shares`: Active SMB, Samba, and NFS network shares inspector. + - `security:hosts`: System `hosts` file parser alerting on custom overrides and external domain redirections. +- **📄 Reports, Asset Inventory & Benchmark (`report` / `toolbox`):** + - `report:export`: Export full diagnostic snapshots to structured `.md` and `.json` files. + - `toolbox:inventory`: Corporate IT asset technical sheet (Hostname, Manufacturer, Model, BIOS Serial Number, RAM modules, Physical SSD/HDD/NVMe drives, MAC addresses) ready for GLPI / CMDB export. + - `toolbox:benchmark`: Zero-dependency CPU single-core (`SHA-256` ops/sec) and 64 MB sequential Disk I/O (`MB/s` write/read) micro-benchmark. +- **⬆️ Over-the-Air Self-Update (`self:update`) & Bilingual Numeric TUI (`en` / `pt_BR`):** + - Fast numeric keyboard navigation (`[1]`–`[9]`, `[0]`) with automatic terminal screen clearing, privilege badge (`Admin / Root` vs `Standard User`), and atomic GitHub Releases self-updating. --- ## Architecture -The project strictly separates presentation (TUI commands), orchestration, and operating-system-specific execution using the **Adapter/Driver Pattern** and **Factory Pattern**. All external OS commands are executed safely through `Symfony\Component\Process\Process` using argument arrays to prevent Command Injection. +The project strictly separates presentation (numeric TUI commands), domain services, and operating-system-specific execution using the **Adapter/Driver Pattern**, **Factory Pattern**, and **Process Executor Abstraction**. All external OS commands execute safely via `Symfony\Component\Process\Process` using argument arrays to prevent Command Injection. ```mermaid flowchart TD User(["IT Technician / SysAdmin"]) --> CLI["CLI Entrypoint (it-toolbox)"] - CLI --> Menu["ToolboxMenuCommand / Subcommands (Laravel Prompts)"] + CLI --> Menu["ToolboxMenuCommand (Numeric TUI + Screen Clear)"] Menu --> I18n["Translator Service (lang/en & lang/pt_BR)"] + Menu --> Services["Services: HealthCheck, ReportExporter, SelfUpdate"] Menu --> Factory["SystemDriverFactory::make(PHP_OS_FAMILY)"] + Services --> Factory Factory -->|Windows| WinDriver["WindowsDriver (SystemDriverInterface)"] Factory -->|Linux| LinDriver["LinuxDriver (SystemDriverInterface)"] - WinDriver --> WinProcess["Symfony Process (Argument Arrays)"] - LinDriver --> LinProcess["Symfony Process / Native Filesystem"] + WinDriver --> Executor["ProcessExecutorInterface / Native Sockets & FS"] + LinDriver --> Executor - WinProcess --> WinAPI["PowerShell CIM / WMI / net / ipconfig / taskkill"] - LinProcess --> LinAPI["/proc / POSIX / CUPS (lpstat/cancel) / ip / ss / resolvectl"] + Executor --> WinAPI["PowerShell CIM/WMI, netsh, Get-WinEvent, SFC/DISM, SMB"] + Executor --> LinAPI["/proc, /sys, POSIX, CUPS, ip/ss/nmcli, journalctl, UFW"] WinAPI --> DTO["ActionResult Readonly DTO"] LinAPI --> DTO @@ -81,7 +98,10 @@ Ideal for field IT technicians and target workstations. Download the self-contai **Windows (x64):** ```powershell -# Download 'it-toolbox-windows-x64.exe' from GitHub Releases and run: +# If Windows SmartScreen blocks the downloaded executable from the internet, unblock it first: +Unblock-File -Path .\it-toolbox-windows-x64.exe + +# Run the interactive TUI: .\it-toolbox-windows-x64.exe # Or launch directly in your preferred language: @@ -89,6 +109,8 @@ Ideal for field IT technicians and target workstations. Download the self-contai .\it-toolbox-windows-x64.exe --lang=pt_BR ``` +> **Windows SmartScreen Note:** Because `it-toolbox-windows-x64.exe` is an unsigned open-source binary downloaded from GitHub, Windows Defender SmartScreen may display a prompt on first launch. You can either run `Unblock-File -Path .\it-toolbox-windows-x64.exe` in PowerShell or click **More info → Run anyway**. + **Linux (x64):** ```bash # Download 'it-toolbox-linux-x64' from GitHub Releases, grant execution permission, and run: @@ -121,20 +143,15 @@ cd it-toolbox-cli composer install ``` -> **Note:** Administrator privileges (Windows) or `sudo` (Linux) are recommended for privileged system operations (spooler restart, system temp cleanup, and DHCP renewal). +> **Note:** Administrator privileges (Windows) or `sudo` (Linux) are recommended for privileged system operations (spooler restart, OS repair, network stack reset, service restarts, and system temp cleanup). ### Interactive TUI Mode -Launch the interactive dashboard. If `--lang` is omitted, an interactive language selector is presented on startup: +Launch the interactive numeric dashboard. If `--lang` is omitted, an interactive language selector is presented on startup: ```bash -# Launch with interactive language selector php it-toolbox - -# Launch directly in English php it-toolbox --lang=en - -# Launch directly in Brazilian Portuguese php it-toolbox --lang=pt_BR ``` @@ -144,19 +161,44 @@ Every module can also be executed directly in headless/CLI scripts or terminal s | Command | Module | Description | Options | | :--- | :--- | :--- | :--- | -| `php it-toolbox menu` | Core TUI | Launch the interactive numeric TUI main menu (default command) | `--lang=en\|pt_BR`, `--once` | -| `php it-toolbox health:check` | Health | Run a full machine health audit with a 0–100 score and recommendations | `--export`, `--lang=en\|pt_BR` | +| `php it-toolbox menu` | Core TUI | Launch the interactive numeric TUI main menu (default) | `--lang=en\|pt_BR`, `--once` | +| `php it-toolbox health:check` | Health | Run full machine health audit with 0–100 score & tips | `--export`, `--lang=en\|pt_BR` | | `php it-toolbox system:info` | System | Display OS, CPU, RAM, and disk health metrics | `--lang=en\|pt_BR` | -| `php it-toolbox system:top` | System | List top processes by resource usage and optionally kill a PID | `--limit=10`, `--lang=en\|pt_BR` | -| `php it-toolbox system:logs` | System | Inspect critical and error OS log events from the last 24 hours | `--limit=15`, `--lang=en\|pt_BR` | -| `php it-toolbox printer:list` | Printers | List installed printers, drivers, ports, and status | `--lang=en\|pt_BR` | -| `php it-toolbox printer:clear` | Printers | Restart print spooler / CUPS and purge stuck print jobs | `--force`, `--lang=en\|pt_BR` | -| `php it-toolbox network:check` | Network | Inspect network interfaces and run ping/DNS health checks | `--lang=en\|pt_BR` | +| `php it-toolbox system:top` | System | List top processes by resource usage and kill a PID | `--limit=10`, `--lang=en\|pt_BR` | +| `php it-toolbox system:logs` | System | Inspect critical/error OS log events (last 24h) | `--limit=15`, `--lang=en\|pt_BR` | +| `php it-toolbox system:services` | System | Inspect critical IT support services & restart one | `--restart=NAME`, `--lang=en\|pt_BR` | +| `php it-toolbox system:battery` | System | Inspect laptop battery health, capacity & wear | `--lang=en\|pt_BR` | +| `php it-toolbox system:startup` | System | List boot & login startup programs / services | `--lang=en\|pt_BR` | +| `php it-toolbox system:usb` | System | List connected USB controllers & peripherals | `--lang=en\|pt_BR` | +| `php it-toolbox system:env` | System | Inspect env variables & audit PATH entries | `--lang=en\|pt_BR` | +| `php it-toolbox system:kill` | System | Force-kill process by PID, name, or top-10 menu | `[target]`, `--force`, `--lang=en\|pt_BR` | +| `php it-toolbox printer:list` | Printers | List installed printers, drivers, ports, and jobs | `--lang=en\|pt_BR` | +| `php it-toolbox printer:clear` | Printers | Restart print spooler / CUPS and purge print queue | `--force`, `--lang=en\|pt_BR` | +| `php it-toolbox printer:test-page` | Printers | Send a diagnostic test page to an installed printer | `[printer]`, `--lang=en\|pt_BR` | +| `php it-toolbox printer:default` | Printers | Set the system default printer | `[printer]`, `--lang=en\|pt_BR` | +| `php it-toolbox network:check` | Network | Inspect network interfaces & run ping/DNS check | `--lang=en\|pt_BR` | | `php it-toolbox network:flush` | Network | Flush DNS resolver cache and renew DHCP lease | `--force`, `--lang=en\|pt_BR` | -| `php it-toolbox network:ports` | Network | List active listening TCP/UDP ports and owning processes | `--lang=en\|pt_BR` | +| `php it-toolbox network:ports` | Network | List active listening TCP/UDP ports & processes | `--lang=en\|pt_BR` | +| `php it-toolbox network:probe` | Network | Test remote TCP port connectivity & latency (ms) | `[host] [port]`, `--timeout=3`, `--lang=...` | +| `php it-toolbox network:wifi` | Network | Inspect Wi-Fi SSID, BSSID, signal %, channel & speed | `--lang=en\|pt_BR` | +| `php it-toolbox network:reset` | Network | Full network stack reset (Winsock/IP/NetworkManager) | `--force`, `--lang=en\|pt_BR` | +| `php it-toolbox network:ssl` | Network | Inspect HTTPS SSL/TLS certificate & days remaining | `[domain]`, `--port=443`, `--lang=en\|pt_BR` | +| `php it-toolbox network:scan` | Network | Discover active LAN devices from ARP / neighbor table | `--lang=en\|pt_BR` | +| `php it-toolbox network:public` | Network | Query external public IP, geolocation, ISP & PTR | `--lang=en\|pt_BR` | | `php it-toolbox clean:temp` | Maintenance | Safely purge temporary files and report freed space | `--force`, `--lang=en\|pt_BR` | -| `php it-toolbox report:export` | Reports | Export full system diagnostic report to `.md` and/or `.json` | `--format=md\|json\|both`, `--output=DIR`, `--lang=en\|pt_BR` | -| `php it-toolbox self:update` | Core CLI | Check GitHub Releases and self-update the running executable | `--check`, `--lang=en\|pt_BR` | +| `php it-toolbox maintenance:browsers` | Maintenance | Clean Chrome, Edge & Firefox cache directories only | `--force`, `--lang=en\|pt_BR` | +| `php it-toolbox maintenance:large-files` | Maintenance | Find the top largest files consuming disk space | `[path]`, `--limit=15`, `--lang=en\|pt_BR` | +| `php it-toolbox maintenance:repair` | Maintenance | Verify/repair OS files & packages (SFC/DISM/dpkg) | `--force`, `--lang=en\|pt_BR` | +| `php it-toolbox maintenance:updates` | Maintenance | Check pending OS patches & package updates | `--lang=en\|pt_BR` | +| `php it-toolbox maintenance:scheduler` | Maintenance | List active scheduled tasks, cron jobs & timers | `--lang=en\|pt_BR` | +| `php it-toolbox security:audit` | Security | Audit Firewall, Antivirus/MAC & UAC/SSH policy | `--lang=en\|pt_BR` | +| `php it-toolbox security:users` | Security | Audit local user accounts & Admin/sudo membership | `--lang=en\|pt_BR` | +| `php it-toolbox security:shares` | Security | List active SMB, Samba, and NFS network shares | `--lang=en\|pt_BR` | +| `php it-toolbox security:hosts` | Security | Audit system hosts file for custom/external redirects | `--lang=en\|pt_BR` | +| `php it-toolbox report:export` | Reports | Export full system diagnostic report (`.md` / `.json`) | `--format=md\|json\|both`, `--output=DIR`, `--lang=...` | +| `php it-toolbox toolbox:inventory` | Asset | Generate GLPI/CMDB hardware & BIOS serial inventory | `--export`, `--lang=en\|pt_BR` | +| `php it-toolbox toolbox:benchmark` | Diagnostic | Run CPU SHA-256 & 64 MB sequential Disk I/O bench | `--lang=en\|pt_BR` | +| `php it-toolbox self:update` | Core CLI | Check GitHub Releases and self-update executable | `--check`, `--lang=en\|pt_BR` | --- @@ -168,15 +210,15 @@ Compile the application into a portable `.phar` (`builds/it-toolbox`) or bundle ```bash # Build portable PHAR only -php it-toolbox app:build it-toolbox --build-version=1.0.0 +php -d phar.readonly=0 it-toolbox app:build it-toolbox --build-version=2.0.0 # Build PHAR + Native Linux & Windows x64 standalone binaries -./scripts/build-standalone.sh 1.0.0 +./scripts/build-standalone.sh 2.0.0 ``` ### Running the Test Suite -The test suite is powered by **Pest PHP** and mocks OS-level processes so all tests run deterministically on both Windows and Linux CI runners: +The test suite is powered by **Pest PHP** and mocks OS-level processes via `ProcessExecutorInterface` so all tests run deterministically on both Windows and Linux CI runners: ```bash # Run all Unit and Feature tests @@ -192,13 +234,13 @@ The test suite is powered by **Pest PHP** and mocks OS-level processes so all te - **Language & Runtime:** PHP 8.3+ (`declare(strict_types=1)`, typed properties, `match` expressions, `readonly` classes) - **Micro-Framework:** [Laravel Zero](https://laravel-zero.com/) -- **Terminal UI (TUI):** [Laravel Prompts](https://laravel.com/docs/prompts) (`select`, `table`, `spin`, `confirm`, `info`, `warning`, `error`) -- **Process Execution:** `Symfony\Component\Process\Process` (strictly array-based arguments for Command Injection prevention) -- **Internationalization:** `Illuminate\Translation` (`lang/en` & `lang/pt_BR`) +- **Terminal UI (TUI):** [Laravel Prompts](https://laravel.com/docs/prompts) + Custom Cross-Platform Numeric TTY Navigation (`InteractsWithTerminal`) +- **Process Execution:** `Symfony\Component\Process\Process` abstracted behind `ProcessExecutorInterface` (strictly array-based arguments for Command Injection prevention) +- **Internationalization:** `Illuminate\Translation` (`lang/en` & `lang/pt_BR` with 100% key parity enforced by CI tests) - **Architectural Patterns:** - **Adapter / Driver Pattern:** `SystemDriverInterface` implemented by `WindowsDriver` and `LinuxDriver`. - **Factory Pattern:** `SystemDriverFactory` dynamically resolves the driver via `PHP_OS_FAMILY`. - - **Data Transfer Objects (DTO):** Immutable `readonly class ActionResult` for standardized operation outcomes. + - **Data Transfer Objects (DTO):** Immutable `readonly class ActionResult` and `ProcessResult`. - **Testing & QA:** Pest PHP, Mockery, Laravel Pint, and GitHub Actions CI across Ubuntu and Windows runners. --- diff --git a/README.pt-BR.md b/README.pt-BR.md index bd51cfc..4f43b86 100644 --- a/README.pt-BR.md +++ b/README.pt-BR.md @@ -11,58 +11,75 @@ ## Visão Geral -O **IT Toolbox CLI (`it-toolbox`)** é um utilitário interativo de terminal (TUI/CLI) multiplataforma desenvolvido em **PHP 8.3+**, **Laravel Zero** e **Laravel Prompts**. Projetado para **Técnicos de Suporte de TI, Analistas de Help Desk e Administradores de Sistemas (SysAdmins)**, ele centraliza tarefas diárias de diagnóstico de hardware e SO, recuperação de filas de impressão (spooler/CUPS), testes de saúde de rede e limpeza segura de arquivos temporários em ambientes **Windows** e **Linux** (agnóstico de distribuição) a partir de um único binário portátil. +O **IT Toolbox CLI (`it-toolbox`)** é um utilitário interativo de terminal (TUI/CLI) multiplataforma desenvolvido em **PHP 8.3+**, **Laravel Zero** e **Laravel Prompts**. Projetado para **Técnicos de Suporte de TI, Analistas de Help Desk e Administradores de Sistemas (SysAdmins)**, ele centraliza **mais de 35 ferramentas de diagnóstico, manutenção, segurança, impressoras, rede e inventário patrimonial** em ambientes **Windows** e **Linux** (agnóstico de distribuição) a partir de um único binário autossuficiente sem dependências. --- -## Funcionalidades +## Funcionalidades (`v2.0.0`) - **🩺 Check-up Geral & Score de Saúde da Máquina (`health:check`):** - Calcula um **Score de Saúde objetivo de 0 a 100 pontos** auditando consumo de RAM, armazenamento em disco, conectividade externa/DNS, fila de impressão e logs críticos do SO, classificando a máquina em **Saudável (`80–100`)**, **Atenção (`50–79`)** ou **Crítico (`0–49`)** com barra visual de integridade, checklist (`✅` / `⚠️` / `❌`) e recomendações práticas de correção. -- **🖥 Diagnóstico de Sistema e Hardware (`system`):** - - Inspeção de metadados do SO, versão do kernel, arquitetura, hostname e tempo de atividade (`uptime`). - - Modelo da CPU, contagem de núcleos/threads, percentual de carga em tempo real e uso de memória RAM física. - - Capacidade de volumes de armazenamento, espaço usado/livre e percentual de ocupação em sistemas de arquivos NTFS/ext4/btrfs/xfs. - - Visualizador dos processos de maior consumo com opção interativa para encerrar tarefas travadas (`kill PID`). - - **Logs Críticos do SO & Erros Recentes (`system:logs`):** Inspeção de eventos críticos e erros registrados nas últimas 24 horas (`Get-WinEvent` no Windows / `journalctl -p err` e `/var/log/syslog` no Linux). +- **🖥 Sistema, Hardware & Serviços (`system`):** + - `system:info`: Metadados do SO, kernel/build, modelo/carga de CPU, RAM física e alerta de discos (`> 85%`). + - `system:top` & `system:kill`: Visualizador dos processos que mais consomem recursos e encerramento forçado por PID, nome ou seleção numérica. + - `system:logs`: Eventos críticos e erros do SO nas últimas 24h (`Get-WinEvent` / `journalctl -p err` / `/var/log/syslog`). + - `system:services`: Status e reinicialização rápida de serviços críticos de suporte (`Spooler`, `wuauserv`, `BITS`, `Dnscache`, `AnyDesk`, `TeamViewer`, `cups`, `ssh`, `docker`, `nginx`, `NetworkManager`). + - `system:battery`: Nível de carga, capacidade projetada vs atual (mWh), desgaste e ciclos da bateria. + - `system:startup`: Programas e serviços configurados na inicialização/boot (`Win32_StartupCommand` / `systemctl list-unit-files --state=enabled`). + - `system:usb`: Controladores e periféricos USB conectados (`Get-PnpDevice` / `lsusb`). + - `system:env`: Auditoria de variáveis de ambiente e validação de diretórios do `PATH` (`✅ Válido`, `❌ Inexistente/Quebrado`, `⚠️ Duplicado`). - **🖨 Gerenciamento de Impressoras e Spooler (`printer`):** - - Listagem de impressoras instaladas, detalhes de drivers, portas/URIs, impressora padrão e status da fila (`PowerShell Get-Printer` no Windows / `CUPS lpstat` no Linux). - - Limpeza automatizada de fila de impressão e reinicialização do serviço de spooler (`net stop/start spooler` e limpeza de `PRINTERS` no Windows / `cancel -a` e `systemctl restart cups` no Linux). -- **🌐 Diagnóstico de Rede e Conectividade (`network`):** - - Inspeção de interfaces de rede ativas (`IPv4`, `IPv6`, `MAC`, estado do link). - - Verificação automatizada de saúde de conectividade (Ping para o Gateway Padrão, latência ICMP externa para `8.8.8.8` / `1.1.1.1` e validação de resolução DNS). - - Limpeza de cache DNS e renovação de concessão DHCP com um comando. - - Scanner de portas `TCP`/`UDP` abertas em escuta e processos proprietários (`Get-NetTCPConnection` / `ss -tulnp`). -- **🧹 Manutenção e Limpeza do Sistema (`maintenance`):** - - Limpeza segura de diretórios temporários de usuário e sistema (`%TEMP%`, `C:\Windows\Temp`, `/tmp`, `/var/tmp`, `~/.cache/thumbnails`), ignorando arquivos em uso/bloqueados com segurança e contabilizando o espaço em disco liberado. -- **📄 Relatórios de Diagnóstico e Exportação (`report`):** - - Exportação de relatórios completos de diagnóstico de hardware, SO, impressoras e rede nos formatos `.md` e `.json` para anexação em chamados técnicos e auditorias. -- **⬆️ Auto-Atualização via GitHub Releases (`self:update`):** - - Consulta automaticamente a API do GitHub Releases em busca de novas versões e atualiza o binário em execução (`.exe`, binário Linux ou `.phar`) de forma atômica. -- **🌍 Interface Bilíngue Nativa (`i18n`):** - - Suporte completo para **Inglês (`en`)** e **Português do Brasil (`pt_BR`)**, selecionável via flag `--lang=` ou dinamicamente dentro do menu interativo numérico TUI. + - `printer:list` & `printer:clear`: Listagem de impressoras, drivers, portas/URIs, jobs pendentes e reinício do Spooler / CUPS com limpeza da fila. + - `printer:test-page` & `printer:default`: Envio de página de teste diagnóstica (`Win32_Printer.PrintTestPage` / `lp -d`) e definição da impressora padrão (`SetDefaultPrinter` / `lpoptions -d`). +- **🌐 Diagnóstico Avançado de Rede & Conectividade (`network`):** + - `network:check`, `network:flush` & `network:ports`: Interfaces (IPv4/IPv6/Gateway/DNS/MAC), teste em cascata, limpeza de DNS e portas em escuta (`Get-NetTCPConnection` / `ss -tulnp`). + - `network:probe`: Teste de porta TCP remota com medição de latência em milissegundos (`OPEN` / `CLOSED` / `TIMEOUT`). + - `network:wifi`: Qualidade do sinal Wi-Fi (`%`), SSID, BSSID, canal, banda e velocidade RX/TX (`netsh wlan` / `nmcli` / `iw`). + - `network:reset`: Reset completo da pilha de rede e DHCP (`ipconfig /release`, `netsh winsock reset`, `netsh int ip reset`, `ipconfig /renew` / `NetworkManager` & `dhclient`). + - `network:ssl`: Inspetor de certificado SSL/TLS HTTPS (CN, Emissor, validade, alerta `< 30` dias e SANs). + - `network:scan`: Descoberta de dispositivos ativos na rede local (LAN) via tabela ARP / vizinhos. + - `network:public`: Consulta de IP público externo, Cidade/Região/País, Provedor (ISP/ASN) e Hostname reverso. +- **🧹 Manutenção Avançada & Limpeza (`maintenance`):** + - `clean:temp`: Limpeza segura de diretórios temporários (`%TEMP%`, `C:\Windows\Temp`, `/tmp`, `/var/tmp`) + flush DNS / `journalctl --vacuum-time=3d`. + - `maintenance:browsers`: Limpa **exclusivamente** arquivos de cache do Chrome, Edge e Firefox (preservando senhas, histórico, cookies e favoritos). + - `maintenance:large-files`: Varredura recursiva para localizar os maiores arquivos ocupando espaço em disco. + - `maintenance:repair`: Verificação e reparo de integridade de arquivos/pacotes do SO (`sfc /scannow` + `DISM` / `dpkg --audit` / `apt-get check` / `rpm -Va` / `pacman -Qk`). + - `maintenance:updates` & `maintenance:scheduler`: Atualizações pendentes (`Microsoft.Update.Session` / `apt` / `dnf` / `pacman`) e tarefas agendadas, cron jobs & systemd timers ativos. +- **🛡 Segurança & Auditoria de Acesso (`security`):** + - `security:audit`: Painel unificado verificando Firewall (`Windows Defender Firewall` / `ufw` / `firewalld` / `nftables`), Antivírus/MAC (`Microsoft Defender` / `AppArmor` / `SELinux`) e Política de Elevação (`UAC` / `SSH PermitRootLogin`). + - `security:users`: Auditoria de usuários locais destacando membros de `Administrators` / `sudo` / `wheel` / `root`. + - `security:shares`: Inspetor de compartilhamentos de rede SMB, Samba e NFS ativos. + - `security:hosts`: Analisador do arquivo `hosts` com alertas para redirecionamentos customizados ou externos. +- **📄 Relatórios, Inventário Patrimonial & Benchmark (`report` / `toolbox`):** + - `report:export`: Exportação de relatórios completos de diagnóstico em `.md` e `.json`. + - `toolbox:inventory`: Ficha técnica patrimonial (Hostname, Fabricante, Modelo, Serial BIOS, módulos de RAM, discos físicos SSD/HDD/NVMe e MACs) pronta para GLPI / CMDB. + - `toolbox:benchmark`: Micro-benchmark rápido sem dependências de CPU single-core (`SHA-256` ops/s) e velocidade sequencial de disco de 64 MB (`MB/s` escrita/leitura). +- **⬆️ Auto-Atualização (`self:update`) & TUI Numérica Bilíngue (`en` / `pt_BR`):** + - Navegação rápida por teclas numéricas (`[1]`–`[9]`, `[0]`) com limpeza automática de tela, indicador de privilégio (`Admin / Root` vs `Usuário Padrão`) e atualização atômica via GitHub Releases. --- ## Arquitetura -O projeto separa estritamente a camada de apresentação (comandos TUI), orquestração e execução específica de cada sistema operacional utilizando **Adapter/Driver Pattern** e **Factory Pattern**. Todos os comandos externos do SO são executados de forma segura via `Symfony\Component\Process\Process` utilizando arrays de argumentos para prevenir *Command Injection*. +O projeto separa estritamente a camada de apresentação (comandos TUI numéricos), serviços de domínio e execução específica de cada sistema operacional utilizando **Adapter/Driver Pattern**, **Factory Pattern** e **Abstração de Execução de Processos**. Todos os comandos externos do SO são executados de forma segura via `Symfony\Component\Process\Process` utilizando arrays de argumentos para prevenir *Command Injection*. ```mermaid flowchart TD User(["Técnico de TI / SysAdmin"]) --> CLI["Entrypoint CLI (it-toolbox)"] - CLI --> Menu["ToolboxMenuCommand / Subcomandos (Laravel Prompts)"] + CLI --> Menu["ToolboxMenuCommand (TUI Numérica + Limpeza de Tela)"] Menu --> I18n["Serviço Translator (lang/en & lang/pt_BR)"] + Menu --> Services["Serviços: HealthCheck, ReportExporter, SelfUpdate"] Menu --> Factory["SystemDriverFactory::make(PHP_OS_FAMILY)"] + Services --> Factory Factory -->|Windows| WinDriver["WindowsDriver (SystemDriverInterface)"] Factory -->|Linux| LinDriver["LinuxDriver (SystemDriverInterface)"] - WinDriver --> WinProcess["Symfony Process (Arrays de Argumentos)"] - LinDriver --> LinProcess["Symfony Process / Filesystem Nativo"] + WinDriver --> Executor["ProcessExecutorInterface / Sockets & FS Nativos"] + LinDriver --> Executor - WinProcess --> WinAPI["PowerShell CIM / WMI / net / ipconfig / taskkill"] - LinProcess --> LinAPI["/proc / POSIX / CUPS (lpstat/cancel) / ip / ss / resolvectl"] + Executor --> WinAPI["PowerShell CIM/WMI, netsh, Get-WinEvent, SFC/DISM, SMB"] + Executor --> LinAPI["/proc, /sys, POSIX, CUPS, ip/ss/nmcli, journalctl, UFW"] WinAPI --> DTO["ActionResult Readonly DTO"] LinAPI --> DTO @@ -81,7 +98,10 @@ Ideal para técnicos de TI em campo e máquinas de clientes. Baixe o executável **Windows (x64):** ```powershell -# Baixe 'it-toolbox-windows-x64.exe' na aba Releases do GitHub e execute: +# Caso o Windows SmartScreen bloqueie o executável baixado da internet, desbloqueie primeiro: +Unblock-File -Path .\it-toolbox-windows-x64.exe + +# Execute a TUI interativa: .\it-toolbox-windows-x64.exe # Ou inicie diretamente no idioma desejado: @@ -89,6 +109,8 @@ Ideal para técnicos de TI em campo e máquinas de clientes. Baixe o executável .\it-toolbox-windows-x64.exe --lang=en ``` +> **Nota sobre o Windows SmartScreen:** Como o `it-toolbox-windows-x64.exe` é um binário open-source sem assinatura digital comercial baixado do GitHub, o Windows Defender SmartScreen pode exibir um aviso na primeira execução. Basta rodar `Unblock-File -Path .\it-toolbox-windows-x64.exe` no PowerShell ou clicar em **Mais informações → Executar assim mesmo**. + **Linux (x64):** ```bash # Baixe 'it-toolbox-linux-x64' na aba Releases, conceda permissão de execução e rode: @@ -121,20 +143,15 @@ cd it-toolbox-cli composer install ``` -> **Nota:** Privilégios de Administrador (Windows) ou `sudo` (Linux) são recomendados para operações privilegiadas do sistema (reinício do spooler, limpeza temporária do sistema e renovação DHCP). +> **Nota:** Privilégios de Administrador (Windows) ou `sudo` (Linux) são recomendados para operações privilegiadas do sistema (reinício do spooler, reparo do SO, reset da pilha de rede, reinício de serviços e limpeza temporária do sistema). ### Modo Interativo (TUI) -Inicie o painel interativo. Caso a flag `--lang` seja omitida, o seletor interativo de idioma será exibido na inicialização: +Inicie o painel interativo numérico. Caso a flag `--lang` seja omitida, o seletor interativo de idioma será exibido na inicialização: ```bash -# Iniciar com seletor interativo de idioma php it-toolbox - -# Iniciar diretamente em Português (Brasil) php it-toolbox --lang=pt_BR - -# Iniciar diretamente em Inglês php it-toolbox --lang=en ``` @@ -144,19 +161,44 @@ Cada módulo também pode ser executado diretamente em scripts ou sessões rápi | Comando | Módulo | Descrição | Opções | | :--- | :--- | :--- | :--- | -| `php it-toolbox menu` | Core TUI | Inicia o menu principal interativo numérico TUI (comando padrão) | `--lang=en\|pt_BR`, `--once` | -| `php it-toolbox health:check` | Saúde | Executa auditoria completa com Score de Saúde (0–100) e recomendações | `--export`, `--lang=en\|pt_BR` | +| `php it-toolbox menu` | Core TUI | Inicia o menu principal interativo numérico TUI (padrão) | `--lang=en\|pt_BR`, `--once` | +| `php it-toolbox health:check` | Saúde | Executa auditoria completa com Score (0–100) e dicas | `--export`, `--lang=en\|pt_BR` | | `php it-toolbox system:info` | Sistema | Exibe métricas de SO, CPU, RAM e saúde de discos | `--lang=en\|pt_BR` | -| `php it-toolbox system:top` | Sistema | Lista os processos de maior consumo e permite encerrar um PID | `--limit=10`, `--lang=en\|pt_BR` | -| `php it-toolbox system:logs` | Sistema | Exibe eventos críticos e erros de log do SO nas últimas 24 horas | `--limit=15`, `--lang=en\|pt_BR` | -| `php it-toolbox printer:list` | Impressoras | Lista impressoras instaladas, drivers, portas e status | `--lang=en\|pt_BR` | -| `php it-toolbox printer:clear` | Impressoras | Reinicia o Spooler / CUPS e limpa trabalhos de impressão travados | `--force`, `--lang=en\|pt_BR` | -| `php it-toolbox network:check` | Rede | Inspeciona interfaces de rede e executa testes de ping e DNS | `--lang=en\|pt_BR` | -| `php it-toolbox network:flush` | Rede | Limpa o cache DNS e renova a concessão de IP via DHCP | `--force`, `--lang=en\|pt_BR` | -| `php it-toolbox network:ports` | Rede | Lista portas TCP/UDP em escuta e seus respectivos processos | `--lang=en\|pt_BR` | -| `php it-toolbox clean:temp` | Manutenção | Limpa diretórios temporários com segurança e exibe espaço liberado | `--force`, `--lang=en\|pt_BR` | -| `php it-toolbox report:export` | Relatórios | Exporta relatório completo de diagnóstico em `.md` e/ou `.json` | `--format=md\|json\|both`, `--output=DIR`, `--lang=en\|pt_BR` | -| `php it-toolbox self:update` | Core CLI | Verifica novas versões no GitHub Releases e auto-atualiza o binário | `--check`, `--lang=en\|pt_BR` | +| `php it-toolbox system:top` | Sistema | Lista processos de maior consumo e encerra por PID | `--limit=10`, `--lang=en\|pt_BR` | +| `php it-toolbox system:logs` | Sistema | Exibe eventos críticos e erros do SO (últimas 24h) | `--limit=15`, `--lang=en\|pt_BR` | +| `php it-toolbox system:services` | Sistema | Inspeciona e reinicia serviços críticos de suporte | `--restart=NOME`, `--lang=en\|pt_BR` | +| `php it-toolbox system:battery` | Sistema | Saúde da bateria, capacidade projetada e ciclos | `--lang=en\|pt_BR` | +| `php it-toolbox system:startup` | Sistema | Lista programas e serviços de inicialização/boot | `--lang=en\|pt_BR` | +| `php it-toolbox system:usb` | Sistema | Lista controladores e periféricos USB conectados | `--lang=en\|pt_BR` | +| `php it-toolbox system:env` | Sistema | Audita variáveis de ambiente e entradas do `PATH` | `--lang=en\|pt_BR` | +| `php it-toolbox system:kill` | Sistema | Encerra processo por PID, nome ou lista top-10 | `[target]`, `--force`, `--lang=en\|pt_BR` | +| `php it-toolbox printer:list` | Impressoras | Lista impressoras instaladas, drivers, portas e jobs | `--lang=en\|pt_BR` | +| `php it-toolbox printer:clear` | Impressoras | Reinicia o Spooler / CUPS e limpa a fila de impressão | `--force`, `--lang=en\|pt_BR` | +| `php it-toolbox printer:test-page` | Impressoras | Envia página de teste diagnóstica para impressora | `[printer]`, `--lang=en\|pt_BR` | +| `php it-toolbox printer:default` | Impressoras | Define a impressora padrão do sistema | `[printer]`, `--lang=en\|pt_BR` | +| `php it-toolbox network:check` | Rede | Inspeciona interfaces de rede e testa ping e DNS | `--lang=en\|pt_BR` | +| `php it-toolbox network:flush` | Rede | Limpa o cache DNS e renova a concessão DHCP | `--force`, `--lang=en\|pt_BR` | +| `php it-toolbox network:ports` | Rede | Lista portas TCP/UDP em escuta e processos | `--lang=en\|pt_BR` | +| `php it-toolbox network:probe` | Rede | Testa conexão TCP remota e mede latência (ms) | `[host] [port]`, `--timeout=3`, `--lang=...` | +| `php it-toolbox network:wifi` | Rede | Inspeciona SSID, BSSID, sinal %, canal e velocidade | `--lang=en\|pt_BR` | +| `php it-toolbox network:reset` | Rede | Reset completo da pilha de rede (Winsock/IP/DHCP) | `--force`, `--lang=en\|pt_BR` | +| `php it-toolbox network:ssl` | Rede | Inspeciona certificado SSL/TLS HTTPS e dias restantes | `[domain]`, `--port=443`, `--lang=en\|pt_BR` | +| `php it-toolbox network:scan` | Rede | Descobre dispositivos ativos na LAN via tabela ARP | `--lang=en\|pt_BR` | +| `php it-toolbox network:public` | Rede | Consulta IP público externo, geolocalização e ISP | `--lang=en\|pt_BR` | +| `php it-toolbox clean:temp` | Manutenção | Limpa diretórios temporários e exibe espaço liberado | `--force`, `--lang=en\|pt_BR` | +| `php it-toolbox maintenance:browsers` | Manutenção | Limpa somente cache do Chrome, Edge e Firefox | `--force`, `--lang=en\|pt_BR` | +| `php it-toolbox maintenance:large-files` | Manutenção | Localiza os maiores arquivos ocupando espaço | `[path]`, `--limit=15`, `--lang=en\|pt_BR` | +| `php it-toolbox maintenance:repair` | Manutenção | Verifica/repara integridade do SO (SFC/DISM/dpkg) | `--force`, `--lang=en\|pt_BR` | +| `php it-toolbox maintenance:updates` | Manutenção | Lista atualizações pendentes do SO e pacotes | `--lang=en\|pt_BR` | +| `php it-toolbox maintenance:scheduler` | Manutenção | Lista tarefas agendadas, cron jobs e timers ativos | `--lang=en\|pt_BR` | +| `php it-toolbox security:audit` | Segurança | Audita Firewall, Antivírus/MAC e UAC/SSH | `--lang=en\|pt_BR` | +| `php it-toolbox security:users` | Segurança | Audita contas locais e privilégios Admin/sudo | `--lang=en\|pt_BR` | +| `php it-toolbox security:shares` | Segurança | Lista compartilhamentos de rede SMB, Samba e NFS | `--lang=en\|pt_BR` | +| `php it-toolbox security:hosts` | Segurança | Audita arquivo hosts por redirecionamentos | `--lang=en\|pt_BR` | +| `php it-toolbox report:export` | Relatórios | Exporta relatório completo de diagnóstico (`.md` / `.json`) | `--format=md\|json\|both`, `--output=DIR`, `--lang=...` | +| `php it-toolbox toolbox:inventory` | Inventário | Gera ficha técnica patrimonial de hardware (GLPI/CMDB) | `--export`, `--lang=en\|pt_BR` | +| `php it-toolbox toolbox:benchmark` | Diagnóstico | Executa benchmark CPU SHA-256 e I/O disco (64 MB) | `--lang=en\|pt_BR` | +| `php it-toolbox self:update` | Core CLI | Verifica GitHub Releases e auto-atualiza o binário | `--check`, `--lang=en\|pt_BR` | --- @@ -168,15 +210,15 @@ Compile a aplicação em um arquivo `.phar` portátil (`builds/it-toolbox`) ou e ```bash # Compilar apenas o PHAR portátil -php it-toolbox app:build it-toolbox --build-version=1.0.0 +php -d phar.readonly=0 it-toolbox app:build it-toolbox --build-version=2.0.0 # Compilar PHAR + Binários Nativos Standalone (Linux & Windows x64) -./scripts/build-standalone.sh 1.0.0 +./scripts/build-standalone.sh 2.0.0 ``` ### Executando a Suíte de Testes -A suíte de testes utiliza **Pest PHP** com mocks dos processos do sistema operacional para que todos os testes rodem de forma determinística tanto no Windows quanto no Linux (CI): +A suíte de testes utiliza **Pest PHP** com mocks dos processos do sistema operacional via `ProcessExecutorInterface` para que todos os testes rodem de forma determinística tanto no Windows quanto no Linux (CI): ```bash # Executar todos os testes Unitários e de Feature @@ -192,13 +234,13 @@ A suíte de testes utiliza **Pest PHP** com mocks dos processos do sistema opera - **Linguagem & Runtime:** PHP 8.3+ (`declare(strict_types=1)`, propriedades tipadas, expressões `match`, classes `readonly`) - **Micro-Framework:** [Laravel Zero](https://laravel-zero.com/) -- **Interface de Terminal (TUI):** [Laravel Prompts](https://laravel.com/docs/prompts) (`select`, `table`, `spin`, `confirm`, `info`, `warning`, `error`) -- **Execução de Processos:** `Symfony\Component\Process\Process` (uso estrito de arrays de argumentos para prevenção de *Command Injection*) -- **Internacionalização:** `Illuminate\Translation` (`lang/en` & `lang/pt_BR`) +- **Interface de Terminal (TUI):** [Laravel Prompts](https://laravel.com/docs/prompts) + Navegação Numérica TTY Multiplataforma (`InteractsWithTerminal`) +- **Execução de Processos:** `Symfony\Component\Process\Process` abstraído via `ProcessExecutorInterface` (uso estrito de arrays de argumentos para prevenção de *Command Injection*) +- **Internacionalização:** `Illuminate\Translation` (`lang/en` & `lang/pt_BR` com 100% de paridade validada por testes no CI) - **Padrões de Projeto (Design Patterns):** - **Adapter / Driver Pattern:** `SystemDriverInterface` implementada por `WindowsDriver` e `LinuxDriver`. - **Factory Pattern:** `SystemDriverFactory` resolve dinamicamente o driver ativo via `PHP_OS_FAMILY`. - - **Data Transfer Objects (DTO):** `readonly class ActionResult` imutável para retorno padronizado de operações. + - **Data Transfer Objects (DTO):** `readonly class ActionResult` e `ProcessResult` imutáveis. - **Testes & Qualidade:** Pest PHP, Mockery, Laravel Pint e GitHub Actions CI em runners Ubuntu e Windows. --- diff --git a/app/Commands/Printer/PrintTestPageCommand.php b/app/Commands/Printer/PrintTestPageCommand.php new file mode 100644 index 0000000..4e7891f --- /dev/null +++ b/app/Commands/Printer/PrintTestPageCommand.php @@ -0,0 +1,94 @@ +resolveLocale(); + + info((string) __('messages.printer.test_page_section')); + + $printerArg = $this->argument('printer'); + if (is_string($printerArg) && trim($printerArg) !== '') { + $selectedPrinter = trim($printerArg); + } else { + /** @var array $printers */ + $printers = spin( + callback: fn (): array => $driver->listPrinters(), + message: (string) __('messages.spinners.printer_list'), + ); + + if ($printers === []) { + warning((string) __('messages.printer.no_printers')); + + return self::SUCCESS; + } + + $menuOptions = []; + $indexedPrinters = []; + foreach (array_values($printers) as $idx => $p) { + $num = (string) ($idx + 1); + $indexedPrinters[$num] = $p['name']; + $defaultBadge = strtolower($p['default'] ?? '') === 'yes' ? ' [*]' : ''; + $menuOptions[$num] = sprintf('%s%s (%s)', $p['name'], $defaultBadge, $p['status'] ?? 'Ready'); + } + $menuOptions['0'] = (string) __('messages.common.cancelled'); + + $choice = $this->promptNumericMenu( + promptLabel: (string) __('messages.printer.select_printer_prompt'), + options: $menuOptions, + defaultKey: '1', + ); + + if ($choice === '0' || ! isset($indexedPrinters[$choice])) { + warning((string) __('messages.common.cancelled')); + + return self::SUCCESS; + } + + $selectedPrinter = $indexedPrinters[$choice]; + } + + $result = spin( + callback: fn () => $driver->printTestPage($selectedPrinter), + message: (string) __('messages.spinners.printer_test_page', ['printer' => $selectedPrinter]), + ); + + return $this->renderActionResult($result); + } +} diff --git a/app/Commands/Printer/SetDefaultPrinterCommand.php b/app/Commands/Printer/SetDefaultPrinterCommand.php new file mode 100644 index 0000000..bd08f33 --- /dev/null +++ b/app/Commands/Printer/SetDefaultPrinterCommand.php @@ -0,0 +1,94 @@ +resolveLocale(); + + info((string) __('messages.printer.default_section')); + + $printerArg = $this->argument('printer'); + if (is_string($printerArg) && trim($printerArg) !== '') { + $selectedPrinter = trim($printerArg); + } else { + /** @var array $printers */ + $printers = spin( + callback: fn (): array => $driver->listPrinters(), + message: (string) __('messages.spinners.printer_list'), + ); + + if ($printers === []) { + warning((string) __('messages.printer.no_printers')); + + return self::SUCCESS; + } + + $menuOptions = []; + $indexedPrinters = []; + foreach (array_values($printers) as $idx => $p) { + $num = (string) ($idx + 1); + $indexedPrinters[$num] = $p['name']; + $defaultBadge = strtolower($p['default'] ?? '') === 'yes' ? ' (*) [Current Default]' : ''; + $menuOptions[$num] = sprintf('%s%s', $p['name'], $defaultBadge); + } + $menuOptions['0'] = (string) __('messages.common.cancelled'); + + $choice = $this->promptNumericMenu( + promptLabel: (string) __('messages.printer.select_default_prompt'), + options: $menuOptions, + defaultKey: '1', + ); + + if ($choice === '0' || ! isset($indexedPrinters[$choice])) { + warning((string) __('messages.common.cancelled')); + + return self::SUCCESS; + } + + $selectedPrinter = $indexedPrinters[$choice]; + } + + $result = spin( + callback: fn () => $driver->setDefaultPrinter($selectedPrinter), + message: (string) __('messages.spinners.printer_default', ['printer' => $selectedPrinter]), + ); + + return $this->renderActionResult($result); + } +} diff --git a/app/Commands/System/BenchmarkCommand.php b/app/Commands/System/BenchmarkCommand.php new file mode 100644 index 0000000..f29a5e9 --- /dev/null +++ b/app/Commands/System/BenchmarkCommand.php @@ -0,0 +1,48 @@ +resolveLocale(); + + info((string) __('messages.toolbox.benchmark_section')); + + $result = spin( + callback: fn () => $driver->runSystemBenchmark(64, 1.0), + message: (string) __('messages.spinners.toolbox_benchmark'), + ); + + return $this->renderActionResult($result); + } +} diff --git a/app/Commands/System/InventoryCommand.php b/app/Commands/System/InventoryCommand.php new file mode 100644 index 0000000..7163163 --- /dev/null +++ b/app/Commands/System/InventoryCommand.php @@ -0,0 +1,203 @@ +resolveLocale(); + + info((string) __('messages.toolbox.inventory_section')); + + $inventory = spin( + callback: fn (): array => $driver->getHardwareInventory(), + message: (string) __('messages.spinners.toolbox_inventory'), + ); + + info((string) __('messages.toolbox.identity_subsection')); + table( + headers: [ + (string) __('messages.common.metric'), + (string) __('messages.common.value'), + ], + rows: $this->formatMapRows($inventory['system_identity']), + ); + + info((string) __('messages.toolbox.cpu_ram_subsection')); + table( + headers: [ + (string) __('messages.common.metric'), + (string) __('messages.common.value'), + ], + rows: $this->formatMapRows($inventory['processor_memory']), + ); + + info((string) __('messages.toolbox.disks_subsection')); + table( + headers: [ + (string) __('messages.toolbox.disk_headers.model'), + (string) __('messages.toolbox.disk_headers.size'), + (string) __('messages.toolbox.disk_headers.media_type'), + (string) __('messages.toolbox.disk_headers.bus_type'), + ], + rows: array_map( + fn (array $disk): array => [ + $disk['model'] ?? '-', + $disk['size'] ?? '-', + $disk['media_type'] ?? '-', + $disk['bus_type'] ?? '-', + ], + $inventory['physical_disks'] + ), + ); + + info((string) __('messages.toolbox.network_subsection')); + table( + headers: [ + (string) __('messages.network.interface_headers.interface'), + (string) __('messages.network.interface_headers.ipv4'), + (string) __('messages.network.interface_headers.mac'), + (string) __('messages.network.interface_headers.status'), + ], + rows: array_map( + fn (array $iface): array => [ + $iface['interface'] ?? '-', + $iface['ipv4'] ?? '-', + $iface['mac'] ?? '-', + $iface['status'] ?? '-', + ], + $inventory['network_adapters'] + ), + ); + + $shouldExport = (bool) $this->option('export'); + if (! $shouldExport && $this->input->isInteractive()) { + $shouldExport = confirm( + label: (string) __('messages.toolbox.ask_export_inventory'), + default: false, + yes: (string) __('messages.common.yes'), + no: (string) __('messages.common.no'), + ); + } + + if ($shouldExport) { + return $this->exportInventorySheet($inventory, $locale); + } + + return self::SUCCESS; + } + + /** + * Map associative inventory fields into translated metric/value rows. + * + * @param array $fields + * @return array + */ + protected function formatMapRows(array $fields): array + { + $rows = []; + foreach ($fields as $key => $val) { + $labelKey = "messages.toolbox.fields.{$key}"; + $label = (string) __($labelKey); + if ($label === $labelKey) { + $label = ucfirst(str_replace('_', ' ', $key)); + } + $rows[] = [$label, (string) $val]; + } + + return $rows; + } + + /** + * Export the asset inventory profile into Markdown (.md) and JSON (.json) files. + * + * @param array $inventory + */ + protected function exportInventorySheet(array $inventory, string $locale): int + { + $dir = rtrim(getcwd() ?: base_path(), '/\\'); + $stamp = date('Y-m-d-His'); + $baseName = sprintf('it-toolbox-inventory-%s', $stamp); + $mdPath = $dir . DIRECTORY_SEPARATOR . $baseName . '.md'; + $jsonPath = $dir . DIRECTORY_SEPARATOR . $baseName . '.json'; + + $payload = [ + 'generated_at' => gmdate('Y-m-d\TH:i:s\Z'), + 'locale' => $locale, + 'os_family' => PHP_OS_FAMILY, + 'inventory' => $inventory, + ]; + + $mdLines = [ + sprintf('# %s — %s', (string) __('messages.app.name'), (string) __('messages.toolbox.inventory_section')), + '', + sprintf('## %s', (string) __('messages.toolbox.identity_subsection')), + '', + sprintf('| %s | %s |', (string) __('messages.common.metric'), (string) __('messages.common.value')), + '| :--- | :--- |', + ]; + + foreach ($this->formatMapRows((array) ($inventory['system_identity'] ?? [])) as [$k, $v]) { + $mdLines[] = sprintf('| %s | %s |', $k, $v); + } + + $mdLines[] = ''; + $mdLines[] = sprintf('## %s', (string) __('messages.toolbox.cpu_ram_subsection')); + $mdLines[] = ''; + $mdLines[] = sprintf('| %s | %s |', (string) __('messages.common.metric'), (string) __('messages.common.value')); + $mdLines[] = '| :--- | :--- |'; + + foreach ($this->formatMapRows((array) ($inventory['processor_memory'] ?? [])) as [$k, $v]) { + $mdLines[] = sprintf('| %s | %s |', $k, $v); + } + + $mdLines[] = ''; + + $mdOk = @file_put_contents($mdPath, implode("\n", $mdLines)) !== false; + $jsonOk = @file_put_contents($jsonPath, (string) json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)) !== false; + + if (! $mdOk || ! $jsonOk) { + error((string) __('messages.report.exported_failed', ['path' => $mdPath])); + + return self::FAILURE; + } + + info((string) __('messages.report.exported_success', ['path' => $mdPath . ', ' . $jsonPath])); + + return self::SUCCESS; + } +} diff --git a/app/Commands/ToolboxMenuCommand.php b/app/Commands/ToolboxMenuCommand.php index 8bb361c..95b4c14 100644 --- a/app/Commands/ToolboxMenuCommand.php +++ b/app/Commands/ToolboxMenuCommand.php @@ -68,8 +68,6 @@ public function handle(): int if ($choice === '1') { $this->executeSubcommand('health:check', $locale); - } elseif ($choice === '7') { - $this->executeSubcommand('report:export', $locale); } elseif ($choice === '8') { $this->executeSubcommand('self:update', $locale); } elseif ($choice === '9') { @@ -81,6 +79,7 @@ public function handle(): int '4' => 'network', '5' => 'maintenance', '6' => 'security', + '7' => 'reports', default => 'system', }; @@ -172,6 +171,8 @@ protected function handleCategorySubmenu(string $category, string $locale): void 'printers' => [ '1' => ['label' => (string) __('messages.menu.actions.printer_list'), 'command' => 'printer:list'], '2' => ['label' => (string) __('messages.menu.actions.printer_clear'), 'command' => 'printer:clear'], + '3' => ['label' => (string) __('messages.menu.actions.printer_test_page'), 'command' => 'printer:test-page'], + '4' => ['label' => (string) __('messages.menu.actions.printer_default'), 'command' => 'printer:default'], ], 'network' => [ '1' => ['label' => (string) __('messages.menu.actions.network_check'), 'command' => 'network:check'], @@ -198,6 +199,11 @@ protected function handleCategorySubmenu(string $category, string $locale): void '3' => ['label' => (string) __('messages.menu.actions.security_shares'), 'command' => 'security:shares'], '4' => ['label' => (string) __('messages.menu.actions.security_hosts'), 'command' => 'security:hosts'], ], + 'reports' => [ + '1' => ['label' => (string) __('messages.menu.actions.report_export'), 'command' => 'report:export'], + '2' => ['label' => (string) __('messages.menu.actions.toolbox_inventory'), 'command' => 'toolbox:inventory'], + '3' => ['label' => (string) __('messages.menu.actions.toolbox_benchmark'), 'command' => 'toolbox:benchmark'], + ], default => [], }; diff --git a/app/Contracts/SystemDriverInterface.php b/app/Contracts/SystemDriverInterface.php index 3fc6522..9a1f5d1 100644 --- a/app/Contracts/SystemDriverInterface.php +++ b/app/Contracts/SystemDriverInterface.php @@ -123,6 +123,22 @@ public function listPrinters(): array; */ public function clearPrintQueue(): ActionResult; + /** + * Send a test page to the specified printer. + * + * @param string $printerName + * @return ActionResult + */ + public function printTestPage(string $printerName): ActionResult; + + /** + * Set the system default printer. + * + * @param string $printerName + * @return ActionResult + */ + public function setDefaultPrinter(string $printerName): ActionResult; + /** * Retrieve active network interfaces, IPv4/IPv6, Gateway, DNS, and MAC addresses. * @@ -272,4 +288,25 @@ public function getNetworkShares(): array; * @return array */ public function inspectHostsFile(?string $customContent = null): array; + + /** + * Run a fast, zero-dependency CPU single-core and Disk sequential I/O micro-benchmark. + * + * @param int $diskSizeMb Temporary file size in MB (default 64 MB). + * @param float $cpuDurationSeconds Duration of the CPU SHA-256 loop in seconds (default 1.0s). + * @return ActionResult + */ + public function runSystemBenchmark(int $diskSizeMb = 64, float $cpuDurationSeconds = 1.0): ActionResult; + + /** + * Retrieve a complete corporate IT asset & hardware inventory profile (ready for GLPI / CMDB). + * + * @return array{ + * system_identity: array, + * processor_memory: array, + * physical_disks: array, + * network_adapters: array + * } + */ + public function getHardwareInventory(): array; } diff --git a/app/Drivers/Concerns/InteractsWithMaintenanceAndSecurity.php b/app/Drivers/Concerns/InteractsWithMaintenanceAndSecurity.php index 7b80bf4..4cafc89 100644 --- a/app/Drivers/Concerns/InteractsWithMaintenanceAndSecurity.php +++ b/app/Drivers/Concerns/InteractsWithMaintenanceAndSecurity.php @@ -242,6 +242,88 @@ public function inspectHostsFile(?string $customContent = null): array return $entries; } + /** + * Run a fast, zero-dependency CPU single-core and Disk sequential I/O micro-benchmark. + */ + public function runSystemBenchmark(int $diskSizeMb = 64, float $cpuDurationSeconds = 1.0): ActionResult + { + $safeSizeMb = max(1, min(256, $diskSizeMb)); + $safeCpuSeconds = max(0.02, min(5.0, $cpuDurationSeconds)); + + // 1. CPU Single-Core Cryptographic SHA-256 Benchmark + $cpuDurationNs = (int) round($safeCpuSeconds * 1_000_000_000); + $cpuStartNs = hrtime(true); + $iterations = 0; + $seed = 'it-toolbox-cli-v2.0.0-benchmark'; + + while ((hrtime(true) - $cpuStartNs) < $cpuDurationNs) { + for ($i = 0; $i < 2500; $i++) { + $seed = hash('sha256', $seed . $i); + $iterations++; + } + } + + $cpuElapsedSec = max(0.001, (hrtime(true) - $cpuStartNs) / 1_000_000_000); + $opsPerSec = (int) round($iterations / $cpuElapsedSec); + + // 2. Disk Sequential Write & Read I/O Benchmark + $tempFile = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'it_toolbox_bench_' . uniqid('', true) . '.tmp'; + $chunkSize = 1048576; // 1 MB + $chunkBuffer = str_repeat( hash('sha512', $seed, true), 16384 ); // 64 bytes * 16384 = 1 MB + + $writeSpeedMb = 0.0; + $readSpeedMb = 0.0; + + try { + $fpWrite = @fopen($tempFile, 'wb'); + if (is_resource($fpWrite)) { + $writeStartNs = hrtime(true); + for ($m = 0; $m < $safeSizeMb; $m++) { + @fwrite($fpWrite, $chunkBuffer, $chunkSize); + } + @fflush($fpWrite); + @fclose($fpWrite); + $writeElapsedSec = max(0.0001, (hrtime(true) - $writeStartNs) / 1_000_000_000); + $writeSpeedMb = round($safeSizeMb / $writeElapsedSec, 1); + } + + if (is_file($tempFile)) { + $fpRead = @fopen($tempFile, 'rb'); + if (is_resource($fpRead)) { + $readStartNs = hrtime(true); + while (! feof($fpRead)) { + @fread($fpRead, $chunkSize); + } + @fclose($fpRead); + $readElapsedSec = max(0.0001, (hrtime(true) - $readStartNs) / 1_000_000_000); + $readSpeedMb = round($safeSizeMb / $readElapsedSec, 1); + } + } + } finally { + if (is_file($tempFile)) { + @unlink($tempFile); + } + } + + $storageTier = match (true) { + $writeSpeedMb >= 350.0 => '🚀 NVMe / Fast SSD', + $writeSpeedMb >= 120.0 => '⚡ SATA SSD', + default => '🐢 HDD / Standard Storage', + }; + + return new ActionResult( + success: true, + message: 'messages.toolbox.benchmark_success', + details: [ + 'cpu_score' => sprintf('%s SHA-256 ops/sec', number_format($opsPerSec)), + 'disk_write_speed' => sprintf('%.1f MB/s (%d MB sample)', $writeSpeedMb, $safeSizeMb), + 'disk_read_speed' => sprintf('%.1f MB/s (%d MB sample)', $readSpeedMb, $safeSizeMb), + 'storage_tier' => $storageTier, + 'driver' => $this->getDriverLabel(), + ], + ); + } + /** * Calculate byte size of a cache file or directory tree safely. */ diff --git a/app/Drivers/LinuxDriver.php b/app/Drivers/LinuxDriver.php index d700962..f1af90c 100644 --- a/app/Drivers/LinuxDriver.php +++ b/app/Drivers/LinuxDriver.php @@ -1672,6 +1672,178 @@ public function getNetworkShares(): array return $shares; } + /** + * {@inheritDoc} + */ + public function printTestPage(string $printerName): ActionResult + { + $cleanName = preg_replace('/[^A-Za-z0-9_.-]/', '', trim($printerName)) ?? ''; + if ($cleanName === '') { + return new ActionResult( + success: false, + message: 'messages.printer.test_page_failed', + details: ['printer' => $printerName, 'driver' => 'Linux'], + ); + } + + $testBanner = implode("\n", [ + '====================================================', + ' IT TOOLBOX CLI - TEST PAGE ', + '====================================================', + 'Printer : ' . $cleanName, + 'Hostname : ' . (gethostname() ?: 'linux-host'), + 'Date/Time: ' . gmdate('Y-m-d H:i:s \U\T\C'), + 'Driver : CUPS / LinuxDriver', + '====================================================', + '', + ]); + + $tmpFile = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'it_toolbox_testpage_' . uniqid() . '.txt'; + @file_put_contents($tmpFile, $testBanner); + + try { + $result = $this->processRunner->run(['lp', '-d', $cleanName, $tmpFile]); + } finally { + @unlink($tmpFile); + } + + if ($result->successful) { + return new ActionResult( + success: true, + message: 'messages.printer.test_page_success', + details: [ + 'printer' => $cleanName, + 'output' => $result->output !== '' ? $result->output : 'Submitted to CUPS queue', + 'driver' => 'Linux', + ], + ); + } + + return new ActionResult( + success: false, + message: 'messages.printer.test_page_failed', + details: [ + 'printer' => $cleanName, + 'error' => $result->errorOutput ?: 'lp command failed', + 'driver' => 'Linux', + ], + ); + } + + /** + * {@inheritDoc} + */ + public function setDefaultPrinter(string $printerName): ActionResult + { + $cleanName = preg_replace('/[^A-Za-z0-9_.-]/', '', trim($printerName)) ?? ''; + if ($cleanName === '') { + return new ActionResult( + success: false, + message: 'messages.printer.default_set_failed', + details: ['printer' => $printerName, 'driver' => 'Linux'], + ); + } + + $result = $this->processRunner->run(['lpoptions', '-d', $cleanName]); + + if ($this->isRoot() && $this->commandExists('lpadmin')) { + $this->processRunner->run(['lpadmin', '-d', $cleanName]); + } + + if ($result->successful) { + return new ActionResult( + success: true, + message: 'messages.printer.default_set_success', + details: [ + 'printer' => $cleanName, + 'driver' => 'Linux', + ], + ); + } + + return new ActionResult( + success: false, + message: 'messages.printer.default_set_failed', + details: [ + 'printer' => $cleanName, + 'error' => $result->errorOutput ?: 'lpoptions command failed', + 'driver' => 'Linux', + ], + ); + } + + /** + * {@inheritDoc} + */ + public function getHardwareInventory(): array + { + $osInfo = $this->getOsInfo(); + $hwInfo = $this->getHardwareDiagnostics(); + $interfaces = $this->getNetworkInterfaces(); + + $vendor = trim((string) ($this->readFile('/sys/class/dmi/id/sys_vendor') ?? '')) ?: 'N/A'; + $product = trim((string) ($this->readFile('/sys/class/dmi/id/product_name') ?? '')) ?: 'N/A'; + $serial = trim((string) ($this->readFile('/sys/class/dmi/id/product_serial') ?? '')) ?: 'N/A'; + $biosVer = trim((string) ($this->readFile('/sys/class/dmi/id/bios_version') ?? '')) ?: 'N/A'; + $boardVendor = trim((string) ($this->readFile('/sys/class/dmi/id/board_vendor') ?? '')); + $boardName = trim((string) ($this->readFile('/sys/class/dmi/id/board_name') ?? '')); + $motherboard = trim($boardVendor . ' ' . $boardName) ?: 'N/A'; + + $physicalDisks = []; + $lsblkResult = $this->processRunner->run(['lsblk', '-d', '-b', '-o', 'NAME,SIZE,ROTA,TRAN,MODEL', '-J']); + if ($lsblkResult->successful && $lsblkResult->output !== '') { + $decoded = json_decode($lsblkResult->output, true); + foreach ((array) ($decoded['blockdevices'] ?? []) as $dev) { + if (! is_array($dev)) { + continue; + } + $name = (string) ($dev['name'] ?? ''); + if (str_starts_with($name, 'loop') || str_starts_with($name, 'ram') || str_starts_with($name, 'sr')) { + continue; + } + $rota = (bool) ($dev['rota'] ?? false); + $tran = strtoupper((string) ($dev['tran'] ?? 'SATA/NVMe')); + $mediaType = (! $rota || str_contains($name, 'nvme')) ? 'SSD / NVMe' : 'HDD (Rotational)'; + + $physicalDisks[] = [ + 'model' => trim((string) ($dev['model'] ?? ('/dev/' . $name))) ?: ('/dev/' . $name), + 'size' => $this->formatBytes((float) ($dev['size'] ?? 0.0)), + 'media_type' => $mediaType, + 'bus_type' => $tran !== '' ? $tran : 'Block', + ]; + } + } + + return [ + 'system_identity' => [ + 'hostname' => $osInfo['hostname'] ?? 'linux-host', + 'manufacturer' => $vendor, + 'model' => $product, + 'serial_number' => $serial, + 'bios_version' => $biosVer, + 'motherboard' => $motherboard, + 'os_edition' => $osInfo['os_name'] ?? 'Linux', + 'os_build' => sprintf('%s (%s)', $osInfo['os_version'] ?? '-', $osInfo['kernel'] ?? '-'), + ], + 'processor_memory' => [ + 'cpu_model' => $hwInfo['cpu_model'] ?? 'Unknown CPU', + 'cpu_cores' => $hwInfo['cpu_cores'] ?? 'N/A', + 'ram_total' => $hwInfo['ram_total'] ?? 'N/A', + 'ram_modules' => 'System Physical Memory (/proc/meminfo)', + ], + 'physical_disks' => $physicalDisks, + 'network_adapters' => array_map( + fn (array $iface): array => [ + 'interface' => $iface['interface'] ?? '-', + 'ipv4' => $iface['ipv4'] ?? '-', + 'mac' => $iface['mac'] ?? '-', + 'status' => $iface['status'] ?? '-', + ], + $interfaces + ), + ]; + } + /** * {@inheritDoc} */ diff --git a/app/Drivers/WindowsDriver.php b/app/Drivers/WindowsDriver.php index 73d5c6f..451be0b 100644 --- a/app/Drivers/WindowsDriver.php +++ b/app/Drivers/WindowsDriver.php @@ -1457,6 +1457,196 @@ public function getNetworkShares(): array return $shares; } + /** + * {@inheritDoc} + */ + public function printTestPage(string $printerName): ActionResult + { + $cleanName = str_replace("'", "''", trim($printerName)); + if ($cleanName === '') { + return new ActionResult( + success: false, + message: 'messages.printer.test_page_failed', + details: ['printer' => $printerName, 'driver' => 'Windows'], + ); + } + + $script = sprintf( + <<<'PS' +$ErrorActionPreference = 'SilentlyContinue'; +$p = Get-CimInstance -ClassName Win32_Printer | Where-Object { $_.Name -eq '%s' } | Select-Object -First 1; +if ($null -eq $p) { + [PSCustomObject]@{ Success = $false; ReturnValue = -1; Error = 'Printer not found' } | ConvertTo-Json -Compress; + exit 0; +} +$res = Invoke-CimMethod -InputObject $p -MethodName PrintTestPage -ErrorAction SilentlyContinue; +$rv = if ($null -ne $res) { [int]$res.ReturnValue } else { -1 }; +[PSCustomObject]@{ + Success = ($rv -eq 0); + ReturnValue = $rv; + Error = if ($rv -eq 0) { '' } else { "WMI ReturnValue: $rv" } +} | ConvertTo-Json -Compress +PS, + $cleanName + ); + + $data = $this->runPowerShellJson($script); + $ok = ($data['Success'] ?? false) === true; + + return new ActionResult( + success: $ok, + message: $ok ? 'messages.printer.test_page_success' : 'messages.printer.test_page_failed', + details: [ + 'printer' => trim($printerName), + 'driver' => 'Windows', + ], + ); + } + + /** + * {@inheritDoc} + */ + public function setDefaultPrinter(string $printerName): ActionResult + { + $cleanName = str_replace("'", "''", trim($printerName)); + if ($cleanName === '') { + return new ActionResult( + success: false, + message: 'messages.printer.default_set_failed', + details: ['printer' => $printerName, 'driver' => 'Windows'], + ); + } + + $script = sprintf( + <<<'PS' +$ErrorActionPreference = 'SilentlyContinue'; +$p = Get-CimInstance -ClassName Win32_Printer | Where-Object { $_.Name -eq '%s' } | Select-Object -First 1; +if ($null -eq $p) { + [PSCustomObject]@{ Success = $false; ReturnValue = -1; Error = 'Printer not found' } | ConvertTo-Json -Compress; + exit 0; +} +$res = Invoke-CimMethod -InputObject $p -MethodName SetDefaultPrinter -ErrorAction SilentlyContinue; +$rv = if ($null -ne $res) { [int]$res.ReturnValue } else { -1 }; +[PSCustomObject]@{ + Success = ($rv -eq 0); + ReturnValue = $rv; + Error = if ($rv -eq 0) { '' } else { "WMI ReturnValue: $rv" } +} | ConvertTo-Json -Compress +PS, + $cleanName + ); + + $data = $this->runPowerShellJson($script); + $ok = ($data['Success'] ?? false) === true; + + return new ActionResult( + success: $ok, + message: $ok ? 'messages.printer.default_set_success' : 'messages.printer.default_set_failed', + details: [ + 'printer' => trim($printerName), + 'driver' => 'Windows', + ], + ); + } + + /** + * {@inheritDoc} + */ + public function getHardwareInventory(): array + { + $script = <<<'PS' +$ErrorActionPreference = 'SilentlyContinue'; +$cs = Get-CimInstance -ClassName Win32_ComputerSystem | Select-Object -First 1; +$bios = Get-CimInstance -ClassName Win32_BIOS | Select-Object -First 1; +$board = Get-CimInstance -ClassName Win32_BaseBoard | Select-Object -First 1; +$os = Get-CimInstance -ClassName Win32_OperatingSystem | Select-Object -First 1; +$cpu = Get-CimInstance -ClassName Win32_Processor | Select-Object -First 1; +$memModules = @(Get-CimInstance -ClassName Win32_PhysicalMemory | ForEach-Object { + $capGb = [Math]::Round(($_.Capacity / 1GB), 1); + "$($capGb)GB @ $($_.Speed)MHz" +}); +$disks = @(Get-PhysicalDisk -ErrorAction SilentlyContinue | ForEach-Object { + [PSCustomObject]@{ + Model = [string]$_.FriendlyName; + Size = [double]$_.Size; + MediaType = [string]$_.MediaType; + BusType = [string]$_.BusType + } +}); +if ($disks.Count -eq 0) { + $disks = @(Get-CimInstance -ClassName Win32_DiskDrive -ErrorAction SilentlyContinue | ForEach-Object { + [PSCustomObject]@{ + Model = [string]$_.Model; + Size = [double]$_.Size; + MediaType = [string]$_.MediaType; + BusType = [string]$_.InterfaceType + } + }); +} +[PSCustomObject]@{ + Hostname = [string]$cs.Name; + Manufacturer = [string]$cs.Manufacturer; + Model = [string]$cs.Model; + Domain = [string]$cs.Domain; + SerialNumber = [string]$bios.SerialNumber; + BiosVersion = [string]$bios.SMBIOSBIOSVersion; + Motherboard = [string]("$($board.Manufacturer) $($board.Product)".Trim()); + OsName = [string]$os.Caption; + OsBuild = [string]("$($os.Version) (Build $($os.BuildNumber))"); + CpuModel = [string]$cpu.Name; + CpuCores = [string]("$($cpu.NumberOfCores) Cores / $($cpu.NumberOfLogicalProcessors) Threads"); + TotalRamBytes = [double]($cs.TotalPhysicalMemory -as [double]); + RamModules = [string]($memModules -join ', '); + Disks = @($disks) +} | ConvertTo-Json -Compress -Depth 4 +PS; + + $data = $this->runPowerShellJson($script); + $interfaces = $this->getNetworkInterfaces(); + + $physicalDisks = []; + foreach ($this->normalizeJsonList((array) ($data['Disks'] ?? [])) as $d) { + if (! is_array($d)) { + continue; + } + $physicalDisks[] = [ + 'model' => trim((string) ($d['Model'] ?? 'Physical Disk')) ?: 'Physical Disk', + 'size' => $this->formatBytes((float) ($d['Size'] ?? 0.0)), + 'media_type' => trim((string) ($d['MediaType'] ?? 'SSD/HDD')) ?: 'SSD/HDD', + 'bus_type' => trim((string) ($d['BusType'] ?? 'SATA/NVMe')) ?: 'SATA/NVMe', + ]; + } + + return [ + 'system_identity' => [ + 'hostname' => trim((string) ($data['Hostname'] ?? (gethostname() ?: 'UNKNOWN'))), + 'manufacturer' => trim((string) ($data['Manufacturer'] ?? 'N/A')) ?: 'N/A', + 'model' => trim((string) ($data['Model'] ?? 'N/A')) ?: 'N/A', + 'serial_number' => trim((string) ($data['SerialNumber'] ?? 'N/A')) ?: 'N/A', + 'bios_version' => trim((string) ($data['BiosVersion'] ?? 'N/A')) ?: 'N/A', + 'motherboard' => trim((string) ($data['Motherboard'] ?? 'N/A')) ?: 'N/A', + 'os_edition' => trim((string) ($data['OsName'] ?? 'Windows')) ?: 'Windows', + 'os_build' => trim((string) ($data['OsBuild'] ?? 'N/A')) ?: 'N/A', + ], + 'processor_memory' => [ + 'cpu_model' => trim((string) ($data['CpuModel'] ?? 'Unknown CPU')) ?: 'Unknown CPU', + 'cpu_cores' => trim((string) ($data['CpuCores'] ?? 'N/A')) ?: 'N/A', + 'ram_total' => $this->formatBytes((float) ($data['TotalRamBytes'] ?? 0.0)), + 'ram_modules' => trim((string) ($data['RamModules'] ?? 'N/A')) ?: 'N/A', + ], + 'physical_disks' => $physicalDisks, + 'network_adapters' => array_map( + fn (array $iface): array => [ + 'interface' => $iface['interface'] ?? '-', + 'ipv4' => $iface['ipv4'] ?? '-', + 'mac' => $iface['mac'] ?? '-', + 'status' => $iface['status'] ?? '-', + ], + $interfaces + ), + ]; + } + /** * {@inheritDoc} */ diff --git a/config/app.php b/config/app.php index 56d2fb5..96f8e50 100644 --- a/config/app.php +++ b/config/app.php @@ -28,7 +28,7 @@ | */ - 'version' => '1.2.0', + 'version' => '2.0.0', /* |-------------------------------------------------------------------------- diff --git a/lang/en/messages.php b/lang/en/messages.php index 1901db8..ecf6170 100644 --- a/lang/en/messages.php +++ b/lang/en/messages.php @@ -36,7 +36,7 @@ 'network' => '🌐 Network & Connectivity Diagnostics', 'maintenance' => '🧹 System Maintenance & Cleanup', 'security' => '🛡 Security & Access Auditing', - 'reports' => '📄 Export Diagnostic Report', + 'reports' => '📄 Reports, Asset Inventory & Benchmark', 'self_update' => '⬆️ Check for Updates (self:update)', 'language' => '🌍 Switch Language (EN / PT-BR)', ], @@ -52,6 +52,8 @@ 'system_kill' => 'Force-Kill Frozen Process by PID, Name or List (system:kill)', 'printer_list' => 'List Installed Printers & Status (printer:list)', 'printer_clear' => 'Restart Spooler & Clear Print Queue (printer:clear)', + 'printer_test_page' => 'Send Diagnostic Test Page to Printer (printer:test-page)', + 'printer_default' => 'Set System Default Printer (printer:default)', 'network_check' => 'Interfaces & Connectivity Health Check (network:check)', 'network_flush' => 'Flush DNS Cache & Renew IP Lease (network:flush)', 'network_ports' => 'Inspect Open Listening Ports (network:ports)', @@ -72,6 +74,8 @@ 'security_shares' => 'Inspect Active Network Shares — SMB, Samba & NFS (security:shares)', 'security_hosts' => 'Audit System Hosts File & Custom Domain Redirects (security:hosts)', 'report_export' => 'Export Full System Diagnostic Report (report:export)', + 'toolbox_inventory' => 'Generate Hardware & IT Asset Inventory Sheet (toolbox:inventory)', + 'toolbox_benchmark' => 'Run CPU Single-Core & Disk I/O Benchmark (toolbox:benchmark)', ], ], @@ -101,6 +105,8 @@ 'killing_process' => 'Terminating process PID :pid...', 'printer_list' => 'Querying installed printers and spooler status...', 'printer_clear' => 'Stopping spooler, purging queue, and restarting service...', + 'printer_test_page' => 'Sending diagnostic test page to ":printer"...', + 'printer_default' => 'Setting ":printer" as the system default printer...', 'network_check' => 'Inspecting network interfaces and testing connectivity...', 'network_flush' => 'Flushing DNS resolver cache and renewing network lease...', 'network_ports' => 'Scanning active listening TCP/UDP ports...', @@ -121,6 +127,8 @@ 'security_shares' => 'Querying active SMB, Samba, and NFS network shares...', 'security_hosts' => 'Inspecting system hosts file for custom domain mappings...', 'report_export' => 'Generating full diagnostic report...', + 'toolbox_benchmark' => 'Running CPU SHA-256 and 64 MB sequential Disk I/O benchmark...', + 'toolbox_inventory' => 'Collecting hardware, BIOS serial, storage, and network inventory...', 'self_update_check' => 'Checking GitHub Releases for newer versions...', 'self_update_download' => 'Downloading and installing update v:version...', ], @@ -285,6 +293,14 @@ 'confirm_clear' => 'This will restart the Print Spooler / CUPS service and delete all pending print jobs. Proceed?', 'queue_cleared_success' => 'Print spooler restarted and pending print queue cleared successfully.', 'queue_cleared_failed' => 'Failed to clear print queue. Verify administrator/sudo permissions.', + 'test_page_section' => 'Printer Diagnostic Test Page', + 'select_printer_prompt' => 'Select the printer number to send a test page:', + 'test_page_success' => 'Diagnostic test page sent to the printer queue successfully.', + 'test_page_failed' => 'Failed to send test page to the selected printer.', + 'default_section' => 'System Default Printer Configuration', + 'select_default_prompt' => 'Select the printer number to set as system default:', + 'default_set_success' => 'Default printer updated successfully.', + 'default_set_failed' => 'Failed to update the system default printer.', ], 'network' => [ @@ -439,6 +455,42 @@ 'battery_health' => 'Battery Health & Wear', 'cycle_count' => 'Charge Cycle Count', 'browsers_cleaned' => 'Browsers Processed', + 'printer' => 'Target Printer', + 'cpu_score' => 'CPU Single-Core Score', + 'disk_write_speed' => 'Disk Sequential Write', + 'disk_read_speed' => 'Disk Sequential Read', + 'storage_tier' => 'Detected Storage Tier', + ], + ], + + 'toolbox' => [ + 'benchmark_section' => 'CPU Single-Core & Disk Sequential I/O Micro-Benchmark', + 'benchmark_success' => 'System CPU and Disk I/O micro-benchmark completed successfully.', + 'inventory_section' => 'Hardware & IT Asset Technical Inventory Sheet (GLPI / CMDB)', + 'identity_subsection' => 'System Identity, BIOS Serial & Operating System', + 'cpu_ram_subsection' => 'Processor & Physical Memory Modules', + 'disks_subsection' => 'Physical Storage Drives', + 'network_subsection' => 'Network Adapters & MAC Addresses', + 'ask_export_inventory' => 'Would you like to export this asset inventory sheet to Markdown (.md) and JSON (.json)?', + 'disk_headers' => [ + 'model' => 'Drive Model', + 'size' => 'Capacity', + 'media_type' => 'Media Type', + 'bus_type' => 'Interface / Bus', + ], + 'fields' => [ + 'hostname' => 'Hostname', + 'manufacturer' => 'Manufacturer', + 'model' => 'System Model', + 'serial_number' => 'BIOS / Chassis Serial Number', + 'bios_version' => 'BIOS / Firmware Version', + 'motherboard' => 'Motherboard', + 'os_edition' => 'OS Edition', + 'os_build' => 'OS Build / Kernel', + 'cpu_model' => 'Processor Model', + 'cpu_cores' => 'Cores / Threads', + 'ram_total' => 'Total Physical RAM', + 'ram_modules' => 'Memory Modules / Slots', ], ], diff --git a/lang/pt_BR/messages.php b/lang/pt_BR/messages.php index 84176b8..d365d72 100644 --- a/lang/pt_BR/messages.php +++ b/lang/pt_BR/messages.php @@ -36,7 +36,7 @@ 'network' => '🌐 Rede & Conectividade', 'maintenance' => '🧹 Limpeza & Manutenção', 'security' => '🛡 Segurança & Auditoria de Acesso', - 'reports' => '📄 Exportar Relatório de Atendimento', + 'reports' => '📄 Relatórios, Inventário & Benchmark', 'self_update' => '⬆️ Verificar Atualizações (self:update)', 'language' => '🌍 Alterar Idioma (EN / PT-BR)', ], @@ -52,6 +52,8 @@ 'system_kill' => 'Encerrar Processo Travado por PID, Nome ou Lista (system:kill)', 'printer_list' => 'Listar Impressoras Instaladas e Status (printer:list)', 'printer_clear' => 'Reiniciar Spooler e Limpar Fila de Impressão (printer:clear)', + 'printer_test_page' => 'Enviar Página de Teste para Impressora (printer:test-page)', + 'printer_default' => 'Definir Impressora Padrão do Sistema (printer:default)', 'network_check' => 'Interfaces e Teste de Saúde de Conectividade (network:check)', 'network_flush' => 'Limpar Cache DNS e Renovar Concessão de IP (network:flush)', 'network_ports' => 'Inspecionar Portas Abertas em Escuta (network:ports)', @@ -72,6 +74,8 @@ 'security_shares' => 'Inspecionar Compartilhamentos Ativos — SMB, Samba e NFS (security:shares)', 'security_hosts' => 'Auditar Arquivo Hosts e Redirecionamentos de Domínio (security:hosts)', 'report_export' => 'Exportar Relatório Completo de Diagnóstico (report:export)', + 'toolbox_inventory' => 'Gerar Ficha Técnica de Inventário Patrimonial (toolbox:inventory)', + 'toolbox_benchmark' => 'Executar Benchmark Rápido de CPU & Disco (toolbox:benchmark)', ], ], @@ -101,6 +105,8 @@ 'killing_process' => 'Encerrando processo PID :pid...', 'printer_list' => 'Consultando impressoras instaladas e status do spooler...', 'printer_clear' => 'Parando spooler, limpando fila e reiniciando serviço...', + 'printer_test_page' => 'Enviando página de teste diagnóstica para ":printer"...', + 'printer_default' => 'Definindo ":printer" como impressora padrão do sistema...', 'network_check' => 'Inspecionando interfaces de rede e testando conectividade...', 'network_flush' => 'Limpando cache de resolução DNS e renovando IP...', 'network_ports' => 'Escaneando portas TCP/UDP ativas em escuta...', @@ -121,6 +127,8 @@ 'security_shares' => 'Consultando compartilhamentos de rede SMB, Samba e NFS ativos...', 'security_hosts' => 'Inspecionando arquivo hosts do sistema por mapeamentos customizados...', 'report_export' => 'Gerando relatório completo de diagnóstico...', + 'toolbox_benchmark' => 'Executando benchmark rápido de CPU SHA-256 e I/O sequencial de 64 MB...', + 'toolbox_inventory' => 'Coletando inventário completo de hardware, BIOS, discos e rede...', 'self_update_check' => 'Consultando GitHub Releases por novas versões...', 'self_update_download' => 'Baixando e instalando atualização v:version...', ], @@ -285,6 +293,14 @@ 'confirm_clear' => 'Isto reiniciará o serviço Spooler de Impressão / CUPS e removerá todos os trabalhos pendentes. Deseja prosseguir?', 'queue_cleared_success' => 'Spooler de impressão reiniciado e fila pendente limpa com sucesso.', 'queue_cleared_failed' => 'Falha ao limpar a fila de impressão. Verifique permissões de Administrador/sudo.', + 'test_page_section' => 'Impressão de Página de Teste Diagnóstica', + 'select_printer_prompt' => 'Selecione o número da impressora para enviar a página de teste:', + 'test_page_success' => 'Página de teste diagnóstica enviada para a fila da impressora com sucesso.', + 'test_page_failed' => 'Falha ao enviar página de teste para a impressora selecionada.', + 'default_section' => 'Configuração de Impressora Padrão do Sistema', + 'select_default_prompt' => 'Selecione o número da impressora para definir como padrão:', + 'default_set_success' => 'Impressora padrão atualizada com sucesso.', + 'default_set_failed' => 'Falha ao atualizar a impressora padrão do sistema.', ], 'network' => [ @@ -439,6 +455,42 @@ 'battery_health' => 'Saúde e Desgaste da Bateria', 'cycle_count' => 'Contagem de Ciclos', 'browsers_cleaned' => 'Navegadores Processados', + 'printer' => 'Impressora Alvo', + 'cpu_score' => 'Score CPU Single-Core', + 'disk_write_speed' => 'Escrita Sequencial em Disco', + 'disk_read_speed' => 'Leitura Sequencial em Disco', + 'storage_tier' => 'Perfil de Armazenamento Detectado', + ], + ], + + 'toolbox' => [ + 'benchmark_section' => 'Micro-Benchmark de CPU Single-Core & I/O Sequencial de Disco', + 'benchmark_success' => 'Micro-benchmark de CPU e I/O de disco concluído com sucesso.', + 'inventory_section' => 'Ficha Técnica de Inventário Patrimonial & Hardware (GLPI / CMDB)', + 'identity_subsection' => 'Identidade do Equipamento, Serial BIOS & Sistema Operacional', + 'cpu_ram_subsection' => 'Processador & Módulos de Memória Física', + 'disks_subsection' => 'Unidades Físicas de Armazenamento', + 'network_subsection' => 'Adaptadores de Rede & Endereços MAC', + 'ask_export_inventory' => 'Deseja exportar esta ficha de inventário patrimonial em Markdown (.md) e JSON (.json)?', + 'disk_headers' => [ + 'model' => 'Modelo do Disco', + 'size' => 'Capacidade', + 'media_type' => 'Tipo de Mídia', + 'bus_type' => 'Interface / Barramento', + ], + 'fields' => [ + 'hostname' => 'Nome do Host', + 'manufacturer' => 'Fabricante', + 'model' => 'Modelo do Equipamento', + 'serial_number' => 'Número de Série (BIOS / Chassi)', + 'bios_version' => 'Versão da BIOS / Firmware', + 'motherboard' => 'Placa-Mãe', + 'os_edition' => 'Edição do SO', + 'os_build' => 'Build / Kernel do SO', + 'cpu_model' => 'Modelo do Processador', + 'cpu_cores' => 'Núcleos / Threads', + 'ram_total' => 'RAM Física Total', + 'ram_modules' => 'Módulos / Slots de Memória', ], ], diff --git a/tests/Feature/ReportExporterTest.php b/tests/Feature/ReportExporterTest.php index 18805bd..9271c2b 100644 --- a/tests/Feature/ReportExporterTest.php +++ b/tests/Feature/ReportExporterTest.php @@ -231,6 +231,31 @@ public function inspectHostsFile(?string $customContent = null): array { return []; } + + public function printTestPage(string $printerName): ActionResult + { + return new ActionResult(true, 'messages.printer.test_page_success'); + } + + public function setDefaultPrinter(string $printerName): ActionResult + { + return new ActionResult(true, 'messages.printer.default_set_success'); + } + + public function runSystemBenchmark(int $diskSizeMb = 64, float $cpuDurationSeconds = 1.0): ActionResult + { + return new ActionResult(true, 'messages.toolbox.benchmark_success'); + } + + public function getHardwareInventory(): array + { + return [ + 'system_identity' => [], + 'processor_memory' => [], + 'physical_disks' => [], + 'network_adapters' => [], + ]; + } }; $tempDir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'it_toolbox_test_' . uniqid(); diff --git a/tests/Unit/HealthCheckServiceTest.php b/tests/Unit/HealthCheckServiceTest.php index 45012dd..9a768f9 100644 --- a/tests/Unit/HealthCheckServiceTest.php +++ b/tests/Unit/HealthCheckServiceTest.php @@ -223,6 +223,31 @@ public function inspectHostsFile(?string $customContent = null): array { return []; } + + public function printTestPage(string $printerName): ActionResult + { + return new ActionResult(true, 'ok'); + } + + public function setDefaultPrinter(string $printerName): ActionResult + { + return new ActionResult(true, 'ok'); + } + + public function runSystemBenchmark(int $diskSizeMb = 64, float $cpuDurationSeconds = 1.0): ActionResult + { + return new ActionResult(true, 'ok'); + } + + public function getHardwareInventory(): array + { + return [ + 'system_identity' => [], + 'processor_memory' => [], + 'physical_disks' => [], + 'network_adapters' => [], + ]; + } }; } diff --git a/tests/Unit/LinuxDriverTest.php b/tests/Unit/LinuxDriverTest.php index a492779..a3f2055 100644 --- a/tests/Unit/LinuxDriverTest.php +++ b/tests/Unit/LinuxDriverTest.php @@ -379,3 +379,84 @@ public function getEffectiveUid(): int ->and($shares[0]['type'])->toBe('Samba (SMB)') ->and($shares[1]['type'])->toBe('NFS Export'); }); + +it('handles Linux CUPS test page, default printer, CPU/Disk micro-benchmark, and DMI hardware inventory', function (): void { + $executor = new class implements ProcessExecutorInterface + { + /** @var array */ + public array $files = [ + '/etc/os-release' => "PRETTY_NAME=\"Ubuntu 24.04.1 LTS\"\nVERSION=\"24.04\"\n", + '/proc/sys/kernel/hostname' => "ubuntu-asset-01\n", + '/proc/uptime' => "3600.00 7200.00\n", + '/proc/cpuinfo' => "processor\t: 0\nmodel name\t: AMD Ryzen 9 7950X\ncpu cores\t: 16\n", + '/proc/loadavg' => "0.15 0.10 0.05 1/100 500\n", + '/proc/meminfo' => "MemTotal: 33554432 kB\nMemAvailable: 25165824 kB\n", + '/etc/resolv.conf' => "nameserver 1.1.1.1\n", + '/sys/class/dmi/id/sys_vendor' => "LENOVO\n", + '/sys/class/dmi/id/product_name' => "ThinkPad P16 Gen 2\n", + '/sys/class/dmi/id/product_serial' => "PF4X9988\n", + '/sys/class/dmi/id/bios_version' => "N3XET50W\n", + '/sys/class/dmi/id/board_vendor' => "LENOVO\n", + '/sys/class/dmi/id/board_name' => "21FA0011BR\n", + ]; + + public function run(array $command, int $timeout = 30): ProcessResult + { + if ($command[0] === 'lp') { + return new ProcessResult(0, 'request id is Office_CUPS-77 (1 file(s))'); + } + + return match ($command) { + ['lpoptions', '-d', 'Office_CUPS'] => new ProcessResult(0, ''), + ['uname', '-r'] => new ProcessResult(0, '6.8.0-45-generic'), + ['uname', '-m'] => new ProcessResult(0, 'x86_64'), + ['ip', '-j', 'route'] => new ProcessResult(0, json_encode([['dst' => 'default', 'gateway' => '192.168.1.1', 'dev' => 'eth0']])), + ['ip', '-j', 'addr'] => new ProcessResult(0, json_encode([[ + 'ifname' => 'eth0', + 'operstate' => 'UP', + 'address' => 'aa:bb:cc:dd:ee:ff', + 'addr_info' => [['family' => 'inet', 'local' => '192.168.1.50', 'prefixlen' => 24]], + ]])), + ['lsblk', '-d', '-b', '-o', 'NAME,SIZE,ROTA,TRAN,MODEL', '-J'] => new ProcessResult(0, json_encode([ + 'blockdevices' => [ + ['name' => 'nvme0n1', 'size' => 1024209543168, 'rota' => false, 'tran' => 'nvme', 'model' => 'WD Black SN850X 1TB'], + ], + ])), + default => new ProcessResult(1, '', '', false), + }; + } + + public function readFile(string $path): ?string + { + return $this->files[$path] ?? null; + } + + public function getEffectiveUid(): int + { + return 1000; + } + }; + + $driver = new LinuxDriver($executor); + + $testPage = $driver->printTestPage('Office_CUPS'); + expect($testPage->success)->toBeTrue() + ->and($testPage->message)->toBe('messages.printer.test_page_success'); + + $defaultSet = $driver->setDefaultPrinter('Office_CUPS'); + expect($defaultSet->success)->toBeTrue() + ->and($defaultSet->message)->toBe('messages.printer.default_set_success'); + + $inventory = $driver->getHardwareInventory(); + expect($inventory['system_identity']['hostname'])->toBe('ubuntu-asset-01') + ->and($inventory['system_identity']['manufacturer'])->toBe('LENOVO') + ->and($inventory['system_identity']['serial_number'])->toBe('PF4X9988') + ->and($inventory['processor_memory']['ram_total'])->toBe('32.00 GB') + ->and($inventory['physical_disks'])->toHaveCount(1) + ->and($inventory['physical_disks'][0]['media_type'])->toBe('SSD / NVMe'); + + $bench = $driver->runSystemBenchmark(1, 0.05); + expect($bench->success)->toBeTrue() + ->and($bench->message)->toBe('messages.toolbox.benchmark_success') + ->and($bench->details['cpu_score'])->toContain('SHA-256 ops/sec'); +}); diff --git a/tests/Unit/WindowsDriverTest.php b/tests/Unit/WindowsDriverTest.php index cf61795..854853c 100644 --- a/tests/Unit/WindowsDriverTest.php +++ b/tests/Unit/WindowsDriverTest.php @@ -525,3 +525,89 @@ public function getEffectiveUid(): int @rmdir($tempDir); } }); + +it('handles Windows printer test page, default printer, CPU/Disk micro-benchmark, and hardware asset inventory', function (): void { + $executor = new class implements ProcessExecutorInterface + { + public int $callIndex = 0; + + public function run(array $command, int $timeout = 30): ProcessResult + { + $this->callIndex++; + + return match ($this->callIndex) { + 1 => new ProcessResult(0, (string) json_encode(['Success' => true, 'ReturnValue' => 0, 'Error' => ''])), + 2 => new ProcessResult(0, (string) json_encode(['Success' => true, 'ReturnValue' => 0, 'Error' => ''])), + 3 => new ProcessResult(0, (string) json_encode([ + 'Hostname' => 'ASSET-WS-042', + 'Manufacturer' => 'Dell Inc.', + 'Model' => 'OptiPlex 7010', + 'SerialNumber' => 'SN-99887766', + 'BiosVersion' => '1.18.0', + 'Motherboard' => 'Dell Inc. 0X88Y', + 'OsName' => 'Microsoft Windows 11 Pro', + 'OsBuild' => '10.0.22631 (Build 22631)', + 'CpuModel' => 'Intel(R) Core(TM) i7-13700', + 'CpuCores' => '16 Cores / 24 Threads', + 'TotalRamBytes' => 34359738368, // 32 GB + 'RamModules' => '16.0GB @ 4800MHz, 16.0GB @ 4800MHz', + 'Disks' => [ + [ + 'Model' => 'Samsung PM9A1 NVMe 512GB', + 'Size' => 512110190592, + 'MediaType' => 'SSD', + 'BusType' => 'NVMe', + ], + ], + ])), + 4 => new ProcessResult(0, (string) json_encode([ + [ + 'InterfaceAlias' => 'Ethernet', + 'IPv4' => '10.0.10.42', + 'IPv6' => '', + 'Gateway' => '10.0.10.1', + 'DnsServers' => '10.0.10.2', + 'MacAddress' => '00-1A-2B-3C-4D-5E', + 'Status' => 'Up', + ], + ])), + default => new ProcessResult(0, '[]'), + }; + } + + public function readFile(string $path): ?string + { + return null; + } + + public function getEffectiveUid(): int + { + return 0; + } + }; + + $driver = new WindowsDriver($executor); + + $testPage = $driver->printTestPage('HP LaserJet M428'); + expect($testPage->success)->toBeTrue() + ->and($testPage->message)->toBe('messages.printer.test_page_success'); + + $defaultSet = $driver->setDefaultPrinter('HP LaserJet M428'); + expect($defaultSet->success)->toBeTrue() + ->and($defaultSet->message)->toBe('messages.printer.default_set_success'); + + $inventory = $driver->getHardwareInventory(); + expect($inventory['system_identity']['hostname'])->toBe('ASSET-WS-042') + ->and($inventory['system_identity']['serial_number'])->toBe('SN-99887766') + ->and($inventory['processor_memory']['ram_total'])->toBe('32.00 GB') + ->and($inventory['physical_disks'])->toHaveCount(1) + ->and($inventory['physical_disks'][0]['bus_type'])->toBe('NVMe') + ->and($inventory['network_adapters'][0]['mac'])->toBe('00-1A-2B-3C-4D-5E'); + + $bench = $driver->runSystemBenchmark(1, 0.05); + expect($bench->success)->toBeTrue() + ->and($bench->message)->toBe('messages.toolbox.benchmark_success') + ->and($bench->details['cpu_score'])->toContain('SHA-256 ops/sec') + ->and($bench->details['disk_write_speed'])->toContain('MB/s') + ->and($bench->details['disk_read_speed'])->toContain('MB/s'); +});