From 0c40398eab025c2284f89973feb9c47b0716cafb Mon Sep 17 00:00:00 2001 From: Dev-lib4n Date: Wed, 18 Nov 2026 15:20:14 -0300 Subject: [PATCH 1/2] 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 2/2] 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 ';'; + } }