From bf64a9c878f311984e83ab2130aaa7cfc7aa5b79 Mon Sep 17 00:00:00 2001 From: Dev-lib4n Date: Wed, 18 Nov 2026 14:04:19 -0300 Subject: [PATCH] feat(v1.2.0): add health:check scoring, system:logs viewer, and self:update via GitHub Releases --- README.md | 14 +- README.pt-BR.md | 14 +- app/Commands/System/HealthCheckCommand.php | 132 ++++++++ app/Commands/System/LogsCommand.php | 82 +++++ app/Commands/System/SelfUpdateCommand.php | 103 ++++++ app/Commands/ToolboxMenuCommand.php | 31 +- app/Contracts/SystemDriverInterface.php | 8 + app/Drivers/LinuxDriver.php | 166 +++++++++ app/Drivers/WindowsDriver.php | 84 +++++ app/Services/HealthCheckService.php | 296 ++++++++++++++++ app/Services/ReportExporterService.php | 35 +- app/Services/SelfUpdateService.php | 377 +++++++++++++++++++++ config/app.php | 2 +- lang/en/messages.php | 74 ++++ lang/pt_BR/messages.php | 74 ++++ tests/Feature/ReportExporterTest.php | 5 + tests/Unit/HealthCheckServiceTest.php | 165 +++++++++ tests/Unit/LinuxDriverTest.php | 58 ++++ tests/Unit/SelfUpdateServiceTest.php | 82 +++++ tests/Unit/WindowsDriverTest.php | 60 ++++ 20 files changed, 1839 insertions(+), 23 deletions(-) create mode 100644 app/Commands/System/HealthCheckCommand.php create mode 100644 app/Commands/System/LogsCommand.php create mode 100644 app/Commands/System/SelfUpdateCommand.php create mode 100644 app/Services/HealthCheckService.php create mode 100644 app/Services/SelfUpdateService.php create mode 100644 tests/Unit/HealthCheckServiceTest.php create mode 100644 tests/Unit/SelfUpdateServiceTest.php diff --git a/README.md b/README.md index 6f74975..6d3bd39 100644 --- a/README.md +++ b/README.md @@ -17,11 +17,14 @@ ## Features +- **🩺 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). - **🖨 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). @@ -33,9 +36,11 @@ - **🧹 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 `.txt` or `.json` files for ticketing systems and audit logs. + - 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 TUI menu. + - Full support for **English (`en`)** and **Brazilian Portuguese (`pt_BR`)**, selectable via `--lang=` flag or dynamically inside the interactive numeric TUI menu. --- @@ -139,9 +144,11 @@ 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 TUI main menu (default command) | `--lang=en\|pt_BR`, `--once` | +| `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 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` | @@ -149,6 +156,7 @@ Every module can also be executed directly in headless/CLI scripts or terminal s | `php it-toolbox network:ports` | Network | List active listening TCP/UDP ports and owning processes | `--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` | --- diff --git a/README.pt-BR.md b/README.pt-BR.md index 0666efb..bd51cfc 100644 --- a/README.pt-BR.md +++ b/README.pt-BR.md @@ -17,11 +17,14 @@ O **IT Toolbox CLI (`it-toolbox`)** é um utilitário interativo de terminal (TU ## Funcionalidades +- **🩺 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). - **🖨 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). @@ -33,9 +36,11 @@ O **IT Toolbox CLI (`it-toolbox`)** é um utilitário interativo de terminal (TU - **🧹 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 `.txt` ou `.json` para anexação em chamados técnicos e auditorias. + - 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 TUI. + - 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. --- @@ -139,9 +144,11 @@ 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 TUI (comando padrão) | `--lang=en\|pt_BR`, `--once` | +| `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 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` | @@ -149,6 +156,7 @@ Cada módulo também pode ser executado diretamente em scripts ou sessões rápi | `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` | --- diff --git a/app/Commands/System/HealthCheckCommand.php b/app/Commands/System/HealthCheckCommand.php new file mode 100644 index 0000000..464bd1b --- /dev/null +++ b/app/Commands/System/HealthCheckCommand.php @@ -0,0 +1,132 @@ +resolveLocale(); + + $audit = spin( + callback: fn (): array => $healthService->runAudit(), + message: (string) __('messages.spinners.health_check'), + ); + + info((string) __('messages.health.section')); + + $scoreBanner = sprintf( + '%s: %s (%s)', + (string) __('messages.health.score_label'), + $audit['progress_bar'], + $audit['state_label'] + ); + + match ($audit['state']) { + 'healthy' => info($scoreBanner), + 'warning' => warning($scoreBanner), + default => error($scoreBanner), + }; + + table( + headers: [ + (string) __('messages.health.headers.category'), + (string) __('messages.health.headers.status'), + (string) __('messages.health.headers.summary'), + (string) __('messages.health.headers.impact'), + ], + rows: array_map( + fn (array $item): array => [ + $item['category'], + sprintf('%s %s', $item['icon'], $item['status']), + $item['summary'], + $item['penalty'] > 0 ? sprintf('-%d pts', $item['penalty']) : '0 pts', + ], + $audit['checks'] + ), + ); + + if ($audit['recommendations'] !== []) { + warning((string) __('messages.health.recommendations_title')); + $recLines = array_map( + fn (string $rec): string => sprintf(' • %s', $rec), + $audit['recommendations'] + ); + note(implode(PHP_EOL, $recLines)); + } else { + info((string) __('messages.health.no_recommendations')); + } + + $shouldExport = (bool) $this->option('export'); + + if (! $shouldExport && $this->input->isInteractive()) { + $shouldExport = confirm( + label: (string) __('messages.health.ask_export'), + default: false, + yes: (string) __('messages.common.yes'), + no: (string) __('messages.common.no'), + ); + } + + if ($shouldExport) { + $exportResult = spin( + callback: fn () => $exporter->export( + format: 'both', + outputDirectory: null, + locale: $locale, + timestamp: null, + healthAudit: $audit, + ), + message: (string) __('messages.spinners.report_export'), + ); + + $paths = isset($exportResult->details['paths']) && is_array($exportResult->details['paths']) + ? implode(', ', array_map('strval', $exportResult->details['paths'])) + : ''; + + if ($exportResult->success) { + info((string) __('messages.report.exported_success', ['path' => $paths])); + } else { + error((string) __('messages.report.exported_failed', ['path' => $paths])); + } + } + + return self::SUCCESS; + } +} diff --git a/app/Commands/System/LogsCommand.php b/app/Commands/System/LogsCommand.php new file mode 100644 index 0000000..9ef5caf --- /dev/null +++ b/app/Commands/System/LogsCommand.php @@ -0,0 +1,82 @@ +resolveLocale(); + + $limit = max(1, (int) $this->option('limit')); + + $result = spin( + callback: fn () => $driver->getCriticalLogs($limit), + message: (string) __('messages.spinners.system_logs'), + ); + + info((string) __('messages.logs.section')); + + /** @var array $events */ + $events = isset($result->details['events']) && is_array($result->details['events']) + ? $result->details['events'] + : []; + + if ($events === []) { + info((string) __('messages.logs.no_logs')); + + return self::SUCCESS; + } + + table( + headers: [ + (string) __('messages.logs.headers.timestamp'), + (string) __('messages.logs.headers.level'), + (string) __('messages.logs.headers.source'), + (string) __('messages.logs.headers.message'), + ], + rows: array_map( + fn (array $event): array => [ + (string) ($event['timestamp'] ?? '-'), + (string) ($event['level'] ?? 'ERROR'), + (string) ($event['source'] ?? '-'), + (string) ($event['message'] ?? '-'), + ], + $events + ), + ); + + return self::SUCCESS; + } +} diff --git a/app/Commands/System/SelfUpdateCommand.php b/app/Commands/System/SelfUpdateCommand.php new file mode 100644 index 0000000..d8d42e5 --- /dev/null +++ b/app/Commands/System/SelfUpdateCommand.php @@ -0,0 +1,103 @@ +resolveLocale(); + + info((string) __('messages.update.section')); + + $check = spin( + callback: fn (): array => $updateService->checkForUpdates(), + message: (string) __('messages.spinners.self_update_check'), + ); + + if (! $check['success']) { + error((string) __('messages.update.check_failed')); + + return self::FAILURE; + } + + if (! $check['update_available']) { + info((string) __('messages.update.up_to_date', [ + 'version' => $check['current_version'], + ])); + + return self::SUCCESS; + } + + info((string) __('messages.update.available', [ + 'current' => $check['current_version'], + 'latest' => $check['latest_version'], + ])); + + if ($this->option('check')) { + return self::SUCCESS; + } + + if ($check['asset_name'] === null) { + warning((string) __('messages.update.source_mode_warning')); + + return self::SUCCESS; + } + + if ($this->input->isInteractive() && ! confirm( + label: (string) __('messages.update.confirm_download', [ + 'version' => $check['latest_version'], + 'asset' => $check['asset_name'], + ]), + default: true, + yes: (string) __('messages.common.yes'), + no: (string) __('messages.common.no'), + )) { + warning((string) __('messages.common.cancelled')); + + return self::SUCCESS; + } + + $result = spin( + callback: fn () => $updateService->performUpdate(), + message: (string) __('messages.spinners.self_update_download', [ + 'version' => $check['latest_version'], + ]), + ); + + return $this->renderActionResult($result); + } +} diff --git a/app/Commands/ToolboxMenuCommand.php b/app/Commands/ToolboxMenuCommand.php index 1d9d67d..912bc32 100644 --- a/app/Commands/ToolboxMenuCommand.php +++ b/app/Commands/ToolboxMenuCommand.php @@ -45,12 +45,14 @@ public function handle(): int $choice = $this->promptNumericMenu( promptLabel: (string) __('messages.menu.main_prompt'), options: [ - '1' => (string) __('messages.menu.categories.system'), - '2' => (string) __('messages.menu.categories.printers'), - '3' => (string) __('messages.menu.categories.network'), - '4' => (string) __('messages.menu.categories.maintenance'), - '5' => (string) __('messages.menu.categories.reports'), - '6' => (string) __('messages.menu.categories.language'), + '1' => (string) __('messages.menu.categories.health_check'), + '2' => (string) __('messages.menu.categories.system'), + '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'), '0' => (string) __('messages.menu.exit'), ], defaultKey: '1', @@ -63,16 +65,20 @@ public function handle(): int return self::SUCCESS; } - if ($choice === '5') { - $this->executeSubcommand('report:export', $locale); + if ($choice === '1') { + $this->executeSubcommand('health:check', $locale); } elseif ($choice === '6') { + $this->executeSubcommand('report:export', $locale); + } elseif ($choice === '7') { + $this->executeSubcommand('self:update', $locale); + } elseif ($choice === '8') { $locale = $this->promptNumericLanguageSwitch($locale); } else { $category = match ($choice) { - '1' => 'system', - '2' => 'printers', - '3' => 'network', - '4' => 'maintenance', + '2' => 'system', + '3' => 'printers', + '4' => 'network', + '5' => 'maintenance', default => 'system', }; @@ -153,6 +159,7 @@ protected function handleCategorySubmenu(string $category, string $locale): void 'system' => [ '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'], ], '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 ceb72b6..d74c41a 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; + /** + * Retrieve recent critical and error events from the OS event log / journal (last 24 hours). + * + * @param int $limit + * @return ActionResult + */ + public function getCriticalLogs(int $limit = 15): ActionResult; + /** * List installed printers, their current status, and pending print jobs. * diff --git a/app/Drivers/LinuxDriver.php b/app/Drivers/LinuxDriver.php index 6b0bd43..88ae3ec 100644 --- a/app/Drivers/LinuxDriver.php +++ b/app/Drivers/LinuxDriver.php @@ -329,6 +329,49 @@ public function killProcess(int $pid): ActionResult ); } + /** + * {@inheritDoc} + */ + public function getCriticalLogs(int $limit = 15): ActionResult + { + $safeLimit = max(1, $limit); + $events = []; + + $journalResult = $this->processRunner->run([ + 'journalctl', + '-p', + 'err', + '-n', + (string) $safeLimit, + '--since', + '24 hours ago', + '--no-pager', + '-o', + 'json', + ]); + + if ($journalResult->successful && $journalResult->output !== '') { + $events = $this->parseJournalctlJsonLogs($journalResult->output, $safeLimit); + } + + if ($events === []) { + $syslogRaw = $this->readFile('/var/log/syslog') ?? $this->readFile('/var/log/messages') ?? ''; + if ($syslogRaw !== '') { + $events = $this->parseSyslogErrors($syslogRaw, $safeLimit); + } + } + + return new ActionResult( + success: true, + message: $events !== [] ? 'messages.logs.fetched_success' : 'messages.logs.no_logs', + details: [ + 'events' => $events, + 'count' => count($events), + 'driver' => 'Linux', + ], + ); + } + /** * {@inheritDoc} */ @@ -1403,4 +1446,127 @@ protected function formatBytes(float $bytes): string return sprintf('%.2f %s', $value, $units[$power]); } + + /** + * Parse journalctl JSON or JSON-Lines output into structured critical log entries. + * + * @return array + */ + protected function parseJournalctlJsonLogs(string $output, int $limit): array + { + $trimmed = trim($output); + if ($trimmed === '' || str_starts_with(strtolower($trimmed), '-- no entries --')) { + return []; + } + + $entries = []; + $decodedWhole = json_decode($trimmed, true); + if (is_array($decodedWhole)) { + $entries = array_is_list($decodedWhole) ? $decodedWhole : [$decodedWhole]; + } else { + $lines = preg_split('/\r\n|\r|\n/', $trimmed) ?: []; + foreach ($lines as $line) { + $line = trim($line); + if ($line === '' || ! str_starts_with($line, '{')) { + continue; + } + $item = json_decode($line, true); + if (is_array($item)) { + $entries[] = $item; + } + } + } + + $events = []; + foreach ($entries as $entry) { + if (! is_array($entry)) { + continue; + } + + $timestamp = '-'; + if (isset($entry['__REALTIME_TIMESTAMP']) && is_numeric($entry['__REALTIME_TIMESTAMP'])) { + $seconds = (int) floor(((float) $entry['__REALTIME_TIMESTAMP']) / 1_000_000); + $timestamp = gmdate('Y-m-d H:i:s', $seconds); + } elseif (isset($entry['SYSLOG_TIMESTAMP'])) { + $timestamp = trim((string) $entry['SYSLOG_TIMESTAMP']); + } elseif (isset($entry['timestamp'])) { + $timestamp = trim((string) $entry['timestamp']); + } + + $priority = isset($entry['PRIORITY']) ? (int) $entry['PRIORITY'] : 3; + $level = $priority <= 2 ? 'CRITICAL' : 'ERROR'; + + $source = trim((string) ($entry['SYSLOG_IDENTIFIER'] ?? $entry['_COMM'] ?? $entry['_SYSTEMD_UNIT'] ?? 'kernel')); + $rawMsg = is_array($entry['MESSAGE'] ?? null) + ? implode(' ', array_map('strval', $entry['MESSAGE'])) + : (string) ($entry['MESSAGE'] ?? '-'); + + $events[] = [ + 'timestamp' => $timestamp !== '' ? $timestamp : '-', + 'level' => $level, + 'source' => $source !== '' ? $source : 'system', + 'message' => $this->truncateLogMessage($rawMsg), + ]; + } + + return array_slice($events, 0, $limit); + } + + /** + * Fallback parser for /var/log/syslog or /var/log/messages error lines. + * + * @return array + */ + protected function parseSyslogErrors(string $raw, int $limit): array + { + $lines = preg_split('/\r\n|\r|\n/', trim($raw)) ?: []; + $matched = []; + + foreach ($lines as $line) { + $line = trim($line); + if ($line === '' || preg_match('/\b(crit|critical|emerg|alert|fatal|panic|err|error|failed)\b/i', $line) !== 1) { + continue; + } + + $level = preg_match('/\b(crit|critical|emerg|alert|fatal|panic)\b/i', $line) === 1 + ? 'CRITICAL' + : 'ERROR'; + + // Match standard syslog: "Nov 18 10:15:02 host service[123]: message" or ISO timestamp + if (preg_match('/^([A-Z][a-z]{2}\s+\d+\s+\d{2}:\d{2}:\d{2}|\d{4}-\d{2}-\d{2}[T\s]\d{2}:\d{2}:\d{2}\S*)\s+\S+\s+([^:]+):\s*(.+)$/', $line, $m) === 1) { + $matched[] = [ + 'timestamp' => trim($m[1]), + 'level' => $level, + 'source' => trim($m[2]), + 'message' => $this->truncateLogMessage($m[3]), + ]; + } else { + $matched[] = [ + 'timestamp' => '-', + 'level' => $level, + 'source' => 'syslog', + 'message' => $this->truncateLogMessage($line), + ]; + } + } + + return array_slice(array_reverse($matched), 0, $limit); + } + + /** + * Normalize whitespace and truncate long log messages cleanly for terminal tables. + */ + protected function truncateLogMessage(string $message, int $maxLength = 90): string + { + $clean = trim((string) preg_replace('/\s+/', ' ', $message)); + if ($clean === '') { + return '-'; + } + + if (mb_strlen($clean) <= $maxLength) { + return $clean; + } + + return rtrim(mb_substr($clean, 0, $maxLength - 3)) . '...'; + } } diff --git a/app/Drivers/WindowsDriver.php b/app/Drivers/WindowsDriver.php index 81908db..96eb920 100644 --- a/app/Drivers/WindowsDriver.php +++ b/app/Drivers/WindowsDriver.php @@ -264,6 +264,73 @@ public function killProcess(int $pid): ActionResult ); } + /** + * {@inheritDoc} + */ + public function getCriticalLogs(int $limit = 15): ActionResult + { + $safeLimit = max(1, $limit); + + $script = sprintf( + <<<'PS' +$ErrorActionPreference = 'SilentlyContinue'; +$events = @(Get-WinEvent -FilterHashtable @{LogName='System','Application'; Level=1,2; StartTime=(Get-Date).AddHours(-24)} -MaxEvents %d -ErrorAction SilentlyContinue | Select-Object TimeCreated, Id, ProviderName, Level, LevelDisplayName, Message | ForEach-Object { + $timeStr = if ($_.TimeCreated -is [DateTime]) { $_.TimeCreated.ToString('yyyy-MM-dd HH:mm:ss') } else { [string]$_.TimeCreated }; + [PSCustomObject]@{ + TimeCreated = [string]$timeStr; + Id = [string]$_.Id; + ProviderName = [string]$_.ProviderName; + Level = [int]($_.Level -as [int]); + LevelDisplayName = [string]$_.LevelDisplayName; + Message = [string](($_.Message -replace '[\r\n\t]+', ' ').Trim()) + } +}); +if ($events.Count -eq 0) { + Write-Output '[]'; +} else { + $events | ConvertTo-Json -Compress +} +PS, + $safeLimit + ); + + $items = $this->normalizeJsonList($this->runPowerShellJson($script)); + + $events = []; + foreach ($items as $item) { + if (! is_array($item) || $item === []) { + continue; + } + + $levelInt = (int) ($item['Level'] ?? 2); + $levelDisplay = strtolower(trim((string) ($item['LevelDisplayName'] ?? ''))); + $levelLabel = ($levelInt === 1 || str_contains($levelDisplay, 'crit')) ? 'CRITICAL' : 'ERROR'; + + $provider = trim((string) ($item['ProviderName'] ?? 'System')); + $eventId = trim((string) ($item['Id'] ?? '')); + $source = $eventId !== '' ? sprintf('%s (ID %s)', $provider, $eventId) : $provider; + + $events[] = [ + 'timestamp' => trim((string) ($item['TimeCreated'] ?? '-')) ?: '-', + 'level' => $levelLabel, + 'source' => $source !== '' ? $source : 'System', + 'message' => $this->truncateLogMessage((string) ($item['Message'] ?? '-')), + ]; + } + + $events = array_slice($events, 0, $safeLimit); + + return new ActionResult( + success: true, + message: $events !== [] ? 'messages.logs.fetched_success' : 'messages.logs.no_logs', + details: [ + 'events' => $events, + 'count' => count($events), + 'driver' => 'Windows', + ], + ); + } + /** * {@inheritDoc} */ @@ -801,4 +868,21 @@ protected function normalizeConsoleOutput(string $output): string return implode(' | ', $lines); } + + /** + * Normalize whitespace and truncate long event log messages cleanly for terminal tables. + */ + protected function truncateLogMessage(string $message, int $maxLength = 90): string + { + $clean = trim((string) preg_replace('/\s+/', ' ', $message)); + if ($clean === '') { + return '-'; + } + + if (mb_strlen($clean) <= $maxLength) { + return $clean; + } + + return rtrim(mb_substr($clean, 0, $maxLength - 3)) . '...'; + } } diff --git a/app/Services/HealthCheckService.php b/app/Services/HealthCheckService.php new file mode 100644 index 0000000..02ba5db --- /dev/null +++ b/app/Services/HealthCheckService.php @@ -0,0 +1,296 @@ +, + * recommendations: array + * } + */ + public function runAudit(): array + { + $score = 100; + $checks = []; + $recommendations = []; + + $hardware = $this->driver->getHardwareDiagnostics(); + $storage = $this->driver->getStorageHealth(); + $connectivity = $this->driver->runConnectivityHealthCheck(); + $printers = $this->driver->listPrinters(); + $logsResult = $this->driver->getCriticalLogs(10); + + // 1. RAM Usage Audit + $ramPercent = $this->extractPercentage($hardware['ram_used'] ?? '0%'); + $ramPenalty = 0; + $ramIcon = '✅'; + $ramStatus = (string) __('messages.health.states.healthy'); + + if ($ramPercent > 95.0) { + $ramPenalty = 25; + $ramIcon = '❌'; + $ramStatus = (string) __('messages.health.states.critical'); + $recommendations[] = (string) __('messages.health.recommendations.high_ram'); + } elseif ($ramPercent > 85.0) { + $ramPenalty = 15; + $ramIcon = '⚠️'; + $ramStatus = (string) __('messages.health.states.warning'); + $recommendations[] = (string) __('messages.health.recommendations.high_ram'); + } + + $score -= $ramPenalty; + $checks[] = [ + 'category' => (string) __('messages.health.categories.ram'), + 'icon' => $ramIcon, + 'status' => $ramStatus, + 'summary' => (string) ($hardware['ram_used'] ?? 'N/A'), + 'penalty' => $ramPenalty, + ]; + + // 2. Storage (Disks) Audit + $diskPenalty = 0; + $maxDiskPercent = 0.0; + $diskSummaries = []; + + foreach ($storage as $disk) { + $pct = $this->extractPercentage($disk['usage_percent'] ?? '0%'); + $maxDiskPercent = max($maxDiskPercent, $pct); + $diskSummaries[] = sprintf('%s: %.1f%%', $disk['mount'] ?? ($disk['filesystem'] ?? 'Disk'), $pct); + + if ($pct > 95.0) { + $diskPenalty += 25; + } elseif ($pct > 85.0) { + $diskPenalty += 15; + } + } + + $diskIcon = '✅'; + $diskStatus = (string) __('messages.health.states.healthy'); + if ($maxDiskPercent > 95.0) { + $diskIcon = '❌'; + $diskStatus = (string) __('messages.health.states.critical'); + $recommendations[] = (string) __('messages.health.recommendations.high_disk'); + } elseif ($maxDiskPercent > 85.0) { + $diskIcon = '⚠️'; + $diskStatus = (string) __('messages.health.states.warning'); + $recommendations[] = (string) __('messages.health.recommendations.high_disk'); + } + + $score -= $diskPenalty; + $checks[] = [ + 'category' => (string) __('messages.health.categories.storage'), + 'icon' => $diskIcon, + 'status' => $diskStatus, + 'summary' => $diskSummaries !== [] ? implode(', ', $diskSummaries) : 'N/A', + 'penalty' => $diskPenalty, + ]; + + // 3. Connectivity & DNS Audit + $netPenalty = 0; + $internetOk = true; + $dnsOk = true; + + if ($connectivity === []) { + $internetOk = false; + $dnsOk = false; + } else { + foreach ($connectivity as $step) { + $checkType = strtolower((string) ($step['check'] ?? '')); + $target = strtolower((string) ($step['target'] ?? '')); + $isStepOk = strtoupper((string) ($step['status'] ?? 'FAIL')) === 'OK'; + + if (str_contains($checkType, 'dns') || str_contains($target, 'google.com') || str_contains($target, 'cloudflare.com')) { + if (! $isStepOk) { + $dnsOk = false; + } + } elseif (str_contains($checkType, 'external') || str_contains($target, '1.1.1.1') || str_contains($target, '8.8.8.8')) { + if (! $isStepOk) { + $internetOk = false; + } + } + } + } + + if (! $internetOk) { + $netPenalty += 25; + $recommendations[] = (string) __('messages.health.recommendations.no_internet'); + } + + if (! $dnsOk) { + $netPenalty += 15; + $recommendations[] = (string) __('messages.health.recommendations.dns_failed'); + } + + $netIcon = '✅'; + $netStatus = (string) __('messages.health.states.healthy'); + if (! $internetOk) { + $netIcon = '❌'; + $netStatus = (string) __('messages.health.states.critical'); + } elseif (! $dnsOk) { + $netIcon = '⚠️'; + $netStatus = (string) __('messages.health.states.warning'); + } + + $score -= $netPenalty; + $checks[] = [ + 'category' => (string) __('messages.health.categories.network'), + 'icon' => $netIcon, + 'status' => $netStatus, + 'summary' => sprintf( + 'Internet: %s | DNS: %s', + $internetOk ? 'OK' : 'FAIL', + $dnsOk ? 'OK' : 'FAIL' + ), + 'penalty' => $netPenalty, + ]; + + // 4. Print Queue & Spooler Audit + $printerPenalty = 0; + $printerIcon = '✅'; + $printerStatus = (string) __('messages.health.states.healthy'); + $printerSummary = (string) __('messages.printer.no_printers'); + + if ($printers !== []) { + $hasIssue = false; + $totalJobs = 0; + + foreach ($printers as $printer) { + $jobs = (int) ($printer['jobs'] ?? 0); + $totalJobs += $jobs; + $statusLower = strtolower((string) ($printer['status'] ?? '')); + + if ($jobs > 0 + || str_contains($statusLower, 'error') + || str_contains($statusLower, 'jam') + || str_contains($statusLower, 'offline') + || str_contains($statusLower, 'paused') + || str_contains($statusLower, 'disabled') + || str_contains($statusLower, 'stopped')) { + $hasIssue = true; + } + } + + $printerSummary = sprintf('%d printers (%d pending jobs)', count($printers), $totalJobs); + + if ($hasIssue) { + $printerPenalty = 10; + $printerIcon = '⚠️'; + $printerStatus = (string) __('messages.health.states.warning'); + $recommendations[] = (string) __('messages.health.recommendations.printer_issue'); + } + } + + $score -= $printerPenalty; + $checks[] = [ + 'category' => (string) __('messages.health.categories.printers'), + 'icon' => $printerIcon, + 'status' => $printerStatus, + 'summary' => $printerSummary, + 'penalty' => $printerPenalty, + ]; + + // 5. Critical OS Logs (last 24h) Audit + $logEvents = isset($logsResult->details['events']) && is_array($logsResult->details['events']) + ? $logsResult->details['events'] + : []; + $logCount = count($logEvents); + $logPenalty = 0; + $logIcon = '✅'; + $logStatus = (string) __('messages.health.states.healthy'); + + if ($logCount > 5) { + $logPenalty = 15; + $logIcon = '❌'; + $logStatus = (string) __('messages.health.states.critical'); + $recommendations[] = (string) __('messages.health.recommendations.critical_logs'); + } elseif ($logCount >= 1) { + $logPenalty = 5; + $logIcon = '⚠️'; + $logStatus = (string) __('messages.health.states.warning'); + $recommendations[] = (string) __('messages.health.recommendations.critical_logs'); + } + + $score -= $logPenalty; + $checks[] = [ + 'category' => (string) __('messages.health.categories.logs'), + 'icon' => $logIcon, + 'status' => $logStatus, + 'summary' => (string) __('messages.health.logs_count_summary', ['count' => $logCount]), + 'penalty' => $logPenalty, + ]; + + $finalScore = max(0, min(100, $score)); + $state = $this->classifyScore($finalScore); + $stateLabel = (string) __("messages.health.states.{$state}"); + + return [ + 'score' => $finalScore, + 'state' => $state, + 'state_label' => $stateLabel, + 'progress_bar' => $this->buildProgressBar($finalScore), + 'checks' => $checks, + 'recommendations' => array_values(array_unique($recommendations)), + ]; + } + + /** + * Classify a 0-100 health score into 'healthy' (80-100), 'warning' (50-79), or 'critical' (0-49). + */ + public function classifyScore(int $score): string + { + if ($score >= 80) { + return 'healthy'; + } + + if ($score >= 50) { + return 'warning'; + } + + return 'critical'; + } + + /** + * Extract a float percentage from a formatted string such as "12.40 GB (88.5%)" or "⚠️ 90.0% [HIGH]". + */ + protected function extractPercentage(string $value): float + { + if (preg_match('/([\d.]+)\s*%/', $value, $matches) === 1) { + return (float) $matches[1]; + } + + return 0.0; + } + + /** + * Build a 20-block visual progress bar for the 0-100 score. + */ + protected function buildProgressBar(int $score): string + { + $totalBlocks = 20; + $filledBlocks = (int) round(($score / 100) * $totalBlocks); + $emptyBlocks = max(0, $totalBlocks - $filledBlocks); + + return sprintf( + '[%s%s] %d/100', + str_repeat('█', $filledBlocks), + str_repeat('░', $emptyBlocks), + $score + ); + } +} diff --git a/app/Services/ReportExporterService.php b/app/Services/ReportExporterService.php index 17dcb26..db9898d 100644 --- a/app/Services/ReportExporterService.php +++ b/app/Services/ReportExporterService.php @@ -52,12 +52,14 @@ public function collectDiagnostics(?string $locale = null): array * @param string|null $outputDirectory Target directory (defaults to current working directory) * @param string|null $locale Target locale ('en' or 'pt_BR') * @param string|null $timestamp Optional fixed timestamp in 'Y-m-d-His' format + * @param array|null $healthAudit Optional health check score & recommendations payload */ public function export( string $format = 'both', ?string $outputDirectory = null, ?string $locale = null, ?string $timestamp = null, + ?array $healthAudit = null, ): ActionResult { $activeLocale = $locale ?? (app()->getLocale() ?: 'en'); app()->setLocale($activeLocale); @@ -78,6 +80,9 @@ public function export( $baseFilename = sprintf('it-toolbox-report-%s', $stamp); $data = $this->collectDiagnostics($activeLocale); + if ($healthAudit !== null) { + $data['health_audit'] = $healthAudit; + } $writtenFiles = []; if ($normalizedFormat === 'md' || $normalizedFormat === 'both') { @@ -136,12 +141,34 @@ public function toMarkdown(array $data, ?string $locale = null): string '', sprintf('- **%s:** `%s`', (string) __('messages.app.detected_os', ['os' => (string) ($data['os_family'] ?? PHP_OS_FAMILY)]), (string) ($data['generated_at'] ?? gmdate('c'))), '', - sprintf('## %s', (string) __('messages.system.os_section')), - '', - sprintf('| %s | %s |', $metricHeader, $valueHeader), - '| :--- | :--- |', ]; + if (isset($data['health_audit']) && is_array($data['health_audit'])) { + $audit = $data['health_audit']; + $lines[] = sprintf('## %s', (string) __('messages.health.section')); + $lines[] = ''; + $lines[] = sprintf( + '- **%s:** `%s` (%s)', + (string) __('messages.health.score_label'), + (string) ($audit['progress_bar'] ?? ($audit['score'] ?? 100)), + (string) ($audit['state_label'] ?? '') + ); + + if (! empty($audit['recommendations']) && is_array($audit['recommendations'])) { + $lines[] = ''; + $lines[] = sprintf('### %s', (string) __('messages.health.recommendations_title')); + foreach ($audit['recommendations'] as $rec) { + $lines[] = sprintf('- %s', (string) $rec); + } + } + $lines[] = ''; + } + + $lines[] = sprintf('## %s', (string) __('messages.system.os_section')); + $lines[] = ''; + $lines[] = sprintf('| %s | %s |', $metricHeader, $valueHeader); + $lines[] = '| :--- | :--- |'; + foreach ((array) ($data['os_info'] ?? []) as $key => $value) { $labelKey = "messages.system.fields.{$key}"; $label = (string) __($labelKey); diff --git a/app/Services/SelfUpdateService.php b/app/Services/SelfUpdateService.php new file mode 100644 index 0000000..7d088f2 --- /dev/null +++ b/app/Services/SelfUpdateService.php @@ -0,0 +1,377 @@ +normalizeVersion($this->getCurrentVersion()); + $targetAsset = $this->resolveTargetAssetName(); + + $rawResponse = $this->fetchUrl(self::GITHUB_LATEST_RELEASE_URL); + if ($rawResponse === null || $rawResponse === '') { + return [ + 'success' => false, + 'update_available' => false, + 'current_version' => $current, + 'latest_version' => $current, + 'asset_name' => $targetAsset, + 'download_url' => null, + 'release_url' => null, + 'error' => 'Failed to reach GitHub Releases API.', + ]; + } + + $decoded = json_decode($rawResponse, true); + if (! is_array($decoded) || ! isset($decoded['tag_name'])) { + return [ + 'success' => false, + 'update_available' => false, + 'current_version' => $current, + 'latest_version' => $current, + 'asset_name' => $targetAsset, + 'download_url' => null, + 'release_url' => null, + 'error' => 'Invalid response payload from GitHub Releases API.', + ]; + } + + $latest = $this->normalizeVersion((string) $decoded['tag_name']); + $updateAvailable = $this->isNewerVersion($current, $latest); + $downloadUrl = $targetAsset !== null + ? $this->findAssetDownloadUrl((array) ($decoded['assets'] ?? []), $targetAsset) + : null; + + return [ + 'success' => true, + 'update_available' => $updateAvailable, + 'current_version' => $current, + 'latest_version' => $latest, + 'asset_name' => $targetAsset, + 'download_url' => $downloadUrl, + 'release_url' => isset($decoded['html_url']) ? (string) $decoded['html_url'] : null, + 'error' => null, + ]; + } + + /** + * Download the appropriate release artifact and atomically replace the current executable. + */ + public function performUpdate(): ActionResult + { + $binaryPath = $this->getRunningBinaryPath(); + if ($binaryPath === '') { + return new ActionResult( + success: false, + message: 'messages.update.source_mode_warning', + details: [ + 'current_version' => $this->normalizeVersion($this->getCurrentVersion()), + ], + ); + } + + $check = $this->checkForUpdates(); + if (! $check['success']) { + return new ActionResult( + success: false, + message: 'messages.update.check_failed', + details: [ + 'error' => (string) ($check['error'] ?? 'API request failed'), + ], + ); + } + + if (! $check['update_available']) { + return new ActionResult( + success: true, + message: 'messages.update.up_to_date', + details: [ + 'current_version' => $check['current_version'], + 'latest_version' => $check['latest_version'], + ], + ); + } + + if ($check['download_url'] === null || $check['download_url'] === '') { + return new ActionResult( + success: false, + message: 'messages.update.asset_not_found', + details: [ + 'latest_version' => $check['latest_version'], + 'asset_name' => (string) ($check['asset_name'] ?? 'unknown'), + ], + ); + } + + $binaryContent = $this->fetchUrl($check['download_url']); + if ($binaryContent === null || $binaryContent === '') { + return new ActionResult( + success: false, + message: 'messages.update.download_failed', + details: [ + 'download_url' => $check['download_url'], + ], + ); + } + + $tempPath = $binaryPath . '.download.tmp'; + $written = @file_put_contents($tempPath, $binaryContent); + if ($written === false || $written <= 0) { + @unlink($tempPath); + + return new ActionResult( + success: false, + message: 'messages.update.replace_failed', + details: [ + 'paths' => [$binaryPath], + ], + ); + } + + @chmod($tempPath, 0755); + + $os = $this->osFamily ?? PHP_OS_FAMILY; + $replaced = $this->replaceBinaryAtomically($tempPath, $binaryPath, $os); + + if (! $replaced) { + @unlink($tempPath); + + return new ActionResult( + success: false, + message: 'messages.update.replace_failed', + details: [ + 'paths' => [$binaryPath], + ], + ); + } + + return new ActionResult( + success: true, + message: 'messages.update.updated_success', + details: [ + 'previous_version' => $check['current_version'], + 'new_version' => $check['latest_version'], + 'asset_name' => (string) $check['asset_name'], + 'paths' => [$binaryPath], + ], + ); + } + + /** + * Compare two semantic version strings and return true if $latestVersion > $currentVersion. + */ + public function isNewerVersion(string $currentVersion, string $latestVersion): bool + { + $cleanCurrent = $this->normalizeVersion($currentVersion); + $cleanLatest = $this->normalizeVersion($latestVersion); + + return version_compare($cleanLatest, $cleanCurrent, '>'); + } + + /** + * Resolve which release artifact should be downloaded for the current runtime environment. + * Returns null when running directly from unpacked source code. + */ + public function resolveTargetAssetName(?string $binaryPath = null, ?string $osFamily = null): ?string + { + $path = $binaryPath ?? $this->getRunningBinaryPath(); + if ($path === '') { + return null; + } + + $os = $osFamily ?? $this->osFamily ?? PHP_OS_FAMILY; + $lowerBase = strtolower(basename($path)); + + if (str_ends_with($lowerBase, '.exe')) { + return 'it-toolbox-windows-x64.exe'; + } + + if (str_ends_with($lowerBase, '.phar')) { + return 'it-toolbox'; + } + + if (str_contains($lowerBase, 'linux-x64') || str_contains($lowerBase, 'linux')) { + return 'it-toolbox-linux-x64'; + } + + if (str_contains($lowerBase, 'windows-x64')) { + return 'it-toolbox-windows-x64.exe'; + } + + // Inspect file header if accessible on disk: ELF binary -> Linux standalone, MZ -> Windows standalone + if (is_file($path) && is_readable($path)) { + $header = (string) @file_get_contents($path, false, null, 0, 4); + if (str_starts_with($header, "\x7fELF")) { + return 'it-toolbox-linux-x64'; + } + if (str_starts_with($header, 'MZ')) { + return 'it-toolbox-windows-x64.exe'; + } + } + + if ($os === 'Windows' && ! str_ends_with($lowerBase, 'it-toolbox')) { + return 'it-toolbox-windows-x64.exe'; + } + + return 'it-toolbox'; + } + + /** + * Normalize a version tag (e.g. "v1.2.0" -> "1.2.0"). + */ + public function normalizeVersion(string $version): string + { + return ltrim(trim($version), 'vV'); + } + + /** + * Get the currently configured application version. + */ + protected function getCurrentVersion(): string + { + if ($this->currentVersion !== null) { + return $this->currentVersion; + } + + if (function_exists('config')) { + return (string) config('app.version', '1.2.0'); + } + + return '1.2.0'; + } + + /** + * Determine the filesystem path of the running PHAR / standalone binary. + * Returns an empty string when running from unpacked PHP source files. + */ + protected function getRunningBinaryPath(): string + { + if ($this->runningBinaryPath !== null) { + return $this->runningBinaryPath; + } + + return Phar::running(false); + } + + /** + * Locate the browser_download_url for the specified asset name in the GitHub release payload. + * + * @param array $assets + */ + protected function findAssetDownloadUrl(array $assets, string $targetAssetName): ?string + { + foreach ($assets as $asset) { + if (! is_array($asset)) { + continue; + } + + if (($asset['name'] ?? '') === $targetAssetName && isset($asset['browser_download_url'])) { + return (string) $asset['browser_download_url']; + } + } + + return null; + } + + /** + * Replace the current executable with the downloaded temporary file. + * On Windows, renames the locked running binary to `.old` before moving the new binary into place. + */ + protected function replaceBinaryAtomically(string $tempPath, string $targetPath, string $osFamily): bool + { + if ($osFamily === 'Windows' || str_ends_with(strtolower($targetPath), '.exe')) { + $oldBackupPath = $targetPath . '.old'; + if (is_file($oldBackupPath)) { + @unlink($oldBackupPath); + } + + if (is_file($targetPath) && ! @rename($targetPath, $oldBackupPath)) { + return false; + } + + if (! @rename($tempPath, $targetPath)) { + // Attempt rollback if moving the new binary failed + if (is_file($oldBackupPath) && ! is_file($targetPath)) { + @rename($oldBackupPath, $targetPath); + } + + return false; + } + + return true; + } + + return @rename($tempPath, $targetPath); + } + + /** + * Perform an HTTPS GET request using the injected test fetcher or PHP's native stream context. + */ + protected function fetchUrl(string $url): ?string + { + if ($this->httpFetcher !== null) { + return ($this->httpFetcher)($url); + } + + $context = stream_context_create([ + 'http' => [ + 'method' => 'GET', + 'header' => implode("\r\n", [ + 'User-Agent: it-toolbox-cli', + 'Accept: application/vnd.github+json', + ]), + 'timeout' => 20, + 'follow_location' => 1, + ], + 'ssl' => [ + 'verify_peer' => true, + 'verify_peer_name' => true, + ], + ]); + + try { + $response = @file_get_contents($url, false, $context); + + return $response === false ? null : $response; + } catch (Throwable) { + return null; + } + } +} diff --git a/config/app.php b/config/app.php index e6715b1..56d2fb5 100644 --- a/config/app.php +++ b/config/app.php @@ -28,7 +28,7 @@ | */ - 'version' => '1.0.0', + 'version' => '1.2.0', /* |-------------------------------------------------------------------------- diff --git a/lang/en/messages.php b/lang/en/messages.php index 4669079..c4377d3 100644 --- a/lang/en/messages.php +++ b/lang/en/messages.php @@ -30,16 +30,19 @@ 'back' => '← Back to Main Menu', 'exit' => '✖ Exit IT Toolbox', 'categories' => [ + 'health_check' => '🩺 Full Health Check & Machine Score (health:check)', 'system' => '🖥 System & Hardware Diagnostics', 'printers' => '🖨 Printers & Spooler Management', 'network' => '🌐 Network & Connectivity Diagnostics', 'maintenance' => '🧹 System Maintenance & Cleanup', 'reports' => '📄 Export Diagnostic Report', + 'self_update' => '⬆️ Check for Updates (self:update)', 'language' => '🌍 Switch Language (EN / PT-BR)', ], 'actions' => [ '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)', '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)', @@ -63,8 +66,10 @@ ], 'spinners' => [ + 'health_check' => 'Running full system health audit and calculating score...', '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...', 'killing_process' => 'Terminating process PID :pid...', 'printer_list' => 'Querying installed printers and spooler status...', 'printer_clear' => 'Stopping spooler, purging queue, and restarting service...', @@ -73,6 +78,8 @@ 'network_ports' => 'Scanning active listening TCP/UDP ports...', 'clean_temp' => 'Scanning and removing temporary files safely...', 'report_export' => 'Generating full diagnostic report...', + 'self_update_check' => 'Checking GitHub Releases for newer versions...', + 'self_update_download' => 'Downloading and installing update v:version...', ], 'system' => [ @@ -116,6 +123,66 @@ 'process_killed_failed' => 'Failed to terminate the selected process.', ], + 'logs' => [ + 'section' => 'Critical OS Logs & Recent Errors (Last 24 Hours)', + 'fetched_success' => 'Critical OS log events retrieved successfully.', + 'no_logs' => 'No critical or error events recorded in the last 24 hours.', + 'headers' => [ + 'timestamp' => 'Timestamp', + 'level' => 'Level', + 'source' => 'Source / Service', + 'message' => 'Message Summary', + ], + ], + + 'health' => [ + 'section' => 'Machine Health Check & Diagnostic Score', + 'score_label' => 'Health Score', + 'states' => [ + 'healthy' => 'Healthy', + 'warning' => 'Warning', + 'critical' => 'Critical', + ], + 'categories' => [ + 'ram' => 'Memory (RAM)', + 'storage' => 'Disk Storage', + 'network' => 'Connectivity & DNS', + 'printers' => 'Print Spooler & Queue', + 'logs' => 'Critical OS Logs (24h)', + ], + 'headers' => [ + 'category' => 'Audit Category', + 'status' => 'State', + 'summary' => 'Observed Metrics', + 'impact' => 'Score Impact', + ], + 'logs_count_summary' => ':count critical/error events in the last 24h', + 'recommendations_title' => 'Recommended Corrective Actions:', + 'no_recommendations' => 'All health checks passed with zero issues detected.', + 'ask_export' => 'Would you like to export this health check and full diagnostic snapshot (MD + JSON)?', + 'recommendations' => [ + 'high_ram' => 'High memory usage detected. Run "system:top" to inspect and terminate memory-heavy processes.', + 'high_disk' => 'Disk usage exceeds 85%. Run "clean:temp" to free up temporary disk space.', + 'no_internet' => 'External internet connectivity failed. Run "network:check" to verify physical adapter and gateway.', + 'dns_failed' => 'DNS resolution failed. Run "network:flush" to flush DNS cache and renew network configuration.', + 'printer_issue' => 'Pending or stalled print jobs detected. Run "printer:clear" to restart the Print Spooler / CUPS queue.', + 'critical_logs' => 'Recent critical OS errors found. Run "system:logs" to inspect event details and failing services.', + ], + ], + + 'update' => [ + 'section' => 'IT Toolbox CLI Self-Update', + 'up_to_date' => 'You are already running the latest version (v:version).', + 'available' => 'A newer version is available! Current: v:current -> Latest: v:latest', + 'confirm_download' => 'Download and install v:version (:asset) now?', + 'updated_success' => 'IT Toolbox CLI has been updated successfully!', + 'check_failed' => 'Unable to check for updates from GitHub Releases. Verify your internet connection.', + 'asset_not_found' => 'Release artifact could not be found in the latest GitHub Release.', + 'download_failed' => 'Failed to download the release binary from GitHub.', + 'replace_failed' => 'Failed to replace the current executable. Check file write permissions.', + 'source_mode_warning' => 'Running from unpacked source code in development mode. Please use "git pull && composer install" to update.', + ], + 'printer' => [ 'list_section' => 'Installed Printers & Spooler Status', 'headers' => [ @@ -181,6 +248,13 @@ 'commands_executed' => 'Commands Executed', 'output' => 'Command Output', 'error' => 'Error Details', + 'current_version' => 'Current Version', + 'latest_version' => 'Latest Version', + 'previous_version' => 'Previous Version', + 'new_version' => 'Updated Version', + 'asset_name' => 'Release Artifact', + 'download_url' => 'Download URL', + 'count' => 'Event Count', ], ], diff --git a/lang/pt_BR/messages.php b/lang/pt_BR/messages.php index 8912a92..648a732 100644 --- a/lang/pt_BR/messages.php +++ b/lang/pt_BR/messages.php @@ -30,16 +30,19 @@ 'back' => '← Voltar ao Menu Principal', 'exit' => '✖ Sair do IT Toolbox', 'categories' => [ + 'health_check' => '🩺 Check-up Geral & Score de Saúde (health:check)', 'system' => '🖥 Diagnóstico de Sistema & Hardware', 'printers' => '🖨 Impressoras & Spooler', 'network' => '🌐 Rede & Conectividade', 'maintenance' => '🧹 Limpeza & Manutenção', 'reports' => '📄 Exportar Relatório de Atendimento', + 'self_update' => '⬆️ Verificar Atualizações (self:update)', 'language' => '🌍 Alterar Idioma (EN / PT-BR)', ], 'actions' => [ '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)', '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)', @@ -63,8 +66,10 @@ ], 'spinners' => [ + 'health_check' => 'Executando auditoria completa de saúde e calculando score...', '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...', '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...', @@ -73,6 +78,8 @@ 'network_ports' => 'Escaneando portas TCP/UDP ativas em escuta...', '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...', + 'self_update_download' => 'Baixando e instalando atualização v:version...', ], 'system' => [ @@ -116,6 +123,66 @@ 'process_killed_failed' => 'Falha ao encerrar o processo selecionado.', ], + 'logs' => [ + 'section' => 'Logs Críticos do SO & Erros Recentes (Últimas 24 Horas)', + 'fetched_success' => 'Eventos críticos de log do SO coletados com sucesso.', + 'no_logs' => 'Nenhum evento crítico ou erro registrado nas últimas 24 horas.', + 'headers' => [ + 'timestamp' => 'Data / Hora', + 'level' => 'Nível', + 'source' => 'Origem / Serviço', + 'message' => 'Resumo da Mensagem', + ], + ], + + 'health' => [ + 'section' => 'Check-up Geral & Score de Saúde da Máquina', + 'score_label' => 'Score de Saúde', + 'states' => [ + 'healthy' => 'Saudável', + 'warning' => 'Atenção', + 'critical' => 'Crítico', + ], + 'categories' => [ + 'ram' => 'Memória (RAM)', + 'storage' => 'Armazenamento (Discos)', + 'network' => 'Conectividade & DNS', + 'printers' => 'Spooler & Fila de Impressão', + 'logs' => 'Logs Críticos do SO (24h)', + ], + 'headers' => [ + 'category' => 'Categoria Auditada', + 'status' => 'Estado', + 'summary' => 'Métricas Observadas', + 'impact' => 'Impacto no Score', + ], + 'logs_count_summary' => ':count eventos críticos/erros nas últimas 24h', + 'recommendations_title' => 'Recomendações Práticas de Ação:', + 'no_recommendations' => 'Todos os testes de integridade passaram sem problemas detectados.', + 'ask_export' => 'Deseja exportar este check-up e o relatório completo de diagnóstico (MD + JSON)?', + 'recommendations' => [ + 'high_ram' => 'Alto consumo de memória detectado. Execute "system:top" para inspecionar e encerrar processos pesados.', + 'high_disk' => 'Uso de disco acima de 85%. Execute "clean:temp" para liberar espaço de arquivos temporários.', + 'no_internet' => 'Sem conectividade externa à internet. Execute "network:check" para verificar adaptador e gateway.', + 'dns_failed' => 'Falha de resolução DNS detectada. Execute "network:flush" para limpar o cache DNS e renovar a rede.', + 'printer_issue' => 'Trabalhos de impressão retidos ou erro no spooler. Execute "printer:clear" para reiniciar a fila.', + 'critical_logs' => 'Erros críticos recentes encontrados no SO. Execute "system:logs" para investigar os serviços afetados.', + ], + ], + + 'update' => [ + 'section' => 'Auto-Atualização do IT Toolbox CLI', + 'up_to_date' => 'Você já está utilizando a versão mais recente (v:version).', + 'available' => 'Nova versão disponível! Atual: v:current -> Mais recente: v:latest', + 'confirm_download' => 'Deseja baixar e instalar a versão v:version (:asset) agora?', + 'updated_success' => 'O IT Toolbox CLI foi atualizado com sucesso!', + 'check_failed' => 'Não foi possível verificar atualizações no GitHub Releases. Verifique sua conexão.', + 'asset_not_found' => 'O artefato correspondente à sua plataforma não foi encontrado na última Release.', + 'download_failed' => 'Falha ao baixar o binário atualizado do GitHub.', + 'replace_failed' => 'Falha ao substituir o executável atual. Verifique as permissões de escrita.', + 'source_mode_warning' => 'Executando via código-fonte em modo de desenvolvimento. Utilize "git pull && composer install" para atualizar.', + ], + 'printer' => [ 'list_section' => 'Impressoras Instaladas e Status do Spooler', 'headers' => [ @@ -181,6 +248,13 @@ 'commands_executed' => 'Comandos Executados', 'output' => 'Saída do Comando', 'error' => 'Detalhes do Erro', + 'current_version' => 'Versão Atual', + 'latest_version' => 'Versão Mais Recente', + 'previous_version' => 'Versão Anterior', + 'new_version' => 'Versão Instalada', + 'asset_name' => 'Artefato da Release', + 'download_url' => 'URL de Download', + 'count' => 'Total de Eventos', ], ], diff --git a/tests/Feature/ReportExporterTest.php b/tests/Feature/ReportExporterTest.php index de14381..f716249 100644 --- a/tests/Feature/ReportExporterTest.php +++ b/tests/Feature/ReportExporterTest.php @@ -57,6 +57,11 @@ public function killProcess(int $pid): 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 listPrinters(): array { return [ diff --git a/tests/Unit/HealthCheckServiceTest.php b/tests/Unit/HealthCheckServiceTest.php new file mode 100644 index 0000000..67e2c25 --- /dev/null +++ b/tests/Unit/HealthCheckServiceTest.php @@ -0,0 +1,165 @@ +> $storage + * @param array> $connectivity + * @param array> $printers + * @param int $criticalLogCount + */ +function makeHealthDriver( + string $ramUsed = '8.00 GB (40.0%)', + array $storage = [['filesystem' => 'C:', 'total' => '500 GB', 'used' => '200 GB', 'available' => '300 GB', 'usage_percent' => '40.0%', 'mount' => 'C:\\']], + array $connectivity = [ + ['target' => '1.1.1.1 (Cloudflare)', 'check' => 'External Ping', 'status' => 'OK', 'latency' => '10 ms'], + ['target' => 'google.com', 'check' => 'DNS Resolution', 'status' => 'OK', 'latency' => '12 ms'], + ], + array $printers = [ + ['name' => 'Office_Printer', 'status' => 'Normal (0 jobs)', 'default' => 'Yes', 'driver' => 'PCL6', 'port' => 'IP', 'jobs' => '0'], + ], + int $criticalLogCount = 0, +): SystemDriverInterface { + return new class($ramUsed, $storage, $connectivity, $printers, $criticalLogCount) implements SystemDriverInterface + { + /** + * @param array> $storage + * @param array> $connectivity + * @param array> $printers + */ + public function __construct( + private readonly string $ramUsed, + private readonly array $storage, + private readonly array $connectivity, + private readonly array $printers, + private readonly int $criticalLogCount, + ) {} + + public function getOsInfo(): array + { + return ['os_name' => 'Test OS', 'os_version' => '1.0', 'kernel' => '1.0', 'architecture' => 'x64', 'hostname' => 'test-host', 'uptime' => '1d']; + } + + public function getHardwareDiagnostics(): array + { + return ['cpu_model' => 'Test CPU', 'cpu_cores' => '8', 'cpu_load' => '10%', 'ram_total' => '20.00 GB', 'ram_used' => $this->ramUsed, 'ram_free' => '12.00 GB']; + } + + public function getStorageHealth(): array + { + return $this->storage; + } + + public function getTopProcesses(int $limit = 10): array + { + return []; + } + + public function killProcess(int $pid): ActionResult + { + return new ActionResult(true, 'ok'); + } + + public function getCriticalLogs(int $limit = 15): ActionResult + { + $events = array_fill(0, $this->criticalLogCount, [ + 'timestamp' => '2026-11-18 10:00:00', + 'level' => 'CRITICAL', + 'source' => 'Kernel', + 'message' => 'Simulated critical error', + ]); + + return new ActionResult(true, 'ok', ['events' => $events, 'count' => count($events)]); + } + + public function listPrinters(): array + { + return $this->printers; + } + + public function clearPrintQueue(): ActionResult + { + return new ActionResult(true, 'ok'); + } + + public function getNetworkInterfaces(): array + { + return []; + } + + public function runConnectivityHealthCheck(): array + { + return $this->connectivity; + } + + public function flushDnsAndRenew(): ActionResult + { + return new ActionResult(true, 'ok'); + } + + public function getListeningPorts(): array + { + return []; + } + + public function cleanTempFiles(): ActionResult + { + return new ActionResult(true, 'ok'); + } + }; +} + +it('calculates a Healthy score (100/100) when all system metrics are optimal', function (): void { + $service = new HealthCheckService(makeHealthDriver()); + $audit = $service->runAudit(); + + expect($audit['score'])->toBe(100) + ->and($audit['state'])->toBe('healthy') + ->and($audit['recommendations'])->toBeEmpty(); +}); + +it('calculates a Warning score (50-79) when RAM > 85%, Disk > 85%, and 2 critical logs exist', function (): void { + // 100 - 15 (RAM 88%) - 15 (Disk 89%) - 5 (2 critical logs) = 65 (Warning) + $driver = makeHealthDriver( + ramUsed: '17.60 GB (88.0%)', + storage: [['filesystem' => 'C:', 'total' => '500 GB', 'used' => '445 GB', 'available' => '55 GB', 'usage_percent' => '⚠️ 89.0% [HIGH]', 'mount' => 'C:\\']], + criticalLogCount: 2, + ); + + $service = new HealthCheckService($driver); + $audit = $service->runAudit(); + + expect($audit['score'])->toBe(65) + ->and($audit['state'])->toBe('warning') + ->and($audit['recommendations'])->toHaveCount(3); +}); + +it('calculates a Critical score (0-49) and enforces 0 minimum floor when severe failures occur', function (): void { + // 100 - 25 (RAM 97%) - 25 (Disk 98%) - 25 (No Internet) - 15 (DNS Fail) - 10 (Printer Error) - 15 (8 Critical Logs) = -15 -> clamped to 0 + $driver = makeHealthDriver( + ramUsed: '19.40 GB (97.0%)', + storage: [['filesystem' => '/', 'total' => '100 GB', 'used' => '98 GB', 'available' => '2 GB', 'usage_percent' => '⚠️ 98.0% [HIGH]', 'mount' => '/']], + connectivity: [ + ['target' => '1.1.1.1 (Cloudflare)', 'check' => 'External Ping', 'status' => 'FAIL', 'latency' => '-'], + ['target' => 'google.com', 'check' => 'DNS Resolution', 'status' => 'FAIL', 'latency' => '-'], + ], + printers: [ + ['name' => 'HP_Laser', 'status' => 'Error (3 jobs)', 'default' => 'Yes', 'driver' => 'CUPS', 'port' => 'ipp', 'jobs' => '3'], + ], + criticalLogCount: 8, + ); + + $service = new HealthCheckService($driver); + $audit = $service->runAudit(); + + expect($audit['score'])->toBe(0) + ->and($audit['state'])->toBe('critical') + ->and($audit['recommendations'])->not->toBeEmpty(); +}); diff --git a/tests/Unit/LinuxDriverTest.php b/tests/Unit/LinuxDriverTest.php index a12f942..3ab8db8 100644 --- a/tests/Unit/LinuxDriverTest.php +++ b/tests/Unit/LinuxDriverTest.php @@ -86,3 +86,61 @@ public function getEffectiveUid(): int ->and($printers[0]['jobs'])->toBe('2') ->and($printers[0]['default'])->toBe('Yes'); }); + +it('parses Linux critical logs from journalctl JSON and falls back to syslog/empty logs cleanly', function (): void { + $executor = new class implements ProcessExecutorInterface + { + public int $callIndex = 0; + + public function run(array $command, int $timeout = 30): ProcessResult + { + $this->callIndex++; + + if ($this->callIndex === 1) { + $line1 = (string) json_encode([ + '__REALTIME_TIMESTAMP' => '1763460000000000', + 'PRIORITY' => '2', + 'SYSLOG_IDENTIFIER' => 'kernel', + 'MESSAGE' => 'EXT4-fs error (device sda1): ext4_find_entry:1455', + ]); + $line2 = (string) json_encode([ + '__REALTIME_TIMESTAMP' => '1763463600000000', + 'PRIORITY' => '3', + 'SYSLOG_IDENTIFIER' => 'sshd', + 'MESSAGE' => 'error: PAM: Authentication failure for root', + ]); + + return new ProcessResult(0, $line1 . "\n" . $line2); + } + + return new ProcessResult(0, '-- No entries --'); + } + + public function readFile(string $path): ?string + { + return null; + } + + public function getEffectiveUid(): int + { + return 0; + } + }; + + $driver = new LinuxDriver($executor); + + $logsResult = $driver->getCriticalLogs(15); + expect($logsResult->success)->toBeTrue() + ->and($logsResult->message)->toBe('messages.logs.fetched_success') + ->and($logsResult->details['count'])->toBe(2) + ->and($logsResult->details['events'][0]['level'])->toBe('CRITICAL') + ->and($logsResult->details['events'][0]['source'])->toBe('kernel') + ->and($logsResult->details['events'][1]['level'])->toBe('ERROR') + ->and($logsResult->details['events'][1]['source'])->toBe('sshd'); + + $emptyResult = $driver->getCriticalLogs(15); + expect($emptyResult->success)->toBeTrue() + ->and($emptyResult->message)->toBe('messages.logs.no_logs') + ->and($emptyResult->details['count'])->toBe(0) + ->and($emptyResult->details['events'])->toBeEmpty(); +}); diff --git a/tests/Unit/SelfUpdateServiceTest.php b/tests/Unit/SelfUpdateServiceTest.php new file mode 100644 index 0000000..8d297bd --- /dev/null +++ b/tests/Unit/SelfUpdateServiceTest.php @@ -0,0 +1,82 @@ +isNewerVersion('1.0.0', 'v1.2.0'))->toBeTrue() + ->and($service->isNewerVersion('v1.2.0', 'v1.2.0'))->toBeFalse() + ->and($service->isNewerVersion('v1.2.0', 'v1.1.9'))->toBeFalse(); +}); + +it('selects the correct GitHub Release artifact by platform and execution mode', function (): void { + $service = new SelfUpdateService(); + + expect($service->resolveTargetAssetName('', 'Linux'))->toBeNull() + ->and($service->resolveTargetAssetName('C:\\Tools\\it-toolbox-windows-x64.exe', 'Windows'))->toBe('it-toolbox-windows-x64.exe') + ->and($service->resolveTargetAssetName('/usr/local/bin/it-toolbox-linux-x64', 'Linux'))->toBe('it-toolbox-linux-x64') + ->and($service->resolveTargetAssetName('/usr/local/bin/it-toolbox.phar', 'Linux'))->toBe('it-toolbox') + ->and($service->resolveTargetAssetName('/usr/local/bin/it-toolbox', 'Linux'))->toBe('it-toolbox'); +}); + +it('returns a friendly git pull warning when attempting self-update in unpacked source mode', function (): void { + $service = new SelfUpdateService( + currentVersion: '1.0.0', + runningBinaryPath: '', + ); + + $result = $service->performUpdate(); + + expect($result->success)->toBeFalse() + ->and($result->message)->toBe('messages.update.source_mode_warning'); +}); + +it('downloads and atomically replaces the executable (with .old backup on Windows)', function (): void { + $tempDir = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'it_toolbox_update_' . uniqid(); + mkdir($tempDir, 0777, true); + $fakeExePath = $tempDir . DIRECTORY_SEPARATOR . 'it-toolbox-windows-x64.exe'; + file_put_contents($fakeExePath, 'OLD_BINARY_PAYLOAD'); + + $fakeReleaseJson = (string) json_encode([ + 'tag_name' => 'v1.3.0', + 'html_url' => 'https://github.com/Dev-lib4n/it-toolbox-cli/releases/tag/v1.3.0', + 'assets' => [ + [ + 'name' => 'it-toolbox-windows-x64.exe', + 'browser_download_url' => 'https://github.com/Dev-lib4n/it-toolbox-cli/releases/download/v1.3.0/it-toolbox-windows-x64.exe', + ], + ], + ]); + + $service = new SelfUpdateService( + httpFetcher: fn (string $url): string => str_contains($url, 'api.github.com') + ? $fakeReleaseJson + : 'NEW_BINARY_PAYLOAD_V1_3_0', + currentVersion: '1.2.0', + runningBinaryPath: $fakeExePath, + osFamily: 'Windows', + ); + + try { + $check = $service->checkForUpdates(); + expect($check['success'])->toBeTrue() + ->and($check['update_available'])->toBeTrue() + ->and($check['latest_version'])->toBe('1.3.0') + ->and($check['asset_name'])->toBe('it-toolbox-windows-x64.exe'); + + $updateResult = $service->performUpdate(); + expect($updateResult->success)->toBeTrue() + ->and($updateResult->message)->toBe('messages.update.updated_success') + ->and(file_get_contents($fakeExePath))->toBe('NEW_BINARY_PAYLOAD_V1_3_0') + ->and(file_exists($fakeExePath . '.old'))->toBeTrue() + ->and(file_get_contents($fakeExePath . '.old'))->toBe('OLD_BINARY_PAYLOAD'); + } finally { + @unlink($fakeExePath); + @unlink($fakeExePath . '.old'); + @unlink($fakeExePath . '.download.tmp'); + @rmdir($tempDir); + } +}); diff --git a/tests/Unit/WindowsDriverTest.php b/tests/Unit/WindowsDriverTest.php index fa339b5..35aafcb 100644 --- a/tests/Unit/WindowsDriverTest.php +++ b/tests/Unit/WindowsDriverTest.php @@ -157,3 +157,63 @@ public function getEffectiveUid(): int ->and($adminResult->message)->toBe('messages.printer.queue_cleared_success') ->and($adminResult->details['deleted_files'])->toBe(4); }); + +it('retrieves critical and error Windows Event Logs and handles empty logs gracefully', 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([ + [ + 'TimeCreated' => '2026-11-18 09:15:00', + 'Id' => '41', + 'ProviderName' => 'Microsoft-Windows-Kernel-Power', + 'Level' => 1, + 'LevelDisplayName' => 'Critical', + 'Message' => 'The system has rebooted without cleanly shutting down first.', + ], + [ + 'TimeCreated' => '2026-11-18 10:30:00', + 'Id' => '1000', + 'ProviderName' => 'Application Error', + 'Level' => 2, + 'LevelDisplayName' => 'Error', + 'Message' => 'Faulting application name: spoolsv.exe', + ], + ])), + default => new ProcessResult(0, '[]'), + }; + } + + public function readFile(string $path): ?string + { + return null; + } + + public function getEffectiveUid(): int + { + return 0; + } + }; + + $driver = new WindowsDriver($executor); + + $logsResult = $driver->getCriticalLogs(15); + expect($logsResult->success)->toBeTrue() + ->and($logsResult->message)->toBe('messages.logs.fetched_success') + ->and($logsResult->details['count'])->toBe(2) + ->and($logsResult->details['events'][0]['level'])->toBe('CRITICAL') + ->and($logsResult->details['events'][0]['source'])->toBe('Microsoft-Windows-Kernel-Power (ID 41)') + ->and($logsResult->details['events'][1]['level'])->toBe('ERROR'); + + $emptyResult = $driver->getCriticalLogs(15); + expect($emptyResult->success)->toBeTrue() + ->and($emptyResult->message)->toBe('messages.logs.no_logs') + ->and($emptyResult->details['count'])->toBe(0) + ->and($emptyResult->details['events'])->toBeEmpty(); +});