Repository: govigilant/vigilant Branch: main Commit: db48e305ec9a Files: 1102 Total size: 1.6 MB Directory structure: gitextract_0yr_cv_n/ ├── .editorconfig ├── .gitattributes ├── .github/ │ └── workflows/ │ ├── code-style.yml │ ├── image.yml │ ├── package-quality.yml │ ├── release-image.yml │ └── tests.yml ├── .gitignore ├── Dockerfile ├── LICENSE.md ├── README.md ├── SECURITY.md ├── app/ │ ├── Console/ │ │ └── Kernel.php │ ├── Exceptions/ │ │ └── Handler.php │ ├── Http/ │ │ ├── Controllers/ │ │ │ └── Controller.php │ │ ├── Kernel.php │ │ └── Middleware/ │ │ ├── Authenticate.php │ │ ├── EncryptCookies.php │ │ ├── PreventRequestsDuringMaintenance.php │ │ ├── RedirectIfAuthenticated.php │ │ ├── TrimStrings.php │ │ ├── TrustHosts.php │ │ ├── TrustProxies.php │ │ ├── ValidateSignature.php │ │ └── VerifyCsrfToken.php │ ├── Providers/ │ │ ├── AppServiceProvider.php │ │ ├── AuthServiceProvider.php │ │ ├── BroadcastServiceProvider.php │ │ ├── EventServiceProvider.php │ │ ├── FortifyServiceProvider.php │ │ ├── HorizonServiceProvider.php │ │ ├── JetstreamServiceProvider.php │ │ └── RouteServiceProvider.php │ └── View/ │ └── Components/ │ ├── AppLayout.php │ └── GuestLayout.php ├── artisan ├── bootstrap/ │ ├── app.php │ └── cache/ │ └── .gitignore ├── composer.json ├── config/ │ ├── app.php │ ├── auth.php │ ├── broadcasting.php │ ├── cache.php │ ├── cors.php │ ├── database.php │ ├── filesystems.php │ ├── fortify.php │ ├── hashing.php │ ├── horizon.php │ ├── jetstream.php │ ├── livewire.php │ ├── logging.php │ ├── mail.php │ ├── queue.php │ ├── sanctum.php │ ├── services.php │ ├── session.php │ └── view.php ├── database/ │ ├── .gitignore │ ├── migrations/ │ │ ├── 2019_08_19_000000_create_failed_jobs_table.php │ │ ├── 2019_12_14_000001_create_personal_access_tokens_table.php │ │ ├── 2024_02_18_184745_create_sessions_table.php │ │ └── 2024_03_23_092656_create_notifications_table.php │ └── seeders/ │ └── DatabaseSeeder.php ├── docker/ │ ├── crontab │ ├── entrypoint.sh │ ├── horizon-entrypoint.sh │ ├── nginx.conf │ ├── php-fpm.ini │ ├── preload.php │ ├── supervisor/ │ │ └── supervisor.conf │ └── www.conf ├── docker-compose.yml ├── package.json ├── packages/ │ ├── certificates/ │ │ ├── .gitignore │ │ ├── composer.json │ │ ├── config/ │ │ │ └── certificates.php │ │ ├── database/ │ │ │ └── migrations/ │ │ │ ├── 2025_04_08_200000_create_create_certificate_monitors_table.php │ │ │ └── 2025_04_12_090000_create_create_certificate_monitor_history_table.php │ │ ├── phpstan.neon │ │ ├── phpunit.xml │ │ ├── resources/ │ │ │ ├── navigation.php │ │ │ └── views/ │ │ │ ├── components/ │ │ │ │ └── empty-states/ │ │ │ │ └── monitors.blade.php │ │ │ ├── index.blade.php │ │ │ ├── livewire/ │ │ │ │ ├── certificate-monitor-form.blade.php │ │ │ │ └── monitor/ │ │ │ │ └── dashboard.blade.php │ │ │ └── monitor/ │ │ │ └── index.blade.php │ │ ├── routes/ │ │ │ └── web.php │ │ ├── src/ │ │ │ ├── Actions/ │ │ │ │ └── CheckCertificate.php │ │ │ ├── Commands/ │ │ │ │ ├── CheckCertificateCommand.php │ │ │ │ └── CheckCertificatesCommand.php │ │ │ ├── Http/ │ │ │ │ └── Controllers/ │ │ │ │ └── CertificateMonitorController.php │ │ │ ├── Jobs/ │ │ │ │ └── CheckCertificateJob.php │ │ │ ├── Livewire/ │ │ │ │ ├── CertificateMonitorForm.php │ │ │ │ ├── Forms/ │ │ │ │ │ └── CertificateMonitorForm.php │ │ │ │ ├── Monitor/ │ │ │ │ │ └── Dashboard.php │ │ │ │ └── Tables/ │ │ │ │ ├── CertificateMonitorHistoryTable.php │ │ │ │ └── CertificateMonitorsTable.php │ │ │ ├── Models/ │ │ │ │ ├── CertificateMonitor.php │ │ │ │ └── CertificateMonitorHistory.php │ │ │ ├── Notifications/ │ │ │ │ ├── CertificateChangedNotification.php │ │ │ │ ├── CertificateExpiredNotification.php │ │ │ │ ├── CertificateExpiresInDaysNotification.php │ │ │ │ ├── Conditions/ │ │ │ │ │ └── DaysCondition.php │ │ │ │ └── UnableToResolveCertificateNotification.php │ │ │ └── ServiceProvider.php │ │ ├── testbench.yaml │ │ └── tests/ │ │ └── TestCase.php │ ├── core/ │ │ ├── .gitignore │ │ ├── composer.json │ │ ├── config/ │ │ │ └── core.php │ │ ├── phpstan.neon │ │ ├── phpunit.xml │ │ ├── resources/ │ │ │ └── navigation.php │ │ ├── routes/ │ │ │ └── web.php │ │ ├── src/ │ │ │ ├── Actions/ │ │ │ │ └── ResolveDataRetention.php │ │ │ ├── Concerns/ │ │ │ │ └── HasDataRetention.php │ │ │ ├── Contracts/ │ │ │ │ └── ResolvesDataRetention.php │ │ │ ├── Data/ │ │ │ │ └── Data.php │ │ │ ├── Facades/ │ │ │ │ └── Navigation.php │ │ │ ├── Http/ │ │ │ │ └── Middleware/ │ │ │ │ └── TeamMiddleware.php │ │ │ ├── Navigation/ │ │ │ │ ├── Navigation.php │ │ │ │ └── NavigationItem.php │ │ │ ├── Policies/ │ │ │ │ └── AllowAllPolicy.php │ │ │ ├── Scopes/ │ │ │ │ └── TeamScope.php │ │ │ ├── ServiceProvider.php │ │ │ ├── Services/ │ │ │ │ └── TeamService.php │ │ │ ├── Validation/ │ │ │ │ └── CanEnableRule.php │ │ │ └── helpers.php │ │ ├── testbench.yaml │ │ └── tests/ │ │ └── TestCase.php │ ├── crawler/ │ │ ├── .gitignore │ │ ├── composer.json │ │ ├── config/ │ │ │ └── crawler.php │ │ ├── database/ │ │ │ └── migrations/ │ │ │ ├── 2024_09_06_213000_create_web_crawlers_table.php │ │ │ ├── 2024_09_06_220000_create_web_crawled_urls_table.php │ │ │ ├── 2025_01_18_220000_crawled_urls_url_length.php │ │ │ ├── 2025_02_01_183000_web_crawlers_enabled_field.php │ │ │ ├── 2025_04_07_200000_web_crawled_urls_url_hash.php │ │ │ ├── 2025_09_28_100000_create_web_crawler_ignored_urls_table.php │ │ │ └── 2025_09_29_190000_web_crawled_urls_ignored_field.php │ │ ├── phpstan.neon │ │ ├── phpunit.xml │ │ ├── resources/ │ │ │ ├── navigation.php │ │ │ └── views/ │ │ │ ├── components/ │ │ │ │ └── empty-states/ │ │ │ │ └── crawlers.blade.php │ │ │ ├── crawler/ │ │ │ │ └── index.blade.php │ │ │ ├── crawlers.blade.php │ │ │ └── livewire/ │ │ │ ├── crawler/ │ │ │ │ └── dashboard.blade.php │ │ │ └── crawler-form.blade.php │ │ ├── routes/ │ │ │ └── web.php │ │ ├── src/ │ │ │ ├── Actions/ │ │ │ │ ├── CollectCrawlerStats.php │ │ │ │ ├── CrawlUrl.php │ │ │ │ ├── ImportSitemaps.php │ │ │ │ ├── ProcessCrawlerState.php │ │ │ │ └── StartCrawler.php │ │ │ ├── Commands/ │ │ │ │ ├── CollectCrawlerStatsCommand.php │ │ │ │ ├── CrawlUrlsCommand.php │ │ │ │ ├── ProcessCrawlerStatesCommand.php │ │ │ │ ├── ScheduleCrawlersCommand.php │ │ │ │ └── StartCrawlerCommand.php │ │ │ ├── Enums/ │ │ │ │ ├── State.php │ │ │ │ └── Status.php │ │ │ ├── Events/ │ │ │ │ └── CrawlerFinishedEvent.php │ │ │ ├── Exports/ │ │ │ │ └── IssuesExport.php │ │ │ ├── Http/ │ │ │ │ └── Controllers/ │ │ │ │ └── CrawlerController.php │ │ │ ├── Jobs/ │ │ │ │ ├── CollectCrawlerStatsJob.php │ │ │ │ ├── CrawUrlJob.php │ │ │ │ ├── ImportSitemapsJob.php │ │ │ │ ├── ProcessCrawlerStateJob.php │ │ │ │ └── StartCrawlerJob.php │ │ │ ├── Listeners/ │ │ │ │ └── CrawlerFinishedListener.php │ │ │ ├── Livewire/ │ │ │ │ ├── Crawler/ │ │ │ │ │ └── Dashboard.php │ │ │ │ ├── CrawlerForm.php │ │ │ │ ├── Crawlers.php │ │ │ │ ├── Forms/ │ │ │ │ │ └── CrawlerForm.php │ │ │ │ └── Tables/ │ │ │ │ ├── CrawledUrlsTable.php │ │ │ │ ├── CrawlerTable.php │ │ │ │ └── IssuesTable.php │ │ │ ├── Models/ │ │ │ │ ├── CrawledUrl.php │ │ │ │ ├── Crawler.php │ │ │ │ └── IgnoredUrl.php │ │ │ ├── Notifications/ │ │ │ │ ├── RatelimitedNotification.php │ │ │ │ └── UrlIssuesNotification.php │ │ │ ├── Observers/ │ │ │ │ ├── CrawledUrlObserver.php │ │ │ │ ├── CrawlerObserver.php │ │ │ │ └── IgnoredUrlObserver.php │ │ │ ├── ServiceProvider.php │ │ │ └── Validation/ │ │ │ ├── EqualDomainRule.php │ │ │ └── ValidRegexLines.php │ │ ├── testbench.yaml │ │ └── tests/ │ │ ├── Actions/ │ │ │ ├── CrawUrlTest.php │ │ │ ├── ProcessCrawlerStateTest.php │ │ │ └── StartCrawlerTest.php │ │ └── TestCase.php │ ├── cve/ │ │ ├── .gitignore │ │ ├── composer.json │ │ ├── config/ │ │ │ └── cve.php │ │ ├── database/ │ │ │ └── migrations/ │ │ │ ├── 2025_04_18_090000_create_cves_table.php │ │ │ ├── 2025_04_18_100000_create_cve_monitors_table.php │ │ │ ├── 2025_04_18_103000_create_cve_monitor_matches_table.php │ │ │ ├── 2025_10_04_135717_add_fulltext_index_to_cves_description.php │ │ │ └── 2025_10_04_135739_add_unique_index_to_cve_monitor_matches.php │ │ ├── phpstan.neon │ │ ├── phpunit.xml │ │ ├── resources/ │ │ │ ├── navigation.php │ │ │ └── views/ │ │ │ ├── components/ │ │ │ │ └── empty-states/ │ │ │ │ └── monitors.blade.php │ │ │ ├── cve.blade.php │ │ │ ├── index.blade.php │ │ │ ├── livewire/ │ │ │ │ └── cve-monitor-form.blade.php │ │ │ └── monitor.blade.php │ │ ├── routes/ │ │ │ └── web.php │ │ ├── src/ │ │ │ ├── Actions/ │ │ │ │ ├── ImportAllCves.php │ │ │ │ ├── ImportCve.php │ │ │ │ ├── ImportCves.php │ │ │ │ ├── MatchCve.php │ │ │ │ └── MatchExistingCves.php │ │ │ ├── Commands/ │ │ │ │ ├── ImportAllCvesCommand.php │ │ │ │ ├── ImportCvesCommand.php │ │ │ │ ├── MatchCveCommand.php │ │ │ │ └── MatchExistingCvesCommand.php │ │ │ ├── Http/ │ │ │ │ └── Controllers/ │ │ │ │ ├── CveController.php │ │ │ │ └── CveMonitorController.php │ │ │ ├── Jobs/ │ │ │ │ ├── ImportAllCvesJob.php │ │ │ │ ├── ImportCvesJob.php │ │ │ │ ├── MatchCveJob.php │ │ │ │ ├── MatchCveMonitorsJob.php │ │ │ │ └── MatchExistingCvesJob.php │ │ │ ├── Livewire/ │ │ │ │ ├── CveMonitorForm.php │ │ │ │ ├── Forms/ │ │ │ │ │ └── CveMonitorForm.php │ │ │ │ └── Tables/ │ │ │ │ ├── CveMonitorMatchesTable.php │ │ │ │ └── CveMonitorTable.php │ │ │ ├── Models/ │ │ │ │ ├── Cve.php │ │ │ │ ├── CveMonitor.php │ │ │ │ └── CveMonitorMatch.php │ │ │ ├── Notifications/ │ │ │ │ ├── Conditions/ │ │ │ │ │ ├── KeywordCondition.php │ │ │ │ │ └── ScoreCondition.php │ │ │ │ └── CveMatchedNotification.php │ │ │ ├── Observers/ │ │ │ │ └── CveMonitorObserver.php │ │ │ └── ServiceProvider.php │ │ ├── testbench.yaml │ │ └── tests/ │ │ ├── Actions/ │ │ │ ├── ImportAllCvesTest.php │ │ │ ├── ImportCveTest.php │ │ │ ├── ImportCvesTest.php │ │ │ └── MatchCveTest.php │ │ ├── Models/ │ │ │ ├── CveMonitorMatchTest.php │ │ │ ├── CveMonitorTest.php │ │ │ └── CveTest.php │ │ ├── Notifications/ │ │ │ └── CveMatchedNotificationTest.php │ │ └── TestCase.php │ ├── dns/ │ │ ├── .gitignore │ │ ├── composer.json │ │ ├── config/ │ │ │ └── dns.php │ │ ├── database/ │ │ │ └── migrations/ │ │ │ ├── 2024_07_16_073000_create_dns_monitors_table.php │ │ │ ├── 2024_07_16_073500_create_dns_monitor_history_table.php │ │ │ ├── 2025_01_23_220000_dns_monitor_value_field_size.php │ │ │ ├── 2025_02_01_180000_dns_monitor_enabled_field.php │ │ │ └── 2025_03_22_090000_dns_monitor_value_field_nullable.php │ │ ├── phpstan.neon │ │ ├── phpunit.xml │ │ ├── resources/ │ │ │ ├── navigation.php │ │ │ └── views/ │ │ │ ├── components/ │ │ │ │ └── empty-states/ │ │ │ │ └── monitors.blade.php │ │ │ └── livewire/ │ │ │ ├── dns-monitor-form.blade.php │ │ │ ├── import.blade.php │ │ │ ├── monitor/ │ │ │ │ └── dashboard.blade.php │ │ │ ├── monitor-history.blade.php │ │ │ └── monitors.blade.php │ │ ├── routes/ │ │ │ └── web.php │ │ ├── src/ │ │ │ ├── Actions/ │ │ │ │ ├── CheckDnsRecord.php │ │ │ │ ├── ResolveGeoIp.php │ │ │ │ └── ResolveRecord.php │ │ │ ├── Client/ │ │ │ │ └── DnsClient.php │ │ │ ├── Commands/ │ │ │ │ ├── CheckAllDnsRecordsCommand.php │ │ │ │ ├── CheckDnsRecordCommand.php │ │ │ │ └── ResolveGeoIpCommand.php │ │ │ ├── Enums/ │ │ │ │ └── Type.php │ │ │ ├── Http/ │ │ │ │ └── Controllers/ │ │ │ │ └── DnsMonitorController.php │ │ │ ├── Jobs/ │ │ │ │ ├── CheckDnsRecordJob.php │ │ │ │ └── ResolveGeoIpJob.php │ │ │ ├── Livewire/ │ │ │ │ ├── DnsImport.php │ │ │ │ ├── DnsMonitorForm.php │ │ │ │ ├── DnsMonitorHistory.php │ │ │ │ ├── DnsMonitors.php │ │ │ │ ├── Forms/ │ │ │ │ │ └── DnsMonitorForm.php │ │ │ │ ├── Monitor/ │ │ │ │ │ └── Dashboard.php │ │ │ │ └── Tables/ │ │ │ │ ├── DnsMonitorHistoryTable.php │ │ │ │ └── DnsMonitorTable.php │ │ │ ├── Models/ │ │ │ │ ├── DnsMonitor.php │ │ │ │ └── DnsMonitorHistory.php │ │ │ ├── Notifications/ │ │ │ │ ├── Conditions/ │ │ │ │ │ └── RecordTypeCondition.php │ │ │ │ ├── RecordChangedNotification.php │ │ │ │ └── RecordNotResolvedNotification.php │ │ │ ├── Observers/ │ │ │ │ └── GeoipObserver.php │ │ │ ├── RecordParsers/ │ │ │ │ ├── A.php │ │ │ │ ├── AAAA.php │ │ │ │ ├── CAA.php │ │ │ │ ├── CNAME.php │ │ │ │ ├── MX.php │ │ │ │ ├── NS.php │ │ │ │ ├── RecordParser.php │ │ │ │ ├── SOA.php │ │ │ │ └── TXT.php │ │ │ └── ServiceProvider.php │ │ ├── testbench.yaml │ │ └── tests/ │ │ ├── Actions/ │ │ │ └── CheckDnsRecordTest.php │ │ └── TestCase.php │ ├── frontend/ │ │ ├── .gitignore │ │ ├── composer.json │ │ ├── phpstan.neon │ │ ├── phpunit.xml │ │ ├── resources/ │ │ │ └── views/ │ │ │ ├── components/ │ │ │ │ ├── card.blade.php │ │ │ │ ├── empty-state.blade.php │ │ │ │ ├── mdash.blade.php │ │ │ │ ├── modal/ │ │ │ │ │ ├── body.blade.php │ │ │ │ │ ├── footer.blade.php │ │ │ │ │ └── header.blade.php │ │ │ │ ├── modal.blade.php │ │ │ │ ├── page-header/ │ │ │ │ │ ├── actions/ │ │ │ │ │ │ └── index.blade.php │ │ │ │ │ └── mobile-actions/ │ │ │ │ │ └── index.blade.php │ │ │ │ ├── stats-card.blade.php │ │ │ │ └── tabs/ │ │ │ │ ├── container.blade.php │ │ │ │ ├── navigation.blade.php │ │ │ │ ├── panel.blade.php │ │ │ │ └── panels.blade.php │ │ │ ├── integrations/ │ │ │ │ └── table/ │ │ │ │ ├── actions-column.blade.php │ │ │ │ ├── chart-column.blade.php │ │ │ │ ├── geoip-column.blade.php │ │ │ │ ├── hover-column.blade.php │ │ │ │ ├── link-column.blade.php │ │ │ │ └── status-column.blade.php │ │ │ └── livewire/ │ │ │ └── charts/ │ │ │ ├── base-chart-placeholder.blade.php │ │ │ └── base-chart.blade.php │ │ ├── src/ │ │ │ ├── Concerns/ │ │ │ │ └── DisplaysAlerts.php │ │ │ ├── Enums/ │ │ │ │ └── AlertType.php │ │ │ ├── Http/ │ │ │ │ └── Livewire/ │ │ │ │ └── BaseChart.php │ │ │ ├── Integrations/ │ │ │ │ └── Table/ │ │ │ │ ├── Actions/ │ │ │ │ │ └── InlineAction.php │ │ │ │ ├── ActionsColumn.php │ │ │ │ ├── BaseTable.php │ │ │ │ ├── ChartColumn.php │ │ │ │ ├── Concerns/ │ │ │ │ │ └── HasInlineActions.php │ │ │ │ ├── DateColumn.php │ │ │ │ ├── Enums/ │ │ │ │ │ └── Status.php │ │ │ │ ├── GeoIpColumn.php │ │ │ │ ├── HoverColumn.php │ │ │ │ ├── LinkColumn.php │ │ │ │ └── StatusColumn.php │ │ │ ├── ServiceProvider.php │ │ │ ├── Traits/ │ │ │ │ └── CanBeInline.php │ │ │ └── Validation/ │ │ │ ├── CleanDomainValidator.php │ │ │ ├── CountryCode.php │ │ │ ├── CronExpression.php │ │ │ └── Fqdn.php │ │ ├── testbench.yaml │ │ └── tests/ │ │ └── TestCase.php │ ├── healthchecks/ │ │ ├── .gitignore │ │ ├── composer.json │ │ ├── config/ │ │ │ └── healthchecks.php │ │ ├── database/ │ │ │ └── migrations/ │ │ │ ├── 2025_11_06_200000_create_healthchecks_table.php │ │ │ ├── 2025_11_06_201000_create_healthcheck_results_table.php │ │ │ ├── 2025_11_06_202000_create_healthcheck_metrics_table.php │ │ │ └── 2025_11_23_150400_update_healthcheck_results_columns.php │ │ ├── phpstan.neon │ │ ├── phpunit.xml │ │ ├── resources/ │ │ │ ├── navigation.php │ │ │ └── views/ │ │ │ ├── components/ │ │ │ │ └── empty-states/ │ │ │ │ └── healthchecks.blade.php │ │ │ ├── healthcheck/ │ │ │ │ └── view.blade.php │ │ │ ├── livewire/ │ │ │ │ ├── charts/ │ │ │ │ │ └── metric-chart.blade.php │ │ │ │ ├── healthcheck-dashboard.blade.php │ │ │ │ ├── healthcheck-form.blade.php │ │ │ │ ├── healthcheck-setup.blade.php │ │ │ │ ├── healthcheck-token-editor.blade.php │ │ │ │ └── healthchecks.blade.php │ │ │ └── platforms/ │ │ │ ├── drupal.blade.php │ │ │ ├── endpoint.blade.php │ │ │ ├── joomla.blade.php │ │ │ ├── laravel.blade.php │ │ │ ├── magento.blade.php │ │ │ ├── statamic.blade.php │ │ │ └── wordpress.blade.php │ │ ├── routes/ │ │ │ ├── api.php │ │ │ └── web.php │ │ ├── src/ │ │ │ ├── Actions/ │ │ │ │ ├── AggregateMetrics.php │ │ │ │ ├── CheckHealth.php │ │ │ │ ├── CheckMetric.php │ │ │ │ └── CheckResult.php │ │ │ ├── Checks/ │ │ │ │ ├── Checker.php │ │ │ │ ├── Endpoint.php │ │ │ │ └── Module.php │ │ │ ├── Commands/ │ │ │ │ ├── AggregateMetricsCommand.php │ │ │ │ ├── CheckHealthcheckCommand.php │ │ │ │ └── ScheduleHealthchecksCommand.php │ │ │ ├── Enums/ │ │ │ │ ├── Status.php │ │ │ │ └── Type.php │ │ │ ├── Http/ │ │ │ │ ├── Controllers/ │ │ │ │ │ └── HealthcheckController.php │ │ │ │ └── Livewire/ │ │ │ │ └── Charts/ │ │ │ │ └── MetricChart.php │ │ │ ├── Jobs/ │ │ │ │ ├── AggregateMetricsJob.php │ │ │ │ ├── CheckHealthcheckJob.php │ │ │ │ ├── CheckMetricJob.php │ │ │ │ └── CheckResultJob.php │ │ │ ├── Livewire/ │ │ │ │ ├── Forms/ │ │ │ │ │ └── HealthcheckForm.php │ │ │ │ ├── HealthcheckDashboard.php │ │ │ │ ├── HealthcheckForm.php │ │ │ │ ├── HealthcheckSetup.php │ │ │ │ ├── HealthcheckTokenEditor.php │ │ │ │ ├── Healthchecks.php │ │ │ │ └── Tables/ │ │ │ │ ├── HealthcheckTable.php │ │ │ │ └── ResultTable.php │ │ │ ├── Models/ │ │ │ │ ├── Healthcheck.php │ │ │ │ ├── Metric.php │ │ │ │ └── Result.php │ │ │ ├── Notifications/ │ │ │ │ ├── Conditions/ │ │ │ │ │ ├── CheckKeyCondition.php │ │ │ │ │ ├── DiskFullInCondition.php │ │ │ │ │ ├── MetricIncreaseNewValueCondition.php │ │ │ │ │ ├── MetricIncreasePercentCondition.php │ │ │ │ │ ├── MetricIncreaseTimeframeCondition.php │ │ │ │ │ ├── MetricKeyCondition.php │ │ │ │ │ ├── MetricUnitCondition.php │ │ │ │ │ ├── MetricValueCondition.php │ │ │ │ │ └── StatusCondition.php │ │ │ │ ├── DiskUsageNotification.php │ │ │ │ ├── HealthCheckFailedNotification.php │ │ │ │ ├── MetricIncreasingNotification.php │ │ │ │ ├── MetricNotification.php │ │ │ │ └── MetricSpikeNotification.php │ │ │ ├── Observers/ │ │ │ │ └── HealthcheckObserver.php │ │ │ └── ServiceProvider.php │ │ ├── testbench.yaml │ │ └── tests/ │ │ ├── Actions/ │ │ │ ├── AggregateMetricsTest.php │ │ │ ├── CheckMetricTest.php │ │ │ └── CheckResultTest.php │ │ └── TestCase.php │ ├── lighthouse/ │ │ ├── .gitignore │ │ ├── composer.json │ │ ├── config/ │ │ │ └── lighthouse.php │ │ ├── database/ │ │ │ └── migrations/ │ │ │ ├── 2024_05_11_105500_create_lighthouse_sites_table.php │ │ │ ├── 2024_05_11_120000_create_lighthouse_results_table.php │ │ │ ├── 2024_05_17_073000_lighthouse_results_aggregated_field_table.php │ │ │ ├── 2024_06_22_160000_create_lighthouse_result_audits_table.php │ │ │ ├── 2024_07_13_200000_lighthouse_site_rename_table.php │ │ │ ├── 2025_02_01_173000_lighthouse_monitors_enabled_field.php │ │ │ ├── 2025_02_03_190000_lighthouse_monitors_next_run_field.php │ │ │ ├── 2025_02_07_210000_lighthouse_monitors_batch_fields.php │ │ │ └── 2025_03_19_200000_lighthouse_monitors_run_started_at_field.php │ │ ├── phpstan.neon │ │ ├── phpunit.xml │ │ ├── resources/ │ │ │ ├── navigation.php │ │ │ └── views/ │ │ │ ├── components/ │ │ │ │ ├── average-difference.blade.php │ │ │ │ └── empty-states/ │ │ │ │ └── monitors.blade.php │ │ │ ├── lighthouse/ │ │ │ │ └── index.blade.php │ │ │ ├── livewire/ │ │ │ │ ├── lighthouse-site-form.blade.php │ │ │ │ ├── lighthouse-sites.blade.php │ │ │ │ └── monitor/ │ │ │ │ └── dashboard.blade.php │ │ │ └── result/ │ │ │ └── index.blade.php │ │ ├── routes/ │ │ │ ├── api.php │ │ │ └── web.php │ │ ├── src/ │ │ │ ├── Actions/ │ │ │ │ ├── AggregateLighthouseBatch.php │ │ │ │ ├── AggregateResults.php │ │ │ │ ├── CalculateTimeDifference.php │ │ │ │ ├── CheckLighthouseResult.php │ │ │ │ ├── CheckLighthouseResultAudit.php │ │ │ │ ├── ProcessLighthouseResult.php │ │ │ │ └── RunLighthouse.php │ │ │ ├── Commands/ │ │ │ │ ├── AggregateLighthouseBatchCommand.php │ │ │ │ ├── AggregateLighthouseResultsCommand.php │ │ │ │ ├── CheckLighthouseCommand.php │ │ │ │ ├── LighthouseCommand.php │ │ │ │ └── ScheduleLighthouseCommand.php │ │ │ ├── Data/ │ │ │ │ └── CategoryResultDifferenceData.php │ │ │ ├── Http/ │ │ │ │ └── Controllers/ │ │ │ │ ├── LighthouseCallbackController.php │ │ │ │ ├── LighthouseMonitorController.php │ │ │ │ └── LighthouseResultController.php │ │ │ ├── Jobs/ │ │ │ │ ├── AggregateLighthouseBatchJob.php │ │ │ │ ├── AggregateLighthouseResultsJob.php │ │ │ │ ├── CheckLighthouseResultJob.php │ │ │ │ └── RunLighthouseJob.php │ │ │ ├── Livewire/ │ │ │ │ ├── Charts/ │ │ │ │ │ ├── LighthouseCategoriesChart.php │ │ │ │ │ └── NumericLighthouseChart.php │ │ │ │ ├── Forms/ │ │ │ │ │ └── LighthouseSiteForm.php │ │ │ │ ├── LighthouseSiteForm.php │ │ │ │ ├── LighthouseSites.php │ │ │ │ ├── Monitor/ │ │ │ │ │ └── Dashboard.php │ │ │ │ └── Tables/ │ │ │ │ ├── LighthouseMonitorsTable.php │ │ │ │ ├── LighthouseResultAuditsTable.php │ │ │ │ └── LighthouseResultsTable.php │ │ │ ├── Models/ │ │ │ │ ├── LighthouseMonitor.php │ │ │ │ ├── LighthouseResult.php │ │ │ │ └── LighthouseResultAudit.php │ │ │ ├── Notifications/ │ │ │ │ ├── CategoryScoreChangedNotification.php │ │ │ │ ├── Conditions/ │ │ │ │ │ ├── Audit/ │ │ │ │ │ │ ├── AuditChangesCondition.php │ │ │ │ │ │ ├── AuditDecreasesCondition.php │ │ │ │ │ │ ├── AuditIncreasesCondition.php │ │ │ │ │ │ ├── AuditPercentCondition.php │ │ │ │ │ │ ├── AuditTypeCondition.php │ │ │ │ │ │ └── AuditValueCondition.php │ │ │ │ │ └── Category/ │ │ │ │ │ ├── AccessibilityPercentScoreCondition.php │ │ │ │ │ ├── AccessibilityScoreDecreasesCondition.php │ │ │ │ │ ├── AccessibilityScoreIncreasesCondition.php │ │ │ │ │ ├── AccessibilityScoreValueCondition.php │ │ │ │ │ ├── AverageScoreChangesCondition.php │ │ │ │ │ ├── AverageScoreCondition.php │ │ │ │ │ ├── AverageScoreDecreasesCondition.php │ │ │ │ │ ├── AverageScoreIncreasesCondition.php │ │ │ │ │ ├── AverageScoreValueCondition.php │ │ │ │ │ ├── BestPracticesPercentScoreCondition.php │ │ │ │ │ ├── BestPracticesScoreDecreasesCondition.php │ │ │ │ │ ├── BestPracticesScoreIncreasesCondition.php │ │ │ │ │ ├── BestPracticesScoreValueCondition.php │ │ │ │ │ ├── PerformancePercentScoreCondition.php │ │ │ │ │ ├── PerformanceScoreDecreasesCondition.php │ │ │ │ │ ├── PerformanceScoreIncreasesCondition.php │ │ │ │ │ ├── PerformanceScoreValueCondition.php │ │ │ │ │ ├── ScoreCondition.php │ │ │ │ │ ├── SeoPercentPercentScoreCondition.php │ │ │ │ │ ├── SeoScoreDecreasesCondition.php │ │ │ │ │ ├── SeoScoreIncreasesCondition.php │ │ │ │ │ └── SeoScoreValueCondition.php │ │ │ │ └── NumericAuditChangedNotification.php │ │ │ ├── Observers/ │ │ │ │ └── LighthouseMonitorObserver.php │ │ │ └── ServiceProvider.php │ │ ├── testbench.yaml │ │ └── tests/ │ │ ├── Actions/ │ │ │ ├── AggregateResultsTest.php │ │ │ ├── CalculateTimeDifferenceTest.php │ │ │ ├── CheckLighthouseResultAuditTest.php │ │ │ ├── CheckLighthouseResultTest.php │ │ │ └── RunLighthouseTest.php │ │ ├── Data/ │ │ │ └── CategoryResultDifferenceDataTest.php │ │ ├── Notifications/ │ │ │ └── Conditions/ │ │ │ ├── Audit/ │ │ │ │ ├── AuditChangeConditionsTest.php │ │ │ │ └── AuditValueConditionTest.php │ │ │ └── Category/ │ │ │ ├── AverageScoreChangeConditionsTest.php │ │ │ ├── AverageScoreValueConditionTest.php │ │ │ └── PerformanceScoreValueConditionTest.php │ │ └── TestCase.php │ ├── notifications/ │ │ ├── .gitignore │ │ ├── composer.json │ │ ├── config/ │ │ │ └── notifications.php │ │ ├── database/ │ │ │ └── migrations/ │ │ │ ├── 2024_02_25_110000_create_notification_triggers_table.php │ │ │ ├── 2024_02_25_111000_create_notification_channels_table.php │ │ │ ├── 2024_02_25_111000_create_notification_triggers_channels_table.php │ │ │ ├── 2024_02_25_112000_create_notification_history_table.php │ │ │ ├── 2024_04_04_193000_notification_trigger_all_channels_field.php │ │ │ ├── 2024_04_12_193000_notification_enabled_field.php │ │ │ ├── 2024_09_22_113000_notification_cooldown_field.php │ │ │ ├── 2026_01_02_150000_add_name_to_notification_channels_table.php │ │ │ └── 2026_01_02_151500_backfill_notification_channel_names.php │ │ ├── phpstan.neon │ │ ├── phpunit.xml │ │ ├── resources/ │ │ │ ├── navigation.php │ │ │ └── views/ │ │ │ ├── channels.blade.php │ │ │ ├── components/ │ │ │ │ ├── condition-builder/ │ │ │ │ │ ├── condition.blade.php │ │ │ │ │ ├── group.blade.php │ │ │ │ │ └── type/ │ │ │ │ │ ├── number.blade.php │ │ │ │ │ ├── select.blade.php │ │ │ │ │ ├── static.blade.php │ │ │ │ │ └── text.blade.php │ │ │ │ └── empty-states/ │ │ │ │ └── channels.blade.php │ │ │ ├── history.blade.php │ │ │ ├── livewire/ │ │ │ │ ├── channels/ │ │ │ │ │ ├── configuration/ │ │ │ │ │ │ ├── discord.blade.php │ │ │ │ │ │ ├── google-chat.blade.php │ │ │ │ │ │ ├── mail.blade.php │ │ │ │ │ │ ├── microsoft-teams.blade.php │ │ │ │ │ │ ├── ntfy.blade.php │ │ │ │ │ │ ├── slack.blade.php │ │ │ │ │ │ ├── telegram.blade.php │ │ │ │ │ │ └── webhook.blade.php │ │ │ │ │ └── form.blade.php │ │ │ │ └── notifications/ │ │ │ │ ├── condition-builder.blade.php │ │ │ │ └── form.blade.php │ │ │ ├── mails/ │ │ │ │ └── notification.blade.php │ │ │ └── notifications.blade.php │ │ ├── routes/ │ │ │ └── web.php │ │ ├── src/ │ │ │ ├── Actions/ │ │ │ │ ├── CheckBurst.php │ │ │ │ ├── CheckCooldown.php │ │ │ │ └── CreateNotifications.php │ │ │ ├── Channels/ │ │ │ │ ├── DiscordChannel.php │ │ │ │ ├── GoogleChatChannel.php │ │ │ │ ├── MailChannel.php │ │ │ │ ├── MicrosoftTeamsChannel.php │ │ │ │ ├── NotificationChannel.php │ │ │ │ ├── NtfyChannel.php │ │ │ │ ├── SlackChannel.php │ │ │ │ ├── TelegramChannel.php │ │ │ │ └── WebhookChannel.php │ │ │ ├── Commands/ │ │ │ │ ├── CreateNotificationsCommand.php │ │ │ │ ├── RenameConditionClassesCommand.php │ │ │ │ └── TestNotificationCommand.php │ │ │ ├── Concerns/ │ │ │ │ └── NotificationFake.php │ │ │ ├── Conditions/ │ │ │ │ ├── Condition.php │ │ │ │ ├── ConditionEngine.php │ │ │ │ ├── FalseCondition.php │ │ │ │ ├── SelectCondition.php │ │ │ │ ├── StaticCondition.php │ │ │ │ └── TrueCondition.php │ │ │ ├── Contracts/ │ │ │ │ └── HasSite.php │ │ │ ├── Enums/ │ │ │ │ ├── ConditionType.php │ │ │ │ └── Level.php │ │ │ ├── Facades/ │ │ │ │ └── NotificationRegistry.php │ │ │ ├── Http/ │ │ │ │ ├── Controllers/ │ │ │ │ │ └── ChannelController.php │ │ │ │ └── Livewire/ │ │ │ │ ├── ChannelForm.php │ │ │ │ ├── Channels/ │ │ │ │ │ └── Configuration/ │ │ │ │ │ ├── ChannelConfiguration.php │ │ │ │ │ ├── Discord.php │ │ │ │ │ ├── GoogleChat.php │ │ │ │ │ ├── Mail.php │ │ │ │ │ ├── MicrosoftTeams.php │ │ │ │ │ ├── Ntfy.php │ │ │ │ │ ├── Slack.php │ │ │ │ │ ├── Telegram.php │ │ │ │ │ └── Webhook.php │ │ │ │ ├── Forms/ │ │ │ │ │ ├── CreateChannelForm.php │ │ │ │ │ └── CreateNotificationForm.php │ │ │ │ ├── NotificationForm.php │ │ │ │ ├── Notifications/ │ │ │ │ │ └── Conditions/ │ │ │ │ │ └── ConditionBuilder.php │ │ │ │ └── Tables/ │ │ │ │ ├── ChannelTable.php │ │ │ │ ├── HistoryTable.php │ │ │ │ └── NotificationTable.php │ │ │ ├── Jobs/ │ │ │ │ ├── CreateNotificationsJob.php │ │ │ │ └── SendNotificationJob.php │ │ │ ├── Mail/ │ │ │ │ └── NotificationMail.php │ │ │ ├── Models/ │ │ │ │ ├── Channel.php │ │ │ │ ├── History.php │ │ │ │ └── Trigger.php │ │ │ ├── Notifications/ │ │ │ │ ├── Notification.php │ │ │ │ ├── NotificationRegistry.php │ │ │ │ └── TestNotification.php │ │ │ ├── Observers/ │ │ │ │ ├── ChannelObserver.php │ │ │ │ └── TriggerObserver.php │ │ │ ├── Scopes/ │ │ │ │ └── HistoryTeamScope.php │ │ │ └── ServiceProvider.php │ │ ├── testbench.yaml │ │ └── tests/ │ │ ├── Channels/ │ │ │ ├── NtfyChannelTest.php │ │ │ └── TelegramChannelTest.php │ │ ├── Conditions/ │ │ │ └── ConditionEngineTest.php │ │ ├── Fakes/ │ │ │ ├── Conditions/ │ │ │ │ ├── FalseCondition.php │ │ │ │ └── TrueCondition.php │ │ │ ├── FakeChannel.php │ │ │ └── FakeNotification.php │ │ ├── Models/ │ │ │ └── ChannelTest.php │ │ ├── Notifications/ │ │ │ ├── NotificationRegistryTest.php │ │ │ └── NotificationTest.php │ │ └── TestCase.php │ ├── onboarding/ │ │ ├── .gitignore │ │ ├── composer.json │ │ ├── config/ │ │ │ └── onboarding.php │ │ ├── database/ │ │ │ └── migrations/ │ │ │ └── 2024_09_29_210000_create_team_onboarding_step_table.php │ │ ├── phpstan.neon │ │ ├── phpunit.xml │ │ ├── resources/ │ │ │ └── views/ │ │ │ ├── complete.blade.php │ │ │ ├── import-domains.blade.php │ │ │ └── notification-channel.blade.php │ │ ├── routes/ │ │ │ └── web.php │ │ ├── src/ │ │ │ ├── Actions/ │ │ │ │ └── ShouldOnboard.php │ │ │ ├── Http/ │ │ │ │ └── Middleware/ │ │ │ │ ├── OnlyOnboarding.php │ │ │ │ └── RedirectToOnboard.php │ │ │ ├── Livewire/ │ │ │ │ ├── Complete.php │ │ │ │ ├── ImportDomains.php │ │ │ │ └── NotificationChannel.php │ │ │ ├── Models/ │ │ │ │ └── OnboardingStep.php │ │ │ └── ServiceProvider.php │ │ ├── testbench.yaml │ │ └── tests/ │ │ └── TestCase.php │ ├── settings/ │ │ ├── .gitignore │ │ ├── composer.json │ │ ├── config/ │ │ │ └── settings.php │ │ ├── phpstan.neon │ │ ├── phpunit.xml │ │ ├── resources/ │ │ │ └── views/ │ │ │ ├── index.blade.php │ │ │ └── tabs/ │ │ │ ├── profile.blade.php │ │ │ ├── security.blade.php │ │ │ └── team.blade.php │ │ ├── routes/ │ │ │ └── web.php │ │ ├── src/ │ │ │ ├── Livewire/ │ │ │ │ ├── Forms/ │ │ │ │ │ ├── ProfileForm.php │ │ │ │ │ └── UpdatePasswordForm.php │ │ │ │ ├── Settings.php │ │ │ │ └── Tabs/ │ │ │ │ ├── Profile.php │ │ │ │ ├── Security.php │ │ │ │ └── Team.php │ │ │ └── ServiceProvider.php │ │ ├── testbench.yaml │ │ └── tests/ │ │ └── TestCase.php │ ├── sites/ │ │ ├── .gitignore │ │ ├── composer.json │ │ ├── config/ │ │ │ └── sites.php │ │ ├── database/ │ │ │ └── migrations/ │ │ │ └── 2024_02_20_170000_create_sites_table.php │ │ ├── phpstan.neon │ │ ├── phpunit.xml │ │ ├── resources/ │ │ │ ├── navigation.php │ │ │ └── views/ │ │ │ ├── components/ │ │ │ │ ├── empty-states/ │ │ │ │ │ └── no-monitors.blade.php │ │ │ │ └── site-card.blade.php │ │ │ ├── livewire/ │ │ │ │ ├── form.blade.php │ │ │ │ ├── import.blade.php │ │ │ │ ├── sites.blade.php │ │ │ │ └── tabs/ │ │ │ │ ├── certificate-monitor.blade.php │ │ │ │ ├── crawler.blade.php │ │ │ │ ├── dns-monitors.blade.php │ │ │ │ ├── healthcheck-monitor.blade.php │ │ │ │ ├── lighthouse-monitor.blade.php │ │ │ │ └── uptime-monitor.blade.php │ │ │ └── sites/ │ │ │ └── view.blade.php │ │ ├── routes/ │ │ │ └── web.php │ │ ├── src/ │ │ │ ├── Actions/ │ │ │ │ └── ImportSite.php │ │ │ ├── Conditions/ │ │ │ │ └── SiteCondition.php │ │ │ ├── Http/ │ │ │ │ ├── Controllers/ │ │ │ │ │ └── SiteController.php │ │ │ │ └── Livewire/ │ │ │ │ ├── Forms/ │ │ │ │ │ └── CreateSiteForm.php │ │ │ │ ├── ImportSites.php │ │ │ │ ├── SiteForm.php │ │ │ │ ├── Sites.php │ │ │ │ ├── Tables/ │ │ │ │ │ └── SiteTable.php │ │ │ │ └── Tabs/ │ │ │ │ ├── CertificateMonitor.php │ │ │ │ ├── Crawler.php │ │ │ │ ├── DnsMonitors.php │ │ │ │ ├── HealthcheckMonitor.php │ │ │ │ ├── LighthouseMonitors.php │ │ │ │ └── UptimeMonitor.php │ │ │ ├── Jobs/ │ │ │ │ └── ImportSiteJob.php │ │ │ ├── Models/ │ │ │ │ └── Site.php │ │ │ ├── Observers/ │ │ │ │ └── SiteObserver.php │ │ │ └── ServiceProvider.php │ │ ├── testbench.yaml │ │ └── tests/ │ │ └── TestCase.php │ ├── uptime/ │ │ ├── .gitignore │ │ ├── composer.json │ │ ├── config/ │ │ │ └── uptime.php │ │ ├── database/ │ │ │ ├── factories/ │ │ │ │ └── MonitorFactory.php │ │ │ └── migrations/ │ │ │ ├── 2024_02_21_190000_create_uptime_monitors_table.php │ │ │ ├── 2024_02_21_190100_create_uptime_results_table.php │ │ │ ├── 2024_02_21_190200_create_uptime_downtimes_table.php │ │ │ ├── 2024_02_22_073000_create_uptime_results_aggregates_table.php │ │ │ ├── 2024_05_21_170200_uptime_downtimes_data_field.php │ │ │ ├── 2025_02_01_170000_uptime_monitors_enabled_field.php │ │ │ ├── 2025_05_06_190000_uptime_monitors_schedule_fields.php │ │ │ ├── 2025_10_05_080000_create_uptime_outposts_table.php │ │ │ ├── 2025_10_06_181706_add_country_to_uptime_results_tables.php │ │ │ ├── 2025_10_06_183423_add_location_to_uptime_monitors_table.php │ │ │ ├── 2025_10_06_184619_add_country_to_uptime_monitors_table.php │ │ │ ├── 2025_10_07_180857_add_geoip_fetched_at_to_uptime_monitors_table.php │ │ │ ├── 2025_10_08_100000_add_closest_outpost_id_to_uptime_monitors_table.php │ │ │ ├── 2025_10_19_152447_add_unavailable_at_to_uptime_outposts_table.php │ │ │ ├── 2025_12_23_192903_add_geoip_automatic_to_uptime_monitors_table.php │ │ │ ├── 2025_12_23_193500_add_geoip_automatic_to_uptime_outposts_table.php │ │ │ └── 2025_12_27_142900_update_ping_monitor_types.php │ │ ├── phpstan.neon │ │ ├── phpunit.xml │ │ ├── resources/ │ │ │ ├── navigation.php │ │ │ └── views/ │ │ │ ├── components/ │ │ │ │ └── empty-states/ │ │ │ │ └── monitors.blade.php │ │ │ ├── livewire/ │ │ │ │ ├── charts/ │ │ │ │ │ ├── column-latency-chart.blade.php │ │ │ │ │ └── latency-chart.blade.php │ │ │ │ ├── monitor/ │ │ │ │ │ ├── dashboard.blade.php │ │ │ │ │ └── form.blade.php │ │ │ │ └── uptime-monitors.blade.php │ │ │ └── monitor/ │ │ │ └── view.blade.php │ │ ├── routes/ │ │ │ ├── api.php │ │ │ └── web.php │ │ ├── src/ │ │ │ ├── Actions/ │ │ │ │ ├── AggregateResults.php │ │ │ │ ├── CalculateUptimePercentage.php │ │ │ │ ├── CheckLatency.php │ │ │ │ ├── CheckUptime.php │ │ │ │ ├── FetchGeolocation.php │ │ │ │ └── Outpost/ │ │ │ │ ├── DetermineOutpost.php │ │ │ │ ├── GenerateOutpostCertificate.php │ │ │ │ ├── GenerateRootCertificate.php │ │ │ │ └── RegisterOutpost.php │ │ │ ├── Commands/ │ │ │ │ ├── AggregateResultsCommand.php │ │ │ │ ├── CheckLatencyCommand.php │ │ │ │ ├── CheckUnavailableOutpostsCommand.php │ │ │ │ ├── CheckUptimeCommand.php │ │ │ │ ├── GenerateRootCaCommand.php │ │ │ │ └── ScheduleUptimeChecksCommand.php │ │ │ ├── Data/ │ │ │ │ └── UptimeResult.php │ │ │ ├── Enums/ │ │ │ │ ├── OutpostStatus.php │ │ │ │ ├── State.php │ │ │ │ └── Type.php │ │ │ ├── Events/ │ │ │ │ ├── DowntimeEndEvent.php │ │ │ │ ├── DowntimeStartEvent.php │ │ │ │ └── UptimeCheckedEvent.php │ │ │ ├── Http/ │ │ │ │ ├── Controllers/ │ │ │ │ │ ├── Api/ │ │ │ │ │ │ ├── OutpostController.php │ │ │ │ │ │ └── OutpostIpController.php │ │ │ │ │ └── UptimeMonitorController.php │ │ │ │ ├── Livewire/ │ │ │ │ │ ├── Charts/ │ │ │ │ │ │ ├── ColumnLatencyChart.php │ │ │ │ │ │ └── LatencyChart.php │ │ │ │ │ ├── Forms/ │ │ │ │ │ │ └── CreateUptimeMonitorForm.php │ │ │ │ │ ├── Monitor/ │ │ │ │ │ │ └── Dashboard.php │ │ │ │ │ ├── Tables/ │ │ │ │ │ │ ├── DowntimeTable.php │ │ │ │ │ │ └── MonitorTable.php │ │ │ │ │ ├── UptimeMonitorForm.php │ │ │ │ │ └── UptimeMonitors.php │ │ │ │ └── Middleware/ │ │ │ │ ├── ExternalOutpostMiddleware.php │ │ │ │ └── OutpostAuthMiddleware.php │ │ │ ├── Jobs/ │ │ │ │ ├── AggregateResultsJob.php │ │ │ │ ├── CheckUnavailableOutpostJob.php │ │ │ │ ├── CheckUptimeJob.php │ │ │ │ └── UpdateMonitorLocationJob.php │ │ │ ├── Listeners/ │ │ │ │ ├── CheckLatencyListener.php │ │ │ │ ├── DowntimeEndNotificationListener.php │ │ │ │ └── DowntimeStartNotificationListener.php │ │ │ ├── Models/ │ │ │ │ ├── Downtime.php │ │ │ │ ├── Monitor.php │ │ │ │ ├── Outpost.php │ │ │ │ ├── Result.php │ │ │ │ └── ResultAggregate.php │ │ │ ├── Notifications/ │ │ │ │ ├── Conditions/ │ │ │ │ │ ├── ClosestCountryCondition.php │ │ │ │ │ ├── CountryCondition.php │ │ │ │ │ ├── LatencyMsCondition.php │ │ │ │ │ └── LatencyPercentCondition.php │ │ │ │ ├── DowntimeEndNotification.php │ │ │ │ ├── DowntimeStartNotification.php │ │ │ │ ├── LatencyChangedNotification.php │ │ │ │ └── LatencyPeakNotification.php │ │ │ ├── Observers/ │ │ │ │ ├── MonitorObserver.php │ │ │ │ └── OutpostObserver.php │ │ │ └── ServiceProvider.php │ │ ├── testbench.yaml │ │ └── tests/ │ │ ├── Fakes/ │ │ │ └── HandlerStatsResponse.php │ │ ├── Feature/ │ │ │ ├── AggregateResultsTest.php │ │ │ ├── DowntimeTest.php │ │ │ └── UptimeTest.php │ │ ├── TestCase.php │ │ └── Unit/ │ │ ├── CalculateUptimePercentageTest.php │ │ ├── DetermineOutpostPerformanceTest.php │ │ ├── DetermineOutpostTest.php │ │ ├── Enums/ │ │ │ └── TypeTest.php │ │ ├── ExternalOutpostMiddlewareTest.php │ │ ├── FetchGeolocationTest.php │ │ ├── GenerateOutpostCertificateTest.php │ │ ├── OutpostAuthMiddlewareTest.php │ │ └── RegisterOutpostTest.php │ └── users/ │ ├── .gitignore │ ├── composer.json │ ├── config/ │ │ └── users.php │ ├── database/ │ │ ├── factories/ │ │ │ ├── TeamFactory.php │ │ │ └── UserFactory.php │ │ └── migrations/ │ │ ├── 2014_10_12_000000_create_users_table.php │ │ ├── 2014_10_12_100000_create_password_reset_tokens_table.php │ │ ├── 2014_10_12_200000_add_two_factor_columns_to_users_table.php │ │ ├── 2020_05_21_100000_create_teams_table.php │ │ ├── 2020_05_21_200000_create_team_user_table.php │ │ ├── 2020_05_21_300000_create_team_invitations_table.php │ │ └── 2024_05_18_100000_team_timezone_field.php │ ├── phpstan.neon │ ├── phpunit.xml │ ├── routes/ │ │ ├── auth.php │ │ └── web.php │ ├── src/ │ │ ├── Actions/ │ │ │ ├── Fortify/ │ │ │ │ ├── CreateNewUser.php │ │ │ │ ├── PasswordValidationRules.php │ │ │ │ ├── ResetUserPassword.php │ │ │ │ ├── UpdateUserPassword.php │ │ │ │ └── UpdateUserProfileInformation.php │ │ │ └── Jetstream/ │ │ │ ├── AddTeamMember.php │ │ │ ├── CreateTeam.php │ │ │ ├── DeleteTeam.php │ │ │ ├── DeleteUser.php │ │ │ ├── InviteTeamMember.php │ │ │ ├── RemoveTeamMember.php │ │ │ └── UpdateTeamName.php │ │ ├── Http/ │ │ │ ├── Controllers/ │ │ │ │ └── SocialiteController.php │ │ │ └── Middleware/ │ │ │ ├── EnsureEmailIsVerified.php │ │ │ └── NoUserMiddleware.php │ │ ├── Models/ │ │ │ ├── Membership.php │ │ │ ├── Team.php │ │ │ ├── TeamInvitation.php │ │ │ └── User.php │ │ ├── Notifications/ │ │ │ └── VerifyEmail.php │ │ ├── Observers/ │ │ │ └── TeamObserver.php │ │ ├── Policies/ │ │ │ └── TeamPolicy.php │ │ ├── ServiceProvider.php │ │ └── Validators/ │ │ └── RegistrationEnabledValidator.php │ ├── testbench.yaml │ └── tests/ │ └── TestCase.php ├── phpunit.xml ├── postcss.config.js ├── public/ │ ├── .htaccess │ ├── index.php │ ├── robots.txt │ └── site.webmanifest ├── resources/ │ ├── css/ │ │ ├── app.css │ │ └── tailwind.sources.css │ ├── js/ │ │ ├── app.js │ │ └── bootstrap.js │ ├── lang/ │ │ └── en/ │ │ └── validation.php │ ├── markdown/ │ │ ├── policy.md │ │ └── terms.md │ ├── navigation.php │ └── views/ │ ├── api/ │ │ ├── api-token-manager.blade.php │ │ └── index.blade.php │ ├── auth/ │ │ ├── confirm-password.blade.php │ │ ├── forgot-password.blade.php │ │ ├── login.blade.php │ │ ├── register.blade.php │ │ ├── reset-password.blade.php │ │ ├── two-factor-challenge.blade.php │ │ └── verify-email.blade.php │ ├── components/ │ │ ├── action-message.blade.php │ │ ├── action-section.blade.php │ │ ├── alert.blade.php │ │ ├── alerts/ │ │ │ ├── danger.blade.php │ │ │ ├── info.blade.php │ │ │ ├── success.blade.php │ │ │ └── warning.blade.php │ │ ├── application-logo.blade.php │ │ ├── application-mark.blade.php │ │ ├── authentication-card-logo.blade.php │ │ ├── authentication-card.blade.php │ │ ├── banner.blade.php │ │ ├── button.blade.php │ │ ├── card.blade.php │ │ ├── checkbox.blade.php │ │ ├── confirmation-modal.blade.php │ │ ├── confirms-password.blade.php │ │ ├── create-button-dropdown.blade.php │ │ ├── create-button.blade.php │ │ ├── danger-button.blade.php │ │ ├── dialog-modal.blade.php │ │ ├── dropdown-link.blade.php │ │ ├── dropdown.blade.php │ │ ├── form/ │ │ │ ├── button.blade.php │ │ │ ├── checkbox.blade.php │ │ │ ├── dropdown-button.blade.php │ │ │ ├── header.blade.php │ │ │ ├── number.blade.php │ │ │ ├── password.blade.php │ │ │ ├── select.blade.php │ │ │ ├── submit-button.blade.php │ │ │ ├── text-list.blade.php │ │ │ ├── text.blade.php │ │ │ ├── textarea.blade.php │ │ │ └── time.blade.php │ │ ├── form-section.blade.php │ │ ├── input-error.blade.php │ │ ├── input.blade.php │ │ ├── label.blade.php │ │ ├── layout/ │ │ │ ├── sidebar/ │ │ │ │ ├── menu.blade.php │ │ │ │ └── mobile-menu.blade.php │ │ │ ├── sidebar.blade.php │ │ │ ├── topbar.blade.php │ │ │ └── user-profile-dropdown.blade.php │ │ ├── modal.blade.php │ │ ├── nav-link.blade.php │ │ ├── page-header.blade.php │ │ ├── password-group.blade.php │ │ ├── responsive-nav-link.blade.php │ │ ├── secondary-button.blade.php │ │ ├── section-border.blade.php │ │ ├── section-title.blade.php │ │ ├── switchable-team.blade.php │ │ └── validation-errors.blade.php │ ├── dashboard.blade.php │ ├── emails/ │ │ └── team-invitation.blade.php │ ├── errors/ │ │ ├── 401.blade.php │ │ ├── 402.blade.php │ │ ├── 403.blade.php │ │ ├── 404.blade.php │ │ ├── 419.blade.php │ │ ├── 429.blade.php │ │ ├── 500.blade.php │ │ ├── 503.blade.php │ │ ├── layout.blade.php │ │ └── minimal.blade.php │ ├── layouts/ │ │ ├── app.blade.php │ │ └── guest.blade.php │ ├── policy.blade.php │ ├── profile/ │ │ ├── delete-user-form.blade.php │ │ ├── logout-other-browser-sessions-form.blade.php │ │ ├── two-factor-authentication-form.blade.php │ │ ├── update-password-form.blade.php │ │ └── update-profile-information-form.blade.php │ ├── teams/ │ │ ├── create-team-form.blade.php │ │ ├── create.blade.php │ │ ├── delete-team-form.blade.php │ │ ├── show.blade.php │ │ ├── team-member-manager.blade.php │ │ └── update-team-name-form.blade.php │ ├── terms.blade.php │ └── vendor/ │ ├── livewire-table/ │ │ ├── columns/ │ │ │ ├── buttons/ │ │ │ │ └── copy.blade.php │ │ │ ├── content/ │ │ │ │ ├── action.blade.php │ │ │ │ ├── boolean.blade.php │ │ │ │ ├── default.blade.php │ │ │ │ └── image.blade.php │ │ │ ├── footer/ │ │ │ │ └── default.blade.php │ │ │ ├── header/ │ │ │ │ └── default.blade.php │ │ │ └── search/ │ │ │ ├── boolean.blade.php │ │ │ ├── date.blade.php │ │ │ ├── default.blade.php │ │ │ └── select.blade.php │ │ ├── components/ │ │ │ ├── button.blade.php │ │ │ ├── dropdown/ │ │ │ │ ├── content.blade.php │ │ │ │ ├── divider.blade.php │ │ │ │ ├── footer.blade.php │ │ │ │ ├── header.blade.php │ │ │ │ ├── index.blade.php │ │ │ │ ├── menu/ │ │ │ │ │ ├── index.blade.php │ │ │ │ │ └── item.blade.php │ │ │ │ └── section.blade.php │ │ │ ├── form/ │ │ │ │ ├── checkbox.blade.php │ │ │ │ ├── group.blade.php │ │ │ │ ├── input.blade.php │ │ │ │ └── select.blade.php │ │ │ ├── icon.blade.php │ │ │ ├── notification/ │ │ │ │ ├── button.blade.php │ │ │ │ └── index.blade.php │ │ │ └── table/ │ │ │ ├── index.blade.php │ │ │ ├── message.blade.php │ │ │ ├── tbody.blade.php │ │ │ ├── td.blade.php │ │ │ ├── tfoot.blade.php │ │ │ ├── th.blade.php │ │ │ ├── thead.blade.php │ │ │ └── tr.blade.php │ │ ├── filters/ │ │ │ ├── boolean.blade.php │ │ │ ├── date.blade.php │ │ │ ├── filter.blade.php │ │ │ └── select.blade.php │ │ ├── icons/ │ │ │ ├── arrow-path.blade.php │ │ │ ├── backspace.blade.php │ │ │ ├── check-circle.blade.php │ │ │ ├── check.blade.php │ │ │ ├── chevron-down.blade.php │ │ │ ├── chevron-left.blade.php │ │ │ ├── chevron-right.blade.php │ │ │ ├── chevron-up-down.blade.php │ │ │ ├── chevron-up.blade.php │ │ │ ├── clipboard-document-check.blade.php │ │ │ ├── clipboard-document.blade.php │ │ │ ├── clock.blade.php │ │ │ ├── cog-6-tooth.blade.php │ │ │ ├── ellipsis-vertical.blade.php │ │ │ ├── eye.blade.php │ │ │ ├── funnel.blade.php │ │ │ ├── information-circle.blade.php │ │ │ ├── list-bullet.blade.php │ │ │ ├── magnifying-glass.blade.php │ │ │ ├── min.blade.php │ │ │ ├── play.blade.php │ │ │ ├── plus.blade.php │ │ │ ├── queue-list.blade.php │ │ │ ├── view-columns.blade.php │ │ │ └── x-mark.blade.php │ │ ├── livewire/ │ │ │ └── livewire-table.blade.php │ │ ├── pagination/ │ │ │ └── pagination.blade.php │ │ ├── table/ │ │ │ └── table.blade.php │ │ └── toolbar/ │ │ ├── buttons/ │ │ │ ├── clear-search.blade.php │ │ │ └── reordering.blade.php │ │ ├── dropdowns/ │ │ │ ├── actions.blade.php │ │ │ ├── configuration.blade.php │ │ │ ├── sections/ │ │ │ │ ├── actions.blade.php │ │ │ │ ├── columns.blade.php │ │ │ │ ├── configuration.blade.php │ │ │ │ ├── filters.blade.php │ │ │ │ ├── polling.blade.php │ │ │ │ ├── results.blade.php │ │ │ │ ├── suggestions.blade.php │ │ │ │ └── trashed.blade.php │ │ │ └── suggestions.blade.php │ │ ├── loader.blade.php │ │ ├── notification.blade.php │ │ ├── search.blade.php │ │ └── toolbar.blade.php │ └── mail/ │ ├── html/ │ │ ├── button.blade.php │ │ ├── footer.blade.php │ │ ├── header.blade.php │ │ ├── layout.blade.php │ │ ├── message.blade.php │ │ ├── panel.blade.php │ │ ├── subcopy.blade.php │ │ ├── table.blade.php │ │ └── themes/ │ │ └── default.css │ └── text/ │ ├── button.blade.php │ ├── footer.blade.php │ ├── header.blade.php │ ├── layout.blade.php │ ├── message.blade.php │ ├── panel.blade.php │ ├── subcopy.blade.php │ └── table.blade.php ├── routes/ │ ├── api.php │ ├── channels.php │ ├── console.php │ └── web.php ├── scripts/ │ ├── generate-tailwind-sources.mjs │ └── package-quality.sh ├── storage/ │ ├── app/ │ │ └── .gitignore │ ├── framework/ │ │ ├── .gitignore │ │ ├── cache/ │ │ │ └── .gitignore │ │ ├── sessions/ │ │ │ └── .gitignore │ │ ├── testing/ │ │ │ └── .gitignore │ │ └── views/ │ │ └── .gitignore │ └── logs/ │ └── .gitignore ├── tests/ │ ├── Browser/ │ │ ├── Notifications/ │ │ │ ├── ChannelsFormTest.php │ │ │ ├── ChannelsIndexTest.php │ │ │ ├── NotificationsFormTest.php │ │ │ └── NotificationsIndexTest.php │ │ ├── Pages/ │ │ │ ├── HomePage.php │ │ │ └── Page.php │ │ ├── Sites/ │ │ │ ├── SitesFormTest.php │ │ │ └── SitesIndexTest.php │ │ ├── Uptime/ │ │ │ ├── UptimeFormTest.php │ │ │ └── UptimeIndexTest.php │ │ ├── console/ │ │ │ └── .gitignore │ │ ├── screenshots/ │ │ │ └── .gitignore │ │ └── source/ │ │ └── .gitignore │ ├── CreatesApplication.php │ ├── DuskTestCase.php │ ├── Feature/ │ │ └── .gitkeep │ ├── TestCase.php │ └── Unit/ │ └── .gitkeep └── vite.config.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .editorconfig ================================================ root = true [*] charset = utf-8 end_of_line = lf indent_size = 4 indent_style = space insert_final_newline = true trim_trailing_whitespace = true [*.md] trim_trailing_whitespace = false [*.{yml,yaml}] indent_size = 2 [docker-compose.yml] indent_size = 4 ================================================ FILE: .gitattributes ================================================ * text=auto eol=lf *.blade.php diff=html *.css diff=css *.html diff=html *.md diff=markdown *.php diff=php /.github export-ignore CHANGELOG.md export-ignore .styleci.yml export-ignore ================================================ FILE: .github/workflows/code-style.yml ================================================ name: PHP Linting on: pull_request: branches: - 'feature/*' push: branches: - 'main' jobs: phplint: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: "laravel-pint" uses: aglipanci/laravel-pint-action@2.0.0 with: preset: laravel pintVersion: 1.21.2 ================================================ FILE: .github/workflows/image.yml ================================================ name: Build and publish image on: workflow_dispatch: push: branches: - 'develop' - 'main' jobs: build-and-push-image: if: ${{ github.event_name != 'pull_request' }} runs-on: ubuntu-latest permissions: packages: write steps: - name: Checkout repository uses: actions/checkout@v3 - name: Log in to the Container registry uses: docker/login-action@v3 with: registry: https://ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Set image tag id: tag shell: bash run: | if [ "${GITHUB_REF}" = "refs/heads/main" ]; then echo "tag=latest" >> "$GITHUB_OUTPUT" else echo "tag=dev" >> "$GITHUB_OUTPUT" fi - name: Build and push Docker image uses: docker/build-push-action@v5 with: push: true tags: ghcr.io/govigilant/vigilant:${{ steps.tag.outputs.tag }} ================================================ FILE: .github/workflows/package-quality.yml ================================================ name: Package quality on: push: branches: [main] pull_request: jobs: get-packages: runs-on: ubuntu-latest outputs: matrix: ${{ steps.set-matrix.outputs.matrix }} steps: - uses: actions/checkout@v3 - id: set-matrix run: | packages=$(ls -d packages/*/ | sed 's|packages/||; s|/||' | jq -R -s -c 'split("\n")[:-1]') echo "Detected packages: $packages" echo "matrix=$packages" >> $GITHUB_OUTPUT quality: needs: get-packages runs-on: ubuntu-latest strategy: matrix: package: ${{ fromJson(needs.get-packages.outputs.matrix) }} steps: - uses: actions/checkout@v3 - name: Setup PHP uses: shivammathur/setup-php@v2 with: php-version: '8.4' extensions: dom, curl, libxml, mbstring, zip, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick, fileinfo coverage: none - name: Run quality check script run: | chmod +x ./scripts/package-quality.sh ./scripts/package-quality.sh "${{ matrix.package }}" shell: bash ================================================ FILE: .github/workflows/release-image.yml ================================================ name: Build and publish release image on: release: types: [published] jobs: build-and-push-release-image: runs-on: ubuntu-latest permissions: packages: write steps: - name: Checkout repository uses: actions/checkout@v3 - name: Log in to the Container registry uses: docker/login-action@v3 with: registry: https://ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Build and push Docker image with release tag uses: docker/build-push-action@v5 with: push: true tags: ghcr.io/govigilant/vigilant:${{ github.event.release.tag_name }} ================================================ FILE: .github/workflows/tests.yml ================================================ name: Tests on: ['push', 'pull_request'] jobs: tests: runs-on: ubuntu-latest name: Tests steps: - name: Checkout code uses: actions/checkout@v4 - name: Setup PHP uses: shivammathur/setup-php@v2 with: php-version: 8.4 extensions: dom, curl, libxml, mbstring, zip, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick, fileinfo coverage: none - name: Install dependencies run: composer install --prefer-dist --no-interaction - name: Execute tests run: vendor/bin/phpunit ================================================ FILE: .gitignore ================================================ /.phpunit.cache /node_modules /public/build /public/hot /public/storage /public/vendor /public/js /public/css /storage/*.key /vendor .env .env.backup .env.production .phpunit.result.cache Homestead.json Homestead.yaml auth.json npm-debug.log yarn-error.log /.fleet /.idea /.vscode /caddy frankenphp frankenphp-worker.php ================================================ FILE: Dockerfile ================================================ FROM php:8.4-fpm-alpine RUN apk add --no-cache \ bash \ git \ curl \ vim \ unzip \ nginx \ supervisor \ dcron \ su-exec \ nodejs \ npm \ libzip-dev \ libxml2-dev \ icu-dev \ libpng-dev \ libjpeg-turbo-dev \ freetype-dev \ pango \ linux-headers \ python3 \ py3-pip \ py3-cffi \ py3-brotli \ && pip3 install --break-system-packages WeasyPrint RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer RUN docker-php-ext-configure gd --with-freetype --with-jpeg \ && docker-php-ext-install \ pdo \ pdo_mysql \ sockets \ pcntl \ zip \ exif \ bcmath \ intl \ gd RUN apk add --no-cache --virtual .build-deps autoconf g++ make \ && pecl install redis \ && docker-php-ext-enable redis \ && apk del .build-deps COPY . /app WORKDIR /app ENV COMPOSER_ALLOW_SUPERUSER=1 RUN composer install --no-dev --prefer-dist --no-interaction RUN npm install RUN npm run build RUN mkdir -p /tmp/public/ \ && cp -r /app/public/* /tmp/public/ \ && chown -R www-data:www-data /app COPY docker/nginx.conf /etc/nginx/http.d/default.conf COPY docker/php-fpm.ini /usr/local/etc/php/conf.d/zzz-fpm-overrides.ini COPY docker/www.conf /usr/local/etc/php-fpm.d/www.conf # Ensure the socket directory exists and is writable RUN mkdir -p /run && chown www-data:www-data /run RUN /usr/bin/crontab /app/docker/crontab ENTRYPOINT ["sh", "/app/docker/entrypoint.sh"] ================================================ FILE: LICENSE.md ================================================ GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . ================================================ FILE: README.md ================================================

Vigilant Logo

All-in-One Web Monitoring Tool


Vigilant: An application designed to monitor all aspects of your website

Monitor all aspects of your website, uptime, health, DNS, Lighthouse, broken links...
Get notified exactly where and when you want with customizable notifications.
Comes with sensible defaults to quickly get started but customizable to fit your needs.


Explore the docs »

Get started · Join the Discord

![Vigilant Screenshot](https://govigilant.io/screenshot.png) ## Getting Started with Vigilant Quickly get started using the hosted version of Vigilant at [app.govigilant.io](https://app.govigilant.io). Prefer to self-host? Take a look at the [documentation](https://govigilant.io/documentation/welcome) on how to get started! ## Tech Stack - Laravel - Livewire - TailwindCSS - AlpineJS - Redis - MySQL ## License Vigilant is open source under the GNU Affero General Public License Version 3 (AGPLv3) or any later version. ================================================ FILE: SECURITY.md ================================================ # Security Policy ## Introduction Vigilant is committed to ensuring the security and integrity of our users' data. This security policy outlines our procedures for handling security vulnerabilities and our disclosure policy. ## Reporting Security Vulnerabilities If you discover a security vulnerability in Vigilant, please report it to us privately via email to one of the maintainers: * @VincentBean ([email](mailto:security@govigilant.io)) When reporting a security vulnerability, please provide as much detail as possible, including: * A clear description of the vulnerability * Steps to reproduce the vulnerability * Any relevant code or configuration files ## Supported Versions This project currently only supports the latest release. We recommend that users always use the latest version of Vigilant to ensure they have the latest security patches. ## Disclosure Guidelines We follow a private disclosure policy. If you discover a security vulnerability, please report it to us privately via email to one of the maintainers listed above. We will respond promptly to reports of vulnerabilities and work to resolve them as quickly as possible. We will not publicly disclose security vulnerabilities until a patch or fix is available to prevent malicious actors from exploiting the vulnerability before a fix is released. ## Security Vulnerability Response Process We take security vulnerabilities seriously and will respond promptly to reports of vulnerabilities. Our response process includes: * Investigating the report and verifying the vulnerability. * Developing a patch or fix for the vulnerability. * Releasing the patch or fix as soon as possible. * Notifying users of the vulnerability and the patch or fix. ## Template Attribution This SECURITY.md file is based on the [GitHub Security Policy Template](https://docs.github.com/en/code-security/getting-started/adding-a-security-policy-to-your-repository). Thank you for helping to keep Vigilant secure! ================================================ FILE: app/Console/Kernel.php ================================================ command(AggregateResultsCommand::class)->hourly(); $schedule->command(ScheduleUptimeChecksCommand::class)->everySecond(); $schedule->command(CheckUnavailableOutpostsCommand::class)->everyFifteenMinutes(); // Healthchecks $schedule->command(ScheduleHealthchecksCommand::class)->everySecond(); $schedule->command(AggregateMetricsCommand::class)->hourly(); // Lighthouse $schedule->command(ScheduleLighthouseCommand::class)->everySecond(); $schedule->command(AggregateLighthouseResultsCommand::class)->daily(); // Dns $schedule->command(CheckAllDnsRecordsCommand::class)->hourly(); // Crawler $schedule->command(ScheduleCrawlersCommand::class)->everyMinute(); $schedule->command(CrawlUrlsCommand::class)->everyMinute(); $schedule->command(ProcessCrawlerStatesCommand::class)->everyMinute(); // Certificates $schedule->command(CheckCertificatesCommand::class)->everyMinute(); // CVE $schedule->command(ImportCvesCommand::class, ['now - 1 hour'])->everyThirtyMinutes(); // Notifications $schedule->command(CreateNotificationsCommand::class)->daily(); $schedule->command('model:prune', [ '--model' => array_keys(config('core.data_retention')), ])->hourly(); } protected function commands(): void { $this->load(__DIR__.'/Commands'); require base_path('routes/console.php'); } } ================================================ FILE: app/Exceptions/Handler.php ================================================ */ protected $dontFlash = [ 'current_password', 'password', 'password_confirmation', ]; /** * Register the exception handling callbacks for the application. */ public function register(): void { $this->reportable(function (Throwable $e) { // }); } } ================================================ FILE: app/Http/Controllers/Controller.php ================================================ */ protected $middleware = [ // \App\Http\Middleware\TrustHosts::class, \App\Http\Middleware\TrustProxies::class, \Illuminate\Http\Middleware\HandleCors::class, \App\Http\Middleware\PreventRequestsDuringMaintenance::class, \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class, \App\Http\Middleware\TrimStrings::class, \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class, ]; /** * The application's route middleware groups. * * @var array> */ protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, TeamMiddleware::class, RedirectToOnboard::class, EnsureEmailIsVerified::class, ], 'api' => [ // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, \Illuminate\Routing\Middleware\ThrottleRequests::class.':api', \Illuminate\Routing\Middleware\SubstituteBindings::class, ], ]; /** * The application's middleware aliases. * Aliases may be used instead of class names to conveniently assign middleware to routes and groups. * * @var array */ protected $middlewareAliases = [ 'auth' => \App\Http\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class, 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class, 'can' => \Illuminate\Auth\Middleware\Authorize::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class, 'precognitive' => \Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class, 'signed' => \App\Http\Middleware\ValidateSignature::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 'verified' => EnsureEmailIsVerified::class, ]; public function addMiddlewareToGroup(string $group, string|array $middleware): void { $this->middlewareGroups[$group] = array_merge($this->middlewareGroups[$group], Arr::wrap($middleware)); } } ================================================ FILE: app/Http/Middleware/Authenticate.php ================================================ expectsJson() ? null : route('login'); } } ================================================ FILE: app/Http/Middleware/EncryptCookies.php ================================================ */ protected $except = [ // ]; } ================================================ FILE: app/Http/Middleware/PreventRequestsDuringMaintenance.php ================================================ */ protected $except = [ // ]; } ================================================ FILE: app/Http/Middleware/RedirectIfAuthenticated.php ================================================ check()) { return redirect(RouteServiceProvider::HOME); } } return $next($request); } } ================================================ FILE: app/Http/Middleware/TrimStrings.php ================================================ */ protected $except = [ 'current_password', 'password', 'password_confirmation', ]; } ================================================ FILE: app/Http/Middleware/TrustHosts.php ================================================ */ public function hosts(): array { return [ $this->allSubdomainsOfApplicationUrl(), ]; } } ================================================ FILE: app/Http/Middleware/TrustProxies.php ================================================ |string|null */ protected $proxies = '*'; /** * The headers that should be used to detect proxies. * * @var int */ protected $headers = Request::HEADER_X_FORWARDED_FOR | Request::HEADER_X_FORWARDED_HOST | Request::HEADER_X_FORWARDED_PORT | Request::HEADER_X_FORWARDED_PROTO | Request::HEADER_X_FORWARDED_AWS_ELB; } ================================================ FILE: app/Http/Middleware/ValidateSignature.php ================================================ */ protected $except = [ // 'fbclid', // 'utm_campaign', // 'utm_content', // 'utm_medium', // 'utm_source', // 'utm_term', ]; } ================================================ FILE: app/Http/Middleware/VerifyCsrfToken.php ================================================ */ protected $except = [ 'paddle/*', ]; } ================================================ FILE: app/Providers/AppServiceProvider.php ================================================ */ protected $policies = [ ]; /** * Register any authentication / authorization services. */ public function boot(): void { // } } ================================================ FILE: app/Providers/BroadcastServiceProvider.php ================================================ > */ protected $listen = [ Registered::class => [ SendEmailVerificationNotification::class, ], ]; /** * Register any events for your application. */ public function boot(): void { // } /** * Determine if events and listeners should be automatically discovered. */ public function shouldDiscoverEvents(): bool { return false; } } ================================================ FILE: app/Providers/FortifyServiceProvider.php ================================================ input(Fortify::username())).'|'.$request->ip()); return Limit::perMinute(5)->by($throttleKey); }); RateLimiter::for('two-factor', function (Request $request) { return Limit::perMinute(5)->by($request->session()->get('login.id')); }); } } ================================================ FILE: app/Providers/HorizonServiceProvider.php ================================================ configurePermissions(); Jetstream::createTeamsUsing(CreateTeam::class); Jetstream::updateTeamNamesUsing(UpdateTeamName::class); Jetstream::addTeamMembersUsing(AddTeamMember::class); Jetstream::inviteTeamMembersUsing(InviteTeamMember::class); Jetstream::removeTeamMembersUsing(RemoveTeamMember::class); Jetstream::deleteTeamsUsing(DeleteTeam::class); Jetstream::deleteUsersUsing(DeleteUser::class); Jetstream::useUserModel(User::class); Jetstream::useTeamModel(Team::class); Jetstream::useTeamInvitationModel(TeamInvitation::class); Jetstream::useMembershipModel(Membership::class); } /** * Configure the roles and permissions that are available within the application. */ protected function configurePermissions(): void { Jetstream::defaultApiTokenPermissions(['read']); Jetstream::role('admin', 'Administrator', [ 'create', 'read', 'update', 'delete', ])->description('Administrator users can perform any action.'); } } ================================================ FILE: app/Providers/RouteServiceProvider.php ================================================ by($request->user()?->id ?: $request->ip()); }); $this->routes(function () { Route::middleware('api') ->prefix('api') ->group(base_path('routes/api.php')); Route::middleware('web') ->group(base_path('routes/web.php')); }); } } ================================================ FILE: app/View/Components/AppLayout.php ================================================ make(Illuminate\Contracts\Console\Kernel::class); $status = $kernel->handle( $input = new Symfony\Component\Console\Input\ArgvInput, new Symfony\Component\Console\Output\ConsoleOutput ); /* |-------------------------------------------------------------------------- | Shutdown The Application |-------------------------------------------------------------------------- | | Once Artisan has finished running, we will fire off the shutdown events | so that any final work may be done by the application before we shut | down the process. This is the last thing to happen to the request. | */ $kernel->terminate($input, $status); exit($status); ================================================ FILE: bootstrap/app.php ================================================ singleton( Illuminate\Contracts\Http\Kernel::class, App\Http\Kernel::class ); $app->singleton( Illuminate\Contracts\Console\Kernel::class, App\Console\Kernel::class ); $app->singleton( Illuminate\Contracts\Debug\ExceptionHandler::class, App\Exceptions\Handler::class ); /* |-------------------------------------------------------------------------- | Return The Application |-------------------------------------------------------------------------- | | This script returns the application instance. The instance is given to | the calling script so we can separate the building of the instances | from the actual running of the application and sending responses. | */ return $app; ================================================ FILE: bootstrap/cache/.gitignore ================================================ * !.gitignore ================================================ FILE: composer.json ================================================ { "name": "laravel/laravel", "type": "project", "description": "Vigilant: All-in-one website monitoring", "keywords": [ "monitoring", "laravel", "vigilant" ], "license": "AGPL-3.0", "require": { "php": "^8.3", "ext-dom": "*", "blade-ui-kit/blade-heroicons": "^2.3", "bluelibraries/dns": "@dev", "codeat3/blade-carbon-icons": "^2.35", "codeat3/blade-line-awesome-icons": "*", "codeat3/blade-phosphor-icons": "^2.2", "codeat3/blade-simple-icons": "^7.16", "codeat3/blade-teeny-icons": "^1.9", "govigilant/laravel-healthchecks": "^1.0", "guzzlehttp/guzzle": "^7.2", "laravel/framework": "^12.0", "laravel/horizon": "^5.23", "laravel/jetstream": "^5.0", "laravel/sanctum": "^4.0", "laravel/socialite": "^5.18", "laravel/tinker": "^2.8", "league/iso3166": "^4.3", "livewire/livewire": "^3.0", "mallardduck/blade-boxicons": "^2.4", "ramonrietdijk/livewire-tables": "^6.0", "vigilant/certificates": "@dev", "vigilant/core": "@dev", "vigilant/crawler": "@dev", "vigilant/cve": "@dev", "vigilant/dns": "@dev", "vigilant/frontend": "@dev", "vigilant/healthchecks": "@dev", "vigilant/lighthouse": "@dev", "vigilant/notifications": "@dev", "vigilant/onboarding": "@dev", "vigilant/settings": "@dev", "vigilant/sites": "@dev", "vigilant/uptime": "@dev", "vigilant/users": "@dev" }, "require-dev": { "fakerphp/faker": "^1.9.1", "laravel/dusk": "^8.1", "laravel/pint": "^1.0", "laravel/sail": "^1.18", "mockery/mockery": "^1.4.4", "nunomaduro/collision": "^8.1", "phpunit/phpunit": "^11.0", "spatie/laravel-ignition": "^2.0" }, "autoload": { "psr-4": { "App\\": "app/", "Database\\Factories\\": "database/factories/", "Database\\Seeders\\": "database/seeders/" } }, "autoload-dev": { "psr-4": { "Tests\\": "tests/" } }, "scripts": { "post-autoload-dump": [ "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump", "@php artisan package:discover --ansi" ], "post-update-cmd": [ "@php artisan vendor:publish --tag=laravel-assets --ansi --force" ], "post-install-cmd": [ "@php artisan vendor:publish --tag=laravel-assets --ansi --force" ], "post-root-package-install": [ "@php -r \"file_exists('.env') || copy('.env.example', '.env');\"" ], "post-create-project-cmd": [ "@php artisan key:generate --ansi" ] }, "extra": { "laravel": { "dont-discover": [] } }, "config": { "optimize-autoloader": true, "preferred-install": "dist", "sort-packages": true, "allow-plugins": { "pestphp/pest-plugin": true, "php-http/discovery": true } }, "minimum-stability": "dev", "prefer-stable": true, "repositories": [ { "type": "path", "url": "./packages/*" }, { "type": "vcs", "url": "git@github.com:VincentBean/dns.git" } ] } ================================================ FILE: config/app.php ================================================ env('APP_NAME', 'Vigilant'), /* |-------------------------------------------------------------------------- | Application Environment |-------------------------------------------------------------------------- | | This value determines the "environment" your application is currently | running in. This may determine how you prefer to configure various | services the application utilizes. Set this in your ".env" file. | */ 'env' => env('APP_ENV', 'production'), /* |-------------------------------------------------------------------------- | Application Debug Mode |-------------------------------------------------------------------------- | | When your application is in debug mode, detailed error messages with | stack traces will be shown on every error that occurs within your | application. If disabled, a simple generic error page is shown. | */ 'debug' => (bool) env('APP_DEBUG', false), /* |-------------------------------------------------------------------------- | Application URL |-------------------------------------------------------------------------- | | This URL is used by the console to properly generate URLs when using | the Artisan command line tool. You should set this to the root of | your application so that it is used when running Artisan tasks. | */ 'url' => env('APP_URL', 'http://localhost'), 'asset_url' => env('ASSET_URL'), /* |-------------------------------------------------------------------------- | Application Timezone |-------------------------------------------------------------------------- | | Here you may specify the default timezone for your application, which | will be used by the PHP date and date-time functions. We have gone | ahead and set this to a sensible default for you out of the box. | */ 'timezone' => 'UTC', /* |-------------------------------------------------------------------------- | Application Locale Configuration |-------------------------------------------------------------------------- | | The application locale determines the default locale that will be used | by the translation service provider. You are free to set this value | to any of the locales which will be supported by the application. | */ 'locale' => 'en', /* |-------------------------------------------------------------------------- | Application Fallback Locale |-------------------------------------------------------------------------- | | The fallback locale determines the locale to use when the current one | is not available. You may change the value to correspond to any of | the language folders that are provided through your application. | */ 'fallback_locale' => 'en', /* |-------------------------------------------------------------------------- | Faker Locale |-------------------------------------------------------------------------- | | This locale will be used by the Faker PHP library when generating fake | data for your database seeds. For example, this will be used to get | localized telephone numbers, street address information and more. | */ 'faker_locale' => 'en_US', /* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | This key is used by the Illuminate encrypter service and should be set | to a random, 32 character string, otherwise these encrypted strings | will not be safe. Please do this before deploying an application! | */ 'key' => env('APP_KEY'), 'cipher' => 'AES-256-CBC', /* |-------------------------------------------------------------------------- | Maintenance Mode Driver |-------------------------------------------------------------------------- | | These configuration options determine the driver used to determine and | manage Laravel's "maintenance mode" status. The "cache" driver will | allow maintenance mode to be controlled across multiple machines. | | Supported drivers: "file", "cache" | */ 'maintenance' => [ 'driver' => 'file', // 'store' => 'redis', ], /* |-------------------------------------------------------------------------- | Autoloaded Service Providers |-------------------------------------------------------------------------- | | The service providers listed here will be automatically loaded on the | request to your application. Feel free to add your own services to | this array to grant expanded functionality to your applications. | */ 'providers' => ServiceProvider::defaultProviders()->merge([ /* * Package Service Providers... */ /* * Application Service Providers... */ App\Providers\AppServiceProvider::class, App\Providers\AuthServiceProvider::class, // App\Providers\BroadcastServiceProvider::class, App\Providers\EventServiceProvider::class, App\Providers\HorizonServiceProvider::class, App\Providers\RouteServiceProvider::class, App\Providers\FortifyServiceProvider::class, App\Providers\JetstreamServiceProvider::class, ])->toArray(), /* |-------------------------------------------------------------------------- | Class Aliases |-------------------------------------------------------------------------- | | This array of class aliases will be registered when this application | is started. However, feel free to register as many as you wish as | the aliases are "lazy" loaded so they don't hinder performance. | */ 'aliases' => Facade::defaultAliases()->merge([ // 'Example' => App\Facades\Example::class, ])->toArray(), ]; ================================================ FILE: config/auth.php ================================================ [ 'guard' => 'web', 'passwords' => 'users', ], /* |-------------------------------------------------------------------------- | Authentication Guards |-------------------------------------------------------------------------- | | Next, you may define every authentication guard for your application. | Of course, a great default configuration has been defined for you | here which uses session storage and the Eloquent user provider. | | All authentication drivers have a user provider. This defines how the | users are actually retrieved out of your database or other storage | mechanisms used by this application to persist your user's data. | | Supported: "session" | */ 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], ], /* |-------------------------------------------------------------------------- | User Providers |-------------------------------------------------------------------------- | | All authentication drivers have a user provider. This defines how the | users are actually retrieved out of your database or other storage | mechanisms used by this application to persist your user's data. | | If you have multiple user tables or models you may configure multiple | sources which represent each model / table. These sources may then | be assigned to any extra authentication guards you have defined. | | Supported: "database", "eloquent" | */ 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => \Vigilant\Users\Models\User::class, ], // 'users' => [ // 'driver' => 'database', // 'table' => 'users', // ], ], /* |-------------------------------------------------------------------------- | Resetting Passwords |-------------------------------------------------------------------------- | | You may specify multiple password reset configurations if you have more | than one user table or model in the application and you want to have | separate password reset settings based on the specific user types. | | The expiry time is the number of minutes that each reset token will be | considered valid. This security feature keeps tokens short-lived so | they have less time to be guessed. You may change this as needed. | | The throttle setting is the number of seconds a user must wait before | generating more password reset tokens. This prevents the user from | quickly generating a very large amount of password reset tokens. | */ 'passwords' => [ 'users' => [ 'provider' => 'users', 'table' => 'password_reset_tokens', 'expire' => 60, 'throttle' => 60, ], ], /* |-------------------------------------------------------------------------- | Password Confirmation Timeout |-------------------------------------------------------------------------- | | Here you may define the amount of seconds before a password confirmation | times out and the user is prompted to re-enter their password via the | confirmation screen. By default, the timeout lasts for three hours. | */ 'password_timeout' => 10800, ]; ================================================ FILE: config/broadcasting.php ================================================ env('BROADCAST_DRIVER', 'null'), /* |-------------------------------------------------------------------------- | Broadcast Connections |-------------------------------------------------------------------------- | | Here you may define all of the broadcast connections that will be used | to broadcast events to other systems or over websockets. Samples of | each available type of connection are provided inside this array. | */ 'connections' => [ 'pusher' => [ 'driver' => 'pusher', 'key' => env('PUSHER_APP_KEY'), 'secret' => env('PUSHER_APP_SECRET'), 'app_id' => env('PUSHER_APP_ID'), 'options' => [ 'cluster' => env('PUSHER_APP_CLUSTER'), 'host' => env('PUSHER_HOST') ?: 'api-'.env('PUSHER_APP_CLUSTER', 'mt1').'.pusher.com', 'port' => env('PUSHER_PORT', 443), 'scheme' => env('PUSHER_SCHEME', 'https'), 'encrypted' => true, 'useTLS' => env('PUSHER_SCHEME', 'https') === 'https', ], 'client_options' => [ // Guzzle client options: https://docs.guzzlephp.org/en/stable/request-options.html ], ], 'ably' => [ 'driver' => 'ably', 'key' => env('ABLY_KEY'), ], 'redis' => [ 'driver' => 'redis', 'connection' => 'default', ], 'log' => [ 'driver' => 'log', ], 'null' => [ 'driver' => 'null', ], ], ]; ================================================ FILE: config/cache.php ================================================ env('CACHE_DRIVER', 'redis'), /* |-------------------------------------------------------------------------- | Cache Stores |-------------------------------------------------------------------------- | | Here you may define all of the cache "stores" for your application as | well as their drivers. You may even define multiple stores for the | same cache driver to group types of items stored in your caches. | | Supported drivers: "apc", "array", "database", "file", | "memcached", "redis", "dynamodb", "octane", "null" | */ 'stores' => [ 'apc' => [ 'driver' => 'apc', ], 'array' => [ 'driver' => 'array', 'serialize' => false, ], 'database' => [ 'driver' => 'database', 'table' => 'cache', 'connection' => null, 'lock_connection' => null, ], 'file' => [ 'driver' => 'file', 'path' => storage_path('framework/cache/data'), 'lock_path' => storage_path('framework/cache/data'), ], 'memcached' => [ 'driver' => 'memcached', 'persistent_id' => env('MEMCACHED_PERSISTENT_ID'), 'sasl' => [ env('MEMCACHED_USERNAME'), env('MEMCACHED_PASSWORD'), ], 'options' => [ // Memcached::OPT_CONNECT_TIMEOUT => 2000, ], 'servers' => [ [ 'host' => env('MEMCACHED_HOST', '127.0.0.1'), 'port' => env('MEMCACHED_PORT', 11211), 'weight' => 100, ], ], ], 'redis' => [ 'driver' => 'redis', 'connection' => 'cache', 'lock_connection' => 'default', ], 'dynamodb' => [ 'driver' => 'dynamodb', 'key' => env('AWS_ACCESS_KEY_ID'), 'secret' => env('AWS_SECRET_ACCESS_KEY'), 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), 'table' => env('DYNAMODB_CACHE_TABLE', 'cache'), 'endpoint' => env('DYNAMODB_ENDPOINT'), ], 'octane' => [ 'driver' => 'octane', ], ], /* |-------------------------------------------------------------------------- | Cache Key Prefix |-------------------------------------------------------------------------- | | When utilizing the APC, database, memcached, Redis, or DynamoDB cache | stores there might be other applications using the same cache. For | that reason, you may prefix every cache key to avoid collisions. | */ 'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_cache_'), ]; ================================================ FILE: config/cors.php ================================================ ['api/*', 'sanctum/csrf-cookie'], 'allowed_methods' => ['*'], 'allowed_origins' => ['*'], 'allowed_origins_patterns' => [], 'allowed_headers' => ['*'], 'exposed_headers' => [], 'max_age' => 0, 'supports_credentials' => false, ]; ================================================ FILE: config/database.php ================================================ env('DB_CONNECTION', 'mysql'), /* |-------------------------------------------------------------------------- | Database Connections |-------------------------------------------------------------------------- | | Here are each of the database connections setup for your application. | Of course, examples of configuring each database platform that is | supported by Laravel is shown below to make development simple. | | | All database work in Laravel is done through the PHP PDO facilities | so make sure you have the driver for your particular database of | choice installed on your machine before you begin development. | */ 'connections' => [ 'sqlite' => [ 'driver' => 'sqlite', 'url' => env('DATABASE_URL'), 'database' => env('DB_DATABASE', database_path('database.sqlite')), 'prefix' => '', 'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true), ], 'mysql' => [ 'driver' => 'mysql', 'url' => env('DATABASE_URL'), 'host' => env('DB_HOST', '127.0.0.1'), 'port' => env('DB_PORT', '3306'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'unix_socket' => env('DB_SOCKET', ''), 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', 'prefix_indexes' => true, 'strict' => true, 'engine' => null, 'options' => extension_loaded('pdo_mysql') ? array_filter([ PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'), ]) : [], ], 'pgsql' => [ 'driver' => 'pgsql', 'url' => env('DATABASE_URL'), 'host' => env('DB_HOST', '127.0.0.1'), 'port' => env('DB_PORT', '5432'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'charset' => 'utf8', 'prefix' => '', 'prefix_indexes' => true, 'search_path' => 'public', 'sslmode' => 'prefer', ], 'sqlsrv' => [ 'driver' => 'sqlsrv', 'url' => env('DATABASE_URL'), 'host' => env('DB_HOST', 'localhost'), 'port' => env('DB_PORT', '1433'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'charset' => 'utf8', 'prefix' => '', 'prefix_indexes' => true, // 'encrypt' => env('DB_ENCRYPT', 'yes'), // 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'), ], ], /* |-------------------------------------------------------------------------- | Migration Repository Table |-------------------------------------------------------------------------- | | This table keeps track of all the migrations that have already run for | your application. Using this information, we can determine which of | the migrations on disk haven't actually been run in the database. | */ 'migrations' => 'migrations', /* |-------------------------------------------------------------------------- | Redis Databases |-------------------------------------------------------------------------- | | Redis is an open source, fast, and advanced key-value store that also | provides a richer body of commands than a typical key-value system | such as APC or Memcached. Laravel makes it easy to dig right in. | */ 'redis' => [ 'client' => env('REDIS_CLIENT', 'phpredis'), 'options' => [ 'cluster' => env('REDIS_CLUSTER', 'redis'), 'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'), ], 'default' => [ 'url' => env('REDIS_URL'), 'host' => env('REDIS_HOST', '127.0.0.1'), 'username' => env('REDIS_USERNAME'), 'password' => env('REDIS_PASSWORD'), 'port' => env('REDIS_PORT', '6379'), 'database' => env('REDIS_DB', '0'), ], 'cache' => [ 'url' => env('REDIS_URL'), 'host' => env('REDIS_HOST', '127.0.0.1'), 'username' => env('REDIS_USERNAME'), 'password' => env('REDIS_PASSWORD'), 'port' => env('REDIS_PORT', '6379'), 'database' => env('REDIS_CACHE_DB', '1'), ], ], ]; ================================================ FILE: config/filesystems.php ================================================ env('FILESYSTEM_DISK', 'local'), /* |-------------------------------------------------------------------------- | Filesystem Disks |-------------------------------------------------------------------------- | | Here you may configure as many filesystem "disks" as you wish, and you | may even configure multiple disks of the same driver. Defaults have | been set up for each driver as an example of the required values. | | Supported Drivers: "local", "ftp", "sftp", "s3" | */ 'disks' => [ 'local' => [ 'driver' => 'local', 'root' => storage_path('app'), 'throw' => false, ], 'public' => [ 'driver' => 'local', 'root' => storage_path('app/public'), 'url' => env('APP_URL').'/storage', 'visibility' => 'public', 'throw' => false, ], 's3' => [ 'driver' => 's3', 'key' => env('AWS_ACCESS_KEY_ID'), 'secret' => env('AWS_SECRET_ACCESS_KEY'), 'region' => env('AWS_DEFAULT_REGION'), 'bucket' => env('AWS_BUCKET'), 'url' => env('AWS_URL'), 'endpoint' => env('AWS_ENDPOINT'), 'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false), 'throw' => false, ], ], /* |-------------------------------------------------------------------------- | Symbolic Links |-------------------------------------------------------------------------- | | Here you may configure the symbolic links that will be created when the | `storage:link` Artisan command is executed. The array keys should be | the locations of the links and the values should be their targets. | */ 'links' => [ public_path('storage') => storage_path('app/public'), ], ]; ================================================ FILE: config/fortify.php ================================================ 'web', /* |-------------------------------------------------------------------------- | Fortify Password Broker |-------------------------------------------------------------------------- | | Here you may specify which password broker Fortify can use when a user | is resetting their password. This configured value should match one | of your password brokers setup in your "auth" configuration file. | */ 'passwords' => 'users', /* |-------------------------------------------------------------------------- | Username / Email |-------------------------------------------------------------------------- | | This value defines which model attribute should be considered as your | application's "username" field. Typically, this might be the email | address of the users but you are free to change this value here. | | Out of the box, Fortify expects forgot password and reset password | requests to have a field named 'email'. If the application uses | another name for the field you may define it below as needed. | */ 'username' => 'email', 'email' => 'email', /* |-------------------------------------------------------------------------- | Lowercase Usernames |-------------------------------------------------------------------------- | | This value defines whether usernames should be lowercased before saving | them in the database, as some database system string fields are case | sensitive. You may disable this for your application if necessary. | */ 'lowercase_usernames' => true, /* |-------------------------------------------------------------------------- | Home Path |-------------------------------------------------------------------------- | | Here you may configure the path where users will get redirected during | authentication or password reset when the operations are successful | and the user is authenticated. You are free to change this value. | */ 'home' => '/', /* |-------------------------------------------------------------------------- | Fortify Routes Prefix / Subdomain |-------------------------------------------------------------------------- | | Here you may specify which prefix Fortify will assign to all the routes | that it registers with the application. If necessary, you may change | subdomain under which all of the Fortify routes will be available. | */ 'prefix' => '', 'domain' => null, /* |-------------------------------------------------------------------------- | Fortify Routes Middleware |-------------------------------------------------------------------------- | | Here you may specify which middleware Fortify will assign to the routes | that it registers with the application. If necessary, you may change | these middleware but typically this provided default is preferred. | */ 'middleware' => ['web', NoUserMiddleware::class], /* |-------------------------------------------------------------------------- | Rate Limiting |-------------------------------------------------------------------------- | | By default, Fortify will throttle logins to five requests per minute for | every email and IP address combination. However, if you would like to | specify a custom rate limiter to call then you may specify it here. | */ 'limiters' => [ 'login' => 'login', 'two-factor' => 'two-factor', ], /* |-------------------------------------------------------------------------- | Register View Routes |-------------------------------------------------------------------------- | | Here you may specify if the routes returning views should be disabled as | you may not need them when building your own application. This may be | especially true if you're writing a custom single-page application. | */ 'views' => true, /* |-------------------------------------------------------------------------- | Features |-------------------------------------------------------------------------- | | Some of the Fortify features are optional. You may disable the features | by removing them from this array. You're free to only remove some of | these features or you can even remove all of these if you need to. | */ 'features' => [ Features::registration(), Features::resetPasswords(), Features::emailVerification(), Features::updateProfileInformation(), Features::updatePasswords(), Features::twoFactorAuthentication([ 'confirm' => true, 'confirmPassword' => true, // 'window' => 0, ]), ], ]; ================================================ FILE: config/hashing.php ================================================ 'bcrypt', /* |-------------------------------------------------------------------------- | Bcrypt Options |-------------------------------------------------------------------------- | | Here you may specify the configuration options that should be used when | passwords are hashed using the Bcrypt algorithm. This will allow you | to control the amount of time it takes to hash the given password. | */ 'bcrypt' => [ 'rounds' => env('BCRYPT_ROUNDS', 12), 'verify' => true, ], /* |-------------------------------------------------------------------------- | Argon Options |-------------------------------------------------------------------------- | | Here you may specify the configuration options that should be used when | passwords are hashed using the Argon algorithm. These will allow you | to control the amount of time it takes to hash the given password. | */ 'argon' => [ 'memory' => 65536, 'threads' => 1, 'time' => 4, 'verify' => true, ], ]; ================================================ FILE: config/horizon.php ================================================ env('HORIZON_DOMAIN'), /* |-------------------------------------------------------------------------- | Horizon Path |-------------------------------------------------------------------------- | | This is the URI path where Horizon will be accessible from. Feel free | to change this path to anything you like. Note that the URI will not | affect the paths of its internal API that aren't exposed to users. | */ 'path' => env('HORIZON_PATH', 'horizon'), /* |-------------------------------------------------------------------------- | Horizon Redis Connection |-------------------------------------------------------------------------- | | This is the name of the Redis connection where Horizon will store the | meta information required for it to function. It includes the list | of supervisors, failed jobs, job metrics, and other information. | */ 'use' => 'default', /* |-------------------------------------------------------------------------- | Horizon Redis Prefix |-------------------------------------------------------------------------- | | This prefix will be used when storing all Horizon data in Redis. You | may modify the prefix when you are running multiple installations | of Horizon on the same server so that they don't have problems. | */ 'prefix' => env( 'HORIZON_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_horizon:' ), /* |-------------------------------------------------------------------------- | Horizon Route Middleware |-------------------------------------------------------------------------- | | These middleware will get attached onto each Horizon route, giving you | the chance to add your own middleware to this list or change any of | the existing middleware. Or, you can simply stick with this list. | */ 'middleware' => ['web'], /* |-------------------------------------------------------------------------- | Queue Wait Time Thresholds |-------------------------------------------------------------------------- | | This option allows you to configure when the LongWaitDetected event | will be fired. Every connection / queue combination may have its | own, unique threshold (in seconds) before this event is fired. | */ 'waits' => [ 'redis:default' => 60, ], /* |-------------------------------------------------------------------------- | Job Trimming Times |-------------------------------------------------------------------------- | | Here you can configure for how long (in minutes) you desire Horizon to | persist the recent and failed jobs. Typically, recent jobs are kept | for one hour while all failed jobs are stored for an entire week. | */ 'trim' => [ 'recent' => 1440, 'pending' => 1440, 'completed' => 60, 'recent_failed' => 10080, 'failed' => 10080, 'monitored' => 10080, ], /* |-------------------------------------------------------------------------- | Silenced Jobs |-------------------------------------------------------------------------- | | Silencing a job will instruct Horizon to not place the job in the list | of completed jobs within the Horizon dashboard. This setting may be | used to fully remove any noisy jobs from the completed jobs list. | */ 'silenced' => [ // App\Jobs\ExampleJob::class, ], /* |-------------------------------------------------------------------------- | Metrics |-------------------------------------------------------------------------- | | Here you can configure how many snapshots should be kept to display in | the metrics graph. This will get used in combination with Horizon's | `horizon:snapshot` schedule to define how long to retain metrics. | */ 'metrics' => [ 'trim_snapshots' => [ 'job' => 24, 'queue' => 24, ], ], /* |-------------------------------------------------------------------------- | Fast Termination |-------------------------------------------------------------------------- | | When this option is enabled, Horizon's "terminate" command will not | wait on all of the workers to terminate unless the --wait option | is provided. Fast termination can shorten deployment delay by | allowing a new instance of Horizon to start while the last | instance will continue to terminate each of its workers. | */ 'fast_termination' => false, /* |-------------------------------------------------------------------------- | Memory Limit (MB) |-------------------------------------------------------------------------- | | This value describes the maximum amount of memory the Horizon master | supervisor may consume before it is terminated and restarted. For | configuring these limits on your workers, see the next section. | */ 'memory_limit' => 64, /* |-------------------------------------------------------------------------- | Queue Worker Configuration |-------------------------------------------------------------------------- | | Here you may define the queue worker settings used by your application | in all environments. These supervisors and settings handle all your | queued jobs and will be provisioned by Horizon during deployment. | */ 'defaults' => [ 'default' => [ 'connection' => 'redis', 'queue' => ['default'], 'balance' => 'auto', 'autoScalingStrategy' => 'time', 'maxProcesses' => 1, 'maxTime' => 0, 'maxJobs' => 0, 'memory' => 128, 'tries' => 1, 'timeout' => 60, 'nice' => 0, ], 'uptime' => [ 'connection' => 'redis', 'queue' => ['uptime'], 'balance' => 'auto', 'autoScalingStrategy' => 'time', 'minProcesses' => 2, 'maxProcesses' => 4, 'maxTime' => 0, 'maxJobs' => 0, 'memory' => 128, 'tries' => 1, 'timeout' => 60, 'nice' => 0, ], 'lighthouse' => [ 'connection' => 'redis', 'queue' => ['lighthouse'], 'balance' => 'auto', 'autoScalingStrategy' => 'time', 'maxProcesses' => 1, 'maxTime' => 0, 'maxJobs' => 0, 'memory' => 128, 'tries' => 1, 'timeout' => 120, 'nice' => 0, ], 'dns' => [ 'connection' => 'redis', 'queue' => ['dns'], 'balance' => 'auto', 'autoScalingStrategy' => 'time', 'maxProcesses' => 1, 'maxTime' => 0, 'maxJobs' => 0, 'memory' => 128, 'tries' => 1, 'timeout' => 30, 'nice' => 0, ], 'crawler' => [ 'connection' => 'redis', 'queue' => ['crawler'], 'balance' => 'auto', 'autoScalingStrategy' => 'time', 'maxProcesses' => 5, 'maxTime' => 0, 'maxJobs' => 0, 'memory' => 128, 'tries' => 1, 'timeout' => 60, 'nice' => 0, ], 'certificates' => [ 'connection' => 'redis', 'queue' => ['certificates'], 'balance' => 'auto', 'autoScalingStrategy' => 'time', 'maxProcesses' => 5, 'maxTime' => 0, 'maxJobs' => 0, 'memory' => 128, 'tries' => 1, 'timeout' => 30, 'nice' => 0, ], 'cve' => [ 'connection' => 'redis', 'queue' => ['cve'], 'balance' => 'auto', 'autoScalingStrategy' => 'time', 'minProcesses' => 1, 'maxProcesses' => 2, 'maxTime' => 0, 'maxJobs' => 0, 'memory' => 512, 'tries' => 1, 'timeout' => 300, 'nice' => 0, ], 'healthchecks' => [ 'connection' => 'redis', 'queue' => ['healthchecks'], 'balance' => 'auto', 'autoScalingStrategy' => 'time', 'minProcesses' => 1, 'maxProcesses' => 4, 'maxTime' => 0, 'maxJobs' => 0, 'memory' => 512, 'tries' => 1, 'timeout' => 300, 'nice' => 0, ], 'notifications' => [ 'connection' => 'redis', 'queue' => ['notifications'], 'balance' => 'auto', 'autoScalingStrategy' => 'time', 'maxProcesses' => 2, 'maxTime' => 0, 'maxJobs' => 0, 'memory' => 128, 'tries' => 1, 'timeout' => 60, 'nice' => 0, ], ], 'environments' => [ 'production' => [], 'test' => [], 'local' => [], ], ]; ================================================ FILE: config/jetstream.php ================================================ 'livewire', /* |-------------------------------------------------------------------------- | Jetstream Route Middleware |-------------------------------------------------------------------------- | | Here you may specify which middleware Jetstream will assign to the routes | that it registers with the application. When necessary, you may modify | these middleware; however, this default value is usually sufficient. | */ 'middleware' => ['web'], 'auth_session' => AuthenticateSession::class, /* |-------------------------------------------------------------------------- | Jetstream Guard |-------------------------------------------------------------------------- | | Here you may specify the authentication guard Jetstream will use while | authenticating users. This value should correspond with one of your | guards that is already present in your "auth" configuration file. | */ 'guard' => 'sanctum', /* |-------------------------------------------------------------------------- | Features |-------------------------------------------------------------------------- | | Some of Jetstream's features are optional. You may disable the features | by removing them from this array. You're free to only remove some of | these features or you can even remove all of these if you need to. | */ 'features' => [ // Features::termsAndPrivacyPolicy(), // Features::profilePhotos(), // Features::api(), env('EDITION', 'ce') === 'ce' ? '' : Features::teams(['invitations' => true]), Features::accountDeletion(), ], /* |-------------------------------------------------------------------------- | Profile Photo Disk |-------------------------------------------------------------------------- | | This configuration value determines the default disk that will be used | when storing profile photos for your application's users. Typically | this will be the "public" disk but you may adjust this if needed. | */ 'profile_photo_disk' => 'public', ]; ================================================ FILE: config/livewire.php ================================================ 'App\\Livewire', /* |--------------------------------------------------------------------------- | View Path |--------------------------------------------------------------------------- | | This value is used to specify where Livewire component Blade templates are | stored when running file creation commands like `artisan make:livewire`. | It is also used if you choose to omit a component's render() method. | */ 'view_path' => resource_path('views/livewire'), /* |--------------------------------------------------------------------------- | Layout |--------------------------------------------------------------------------- | The view that will be used as the layout when rendering a single component | as an entire page via `Route::get('/post/create', CreatePost::class);`. | In this case, the view returned by CreatePost will render into $slot. | */ 'layout' => 'layouts.app', /* |--------------------------------------------------------------------------- | Lazy Loading Placeholder |--------------------------------------------------------------------------- | Livewire allows you to lazy load components that would otherwise slow down | the initial page load. Every component can have a custom placeholder or | you can define the default placeholder view for all components below. | */ 'lazy_placeholder' => null, /* |--------------------------------------------------------------------------- | Temporary File Uploads |--------------------------------------------------------------------------- | | Livewire handles file uploads by storing uploads in a temporary directory | before the file is stored permanently. All file uploads are directed to | a global endpoint for temporary storage. You may configure this below: | */ 'temporary_file_upload' => [ 'disk' => null, // Example: 'local', 's3' | Default: 'default' 'rules' => null, // Example: ['file', 'mimes:png,jpg'] | Default: ['required', 'file', 'max:12288'] (12MB) 'directory' => null, // Example: 'tmp' | Default: 'livewire-tmp' 'middleware' => null, // Example: 'throttle:5,1' | Default: 'throttle:60,1' 'preview_mimes' => [ // Supported file types for temporary pre-signed file URLs... 'png', 'gif', 'bmp', 'svg', 'wav', 'mp4', 'mov', 'avi', 'wmv', 'mp3', 'm4a', 'jpg', 'jpeg', 'mpga', 'webp', 'wma', ], 'max_upload_time' => 5, // Max duration (in minutes) before an upload is invalidated... ], /* |--------------------------------------------------------------------------- | Render On Redirect |--------------------------------------------------------------------------- | | This value determines if Livewire will run a component's `render()` method | after a redirect has been triggered using something like `redirect(...)` | Setting this to true will render the view once more before redirecting | */ 'render_on_redirect' => false, /* |--------------------------------------------------------------------------- | Eloquent Model Binding |--------------------------------------------------------------------------- | | Previous versions of Livewire supported binding directly to eloquent model | properties using wire:model by default. However, this behavior has been | deemed too "magical" and has therefore been put under a feature flag. | */ 'legacy_model_binding' => false, /* |--------------------------------------------------------------------------- | Auto-inject Frontend Assets |--------------------------------------------------------------------------- | | By default, Livewire automatically injects its JavaScript and CSS into the | and of pages containing Livewire components. By disabling | this behavior, you need to use @livewireStyles and @livewireScripts. | */ 'inject_assets' => true, /* |--------------------------------------------------------------------------- | Navigate (SPA mode) |--------------------------------------------------------------------------- | | By adding `wire:navigate` to links in your Livewire application, Livewire | will prevent the default link handling and instead request those pages | via AJAX, creating an SPA-like effect. Configure this behavior here. | */ 'navigate' => [ 'show_progress_bar' => true, 'progress_bar_color' => '#AF3029', ], /* |--------------------------------------------------------------------------- | HTML Morph Markers |--------------------------------------------------------------------------- | | Livewire intelligently "morphs" existing HTML into the newly rendered HTML | after each update. To make this process more reliable, Livewire injects | "markers" into the rendered Blade surrounding @if, @class & @foreach. | */ 'inject_morph_markers' => true, /* |--------------------------------------------------------------------------- | Pagination Theme |--------------------------------------------------------------------------- | | When enabling Livewire's pagination feature by using the `WithPagination` | trait, Livewire will use Tailwind templates to render pagination views | on the page. If you want Bootstrap CSS, you can specify: "bootstrap" | */ 'pagination_theme' => 'tailwind', ]; ================================================ FILE: config/logging.php ================================================ env('LOG_CHANNEL', 'daily'), /* |-------------------------------------------------------------------------- | Deprecations Log Channel |-------------------------------------------------------------------------- | | This option controls the log channel that should be used to log warnings | regarding deprecated PHP and library features. This allows you to get | your application ready for upcoming major versions of dependencies. | */ 'deprecations' => [ 'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'), 'trace' => false, ], /* |-------------------------------------------------------------------------- | Log Channels |-------------------------------------------------------------------------- | | Here you may configure the log channels for your application. Out of | the box, Laravel uses the Monolog PHP logging library. This gives | you a variety of powerful log handlers / formatters to utilize. | | Available Drivers: "single", "daily", "slack", "syslog", | "errorlog", "monolog", | "custom", "stack" | */ 'channels' => [ 'stack' => [ 'driver' => 'stack', 'channels' => ['single'], 'ignore_exceptions' => false, ], 'single' => [ 'driver' => 'single', 'path' => storage_path('logs/laravel.log'), 'level' => env('LOG_LEVEL', 'info'), 'replace_placeholders' => true, ], 'daily' => [ 'driver' => 'daily', 'path' => storage_path('logs/laravel.log'), 'level' => env('LOG_LEVEL', 'info'), 'days' => 14, 'replace_placeholders' => true, ], 'slack' => [ 'driver' => 'slack', 'url' => env('LOG_SLACK_WEBHOOK_URL'), 'username' => 'Laravel Log', 'emoji' => ':boom:', 'level' => env('LOG_LEVEL', 'critical'), 'replace_placeholders' => true, ], 'papertrail' => [ 'driver' => 'monolog', 'level' => env('LOG_LEVEL', 'debug'), 'handler' => env('LOG_PAPERTRAIL_HANDLER', SyslogUdpHandler::class), 'handler_with' => [ 'host' => env('PAPERTRAIL_URL'), 'port' => env('PAPERTRAIL_PORT'), 'connectionString' => 'tls://'.env('PAPERTRAIL_URL').':'.env('PAPERTRAIL_PORT'), ], 'processors' => [PsrLogMessageProcessor::class], ], 'stderr' => [ 'driver' => 'monolog', 'level' => env('LOG_LEVEL', 'debug'), 'handler' => StreamHandler::class, 'formatter' => env('LOG_STDERR_FORMATTER'), 'with' => [ 'stream' => 'php://stderr', ], 'processors' => [PsrLogMessageProcessor::class], ], 'syslog' => [ 'driver' => 'syslog', 'level' => env('LOG_LEVEL', 'debug'), 'facility' => LOG_USER, 'replace_placeholders' => true, ], 'errorlog' => [ 'driver' => 'errorlog', 'level' => env('LOG_LEVEL', 'debug'), 'replace_placeholders' => true, ], 'null' => [ 'driver' => 'monolog', 'handler' => NullHandler::class, ], 'emergency' => [ 'path' => storage_path('logs/laravel.log'), ], ], ]; ================================================ FILE: config/mail.php ================================================ env('MAIL_MAILER', 'smtp'), /* |-------------------------------------------------------------------------- | Mailer Configurations |-------------------------------------------------------------------------- | | Here you may configure all of the mailers used by your application plus | their respective settings. Several examples have been configured for | you and you are free to add your own as your application requires. | | Laravel supports a variety of mail "transport" drivers to be used while | sending an e-mail. You will specify which one you are using for your | mailers below. You are free to add additional mailers as required. | | Supported: "smtp", "sendmail", "mailgun", "ses", "ses-v2", | "postmark", "log", "array", "failover", "roundrobin" | */ 'mailers' => [ 'smtp' => [ 'transport' => 'smtp', 'url' => env('MAIL_URL'), 'host' => env('MAIL_HOST', 'smtp.mailgun.org'), 'port' => env('MAIL_PORT', 587), 'encryption' => env('MAIL_ENCRYPTION', 'tls'), 'username' => env('MAIL_USERNAME'), 'password' => env('MAIL_PASSWORD'), 'timeout' => null, 'local_domain' => env('MAIL_EHLO_DOMAIN'), 'verify_peer' => env('MAIL_VERIFY_PEER') === 'true', ], 'ses' => [ 'transport' => 'ses', ], 'postmark' => [ 'transport' => 'postmark', // 'message_stream_id' => null, // 'client' => [ // 'timeout' => 5, // ], ], 'mailgun' => [ 'transport' => 'mailgun', // 'client' => [ // 'timeout' => 5, // ], ], 'sendmail' => [ 'transport' => 'sendmail', 'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -bs -i'), ], 'log' => [ 'transport' => 'log', 'channel' => env('MAIL_LOG_CHANNEL'), ], 'array' => [ 'transport' => 'array', ], 'failover' => [ 'transport' => 'failover', 'mailers' => [ 'smtp', 'log', ], ], 'roundrobin' => [ 'transport' => 'roundrobin', 'mailers' => [ 'ses', 'postmark', ], ], ], /* |-------------------------------------------------------------------------- | Global "From" Address |-------------------------------------------------------------------------- | | You may wish for all e-mails sent by your application to be sent from | the same address. Here, you may specify a name and address that is | used globally for all e-mails that are sent by your application. | */ 'from' => [ 'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'), 'name' => env('MAIL_FROM_NAME', 'Example'), ], /* |-------------------------------------------------------------------------- | Markdown Mail Settings |-------------------------------------------------------------------------- | | If you are using Markdown based email rendering, you may configure your | theme and component paths here, allowing you to customize the design | of the emails. Or, you may simply stick with the Laravel defaults! | */ 'markdown' => [ 'theme' => 'default', 'paths' => [ resource_path('views/vendor/mail'), ], ], ]; ================================================ FILE: config/queue.php ================================================ env('QUEUE_CONNECTION', 'redis'), /* |-------------------------------------------------------------------------- | Queue Connections |-------------------------------------------------------------------------- | | Here you may configure the connection information for each server that | is used by your application. A default configuration has been added | for each back-end shipped with Laravel. You are free to add more. | | Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null" | */ 'connections' => [ 'sync' => [ 'driver' => 'sync', ], 'database' => [ 'driver' => 'database', 'table' => 'jobs', 'queue' => 'default', 'retry_after' => 90, 'after_commit' => false, ], 'beanstalkd' => [ 'driver' => 'beanstalkd', 'host' => 'localhost', 'queue' => 'default', 'retry_after' => 90, 'block_for' => 0, 'after_commit' => false, ], 'sqs' => [ 'driver' => 'sqs', 'key' => env('AWS_ACCESS_KEY_ID'), 'secret' => env('AWS_SECRET_ACCESS_KEY'), 'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'), 'queue' => env('SQS_QUEUE', 'default'), 'suffix' => env('SQS_SUFFIX'), 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), 'after_commit' => false, ], 'redis' => [ 'driver' => 'redis', 'connection' => 'default', 'queue' => env('REDIS_QUEUE', 'default'), 'retry_after' => 3600, 'block_for' => null, 'after_commit' => false, ], ], /* |-------------------------------------------------------------------------- | Job Batching |-------------------------------------------------------------------------- | | The following options configure the database and table that store job | batching information. These options can be updated to any database | connection and table which has been defined by your application. | */ 'batching' => [ 'database' => env('DB_CONNECTION', 'mysql'), 'table' => 'job_batches', ], /* |-------------------------------------------------------------------------- | Failed Queue Jobs |-------------------------------------------------------------------------- | | These options configure the behavior of failed queue job logging so you | can control which database and table are used to store the jobs that | have failed. You may change them to any database / table you wish. | */ 'failed' => [ 'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'), 'database' => env('DB_CONNECTION', 'mysql'), 'table' => 'failed_jobs', ], ]; ================================================ FILE: config/sanctum.php ================================================ explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf( '%s%s', 'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1', Sanctum::currentApplicationUrlWithPort() ))), /* |-------------------------------------------------------------------------- | Sanctum Guards |-------------------------------------------------------------------------- | | This array contains the authentication guards that will be checked when | Sanctum is trying to authenticate a request. If none of these guards | are able to authenticate the request, Sanctum will use the bearer | token that's present on an incoming request for authentication. | */ 'guard' => ['web'], /* |-------------------------------------------------------------------------- | Expiration Minutes |-------------------------------------------------------------------------- | | This value controls the number of minutes until an issued token will be | considered expired. This will override any values set in the token's | "expires_at" attribute, but first-party sessions are not affected. | */ 'expiration' => null, /* |-------------------------------------------------------------------------- | Token Prefix |-------------------------------------------------------------------------- | | Sanctum can prefix new tokens in order to take advantage of numerous | security scanning initiatives maintained by open source platforms | that notify developers if they commit tokens into repositories. | | See: https://docs.github.com/en/code-security/secret-scanning/about-secret-scanning | */ 'token_prefix' => env('SANCTUM_TOKEN_PREFIX', ''), /* |-------------------------------------------------------------------------- | Sanctum Middleware |-------------------------------------------------------------------------- | | When authenticating your first-party SPA with Sanctum you may need to | customize some of the middleware Sanctum uses while processing the | request. You may change the middleware listed below as required. | */ 'middleware' => [ 'authenticate_session' => Laravel\Sanctum\Http\Middleware\AuthenticateSession::class, 'encrypt_cookies' => App\Http\Middleware\EncryptCookies::class, 'verify_csrf_token' => App\Http\Middleware\VerifyCsrfToken::class, ], ]; ================================================ FILE: config/services.php ================================================ [ 'domain' => env('MAILGUN_DOMAIN'), 'secret' => env('MAILGUN_SECRET'), 'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'), 'scheme' => 'https', ], 'postmark' => [ 'token' => env('POSTMARK_TOKEN'), ], 'ses' => [ 'key' => env('AWS_ACCESS_KEY_ID'), 'secret' => env('AWS_SECRET_ACCESS_KEY'), 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'), ], 'google' => [ 'enabled' => env('GOOGLE_LOGIN_ENABLED', false), 'client_id' => env('GOOGLE_CLIENT_ID'), 'client_secret' => env('GOOGLE_CLIENT_SECRET'), 'redirect' => env('GOOGLE_REDIRECT_URI'), ], ]; ================================================ FILE: config/session.php ================================================ env('SESSION_DRIVER', 'database'), /* |-------------------------------------------------------------------------- | Session Lifetime |-------------------------------------------------------------------------- | | Here you may specify the number of minutes that you wish the session | to be allowed to remain idle before it expires. If you want them | to immediately expire on the browser closing, set that option. | */ 'lifetime' => env('SESSION_LIFETIME', 1440), 'expire_on_close' => false, /* |-------------------------------------------------------------------------- | Session Encryption |-------------------------------------------------------------------------- | | This option allows you to easily specify that all of your session data | should be encrypted before it is stored. All encryption will be run | automatically by Laravel and you can use the Session like normal. | */ 'encrypt' => false, /* |-------------------------------------------------------------------------- | Session File Location |-------------------------------------------------------------------------- | | When using the native session driver, we need a location where session | files may be stored. A default has been set for you but a different | location may be specified. This is only needed for file sessions. | */ 'files' => storage_path('framework/sessions'), /* |-------------------------------------------------------------------------- | Session Database Connection |-------------------------------------------------------------------------- | | When using the "database" or "redis" session drivers, you may specify a | connection that should be used to manage these sessions. This should | correspond to a connection in your database configuration options. | */ 'connection' => env('SESSION_CONNECTION'), /* |-------------------------------------------------------------------------- | Session Database Table |-------------------------------------------------------------------------- | | When using the "database" session driver, you may specify the table we | should use to manage the sessions. Of course, a sensible default is | provided for you; however, you are free to change this as needed. | */ 'table' => 'sessions', /* |-------------------------------------------------------------------------- | Session Cache Store |-------------------------------------------------------------------------- | | While using one of the framework's cache driven session backends you may | list a cache store that should be used for these sessions. This value | must match with one of the application's configured cache "stores". | | Affects: "apc", "dynamodb", "memcached", "redis" | */ 'store' => env('SESSION_STORE'), /* |-------------------------------------------------------------------------- | Session Sweeping Lottery |-------------------------------------------------------------------------- | | Some session drivers must manually sweep their storage location to get | rid of old sessions from storage. Here are the chances that it will | happen on a given request. By default, the odds are 2 out of 100. | */ 'lottery' => [2, 100], /* |-------------------------------------------------------------------------- | Session Cookie Name |-------------------------------------------------------------------------- | | Here you may change the name of the cookie used to identify a session | instance by ID. The name specified here will get used every time a | new session cookie is created by the framework for every driver. | */ 'cookie' => env( 'SESSION_COOKIE', Str::slug(env('APP_NAME', 'laravel'), '_').'_session' ), /* |-------------------------------------------------------------------------- | Session Cookie Path |-------------------------------------------------------------------------- | | The session cookie path determines the path for which the cookie will | be regarded as available. Typically, this will be the root path of | your application but you are free to change this when necessary. | */ 'path' => '/', /* |-------------------------------------------------------------------------- | Session Cookie Domain |-------------------------------------------------------------------------- | | Here you may change the domain of the cookie used to identify a session | in your application. This will determine which domains the cookie is | available to in your application. A sensible default has been set. | */ 'domain' => env('SESSION_DOMAIN'), /* |-------------------------------------------------------------------------- | HTTPS Only Cookies |-------------------------------------------------------------------------- | | By setting this option to true, session cookies will only be sent back | to the server if the browser has a HTTPS connection. This will keep | the cookie from being sent to you when it can't be done securely. | */ 'secure' => env('SESSION_SECURE_COOKIE'), /* |-------------------------------------------------------------------------- | HTTP Access Only |-------------------------------------------------------------------------- | | Setting this value to true will prevent JavaScript from accessing the | value of the cookie and the cookie will only be accessible through | the HTTP protocol. You are free to modify this option if needed. | */ 'http_only' => true, /* |-------------------------------------------------------------------------- | Same-Site Cookies |-------------------------------------------------------------------------- | | This option determines how your cookies behave when cross-site requests | take place, and can be used to mitigate CSRF attacks. By default, we | will set this value to "lax" since this is a secure default value. | | Supported: "lax", "strict", "none", null | */ 'same_site' => 'lax', /* |-------------------------------------------------------------------------- | Partitioned Cookies |-------------------------------------------------------------------------- | | Setting this value to true will tie the cookie to the top-level site for | a cross-site context. Partitioned cookies are accepted by the browser | when flagged "secure" and the Same-Site attribute is set to "none". | */ 'partitioned' => false, ]; ================================================ FILE: config/view.php ================================================ [ resource_path('views'), ], /* |-------------------------------------------------------------------------- | Compiled View Path |-------------------------------------------------------------------------- | | This option determines where all the compiled Blade templates will be | stored for your application. Typically, this is within the storage | directory. However, as usual, you are free to change this value. | */ 'compiled' => env( 'VIEW_COMPILED_PATH', realpath(storage_path('framework/views')) ), ]; ================================================ FILE: database/.gitignore ================================================ *.sqlite* ================================================ FILE: database/migrations/2019_08_19_000000_create_failed_jobs_table.php ================================================ id(); $table->string('uuid')->unique(); $table->text('connection'); $table->text('queue'); $table->longText('payload'); $table->longText('exception'); $table->timestamp('failed_at')->useCurrent(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('failed_jobs'); } }; ================================================ FILE: database/migrations/2019_12_14_000001_create_personal_access_tokens_table.php ================================================ id(); $table->morphs('tokenable'); $table->string('name'); $table->string('token', 64)->unique(); $table->text('abilities')->nullable(); $table->timestamp('last_used_at')->nullable(); $table->timestamp('expires_at')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('personal_access_tokens'); } }; ================================================ FILE: database/migrations/2024_02_18_184745_create_sessions_table.php ================================================ string('id')->primary(); $table->foreignId('user_id')->nullable()->index(); $table->string('ip_address', 45)->nullable(); $table->text('user_agent')->nullable(); $table->longText('payload'); $table->integer('last_activity')->index(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('sessions'); } }; ================================================ FILE: database/migrations/2024_03_23_092656_create_notifications_table.php ================================================ uuid('id')->primary(); $table->string('type'); $table->morphs('notifiable'); $table->text('data'); $table->timestamp('read_at')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('notifications'); } }; ================================================ FILE: database/seeders/DatabaseSeeder.php ================================================ create(); $latencyMin = 5; $latencyMax = 20; $currentDate = now(); for ($i = 0; $i < 72; $i++) { $currentDate->subHour(); $monitor->aggregatedResults()->create([ 'total_time' => rand($latencyMin, $latencyMax), 'created_at' => $currentDate, 'updated_at' => $currentDate, ]); } } } ================================================ FILE: docker/crontab ================================================ * * * * * /usr/local/bin/php /app/artisan schedule:run >> /app/storage/logs/schedule.log 2>&1 ================================================ FILE: docker/entrypoint.sh ================================================ #!/bin/sh cp -f -r /tmp/public/* /app/public mkdir -p /app/storage/framework/cache mkdir -p /app/storage/framework/sessions mkdir -p /app/storage/framework/views mkdir -p /app/storage/logs chown -R www-data:www-data /app/storage if ! grep -q "^APP_KEY=" ".env" || [ -z "$(grep "^APP_KEY=" ".env" | cut -d '=' -f2)" ]; then php artisan key:generate fi php artisan optimize:clear php artisan migrate --force php artisan storage:link php artisan notifications:create php artisan notifications:rename-classes php artisan optimize /usr/bin/supervisord -c /app/docker/supervisor/supervisor.conf ================================================ FILE: docker/horizon-entrypoint.sh ================================================ #!/bin/sh mkdir -p /app/storage/framework/cache mkdir -p /app/storage/framework/sessions mkdir -p /app/storage/framework/views mkdir -p /app/storage/logs chown -R www-data:www-data /app/storage exec su-exec www-data php artisan horizon ================================================ FILE: docker/nginx.conf ================================================ server { listen 8000; server_name _; root /app/public; index index.php; access_log /app/storage/logs/nginx-access.log; error_log /app/storage/logs/nginx-error.log; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 30; keepalive_requests 1000; gzip on; gzip_comp_level 5; gzip_min_length 256; gzip_proxied any; gzip_vary on; gzip_types application/javascript application/json application/xml application/rss+xml text/css text/javascript text/plain text/xml image/svg+xml; location ~* \.(css|js|ico|gif|jpe?g|png|webp|avif|svg|woff2?|ttf|eot|otf)$ { expires 30d; access_log off; add_header Cache-Control "public, immutable"; try_files $uri /index.php?$query_string; } location / { try_files $uri $uri/ /index.php?$query_string; } location = /index.php { fastcgi_pass unix:/run/php-fpm.sock; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; fastcgi_read_timeout 300; fastcgi_buffering on; fastcgi_buffer_size 16k; fastcgi_buffers 16 16k; fastcgi_busy_buffers_size 32k; } location ~ \.php$ { return 404; } location ~ /\.ht { deny all; } } ================================================ FILE: docker/php-fpm.ini ================================================ max_execution_time = 300 max_input_time = 60 memory_limit = 256M expose_php = Off display_errors = Off log_errors = On error_log = /app/storage/logs/php-errors.log error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT opcache.enable = 1 opcache.memory_consumption = 256 opcache.interned_strings_buffer = 16 opcache.max_accelerated_files = 20000 opcache.validate_timestamps = 0 opcache.save_comments = 1 opcache.enable_file_override = 1 opcache.preload = /app/docker/preload.php opcache.preload_user = www-data opcache.jit_buffer_size = 64M opcache.jit = 1255 realpath_cache_size = 4096K realpath_cache_ttl = 600 ================================================ FILE: docker/preload.php ================================================ 'certificates', ]; ================================================ FILE: packages/certificates/database/migrations/2025_04_08_200000_create_create_certificate_monitors_table.php ================================================ id(); $table->foreignIdFor(Site::class)->nullable()->constrained()->onDelete('cascade'); $table->foreignIdFor(Team::class)->constrained()->onDelete('cascade'); $table->boolean('enabled')->default(true); $table->dateTime('next_check')->nullable(); $table->string('domain'); $table->integer('port')->default(443); $table->string('serial_number')->nullable(); $table->string('protocol')->nullable(); $table->string('fingerprint')->nullable(); $table->dateTime('valid_from')->nullable(); $table->dateTime('valid_to')->nullable(); $table->json('data')->nullable(); $table->timestamps(); }); } public function down(): void { Schema::dropIfExists('certificate_monitors'); } }; ================================================ FILE: packages/certificates/database/migrations/2025_04_12_090000_create_create_certificate_monitor_history_table.php ================================================ id(); $table->foreignIdFor(CertificateMonitor::class)->nullable()->constrained()->onDelete('cascade'); $table->foreignIdFor(Team::class)->constrained()->onDelete('cascade'); $table->string('serial_number')->nullable(); $table->string('protocol')->nullable(); $table->string('fingerprint')->nullable(); $table->dateTime('valid_from')->nullable(); $table->dateTime('valid_to')->nullable(); $table->json('data')->nullable(); $table->timestamps(); }); } public function down(): void { Schema::dropIfExists('certificate_monitor_histories'); } }; ================================================ FILE: packages/certificates/phpstan.neon ================================================ includes: - ./vendor/larastan/larastan/extension.neon - ./vendor/phpstan/phpstan-mockery/extension.neon parameters: paths: - src - tests level: 8 ignoreErrors: - identifier: missingType.iterableValue - identifier: missingType.generics ================================================ FILE: packages/certificates/phpunit.xml ================================================ ./tests/* ./src ================================================ FILE: packages/certificates/resources/navigation.php ================================================ parent('infrastructure') ->icon('phosphor-certificate') ->gate('use-certificates') ->routeIs('certificate*') ->sort(600); ================================================ FILE: packages/certificates/resources/views/components/empty-states/monitors.blade.php ================================================ ================================================ FILE: packages/certificates/resources/views/index.blade.php ================================================ @lang('Add Certificate Monitor') @lang('Add Certificate Monitor') @if ($hasMonitors) @else @endif ================================================ FILE: packages/certificates/resources/views/livewire/certificate-monitor-form.blade.php ================================================
@if (!$inline) @endif
@if (!$inline) @endif @if (!$inline) @endif
================================================ FILE: packages/certificates/resources/views/livewire/monitor/dashboard.blade.php ================================================
@if ($monitor->valid_to === null) @lang('Unknown') @elseif ($monitor->valid_to->isPast()) @lang('Expired :diff ago', ['diff' => $monitor->valid_to->longAbsoluteDiffForHumans()]) @else @lang('Expires in :diff', ['diff' => $monitor->valid_to->longAbsoluteDiffForHumans()]) @endif @if ($monitor->valid_from === null) @lang('Unknown') @else {{ $monitor->valid_from->toDatetimeString() }} @endif @if ($monitor->valid_to === null) @lang('Unknown') @else {{ $monitor->valid_to->toDatetimeString() }} @endif @if (data_get($monitor->data ?? [], 'issuer.CN') === null) @lang('Unknown') @else {{ data_get($monitor->data, 'issuer.CN') }} @endif
================================================ FILE: packages/certificates/resources/views/monitor/index.blade.php ================================================ @lang('Edit') @lang('Delete') @lang('Edit') @lang('Delete')

{{ __('History') }}

@lang('View the history of this certificate monitor.')

@lang('Delete Certificate Monitor')

@lang('Are you sure you want to delete this certificate monitor?')

@svg('phosphor-warning-circle', 'w-5 h-5 text-orange mt-0.5')

{{ $monitor->domain }}

@lang('This action cannot be undone. All certificate history for this monitor will be permanently deleted.')

@lang('Cancel')
@csrf @method('DELETE') @lang('Delete Monitor')
================================================ FILE: packages/certificates/routes/web.php ================================================ group(function () { Route::get('/', [CertificateMonitorController::class, 'list'])->name('certificates'); Route::get('/create', CertificateMonitorForm::class)->name('certificates.create'); Route::get('/{monitor}', [CertificateMonitorController::class, 'index'])->name('certificates.index')->can('view,monitor'); Route::get('/edit/{monitor}', CertificateMonitorForm::class)->name('certificates.edit'); Route::delete('/{monitor}', [CertificateMonitorController::class, 'delete'])->name('certificates.delete')->can('delete,monitor'); }); ================================================ FILE: packages/certificates/src/Actions/CheckCertificate.php ================================================ [ 'capture_peer_cert' => true, 'verify_peer' => false, 'verify_peer_name' => false, ], ]); $client = @stream_socket_client( "ssl://{$monitor->domain}:{$monitor->port}", $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $context ); if ($client === false) { UnableToResolveCertificateNotification::notify($monitor, $errstr); return; } $metadata = stream_get_meta_data($client); $contParams = stream_context_get_params($client); $certificate = openssl_x509_parse($contParams['options']['ssl']['peer_certificate']); if ($certificate === false) { UnableToResolveCertificateNotification::notify($monitor, 'Unable to parse certificate'); return; } $fingerprint = openssl_x509_fingerprint($contParams['options']['ssl']['peer_certificate'], 'sha256'); $validTo = Carbon::createFromTimestampUTC(data_get($certificate, 'validTo_time_t')); if ($validTo->isAfter(now()->addDays(30))) { $nextCheck = now()->addDays(30); } elseif ($validTo->isAfter(now()->addDays(7))) { $nextCheck = now()->addDays(7); } else { $nextCheck = $validTo->subDay(); if ($nextCheck->isPast()) { $nextCheck = now()->addHours(3); } } if ($validTo->isPast()) { CertificateExpiredNotification::notify($monitor); } else { } if ($monitor->fingerprint !== $fingerprint) { $history = $monitor->history()->create([ 'serial_number' => data_get($certificate, 'serialNumber'), 'protocol' => data_get($metadata, 'crypto.protocol'), 'fingerprint' => $fingerprint, 'valid_from' => Carbon::createFromTimestampUTC(data_get($certificate, 'validFrom_time_t')), 'valid_to' => $validTo, 'data' => array_merge( $certificate, [ 'metadata' => $metadata, ] ), ]); CertificateChangedNotification::notify($monitor, $history); } $monitor->update([ 'next_check' => $nextCheck, 'serial_number' => data_get($certificate, 'serialNumber'), 'protocol' => data_get($metadata, 'crypto.protocol'), 'fingerprint' => $fingerprint, 'valid_from' => Carbon::createFromTimestampUTC(data_get($certificate, 'validFrom_time_t')), 'valid_to' => $validTo, 'data' => array_merge( $certificate, [ 'metadata' => $metadata, ] ), ]); if ($validTo->isFuture()) { CertificateExpiresInDaysNotification::notify($monitor); } } } ================================================ FILE: packages/certificates/src/Commands/CheckCertificateCommand.php ================================================ argument('id'); $monitor = CertificateMonitor::query() ->withoutGlobalScopes() ->findOrFail($id); CheckCertificateJob::dispatch($monitor); return static::SUCCESS; } } ================================================ FILE: packages/certificates/src/Commands/CheckCertificatesCommand.php ================================================ withoutGlobalScopes() ->where('enabled', '=', true) ->where(function (Builder $query): void { $query->where('next_check', '<=', now()) ->orWhereNull('next_check'); }) ->get() ->each(fn (CertificateMonitor $monitor): PendingDispatch => CheckCertificateJob::dispatch($monitor)); return static::SUCCESS; } } ================================================ FILE: packages/certificates/src/Http/Controllers/CertificateMonitorController.php ================================================ exists(); return view($view, [ 'hasMonitors' => $hasMonitors, ]); } public function index(CertificateMonitor $monitor): mixed { /** @var view-string $view */ $view = 'certificates::monitor.index'; return view($view, [ 'monitor' => $monitor, ]); } public function delete(CertificateMonitor $monitor): RedirectResponse { $monitor->delete(); $this->alert( __('Deleted'), __('Certificate monitor was successfully deleted'), AlertType::Success ); return response()->redirectToRoute('certificates'); } } ================================================ FILE: packages/certificates/src/Jobs/CheckCertificateJob.php ================================================ onQueue(config()->string('certificates.queue')); } public function handle(CheckCertificate $certificate, TeamService $teamService): void { $teamService->setTeamById($this->monitor->team_id); $certificate->check($this->monitor); } public function uniqueId(): int { return $this->monitor->id; } } ================================================ FILE: packages/certificates/src/Livewire/CertificateMonitorForm.php ================================================ exists) { $this->authorize('update', $monitor); } else { $this->authorize('create', $monitor); } $this->form->fill($monitor->toArray()); $this->certificateMonitor = $monitor; } } #[On('save')] public function save(): void { $this->validate(); if ($this->certificateMonitor->exists) { $this->authorize('update', $this->certificateMonitor); $this->certificateMonitor->update($this->form->all()); } else { $this->authorize('create', $this->certificateMonitor); $this->certificateMonitor = CertificateMonitor::query()->create( $this->form->all() ); } if (! $this->inline) { $this->alert( __('Saved'), __('Certificate monitor was successfully :action', ['action' => $this->certificateMonitor->wasRecentlyCreated ? 'created' : 'saved']), AlertType::Success ); $this->redirectRoute('certificates.index', ['monitor' => $this->certificateMonitor]); } } public function render(): mixed { /** @var view-string $view */ $view = 'certificates::livewire.certificate-monitor-form'; return view($view, [ 'updating' => $this->certificateMonitor->exists, ]); } } ================================================ FILE: packages/certificates/src/Livewire/Forms/CertificateMonitorForm.php ================================================ ['boolean', new CanEnableRule(CertificateMonitor::class)], 'domain' => ['required', 'string', 'max:255', new CleanDomainValidator, new Fqdn], ] ); } } ================================================ FILE: packages/certificates/src/Livewire/Monitor/Dashboard.php ================================================ monitorId = $monitorId; } public function render(): mixed { $monitor = CertificateMonitor::query()->findOrFail($this->monitorId); /** @var view-string $view */ $view = 'certificates::livewire.monitor.dashboard'; return view($view, [ 'monitor' => $monitor, ]); } } ================================================ FILE: packages/certificates/src/Livewire/Tables/CertificateMonitorHistoryTable.php ================================================ monitorId = $monitorId; } protected function columns(): array { return [ Column::make(__('Domain'), 'certificateMonitor.domain') ->sortable() ->searchable(), DateColumn::make(__('Changed At'), 'created_at') ->sortable(), Column::make(__('Issuer')) ->displayUsing(function (CertificateMonitorHistory $monitor): string { return data_get($monitor->data ?? [], 'issuer.CN', __('Unknown')); }), DateColumn::make(__('Valid From'), 'valid_from') ->sortable() ->searchable(), DateColumn::make(__('Valid To'), 'valid_to') ->sortable() ->searchable(), Column::make(__('Protocol'), 'protocol') ->hide() ->sortable() ->searchable(), ]; } protected function query(): Builder { return parent::query() ->where('certificate_monitor_id', '=', $this->monitorId); } } ================================================ FILE: packages/certificates/src/Livewire/Tables/CertificateMonitorsTable.php ================================================ sortable() ->searchable(), StatusColumn::make(__('Expires In'), 'valid_to', 'expires_in') ->sortable() ->text(function (CertificateMonitor $monitor): string { if (! $monitor->enabled) { return __('Disabled'); } if ($monitor->valid_to === null) { return __('Unknown'); } if ($monitor->valid_to->isPast()) { return __('Expired'); } return $monitor->valid_to->longRelativeDiffForHumans(); }) ->status(function (CertificateMonitor $monitor): Status { if (! $monitor->enabled) { return Status::Danger; } if ($monitor->valid_to === null) { return Status::Danger; } if ($monitor->valid_to->isPast()) { return Status::Danger; } if ($monitor->valid_to->greaterThan(now()->addWeek())) { return Status::Success; } return Status::Warning; }), Column::make(__('Issuer')) ->displayUsing(function (CertificateMonitor $monitor): string { return data_get($monitor->data ?? [], 'issuer.CN', __('Unknown')); }), DateColumn::make(__('Valid From'), 'valid_from') ->sortable() ->searchable(), DateColumn::make(__('Valid To'), 'valid_to') ->sortable() ->searchable(), Column::make(__('Protocol'), 'protocol') ->hide() ->sortable() ->searchable(), ]; } protected function filters(): array { return [ SelectFilter::make(__('Site'), 'site_id') ->options( Site::query() ->orderBy('url') ->pluck('url', 'id') ->toArray() ), ]; } protected function actions(): array { return [ Action::make(__('Check Now'), function (Enumerable $models): void { $models->each(fn (CertificateMonitor $monitor) => CheckCertificateJob::dispatch($monitor)); }, 'run'), Action::make(__('Enable'), function (Enumerable $models): void { foreach ($models as $model) { if (! Gate::allows('create', $model)) { break; } $model->update(['enabled' => true]); } }, 'enable'), Action::make(__('Disable'), function (Enumerable $models): void { $models->each(fn (CertificateMonitor $monitor) => $monitor->update(['enabled' => false])); }, 'disable'), Action::make(__('Delete'), function (Enumerable $models): void { $models->each(fn (CertificateMonitor $monitor): ?bool => $monitor->delete()); }, 'delete'), ]; } protected function link(Model $model): ?string { return route('certificates.index', ['monitor' => $model]); } } ================================================ FILE: packages/certificates/src/Models/CertificateMonitor.php ================================================ $history */ #[ObservedBy(TeamObserver::class)] #[ScopedBy(TeamScope::class)] class CertificateMonitor extends Model { protected $guarded = []; protected $casts = [ 'enabled' => 'boolean', 'next_check' => 'datetime', 'valid_from' => 'datetime', 'valid_to' => 'datetime', 'data' => 'array', ]; public function history(): HasMany { return $this->hasMany(CertificateMonitorHistory::class); } public function site(): BelongsTo { return $this->belongsTo(Site::class); } public function team(): BelongsTo { return $this->belongsTo(Team::class); } } ================================================ FILE: packages/certificates/src/Models/CertificateMonitorHistory.php ================================================ 'datetime', 'valid_to' => 'datetime', 'data' => 'array', ]; public function certificateMonitor(): BelongsTo { return $this->belongsTo(CertificateMonitor::class); } public function team(): BelongsTo { return $this->belongsTo(Team::class); } public function prunable(): Builder { return static::withoutGlobalScopes()->where('created_at', '<=', $this->retentionPeriod()); } } ================================================ FILE: packages/certificates/src/Notifications/CertificateChangedNotification.php ================================================ $this->monitor->domain, ]); } public function description(): string { return __('The certificate on :domain has been updated. The new expiration date is :validto, old expiration date was :oldvalidto', [ 'domain' => $this->monitor->domain, 'validto' => $this->monitor->valid_to?->toDateString() ?? '?', 'oldvalidto' => $this->old->valid_to?->toDateString() ?? '?', ]); } public static function info(): ?string { return __('Triggered when an SSL certificate is replaced or renewed.'); } public function uniqueId(): string|int { return $this->monitor->id; } public function site(): ?Site { return $this->monitor->site; } } ================================================ FILE: packages/certificates/src/Notifications/CertificateExpiredNotification.php ================================================ $this->monitor->domain, 'validto' => $this->monitor->valid_to?->toDateString() ?? '?', ]); } public static function info(): ?string { return __('Triggered when an SSL certificate has expired.'); } public function uniqueId(): string|int { return $this->monitor->id; } public function site(): ?Site { return $this->monitor->site; } } ================================================ FILE: packages/certificates/src/Notifications/CertificateExpiresInDaysNotification.php ================================================ 'group', 'children' => [ [ 'type' => 'condition', 'condition' => DaysCondition::class, 'value' => 14, ], ], ]; public function __construct(public CertificateMonitor $monitor) {} public function title(): string { return __('The certificate on :domain will expire in :difference', [ 'domain' => $this->monitor->domain, 'difference' => $this->monitor->valid_to?->shortAbsoluteDiffForHumans() ?? '?', ]); } public function description(): string { return __('The certificate on :domain will expire on :date which is :difference', [ 'domain' => $this->monitor->domain, 'validto' => $this->monitor->valid_to?->shortAbsoluteDiffForHumans() ?? '?', 'date' => $this->monitor->valid_to?->toDateString() ?? '?', ]); } public static function info(): ?string { return __('Triggered when an SSL certificate is approaching expiration.'); } public function uniqueId(): string|int { return $this->monitor->id; } public function site(): ?Site { return $this->monitor->site; } } ================================================ FILE: packages/certificates/src/Notifications/Conditions/DaysCondition.php ================================================ monitor->valid_to; if ($validTo === null) { return false; } return $validTo->diffInDays(now()) <= $value && $validTo->diffInDays(now()) > 0; } } ================================================ FILE: packages/certificates/src/Notifications/UnableToResolveCertificateNotification.php ================================================ $this->monitor->domain, ]); } public function description(): string { return __('Error: :error', [ 'error' => $this->error, ]); } public static function info(): ?string { return __('Triggered when an SSL certificate cannot be retrieved or validated.'); } public function uniqueId(): string|int { return $this->monitor->id; } public function site(): ?Site { return $this->monitor->site; } } ================================================ FILE: packages/certificates/src/ServiceProvider.php ================================================ registerConfig(); } protected function registerConfig(): static { $this->mergeConfigFrom(__DIR__.'/../config/certificates.php', 'certificates'); return $this; } public function boot(): void { $this ->bootRoutes() ->bootConfig() ->bootMigrations() ->bootCommands() ->bootViews() ->bootLivewire() ->bootNavigation() ->bootNotifications() ->bootGates() ->bootPolicies(); } protected function bootRoutes(): static { if (! $this->app->routesAreCached()) { Route::middleware(['web', 'auth']) ->group(fn () => $this->loadRoutesFrom(__DIR__.'/../routes/web.php')); } return $this; } protected function bootConfig(): static { $this->publishes([ __DIR__.'/../config/certificates.php' => config_path('certificates.php'), ], 'config'); return $this; } protected function bootMigrations(): static { $this->loadMigrationsFrom(__DIR__.'/../database/migrations'); return $this; } protected function bootCommands(): static { if ($this->app->runningInConsole()) { $this->commands([ CheckCertificateCommand::class, CheckCertificatesCommand::class, ]); } return $this; } protected function bootViews(): static { $this->loadViewsFrom(__DIR__.'/../resources/views', 'certificates'); return $this; } protected function bootLivewire(): static { Livewire::component('certificate-monitor-table', CertificateMonitorsTable::class); Livewire::component('certificate-monitor-history-table', CertificateMonitorHistoryTable::class); Livewire::component('certificate-monitor-form', CertificateMonitorForm::class); Livewire::component('certificate-monitor-dashboard', Dashboard::class); return $this; } protected function bootNavigation(): static { Navigation::path(__DIR__.'/../resources/navigation.php'); return $this; } protected function bootNotifications(): static { NotificationRegistry::registerNotification([ CertificateExpiresInDaysNotification::class, CertificateExpiredNotification::class, ]); NotificationRegistry::registerCondition(CertificateExpiresInDaysNotification::class, [ SiteCondition::class, DaysCondition::class, ]); NotificationRegistry::registerCondition(CertificateExpiredNotification::class, [ SiteCondition::class, ]); return $this; } protected function bootGates(): static { if (ce()) { Gate::define('use-certificates', function (User $user): bool { return ce(); }); } return $this; } protected function bootPolicies(): static { if (ce()) { Gate::policy(CertificateMonitor::class, AllowAllPolicy::class); } return $this; } } ================================================ FILE: packages/certificates/testbench.yaml ================================================ providers: - Vigilant\Certificates\ServiceProvider ================================================ FILE: packages/certificates/tests/TestCase.php ================================================ set('database.default', 'testbench'); $app['config']->set('database.connections.testbench', [ 'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '', ]); } } ================================================ FILE: packages/core/.gitignore ================================================ vendor composer.lock .phpunit.result.cache ================================================ FILE: packages/core/composer.json ================================================ { "name": "vigilant/core", "description": "Vigilant Core", "type": "package", "license": "AGPL", "authors": [ { "name": "Vincent Boon", "email": "info@vincentbean.com", "role": "Developer" } ], "require": { "php": "^8.3", "laravel/framework": "^12.0", "vigilant/certificates": "@dev", "vigilant/crawler": "@dev", "vigilant/cve": "@dev", "vigilant/dns": "@dev", "vigilant/frontend": "@dev", "vigilant/lighthouse": "@dev", "vigilant/notifications": "@dev", "vigilant/onboarding": "@dev", "vigilant/settings": "@dev", "vigilant/sites": "@dev", "vigilant/uptime": "@dev", "vigilant/users": "@dev" }, "require-dev": { "laravel/pint": "^1.6", "larastan/larastan": "^3.0", "orchestra/testbench": "^10.0", "phpstan/phpstan-mockery": "^2.0", "phpunit/phpunit": "^11.0" }, "autoload": { "psr-4": { "Vigilant\\Core\\": "src" }, "files": [ "src/helpers.php" ] }, "autoload-dev": { "psr-4": { "Vigilant\\Core\\Tests\\": "tests" } }, "scripts": { "test": "phpunit", "analyse": "phpstan", "style": "pint --test", "quality": [ "@test", "@analyse" ] }, "config": { "sort-packages": true, "allow-plugins": { "php-http/discovery": true } }, "extra": { "laravel": { "providers": [ "Vigilant\\Core\\ServiceProvider" ], "aliases": { "Navigation": "Vigilant\\Core\\Facades\\Navigation" } } }, "minimum-stability": "dev", "prefer-stable": true, "repositories": [ { "type": "path", "url": "../*" } ] } ================================================ FILE: packages/core/config/core.php ================================================ env('EDITION', 'ce'), 'user_agent' => 'Vigilant Bot', 'data_retention' => [ DnsMonitorHistory::class => env('DATA_RETENTION_DNS_MONITOR_HISTORY', 180), Downtime::class => env('DATA_RETENTION_DOWNTIME', 730), Result::class => env('DATA_RETENTION_UPTIME_RESULT', 180), LighthouseResult::class => env('DATA_RETENTION_LIGHTHOUSE', 180), History::class => env('DATA_RETENTION_NOTIFICATION_HISTORY', 90), CertificateMonitorHistory::class => env('DATA_RETENTION_CERTIFICATE_MONITOR_HISTORY', 180), HealthcheckResult::class => env('DATA_RETENTION_HEALTHCHECK_RESULT', 180), Metric::class => env('DATA_RETENTION_HEALTHCHECK_METRIC', 180), ], ]; ================================================ FILE: packages/core/phpstan.neon ================================================ includes: - ./vendor/larastan/larastan/extension.neon - ./vendor/phpstan/phpstan-mockery/extension.neon parameters: paths: - src - tests level: 8 ignoreErrors: - identifier: missingType.iterableValue - identifier: missingType.generics - identifier: trait.unused ================================================ FILE: packages/core/phpunit.xml ================================================ ./tests/* ./src ================================================ FILE: packages/core/resources/navigation.php ================================================ code('health') ->icon('phosphor-heart-half-duotone') ->sort(200); Navigation::add(null, 'Performance') ->code('performance') ->icon('carbon-chart-line-smooth') ->sort(300); Navigation::add(null, 'Infrastructure') ->code('infrastructure') ->icon('carbon-cloud-monitoring') ->sort(400); ================================================ FILE: packages/core/routes/web.php ================================================ subDays($days); } } ================================================ FILE: packages/core/src/Concerns/HasDataRetention.php ================================================ resolve(static::class); } } ================================================ FILE: packages/core/src/Contracts/ResolvesDataRetention.php ================================================ validate($data); } public function offsetExists(mixed $offset): bool { return array_key_exists($offset, $this->data); } public function offsetGet(mixed $offset): mixed { return $this->data[$offset] ?? null; } public function offsetSet(mixed $offset, mixed $value): void { $this->data[$offset] = $value; } public function offsetUnset(mixed $offset): void { unset($this->data[$offset]); } public function validate(array $data): void { Validator::make($data, $this->rules)->validate(); } public static function of(array $data): static { return new static($data); } public function toArray(): array { return $this->data; } } ================================================ FILE: packages/core/src/Facades/Navigation.php ================================================ teamService->fromAuth(); return $next($request); } } ================================================ FILE: packages/core/src/Navigation/Navigation.php ================================================ paths[] = $path; return $this; } public function add( ?string $url, string $name, ): NavigationItem { $item = new NavigationItem($name, $url); $this->items[] = $item; return $item; } public function items(): array { if (! $this->loaded) { foreach ($this->paths as $path) { require $path; } $this->loaded = true; } return collect($this->items) ->map(function (NavigationItem $item) { if ($item->parent !== null) { return null; } $children = collect($this->items) ->filter(fn (NavigationItem $child) => $child->parent === $item->code) ->sortBy('sort') ->toArray(); $item->children = $children; return $item; }) ->whereNotNull() ->sortBy('sort') ->toArray(); } } ================================================ FILE: packages/core/src/Navigation/NavigationItem.php ================================================ code = str($name) ->slug() ->replace('-', '_') ->toString(); } } public function active(): bool { if ($this->routeIs !== null) { return Route::is($this->routeIs); } return request()->url() === $this->url; } public function shouldRender(): bool { if ($this->gate === null) { return true; } return Gate::check($this->gate); } public function name(string $name): static { $this->name = $name; return $this; } public function routeIs(string ...$routeIs): static { $this->routeIs = $routeIs; return $this; } public function url(string $url): static { $this->url = $url; return $this; } public function icon(string $icon): static { $this->icon = $icon; return $this; } public function gate(string $gate): static { $this->gate = $gate; return $this; } public function sort(int $sort): static { $this->sort = $sort; return $this; } public function code(string $code): static { $this->code = $code; return $this; } public function parent(string $parent): static { $this->parent = $parent; return $this; } public function hasChildren(): bool { return count($this->children) > 0; } public function getChildren(): array { return $this->children; } } ================================================ FILE: packages/core/src/Policies/AllowAllPolicy.php ================================================ team(); $builder->where($model->qualifyColumn('team_id'), '=', $team->id); } } ================================================ FILE: packages/core/src/ServiceProvider.php ================================================ registerConfig() ->registerSingletons(); } protected function registerConfig(): static { $this->mergeConfigFrom(__DIR__.'/../config/core.php', 'core'); return $this; } protected function registerSingletons(): static { $this->app->scoped(TeamService::class); $this->app->singleton(Navigation::class); return $this; } public function boot(): void { $this ->bootActions() ->bootConfig() ->bootMigrations() ->bootCommands() ->bootRoutes() ->bootNavigation(); } protected function bootActions(): static { if (ce()) { $this->app->singleton(ResolvesDataRetention::class, ResolveDataRetention::class); } return $this; } protected function bootConfig(): static { $this->publishes([ __DIR__.'/../config/core.php' => config_path('core.php'), ], 'config'); return $this; } protected function bootMigrations(): static { $this->loadMigrationsFrom(__DIR__.'/../database/migrations'); return $this; } protected function bootCommands(): static { if ($this->app->runningInConsole()) { $this->commands([ ]); } return $this; } protected function bootRoutes(): static { if (! $this->app->routesAreCached()) { Route::middleware(['web', 'auth']) ->group(fn () => $this->loadRoutesFrom(__DIR__.'/../routes/web.php')); } return $this; } protected function bootNavigation(): static { NavigationFacade::path(__DIR__.'/../resources/navigation.php'); return $this; } } ================================================ FILE: packages/core/src/Services/TeamService.php ================================================ team = $user->currentTeam; } public function setTeam(?Team $team): void { $this->team = $team; } public function setTeamById(int $teamId): void { /** @var Team $team */ $team = Team::query()->findOrFail($teamId); $this->setTeam($team); } public function team(): Team { if ($this->team === null) { $this->fromAuth(); } throw_if($this->team === null, 'No team'); return $this->team; } public static function instance(): TeamService { /** @var TeamService $instance */ $instance = app(TeamService::class); return $instance; } public static function fake(): Team { /** @var Team $team */ $team = Team::factory()->create(); static::instance()->setTeam($team); return $team; } } ================================================ FILE: packages/core/src/Validation/CanEnableRule.php ================================================ user(); if ($user === null) { return; } if (! $user->can('create', $this->model)) { $fail('Unable to enable this resource, check your billing plan.'); } } } ================================================ FILE: packages/core/src/helpers.php ================================================ timezone($teamService->team()->timezone ?? 'UTC'); } } if (! function_exists('ce')) { function ce(): bool { return config('core.edition', 'ce') === 'ce'; } } ================================================ FILE: packages/core/testbench.yaml ================================================ providers: - Vigilant\Core\ServiceProvider ================================================ FILE: packages/core/tests/TestCase.php ================================================ set('database.default', 'testbench'); $app['config']->set('database.connections.testbench', [ 'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '', ]); } } ================================================ FILE: packages/crawler/.gitignore ================================================ vendor composer.lock .phpunit.result.cache ================================================ FILE: packages/crawler/composer.json ================================================ { "name": "vigilant/crawler", "description": "Vigilant Crawler", "type": "package", "license": "AGPL", "authors": [ { "name": "Vincent Boon", "email": "info@vincentbean.com", "role": "Developer" } ], "require": { "php": "^8.3", "guzzlehttp/guzzle": "^7.8", "laravel/framework": "^12.0", "livewire/livewire": "^3.4", "maatwebsite/excel": "^3.1", "vigilant/core": "@dev", "vigilant/sites": "@dev", "vigilant/users": "@dev", "vigilant/frontend": "@dev", "vigilant/notifications": "@dev", "mtownsend/xml-to-array": "^2.0" }, "require-dev": { "laravel/pint": "^1.6", "larastan/larastan": "^3.0", "orchestra/testbench": "^10.0", "phpstan/phpstan-mockery": "^2.0", "phpunit/phpunit": "^11.0" }, "autoload": { "psr-4": { "Vigilant\\Crawler\\": "src", "Vigilant\\Crawler\\Database\\Factories\\": "database/factories", "Vigilant\\Users\\Database\\Factories\\": "../users/database/factories" } }, "autoload-dev": { "psr-4": { "Vigilant\\Crawler\\Tests\\": "tests" } }, "scripts": { "test": "phpunit", "analyse": "phpstan", "style": "pint --test", "quality": [ "@test", "@analyse" ] }, "config": { "sort-packages": true, "allow-plugins": { "php-http/discovery": true } }, "extra": { "laravel": { "providers": [ "Vigilant\\Crawler\\ServiceProvider" ] } }, "minimum-stability": "dev", "prefer-stable": true, "repositories": [ { "type": "path", "url": "../*" } ] } ================================================ FILE: packages/crawler/config/crawler.php ================================================ 'crawler', 'timeout' => env('CRAWLER_TIMEOUT', 5), 'connect_timeout' => env('CRAWLER_CONNECT_TIMEOUT', 2), 'crawls_per_minute' => (int) env('CRAWLER_CRAWLS_PER_MINUTE', 500), 'platform_blacklists' => [ 'magento1' => [ 'label' => 'Magento 1', 'patterns' => [ '~^https?://[^/]+/index\.php/admin~i', '~^https?://[^/]+/admin~i', '~^https?://[^/]+/api/~i', '~^https?://[^/]+/cron\.php~i', '~^https?://[^/]+/index\.php/customer/account~i', '~^https?://[^/]+/customer/account/login~i', '~^https?://[^/]+/customer/account/create~i', '~^https?://[^/]+/customer/account/logout~i', '~^https?://[^/]+/checkout/~i', '~^https?://[^/]+/cart~i', '~^https?://[^/]+/wishlist/~i', '~^https?://[^/]+/review/product/~i', '~^https?://[^/]+/newsletter/subscriber/~i', '~^https?://[^/]+/contacts/index/post~i', '~^https?://[^/]+/catalogsearch/ajax/~i', '~^https?://[^/]+/sendfriend/~i', '~^https?://[^/]+/catalog/product_compare/~i', '~^https?://[^/]+/tag/~i', '~^https?://[^/]+/rating/~i', '~^https?://[^/]+/poll/~i', '~^https?://[^/]+/paypal/~i', ], ], 'magento2' => [ 'label' => 'Magento 2', 'patterns' => [ '~^https?://[^/]+/admin~i', '~^https?://[^/]+/rest/~i', '~^https?://[^/]+/graphql~i', '~^https?://[^/]+/soap/~i', '~^https?://[^/]+/cron\.php~i', '~^https?://[^/]+/index\.php/customer/account~i', '~^https?://[^/]+/customer/account/login~i', '~^https?://[^/]+/customer/account/create~i', '~^https?://[^/]+/customer/account/logout~i', '~^https?://[^/]+/checkout/~i', '~^https?://[^/]+/onestepcheckout/~i', '~^https?://[^/]+/cart~i', '~^https?://[^/]+/wishlist/~i', '~^https?://[^/]+/review/product/~i', '~^https?://[^/]+/newsletter/subscriber/~i', '~^https?://[^/]+/contact/index/post~i', '~^https?://[^/]+/search/ajax/~i', '~^https?://[^/]+/catalogsearch/ajax/~i', '~^https?://[^/]+/page_cache/~i', '~^https?://[^/]+/static/version~i', '~^https?://[^/]+/media/tmp/~i', '~^https?://[^/]+/pub/media/tmp/~i', '~^https?://[^/]+/sendfriend/~i', '~^https?://[^/]+/catalog/product_compare/~i', ], ], 'wordpress' => [ 'label' => 'WordPress', 'patterns' => [ '~^https?://[^/]+/wp-admin~i', '~^https?://[^/]+/wp-login\.php~i', '~^https?://[^/]+/wp-cron\.php~i', '~^https?://[^/]+/wp-json/~i', '~^https?://[^/]+/xmlrpc\.php~i', '~^https?://[^/]+/\?feed=~i', '~^https?://[^/]+/feed/~i', '~^https?://[^/]+/comments/feed/~i', '~[?&]replytocom=~i', '~[?&]preview=true~i', '~^https?://[^/]+/\?p=\d+&preview=true~i', '~^https?://[^/]+/wp-content/uploads/~i', '~^https?://[^/]+/\?add-to-cart=~i', '~^https?://[^/]+/cart/~i', '~^https?://[^/]+/checkout/~i', '~^https?://[^/]+/my-account/~i', '~^https?://[^/]+/\?wc-ajax=~i', '~^https?://[^/]+/wp-trackback\.php~i', ], ], 'joomla' => [ 'label' => 'Joomla', 'patterns' => [ '~^https?://[^/]+/administrator/~i', '~^https?://[^/]+/index\.php\?option=com_users&task=user\.login~i', '~^https?://[^/]+/index\.php\?option=com_users&task=user\.logout~i', '~^https?://[^/]+/index\.php\?option=com_users&task=registration~i', '~^https?://[^/]+/index\.php\?option=com_contact&task=contact\.submit~i', '~[?&]format=feed~i', '~[?&]format=json~i', '~[?&]format=raw~i', '~[?&]tmpl=component~i', '~^https?://[^/]+/index\.php\?option=com_search~i', '~^https?://[^/]+/index\.php\?option=com_finder~i', '~^https?://[^/]+/index\.php\?option=com_ajax~i', '~^https?://[^/]+/cache/~i', '~^https?://[^/]+/tmp/~i', '~^https?://[^/]+/logs/~i', '~^https?://[^/]+/cli/~i', ], ], 'drupal' => [ 'label' => 'Drupal', 'patterns' => [ '~^https?://[^/]+/admin/~i', '~^https?://[^/]+/user/login~i', '~^https?://[^/]+/user/logout~i', '~^https?://[^/]+/user/register~i', '~^https?://[^/]+/user/password~i', '~^https?://[^/]+/\?q=user/~i', '~^https?://[^/]+/\?q=admin/~i', '~^https?://[^/]+/jsonapi/~i', '~^https?://[^/]+/api/~i', '~^https?://[^/]+/batch\b~i', '~[?&]ajax_form=1~i', '~^https?://[^/]+/cron/~i', '~^https?://[^/]+/update\.php~i', '~^https?://[^/]+/install\.php~i', '~^https?://[^/]+/rebuild\.php~i', '~^https?://[^/]+/core/rebuild\.php~i', '~^https?://[^/]+/sites/default/files/~i', ], ], ], ]; ================================================ FILE: packages/crawler/database/migrations/2024_09_06_213000_create_web_crawlers_table.php ================================================ id(); $table->foreignIdFor(Site::class)->nullable()->constrained()->onDelete('cascade'); $table->foreignIdFor(Team::class)->constrained()->onDelete('cascade'); $table->string('state')->default(State::Pending->value); $table->string('schedule'); $table->string('start_url'); $table->json('sitemaps')->nullable(); $table->json('crawler_stats')->nullable(); $table->json('settings')->nullable(); $table->timestamps(); }); } public function down(): void { Schema::dropIfExists('web_crawlers'); } }; ================================================ FILE: packages/crawler/database/migrations/2024_09_06_220000_create_web_crawled_urls_table.php ================================================ uuid(); $table->foreignIdFor(Crawler::class)->nullable()->constrained('web_crawlers')->onDelete('cascade'); $table->foreignIdFor(Team::class)->constrained()->onDelete('cascade'); $table->uuid('found_on_id')->nullable(); $table->boolean('crawled')->default(false); $table->string('url', 2048); $table->integer('status')->nullable(); $table->timestamps(); $table->index(['crawler_id', 'crawled']); }); } public function down(): void { Schema::dropIfExists('web_crawled_urls'); } }; ================================================ FILE: packages/crawler/database/migrations/2025_01_18_220000_crawled_urls_url_length.php ================================================ string('url', 8192)->change(); }); } }; ================================================ FILE: packages/crawler/database/migrations/2025_02_01_183000_web_crawlers_enabled_field.php ================================================ boolean('enabled')->default(true)->after('id'); }); } public function down(): void { Schema::dropColumns('web_crawlers', ['enabled']); } }; ================================================ FILE: packages/crawler/database/migrations/2025_04_07_200000_web_crawled_urls_url_hash.php ================================================ string('url_hash')->after('url'); $table->index(['crawler_id', 'url_hash']); }); } }; ================================================ FILE: packages/crawler/database/migrations/2025_09_28_100000_create_web_crawler_ignored_urls_table.php ================================================ id(); $table->foreignIdFor(Crawler::class)->nullable()->constrained('web_crawlers')->onDelete('cascade'); $table->string('url_hash'); $table->timestamps(); $table->unique(['crawler_id', 'url_hash']); }); } public function down(): void { Schema::dropIfExists('web_crawler_ignored_urls'); } }; ================================================ FILE: packages/crawler/database/migrations/2025_09_29_190000_web_crawled_urls_ignored_field.php ================================================ boolean('ignored')->default(false)->after('crawled')->index(); }); } public function down(): void { Schema::table('web_crawled_urls', function (Blueprint $table): void { $table->dropColumn('ignored'); }); } }; ================================================ FILE: packages/crawler/phpstan.neon ================================================ includes: - ./vendor/larastan/larastan/extension.neon - ./vendor/phpstan/phpstan-mockery/extension.neon parameters: paths: - src - tests level: 8 treatPhpDocTypesAsCertain: false ignoreErrors: - identifier: missingType.iterableValue - identifier: missingType.generics ================================================ FILE: packages/crawler/phpunit.xml ================================================ ./tests/* ./src ================================================ FILE: packages/crawler/resources/navigation.php ================================================ parent('health') ->icon('carbon-text-link') ->gate('use-crawler') ->routeIs('crawler*') ->sort(3); ================================================ FILE: packages/crawler/resources/views/components/empty-states/crawlers.blade.php ================================================ ================================================ FILE: packages/crawler/resources/views/crawler/index.blade.php ================================================ @lang('Edit') @lang('Delete') @lang('Edit') @lang('Delete') @if ($crawler->state === \Vigilant\Crawler\Enums\State::Crawling)

{{ __('Crawling') }}

@endif

{{ __('Issues') }}

@lang('Delete Crawler Monitor')

@lang('Are you sure you want to delete this crawler monitor?')

@svg('phosphor-warning-circle', 'w-5 h-5 text-orange mt-0.5')

{{ $crawler->start_url }}

@lang('This action cannot be undone. All crawl data and issues for this monitor will be permanently deleted.')

@lang('Cancel')
@csrf @method('DELETE') @lang('Delete Monitor')
================================================ FILE: packages/crawler/resources/views/crawlers.blade.php ================================================
@lang('Add Crawler') @lang('Add Crawler') @if ($hasCrawlers) @else @endif
================================================ FILE: packages/crawler/resources/views/livewire/crawler/dashboard.blade.php ================================================
{{ $total_url_count }} {{ $issue_count }} {{ $nextRun }} {{ $ignored_count }}
================================================ FILE: packages/crawler/resources/views/livewire/crawler-form.blade.php ================================================
@if (!$inline) @endif
@if (!$inline) @endif
@lang('Choose how often the website should be crawled')
@lang('On') @lang('At')
@error('schedule') {{ $message }} @enderror @if ($invalidDay) @lang('Warning! Setting the day above 28 will cause it to NOT run montly') @endif
@if (!$inline)
@lang('Pre-fills the URL blacklist for the selected platform.')
@endif
================================================ FILE: packages/crawler/routes/web.php ================================================ middleware('can:use-crawler') ->group(function (): void { Route::get('', Crawlers::class)->name('crawler.index'); Route::get('/create', CrawlerForm::class)->name('crawler.create'); Route::get('/{crawler}', [CrawlerController::class, 'index'])->name('crawler.view'); Route::delete('/{crawler}', [CrawlerController::class, 'delete'])->name('crawler.delete')->can('delete,crawler'); Route::get('/{crawler}/edit', CrawlerForm::class)->name('crawler.edit'); }); ================================================ FILE: packages/crawler/src/Actions/CollectCrawlerStats.php ================================================ teamService->setTeamById($crawler->team_id); /** @var Collection $statuses */ $statuses = $crawler ->urls() ->where('crawled', '=', true) ->where('ignored', '=', false) ->selectRaw('status, COUNT(*) AS count') ->groupBy('status') ->get() ->pluck('count', 'status'); $stats = [ 'total_url_count' => $statuses->sum(), 'statuses' => $statuses, 'issue_count' => $crawler->urls() ->where('crawled', '=', true) ->where('ignored', '=', false) ->where(function (Builder $query): void { $query->where('status', '>=', 400) ->orWhere('status', '=', 0); }) ->count(), ]; $crawler->update([ 'crawler_stats' => $stats, ]); $crawler ->urls() ->where('status', '=', 200) ->whereDoesntHave('foundOn') ->select(['web_crawled_urls.uuid']) ->lazy() ->chunk(1000) ->each(fn (LazyCollection $urls) => CrawledUrl::query()->whereIn('uuid', $urls->pluck('uuid'))->delete()); if ($shouldNotify && $stats['issue_count'] > 0) { UrlIssuesNotification::notify($crawler); } } } ================================================ FILE: packages/crawler/src/Actions/CrawlUrl.php ================================================ teamService->setTeamById($url->team_id); $canCreateCrawledUrl = Gate::check('create-crawled-url', $url->crawler); if (! $canCreateCrawledUrl) { $url->crawler->update([ 'state' => State::Limited, ]); return; } $allowedHost = parse_url($url->url, PHP_URL_HOST); if (! is_string($allowedHost)) { $url->update([ 'status' => 0, 'crawled' => true, ]); return; } try { $response = $this->fetchResponse($url->url, $allowedHost); } catch (ConnectionException) { if ($try < 3) { $this->crawl($url, $try + 1); return; } $url->update([ 'status' => 0, 'crawled' => true, ]); return; } $baseUrl = parse_url($url->url) ?: []; if (! $response->successful()) { $url->update([ 'status' => $response->status(), 'crawled' => true, ]); if ($response->status() === 429 && $url->crawler !== null) { $url->crawler->update([ 'state' => State::Ratelimited, ]); RatelimitedNotification::notify($url->crawler); } return; } $html = $response->body(); if (! isset($baseUrl['host'], $baseUrl['scheme'])) { $url->update(['crawled' => true]); return; } $links = $this->extractLinks($html, $baseUrl); $queuedLinks = []; foreach ($links as $link) { if (strlen($link) > 8192) { $link = substr($link, 0, 8192); } $hash = md5($link); $queuedLinks[$hash] = [ 'crawler_id' => $url->crawler_id, 'url_hash' => $hash, 'url' => $link, 'found_on_id' => $url->uuid, ]; } $existingLinks = CrawledUrl::query() ->where('crawler_id', '=', $url->crawler_id) ->whereIn('url_hash', Arr::pluck($queuedLinks, 'url_hash')) ->pluck('url_hash') ->all(); $blacklistPatterns = $this->buildBlacklistPatterns($url->crawler); $queuedLinks = collect($queuedLinks) ->reject(fn (array $record): bool => in_array($record['url_hash'], $existingLinks, true)) ->when($blacklistPatterns->isNotEmpty(), fn (Collection $links): Collection => $links ->reject(fn (array $record): bool => $blacklistPatterns ->contains(fn (string $pattern): bool => @preg_match($pattern, $record['url']) === 1) ) ) ->all(); if ($queuedLinks !== []) { $timestamp = now(); $records = []; $ignoredHashes = []; if ($url->crawler_id !== null) { $ignoredHashes = IgnoredUrl::query() ->where('crawler_id', '=', $url->crawler_id) ->whereIn('url_hash', array_keys($queuedLinks)) ->pluck('url_hash') ->all(); } foreach ($queuedLinks as $record) { $records[] = [ 'uuid' => (string) Str::uuid(), 'crawler_id' => $record['crawler_id'], 'team_id' => $url->team_id, 'url_hash' => $record['url_hash'], 'url' => $record['url'], 'found_on_id' => $record['found_on_id'], 'ignored' => in_array($record['url_hash'], $ignoredHashes, true), 'crawled' => false, 'created_at' => $timestamp, 'updated_at' => $timestamp, ]; } CrawledUrl::query()->insertOrIgnore($records); } $url->update([ 'status' => $response->status(), 'crawled' => true, ]); } protected function buildBlacklistPatterns(Crawler $crawler): \Illuminate\Support\Collection { return collect(explode("\n", (string) ($crawler->settings['url_blacklist'] ?? ''))) ->map(fn (string $line): string => trim($line)) ->filter() ->values(); } protected function extractLinks(string $html, array $baseUrl): array { if ($html === '' || stripos($html, '"\']+))~i'; if (! preg_match_all($pattern, $html, $matches, PREG_SET_ORDER)) { return []; } $links = []; foreach ($matches as $match) { $href = $match[1] ?? $match[2] ?? $match[3] ?? ''; $href = html_entity_decode(trim($href), ENT_QUOTES | ENT_HTML5); if ($href === '' || $href === '#') { continue; } $lowerHref = strtolower($href); if (str_starts_with($lowerHref, 'mailto:') || str_starts_with($lowerHref, 'tel:') || str_starts_with($lowerHref, 'javascript:')) { continue; } if (! filter_var($href, FILTER_VALIDATE_URL)) { $href = $this->resolveRelativeUrl($href, $baseUrl); } if (! filter_var($href, FILTER_VALIDATE_URL) || ! $this->isSameDomain($href, $baseUrl['host'])) { continue; } $href = $this->withoutQuery($href); $normalized = rtrim($href, '/#'); if ($normalized === '') { continue; } $links[$normalized] = true; } return array_keys($links); } protected function fetchResponse(string $currentUrl, ?string $allowedDomain, int $redirectCount = 0): Response { $response = $this->sendRequest($currentUrl); $nextUrl = $this->nextRedirectUrl($response, $currentUrl, $allowedDomain, $redirectCount); if ($nextUrl !== null) { return $this->fetchResponse($nextUrl, $allowedDomain, $redirectCount + 1); } return $response; } protected function sendRequest(string $url): Response { $timeout = config()->integer('crawler.timeout', 5); $connectTimeout = config()->integer('crawler.connect_timeout', $timeout); return Http::timeout($timeout) ->connectTimeout($connectTimeout) ->withOptions(['verify' => false, 'allow_redirects' => false]) ->withUserAgent(config('core.user_agent')) ->get($url); } protected function nextRedirectUrl(Response $response, string $currentUrl, ?string $allowedDomain, int $redirectCount): ?string { if (! $response->redirect() || $allowedDomain === null || $redirectCount >= self::MAX_REDIRECTS) { return null; } $redirectLocation = $response->header('Location'); if (is_array($redirectLocation)) { $redirectLocation = $redirectLocation[0] ?? null; } if (! is_string($redirectLocation) || $redirectLocation === '') { return null; } if (! filter_var($redirectLocation, FILTER_VALIDATE_URL)) { $baseParts = parse_url($currentUrl); if ($baseParts === false || ! isset($baseParts['scheme'], $baseParts['host'])) { return null; } $redirectLocation = $this->resolveRelativeUrl($redirectLocation, $baseParts); } return $this->isSameDomain($redirectLocation, $allowedDomain) ? $redirectLocation : null; } protected function isSameDomain(string $url, string $domain): bool { $host = parse_url($url, PHP_URL_HOST); if ($host === null || $host === false) { return false; } $host = strtolower($host); $domain = strtolower($domain); // Match exact domain or proper subdomain (with dot boundary) return $host === $domain || preg_match('/\.'.preg_quote($domain, '/').'$/', $host); } protected function withoutQuery(string $url): string { $parts = parse_url($url); if ($parts === false || ! isset($parts['scheme'], $parts['host'])) { return $url; } $scheme = $parts['scheme']; $host = $parts['host']; $userInfo = ''; if (isset($parts['user'])) { $userInfo = $parts['user']; if (isset($parts['pass'])) { $userInfo .= ':'.$parts['pass']; } $userInfo .= '@'; } $port = isset($parts['port']) ? ':'.$parts['port'] : ''; $path = $parts['path'] ?? ''; if ($path === '') { $path = '/'; } return $scheme.'://'.$userInfo.$host.$port.$path; } protected function resolveRelativeUrl(string $relativeUrl, array $baseUrlParts): string { // If the relative URL starts with "//", it refers to a protocol-relative URL if (strpos($relativeUrl, '//') === 0) { return $baseUrlParts['scheme'].':'.$relativeUrl; } // If the relative URL starts with "/", it's an absolute path relative to the domain if (strpos($relativeUrl, '/') === 0) { return $baseUrlParts['scheme'].'://'.$baseUrlParts['host'].$relativeUrl; } // Otherwise, it's a relative path, resolve by appending to base path $basePath = isset($baseUrlParts['path']) ? dirname($baseUrlParts['path']) : ''; if ($basePath === '/') { $basePath = ''; } return $baseUrlParts['scheme'].'://'.$baseUrlParts['host'].$basePath.'/'.ltrim($relativeUrl, '/'); } } ================================================ FILE: packages/crawler/src/Actions/ImportSitemaps.php ================================================ sitemaps ?? [] as $sitemap) { $this->processSitemap($crawler, $sitemap); } } protected function processSitemap(Crawler $crawler, string $url): void { if (in_array($url, $this->processed, true)) { return; } $this->processed[] = $url; $response = Http::withHeaders([ 'Accept' => 'application/xml', ])->get($url); if (! $response->successful()) { return; } $xml = $response->body(); $parsed = XmlToArray::convert($xml, true); $root = $parsed['@root'] ?? 'urlset'; if ($root === 'urlset') { /** @var array $urls */ $urls = $parsed['url'] ?? []; $urls = collect($urls)->pluck('loc')->filter(); $this->storeUrls($crawler, $urls); } if ($root === 'sitemapindex') { /** @var array $sitemaps */ $sitemaps = $parsed['sitemap'] ?? []; $nested = collect($sitemaps)->pluck('loc')->filter(); foreach ($nested as $nestedSitemapUrl) { $this->processSitemap($crawler, $nestedSitemapUrl); } } } protected function storeUrls(Crawler $crawler, Collection $urls): void { $chunks = $urls->chunk(5000); foreach ($chunks as $chunk) { $existingUrls = $crawler->urls()->whereIn('url', $chunk)->pluck('url'); $newUrls = $chunk->diff($existingUrls); if ($newUrls->isEmpty()) { continue; } $timestamp = now(); $urlHashes = $newUrls->map(fn ($url): string => md5($url)); $ignoredHashes = $urlHashes->isEmpty() ? [] : IgnoredUrl::query() ->where('crawler_id', '=', $crawler->id) ->whereIn('url_hash', $urlHashes->all()) ->pluck('url_hash') ->all(); $crawler->urls()->insert( $newUrls->map(function ($url) use ($crawler, $timestamp, $ignoredHashes): array { $hash = md5($url); return [ 'uuid' => (new CrawledUrl)->newUniqueId(), 'crawler_id' => $crawler->id, 'team_id' => $crawler->team_id, 'url' => $url, 'url_hash' => $hash, 'ignored' => in_array($hash, $ignoredHashes, true), 'created_at' => $timestamp, 'updated_at' => $timestamp, ]; })->toArray() ); } } } ================================================ FILE: packages/crawler/src/Actions/ProcessCrawlerState.php ================================================ teamService->setTeamById($crawler->team_id); if ($crawler->state === State::Pending) { $this->starter->start($crawler); return; } if ($crawler->state === State::Crawling && $this->finished($crawler)) { $crawler->update([ 'state' => State::Finished, ]); event(new CrawlerFinishedEvent($crawler)); return; } } protected function finished(Crawler $crawler): bool { $crawledUrlCount = $crawler ->urls() ->where('crawled', '=', true) ->count(); $uncrawledUrlCount = $crawler ->urls() ->where('crawled', '=', false) ->count(); return $crawledUrlCount > 0 && $uncrawledUrlCount === 0; } } ================================================ FILE: packages/crawler/src/Actions/StartCrawler.php ================================================ urls()->delete(); $crawler->urls()->firstOrCreate([ 'url' => $crawler->start_url, ]); if ($crawler->sitemaps !== null && count($crawler->sitemaps) > 0) { ImportSitemapsJob::dispatch($crawler); } $crawler->update([ 'state' => State::Crawling, 'crawler_stats' => null, ]); } } ================================================ FILE: packages/crawler/src/Commands/CollectCrawlerStatsCommand.php ================================================ argument('crawlerId'); /** @var Crawler $crawler */ $crawler = Crawler::query()->withoutGlobalScopes()->findOrFail($crawlerId); CollectCrawlerStatsJob::dispatch($crawler); return static::SUCCESS; } } ================================================ FILE: packages/crawler/src/Commands/CrawlUrlsCommand.php ================================================ integer('crawler.crawls_per_minute'); CrawledUrl::query() ->withoutGlobalScopes() ->where('crawled', '=', false) ->whereHas('crawler', fn (Builder $query) => $query->withoutGlobalScopes()->where('state', '=', State::Crawling)) ->take($count) ->get() ->each(fn (CrawledUrl $url): PendingDispatch => CrawUrlJob::dispatch($url)); return static::SUCCESS; } } ================================================ FILE: packages/crawler/src/Commands/ProcessCrawlerStatesCommand.php ================================================ withoutGlobalScopes() ->whereIn('state', [ State::Pending, State::Crawling, ]) ->get() ->each(fn (Crawler $crawler): PendingDispatch => ProcessCrawlerStateJob::dispatch($crawler)); return static::SUCCESS; } } ================================================ FILE: packages/crawler/src/Commands/ScheduleCrawlersCommand.php ================================================ withoutGlobalScopes() ->where('enabled', '=', true) ->where('state', '!=', State::Crawling) ->get() ->each(function (Crawler $crawler) use ($starter) { if (CronExpression::isValidExpression($crawler->schedule)) { $expression = new CronExpression($crawler->schedule); if ($expression->isDue(now())) { $starter->start($crawler); } } }); return static::SUCCESS; } } ================================================ FILE: packages/crawler/src/Commands/StartCrawlerCommand.php ================================================ argument('crawlerId'); /** @var Crawler $crawler */ $crawler = Crawler::query()->withoutGlobalScopes()->findOrFail($crawlerId); $teamService->setTeamById($crawler->team_id); $starter->start($crawler); return static::SUCCESS; } } ================================================ FILE: packages/crawler/src/Enums/State.php ================================================ 'Pending', State::Crawling => 'Crawling', State::Finished => 'Finished', State::Ratelimited => 'Rate Limited', State::Limited => 'Limited', State::Failed => 'Failed', }; } } ================================================ FILE: packages/crawler/src/Enums/Status.php ================================================ 'Failed to connect', Status::BAD_REQUEST => 'Bad Request', Status::UNAUTHORIZED => 'Unauthorized', Status::PAYMENT_REQUIRED => 'Payment Required', Status::FORBIDDEN => 'Forbidden', Status::NOT_FOUND => 'Not Found', Status::METHOD_NOT_ALLOWED => 'Method Not Allowed', Status::NOT_ACCEPTABLE => 'Not Acceptable', Status::PROXY_AUTHENTICATION_REQUIRED => 'Proxy Authentication Required', Status::REQUEST_TIMEOUT => 'Request Timeout', Status::CONFLICT => 'Conflict', Status::GONE => 'Gone', Status::LENGTH_REQUIRED => 'Length Required', Status::PRECONDITION_FAILED => 'Precondition Failed', Status::PAYLOAD_TOO_LARGE => 'Payload Too Large', Status::URI_TOO_LONG => 'URI Too Long', Status::UNSUPPORTED_MEDIA_TYPE => 'Unsupported Media Type', Status::RANGE_NOT_SATISFIABLE => 'Range Not Satisfiable', Status::EXPECTATION_FAILED => 'Expectation Failed', Status::IM_A_TEAPOT => "I'm a Teapot", Status::MISDIRECTED_REQUEST => 'Misdirected Request', Status::UNPROCESSABLE_ENTITY => 'Unprocessable Entity', Status::LOCKED => 'Locked', Status::FAILED_DEPENDENCY => 'Failed Dependency', Status::TOO_EARLY => 'Too Early', Status::UPGRADE_REQUIRED => 'Upgrade Required', Status::PRECONDITION_REQUIRED => 'Precondition Required', Status::RATE_LIMITED => 'Rate Limited', Status::REQUEST_HEADER_FIELDS_TOO_LARGE => 'Request Header Fields Too Large', Status::UNAVAILABLE_FOR_LEGAL_REASONS => 'Unavailable For Legal Reasons', Status::INTERNAL_SERVER_ERROR => 'Internal Server Error', Status::NOT_IMPLEMENTED => 'Not Implemented', Status::BAD_GATEWAY => 'Bad Gateway', Status::SERVICE_UNAVAILABLE => 'Service Unavailable', Status::GATEWAY_TIMEOUT => 'Gateway Timeout', Status::HTTP_VERSION_NOT_SUPPORTED => 'HTTP Version Not Supported', Status::VARIANT_ALSO_NEGOTIATES => 'Variant Also Negotiates', Status::INSUFFICIENT_STORAGE => 'Insufficient Storage', Status::LOOP_DETECTED => 'Loop Detected', Status::NOT_EXTENDED => 'Not Extended', Status::NETWORK_AUTHENTICATION_REQUIRED => 'Network Authentication Required', // Cloudflare-specific status codes Status::CLOUDFLARE_UNKNOWN_ERROR => 'Unknown Error (Cloudflare)', Status::CLOUDFLARE_WEB_SERVER_DOWN => 'Web Server Is Down (Cloudflare)', Status::CLOUDFLARE_CONNECTION_TIMED_OUT => 'Connection Timed Out (Cloudflare)', Status::CLOUDFLARE_ORIGIN_UNREACHABLE => 'Origin Is Unreachable (Cloudflare)', Status::CLOUDFLARE_TIMEOUT => 'A Timeout Occurred (Cloudflare)', Status::CLOUDFLARE_SSL_HANDSHAKE_FAILED => 'SSL Handshake Failed (Cloudflare)', Status::CLOUDFLARE_INVALID_SSL_CERTIFICATE => 'Invalid SSL Certificate (Cloudflare)', Status::CLOUDFLARE_RAILGUN_ERROR => 'Railgun Error (Cloudflare)', Status::CLOUDFLARE_ERROR => 'Cloudflare Error', }; } } ================================================ FILE: packages/crawler/src/Events/CrawlerFinishedEvent.php ================================================ collection; } public function headings(): array { return [ 'URL', 'Status Code', 'Status', 'Found On', 'Ignored', ]; } public function map(mixed $row): array { /** @var CrawledUrl $row */ return [ $row->url, $row->status, Status::tryFrom($row->status)?->label() ?? (string) $row->status, $row->foundOn->url ?? '', $row->ignored ? 'Yes' : 'No', ]; } } ================================================ FILE: packages/crawler/src/Http/Controllers/CrawlerController.php ================================================ $crawler, ]); } public function delete(Crawler $crawler): mixed { $crawler->delete(); $this->alert( __('Deleted'), __('Crawler was successfully deleted'), AlertType::Success ); return response()->redirectToRoute('crawler.index'); } } ================================================ FILE: packages/crawler/src/Jobs/CollectCrawlerStatsJob.php ================================================ onQueue(config('crawler.queue')); } public function handle(CollectCrawlerStats $crawlerStats): void { $crawlerStats->collect($this->crawler, $this->shouldNotify); } public function uniqueId(): int { return $this->crawler->id; } } ================================================ FILE: packages/crawler/src/Jobs/CrawUrlJob.php ================================================ onQueue(config('crawler.queue')); } public function handle(CrawlUrl $url): void { $url->crawl($this->url); } public function tags(): array { return [ $this->url->uuid, $this->url->url, ]; } public function uniqueId(): string { return $this->url->uuid; } } ================================================ FILE: packages/crawler/src/Jobs/ImportSitemapsJob.php ================================================ onQueue(config('crawler.queue')); } public function handle(ImportSitemaps $sitemaps): void { $sitemaps->import($this->crawler); } public function uniqueId(): int { return $this->crawler->id; } } ================================================ FILE: packages/crawler/src/Jobs/ProcessCrawlerStateJob.php ================================================ onQueue(config('crawler.queue')); } public function handle(ProcessCrawlerState $state): void { $state->process($this->crawler); } public function uniqueId(): int { return $this->crawler->id; } } ================================================ FILE: packages/crawler/src/Jobs/StartCrawlerJob.php ================================================ onQueue(config('crawler.queue')); } public function handle(StartCrawler $starter, TeamService $teamService): void { $teamService->setTeamById($this->crawler->team_id); $starter->start($this->crawler); } public function uniqueId(): int { return $this->crawler->id; } } ================================================ FILE: packages/crawler/src/Listeners/CrawlerFinishedListener.php ================================================ crawler); } } ================================================ FILE: packages/crawler/src/Livewire/Crawler/Dashboard.php ================================================ crawlerId = $crawlerId; } public function render(): mixed { /** @var Crawler $crawler */ $crawler = Crawler::query()->findOrFail($this->crawlerId); $nextRun = Carbon::parse((new CronExpression($crawler->schedule))->getNextRunDate()); /** @var view-string $view */ $view = 'crawler::livewire.crawler.dashboard'; return view($view, [ 'total_url_count' => $crawler->totalUrlCount(), 'issue_count' => $crawler->issueCount() ?? 0, 'ignored_count' => $crawler->urls()->where('ignored', '=', true)->count(), 'nextRun' => $crawler->enabled ? $nextRun->diffForHumans() : __('Crawler disabled'), ]); } } ================================================ FILE: packages/crawler/src/Livewire/CrawlerForm.php ================================================ exists) { $this->authorize('update', $crawler); $this->form->fill($crawler->toArray()); $this->form->url_blacklist = $crawler->settings['url_blacklist'] ?? ''; } else { $this->authorize('create', Crawler::class); if ($siteId !== null) { /** @var Site $site */ $site = Site::query()->findOrFail($siteId); $this->form->start_url = $site->url; $this->form->site_id = $siteId; } } if ($crawler !== null) { $this->crawler = $crawler; } } public function addListItem(string $field): void { if ($field === 'form.sitemaps') { $this->form->sitemaps[] = ''; } } #[On('save')] public function save(): void { $this->form->sitemaps = $this->form->sitemaps !== null ? array_filter($this->form->sitemaps) : null; $this->form->schedule = $this->getCronSchedule(); $this->form->settings = array_merge($this->form->settings ?? [], [ 'url_blacklist' => $this->form->url_blacklist, ]); $this->validate(); /** @var array $formData */ $formData = $this->form->all(); $data = collect($formData)->except('url_blacklist')->all(); if ($this->crawler->exists) { $this->authorize('update', $this->crawler); $this->crawler->update($data); } else { $this->authorize('create', $this->crawler); $this->crawler = Crawler::query()->create($data); } if (! $this->inline) { $this->alert( __('Saved'), __('Crawler was successfully :action', ['action' => $this->crawler->wasRecentlyCreated ? 'created' : 'saved']), AlertType::Success ); $this->redirectRoute('crawler.view', ['crawler' => $this->crawler]); } } protected function getCronSchedule(): string { $type = $this->form->settings['scheduleConfig']['type'] ?? 'montly'; $hour = $this->form->settings['scheduleConfig']['hour'] ?? 0; $weekDay = $this->form->settings['scheduleConfig']['weekDay'] ?? 0; $monthDay = $this->form->settings['scheduleConfig']['monthDay'] ?? 0; return match ($type) { 'daily' => "0 $hour * * *", 'weekly' => "0 $hour * * $weekDay", default => "0 $hour $monthDay * *", }; } public function render(): mixed { /** @var view-string $view */ $view = 'crawler::livewire.crawler-form'; return view($view, [ 'updating' => $this->crawler->exists, 'invalidDay' => ($this->form->settings['scheduleConfig']['monthDay'] ?? 0) > 28, ]); } } ================================================ FILE: packages/crawler/src/Livewire/Crawlers.php ================================================ exists(); return view($view, [ 'hasCrawlers' => $hasCrawlers, ]); } } ================================================ FILE: packages/crawler/src/Livewire/Forms/CrawlerForm.php ================================================ [ 'type' => 'monthly', 'hour' => '9', 'weekDay' => 1, 'monthDay' => 1, ], ]; public function rules(): array { return [ 'schedule' => ['required', new CronExpression], 'start_url' => ['required', 'max:255', 'url'], 'sitemaps' => ['required_without:start_url', 'array', new EqualDomainRule], 'sitemaps.*' => ['required', 'url'], 'settings' => ['array'], 'enabled' => ['boolean', new CanEnableRule(Crawler::class)], 'url_blacklist' => ['nullable', 'string', new ValidRegexLines], ]; } } ================================================ FILE: packages/crawler/src/Livewire/Tables/CrawledUrlsTable.php ================================================ '', ]; #[Locked] public int $crawlerId; public function mount(int $crawlerId): void { $this->crawlerId = $crawlerId; } protected function columns(): array { return [ LinkColumn::make(__('URL'), 'url') ->openInNewTab() ->searchable() ->sortable(), Column::make(__('Crawled'), 'crawled') ->displayUsing(fn (bool $crawled): string => $crawled ? __('Yes') : __('No')) ->sortable(), ]; } protected function filters(): array { return [ SelectFilter::make(__('Crawled'), 'crawled') ->options([ 'yes' => __('Crawled'), 'no' => __('Not crawled'), ]) ->filterUsing(function (Builder $builder, ?string $value): void { if ($value === 'yes') { $builder->where($builder->qualifyColumn('crawled'), '=', true); } elseif ($value === 'no') { $builder->where($builder->qualifyColumn('crawled'), '=', false); } }), ]; } protected function query(): Builder { return parent::query() ->where('web_crawled_urls.crawler_id', '=', $this->crawlerId); } } ================================================ FILE: packages/crawler/src/Livewire/Tables/CrawlerTable.php ================================================ 'None', '10s' => 'Every 10 seconds', ]; protected function columns(): array { return [ StatusColumn::make(__('Status')) ->text(function (Crawler $crawler): string { return $crawler->enabled ? __('Enabled') : __('Disabled'); }) ->status(function (Crawler $crawler): Status { return $crawler->enabled ? Status::Success : Status::Danger; }), Column::make(__('URL'), 'start_url') ->searchable() ->sortable(), Column::make(__('Next Run'), 'schedule') ->displayUsing(function (string $schedule, Crawler $crawler): ?string { if (! $crawler->enabled) { return null; } try { $expression = new CronExpression($schedule); } catch (InvalidArgumentException) { return null; } $nextRun = Carbon::parse($expression->getNextRunDate()); return $nextRun->diffForHumans(); }) ->sortable(), Column::make(__('Status'), 'state') ->displayUsing(fn (State $state): string => __($state->label())) ->sortable(), StatusColumn::make(__('Issues')) ->text(function (Crawler $crawler): string { $issueCount = $crawler->issueCount() ?? 0; return trans_choice( ':count issue|:count issues', $issueCount, ['count' => $issueCount] ); }) ->status(function (Crawler $crawler): Status { $count = $crawler->issueCount(); if ($count === null || $count === 0) { return Status::Success; } $total = $crawler->totalUrlCount(); $threshold = $total * 0.05; return $count > $threshold ? Status::Danger : Status::Warning; }), Column::make(__('URLs crawled'), function (Crawler $crawler): string { return sprintf( '%d / %d', $crawler->urls()->where('crawled', '=', true)->count(), $crawler->urls()->count(), ); }), ActionsColumn::make(__('Actions')) ->actions([ InlineAction::make('start', __('Start crawler'), 'phosphor-play-bold') ->visible(fn (Crawler $crawler): bool => $crawler->state !== State::Crawling && $crawler->enabled), ]), ]; } protected function filters(): array { return [ SelectFilter::make(__('Site'), 'site_id') ->options( Site::query() ->orderBy('url') ->pluck('url', 'id') ->toArray() ), ]; } protected function actions(): array { return [ Action::make(__('Start Crawler'), function (Enumerable $models): void { /** @var StartCrawler $starter */ $starter = app(StartCrawler::class); $models ->where('state', '!=', State::Crawling) ->each(fn (Crawler $crawler) => $starter->start($crawler)); }, 'start'), Action::make(__('Enable'), function (Enumerable $models): void { foreach ($models as $model) { if (! Gate::allows('create', $model)) { break; } $model->update(['enabled' => true]); } }, 'enable'), Action::make(__('Disable'), function (Enumerable $models): void { $models->each(fn (Crawler $crawler) => $crawler->update(['enabled' => false])); }, 'disable'), Action::make(__('Delete'), function (Enumerable $models): void { $models->each(fn (Crawler $crawler): ?bool => $crawler->delete()); }, 'delete'), ]; } protected function link(Model $model): ?string { return route('crawler.view', ['crawler' => $model]); } } ================================================ FILE: packages/crawler/src/Livewire/Tables/IssuesTable.php ================================================ 'hide', ]; protected string $model = CrawledUrl::class; #[Locked] public int $crawlerId; public function mount(int $crawlerId): void { $this->crawlerId = $crawlerId; } protected function columns(): array { return [ LinkColumn::make(__('URL'), 'url') ->openInNewTab() ->searchable() ->sortable(), Column::make(__('Status'), 'status') ->displayUsing(fn (int $status): string => Status::tryFrom($status)?->label() ?? (string) $status) ->sortable(), LinkColumn::make(__('Found On'), 'foundOn.url') ->openInNewTab() ->searchable() ->sortable(), ActionsColumn::make(__('Actions')) ->actions([ InlineAction::make('ignoreUrl', __('Ignore'), 'phosphor-eye-slash-light') ->visible(fn (CrawledUrl $url): bool => ! $url->ignored), InlineAction::make('unignoreUrl', __('Unignore'), 'phosphor-eye-light') ->visible(fn (CrawledUrl $url): bool => $url->ignored), ]), ]; } protected function actions(): array { return [ Action::make(__('Export All'), function (): BinaryFileResponse { $collection = $this->appliedQuery()->with('foundOn')->get(); return Excel::download( new IssuesExport($collection), $this->generateFilename(), ); })->standalone(), Action::make(__('Export Selected'), function (Enumerable $models): BinaryFileResponse { return Excel::download( new IssuesExport($models->collect()), $this->generateFilename(), ); }), Action::make(__('Ignore Selected'), function (Enumerable $models): void { foreach ($models as $model) { IgnoredUrl::firstOrCreate([ 'crawler_id' => $this->crawlerId, 'url_hash' => $model->url_hash, ]); $model->update(['ignored' => true]); } CollectCrawlerStatsJob::dispatch(Crawler::query()->findOrFail($this->crawlerId), false); }, 'ignoreUrl'), Action::make(__('Unignore Selected'), function (Enumerable $models): void { foreach ($models as $model) { IgnoredUrl::query() ->where('crawler_id', '=', $this->crawlerId) ->where('url_hash', '=', $model->url_hash) ->delete(); $model->ignored = false; $model->save(); } CollectCrawlerStatsJob::dispatch(Crawler::query()->findOrFail($this->crawlerId), false); }, 'unignoreUrl'), ]; } protected function generateFilename(): string { $crawler = Crawler::query()->with('site')->findOrFail($this->crawlerId); $host = $crawler->site?->url ? parse_url($crawler->site->url, PHP_URL_HOST) : null; $domain = Str::slug($host ?: 'unknown'); $date = now()->format('Y-m-d'); return "{$domain}-broken-links-{$date}.csv"; } protected function filters(): array { return [ SelectFilter::make(__('Ignored URLs'), 'ignored_urls') ->options([ 'hide' => __('Hide Ignored'), 'only' => __('Only Ignored'), ]) ->filterUsing(function (Builder $builder, ?string $value): void { if ($value === 'hide') { $builder->where($builder->qualifyColumn('ignored'), '=', false); } elseif ($value === 'only') { $builder->where($builder->qualifyColumn('ignored'), '=', true); } }), ]; } protected function query(): Builder { return parent::query() ->where('web_crawled_urls.crawler_id', '=', $this->crawlerId) ->where(function (Builder $query): void { $query->where('web_crawled_urls.status', '>=', 400) ->orWhere('web_crawled_urls.status', '=', 0); }); } } ================================================ FILE: packages/crawler/src/Models/CrawledUrl.php ================================================ 'bool', 'ignored' => 'bool', ]; public function site(): BelongsTo { return $this->belongsTo(Site::class); } public function team(): BelongsTo { return $this->belongsTo(Team::class); } public function crawler(): BelongsTo { return $this->belongsTo(Crawler::class); } public function foundOn(): BelongsTo { return $this->belongsTo(static::class, 'found_on_id', 'uuid'); } public function hash(): void { if ($this->url_hash === null) { $this->url_hash = md5($this->url); } } } ================================================ FILE: packages/crawler/src/Models/Crawler.php ================================================ $urls */ #[ObservedBy([TeamObserver::class, CrawlerObserver::class])] #[ScopedBy(TeamScope::class)] class Crawler extends Model { protected $table = 'web_crawlers'; protected $guarded = []; protected $casts = [ 'enabled' => 'boolean', 'state' => State::class, 'crawler_stats' => 'array', 'sitemaps' => 'array', 'settings' => 'array', ]; public function totalUrlCount(): int { return $this->crawler_stats === null ? $this->urls()->count() : $this->crawler_stats['total_url_count'] ?? 0; } public function issueCount(): ?int { return $this->crawler_stats === null ? null : $this->crawler_stats['issue_count'] ?? 0; } public function site(): BelongsTo { return $this->belongsTo(Site::class); } public function team(): BelongsTo { return $this->belongsTo(Team::class); } public function urls(): HasMany { return $this->hasMany(CrawledUrl::class, 'crawler_id', 'id'); } public function ignoredUrls(): HasMany { return $this->hasMany(IgnoredUrl::class, 'crawler_id', 'id'); } } ================================================ FILE: packages/crawler/src/Models/IgnoredUrl.php ================================================ hasOne(CrawledUrl::class, 'url_hash', 'url_hash') ->where('crawler_id', '=', $this->crawler_id); } public function crawler(): BelongsTo { return $this->belongsTo(Crawler::class); } } ================================================ FILE: packages/crawler/src/Notifications/RatelimitedNotification.php ================================================ $this->crawler]); } public function site(): ?Site { return $this->crawler->site; } public function uniqueId(): string|int { return $this->crawler->id; } } ================================================ FILE: packages/crawler/src/Notifications/UrlIssuesNotification.php ================================================ crawler->crawler_stats['issue_count'] ?? 0; return __(':count URL\'s found with issues on :site', [ 'count' => $count, 'site' => $this->site()->url ?? $this->crawler->start_url, ]); } public static function info(): ?string { return __('Triggered when the crawler discovers URLs with broken links, errors, or other issues.'); } public function viewUrl(): ?string { return route('crawler.view', ['crawler' => $this->crawler]); } public function site(): ?Site { return $this->crawler->site; } public function uniqueId(): string|int { return $this->crawler->id; } } ================================================ FILE: packages/crawler/src/Observers/CrawledUrlObserver.php ================================================ hash(); $url->ignored = IgnoredUrl::query() ->where('crawler_id', '=', $url->crawler_id) ->where('url_hash', '=', $url->url_hash) ->exists(); } } ================================================ FILE: packages/crawler/src/Observers/CrawlerObserver.php ================================================ crawler, false); } } ================================================ FILE: packages/crawler/src/ServiceProvider.php ================================================ registerConfig(); } protected function registerConfig(): static { $this->mergeConfigFrom(__DIR__.'/../config/crawler.php', 'crawler'); return $this; } public function boot(): void { $this ->bootConfig() ->bootMigrations() ->bootCommands() ->bootViews() ->bootLivewire() ->bootRoutes() ->bootEvents() ->bootNavigation() ->bootNotifications() ->bootGates() ->bootPolicies(); } protected function bootConfig(): static { $this->publishes([ __DIR__.'/../config/crawler.php' => config_path('crawler.php'), ], 'config'); return $this; } protected function bootMigrations(): static { $this->loadMigrationsFrom(__DIR__.'/../database/migrations'); return $this; } protected function bootCommands(): static { if ($this->app->runningInConsole()) { $this->commands([ StartCrawlerCommand::class, CrawlUrlsCommand::class, CollectCrawlerStatsCommand::class, ProcessCrawlerStatesCommand::class, ScheduleCrawlersCommand::class, ]); } return $this; } protected function bootViews(): static { $this->loadViewsFrom(__DIR__.'/../resources/views', 'crawler'); return $this; } protected function bootLivewire(): static { Livewire::component('crawlers', Crawlers::class); Livewire::component('crawler-table', CrawlerTable::class); Livewire::component('crawler-form', CrawlerForm::class); Livewire::component('crawler-dashboard', Dashboard::class); Livewire::component('crawler-issues-table', IssuesTable::class); Livewire::component('crawler-crawled-urls-table', CrawledUrlsTable::class); return $this; } protected function bootRoutes(): static { if (! $this->app->routesAreCached()) { Route::middleware(['web', 'auth']) ->group(fn () => $this->loadRoutesFrom(__DIR__.'/../routes/web.php')); } return $this; } protected function bootEvents(): static { Event::listen(CrawlerFinishedEvent::class, CrawlerFinishedListener::class); return $this; } protected function bootNavigation(): static { Navigation::path(__DIR__.'/../resources/navigation.php'); return $this; } protected function bootNotifications(): static { NotificationRegistry::registerNotification([ UrlIssuesNotification::class, RatelimitedNotification::class, ]); NotificationRegistry::registerCondition(UrlIssuesNotification::class, [ SiteCondition::class, ]); NotificationRegistry::registerCondition(RatelimitedNotification::class, [ SiteCondition::class, ]); return $this; } protected function bootGates(): static { Gate::define('use-crawler', function (User $user): bool { return ce(); }); return $this; } protected function bootPolicies(): static { if (ce()) { Gate::policy(Crawler::class, AllowAllPolicy::class); Gate::define('create-crawled-url', function (?User $user, Crawler $crawler): bool { return true; }); } return $this; } } ================================================ FILE: packages/crawler/src/Validation/EqualDomainRule.php ================================================ data = $data; return $this; } public function __invoke(string $attribute, mixed $value, Closure $fail): void { $startUrl = $this->data['start_url'] ?? null; $sitemaps = $this->data['sitemaps'] ?? []; if ($startUrl && ! empty($sitemaps)) { $startUrlDomain = parse_url($startUrl, PHP_URL_HOST); foreach ($sitemaps as $sitemap) { $sitemapDomain = parse_url($sitemap, PHP_URL_HOST); if ($sitemapDomain !== $startUrlDomain) { $fail(__('The domains of the start URL and sitemaps must be the same domain')); return; } } } } } ================================================ FILE: packages/crawler/src/Validation/ValidRegexLines.php ================================================ map(fn (string $line): string => trim($line)) ->filter() ->each(function (string $line) use ($fail): void { if (@preg_match($line, '') === false) { $fail(__('One or more URL blacklist patterns are not valid regular expressions.')); } }); } } ================================================ FILE: packages/crawler/testbench.yaml ================================================ providers: - Vigilant\Crawler\ServiceProvider ================================================ FILE: packages/crawler/tests/Actions/CrawUrlTest.php ================================================ Http::response(' '), ])->preventStrayRequests(); /** @var Crawler $crawler */ $crawler = Crawler::query()->create([ 'start_url' => 'vigilant', 'state' => State::Crawling, 'schedule' => '0 0 * * *', ]); /** @var CrawledUrl $crawledUrl */ $crawledUrl = $crawler->urls()->create([ 'url' => 'https://govigilant.io/url-1', 'crawled' => false, ]); /** @var CrawlUrl $action */ $action = app(CrawlUrl::class); $action->crawl($crawledUrl); $crawledUrl->refresh(); $this->assertEquals(200, $crawledUrl->status); $this->assertTrue($crawledUrl->crawled); $foundUrls = $crawler->urls() ->where('crawled', '=', false) ->pluck('url') ->toArray(); $discoveredUrls = array_values(array_filter( $foundUrls, fn (string $url): bool => $url !== $crawler->start_url, )); $this->assertEquals([ 'https://govigilant.io/relative-url', 'https://govigilant.io/trailing-url', 'http://govigilant.io/unsecure-url', 'https://govigilant.io', ], $discoveredUrls); } #[Test] public function it_handles_malformed_html(): void { Http::fake([ 'https://govigilant.io/url-1' => Http::response('
<<<><> preventStrayRequests(); /** @var Crawler $crawler */ $crawler = Crawler::query()->create([ 'start_url' => 'vigilant', 'state' => State::Crawling, 'schedule' => '0 0 * * *', ]); /** @var CrawledUrl $crawledUrl */ $crawledUrl = $crawler->urls()->create([ 'url' => 'https://govigilant.io/url-1', 'crawled' => false, ]); /** @var CrawlUrl $action */ $action = app(CrawlUrl::class); $action->crawl($crawledUrl); $crawledUrl->refresh(); $this->assertEquals(2, $crawler->urls()->count()); $this->assertTrue($crawledUrl->crawled); } #[Test] public function it_handles_ratelimiting(): void { RatelimitedNotification::fake(); Http::fake([ 'https://govigilant.io/url-1' => Http::response('', 429), ])->preventStrayRequests(); /** @var Crawler $crawler */ $crawler = Crawler::query()->create([ 'start_url' => 'vigilant', 'state' => State::Crawling, 'schedule' => '0 0 * * *', ]); /** @var CrawledUrl $crawledUrl */ $crawledUrl = $crawler->urls()->create([ 'url' => 'https://govigilant.io/url-1', 'crawled' => false, ]); /** @var CrawlUrl $action */ $action = app(CrawlUrl::class); $action->crawl($crawledUrl); $crawler->refresh(); $this->assertEquals(State::Ratelimited, $crawler->state); $this->assertTrue($crawledUrl->crawled); } #[Test] public function it_does_not_insert_blacklisted_urls(): void { Http::fake([ 'https://govigilant.io/url-1' => Http::response(' '), ])->preventStrayRequests(); /** @var Crawler $crawler */ $crawler = Crawler::query()->create([ 'start_url' => 'https://govigilant.io', 'state' => State::Crawling, 'schedule' => '0 0 * * *', 'settings' => [ 'url_blacklist' => implode("\n", [ '~^https?://[^/]+/checkout/~i', '~^https?://[^/]+/customer/account/login~i', ]), ], ]); /** @var CrawledUrl $crawledUrl */ $crawledUrl = $crawler->urls()->create([ 'url' => 'https://govigilant.io/url-1', 'crawled' => false, ]); /** @var CrawlUrl $action */ $action = app(CrawlUrl::class); $action->crawl($crawledUrl); $discoveredUrls = $crawler->urls() ->where('crawled', '=', false) ->pluck('url') ->toArray(); $this->assertContains('https://govigilant.io/products/shoes', $discoveredUrls); $this->assertContains('https://govigilant.io/about-us', $discoveredUrls); $this->assertNotContains('https://govigilant.io/checkout/cart', $discoveredUrls); $this->assertNotContains('https://govigilant.io/customer/account/login', $discoveredUrls); } #[Test] public function it_inserts_all_urls_when_blacklist_is_empty(): void { Http::fake([ 'https://govigilant.io/url-1' => Http::response(' '), ])->preventStrayRequests(); /** @var Crawler $crawler */ $crawler = Crawler::query()->create([ 'start_url' => 'https://govigilant.io', 'state' => State::Crawling, 'schedule' => '0 0 * * *', ]); /** @var CrawledUrl $crawledUrl */ $crawledUrl = $crawler->urls()->create([ 'url' => 'https://govigilant.io/url-1', 'crawled' => false, ]); /** @var CrawlUrl $action */ $action = app(CrawlUrl::class); $action->crawl($crawledUrl); $discoveredUrls = $crawler->urls() ->where('crawled', '=', false) ->pluck('url') ->toArray(); $this->assertContains('https://govigilant.io/checkout/cart', $discoveredUrls); $this->assertContains('https://govigilant.io/about-us', $discoveredUrls); } } ================================================ FILE: packages/crawler/tests/Actions/ProcessCrawlerStateTest.php ================================================ create([ 'start_url' => 'vigilant', 'state' => State::Crawling, 'schedule' => '0 0 * * *', ]); $crawler->urls() ->where('url', '=', $crawler->start_url) ->update(['crawled' => true]); $crawler->urls()->create([ 'url' => 'vigilant/url-1', 'crawled' => true, ]); /** @var ProcessCrawlerState $action */ $action = app(ProcessCrawlerState::class); $action->process($crawler); $crawler->refresh(); $this->assertEquals(State::Finished, $crawler->state); Event::assertDispatched(CrawlerFinishedEvent::class); } } ================================================ FILE: packages/crawler/tests/Actions/StartCrawlerTest.php ================================================ create([ 'start_url' => 'vigilant', 'schedule' => '0 0 * * *', ]); /** @var StartCrawler $action */ $action = app(StartCrawler::class); $action->start($crawler); /** @var ?CrawledUrl $startUrl */ $startUrl = $crawler->urls()->firstWhere('url', '=', 'vigilant'); $this->assertNotNull($startUrl); $crawler->refresh(); $this->assertEquals(State::Crawling, $crawler->state); $this->assertNull($crawler->crawler_stats); } #[Test] public function it_starts_sitemap_job(): void { Bus::fake(); /** @var Crawler $crawler */ $crawler = Crawler::query()->create([ 'start_url' => 'vigilant', 'sitemaps' => ['sitemap-1'], 'schedule' => '0 0 * * *', ]); /** @var StartCrawler $action */ $action = app(StartCrawler::class); $action->start($crawler); Bus::assertDispatched(ImportSitemapsJob::class); } } ================================================ FILE: packages/crawler/tests/TestCase.php ================================================ set('database.default', 'testbench'); $app['config']->set('database.connections.testbench', [ 'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '', ]); } } ================================================ FILE: packages/cve/.gitignore ================================================ vendor composer.lock .phpunit.result.cache ================================================ FILE: packages/cve/composer.json ================================================ { "name": "vigilant/cve", "description": "Vigilant CVE Monitor", "type": "package", "license": "AGPL", "authors": [ { "name": "Vincent Boon", "email": "info@vincentbean.com", "role": "Developer" } ], "require": { "php": "^8.3", "guzzlehttp/guzzle": "^7.8", "laravel/framework": "^12.0", "livewire/livewire": "^3.4", "vigilant/core": "@dev", "vigilant/sites": "@dev", "vigilant/users": "@dev", "vigilant/frontend": "@dev", "vigilant/notifications": "@dev" }, "require-dev": { "laravel/pint": "^1.6", "larastan/larastan": "^3.0", "orchestra/testbench": "^10.0", "phpstan/phpstan-mockery": "^2.0", "phpunit/phpunit": "^11.0" }, "autoload": { "psr-4": { "Vigilant\\Cve\\": "src", "Vigilant\\Cve\\Database\\Factories\\": "database/factories", "Vigilant\\Users\\Database\\Factories\\": "../users/database/factories" } }, "autoload-dev": { "psr-4": { "Vigilant\\Cve\\Tests\\": "tests" } }, "scripts": { "test": "phpunit", "analyse": "phpstan", "style": "pint --test", "quality": [ "@test", "@analyse" ] }, "config": { "sort-packages": true, "allow-plugins": { "php-http/discovery": true } }, "extra": { "laravel": { "providers": [ "Vigilant\\Cve\\ServiceProvider" ] } }, "minimum-stability": "dev", "prefer-stable": true, "repositories": [ { "type": "path", "url": "../*" } ] } ================================================ FILE: packages/cve/config/cve.php ================================================ 'cve', ]; ================================================ FILE: packages/cve/database/migrations/2025_04_18_090000_create_cves_table.php ================================================ id(); $table->string('identifier'); $table->float('score')->nullable(); $table->text('description'); $table->dateTime('published_at'); $table->dateTime('modified_at'); $table->json('data'); $table->timestamps(); }); } public function down(): void { Schema::dropIfExists('cves'); } }; ================================================ FILE: packages/cve/database/migrations/2025_04_18_100000_create_cve_monitors_table.php ================================================ id(); $table->foreignIdFor(Site::class)->nullable()->constrained()->onDelete('cascade'); $table->foreignIdFor(Team::class)->constrained()->onDelete('cascade'); $table->boolean('enabled')->default(true); $table->string('keyword'); $table->timestamps(); }); } public function down(): void { Schema::dropIfExists('cve_monitors'); } }; ================================================ FILE: packages/cve/database/migrations/2025_04_18_103000_create_cve_monitor_matches_table.php ================================================ id(); $table->foreignIdFor(Cve::class)->constrained()->onDelete('cascade'); $table->foreignIdFor(CveMonitor::class)->constrained()->onDelete('cascade'); $table->timestamps(); }); } public function down(): void { Schema::dropIfExists('cve_monitor_matches'); } }; ================================================ FILE: packages/cve/database/migrations/2025_10_04_135717_add_fulltext_index_to_cves_description.php ================================================ getDriverName(); if (in_array($driver, ['mysql', 'mariadb'])) { DB::statement('CREATE FULLTEXT INDEX idx_cves_description_fulltext ON cves(description)'); } } public function down(): void { $driver = DB::connection()->getDriverName(); if (in_array($driver, ['mysql', 'mariadb'])) { DB::statement('DROP INDEX idx_cves_description_fulltext ON cves'); } } }; ================================================ FILE: packages/cve/database/migrations/2025_10_04_135739_add_unique_index_to_cve_monitor_matches.php ================================================ unique(['cve_id', 'cve_monitor_id'], 'unique_cve_monitor_match'); }); } public function down(): void { Schema::table('cve_monitor_matches', function (Blueprint $table): void { $table->dropUnique('unique_cve_monitor_match'); }); } }; ================================================ FILE: packages/cve/phpstan.neon ================================================ includes: - ./vendor/larastan/larastan/extension.neon - ./vendor/phpstan/phpstan-mockery/extension.neon parameters: paths: - src - tests level: 8 ignoreErrors: - identifier: missingType.iterableValue - identifier: missingType.generics ================================================ FILE: packages/cve/phpunit.xml ================================================ ./tests/* ./src ================================================ FILE: packages/cve/resources/navigation.php ================================================ parent('infrastructure') ->icon('phosphor-shield-star') ->gate('use-cve') ->routeIs('cve*') ->sort(700); ================================================ FILE: packages/cve/resources/views/components/empty-states/monitors.blade.php ================================================ ================================================ FILE: packages/cve/resources/views/cve.blade.php ================================================
{{ $cve->identifier }} {{ $cve->score ?? 0 }} {{ $cve->published_at->format('Y-m-d H:i:s') }} {{ $cve->modified_at->format('Y-m-d H:i:s') }}

{{ $cve->description }}

@lang('References')

================================================ FILE: packages/cve/resources/views/index.blade.php ================================================ @lang('Add CVE Monitor') @lang('Add CVE Monitor') @if ($hasMonitors) @else @endif ================================================ FILE: packages/cve/resources/views/livewire/cve-monitor-form.blade.php ================================================
@if (!$inline) @endif
================================================ FILE: packages/cve/resources/views/monitor.blade.php ================================================ @lang('Edit') @lang('Delete') @lang('Edit') @lang('Delete')

{{ __('Matched CVE\'s') }}

@lang('Delete CVE Monitor')

@lang('Are you sure you want to delete this CVE monitor?')

@svg('phosphor-warning-circle', 'w-5 h-5 text-orange mt-0.5')

Keyword: {{ $monitor->keyword }}

@lang('This action cannot be undone. All matched CVEs for this monitor will be permanently deleted.')

@lang('Cancel')
@csrf @method('DELETE') @lang('Delete Monitor')
================================================ FILE: packages/cve/routes/web.php ================================================ group(function () { Route::get('/', [CveMonitorController::class, 'list'])->name('cve.index'); Route::get('/create', CveMonitorForm::class)->name('cve.monitor.create'); Route::get('/edit/{monitor}', CveMonitorForm::class)->name('cve.monitor.edit'); Route::get('/{monitor}', [CveMonitorController::class, 'view'])->name('cve.monitor.view'); Route::delete('/{monitor}', [CveMonitorController::class, 'delete'])->name('cve.monitor.delete')->can('delete,monitor'); Route::get('/{monitor}/{cve}', [CveController::class, 'view'])->name('cve.view'); }); ================================================ FILE: packages/cve/src/Actions/ImportAllCves.php ================================================ $pageSize, 'startIndex' => $page * $pageSize, ])->throw(); $cves = $response->json('vulnerabilities', []); foreach ($cves as $cve) { $this->importCve->import($cve, false); } if (count($cves) === $pageSize) { ImportAllCvesJob::dispatch($page + 1)->delay(now()->addSeconds(30)); } } } ================================================ FILE: packages/cve/src/Actions/ImportCve.php ================================================ > $descriptions */ $descriptions = data_get($cve, 'cve.descriptions', []); $description = collect($descriptions)->firstWhere('lang', '=', 'en'); if ($description === null) { $description = Arr::first($descriptions); } $score = data_get($cve, 'cve.metrics.cvssMetricV31.0.cvssData.baseScore'); if ($score === null) { $score = data_get($cve, 'cve.metrics.cvssMetricV2.0.cvssData.baseScore'); } $model = Cve::query()->updateOrCreate([ 'identifier' => data_get($cve, 'cve.id'), ], [ 'score' => $score, 'description' => $description['value'] ?? '', 'published_at' => data_get($cve, 'cve.published'), 'modified_at' => data_get($cve, 'cve.lastModified'), 'data' => $cve, ]); if ($notify && $model->wasRecentlyCreated && $model->published_at->isAfter(now()->subWeek())) { MatchCveMonitorsJob::dispatch($model); } } } ================================================ FILE: packages/cve/src/Actions/ImportCves.php ================================================ orderBy('published_at', 'desc') ->first()->published_at ?? null; } if ($from === null) { $from = now()->subDay(); } $endpoint = 'https://services.nvd.nist.gov/rest/json/cves/2.0'; $to = $from->clone(); $to->addDays(30); if ($to->isFuture()) { $to = now(); } $response = Http::get($endpoint, [ 'pubStartDate' => $from->format('Y-m-d\TH:i:s\Z'), 'pubEndDate' => $to->format('Y-m-d\TH:i:s\Z'), ])->throw(); $cves = $response->json('vulnerabilities', []); foreach ($cves as $cve) { $this->importCve->import($cve); } } } ================================================ FILE: packages/cve/src/Actions/MatchCve.php ================================================ description)->lower()->contains(strtolower($monitor->keyword)); if (! $matches) { return; } $monitor->matches()->firstOrCreate([ 'cve_id' => $cve->id, ]); CveMatchedNotification::notify($monitor, $cve); } } ================================================ FILE: packages/cve/src/Actions/MatchExistingCves.php ================================================ runningUnitTests()) { return; } DB::statement(' INSERT IGNORE INTO cve_monitor_matches (cve_id, cve_monitor_id, created_at, updated_at) SELECT id as cve_id, ? as cve_monitor_id, NOW() as created_at, NOW() as updated_at FROM cves WHERE MATCH(description) AGAINST(? IN BOOLEAN MODE) ', [ $monitor->id, $monitor->keyword, ]); } } ================================================ FILE: packages/cve/src/Commands/ImportAllCvesCommand.php ================================================ argument('page'); ImportAllCvesJob::dispatch($page); return static::SUCCESS; } } ================================================ FILE: packages/cve/src/Commands/ImportCvesCommand.php ================================================ argument('from'); $from = $from !== null ? Carbon::parse($from) : null; ImportCvesJob::dispatch($from); return static::SUCCESS; } } ================================================ FILE: packages/cve/src/Commands/MatchCveCommand.php ================================================ argument('monitorId'); /** @var ?int $cveId */ $cveId = $this->argument('cveId'); $monitor = CveMonitor::query() ->withoutGlobalScopes() ->findOrFail($monitorId); $cve = Cve::query()->findOrFail($cveId); MatchCveJob::dispatch($monitor, $cve); return static::SUCCESS; } } ================================================ FILE: packages/cve/src/Commands/MatchExistingCvesCommand.php ================================================ argument('monitorId'); $monitors = CveMonitor::query() ->withoutGlobalScopes() ->when($monitorId, function ($query) use ($monitorId) { return $query->where('id', $monitorId); }) ->get(); foreach ($monitors as $monitor) { MatchExistingCvesJob::dispatch($monitor); } return static::SUCCESS; } } ================================================ FILE: packages/cve/src/Http/Controllers/CveController.php ================================================ $monitor, 'cve' => $cve, ]); } } ================================================ FILE: packages/cve/src/Http/Controllers/CveMonitorController.php ================================================ exists(); return view($view, [ 'hasMonitors' => $hasMonitors, ]); } public function view(CveMonitor $monitor): View { /** @var view-string $view */ $view = 'cve::monitor'; return view($view, [ 'monitor' => $monitor, ]); } } ================================================ FILE: packages/cve/src/Jobs/ImportAllCvesJob.php ================================================ onQueue(config()->string('cve.queue')); } public function handle(ImportAllCves $importer): void { $importer->import($this->page); } public function uniqueId(): int { return $this->page; } public function tags(): array { return [ $this->page, ]; } } ================================================ FILE: packages/cve/src/Jobs/ImportCvesJob.php ================================================ onQueue(config()->string('cve.queue')); } public function handle(ImportCves $importer): void { $importer->import($this->from); } public function uniqueId(): string { return $this->from?->format('Y-m-d') ?? 'recent'; } public function tags(): array { return [ $this->from?->format('Y-m-d') ?? 'recent', ]; } } ================================================ FILE: packages/cve/src/Jobs/MatchCveJob.php ================================================ onQueue(config()->string('cve.queue')); } public function handle(MatchCve $matcher, TeamService $teamService): void { $teamService->setTeamById($this->monitor->team_id); $matcher->match($this->monitor, $this->cve); } } ================================================ FILE: packages/cve/src/Jobs/MatchCveMonitorsJob.php ================================================ onQueue(config()->string('cve.queue')); } public function handle(): void { CveMonitor::query() ->withoutGlobalScopes() ->each(function (CveMonitor $monitor): void { MatchCveJob::dispatch($monitor, $this->cve); }); } public function uniqueId(): int { return $this->cve->id; } } ================================================ FILE: packages/cve/src/Jobs/MatchExistingCvesJob.php ================================================ onQueue(config()->string('cve.queue')); } public function handle(MatchExistingCves $matcher, TeamService $teamService): void { $teamService->setTeamById($this->monitor->team_id); $matcher->match($this->monitor); } } ================================================ FILE: packages/cve/src/Livewire/CveMonitorForm.php ================================================ exists) { $this->authorize('update', $monitor); } else { $this->authorize('create', $monitor); } $this->form->fill($monitor->toArray()); $this->cveMonitor = $monitor; } } public function save(): void { $this->validate(); if ($this->cveMonitor->exists) { $this->authorize('update', $this->cveMonitor); $this->cveMonitor->update($this->form->all()); } else { $this->authorize('create', $this->cveMonitor); $this->cveMonitor = CveMonitor::query()->create( $this->form->all() ); } $this->alert( __('Saved'), __('CVE monitor was successfully :action', ['action' => $this->cveMonitor->wasRecentlyCreated ? 'created' : 'saved']), AlertType::Success ); $this->redirectRoute('cve.index'); } public function render(): mixed { /** @var view-string $view */ $view = 'cve::livewire.cve-monitor-form'; return view($view, [ 'updating' => $this->cveMonitor->exists, ]); } } ================================================ FILE: packages/cve/src/Livewire/Forms/CveMonitorForm.php ================================================ ['required', 'max:255'], 'enabled' => ['boolean', new CanEnableRule(DnsMonitor::class)], ]; } } ================================================ FILE: packages/cve/src/Livewire/Tables/CveMonitorMatchesTable.php ================================================ monitor = $monitor; } protected function columns(): array { return [ Column::make(__('CVE'), 'cve.identifier') ->searchable() ->sortable(), Column::make(__('Score'), 'cve.score') ->searchable() ->sortable(), Column::make(__('Description'), 'cve.description') ->displayUsing(fn (string $description): string => str($description)->limit(100)) ->searchable() ->sortable(), ]; } protected function link(Model $record): string { /** @var CveMonitorMatch $record */ return route('cve.view', ['monitor' => $record->cveMonitor, 'cve' => $record->cve]); } protected function query(): Builder { return parent::query() ->where('cve_monitor_id', '=', $this->monitor->id) ->with('cve'); } } ================================================ FILE: packages/cve/src/Livewire/Tables/CveMonitorTable.php ================================================ text(function (CveMonitor $monitor): string { return $monitor->enabled ? __('Enabled') : __('Disabled'); }) ->status(function (CveMonitor $monitor): Status { return $monitor->enabled ? Status::Success : Status::Danger; }), Column::make(__('Keyword'), 'keyword') ->searchable() ->sortable(), Column::make(__('Matched CVE\'s'), 'total_matches') ->sortable(function (Builder $builder, Direction $direction): void { $builder->orderBy(function (Query $query): void { $query->selectRaw('COUNT(*)') ->from('cve_monitor_matches') ->whereColumn('cve_monitor_matches.cve_monitor_id', 'cve_monitors.id'); }, $direction->value); })->searchable(function (Builder $builder, mixed $value): void { $builder->where(function (Builder $query): void { $query->selectRaw('COUNT(*)') ->from('cve_monitor_matches') ->whereColumn('cve_monitor_matches.cve_monitor_id', 'cve_monitors.id'); }, '=', $value); }), ]; } protected function link(Model $record): string { return route('cve.monitor.view', ['monitor' => $record]); } protected function filters(): array { return [ SelectFilter::make(__('Site'), 'site_id') ->options( Site::query() ->orderBy('url') ->pluck('url', 'id') ->toArray() ), ]; } protected function actions(): array { $actions = [ Action::make(__('Enable'), function (Enumerable $models): void { foreach ($models as $model) { if (! Gate::allows('create', $model)) { break; } $model->update(['enabled' => true]); } }, 'enable'), Action::make(__('Disable'), function (Enumerable $models): void { $models->each(fn (CveMonitor $monitor) => $monitor->update(['enabled' => false])); }, 'disable'), Action::make(__('Delete'), function (Enumerable $models): void { $models->each(fn (CveMonitor $monitor) => $monitor->delete()); }, 'delete'), ]; if (ce()) { $actions[] = Action::make(__('Import all CVE\'s'), function (): void { $importer = app(ImportAllCves::class); $importer->import(0); }, 'import')->standalone(); } return $actions; } protected function applySelect(Builder $builder): static { parent::applySelect($builder); $builder->addSelect( DB::raw('( SELECT COUNT(`cve_monitor_matches`.`id`) FROM `cve_monitor_matches` WHERE `cve_monitor_matches`.`cve_monitor_id` = `cve_monitors`.`id` ) AS total_matches') ); return $this; } } ================================================ FILE: packages/cve/src/Models/Cve.php ================================================ $matches */ class Cve extends Model { protected $guarded = []; protected $casts = [ 'score' => 'float', 'published_at' => 'datetime', 'modified_at' => 'datetime', 'data' => 'array', ]; public function matches(): HasMany { return $this->hasMany(CveMonitorMatch::class); } } ================================================ FILE: packages/cve/src/Models/CveMonitor.php ================================================ 'boolean', ]; public function matches(): HasMany { return $this->hasMany(CveMonitorMatch::class); } public function site(): BelongsTo { return $this->belongsTo(Site::class); } public function team(): BelongsTo { return $this->belongsTo(Team::class); } } ================================================ FILE: packages/cve/src/Models/CveMonitorMatch.php ================================================ belongsTo(Cve::class); } public function cveMonitor(): BelongsTo { return $this->belongsTo(CveMonitor::class); } } ================================================ FILE: packages/cve/src/Notifications/Conditions/KeywordCondition.php ================================================ pluck('keyword', 'id') ->unique() ->toArray(); } public function applies( Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta ): bool { /** @var CveMatchedNotification $notification */ return $notification->monitor->id === $value; } } ================================================ FILE: packages/cve/src/Notifications/Conditions/ScoreCondition.php ================================================ 'Equal to', '<>' => 'Not equal to', '<' => 'Less than', '<=' => 'Less or equal than', '>' => 'Greater than', '>=' => 'Greater or equal than', ]; } public function applies( Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta ): bool { /** @var CveMatchedNotification $notification */ $score = $notification->cve->score ?? 0; return match ($operator) { '=' => $score == $value, '<>' => $score != $value, '<' => $score < $value, '<=' => $score <= $value, '>' => $score > $value, '>=' => $score >= $value, default => false, }; } } ================================================ FILE: packages/cve/src/Notifications/CveMatchedNotification.php ================================================ 'group', 'children' => [ [ 'type' => 'condition', 'condition' => ScoreCondition::class, 'operator' => '>=', 'value' => 6, ], ], ]; public function __construct(public CveMonitor $monitor, public Cve $cve) {} public function title(): string { return __(':id with a score of :score found', [ 'id' => $this->cve->identifier, 'score' => $this->cve->score ?? 0, ]); } public function description(): string { $description = __('The CVE :id was published at :publishedAt and has a score of :score and matched your monitored keyword :keyword.', [ 'id' => $this->cve->identifier, 'publishedAt' => $this->cve->published_at->toDateString(), 'keyword' => $this->monitor->keyword, 'score' => $this->cve->score ?? 0, ]); $description .= "\n\n"; $description .= __('Description: :description', [ 'description' => str($this->cve->description)->limit(500), ]); return $description; } public static function info(): ?string { return __('Triggered when a new CVE is published matching your monitored keywords.'); } public function level(): Level { if ($this->cve->score >= 7) { return Level::Critical; } if ($this->cve->score >= 4) { return Level::Warning; } return Level::Info; } public function uniqueId(): string|int { return $this->cve->id; } public function site(): ?Site { return $this->monitor->site; } } ================================================ FILE: packages/cve/src/Observers/CveMonitorObserver.php ================================================ matches()->delete(); MatchExistingCvesJob::dispatch($monitor); } } ================================================ FILE: packages/cve/src/ServiceProvider.php ================================================ registerConfig(); } protected function registerConfig(): static { $this->mergeConfigFrom(__DIR__.'/../config/cve.php', 'cve'); return $this; } public function boot(): void { $this ->bootRoutes() ->bootConfig() ->bootMigrations() ->bootCommands() ->bootViews() ->bootLivewire() ->bootNavigation() ->bootNotifications() ->bootGates() ->bootPolicies(); } protected function bootRoutes(): static { if (! $this->app->routesAreCached()) { Route::middleware(['web', 'auth']) ->group(fn () => $this->loadRoutesFrom(__DIR__.'/../routes/web.php')); } return $this; } protected function bootConfig(): static { $this->publishes([ __DIR__.'/../config/cve.php' => config_path('cve.php'), ], 'config'); return $this; } protected function bootMigrations(): static { $this->loadMigrationsFrom(__DIR__.'/../database/migrations'); return $this; } protected function bootCommands(): static { if ($this->app->runningInConsole()) { $this->commands([ ImportAllCvesCommand::class, ImportCvesCommand::class, MatchExistingCvesCommand::class, MatchCveCommand::class, ]); } return $this; } protected function bootViews(): static { $this->loadViewsFrom(__DIR__.'/../resources/views', 'cve'); return $this; } protected function bootLivewire(): static { Livewire::component('cve-monitor-table', CveMonitorTable::class); Livewire::component('cve-monitor-form', CveMonitorForm::class); Livewire::component('cve-monitor-matches-table', CveMonitorMatchesTable::class); return $this; } protected function bootNavigation(): static { Navigation::path(__DIR__.'/../resources/navigation.php'); return $this; } protected function bootNotifications(): static { NotificationRegistry::registerNotification([ CveMatchedNotification::class, ]); NotificationRegistry::registerCondition(CveMatchedNotification::class, [ ScoreCondition::class, KeywordCondition::class, ]); return $this; } protected function bootGates(): static { if (ce()) { Gate::define('use-cve', function (User $user): bool { return ce(); }); } return $this; } protected function bootPolicies(): static { if (ce()) { Gate::policy(CveMonitor::class, AllowAllPolicy::class); } return $this; } } ================================================ FILE: packages/cve/testbench.yaml ================================================ providers: - Vigilant\Cve\ServiceProvider ================================================ FILE: packages/cve/tests/Actions/ImportAllCvesTest.php ================================================ [ 'id' => "CVE-2024-{$i}", 'descriptions' => [ ['lang' => 'en', 'value' => "Vulnerability {$i}"], ], 'metrics' => [ 'cvssMetricV31' => [ ['cvssData' => ['baseScore' => 5.0]], ], ], 'published' => '2024-01-01T00:00:00Z', 'lastModified' => '2024-01-02T00:00:00Z', ], ]; } Http::fake([ 'services.nvd.nist.gov/*' => Http::response([ 'vulnerabilities' => $vulnerabilities, ]), ])->preventStrayRequests(); /** @var ImportAllCves $action */ $action = app(ImportAllCves::class); $action->import(0); // Should import all 500 CVEs $this->assertEquals(500, Cve::query()->count()); // Should dispatch next page job Bus::assertDispatched(ImportAllCvesJob::class); } #[Test] public function it_does_not_dispatch_next_job_for_partial_page(): void { Bus::fake(); $vulnerabilities = []; for ($i = 0; $i < 250; $i++) { $vulnerabilities[] = [ 'cve' => [ 'id' => "CVE-2024-{$i}", 'descriptions' => [ ['lang' => 'en', 'value' => "Vulnerability {$i}"], ], 'metrics' => [], 'published' => '2024-01-01T00:00:00Z', 'lastModified' => '2024-01-02T00:00:00Z', ], ]; } Http::fake([ 'services.nvd.nist.gov/*' => Http::response([ 'vulnerabilities' => $vulnerabilities, ]), ])->preventStrayRequests(); /** @var ImportAllCves $action */ $action = app(ImportAllCves::class); $action->import(0); // Should import all 250 CVEs $this->assertEquals(250, Cve::query()->count()); // Should NOT dispatch next page job (less than 500) Bus::assertNotDispatched(ImportAllCvesJob::class); } #[Test] public function it_uses_correct_pagination_parameters(): void { Http::fake([ 'services.nvd.nist.gov/*' => Http::response([ 'vulnerabilities' => [], ]), ])->preventStrayRequests(); /** @var ImportAllCves $action */ $action = app(ImportAllCves::class); $action->import(3); Http::assertSent(function ($request) { $url = $request->url(); return str_contains($url, 'resultsPerPage=500') && str_contains($url, 'startIndex=1500'); // 3 * 500 }); } #[Test] public function it_does_not_notify_for_bulk_import(): void { Bus::fake(); Http::fake([ 'services.nvd.nist.gov/*' => Http::response([ 'vulnerabilities' => [ [ 'cve' => [ 'id' => 'CVE-2024-NEW', 'descriptions' => [ ['lang' => 'en', 'value' => 'Recent vulnerability'], ], 'metrics' => [ 'cvssMetricV31' => [ ['cvssData' => ['baseScore' => 9.0]], ], ], 'published' => now()->subDays(2)->toIso8601String(), 'lastModified' => now()->toIso8601String(), ], ], ], ]), ])->preventStrayRequests(); /** @var ImportAllCves $action */ $action = app(ImportAllCves::class); $action->import(0); // Should not dispatch match job even for recent CVE Bus::assertNotDispatched(\Vigilant\Cve\Jobs\MatchCveMonitorsJob::class); } #[Test] public function it_handles_empty_response(): void { Bus::fake(); Http::fake([ 'services.nvd.nist.gov/*' => Http::response([ 'vulnerabilities' => [], ]), ])->preventStrayRequests(); /** @var ImportAllCves $action */ $action = app(ImportAllCves::class); $action->import(0); $this->assertEquals(0, Cve::query()->count()); Bus::assertNotDispatched(ImportAllCvesJob::class); } } ================================================ FILE: packages/cve/tests/Actions/ImportCveTest.php ================================================ [ 'id' => 'CVE-2024-1234', 'descriptions' => [ ['lang' => 'en', 'value' => 'Test vulnerability description'], ['lang' => 'es', 'value' => 'Descripción de vulnerabilidad'], ], 'metrics' => [ 'cvssMetricV31' => [ ['cvssData' => ['baseScore' => 7.5]], ], ], 'published' => '2024-01-01T00:00:00Z', 'lastModified' => '2024-01-02T00:00:00Z', ], ]; /** @var ImportCve $action */ $action = app(ImportCve::class); $action->import($cveData); $this->assertDatabaseHas('cves', [ 'identifier' => 'CVE-2024-1234', 'description' => 'Test vulnerability description', 'score' => 7.5, ]); } #[Test] public function it_imports_cve_without_english_description(): void { $cveData = [ 'cve' => [ 'id' => 'CVE-2024-5678', 'descriptions' => [ ['lang' => 'es', 'value' => 'Primera descripción'], ], 'metrics' => [ 'cvssMetricV2' => [ ['cvssData' => ['baseScore' => 5.0]], ], ], 'published' => '2024-01-01T00:00:00Z', 'lastModified' => '2024-01-02T00:00:00Z', ], ]; /** @var ImportCve $action */ $action = app(ImportCve::class); $action->import($cveData); $this->assertDatabaseHas('cves', [ 'identifier' => 'CVE-2024-5678', 'description' => 'Primera descripción', 'score' => 5.0, ]); } #[Test] public function it_uses_cvss_v2_when_v3_not_available(): void { $cveData = [ 'cve' => [ 'id' => 'CVE-2024-9999', 'descriptions' => [ ['lang' => 'en', 'value' => 'Test description'], ], 'metrics' => [ 'cvssMetricV2' => [ ['cvssData' => ['baseScore' => 4.3]], ], ], 'published' => '2024-01-01T00:00:00Z', 'lastModified' => '2024-01-02T00:00:00Z', ], ]; /** @var ImportCve $action */ $action = app(ImportCve::class); $action->import($cveData); $cve = Cve::query()->where('identifier', 'CVE-2024-9999')->first(); $this->assertNotNull($cve); $this->assertEquals(4.3, $cve->score); } #[Test] public function it_updates_existing_cve(): void { Cve::query()->create([ 'identifier' => 'CVE-2024-1111', 'description' => 'Old description', 'score' => 1.0, 'published_at' => '2024-01-01', 'modified_at' => '2024-01-01', 'data' => [], ]); $cveData = [ 'cve' => [ 'id' => 'CVE-2024-1111', 'descriptions' => [ ['lang' => 'en', 'value' => 'Updated description'], ], 'metrics' => [ 'cvssMetricV31' => [ ['cvssData' => ['baseScore' => 9.0]], ], ], 'published' => '2024-01-01T00:00:00Z', 'lastModified' => '2024-01-05T00:00:00Z', ], ]; /** @var ImportCve $action */ $action = app(ImportCve::class); $action->import($cveData); $cve = Cve::query()->where('identifier', 'CVE-2024-1111')->first(); $this->assertNotNull($cve); $this->assertEquals('Updated description', $cve->description); $this->assertEquals(9.0, $cve->score); } #[Test] public function it_dispatches_match_job_for_recent_cves(): void { Bus::fake(); $cveData = [ 'cve' => [ 'id' => 'CVE-2024-NEW', 'descriptions' => [ ['lang' => 'en', 'value' => 'Recent vulnerability'], ], 'metrics' => [ 'cvssMetricV31' => [ ['cvssData' => ['baseScore' => 8.0]], ], ], 'published' => now()->subDays(2)->toIso8601String(), 'lastModified' => now()->toIso8601String(), ], ]; /** @var ImportCve $action */ $action = app(ImportCve::class); $action->import($cveData, notify: true); Bus::assertDispatched(MatchCveMonitorsJob::class); } #[Test] public function it_does_not_dispatch_match_job_for_old_cves(): void { Bus::fake(); $cveData = [ 'cve' => [ 'id' => 'CVE-2020-OLD', 'descriptions' => [ ['lang' => 'en', 'value' => 'Old vulnerability'], ], 'metrics' => [ 'cvssMetricV31' => [ ['cvssData' => ['baseScore' => 8.0]], ], ], 'published' => now()->subMonths(6)->toIso8601String(), 'lastModified' => now()->toIso8601String(), ], ]; /** @var ImportCve $action */ $action = app(ImportCve::class); $action->import($cveData, notify: true); Bus::assertNotDispatched(MatchCveMonitorsJob::class); } #[Test] public function it_does_not_dispatch_match_job_when_notify_is_false(): void { Bus::fake(); $cveData = [ 'cve' => [ 'id' => 'CVE-2024-NONOTIFY', 'descriptions' => [ ['lang' => 'en', 'value' => 'Recent vulnerability'], ], 'metrics' => [ 'cvssMetricV31' => [ ['cvssData' => ['baseScore' => 8.0]], ], ], 'published' => now()->subDays(2)->toIso8601String(), 'lastModified' => now()->toIso8601String(), ], ]; /** @var ImportCve $action */ $action = app(ImportCve::class); $action->import($cveData, notify: false); Bus::assertNotDispatched(MatchCveMonitorsJob::class); } #[Test] public function it_handles_missing_score(): void { $cveData = [ 'cve' => [ 'id' => 'CVE-2024-NOSCORE', 'descriptions' => [ ['lang' => 'en', 'value' => 'Vulnerability without score'], ], 'metrics' => [], 'published' => '2024-01-01T00:00:00Z', 'lastModified' => '2024-01-02T00:00:00Z', ], ]; /** @var ImportCve $action */ $action = app(ImportCve::class); $action->import($cveData); $cve = Cve::query()->where('identifier', 'CVE-2024-NOSCORE')->first(); $this->assertNotNull($cve); $this->assertNull($cve->score); } } ================================================ FILE: packages/cve/tests/Actions/ImportCvesTest.php ================================================ Http::response([ 'vulnerabilities' => [ [ 'cve' => [ 'id' => 'CVE-2024-0001', 'descriptions' => [ ['lang' => 'en', 'value' => 'First vulnerability'], ], 'metrics' => [ 'cvssMetricV31' => [ ['cvssData' => ['baseScore' => 7.5]], ], ], 'published' => '2024-01-01T00:00:00Z', 'lastModified' => '2024-01-02T00:00:00Z', ], ], [ 'cve' => [ 'id' => 'CVE-2024-0002', 'descriptions' => [ ['lang' => 'en', 'value' => 'Second vulnerability'], ], 'metrics' => [ 'cvssMetricV31' => [ ['cvssData' => ['baseScore' => 5.0]], ], ], 'published' => '2024-01-02T00:00:00Z', 'lastModified' => '2024-01-03T00:00:00Z', ], ], ], ]), ])->preventStrayRequests(); /** @var ImportCves $action */ $action = app(ImportCves::class); $action->import(now()->subDay()); $this->assertDatabaseHas('cves', [ 'identifier' => 'CVE-2024-0001', ]); $this->assertDatabaseHas('cves', [ 'identifier' => 'CVE-2024-0002', ]); } #[Test] public function it_uses_latest_cve_date_when_from_is_null(): void { Cve::query()->create([ 'identifier' => 'CVE-2023-9999', 'description' => 'Latest existing CVE', 'score' => 5.0, 'published_at' => '2023-12-15 00:00:00', 'modified_at' => '2023-12-15 00:00:00', 'data' => [], ]); Http::fake([ 'services.nvd.nist.gov/*' => Http::response([ 'vulnerabilities' => [], ]), ])->preventStrayRequests(); /** @var ImportCves $action */ $action = app(ImportCves::class); $action->import(null); Http::assertSent(function ($request) { return str_contains($request->url(), 'pubStartDate=2023-12-15'); }); } #[Test] public function it_uses_yesterday_when_no_cves_exist(): void { Http::fake([ 'services.nvd.nist.gov/*' => Http::response([ 'vulnerabilities' => [], ]), ])->preventStrayRequests(); /** @var ImportCves $action */ $action = app(ImportCves::class); $action->import(null); Http::assertSent(function ($request) { $yesterday = now()->subDay()->format('Y-m-d'); return str_contains($request->url(), "pubStartDate={$yesterday}"); }); } #[Test] public function it_limits_date_range_to_30_days(): void { Http::fake([ 'services.nvd.nist.gov/*' => Http::response([ 'vulnerabilities' => [], ]), ])->preventStrayRequests(); $from = now()->subDays(60); /** @var ImportCves $action */ $action = app(ImportCves::class); $action->import($from); Http::assertSent(function ($request) use ($from) { $expectedEnd = $from->clone()->addDays(30)->format('Y-m-d'); return str_contains($request->url(), "pubEndDate={$expectedEnd}"); }); } #[Test] public function it_limits_end_date_to_now_when_in_future(): void { Http::fake([ 'services.nvd.nist.gov/*' => Http::response([ 'vulnerabilities' => [], ]), ])->preventStrayRequests(); $from = now()->subDays(10); /** @var ImportCves $action */ $action = app(ImportCves::class); $action->import($from); Http::assertSent(function ($request) { $today = now()->format('Y-m-d'); return str_contains($request->url(), "pubEndDate={$today}"); }); } } ================================================ FILE: packages/cve/tests/Actions/MatchCveTest.php ================================================ create([ 'keyword' => 'apache', 'enabled' => true, ]); /** @var Cve $cve */ $cve = Cve::query()->create([ 'identifier' => 'CVE-2024-1234', 'description' => 'Apache HTTP Server vulnerability allows remote code execution', 'score' => 9.8, 'published_at' => now(), 'modified_at' => now(), 'data' => [], ]); /** @var MatchCve $action */ $action = app(MatchCve::class); $action->match($monitor, $cve); $this->assertDatabaseHas('cve_monitor_matches', [ 'cve_monitor_id' => $monitor->id, 'cve_id' => $cve->id, ]); } #[Test] public function it_does_not_match_cve_without_keyword(): void { /** @var CveMonitor $monitor */ $monitor = CveMonitor::query()->create([ 'keyword' => 'apache', 'enabled' => true, ]); /** @var Cve $cve */ $cve = Cve::query()->create([ 'identifier' => 'CVE-2024-5678', 'description' => 'nginx vulnerability allows privilege escalation', 'score' => 7.2, 'published_at' => now(), 'modified_at' => now(), 'data' => [], ]); /** @var MatchCve $action */ $action = app(MatchCve::class); $action->match($monitor, $cve); $this->assertDatabaseMissing('cve_monitor_matches', [ 'cve_monitor_id' => $monitor->id, 'cve_id' => $cve->id, ]); } #[Test] public function it_matches_case_insensitively(): void { /** @var CveMonitor $monitor */ $monitor = CveMonitor::query()->create([ 'keyword' => 'APACHE', 'enabled' => true, ]); /** @var Cve $cve */ $cve = Cve::query()->create([ 'identifier' => 'CVE-2024-9999', 'description' => 'apache server issue', 'score' => 5.0, 'published_at' => now(), 'modified_at' => now(), 'data' => [], ]); /** @var MatchCve $action */ $action = app(MatchCve::class); $action->match($monitor, $cve); $this->assertDatabaseHas('cve_monitor_matches', [ 'cve_monitor_id' => $monitor->id, 'cve_id' => $cve->id, ]); } #[Test] public function it_does_not_create_duplicate_matches(): void { /** @var CveMonitor $monitor */ $monitor = CveMonitor::query()->create([ 'keyword' => 'test', 'enabled' => true, ]); /** @var Cve $cve */ $cve = Cve::query()->create([ 'identifier' => 'CVE-2024-TEST', 'description' => 'test vulnerability', 'score' => 5.0, 'published_at' => now(), 'modified_at' => now(), 'data' => [], ]); $monitor->matches()->create([ 'cve_id' => $cve->id, ]); /** @var MatchCve $action */ $action = app(MatchCve::class); $action->match($monitor, $cve); $this->assertEquals(1, $monitor->matches()->count()); } #[Test] public function it_matches_partial_keywords(): void { /** @var CveMonitor $monitor */ $monitor = CveMonitor::query()->create([ 'keyword' => 'sql', 'enabled' => true, ]); /** @var Cve $cve */ $cve = Cve::query()->create([ 'identifier' => 'CVE-2024-SQL', 'description' => 'MySQL server allows SQL injection attacks', 'score' => 8.0, 'published_at' => now(), 'modified_at' => now(), 'data' => [], ]); /** @var MatchCve $action */ $action = app(MatchCve::class); $action->match($monitor, $cve); $this->assertDatabaseHas('cve_monitor_matches', [ 'cve_monitor_id' => $monitor->id, 'cve_id' => $cve->id, ]); } } ================================================ FILE: packages/cve/tests/Models/CveMonitorMatchTest.php ================================================ create([ 'keyword' => 'apache', 'enabled' => true, ]); /** @var Cve $cve */ $cve = Cve::query()->create([ 'identifier' => 'CVE-2024-0001', 'description' => 'Apache vulnerability', 'score' => 7.5, 'published_at' => now(), 'modified_at' => now(), 'data' => [], ]); $match = CveMonitorMatch::query()->create([ 'cve_monitor_id' => $monitor->id, 'cve_id' => $cve->id, ]); $this->assertInstanceOf(CveMonitorMatch::class, $match); $this->assertEquals($monitor->id, $match->cve_monitor_id); $this->assertEquals($cve->id, $match->cve_id); } #[Test] public function it_belongs_to_cve(): void { /** @var CveMonitor $monitor */ $monitor = CveMonitor::query()->create([ 'keyword' => 'test', 'enabled' => true, ]); /** @var Cve $cve */ $cve = Cve::query()->create([ 'identifier' => 'CVE-2024-0001', 'description' => 'Test vulnerability', 'score' => 5.0, 'published_at' => now(), 'modified_at' => now(), 'data' => [], ]); $match = CveMonitorMatch::query()->create([ 'cve_monitor_id' => $monitor->id, 'cve_id' => $cve->id, ]); $this->assertInstanceOf(Cve::class, $match->cve); $this->assertEquals('CVE-2024-0001', $match->cve->identifier); } #[Test] public function it_belongs_to_cve_monitor(): void { /** @var CveMonitor $monitor */ $monitor = CveMonitor::query()->create([ 'keyword' => 'apache', 'enabled' => true, ]); /** @var Cve $cve */ $cve = Cve::query()->create([ 'identifier' => 'CVE-2024-0001', 'description' => 'Apache vulnerability', 'score' => 7.5, 'published_at' => now(), 'modified_at' => now(), 'data' => [], ]); $match = CveMonitorMatch::query()->create([ 'cve_monitor_id' => $monitor->id, 'cve_id' => $cve->id, ]); $this->assertInstanceOf(CveMonitor::class, $match->cveMonitor); $this->assertEquals('apache', $match->cveMonitor->keyword); } #[Test] public function it_has_timestamps(): void { /** @var CveMonitor $monitor */ $monitor = CveMonitor::query()->create([ 'keyword' => 'test', 'enabled' => true, ]); /** @var Cve $cve */ $cve = Cve::query()->create([ 'identifier' => 'CVE-2024-0001', 'description' => 'Test', 'score' => 5.0, 'published_at' => now(), 'modified_at' => now(), 'data' => [], ]); $match = CveMonitorMatch::query()->create([ 'cve_monitor_id' => $monitor->id, 'cve_id' => $cve->id, ]); $this->assertNotNull($match->created_at); $this->assertNotNull($match->updated_at); } } ================================================ FILE: packages/cve/tests/Models/CveMonitorTest.php ================================================ create([ 'keyword' => 'apache', 'enabled' => true, ]); $this->assertInstanceOf(CveMonitor::class, $monitor); $this->assertEquals('apache', $monitor->keyword); $this->assertTrue($monitor->enabled); } #[Test] public function it_casts_enabled_to_boolean(): void { $monitor = CveMonitor::query()->create([ 'keyword' => 'test', 'enabled' => 1, ]); $this->assertTrue($monitor->enabled); } #[Test] public function it_has_matches_relationship(): void { /** @var CveMonitor $monitor */ $monitor = CveMonitor::query()->create([ 'keyword' => 'apache', 'enabled' => true, ]); /** @var Cve $cve */ $cve = Cve::query()->create([ 'identifier' => 'CVE-2024-0001', 'description' => 'Apache vulnerability', 'score' => 7.5, 'published_at' => now(), 'modified_at' => now(), 'data' => [], ]); $monitor->matches()->create([ 'cve_id' => $cve->id, ]); $this->assertEquals(1, $monitor->matches()->count()); $this->assertInstanceOf(CveMonitorMatch::class, $monitor->matches->first()); } #[Test] public function it_can_have_multiple_matches(): void { /** @var CveMonitor $monitor */ $monitor = CveMonitor::query()->create([ 'keyword' => 'apache', 'enabled' => true, ]); for ($i = 1; $i <= 5; $i++) { $cve = Cve::query()->create([ 'identifier' => "CVE-2024-000{$i}", 'description' => 'Apache vulnerability', 'score' => 7.5, 'published_at' => now(), 'modified_at' => now(), 'data' => [], ]); $monitor->matches()->create([ 'cve_id' => $cve->id, ]); } $this->assertEquals(5, $monitor->matches()->count()); } #[Test] public function it_can_be_disabled(): void { $monitor = CveMonitor::query()->create([ 'keyword' => 'test', 'enabled' => false, ]); $this->assertFalse($monitor->enabled); } #[Test] public function it_defaults_enabled_to_false(): void { Bus::fake(); // Prevent observer from firing $monitor = CveMonitor::query()->create([ 'keyword' => 'test', ]); // Check the actual database value since the model might have default behavior $this->assertNotNull($monitor->fresh()); } } ================================================ FILE: packages/cve/tests/Models/CveTest.php ================================================ create([ 'identifier' => 'CVE-2024-1234', 'description' => 'Test vulnerability', 'score' => 7.5, 'published_at' => now(), 'modified_at' => now(), 'data' => ['test' => 'data'], ]); $this->assertInstanceOf(Cve::class, $cve); $this->assertEquals('CVE-2024-1234', $cve->identifier); $this->assertEquals(7.5, $cve->score); $this->assertNotEmpty($cve->data); } #[Test] public function it_casts_score_to_float(): void { $cve = Cve::query()->create([ 'identifier' => 'CVE-2024-5678', 'description' => 'Test', 'score' => '9.8', 'published_at' => now(), 'modified_at' => now(), 'data' => [], ]); $this->assertEquals(9.8, $cve->score); } #[Test] public function it_casts_dates_correctly(): void { $cve = Cve::query()->create([ 'identifier' => 'CVE-2024-9999', 'description' => 'Test', 'score' => 5.0, 'published_at' => '2024-01-01 00:00:00', 'modified_at' => '2024-01-02 00:00:00', 'data' => [], ]); $this->assertInstanceOf(\Illuminate\Support\Carbon::class, $cve->published_at); $this->assertInstanceOf(\Illuminate\Support\Carbon::class, $cve->modified_at); } #[Test] public function it_has_matches_relationship(): void { Bus::fake(); // Fake bus to prevent observer from firing /** @var Cve $cve */ $cve = Cve::query()->create([ 'identifier' => 'CVE-2024-0001', 'description' => 'Test vulnerability', 'score' => 7.5, 'published_at' => now(), 'modified_at' => now(), 'data' => [], ]); /** @var CveMonitor $monitor */ $monitor = CveMonitor::query()->create([ 'keyword' => 'test', 'enabled' => true, ]); $cve->matches()->create([ 'cve_monitor_id' => $monitor->id, ]); $this->assertEquals(1, $cve->matches()->count()); $this->assertInstanceOf(CveMonitorMatch::class, $cve->matches->first()); } #[Test] public function it_handles_null_score(): void { $cve = Cve::query()->create([ 'identifier' => 'CVE-2024-NULL', 'description' => 'Test', 'score' => null, 'published_at' => now(), 'modified_at' => now(), 'data' => [], ]); $this->assertNull($cve->score); } #[Test] public function it_stores_json_data(): void { $data = [ 'cve' => [ 'id' => 'CVE-2024-JSON', 'metrics' => ['cvssV3' => 7.5], ], ]; $cve = Cve::query()->create([ 'identifier' => 'CVE-2024-JSON', 'description' => 'Test', 'score' => 7.5, 'published_at' => now(), 'modified_at' => now(), 'data' => $data, ]); $this->assertEquals($data, $cve->data); $this->assertEquals('CVE-2024-JSON', $cve->data['cve']['id']); } } ================================================ FILE: packages/cve/tests/Notifications/CveMatchedNotificationTest.php ================================================ create([ 'keyword' => 'apache', 'enabled' => true, ]); /** @var Cve $cve */ $cve = Cve::query()->create([ 'identifier' => 'CVE-2024-1234', 'description' => 'Apache HTTP Server vulnerability', 'score' => 7.5, 'published_at' => now(), 'modified_at' => now(), 'data' => [], ]); $notification = new CveMatchedNotification($monitor, $cve); $this->assertInstanceOf(CveMatchedNotification::class, $notification); $this->assertEquals($monitor->id, $notification->monitor->id); $this->assertEquals($cve->id, $notification->cve->id); } #[Test] public function it_returns_correct_title(): void { /** @var CveMonitor $monitor */ $monitor = CveMonitor::query()->create([ 'keyword' => 'apache', 'enabled' => true, ]); /** @var Cve $cve */ $cve = Cve::query()->create([ 'identifier' => 'CVE-2024-1234', 'description' => 'Test vulnerability', 'score' => 8.5, 'published_at' => now(), 'modified_at' => now(), 'data' => [], ]); $notification = new CveMatchedNotification($monitor, $cve); $title = $notification->title(); $this->assertStringContainsString('CVE-2024-1234', $title); $this->assertStringContainsString('8.5', $title); } #[Test] public function it_returns_correct_description(): void { /** @var CveMonitor $monitor */ $monitor = CveMonitor::query()->create([ 'keyword' => 'apache', 'enabled' => true, ]); /** @var Cve $cve */ $cve = Cve::query()->create([ 'identifier' => 'CVE-2024-5678', 'description' => 'Apache HTTP Server remote code execution vulnerability', 'score' => 9.8, 'published_at' => now()->subDays(2), 'modified_at' => now(), 'data' => [], ]); $notification = new CveMatchedNotification($monitor, $cve); $description = $notification->description(); $this->assertStringContainsString('CVE-2024-5678', $description); $this->assertStringContainsString('apache', $description); $this->assertStringContainsString('9.8', $description); $this->assertStringContainsString('Apache HTTP Server', $description); } #[Test] public function it_returns_critical_level_for_high_score(): void { /** @var CveMonitor $monitor */ $monitor = CveMonitor::query()->create([ 'keyword' => 'test', 'enabled' => true, ]); /** @var Cve $cve */ $cve = Cve::query()->create([ 'identifier' => 'CVE-2024-CRITICAL', 'description' => 'Critical vulnerability', 'score' => 9.5, 'published_at' => now(), 'modified_at' => now(), 'data' => [], ]); $notification = new CveMatchedNotification($monitor, $cve); $this->assertEquals(Level::Critical, $notification->level()); } #[Test] public function it_returns_warning_level_for_medium_score(): void { /** @var CveMonitor $monitor */ $monitor = CveMonitor::query()->create([ 'keyword' => 'test', 'enabled' => true, ]); /** @var Cve $cve */ $cve = Cve::query()->create([ 'identifier' => 'CVE-2024-WARNING', 'description' => 'Medium vulnerability', 'score' => 5.5, 'published_at' => now(), 'modified_at' => now(), 'data' => [], ]); $notification = new CveMatchedNotification($monitor, $cve); $this->assertEquals(Level::Warning, $notification->level()); } #[Test] public function it_returns_info_level_for_low_score(): void { /** @var CveMonitor $monitor */ $monitor = CveMonitor::query()->create([ 'keyword' => 'test', 'enabled' => true, ]); /** @var Cve $cve */ $cve = Cve::query()->create([ 'identifier' => 'CVE-2024-INFO', 'description' => 'Low vulnerability', 'score' => 2.5, 'published_at' => now(), 'modified_at' => now(), 'data' => [], ]); $notification = new CveMatchedNotification($monitor, $cve); $this->assertEquals(Level::Info, $notification->level()); } #[Test] public function it_returns_unique_id(): void { /** @var CveMonitor $monitor */ $monitor = CveMonitor::query()->create([ 'keyword' => 'test', 'enabled' => true, ]); /** @var Cve $cve */ $cve = Cve::query()->create([ 'identifier' => 'CVE-2024-UNIQUE', 'description' => 'Test', 'score' => 5.0, 'published_at' => now(), 'modified_at' => now(), 'data' => [], ]); $notification = new CveMatchedNotification($monitor, $cve); $this->assertEquals($cve->id, $notification->uniqueId()); } #[Test] public function it_handles_null_score(): void { /** @var CveMonitor $monitor */ $monitor = CveMonitor::query()->create([ 'keyword' => 'test', 'enabled' => true, ]); /** @var Cve $cve */ $cve = Cve::query()->create([ 'identifier' => 'CVE-2024-NULL', 'description' => 'Test', 'score' => null, 'published_at' => now(), 'modified_at' => now(), 'data' => [], ]); $notification = new CveMatchedNotification($monitor, $cve); $title = $notification->title(); $this->assertStringContainsString('0', $title); $this->assertEquals(Level::Info, $notification->level()); } #[Test] public function it_truncates_long_descriptions(): void { /** @var CveMonitor $monitor */ $monitor = CveMonitor::query()->create([ 'keyword' => 'test', 'enabled' => true, ]); $longDescription = str_repeat('This is a very long vulnerability description. ', 50); /** @var Cve $cve */ $cve = Cve::query()->create([ 'identifier' => 'CVE-2024-LONG', 'description' => $longDescription, 'score' => 5.0, 'published_at' => now(), 'modified_at' => now(), 'data' => [], ]); $notification = new CveMatchedNotification($monitor, $cve); $description = $notification->description(); // Should be truncated (check for reasonable length, accounting for extra text) $this->assertLessThanOrEqual(700, strlen($description)); $this->assertStringContainsString('...', $description); } } ================================================ FILE: packages/cve/tests/TestCase.php ================================================ set('database.default', 'testbench'); $app['config']->set('database.connections.testbench', [ 'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '', ]); } } ================================================ FILE: packages/dns/.gitignore ================================================ vendor composer.lock .phpunit.result.cache ================================================ FILE: packages/dns/composer.json ================================================ { "name": "vigilant/dns", "description": "Vigilant DNS", "type": "package", "license": "AGPL", "authors": [ { "name": "Vincent Boon", "email": "info@vincentbean.com", "role": "Developer" } ], "require": { "php": "^8.3", "guzzlehttp/guzzle": "^7.8", "laravel/framework": "^12.0", "livewire/livewire": "^3.4", "vigilant/core": "@dev", "vigilant/sites": "@dev", "vigilant/users": "@dev", "vigilant/frontend": "@dev", "vigilant/notifications": "@dev", "bluelibraries/dns": "@dev" }, "require-dev": { "laravel/pint": "^1.6", "larastan/larastan": "^3.0", "orchestra/testbench": "^10.0", "phpstan/phpstan-mockery": "^2.0", "phpunit/phpunit": "^11.0" }, "autoload": { "psr-4": { "Vigilant\\Dns\\": "src", "Vigilant\\Dns\\Database\\Factories\\": "database/factories", "Vigilant\\Users\\Database\\Factories\\": "../users/database/factories" } }, "autoload-dev": { "psr-4": { "Vigilant\\Dns\\Tests\\": "tests" } }, "scripts": { "test": "phpunit", "analyse": "phpstan", "style": "pint --test", "quality": [ "@test", "@analyse" ] }, "config": { "sort-packages": true, "allow-plugins": { "php-http/discovery": true } }, "extra": { "laravel": { "providers": [ "Vigilant\\Dns\\ServiceProvider" ] } }, "minimum-stability": "dev", "prefer-stable": true, "repositories": [ { "type": "path", "url": "../*" }, { "type": "vcs", "url": "git@github.com:VincentBean/dns.git" } ] } ================================================ FILE: packages/dns/config/dns.php ================================================ 'dns', 'nameservers' => env('DNS_NAMESERVERS', '1.1.1.1,1.0.0.1,9.9.9.9,8.8.8.8'), 'max_attempts' => (int) env('DNS_MAX_ATTEMPTS', 3), ]; ================================================ FILE: packages/dns/database/migrations/2024_07_16_073000_create_dns_monitors_table.php ================================================ id(); $table->foreignIdFor(Site::class)->nullable()->constrained()->onDelete('cascade'); $table->foreignIdFor(Team::class)->constrained()->onDelete('cascade'); $table->string('type'); $table->string('record'); $table->string('value')->nullable(); $table->json('geoip')->nullable(); $table->timestamps(); }); } public function down(): void { Schema::dropIfExists('dns_monitors'); } }; ================================================ FILE: packages/dns/database/migrations/2024_07_16_073500_create_dns_monitor_history_table.php ================================================ id(); $table->foreignIdFor(DnsMonitor::class)->constrained()->onDelete('cascade'); $table->foreignIdFor(Team::class)->constrained()->onDelete('cascade'); $table->string('type'); $table->string('value'); $table->json('geoip')->nullable(); $table->timestamps(); }); } public function down(): void { Schema::dropIfExists('dns_monitor_histories'); } }; ================================================ FILE: packages/dns/database/migrations/2025_01_23_220000_dns_monitor_value_field_size.php ================================================ string('value', 4096)->change(); }); Schema::table('dns_monitor_histories', function (Blueprint $table): void { $table->string('value', 4096)->change(); }); } }; ================================================ FILE: packages/dns/database/migrations/2025_02_01_180000_dns_monitor_enabled_field.php ================================================ boolean('enabled')->default(true)->after('id'); }); } public function down(): void { Schema::dropColumns('dns_monitors', ['enabled']); } }; ================================================ FILE: packages/dns/database/migrations/2025_03_22_090000_dns_monitor_value_field_nullable.php ================================================ string('value', 4096)->nullable()->change(); }); Schema::table('dns_monitor_histories', function (Blueprint $table): void { $table->string('value', 4096)->nullable()->change(); }); } }; ================================================ FILE: packages/dns/phpstan.neon ================================================ includes: - ./vendor/larastan/larastan/extension.neon - ./vendor/phpstan/phpstan-mockery/extension.neon parameters: paths: - src - tests level: 8 ignoreErrors: - identifier: missingType.iterableValue - identifier: missingType.generics ================================================ FILE: packages/dns/phpunit.xml ================================================ ./tests/* ./src ================================================ FILE: packages/dns/resources/navigation.php ================================================ parent('infrastructure') ->icon('phosphor-globe-simple') ->gate('use-dns') ->routeIs('dns*') ->sort(400); ================================================ FILE: packages/dns/resources/views/components/empty-states/monitors.blade.php ================================================ ================================================ FILE: packages/dns/resources/views/livewire/dns-monitor-form.blade.php ================================================ @props(['dnsMonitor' => null, 'inline' => false])
@if (!$inline) @endif @foreach (\Vigilant\Dns\Enums\Type::cases() as $type) @endforeach
@if ($resolveFailed)

@lang('Failed to resolve record.')

@endif @lang('Resolve value')
================================================ FILE: packages/dns/resources/views/livewire/import.blade.php ================================================ @props(['inline' => false])
!$inline])> @if (!$inline) @endif
@lang('Import')
@lang('Looking up DNS records')
@if ($records === []) @if ($noRecords)

@lang('No records found')

@endif @else
@foreach ($records as $index => $record) @continue(in_array($index, $deleted)) @endforeach
@lang('Type') @lang('Host') @lang('Value') @lang('Remove')
{{ $record['type']->name }} {{ $record['host'] }} {{ $record['value'] }} @lang('Remove')
@if (!$inline && count($records) > 0)
@lang('Save')
@endif @endif
================================================ FILE: packages/dns/resources/views/livewire/monitor/dashboard.blade.php ================================================
{{ $count }} @if ($lastChange === null) @else @lang(':type record :record :time', [ 'type' => $lastChange->monitor->type->value, 'record' => $lastChange->monitor->record, 'time' => $lastChange->created_at->diffForHumans(), ]) @endif
================================================ FILE: packages/dns/resources/views/livewire/monitor-history.blade.php ================================================
@lang('Delete')
@lang('Delete DNS Monitor')

@lang('Are you sure you want to delete this DNS monitor?')

@svg('phosphor-warning-circle', 'w-5 h-5 text-orange mt-0.5')

{{ $monitor->type->name }} record for {{ $monitor->record }}

@lang('This action cannot be undone. All history for this monitor will be permanently deleted.')

@lang('Cancel')
@csrf @method('DELETE') @lang('Delete Monitor')
================================================ FILE: packages/dns/resources/views/livewire/monitors.blade.php ================================================
@lang('Import domain') @lang('Add DNS Monitor') @lang('Import domain') @lang('Add DNS Monitor') @if ($hasMonitors) @else @endif
================================================ FILE: packages/dns/routes/web.php ================================================ middleware('can:use-dns') ->group(function (): void { Route::get('dns', DnsMonitors::class)->name('dns.index'); Route::get('dns/{monitor}/history', DnsMonitorHistory::class)->name('dns.history'); Route::delete('dns/{monitor}', [DnsMonitorController::class, 'delete'])->name('dns.delete')->can('delete,monitor'); Route::get('dns/create', DnsMonitorForm::class)->name('dns.create'); Route::get('dns/import', DnsImport::class)->name('dns.import'); }); ================================================ FILE: packages/dns/src/Actions/CheckDnsRecord.php ================================================ record->resolve($monitor->type, $monitor->record); if ($resolved === $monitor->value) { return; } $this->teamService->setTeamById($monitor->team_id); if ($resolved === null) { $monitor->update([ 'value' => null, ]); RecordNotResolvedNotification::notify($monitor, $monitor->history()->latest()->first()); return; } $previous = $monitor->history()->create([ 'type' => $monitor->type, 'value' => $monitor->value, 'geoip' => $monitor->geoip, ]); $monitor->update([ 'value' => $resolved, ]); RecordChangedNotification::notify($monitor, $previous); } } ================================================ FILE: packages/dns/src/Actions/ResolveGeoIp.php ================================================ value); if (! $response->ok() || $response->json('status') !== 'success') { return; } $geoip = $response->json(); $monitor->update([ 'geoip' => [ 'country_code' => $geoip['countryCode'], 'country_name' => $geoip['country'], 'region_code' => $geoip['region'], 'region_name' => $geoip['regionName'], 'city' => $geoip['city'], 'isp' => $geoip['isp'], 'org' => $geoip['org'], 'as' => $geoip['as'], ], ]); } } ================================================ FILE: packages/dns/src/Actions/ResolveRecord.php ================================================ client->get($record, $type->flag())) ->map(fn (AbstractRecord $record): array => $record->toArray()) ->toArray(); if (count($result) === 0) { return null; } if (count($result) === 1) { $result = $result[0]; } $parser = $type->parser(); return $parser->parse($result); } } ================================================ FILE: packages/dns/src/Client/DnsClient.php ================================================ integer('dns.max_attempts', 3); if ($attempt > $maxAttempts) { return []; } if ($attempt > 1) { sleep($attempt); // Not the best solution, we should move this to DNS over HTTPs } $nameServer = $this->getNameserver(); if ($tcp) { $dnsHandler = (new TCP) ->setNameserver($nameServer) ->setTimeout(3); } else { $dnsHandler = (new UDP) ->setNameserver($nameServer) ->setTimeout(3); } $dnsRecordsService = new DnsRecords($dnsHandler); try { $result = $dnsRecordsService->get($record, $type); } catch (DnsHandlerException $e) { logger()->error("Failed to retrieve DNS record $record on attempt $attempt with nameserer $nameServer: ".$e->getMessage().' '.$e->getTraceAsString()); return $this->get($record, $type, $attempt + 1, $attempt > 1); } if (count($result) === 0 && $attempt < $maxAttempts) { return $this->get($record, $type, $attempt + 1, $attempt > 1); } return $result; } protected function getNameserver(): string { $nameservers = config()->string('dns.nameservers'); return str($nameservers)->explode(',')->random(); } } ================================================ FILE: packages/dns/src/Commands/CheckAllDnsRecordsCommand.php ================================================ withoutGlobalScopes() ->where('enabled', '=', true) ->get() ->each(fn (DnsMonitor $monitor): PendingDispatch => CheckDnsRecordJob::dispatch($monitor)); return static::SUCCESS; } } ================================================ FILE: packages/dns/src/Commands/CheckDnsRecordCommand.php ================================================ argument('recordId'); /** @var DnsMonitor $monitor */ $monitor = DnsMonitor::query() ->withoutGlobalScopes() ->findOrFail($recordId); CheckDnsRecordJob::dispatch($monitor); return static::SUCCESS; } } ================================================ FILE: packages/dns/src/Commands/ResolveGeoIpCommand.php ================================================ argument('monitorId'); DnsMonitor::query() ->withoutGlobalScopes() ->when($monitorId !== null, fn (Builder $query) => $query->where('id', '=', $monitorId)) ->whereIn('type', Type::geoIpableTypes()) ->lazy() ->each(fn (DnsMonitor $monitor) => ResolveGeoIpJob::dispatch($monitor)); return static::SUCCESS; } } ================================================ FILE: packages/dns/src/Enums/Type.php ================================================ RecordTypes::A, self::AAAA => RecordTypes::AAAA, self::CNAME => RecordTypes::CNAME, self::MX => RecordTypes::MX, self::NS => RecordTypes::NS, self::PTR => RecordTypes::PTR, self::SOA => RecordTypes::SOA, self::SRV => RecordTypes::SRV, self::TXT => RecordTypes::TXT, self::NAPTR => RecordTypes::NAPTR, self::CAA => RecordTypes::CAA, }; } public function hasParser(): bool { return class_exists('\Vigilant\Dns\RecordParsers\\'.$this->name); } public function parser(): RecordParser { $class = '\Vigilant\Dns\RecordParsers\\'.$this->name; throw_if(! class_exists($class), 'No parser for type '.$this->name); /** @var RecordParser $instance */ $instance = app($class); return $instance; } public static function geoIpableTypes(): array { return [ Type::A, Type::AAAA, Type::CNAME, Type::MX, Type::PTR, ]; } } ================================================ FILE: packages/dns/src/Http/Controllers/DnsMonitorController.php ================================================ delete(); $this->alert( __('Deleted'), __('DNS monitor was successfully deleted'), AlertType::Success ); return response()->redirectToRoute('dns.index'); } } ================================================ FILE: packages/dns/src/Jobs/CheckDnsRecordJob.php ================================================ onQueue(config('dns.queue')); } public function handle(CheckDnsRecord $record): void { $record->check($this->monitor); } public function uniqueId(): int { return $this->monitor->id; } } ================================================ FILE: packages/dns/src/Jobs/ResolveGeoIpJob.php ================================================ onQueue(config('dns.queue')); } public function handle(ResolveGeoIp $geoIp): void { $geoIp->resolve($this->monitor); } public function uniqueId(): int { return $this->monitor->id; } } ================================================ FILE: packages/dns/src/Livewire/DnsImport.php ================================================ siteId = $siteId; if ($siteId !== null) { /** @var Site $site */ $site = Site::query()->findOrFail($siteId); $this->records = $site->dnsMonitors->map(function (DnsMonitor $monitor): array { return [ 'monitor_id' => $monitor->id, 'type' => $monitor->type, 'host' => $monitor->record, 'value' => $monitor->value, ]; })->toArray(); $this->domain = Str::of($site->url)->replace(['https://', 'http://'], '')->before('/')->value(); } } public function remove(int $index): void { $this->deleted[] = $index; if (count($this->deleted) === count($this->records)) { $this->records = []; } } #[On('save')] public function save(): void { $this->authorize('create', DnsMonitor::class); foreach ($this->records as $index => $record) { if (in_array($index, $this->deleted)) { if (array_key_exists('monitor_id', $record)) { DnsMonitor::query() ->where('id', '=', $record['monitor_id']) ->delete(); } continue; } DnsMonitor::query()->updateOrCreate([ 'site_id' => $this->siteId, 'type' => $record['type'], 'record' => $record['host'], ], [ 'value' => $record['value'], ]); } if ($this->inline) { return; } $this->alert( __('Saved'), __('Selected records are being monitored'), AlertType::Success ); $this->redirectRoute('dns.index'); } public function lookup(): void { $this->records = []; $this->validate([ 'domain' => ['required', 'max:255', new Fqdn], ]); /** @var DnsClient $client */ $client = app(DnsClient::class); /** @var array $records */ $records = $client->get($this->domain, [ RecordTypes::A, RecordTypes::AAAA, RecordTypes::CNAME, RecordTypes::SOA, RecordTypes::TXT, RecordTypes::MX, RecordTypes::NS, ]); foreach ($records as $record) { $data = $record->toArray(); $type = Type::tryFrom($data['type']); if ($type === null) { continue; } $value = $type->parser()->parse($data); $this->records[] = [ 'type' => $type, 'host' => $data['host'], 'value' => $value, ]; } $this->noRecords = count($records) === 0; $this->deleted = []; } public function render(): View { /** @var view-string $view */ $view = 'dns::livewire.import'; return view($view); } } ================================================ FILE: packages/dns/src/Livewire/DnsMonitorForm.php ================================================ exists) { $this->authorize('update', $monitor); } else { $this->authorize('create', $monitor); } $this->form->fill($monitor->toArray()); $this->dnsMonitor = $monitor; } } public function resolve(): void { $this->validate([ 'form.record' => 'required', 'form.type' => 'required', ]); /** @var ResolveRecord $resolver */ $resolver = app(ResolveRecord::class); $result = $resolver->resolve($this->form->type, $this->form->record); if ($result !== null) { $this->form->value = $result; $this->resolveFailed = false; } else { $this->resolveFailed = true; } } public function save(): void { $this->validate(); if ($this->dnsMonitor->exists) { $this->authorize('update', $this->dnsMonitor); $this->dnsMonitor->update($this->form->all()); } else { $this->authorize('create', $this->dnsMonitor); $exists = DnsMonitor::query() ->where('record', '=', $this->form->record) ->where('type', '=', $this->form->type) ->exists(); if ($exists) { $this->addError('form.record', __('DNS monitor with this record and type already exists')); return; } $this->dnsMonitor = DnsMonitor::query()->create( $this->form->all() ); } $this->alert( __('Saved'), __('DNS monitor was successfully :action', ['action' => $this->dnsMonitor->wasRecentlyCreated ? 'created' : 'saved']), AlertType::Success ); $this->redirectRoute('dns.index'); } public function render(): mixed { /** @var view-string $view */ $view = 'dns::livewire.dns-monitor-form'; return view($view, [ 'updating' => $this->dnsMonitor->exists, ]); } } ================================================ FILE: packages/dns/src/Livewire/DnsMonitorHistory.php ================================================ monitor = $monitor; } public function render(): View { /** @var view-string $view */ $view = 'dns::livewire.monitor-history'; return view($view, [ 'monitor' => $this->monitor, ]); } } ================================================ FILE: packages/dns/src/Livewire/DnsMonitors.php ================================================ exists(); return view($view, [ 'hasMonitors' => $hasMonitors, ]); } } ================================================ FILE: packages/dns/src/Livewire/Forms/DnsMonitorForm.php ================================================ [ 'required', Rule::enum(Type::class), ], 'record' => ['required', 'max:255', new Fqdn], 'value' => ['nullable', 'max:255'], 'enabled' => ['boolean', new CanEnableRule(DnsMonitor::class)], ]; } } ================================================ FILE: packages/dns/src/Livewire/Monitor/Dashboard.php ================================================ siteId = $siteId; } public function render(): mixed { $dnsMonitors = DnsMonitor::query() ->where('site_id', $this->siteId) ->get(); $latestChange = DnsMonitorHistory::query() ->whereIn('dns_monitor_id', $dnsMonitors->pluck('id')) ->orderByDesc('created_at') ->first(); /** @var view-string $view */ $view = 'dns::livewire.monitor.dashboard'; return view($view, [ 'count' => $dnsMonitors->count(), 'lastChange' => $latestChange, ]); } } ================================================ FILE: packages/dns/src/Livewire/Tables/DnsMonitorHistoryTable.php ================================================ monitor = $monitor; } protected function columns(): array { return [ Column::make(__('Type'), 'type') ->searchable() ->sortable(), HoverColumn::make(__('Value'), 'value') ->searchable() ->sortable(), Column::make(__('Modified At'), 'created_at') ->searchable() ->sortable(), ]; } protected function query(): Builder { return parent::query()->where('dns_monitor_id', '=', $this->monitor->id); } } ================================================ FILE: packages/dns/src/Livewire/Tables/DnsMonitorTable.php ================================================ text(function (DnsMonitor $monitor): string { return $monitor->enabled ? __('Enabled') : __('Disabled'); }) ->status(function (DnsMonitor $monitor): Status { return $monitor->enabled ? Status::Success : Status::Danger; }), Column::make(__('Type'), 'type') ->searchable() ->sortable(), Column::make(__('Record'), 'record') ->searchable() ->sortable(), HoverColumn::make(__('Value'), 'value') ->searchable() ->sortable(), Column::make(__('Last modified'), fn (DnsMonitor $monitor): string => $monitor->lastHistory()?->created_at?->toDateString() ?? '-'), GeoIpColumn::make(__('Location'), 'geoip.country_code'), ]; } protected function link(Model $record): string { return route('dns.history', ['monitor' => $record]); } protected function filters(): array { return [ SelectFilter::make(__('Site'), 'site_id') ->options( Site::query() ->orderBy('url') ->pluck('url', 'id') ->toArray() ), ]; } protected function actions(): array { return [ Action::make(__('Check'), function (Enumerable $models): void { $models->each(fn (DnsMonitor $monitor) => CheckDnsRecordJob::dispatch($monitor)); }, 'check'), Action::make(__('Enable'), function (Enumerable $models): void { foreach ($models as $model) { if (! Gate::allows('create', $model)) { break; } $model->update(['enabled' => true]); } }, 'enable'), Action::make(__('Disable'), function (Enumerable $models): void { $models->each(fn (DnsMonitor $monitor) => $monitor->update(['enabled' => false])); }, 'disable'), Action::make(__('Delete'), function (Enumerable $models): void { $models->each(fn (DnsMonitor $monitor) => $monitor->delete()); }, 'delete'), ]; } } ================================================ FILE: packages/dns/src/Models/DnsMonitor.php ================================================ $history */ #[ObservedBy([TeamObserver::class, GeoipObserver::class])] #[ScopedBy(TeamScope::class)] class DnsMonitor extends Model { protected $guarded = []; protected $casts = [ 'enabled' => 'bool', 'type' => Type::class, 'geoip' => 'array', ]; public function site(): BelongsTo { return $this->belongsTo(Site::class); } public function history(): HasMany { return $this->hasMany(DnsMonitorHistory::class); } public function lastHistory(): ?DnsMonitorHistory { /** @var ?DnsMonitorHistory $history */ $history = $this->history()->orderByDesc('id')->first(); return $history; } } ================================================ FILE: packages/dns/src/Models/DnsMonitorHistory.php ================================================ Type::class, 'geoip' => 'array', ]; public function monitor(): BelongsTo { return $this->belongsTo(DnsMonitor::class, 'dns_monitor_id'); } public function prunable(): Builder { return static::withoutGlobalScopes()->where('created_at', '<=', $this->retentionPeriod()); } } ================================================ FILE: packages/dns/src/Notifications/Conditions/RecordTypeCondition.php ================================================ mapWithKeys(fn (Type $type): array => [$type->value => $type->name]) ->toArray(); } public function operators(): array { return [ '=' => 'is', '!=' => 'is not', ]; } public function applies(Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta): bool { /** @var RecordChangedNotification|RecordNotResolvedNotification $notification */ $selectedType = Type::tryFrom($value); if ($selectedType === null) { return false; } $type = $notification->monitor->type; return match ($operator) { '=' => $type == $selectedType, '!=' => $type != $selectedType, default => false, }; } } ================================================ FILE: packages/dns/src/Notifications/RecordChangedNotification.php ================================================ $this->monitor->type->name, 'record' => $this->monitor->record]); } public function description(): string { return __('The :type record for :record has been changed from :old to :new at :changedate', [ 'type' => $this->monitor->type->name, 'record' => $this->monitor->record, 'old' => $this->previous->value ?? '?', 'new' => $this->monitor->value ?? '?', 'changedate' => $this->previous->created_at?->toDateString() ?? '?', ]); } public static function info(): ?string { return __('Triggered when a DNS record value changes.'); } public function level(): Level { $critical = [ Type::A, Type::AAAA, Type::NS, Type::MX, ]; return in_array($this->monitor->type, $critical) ? Level::Critical : Level::Warning; } public function site(): ?Site { return $this->monitor->site; } public function uniqueId(): string|int { return $this->monitor->id; } } ================================================ FILE: packages/dns/src/Notifications/RecordNotResolvedNotification.php ================================================ $this->monitor->record]); } public function description(): string { return __('The DNS record for :record was not resolved. The previous value was :old', [ 'old' => $this->previous->value ?? 'None', 'record' => $this->monitor->record, ]); } public static function info(): ?string { return __('Triggered when a DNS record fails to resolve or becomes unavailable.'); } public function site(): ?Site { return $this->monitor->site; } public function uniqueId(): string|int { return $this->monitor->id; } } ================================================ FILE: packages/dns/src/Observers/GeoipObserver.php ================================================ isDirty('value') && in_array($monitor->type, Type::geoIpableTypes())) { ResolveGeoIpJob::dispatch($monitor)->delay(now()->addSeconds(5)); } } public function created(DnsMonitor $monitor): void { if (in_array($monitor->type, Type::geoIpableTypes())) { ResolveGeoIpJob::dispatch($monitor); } } } ================================================ FILE: packages/dns/src/RecordParsers/A.php ================================================ field, $result)) { return $result[$this->field]; } $values = collect($result)->pluck($this->field); return $values->isEmpty() ? null : $values->implode(','); } } ================================================ FILE: packages/dns/src/RecordParsers/SOA.php ================================================ registerConfig(); } protected function registerConfig(): static { $this->mergeConfigFrom(__DIR__.'/../config/dns.php', 'dns'); return $this; } public function boot(): void { $this ->bootConfig() ->bootMigrations() ->bootCommands() ->bootViews() ->bootLivewire() ->bootRoutes() ->bootNavigation() ->bootNotifications() ->bootGates() ->bootPolicies(); } protected function bootConfig(): static { $this->publishes([ __DIR__.'/../config/dns.php' => config_path('dns.php'), ], 'config'); return $this; } protected function bootMigrations(): static { $this->loadMigrationsFrom(__DIR__.'/../database/migrations'); return $this; } protected function bootCommands(): static { if ($this->app->runningInConsole()) { $this->commands([ CheckDnsRecordCommand::class, CheckAllDnsRecordsCommand::class, ResolveGeoIpCommand::class, ]); } return $this; } protected function bootViews(): static { $this->loadViewsFrom(__DIR__.'/../resources/views', 'dns'); return $this; } protected function bootLivewire(): static { Livewire::component('dns-monitors', DnsMonitors::class); Livewire::component('dns-monitor-form', DnsMonitorForm::class); Livewire::component('dns-monitor-table', DnsMonitorTable::class); Livewire::component('dns-monitor-history-table', DnsMonitorHistoryTable::class); Livewire::component('dns-monitor-import', DnsImport::class); Livewire::component('dns-monitor-dashboard', Dashboard::class); return $this; } protected function bootRoutes(): static { if (! $this->app->routesAreCached()) { Route::middleware(['web', 'auth']) ->group(fn () => $this->loadRoutesFrom(__DIR__.'/../routes/web.php')); } return $this; } protected function bootNavigation(): static { Navigation::path(__DIR__.'/../resources/navigation.php'); return $this; } protected function bootNotifications(): static { NotificationRegistry::registerNotification([ RecordChangedNotification::class, RecordNotResolvedNotification::class, ]); NotificationRegistry::registerCondition(RecordChangedNotification::class, [ SiteCondition::class, RecordTypeCondition::class, ]); NotificationRegistry::registerCondition(RecordNotResolvedNotification::class, [ SiteCondition::class, RecordTypeCondition::class, ]); return $this; } protected function bootGates(): static { Gate::define('use-dns', function (User $user): bool { return ce(); }); return $this; } protected function bootPolicies(): static { if (ce()) { Gate::policy(DnsMonitor::class, AllowAllPolicy::class); } return $this; } } ================================================ FILE: packages/dns/testbench.yaml ================================================ providers: - Vigilant\Dns\ServiceProvider ================================================ FILE: packages/dns/tests/Actions/CheckDnsRecordTest.php ================================================ mock(ResolveRecord::class, function (MockInterface $mock): void { $mock->shouldReceive('resolve')->with(Type::A, 'govigilant.io')->andReturn('127.0.0.1'); }); $monitor = DnsMonitor::query()->create([ 'type' => Type::A, 'record' => 'govigilant.io', 'value' => '127.0.0.1', ]); /** @var CheckDnsRecord $action */ $action = app(CheckDnsRecord::class); $action->check($monitor); $this->assertFalse(RecordChangedNotification::wasDispatched()); } #[Test] public function it_handles_change(): void { RecordChangedNotification::fake(); $this->mock(ResolveRecord::class, function (MockInterface $mock): void { $mock->shouldReceive('resolve')->with(Type::A, 'govigilant.io')->andReturn('127.0.0.2'); }); $monitor = DnsMonitor::query()->create([ 'type' => Type::A, 'record' => 'govigilant.io', 'value' => '127.0.0.1', ]); /** @var CheckDnsRecord $action */ $action = app(CheckDnsRecord::class); $action->check($monitor); $this->assertTrue(RecordChangedNotification::wasDispatched()); $this->assertEquals(1, $monitor->history->count()); $this->assertEquals('127.0.0.1', $monitor->history->first()?->value); } } ================================================ FILE: packages/dns/tests/TestCase.php ================================================ set('database.default', 'testbench'); $app['config']->set('database.connections.testbench', [ 'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '', ]); } } ================================================ FILE: packages/frontend/.gitignore ================================================ vendor composer.lock .phpunit.result.cache ================================================ FILE: packages/frontend/composer.json ================================================ { "name": "vigilant/frontend", "description": "Vigilant Frontend - Collection of frontend components", "type": "package", "license": "AGPL", "authors": [ { "name": "Vincent Boon", "email": "info@vincentbean.com", "role": "Developer" } ], "require": { "php": "^8.3", "laravel/framework": "^12.0", "league/iso3166": "^4.3", "livewire/livewire": "^3.4", "outhebox/blade-flags": "^1.5", "ramonrietdijk/livewire-tables": "^6.0", "vigilant/core": "@dev" }, "require-dev": { "laravel/pint": "^1.6", "larastan/larastan": "^3.0", "orchestra/testbench": "^10.0", "phpstan/phpstan-mockery": "^2.0", "phpunit/phpunit": "^11.0" }, "autoload": { "psr-4": { "Vigilant\\Frontend\\": "src" } }, "autoload-dev": { "psr-4": { "Vigilant\\Frontend\\Tests\\": "tests" } }, "scripts": { "test": "phpunit", "analyse": "phpstan", "style": "pint --test", "quality": [ "@test", "@analyse" ] }, "config": { "sort-packages": true, "allow-plugins": { "php-http/discovery": true } }, "extra": { "laravel": { "providers": [ "Vigilant\\Frontend\\ServiceProvider" ] } }, "minimum-stability": "dev", "prefer-stable": true, "repositories": [ { "type": "path", "url": "../*" } ] } ================================================ FILE: packages/frontend/phpstan.neon ================================================ includes: - ./vendor/larastan/larastan/extension.neon - ./vendor/phpstan/phpstan-mockery/extension.neon parameters: paths: - src - tests level: 8 ignoreErrors: - identifier: missingType.iterableValue - identifier: trait.unused ================================================ FILE: packages/frontend/phpunit.xml ================================================ ./tests/* ./src ================================================ FILE: packages/frontend/resources/views/components/card.blade.php ================================================ @props(['padding' => true])
merge(['class' => 'border border-base-700 shadow-xl rounded-xl overflow-hidden backdrop-blur-sm relative ' . ($padding ? 'px-6 py-8 sm:p-8' : '')]) }}>
{{ $slot }}
================================================ FILE: packages/frontend/resources/views/components/empty-state.blade.php ================================================ @props([ 'title', 'description', 'icon' => 'phosphor-warning-circle', 'iconClass' => 'h-12 w-12 text-base-100', 'iconWrapperClass' => 'rounded-full bg-base-700/50 p-4 mb-6', 'buttonHref' => null, 'buttonText' => null, 'buttonClass' => 'bg-red text-base-50 px-5 py-2.5 rounded-lg transition-all duration-300', 'wrapperClass' => 'mx-auto max-w-3xl text-center py-12', 'cardClass' => 'bg-base-850/50 border-base-700/50', 'contentClass' => 'flex flex-col items-center', 'titleClass' => 'text-2xl font-bold text-base-50 mb-2', 'descriptionClass' => 'text-base text-base-300 mb-8 max-w-md', ])
@if ($icon)
@svg($icon, $iconClass)
@endif

{{ $title }}

@if ($description)

{{ $description }}

@endif @if ($buttonHref && $buttonText) {{ $buttonText }} @endif
================================================ FILE: packages/frontend/resources/views/components/mdash.blade.php ================================================ - ================================================ FILE: packages/frontend/resources/views/components/modal/body.blade.php ================================================
{{ $slot }}
================================================ FILE: packages/frontend/resources/views/components/modal/footer.blade.php ================================================
{{ $slot }}
================================================ FILE: packages/frontend/resources/views/components/modal/header.blade.php ================================================ @props(['icon' => null, 'iconColor' => 'red', 'show' => 'show'])
@if($icon)
@svg($icon, 'w-6 h-6 text-' . $iconColor)
@endif

{{ $slot }}

================================================ FILE: packages/frontend/resources/views/components/modal.blade.php ================================================ @props(['show' => 'show', 'maxWidth' => '2xl']) @php $maxWidth = [ 'sm' => 'sm:max-w-sm', 'md' => 'sm:max-w-md', 'lg' => 'sm:max-w-lg', 'xl' => 'sm:max-w-xl', '2xl' => 'sm:max-w-2xl', ][$maxWidth]; @endphp ================================================ FILE: packages/frontend/resources/views/components/page-header/actions/index.blade.php ================================================ ================================================ FILE: packages/frontend/resources/views/components/page-header/mobile-actions/index.blade.php ================================================
================================================ FILE: packages/frontend/resources/views/components/stats-card.blade.php ================================================ @props(['title', 'icon' => null, 'trend' => null, 'trendUp' => null])
@if($icon)
@svg($icon, 'w-5 h-5 text-blue-light')
@endif
{{ $title }}
@if($trend !== null)
$trendUp, 'bg-red/10 text-red-light border border-red/30' => !$trendUp, ])> @if($trendUp) @else @endif {{ $trend }}%
@endif
{{ $slot }}
================================================ FILE: packages/frontend/resources/views/components/tabs/container.blade.php ================================================ @props([ 'tabs' => [], 'activeTab' => '', ])
{{ $slot }}
================================================ FILE: packages/frontend/resources/views/components/tabs/navigation.blade.php ================================================ @props([ 'tabs' => [], ])
merge(['class' => 'mb-8']) }}>
================================================ FILE: packages/frontend/resources/views/components/tabs/panel.blade.php ================================================ @props([ 'key' => '', 'cloak' => true, ])
merge(['class' => 'space-y-6']) }}> {{ $slot }}
================================================ FILE: packages/frontend/resources/views/components/tabs/panels.blade.php ================================================ @props([ 'tabs' => [], ])
merge(['class' => 'space-y-6']) }}> @foreach($tabs as $index => $tab) @if(!isset($tab['gate']) || auth()->user()->can($tab['gate']))
@if(isset($tab['title']) || isset($tab['description']) || isset($tab['route']))
@if(isset($tab['title']))

@if(isset($tab['icon'])) @svg($tab['icon'], 'size-6 text-' . ($tab['color'] ?? 'red')) @endif {{ $tab['title'] }}

@endif @if(isset($tab['description']))

{{ $tab['description'] }}

@endif
@if(isset($tab['route'])) @lang('View Details') @svg('tni-right-o', 'size-4 group-hover:translate-x-1 transition-transform duration-300') @endif
@endif {{ $slot }}
@endif @endforeach
================================================ FILE: packages/frontend/resources/views/integrations/table/actions-column.blade.php ================================================
@foreach ($actions as $action) @continue(!$action->isVisible($model)) {{ $action->name }} @svg($action->icon, 'h-5 w-5 text-base-200 hover:text-red cursor-pointer') @endforeach
================================================ FILE: packages/frontend/resources/views/integrations/table/chart-column.blade.php ================================================
@if (isset($title)) {!! $title !!} @endif
================================================ FILE: packages/frontend/resources/views/integrations/table/geoip-column.blade.php ================================================ @if(isset($country_code))
{{ collect([$country_name, $region_name, $city, $isp, $org, $as])->whereNotNull()->implode(PHP_EOL) }} {{ $country_name }}
@lang('N/A') @endif ================================================ FILE: packages/frontend/resources/views/integrations/table/hover-column.blade.php ================================================
@if($raw) {!! $value !!} @else {{ $value }} @endif {{ $preview }}
================================================ FILE: packages/frontend/resources/views/integrations/table/link-column.blade.php ================================================ ================================================ FILE: packages/frontend/resources/views/integrations/table/status-column.blade.php ================================================
@if ($status !== null)
@if ($status === \Vigilant\Frontend\Integrations\Table\Enums\Status::Success)
@elseif($status === \Vigilant\Frontend\Integrations\Table\Enums\Status::Warning)
@else
@endif
@endif @if ($text !== null)

{{ $text }}

@else
@endif
================================================ FILE: packages/frontend/resources/views/livewire/charts/base-chart-placeholder.blade.php ================================================
$addStyle, ])>
Loading Chart
================================================ FILE: packages/frontend/resources/views/livewire/charts/base-chart.blade.php ================================================
$addStyle, ])>
================================================ FILE: packages/frontend/src/Concerns/DisplaysAlerts.php ================================================ flash('alert'); session()->flash('alert-title', $title); session()->flash('alert-message', $message); session()->flash('alert-type', $type); } protected function alertBrowser(string $title, string $message = '', AlertType $type = AlertType::Info): void { $this->dispatch('alert', [ 'id' => uniqid(), 'title' => $title, 'message' => $message, 'type' => $type->value, ]); } } ================================================ FILE: packages/frontend/src/Enums/AlertType.php ================================================ value; } } ================================================ FILE: packages/frontend/src/Http/Livewire/BaseChart.php ================================================ defaultOptions(), $this->data()); $this->dispatch($this->getIdentifier().'-update-chart', $data); } public function placeholder(): mixed { /** @var view-string $view */ $view = 'frontend::livewire.charts.base-chart-placeholder'; return view($view, [ 'height' => $this->height, ]); } public function render(): View { /** @var view-string $view */ $view = 'frontend::livewire.charts.base-chart'; return view($view, [ 'identifier' => $this->getIdentifier(), 'height' => $this->height, ]); } public function defaultOptions(): array { return [ 'options' => [ 'maintainAspectRatio' => false, 'responsive' => true, 'plugins' => [ 'legend' => [ 'position' => 'top', 'align' => 'end', 'labels' => [ 'color' => $this->getColor('text-secondary'), 'font' => [ 'size' => 12, ], 'padding' => 12, 'usePointStyle' => true, 'pointStyle' => 'circle', ], ], 'title' => [ 'display' => false, ], 'tooltip' => [ 'position' => 'average', 'mode' => 'index', 'intersect' => false, 'backgroundColor' => $this->getColor('bg-elevated'), 'titleColor' => $this->getColor('text-primary'), 'bodyColor' => $this->getColor('text-secondary'), 'borderColor' => $this->getColor('border'), 'borderWidth' => 1, 'padding' => 12, ], ], 'scales' => [ 'x' => [ 'title' => [ 'color' => $this->getColor('text-muted'), ], 'grid' => [ 'display' => false, ], 'ticks' => [ 'color' => $this->getColor('text-muted'), 'font' => [ 'size' => 11, ], 'maxRotation' => 0, ], ], 'y' => [ 'title' => [ 'color' => $this->getColor('text-muted'), ], 'grid' => [ 'color' => $this->getColor('grid'), 'drawBorder' => false, ], 'ticks' => [ 'color' => $this->getColor('text-muted'), 'font' => [ 'size' => 11, ], ], ], ], 'interaction' => [ 'mode' => 'index', 'intersect' => false, ], ], ]; } protected function dataset(array $dataset): array { return array_merge([ 'pointRadius' => 1, 'pointHoverRadius' => 4, 'borderCapStyle' => 'round', 'borderJoinStyle' => 'round', 'borderWidth' => 2, 'tension' => 0.4, ], $dataset); } /** * Get a color from the design system * * @param string $key Color key * @return string Hex color or rgba string */ protected function getColor(string $key): string { return match ($key) { // Text colors 'text-primary' => '#F4F4FA', // base-100 'text-secondary' => '#D8D8E8', // base-200 'text-muted' => '#A8A8C0', // base-400 // Background colors 'bg-elevated' => '#232333', // base-850 'bg-main' => '#1A1A24', // base-900 // Border colors 'border' => '#444459', // base-700 'grid' => '#2D2D42', // base-800 default => '#F4F4FA', }; } /** * Get chart line colors from the design system * Returns an array of color sets with border and background * * @return array */ protected function getChartColors(): array { return [ ['border' => '#3B82F6', 'bg' => 'rgba(59, 130, 246, 0.1)'], // blue ['border' => '#6366F1', 'bg' => 'rgba(99, 102, 241, 0.1)'], // indigo ['border' => '#10B981', 'bg' => 'rgba(16, 185, 129, 0.1)'], // green ['border' => '#F97316', 'bg' => 'rgba(249, 115, 22, 0.1)'], // orange ['border' => '#8B5CF6', 'bg' => 'rgba(139, 92, 246, 0.1)'], // purple ['border' => '#EC4899', 'bg' => 'rgba(236, 72, 153, 0.1)'], // magenta ['border' => '#06B6D4', 'bg' => 'rgba(6, 182, 212, 0.1)'], // cyan ['border' => '#EF4444', 'bg' => 'rgba(239, 68, 68, 0.1)'], // red ]; } /** * Get a specific chart color by index * * @param int $index Color index (cycles through available colors) * @return array{border: string, bg: string} */ protected function getChartColor(int $index): array { $colors = $this->getChartColors(); return $colors[$index % count($colors)]; } protected function getIdentifier(): string { return Str::slug(get_class($this)); } } ================================================ FILE: packages/frontend/src/Integrations/Table/Actions/InlineAction.php ================================================ visible = $callback; return $this; } public function isVisible(Model $model): bool { if ($this->visible === null) { return true; } return ($this->visible)($model); } } ================================================ FILE: packages/frontend/src/Integrations/Table/ActionsColumn.php ================================================ actions = $actions; return $this; } public function render(Model $model): mixed { return view('frontend::integrations.table.actions-column', [ 'actions' => $this->actions, 'model' => $model, 'column' => $this, ]); } } ================================================ FILE: packages/frontend/src/Integrations/Table/BaseTable.php ================================================ component = $component; return $this; } public function parameters(Closure $parameterCallback): static { $this->parameterCallback = $parameterCallback; return $this; } public function render(Model $model): mixed { return view('frontend::integrations.table.chart-column', [ 'component' => $this->component, 'parameters' => ($this->parameterCallback)($model), ]); } } ================================================ FILE: packages/frontend/src/Integrations/Table/Concerns/HasInlineActions.php ================================================ runAction($code, [$id]); } } ================================================ FILE: packages/frontend/src/Integrations/Table/DateColumn.php ================================================ getValue($model); if ($this->displayUsing !== null) { return call_user_func($this->displayUsing, $value, $model); } if ($value === null) { return null; } /** @var Carbon $date */ $date = teamTimezone(Carbon::parse($value)); return $this->format === null ? $date->toDateTimeString() : $date->format($this->format); } } ================================================ FILE: packages/frontend/src/Integrations/Table/Enums/Status.php ================================================ maxLength = $length; return $this; } public function render(Model $model): mixed { $value = $this->resolveValue($model); return view('frontend::integrations.table.hover-column', [ 'value' => $value, 'preview' => strip_tags(Str::limit($value, $this->maxLength)), 'raw' => $this->raw, ]); } } ================================================ FILE: packages/frontend/src/Integrations/Table/LinkColumn.php ================================================ linkCallback = $linkCallback; return $this; } public function text(Closure $textCallback): static { $this->textCallback = $textCallback; return $this; } public function openInNewTab(bool $newTab = true): static { $this->newTab = $newTab; return $this; } public function render(Model $model): mixed { $url = $this->linkCallback !== null ? ($this->linkCallback)($model) : $this->resolveValue($model); $text = $this->textCallback !== null ? ($this->textCallback)($model) : $url; return view('frontend::integrations.table.link-column', [ 'link' => $url, 'text' => $text, 'newTab' => $this->newTab, ]); } } ================================================ FILE: packages/frontend/src/Integrations/Table/StatusColumn.php ================================================ statusCallback = $statusCallback; return $this; } public function text(Closure $textCallback): static { $this->textCallback = $textCallback; return $this; } public function render(Model $model): mixed { return view('frontend::integrations.table.status-column', [ 'text' => ($this->textCallback)($model), 'status' => ($this->statusCallback)($model), ]); } } ================================================ FILE: packages/frontend/src/ServiceProvider.php ================================================ bootViews() ->bootLivewire(); } protected function bootViews(): static { $this->loadViewsFrom(__DIR__.'/../resources/views', 'frontend'); return $this; } protected function bootLivewire(): static { // Livewire::component('sites', Sites::class); return $this; } } ================================================ FILE: packages/frontend/src/Traits/CanBeInline.php ================================================ containsUrlSpecificCharacters($value)) { $fail(__('Please enter only the domain (e.g., govigilant.io)')); } } private function containsUrlSpecificCharacters(string $value): bool { return strpbrk($value, '/:#?') !== false; } } ================================================ FILE: packages/frontend/src/Validation/CountryCode.php ================================================ iso3166 ??= new ISO3166; try { match ($this->format) { 'alpha3' => $iso3166->alpha3($value), 'numeric' => $iso3166->numeric($value), default => $iso3166->alpha2($value), }; } catch (\Throwable) { $fail(__('The :attribute field must be a valid country code.')); } } } ================================================ FILE: packages/frontend/src/Validation/CronExpression.php ================================================ allowSubdomains) { $pattern = '/^(?:[a-z0-9-]+\.)*[a-z0-9-]+\.[a-z]{2,}$/i'; } else { $pattern = '/^[a-z0-9-]+\.[a-z]{2,}$/i'; } if (! preg_match($pattern, $value)) { $fail(__('Invalid domain name, please enter a domain name + tld. For example: govigilant.io')); } } } ================================================ FILE: packages/frontend/testbench.yaml ================================================ providers: - Vigilant\Frontend\ServiceProvider ================================================ FILE: packages/frontend/tests/TestCase.php ================================================ set('database.default', 'testbench'); $app['config']->set('database.connections.testbench', [ 'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '', ]); } } ================================================ FILE: packages/healthchecks/.gitignore ================================================ vendor composer.lock .phpunit.result.cache ================================================ FILE: packages/healthchecks/composer.json ================================================ { "name": "vigilant/healthchecks", "description": "Vigilant Healthchecks", "type": "package", "license": "AGPL", "authors": [ { "name": "Vincent Boon", "email": "info@vincentbean.com", "role": "Developer" } ], "require": { "php": "^8.3", "guzzlehttp/guzzle": "^7.8", "laravel/framework": "^12.0", "livewire/livewire": "^3.4", "vigilant/core": "@dev", "vigilant/frontend": "@dev", "vigilant/notifications": "@dev", "vigilant/sites": "@dev", "vigilant/users": "@dev" }, "require-dev": { "laravel/pint": "^1.6", "larastan/larastan": "^3.0", "orchestra/testbench": "^10.0", "phpstan/phpstan-mockery": "^2.0", "phpunit/phpunit": "^11.0" }, "autoload": { "psr-4": { "Vigilant\\Healthchecks\\": "src", "Vigilant\\Healthchecks\\Database\\Factories\\": "database/factories", "Vigilant\\Users\\Database\\Factories\\": "../users/database/factories" } }, "autoload-dev": { "psr-4": { "Vigilant\\Healthchecks\\Tests\\": "tests" } }, "scripts": { "test": "phpunit", "analyse": "phpstan", "style": "pint --test", "quality": [ "@test", "@analyse" ] }, "config": { "sort-packages": true, "allow-plugins": { "php-http/discovery": true } }, "extra": { "laravel": { "providers": [ "Vigilant\\Healthchecks\\ServiceProvider" ] } }, "minimum-stability": "dev", "prefer-stable": true, "repositories": [ { "type": "path", "url": "../*" } ] } ================================================ FILE: packages/healthchecks/config/healthchecks.php ================================================ 'healthchecks', 'http_timeout' => env('HEALTHCHECKS_HTTP_TIMEOUT', 10), 'http_max_attempts' => env('HEALTHCHECKS_HTTP_MAX_ATTEMPTS', 2), 'intervals' => [ 60 => 'Every minute', 300 => 'Every 5 minutes', 600 => 'Every 10 minutes', 1800 => 'Every 30 minutes', 3600 => 'Every hour', 21600 => 'Every 6 hours', 43200 => 'Every 12 hours', 86400 => 'Daily', ], ]; ================================================ FILE: packages/healthchecks/database/migrations/2025_11_06_200000_create_healthchecks_table.php ================================================ id(); $table->foreignIdFor(Site::class)->nullable()->constrained()->onDelete('cascade'); $table->foreignIdFor(Team::class)->constrained()->onDelete('cascade'); $table->boolean('enabled')->default(true); $table->string('domain'); $table->string('type'); $table->string('endpoint')->nullable(); $table->string('token'); $table->dateTime('next_check_at')->nullable(); $table->dateTime('last_check_at')->nullable(); $table->integer('interval'); $table->string('status')->nullable(); $table->timestamps(); }); } public function down(): void { Schema::dropIfExists('healthchecks'); } }; ================================================ FILE: packages/healthchecks/database/migrations/2025_11_06_201000_create_healthcheck_results_table.php ================================================ id(); $table->foreignIdFor(Healthcheck::class)->constrained()->onDelete('cascade'); $table->integer('run_id')->nullable(); $table->string('key'); $table->string('status'); $table->string('message')->nullable(); $table->json('data')->nullable(); $table->timestamps(); }); } public function down(): void { Schema::dropIfExists('healthcheck_results'); } }; ================================================ FILE: packages/healthchecks/database/migrations/2025_11_06_202000_create_healthcheck_metrics_table.php ================================================ id(); $table->foreignIdFor(Healthcheck::class)->constrained()->onDelete('cascade'); $table->integer('run_id')->nullable(); $table->string('key'); $table->decimal('value'); $table->string('unit')->nullable(); $table->timestamps(); }); } public function down(): void { Schema::dropIfExists('healthcheck_metrics'); } }; ================================================ FILE: packages/healthchecks/database/migrations/2025_11_23_150400_update_healthcheck_results_columns.php ================================================ dropColumn('run_id'); $table->timestamp('last_checked_at')->nullable()->after('data'); $table->timestamp('last_unhealthy_at')->nullable()->after('last_checked_at'); $table->unique(['healthcheck_id', 'key'], 'unique_healthcheck_result'); }); } public function down(): void { Schema::table('healthcheck_results', function (Blueprint $table): void { $table->dropUnique('unique_healthcheck_result'); $table->dropColumn('last_unhealthy_at'); $table->dropColumn('last_checked_at'); $table->integer('run_id')->nullable()->after('healthcheck_id'); }); } }; ================================================ FILE: packages/healthchecks/phpstan.neon ================================================ includes: - ./vendor/larastan/larastan/extension.neon - ./vendor/phpstan/phpstan-mockery/extension.neon parameters: paths: - src - tests level: 8 ignoreErrors: - identifier: missingType.iterableValue - identifier: missingType.generics ================================================ FILE: packages/healthchecks/phpunit.xml ================================================ ./tests/* ./src ================================================ FILE: packages/healthchecks/resources/navigation.php ================================================ icon('phosphor-heartbeat') ->parent('health') ->gate('use-healthchecks') ->routeIs('healthchecks*') ->sort(2); ================================================ FILE: packages/healthchecks/resources/views/components/empty-states/healthchecks.blade.php ================================================ ================================================ FILE: packages/healthchecks/resources/views/healthcheck/view.blade.php ================================================ @if ($healthcheck->type !== \Vigilant\Healthchecks\Enums\Type::Endpoint) @lang('Setup') @endif @lang('Edit') @lang('Delete') @if ($healthcheck->type !== \Vigilant\Healthchecks\Enums\Type::Endpoint) @lang('Setup') @endif @lang('Edit') @lang('Delete')
{{ $healthcheck->domain }} {{ $healthcheck->last_check_at ? $healthcheck->last_check_at->diffForHumans() : __('Never') }} @if ($healthcheck->status === \Vigilant\Healthchecks\Enums\Status::Healthy) {{ __('Healthy') }} @elseif($healthcheck->status === \Vigilant\Healthchecks\Enums\Status::Warning) {{ __('Warning') }} @elseif($healthcheck->status === \Vigilant\Healthchecks\Enums\Status::Unhealthy) {{ __('Unhealthy') }} @else {{ __('Unknown') }} @endif {{ $healthcheck->interval }}s

{{ __('Metrics') }}

{{ __('Results') }}

@lang('Delete Healthcheck')

@lang('Are you sure you want to delete this healthcheck?')

@svg('phosphor-warning-circle', 'w-5 h-5 text-orange mt-0.5')

{{ $healthcheck->domain }}

@lang('This action cannot be undone. All healthcheck history and results for this monitor will be permanently deleted.')

@lang('Cancel')
@csrf @method('DELETE') @lang('Delete Healthcheck')
================================================ FILE: packages/healthchecks/resources/views/livewire/charts/metric-chart.blade.php ================================================
@if (count($availableKeys))
@foreach ($availableKeys as $key) @endforeach
@else

{{ __('No metrics available') }}

@endif
================================================ FILE: packages/healthchecks/resources/views/livewire/healthcheck-dashboard.blade.php ================================================
{{ $healthcheck->domain }} {{ $healthcheck->last_check_at ? $healthcheck->last_check_at->diffForHumans() : __('Never') }} @if($healthcheck->status === \Vigilant\Healthchecks\Enums\Status::Healthy) {{ __('Healthy') }} @elseif($healthcheck->status === \Vigilant\Healthchecks\Enums\Status::Warning) {{ __('Warning') }} @elseif($healthcheck->status === \Vigilant\Healthchecks\Enums\Status::Unhealthy) {{ __('Unhealthy') }} @else {{ __('Unknown') }} @endif {{ $healthcheck->interval }}s

{{ __('Metrics') }}

{{ __('Recent Results') }}

================================================ FILE: packages/healthchecks/resources/views/livewire/healthcheck-form.blade.php ================================================ @props(['updating' => false, 'inline' => false])
@if (!$inline) @endif
@if (!$inline) @endif @foreach (config('healthchecks.intervals') as $interval => $label) @endforeach
endpoint() . "'" : "''" }}, @endforeach }, get hasMore() { return this.totalPlatforms > 12; } }" x-init="$watch('selectedType', value => { if (platformEndpoints[value] !== undefined) { $wire.set('form.endpoint', platformEndpoints[value]); } })">

@lang('Select your platform, if you have not installed the Vigilant healthcheck module then select "Endpoint".')

@foreach (\Vigilant\Healthchecks\Enums\Type::cases() as $type) @endforeach

@lang('Override the default endpoint path for this platform')

@if (!$inline)
@endif
================================================ FILE: packages/healthchecks/resources/views/livewire/healthcheck-setup.blade.php ================================================
@if ($isNew)

{{ __('Healthcheck Created Successfully!') }}

{{ __('Your healthcheck has been created. Follow the instructions below to integrate it with your platform.') }}

@endif

{{ __('Integration Instructions') }}

@includeIf('healthchecks::platforms.' . $healthcheck->type->value, ['healthcheck' => $healthcheck])
================================================ FILE: packages/healthchecks/resources/views/livewire/healthcheck-token-editor.blade.php ================================================
@if ($healthcheck->type->generatesOwnToken())

{{ __('Enter the token generated by :platform and save it here to authenticate healthchecks.', ['platform' => $healthcheck->type->label()]) }}

@else

{{ __('This token is generated by Vigilant. Copy it into your platform configuration to enable healthchecks.') }}

@endif
================================================ FILE: packages/healthchecks/resources/views/livewire/healthchecks.blade.php ================================================
@lang('Add Healthcheck') @lang('Add Healthcheck') @if ($hasHealthchecks) @else @endif
================================================ FILE: packages/healthchecks/resources/views/platforms/drupal.blade.php ================================================
{{ __('Setup your Drupal healthcheck') }}
  1. {{ __('Install the Drupal healthcheck module') }}
  2. {{ __('In your Drupal site go to Configuration > Vigilant Healthchecks') }}
  3. {{ __('Paste the token above in your Drupal site') }}
================================================ FILE: packages/healthchecks/resources/views/platforms/endpoint.blade.php ================================================
{{ __('Setup Steps') }}
  1. {{ __('Copy the token above') }}
  2. {{ __('Add this token to your platform\'s configuration') }}
  3. {{ __('Ensure your endpoint :endpoint returns an HTTP 200 status', ['endpoint' => $healthcheck->endpoint]) }}
  4. {{ __('The healthcheck will run automatically at the configured interval') }}
{{ __('Endpoint Details') }}
{{ __('Domain:') }} {{ $healthcheck->domain }}
{{ __('Endpoint:') }} {{ $healthcheck->endpoint }}
{{ __('Check Interval:') }} {{ __('Every :interval minutes', ['interval' => $healthcheck->interval]) }}
================================================ FILE: packages/healthchecks/resources/views/platforms/joomla.blade.php ================================================
{{ __('Setup your Joomla healthcheck') }}
  1. {{ __('Install the Joomla healthcheck module') }}
  2. {{ __('In your administrator go to System > Plugins > Vigilant Healthchecks') }}
  3. {{ __('Paste the token above in your Joomla site') }}
================================================ FILE: packages/healthchecks/resources/views/platforms/laravel.blade.php ================================================
{{ __('Laravel Setup Steps') }}
  1. {{ __('Install the Laravel healthcheck package') }}
  2. {{ __('Configure the token in your environment file') }}
================================================ FILE: packages/healthchecks/resources/views/platforms/magento.blade.php ================================================
{{ __('Setup your Magento 2 healthcheck') }}
  1. {{ __('Install the Magento 2 healthcheck module') }}
  2. {{ __('In your Magento 2 backend, go to System > Integrations') }}
  3. {{ __('Create an integration with permissions for the "Health Endpoint"') }}
  4. {{ __('Activate the integration and paste the access token here') }}
================================================ FILE: packages/healthchecks/resources/views/platforms/statamic.blade.php ================================================
{{ __('Statamic Setup Steps') }}
  1. {{ __('Install the Statamic healthcheck package') }}
  2. {{ __('Configure the token in your environment file') }}
================================================ FILE: packages/healthchecks/resources/views/platforms/wordpress.blade.php ================================================
{{ __('Setup your WordPress healthcheck') }}
  1. {{ __('Install the WordPress healthcheck module') }}
  2. {{ __('In your wp-admin go to Settings > Vigilant Healthchecks') }}
  3. {{ __('Paste the token above in your WordPress site') }}
================================================ FILE: packages/healthchecks/routes/api.php ================================================ middleware('can:use-healthchecks') ->group(function (): void { Route::get('/', Healthchecks::class)->name('healthchecks.index'); Route::get('/create', HealthcheckForm::class)->name('healthchecks.create'); Route::get('/{healthcheck}', [HealthcheckController::class, 'index'])->name('healthchecks.view'); Route::get('/{healthcheck}/setup', HealthcheckSetup::class)->name('healthchecks.setup'); Route::delete('/{healthcheck}', [HealthcheckController::class, 'delete'])->name('healthchecks.delete')->can('delete,healthcheck'); Route::get('/{healthcheck}/edit', HealthcheckForm::class)->name('healthchecks.edit'); }); ================================================ FILE: packages/healthchecks/src/Actions/AggregateMetrics.php ================================================ latestAggregatableHourStart(); if ($latestAggregatableHour === null) { return; } $hourBuckets = $this->hourBuckets($latestAggregatableHour); if ($hourBuckets->isEmpty()) { return; } foreach ($hourBuckets as $hourStart) { $this->aggregateHour($hourStart); } } protected function hourBuckets(Carbon $latestAggregatableHour): Collection { $hours = collect(); $upperBound = $latestAggregatableHour->copy()->addHour(); Metric::query() ->select('id', 'created_at') ->whereNotNull('created_at') ->where('created_at', '<', $upperBound) ->orderBy('id') ->chunkById(1000, function ($metrics) use (&$hours): void { foreach ($metrics as $metric) { $createdAt = $metric->created_at; if ($createdAt === null) { continue; } $hourStart = $createdAt->copy()->startOfHour(); $hours->put((int) $hourStart->timestamp, $hourStart); } }); return $hours ->sortKeys() ->values(); } protected function aggregateHour(Carbon $hourStart): void { $hourEnd = $hourStart->copy()->addHour(); $metrics = Metric::query() ->whereNotNull('created_at') ->where('created_at', '>=', $hourStart) ->where('created_at', '<', $hourEnd) ->orderBy('healthcheck_id') ->orderBy('key') ->orderBy('unit') ->orderBy('created_at') ->orderBy('id') ->get(); if ($metrics->isEmpty()) { return; } $metrics ->groupBy(function (Metric $metric): string { $unit = $metric->unit ?? '__null__'; return implode('|', [ $metric->healthcheck_id, $metric->key, $unit, ]); }) ->each(function (Collection $group): void { $this->aggregateGroup($group); }); } protected function aggregateGroup(Collection $metrics): void { if ($metrics->count() <= 1) { return; } $sorted = $metrics->sortBy(function (Metric $metric): string { $timestamp = $metric->created_at?->format('YmdHisu') ?? '000000000000000000'; return $timestamp.'|'.$metric->id; })->values(); $average = $sorted->avg(fn (Metric $metric): float => (float) $metric->value); if ($average === null) { return; } /** @var Metric $first */ $first = $sorted->shift(); $idsToDelete = $sorted->pluck('id')->filter()->all(); DB::transaction(function () use ($first, $average, $idsToDelete): void { $first->forceFill([ 'value' => round($average, 2), ])->save(); if ($idsToDelete !== []) { Metric::query() ->whereIn('id', $idsToDelete) ->delete(); } }); } protected function latestAggregatableHourStart(): ?Carbon { $now = Carbon::now(); $start = $now->copy()->subHours(2)->startOfHour(); if ($start->greaterThanOrEqualTo($now)) { return null; } return $start; } } ================================================ FILE: packages/healthchecks/src/Actions/CheckHealth.php ================================================ type->checker(); $runId = $checker->check($healthcheck); } catch (Exception $e) { logger()->error('Healthcheck failed for Healthcheck ID '.$healthcheck->id.': '.$e->getMessage()); if (app()->isLocal()) { throw $e; } $healthcheck->update([ 'status' => Status::Unhealthy, ]); } $healthcheck->update([ 'next_check_at' => now()->addSeconds($healthcheck->interval), 'last_check_at' => now(), ]); if ($runId !== null) { CheckResultJob::dispatch($healthcheck, $runId); } } } ================================================ FILE: packages/healthchecks/src/Actions/CheckMetric.php ================================================ $metrics */ $metrics = $healthcheck->metrics() ->where('run_id', '=', $runId) ->get(); if ($metrics->isEmpty()) { return; } foreach ($metrics as $metric) { MetricNotification::notify($metric); } $this->checkIncreasingMetrics($healthcheck, $metrics); $this->checkDiskUsage($healthcheck, $metrics); } protected function checkIncreasingMetrics(Healthcheck $healthcheck, Collection $metrics): void { $metricsByKey = $metrics->groupBy('key'); foreach ($metricsByKey as $key => $keyMetrics) { $currentMetric = $keyMetrics->first(); $increaseData = $this->calculateMetricIncrease($healthcheck, $key, $currentMetric); if ($increaseData !== null) { if (isset($increaseData['detection_type']) && $increaseData['detection_type'] === 'sudden_spike') { MetricSpikeNotification::notify($currentMetric, $increaseData); } else { MetricIncreasingNotification::notify($currentMetric, $increaseData); } } } } public function calculateMetricIncrease(Healthcheck $healthcheck, string $key, Metric $currentMetric): ?array { /** @var Collection $historicalMetrics */ $historicalMetrics = $healthcheck->metrics() ->where('key', '=', $key) ->where('created_at', '<=', $currentMetric->created_at) ->orderBy('created_at', 'desc') ->limit(60) ->get(); if ($historicalMetrics->count() < 2 || $currentMetric->created_at === null) { return null; } $currentValue = $currentMetric->value; // Spike detection $recentMetrics = $historicalMetrics->take(5); if ($recentMetrics->count() >= 3) { $spikeResult = $this->detectSpike($recentMetrics, $currentValue, $currentMetric); if ($spikeResult !== null) { return $spikeResult; } } $intervalResults = []; $intervals = MetricIncreaseTimeframeCondition::INTERVALS; foreach ($intervals as $index => $interval) { $minBound = $interval; $maxBound = $intervals[$index + 1] ?? null; $baselineMetric = $this->findBaselineMetricForRange( $historicalMetrics, $currentMetric, $minBound, $maxBound ); if ($baselineMetric === null) { continue; } $oldValue = $baselineMetric->value; if ($oldValue == 0) { continue; } $percentIncrease = (($currentValue - $oldValue) / $oldValue) * 100; if ($percentIncrease <= 0) { continue; } $intervalResults[] = [ 'key' => $key, 'old_value' => $oldValue, 'new_value' => $currentValue, 'unit' => $currentMetric->unit, 'percent_increase' => $percentIncrease, 'timeframe_minutes' => $interval, 'sample_size' => $historicalMetrics->count(), 'detection_type' => 'long_term_trend', ]; } if ($intervalResults === []) { return null; } return $intervalResults; } protected function findBaselineMetricForRange( Collection $historicalMetrics, Metric $currentMetric, int $minBoundary, ?int $maxBoundary ): ?Metric { if ($currentMetric->created_at === null) { return null; } return $historicalMetrics->first(function (Metric $metric) use ($currentMetric, $minBoundary, $maxBoundary) { if ($metric->is($currentMetric) || $metric->created_at === null) { return false; } $difference = $currentMetric->created_at->diffInMinutes($metric->created_at, true); if ($difference < $minBoundary) { return false; } if ($maxBoundary !== null && $difference >= $maxBoundary) { return false; } return true; }); } public function detectSpike(Collection $recentMetrics, float $currentValue, Metric $currentMetric): ?array { /** @var Metric $recentOldest */ $recentOldest = $recentMetrics->last(); $recentOldestValue = $recentOldest->value; if ($recentOldestValue == 0) { return null; } $percentIncrease = (($currentValue - $recentOldestValue) / $recentOldestValue) * 100; // Spike threshold: 50% increase if ($percentIncrease < 50) { return null; } $timeframeMinutes = $currentMetric->created_at?->diffInMinutes($recentOldest->created_at, true) ?? 0; return [ 'key' => $currentMetric->key, 'old_value' => $recentOldestValue, 'new_value' => $currentValue, 'unit' => $currentMetric->unit, 'percent_increase' => $percentIncrease, 'timeframe_minutes' => $timeframeMinutes, 'sample_size' => $recentMetrics->count(), 'detection_type' => 'sudden_spike', ]; } protected function checkDiskUsage(Healthcheck $healthcheck, Collection $metrics): void { /** @var ?Metric $diskMetric */ $diskMetric = $metrics->firstWhere('key', 'disk_usage'); if (! $diskMetric || $diskMetric->unit !== '%') { return; } /** @var Collection $historicalMetrics */ $historicalMetrics = $healthcheck->metrics() ->where('key', 'disk_usage') ->where('created_at', '<=', $diskMetric->created_at) ->orderBy('created_at', 'desc') ->limit(60) ->get(); $currentUsage = $diskMetric->value; /** @var ?Metric $oldestMetric */ $oldestMetric = $historicalMetrics->last(); if ($oldestMetric === null) { return; } $oldestUsage = $oldestMetric->value; $timeframeHours = $oldestMetric->created_at?->diffInHours($diskMetric->created_at, true) ?? 0; if ($timeframeHours == 0) { return; } $velocity = ($currentUsage - $oldestUsage) / $timeframeHours; if ($velocity <= 0) { return; } $remainingSpace = 100 - $currentUsage; $hoursUntilFull = $remainingSpace / $velocity; if ($hoursUntilFull < 0) { return; } $estimatedFullAt = now()->addHours($hoursUntilFull); DiskUsageNotification::notify( $healthcheck, $currentUsage, $velocity, $hoursUntilFull, $estimatedFullAt ); } } ================================================ FILE: packages/healthchecks/src/Actions/CheckResult.php ================================================ $results */ $results = $healthcheck->results()->get(); $overallStatus = Status::Healthy; $unhealthy = false; $hasWarning = false; foreach ($results as $result) { if ($result->status === Status::Unhealthy) { $unhealthy = true; break; } if ($result->status === Status::Warning) { $hasWarning = true; } } if ($unhealthy) { $overallStatus = Status::Unhealthy; } elseif ($hasWarning) { $overallStatus = Status::Warning; } if ($unhealthy || $hasWarning) { HealthCheckFailedNotification::notify($healthcheck, $runId); } $healthcheck->update(['status' => $overallStatus]); CheckMetricJob::dispatch($healthcheck, $runId); } } ================================================ FILE: packages/healthchecks/src/Checks/Checker.php ================================================ metrics()->where('run_id', '=', $candidate)->exists(); if (! $exists) { return $candidate; } } throw new RuntimeException('Could not generate unique run ID'); } protected function persistResult(Healthcheck $healthcheck, string $key, Status $status, ?string $message = null, ?array $data = null): void { $attributes = [ 'status' => $status, 'message' => $message, 'data' => $data, 'last_checked_at' => now(), ]; if ($status === Status::Unhealthy) { $attributes['last_unhealthy_at'] = now(); } $healthcheck->results()->updateOrCreate( ['key' => $key], $attributes ); } /** * @param Closure(PendingRequest): Response $callback * * @throws ConnectionException */ protected function performHttpCall(Healthcheck $healthcheck, Closure $callback): Response { $maxAttempts = max((int) config('healthchecks.http_max_attempts', 2), 1); for ($attempt = 1; $attempt <= $maxAttempts; $attempt++) { try { $request = Http::baseUrl($healthcheck->domain); return $callback($request); } catch (ConnectionException $e) { if ($attempt === $maxAttempts) { throw $e; } sleep(1); } } throw new RuntimeException('Unable to perform HTTP call.'); } } ================================================ FILE: packages/healthchecks/src/Checks/Endpoint.php ================================================ endpoint === null, InvalidArgumentException::class, 'Healthcheck endpoint is not defined'); $timeout = config('healthchecks.http_timeout', 10); $runId = $this->generateRunId($healthcheck); try { $response = $this->performHttpCall( $healthcheck, function (PendingRequest $request) use ($timeout, $healthcheck): Response { return $request ->timeout($timeout) ->get($healthcheck->endpoint); } ); $healthy = $response->ok(); $status = $healthy ? Status::Healthy : Status::Unhealthy; $message = $healthy ? __('Endpoint is reachable') : __('Endpoint returned status code :code', ['code' => $response->status()]); $this->persistResult($healthcheck, 'endpoint_check', $status, $message); } catch (ConnectionException $e) { $this->persistResult( $healthcheck, 'connection', Status::Unhealthy, 'Failed to connect to endpoint', [ 'error' => $e->getMessage(), ] ); } return $runId; } } ================================================ FILE: packages/healthchecks/src/Checks/Module.php ================================================ generateRunId($healthcheck); $endpoint = blank($healthcheck->endpoint) ? $healthcheck->type->endpoint() : $healthcheck->endpoint; throw_if($endpoint === null, 'Endpoint is required'); try { $response = $this->performHttpCall( $healthcheck, function (PendingRequest $request) use ($healthcheck, $endpoint): Response { return $request ->withToken($healthcheck->token) ->post($endpoint); } ); } catch (ConnectionException) { $this->persistResult($healthcheck, 'connection', Status::Unhealthy, 'Could not connect'); return $runId; } if ($response->failed()) { $this->persistResult($healthcheck, 'connection', Status::Unhealthy, 'Failed to check health, status: '.$response->status()); return $runId; } $this->persistResult($healthcheck, 'connection', Status::Healthy); $checks = $response->json($healthcheck->type->checksResponseKey(), []); $metrics = $response->json($healthcheck->type->metricsResponseKey(), []); foreach ($checks as $check) { $validator = Validator::make($check, [ 'type' => ['required', 'string'], 'key' => ['nullable', 'string'], 'status' => ['required', 'string', 'in:healthy,unhealthy,failed'], 'message' => ['nullable', 'string'], ]); if ($validator->fails()) { continue; } $status = Status::from($check['status']); $key = $check['type']; if (! blank($check['key'] ?? null)) { $key .= '_'.$check['key']; } $this->persistResult($healthcheck, str($key)->limit(255)->toString(), $status, $check['message'] ?? null); } foreach ($metrics as $metric) { $validator = Validator::make($metric, [ 'type' => ['required', 'string'], 'value' => ['required', 'numeric'], 'unit' => ['required', 'string'], ]); if ($validator->fails()) { continue; } $healthcheck->metrics()->create([ 'run_id' => $runId, 'key' => $metric['type'], 'value' => $metric['value'], 'unit' => $metric['unit'], ]); } return $runId; } } ================================================ FILE: packages/healthchecks/src/Commands/AggregateMetricsCommand.php ================================================ argument('healthcheckId'); /** @var Healthcheck $healthcheck */ $healthcheck = Healthcheck::query()->withoutGlobalScopes()->findOrFail($healthcheckId); CheckHealthcheckJob::dispatch($healthcheck); return static::SUCCESS; } } ================================================ FILE: packages/healthchecks/src/Commands/ScheduleHealthchecksCommand.php ================================================ withoutGlobalScopes() ->where('enabled', '=', true) ->where(function (Builder $builder): void { $builder->where('next_check_at', '<=', now()) ->orWhereNull('next_check_at'); }) ->get() ->each(function (Healthcheck $healthcheck): void { CheckHealthcheckJob::dispatch($healthcheck); }); return static::SUCCESS; } } ================================================ FILE: packages/healthchecks/src/Enums/Status.php ================================================ ucfirst($this->value), }; } public function icon(): string { return match ($this) { self::Endpoint => 'phosphor-heartbeat', self::Laravel => 'si-laravel', self::Statamic => 'si-statamic', self::Magento => 'bxl-magento', self::Wordpress => 'si-wordpress', self::Joomla => 'si-joomla', self::Drupal => 'si-drupal', }; } public function endpoint(): ?string { return match ($this) { self::Endpoint => null, self::Magento => 'rest/V1/vigilant/health', self::Wordpress => 'wp-json/vigilant/v1/health', self::Joomla => 'index.php?option=io_govigilant&task=health.check', self::Drupal => 'vigilant/health', default => 'api/vigilant/health' }; } public function checker(): Checker { $class = match ($this) { self::Endpoint => Endpoint::class, default => Module::class, }; return app($class); } public function generatesOwnToken(): bool { return match ($this) { self::Magento => true, default => false, }; } public function checksResponseKey(): string { return match ($this) { self::Magento => '0', default => 'checks', }; } public function metricsResponseKey(): string { return match ($this) { self::Magento => '1', default => 'metrics', }; } } ================================================ FILE: packages/healthchecks/src/Http/Controllers/HealthcheckController.php ================================================ $healthcheck, ]); } public function delete(Healthcheck $healthcheck): mixed { $healthcheck->delete(); $this->alert( __('Deleted'), __('Healthcheck was successfully deleted'), AlertType::Success ); return response()->redirectToRoute('healthchecks.index'); } } ================================================ FILE: packages/healthchecks/src/Http/Livewire/Charts/MetricChart.php ================================================ 'required', ])->validate(); $this->healthcheckId = $data['healthcheckId']; $this->availableKeys = $this->getAvailableKeys()->toArray(); if (! empty($this->availableKeys)) { $this->selectedKey = $this->availableKeys[0]; } } public function setMetricKey(string $key): void { $this->selectedKey = $key; $this->loadChart(); } public function setDateRange(string $range): void { $this->dateRange = $range; $this->loadChart(); } protected function getDateRangeStart(): Carbon { return match ($this->dateRange) { 'hour' => now()->subHour(), 'day' => now()->subDay(), 'week' => now()->subWeek(), 'month' => now()->subMonth(), '3months' => now()->subMonths(3), '6months' => now()->subMonths(6), default => now()->subWeek(), }; } protected function getDateRangeOptions(): array { return [ 'hour' => 'Hour', 'day' => 'Day', 'week' => 'Week', 'month' => 'Month', '3months' => '3 Months', '6months' => '6 Months', ]; } protected function getAvailableKeys(): Collection { return Metric::query() ->where('healthcheck_id', '=', $this->healthcheckId) ->whereNotNull('key') ->where('key', '!=', '') ->selectRaw('`key`, COUNT(*) as count') ->groupBy('key') ->orderByDesc('count') ->get() ->pluck('key'); } protected function points(): Collection { if (empty($this->selectedKey)) { return collect(); } return Metric::query() ->where('healthcheck_id', '=', $this->healthcheckId) ->where('key', '=', $this->selectedKey) ->where('created_at', '>=', $this->getDateRangeStart()) ->orderBy('created_at', 'asc') ->get(); } public function data(): array { $points = $this->points(); if ($points->isEmpty()) { return [ 'type' => 'line', 'data' => [ 'labels' => [], 'datasets' => [], ], ]; } $labels = $points->pluck('created_at'); $data = $points->pluck('value'); $unit = $points->first()->unit ?? ''; $dateFormat = match ($this->dateRange) { 'hour' => 'H:i', 'day' => 'd/m H:i', 'week' => 'd/m H:i', 'month' => 'd/m', '3months' => 'd/m', '6months' => 'd/m', default => 'd/m H:i', }; $color = $this->getChartColor(0); return [ 'type' => 'line', 'data' => [ 'labels' => $labels->map(fn (Carbon $carbon): string => teamTimezone($carbon)->format($dateFormat))->toArray(), 'datasets' => [ [ 'label' => $this->selectedKey, 'data' => $data->toArray(), 'pointRadius' => 1, 'pointHoverRadius' => 4, 'borderWidth' => 2, 'borderColor' => $color['border'], 'backgroundColor' => $color['bg'], 'fill' => true, 'tension' => 0.4, 'unit' => $unit, ], ], ], 'options' => [ 'plugins' => [ 'legend' => [ 'display' => true, ], 'tooltip' => [ 'enabled' => true, ], ], 'scales' => [ 'y' => [ 'display' => true, 'beginAtZero' => true, ], 'x' => [ 'display' => true, ], ], ], ]; } protected function getIdentifier(): string { return Str::slug(get_class($this)).$this->healthcheckId; } public function render(): View { /** @var view-string $view */ $view = 'healthchecks::livewire.charts.metric-chart'; return view($view, [ 'identifier' => $this->getIdentifier(), 'height' => $this->height, 'availableKeys' => $this->getAvailableKeys(), 'dateRangeOptions' => $this->getDateRangeOptions(), ]); } } ================================================ FILE: packages/healthchecks/src/Jobs/AggregateMetricsJob.php ================================================ onQueue(config()->string('healthchecks.queue')); } public function handle(AggregateMetrics $aggregateMetrics): void { $aggregateMetrics->handle(); } public function uniqueId(): string { return 'aggregate-metrics'; } } ================================================ FILE: packages/healthchecks/src/Jobs/CheckHealthcheckJob.php ================================================ onQueue(config()->string('healthchecks.queue')); } public function handle(CheckHealth $checkHealth, TeamService $teamService): void { $teamService->setTeamById($this->healthcheck->team_id); $checkHealth->check($this->healthcheck); } public function uniqueId(): int { return $this->healthcheck->id; } } ================================================ FILE: packages/healthchecks/src/Jobs/CheckMetricJob.php ================================================ onQueue(config()->string('healthchecks.queue')); } public function handle(CheckMetric $checkMetric, TeamService $teamService): void { $teamService->setTeamById($this->healthcheck->team_id); $checkMetric->check($this->healthcheck, $this->runId); } public function uniqueId(): string { return 'metric-'.$this->healthcheck->id.'-'.$this->runId; } } ================================================ FILE: packages/healthchecks/src/Jobs/CheckResultJob.php ================================================ onQueue(config()->string('healthchecks.queue')); } public function handle(CheckResult $result, TeamService $teamService): void { $teamService->setTeamById($this->healthcheck->team_id); $result->check($this->healthcheck, $this->runId); } public function uniqueId(): string { return $this->healthcheck->id.'-'.$this->runId; } } ================================================ FILE: packages/healthchecks/src/Livewire/Forms/HealthcheckForm.php ================================================ ['required', 'string', 'max:255', 'url'], 'type' => ['required', Rule::enum(Type::class)], 'endpoint' => ['nullable', 'string', 'max:255', 'required_if:type,endpoint'], 'interval' => ['required', 'integer', 'in:'.implode(',', array_keys(config('healthchecks.intervals')))], 'enabled' => ['boolean', new CanEnableRule(Healthcheck::class)], ]; } public function cleanDomain(): void { if (empty($this->domain)) { return; } $parsed = parse_url($this->domain); if ($parsed === false) { return; } $scheme = $parsed['scheme'] ?? 'https'; $host = $parsed['host'] ?? $this->domain; $port = isset($parsed['port']) ? ":{$parsed['port']}" : ''; $this->domain = "{$scheme}://{$host}{$port}"; } public function normalizeEndpoint(): void { if ($this->type !== Type::Endpoint && blank($this->endpoint)) { $this->endpoint = null; } } } ================================================ FILE: packages/healthchecks/src/Livewire/HealthcheckDashboard.php ================================================ healthcheckId = $healthcheckId; } public function render(): View { $healthcheck = Healthcheck::query()->findOrFail($this->healthcheckId); /** @var view-string $view */ $view = 'healthchecks::livewire.healthcheck-dashboard'; return view($view, [ 'healthcheck' => $healthcheck, ]); } } ================================================ FILE: packages/healthchecks/src/Livewire/HealthcheckForm.php ================================================ inline = $inline; if ($healthcheck !== null) { $this->form->fill($healthcheck->except('type')); $this->healthcheck = $healthcheck; if ($healthcheck->exists) { $this->authorize('update', $healthcheck); $this->form->type = $healthcheck->type; } else { $this->authorize('create', $healthcheck); /** @var array $intervals */ $intervals = config('healthchecks.intervals', []); /** @var int $defaultInterval */ $defaultInterval = collect($intervals)->keys()->first() ?? 60; $this->form->interval = $defaultInterval; } } } #[On('save')] public function save(): void { $this->form->cleanDomain(); $this->form->normalizeEndpoint(); $this->validate(); $isNew = ! $this->healthcheck->exists; if ($this->healthcheck->exists) { $this->authorize('update', $this->healthcheck); $this->healthcheck->update($this->form->all()); } else { $this->authorize('create', $this->healthcheck); $this->healthcheck = Healthcheck::query()->create( $this->form->all() ); } $this->alert( __('Saved'), __('Healthcheck was successfully :action', ['action' => $this->healthcheck->wasRecentlyCreated ? 'created' : 'saved']), AlertType::Success ); if (! $this->inline) { if ($isNew) { if ($this->healthcheck->type === Type::Endpoint) { $this->redirectRoute('healthchecks.index'); } else { $this->redirectRoute('healthchecks.setup', ['healthcheck' => $this->healthcheck, 'new' => 1]); } } else { $this->redirectRoute('healthchecks.index'); } } } public function render(): View { /** @var view-string $view */ $view = 'healthchecks::livewire.healthcheck-form'; return view($view, [ 'updating' => $this->healthcheck->exists, 'inline' => $this->inline, ]); } } ================================================ FILE: packages/healthchecks/src/Livewire/HealthcheckSetup.php ================================================ authorize('view', $healthcheck); $this->healthcheck = $healthcheck; $this->isNew = request()->query('new') === '1'; } public function render(): View { /** @var view-string $view */ $view = 'healthchecks::livewire.healthcheck-setup'; return view($view, [ 'isNew' => $this->isNew, ]); } } ================================================ FILE: packages/healthchecks/src/Livewire/HealthcheckTokenEditor.php ================================================ authorize('view', $healthcheck); $this->healthcheck = $healthcheck; $this->token = (string) $healthcheck->token; } protected function rules(): array { return [ 'token' => ['required', 'string'], ]; } public function save(): void { if (! $this->healthcheck->type->generatesOwnToken()) { return; } $this->authorize('update', $this->healthcheck); $this->validate(); $this->healthcheck->update([ 'token' => $this->token, ]); $this->healthcheck->refresh(); $this->token = (string) $this->healthcheck->token; $this->alert( __('Saved'), __('Token updated successfully.'), AlertType::Success ); } public function render(): View { /** @var view-string $view */ $view = 'healthchecks::livewire.healthcheck-token-editor'; return view($view); } } ================================================ FILE: packages/healthchecks/src/Livewire/Healthchecks.php ================================================ exists(); return view($view, [ 'hasHealthchecks' => $hasHealthchecks, ]); } } ================================================ FILE: packages/healthchecks/src/Livewire/Tables/HealthcheckTable.php ================================================ 'None', '30s' => 'Every 30 seconds', ]; protected function columns(): array { return [ StatusColumn::make(__('Status')) ->text(function (Healthcheck $healthcheck): string { if (! $healthcheck->enabled) { return __('Disabled'); } if ($healthcheck->status === null) { return __('Unknown'); } return match ($healthcheck->status) { HealthStatus::Healthy => __('Healthy'), HealthStatus::Unhealthy => __('Unhealthy'), default => __('Unknown'), }; }) ->status(function (Healthcheck $healthcheck): Status { if (! $healthcheck->enabled) { return Status::Danger; } if ($healthcheck->status === null) { return Status::Warning; } return match ($healthcheck->status) { HealthStatus::Healthy => Status::Success, HealthStatus::Unhealthy => Status::Danger, default => Status::Warning, }; }), Column::make(__('Domain'), 'domain') ->searchable() ->sortable(), Column::make(__('Last check'), 'last_check_at') ->sortable(), ]; } protected function filters(): array { return [ SelectFilter::make(__('Site'), 'site_id') ->options( Site::query() ->orderBy('url') ->pluck('url', 'id') ->toArray() ), ]; } protected function actions(): array { return [ Action::make(__('Enable'), function (Enumerable $models): void { foreach ($models as $model) { if (! Gate::allows('create', $model)) { break; } $model->update(['enabled' => true]); } }, 'enable'), Action::make(__('Disable'), function (Enumerable $models): void { $models->each(fn (Healthcheck $healthcheck) => $healthcheck->update(['enabled' => false])); }, 'disable'), Action::make(__('Delete'), function (Enumerable $models): void { $models->each(fn (Healthcheck $healthcheck) => $healthcheck->delete()); }, 'delete'), ]; } public function link(Model $model): ?string { return route('healthchecks.view', ['healthcheck' => $model]); } } ================================================ FILE: packages/healthchecks/src/Livewire/Tables/ResultTable.php ================================================ healthcheckId = $healthcheckId; Healthcheck::query()->findOrFail($healthcheckId); } protected function columns(): array { return [ DateColumn::make(__('Last checked'), 'last_checked_at') ->sortable(), Column::make(__('Key'), 'key') ->sortable(), StatusColumn::make(__('Status')) ->text(function (Result $result): string { return match ($result->status) { Status::Healthy => __('Healthy'), Status::Warning => __('Warning'), Status::Unhealthy => __('Unhealthy'), }; }) ->status(function (Result $result): TableStatus { return match ($result->status) { Status::Healthy => TableStatus::Success, Status::Warning => TableStatus::Warning, Status::Unhealthy => TableStatus::Danger, }; }), Column::make(__('Message'), 'message'), DateColumn::make(__('Last unhealthy'), 'last_unhealthy_at') ->sortable(), ]; } protected function query(): Builder { return parent::query() ->where('healthcheck_id', '=', $this->healthcheckId); } } ================================================ FILE: packages/healthchecks/src/Models/Healthcheck.php ================================================ $results * @property Collection $metrics */ #[ScopedBy([TeamScope::class])] #[ObservedBy([TeamObserver::class, HealthcheckObserver::class])] class Healthcheck extends Model { protected $guarded = []; protected $casts = [ 'enabled' => 'boolean', 'type' => Type::class, 'status' => Status::class, 'next_check_at' => 'datetime', 'last_check_at' => 'datetime', ]; public function site(): BelongsTo { return $this->belongsTo(Site::class); } public function team(): BelongsTo { return $this->belongsTo(Team::class); } public function results(): HasMany { return $this->hasMany(Result::class); } public function metrics(): HasMany { return $this->hasMany(Metric::class); } } ================================================ FILE: packages/healthchecks/src/Models/Metric.php ================================================ 'decimal:2', ]; public function healthcheck(): BelongsTo { return $this->belongsTo(Healthcheck::class); } public function prunable(): Builder { return static::withoutGlobalScopes()->where('created_at', '<=', $this->retentionPeriod()); } } ================================================ FILE: packages/healthchecks/src/Models/Result.php ================================================ Status::class, 'data' => 'array', 'last_checked_at' => 'datetime', 'last_unhealthy_at' => 'datetime', ]; public function healthcheck(): BelongsTo { return $this->belongsTo(Healthcheck::class); } public function prunable(): Builder { return static::withoutGlobalScopes()->where('created_at', '<=', $this->retentionPeriod()); } } ================================================ FILE: packages/healthchecks/src/Notifications/Conditions/CheckKeyCondition.php ================================================ whereNotNull('key') ->distinct('key') ->orderBy('key') ->pluck('key', 'key') ->toArray(); } public function applies(Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta): bool { /** @var HealthCheckFailedNotification $notification */ return $notification->healthcheck->results() ->where('key', '=', $value) ->exists(); } } ================================================ FILE: packages/healthchecks/src/Notifications/Conditions/DiskFullInCondition.php ================================================ 'Less than', '<=' => 'Less or equal than', '>' => 'Greater than', '>=' => 'Greater or equal than', ]; } public function applies(Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta): bool { /** @var DiskUsageNotification $notification */ $hoursUntilFull = $notification->hoursUntilFull; $result = match ($operator) { '>' => $hoursUntilFull > $value, '>=' => $hoursUntilFull >= $value, '<' => $hoursUntilFull < $value, '<=' => $hoursUntilFull <= $value, default => false, }; return $result; } } ================================================ FILE: packages/healthchecks/src/Notifications/Conditions/MetricIncreaseNewValueCondition.php ================================================ 'Less than', '<=' => 'Less or equal than', '>' => 'Greater than', '>=' => 'Greater or equal than', ]; } public function applies(Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta): bool { /** @var MetricIncreasingNotification $notification */ $metricDatas = $notification->increasedMetrics; if (empty($metricDatas)) { return false; } if (! isset($metricDatas[0]) || ! is_array($metricDatas[0])) { $metricDatas = [$metricDatas]; } foreach ($metricDatas as $metricData) { if (! is_array($metricData)) { continue; } if ($operand !== null && ($metricData['key'] ?? null) !== $operand) { continue; } $newValue = $metricData['new_value'] ?? $notification->metric->value ?? null; if ($newValue === null) { continue; } $result = match ($operator) { '>' => $newValue > $value, '>=' => $newValue >= $value, '<' => $newValue < $value, '<=' => $newValue <= $value, default => false, }; if ($result) { return true; } } return false; } } ================================================ FILE: packages/healthchecks/src/Notifications/Conditions/MetricIncreasePercentCondition.php ================================================ 'Less than', '<=' => 'Less or equal than', '>' => 'Greater than', '>=' => 'Greater or equal than', ]; } public function applies(Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta): bool { /** @var MetricIncreasingNotification $notification */ $metricDatas = $notification->increasedMetrics; if (empty($metricDatas)) { return false; } if (! isset($metricDatas[0]) || ! is_array($metricDatas[0])) { $metricDatas = [$metricDatas]; } foreach ($metricDatas as $metricData) { if (! is_array($metricData)) { continue; } if ($operand !== null && ($metricData['key'] ?? null) !== $operand) { continue; } $percentIncrease = $metricData['percent_increase'] ?? null; if ($percentIncrease === null) { continue; } $result = match ($operator) { '>' => $percentIncrease > $value, '>=' => $percentIncrease >= $value, '<' => $percentIncrease < $value, '<=' => $percentIncrease <= $value, default => false, }; if ($result) { return true; } } return false; } } ================================================ FILE: packages/healthchecks/src/Notifications/Conditions/MetricIncreaseTimeframeCondition.php ================================================ */ public function options(): array { $options = []; foreach (self::INTERVALS as $minutes) { $options[$minutes] = sprintf('%d minutes', $minutes); } return $options; } public function applies(Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta): bool { /** @var MetricIncreasingNotification $notification */ $metricDatas = $notification->increasedMetrics; if (empty($metricDatas) || $value === null) { return false; } if (! isset($metricDatas[0]) || ! is_array($metricDatas[0])) { $metricDatas = [$metricDatas]; } $threshold = (int) $value; foreach ($metricDatas as $metricData) { if (! is_array($metricData)) { continue; } if ($operand !== null && ($metricData['key'] ?? null) !== $operand) { continue; } $timeframeMinutes = $metricData['timeframe_minutes'] ?? null; if ($timeframeMinutes === null) { continue; } if ((int) $timeframeMinutes === $threshold) { return true; } } return false; } } ================================================ FILE: packages/healthchecks/src/Notifications/Conditions/MetricKeyCondition.php ================================================ whereNotNull('key') ->distinct('key') ->orderBy('key') ->pluck('key', 'key') ->toArray(); } public function operators(): array { return [ '=' => 'is', '!=' => 'is not', ]; } public function applies(Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta): bool { /** @var MetricNotification $notification */ $key = $notification->metric->key; return match ($operator) { '=' => $key === $value, '!=' => $key !== $value, default => $key === $value, }; } } ================================================ FILE: packages/healthchecks/src/Notifications/Conditions/MetricUnitCondition.php ================================================ whereNotNull('unit') ->distinct('unit') ->orderBy('unit') ->pluck('unit', 'unit') ->toArray(); } public function applies(Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta): bool { /** @var MetricNotification $notification */ return $notification->metric->unit === $value; } } ================================================ FILE: packages/healthchecks/src/Notifications/Conditions/MetricValueCondition.php ================================================ 'Less than', '<=' => 'Less or equal than', '>' => 'Greater than', '>=' => 'Greater or equal than', ]; } public function applies(Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta): bool { /** @var MetricNotification $notification */ $metric = $notification->metric->value; return match ($operator) { '>' => $metric > $value, '>=' => $metric >= $value, '<' => $metric < $value, '<=' => $metric <= $value, default => false, }; } } ================================================ FILE: packages/healthchecks/src/Notifications/Conditions/StatusCondition.php ================================================ value => 'Unhealthy', Status::Warning->value => 'Warning', ]; } public function applies(Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta): bool { /** @var HealthCheckFailedNotification $notification */ $status = Status::tryFrom($value); if ($status === null) { return false; } return $notification->healthcheck->results() ->where('status', '=', $status) ->exists(); } } ================================================ FILE: packages/healthchecks/src/Notifications/DiskUsageNotification.php ================================================ 'group', 'operator' => 'any', 'children' => [ [ 'type' => 'condition', 'condition' => DiskFullInCondition::class, 'operator' => '<=', 'value' => 24, ], ], ]; public function __construct( public Healthcheck $healthcheck, public float $currentUsage, public float $velocity, public float $hoursUntilFull, public ?Carbon $estimatedFullAt = null ) {} public function title(): string { $domain = $this->healthcheck->domain; return __('Disk usage critical for :domain', ['domain' => $domain]); } public function description(): string { $hours = round($this->hoursUntilFull, 1); $velocityPerHour = round($this->velocity, 2); $message = __('Current disk usage: :usage%', ['usage' => round($this->currentUsage, 2)]).PHP_EOL; $message .= __('Growth rate: :rate% per hour', ['rate' => $velocityPerHour]).PHP_EOL; $message .= __('Estimated to reach 100% in: :hours hours', ['hours' => $hours]).PHP_EOL; if ($this->estimatedFullAt) { $message .= __('Estimated full at: :time', ['time' => teamTimezone($this->estimatedFullAt)->toDateTimeString()]); } return $message; } public static function info(): ?string { return __('Triggered when disk usage is projected to reach 100% within a specified timeframe.'); } public function uniqueId(): string { return 'disk-usage-'.$this->healthcheck->id; } public function site(): ?Site { return $this->healthcheck->site; } } ================================================ FILE: packages/healthchecks/src/Notifications/HealthCheckFailedNotification.php ================================================ 'group', 'operator' => 'any', 'children' => [ [ 'type' => 'condition', 'condition' => StatusCondition::class, 'value' => Status::Unhealthy->value, ], ], ]; public function __construct( public Healthcheck $healthcheck, public int $runId ) {} public function title(): string { return __('Healthcheck failed for :domain', ['domain' => $this->healthcheck->domain]); } public function description(): string { /** @var \Illuminate\Database\Eloquent\Collection $results */ $results = $this->healthcheck->results() ->where('status', '!=', Status::Healthy) ->get(); $failedChecks = $results->map(function (Result $result): string { if ($result->message === null) { return $result->key; } return $result->key.': '.$result->message; })->implode(PHP_EOL); return __('Healthchecks have failed:').PHP_EOL.$failedChecks; } public static function info(): ?string { return __('Triggered when a healthcheck fails.'); } public function uniqueId(): string { /** @var \Illuminate\Database\Eloquent\Collection $results */ $results = $this->healthcheck->results() ->where('status', '!=', Status::Healthy) ->orderBy('key') ->get(); $keys = $results ->pluck('key') ->implode('-'); return $this->healthcheck->id.'-'.$keys; } public function site(): ?Site { return $this->healthcheck->site; } } ================================================ FILE: packages/healthchecks/src/Notifications/MetricIncreasingNotification.php ================================================ 'group', 'operator' => 'all', 'children' => [ [ 'type' => 'condition', 'condition' => MetricIncreasePercentCondition::class, 'operator' => '>=', 'value' => 25, ], [ 'type' => 'condition', 'condition' => MetricIncreaseNewValueCondition::class, 'operator' => '>=', 'value' => 20, ], [ 'type' => 'condition', 'condition' => MetricIncreaseTimeframeCondition::class, 'operator' => '=', 'value' => 10, ], ], ]; public function __construct( public Metric $metric, public array $increasedMetrics = [] ) {} public function title(): string { $domain = $this->metric->healthcheck->domain ?? '?'; return __('Metric increasing for :domain', ['domain' => $domain]); } public function description(): string { $key = $this->metric->key; $value = $this->metric->value; $unit = $this->metric->unit; if (! empty($this->increasedMetrics)) { $metricData = $this->increasedMetrics; if (isset($metricData[0]) && is_array($metricData[0])) { $sorted = $metricData; usort($sorted, static function (array $left, array $right): int { return ($left['timeframe_minutes'] ?? PHP_INT_MAX) <=> ($right['timeframe_minutes'] ?? PHP_INT_MAX); }); $metricData = $sorted[0]; } if (! empty($metricData)) { $percentIncrease = round($metricData['percent_increase'] ?? 0, 1); $timeframeMinutes = $metricData['timeframe_minutes'] ?? 0; $oldValue = $metricData['old_value'] ?? 0; return __('The metric ":key" has increased by :percent% (from :old_value:unit to :new_value:unit) over the past :timeframe minutes.', [ 'key' => $key, 'percent' => $percentIncrease, 'old_value' => $oldValue, 'new_value' => $value, 'unit' => $unit, 'timeframe' => $timeframeMinutes, ]); } } return __('The metric ":key" has increased to :value:unit.', [ 'key' => $key, 'value' => $value, 'unit' => $unit, ]); } public static function info(): ?string { return __('Triggered when a metric increases by a specified percentage within a timeframe.'); } public function uniqueId(): string { return 'metric-increasing-'.$this->metric->key; } public function site(): ?Site { return $this->metric->healthcheck?->site; } } ================================================ FILE: packages/healthchecks/src/Notifications/MetricNotification.php ================================================ 'group', 'operator' => 'all', 'children' => [ [ 'type' => 'condition', 'condition' => MetricUnitCondition::class, 'value' => '%', ], [ 'type' => 'condition', 'condition' => MetricValueCondition::class, 'operator' => '>', 'value' => 80, ], ], ]; public function __construct( public Metric $metric ) {} public function title(): string { $domain = $this->metric->healthcheck->domain ?? '?'; return __('Metric threshold exceeded for :domain', ['domain' => $domain]); } public function description(): string { $key = $this->metric->key; $value = $this->metric->value; $unit = $this->metric->unit; return __('The metric ":key" has exceeded its configured threshold with a value of :value:unit.', [ 'key' => $key, 'value' => $value, 'unit' => $unit, ]); } public static function info(): ?string { return __('Triggered when a healthcheck metric exceeds configured thresholds.'); } public function uniqueId(): string { return $this->metric->key; } public function site(): ?Site { return $this->metric->healthcheck?->site; } } ================================================ FILE: packages/healthchecks/src/Notifications/MetricSpikeNotification.php ================================================ 'group', 'operator' => 'all', 'children' => [ [ 'type' => 'condition', 'condition' => MetricIncreasePercentCondition::class, 'operator' => '>=', 'value' => 40, ], [ 'type' => 'condition', 'condition' => MetricIncreaseTimeframeCondition::class, 'operator' => '<=', 'value' => 5, ], ], ]; public function __construct( public Metric $metric, public array $spikeMetrics = [] ) {} public function title(): string { $domain = $this->metric->healthcheck->domain ?? '?'; return __('Metric spike detected for :domain', ['domain' => $domain]); } public function description(): string { $key = $this->metric->key; $value = $this->metric->value; $unit = $this->metric->unit; if (! empty($this->spikeMetrics)) { $percentIncrease = round($this->spikeMetrics['percent_increase'] ?? 0, 1); $timeframeMinutes = $this->spikeMetrics['timeframe_minutes'] ?? 0; $oldValue = $this->spikeMetrics['old_value'] ?? 0; return __('The metric ":key" suddenly spiked by :percent% (from :old_value:unit to :new_value:unit) within :timeframe minutes.', [ 'key' => $key, 'percent' => $percentIncrease, 'old_value' => $oldValue, 'new_value' => $value, 'unit' => $unit, 'timeframe' => $timeframeMinutes, ]); } return __('The metric ":key" suddenly spiked to :value:unit.', [ 'key' => $key, 'value' => $value, 'unit' => $unit, ]); } public static function info(): ?string { return __('Triggered when a metric suddenly spikes by a large percentage in a short timeframe.'); } public function uniqueId(): string { return 'metric-spike-'.$this->metric->key; } public function site(): ?Site { return $this->metric->healthcheck?->site; } } ================================================ FILE: packages/healthchecks/src/Observers/HealthcheckObserver.php ================================================ token)) { $healthcheck->token = Str::random(32); } } public function created(Healthcheck $healthcheck): void { CheckHealthcheckJob::dispatch($healthcheck); } } ================================================ FILE: packages/healthchecks/src/ServiceProvider.php ================================================ registerConfig(); } protected function registerConfig(): static { $this->mergeConfigFrom(__DIR__.'/../config/healthchecks.php', 'healthchecks'); return $this; } public function boot(): void { $this ->bootConfig() ->bootMigrations() ->bootCommands() ->bootViews() ->bootLivewire() ->bootRoutes() ->bootNavigation() ->bootNotifications() ->bootGates() ->bootPolicies(); } protected function bootConfig(): static { $this->publishes([ __DIR__.'/../config/healthchecks.php' => config_path('healthchecks.php'), ], 'config'); return $this; } protected function bootMigrations(): static { $this->loadMigrationsFrom(__DIR__.'/../database/migrations'); return $this; } protected function bootCommands(): static { if ($this->app->runningInConsole()) { $this->commands([ AggregateMetricsCommand::class, CheckHealthcheckCommand::class, ScheduleHealthchecksCommand::class, ]); } return $this; } protected function bootViews(): static { $this->loadViewsFrom(__DIR__.'/../resources/views', 'healthchecks'); return $this; } protected function bootLivewire(): static { Livewire::component('healthchecks', Healthchecks::class); Livewire::component('healthcheck-form', HealthcheckForm::class); Livewire::component('healthcheck-table', HealthcheckTable::class); Livewire::component('healthcheck-result-table', ResultTable::class); Livewire::component('healthcheck-metric-chart', MetricChart::class); Livewire::component('healthcheck-dashboard', HealthcheckDashboard::class); Livewire::component('healthcheck-token-editor', HealthcheckTokenEditor::class); return $this; } protected function bootRoutes(): static { if (! $this->app->routesAreCached()) { Route::middleware(['web', 'auth']) ->group(fn () => $this->loadRoutesFrom(__DIR__.'/../routes/web.php')); Route::prefix('api') ->middleware(['api']) ->group(fn () => $this->loadRoutesFrom(__DIR__.'/../routes/api.php')); } return $this; } protected function bootNavigation(): static { Navigation::path(__DIR__.'/../resources/navigation.php'); return $this; } protected function bootNotifications(): static { NotificationRegistry::registerNotification([ HealthCheckFailedNotification::class, MetricNotification::class, MetricIncreasingNotification::class, DiskUsageNotification::class, ]); NotificationRegistry::registerCondition(HealthCheckFailedNotification::class, [ StatusCondition::class, CheckKeyCondition::class, SiteCondition::class, ]); NotificationRegistry::registerCondition(MetricNotification::class, [ MetricKeyCondition::class, MetricValueCondition::class, MetricUnitCondition::class, SiteCondition::class, ]); NotificationRegistry::registerCondition(MetricIncreasingNotification::class, [ MetricKeyCondition::class, MetricIncreasePercentCondition::class, MetricIncreaseNewValueCondition::class, MetricIncreaseTimeframeCondition::class, SiteCondition::class, ]); NotificationRegistry::registerCondition(DiskUsageNotification::class, [ DiskFullInCondition::class, SiteCondition::class, ]); return $this; } protected function bootGates(): static { Gate::define('use-healthchecks', function (User $user) { return ce(); }); return $this; } protected function bootPolicies(): static { if (ce()) { Gate::policy(Healthcheck::class, AllowAllPolicy::class); } return $this; } } ================================================ FILE: packages/healthchecks/testbench.yaml ================================================ providers: - Vigilant\Healthchecks\ServiceProvider ================================================ FILE: packages/healthchecks/tests/Actions/AggregateMetricsTest.php ================================================ create(); $team = Team::factory()->create(['user_id' => $user->id]); $healthcheck = Healthcheck::query()->create([ 'team_id' => $team->id, 'site_id' => null, 'enabled' => true, 'domain' => 'example.com', 'type' => Type::Endpoint->value, 'token' => 'token', 'interval' => 5, ]); $first = Metric::query()->create([ 'healthcheck_id' => $healthcheck->id, 'key' => 'cpu', 'value' => 10, 'unit' => '%', 'created_at' => Carbon::parse('2025-01-01 10:05:00'), 'updated_at' => Carbon::parse('2025-01-01 10:05:00'), ]); $second = Metric::query()->create([ 'healthcheck_id' => $healthcheck->id, 'key' => 'cpu', 'value' => 20, 'unit' => '%', 'created_at' => Carbon::parse('2025-01-01 10:15:00'), 'updated_at' => Carbon::parse('2025-01-01 10:15:00'), ]); $third = Metric::query()->create([ 'healthcheck_id' => $healthcheck->id, 'key' => 'cpu', 'value' => 30, 'unit' => '%', 'created_at' => Carbon::parse('2025-01-01 10:45:00'), 'updated_at' => Carbon::parse('2025-01-01 10:45:00'), ]); $recentOne = Metric::query()->create([ 'healthcheck_id' => $healthcheck->id, 'key' => 'cpu', 'value' => 60, 'unit' => '%', 'created_at' => Carbon::parse('2025-01-01 11:05:00'), 'updated_at' => Carbon::parse('2025-01-01 11:05:00'), ]); $recentTwo = Metric::query()->create([ 'healthcheck_id' => $healthcheck->id, 'key' => 'cpu', 'value' => 70, 'unit' => '%', 'created_at' => Carbon::parse('2025-01-01 11:20:00'), 'updated_at' => Carbon::parse('2025-01-01 11:20:00'), ]); app(AggregateMetrics::class)->handle(); $this->assertDatabaseCount('healthcheck_metrics', 3); $firstRefreshed = $first->fresh(); $this->assertInstanceOf(Metric::class, $firstRefreshed); $this->assertSame('20.00', $firstRefreshed->value); $this->assertDatabaseMissing('healthcheck_metrics', ['id' => $second->id]); $this->assertDatabaseMissing('healthcheck_metrics', ['id' => $third->id]); $this->assertDatabaseHas('healthcheck_metrics', ['id' => $recentOne->id]); $this->assertDatabaseHas('healthcheck_metrics', ['id' => $recentTwo->id]); $this->assertSame(2, Metric::query() ->where('created_at', '>=', Carbon::parse('2025-01-01 11:00:00')) ->count()); Carbon::setTestNow(); } } ================================================ FILE: packages/healthchecks/tests/Actions/CheckMetricTest.php ================================================ create([ 'domain' => 'example.com', 'type' => Type::Laravel, 'interval' => 5, 'token' => 'test-token', ]); /** @var CheckMetric $action */ $action = app(CheckMetric::class); $action->check($healthcheck, 1); $this->assertFalse(MetricIncreasingNotification::wasDispatched()); $this->assertFalse(MetricSpikeNotification::wasDispatched()); } #[Test] public function it_detects_metric_spike(): void { MetricSpikeNotification::fake(); $healthcheck = Healthcheck::query()->create([ 'domain' => 'example.com', 'type' => Type::Laravel, 'interval' => 5, 'token' => 'test-token', ]); $now = Carbon::now(); // Create four stable metrics and a sudden spike on the fifth run foreach ([100, 105, 110, 115] as $index => $value) { Metric::query()->create([ 'healthcheck_id' => $healthcheck->id, 'run_id' => $index + 1, 'key' => 'memory_usage', 'value' => $value, 'unit' => 'MB', 'created_at' => $now->copy()->subMinutes(4 - $index), ]); } Metric::query()->create([ 'healthcheck_id' => $healthcheck->id, 'run_id' => 5, 'key' => 'memory_usage', 'value' => 200, 'unit' => 'MB', 'created_at' => $now, ]); /** @var CheckMetric $action */ $action = app(CheckMetric::class); $action->check($healthcheck, 5); $this->assertTrue(MetricSpikeNotification::wasDispatched(function ($notification): bool { if (! $notification instanceof MetricSpikeNotification) { return true; } return $notification->spikeMetrics['key'] === 'memory_usage' && $notification->spikeMetrics['old_value'] == 100 && $notification->spikeMetrics['new_value'] == 200 && $notification->spikeMetrics['percent_increase'] == 100 && $notification->spikeMetrics['sample_size'] == 5 && $notification->spikeMetrics['detection_type'] === 'sudden_spike'; })); } #[Test] public function it_detects_long_term_metric_increase(): void { MetricIncreasingNotification::fake(); $healthcheck = Healthcheck::query()->create([ 'domain' => 'example.com', 'type' => Type::Laravel, 'interval' => 5, 'token' => 'test-token', ]); $now = Carbon::now(); // Create 7 historical metrics covering the last 60 minutes for ($i = 0; $i < 7; $i++) { Metric::query()->create([ 'healthcheck_id' => $healthcheck->id, 'run_id' => $i + 1, 'key' => 'memory_usage', 'value' => 100 + ($i * 15), 'unit' => 'MB', 'created_at' => $now->copy()->subMinutes(60 - ($i * 10)), ]); } /** @var CheckMetric $action */ $action = app(CheckMetric::class); $action->check($healthcheck, 7); $matched = false; MetricIncreasingNotification::wasDispatched(function ($notification) use (&$matched): bool { if (! $notification instanceof MetricIncreasingNotification) { return true; } $entries = $notification->increasedMetrics; if (! isset($entries[0]) || ! is_array($entries[0])) { return true; } $match = collect($entries)->first(function (array $entry): bool { return ($entry['key'] ?? null) === 'memory_usage' && ($entry['old_value'] ?? null) == 100 && ($entry['new_value'] ?? null) == 190 && round($entry['percent_increase'] ?? 0, 0) == 90 && ($entry['timeframe_minutes'] ?? null) === 60; }); if ($match !== null) { $matched = true; } return true; }); $this->assertTrue($matched); } #[Test] public function it_only_checks_configured_timeframes(): void { MetricIncreasingNotification::fake(); MetricSpikeNotification::fake(); $healthcheck = Healthcheck::query()->create([ 'domain' => 'example.com', 'type' => Type::Laravel, 'interval' => 5, 'token' => 'interval-test-token', ]); $now = Carbon::now(); $runId = 0; $dataPoints = [ 60 => 10, 30 => 15, 15 => 18, 10 => 20, 5 => 22, 2 => 23, 0 => 24, ]; foreach ($dataPoints as $minutesAgo => $value) { $runId++; Metric::query()->create([ 'healthcheck_id' => $healthcheck->id, 'run_id' => $runId, 'key' => 'cpu_load', 'value' => $value, 'unit' => '%', 'created_at' => $now->copy()->subMinutes($minutesAgo), ]); } /** @var CheckMetric $action */ $action = app(CheckMetric::class); $action->check($healthcheck, $runId); $matched = false; MetricIncreasingNotification::wasDispatched(function ($notification) use (&$matched): bool { if (! $notification instanceof MetricIncreasingNotification) { return true; } $entries = array_filter( $notification->increasedMetrics, static fn ($entry) => is_array($entry) ); if ($entries === []) { return true; } $timeframes = array_map( static fn (array $entry) => $entry['timeframe_minutes'] ?? null, $entries ); $timeframes = array_filter($timeframes, static fn ($value) => $value !== null); sort($timeframes); if ($timeframes === MetricIncreaseTimeframeCondition::INTERVALS) { $matched = true; } return true; }); $this->assertTrue($matched); } #[Test] public function it_notifies_when_disk_usage_is_increasing(): void { DiskUsageNotification::fake(); $healthcheck = Healthcheck::query()->create([ 'domain' => 'example.com', 'type' => Type::Laravel, 'interval' => 5, 'token' => 'disk-test-token', ]); $now = Carbon::now(); Metric::query()->create([ 'healthcheck_id' => $healthcheck->id, 'run_id' => 1, 'key' => 'disk_usage', 'value' => 70, 'unit' => '%', 'created_at' => $now->copy()->subHours(5), ]); Metric::query()->create([ 'healthcheck_id' => $healthcheck->id, 'run_id' => 2, 'key' => 'disk_usage', 'value' => 90, 'unit' => '%', 'created_at' => $now, ]); /** @var CheckMetric $action */ $action = app(CheckMetric::class); $action->check($healthcheck, 2); $this->assertTrue(DiskUsageNotification::wasDispatched(function ($notification) use ($healthcheck): bool { if (! $notification instanceof DiskUsageNotification) { return true; } return $notification->healthcheck->is($healthcheck) && $notification->currentUsage === 90.0 && $notification->velocity === 4.0 && $notification->hoursUntilFull === 2.5; })); } } ================================================ FILE: packages/healthchecks/tests/Actions/CheckResultTest.php ================================================ fakeNotification(HealthCheckFailedNotification::class); $healthcheck = Healthcheck::query()->create([ 'domain' => 'example.com', 'type' => Type::Laravel, 'interval' => 5, 'token' => 'result-test-token', ]); Result::query()->create([ 'healthcheck_id' => $healthcheck->id, 'key' => 'uptime', 'status' => Status::Unhealthy, 'message' => 'Service unavailable', ]); /** @var CheckResult $action */ $action = app(CheckResult::class); $action->check($healthcheck, 42); $this->assertNotificationDispatched( HealthCheckFailedNotification::class, function (HealthCheckFailedNotification $notification) use ($healthcheck): bool { return $notification->healthcheck->is($healthcheck) && $notification->runId === 42; } ); $refreshedHealthcheck = $healthcheck->fresh(); $this->assertInstanceOf(Healthcheck::class, $refreshedHealthcheck); $this->assertSame(Status::Unhealthy, $refreshedHealthcheck->status); Bus::assertDispatched(CheckMetricJob::class, function (CheckMetricJob $job) use ($healthcheck) { return $job->healthcheck->is($healthcheck) && $job->runId === 42; }); } #[Test] public function it_sets_status_to_warning_when_results_have_warnings(): void { Bus::fake(); $this->fakeNotification(HealthCheckFailedNotification::class); $healthcheck = Healthcheck::query()->create([ 'domain' => 'example.com', 'type' => Type::Laravel, 'interval' => 5, 'token' => 'result-warning-token', ]); Result::query()->create([ 'healthcheck_id' => $healthcheck->id, 'key' => 'uptime', 'status' => Status::Warning, 'message' => 'Slow response', ]); /** @var CheckResult $action */ $action = app(CheckResult::class); $action->check($healthcheck, 7); $this->assertNotificationDispatched( HealthCheckFailedNotification::class, function (HealthCheckFailedNotification $notification) use ($healthcheck): bool { return $notification->healthcheck->is($healthcheck) && $notification->runId === 7; } ); $refreshedHealthcheck = $healthcheck->fresh(); $this->assertInstanceOf(Healthcheck::class, $refreshedHealthcheck); $this->assertSame(Status::Warning, $refreshedHealthcheck->status); Bus::assertDispatched(CheckMetricJob::class, function (CheckMetricJob $job) use ($healthcheck) { return $job->healthcheck->is($healthcheck) && $job->runId === 7; }); } #[Test] public function it_does_not_notify_when_all_results_are_healthy(): void { Bus::fake(); $this->fakeNotification(HealthCheckFailedNotification::class); $healthcheck = Healthcheck::query()->create([ 'domain' => 'example.com', 'type' => Type::Laravel, 'interval' => 5, 'token' => 'result-healthy-token', ]); Result::query()->create([ 'healthcheck_id' => $healthcheck->id, 'key' => 'uptime', 'status' => Status::Healthy, ]); /** @var CheckResult $action */ $action = app(CheckResult::class); $action->check($healthcheck, 99); $this->assertNotificationNotDispatched(HealthCheckFailedNotification::class); $refreshedHealthcheck = $healthcheck->fresh(); $this->assertInstanceOf(Healthcheck::class, $refreshedHealthcheck); $this->assertSame(Status::Healthy, $refreshedHealthcheck->status); Bus::assertDispatched(CheckMetricJob::class, function (CheckMetricJob $job) use ($healthcheck) { return $job->healthcheck->is($healthcheck) && $job->runId === 99; }); } /** * @param class-string<\Vigilant\Notifications\Notifications\Notification> $notificationClass */ private function fakeNotification(string $notificationClass): void { $notificationClass::fake(); $this->resetNotificationFakes($notificationClass); } /** * @param class-string<\Vigilant\Notifications\Notifications\Notification> $notificationClass */ private function assertNotificationNotDispatched(string $notificationClass): void { $this->assertEmpty( $this->notificationDispatches($notificationClass), "Did not expect {$notificationClass} to be dispatched." ); } /** * @param class-string<\Vigilant\Notifications\Notifications\Notification> $notificationClass */ private function assertNotificationDispatched(string $notificationClass, callable $callback): void { $dispatches = $this->notificationDispatches($notificationClass); $this->assertNotEmpty( $dispatches, "Expected {$notificationClass} to be dispatched." ); $matched = false; foreach ($dispatches as $dispatch) { if ($callback($dispatch)) { $matched = true; break; } } $this->assertTrue( $matched, "No dispatched {$notificationClass} matched the provided conditions." ); } /** * @param class-string<\Vigilant\Notifications\Notifications\Notification> $notificationClass * @return array */ private function notificationDispatches(string $notificationClass): array { $property = new \ReflectionProperty($notificationClass, 'fakeDispatches'); $property->setAccessible(true); /** @var array $dispatches */ $dispatches = $property->getValue(); return $dispatches; } /** * @param class-string<\Vigilant\Notifications\Notifications\Notification> $notificationClass */ private function resetNotificationFakes(string $notificationClass): void { $property = new \ReflectionProperty($notificationClass, 'fakeDispatches'); $property->setAccessible(true); $property->setValue(null, []); } } ================================================ FILE: packages/healthchecks/tests/TestCase.php ================================================ set('database.default', 'testbench'); $app['config']->set('database.connections.testbench', [ 'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '', ]); } protected function setUp(): void { parent::setUp(); TeamService::fake(); } } ================================================ FILE: packages/lighthouse/.gitignore ================================================ vendor composer.lock .phpunit.result.cache ================================================ FILE: packages/lighthouse/composer.json ================================================ { "name": "vigilant/lighthouse", "description": "Vigilant Lighthouse", "type": "package", "license": "AGPL", "authors": [ { "name": "Vincent Boon", "email": "info@vincentbean.com", "role": "Developer" } ], "require": { "php": "^8.3", "guzzlehttp/guzzle": "^7.8", "laravel/framework": "^12.0", "livewire/livewire": "^3.4", "vigilant/core": "@dev", "vigilant/sites": "@dev", "vigilant/users": "@dev", "vigilant/frontend": "@dev", "vigilant/notifications": "@dev", "geerlingguy/ping": "^1.2" }, "require-dev": { "laravel/pint": "^1.6", "larastan/larastan": "^3.0", "orchestra/testbench": "^10.0", "phpstan/phpstan-mockery": "^2.0", "phpunit/phpunit": "^11.0" }, "autoload": { "psr-4": { "Vigilant\\Lighthouse\\": "src", "Vigilant\\Lighthouse\\Database\\Factories\\": "database/factories", "Vigilant\\Users\\Database\\Factories\\": "../users/database/factories" } }, "autoload-dev": { "psr-4": { "Vigilant\\Lighthouse\\Tests\\": "tests" } }, "scripts": { "test": "phpunit", "analyse": "phpstan", "style": "pint --test", "quality": [ "@test", "@analyse" ] }, "config": { "sort-packages": true, "allow-plugins": { "php-http/discovery": true } }, "extra": { "laravel": { "providers": [ "Vigilant\\Lighthouse\\ServiceProvider" ] } }, "minimum-stability": "dev", "prefer-stable": true, "repositories": [ { "type": "path", "url": "../*" } ] } ================================================ FILE: packages/lighthouse/config/lighthouse.php ================================================ 'lighthouse', 'intervals' => [ 60 => 'Hourly', 60 * 3 => 'Every 3 hours', 60 * 6 => 'Every 6 hours', 60 * 12 => 'Every 12 hours', 60 * 24 => 'Daily', 60 * 24 * 7 => 'Weekly', ], 'runs' => env('LIGHTHOUSE_RUNS', 3), 'workers' => explode(',', env('LIGHTHOUSE_WORKERS', 'lighthouse')), /* URL to Vigilant */ 'lighthouse_app_url' => env('LIGHTHOUSE_APP_URL', 'http://app:8000'), ]; ================================================ FILE: packages/lighthouse/database/migrations/2024_05_11_105500_create_lighthouse_sites_table.php ================================================ id(); $table->foreignIdFor(Site::class)->nullable()->constrained()->onDelete('cascade'); $table->foreignIdFor(Team::class)->constrained()->onDelete('cascade'); $table->string('url'); $table->json('settings'); $table->string('interval'); $table->timestamps(); }); } public function down(): void { Schema::dropIfExists('lighthouse_monitors'); } }; ================================================ FILE: packages/lighthouse/database/migrations/2024_05_11_120000_create_lighthouse_results_table.php ================================================ id(); $table->unsignedBigInteger('lighthouse_site_id'); $table->foreignIdFor(Team::class)->constrained()->onDelete('cascade'); $table->float('performance'); $table->float('accessibility'); $table->float('best_practices'); $table->float('seo'); $table->timestamps(); $table->foreign('lighthouse_site_id') ->references('id') ->on('lighthouse_monitors') ->onDelete('cascade'); }); } public function down(): void { Schema::dropIfExists('lighthouse_results'); } }; ================================================ FILE: packages/lighthouse/database/migrations/2024_05_17_073000_lighthouse_results_aggregated_field_table.php ================================================ boolean('aggregated')->after('seo')->default(0); }); } public function down(): void { Schema::dropColumns('lighthouse_results', ['aggregated']); } }; ================================================ FILE: packages/lighthouse/database/migrations/2024_06_22_160000_create_lighthouse_result_audits_table.php ================================================ id(); $table->foreignIdFor(LighthouseResult::class)->constrained()->onDelete('cascade'); $table->foreignIdFor(Team::class)->constrained()->onDelete('cascade'); $table->string('audit')->index(); $table->string('title', 1024); $table->string('explanation', 1024)->nullable(); $table->text('description')->nullable(); $table->float('score')->nullable(); $table->string('scoreDisplayMode'); $table->json('details')->nullable(); $table->json('warnings')->nullable(); $table->json('items')->nullable(); $table->json('metricSavings')->nullable(); $table->float('guidanceLevel')->nullable(); $table->float('numericValue')->nullable(); $table->string('numericUnit')->nullable(); $table->timestamps(); }); } public function down(): void { Schema::dropIfExists('lighthouse_result_audits'); } }; ================================================ FILE: packages/lighthouse/database/migrations/2024_07_13_200000_lighthouse_site_rename_table.php ================================================ renameColumn('lighthouse_site_id', 'lighthouse_monitor_id'); }); } public function down(): void { Schema::rename('lighthouse_monitors', 'lighthouse_sites'); Schema::table('lighthouse_results', function (Blueprint $table): void { $table->renameColumn('lighthouse_monitor_id', 'lighthouse_site_id'); }); } }; ================================================ FILE: packages/lighthouse/database/migrations/2025_02_01_173000_lighthouse_monitors_enabled_field.php ================================================ boolean('enabled')->default(true)->after('id'); }); } public function down(): void { Schema::dropColumns('lighthouse_monitors', ['enabled']); } }; ================================================ FILE: packages/lighthouse/database/migrations/2025_02_03_190000_lighthouse_monitors_next_run_field.php ================================================ withoutGlobalScopes()->update(['interval' => 60]); Schema::table('lighthouse_monitors', function (Blueprint $table): void { $table->integer('interval')->change(); $table->dateTime('next_run')->nullable()->after('interval'); }); } public function down(): void { Schema::dropColumns('lighthouse_monitors', ['next_run']); Schema::table('lighthouse_monitors', function (Blueprint $table): void { $table->string('interval')->change(); }); } }; ================================================ FILE: packages/lighthouse/database/migrations/2025_02_07_210000_lighthouse_monitors_batch_fields.php ================================================ uuid('batch_id')->after('team_id')->nullable(); }); } public function down(): void { Schema::table('lighthouse_results', function (Blueprint $table): void { $table->dropColumn('batch_id'); }); } }; ================================================ FILE: packages/lighthouse/database/migrations/2025_03_19_200000_lighthouse_monitors_run_started_at_field.php ================================================ dateTime('run_started_at')->nullable()->after('next_run'); }); } public function down(): void { Schema::table('lighthouse_monitors', function (Blueprint $table): void { $table->dropColumn('run_started_at'); }); } }; ================================================ FILE: packages/lighthouse/phpstan.neon ================================================ includes: - ./vendor/larastan/larastan/extension.neon - ./vendor/phpstan/phpstan-mockery/extension.neon parameters: paths: - src - tests level: 8 ignoreErrors: - identifier: missingType.iterableValue - identifier: missingType.generics ================================================ FILE: packages/lighthouse/phpunit.xml ================================================ ./tests/* ./src ================================================ FILE: packages/lighthouse/resources/navigation.php ================================================ parent('performance') ->icon('phosphor-lighthouse-light') ->gate('use-lighthouse') ->routeIs('lighthouse*') ->sort(300); ================================================ FILE: packages/lighthouse/resources/views/components/average-difference.blade.php ================================================ @props(['difference']) @if ($difference !== null) @php($differencePercent = $difference->averageDifference()) $differencePercent > 0, 'text-base-600' => $differencePercent == 0, 'text-red-light' => $differencePercent < 0, ])>{{ round($differencePercent, 1) . '%' }} @else - @endif ================================================ FILE: packages/lighthouse/resources/views/components/empty-states/monitors.blade.php ================================================ ================================================ FILE: packages/lighthouse/resources/views/lighthouse/index.blade.php ================================================ @lang('Edit') @lang('Delete') @lang('Edit') @lang('Delete')
@foreach ($charts as $chart)

{{ $chart['title'] }}

{{ $chart['description'] }}
Learn more about the {{ $chart['title'] }} metric.

@endforeach

{{ __('Results') }}

@lang('View the raw results from each Lighthouse run')

@if (count($screenshots) > 0)

@lang('Timeline')

@foreach ($screenshots as $screenshot)
{{ $screenshot['timing'] }}ms
@endforeach
@endif
@lang('Delete Lighthouse Monitor')

@lang('Are you sure you want to delete this Lighthouse monitor?')

@svg('phosphor-warning-circle', 'w-5 h-5 text-orange mt-0.5')

{{ $lighthouseMonitor->url }}

@lang('This action cannot be undone. All performance data and reports for this monitor will be permanently deleted.')

@lang('Cancel')
@csrf @method('DELETE') @lang('Delete Monitor')
================================================ FILE: packages/lighthouse/resources/views/livewire/lighthouse-site-form.blade.php ================================================
@if (!$inline) @endif
@if (!$inline) @endif @foreach (config('lighthouse.intervals') as $interval => $label) @endforeach @if (!$inline) @endif
================================================ FILE: packages/lighthouse/resources/views/livewire/lighthouse-sites.blade.php ================================================
@lang('Add Lighthouse Monitor') @lang('Add Lighthouse Monitor') @if ($hasMonitors) @else @endif
================================================ FILE: packages/lighthouse/resources/views/livewire/monitor/dashboard.blade.php ================================================
@foreach (['performance', 'accessibility', 'best_practices', 'seo'] as $category) @php $color = 'text-red'; if ($lastResult !== null) { $percentage = round($lastResult[$category] * 100); $color = match (true) { $percentage > 80 => 'text-green-light', $percentage > 60 => 'text-orange-light', default => 'text-red-light', }; } @endphp {{ $lastResult === null ? __('-') : $percentage . '%' }} @endforeach @foreach (['7d' => 'Week', '30d' => 'Month', '90d' => '3 Months', '180d' => '6 Months'] as $timeframe => $label) @endforeach
================================================ FILE: packages/lighthouse/resources/views/result/index.blade.php ================================================
@foreach(['performance', 'accessibility', 'best_practices', 'seo'] as $category) @php $color = 'text-red'; $percentage = round($result[$category] * 100); $color = match(true) { $percentage > 80 => 'text-green-light', $percentage > 60 => 'text-orange-light', default => 'text-red-light' }; @endphp
{{ str_replace('_', ' ', ucfirst($category)) }}
{{ $percentage . '%' }}
@endforeach

{{ __('Audits') }}

================================================ FILE: packages/lighthouse/routes/api.php ================================================ middleware('signed:relative') ->name('lighthouse.callback'); ================================================ FILE: packages/lighthouse/routes/web.php ================================================ middleware('can:use-lighthouse') ->group(function (): void { Route::get('/', LighthouseSites::class)->name('lighthouse'); Route::get('/create', LighthouseSiteForm::class)->name('lighthouse.create'); Route::get('/{monitor}', [LighthouseMonitorController::class, 'index'])->name('lighthouse.index')->can('view,monitor'); Route::delete('/{monitor}', [LighthouseMonitorController::class, 'delete'])->name('lighthouse.delete')->can('delete,monitor'); Route::get('/{monitor}/edit', LighthouseSiteForm::class)->name('lighthouse.edit'); Route::get('/ressult/{result}', [LighthouseResultController::class, 'index'])->name('lighthouse.result.index'); }); ================================================ FILE: packages/lighthouse/src/Actions/AggregateLighthouseBatch.php ================================================ $results */ $results = $monitor->lighthouseResults()->where('batch_id', '=', $batchId)->get(); if ($results->isEmpty()) { return; } if ($results->count() === 1) { CheckLighthouseResultJob::dispatch($results->first()); return; } /** @var LighthouseResult $resultAverages */ $resultAverages = $monitor->lighthouseResults() ->where('batch_id', '=', $batchId) ->groupBy('batch_id') ->selectRaw('AVG(performance) as performance, AVG(accessibility) as accessibility, AVG(best_practices) as best_practices, AVG(seo) as seo') ->first(); /** @var LighthouseResult $newResult */ $newResult = $monitor->lighthouseResults()->create([ 'performance' => $resultAverages->performance, 'accessibility' => $resultAverages->accessibility, 'best_practices' => $resultAverages->best_practices, 'seo' => $resultAverages->seo, ]); /** @var LighthouseResult $firstResult */ $firstResult = $monitor->lighthouseResults()->where('batch_id', '=', $batchId)->first(); $auditCategories = $firstResult->audits()->select('audit')->distinct()->get()->pluck('audit')->toArray(); foreach ($auditCategories as $audit) { /** @var ?LighthouseResultAudit $averages */ $averages = LighthouseResultAudit::query() ->whereIn('lighthouse_result_id', $results->pluck('id')) ->where('audit', '=', $audit) ->selectRaw('AVG(score) as score, AVG(numericValue) as numericValue') ->first(); /** @var ?LighthouseResultAudit $allValues */ $allValues = LighthouseResultAudit::query() ->whereIn('lighthouse_result_id', $results->pluck('id')) ->where('audit', '=', $audit) ->first(); if ($averages === null || $allValues === null) { continue; } $newResult->audits()->create(array_merge([ 'audit' => $audit, 'score' => $averages->score, 'numericValue' => $averages->numericValue, ], $allValues->only(['title', 'explanation', 'description', 'scoreDisplayMode', 'details', 'warnings', 'items', 'metricSavings', 'guidanceLevel', 'numericUnit']))); } $monitor->lighthouseResults()->where('batch_id', '=', $batchId)->delete(); CheckLighthouseResultJob::dispatch($newResult); } } ================================================ FILE: packages/lighthouse/src/Actions/AggregateResults.php ================================================ lighthouseResults() ->where('aggregated', '=', false) ->where('created_at', '>=', $from) ->where('created_at', '<=', $till) ->get(); if ($results->isEmpty()) { return; } /** @var LighthouseResult $aggregate */ $aggregate = $results->first(); $aggregate->performance = round($results->average('performance') ?? 0, 2); $aggregate->accessibility = round($results->average('accessibility') ?? 0, 2); $aggregate->best_practices = round($results->average('best_practices') ?? 0, 2); $aggregate->seo = round($results->average('seo') ?? 0, 2); $aggregate->aggregated = true; $aggregate->save(); $idsToDelete = $results ->where('id', '!=', $aggregate->id) ->pluck('id') ->toArray(); LighthouseResultAudit::query() ->whereIn('lighthouse_result_id', $idsToDelete) ->delete(); LighthouseResult::query() ->whereIn('id', $idsToDelete) ->delete(); } } ================================================ FILE: packages/lighthouse/src/Actions/CalculateTimeDifference.php ================================================ lighthouseResults()->where('created_at', '<=', $from)->count() === 0) { return null; } $results = $monitor->lighthouseResults() ->where('created_at', '>=', $from) ->get(); if ($results->isEmpty()) { return null; } /** @var LighthouseResult $firstResult */ $firstResult = $results->sortBy('created_at')->first(); if ($firstResult->created_at === null || $from->diffInDays($firstResult->created_at) > 7) { return null; } $take = (int) max(1, round($results->count() * $sampleSize)); $old = $results->take($take); $new = $results->skip($results->count() - $take)->take($take); return CategoryResultDifferenceData::of([ 'performance_old' => $old->average('performance'), 'performance_new' => $new->average('performance'), 'accessibility_old' => $old->average('accessibility'), 'accessibility_new' => $new->average('accessibility'), 'best_practices_old' => $old->average('best_practices'), 'best_practices_new' => $new->average('best_practices'), 'seo_old' => $old->average('seo'), 'seo_new' => $new->average('seo'), ]); } } ================================================ FILE: packages/lighthouse/src/Actions/CheckLighthouseResult.php ================================================ where('lighthouse_monitor_id', '=', $result->lighthouse_monitor_id) ->count(); // Not enough data if ($totalResultCount < 10) { return; } // take 10% of the result set to calculate the current value $currentLimit = (int) floor($totalResultCount * 0.1); // take 30% of the result set before the current to calculate the previous value $previousLimit = (int) floor($totalResultCount * 0.3); $current = $this->averageResults($result->lighthouse_monitor_id, $currentLimit, 0) ->mapWithKeys(fn (?float $score, string $key) => [$key.'_new' => $score ?? 0]); $previous = $this->averageResults($result->lighthouse_monitor_id, $previousLimit, $currentLimit) ->mapWithKeys(fn (?float $score, string $key) => [$key.'_old' => $score ?? 0]); $data = CategoryResultDifferenceData::of($current->merge($previous)->toArray()); CategoryScoreChangedNotification::notify($result, $data); /** @var Collection $audits */ $audits = $result->audits()->get(); $audits->each(fn (LighthouseResultAudit $audit) => $this->checkLighthouseResultAudit->check($audit)); } protected function averageResults(int $lighthouseSiteId, int $count, int $skip): Collection { $results = LighthouseResult::query() ->where('lighthouse_monitor_id', '=', $lighthouseSiteId) ->orderByDesc('id') ->skip($skip) ->take($count) ->get(); return collect($this->categories) ->mapWithKeys(fn (string $category): array => [$category => $results->average($category)]); } } ================================================ FILE: packages/lighthouse/src/Actions/CheckLighthouseResultAudit.php ================================================ scoreDisplayMode !== 'numeric') { return; } /** @var ?int $monitorId */ $monitorId = $audit->lighthouseResult?->lighthouse_monitor_id; throw_if($monitorId === null, 'Invalid relationship'); $totalResultCount = LighthouseResultAudit::query() ->join('lighthouse_results', function (JoinClause $join) use ($monitorId) { $join->on('lighthouse_results.id', '=', 'lighthouse_result_audits.lighthouse_result_id') ->where('lighthouse_results.lighthouse_monitor_id', '=', $monitorId) ->where('lighthouse_results.created_at', '>', now()->subMonth()); }) ->where('audit', '=', $audit->audit) ->count(); // Not enough data if ($totalResultCount < 10) { return; } // take 10% of the result set to calculate the current value $currentLimit = (int) floor($totalResultCount * 0.1); // take 30% of the result set before the current to calculate the previous value $previousLimit = (int) floor($totalResultCount * 0.3); $current = $this->averageNumericValue($audit, $currentLimit, 0); $previous = $this->averageNumericValue($audit, $previousLimit, $currentLimit); if ($previous == 0) { $percentDifference = ($current == 0) ? 0 : 100; } else { $percentDifference = (($current - $previous) / $previous) * 100; } if ($percentDifference > 0) { NumericAuditChangedNotification::notify($audit, $percentDifference, $previous, $current); } } protected function averageNumericValue(LighthouseResultAudit $audit, int $count = 3, int $skip = 0): float { /** @var ?int $monitorId */ $monitorId = $audit->lighthouseResult?->lighthouse_monitor_id; throw_if($monitorId === null, 'Invalid relationship'); return (float) LighthouseResultAudit::query() ->join('lighthouse_results', function (JoinClause $join) use ($monitorId) { $join->on('lighthouse_results.id', '=', 'lighthouse_result_audits.lighthouse_result_id') ->where('lighthouse_results.lighthouse_monitor_id', '=', $monitorId); }) ->where('audit', '=', $audit->audit) ->orderByDesc('lighthouse_result_audits.id') ->skip($skip) ->take($count) ->get() ->average('numericValue'); } } ================================================ FILE: packages/lighthouse/src/Actions/ProcessLighthouseResult.php ================================================ $categoriesResult */ $categoriesResult = $result['categories'] ?? []; /** @var array $audits */ $audits = $result['audits']; $categories = collect($categoriesResult) ->mapWithKeys(function (array $result, string $key): array { return [str_replace('-', '_', $key) => $result['score']]; }) ->toArray(); /** @var LighthouseResult $result */ $result = $monitor->lighthouseResults()->create(array_merge(['batch_id' => $batchId], $categories)); foreach ($audits as $audit) { $result->audits()->create([ 'audit' => $audit['id'], 'title' => $audit['title'], 'explanation' => $audit['explanation'] ?? null, 'description' => $audit['description'] ?? null, 'score' => $audit['score'] ?? null, 'scoreDisplayMode' => $audit['scoreDisplayMode'], 'details' => $audit['details'] ?? null, 'warnings' => $audit['warnings'] ?? null, 'items' => $audit['items'] ?? null, 'metricSavings' => $audit['metricSavings'] ?? null, 'guidanceLevel' => $audit['guidanceLevel'] ?? null, 'numericValue' => $audit['numericValue'] ?? null, 'numericUnit' => $audit['numericUnit'] ?? null, ]); } $batchCount = $monitor->lighthouseResults() ->where('batch_id', $batchId) ->count(); /** @var int $lighthouseRuns */ $lighthouseRuns = config('lighthouse.runs'); if ($batchCount >= $lighthouseRuns) { AggregateLighthouseBatchJob::dispatch($monitor, $batchId); $monitor->update([ 'run_started_at' => null, ]); } else { RunLighthouseJob::dispatch($monitor, $batchId); } } } ================================================ FILE: packages/lighthouse/src/Actions/RunLighthouse.php ================================================ getAvailableWorker(); if ($worker === null) { logger()->warning('No available workers to run Lighthouse job'); return; } if ($batchId === null) { $batchId = str()->uuid(); $monitor->update([ 'next_run' => now()->addMinutes($monitor->interval), ]); } $vigilantUrl = config()->string('lighthouse.lighthouse_app_url'); Http::baseUrl($worker) ->post('lighthouse', [ 'website' => $monitor->url, 'callback_url' => $vigilantUrl.URL::signedRoute('lighthouse.callback', ['monitorId' => $monitor->id, 'batch' => $batchId, 'worker' => $worker], absolute: false), ]) ->throw(); $monitor->update([ 'run_started_at' => now(), ]); } public function getAvailableWorker(): ?string { $lockKey = 'lighthouse:worker:lock'; $workers = config()->array('lighthouse.workers'); $lock = cache()->lock($lockKey, 5); if (! $lock->get()) { return null; // Another process is selecting a worker } try { foreach ($workers as $worker) { $workerCacheKey = 'lighthouse:worker:'.$worker; if (cache()->has($workerCacheKey)) { continue; } cache()->put($workerCacheKey, true, now()->addMinutes(5)); return $worker; } } finally { $lock->release(); } return null; } } ================================================ FILE: packages/lighthouse/src/Commands/AggregateLighthouseBatchCommand.php ================================================ argument('resultId'); /** @var LighthouseResult $result */ $result = LighthouseResult::query() ->withoutGlobalScopes() ->whereNotNull('batch_id') ->where('id', '=', $resultId) ->firstOrFail(); $teamService->setTeamById($result->team_id); $aggregator->aggregateBatch($result->lighthouseSite, $result->batch_id); // @phpstan-ignore-line return static::SUCCESS; } } ================================================ FILE: packages/lighthouse/src/Commands/AggregateLighthouseResultsCommand.php ================================================ withoutGlobalScopes() ->get(); /** @var LighthouseMonitor $site */ foreach ($sites as $site) { /** @var ?LighthouseResult $lastNonAggregatedResult */ $lastNonAggregatedResult = $site->lighthouseResults() ->withoutGlobalScopes() ->where('aggregated', '=', false) ->where('created_at', '<', now()->toDateString()) ->orderBy('created_at') ->first(); if ($lastNonAggregatedResult === null) { continue; } $days = round($lastNonAggregatedResult->created_at?->diffInDays(now()) ?? 0); $start = $lastNonAggregatedResult->created_at; if ($start === null) { continue; } for ($i = 0; $i < $days; $i++) { $end = $start->clone()->addDay(); $this->info("Aggregating for site {$site->id} from {$start->toDateString()} to {$end->toDateString()}"); AggregateLighthouseResultsJob::dispatch($site, $start, $end); $start->addDay(); if ($start->diffInDays(now()) <= 2) { break; } } } return static::SUCCESS; } } ================================================ FILE: packages/lighthouse/src/Commands/CheckLighthouseCommand.php ================================================ argument('resultId'); /** @var LighthouseResult $result */ $result = LighthouseResult::query()->withoutGlobalScopes()->findOrFail($resultId); $teamService->setTeamById($result->team_id); $lighthouseResult->check($result); return static::SUCCESS; } } ================================================ FILE: packages/lighthouse/src/Commands/LighthouseCommand.php ================================================ argument('siteId'); /** @var LighthouseMonitor $site */ $site = LighthouseMonitor::query() ->withoutGlobalScopes() ->findOrFail($siteId); RunLighthouseJob::dispatch($site); return static::SUCCESS; } } ================================================ FILE: packages/lighthouse/src/Commands/ScheduleLighthouseCommand.php ================================================ withoutGlobalScopes() ->where('enabled', '=', true) ->where(function (Builder $query): void { $query ->whereNull('run_started_at') ->orWhere('run_started_at', '<=', now()->subHour()); }) ->where(function (Builder $query): void { $query ->whereNull('next_run') ->orWhere('next_run', '<=', now()); }) ->get() ->each(fn (LighthouseMonitor $monitor): PendingDispatch => RunLighthouseJob::dispatch($monitor)); return static::SUCCESS; } } ================================================ FILE: packages/lighthouse/src/Data/CategoryResultDifferenceData.php ================================================ ['required', 'numeric'], 'performance_new' => ['required', 'numeric'], 'accessibility_old' => ['required', 'numeric'], 'accessibility_new' => ['required', 'numeric'], 'best_practices_old' => ['required', 'numeric'], 'best_practices_new' => ['required', 'numeric'], 'seo_old' => ['required', 'numeric'], 'seo_new' => ['required', 'numeric'], ]; public function performanceOld(): float { return $this['performance_old']; } public function performanceNew(): float { return $this['performance_new']; } public function performanceDifference(): float { return $this->calculateDifference($this->performanceOld(), $this->performanceNew()); } public function accessibilityOld(): float { return $this['accessibility_old']; } public function accessibilityNew(): float { return $this['accessibility_new']; } public function accessibilityDifference(): float { return $this->calculateDifference($this->accessibilityOld(), $this->accessibilityNew()); } public function bestPracticesOld(): float { return $this['best_practices_old']; } public function bestPracticesNew(): float { return $this['best_practices_new']; } public function bestPracticesDifference(): float { return $this->calculateDifference($this->bestPracticesOld(), $this->bestPracticesNew()); } public function seoOld(): float { return $this['seo_old']; } public function seoNew(): float { return $this['seo_new']; } public function seoDifference(): float { return $this->calculateDifference($this->seoOld(), $this->seoNew()); } public function averageDifference(): float { return (float) collect([ $this->performanceDifference(), $this->accessibilityDifference(), $this->bestPracticesDifference(), $this->seoDifference(), ])->average(); } protected function calculateDifference(float $old, float $new): float { if ($old == 0) { return 0; } $difference = (($new - $old) / $old) * 100; return round($difference, 1); } } ================================================ FILE: packages/lighthouse/src/Http/Controllers/LighthouseCallbackController.php ================================================ forget('lighthouse:worker:'.$worker); $monitor = LighthouseMonitor::query() ->withoutGlobalScopes() ->findOrFail($monitorId); $teamService->setTeamById($monitor->team_id); $result = $request->only(['categories', 'audits']); $processor->process($monitor, $batchId, $result); } } ================================================ FILE: packages/lighthouse/src/Http/Controllers/LighthouseMonitorController.php ================================================ lighthouseResults()->get(); /** @var ?LighthouseResult $lastResult */ $lastResult = $lastResults->last(); if ($lastResult !== null) { /** @var ?LighthouseResultAudit $screenshotAudit */ $screenshotAudit = $lastResult->audits() ->firstWhere('audit', '=', 'screenshot-thumbnails'); if ($screenshotAudit !== null) { $screenshots = $screenshotAudit->details['items'] ?? []; } } /** @var view-string $view */ $view = 'lighthouse::lighthouse.index'; return view($view, [ 'lighthouseMonitor' => $monitor, 'screenshots' => $screenshots ?? [], 'charts' => [ [ 'audit' => 'first-contentful-paint', 'title' => 'First Contentful Paint', 'description' => 'First Contentful Paint marks the time at which the first text or image is painted.', 'link' => 'https://developer.chrome.com/docs/lighthouse/performance/first-contentful-paint/', ], [ 'audit' => 'largest-contentful-paint', 'title' => 'Largest Contentful Paint', 'description' => 'Largest Contentful Paint marks the time at which the largest text or image is painted.', 'link' => 'https://developer.chrome.com/docs/lighthouse/performance/lighthouse-largest-contentful-paint/', ], [ 'audit' => 'speed-index', 'title' => 'Speed Index', 'description' => ' Speed Index shows how quickly the contents of a page are visibly populated.', 'link' => 'https://developer.chrome.com/docs/lighthouse/performance/speed-index/', ], [ 'audit' => 'interactive', 'title' => 'Time to Interactive', 'description' => 'Time to Interactive is the amount of time it takes for the page to become fully interactive.', 'link' => 'https://developer.chrome.com/docs/lighthouse/performance/interactive/', ], [ 'audit' => 'total-blocking-time', 'title' => 'Total Blocking Time', 'description' => 'Sum of all time periods between FCP and Time to Interactive, when task length exceeded 50ms, expressed in milliseconds.', 'link' => 'https://developer.chrome.com/docs/lighthouse/performance/lighthouse-total-blocking-time/', ], [ 'audit' => 'cumulative-layout-shift', 'title' => 'Cumulative Layout Shift', 'description' => 'Cumulative Layout Shift measures the movement of visible elements within the viewport.', 'link' => 'https://web.dev/articles/cls', ], ], ]); } public function delete(LighthouseMonitor $monitor): mixed { $monitor->delete(); $this->alert( __('Deleted'), __('Lighthouse monitor was successfully deleted'), AlertType::Success ); return response()->redirectToRoute('lighthouse'); } } ================================================ FILE: packages/lighthouse/src/Http/Controllers/LighthouseResultController.php ================================================ $result, ]); } } ================================================ FILE: packages/lighthouse/src/Jobs/AggregateLighthouseBatchJob.php ================================================ onQueue(config('lighthouse.queue')); } public function handle(TeamService $teamService, AggregateLighthouseBatch $aggregator): void { $teamService->setTeamById($this->site->team_id); $aggregator->aggregateBatch($this->site, $this->batchId); } public function uniqueId(): int { return $this->site->id; } } ================================================ FILE: packages/lighthouse/src/Jobs/AggregateLighthouseResultsJob.php ================================================ onQueue(config('lighthouse.queue')); } public function handle(AggregateResults $aggregateResults, TeamService $teamService): void { $teamService->setTeamById($this->site->team_id); $aggregateResults->aggregate( $this->site, $this->from, $this->till ); } public function uniqueId(): string { return $this->site->id.$this->from->getTimestamp(); } } ================================================ FILE: packages/lighthouse/src/Jobs/CheckLighthouseResultJob.php ================================================ onQueue(config('lighthouse.queue')); } public function handle(CheckLighthouseResult $checker, TeamService $teamService): void { $teamService->setTeamById($this->result->team_id); $checker->check($this->result); } public function uniqueId(): int { return $this->result->id; } } ================================================ FILE: packages/lighthouse/src/Jobs/RunLighthouseJob.php ================================================ onQueue(config('lighthouse.queue')); } public function handle(RunLighthouse $lighthouse, TeamService $teamService): void { $teamService->setTeamById($this->site->team_id); $lighthouse->run($this->site, $this->batchId); } public function uniqueId(): int { return $this->site->id; } } ================================================ FILE: packages/lighthouse/src/Livewire/Charts/LighthouseCategoriesChart.php ================================================ 'required', ])->validate(); $this->lighthouseMonitorId = $data['lighthouseMonitorId']; } public function data(): array { $results = LighthouseResult::query() ->where('lighthouse_monitor_id', '=', $this->lighthouseMonitorId) ->whereNull('batch_id') ->get(); $labels = $results->pluck('created_at')->map(fn (Carbon $carbon): string => $carbon->toDateTimeString()); $colors = $this->getChartColors(); return [ 'type' => 'line', 'data' => [ 'labels' => $labels, 'datasets' => [ $this->dataset([ 'label' => 'Performance', 'data' => $results->pluck('performance')->map(fn (float $value): float => $value * 100), 'borderColor' => $colors[0]['border'], // blue 'backgroundColor' => $colors[0]['bg'], 'fill' => true, 'unit' => '%', ]), $this->dataset([ 'label' => 'Accessibility', 'data' => $results->pluck('accessibility')->map(fn (float $value): float => $value * 100), 'borderColor' => $colors[2]['border'], // green 'backgroundColor' => $colors[2]['bg'], 'fill' => true, 'unit' => '%', ]), $this->dataset([ 'label' => 'Best Practices', 'data' => $results->pluck('best_practices')->map(fn (float $value): float => $value * 100), 'borderColor' => $colors[4]['border'], // purple 'backgroundColor' => $colors[4]['bg'], 'fill' => true, 'unit' => '%', ]), $this->dataset([ 'label' => 'SEO', 'data' => $results->pluck('seo')->map(fn (float $value): float => $value * 100), 'borderColor' => $colors[3]['border'], // orange 'backgroundColor' => $colors[3]['bg'], 'fill' => true, 'unit' => '%', ]), ], ], 'options' => [ 'plugins' => [ 'legend' => [ 'display' => true, 'position' => 'top', 'align' => 'start', ], ], 'scales' => [ 'y' => [ 'display' => true, 'min' => 0, 'max' => 100, ], 'x' => [ 'display' => false, ], ], ], ]; } protected function getIdentifier(): string { return Str::slug(get_class($this)).$this->lighthouseMonitorId; } } ================================================ FILE: packages/lighthouse/src/Livewire/Charts/NumericLighthouseChart.php ================================================ 'required', ])->validate(); $this->lighthouseMonitorId = $data['lighthouseMonitorId']; } public function data(): array { $resultIds = LighthouseResult::query() ->select(['id']) ->where('lighthouse_monitor_id', '=', $this->lighthouseMonitorId) ->get() ->pluck('id'); $audits = LighthouseResultAudit::query() ->whereIn('lighthouse_result_id', $resultIds) ->where('audit', '=', $this->audit) ->get(); $audit = $audits->first(); if ($audit === null) { return []; } $title = $audit['title']; $unit = $audit['numericUnit']; $formatter = match ($unit) { 'millisecond' => fn (mixed $value): float => round($value / 1000, 1), default => fn (mixed $value): mixed => $value ?? '-', }; $color = $this->getChartColor(0); // Use first color (blue) return [ 'type' => 'line', 'data' => [ 'labels' => $audits->map(fn (LighthouseResultAudit $audit): string => $audit->created_at?->toDateTimeString('minute') ?? '-')->toArray(), 'datasets' => [ $this->dataset([ 'label' => $title, 'data' => $audits->map(fn (LighthouseResultAudit $audit): string => $formatter($audit['numericValue']))->toArray(), 'borderColor' => $color['border'], 'backgroundColor' => $color['bg'], 'fill' => true, 'unit' => 's', ]), ], ], 'options' => [ 'plugins' => [ 'legend' => [ 'display' => false, ], ], 'scales' => [ 'y' => [ 'display' => true, 'min' => 0, ], 'x' => [ 'display' => false, ], ], ], ]; } protected function getIdentifier(): string { return Str::slug(get_class($this)).$this->lighthouseMonitorId.$this->audit; } } ================================================ FILE: packages/lighthouse/src/Livewire/Forms/LighthouseSiteForm.php ================================================ '', ]; public int $interval = 60 * 24; public function getRules(): array { return array_merge(parent::getRules(), [ 'enabled' => ['boolean', new CanEnableRule(LighthouseMonitor::class)], 'interval' => ['required', 'integer', 'in:'.implode(',', array_keys(config('lighthouse.intervals')))], ] ); } } ================================================ FILE: packages/lighthouse/src/Livewire/LighthouseSiteForm.php ================================================ exists) { $this->authorize('update', $monitor); } else { $this->authorize('create', $monitor); /** @var int $defaultInterval */ $defaultInterval = collect(config('lighthouse.intervals'))->keys()->first() ?? 60 * 24; // @phpstan-ignore-line $this->form->interval = $defaultInterval; } $this->form->fill($monitor->toArray()); $this->lighthouseMonitor = $monitor; } } #[On('save')] public function save(): void { $this->validate(); if ($this->lighthouseMonitor->exists) { $this->authorize('update', $this->lighthouseMonitor); $this->lighthouseMonitor->update($this->form->all()); } else { $this->authorize('create', $this->lighthouseMonitor); $this->lighthouseMonitor = LighthouseMonitor::query()->create( $this->form->all() ); } if (! $this->inline) { $this->alert( __('Saved'), __('Lighthouse monitor was successfully :action', ['action' => $this->lighthouseMonitor->wasRecentlyCreated ? 'created' : 'saved']), AlertType::Success ); $this->redirectRoute('lighthouse.index', ['monitor' => $this->lighthouseMonitor]); } } public function render(): mixed { /** @var view-string $view */ $view = 'lighthouse::livewire.lighthouse-site-form'; return view($view, [ 'updating' => $this->lighthouseMonitor->exists, ]); } } ================================================ FILE: packages/lighthouse/src/Livewire/LighthouseSites.php ================================================ exists(); return view($view, [ 'hasMonitors' => $hasMonitors, ]); } } ================================================ FILE: packages/lighthouse/src/Livewire/Monitor/Dashboard.php ================================================ monitorId = $monitorId; } public function render(): mixed { /** @var CalculateTimeDifference $timeDifference */ $timeDifference = app(CalculateTimeDifference::class); /** @var LighthouseMonitor $monitor */ $monitor = LighthouseMonitor::query()->findOrFail($this->monitorId); $lastResults = $monitor ->lighthouseResults() ->take(10) ->get(); /** @var view-string $view */ $view = 'lighthouse::livewire.monitor.dashboard'; return view($view, [ 'lighthouseMonitor' => $monitor, 'lastResult' => [ 'performance' => $lastResults->average('performance'), 'accessibility' => $lastResults->average('accessibility'), 'best_practices' => $lastResults->average('best_practices'), 'seo' => $lastResults->average('seo'), ], 'difference' => [ '7d' => $timeDifference->calculate($monitor, now()->subDays(7)), '30d' => $timeDifference->calculate($monitor, now()->subMonth()), '90d' => $timeDifference->calculate($monitor, now()->subMonths(3)), '180d' => $timeDifference->calculate($monitor, now()->subMonths(6)), ], ]); } } ================================================ FILE: packages/lighthouse/src/Livewire/Tables/LighthouseMonitorsTable.php ================================================ text(function (LighthouseMonitor $monitor): string { return $monitor->enabled ? __('Enabled') : __('Disabled'); }) ->status(function (LighthouseMonitor $monitor): Status { return $monitor->enabled ? Status::Success : Status::Danger; }), Column::make(__('URL'), 'url') ->sortable() ->searchable(), Column::make(__('Performance'), 'performance') ->displayUsing(fn (?float $value): string => static::scoreDisplay($value)) ->asHtml() ->sortable(function (Builder $builder, Direction $direction): void { if ($direction === Direction::Ascending) { $builder->orderBy('lighthouse_results.performance'); } else { $builder->orderByDesc('lighthouse_results.performance'); } }), Column::make(__('Accessibility'), 'accessibility') ->displayUsing(fn (?float $value): string => static::scoreDisplay($value)) ->asHtml() ->sortable(function (Builder $builder, Direction $direction): void { if ($direction === Direction::Ascending) { $builder->orderBy('lighthouse_results.accessibility'); } else { $builder->orderByDesc('lighthouse_results.accessibility'); } }), Column::make(__('Best Practices'), 'best_practices') ->displayUsing(fn (?float $value): string => static::scoreDisplay($value)) ->asHtml() ->sortable(function (Builder $builder, Direction $direction): void { if ($direction === Direction::Ascending) { $builder->orderBy('lighthouse_results.best_practices'); } else { $builder->orderByDesc('lighthouse_results.best_practices'); } }), Column::make(__('SEO'), 'seo') ->displayUsing(fn (?float $value): string => static::scoreDisplay($value)) ->asHtml() ->sortable(function (Builder $builder, Direction $direction): void { if ($direction === Direction::Ascending) { $builder->orderBy('lighthouse_results.seo'); } else { $builder->orderByDesc('lighthouse_results.seo'); } }), ]; } public static function scoreDisplay(?float $value): string { if ($value === null) { return '-'; } $percentage = round($value * 100); $color = match (true) { $percentage > 80 => 'text-green-light', $percentage >= 60 => 'text-orange-light', default => 'text-red-light' }; return ''.$percentage.'%'; } protected function filters(): array { return [ SelectFilter::make(__('Site'), 'site_id') ->options( Site::query() ->orderBy('url') ->pluck('url', 'id') ->toArray() ), ]; } protected function actions(): array { return [ Action::make(__('Run Lighthouse'), function (Enumerable $models): void { $models->each(fn (LighthouseMonitor $monitor) => RunLighthouseJob::dispatch($monitor)); }, 'run'), Action::make(__('Enable'), function (Enumerable $models): void { foreach ($models as $model) { if (! Gate::allows('create', $model)) { break; } $model->update(['enabled' => true]); } }, 'enable'), Action::make(__('Disable'), function (Enumerable $models): void { $models->each(fn (LighthouseMonitor $monitor) => $monitor->update(['enabled' => false])); }, 'disable'), Action::make(__('Delete'), function (Enumerable $models): void { $models->each(fn (LighthouseMonitor $monitor): ?bool => $monitor->delete()); }, 'delete'), ]; } protected function appliedQuery(): Builder { return parent::appliedQuery() ->leftJoin('lighthouse_results', function (JoinClause $join): void { $join->on('lighthouse_monitors.id', '=', 'lighthouse_results.lighthouse_monitor_id') ->whereRaw('lighthouse_results.id IN (SELECT MAX(id) FROM lighthouse_results GROUP BY lighthouse_monitor_id)'); })->select([ 'lighthouse_monitors.*', 'lighthouse_results.performance', 'lighthouse_results.accessibility', 'lighthouse_results.best_practices', 'lighthouse_results.seo', ]); } protected function link(Model $model): ?string { return route('lighthouse.index', ['monitor' => $model]); } } ================================================ FILE: packages/lighthouse/src/Livewire/Tables/LighthouseResultAuditsTable.php ================================================ resultId = $resultId; } protected function columns(): array { return [ Column::make(__('Audit'), 'title') ->displayUsing(fn (string $audit): string => Str::inlineMarkdown($audit)) ->asHtml() ->sortable(), HoverColumn::make(__('Description'), 'description') ->displayUsing(fn (mixed $value) => Str::markdown($value)) ->asHtml(), HoverColumn::make(__('Explanation'), 'explanation') ->sortable() ->displayUsing(fn (mixed $value) => Str::markdown($value ?? '')) ->asHtml(), Column::make(__('Score'), 'score') ->displayUsing(fn (?float $score) => $score !== null ? ($score * 100).'%' : '-') ->sortable(), Column::make(__('Value'), 'numericValue') ->displayUsing(fn (?float $value) => $value !== null ? round($value, 2) : '-') ->sortable(), Column::make(__('Unit'), 'numericUnit') ->displayUsing(fn (?string $value) => $value !== null ? $value : '-') ->sortable(), ]; } protected function query(): Builder { return parent::query() ->where('lighthouse_result_id', '=', $this->resultId); } } ================================================ FILE: packages/lighthouse/src/Livewire/Tables/LighthouseResultsTable.php ================================================ monitorId = $monitorId; } protected function columns(): array { return [ DateColumn::make(__('Ran At'), 'created_at') ->sortable(), Column::make(__('Performance'), 'performance') ->displayUsing(fn (?float $value): string => $this->scoreDisplay($value)) ->asHtml() ->sortable(), Column::make(__('Accessibility'), 'accessibility') ->displayUsing(fn (?float $value): string => $this->scoreDisplay($value)) ->asHtml() ->sortable(), Column::make(__('Best Practices'), 'best_practices') ->displayUsing(fn (?float $value): string => $this->scoreDisplay($value)) ->asHtml() ->sortable(), Column::make(__('SEO'), 'seo') ->displayUsing(fn (?float $value): string => $this->scoreDisplay($value)) ->asHtml() ->sortable(), ]; } protected function scoreDisplay(?float $value): string { if ($value === null) { return '-'; } $percentage = round($value * 100); $color = match (true) { $percentage > 60 => 'text-orange-light', $percentage > 80 => 'text-green-light', default => 'text-red-light' }; return ''.$percentage.'%'; } protected function link(Model $model): ?string { return route('lighthouse.result.index', ['result' => $model]); } protected function query(): Builder { return parent::query() ->where('lighthouse_monitor_id', '=', $this->monitorId) ->whereNull('batch_id'); } } ================================================ FILE: packages/lighthouse/src/Models/LighthouseMonitor.php ================================================ $lighthouseResults */ #[ObservedBy([TeamObserver::class, LighthouseMonitorObserver::class])] #[ScopedBy([TeamScope::class])] class LighthouseMonitor extends Model { protected $guarded = []; protected $casts = [ 'enabled' => 'bool', 'settings' => 'array', 'next_run' => 'datetime', 'run_started_at' => 'datetime', ]; public function site(): BelongsTo { return $this->belongsTo(Site::class); } public function lighthouseResults(): HasMany { return $this->hasMany(LighthouseResult::class); } } ================================================ FILE: packages/lighthouse/src/Models/LighthouseResult.php ================================================ $audits */ #[ObservedBy([TeamObserver::class])] #[ScopedBy([TeamScope::class])] class LighthouseResult extends Model { use HasDataRetention; use Prunable; protected $guarded = []; protected $casts = [ 'aggregated' => 'bool', ]; public function lighthouseSite(): BelongsTo { return $this->belongsTo(LighthouseMonitor::class, 'lighthouse_monitor_id'); } public function audits(): HasMany { return $this->hasMany(LighthouseResultAudit::class); } public function prunable(): Builder { return static::withoutGlobalScopes()->where('created_at', '<=', $this->retentionPeriod()); } } ================================================ FILE: packages/lighthouse/src/Models/LighthouseResultAudit.php ================================================ 'array', 'warnings' => 'array', 'items' => 'array', 'metricSavings' => 'array', ]; public function lighthouseResult(): BelongsTo { return $this->belongsTo(LighthouseResult::class); } } ================================================ FILE: packages/lighthouse/src/Notifications/CategoryScoreChangedNotification.php ================================================ 'group', 'children' => [ [ 'type' => 'condition', 'condition' => AverageScoreChangesCondition::class, 'operator' => '>=', 'value' => 20, ], ], ]; public function __construct( public LighthouseResult $result, public CategoryResultDifferenceData $data ) {} public function title(): string { return __('Average lighthouse score changed on :url', [ 'url' => $this->result->lighthouseSite->url, ]); } public function description(): string { $performanceOld = $this->data->performanceOld() * 100; $performanceNew = $this->data->performanceNew() * 100; $accessibilityOld = $this->data->accessibilityOld() * 100; $accessibilityNew = $this->data->accessibilityNew() * 100; $bestPracticesOld = $this->data->bestPracticesOld() * 100; $bestPracticesNew = $this->data->bestPracticesNew() * 100; $seoOld = $this->data->seoOld() * 100; $seoNew = $this->data->seoNew() * 100; return __('New values are: Performance :performance, Accessibility :accessibility, Best Practices :best_practices, SEO :seo', [ 'performance' => "$performanceOld% => $performanceNew%", 'accessibility' => "$accessibilityOld% => $accessibilityNew%", 'best_practices' => "$bestPracticesOld% => $bestPracticesNew%", 'seo' => "$seoOld% => $seoNew%", ] ); } public static function info(): ?string { return __('Triggered when any Lighthouse category score changes significantly.'); } public function level(): Level { return $this->mostlyNegative() ? Level::Warning : Level::Success; } protected function mostlyNegative(): bool { return $this->data->averageDifference() < 0; } public function uniqueId(): string|int { return $this->result->id; } public function site(): ?Site { return $this->result->lighthouseSite->site; } } ================================================ FILE: packages/lighthouse/src/Notifications/Conditions/Audit/AuditChangesCondition.php ================================================ =' => 'By at least', '>' => 'By more than', ]; } public function applies( Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta ): bool { /** @var NumericAuditChangedNotification $notification */ $percentChange = abs($notification->percentChanged); return match ($operator) { '>' => $percentChange > $value, '>=' => $percentChange >= $value, default => false, }; } } ================================================ FILE: packages/lighthouse/src/Notifications/Conditions/Audit/AuditDecreasesCondition.php ================================================ =' => 'By at least', '>' => 'By more than', ]; } public function applies( Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta ): bool { /** @var NumericAuditChangedNotification $notification */ $percentChange = $notification->percentChanged; return match ($operator) { '>' => $percentChange < -$value, '>=' => $percentChange <= -$value, default => false, }; } } ================================================ FILE: packages/lighthouse/src/Notifications/Conditions/Audit/AuditIncreasesCondition.php ================================================ =' => 'By at least', '>' => 'By more than', ]; } public function applies( Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta ): bool { /** @var NumericAuditChangedNotification $notification */ $percentChange = $notification->percentChanged; return match ($operator) { '>' => $percentChange > $value, '>=' => $percentChange >= $value, default => false, }; } } ================================================ FILE: packages/lighthouse/src/Notifications/Conditions/Audit/AuditPercentCondition.php ================================================ 'Relative', 'absolute' => 'Absolute', ]; } public function operators(): array { return [ '=' => 'Equal to', '<>' => 'Not equal to', '<' => 'Less than', '<=' => 'Less or equal than', '>' => 'Greater than', '>=' => 'Greater or equal than', ]; } public function applies( Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta ): bool { /** @var NumericAuditChangedNotification $notification */ $percent = $notification->percentChanged; if ($operand === 'absolute') { $percent = abs($percent); } return match ($operator) { '=' => $percent == $value, '<>' => $percent != $value, '<' => $percent < $value, '<=' => $percent <= $value, '>' => $percent > $value, '>=' => $percent >= $value, default => false, }; } } ================================================ FILE: packages/lighthouse/src/Notifications/Conditions/Audit/AuditTypeCondition.php ================================================ 'Equal to', '<>' => 'Not equal to', ]; } public function applies( Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta ): bool { /** @var NumericAuditChangedNotification $notification */ $audit = $notification->audit->audit; return match ($operator) { '=' => $audit == $value, '<>' => $audit != $value, default => false, }; } public function options(): array { return cache()->remember( 'audit-type-condition:options', now()->addDay(), function (): array { return LighthouseResultAudit::query() ->whereNotNull('numericValue') ->select('audit', 'title', 'numericUnit') ->distinct() ->get() ->mapWithKeys(fn (LighthouseResultAudit $audit) => [$audit->audit => $audit->title.' ('.$audit->numericUnit.')']) ->toArray(); } ); } } ================================================ FILE: packages/lighthouse/src/Notifications/Conditions/Audit/AuditValueCondition.php ================================================ 'New value', 'old' => 'Old value', ]; } public function operators(): array { return [ '=' => 'Equal to', '<>' => 'Not equal to', '<' => 'Less than', '<=' => 'Less than or equal to', '>' => 'Greater than', '>=' => 'Greater than or equal to', ]; } public function applies( Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta ): bool { /** @var NumericAuditChangedNotification $notification */ $auditValue = $operand === 'old' ? $notification->previous : $notification->current; return match ($operator) { '=' => $auditValue == $value, '<>' => $auditValue != $value, '<' => $auditValue < $value, '<=' => $auditValue <= $value, '>' => $auditValue > $value, '>=' => $auditValue >= $value, default => false, }; } } ================================================ FILE: packages/lighthouse/src/Notifications/Conditions/Category/AccessibilityPercentScoreCondition.php ================================================ data->accessibilityDifference(); } } ================================================ FILE: packages/lighthouse/src/Notifications/Conditions/Category/AccessibilityScoreDecreasesCondition.php ================================================ =' => 'By at least', '>' => 'By more than', ]; } public function applies( Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta ): bool { /** @var CategoryScoreChangedNotification $notification */ $change = $notification->data->accessibilityDifference(); return match ($operator) { '>' => $change < -$value, '>=' => $change <= -$value, default => false, }; } } ================================================ FILE: packages/lighthouse/src/Notifications/Conditions/Category/AccessibilityScoreIncreasesCondition.php ================================================ =' => 'By at least', '>' => 'By more than', ]; } public function applies( Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta ): bool { /** @var CategoryScoreChangedNotification $notification */ $change = $notification->data->accessibilityDifference(); return match ($operator) { '>' => $change > $value, '>=' => $change >= $value, default => false, }; } } ================================================ FILE: packages/lighthouse/src/Notifications/Conditions/Category/AccessibilityScoreValueCondition.php ================================================ 'New value', 'old' => 'Old value', ]; } public function operators(): array { return [ '=' => 'Equal to', '<>' => 'Not equal to', '<' => 'Less than', '<=' => 'Less than or equal to', '>' => 'Greater than', '>=' => 'Greater than or equal to', ]; } public function applies( Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta ): bool { /** @var CategoryScoreChangedNotification $notification */ $score = $operand === 'old' ? $notification->data->accessibilityOld() * 100 : $notification->data->accessibilityNew() * 100; return match ($operator) { '=' => $score == $value, '<>' => $score != $value, '<' => $score < $value, '<=' => $score <= $value, '>' => $score > $value, '>=' => $score >= $value, default => false, }; } } ================================================ FILE: packages/lighthouse/src/Notifications/Conditions/Category/AverageScoreChangesCondition.php ================================================ =' => 'By at least', '>' => 'By more than', ]; } public function applies( Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta ): bool { /** @var CategoryScoreChangedNotification $notification */ $change = abs($notification->data->averageDifference()); return match ($operator) { '>' => $change > $value, '>=' => $change >= $value, default => false, }; } } ================================================ FILE: packages/lighthouse/src/Notifications/Conditions/Category/AverageScoreCondition.php ================================================ 'Relative', 'absolute' => 'Absolute', ]; } public function operators(): array { return [ '=' => 'Equal to', '<>' => 'Not equal to', '<' => 'Less than', '<=' => 'Less or equal than', '>' => 'Greater than', '>=' => 'Greater or equal than', ]; } public function applies( Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta ): bool { /** @var CategoryScoreChangedNotification $notification */ $averageScore = $notification->data->averageDifference(); if ($operand === 'absolute') { $averageScore = abs($averageScore); } return match ($operator) { '=' => $averageScore == $value, '<>' => $averageScore != $value, '<' => $averageScore < $value, '<=' => $averageScore <= $value, '>' => $averageScore > $value, '>=' => $averageScore >= $value, default => false, }; } } ================================================ FILE: packages/lighthouse/src/Notifications/Conditions/Category/AverageScoreDecreasesCondition.php ================================================ =' => 'By at least', '>' => 'By more than', ]; } public function applies( Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta ): bool { /** @var CategoryScoreChangedNotification $notification */ $change = $notification->data->averageDifference(); return match ($operator) { '>' => $change < -$value, '>=' => $change <= -$value, default => false, }; } } ================================================ FILE: packages/lighthouse/src/Notifications/Conditions/Category/AverageScoreIncreasesCondition.php ================================================ =' => 'By at least', '>' => 'By more than', ]; } public function applies( Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta ): bool { /** @var CategoryScoreChangedNotification $notification */ $change = $notification->data->averageDifference(); return match ($operator) { '>' => $change > $value, '>=' => $change >= $value, default => false, }; } } ================================================ FILE: packages/lighthouse/src/Notifications/Conditions/Category/AverageScoreValueCondition.php ================================================ 'New value', 'old' => 'Old value', ]; } public function operators(): array { return [ '=' => 'Equal to', '<>' => 'Not equal to', '<' => 'Less than', '<=' => 'Less than or equal to', '>' => 'Greater than', '>=' => 'Greater than or equal to', ]; } public function applies( Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta ): bool { /** @var CategoryScoreChangedNotification $notification */ $scores = $operand === 'old' ? [ $notification->data->performanceOld(), $notification->data->accessibilityOld(), $notification->data->bestPracticesOld(), $notification->data->seoOld(), ] : [ $notification->data->performanceNew(), $notification->data->accessibilityNew(), $notification->data->bestPracticesNew(), $notification->data->seoNew(), ]; $averageScore = collect($scores)->average() * 100; return match ($operator) { '=' => $averageScore == $value, '<>' => $averageScore != $value, '<' => $averageScore < $value, '<=' => $averageScore <= $value, '>' => $averageScore > $value, '>=' => $averageScore >= $value, default => false, }; } } ================================================ FILE: packages/lighthouse/src/Notifications/Conditions/Category/BestPracticesPercentScoreCondition.php ================================================ data->bestPracticesDifference(); } } ================================================ FILE: packages/lighthouse/src/Notifications/Conditions/Category/BestPracticesScoreDecreasesCondition.php ================================================ =' => 'By at least', '>' => 'By more than', ]; } public function applies( Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta ): bool { /** @var CategoryScoreChangedNotification $notification */ $change = $notification->data->bestPracticesDifference(); return match ($operator) { '>' => $change < -$value, '>=' => $change <= -$value, default => false, }; } } ================================================ FILE: packages/lighthouse/src/Notifications/Conditions/Category/BestPracticesScoreIncreasesCondition.php ================================================ =' => 'By at least', '>' => 'By more than', ]; } public function applies( Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta ): bool { /** @var CategoryScoreChangedNotification $notification */ $change = $notification->data->bestPracticesDifference(); return match ($operator) { '>' => $change > $value, '>=' => $change >= $value, default => false, }; } } ================================================ FILE: packages/lighthouse/src/Notifications/Conditions/Category/BestPracticesScoreValueCondition.php ================================================ 'New value', 'old' => 'Old value', ]; } public function operators(): array { return [ '=' => 'Equal to', '<>' => 'Not equal to', '<' => 'Less than', '<=' => 'Less than or equal to', '>' => 'Greater than', '>=' => 'Greater than or equal to', ]; } public function applies( Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta ): bool { /** @var CategoryScoreChangedNotification $notification */ $score = $operand === 'old' ? $notification->data->bestPracticesOld() * 100 : $notification->data->bestPracticesNew() * 100; return match ($operator) { '=' => $score == $value, '<>' => $score != $value, '<' => $score < $value, '<=' => $score <= $value, '>' => $score > $value, '>=' => $score >= $value, default => false, }; } } ================================================ FILE: packages/lighthouse/src/Notifications/Conditions/Category/PerformancePercentScoreCondition.php ================================================ data->performanceDifference(); } } ================================================ FILE: packages/lighthouse/src/Notifications/Conditions/Category/PerformanceScoreDecreasesCondition.php ================================================ =' => 'By at least', '>' => 'By more than', ]; } public function applies( Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta ): bool { /** @var CategoryScoreChangedNotification $notification */ $change = $notification->data->performanceDifference(); return match ($operator) { '>' => $change < -$value, '>=' => $change <= -$value, default => false, }; } } ================================================ FILE: packages/lighthouse/src/Notifications/Conditions/Category/PerformanceScoreIncreasesCondition.php ================================================ =' => 'By at least', '>' => 'By more than', ]; } public function applies( Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta ): bool { /** @var CategoryScoreChangedNotification $notification */ $change = $notification->data->performanceDifference(); return match ($operator) { '>' => $change > $value, '>=' => $change >= $value, default => false, }; } } ================================================ FILE: packages/lighthouse/src/Notifications/Conditions/Category/PerformanceScoreValueCondition.php ================================================ 'New value', 'old' => 'Old value', ]; } public function operators(): array { return [ '=' => 'Equal to', '<>' => 'Not equal to', '<' => 'Less than', '<=' => 'Less than or equal to', '>' => 'Greater than', '>=' => 'Greater than or equal to', ]; } public function applies( Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta ): bool { /** @var CategoryScoreChangedNotification $notification */ $score = $operand === 'old' ? $notification->data->performanceOld() * 100 : $notification->data->performanceNew() * 100; return match ($operator) { '=' => $score == $value, '<>' => $score != $value, '<' => $score < $value, '<=' => $score <= $value, '>' => $score > $value, '>=' => $score >= $value, default => false, }; } } ================================================ FILE: packages/lighthouse/src/Notifications/Conditions/Category/ScoreCondition.php ================================================ 'Relative', 'absolute' => 'Absolute', ]; } public function operators(): array { return [ '=' => 'Equal to', '<>' => 'Not equal to', '<' => 'Less than', '<=' => 'Less or equal than', '>' => 'Greater than', '>=' => 'Greater or equal than', ]; } public function applies( Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta ): bool { /** @var CategoryScoreChangedNotification $notification */ $score = $this->score($notification); if ($operand === 'absolute') { $score = abs($score); } return match ($operator) { '=' => $score == $value, '<>' => $score != $value, '<' => $score < $value, '<=' => $score <= $value, '>' => $score > $value, '>=' => $score >= $value, default => false, }; } abstract protected function score(CategoryScoreChangedNotification $notification): float; } ================================================ FILE: packages/lighthouse/src/Notifications/Conditions/Category/SeoPercentPercentScoreCondition.php ================================================ data->seoDifference(); } } ================================================ FILE: packages/lighthouse/src/Notifications/Conditions/Category/SeoScoreDecreasesCondition.php ================================================ =' => 'By at least', '>' => 'By more than', ]; } public function applies( Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta ): bool { /** @var CategoryScoreChangedNotification $notification */ $change = $notification->data->seoDifference(); return match ($operator) { '>' => $change < -$value, '>=' => $change <= -$value, default => false, }; } } ================================================ FILE: packages/lighthouse/src/Notifications/Conditions/Category/SeoScoreIncreasesCondition.php ================================================ =' => 'By at least', '>' => 'By more than', ]; } public function applies( Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta ): bool { /** @var CategoryScoreChangedNotification $notification */ $change = $notification->data->seoDifference(); return match ($operator) { '>' => $change > $value, '>=' => $change >= $value, default => false, }; } } ================================================ FILE: packages/lighthouse/src/Notifications/Conditions/Category/SeoScoreValueCondition.php ================================================ 'New value', 'old' => 'Old value', ]; } public function operators(): array { return [ '=' => 'Equal to', '<>' => 'Not equal to', '<' => 'Less than', '<=' => 'Less than or equal to', '>' => 'Greater than', '>=' => 'Greater than or equal to', ]; } public function applies( Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta ): bool { /** @var CategoryScoreChangedNotification $notification */ $score = $operand === 'old' ? $notification->data->seoOld() * 100 : $notification->data->seoNew() * 100; return match ($operator) { '=' => $score == $value, '<>' => $score != $value, '<' => $score < $value, '<=' => $score <= $value, '>' => $score > $value, '>=' => $score >= $value, default => false, }; } } ================================================ FILE: packages/lighthouse/src/Notifications/NumericAuditChangedNotification.php ================================================ 'group', 'children' => [ [ 'type' => 'condition', 'condition' => AuditChangesCondition::class, 'operator' => '>=', 'value' => 10, ], ], ]; public function __construct( public LighthouseResultAudit $audit, public float $percentChanged, public float $previous, public float $current, ) {} public function title(): string { return __('Lighthouse numeric audit \':audit\' on :url changed by :percent %', [ 'audit' => $this->audit->title, 'url' => $this->audit->lighthouseResult->lighthouseSite->url ?? '?', 'percent' => round($this->percentChanged), ]); } public function description(): string { return __('Raw value changed from from :previous to :current', [ 'previous' => $this->roundRawValue($this->previous), 'current' => $this->roundRawValue($this->current), ]); } public static function info(): ?string { return __('Triggered when a specific Lighthouse audit metric changes.'); } public function site(): ?Site { return $this->audit->lighthouseResult?->lighthouseSite?->site; } public function uniqueId(): string|int { return $this->audit->id; } protected function roundRawValue(float $rawValue): float { if ($rawValue > 10) { return round($rawValue); } if ($rawValue > 0) { return round($rawValue, 2); } if ($rawValue == 0) { return 0.00; } $strNumber = rtrim(rtrim(sprintf('%.10f', $rawValue), '0'), '.'); return (float) $strNumber; } } ================================================ FILE: packages/lighthouse/src/Observers/LighthouseMonitorObserver.php ================================================ registerConfig(); } protected function registerConfig(): static { $this->mergeConfigFrom(__DIR__.'/../config/lighthouse.php', 'lighthouse'); return $this; } public function boot(): void { $this ->bootConfig() ->bootMigrations() ->bootCommands() ->bootViews() ->bootLivewire() ->bootRoutes() ->bootNavigation() ->bootNotifications() ->bootGates() ->bootPolicies(); } protected function bootConfig(): static { $this->publishes([ __DIR__.'/../config/lighthouse.php' => config_path('lighthouse.php'), ], 'config'); return $this; } protected function bootMigrations(): static { $this->loadMigrationsFrom(__DIR__.'/../database/migrations'); return $this; } protected function bootCommands(): static { if ($this->app->runningInConsole()) { $this->commands([ LighthouseCommand::class, ScheduleLighthouseCommand::class, CheckLighthouseCommand::class, AggregateLighthouseResultsCommand::class, AggregateLighthouseBatchCommand::class, ]); } return $this; } protected function bootViews(): static { $this->loadViewsFrom(__DIR__.'/../resources/views', 'lighthouse'); return $this; } protected function bootLivewire(): static { Livewire::component('lighthouse', LighthouseSites::class); Livewire::component('lighthouse-sites-table', LighthouseMonitorsTable::class); Livewire::component('lighthouse-results-table', LighthouseResultsTable::class); Livewire::component('lighthouse-site-form', LighthouseSiteForm::class); Livewire::component('lighthouse-categories-chart', LighthouseCategoriesChart::class); Livewire::component('lighthouse-result-audits-table', LighthouseResultAuditsTable::class); Livewire::component('lighthouse-numeric-chart', NumericLighthouseChart::class); Livewire::component('lighthouse-monitor-dashboard', Dashboard::class); return $this; } protected function bootRoutes(): static { if (! $this->app->routesAreCached()) { Route::middleware(['web', 'auth']) ->group(fn () => $this->loadRoutesFrom(__DIR__.'/../routes/web.php')); Route::prefix('api/v1/lighthouse') ->group(fn () => $this->loadRoutesFrom(__DIR__.'/../routes/api.php')); } return $this; } protected function bootNavigation(): static { Navigation::path(__DIR__.'/../resources/navigation.php'); return $this; } protected function bootNotifications(): static { NotificationRegistry::registerNotification([ CategoryScoreChangedNotification::class, NumericAuditChangedNotification::class, ]); NotificationRegistry::registerCondition(CategoryScoreChangedNotification::class, [ SiteCondition::class, // Change-based conditions (new, clearer) AverageScoreIncreasesCondition::class, AverageScoreDecreasesCondition::class, AverageScoreChangesCondition::class, PerformanceScoreIncreasesCondition::class, PerformanceScoreDecreasesCondition::class, AccessibilityScoreIncreasesCondition::class, AccessibilityScoreDecreasesCondition::class, BestPracticesScoreIncreasesCondition::class, BestPracticesScoreDecreasesCondition::class, SeoScoreIncreasesCondition::class, SeoScoreDecreasesCondition::class, // Absolute value conditions AverageScoreValueCondition::class, PerformanceScoreValueCondition::class, AccessibilityScoreValueCondition::class, BestPracticesScoreValueCondition::class, SeoScoreValueCondition::class, // Legacy conditions (kept for backward compatibility) AverageScoreCondition::class, AccessibilityPercentScoreCondition::class, BestPracticesPercentScoreCondition::class, PerformancePercentScoreCondition::class, SeoPercentPercentScoreCondition::class, ]); NotificationRegistry::registerCondition(NumericAuditChangedNotification::class, [ // Change-based conditions (new, clearer) AuditIncreasesCondition::class, AuditDecreasesCondition::class, AuditChangesCondition::class, // Absolute value condition AuditValueCondition::class, // Legacy condition (kept for backward compatibility) AuditPercentCondition::class, AuditTypeCondition::class, ]); return $this; } protected function bootGates(): static { if (ce()) { Gate::define('use-lighthouse', function (User $user): bool { return ce(); }); } return $this; } protected function bootPolicies(): static { if (ce()) { Gate::policy(LighthouseMonitor::class, AllowAllPolicy::class); } return $this; } } ================================================ FILE: packages/lighthouse/testbench.yaml ================================================ providers: - Vigilant\Lighthouse\ServiceProvider ================================================ FILE: packages/lighthouse/tests/Actions/AggregateResultsTest.php ================================================ create([ 'team_id' => 1, 'url' => 'https://govigilant.io', 'settings' => [], 'interval' => '0 * * * *', ]); for ($i = 0; $i < 5; $i++) { $site->lighthouseResults()->create([ 'performance' => 1, 'accessibility' => 1, 'best_practices' => 1, 'seo' => 1, 'created_at' => now()->subHours($i), 'updated_at' => now()->subHours($i), ]); } for ($i = 5; $i < 10; $i++) { $site->lighthouseResults()->create([ 'performance' => 0.5, 'accessibility' => 0.5, 'best_practices' => 0.5, 'seo' => 0.5, 'created_at' => now()->subHours($i), 'updated_at' => now()->subHours($i), ]); } /** @var AggregateResults $action */ $action = app(AggregateResults::class); $action->aggregate($site, now()->subHours(10), now()); $this->assertCount(1, $site->lighthouseResults); $this->assertNotNull($site->lighthouseResults->first()); $this->assertNotNull($site->lighthouseResults->first()); $this->assertNotNull($site->lighthouseResults->first()); $this->assertNotNull($site->lighthouseResults->first()); $this->assertEquals(0.75, $site->lighthouseResults->first()->performance); $this->assertEquals(0.75, $site->lighthouseResults->first()->accessibility); $this->assertEquals(0.75, $site->lighthouseResults->first()->best_practices); $this->assertEquals(0.75, $site->lighthouseResults->first()->seo); } } ================================================ FILE: packages/lighthouse/tests/Actions/CalculateTimeDifferenceTest.php ================================================ create([ 'team_id' => 1, 'url' => 'https://govigilant.io', 'settings' => [], 'interval' => '0 * * * *', ]); $site->lighthouseResults()->create([ 'performance' => 1, 'accessibility' => 1, 'best_practices' => 1, 'seo' => 1, 'created_at' => now()->subHours(24), 'updated_at' => now()->subHours(24), ]); $site->lighthouseResults()->create([ 'performance' => 1, 'accessibility' => 1, 'best_practices' => 1, 'seo' => 1, 'created_at' => now()->subHours(23), 'updated_at' => now()->subHours(23), ]); $site->lighthouseResults()->create([ 'performance' => 1, 'accessibility' => 1, 'best_practices' => 1, 'seo' => 1, 'created_at' => now()->subHours(22), 'updated_at' => now()->subHours(22), ]); $site->lighthouseResults()->create([ 'performance' => 1, 'accessibility' => 1, 'best_practices' => 1, 'seo' => 1, 'created_at' => now()->subHours(21), 'updated_at' => now()->subHours(21), ]); $site->lighthouseResults()->create([ 'performance' => 1, 'accessibility' => 1, 'best_practices' => 1, 'seo' => 1, 'created_at' => now()->subHours(20), 'updated_at' => now()->subHours(20), ]); $site->lighthouseResults()->create([ 'performance' => 1, 'accessibility' => 1, 'best_practices' => 1, 'seo' => 1, 'created_at' => now()->subHours(19), 'updated_at' => now()->subHours(19), ]); $site->lighthouseResults()->create([ 'performance' => 1, 'accessibility' => 1, 'best_practices' => 1, 'seo' => 1, 'created_at' => now()->subHours(18), 'updated_at' => now()->subHours(18), ]); $site->lighthouseResults()->create([ 'performance' => 1, 'accessibility' => 1, 'best_practices' => 1, 'seo' => 1, 'created_at' => now()->subHours(17), 'updated_at' => now()->subHours(17), ]); $site->lighthouseResults()->create([ 'performance' => 1, 'accessibility' => 1, 'best_practices' => 1, 'seo' => 1, 'created_at' => now()->subHours(16), 'updated_at' => now()->subHours(16), ]); $site->lighthouseResults()->create([ 'performance' => 0.5, 'accessibility' => 0.5, 'best_practices' => 0.5, 'seo' => 0.5, 'created_at' => now()->subHours(15), 'updated_at' => now()->subHours(15), ]); $site->lighthouseResults()->create([ 'performance' => 0.5, 'accessibility' => 0.5, 'best_practices' => 0.5, 'seo' => 0.5, 'created_at' => now()->subHours(14), 'updated_at' => now()->subHours(14), ]); /** @var CalculateTimeDifference $action */ $action = app(CalculateTimeDifference::class); $result = $action->calculate($site, now()->subHours(24)); $this->assertNotNull($result); $this->assertEquals(0.5, $result->performanceNew()); $this->assertEquals(1, $result->performanceOld()); $this->assertEquals(-50, $result->performanceDifference()); } } ================================================ FILE: packages/lighthouse/tests/Actions/CheckLighthouseResultAuditTest.php ================================================ create([ 'team_id' => 1, 'url' => 'https://govigilant.io', 'settings' => [], 'interval' => '0 * * * *', ]); /** @var LighthouseResult $result */ $result = $site->lighthouseResults()->create([ 'performance' => 0.5, 'accessibility' => 0.5, 'best_practices' => 0.5, 'seo' => 0.5, 'created_at' => now(), 'updated_at' => now(), ]); for ($i = 0; $i < 100; $i++) { $result->audits()->create([ 'audit' => 'test', 'title' => 'test', 'explanation' => 'test', 'description' => 'test', 'score' => 1, 'scoreDisplayMode' => 'numeric', 'numericValue' => $i * 10, ]); } /** @var LighthouseResultAudit $audit */ $audit = $result->audits()->create([ 'audit' => 'test', 'title' => 'test', 'explanation' => 'test', 'description' => 'test', 'score' => 1, 'scoreDisplayMode' => 'numeric', 'numericValue' => 100, ]); /** @var CheckLighthouseResultAudit $action */ $action = app(CheckLighthouseResultAudit::class); $action->check($audit); $this->assertTrue(NumericAuditChangedNotification::wasDispatched(function ( NumericAuditChangedNotification $notification ): bool { return round($notification->percentChanged) == 15; })); } } ================================================ FILE: packages/lighthouse/tests/Actions/CheckLighthouseResultTest.php ================================================ mock(CheckLighthouseResultAudit::class, function (MockInterface $mock): void { $mock->shouldReceive('check')->andReturn(); }); /** @var LighthouseMonitor $site */ $site = LighthouseMonitor::query()->create([ 'team_id' => 1, 'url' => 'https://govigilant.io', 'settings' => [], 'interval' => '0 * * * *', ]); for ($i = 0; $i < 4; $i++) { $site->lighthouseResults()->create([ 'performance' => 0.5, 'accessibility' => 0.5, 'best_practices' => 0.5, 'seo' => 0.5, 'created_at' => now(), 'updated_at' => now(), ]); } for ($i = 0; $i < 12; $i++) { $site->lighthouseResults()->create([ 'performance' => 0.7, 'accessibility' => 0.7, 'best_practices' => 0.7, 'seo' => 0.5, 'created_at' => now(), 'updated_at' => now(), ]); } /** @var LighthouseResult $lastResult */ $lastResult = $site->lighthouseResults->last(); /** @var CheckLighthouseResult $action */ $action = app(CheckLighthouseResult::class); $action->check($lastResult); $this->assertTrue(CategoryScoreChangedNotification::wasDispatched()); } } ================================================ FILE: packages/lighthouse/tests/Actions/RunLighthouseTest.php ================================================ set('lighthouse.workers', ['worker']); config()->set('lighthouse.lighthouse_app_url', 'app'); Http::fake([ 'worker/lighthouse' => Http::response([], 200), ])->preventStrayRequests(); $monitor = LighthouseMonitor::query()->create([ 'enabled' => true, 'team_id' => 1, 'url' => 'vigilant', 'settings' => [], 'interval' => 60, ]); $action = app(RunLighthouse::class); $action->run($monitor, null); $monitor->refresh(); $this->assertNotNull($monitor->next_run); $this->assertNotNull($monitor->run_started_at); Http::assertSent(function (Request $request) { return $request->url() === 'worker/lighthouse' && $request['website'] === 'vigilant'; }); } #[Test] public function it_gets_worker(): void { config()->set('lighthouse.workers', [ 'worker_1', 'worker_2', 'worker_3', ]); $action = app(RunLighthouse::class); $this->assertEquals('worker_1', $action->getAvailableWorker()); $this->assertEquals('worker_2', $action->getAvailableWorker()); $this->assertEquals('worker_3', $action->getAvailableWorker()); for ($i = 0; $i < 10; $i++) { $this->assertNull($action->getAvailableWorker()); } cache()->forget('lighthouse:worker:worker_1'); $this->assertEquals('worker_1', $action->getAvailableWorker()); cache()->flush(); $this->assertEquals('worker_1', $action->getAvailableWorker()); $this->assertEquals('worker_2', $action->getAvailableWorker()); $this->assertEquals('worker_3', $action->getAvailableWorker()); } } ================================================ FILE: packages/lighthouse/tests/Data/CategoryResultDifferenceDataTest.php ================================================ 0.5, 'performance_new' => 1, 'accessibility_old' => 1, 'accessibility_new' => 0.5, 'best_practices_old' => 1, 'best_practices_new' => 1, 'seo_old' => 0, 'seo_new' => 0, ]); $this->assertEquals(100, $data->performanceDifference()); $this->assertEquals(-50, $data->accessibilityDifference()); $this->assertEquals(0, $data->bestPracticesDifference()); $this->assertEquals(0, $data->seoDifference()); } } ================================================ FILE: packages/lighthouse/tests/Notifications/Conditions/Audit/AuditChangeConditionsTest.php ================================================ makeNotification(100, 150, 50); $this->assertTrue($condition->applies($notification, null, '>=', 40, null)); $this->assertTrue($condition->applies($notification, null, '>=', 50, null)); $this->assertFalse($condition->applies($notification, null, '>=', 60, null)); $this->assertTrue($condition->applies($notification, null, '>', 40, null)); $this->assertFalse($condition->applies($notification, null, '>', 50, null)); } #[Test] public function it_checks_audit_decreases(): void { $condition = new AuditDecreasesCondition; // 33.33% decrease $notification = $this->makeNotification(150, 100, -33.33); $this->assertTrue($condition->applies($notification, null, '>=', 30, null)); $this->assertTrue($condition->applies($notification, null, '>=', 33, null)); $this->assertFalse($condition->applies($notification, null, '>=', 40, null)); $this->assertTrue($condition->applies($notification, null, '>', 30, null)); $this->assertFalse($condition->applies($notification, null, '>', 33.33, null)); } #[Test] public function it_checks_audit_changes_either_direction(): void { $conditionIncrease = new AuditChangesCondition; $conditionDecrease = new AuditChangesCondition; $notificationIncrease = $this->makeNotification(100, 150, 50); $notificationDecrease = $this->makeNotification(150, 100, -33.33); $this->assertTrue($conditionIncrease->applies($notificationIncrease, null, '>=', 40, null)); $this->assertTrue($conditionDecrease->applies($notificationDecrease, null, '>=', 30, null)); $this->assertTrue($conditionIncrease->applies($notificationIncrease, null, '>', 40, null)); $this->assertFalse($conditionIncrease->applies($notificationIncrease, null, '>', 50, null)); } #[Test] public function it_does_not_trigger_increase_on_decrease(): void { $condition = new AuditIncreasesCondition; $notification = $this->makeNotification(150, 100, -33.33); $this->assertFalse($condition->applies($notification, null, '>=', 10, null)); } #[Test] public function it_does_not_trigger_decrease_on_increase(): void { $condition = new AuditDecreasesCondition; $notification = $this->makeNotification(100, 150, 50); $this->assertFalse($condition->applies($notification, null, '>=', 10, null)); } protected function makeNotification(float $previous, float $current, float $percentChanged): NumericAuditChangedNotification { $monitor = LighthouseMonitor::query()->create([ 'team_id' => 1, 'url' => 'https://example.com', 'settings' => [], 'interval' => '0 * * * *', ]); $result = LighthouseResult::query()->create([ 'lighthouse_monitor_id' => $monitor->id, 'performance' => 0.7, 'accessibility' => 0.7, 'best_practices' => 0.7, 'seo' => 0.7, ]); $audit = LighthouseResultAudit::query()->create([ 'lighthouse_result_id' => $result->id, 'team_id' => 1, 'audit' => 'first-contentful-paint', 'title' => 'First Contentful Paint', 'description' => 'Test audit', 'score' => 0.5, 'scoreDisplayMode' => 'numeric', 'numericValue' => $current, 'numericUnit' => 'millisecond', ]); return new NumericAuditChangedNotification($audit, $percentChanged, $previous, $current); } } ================================================ FILE: packages/lighthouse/tests/Notifications/Conditions/Audit/AuditValueConditionTest.php ================================================ makeNotification(100, 150, 50); $this->assertTrue($condition->applies($notification, 'new', '>', 140, null)); $this->assertFalse($condition->applies($notification, 'new', '>', 150, null)); $this->assertTrue($condition->applies($notification, 'new', '>=', 150, null)); } #[Test] public function it_checks_new_value_less_than_threshold(): void { $condition = new AuditValueCondition; $notification = $this->makeNotification(150, 100, -33.33); $this->assertTrue($condition->applies($notification, 'new', '<', 110, null)); $this->assertFalse($condition->applies($notification, 'new', '<', 100, null)); $this->assertTrue($condition->applies($notification, 'new', '<=', 100, null)); } #[Test] public function it_checks_old_value_greater_than_threshold(): void { $condition = new AuditValueCondition; $notification = $this->makeNotification(150, 100, -33.33); $this->assertTrue($condition->applies($notification, 'old', '>', 140, null)); $this->assertFalse($condition->applies($notification, 'old', '>', 150, null)); $this->assertTrue($condition->applies($notification, 'old', '>=', 150, null)); } #[Test] public function it_checks_old_value_less_than_threshold(): void { $condition = new AuditValueCondition; $notification = $this->makeNotification(100, 150, 50); $this->assertTrue($condition->applies($notification, 'old', '<', 110, null)); $this->assertFalse($condition->applies($notification, 'old', '<', 100, null)); $this->assertTrue($condition->applies($notification, 'old', '<=', 100, null)); } #[Test] public function it_checks_equality(): void { $condition = new AuditValueCondition; $notification = $this->makeNotification(100, 100, 0); $this->assertTrue($condition->applies($notification, 'new', '=', 100, null)); $this->assertFalse($condition->applies($notification, 'new', '=', 150, null)); $this->assertTrue($condition->applies($notification, 'new', '<>', 150, null)); } protected function makeNotification(float $previous, float $current, float $percentChanged): NumericAuditChangedNotification { $monitor = LighthouseMonitor::query()->create([ 'team_id' => 1, 'url' => 'https://example.com', 'settings' => [], 'interval' => '0 * * * *', ]); $result = LighthouseResult::query()->create([ 'lighthouse_monitor_id' => $monitor->id, 'performance' => 0.7, 'accessibility' => 0.7, 'best_practices' => 0.7, 'seo' => 0.7, ]); $audit = LighthouseResultAudit::query()->create([ 'lighthouse_result_id' => $result->id, 'team_id' => 1, 'audit' => 'first-contentful-paint', 'title' => 'First Contentful Paint', 'description' => 'Test audit', 'score' => 0.5, 'scoreDisplayMode' => 'numeric', 'numericValue' => $current, 'numericUnit' => 'millisecond', ]); return new NumericAuditChangedNotification($audit, $percentChanged, $previous, $current); } } ================================================ FILE: packages/lighthouse/tests/Notifications/Conditions/Category/AverageScoreChangeConditionsTest.php ================================================ makeNotification(0.5, 0.6); $this->assertTrue($condition->applies($notification, null, '>=', 15, null)); $this->assertTrue($condition->applies($notification, null, '>=', 20, null)); $this->assertFalse($condition->applies($notification, null, '>=', 25, null)); $this->assertTrue($condition->applies($notification, null, '>', 15, null)); $this->assertFalse($condition->applies($notification, null, '>', 20, null)); } #[Test] public function it_checks_score_decreases(): void { $condition = new AverageScoreDecreasesCondition; // 20% decrease $notification = $this->makeNotification(0.6, 0.5); $this->assertTrue($condition->applies($notification, null, '>=', 15, null)); $this->assertTrue($condition->applies($notification, null, '>=', 16.7, null)); $this->assertFalse($condition->applies($notification, null, '>=', 20, null)); $this->assertTrue($condition->applies($notification, null, '>', 15, null)); $this->assertFalse($condition->applies($notification, null, '>', 16.7, null)); } #[Test] public function it_checks_score_changes_either_direction(): void { $conditionIncrease = new AverageScoreChangesCondition; $conditionDecrease = new AverageScoreChangesCondition; $notificationIncrease = $this->makeNotification(0.5, 0.6); $notificationDecrease = $this->makeNotification(0.6, 0.5); $this->assertTrue($conditionIncrease->applies($notificationIncrease, null, '>=', 15, null)); $this->assertTrue($conditionDecrease->applies($notificationDecrease, null, '>=', 15, null)); $this->assertTrue($conditionIncrease->applies($notificationIncrease, null, '>', 15, null)); $this->assertFalse($conditionIncrease->applies($notificationIncrease, null, '>', 20, null)); } #[Test] public function it_does_not_trigger_increase_on_decrease(): void { $condition = new AverageScoreIncreasesCondition; $notification = $this->makeNotification(0.6, 0.5); $this->assertFalse($condition->applies($notification, null, '>=', 10, null)); } #[Test] public function it_does_not_trigger_decrease_on_increase(): void { $condition = new AverageScoreDecreasesCondition; $notification = $this->makeNotification(0.5, 0.6); $this->assertFalse($condition->applies($notification, null, '>=', 10, null)); } protected function makeNotification(float $oldScore, float $newScore): CategoryScoreChangedNotification { $monitor = LighthouseMonitor::query()->create([ 'team_id' => 1, 'url' => 'https://example.com', 'settings' => [], 'interval' => '0 * * * *', ]); $result = LighthouseResult::query()->create([ 'lighthouse_monitor_id' => $monitor->id, 'performance' => $newScore, 'accessibility' => $newScore, 'best_practices' => $newScore, 'seo' => $newScore, ]); $data = CategoryResultDifferenceData::of([ 'performance_old' => $oldScore, 'performance_new' => $newScore, 'accessibility_old' => $oldScore, 'accessibility_new' => $newScore, 'best_practices_old' => $oldScore, 'best_practices_new' => $newScore, 'seo_old' => $oldScore, 'seo_new' => $newScore, ]); return new CategoryScoreChangedNotification($result, $data); } } ================================================ FILE: packages/lighthouse/tests/Notifications/Conditions/Category/AverageScoreValueConditionTest.php ================================================ makeNotification([0.5, 0.6, 0.7, 0.8], [0.7, 0.8, 0.8, 0.9]); // Average new: (70 + 80 + 80 + 90) / 4 = 80 $this->assertTrue($condition->applies($notification, 'new', '>', 75, null)); $this->assertFalse($condition->applies($notification, 'new', '>', 80, null)); $this->assertTrue($condition->applies($notification, 'new', '>=', 80, null)); } #[Test] public function it_checks_new_average_value_less_than_threshold(): void { $condition = new AverageScoreValueCondition; $notification = $this->makeNotification([0.7, 0.8, 0.8, 0.9], [0.4, 0.5, 0.5, 0.6]); // Average new: (40 + 50 + 50 + 60) / 4 = 50 $this->assertTrue($condition->applies($notification, 'new', '<', 60, null)); $this->assertFalse($condition->applies($notification, 'new', '<', 50, null)); $this->assertTrue($condition->applies($notification, 'new', '<=', 50, null)); } #[Test] public function it_checks_old_average_value_greater_than_threshold(): void { $condition = new AverageScoreValueCondition; $notification = $this->makeNotification([0.7, 0.8, 0.8, 0.9], [0.4, 0.5, 0.5, 0.6]); // Average old: (70 + 80 + 80 + 90) / 4 = 80 $this->assertTrue($condition->applies($notification, 'old', '>', 75, null)); $this->assertFalse($condition->applies($notification, 'old', '>', 80, null)); $this->assertTrue($condition->applies($notification, 'old', '>=', 80, null)); } #[Test] public function it_checks_equality(): void { $condition = new AverageScoreValueCondition; $notification = $this->makeNotification([0.5, 0.5, 0.5, 0.5], [0.6, 0.6, 0.6, 0.6]); $this->assertTrue($condition->applies($notification, 'new', '=', 60, null)); $this->assertFalse($condition->applies($notification, 'new', '=', 50, null)); $this->assertTrue($condition->applies($notification, 'new', '<>', 50, null)); } protected function makeNotification(array $oldScores, array $newScores): CategoryScoreChangedNotification { $monitor = LighthouseMonitor::query()->create([ 'team_id' => 1, 'url' => 'https://example.com', 'settings' => [], 'interval' => '0 * * * *', ]); $result = LighthouseResult::query()->create([ 'lighthouse_monitor_id' => $monitor->id, 'performance' => $newScores[0], 'accessibility' => $newScores[1], 'best_practices' => $newScores[2], 'seo' => $newScores[3], ]); $data = CategoryResultDifferenceData::of([ 'performance_old' => $oldScores[0], 'performance_new' => $newScores[0], 'accessibility_old' => $oldScores[1], 'accessibility_new' => $newScores[1], 'best_practices_old' => $oldScores[2], 'best_practices_new' => $newScores[2], 'seo_old' => $oldScores[3], 'seo_new' => $newScores[3], ]); return new CategoryScoreChangedNotification($result, $data); } } ================================================ FILE: packages/lighthouse/tests/Notifications/Conditions/Category/PerformanceScoreValueConditionTest.php ================================================ makeNotification(0.5, 0.8); $this->assertTrue($condition->applies($notification, 'new', '>', 70, null)); $this->assertFalse($condition->applies($notification, 'new', '>', 80, null)); $this->assertTrue($condition->applies($notification, 'new', '>=', 80, null)); } #[Test] public function it_checks_new_value_less_than_threshold(): void { $condition = new PerformanceScoreValueCondition; $notification = $this->makeNotification(0.8, 0.5); $this->assertTrue($condition->applies($notification, 'new', '<', 60, null)); $this->assertFalse($condition->applies($notification, 'new', '<', 50, null)); $this->assertTrue($condition->applies($notification, 'new', '<=', 50, null)); } #[Test] public function it_checks_old_value_greater_than_threshold(): void { $condition = new PerformanceScoreValueCondition; $notification = $this->makeNotification(0.8, 0.5); $this->assertTrue($condition->applies($notification, 'old', '>', 70, null)); $this->assertFalse($condition->applies($notification, 'old', '>', 80, null)); $this->assertTrue($condition->applies($notification, 'old', '>=', 80, null)); } #[Test] public function it_checks_old_value_less_than_threshold(): void { $condition = new PerformanceScoreValueCondition; $notification = $this->makeNotification(0.5, 0.8); $this->assertTrue($condition->applies($notification, 'old', '<', 60, null)); $this->assertFalse($condition->applies($notification, 'old', '<', 50, null)); $this->assertTrue($condition->applies($notification, 'old', '<=', 50, null)); } #[Test] public function it_checks_equality(): void { $condition = new PerformanceScoreValueCondition; $notification = $this->makeNotification(0.5, 0.5); $this->assertTrue($condition->applies($notification, 'new', '=', 50, null)); $this->assertFalse($condition->applies($notification, 'new', '=', 60, null)); $this->assertTrue($condition->applies($notification, 'new', '<>', 60, null)); } protected function makeNotification(float $oldPerformance, float $newPerformance): CategoryScoreChangedNotification { $monitor = LighthouseMonitor::query()->create([ 'team_id' => 1, 'url' => 'https://example.com', 'settings' => [], 'interval' => '0 * * * *', ]); $result = LighthouseResult::query()->create([ 'lighthouse_monitor_id' => $monitor->id, 'performance' => $newPerformance, 'accessibility' => 0.7, 'best_practices' => 0.7, 'seo' => 0.7, ]); $data = CategoryResultDifferenceData::of([ 'performance_old' => $oldPerformance, 'performance_new' => $newPerformance, 'accessibility_old' => 0.7, 'accessibility_new' => 0.7, 'best_practices_old' => 0.7, 'best_practices_new' => 0.7, 'seo_old' => 0.7, 'seo_new' => 0.7, ]); return new CategoryScoreChangedNotification($result, $data); } } ================================================ FILE: packages/lighthouse/tests/TestCase.php ================================================ set('database.default', 'testbench'); $app['config']->set('database.connections.testbench', [ 'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '', ]); } protected function setUp(): void { parent::setUp(); TeamService::fake(); Bus::fake([ RunLighthouseJob::class, ]); } } ================================================ FILE: packages/notifications/.gitignore ================================================ vendor composer.lock .phpunit.result.cache ================================================ FILE: packages/notifications/composer.json ================================================ { "name": "vigilant/notifications", "description": "Vigilant Notifications", "type": "package", "license": "AGPL", "authors": [ { "name": "Vincent Boon", "email": "info@vincentbean.com", "role": "Developer" } ], "require": { "php": "^8.3", "guzzlehttp/guzzle": "^7.2", "laravel/framework": "^12.0", "livewire/livewire": "^3.4", "vigilant/core": "@dev", "vigilant/sites": "@dev", "vigilant/users": "@dev" }, "require-dev": { "laravel/pint": "^1.6", "larastan/larastan": "^3.0", "orchestra/testbench": "^10.0", "phpstan/phpstan-mockery": "^2.0", "phpunit/phpunit": "^11.0" }, "autoload": { "psr-4": { "Vigilant\\Notifications\\": "src" } }, "autoload-dev": { "psr-4": { "Vigilant\\Notifications\\Tests\\": "tests", "Vigilant\\Users\\Database\\Factories\\": "../users/database/factories" } }, "scripts": { "test": "phpunit", "analyse": "phpstan", "style": "pint --test", "quality": [ "@test", "@analyse" ] }, "config": { "sort-packages": true, "allow-plugins": { "php-http/discovery": true } }, "extra": { "laravel": { "providers": [ "Vigilant\\Notifications\\ServiceProvider" ], "aliases": { "NotificationRegistry": "Vigilant\\Notifications\\Facades\\NotificationRegistry" } } }, "minimum-stability": "dev", "prefer-stable": true, "repositories": [ { "type": "path", "url": "../*" } ] } ================================================ FILE: packages/notifications/config/notifications.php ================================================ 'notifications', /* * Move the old condition classes in the DB to the new ones * Old class => new class */ 'moved_conditions' => [ \Vigilant\Lighthouse\Notifications\Conditions\AccessibilityPercentScoreCondition::class => \Vigilant\Lighthouse\Notifications\Conditions\Category\AccessibilityPercentScoreCondition::class, \Vigilant\Lighthouse\Notifications\Conditions\AverageScoreCondition::class => \Vigilant\Lighthouse\Notifications\Conditions\Category\AverageScoreCondition::class, \Vigilant\Lighthouse\Notifications\Conditions\BestPracticesPercentScoreCondition::class => \Vigilant\Lighthouse\Notifications\Conditions\Category\BestPracticesPercentScoreCondition::class, \Vigilant\Lighthouse\Notifications\Conditions\SeoPercentPercentScoreCondition::class => \Vigilant\Lighthouse\Notifications\Conditions\Category\SeoPercentPercentScoreCondition::class, ], ]; ================================================ FILE: packages/notifications/database/migrations/2024_02_25_110000_create_notification_triggers_table.php ================================================ id(); $table->foreignIdFor(Team::class); $table->string('notification')->index(); $table->json('conditions'); $table->timestamps(); }); } public function down(): void { Schema::dropIfExists('notification_triggers'); } }; ================================================ FILE: packages/notifications/database/migrations/2024_02_25_111000_create_notification_channels_table.php ================================================ id(); $table->foreignIdFor(Team::class); $table->string('channel'); $table->json('settings'); $table->timestamps(); }); } public function down(): void { Schema::dropIfExists('notification_channels'); } }; ================================================ FILE: packages/notifications/database/migrations/2024_02_25_111000_create_notification_triggers_channels_table.php ================================================ id(); $table->unsignedBigInteger('channel_id'); $table->unsignedBigInteger('trigger_id'); $table->foreign('channel_id', 'channel_id') ->references('id')->on('notification_channels')->onDelete('cascade'); $table->foreign('trigger_id', 'trigger_id') ->references('id')->on('notification_triggers')->onDelete('cascade'); $table->unique(['channel_id', 'trigger_id'], 'unique_notification_channel_trigger'); }); } public function down(): void { Schema::dropIfExists('notification_channel_notification_trigger'); } }; ================================================ FILE: packages/notifications/database/migrations/2024_02_25_112000_create_notification_history_table.php ================================================ id(); $table->foreignIdFor(Channel::class) ->index() ->constrained('notification_channels') ->cascadeOnDelete(); $table->foreignIdFor(Trigger::class) ->nullable() ->index() ->constrained('notification_triggers') ->cascadeOnDelete(); $table->string('notification'); $table->string('uniqueId'); $table->json('data'); $table->timestamps(); }); } public function down(): void { Schema::dropIfExists('notification_history'); } }; ================================================ FILE: packages/notifications/database/migrations/2024_04_04_193000_notification_trigger_all_channels_field.php ================================================ boolean('all_channels')->default(false)->after('conditions'); }); } public function down(): void { Schema::dropColumns('notification_triggers', ['all_channels']); } }; ================================================ FILE: packages/notifications/database/migrations/2024_04_12_193000_notification_enabled_field.php ================================================ boolean('enabled')->default(true)->after('team_id'); $table->string('name')->after('notification'); }); } public function down(): void { Schema::dropColumns('notification_triggers', ['enabled', 'name']); } }; ================================================ FILE: packages/notifications/database/migrations/2024_09_22_113000_notification_cooldown_field.php ================================================ integer('cooldown')->nullable()->after('conditions'); }); } public function down(): void { Schema::dropColumns('notification_triggers', ['cooldown']); } }; ================================================ FILE: packages/notifications/database/migrations/2026_01_02_150000_add_name_to_notification_channels_table.php ================================================ string('name')->nullable()->after('channel'); }); } public function down(): void { Schema::table('notification_channels', function (Blueprint $table): void { $table->dropColumn('name'); }); } }; ================================================ FILE: packages/notifications/database/migrations/2026_01_02_151500_backfill_notification_channel_names.php ================================================ whereNull('name') ->chunkById(100, function ($channels): void { /** @var \Illuminate\Support\Collection $channels */ $channels->each(function (Channel $channel): void { $channelType = $channel->channel; if (! is_string($channelType) || ! class_exists($channelType) || ! is_subclass_of($channelType, NotificationChannel::class)) { return; } $channel->forceFill(['name' => $channelType::$name])->save(); }); }); }); }); } }; ================================================ FILE: packages/notifications/phpstan.neon ================================================ includes: - ./vendor/larastan/larastan/extension.neon - ./vendor/phpstan/phpstan-mockery/extension.neon parameters: paths: - src - tests level: 8 treatPhpDocTypesAsCertain: false ignoreErrors: - '#Unsafe usage of new static#' - identifier: missingType.iterableValue - identifier: missingType.generics - '#return type contains unknown class Vigilant\\Notifications\\Facades\\Notification#' ================================================ FILE: packages/notifications/phpunit.xml ================================================ ./tests/* ./src ================================================ FILE: packages/notifications/resources/navigation.php ================================================ code('notifications') ->routeIs('notifications*') ->icon('tni-exclamation-circle-o') ->sort(1000); Navigation::add(route('notifications'), 'Notification Types') ->parent('notifications') ->icon('phosphor-list-heart-duotone') ->routeIs('notifications', 'notifications.trigger.*') ->sort(1); Navigation::add(route('notifications.channels'), 'Notification Channels') ->parent('notifications') ->icon('phosphor-chat-centered-dots-bold') ->routeIs('notifications.channel*') ->sort(2); Navigation::add(route('notifications.history'), 'Notification History') ->parent('notifications') ->icon('tni-history-o') ->routeIs('notifications.history') ->sort(3); ================================================ FILE: packages/notifications/resources/views/channels.blade.php ================================================ @lang('Add Channel') @if ($hasChannels) @else @endif ================================================ FILE: packages/notifications/resources/views/components/condition-builder/condition.blade.php ================================================ @php($instance = app($condition['condition'])) @php($operators = $instance->operators()) @php($operands = $instance->operands())
{{ $condition['condition']::$name }} @if ($condition['condition']::info()) ℹ️ @endif
@if (count($operands ?? []) > 0)
@endif @if (count($operators ?? []) > 0)
@endif
================================================ FILE: packages/notifications/resources/views/components/condition-builder/group.blade.php ================================================
@if (!blank($path)) @endif
@foreach ($children as $index => $child) @if ($child['type'] === 'group')
@endif @if ($child['type'] === 'condition')
@endif @endforeach
@lang('New Group')
@lang('New Condition')
================================================ FILE: packages/notifications/resources/views/components/condition-builder/type/number.blade.php ================================================
================================================ FILE: packages/notifications/resources/views/components/condition-builder/type/select.blade.php ================================================
================================================ FILE: packages/notifications/resources/views/components/condition-builder/type/static.blade.php ================================================
{{-- Static conditions don't require any input --}}
================================================ FILE: packages/notifications/resources/views/components/condition-builder/type/text.blade.php ================================================
================================================ FILE: packages/notifications/resources/views/components/empty-states/channels.blade.php ================================================ ================================================ FILE: packages/notifications/resources/views/history.blade.php ================================================ ================================================ FILE: packages/notifications/resources/views/livewire/channels/configuration/discord.blade.php ================================================
================================================ FILE: packages/notifications/resources/views/livewire/channels/configuration/google-chat.blade.php ================================================
================================================ FILE: packages/notifications/resources/views/livewire/channels/configuration/mail.blade.php ================================================
================================================ FILE: packages/notifications/resources/views/livewire/channels/configuration/microsoft-teams.blade.php ================================================
================================================ FILE: packages/notifications/resources/views/livewire/channels/configuration/ntfy.blade.php ================================================
@if (($settings['auth_method'] ?? '') === 'username') @endif @if (($settings['auth_method'] ?? '') === 'token') @endif
================================================ FILE: packages/notifications/resources/views/livewire/channels/configuration/slack.blade.php ================================================
================================================ FILE: packages/notifications/resources/views/livewire/channels/configuration/telegram.blade.php ================================================

How to get your chat ID:

  1. Send a message to your bot on Telegram
  2. Visit https://api.telegram.org/bot{your_bot_token}/getUpdates
  3. Look for the chatid field in the response
================================================ FILE: packages/notifications/resources/views/livewire/channels/configuration/webhook.blade.php ================================================
================================================ FILE: packages/notifications/resources/views/livewire/channels/form.blade.php ================================================
@if (!$inline) @if($updating) @lang('Delete') @lang('Delete') @endif @endif
@if ($testSent) @endif @foreach (\Vigilant\Notifications\Facades\NotificationRegistry::channels() as $channel) @endforeach

{{ __('Configuration') }}

@if ($settingsComponent !== null) @livewire($settingsComponent, ['channel' => $this->form->channel, 'settings' => $channelModel?->settings ?? []], key($this->form->channel)) @else {{ __('Select a channel to configure') }} @endif Test
@if($updating && !$inline)
@lang('Delete Notification Channel')

@lang('Are you sure you want to delete this notification channel?')

@svg('phosphor-warning-circle', 'w-5 h-5 text-orange mt-0.5')

{{ $channelModel->title() }}

@lang('This action cannot be undone. All channel settings will be permanently deleted and notifications will no longer be sent to this channel.')

@lang('Cancel') @lang('Delete Channel')
@endif
================================================ FILE: packages/notifications/resources/views/livewire/notifications/condition-builder.blade.php ================================================
================================================ FILE: packages/notifications/resources/views/livewire/notifications/form.blade.php ================================================
@if($updating) @lang('Delete') @lang('Delete') @endif
@foreach (\Vigilant\Notifications\Facades\NotificationRegistry::notifications() as $notification) @endforeach @if ($form->notification && $form->notification::info())

ℹ️ {{ $form->notification::info() }}

@endif @foreach (\Vigilant\Notifications\Models\Channel::query()->get() as $channel) @endforeach
@if ($updating)

@lang('Conditions')

@lang('Only notify when these conditions match')

@endif
@if($updating)
@lang('Delete Notification Trigger')

@lang('Are you sure you want to delete this notification trigger?')

@svg('phosphor-warning-circle', 'w-5 h-5 text-orange mt-0.5')

{{ $form->name }}

@lang('This action cannot be undone. All trigger conditions and settings will be permanently deleted.')

@lang('Cancel') @lang('Delete Trigger')
@endif
================================================ FILE: packages/notifications/resources/views/mails/notification.blade.php ================================================

{{ $description }}

@if($viewUrl !== null) @lang('View in Vigilant') @endif @if($url !== null && $urlTitle !== null) @lang($urlTitle) @endif ================================================ FILE: packages/notifications/resources/views/notifications.blade.php ================================================ @lang('Add Notification') ================================================ FILE: packages/notifications/routes/web.php ================================================ group(function () { Route::view('/', 'notifications::notifications')->name('notifications'); Route::get('create', NotificationForm::class)->name('notifications.trigger.create'); Route::get('edit/{trigger}', NotificationForm::class)->name('notifications.trigger.edit'); Route::prefix('channels')->group(function () { Route::get('/', [ChannelController::class, 'index'])->name('notifications.channels'); Route::get('create', ChannelForm::class)->name('notifications.channel.create'); Route::get('edit/{channel}', ChannelForm::class)->name('notifications.channel.edit'); }); Route::view('history', 'notifications::history')->name('notifications.history'); }); ================================================ FILE: packages/notifications/src/Actions/CheckBurst.php ================================================ cacheKey($notification, $trigger, $channel); return ! cache()->add($key, 1, self::BURST_SECONDS); } protected function cacheKey(Notification $notification, Trigger $trigger, Channel $channel): string { return sprintf('notifications:burst:%s:%s:%s:%s', $notification::class, $notification->uniqueId(), $trigger->id, $channel->id); } } ================================================ FILE: packages/notifications/src/Actions/CheckCooldown.php ================================================ cooldown; if ($cooldown === null) { $cooldown = $notification::$defaultCooldown; } if ($cooldown === null || $cooldown === 0) { return false; } /** @var ?History $lastNotification */ $lastNotification = $channel->history() ->where('trigger_id', '=', $trigger->id) ->where('uniqueId', '=', $notification->uniqueId()) ->orderByDesc('created_at') ->first(); if ($lastNotification === null) { return false; } $minutesSinceLastNotification = $lastNotification->created_at?->diffInMinutes() ?? 0; return $minutesSinceLastNotification < $cooldown; } } ================================================ FILE: packages/notifications/src/Actions/CreateNotifications.php ================================================ $notification */ foreach ($notifications as $notification) { if (! $notification::$autoCreate) { continue; } Trigger::query()->firstOrCreate([ 'team_id' => $team->id, 'notification' => $notification, ], [ 'enabled' => true, 'name' => $notification::$name, 'all_channels' => true, 'conditions' => $notification::$defaultConditions, 'cooldown' => $notification::$defaultCooldown, ]); } } } ================================================ FILE: packages/notifications/src/Channels/DiscordChannel.php ================================================ ['required', 'url', 'starts_with:https://discord.com/api/webhooks'], ]; public function fire(Notification $notification, Channel $channel): void { $settings = $channel->settings; $description = $notification->description(); if ($viewUrl = $notification->viewUrl()) { $description .= __("\n\n[View in Vigilant](:url)", ['url' => $viewUrl]); } $fields = []; if (($url = $notification->url()) && ($urlTitle = $notification->urlTitle())) { $fields[] = [ 'name' => $urlTitle, 'value' => __('[Click here](:url)', ['url' => $url]), 'inline' => true, ]; } $payload = [ 'embeds' => [ [ 'title' => $notification->title(), 'description' => $description, 'color' => $notification->level()->color(), 'fields' => $fields, ], ], ]; Http::post($settings['webhook_url'], $payload); } } ================================================ FILE: packages/notifications/src/Channels/GoogleChatChannel.php ================================================ ['required', 'url', 'starts_with:https://chat.googleapis.com/v1/spaces/'], ]; public function fire(Notification $notification, Channel $channel): void { $settings = $channel->settings; $description = $notification->description(); if ($viewUrl = $notification->viewUrl()) { $description .= "\n\n[View in Vigilant]($viewUrl)"; } $lines = []; $lines[] = '*'.$notification->title().'*'; $lines[] = $description; if (($url = $notification->url()) && ($urlTitle = $notification->urlTitle())) { $lines[] = "\n[".$urlTitle."]($url)"; } $payload = [ 'text' => implode("\n", $lines), ]; Http::post($settings['webhook_url'], $payload); } } ================================================ FILE: packages/notifications/src/Channels/MailChannel.php ================================================ ['required', 'email'], ]; public function fire(Notification $notification, Channel $channel): void { $settings = $channel->settings; /** @var string $to */ $to = $settings['to']; Mail::to($to)->send(new NotificationMail($notification)); } } ================================================ FILE: packages/notifications/src/Channels/MicrosoftTeamsChannel.php ================================================ ['required', 'url', 'starts_with:https://outlook.office.com/webhook/'], ]; public function fire(Notification $notification, Channel $channel): void { $settings = $channel->settings; $description = $notification->description(); if ($viewUrl = $notification->viewUrl()) { $description .= "\n\n[View in Vigilant]($viewUrl)"; } $facts = []; if (($url = $notification->url()) && ($urlTitle = $notification->urlTitle())) { $facts[] = [ 'name' => $urlTitle, 'value' => "[Click here]($url)", ]; } $payload = [ '@type' => 'MessageCard', '@context' => 'http://schema.org/extensions', 'summary' => $notification->title(), 'themeColor' => $notification->level()->color(), 'title' => $notification->title(), 'text' => $description, 'sections' => count($facts) ? [ [ 'facts' => $facts, ], ] : [], ]; Http::post($settings['webhook_url'], $payload); } } ================================================ FILE: packages/notifications/src/Channels/NotificationChannel.php ================================================ rules; } abstract public function fire(Notification $notification, Channel $channel): void; } ================================================ FILE: packages/notifications/src/Channels/NtfyChannel.php ================================================ ['required', 'url'], 'topic' => ['required'], 'auth_method' => ['nullable', 'in:username,token'], 'username' => ['required_if:auth_method,username'], 'password' => ['required_if:auth_method,username'], 'token' => ['required_if:auth_method,token'], ]; public function fire(Notification $notification, Channel $channel): void { $settings = $channel->settings; $tag = match ($notification->level()) { Level::Info => 'grey_exclamation', Level::Warning => 'warning', Level::Critical => 'triangular_flag_on_post', Level::Success => 'white_check_mark', }; $request = Http::baseUrl($settings['server']) ->withHeaders([ 'Title' => $notification->title().' - '.config('app.name'), 'Tags' => $tag, ]); $viewUrl = $notification->viewUrl(); $url = $notification->url(); $urlTitle = $notification->urlTitle(); if ($viewUrl !== null) { $request->withHeader('click', $viewUrl); } if ($url !== null && $urlTitle !== null) { $request->withHeader('Actions', "view, $urlTitle, $url, clear=true"); } if ($settings['auth_method'] === 'username') { $request->withBasicAuth( $settings['username'], $settings['password'], ); } if ($settings['auth_method'] === 'token') { $request->withToken($settings['token']); } $request ->withBody($notification->description()) ->post($settings['topic']); } } ================================================ FILE: packages/notifications/src/Channels/SlackChannel.php ================================================ ['required', 'url'], ]; public function fire(Notification $notification, Channel $channel): void { $settings = $channel->settings; $blocks = []; $blocks[] = [ 'type' => 'section', 'text' => [ 'type' => 'mrkdwn', 'text' => "*{$notification->title()}*\n{$notification->description()}", ], ]; if ($viewUrl = $notification->viewUrl()) { $blocks[] = [ 'type' => 'actions', 'elements' => [ [ 'type' => 'button', 'text' => [ 'type' => 'plain_text', 'text' => __('View in Vigilant'), 'emoji' => true, ], 'url' => $viewUrl, 'action_id' => 'view_more_button', ], ], ]; } if (($url = $notification->url()) && ($urlTitle = $notification->urlTitle())) { $blocks[] = [ 'type' => 'actions', 'elements' => [ [ 'type' => 'button', 'text' => [ 'type' => 'plain_text', 'text' => __($urlTitle), 'emoji' => true, ], 'url' => $url, 'action_id' => 'action_button', ], ], ]; } $payload = [ 'blocks' => $blocks, 'attachments' => [ [ 'color' => $notification->level()->color(), ], ], ]; Http::post($settings['webhook_url'], $payload); } } ================================================ FILE: packages/notifications/src/Channels/TelegramChannel.php ================================================ ['required', 'string'], 'chat_id' => ['required', 'string'], ]; public function fire(Notification $notification, Channel $channel): void { $settings = $channel->settings; $title = $this->escapeMarkdownV2($notification->title()); $description = $this->escapeMarkdownV2($notification->description()); $text = "*{$title}*\n\n{$description}"; $inlineKeyboard = []; if ($viewUrl = $notification->viewUrl()) { $inlineKeyboard[] = [ [ 'text' => __('View in Vigilant'), 'url' => $viewUrl, ], ]; } if (($url = $notification->url()) && ($urlTitle = $notification->urlTitle())) { $inlineKeyboard[] = [ [ 'text' => __($urlTitle), 'url' => $url, ], ]; } $payload = [ 'chat_id' => $settings['chat_id'], 'text' => $text, 'parse_mode' => 'MarkdownV2', ]; if (! empty($inlineKeyboard)) { $payload['reply_markup'] = [ 'inline_keyboard' => $inlineKeyboard, ]; } $url = "https://api.telegram.org/bot{$settings['bot_token']}/sendMessage"; Http::post($url, $payload); } protected function escapeMarkdownV2(string $text): string { return preg_replace('/([_*\[\]()~`>#+\-=|{}.!\\\\])/', '\\\\$1', $text) ?? ''; } } ================================================ FILE: packages/notifications/src/Channels/WebhookChannel.php ================================================ ['required', 'url'], ]; public function fire(Notification $notification, Channel $channel): void { Http::post($channel->settings['url'], [ 'level' => $notification->level(), 'title' => $notification->title(), 'description' => $notification->description(), ]); } } ================================================ FILE: packages/notifications/src/Commands/CreateNotificationsCommand.php ================================================ argument('teamId'); Team::query() ->when($teamId !== null, fn (Builder $builder): Builder => $builder->where('team_id', '=', $teamId)) ->get() ->each(fn (Team $team): PendingDispatch => CreateNotificationsJob::dispatch($team)); return static::SUCCESS; } } ================================================ FILE: packages/notifications/src/Commands/RenameConditionClassesCommand.php ================================================ $renamed */ $renamed = config('notifications.moved_conditions'); foreach ($renamed as $old => $new) { $this->info("Checking $old => $new"); $oldClass = Str::replace('\\', '\\\\\\\\', $old); $triggers = Trigger::query() ->withoutGlobalScopes() ->whereRaw("JSON_UNQUOTE(JSON_EXTRACT(conditions, '$')) LIKE ?", ["%$oldClass%"]) ->get(); $this->info("Found {$triggers->count()} triggers to update"); foreach ($triggers as $trigger) { $trigger->update([ 'conditions' => $this->processGroup($trigger->conditions, $old, $new), ]); } $this->newLine(); } return static::SUCCESS; } protected function processGroup(array $group, string $old, string $new): array { foreach ($group['children'] ?? [] as $index => $child) { if ($child['type'] === 'condition') { if ($child['condition'] === $old) { data_set($group, "children.$index.condition", $new); } } if ($child['type'] === 'group') { data_set($group, "children.$index", $this->processGroup($child, $old, $new)); } } return $group; } } ================================================ FILE: packages/notifications/src/Commands/TestNotificationCommand.php ================================================ argument('channelId'); /** @var Channel $channel */ $channel = Channel::query()->withoutGlobalScopes()->findOrFail($channelId); foreach (Level::cases() as $level) { SendNotificationJob::dispatchSync( new TestNotification($level), $channel->team_id, $channel->id ); } return static::SUCCESS; } } ================================================ FILE: packages/notifications/src/Concerns/NotificationFake.php ================================================ */ protected static array $fakeDispatches = []; public static function fake(): void { static::$faked = true; } public static function wasDispatched(?\Closure $callback = null): bool { if ($callback !== null) { foreach (static::$fakeDispatches as $dispatch) { if (! $callback($dispatch)) { return false; } } return true; } return count(static::$fakeDispatches) > 0; } } ================================================ FILE: packages/notifications/src/Conditions/Condition.php ================================================ $meta */ abstract public function applies(Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta): bool; /** @return array */ public function operators(): array { return []; } /** @return array */ public function operands(): array { return []; } /** @return array */ public function metadata(): array { return []; } public static function info(): ?string { return null; } } ================================================ FILE: packages/notifications/src/Conditions/ConditionEngine.php ================================================ $children */ $children = collect($group['children'] ?? []); // @phpstan-ignore-line if ($children->isEmpty()) { return true; } $applies = true; foreach ($children as $condition) { if ($condition['type'] == 'condition') { if (! NotificationRegistry::hasCondition(get_class($notification), $condition['condition'])) { continue; } /** @var Condition $instance */ $instance = app($condition['condition']); $applies = $instance->applies( $notification, $condition['operand'] ?? null, $condition['operator'] ?? null, $condition['value'] ?? null, $condition['meta'] ?? null ); } if ($condition['type'] == 'group') { $applies = $this->checkGroup($notification, $condition, $condition['operator']); } if ($operator === 'any' && $applies) { return true; } if ($operator === 'all' && ! $applies) { return false; } } return $applies; } } ================================================ FILE: packages/notifications/src/Conditions/FalseCondition.php ================================================ 'Equal to', '!=' => 'Not equal to', ]; } public function operands(): array { return [ 'operand-a' => 'Operand A', 'operand-b' => 'Operand B', ]; } } ================================================ FILE: packages/notifications/src/Conditions/SelectCondition.php ================================================ */ abstract public function options(): array; } ================================================ FILE: packages/notifications/src/Conditions/StaticCondition.php ================================================ 'Equal to', '!=' => 'Not equal to', ]; } public function operands(): array { return [ 'operand-a' => 'Operand A', 'operand-b' => 'Operand B', ]; } } ================================================ FILE: packages/notifications/src/Contracts/HasSite.php ================================================ value; } } ================================================ FILE: packages/notifications/src/Enums/Level.php ================================================ 0x3498DB, // Blue Level::Warning => 0xF1C40F, // Yellow Level::Critical => 0xE74C3C, // Red Level::Success => 0x2ECC71, // Green }; } } ================================================ FILE: packages/notifications/src/Facades/NotificationRegistry.php ================================================ > notifications() * @method static array channels() * @method static array conditions(string $notification) * @method static bool hasCondition(string $notification, string $condition) * @method static void fake() */ class NotificationRegistry extends Facade { protected static function getFacadeAccessor(): string { return Registry::class; } } ================================================ FILE: packages/notifications/src/Http/Controllers/ChannelController.php ================================================ exists(); return view($view, [ 'hasChannels' => $hasChannels, ]); } } ================================================ FILE: packages/notifications/src/Http/Livewire/ChannelForm.php ================================================ channelModel = $channel; $this->form->fill($channel->toArray()); if (class_exists($channel->channel)) { $this->settingsComponent = $channel->channel::$component ?? null; // If prefilled with settings, mark as validated if (!empty($channel->settings)) { $this->componentValidated = true; } } } else { $this->channelModel = new Channel(); } } public function updated(): void { if (blank($this->form->channel)) { return; } $this->form->settings = []; $this->settingsComponent = $this->form->channel::$component ?? null; } #[On('update-channel-settings')] public function updateChannelSettings(array $settings): void { $this->form->settings = $settings; } #[On('update-channel-validated')] public function updateChannelValidated(bool $validated): void { $this->componentValidated = $validated; } public function save(bool $redirect = true, bool $dispatchSaved = true): void { if (! $this->componentValidated && $this->settingsComponent !== null) { return; } $this->validate(); $data = $this->form->all(); $data['name'] = blank($data['name'] ?? null) ? null : $data['name']; if ($this->channelModel->exists) { $this->channelModel->update($data); } else { $this->channelModel = Channel::query()->create($data); } if ($this->inline) { if ($dispatchSaved) { $this->dispatch('channel-saved', [ 'channel' => $this->channelModel, ]); } return; } if ($redirect) { $this->redirectRoute('notifications.channel.edit', ['channel' => $this->channelModel]); $this->alert( __('Saved'), __('Channel was successfully :action', ['action' => $this->channelModel->wasRecentlyCreated ? 'created' : 'saved']), AlertType::Success ); } } public function test(): void { $this->save(false, false); if (! $this->channelModel->exists) { return; } SendNotificationJob::dispatchSync( new TestNotification, $this->channelModel->team_id, $this->channelModel->id ); $this->testSent = true; } public function delete(): void { if (! $this->channelModel->exists) { return; } $this->channelModel->delete(); $this->alert( __('Deleted'), __('Channel was successfully deleted'), AlertType::Success ); $this->redirectRoute('notifications.channels'); } public function render(): mixed { /** @var view-string $view */ $view = 'notifications::livewire.channels.form'; return view($view, [ 'updating' => $this->channelModel->exists, ]); } } ================================================ FILE: packages/notifications/src/Http/Livewire/Channels/Configuration/ChannelConfiguration.php ================================================ channel = $channel; $this->settings = $settings; } public function updated(): void { $this->dispatch('update-channel-validated', false); /** @var NotificationChannel $channel */ $channel = app($this->channel); $this->rules = collect($channel->rules()) ->mapWithKeys(fn (string|array $rules, string $key) => ["settings.$key" => $rules]) ->toArray(); $this->validate(); $this->dispatch('update-channel-settings', $this->settings); $this->dispatch('update-channel-validated', true); } abstract public function render(): View; } ================================================ FILE: packages/notifications/src/Http/Livewire/Channels/Configuration/Discord.php ================================================ trigger = $trigger; $this->form->fill($trigger->toArray()); if ($trigger->exists) { $this->channels = $trigger->channels->pluck('id')->toArray(); } } } #[On('conditions-updated')] public function conditionsUpdated(array $conditions): void { $this->form->conditions = $conditions; } public function save(): void { $this->validate(); if ($this->trigger->exists) { // Never update the notification because of the linked conditions $this->trigger->update($this->form->except(['notification'])); } else { $this->trigger = Trigger::query()->create( $this->form->all() ); } $this->trigger->channels()->sync($this->channels); $this->alert( __('Saved'), __('Notification was successfully :action', ['action' => $this->trigger->wasRecentlyCreated ? 'created' : 'saved']), AlertType::Success ); $this->redirectRoute('notifications.trigger.edit', ['trigger' => $this->trigger]); } public function delete(): void { if (! $this->trigger->exists) { return; } $this->trigger->delete(); $this->alert( __('Deleted'), __('Notification trigger was successfully deleted'), AlertType::Success ); $this->redirectRoute('notifications'); } public function render(): mixed { /** @var view-string $view */ $view = 'notifications::livewire.notifications.form'; return view($view, [ 'updating' => $this->trigger->exists, ]); } } ================================================ FILE: packages/notifications/src/Http/Livewire/Notifications/Conditions/ConditionBuilder.php ================================================ 'group', 'operator' => 'any', ]; public array $children = []; public function mount(string $notification, array $initial = []): void { $this->notification = $notification; if ($initial === []) { return; } $this->parent['operator'] = $initial['operator'] ?? 'any'; $this->children = $initial['children'] ?? []; } public array $selectedCondition = []; public function addCondition(string $path): void { $condition = $this->selectedCondition[md5($path)] ?? Arr::first($this->conditions()); $this->addToPath($path, [ 'type' => 'condition', 'condition' => $condition, 'value' => null, ]); } public function addGroup(string $path): void { $this->addToPath($path, [ 'type' => 'group', 'operator' => 'all', 'children' => [], ]); } public function deletePath(string $path): void { Arr::forget($this->children, $path); $this->children = array_values($this->children); $this->updated(); } protected function addToPath(string $path, array $item): void { if (blank($path)) { $this->children[] = $item; } else { $children = data_get($this->children, $path.'.children', []); $children[] = $item; data_set($this->children, $path.'.children', $children); } $this->updated(); } public function updated(): void { $conditions = $this->parent; $conditions['children'] = $this->children; $this->dispatch('conditions-updated', $conditions); } public function render(): mixed { /** @var view-string $view */ $view = 'notifications::livewire.notifications.condition-builder'; return view($view, [ 'conditions' => $this->conditions(), ]); } protected function conditions(): array { return NotificationRegistry::conditions($this->notification); } } ================================================ FILE: packages/notifications/src/Http/Livewire/Tables/ChannelTable.php ================================================ displayUsing(function (?string $name, Channel $channel): string { return $channel->title(); }), Column::make(__('Channel Type'), 'channel') ->displayUsing(function (string $channel) { /** @var class-string $channel */ return $channel::$name; }), Column::make(__('Notifications Sent'), 'total_notification_history') ->sortable(function (Builder $builder, Direction $direction): void { $builder->orderBy(function (QueryBuilder $query): void { $query->selectRaw('COUNT(*)')->from('notification_history')->where('channel_id', '=', DB::raw('notification_channels.id')); }, $direction->value); }), ]; } protected function actions(): array { return [ Action::make(__('Delete'), function (Enumerable $models): void { $models->each(fn (Channel $channel) => $channel->delete()); }, 'delete'), ]; } public function link(Model $model): ?string { return route('notifications.channel.edit', ['channel' => $model]); } protected function applySelect(Builder $builder): static { parent::applySelect($builder); $builder->addSelect( DB::raw('(SELECT COUNT(`notification_history`.`id`) FROM `notification_history` WHERE `notification_history`.`channel_id` = `notification_channels`.`id` GROUP BY `notification_history`.`channel_id`) AS total_notification_history') ); return $this; } } ================================================ FILE: packages/notifications/src/Http/Livewire/Tables/HistoryTable.php ================================================ searchable(), Column::make(__('Channel'), 'channel.channel') ->searchable() ->displayUsing(function (?string $channel) { if ($channel === null) { return null; } /** @var class-string $channel */ return $channel::$name; }), Column::make(__('Level'), 'data.level') ->displayUsing(fn (string $level) => Level::tryFrom($level)->name ?? $level), Column::make(__('Notification'), 'data.title') ->searchable(function (Builder $builder, mixed $search) { $builder->where('data->title', 'LIKE', '%'.$search.'%'); }), Column::make(__('Details'), 'data.description') ->displayUsing(fn (string $description): string => str($description)->limit(100)) ->searchable(function (Builder $builder, mixed $search) { $builder->where('data->description', 'LIKE', '%'.$search.'%'); }), DateColumn::make(__('Notified At'), 'created_at') ->sortable(), ]; } protected function filters(): array { return [ SelectFilter::make(__('Level'), 'data->level') ->options( collect(Level::cases()) ->mapWithKeys(fn (Level $level) => [$level->value => $level->name]) ->toArray() ), SelectFilter::make(__('Channel'), 'channel_id') ->options( Channel::query() ->select(['id', 'channel']) ->get() ->mapwithKeys(function (Channel $channel): array { /** @var class-string $class */ $class = $channel->channel; return [$channel->id => $class::$name]; }) ->toArray() ), ]; } } ================================================ FILE: packages/notifications/src/Http/Livewire/Tables/NotificationTable.php ================================================ sortable(), Column::make(__('Name'), 'name') ->sortable() ->searchable(), Column::make(__('Type'), 'notification') ->displayUsing(function (string $notification) { if (! class_exists($notification)) { return $notification; } /** @var class-string $notification */ return $notification::$name; }), Column::make(__('Channels')) ->displayUsing(function (Trigger $trigger) { return $trigger->all_channels ? __('All Channels') : __(':count Channel(s)', ['count' => $trigger->channels()->count()]); }), Column::make(__('Notifications Sent'), 'total_notification_history') ->sortable(function (Builder $builder, Direction $direction): void { $builder->orderBy(function (QueryBuilder $query): void { $query->selectRaw('COUNT(*)')->from('notification_history')->where('trigger_id', '=', DB::raw('notification_triggers.id')); }, $direction->value); }), ]; } protected function filters(): array { return [ BooleanFilter::make(__('Enabled'), 'enabled'), SelectFilter::make(__('Type'), 'notification') ->options( collect(NotificationRegistry::notifications()) ->mapWithKeys(fn (string $notification): array => [$notification => $notification::$name]) // @phpstan-ignore-line ->toArray() ), ]; } protected function actions(): array { return [ Action::make(__('Enable'), function (Enumerable $models): void { Trigger::query() ->whereIn('id', $models->pluck('id')) ->update([ 'enabled' => true, ]); }, 'enable'), Action::make(__('Disable'), function (Enumerable $models): void { Trigger::query() ->whereIn('id', $models->pluck('id')) ->update([ 'enabled' => false, ]); }, 'disable'), Action::make(__('Delete'), function (Enumerable $models): void { $models->each(fn (Trigger $trigger) => $trigger->delete()); }, 'delete'), ]; } public function link(Model $model): ?string { return route('notifications.trigger.edit', ['trigger' => $model]); } protected function applySelect(Builder $builder): static { parent::applySelect($builder); $builder->addSelect( DB::raw('(SELECT COUNT(`notification_history`.`id`) FROM `notification_history` WHERE `notification_history`.`trigger_id` = `notification_triggers`.`id` GROUP BY `notification_history`.`trigger_id`) AS total_notification_history') ); return $this; } } ================================================ FILE: packages/notifications/src/Jobs/CreateNotificationsJob.php ================================================ onQueue(config('notifications.queue')); } public function handle(CreateNotifications $notifications, TeamService $teamService): void { $teamService->setTeam($this->team); $notifications->create($this->team); } public function uniqueId(): int { return $this->team->id; } } ================================================ FILE: packages/notifications/src/Jobs/SendNotificationJob.php ================================================ onQueue(config('notifications.queue')); } public function handle(TeamService $teamService): void { $teamService->setTeamById($this->teamId); /** @var Channel $channel */ $channel = Channel::query()->findOrFail($this->channelId); /** @var NotificationChannel $instance */ $instance = app($channel->channel); $instance->fire($this->notification, $channel); $channel->history()->create([ 'trigger_id' => $this->triggerId, 'notification' => get_class($this->notification), 'uniqueId' => $this->notification->uniqueId(), 'data' => $this->notification->toArray(), ]); } public function uniqueId(): string { return implode('-', [ get_class($this->notification), $this->channelId, $this->triggerId ?? 0, $this->notification->uniqueId(), ]); } } ================================================ FILE: packages/notifications/src/Mail/NotificationMail.php ================================================ notification->level()->name, $this->notification->title(), 'Vigilant', ]) ); } public function content(): Content { return new Content( view: 'notifications::mails.notification', with: [ 'description' => $this->notification->description(), 'viewUrl' => $this->notification->viewUrl(), 'url' => $this->notification->url(), 'urlTitle' => $this->notification->urlTitle(), ], ); } } ================================================ FILE: packages/notifications/src/Models/Channel.php ================================================ $history */ #[ObservedBy([ChannelObserver::class])] #[ScopedBy([TeamScope::class])] class Channel extends Model { protected $table = 'notification_channels'; protected $guarded = []; protected $casts = [ 'settings' => 'array', ]; public function title(): string { if (filled($this->name)) { return $this->name; } if (is_string($this->channel) && class_exists($this->channel) && is_subclass_of($this->channel, NotificationChannel::class)) { /** @var class-string $channel */ $channel = $this->channel; return $channel::$name; } return (string) $this->channel; } public function history(): HasMany { return $this->hasMany(History::class); } } ================================================ FILE: packages/notifications/src/Models/History.php ================================================ 'array', ]; public function trigger(): BelongsTo { return $this->belongsTo(Trigger::class); } public function channel(): BelongsTo { return $this->belongsTo(Channel::class); } public function prunable(): Builder { return static::withoutGlobalScopes()->where('created_at', '<=', $this->retentionPeriod()); } } ================================================ FILE: packages/notifications/src/Models/Trigger.php ================================================ $channels * @property Collection $history */ #[ObservedBy([TriggerObserver::class])] #[ScopedBy([TeamScope::class])] class Trigger extends Model { protected $table = 'notification_triggers'; protected $guarded = []; protected $casts = [ 'enabled' => 'bool', 'conditions' => 'array', 'all_channels' => 'bool', ]; public function team(): BelongsTo { return $this->belongsTo(Team::class); } public function channels(): BelongsToMany { return $this->belongsToMany(Channel::class, 'notification_channel_notification_trigger'); } public function history(): HasMany { return $this->hasMany(History::class); } } ================================================ FILE: packages/notifications/src/Notifications/Notification.php ================================================ $triggers */ $triggers = Trigger::query() ->with('channels') ->where('enabled', '=', true) ->where('notification', '=', static::class) ->get(); /** @var ConditionEngine $conditionEngine */ $conditionEngine = app(ConditionEngine::class); /** @var CheckCooldown $cooldownCheck */ $cooldownCheck = app(CheckCooldown::class); /** @var CheckBurst $burstCheck */ $burstCheck = app(CheckBurst::class); foreach ($triggers as $trigger) { if (! $conditionEngine->checkGroup($instance, $trigger->conditions, $trigger->conditions['operator'] ?? 'any')) { continue; } $channels = $trigger->all_channels ? Channel::all() : $trigger->channels; foreach ($channels as $channel) { if ($cooldownCheck->onCooldown($trigger, $channel, $instance)) { continue; } if ($burstCheck->isBursting($instance, $trigger, $channel)) { return; } SendNotificationJob::dispatch($instance, $channel->team_id, $channel->id, $trigger->id); } } } abstract public function uniqueId(): string|int; public function level(): Level { return $this->level; } public function title(): string { return $this->title; } public function description(): string { return $this->description; } public static function info(): ?string { return null; } public function viewUrl(): ?string { return null; } public function url(): ?string { return null; } public function urlTitle(): ?string { return null; } public function toArray(): array { return [ 'title' => $this->title(), 'description' => $this->description(), 'level' => $this->level(), ]; } } ================================================ FILE: packages/notifications/src/Notifications/NotificationRegistry.php ================================================ |array> $notification */ public function registerNotification(string|array $notification): static { $this->notifications = array_merge($this->notifications(), Arr::wrap($notification)); return $this; } /** * @param class-string|array> $condition */ public function registerCondition(string $notification, string|array $condition): static { $this->conditions[$notification] = array_merge($this->conditions($notification), Arr::wrap($condition)); return $this; } /** * @param class-string|array> $channel */ public function registerChannel(string|array $channel): static { $this->channels = array_merge($this->channels(), Arr::wrap($channel)); return $this; } public function notifications(): array { return $this->notifications; } public function channels(): array { return $this->channels; } public function conditions(string $notification): array { return $this->conditions[$notification] ?? []; } public function hasCondition(string $notification, string $condition): bool { return in_array($condition, $this->conditions($notification)); } public function fake(): void { $this->notifications = []; $this->channels = []; $this->conditions = []; } } ================================================ FILE: packages/notifications/src/Notifications/TestNotification.php ================================================ level->name; } public function viewUrl(): ?string { return route('notifications'); } public function url(): ?string { return route('notifications'); } public function urlTitle(): ?string { return __('Details'); } /** @codeCoverageIgnore */ public function uniqueId(): string { return $this->level->value; } } ================================================ FILE: packages/notifications/src/Observers/ChannelObserver.php ================================================ currentTeam !== null) { $channel->team_id = $user->currentTeam->id; } } } ================================================ FILE: packages/notifications/src/Observers/TriggerObserver.php ================================================ team_id === null) { /** @var ?User $user */ $user = Auth::user(); if ($user !== null && $user->currentTeam !== null) { $trigger->team_id = $user->currentTeam->id; } } } } ================================================ FILE: packages/notifications/src/Scopes/HistoryTeamScope.php ================================================ team(); $builder->whereHas('channel', function (Builder $query) use ($team) { $query->where($query->qualifyColumn('team_id'), '=', $team->id); }); } } ================================================ FILE: packages/notifications/src/ServiceProvider.php ================================================ registerConfig() ->registerSingletons(); } protected function registerConfig(): static { $this->mergeConfigFrom(__DIR__.'/../config/notifications.php', 'notifications'); return $this; } protected function registerSingletons(): static { $this->app->singleton(\Vigilant\Notifications\Notifications\NotificationRegistry::class); return $this; } public function boot(): void { $this ->bootConfig() ->bootMigrations() ->bootCommands() ->bootViews() ->bootEvents() ->bootLivewire() ->bootRoutes() ->bootNavigation() ->bootNotificationChannels() ->bootPolicies(); } protected function bootConfig(): static { $this->publishes([ __DIR__.'/../config/notifications.php' => config_path('notifications.php'), ], 'config'); return $this; } protected function bootMigrations(): static { $this->loadMigrationsFrom(__DIR__.'/../database/migrations'); return $this; } protected function bootCommands(): static { if ($this->app->runningInConsole()) { $this->commands([ CreateNotificationsCommand::class, RenameConditionClassesCommand::class, TestNotificationCommand::class, ]); } return $this; } protected function bootViews(): static { $this->loadViewsFrom(__DIR__.'/../resources/views', 'notifications'); return $this; } protected function bootEvents(): static { Team::created(fn (Team $team): PendingDispatch => CreateNotificationsJob::dispatch($team)); return $this; } protected function bootLivewire(): static { Livewire::component('notification-table', NotificationTable::class); Livewire::component('notification-form', NotificationForm::class); Livewire::component('notification-history-table', HistoryTable::class); Livewire::component('notification-condition-builder', Notifications\Conditions\ConditionBuilder::class); Livewire::component('channel-table', ChannelTable::class); Livewire::component('channel-form', ChannelForm::class); Livewire::component('channel-configuration-webhook', Webhook::class); Livewire::component('channel-configuration-ntfy', Ntfy::class); Livewire::component('channel-configuration-mail', Mail::class); Livewire::component('channel-configuration-slack', Slack::class); Livewire::component('channel-configuration-discord', Discord::class); Livewire::component('channel-configuration-google-chat', GoogleChat::class); Livewire::component('channel-configuration-microsoft-teams', MicrosoftTeams::class); Livewire::component('channel-configuration-telegram', Telegram::class); return $this; } protected function bootRoutes(): static { if (! $this->app->routesAreCached()) { Route::middleware(['web', 'auth']) ->group(fn () => $this->loadRoutesFrom(__DIR__.'/../routes/web.php')); } return $this; } protected function bootNavigation(): static { Navigation::path(__DIR__.'/../resources/navigation.php'); return $this; } protected function bootNotificationChannels(): static { NotificationRegistry::registerChannel([ NtfyChannel::class, MailChannel::class, DiscordChannel::class, SlackChannel::class, GoogleChatChannel::class, MicrosoftTeamsChannel::class, TelegramChannel::class, ]); return $this; } protected function bootPolicies(): static { Gate::policy(Trigger::class, AllowAllPolicy::class); Gate::policy(Channel::class, AllowAllPolicy::class); return $this; } } ================================================ FILE: packages/notifications/testbench.yaml ================================================ providers: - Vigilant\Notifications\ServiceProvider ================================================ FILE: packages/notifications/tests/Channels/NtfyChannelTest.php ================================================ set('app.name', 'Vigilant'); Http::fake([ 'ntfy/topic' => Http::response(), ]); Channel::withoutEvents(function () { Channel::query()->create([ 'team_id' => 1, 'channel' => NtfyChannel::class, 'settings' => [ 'server' => 'ntfy', 'topic' => 'topic', 'auth_method' => 'username', 'username' => 'username', 'password' => 'password', ], ]); }); $notification = FakeNotification::make(1); /** @var Channel $channelModel */ $channelModel = Channel::query()->withoutGlobalScopes()->first(); /** @var NtfyChannel $channel */ $channel = app(NtfyChannel::class); $channel->fire($notification, $channelModel); Http::assertSent(function (Request $request): bool { return $request->header('Authorization') === ['Basic dXNlcm5hbWU6cGFzc3dvcmQ='] && $request->header('Title') === ['Title of this fake notification - Vigilant'] && $request->header('Tags') === ['triangular_flag_on_post'] && $request->body() === 'Description of this fake notification'; }); } } ================================================ FILE: packages/notifications/tests/Channels/TelegramChannelTest.php ================================================ Http::response(), ]); Channel::withoutEvents(function () { Channel::query()->create([ 'team_id' => 1, 'channel' => TelegramChannel::class, 'settings' => [ 'bot_token' => 'test_bot_token', 'chat_id' => '123456789', ], ]); }); $notification = FakeNotification::make(1); /** @var Channel $channelModel */ $channelModel = Channel::query()->withoutGlobalScopes()->first(); /** @var TelegramChannel $channel */ $channel = app(TelegramChannel::class); $channel->fire($notification, $channelModel); Http::assertSent(function (Request $request): bool { $body = $request->data(); return $request->url() === 'https://api.telegram.org/bottest_bot_token/sendMessage' && $body['chat_id'] === '123456789' && $body['text'] === "*Title of this fake notification*\n\nDescription of this fake notification" && $body['parse_mode'] === 'MarkdownV2'; }); } #[Test] public function it_escapes_markdown_v2_special_characters(): void { Http::fake([ 'api.telegram.org/*' => Http::response(), ]); Channel::withoutEvents(function () { Channel::query()->create([ 'team_id' => 1, 'channel' => TelegramChannel::class, 'settings' => [ 'bot_token' => 'test_bot_token', 'chat_id' => '123456789', ], ]); }); $notification = new class(1) extends FakeNotification { public string $title = 'Alert: CPU_usage > 90% [critical]'; public string $description = 'Host 192.168.1.1 is down. Check #monitoring.'; }; /** @var Channel $channelModel */ $channelModel = Channel::query()->withoutGlobalScopes()->first(); /** @var TelegramChannel $channel */ $channel = app(TelegramChannel::class); $channel->fire($notification, $channelModel); Http::assertSent(function (Request $request): bool { $body = $request->data(); return $body['text'] === "*Alert: CPU\_usage \> 90% \[critical\]*\n\nHost 192\.168\.1\.1 is down\. Check \#monitoring\." && $body['parse_mode'] === 'MarkdownV2'; }); } #[Test] public function it_sends_telegram_message_with_inline_keyboard(): void { Http::fake([ 'api.telegram.org/*' => Http::response(), ]); Channel::withoutEvents(function () { Channel::query()->create([ 'team_id' => 1, 'channel' => TelegramChannel::class, 'settings' => [ 'bot_token' => 'test_bot_token', 'chat_id' => '123456789', ], ]); }); $notification = new class(1) extends FakeNotification { public function viewUrl(): string { return 'https://example.com/view'; } public function url(): string { return 'https://example.com/action'; } public function urlTitle(): string { return 'Take Action'; } }; /** @var Channel $channelModel */ $channelModel = Channel::query()->withoutGlobalScopes()->first(); /** @var TelegramChannel $channel */ $channel = app(TelegramChannel::class); $channel->fire($notification, $channelModel); Http::assertSent(function (Request $request): bool { $body = $request->data(); return $request->url() === 'https://api.telegram.org/bottest_bot_token/sendMessage' && isset($body['reply_markup']['inline_keyboard']) && count($body['reply_markup']['inline_keyboard']) === 2 && $body['reply_markup']['inline_keyboard'][0][0]['text'] === 'View in Vigilant' && $body['reply_markup']['inline_keyboard'][0][0]['url'] === 'https://example.com/view' && $body['reply_markup']['inline_keyboard'][1][0]['text'] === 'Take Action' && $body['reply_markup']['inline_keyboard'][1][0]['url'] === 'https://example.com/action'; }); } } ================================================ FILE: packages/notifications/tests/Conditions/ConditionEngineTest.php ================================================ assertEquals($expected, $engine->checkGroup( FakeNotification::make(1), $groups, $operator )); } public static function conditions(): array { return [ 'No conditions' => [ 'groups' => [], 'operator' => 'all', 'expected' => true, ], 'True' => [ 'groups' => [ 'type' => 'group', 'children' => [ [ 'type' => 'condition', 'condition' => TrueCondition::class, 'operator' => '=', ], ], ], 'operator' => 'all', 'expected' => true, ], 'False' => [ 'groups' => [ 'type' => 'group', 'children' => [ [ 'type' => 'condition', 'condition' => FalseCondition::class, 'operator' => '=', ], ], ], 'operator' => 'all', 'expected' => false, ], 'Any' => [ 'groups' => [ 'type' => 'group', 'children' => [ [ 'type' => 'condition', 'condition' => FalseCondition::class, 'operator' => '=', ], [ 'type' => 'condition', 'condition' => TrueCondition::class, 'operator' => '=', ], ], ], 'operator' => 'any', 'expected' => true, ], 'All' => [ 'groups' => [ 'type' => 'group', 'children' => [ [ 'type' => 'condition', 'condition' => TrueCondition::class, 'operator' => '=', ], [ 'type' => 'condition', 'condition' => FalseCondition::class, 'operator' => '=', ], ], ], 'operator' => 'all', 'expected' => false, ], 'Children' => [ 'groups' => [ 'type' => 'group', 'children' => [ [ 'type' => 'group', 'operator' => 'all', 'children' => [ [ 'type' => 'condition', 'condition' => TrueCondition::class, 'operator' => '=', ], [ 'type' => 'condition', 'condition' => TrueCondition::class, 'operator' => '=', ], ], ], [ 'type' => 'group', 'operator' => 'all', 'children' => [ [ 'type' => 'condition', 'condition' => TrueCondition::class, 'operator' => '=', ], [ 'type' => 'group', 'operator' => 'any', 'children' => [ [ 'type' => 'condition', 'condition' => FalseCondition::class, 'operator' => '=', ], [ 'type' => 'condition', 'condition' => TrueCondition::class, 'operator' => '=', ], ], ], ], ], ], ], 'operator' => 'all', 'expected' => true, ], ]; } } ================================================ FILE: packages/notifications/tests/Fakes/Conditions/FalseCondition.php ================================================ number; } } ================================================ FILE: packages/notifications/tests/Models/ChannelTest.php ================================================ withoutGlobalScopes()->create([ 'team_id' => 1, 'channel' => SlackChannel::class, 'name' => 'Primary Slack', 'settings' => [], ]); }); $this->assertSame('Primary Slack', $channel->title()); } #[Test] public function it_falls_back_to_the_channel_display_name(): void { $channel = Channel::withoutEvents(function () { return Channel::query()->withoutGlobalScopes()->create([ 'team_id' => 1, 'channel' => SlackChannel::class, 'settings' => [], ]); }); $this->assertSame(SlackChannel::$name, $channel->title()); } } ================================================ FILE: packages/notifications/tests/Notifications/NotificationRegistryTest.php ================================================ assertEquals([ FakeNotification::class, ], NotificationRegistry::notifications()); } #[Test] public function it_can_register_channels(): void { NotificationRegistry::registerChannel(FakeChannel::class); $this->assertEquals([ FakeChannel::class, ], NotificationRegistry::channels()); } } ================================================ FILE: packages/notifications/tests/Notifications/NotificationTest.php ================================================ create([ 'team_id' => $team->id, 'channel' => FakeChannel::class, 'settings' => [], ]); Channel::query()->create([ 'team_id' => $team->id, 'channel' => FakeChannel::class, 'settings' => [], ]); Channel::query()->create([ 'team_id' => $team->id + 1, 'channel' => FakeChannel::class, 'settings' => [], ]); Trigger::query()->create([ 'team_id' => $team->id, 'notification' => FakeNotification::class, 'name' => 'Fake Notification', 'conditions' => [], 'all_channels' => true, ]); Trigger::query()->create([ 'team_id' => $team->id, 'notification' => FakeNotification::class, 'name' => 'Fake Notification', 'conditions' => [], 'all_channels' => true, ]); FakeNotification::notify(1); Bus::assertDispatchedTimes(SendNotificationJob::class, 4); } #[Test] public function it_dispatches_notification_single_channels_job(): void { Bus::fake(); $team = TeamService::fake(); Channel::query()->create([ 'team_id' => $team->id, 'channel' => FakeChannel::class, 'settings' => ['a'], ]); Channel::query()->create([ 'team_id' => $team->id, 'channel' => FakeChannel::class, 'settings' => ['b'], ]); /** @var Trigger $trigger */ $trigger = Trigger::query()->create([ 'team_id' => $team->id, 'notification' => FakeNotification::class, 'name' => 'Fake Notification', 'conditions' => [], 'all_channels' => false, ]); $trigger->channels()->sync([Channel::query()->first()->id ?? 1]); FakeNotification::notify(1); Bus::assertDispatched(SendNotificationJob::class, function (SendNotificationJob $job): bool { return $job->notification instanceof FakeNotification; }); } #[Test] public function it_it_arrayable(): void { $notification = FakeNotification::make(1); $this->assertEquals([ 'title' => 'Title of this fake notification', 'description' => 'Description of this fake notification', 'level' => Level::Critical, ], $notification->toArray()); } } ================================================ FILE: packages/notifications/tests/TestCase.php ================================================ set('database.default', 'testbench'); $app['config']->set('database.connections.testbench', [ 'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '', ]); } protected function setUp(): void { parent::setUp(); TeamService::fake(); } } ================================================ FILE: packages/onboarding/.gitignore ================================================ vendor composer.lock .phpunit.result.cache ================================================ FILE: packages/onboarding/composer.json ================================================ { "name": "vigilant/onboarding", "description": "Vigilant Onboarding", "type": "package", "license": "AGPL", "authors": [ { "name": "Vincent Boon", "email": "info@vincentbean.com", "role": "Developer" } ], "require": { "php": "^8.3", "guzzlehttp/guzzle": "^7.8", "laravel/framework": "^12.0", "livewire/livewire": "^3.4", "vigilant/core": "@dev", "vigilant/sites": "@dev", "vigilant/users": "@dev", "vigilant/frontend": "@dev" }, "require-dev": { "laravel/pint": "^1.6", "larastan/larastan": "^3.0", "orchestra/testbench": "^10.0", "phpstan/phpstan-mockery": "^2.0", "phpunit/phpunit": "^11.0" }, "autoload": { "psr-4": { "Vigilant\\OnBoarding\\": "src" } }, "autoload-dev": { "psr-4": { "Vigilant\\OnBoarding\\Tests\\": "tests" } }, "scripts": { "test": "phpunit", "analyse": "phpstan", "style": "pint --test", "quality": [ "@test", "@analyse" ] }, "config": { "sort-packages": true, "allow-plugins": { "php-http/discovery": true } }, "extra": { "laravel": { "providers": [ "Vigilant\\OnBoarding\\ServiceProvider" ] } }, "minimum-stability": "dev", "prefer-stable": true, "repositories": [ { "type": "path", "url": "../*" } ] } ================================================ FILE: packages/onboarding/config/onboarding.php ================================================ id(); $table->foreignIdFor(Team::class)->index(); $table->string('step')->nullable(); $table->dateTime('finished_at')->nullable(); $table->timestamps(); }); } public function down(): void { Schema::dropIfExists('team_onboarding_step'); } }; ================================================ FILE: packages/onboarding/phpstan.neon ================================================ includes: - ./vendor/larastan/larastan/extension.neon - ./vendor/phpstan/phpstan-mockery/extension.neon parameters: paths: - src - tests level: 8 ================================================ FILE: packages/onboarding/phpunit.xml ================================================ ./tests/* ./src ================================================ FILE: packages/onboarding/resources/views/complete.blade.php ================================================ ================================================ FILE: packages/onboarding/resources/views/import-domains.blade.php ================================================
1
Add Sites
2
Notifications
3
Done

@lang('Welcome to Vigilant, :name!', ['name' => $name]) 👋

@lang('Let\'s get you started by importing your websites. Add your domains below and we\'ll set up monitoring for you.')

@lang('What you\'ll get')

@lang('Uptime Monitoring')

@lang('24/7 monitoring to ensure your sites stay online')

@lang('Performance Tracking')

@lang('Monitor site speed and performance metrics')

@lang('Instant Alerts')

@lang('Get notified immediately when issues arise')

================================================ FILE: packages/onboarding/resources/views/notification-channel.blade.php ================================================
Add Sites
2
Notifications
3
Done

@lang('Setup Your Notification Channel')

@lang('Choose how you want to receive alerts when your sites have issues. You can add more channels later.')

================================================ FILE: packages/onboarding/routes/web.php ================================================ group(function () { Route::get('setup', ImportDomains::class) ->name('onboard'); Route::get('setup/notifications', NotificationChannel::class) ->name('onboard.notifications'); Route::get('setup/complete', Complete::class) ->name('onboard.complete'); }); ================================================ FILE: packages/onboarding/src/Actions/ShouldOnboard.php ================================================ team(); /** @var ?OnboardingStep $onBoard */ $onBoard = OnboardingStep::query() ->where('team_id', '=', $team->id) ->where('step', '=', 'complete') ->first(); if ($onBoard !== null && $onBoard->finished_at !== null) { return false; } return true; } } ================================================ FILE: packages/onboarding/src/Http/Middleware/OnlyOnboarding.php ================================================ shouldOnboard()) { return redirect()->route('sites'); } return $next($request); } } ================================================ FILE: packages/onboarding/src/Http/Middleware/RedirectToOnboard.php ================================================ user(); if ( $user === null || $user->email_verified_at === null || Route::is('onboard*') || Route::is('livewire.*') || Route::is('default.livewire.*') || Route::is('quick-setup') || ! $shouldOnboard->shouldOnboard() ) { return $next($request); } return redirect()->route('onboard'); } } ================================================ FILE: packages/onboarding/src/Livewire/Complete.php ================================================ user(); OnboardingStep::query()->updateOrCreate( ['team_id' => $user->currentTeam?->id], ['step' => 'complete', 'finished_at' => now()] ); $this->redirectRoute('sites'); } public function goBack(): void { $this->redirectRoute('onboard.notifications'); } public function checkStepFinished(): void { /** @var User $user */ $user = auth()->user(); OnboardingStep::query()->updateOrCreate( ['team_id' => $user->currentTeam?->id], ['step' => 'complete', 'finished_at' => now()] ); } public function render(): mixed { /** @var view-string $view */ $view = 'onboarding::complete'; return view($view); } } ================================================ FILE: packages/onboarding/src/Livewire/ImportDomains.php ================================================ user(); OnboardingStep::query()->updateOrCreate( ['team_id' => $user->currentTeam?->id], ['step' => 'domain-import', 'finished_at' => now()] ); $this->redirectRoute('onboard.notifications'); } public function checkStepFinished(): void { // Allow users to return to this step even if completed } public function skipOnboarding(): void { /** @var User $user */ $user = auth()->user(); OnboardingStep::query()->updateOrCreate( ['team_id' => $user->currentTeam?->id], ['step' => 'complete', 'finished_at' => now()] ); $this->redirectRoute('sites'); } public function render(): mixed { /** @var view-string $view */ $view = 'onboarding::import-domains'; return view($view, [ 'name' => ucfirst(auth()->user()->name ?? 'User'), ]); } } ================================================ FILE: packages/onboarding/src/Livewire/NotificationChannel.php ================================================ user(); $this->channel = new Channel([ 'channel' => MailChannel::class, 'name' => 'E-mail', 'settings' => [ 'to' => $user->email, ], ]); } #[On('channel-saved')] public function redirectNextStep(): void { /** @var User $user */ $user = auth()->user(); OnboardingStep::query()->updateOrCreate( ['team_id' => $user->currentTeam?->id], ['step' => 'notification-channel', 'finished_at' => now()] ); $this->redirectRoute('onboard.complete'); } public function goBack(): void { /** @var User $user */ $user = auth()->user(); // Clear the current step so users can go back OnboardingStep::query() ->where('team_id', '=', $user->currentTeam?->id) ->where('step', '=', 'notification-channel') ->delete(); $this->redirectRoute('onboard'); } public function checkStepFinished(): void { /** @var User $user */ $user = auth()->user(); $onBoard = OnboardingStep::query() ->where('team_id', '=', $user->currentTeam?->id) ->where('step', '=', 'notification-channel') ->first(); if ($onBoard !== null && $onBoard->finished_at !== null) { $this->redirectRoute('onboard.complete'); } } public function skipOnboarding(): void { /** @var User $user */ $user = auth()->user(); OnboardingStep::query()->updateOrCreate( ['team_id' => $user->currentTeam?->id], ['step' => 'complete', 'finished_at' => now()] ); $this->redirectRoute('sites'); } public function render(): mixed { /** @var view-string $view */ $view = 'onboarding::notification-channel'; return view($view); } } ================================================ FILE: packages/onboarding/src/Models/OnboardingStep.php ================================================ registerConfig(); } protected function registerConfig(): static { $this->mergeConfigFrom(__DIR__.'/../config/onboarding.php', 'onboarding'); return $this; } public function boot(): void { $this ->bootConfig() ->bootMigrations() ->bootCommands() ->bootViews() ->bootLivewire() ->bootRoutes(); } protected function bootConfig(): static { $this->publishes([ __DIR__.'/../config/onboarding.php' => config_path('onboarding.php'), ], 'config'); return $this; } protected function bootMigrations(): static { $this->loadMigrationsFrom(__DIR__.'/../database/migrations'); return $this; } protected function bootCommands(): static { if ($this->app->runningInConsole()) { $this->commands([ ]); } return $this; } protected function bootViews(): static { $this->loadViewsFrom(__DIR__.'/../resources/views', 'onboarding'); return $this; } protected function bootLivewire(): static { Livewire::component('onboarding-import-domains', ImportDomains::class); Livewire::component('onboarding-monitoring-channel', NotificationChannel::class); Livewire::component('onboarding-complete', Complete::class); return $this; } protected function bootRoutes(): static { if (! $this->app->routesAreCached()) { Route::middleware(['web', 'auth']) ->group(fn () => $this->loadRoutesFrom(__DIR__.'/../routes/web.php')); } return $this; } } ================================================ FILE: packages/onboarding/testbench.yaml ================================================ providers: - Vigilant\OnBoarding\ServiceProvider ================================================ FILE: packages/onboarding/tests/TestCase.php ================================================ set('database.default', 'testbench'); $app['config']->set('database.connections.testbench', [ 'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '', ]); } } ================================================ FILE: packages/settings/.gitignore ================================================ vendor composer.lock .phpunit.result.cache ================================================ FILE: packages/settings/composer.json ================================================ { "name": "vigilant/settings", "description": "Vigilant settings", "type": "package", "license": "AGPL", "authors": [ { "name": "Vincent Boon", "email": "info@vincentbean.com", "role": "Developer" } ], "require": { "php": "^8.3", "guzzlehttp/guzzle": "^7.8", "laravel/framework": "^12.0", "livewire/livewire": "^3.4", "vigilant/core": "@dev", "vigilant/sites": "@dev", "vigilant/users": "@dev", "vigilant/frontend": "@dev" }, "require-dev": { "laravel/pint": "^1.6", "larastan/larastan": "^3.0", "orchestra/testbench": "^10.0", "phpstan/phpstan-mockery": "^2.0", "phpunit/phpunit": "^11.0" }, "autoload": { "psr-4": { "Vigilant\\Settings\\": "src", "Vigilant\\Settings\\Database\\Factories\\": "database/factories", "Vigilant\\Users\\Database\\Factories\\": "../users/database/factories" } }, "autoload-dev": { "psr-4": { "Vigilant\\Settings\\Tests\\": "tests" } }, "scripts": { "test": "phpunit", "analyse": "phpstan", "style": "pint --test", "quality": [ "@test", "@analyse" ] }, "config": { "sort-packages": true, "allow-plugins": { "php-http/discovery": true } }, "extra": { "laravel": { "providers": [ "Vigilant\\Settings\\ServiceProvider" ] } }, "minimum-stability": "dev", "prefer-stable": true, "repositories": [ { "type": "path", "url": "../*" } ] } ================================================ FILE: packages/settings/config/settings.php ================================================ ./tests/* ./src ================================================ FILE: packages/settings/resources/views/index.blade.php ================================================
{{-- Tab Navigation --}}
{{-- Tab Panels --}}
@foreach($tabs as $key => $data)
first)x-cloak @endif x-transition:enter="transition ease-out duration-300" x-transition:enter-start="opacity-0 transform translate-y-4" x-transition:enter-end="opacity-100 transform translate-y-0"> @if(array_key_exists('component', $data)) @endif
@endforeach
================================================ FILE: packages/settings/resources/views/tabs/profile.blade.php ================================================
@lang('Profile')
{{-- Password change--}} {{-- Delete account --}} {{-- @if (Laravel\Fortify\Features::enabled(Laravel\Fortify\Features::updatePasswords()))--}} {{--
--}} {{-- @livewire('profile.update-password-form')--}} {{--
--}} {{-- --}} {{-- @endif--}} {{-- @if (Laravel\Jetstream\Jetstream::hasAccountDeletionFeatures())--}} {{-- --}} {{--
--}} {{-- @livewire('profile.delete-user-form')--}} {{--
--}} {{-- @endif--}}
================================================ FILE: packages/settings/resources/views/tabs/security.blade.php ================================================
@lang('Password')
@lang('Additional Security Settings') @if (Laravel\Fortify\Features::canManageTwoFactorAuthentication())
@livewire('profile.two-factor-authentication-form')
@endif
@livewire('profile.logout-other-browser-sessions-form')
================================================ FILE: packages/settings/resources/views/tabs/team.blade.php ================================================
@livewire('teams.update-team-name-form', ['team' => $team]) @livewire('teams.team-member-manager', ['team' => $team]) @if (Gate::check('delete', $team) && ! $team->personal_team)
@livewire('teams.delete-team-form', ['team' => $team])
@endif
================================================ FILE: packages/settings/routes/web.php ================================================ name('settings'); ================================================ FILE: packages/settings/src/Livewire/Forms/ProfileForm.php ================================================ ['required', 'string', 'current_password:web'], 'password' => $this->passwordRules(), ]; } public function messages(): array { return [ 'current_password.current_password' => __('The provided password does not match your current password.'), ]; } } ================================================ FILE: packages/settings/src/Livewire/Settings.php ================================================ tab)) { /** @var string $tab */ $tab = Arr::first(array_keys($this->tabs())); $this->tab = $tab; } } protected function tabs(): array { $tabs = []; $tabs['profile'] = [ 'title' => 'Profile', 'component' => 'settings-tab-profile', ]; $tabs['security'] = [ 'title' => 'Account Security', 'component' => 'settings-tab-security', ]; if (Jetstream::hasTeamFeatures()) { $tabs['team'] = [ 'title' => 'Team Settings', 'component' => 'settings-tab-team', ]; } if (! ce()) { $tabs['billing'] = [ 'title' => 'Billing', 'component' => 'settings-tab-billing', ]; $tabs['company'] = [ 'title' => 'Company Info', 'component' => 'settings-tab-company-info', ]; } return $tabs; } public function render(): mixed { /** @var view-string $view */ $view = 'settings::index'; return view($view, [ 'tabs' => $this->tabs(), 'tab' => $this->tab, ]); } } ================================================ FILE: packages/settings/src/Livewire/Tabs/Profile.php ================================================ user(); $this->form->fill($user->toArray()); } public function save(): void { $this->validate(); /** @var User $user */ $user = auth()->user(); $validated = $this->form->validate(); $user->update($validated); $this->alert( __('Saved'), __('Profile information saved'), AlertType::Success ); } public function render(): mixed { /** @var view-string $view */ $view = 'settings::tabs.profile'; return view($view); } } ================================================ FILE: packages/settings/src/Livewire/Tabs/Security.php ================================================ password->validate(); /** @var User $user */ $user = auth()->user(); $user->forceFill([ 'password' => Hash::make($validated['password']), ])->save(); $this->password->reset(); $this->alertBrowser( __('Saved'), __('Password changed'), AlertType::Success ); } public function render(): mixed { /** @var view-string $view */ $view = 'settings::tabs.security'; return view($view); } } ================================================ FILE: packages/settings/src/Livewire/Tabs/Team.php ================================================ user(); /** @var view-string $view */ $view = 'settings::tabs.team'; return view($view, [ 'team' => $user->currentTeam, ]); } } ================================================ FILE: packages/settings/src/ServiceProvider.php ================================================ registerConfig(); } protected function registerConfig(): static { $this->mergeConfigFrom(__DIR__.'/../config/settings.php', 'settings'); return $this; } public function boot(): void { $this ->bootConfig() ->bootMigrations() ->bootCommands() ->bootViews() ->bootLivewire() ->bootRoutes(); } protected function bootConfig(): static { $this->publishes([ __DIR__.'/../config/settings.php' => config_path('settings.php'), ], 'config'); return $this; } protected function bootMigrations(): static { $this->loadMigrationsFrom(__DIR__.'/../database/migrations'); return $this; } protected function bootCommands(): static { if ($this->app->runningInConsole()) { $this->commands([ ]); } return $this; } protected function bootViews(): static { $this->loadViewsFrom(__DIR__.'/../resources/views', 'settings'); return $this; } protected function bootLivewire(): static { Livewire::component('settings-tab-profile', Profile::class); Livewire::component('settings-tab-team', Team::class); Livewire::component('settings-tab-security', Security::class); return $this; } protected function bootRoutes(): static { if (! $this->app->routesAreCached()) { Route::middleware(['web', 'auth']) ->group(fn () => $this->loadRoutesFrom(__DIR__.'/../routes/web.php')); } return $this; } } ================================================ FILE: packages/settings/testbench.yaml ================================================ providers: - Vigilant\Settings\ServiceProvider ================================================ FILE: packages/settings/tests/TestCase.php ================================================ set('database.default', 'testbench'); $app['config']->set('database.connections.testbench', [ 'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '', ]); } } ================================================ FILE: packages/sites/.gitignore ================================================ vendor composer.lock .phpunit.result.cache ================================================ FILE: packages/sites/composer.json ================================================ { "name": "vigilant/sites", "description": "Vigilant Sites", "type": "package", "license": "AGPL", "authors": [ { "name": "Vincent Boon", "email": "info@vincentbean.com", "role": "Developer" } ], "require": { "php": "^8.3", "laravel/framework": "^12.0", "livewire/livewire": "^3.4", "vigilant/core": "@dev", "vigilant/notifications": "@dev", "vigilant/lighthouse": "@dev", "vigilant/dns": "@dev", "vigilant/uptime": "@dev", "vigilant/crawler": "@dev", "vigilant/certificates": "@dev", "vigilant/healthchecks": "@dev" }, "require-dev": { "laravel/pint": "^1.6", "larastan/larastan": "^3.0", "orchestra/testbench": "^10.0", "phpstan/phpstan-mockery": "^2.0", "phpunit/phpunit": "^11.0" }, "autoload": { "psr-4": { "Vigilant\\Sites\\": "src" } }, "autoload-dev": { "psr-4": { "Vigilant\\Sites\\Tests\\": "tests" } }, "scripts": { "test": "phpunit", "analyse": "phpstan", "style": "pint --test", "quality": [ "@test", "@analyse" ] }, "config": { "sort-packages": true, "allow-plugins": { "php-http/discovery": true } }, "extra": { "laravel": { "providers": [ "Vigilant\\Sites\\ServiceProvider" ] } }, "minimum-stability": "dev", "prefer-stable": true, "repositories": [ { "type": "path", "url": "../*" } ] } ================================================ FILE: packages/sites/config/sites.php ================================================ 'default', ]; ================================================ FILE: packages/sites/database/migrations/2024_02_20_170000_create_sites_table.php ================================================ id(); $table->foreignIdFor(Team::class)->index(); $table->string('url'); $table->timestamps(); }); } public function down(): void { Schema::dropIfExists('sites'); } }; ================================================ FILE: packages/sites/phpstan.neon ================================================ includes: - ./vendor/larastan/larastan/extension.neon - ./vendor/phpstan/phpstan-mockery/extension.neon parameters: paths: - src - tests level: 8 ignoreErrors: - '#return type with generic class#' ================================================ FILE: packages/sites/phpunit.xml ================================================ ./tests/* ./src ================================================ FILE: packages/sites/resources/navigation.php ================================================ routeIs('site*') ->icon('tni-hd-screen-o') ->sort(100); ================================================ FILE: packages/sites/resources/views/components/empty-states/no-monitors.blade.php ================================================ @props(['site']) ================================================ FILE: packages/sites/resources/views/components/site-card.blade.php ================================================ @props(['site']) @php use Vigilant\Lighthouse\Livewire\Tables\LighthouseMonitorsTable; use Vigilant\Uptime\Actions\CalculateUptimePercentage; use Vigilant\Frontend\Integrations\Table\Enums\Status; /** @var \Vigilant\Sites\Models\Site $site */ // Calculate uptime $calculateUptime = app(CalculateUptimePercentage::class); $uptimeMonitor = $site->uptimeMonitor; $uptimePercentage = $uptimeMonitor ? $calculateUptime->calculate($uptimeMonitor) : null; // Get Lighthouse score $lighthouseMonitor = $site->lighthouseMonitors()->first(); $lighthouseResult = $lighthouseMonitor?->lighthouseResults()->orderByDesc('id')->first(); $lighthouseScore = null; if ($lighthouseResult) { $scores = [ $lighthouseResult->performance, $lighthouseResult->accessibility, $lighthouseResult->best_practices, $lighthouseResult->seo, ]; $lighthouseScore = array_sum($scores) / count($scores); } // Get last downtime $lastDowntime = null; if ($uptimeMonitor) { $lastDowntime = $uptimeMonitor->downtimes()->whereNotNull('end')->orderByDesc('start')->first(); } // Get link issues $crawler = $site->crawler; $issueCount = $crawler?->issueCount() ?? 0; $totalUrlCount = $crawler?->totalUrlCount() ?? 0; $issueStatus = null; if ($crawler) { if ($issueCount === 0) { $issueStatus = Status::Success; } else { $threshold = $totalUrlCount * 0.05; $issueStatus = $issueCount > $threshold ? Status::Danger : Status::Warning; } } // Get certificate info $certificate = $site->certificateMonitor; $certificateStatus = null; if ($certificate && $certificate->valid_to) { $diff = now()->diffInDays($certificate->valid_to); if ($diff > 30) { $certificateStatus = Status::Success; } elseif ($diff > 7) { $certificateStatus = Status::Warning; } else { $certificateStatus = Status::Danger; } } // Get healthcheck info $healthcheck = $site->healthcheck; $healthcheckStatus = null; if ($healthcheck) { $healthcheckStatus = match($healthcheck->status?->value ?? null) { 'healthy' => Status::Success, 'warning' => Status::Warning, 'unhealthy' => Status::Danger, default => null, }; } @endphp

{{ $site->url }}

Lighthouse
@if ($lighthouseScore !== null) {!! LighthouseMonitorsTable::scoreDisplay($lighthouseScore) !!} @elseif ($lighthouseResult === null && $lighthouseMonitor !== null) {{ __('No Results') }} @else @endif
Uptime
@if ($uptimePercentage !== null) @php $uptimeClass = match (true) { $uptimePercentage > 95 => 'text-green-light', $uptimePercentage > 80 => 'text-orange', default => 'text-red', }; @endphp {{ $uptimePercentage }}% @elseif ($uptimeMonitor !== null) {{ __('Not available yet') }} @else @endif
@if ($uptimeMonitor !== null)
Last downtime
@if ($lastDowntime !== null) {{ teamTimezone($lastDowntime->start)->diffForHumans() }} @else {{ __('Never') }} @endif
@endif @if ($crawler !== null)
Link Issues
@if ($issueStatus === Status::Success)
@elseif($issueStatus === Status::Warning)
@else
@endif
{{ __(':count issues', ['count' => $issueCount]) }}
@endif @if ($certificate !== null && $certificate->valid_to !== null)
Certificate
@if ($certificateStatus === Status::Success)
@elseif($certificateStatus === Status::Warning)
@else
@endif
{{ __('Expires in :diff', ['diff' => teamTimezone($certificate->valid_to)->shortAbsoluteDiffForHumans()]) }}
@endif
@if ($healthcheck !== null)
@if ($healthcheckStatus === Status::Success)
@elseif($healthcheckStatus === Status::Warning)
@elseif($healthcheckStatus === Status::Danger)
@else
@endif
Health
@if ($healthcheck->status) {{ ucfirst($healthcheck->status->value) }} @else {{ __('Unknown') }} @endif
@endif
{{ __('View details') }}
================================================ FILE: packages/sites/resources/views/livewire/form.blade.php ================================================
@if (!$inline) @endif
@if ($updating)
@foreach ($tabs as $key => $data)
@endforeach
@endif @if (!$inline) @endif
================================================ FILE: packages/sites/resources/views/livewire/import.blade.php ================================================
@if (!$inline) @endif
@if ($validatedDomains === [])
@lang('Add domains or URLs to import, one per line')
@error('urls') {{ $message }} @enderror

@lang('Monitoring Features')

@lang('Select which monitors to enable for your imported sites')

@foreach ($availableMonitors as $key => $monitor) @endforeach
@error('monitors') {{ $message }} @enderror
@else

@lang('Ready to import :count sites', ['count' => count($validatedDomains)])

@lang('Review the domains below before importing')

    @foreach ($validatedDomains as $domain)
  • {{ $domain }}
  • @endforeach
@endif
================================================ FILE: packages/sites/resources/views/livewire/sites.blade.php ================================================
@lang('Add Multiple Sites') @lang('Add Site') @lang('Add Site') @lang('Add Multiple Sites')
@if ($sites->count() > 0)
@foreach ($sites as $site) @endforeach
@if ($sites->hasPages())
{{ $sites->links() }}
@endif @else

{{ __('No sites yet') }}

{{ __('Get started by adding your first site.') }}

@lang('Add Site')
@endif
================================================ FILE: packages/sites/resources/views/livewire/tabs/certificate-monitor.blade.php ================================================
@if ($enabled) @endif
================================================ FILE: packages/sites/resources/views/livewire/tabs/crawler.blade.php ================================================
@if($enabled) @endif
================================================ FILE: packages/sites/resources/views/livewire/tabs/dns-monitors.blade.php ================================================
================================================ FILE: packages/sites/resources/views/livewire/tabs/healthcheck-monitor.blade.php ================================================
@if($enabled) @endif
================================================ FILE: packages/sites/resources/views/livewire/tabs/lighthouse-monitor.blade.php ================================================

@lang('Pages')

@lang('Select which pages have to be monitored by Lighthouse. You may add multiple URLs.')

@lang('URL')

@lang('Interval')

@foreach ($monitors as $index => $monitor)
@error("monitors.$index.url") {{ $message }} @enderror
@if (!blank($monitor['id'] ?? null))
@lang('View')
@else @endif @endforeach
@lang('Add Lighthouse Monitor')
================================================ FILE: packages/sites/resources/views/livewire/tabs/uptime-monitor.blade.php ================================================
@if($enabled) @endif
================================================ FILE: packages/sites/resources/views/sites/view.blade.php ================================================ @lang('Edit') @lang('Delete') @lang('Edit') @lang('Delete') @if ($empty) @else {{-- Tab Navigation --}} {{-- Tab Panels --}}
@foreach($tabs as $index => $tab) @if(!isset($tab['gate']) || auth()->user()->can($tab['gate'])) {{-- Section Header with Link --}}

@svg($tab['icon'], 'size-6 text-' . $tab['color']) {{ $tab['title'] }}

{{ $tab['description'] }}

@lang('View Details') @svg('tni-right-o', 'size-4 group-hover:translate-x-1 transition-transform duration-300')
@if($tab['key'] === 'uptime') @elseif($tab['key'] === 'lighthouse') @elseif($tab['key'] === 'crawler') @elseif($tab['key'] === 'dns') @elseif($tab['key'] === 'certificate') @elseif($tab['key'] === 'healthcheck') @endif
@endif @endforeach
@endif
@lang('Delete Site')

@lang('Are you sure you want to delete this site?')

@svg('phosphor-warning-circle', 'w-5 h-5 text-orange mt-0.5')

{{ $site->url }}

@lang('This action cannot be undone. This will permanently delete the site and all associated monitors (uptime, lighthouse, crawler, etc.).')

@lang('Cancel')
@csrf @method('DELETE') @lang('Delete Site')
================================================ FILE: packages/sites/routes/web.php ================================================ name('sites'); Route::get('site/create', SiteForm::class)->name('site.create'); Route::get('site/{site}', [SiteController::class, 'view'])->name('site.view'); Route::get('site/edit/{site}', SiteForm::class)->name('site.edit'); Route::delete('site/{site}', [SiteController::class, 'delete'])->name('site.delete'); Route::get('sites/import', ImportSites::class)->name('site.import'); ================================================ FILE: packages/sites/src/Actions/ImportSite.php ================================================ $monitors */ public function import(int $teamId, string $domain, array $monitors): void { $this->teamService->setTeamById($teamId); $user = User::query()->firstWhere('current_team_id', $teamId); throw_if($user === null, 'User not found'); if (Gate::forUser($user)->denies('create', Site::class)) { return; } $site = Site::query()->firstOrCreate(['url' => 'https://'.$domain]); if ($monitors['uptime'] ?? false) { $this->importUptime($site); } if ($monitors['lighthouse'] ?? false) { $this->importLighthouse($site); } if ($monitors['dns'] ?? false) { $this->importDns($site); } if ($monitors['certificate'] ?? false) { $this->importCertificate($site); } if ($monitors['crawler'] ?? false) { $this->importCrawler($site); } } protected function importUptime(Site $site): void { Monitor::query()->firstOrCreate([ 'site_id' => $site->id, 'team_id' => $site->team_id, ], [ 'name' => $site->url, 'enabled' => true, 'type' => Type::Http, 'interval' => 60, 'retries' => 1, 'timeout' => 5, 'settings' => [ 'host' => $site->url, ], ]); } protected function importLighthouse(Site $site): void { $intervals = array_keys(config()->array('lighthouse.intervals')); LighthouseMonitor::query()->firstOrCreate([ 'site_id' => $site->id, 'team_id' => $site->team_id, ], [ 'url' => $site->url, 'interval' => Arr::first($intervals), 'settings' => [], ]); } protected function importDns(Site $site): void { /** @var array $records */ $records = $this->dnsClient->get($this->stripProtocol($site->url), [ RecordTypes::A, RecordTypes::AAAA, RecordTypes::CNAME, RecordTypes::SOA, RecordTypes::TXT, RecordTypes::MX, RecordTypes::NS, ]); foreach ($records as $record) { $data = $record->toArray(); $type = DnsType::tryFrom($data['type']); if ($type === null || ! $type->hasParser()) { continue; } $value = $type->parser()->parse($data); DnsMonitor::query()->updateOrCreate([ 'site_id' => $site->id, 'team_id' => $site->team_id, 'type' => $type, 'record' => $record->getHost(), ], [ 'value' => $value, ]); } } protected function importCertificate(Site $site): void { CertificateMonitor::query()->firstOrCreate([ 'site_id' => $site->id, 'team_id' => $site->team_id, ], [ 'domain' => $this->stripProtocol($site->url), 'port' => str_starts_with($site->url, 'https://') ? 443 : 80, ]); } protected function importCrawler(Site $site): void { Crawler::query()->firstOrCreate([ 'site_id' => $site->id, 'team_id' => $site->team_id, ], [ 'state' => State::Pending, 'schedule' => '0 10 * * 1', 'start_url' => $site->url, ]); } protected function stripProtocol(string $domain): string { return preg_replace('#^https?://#', '', $domain) ?? $domain; } } ================================================ FILE: packages/sites/src/Conditions/SiteCondition.php ================================================ site(); if ($site === null) { return false; } return match ($operator) { '=' => $site->id == $value, '!=' => $site->id != $value, default => false, }; } /** {@inheritDoc} */ public function operators(): array { return [ '=' => 'is', '!=' => 'is not', ]; } /** {@inheritDoc} */ public function options(): array { return Site::query()->get() ->mapWithKeys(fn (Site $site): array => [$site->id => $site->url]) ->toArray(); } } ================================================ FILE: packages/sites/src/Http/Controllers/SiteController.php ================================================ $site->uptimeMonitor, 'lighthouseMonitor' => $site->lighthouseMonitors->first(), 'crawler' => $site->crawler, 'certificateMonitor' => $site->certificateMonitor, 'healthcheck' => $site->healthcheck, ]; // Define tabs configuration $tabs = []; if ($site->uptimeMonitor !== null) { $tabs[] = [ 'key' => 'uptime', 'label' => __('Uptime'), 'icon' => 'tni-double-caret-up-circle-o', 'color' => 'red', 'title' => __('Uptime Monitoring'), 'description' => __('Monitor your site availability and response times'), 'route' => route('uptime.monitor.view', ['monitor' => $site->uptimeMonitor]), 'monitor' => $site->uptimeMonitor, 'component' => 'monitor-dashboard', 'componentKey' => 'uptime-dashboard', 'gate' => 'use-uptime', ]; } if ($site->lighthouseMonitors->first() !== null) { $tabs[] = [ 'key' => 'lighthouse', 'label' => __('Lighthouse'), 'icon' => 'phosphor-lighthouse-light', 'color' => 'blue', 'title' => __('Lighthouse Performance'), 'description' => __('Track your site performance, accessibility, and SEO scores'), 'route' => route('lighthouse.index', ['monitor' => $site->lighthouseMonitors->first()]), 'monitor' => $site->lighthouseMonitors->first(), 'component' => 'lighthouse-monitor-dashboard', 'componentKey' => 'lighthouse-dashboard', ]; } if ($site->crawler !== null) { $tabs[] = [ 'key' => 'crawler', 'label' => __('URL Issues'), 'icon' => 'carbon-text-link', 'color' => 'purple', 'title' => __('URL Issues'), 'description' => __('Identify broken links and crawl errors on your site'), 'route' => route('crawler.view', ['crawler' => $site->crawler]), 'monitor' => $site->crawler, 'component' => 'crawler-dashboard', 'componentKey' => 'crawler-dashboard', ]; } if ($site->dnsMonitors->count() > 0) { $tabs[] = [ 'key' => 'dns', 'label' => __('DNS Records'), 'icon' => 'phosphor-globe-simple', 'color' => 'indigo', 'title' => __('DNS Records'), 'description' => __('Monitor your DNS configuration and record changes'), 'route' => route('dns.index'), 'monitor' => $site, 'component' => 'dns-monitor-dashboard', 'componentKey' => 'dns-dashboard', ]; } if ($site->certificateMonitor !== null) { $tabs[] = [ 'key' => 'certificate', 'label' => __('Certificate'), 'icon' => 'phosphor-certificate', 'color' => 'green', 'title' => __('SSL Certificate'), 'description' => __('Monitor SSL certificate validity and expiration dates'), 'route' => route('certificates.index', ['monitor' => $site->certificateMonitor]), 'monitor' => $site->certificateMonitor, 'component' => 'certificate-monitor-dashboard', 'componentKey' => 'certificate-dashboard', 'gate' => 'use-certificates', ]; } if ($site->healthcheck !== null) { $tabs[] = [ 'key' => 'healthcheck', 'label' => __('Healthcheck'), 'icon' => 'phosphor-heartbeat', 'color' => 'teal', 'title' => __('Healthcheck Monitoring'), 'description' => __('Monitor application health and custom metrics'), 'route' => route('healthchecks.view', ['healthcheck' => $site->healthcheck]), 'monitor' => $site->healthcheck, 'component' => 'healthcheck-dashboard', 'componentKey' => 'healthcheck-dashboard', 'gate' => 'use-healthchecks', ]; } $data = array_merge([ 'site' => $site, 'empty' => collect($monitors)->filter()->isEmpty(), 'tabs' => $tabs, ], $monitors); /** @var view-string $view */ $view = 'sites::sites.view'; return view($view, $data); } public function delete(Site $site): RedirectResponse { $site->delete(); return redirect()->route('sites')->with('success', __('Site deleted successfully.')); } } ================================================ FILE: packages/sites/src/Http/Livewire/Forms/CreateSiteForm.php ================================================ */ public array $validatedDomains = []; /** @var array */ public array $monitors = [ 'uptime' => true, 'lighthouse' => true, 'dns' => true, 'certificate' => true, 'crawler' => true, ]; public function mount(): void { if (session()->has('import_urls')) { $this->urls = implode(PHP_EOL, session()->get('import_urls', [])); session()->forget('import_urls'); } } public function confirm(): void { $this->validatedDomains = str($this->urls) ->explode("\n") ->map(fn (string $url): string => trim($url)) ->map(function (string $url): string { $url = preg_replace('#^https?://#', '', $url) ?? ''; $url = preg_replace('#/.*$#', '', $url) ?? ''; return $url; }) ->filter(fn (string $url): bool => ! blank($url)) ->filter(fn (string $url): mixed => preg_match('/^(?!:\/\/)([a-zA-Z0-9-_]+\.)+[a-zA-Z]{2,}$/', $url) === 1) ->all(); $this->urls = implode(PHP_EOL, $this->validatedDomains); $this->validate([ 'urls' => 'required|string', 'monitors' => 'array|min:1', ]); } public function cancel(): void { $this->validatedDomains = []; } public function import(): void { /** @var User $user */ $user = auth()->user(); abort_if($user->current_team_id === null, 403); foreach ($this->validatedDomains as $domain) { ImportSiteJob::dispatch( teamId: $user->current_team_id, domain: $domain, monitors: $this->monitors, ); } if ($this->inline) { $this->dispatch('sites-imported'); return; } $this->alert( __('Saved'), __(':count sites are being imported', ['count' => count($this->validatedDomains)]), AlertType::Success ); $this->redirectRoute('sites'); } public function render(): View { /** @var view-string $view */ $view = 'sites::livewire.import'; return view($view, [ 'availableMonitors' => [ 'uptime' => [ 'label' => __('Uptime'), 'description' => __('Track uptime and response times, get notified when your site goes down'), ], 'lighthouse' => [ 'label' => __('Lighthouse'), 'description' => __('Monitor Google Lighthouse scores'), ], 'dns' => [ 'label' => __('DNS'), 'description' => __('Track changes in DNS records'), ], 'certificate' => [ 'label' => __('Certificate'), 'description' => __('Monitor SSL certificate expiration and validity'), ], 'crawler' => [ 'label' => __('Link Issues'), 'description' => __('Crawl your site to find broken links and errors'), ], ], ]); } } ================================================ FILE: packages/sites/src/Http/Livewire/SiteForm.php ================================================ form->fill($site->toArray()); $this->site = $site; } if ($domain = request()->query('domain')) { $this->form->fill(['url' => $this->normalizeDomainToUrl($domain)]); } } protected function normalizeDomainToUrl(string $domain): string { $domain = strtolower(trim($domain)); if (str_starts_with($domain, 'http://') || str_starts_with($domain, 'https://')) { return $domain; } return 'https://' . $domain; } #[On('save')] public function save(): void { // Save tabs if ($this->site->exists) { $this->dispatch('save'); } $this->form->url = $this->normalizeUrl($this->form->url); $this->validate(); if ($this->site->exists) { $this->site->update($this->form->all()); } else { $this->site = Site::query()->create( $this->form->all() ); } if ($this->inline) { $this->dispatch('siteSaved', $this->site->id); return; } $this->alert( __('Saved'), __('Site was successfully :action', ['action' => $this->site->wasRecentlyCreated ? 'created' : 'saved']), AlertType::Success ); $this->redirectRoute('site.view', ['site' => $this->site]); } public function render(): View { $tabs = collect($this->tabs()) ->filter(fn (array $tab) => ! array_key_exists('gate', $tab) || Gate::check($tab['gate'])) ->toArray(); /** @var view-string $view */ $view = 'sites::livewire.form'; return view($view, [ 'updating' => $this->site->exists, 'tabs' => $tabs, ]); } private function normalizeUrl(?string $url): string { if ($url === null) { return ''; } $parts = parse_url($url); if ($parts === false || ! isset($parts['scheme'], $parts['host'])) { return rtrim($url, '/'); } return sprintf('%s://%s', $parts['scheme'], $parts['host']); } /** @return array> */ protected function tabs(): array { return [ 'uptime' => [ 'title' => __('Uptime Monitoring'), 'component' => 'sites.tabs.uptime-monitor', 'gate' => 'use-uptime', 'model' => UptimeMonitor::class, ], 'lighthouse' => [ 'title' => __('Lighthouse Monitoring'), 'component' => 'sites.tabs.lighthouse-monitor', 'gate' => 'use-lighthouse', 'model' => LighthouseMonitor::class, ], 'dns' => [ 'title' => __('DNS Monitoring'), 'component' => 'sites.tabs.dns-monitors', 'gate' => 'use-dns', 'model' => DnsMonitor::class, ], 'crawler' => [ 'title' => __('Link Issues'), 'component' => 'sites.tabs.crawler', 'gate' => 'use-crawler', 'model' => Crawler::class, ], 'certificates' => [ 'title' => __('Certificate Monitoring'), 'component' => 'sites.tabs.certificate-monitor', 'gate' => 'use-certificates', 'model' => CertificateMonitor::class, ], 'healthcheck' => [ 'title' => __('Healthcheck Monitoring'), 'component' => 'sites.tabs.healthcheck-monitor', 'gate' => 'use-healthchecks', 'model' => Healthcheck::class, ], ]; } } ================================================ FILE: packages/sites/src/Http/Livewire/Sites.php ================================================ with([ 'uptimeMonitor.downtimes', 'lighthouseMonitors.lighthouseResults', 'crawler', 'certificateMonitor', ]) ->paginate(10); /** @var view-string $view */ $view = 'sites::livewire.sites'; return view($view, [ 'sites' => $sites, ]); } } ================================================ FILE: packages/sites/src/Http/Livewire/Tables/SiteTable.php ================================================ */ protected function columns(): array { /** @var CalculateUptimePercentage $calculateUptime */ $calculateUptime = app(CalculateUptimePercentage::class); return [ Column::make(__('URL'), 'url'), Column::make(__('Average Lighthouse Score')) ->displayUsing(function (Site $site) { /** @var ?LighthouseMonitor $monitor */ $monitor = $site->lighthouseMonitors()->first(); if ($monitor === null) { return null; } /** @var ?LighthouseResult $result */ $result = $monitor->lighthouseResults()->orderByDesc('id')->first(); if ($result === null) { return __('No Results'); } $scores = [ $result->performance, $result->accessibility, $result->best_practices, $result->seo, ]; $score = array_sum($scores) / count($scores); return LighthouseMonitorsTable::scoreDisplay($score); }) ->asHtml(), Column::make(__('Uptime')) ->displayUsing(function (Site $site) use ($calculateUptime) { $monitor = $site->uptimeMonitor; if ($monitor === null) { return null; } $percentage = $calculateUptime->calculate($monitor); if ($percentage === null) { return __('Not available yet'); } $class = match (true) { $percentage > 95 => 'text-green-light', $percentage > 80 => 'text-orange', default => 'text-red' }; return "$percentage%"; }) ->asHtml(), Column::make(__('Last downtime')) ->displayUsing(function (Site $site) { $monitor = $site->uptimeMonitor; if ($monitor === null) { return null; } /** @var ?Downtime $lastDowntime */ $lastDowntime = $monitor->downtimes() ->whereNotNull('end') ->orderByDesc('start') ->first(); if ($lastDowntime === null) { return __('Never'); } return teamTimezone($lastDowntime->start)->diffForHumans(); }), StatusColumn::make(__('Link Issues')) ->text(function (Site $site) { $crawler = $site->crawler; if ($crawler === null) { return null; } return __(':count issues', ['count' => $crawler->issueCount() ?? '0']); }) ->status(function (Site $site): ?Status { $crawler = $site->crawler; if ($crawler === null) { return null; } $count = $crawler->issueCount(); if ($count === null || $count === 0) { return Status::Success; } $total = $crawler->totalUrlCount(); $threshold = $total * 0.05; return $count > $threshold ? Status::Danger : Status::Warning; }), StatusColumn::make(__('Certificate')) ->text(function (Site $site) { $certificate = $site->certificateMonitor; if ($certificate === null || $certificate->valid_to === null) { return null; } return __('Expires in :diff', [ 'diff' => teamTimezone($certificate->valid_to)->longAbsoluteDiffForHumans(), ]); }) ->status(function (Site $site): ?Status { $certificate = $site->certificateMonitor; if ($certificate === null || $certificate->valid_to === null) { return null; } $validTo = $certificate->valid_to; $diff = now()->diffInDays($validTo); if ($diff > 30) { return Status::Success; } if ($diff > 7) { return Status::Warning; } return Status::Danger; }), ]; } protected function actions(): array { return [ Action::make(__('Delete'), function (Enumerable $models): void { $models->each(fn (Site $site) => $site->delete()); }, 'delete'), ]; } public function link(Model $model): ?string { return route('site.view', ['site' => $model]); } } ================================================ FILE: packages/sites/src/Http/Livewire/Tabs/CertificateMonitor.php ================================================ siteId = $site->id; $this->enabled = $this->monitor()->exists; } #[Computed] public function monitor(): CertificateMonitorModel { /** @var Site $site */ $site = Site::query()->findOrFail($this->siteId); /** @var ?CertificateMonitorModel $monitor */ $monitor = $site->certificateMonitor; if ($monitor === null) { $monitor = new CertificateMonitorModel([ 'site_id' => $site->id, 'domain' => preg_replace('/^https?:\/\//', '', $site->url), 'port' => 443, ]); } return $monitor; } #[On('save')] public function save(): void { if (! $this->enabled && $this->monitor()->exists) { $this->monitor()->delete(); } } public function render(): mixed { /** @var view-string $view */ $view = 'sites::livewire.tabs.certificate-monitor'; return view($view); } } ================================================ FILE: packages/sites/src/Http/Livewire/Tabs/Crawler.php ================================================ siteId = $site->id; $this->enabled = $this->crawler()->exists; } #[Computed] public function crawler(): CrawlerModel { /** @var Site $site */ $site = Site::query()->findOrFail($this->siteId); /** @var ?CrawlerModel $crawler */ $crawler = $site->crawler; if ($crawler === null) { $crawler = new CrawlerModel([ 'site_id' => $site->id, 'start_url' => $site->url, ]); } return $crawler; } public function render(): mixed { /** @var view-string $view */ $view = 'sites::livewire.tabs.crawler'; return view($view, [ 'siteId' => $this->siteId, ]); } } ================================================ FILE: packages/sites/src/Http/Livewire/Tabs/DnsMonitors.php ================================================ siteId = $site->id; } public function render(): mixed { /** @var view-string $view */ $view = 'sites::livewire.tabs.dns-monitors'; return view($view); } } ================================================ FILE: packages/sites/src/Http/Livewire/Tabs/HealthcheckMonitor.php ================================================ siteId = $site->id; $this->enabled = $this->healthcheck()->exists; } #[Computed] public function healthcheck(): Healthcheck { /** @var Site $site */ $site = Site::query()->findOrFail($this->siteId); /** @var ?Healthcheck $healthcheck */ $healthcheck = $site->healthcheck; if ($healthcheck === null) { $healthcheck = new Healthcheck([ 'site_id' => $site->id, 'domain' => $site->url, 'type' => Type::Endpoint, 'enabled' => true, 'interval' => 60, ]); } return $healthcheck; } #[On('save')] public function save(): void { if (! $this->enabled && $this->healthcheck()->exists) { $this->healthcheck()->delete(); } } public function render(): mixed { /** @var view-string $view */ $view = 'sites::livewire.tabs.healthcheck-monitor'; return view($view); } } ================================================ FILE: packages/sites/src/Http/Livewire/Tabs/LighthouseMonitors.php ================================================ > $monitors */ #[Validate] public array $monitors = []; /** @return array> */ public function rules(): array { return [ 'monitors.*.id' => ['nullable'], 'monitors.*.url' => ['required', 'url'], 'monitors.*.interval' => ['required', 'in:'.implode(',', array_keys(config('lighthouse.intervals')))], ]; } /** @return array */ public function validationAttributes(): array { return [ 'monitors.*.url' => 'URL', ]; } public function mount(Site $site): void { $this->siteId = $site->id; $this->monitors = $site->lighthouseMonitors->map(function (LighthouseMonitor $monitor): array { return [ 'id' => $monitor->id, 'url' => $monitor->url, 'interval' => $monitor->interval, ]; })->toArray(); } public function updated(): void { $this->validate(); } #[On('save')] public function save(): void { abort_if(Gate::denies('use-lighthouse'), 403); $monitors = $this->validate()['monitors'] ?? []; foreach ($monitors as $monitor) { if (! blank($monitor['id'] ?? null)) { /** @var LighthouseMonitor $model */ $model = LighthouseMonitor::query()->findOrFail($monitor['id']); } else { /** @var LighthouseMonitor $model */ $model = LighthouseMonitor::query()->newModelInstance([ 'site_id' => $this->siteId, 'settings' => [], ]); } $model->url = $monitor['url']; $model->interval = $monitor['interval']; $model->save(); } } public function addPage(): void { /** @var Site $site */ $site = Site::query()->findOrFail($this->siteId); $defaultInterval = collect(config('lighthouse.intervals'))->keys()->first() ?? 60 * 24; // @phpstan-ignore-line $this->monitors[] = [ 'url' => $site->url, 'interval' => $defaultInterval, ]; } public function render(): mixed { /** @var view-string $view */ $view = 'sites::livewire.tabs.lighthouse-monitor'; return view($view, [ 'monitors' => $this->monitors, ]); } } ================================================ FILE: packages/sites/src/Http/Livewire/Tabs/UptimeMonitor.php ================================================ siteId = $site->id; $this->enabled = $this->monitor()->exists; } #[Computed] public function monitor(): Monitor { /** @var Site $site */ $site = Site::query()->findOrFail($this->siteId); /** @var ?Monitor $monitor */ $monitor = $site->uptimeMonitor; if ($monitor === null) { $monitor = new Monitor([ 'site_id' => $site->id, 'name' => $site->url, 'type' => Type::Http, 'settings' => [ 'host' => $site->url, ], ]); } return $monitor; } #[On('save')] public function save(): void { if (! $this->enabled && $this->monitor()->exists) { $this->monitor()->delete(); } } public function render(): mixed { /** @var view-string $view */ $view = 'sites::livewire.tabs.uptime-monitor'; return view($view); } } ================================================ FILE: packages/sites/src/Jobs/ImportSiteJob.php ================================================ $monitors */ public function __construct( public int $teamId, public string $domain, public array $monitors, ) { $this->onQueue(config()->string('sites.queue')); } public function handle(ImportSite $importer): void { $importer->import( teamId: $this->teamId, domain: $this->domain, monitors: $this->monitors, ); } public function uniqueId(): string { return $this->teamId.'-'.$this->domain; } /** @return array */ public function tags(): array { return [ 'team:'.$this->teamId, $this->domain, ]; } } ================================================ FILE: packages/sites/src/Models/Site.php ================================================ $lighthouseMonitors * @property Collection $dnsMonitors * @property ?CertificateMonitor $certificateMonitor * @property ?Healthcheck $healthcheck */ #[ObservedBy([SiteObserver::class])] #[ScopedBy([TeamScope::class])] class Site extends Model { protected $guarded = []; public function uptimeMonitor(): HasOne { return $this->hasOne(UptimeMonitor::class); } public function lighthouseMonitors(): HasMany { return $this->hasMany(LighthouseMonitor::class); } public function dnsMonitors(): HasMany { return $this->hasMany(DnsMonitor::class); } public function crawler(): HasOne { return $this->hasOne(Crawler::class); } public function certificateMonitor(): HasOne { return $this->hasOne(CertificateMonitor::class); } public function healthcheck(): HasOne { return $this->hasOne(Healthcheck::class); } } ================================================ FILE: packages/sites/src/Observers/SiteObserver.php ================================================ team_id = $teamService->team()->id; } } ================================================ FILE: packages/sites/src/ServiceProvider.php ================================================ registerConfig() ->registerActions(); } protected function registerConfig(): static { $this->mergeConfigFrom(__DIR__.'/../config/sites.php', 'sites'); return $this; } protected function registerActions(): static { return $this; } public function boot(): void { $this ->bootConfig() ->bootMigrations() ->bootCommands() ->bootViews() ->bootLivewire() ->bootRoutes() ->bootNavigation() ->bootNotifications() ->bootPolicies(); } protected function bootConfig(): static { $this->publishes([ __DIR__.'/../config/sites.php' => config_path('sites.php'), ], 'config'); return $this; } protected function bootMigrations(): static { $this->loadMigrationsFrom(__DIR__.'/../database/migrations'); return $this; } protected function bootCommands(): static { if ($this->app->runningInConsole()) { $this->commands([ ]); } return $this; } protected function bootViews(): static { $this->loadViewsFrom(__DIR__.'/../resources/views', 'sites'); return $this; } protected function bootLivewire(): static { Livewire::component('sites', Sites::class); Livewire::component('sites.create', SiteForm::class); Livewire::component('sites.table', SiteTable::class); Livewire::component('sites.import', ImportSites::class); Livewire::component('sites.tabs.uptime-monitor', UptimeMonitor::class); Livewire::component('sites.tabs.lighthouse-monitor', LighthouseMonitors::class); Livewire::component('sites.tabs.dns-monitors', DnsMonitors::class); Livewire::component('sites.tabs.crawler', Crawler::class); Livewire::component('sites.tabs.certificate-monitor', CertificateMonitor::class); Livewire::component('sites.tabs.healthcheck-monitor', HealthcheckMonitor::class); return $this; } protected function bootRoutes(): static { if (! $this->app->routesAreCached()) { Route::middleware(['web', 'auth']) ->group(fn () => $this->loadRoutesFrom(__DIR__.'/../routes/web.php')); } return $this; } protected function bootNavigation(): static { Navigation::path(__DIR__.'/../resources/navigation.php'); return $this; } protected function bootNotifications(): static { NotificationRegistry::registerCondition(DowntimeStartNotification::class, [ SiteCondition::class, ]); return $this; } protected function bootPolicies(): static { if (ce()) { Gate::policy(Site::class, AllowAllPolicy::class); } return $this; } } ================================================ FILE: packages/sites/testbench.yaml ================================================ providers: - Vigilant\Sites\ServiceProvider ================================================ FILE: packages/sites/tests/TestCase.php ================================================ set('database.default', 'testbench'); $app['config']->set('database.connections.testbench', [ 'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '', ]); } } ================================================ FILE: packages/uptime/.gitignore ================================================ vendor composer.lock .phpunit.result.cache ================================================ FILE: packages/uptime/composer.json ================================================ { "name": "vigilant/uptime", "description": "Vigilant Uptime", "type": "package", "license": "AGPL", "authors": [ { "name": "Vincent Boon", "email": "info@vincentbean.com", "role": "Developer" } ], "require": { "php": "^8.3", "geerlingguy/ping": "^1.2", "guzzlehttp/guzzle": "^7.8", "laravel/framework": "^12.0", "livewire/livewire": "^3.4", "vigilant/core": "@dev", "vigilant/dns": "@dev", "vigilant/frontend": "@dev", "vigilant/notifications": "@dev", "vigilant/sites": "@dev", "vigilant/users": "@dev" }, "require-dev": { "laravel/pint": "^1.6", "larastan/larastan": "^3.0", "orchestra/testbench": "^10.0", "phpstan/phpstan-mockery": "^2.0", "phpunit/phpunit": "^11.0" }, "autoload": { "psr-4": { "Vigilant\\Uptime\\": "src", "Vigilant\\Uptime\\Database\\Factories\\": "database/factories", "Vigilant\\Users\\Database\\Factories\\": "../users/database/factories" } }, "autoload-dev": { "psr-4": { "Vigilant\\Uptime\\Tests\\": "tests" } }, "scripts": { "test": "phpunit", "analyse": "phpstan", "style": "pint --test", "quality": [ "@test", "@analyse" ] }, "config": { "sort-packages": true, "allow-plugins": { "php-http/discovery": true } }, "extra": { "laravel": { "providers": [ "Vigilant\\Uptime\\ServiceProvider" ] } }, "minimum-stability": "dev", "prefer-stable": true, "repositories": [ { "type": "path", "url": "../*" } ] } ================================================ FILE: packages/uptime/config/uptime.php ================================================ 'uptime', 'intervals' => [ 1 => 'Every second', 5 => 'Every 5 seconds', 10 => 'Every 10 seconds', 20 => 'Every 20 seconds', 30 => 'Every 30 seconds', 60 => 'Every minute', 300 => 'Every 5 minutes', 600 => 'Every 10 minutes', 3600 => 'Every hour', ], 'allow_external_outposts' => env('UPTIME_ALLOW_EXTERNAL_OUTPOSTS', false), 'outpost_secret' => env('UPTIME_OUTPOST_SECRET', 'outpost-secret'), ]; ================================================ FILE: packages/uptime/database/factories/MonitorFactory.php ================================================ 1, 'name' => 'Monitor', 'type' => Type::Http, 'settings' => [ 'host' => '1.1.1.1', ], 'interval' => '* * * * *', 'retries' => 1, 'timeout' => 5, ]; } } ================================================ FILE: packages/uptime/database/migrations/2024_02_21_190000_create_uptime_monitors_table.php ================================================ id(); $table->foreignIdFor(Site::class)->nullable()->constrained()->onDelete('cascade'); $table->foreignIdFor(Team::class)->constrained()->onDelete('cascade'); $table->string('name'); $table->string('type'); $table->json('settings'); $table->string('interval'); $table->integer('retries'); $table->integer('timeout'); $table->timestamps(); }); } public function down(): void { Schema::dropIfExists('uptime_monitors'); } }; ================================================ FILE: packages/uptime/database/migrations/2024_02_21_190100_create_uptime_results_table.php ================================================ id(); $table->foreignIdFor(Monitor::class)->index()->constrained('uptime_monitors')->onDelete('cascade'); $table->float('total_time'); $table->timestamps(); }); } public function down(): void { Schema::dropIfExists('uptime_results'); } }; ================================================ FILE: packages/uptime/database/migrations/2024_02_21_190200_create_uptime_downtimes_table.php ================================================ id(); $table->foreignIdFor(Monitor::class)->index()->constrained('uptime_monitors')->onDelete('cascade'); $table->dateTime('start'); $table->dateTime('end')->nullable(); $table->timestamps(); }); } public function down(): void { Schema::dropIfExists('uptime_downtimes'); } }; ================================================ FILE: packages/uptime/database/migrations/2024_02_22_073000_create_uptime_results_aggregates_table.php ================================================ id(); $table->foreignIdFor(Monitor::class)->index()->constrained('uptime_monitors')->onDelete('cascade'); $table->float('total_time'); $table->timestamps(); }); } public function down(): void { Schema::dropIfExists('uptime_results_aggregates'); } }; ================================================ FILE: packages/uptime/database/migrations/2024_05_21_170200_uptime_downtimes_data_field.php ================================================ json('data')->nullable()->after('end'); }); } public function down(): void { Schema::dropColumns('uptime_downtimes', ['data']); } }; ================================================ FILE: packages/uptime/database/migrations/2025_02_01_170000_uptime_monitors_enabled_field.php ================================================ boolean('enabled')->after('id')->default(true); }); } public function down(): void { Schema::dropColumns('uptime_monitors', ['enabled']); } }; ================================================ FILE: packages/uptime/database/migrations/2025_05_06_190000_uptime_monitors_schedule_fields.php ================================================ timestamp('next_run')->nullable()->after('settings'); $table->integer('interval')->default(60)->after('next_run'); $table->string('state')->default('up')->after('name'); $table->integer('try')->default(0)->after('state'); }); } public function down(): void { Schema::table('uptime_monitors', function (Blueprint $table): void { $table->dropColumn(['next_run', 'interval', 'state']); }); Schema::table('uptime_monitors', function (Blueprint $table): void { $table->string('interval')->default('* * * * *')->after('settings'); }); } }; ================================================ FILE: packages/uptime/database/migrations/2025_10_05_080000_create_uptime_outposts_table.php ================================================ id(); $table->string('ip'); $table->integer('port'); $table->string('external_ip'); $table->string('status')->index(); $table->string('country')->nullable(); $table->float('latitude', 10, 6)->nullable(); $table->float('longitude', 10, 6)->nullable(); $table->dateTime('last_available_at'); $table->timestamps(); $table->unique(['ip', 'port']); }); } public function down(): void { Schema::dropIfExists('uptime_outposts'); } }; ================================================ FILE: packages/uptime/database/migrations/2025_10_06_181706_add_country_to_uptime_results_tables.php ================================================ string('country')->nullable()->after('total_time'); }); Schema::table('uptime_results_aggregates', function (Blueprint $table) { $table->string('country')->nullable()->after('total_time'); }); } public function down(): void { Schema::table('uptime_results', function (Blueprint $table) { $table->dropColumn('country'); }); Schema::table('uptime_results_aggregates', function (Blueprint $table) { $table->dropColumn('country'); }); } }; ================================================ FILE: packages/uptime/database/migrations/2025_10_06_183423_add_location_to_uptime_monitors_table.php ================================================ float('latitude', 10, 6)->nullable()->after('timeout'); $table->float('longitude', 10, 6)->nullable()->after('latitude'); }); } public function down(): void { Schema::table('uptime_monitors', function (Blueprint $table) { $table->dropColumn(['latitude', 'longitude']); }); } }; ================================================ FILE: packages/uptime/database/migrations/2025_10_06_184619_add_country_to_uptime_monitors_table.php ================================================ string('country')->nullable()->after('timeout'); }); } public function down(): void { Schema::table('uptime_monitors', function (Blueprint $table) { $table->dropColumn('country'); }); } }; ================================================ FILE: packages/uptime/database/migrations/2025_10_07_180857_add_geoip_fetched_at_to_uptime_monitors_table.php ================================================ timestamp('geoip_fetched_at')->nullable()->after('longitude'); }); } public function down(): void { Schema::table('uptime_monitors', function (Blueprint $table): void { $table->dropColumn('geoip_fetched_at'); }); } }; ================================================ FILE: packages/uptime/database/migrations/2025_10_08_100000_add_closest_outpost_id_to_uptime_monitors_table.php ================================================ foreignIdFor(Outpost::class, 'closest_outpost_id')->after('team_id')->nullable()->constrained('uptime_outposts')->onDelete('set null'); }); } public function down(): void { Schema::table('uptime_monitors', function (Blueprint $table): void { $table->dropForeign(['closest_outpost_id']); $table->dropColumn('closest_outpost_id'); }); } }; ================================================ FILE: packages/uptime/database/migrations/2025_10_19_152447_add_unavailable_at_to_uptime_outposts_table.php ================================================ dateTime('unavailable_at')->nullable()->after('last_available_at'); }); } public function down(): void { Schema::table('uptime_outposts', function (Blueprint $table): void { $table->dropColumn('unavailable_at'); }); } }; ================================================ FILE: packages/uptime/database/migrations/2025_12_23_192903_add_geoip_automatic_to_uptime_monitors_table.php ================================================ boolean('geoip_automatic')->default(true)->after('geoip_fetched_at'); }); } public function down(): void { Schema::table('uptime_monitors', function (Blueprint $table): void { $table->dropColumn('geoip_automatic'); }); } }; ================================================ FILE: packages/uptime/database/migrations/2025_12_23_193500_add_geoip_automatic_to_uptime_outposts_table.php ================================================ boolean('geoip_automatic')->default(true)->after('longitude'); }); } public function down(): void { Schema::table('uptime_outposts', function (Blueprint $table): void { $table->dropColumn('geoip_automatic'); }); } }; ================================================ FILE: packages/uptime/database/migrations/2025_12_27_142900_update_ping_monitor_types.php ================================================ where('type', '=', 'ping') ->update(['type' => 'icmp']); } public function down(): void { DB::table('uptime_monitors') ->where('type', '=', 'tcp') ->update(['type' => 'ping']); } }; ================================================ FILE: packages/uptime/phpstan.neon ================================================ includes: - ./vendor/larastan/larastan/extension.neon - ./vendor/phpstan/phpstan-mockery/extension.neon parameters: paths: - src - tests level: 8 ignoreErrors: - identifier: missingType.iterableValue - identifier: missingType.generics ================================================ FILE: packages/uptime/phpunit.xml ================================================ ./tests/* ./src ================================================ FILE: packages/uptime/resources/navigation.php ================================================ icon('tni-double-caret-up-circle-o') ->parent('health') ->gate('use-uptime') ->routeIs('uptime*') ->sort(1); ================================================ FILE: packages/uptime/resources/views/components/empty-states/monitors.blade.php ================================================ ================================================ FILE: packages/uptime/resources/views/livewire/charts/column-latency-chart.blade.php ================================================
@if ($hasPoints)
@else
-
@endif
================================================ FILE: packages/uptime/resources/views/livewire/charts/latency-chart.blade.php ================================================
@if ($availableCountries->count() > 1)
@foreach ($availableCountries as $country) @endforeach
@else
@endif
================================================ FILE: packages/uptime/resources/views/livewire/monitor/dashboard.blade.php ================================================
{{ $monitor->settings['host'] ?? '' }} {{ $lastDowntime === null ? __('Never') : teamTimezone($lastDowntime->end)->diffForHumans() }} @if ($lastDowntime !== null) @lang('For :time', ['time' => teamTimezone($lastDowntime->start)->longAbsoluteDiffForHumans(teamTimezone($lastDowntime->end))]) @endif @if ($uptime30d === null) @else {{ number_format($uptime30d, 2) }}% @endif @if ($uptime7d === null) @else {{ number_format($uptime7d, 2) }}% @endif
================================================ FILE: packages/uptime/resources/views/livewire/monitor/form.blade.php ================================================
@if (!$inline) @endif
@if (!$inline) @endif
@foreach (\Vigilant\Uptime\Enums\Type::cases() as $type) @endforeach
Loading...
@if ($form->type === \Vigilant\Uptime\Enums\Type::Http->value) @elseif ($form->type === \Vigilant\Uptime\Enums\Type::Ping->value) @elseif ($form->type === \Vigilant\Uptime\Enums\Type::Tcp->value) @endif
@foreach (config('uptime.intervals') as $interval => $label) @endforeach

@lang('Set location manually')

@lang('Override the location of this monitor manually.')
@error('form.geoip_automatic') {{ $message }} @enderror
@if (!$form->geoip_automatic)
@endif
@if (!$inline) @endif
================================================ FILE: packages/uptime/resources/views/livewire/uptime-monitors.blade.php ================================================
@lang('Add Uptime Monitor') @lang('Add Uptime Monitor') @if ($hasMonitors) @else @endif
================================================ FILE: packages/uptime/resources/views/monitor/view.blade.php ================================================ @lang('Edit') @lang('Delete') @lang('Edit') @lang('Delete')

{{ __('Downtimes') }}

@lang('Delete Uptime Monitor')

@lang('Are you sure you want to delete this uptime monitor?')

@svg('phosphor-warning-circle', 'w-5 h-5 text-orange mt-0.5')

{{ $monitor->name }}

@lang('This action cannot be undone. All uptime history and downtime records for this monitor will be permanently deleted.')

@lang('Cancel')
@csrf @method('DELETE') @lang('Delete Monitor')
================================================ FILE: packages/uptime/routes/api.php ================================================ group(function (): void { Route::prefix('outposts') ->middleware([OutpostAuthMiddleware::class, ExternalOutpostMiddleware::class]) ->group(function (): void { Route::post('register', [OutpostController::class, 'register']); Route::post('unregister', [OutpostController::class, 'unregister']); }); Route::get('uptime/ips/{format}', [OutpostIpController::class, 'list']) ->middleware('throttle:uptime-ips'); }); ================================================ FILE: packages/uptime/routes/web.php ================================================ middleware('can:use-uptime') ->group(function (): void { Route::get('/', UptimeMonitors::class)->name('uptime'); Route::get('/create-monitor', UptimeMonitorForm::class)->name('uptime.monitor.create'); Route::get('/monitor/{monitor}', [UptimeMonitorController::class, 'index'])->name('uptime.monitor.view'); Route::delete('/monitor/{monitor}', [UptimeMonitorController::class, 'delete'])->name('uptime.monitor.delete')->can('delete,monitor'); Route::get('/monitor/{monitor}/edit', UptimeMonitorForm::class)->name('uptime.monitor.edit'); Route::get('outposts', [OutpostController::class, 'list']) ->middleware('auth'); }); ================================================ FILE: packages/uptime/src/Actions/AggregateResults.php ================================================ results() ->select(['id', 'country', 'created_at']) ->where('created_at', '<', now()->subHour()) ->get(); $groupedByCountry = $results->groupBy('country'); foreach ($groupedByCountry as $country => $countryResults) { /** @var \Illuminate\Support\Collection $countryResults */ $groupedByHour = $countryResults->groupBy(function (Result $result) { return $result->created_at?->startOfHour()->toDateTimeString() ?? ''; }); foreach ($groupedByHour as $hour => $hourResults) { $ids = $hourResults->pluck('id')->toArray(); $averageTotalTime = Result::query() ->whereIn('id', $ids) ->average('total_time'); ResultAggregate::query()->create([ 'monitor_id' => $monitor->id, 'total_time' => $averageTotalTime, 'country' => $country, 'created_at' => $hour, 'updated_at' => $hour, ]); Result::query()->whereIn('id', $ids)->delete(); } } } } ================================================ FILE: packages/uptime/src/Actions/CalculateUptimePercentage.php ================================================ modify($carbonModifier); /** @var ?ResultAggregate $firstResult */ $firstResult = $monitor->aggregatedResults() ->where('created_at', '>=', $dateThreshold) ->orderBy('created_at') ->first(); if ($firstResult === null || $firstResult->created_at === null) { return null; } $minutesSinceFirstResult = $firstResult->created_at->diffInMinutes(now()); $downtimes = $monitor->downtimes() ->where('created_at', '>=', $firstResult->created_at) ->whereNotNull('end') ->get(); $downtimeMinutes = 0; /** @var Downtime $downtime */ foreach ($downtimes as $downtime) { $duration = $downtime->start->diffInMinutes($downtime->end); $downtimeMinutes += $duration; } $totalMinutes = $minutesSinceFirstResult - $downtimeMinutes; $uptimePercentage = ($totalMinutes / $minutesSinceFirstResult) * 100; return floor($uptimePercentage * 100) / 100; } } ================================================ FILE: packages/uptime/src/Actions/CheckLatency.php ================================================ results() ->distinct('country') ->pluck('country') ->filter() ->all(); foreach ($countries as $country) { $this->checkForCountry($monitor, $country); } } protected function checkForCountry(Monitor $monitor, string $country): void { $currentAverage = (float) $monitor->results() ->where('country', '=', $country) ->average('total_time'); $averages = $monitor->aggregatedResults() ->where('country', '=', $country) ->orderByDesc('created_at') ->take(12); // Past 12 hours // Skip if we don't have enough data if ($averages->count() < 10) { return; } $aggregatedAverage = (float) $averages->average('total_time'); if ($currentAverage > 0 && $aggregatedAverage > 0) { $percentageDifference = round((($currentAverage - $aggregatedAverage) / $aggregatedAverage) * 100); if (abs($percentageDifference) > 0) { LatencyChangedNotification::notify( $monitor, $percentageDifference, $aggregatedAverage, $currentAverage, $country ); } // Check for peak - recent results are significantly higher $this->checkForPeak($monitor, $country, $aggregatedAverage); } } protected function checkForPeak(Monitor $monitor, string $country, float $aggregatedAverage): void { // Get all recent results to calculate average $allRecentResults = $monitor->results() ->where('country', '=', $country) ->orderByDesc('created_at') ->pluck('total_time'); if ($allRecentResults->count() < 15) { return; } // Get the last 5 checks $lastFiveResults = $allRecentResults->take(5); // Calculate average excluding the last 5 results to avoid skewing $recentAverage = (float) $allRecentResults->slice(5)->average(); // Check if all of the last 5 checks are above the recent average $allAboveAverage = $lastFiveResults->every(function ($latency) use ($recentAverage) { return $latency > $recentAverage; }); if ($allAboveAverage && $recentAverage > 0) { $peakLatency = (float) $lastFiveResults->max(); $peakPercentIncrease = (($peakLatency - $recentAverage) / $recentAverage) * 100; LatencyPeakNotification::notify( $monitor, $peakLatency, $recentAverage, $peakPercentIncrease, $country ); } } } ================================================ FILE: packages/uptime/src/Actions/CheckUptime.php ================================================ update([ 'next_run' => now()->addSeconds($monitor->interval), ]); $result = null; $outpostCountry = null; $excludedOutpostIds = []; $maxAttempts = 3; // Add 5s to give some buffer time for the outpost to respond $timeout = $monitor->retries > 0 ? ($monitor->timeout * $monitor->retries) + 5 : $monitor->timeout + 5; for ($i = 0; $i < $maxAttempts; $i++) { $isLastAttempt = $i === $maxAttempts - 1; $outpost = $this->determineOutpost->determine($monitor, $excludedOutpostIds); if ($outpost === null) { logger()->error('No outpost available for uptime check'); if ($isLastAttempt) { $result = new UptimeResult( up: false, totalTime: 0, country: null, data: ['error' => 'no_outpost_available'], ); break; } continue; } $excludedOutpostIds[] = $outpost->id; $certPath = $this->rootCertificateGenerator->getRootCertificatePath(); try { $response = Http::baseUrl($outpost->url()) ->withToken(config('uptime.outpost_secret')) ->withOptions([ 'verify' => $certPath, ]) ->timeout($timeout) ->post('run-check', [ 'type' => $monitor->type->outpostValue(), 'target' => $monitor->type->formatTarget($monitor), 'timeout' => $monitor->timeout, ]); } catch (ConnectionException $e) { $message = strtolower($e->getMessage()); $isTimeout = str_contains($message, 'timed out'); if (! $isTimeout) { $outpost->update([ 'status' => OutpostStatus::Unavailable, ]); } logger()->error( $isTimeout ? 'Outpost timed out during uptime check' : 'Outpost connection error during uptime check', [ 'outpost_id' => $outpost->id, 'uptime_monitor_id' => $monitor->id, 'target' => $monitor->type->formatTarget($monitor), 'error' => $e->getMessage(), ] ); if ($isLastAttempt) { $result = new UptimeResult( up: false, totalTime: 0, country: $outpost->country, data: [ 'error' => $isTimeout ? 'timeout' : 'connection_exception', 'message' => $e->getMessage(), ], ); break; } continue; } if ($response->successful()) { $result = new UptimeResult( up: $response->json('up', false), totalTime: $response->json('latency_ms', 0), country: $outpost->country, data: $response->json(), ); $outpostCountry = $outpost->country; $outpost->update([ 'last_available_at' => now(), ]); if (! $result->up) { continue; } break; } $outpost->update([ 'status' => OutpostStatus::Unavailable, ]); logger()->error('Outpost returned unsuccessful response during uptime check', [ 'outpost' => $outpost->ip, 'status' => $response->status(), 'body' => $response->body(), 'uptime_monitor_id' => $monitor->id, 'target' => $monitor->type->formatTarget($monitor), ]); if ($isLastAttempt) { $result = new UptimeResult( up: false, totalTime: 0, country: $outpost->country, data: [ 'error' => 'unsuccessful_response', 'status' => $response->status(), ], ); break; } } if ($result === null) { logger()->error('All outposts failed to perform uptime check'); return; } /** @var ?Downtime $currentDowntime */ $currentDowntime = $monitor->downtimes() ->whereNull('end') ->first(); if (! $result->up) { if ($currentDowntime === null) { if ($monitor->try <= $monitor->retries) { $monitor->update([ 'try' => $monitor->try + 1, 'state' => State::Retrying, ]); return; } $monitor->downtimes()->create([ 'start' => now(), 'data' => $result->data, ]); $monitor->update([ 'state' => State::Down, 'try' => 0, ]); DowntimeStartEvent::dispatch($monitor); } } else { if ($currentDowntime !== null) { $currentDowntime->update([ 'end' => now(), ]); $monitor->update([ 'state' => State::Up, 'try' => 0, ]); DowntimeEndEvent::dispatch($currentDowntime); } $monitor->results()->create([ 'total_time' => $result->totalTime, 'country' => $outpostCountry, ]); } event(new UptimeCheckedEvent($monitor)); } } ================================================ FILE: packages/uptime/src/Actions/FetchGeolocation.php ================================================ extractHost($target); if ($host === null) { return null; } // If host is a domain, resolve it to an IP address if (! $this->isIpAddress($host)) { $host = $this->resolveToIp($host); if ($host === null) { return null; } $host = str($host)->before(',')->toString(); } try { $response = Http::timeout(10) ->get('https://free.freeipapi.com/api/json/'.$host); if (! $response->successful()) { return null; } $data = $response->json(); return [ 'country' => $data['countryCode'] ?? null, 'latitude' => $data['latitude'] ?? null, 'longitude' => $data['longitude'] ?? null, ]; } catch (\Exception $e) { logger()->warning('Failed to fetch geolocation for '.$host, [ 'error' => $e->getMessage(), ]); return null; } } protected function extractHost(string $target): ?string { // If it's a URL, parse the hostname if (str_starts_with($target, 'http://') || str_starts_with($target, 'https://')) { $parsed = parse_url($target); return $parsed['host'] ?? null; } // If it's in format host:port, extract the host part if (str_contains($target, ':')) { $parts = explode(':', $target); return $parts[0]; } // Otherwise, assume it's already a hostname or IP return $target; } protected function isIpAddress(string $host): bool { return filter_var($host, FILTER_VALIDATE_IP) !== false; } protected function resolveToIp(string $domain): ?string { try { $dnsMonitor = DnsMonitor::where('record', $domain) ->whereIn('type', [Type::A, Type::AAAA]) ->where('enabled', '=', true) ->first(); if ($dnsMonitor && $dnsMonitor->value) { return $dnsMonitor->value; } } catch (\Exception $e) { // DNS monitor table may not exist (e.g., in tests), continue with DNS resolution } try { $ip = $this->resolveRecord->resolve(Type::A, $domain); if ($ip !== null) { return $ip; } return $this->resolveRecord->resolve(Type::AAAA, $domain); } catch (\Exception $e) { logger()->warning('Failed to resolve domain to IP for '.$domain, [ 'error' => $e->getMessage(), ]); return null; } } } ================================================ FILE: packages/uptime/src/Actions/Outpost/DetermineOutpost.php ================================================ latitude === null || $monitor->longitude === null) { if ($monitor !== null && $monitor->shouldFetchGeoip()) { UpdateMonitorLocationJob::dispatch($monitor); } return Outpost::query() ->where('status', '=', OutpostStatus::Available) ->when(count($excludedOutposts) > 0, fn (Builder $query) => $query->whereNotIn('id', $excludedOutposts)) ->inRandomOrder() ->first(); } // Update closest outpost if not set (don't exclude from finding closest) if ($monitor->closest_outpost_id === null) { $this->updateClosestOutpost($monitor); } // 50% of the time, select the closest outpost if (rand(0, 1) === 0) { return $this->selectClosestOutpost($monitor, $excludedOutposts); } // 50% of the time, select a remote outpost return $this->selectRemoteOutpost($monitor, $excludedOutposts); } protected function updateClosestOutpost(Monitor $monitor): void { $closestOutpost = $this->findClosestOutpost($monitor); if ($closestOutpost !== null) { $monitor->update([ 'closest_outpost_id' => $closestOutpost->id, ]); } } protected function selectClosestOutpost(Monitor $monitor, array $excludedOutposts): ?Outpost { // Try to use the cached closest outpost if it's not excluded if ($monitor->closest_outpost_id !== null && ! in_array($monitor->closest_outpost_id, $excludedOutposts)) { $outpost = Outpost::query() ->where('id', $monitor->closest_outpost_id) ->where('status', '=', OutpostStatus::Available) ->first(); if ($outpost !== null) { return $outpost; } } // Find the next closest outpost that's not excluded return $this->findClosestOutpost($monitor, $excludedOutposts); } protected function selectRemoteOutpost(Monitor $monitor, array $excludedOutposts): ?Outpost { $excludedIds = $excludedOutposts; if ($monitor->closest_outpost_id !== null) { $excludedIds[] = $monitor->closest_outpost_id; } $outpost = Outpost::query() ->where('status', '=', OutpostStatus::Available) ->when(count($excludedIds) > 0, fn (Builder $query) => $query->whereNotIn('id', $excludedIds)) ->inRandomOrder() ->first(); // If no remote outpost available, fallback to any available outpost if ($outpost === null) { $outpost = Outpost::query() ->where('status', '=', OutpostStatus::Available) ->when(count($excludedOutposts) > 0, fn (Builder $query) => $query->whereNotIn('id', $excludedOutposts)) ->inRandomOrder() ->first(); } return $outpost; } protected function findClosestOutpost(Monitor $monitor, array $excludedOutposts = []): ?Outpost { $earthRadius = 6371; // Earth's radius in kilometers return Outpost::query() ->where('status', '=', OutpostStatus::Available) ->whereNotNull('latitude') ->whereNotNull('longitude') ->when(count($excludedOutposts) > 0, fn (Builder $query) => $query->whereNotIn('id', $excludedOutposts)) ->selectRaw( 'uptime_outposts.*, '. '(? * 2 * ASIN(SQRT('. 'POW(SIN(RADIANS((latitude - ?)) / 2), 2) + '. 'COS(RADIANS(?)) * COS(RADIANS(latitude)) * '. 'POW(SIN(RADIANS((longitude - ?)) / 2), 2)'. '))) as distance', [$earthRadius, $monitor->latitude, $monitor->latitude, $monitor->longitude] ) ->orderBy('distance') ->first(); } } ================================================ FILE: packages/uptime/src/Actions/Outpost/GenerateOutpostCertificate.php ================================================ rootCertificateGenerator->getRootCertificate(); $rootKey = $this->rootCertificateGenerator->getRootPrivateKey(); $rootCertResource = openssl_x509_read($rootCert); $rootKeyResource = openssl_pkey_get_private($rootKey); if ($rootCertResource === false) { throw new \RuntimeException('Failed to read root certificate: '.openssl_error_string()); } if ($rootKeyResource === false) { throw new \RuntimeException('Failed to read root private key: '.openssl_error_string()); } // Generate new private key $privateKey = openssl_pkey_new([ 'private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA, ]); $dn = [ 'countryName' => 'US', 'stateOrProvinceName' => 'State', 'localityName' => 'City', 'organizationName' => 'Vigilant', 'organizationalUnitName' => 'Outpost', 'commonName' => $commonName, ]; // Detect if IP or DNS and build SAN accordingly $sanEntry = filter_var($outpostIp, FILTER_VALIDATE_IP) ? "IP:{$outpostIp}" : "DNS:{$outpostIp}"; // Build a minimal OpenSSL config that defines all required sections $tmpConfig = tempnam(sys_get_temp_dir(), 'openssl_'); $configData = << 'sha256', 'config' => $tmpConfig, 'req_extensions' => 'v3_req', ]); if ($csr === false || $csr === true) { throw new \RuntimeException('Failed to generate CSR: '.openssl_error_string()); } // Sign CSR with the root CA $cert = openssl_csr_sign( $csr, $rootCertResource, $rootKeyResource, $validityDays, [ 'digest_alg' => 'sha256', 'config' => $tmpConfig, 'x509_extensions' => 'v3_req', ] ); if ($cert === false) { throw new \RuntimeException('Failed to sign certificate: '.openssl_error_string()); } openssl_pkey_export($privateKey, $privateKeyPem); openssl_x509_export($cert, $certPem); @unlink($tmpConfig); return [ 'certificate' => $certPem, 'private_key' => $privateKeyPem, 'root_certificate' => $rootCert, ]; } } ================================================ FILE: packages/uptime/src/Actions/Outpost/GenerateRootCertificate.php ================================================ exists()) { return; } $privateKey = openssl_pkey_new([ 'private_key_bits' => 4096, 'private_key_type' => OPENSSL_KEYTYPE_RSA, ]); $dn = [ 'countryName' => 'NL', 'stateOrProvinceName' => 'State', 'localityName' => 'City', 'organizationName' => 'Vigilant', 'organizationalUnitName' => 'Uptime Monitoring', 'commonName' => 'Vigilant Root CA', ]; $csr = openssl_csr_new($dn, $privateKey, ['digest_alg' => 'sha256']); if ($csr === false || $csr === true) { throw new \RuntimeException('Failed to generate CSR: '.openssl_error_string()); } $cert = openssl_csr_sign($csr, null, $privateKey, 3650, ['digest_alg' => 'sha256']); if ($cert === false) { throw new \RuntimeException('Failed to sign certificate: '.openssl_error_string()); } openssl_pkey_export($privateKey, $privateKeyPem); openssl_x509_export($cert, $certPem); $this->disk()->put(self::ROOT_CA_KEY_PATH, $privateKeyPem); $this->disk()->put(self::ROOT_CA_CERT_PATH, $certPem); chmod($this->disk()->path(self::ROOT_CA_KEY_PATH), 0600); chmod($this->disk()->path(self::ROOT_CA_CERT_PATH), 0644); } public function exists(): bool { return $this->disk()->exists(self::ROOT_CA_KEY_PATH) && $this->disk()->exists(self::ROOT_CA_CERT_PATH); } public function getRootCertificatePath(): string { if (! $this->exists()) { $this->generate(); } return $this->disk()->path(self::ROOT_CA_CERT_PATH); } public function getRootCertificate(): string { if (! $this->exists()) { $this->generate(); } $cert = $this->disk()->get(self::ROOT_CA_CERT_PATH); if ($cert === null) { throw new \RuntimeException('Failed to read root certificate from disk'); } return $cert; } public function getRootPrivateKey(): string { if (! $this->exists()) { $this->generate(); } $key = $this->disk()->get(self::ROOT_CA_KEY_PATH); if ($key === null) { throw new \RuntimeException('Failed to read root private key from disk'); } return $key; } protected function disk(): Filesystem { return Storage::disk('local'); } } ================================================ FILE: packages/uptime/src/Actions/Outpost/RegisterOutpost.php ================================================ updateOrCreate([ 'ip' => $ip, 'port' => $port, ], [ 'external_ip' => $externalIp, 'status' => OutpostStatus::Available, 'country' => $country !== null ? strtoupper($country) : null, 'latitude' => $latitude !== null ? (float) $latitude : null, 'longitude' => $longitude !== null ? (float) $longitude : null, 'geoip_automatic' => false, 'last_available_at' => now(), ]); } $existingOutpost = Outpost::query() ->where('ip', '=', $ip) ->where('port', '=', $port) ->first(); if ($existingOutpost && $existingOutpost->country !== null) { $existingOutpost->external_ip = $externalIp; $existingOutpost->last_available_at = now(); $existingOutpost->status = OutpostStatus::Available; $existingOutpost->save(); return $existingOutpost; } $geolocation = $this->fetchGeolocation->fetch($externalIp); return Outpost::query()->updateOrCreate([ 'ip' => $ip, 'port' => $port, ], [ 'external_ip' => $externalIp, 'status' => OutpostStatus::Available, 'country' => isset($geolocation['country']) ? strtoupper($geolocation['country']) : null, 'latitude' => $geolocation['latitude'] ?? null, 'longitude' => $geolocation['longitude'] ?? null, 'geoip_automatic' => true, 'last_available_at' => now(), ]); } } ================================================ FILE: packages/uptime/src/Commands/AggregateResultsCommand.php ================================================ withoutGlobalScopes() ->get(); foreach ($monitors as $monitor) { AggregateResultsJob::dispatch($monitor); } return static::SUCCESS; } } ================================================ FILE: packages/uptime/src/Commands/CheckLatencyCommand.php ================================================ argument('monitorId'); /** @var Monitor $monitor */ $monitor = Monitor::query()->withoutGlobalScopes()->findOrFail($monitorId); $teamService->setTeamById($monitor->team_id); $checkLatency->check($monitor); return static::SUCCESS; } } ================================================ FILE: packages/uptime/src/Commands/CheckUnavailableOutpostsCommand.php ================================================ where('status', '=', OutpostStatus::Unavailable) ->whereNotNull('unavailable_at') ->where('unavailable_at', '<=', now()->subMinutes(15)) ->get(); foreach ($outposts as $outpost) { CheckUnavailableOutpostJob::dispatch($outpost); } return static::SUCCESS; } } ================================================ FILE: packages/uptime/src/Commands/CheckUptimeCommand.php ================================================ argument('monitorId'); /** @var Monitor $monitor */ $monitor = Monitor::query()->withoutGlobalScopes()->findOrFail($monitorId); CheckUptimeJob::dispatch($monitor); return static::SUCCESS; } } ================================================ FILE: packages/uptime/src/Commands/GenerateRootCaCommand.php ================================================ exists()) { $this->info('Root CA certificate already exists.'); return static::SUCCESS; } $this->info('Generating root CA certificate...'); $generator->generate(); $this->info('Root CA certificate generated successfully.'); return static::SUCCESS; } } ================================================ FILE: packages/uptime/src/Commands/ScheduleUptimeChecksCommand.php ================================================ withoutGlobalScopes() ->where('enabled', '=', true) ->where(function (Builder $builder): void { $builder->where('next_run', '<=', now()) ->orWhereNull('next_run'); }) ->get() ->each(function (Monitor $monitor): void { CheckUptimeJob::dispatch($monitor); }); return static::SUCCESS; } } ================================================ FILE: packages/uptime/src/Data/UptimeResult.php ================================================ 'HTTP(s)', Type::Ping => 'Ping', Type::Tcp => 'TCP', }; } public function outpostValue(): string { return match ($this) { Type::Http => 'http', Type::Ping => 'icmp', Type::Tcp => 'tcp', }; } public function formatTarget(Monitor $monitor): string { if ($this === Type::Http) { $validator = Validator::make($monitor->settings, [ 'host' => ['required', 'url'], ]); if ($validator->fails()) { $validator = Validator::make($monitor->settings, [ 'host' => ['required', 'ip'], ]); } $settings = $validator->validate(); return $settings['host']; } if ($this === Type::Ping) { $settings = Validator::validate($monitor->settings, [ 'host' => ['required', 'ip'], ]); return $settings['host']; } $settings = Validator::validate($monitor->settings, [ 'host' => ['required', 'ip'], 'port' => ['integer', 'min:1', 'max:65535'], ]); return sprintf('%s:%s', $settings['host'], $settings['port']); } } ================================================ FILE: packages/uptime/src/Events/DowntimeEndEvent.php ================================================ filled('country') && $request->filled('latitude') && $request->filled('longitude')); $request->validate([ 'ip' => 'required|ip', 'port' => 'required|integer|min:1|max:65535', 'country' => [ 'nullable', 'string', new CountryCode, Rule::requiredIf(! $geoipAutomatic), ], 'latitude' => [ 'nullable', 'numeric', 'between:-90,90', Rule::requiredIf(! $geoipAutomatic), ], 'longitude' => [ 'nullable', 'numeric', 'between:-180,180', Rule::requiredIf(! $geoipAutomatic), ], ]); $clientIp = $request->ip(); if ($clientIp === null) { return response()->json(['message' => 'Unable to determine client IP address.'], 400); } $outpost = $registrar->register( $request->input('ip'), $clientIp, $request->input('port'), $geoipAutomatic, $request->input('country'), $request->input('latitude'), $request->input('longitude') ); // Generate a short-lived certificate for the outpost (valid for 30 days) $commonName = sprintf('outpost-%s-%d', $outpost->ip, $outpost->port); $certificate = $certificateGenerator->generate($commonName, $clientIp, 30); return response()->json($certificate); } public function unregister(Request $request): JsonResponse { $request->validate([ 'ip' => 'required|ip', 'port' => 'required|integer|min:1|max:65535', ]); Outpost::query() ->where('ip', $request->ip()) ->where('external_ip', $request->input('ip')) ->where('port', $request->input('port')) ->delete(); return response()->json(['message' => 'Outpost unregistered successfully.']); } public function list(): JsonResponse { $outposts = Outpost::query()->get(); return response()->json($outposts); } } ================================================ FILE: packages/uptime/src/Http/Controllers/Api/OutpostIpController.php ================================================ remember( 'uptime:outposts:ips', now()->addMinutes(15), fn (): Collection => Outpost::query() ->select('external_ip') ->distinct() ->where('status', '=', OutpostStatus::Available) ->pluck('external_ip') ); if ($format === 'text') { return response( $ips->implode("\n"), 200, ['Content-Type' => 'text/plain'] ); } if ($format === 'json') { return response()->json($ips); } return response()->json(['message' => 'Invalid format. Use "text" or "json".'], 400); } } ================================================ FILE: packages/uptime/src/Http/Controllers/UptimeMonitorController.php ================================================ $monitor, ]); } public function delete(Monitor $monitor): mixed { $monitor->delete(); $this->alert( __('Deleted'), __('Uptime monitor was successfully deleted'), AlertType::Success ); return response()->redirectToRoute('uptime'); } } ================================================ FILE: packages/uptime/src/Http/Livewire/Charts/ColumnLatencyChart.php ================================================ dateRange = 'week'; // Ensure we have the closest country selected $closestCountry = $this->getClosestCountry(); if ($closestCountry) { $countries = $this->availableCountries(); if ($countries->contains($closestCountry)) { $this->selectedCountries = [$closestCountry]; } } } public function data(): array { $points = $this->points()->pluck('total_time')->map(fn (float $time): int => (int) round($time)); return [ 'type' => 'line', 'data' => [ 'labels' => $points, 'datasets' => [ [ 'label' => 'Latency', 'data' => $points, 'pointRadius' => 0, 'pointHoverRadius' => 0, 'borderWidth' => 2, 'borderColor' => '#337F1F', 'tension' => 0.4, ], ], ], 'options' => [ 'plugins' => [ 'legend' => [ 'display' => false, ], 'tooltip' => [ 'enabled' => false, ], ], 'scales' => [ 'y' => [ 'display' => false, 'beginAtZero' => true, ], 'x' => [ 'display' => false, ], ], ], ]; } public function render(): View { /** @var view-string $view */ $view = 'uptime::livewire.charts.column-latency-chart'; return view($view, [ 'identifier' => $this->getIdentifier(), 'height' => $this->height, 'hasPoints' => $this->points()->isNotEmpty(), ]); } } ================================================ FILE: packages/uptime/src/Http/Livewire/Charts/LatencyChart.php ================================================ 'required', ])->validate(); $this->monitorId = $data['monitorId']; $countries = $this->availableCountries(); if ($countries->isNotEmpty()) { $closestCountry = $this->getClosestCountry(); if ($closestCountry && $countries->contains($closestCountry)) { $this->selectedCountries = [$closestCountry]; } else { $this->selectedCountries = [$countries->first()]; } } } public function toggleCountry(string $country): void { if (in_array($country, $this->selectedCountries)) { $this->selectedCountries = array_values(array_diff($this->selectedCountries, [$country])); } else { $this->selectedCountries[] = $country; } $this->loadChart(); } public function setDateRange(string $range): void { $this->dateRange = $range; $this->loadChart(); } public function selectAllCountries(): void { $this->selectedCountries = $this->availableCountries()->toArray(); $this->loadChart(); } public function clearCountries(): void { $this->selectedCountries = []; $this->loadChart(); } protected function getClosestCountry(): ?string { $monitor = Monitor::query() ->with('closestOutpost') ->find($this->monitorId); return $monitor?->closestOutpost?->country; } protected function getDateRangeStart(): Carbon { return match ($this->dateRange) { 'hour' => now()->subHour(), 'week' => now()->subWeek(), 'month' => now()->subMonth(), '3months' => now()->subMonths(3), '6months' => now()->subMonths(6), default => now()->subWeek(), }; } protected function getDateRangeOptions(): array { return [ 'hour' => 'Hour', 'week' => 'Week', 'month' => 'Month', '3months' => '3 Months', '6months' => '6 Months', ]; } protected function availableCountries(): Collection { // For hour range, use Result table; for others, use ResultAggregate $model = $this->dateRange === 'hour' ? Result::class : ResultAggregate::class; return $model::query() ->where('monitor_id', '=', $this->monitorId) ->whereNotNull('country') ->where('country', '!=', '') ->selectRaw('country, COUNT(*) as count') ->groupBy('country') ->orderByDesc('count') ->get() ->pluck('country'); } protected function points(): Collection { // For hour range, use Result table; for others, use ResultAggregate $model = $this->dateRange === 'hour' ? Result::class : ResultAggregate::class; $query = $model::query() ->where('monitor_id', '=', $this->monitorId) ->where('created_at', '>=', $this->getDateRangeStart()); if (! empty($this->selectedCountries)) { $query->whereIn('country', $this->selectedCountries); } return $query ->orderBy('created_at', 'asc') ->get(); } public function data(): array { if (count($this->selectedCountries) > 1) { return $this->multiCountryData(); } return $this->singleLineData(); } protected function singleLineData(): array { $points = $this->points(); $labels = $points->pluck('created_at'); $data = $points->pluck('total_time')->map(fn (float $time): int => (int) round($time)); $dateFormat = $this->dateRange === 'week' ? 'd/m H:i' : 'd/m'; if ($this->dateRange === 'hour') { $dateFormat = 'H:i'; } return [ 'type' => 'line', 'data' => [ 'labels' => $labels->map(fn (Carbon $carbon): string => teamTimezone($carbon)->format($dateFormat))->toArray(), 'datasets' => [ [ 'label' => 'Latency', 'data' => $data->toArray(), 'pointRadius' => 0, 'pointHoverRadius' => 0, 'borderWidth' => 2, 'borderColor' => '#337F1F', 'tension' => 0.4, 'unit' => 'ms', ], ], ], 'options' => [ 'plugins' => [ 'legend' => [ 'display' => true, ], 'tooltip' => [ 'enabled' => true, ], ], 'scales' => [ 'y' => [ 'display' => true, 'beginAtZero' => true, ], 'x' => [ 'display' => true, ], ], ], ]; } protected function multiCountryData(): array { // Design system colors from styleguide $colors = [ ['border' => '#3B82F6', 'bg' => 'rgba(59, 130, 246, 0.1)'], // blue ['border' => '#6366F1', 'bg' => 'rgba(99, 102, 241, 0.1)'], // indigo ['border' => '#10B981', 'bg' => 'rgba(16, 185, 129, 0.1)'], // green ['border' => '#F97316', 'bg' => 'rgba(249, 115, 22, 0.1)'], // orange ['border' => '#8B5CF6', 'bg' => 'rgba(139, 92, 246, 0.1)'], // purple ['border' => '#EC4899', 'bg' => 'rgba(236, 72, 153, 0.1)'], // magenta ['border' => '#06B6D4', 'bg' => 'rgba(6, 182, 212, 0.1)'], // cyan ['border' => '#EF4444', 'bg' => 'rgba(239, 68, 68, 0.1)'], // red ]; $limit = match ($this->dateRange) { 'hour' => 60, // ~1 hour of minute data 'week' => 168, // ~1 week of hourly data 'month' => 720, // ~1 month of hourly data '3months' => 2160, // ~3 months of hourly data '6months' => 4320, // ~6 months of hourly data default => 168, }; $model = $this->dateRange === 'hour' ? Result::class : ResultAggregate::class; $countryData = []; $allTimestamps = collect(); foreach ($this->selectedCountries as $country) { $query = $model::query() ->where('monitor_id', '=', $this->monitorId) ->where('country', '=', $country) ->where('created_at', '>=', $this->getDateRangeStart()); $points = $query ->orderBy('created_at', 'asc') ->limit($limit) ->get(); $countryData[$country] = []; foreach ($points as $point) { if ($point->created_at === null) { continue; } $timestamp = $point->created_at->timestamp; $countryData[$country][$timestamp] = round($point->total_time); // @phpstan-ignore-line $allTimestamps->push($timestamp); } } $uniqueTimestamps = $allTimestamps->unique()->sort()->values(); $datasets = []; foreach ($this->selectedCountries as $index => $country) { $data = []; foreach ($uniqueTimestamps as $timestamp) { $data[] = $countryData[$country][$timestamp] ?? null; } $colorSet = $colors[$index % count($colors)]; $datasets[] = [ 'label' => strtoupper($country), 'data' => $data, 'pointRadius' => 1, 'pointHoverRadius' => 4, 'borderWidth' => 2, 'borderColor' => $colorSet['border'], 'backgroundColor' => $colorSet['bg'], 'fill' => true, 'tension' => 0.4, 'unit' => 'ms', 'spanGaps' => true, ]; } $labels = $uniqueTimestamps->map(function ($timestamp) { $dateFormat = $this->dateRange === 'hour' ? 'H:i' : 'd/m H:i'; return teamTimezone(Carbon::createFromTimestamp($timestamp))->format($dateFormat); })->toArray(); return [ 'type' => 'line', 'data' => [ 'labels' => $labels, 'datasets' => $datasets, ], 'options' => [ 'responsive' => true, 'maintainAspectRatio' => false, 'plugins' => [ 'legend' => [ 'display' => true, 'position' => 'top', 'align' => 'end', 'labels' => [ 'color' => '#D8D8E8', // base-200 'font' => [ 'size' => 12, ], 'padding' => 12, 'usePointStyle' => true, 'pointStyle' => 'circle', ], ], 'tooltip' => [ 'enabled' => true, 'mode' => 'index', 'intersect' => false, 'backgroundColor' => '#232333', // base-850 'titleColor' => '#F4F4FA', // base-100 'bodyColor' => '#D8D8E8', // base-200 'borderColor' => '#444459', // base-700 'borderWidth' => 1, 'padding' => 12, ], ], 'scales' => [ 'y' => [ 'display' => true, 'beginAtZero' => true, 'grid' => [ 'color' => '#2D2D42', // base-800 'drawBorder' => false, ], 'ticks' => [ 'color' => '#A8A8C0', // base-400 'font' => [ 'size' => 11, ], ], ], 'x' => [ 'display' => true, 'grid' => [ 'display' => false, ], 'ticks' => [ 'color' => '#A8A8C0', // base-400 'font' => [ 'size' => 11, ], 'maxRotation' => 0, ], ], ], 'interaction' => [ 'mode' => 'index', 'intersect' => false, ], ], ]; } protected function getIdentifier(): string { return Str::slug(get_class($this)).$this->monitorId; } public function render(): View { /** @var view-string $view */ $view = 'uptime::livewire.charts.latency-chart'; return view($view, [ 'identifier' => $this->getIdentifier(), 'height' => $this->height, 'availableCountries' => $this->availableCountries(), 'closestCountry' => $this->getClosestCountry(), 'dateRangeOptions' => $this->getDateRangeOptions(), ]); } } ================================================ FILE: packages/uptime/src/Http/Livewire/Forms/CreateUptimeMonitorForm.php ================================================ value; public array $settings = [ 'host' => '', ]; public int $interval = 60; #[Validate('required|integer|min:0|max:3')] public ?int $retries = 0; #[Validate('required|integer|max:10')] public ?int $timeout = 5; public bool $geoip_automatic = true; public ?string $country = null; public ?float $latitude = null; public ?float $longitude = null; public function getRules(): array { return array_merge(parent::getRules(), [ 'type' => ['required', Rule::enum(Type::class)], 'name' => ['required', 'string', 'max:255'], 'interval' => ['required', 'integer', 'in:'.implode(',', array_keys(config('uptime.intervals')))], 'settings.port' => ['integer', 'min:1', 'max:65535', sprintf('required_if:type,%s', Type::Tcp->value)], 'settings.host' => [sprintf('required_if:type,%s,%s,%s', Type::Http->value, Type::Ping->value, Type::Tcp->value)], 'enabled' => ['boolean', new CanEnableRule(Monitor::class)], 'geoip_automatic' => ['boolean'], 'country' => [ Rule::requiredIf(fn () => ! $this->geoip_automatic), 'nullable', 'string', new CountryCode, ], 'latitude' => [ Rule::requiredIf(fn () => ! $this->geoip_automatic), 'nullable', 'numeric', 'between:-90,90', ], 'longitude' => [ Rule::requiredIf(fn () => ! $this->geoip_automatic), 'nullable', 'numeric', 'between:-180,180', ], ]); } public function all(): array { $values = parent::all(); if ($this->geoip_automatic) { $values['country'] = null; $values['latitude'] = null; $values['longitude'] = null; } elseif ($values['country'] !== null) { $values['country'] = strtoupper(trim($values['country'])); } return $values; } } ================================================ FILE: packages/uptime/src/Http/Livewire/Monitor/Dashboard.php ================================================ monitorId = $monitorId; } public function render(): View { $uptimePercentage = app(CalculateUptimePercentage::class); /** @var Monitor $monitor */ $monitor = Monitor::query()->findOrFail($this->monitorId); /** @var view-string $view */ $view = 'uptime::livewire.monitor.dashboard'; return view($view, [ 'monitor' => $monitor, 'lastDowntime' => $monitor->downtimes() ->whereNotNull('end') ->orderByDesc('start') ->first(), 'uptime30d' => $uptimePercentage->calculate($monitor, '-30 days'), 'uptime7d' => $uptimePercentage->calculate($monitor, '-7 days'), ]); } } ================================================ FILE: packages/uptime/src/Http/Livewire/Tables/DowntimeTable.php ================================================ monitorId = $monitorId; Monitor::query()->findOrFail($monitorId); } protected function columns(): array { return [ DateColumn::make(__('Start'), 'start') ->sortable(), DateColumn::make(__('End'), 'end') ->sortable(), Column::make(__('Duration'), function (Downtime $downtime) { if ($downtime->end === null) { return __('Ongoing'); } return teamTimezone($downtime->start)->longAbsoluteDiffForHumans(teamTimezone($downtime->end)); }), ]; } protected function query(): Builder { return parent::query() ->where('monitor_id', '=', $this->monitorId); } } ================================================ FILE: packages/uptime/src/Http/Livewire/Tables/MonitorTable.php ================================================ 'None', '30s' => 'Every 30 seconds', ]; protected function columns(): array { /** @var CalculateUptimePercentage $calculateUptime */ $calculateUptime = app(CalculateUptimePercentage::class); return [ StatusColumn::make(__('Status')) ->text(function (Monitor $monitor): string { if (! $monitor->enabled) { return __('Disabled'); } $downtime = $monitor->currentDowntime(); if ($downtime !== null) { return __('Down'); } /** @var null|Result|ResultAggregate $lastResult */ $lastResult = $monitor->results()->orderByDesc('created_at')->first(); if ($lastResult === null) { $lastResult = $monitor->aggregatedResults()->orderByDesc('created_at')->first(); } if ($lastResult === null || ! isset($lastResult->created_at)) { return __('Unknown'); } if ($lastResult->created_at->lessThan(now()->subMinutes(5))) { return __('Last check: :time', ['time' => $lastResult->created_at->diffForHumans()]); } return __('Up'); }) ->status(function (Monitor $monitor): Status { $downtime = $monitor->currentDowntime(); if ($downtime !== null || ! $monitor->enabled) { return Status::Danger; } /** @var null|Result|ResultAggregate $lastResult */ $lastResult = $monitor->results()->orderByDesc('created_at')->first() ?? $monitor->aggregatedResults()->orderByDesc('created_at')->first(); if ($lastResult === null || $lastResult->created_at === null || $lastResult->created_at->lessThan(now()->subMinutes(5))) { return Status::Warning; } return Status::Success; }), Column::make(__('Name'), 'name') ->searchable() ->sortable(), ChartColumn::make(__('Latency')) ->component('monitor-column-latency-chart') ->parameters(fn (Monitor $monitor) => ['monitorId' => $monitor->id]), Column::make(__('Uptime')) ->displayUsing(function (Monitor $monitor) use ($calculateUptime) { $percentage = $calculateUptime->calculate($monitor); if ($percentage === null) { return __('Not available yet'); } $class = match (true) { $percentage > 95 => 'text-green-light', $percentage > 80 => 'text-orange', default => 'text-red' }; return "".number_format($percentage, 2).'%'; }) ->asHtml(), Column::make(__('Last downtime')) ->displayUsing(function (Monitor $monitor) { /** @var ?Downtime $lastDowntime */ $lastDowntime = $monitor->downtimes() ->whereNotNull('end') ->orderByDesc('start') ->first(); if ($lastDowntime === null) { return __('Never'); } return teamTimezone($lastDowntime->start)->diffForHumans(); }), ]; } protected function filters(): array { return [ SelectFilter::make(__('Site'), 'site_id') ->options( Site::query() ->orderBy('url') ->pluck('url', 'id') ->toArray() ), ]; } protected function actions(): array { return [ Action::make(__('Enable'), function (Enumerable $models): void { foreach ($models as $model) { if (! Gate::allows('create', $model)) { break; } $model->update(['enabled' => true]); } }, 'enable'), Action::make(__('Disable'), function (Enumerable $models): void { $models->each(fn (Monitor $monitor) => $monitor->update(['enabled' => false])); }, 'disable'), Action::make(__('Delete'), function (Enumerable $models): void { $models->each(fn (Monitor $monitor) => $monitor->delete()); }, 'delete'), ]; } public function link(Model $model): ?string { return route('uptime.monitor.view', ['monitor' => $model]); } } ================================================ FILE: packages/uptime/src/Http/Livewire/UptimeMonitorForm.php ================================================ exists) { $this->authorize('update', $monitor); } else { $this->authorize('create', $monitor); } $this->form->fill($monitor->toArray()); $this->monitor = $monitor; } /** @var array $availableIntervals */ $availableIntervals = array_keys(config('uptime.intervals', [])); if (! in_array($this->form->interval, $availableIntervals) && count($availableIntervals) > 0) { $this->form->interval = $availableIntervals[0]; } } #[On('save')] public function save(): void { $this->validate(); if ($this->monitor->exists) { $this->authorize('update', $this->monitor); $this->monitor->update($this->form->all()); } else { $this->authorize('create', $this->monitor); $this->monitor = Monitor::query()->create( $this->form->all() ); } if (! $this->inline) { $this->alert( __('Saved'), __('Uptime monitor was successfully :action', ['action' => $this->monitor->wasRecentlyCreated ? 'created' : 'saved']), AlertType::Success ); $this->redirectRoute('uptime'); } } public function render(): mixed { /** @var view-string $view */ $view = 'uptime::livewire.monitor.form'; return view($view, [ 'updating' => $this->monitor->exists, ]); } } ================================================ FILE: packages/uptime/src/Http/Livewire/UptimeMonitors.php ================================================ exists(); return view($view, [ 'hasMonitors' => $hasMonitors, ]); } } ================================================ FILE: packages/uptime/src/Http/Middleware/ExternalOutpostMiddleware.php ================================================ ip(); if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) { if (! $allowExternalOutposts) { return response()->json(['message' => 'External outposts are not allowed.'], 403); } } return $next($request); } } ================================================ FILE: packages/uptime/src/Http/Middleware/OutpostAuthMiddleware.php ================================================ header('X-Outpost-Token'); if ($token !== config('uptime.outpost_token')) { return response()->json(['message' => 'Unauthorized'], 401); } return $next($request); } } ================================================ FILE: packages/uptime/src/Jobs/AggregateResultsJob.php ================================================ onQueue(config('uptime.queue')); } public function handle(AggregateResults $results): void { $results->aggregate($this->monitor); } public function uniqueId(): int { return $this->monitor->id; } } ================================================ FILE: packages/uptime/src/Jobs/CheckUnavailableOutpostJob.php ================================================ onQueue(config('uptime.queue')); } public function handle(): void { try { $response = Http::timeout(5) ->connectTimeout(5) ->baseUrl($this->outpost->url()) ->get('health'); if ($response->successful()) { $this->outpost->update([ 'status' => OutpostStatus::Available, 'unavailable_at' => null, 'last_available_at' => now(), ]); } else { $this->outpost->delete(); } } catch (ConnectionException) { $this->outpost->delete(); } } public function uniqueId(): int { return $this->outpost->id; } } ================================================ FILE: packages/uptime/src/Jobs/CheckUptimeJob.php ================================================ onQueue(config('uptime.queue')); } public function handle(CheckUptime $uptime, TeamService $teamService): void { $teamService->setTeamById($this->monitor->team_id); $uptime->check($this->monitor); } public function uniqueId(): int { return $this->monitor->id; } } ================================================ FILE: packages/uptime/src/Jobs/UpdateMonitorLocationJob.php ================================================ onQueue(config('uptime.queue')); } public function handle(FetchGeolocation $fetchGeolocation): void { if (! $this->monitor->shouldFetchGeoip()) { return; } $target = $this->monitor->type->formatTarget($this->monitor); $geolocation = $fetchGeolocation->fetch($target); if ($geolocation === null) { return; } $this->monitor->updateQuietly([ 'country' => $geolocation['country'], 'latitude' => $geolocation['latitude'], 'longitude' => $geolocation['longitude'], 'geoip_fetched_at' => now(), ]); } } ================================================ FILE: packages/uptime/src/Listeners/CheckLatencyListener.php ================================================ checker->check($event->monitor); } } ================================================ FILE: packages/uptime/src/Listeners/DowntimeEndNotificationListener.php ================================================ downtime); } } ================================================ FILE: packages/uptime/src/Listeners/DowntimeStartNotificationListener.php ================================================ teamService->setTeam($event->monitor->team); DowntimeStartNotification::notify($event->monitor); } } ================================================ FILE: packages/uptime/src/Models/Downtime.php ================================================ 'datetime', 'end' => 'datetime', 'data' => 'array', ]; public function monitor(): BelongsTo { return $this->belongsTo(Monitor::class); } public function prunable(): Builder { return static::withoutGlobalScopes()->where('created_at', '<=', $this->retentionPeriod()); } } ================================================ FILE: packages/uptime/src/Models/Monitor.php ================================================ $results * @property Collection $aggregatedResults * @property Collection $downtimes */ #[ObservedBy([MonitorObserver::class])] #[ScopedBy([TeamScope::class])] class Monitor extends Model { use HasFactory; protected $table = 'uptime_monitors'; protected $guarded = []; protected $casts = [ 'enabled' => 'boolean', 'type' => Type::class, 'settings' => 'array', 'next_run' => 'datetime', 'state' => State::class, 'interval' => 'integer', 'latitude' => 'float', 'longitude' => 'float', 'geoip_fetched_at' => 'datetime', 'geoip_automatic' => 'boolean', ]; public function site(): BelongsTo { return $this->belongsTo(Site::class); } public function results(): HasMany { return $this->hasMany(Result::class); } public function aggregatedResults(): HasMany { return $this->hasMany(ResultAggregate::class); } public function downtimes(): HasMany { return $this->hasMany(Downtime::class); } public function team(): BelongsTo { return $this->belongsTo(Team::class); } public function closestOutpost(): BelongsTo { return $this->belongsTo(Outpost::class, 'closest_outpost_id'); } public function currentDowntime(): ?Downtime { /** @var ?Downtime $downtime */ $downtime = $this->downtimes() ->whereNull('end') ->orderByDesc('start') ->first(); return $downtime; } public function shouldFetchGeoip(): bool { if (! $this->geoip_automatic) { return false; } if ($this->geoip_fetched_at === null) { return true; } return $this->geoip_fetched_at->lt(now()->subDay()); } protected static function newFactory(): MonitorFactory { return new MonitorFactory; } } ================================================ FILE: packages/uptime/src/Models/Outpost.php ================================================ OutpostStatus::class, 'latitude' => 'float', 'longitude' => 'float', 'geoip_automatic' => 'boolean', 'last_available_at' => 'datetime', 'unavailable_at' => 'datetime', ]; public function url(): string { return "https://{$this->ip}:{$this->port}"; } } ================================================ FILE: packages/uptime/src/Models/Result.php ================================================ belongsTo(Monitor::class); } public function prunable(): Builder { return static::withoutGlobalScopes()->where('created_at', '<=', $this->retentionPeriod()); } } ================================================ FILE: packages/uptime/src/Models/ResultAggregate.php ================================================ belongsTo(Monitor::class); } } ================================================ FILE: packages/uptime/src/Notifications/Conditions/ClosestCountryCondition.php ================================================ country; if ($country === null) { return false; } $closestCountry = $notification->monitor->closestOutpost?->country; if ($closestCountry === null) { return false; } return $country === $closestCountry; } public static function info(): ?string { return __('Only triggers when the notification originates from your geographically closest monitoring location.'); } } ================================================ FILE: packages/uptime/src/Notifications/Conditions/CountryCondition.php ================================================ whereNotNull('country') ->distinct('country') ->orderBy('country') ->pluck('country', 'country') ->toArray(); } public function operators(): array { return [ '=' => 'is', '!=' => 'is not', ]; } public function applies( Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta ): bool { /** @var LatencyChangedNotification|LatencyPeakNotification $notification */ $country = $notification->country; if ($country === null) { return false; } return match ($operator) { '=' => $country == $value, '!=' => $country != $value, default => false, }; } } ================================================ FILE: packages/uptime/src/Notifications/Conditions/LatencyMsCondition.php ================================================ 'Current', 'change' => 'Change', 'change_absolute' => 'Change (absolute)', ]; } public function operators(): array { return [ '=' => 'Equal to', '<>' => 'Not equal to', '<' => 'Less than', '<=' => 'Less or equal than', '>' => 'Greater than', '>=' => 'Greater or equal than', ]; } public function applies( Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta ): bool { /** @var LatencyChangedNotification|LatencyPeakNotification $notification */ $msValue = match ($operand) { 'current' => $this->getCurrentLatency($notification), 'change' => $this->getLatencyChange($notification), 'change_absolute' => abs($this->getLatencyChange($notification)), default => 0, }; return match ($operator) { '=' => $msValue == $value, '<>' => $msValue != $value, '<' => $msValue < $value, '<=' => $msValue <= $value, '>' => $msValue > $value, '>=' => $msValue >= $value, default => false, }; } protected function getCurrentLatency(LatencyChangedNotification|LatencyPeakNotification $notification): float { if ($notification instanceof LatencyChangedNotification) { return $notification->currentAverage; } return $notification->peakLatency; } protected function getLatencyChange(LatencyChangedNotification|LatencyPeakNotification $notification): float { if ($notification instanceof LatencyChangedNotification) { return $notification->currentAverage - $notification->previousAverage; } return $notification->peakLatency - $notification->averageLatency; } } ================================================ FILE: packages/uptime/src/Notifications/Conditions/LatencyPercentCondition.php ================================================ 'Relative', 'absolute' => 'Absolute', ]; } public function operators(): array { return [ '=' => 'Equal to', '<>' => 'Not equal to', '<' => 'Less than', '<=' => 'Less or equal than', '>' => 'Greater than', '>=' => 'Greater or equal than', ]; } public function applies( Notification $notification, ?string $operand, ?string $operator, mixed $value, ?array $meta ): bool { /** @var LatencyChangedNotification $notification */ $percentChanged = $notification->percent; if ($operand === 'absolute') { $percentChanged = abs($percentChanged); } return match ($operator) { '=' => $percentChanged == $value, '<>' => $percentChanged != $value, '<' => $percentChanged < $value, '<=' => $percentChanged <= $value, '>' => $percentChanged > $value, '>=' => $percentChanged >= $value, default => false, }; } } ================================================ FILE: packages/uptime/src/Notifications/DowntimeEndNotification.php ================================================ downtime->monitor; $site = $monitor->site->url ?? $monitor->settings['host'] ?? ''; return __(':site is back up!', ['site' => $site]); } public function description(): string { return __('When down at :start and became available on :end. Downtime: :downtime', [ 'start' => $this->downtime->start->toDateTimeString(), 'end' => $this->downtime->end?->toDateTimeString() ?? __('Unknown'), 'downtime' => $this->downtime->start->longAbsoluteDiffForHumans($this->downtime->end), ]); } public static function info(): ?string { return __('Triggered when your site recovers and becomes available again after downtime.'); } public function uniqueId(): string|int { return $this->downtime->id; } public function site(): ?Site { return $this->downtime->monitor?->site; } } ================================================ FILE: packages/uptime/src/Notifications/DowntimeStartNotification.php ================================================ monitor->site->url ?? $this->monitor->settings['host'] ?? ''; return __(':host is down!', ['host' => $host]); } public function description(): string { $downtime = $this->monitor->currentDowntime(); if ($downtime === null) { return ''; } return __('Since: :start', ['start' => $downtime->start->toDateTimeString()]); } public static function info(): ?string { return __('Triggered when your site becomes unreachable.'); } public function uniqueId(): string { return (string) $this->monitor->id; } public function site(): ?Site { return $this->monitor->site; } } ================================================ FILE: packages/uptime/src/Notifications/LatencyChangedNotification.php ================================================ 'group', 'operator' => 'all', 'children' => [ [ 'type' => 'condition', 'condition' => LatencyPercentCondition::class, 'operator' => '>=', 'operand' => 'absolute', 'value' => 50, ], ], ]; public function __construct( public Monitor $monitor, public float $percent, public float $previousAverage, public float $currentAverage, public ?string $country = null ) {} public function title(): string { $site = $this->site()->url ?? $this->monitor->settings['host'] ?? ''; $country = $this->country ? " in {$this->country}" : ''; return __(':site latency changed by :percent % from :country', ['site' => $site, 'percent' => $this->percent, 'country' => $country]); } public function description(): string { if ($this->country) { return __('Past 12 hour average: :previous ms. Current average: :current ms from :country', [ 'previous' => round($this->previousAverage, 2), 'current' => round($this->currentAverage, 2), 'country' => $this->country, ]); } else { return __('Past 12 hour average: :previous ms. Current average: :current ms', [ 'previous' => round($this->previousAverage, 2), 'current' => round($this->currentAverage, 2), ]); } } public static function info(): ?string { return __('Triggered after an uptime check if the latency has changed.'); } public function viewUrl(): ?string { return route('uptime.monitor.view', ['monitor' => $this->monitor]); } public function level(): Level { return match (true) { $this->percent < 100 => Level::Info, $this->percent < 200 => Level::Warning, default => Level::Critical, }; } public function uniqueId(): string|int { return $this->country ? "{$this->monitor->id}_{$this->country}" : $this->monitor->id; } public function site(): ?Site { return $this->monitor->site; } } ================================================ FILE: packages/uptime/src/Notifications/LatencyPeakNotification.php ================================================ 'group', 'operator' => 'all', 'children' => [ [ 'type' => 'condition', 'condition' => LatencyPercentCondition::class, 'operator' => '>=', 'operand' => 'absolute', 'value' => 100, ], [ 'type' => 'condition', 'condition' => LatencyMsCondition::class, 'operator' => '>=', 'operand' => 'change_absolute', 'value' => 500, ], [ 'type' => 'condition', 'condition' => ClosestCountryCondition::class, ], ], ]; public function __construct( public Monitor $monitor, public float $peakLatency, public float $averageLatency, public float $percent, public ?string $country = null ) {} public function title(): string { $site = $this->site()->url ?? $this->monitor->settings['host'] ?? ''; if ($this->country) { return __(':site latency is peaking from :country', ['site' => $site, 'country' => $this->country]); } else { return __(':site latency is peaking', ['site' => $site]); } } public function description(): string { $country = $this->country ? " ({$this->country})" : ''; return __('Current peak: :peak ms. Average: :average ms (+:percent%) from :country', [ 'peak' => round($this->peakLatency, 2), 'average' => round($this->averageLatency, 2), 'percent' => round($this->percent, 0), 'country' => $country, ]); } public static function info(): ?string { return __('Triggered when latency spikes significantly above the average in the past hour.'); } public function viewUrl(): ?string { return route('uptime.monitor.view', ['monitor' => $this->monitor]); } public function level(): Level { return match (true) { $this->percent < 100 => Level::Info, $this->percent < 200 => Level::Warning, default => Level::Critical, }; } public function uniqueId(): string|int { return $this->country ? "peak_{$this->monitor->id}_{$this->country}" : "peak_{$this->monitor->id}"; } public function site(): ?Site { return $this->monitor->site; } } ================================================ FILE: packages/uptime/src/Observers/MonitorObserver.php ================================================ team(); $monitor->team_id = $team->id; } public function created(Monitor $monitor): void { UpdateMonitorLocationJob::dispatch($monitor); CheckUptimeJob::dispatch($monitor); } } ================================================ FILE: packages/uptime/src/Observers/OutpostObserver.php ================================================ status === OutpostStatus::Unavailable) { Monitor::query() ->withoutGlobalScopes() ->where('closest_outpost_id', $outpost->id) ->update(['closest_outpost_id' => null]); // Set unavailable_at if not already set if ($outpost->unavailable_at === null) { $outpost->updateQuietly(['unavailable_at' => now()]); } } } public function deleted(Outpost $outpost): void { // Clear the closest_outpost_id for monitors using this outpost Monitor::query() ->withoutGlobalScopes() ->where('closest_outpost_id', $outpost->id) ->update(['closest_outpost_id' => null]); } } ================================================ FILE: packages/uptime/src/ServiceProvider.php ================================================ registerConfig(); } protected function registerConfig(): static { $this->mergeConfigFrom(__DIR__.'/../config/uptime.php', 'uptime'); return $this; } public function boot(): void { $this ->bootConfig() ->bootMigrations() ->bootCommands() ->bootViews() ->bootLivewire() ->bootRoutes() ->bootEvents() ->bootRatelimiting() ->bootNavigation() ->bootNotifications() ->bootGates() ->bootPolicies(); } protected function bootConfig(): static { $this->publishes([ __DIR__.'/../config/uptime.php' => config_path('uptime.php'), ], 'config'); return $this; } protected function bootMigrations(): static { $this->loadMigrationsFrom(__DIR__.'/../database/migrations'); return $this; } protected function bootCommands(): static { if ($this->app->runningInConsole()) { $this->commands([ CheckUptimeCommand::class, AggregateResultsCommand::class, ScheduleUptimeChecksCommand::class, CheckLatencyCommand::class, GenerateRootCaCommand::class, CheckUnavailableOutpostsCommand::class, ]); } return $this; } protected function bootViews(): static { $this->loadViewsFrom(__DIR__.'/../resources/views', 'uptime'); return $this; } protected function bootLivewire(): static { Livewire::component('uptime', UptimeMonitors::class); Livewire::component('uptime-monitor-form', UptimeMonitorForm::class); Livewire::component('uptime-monitor-table', MonitorTable::class); Livewire::component('uptime-downtime-table', DowntimeTable::class); Livewire::component('monitor-column-latency-chart', ColumnLatencyChart::class); Livewire::component('monitor-latency-chart', LatencyChart::class); Livewire::component('monitor-dashboard', Dashboard::class); return $this; } protected function bootRoutes(): static { if (! $this->app->routesAreCached()) { Route::middleware(['web', 'auth']) ->group(fn () => $this->loadRoutesFrom(__DIR__.'/../routes/web.php')); Route::prefix('api') ->middleware(['api']) ->group(fn () => $this->loadRoutesFrom(__DIR__.'/../routes/api.php')); } return $this; } protected function bootEvents(): static { Event::listen(DowntimeStartEvent::class, DowntimeStartNotificationListener::class); Event::listen(DowntimeEndEvent::class, DowntimeEndNotificationListener::class); Event::listen(UptimeCheckedEvent::class, CheckLatencyListener::class); return $this; } protected function bootRatelimiting(): static { RateLimiter::for('uptime-ips', function (Request $request): Limit { return Limit::perMinute(10)->by($request->ip); }); return $this; } protected function bootNavigation(): static { Navigation::path(__DIR__.'/../resources/navigation.php'); return $this; } protected function bootNotifications(): static { NotificationRegistry::registerNotification([ DowntimeStartNotification::class, DowntimeEndNotification::class, LatencyChangedNotification::class, LatencyPeakNotification::class, ]); NotificationRegistry::registerCondition(LatencyChangedNotification::class, [ LatencyPercentCondition::class, LatencyMsCondition::class, CountryCondition::class, ClosestCountryCondition::class, ]); NotificationRegistry::registerCondition(LatencyPeakNotification::class, [ LatencyPercentCondition::class, LatencyMsCondition::class, CountryCondition::class, ClosestCountryCondition::class, ]); return $this; } protected function bootGates(): static { Gate::define('use-uptime', function (User $user) { return ce(); }); return $this; } protected function bootPolicies(): static { if (ce()) { Gate::policy(Monitor::class, AllowAllPolicy::class); } return $this; } } ================================================ FILE: packages/uptime/testbench.yaml ================================================ providers: - Vigilant\Uptime\ServiceProvider ================================================ FILE: packages/uptime/tests/Fakes/HandlerStatsResponse.php ================================================ handlerStats = $handlerStats; return $this; } public function handlerStats(): array { return $this->handlerStats; } public function then(?callable $onFulfilled = null, ?callable $onRejected = null): PromiseInterface { return $this; } public function otherwise(callable $onRejected): PromiseInterface { return $this; } public function getState(): string { return ''; } public function resolve($value): void { // } public function reject($reason): void { // } public function cancel(): void { // } public function wait(bool $unwrap = true) { // } } ================================================ FILE: packages/uptime/tests/Feature/AggregateResultsTest.php ================================================ create([ 'team_id' => 1, 'name' => 'Test Monitor', 'type' => Type::Http, 'settings' => [ 'host' => 'http://service', ], 'interval' => '* * * * *', 'retries' => 1, 'timeout' => 1, ]); }); $this->assertNotNull($monitor); for ($minute = 0; $minute < (60 * 24); $minute++) { $date = now()->subMinutes($minute); $monitor->results()->create([ 'total_time' => $minute, 'country' => 'US', 'created_at' => $date, 'updated_at' => $date, ]); } $this->artisan(AggregateResultsCommand::class); $this->assertCount(24, $monitor->aggregatedResults); } public function test_it_aggregates_uptime_results_per_country(): void { $monitor = null; Monitor::withoutEvents(function () use (&$monitor) { /** @var Monitor $monitor */ $monitor = Monitor::query()->create([ 'team_id' => 1, 'name' => 'Test Monitor', 'type' => Type::Http, 'settings' => [ 'host' => 'http://service', ], 'interval' => '* * * * *', 'retries' => 1, 'timeout' => 1, ]); }); $this->assertNotNull($monitor); // Create results from different countries for ($minute = 0; $minute < 120; $minute++) { $date = now()->subMinutes($minute); $country = $minute % 2 === 0 ? 'US' : 'DE'; $monitor->results()->create([ 'total_time' => $minute, 'country' => $country, 'created_at' => $date, 'updated_at' => $date, ]); } $this->artisan(AggregateResultsCommand::class); // Should create separate aggregates for US and DE $usAggregates = $monitor->aggregatedResults()->where('country', 'US')->count(); $deAggregates = $monitor->aggregatedResults()->where('country', 'DE')->count(); $this->assertGreaterThan(0, $usAggregates); $this->assertGreaterThan(0, $deAggregates); } } ================================================ FILE: packages/uptime/tests/Feature/DowntimeTest.php ================================================ create([ 'team_id' => 1, 'name' => 'Test Monitor', 'type' => Type::Http, 'settings' => [ 'host' => 'http://service', ], 'interval' => '* * * * *', 'retries' => 0, 'timeout' => 1, ]); }); $this->assertNotNull($monitor); $outpost = \Vigilant\Uptime\Models\Outpost::create([ 'ip' => '127.0.0.1', 'port' => 3000, 'external_ip' => '127.0.0.1', 'status' => \Vigilant\Uptime\Enums\OutpostStatus::Available, 'country' => 'US', 'last_available_at' => now(), ]); Http::fake([ 'https://127.0.0.1:3000/*' => Http::response([ 'up' => false, 'latency_ms' => 0, ]), ]); $this->artisan(CheckUptimeCommand::class, [ 'monitorId' => $monitor->id, ]); $this->artisan(CheckUptimeCommand::class, [ 'monitorId' => $monitor->id, ]); Event::assertDispatchedTimes(DowntimeStartEvent::class, 1); } public function test_it_resolves_downtime(): void { Event::fake(); $monitor = null; Monitor::withoutEvents(function () use (&$monitor) { /** @var Monitor $monitor */ $monitor = Monitor::query()->create([ 'team_id' => 1, 'name' => 'Test Monitor', 'type' => Type::Http, 'settings' => [ 'host' => 'http://service', ], 'interval' => '* * * * *', 'retries' => 0, 'timeout' => 1, ]); }); $this->assertNotNull($monitor); $monitor->downtimes()->create([ 'start' => now()->subMinutes(5), ]); $outpost = \Vigilant\Uptime\Models\Outpost::create([ 'ip' => '127.0.0.1', 'port' => 3000, 'external_ip' => '127.0.0.1', 'status' => \Vigilant\Uptime\Enums\OutpostStatus::Available, 'country' => 'US', 'last_available_at' => now(), ]); Http::fake([ 'https://127.0.0.1:3000/*' => Http::response([ 'up' => true, 'latency_ms' => 100, ]), ]); $this->artisan(CheckUptimeCommand::class, [ 'monitorId' => $monitor->id, ]); Event::assertDispatched(DowntimeEndEvent::class); $this->assertNotNull($monitor->downtimes()->whereNotNull('end')->first()); } } ================================================ FILE: packages/uptime/tests/Feature/UptimeTest.php ================================================ create([ 'team_id' => 1, 'name' => 'Test Monitor', 'type' => Type::Http, 'settings' => [ 'host' => 'http://service', ], 'interval' => '* * * * *', 'retries' => 1, 'timeout' => 1, ]); $outpost = \Vigilant\Uptime\Models\Outpost::create([ 'ip' => '127.0.0.1', 'port' => 3000, 'external_ip' => '127.0.0.1', 'status' => \Vigilant\Uptime\Enums\OutpostStatus::Available, 'country' => 'US', 'last_available_at' => now(), ]); Http::fake([ 'https://127.0.0.1:3000/*' => Http::response([ 'up' => true, 'latency_ms' => 100, ]), ]); $this->artisan(CheckUptimeCommand::class, [ 'monitorId' => $monitor->id, ]); $this->artisan(CheckUptimeCommand::class, [ 'monitorId' => $monitor->id, ]); $results = $monitor->results; $this->assertCount(2, $results); } public function test_it_checks_uptime_via_ping(): void { $monitor = null; /** @var Monitor $monitor */ $monitor = Monitor::query()->create([ 'team_id' => 1, 'name' => 'Test Monitor', 'type' => Type::Ping, 'settings' => [ 'host' => '127.0.0.1', ], 'interval' => '* * * * *', 'retries' => 1, 'timeout' => 1, ]); $outpost = \Vigilant\Uptime\Models\Outpost::create([ 'ip' => '127.0.0.1', 'port' => 3000, 'external_ip' => '127.0.0.1', 'status' => \Vigilant\Uptime\Enums\OutpostStatus::Available, 'country' => 'US', 'last_available_at' => now(), ]); Http::fake([ 'https://127.0.0.1:3000/*' => Http::response([ 'up' => true, 'latency_ms' => 10, ]), ]); $this->artisan(CheckUptimeCommand::class, [ 'monitorId' => $monitor->id, ]); /** @var Result $result */ $result = $monitor->results->first(); $this->assertEquals(10, $result->total_time); } } ================================================ FILE: packages/uptime/tests/TestCase.php ================================================ set('database.default', 'testbench'); $app['config']->set('database.connections.testbench', [ 'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '', ]); } protected function setUp(): void { parent::setUp(); TeamService::fake(); } } ================================================ FILE: packages/uptime/tests/Unit/CalculateUptimePercentageTest.php ================================================ Monitor::factory()->create()); ResultAggregate::query()->create([ 'monitor_id' => $monitor->id, 'total_time' => 0, 'created_at' => '2024-02-24 00:00:00', ]); Downtime::query()->create([ 'monitor_id' => $monitor->id, 'start' => '2024-02-24 00:00:00', 'end' => '2024-02-24 01:00:00', 'created_at' => '2024-02-24 00:00:00', 'updated_at' => '2024-02-24 01:00:00', ]); /** @var CalculateUptimePercentage $action */ $action = app(CalculateUptimePercentage::class); $this->assertEquals(90, $action->calculate($monitor)); } } ================================================ FILE: packages/uptime/tests/Unit/DetermineOutpostPerformanceTest.php ================================================ create([ 'team_id' => 1, 'name' => 'Test Monitor', 'type' => Type::Http, 'settings' => ['host' => 'http://example.com'], 'interval' => '* * * * *', 'retries' => 1, 'timeout' => 5, 'country' => 'US', 'latitude' => 40.0, 'longitude' => -70.0, ]); // Create thousands of outposts efficiently $outpostsData = []; $countries = ['US', 'UK', 'DE', 'FR', 'JP', 'AU', 'CA', 'BR', 'IN', 'SG']; for ($i = 0; $i < 1000; $i++) { $country = $countries[$i % count($countries)]; $outpostsData[] = [ 'ip' => '192.168.'.floor($i / 256).'.'.($i % 256), 'port' => 8080 + ($i % 100), 'external_ip' => floor($i / 256).'.'.($i % 256).'.1.1', 'status' => OutpostStatus::Available->value, 'country' => $country, 'latitude' => 40.0 + ($i % 10), 'longitude' => -70.0 + ($i % 10), 'last_available_at' => now(), 'created_at' => now(), 'updated_at' => now(), ]; } // Batch insert for performance foreach (array_chunk($outpostsData, 500) as $chunk) { Outpost::query()->insert($chunk); } $determineOutpost = new DetermineOutpost; // Measure performance $startTime = microtime(true); $iterations = 100; for ($i = 0; $i < $iterations; $i++) { $outpost = $determineOutpost->determine($monitor); $this->assertNotNull($outpost); } $endTime = microtime(true); $avgTime = ($endTime - $startTime) / $iterations; // Should complete each selection in less than 10ms on average $this->assertLessThan(0.01, $avgTime, 'Average selection time should be less than 10ms'); // Verify distribution - with distance-based selection, we should have a mix // of closest and remote outposts $closestSelections = 0; $remoteSelections = 0; for ($i = 0; $i < 100; $i++) { $outpost = $determineOutpost->determine($monitor); $this->assertNotNull($outpost); // The closest outpost will be at 40.0, -70.0 (the first one created) if ($outpost->latitude == 40.0 && $outpost->longitude == -70.0) { $closestSelections++; } else { $remoteSelections++; } } // Should maintain roughly 50/50 distribution between closest and remote $this->assertGreaterThan(30, $closestSelections); $this->assertGreaterThan(30, $remoteSelections); } public function test_it_uses_database_queries_not_memory(): void { // Create monitor and outposts $monitor = Monitor::query()->create([ 'team_id' => 1, 'name' => 'Test Monitor', 'type' => Type::Http, 'settings' => ['host' => 'http://example.com'], 'interval' => '* * * * *', 'retries' => 1, 'timeout' => 5, 'country' => 'US', 'latitude' => 40.0, 'longitude' => -70.0, ]); // Create 100 outposts for ($i = 0; $i < 100; $i++) { Outpost::query()->create([ 'ip' => "192.168.1.{$i}", 'port' => 8080, 'external_ip' => "1.2.3.{$i}", 'status' => OutpostStatus::Available, 'country' => $i < 50 ? 'US' : 'UK', 'latitude' => 40.0 + $i, 'longitude' => -70.0 + $i, 'last_available_at' => now(), ]); } // Enable query log \DB::enableQueryLog(); $determineOutpost = new DetermineOutpost; $determineOutpost->determine($monitor); $queries = \DB::getQueryLog(); // Should use efficient queries // - 1 query to find/update closest outpost // - 1 query to select either closest or remote outpost // - 1 update query for monitor's closest_outpost_id $this->assertLessThanOrEqual(3, count($queries), 'Should use at most 3 queries'); foreach ($queries as $query) { // Verify queries use LIMIT to avoid loading all records $sql = strtolower($query['query']); // All select queries should have a limit if (strpos($sql, 'select') !== false && strpos($sql, 'from') !== false) { $this->assertTrue( strpos($sql, 'limit') !== false, 'Query should use LIMIT to avoid loading all records: '.$query['query'] ); } } } public function test_remote_selection_distributes_across_all_countries(): void { $monitor = Monitor::query()->create([ 'team_id' => 1, 'name' => 'Test Monitor', 'type' => Type::Http, 'settings' => ['host' => 'http://example.com'], 'interval' => '* * * * *', 'retries' => 1, 'timeout' => 5, 'country' => 'US', 'latitude' => 40.0, 'longitude' => -70.0, ]); // Create outposts in different countries $countries = ['UK', 'DE', 'FR', 'JP', 'AU']; foreach ($countries as $index => $country) { Outpost::query()->create([ 'ip' => "192.168.1.{$index}", 'port' => 8080, 'external_ip' => "1.2.3.{$index}", 'status' => OutpostStatus::Available, 'country' => $country, 'latitude' => 40.0 + ($index * 5), 'longitude' => -70.0 + ($index * 5), 'last_available_at' => now(), ]); } $determineOutpost = new DetermineOutpost; $selectedCountries = []; // Run many selections to see distribution for ($i = 0; $i < 100; $i++) { $outpost = $determineOutpost->determine($monitor); $this->assertNotNull($outpost); if ($outpost->country !== 'US') { $selectedCountries[] = $outpost->country; } } // Should have selected from multiple different countries $uniqueCountries = array_unique($selectedCountries); $this->assertGreaterThan(1, count($uniqueCountries), 'Should select from multiple remote countries'); } } ================================================ FILE: packages/uptime/tests/Unit/DetermineOutpostTest.php ================================================ create([ 'team_id' => 1, 'name' => 'Test Monitor', 'type' => Type::Http, 'settings' => ['host' => 'http://example.com'], 'interval' => '* * * * *', 'retries' => 1, 'timeout' => 5, ]); $result = $determineOutpost->determine($monitor); $this->assertNull($result); } public function test_it_selects_same_country_outpost_approximately_50_percent(): void { // Create a monitor in Boston, US $monitor = Monitor::query()->create([ 'team_id' => 1, 'name' => 'Test Monitor', 'type' => Type::Http, 'settings' => ['host' => 'http://example.com'], 'interval' => '* * * * *', 'retries' => 1, 'timeout' => 5, 'country' => 'US', 'latitude' => 42.3601, 'longitude' => -71.0589, ]); // Create outposts: two in US (Boston and Chicago), one in UK (London), one in DE (Berlin) $usOutpost1 = Outpost::query()->create([ 'ip' => '192.168.1.1', 'port' => 8080, 'external_ip' => '1.2.3.4', 'status' => OutpostStatus::Available, 'country' => 'US', 'latitude' => 42.3601, 'longitude' => -71.0589, // Boston (same as monitor - closest) 'last_available_at' => now(), ]); $usOutpost2 = Outpost::query()->create([ 'ip' => '192.168.1.2', 'port' => 8080, 'external_ip' => '1.2.3.5', 'status' => OutpostStatus::Available, 'country' => 'US', 'latitude' => 41.8781, 'longitude' => -87.6298, // Chicago 'last_available_at' => now(), ]); $ukOutpost = Outpost::query()->create([ 'ip' => '192.168.1.3', 'port' => 8080, 'external_ip' => '1.2.3.6', 'status' => OutpostStatus::Available, 'country' => 'UK', 'latitude' => 51.5074, 'longitude' => -0.1278, // London 'last_available_at' => now(), ]); $deOutpost = Outpost::query()->create([ 'ip' => '192.168.1.4', 'port' => 8081, 'external_ip' => '1.2.3.7', 'status' => OutpostStatus::Available, 'country' => 'DE', 'latitude' => 52.5200, 'longitude' => 13.4050, // Berlin 'last_available_at' => now(), ]); $determineOutpost = new DetermineOutpost; $closestCount = 0; $remoteCount = 0; // Run the selection 200 times for better statistical distribution for ($i = 0; $i < 200; $i++) { $selected = $determineOutpost->determine($monitor); $this->assertNotNull($selected); if ($selected->id === $usOutpost1->id) { $closestCount++; } else { $remoteCount++; } } // Closest outpost (Boston) should be selected approximately 50% of the time (allow variance for randomness) $this->assertGreaterThan(60, $closestCount); $this->assertLessThan(140, $closestCount); // Remote outposts should be selected approximately 50% of the time $this->assertGreaterThan(60, $remoteCount); $this->assertLessThan(140, $remoteCount); } public function test_it_distributes_remote_country_outposts_evenly(): void { // Create monitors with different IDs and locations to test distribution $monitors = []; for ($i = 0; $i < 10; $i++) { $monitors[] = Monitor::query()->create([ 'team_id' => 1, 'name' => "Test Monitor {$i}", 'type' => Type::Http, 'settings' => ['host' => 'http://example.com'], 'interval' => '* * * * *', 'retries' => 1, 'timeout' => 5, 'country' => 'US', 'latitude' => 42.3601, 'longitude' => -71.0589, // Boston ]); } // Create outposts $usOutpost = Outpost::query()->create([ 'ip' => '192.168.1.1', 'port' => 8080, 'external_ip' => '1.2.3.4', 'status' => OutpostStatus::Available, 'country' => 'US', 'latitude' => 42.3601, 'longitude' => -71.0589, // Boston (closest) 'last_available_at' => now(), ]); $ukOutpost = Outpost::query()->create([ 'ip' => '192.168.1.2', 'port' => 8080, 'external_ip' => '1.2.3.5', 'status' => OutpostStatus::Available, 'country' => 'UK', 'latitude' => 51.5074, 'longitude' => -0.1278, // London (farthest from Boston) 'last_available_at' => now(), ]); $deOutpost = Outpost::query()->create([ 'ip' => '192.168.1.3', 'port' => 8080, 'external_ip' => '1.2.3.6', 'status' => OutpostStatus::Available, 'country' => 'DE', 'latitude' => 52.5200, 'longitude' => 13.4050, // Berlin 'last_available_at' => now(), ]); $determineOutpost = new DetermineOutpost; $ukSelections = 0; $deSelections = 0; // Test remote selection for multiple runs per monitor foreach ($monitors as $monitor) { // Run selection multiple times, filter for remote selections only for ($i = 0; $i < 20; $i++) { $selected = $determineOutpost->determine($monitor); $this->assertNotNull($selected); if ($selected->id !== $usOutpost->id) { if ($selected->country === 'UK') { $ukSelections++; } elseif ($selected->country === 'DE') { $deSelections++; } } } } // Both remote outposts should have been selected $this->assertGreaterThan(0, $ukSelections); $this->assertGreaterThan(0, $deSelections); } public function test_it_handles_monitor_without_country(): void { $monitor = Monitor::query()->create([ 'team_id' => 1, 'name' => 'Test Monitor', 'type' => Type::Http, 'settings' => ['host' => 'http://example.com'], 'interval' => '* * * * *', 'retries' => 1, 'timeout' => 5, ]); $outpost = Outpost::query()->create([ 'ip' => '192.168.1.1', 'port' => 8080, 'external_ip' => '1.2.3.4', 'status' => OutpostStatus::Available, 'country' => 'US', 'latitude' => 42.3601, 'longitude' => -71.0589, 'last_available_at' => now(), ]); $determineOutpost = new DetermineOutpost; $result = $determineOutpost->determine($monitor); $this->assertNotNull($result); $this->assertEquals($outpost->id, $result->id); } public function test_it_handles_single_outpost_in_same_country(): void { $monitor = Monitor::query()->create([ 'team_id' => 1, 'name' => 'Test Monitor', 'type' => Type::Http, 'settings' => ['host' => 'http://example.com'], 'interval' => '* * * * *', 'retries' => 1, 'timeout' => 5, 'country' => 'US', 'latitude' => 42.3601, 'longitude' => -71.0589, ]); $outpost = Outpost::query()->create([ 'ip' => '192.168.1.1', 'port' => 8080, 'external_ip' => '1.2.3.4', 'status' => OutpostStatus::Available, 'country' => 'US', 'latitude' => 42.3601, 'longitude' => -71.0589, 'last_available_at' => now(), ]); $determineOutpost = new DetermineOutpost; // Should always return the single outpost for ($i = 0; $i < 10; $i++) { $result = $determineOutpost->determine($monitor); $this->assertNotNull($result); $this->assertEquals($outpost->id, $result->id); } } public function test_it_handles_no_same_country_outposts(): void { $monitor = Monitor::query()->create([ 'team_id' => 1, 'name' => 'Test Monitor', 'type' => Type::Http, 'settings' => ['host' => 'http://example.com'], 'interval' => '* * * * *', 'retries' => 1, 'timeout' => 5, 'country' => 'US', 'latitude' => 42.3601, 'longitude' => -71.0589, ]); // Only create outposts in other countries $ukOutpost = Outpost::query()->create([ 'ip' => '192.168.1.1', 'port' => 8080, 'external_ip' => '1.2.3.4', 'status' => OutpostStatus::Available, 'country' => 'UK', 'latitude' => 51.5074, 'longitude' => -0.1278, 'last_available_at' => now(), ]); $deOutpost = Outpost::query()->create([ 'ip' => '192.168.1.2', 'port' => 8080, 'external_ip' => '1.2.3.5', 'status' => OutpostStatus::Available, 'country' => 'DE', 'latitude' => 52.5200, 'longitude' => 13.4050, 'last_available_at' => now(), ]); $determineOutpost = new DetermineOutpost; // Should still return an outpost (from other countries) $result = $determineOutpost->determine($monitor); $this->assertNotNull($result); $this->assertContains($result->country, ['UK', 'DE']); } public function test_it_stores_closest_outpost_id(): void { $monitor = Monitor::query()->create([ 'team_id' => 1, 'name' => 'Test Monitor', 'type' => Type::Http, 'settings' => ['host' => 'http://example.com'], 'interval' => '* * * * *', 'retries' => 1, 'timeout' => 5, 'country' => 'US', 'latitude' => 42.3601, 'longitude' => -71.0589, ]); $closestOutpost = Outpost::query()->create([ 'ip' => '192.168.1.1', 'port' => 8080, 'external_ip' => '1.2.3.4', 'status' => OutpostStatus::Available, 'country' => 'US', 'latitude' => 42.3601, 'longitude' => -71.0589, // Same location as monitor 'last_available_at' => now(), ]); $farOutpost = Outpost::query()->create([ 'ip' => '192.168.1.2', 'port' => 8080, 'external_ip' => '1.2.3.5', 'status' => OutpostStatus::Available, 'country' => 'UK', 'latitude' => 51.5074, 'longitude' => -0.1278, 'last_available_at' => now(), ]); $determineOutpost = new DetermineOutpost; // Initially, no closest outpost is set $this->assertNull($monitor->closest_outpost_id); // Determine outpost should store the closest one $result = $determineOutpost->determine($monitor); $monitor->refresh(); $this->assertNotNull($monitor->closest_outpost_id); $this->assertEquals($closestOutpost->id, $monitor->closest_outpost_id); } public function test_it_nullifies_closest_outpost_when_outpost_deleted(): void { $monitor = Monitor::query()->create([ 'team_id' => 1, 'name' => 'Test Monitor', 'type' => Type::Http, 'settings' => ['host' => 'http://example.com'], 'interval' => '* * * * *', 'retries' => 1, 'timeout' => 5, 'country' => 'US', 'latitude' => 42.3601, 'longitude' => -71.0589, ]); $outpost = Outpost::query()->create([ 'ip' => '192.168.1.1', 'port' => 8080, 'external_ip' => '1.2.3.4', 'status' => OutpostStatus::Available, 'country' => 'US', 'latitude' => 42.3601, 'longitude' => -71.0589, 'last_available_at' => now(), ]); // Set the closest outpost $monitor->update(['closest_outpost_id' => $outpost->id]); // Delete the outpost $outpost->delete(); // Verify the closest_outpost_id is set to null $monitor->refresh(); $this->assertNull($monitor->closest_outpost_id); } public function test_it_nullifies_closest_outpost_when_outpost_becomes_unavailable(): void { $monitor = Monitor::query()->create([ 'team_id' => 1, 'name' => 'Test Monitor', 'type' => Type::Http, 'settings' => ['host' => 'http://example.com'], 'interval' => '* * * * *', 'retries' => 1, 'timeout' => 5, 'country' => 'US', 'latitude' => 42.3601, 'longitude' => -71.0589, ]); $outpost = Outpost::query()->create([ 'ip' => '192.168.1.1', 'port' => 8080, 'external_ip' => '1.2.3.4', 'status' => OutpostStatus::Available, 'country' => 'US', 'latitude' => 42.3601, 'longitude' => -71.0589, 'last_available_at' => now(), ]); // Set the closest outpost $monitor->update(['closest_outpost_id' => $outpost->id]); // Mark the outpost as unavailable $outpost->update(['status' => OutpostStatus::Unavailable]); // Verify the closest_outpost_id is set to null $monitor->refresh(); $this->assertNull($monitor->closest_outpost_id); } public function test_it_uses_cached_closest_outpost_when_available(): void { $monitor = Monitor::query()->create([ 'team_id' => 1, 'name' => 'Test Monitor', 'type' => Type::Http, 'settings' => ['host' => 'http://example.com'], 'interval' => '* * * * *', 'retries' => 1, 'timeout' => 5, 'country' => 'US', 'latitude' => 42.3601, 'longitude' => -71.0589, ]); $closestOutpost = Outpost::query()->create([ 'ip' => '192.168.1.1', 'port' => 8080, 'external_ip' => '1.2.3.4', 'status' => OutpostStatus::Available, 'country' => 'US', 'latitude' => 42.3601, 'longitude' => -71.0589, 'last_available_at' => now(), ]); $remoteOutpost = Outpost::query()->create([ 'ip' => '192.168.1.2', 'port' => 8080, 'external_ip' => '1.2.3.5', 'status' => OutpostStatus::Available, 'country' => 'UK', 'latitude' => 51.5074, 'longitude' => -0.1278, 'last_available_at' => now(), ]); // Pre-set the closest outpost $monitor->update(['closest_outpost_id' => $closestOutpost->id]); $determineOutpost = new DetermineOutpost; // When selecting closest, it should use the cached value $closestSelections = 0; for ($i = 0; $i < 100; $i++) { $result = $determineOutpost->determine($monitor); if ($result !== null && $result->id === $closestOutpost->id) { $closestSelections++; } } // Should use the cached closest outpost approximately 50% of the time $this->assertGreaterThan(30, $closestSelections); $this->assertLessThan(70, $closestSelections); } public function test_excluded_outposts_dont_affect_closest_cache(): void { $monitor = Monitor::query()->create([ 'team_id' => 1, 'name' => 'Test Monitor', 'type' => Type::Http, 'settings' => ['host' => 'http://example.com'], 'interval' => '* * * * *', 'retries' => 1, 'timeout' => 5, 'country' => 'US', 'latitude' => 42.3601, 'longitude' => -71.0589, ]); $closestOutpost = Outpost::query()->create([ 'ip' => '192.168.1.1', 'port' => 8080, 'external_ip' => '1.2.3.4', 'status' => OutpostStatus::Available, 'country' => 'US', 'latitude' => 42.3601, 'longitude' => -71.0589, // Same as monitor (closest) 'last_available_at' => now(), ]); $secondClosest = Outpost::query()->create([ 'ip' => '192.168.1.2', 'port' => 8080, 'external_ip' => '1.2.3.5', 'status' => OutpostStatus::Available, 'country' => 'US', 'latitude' => 42.3650, 'longitude' => -71.0600, // Very close to monitor 'last_available_at' => now(), ]); $remoteOutpost = Outpost::query()->create([ 'ip' => '192.168.1.3', 'port' => 8080, 'external_ip' => '1.2.3.6', 'status' => OutpostStatus::Available, 'country' => 'UK', 'latitude' => 51.5074, 'longitude' => -0.1278, 'last_available_at' => now(), ]); $determineOutpost = new DetermineOutpost; // First call should set the closest outpost $determineOutpost->determine($monitor); $monitor->refresh(); $this->assertEquals($closestOutpost->id, $monitor->closest_outpost_id); // When we exclude the closest outpost (simulating retry after failure), // it should NOT return the excluded outpost // Test multiple times to account for randomness in selection $excludedReturned = false; for ($i = 0; $i < 10; $i++) { $result = $determineOutpost->determine($monitor, [$closestOutpost->id]); // Should never get the excluded closest outpost if ($result !== null && $result->id === $closestOutpost->id) { $excludedReturned = true; break; } } $this->assertFalse($excludedReturned, 'Excluded outpost should never be returned'); // The cached closest_outpost_id should NOT have changed $monitor->refresh(); $this->assertEquals($closestOutpost->id, $monitor->closest_outpost_id, 'Closest outpost cache should not change when using excluded outposts'); } } ================================================ FILE: packages/uptime/tests/Unit/Enums/TypeTest.php ================================================ make([ 'settings' => ['host' => '127.0.0.1'], 'type' => Type::Http, ]); $this->assertSame('127.0.0.1', Type::Http->formatTarget($monitor)); } } ================================================ FILE: packages/uptime/tests/Unit/ExternalOutpostMiddlewareTest.php ================================================ false]); $middleware = new ExternalOutpostMiddleware; $request = Request::create('/test', 'GET'); $request->server->set('REMOTE_ADDR', '192.168.1.1'); $response = $middleware->handle($request, function ($req) { return response()->json(['success' => true]); }); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals(['success' => true], $response->getData(true)); } public function test_it_allows_localhost_when_external_outposts_disabled(): void { config(['uptime.allow_external_outposts' => false]); $middleware = new ExternalOutpostMiddleware; $request = Request::create('/test', 'GET'); $request->server->set('REMOTE_ADDR', '127.0.0.1'); $response = $middleware->handle($request, function ($req) { return response()->json(['success' => true]); }); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals(['success' => true], $response->getData(true)); } public function test_it_denies_public_ip_when_external_outposts_disabled(): void { config(['uptime.allow_external_outposts' => false]); $middleware = new ExternalOutpostMiddleware; $request = Request::create('/test', 'GET'); $request->server->set('REMOTE_ADDR', '8.8.8.8'); $response = $middleware->handle($request, function ($req) { return response()->json(['success' => true]); }); $this->assertEquals(403, $response->getStatusCode()); $this->assertEquals(['message' => 'External outposts are not allowed.'], $response->getData(true)); } public function test_it_allows_public_ip_when_external_outposts_enabled(): void { config(['uptime.allow_external_outposts' => true]); $middleware = new ExternalOutpostMiddleware; $request = Request::create('/test', 'GET'); $request->server->set('REMOTE_ADDR', '8.8.8.8'); $response = $middleware->handle($request, function ($req) { return response()->json(['success' => true]); }); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals(['success' => true], $response->getData(true)); } public function test_it_allows_private_ip_when_external_outposts_enabled(): void { config(['uptime.allow_external_outposts' => true]); $middleware = new ExternalOutpostMiddleware; $request = Request::create('/test', 'GET'); $request->server->set('REMOTE_ADDR', '10.0.0.1'); $response = $middleware->handle($request, function ($req) { return response()->json(['success' => true]); }); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals(['success' => true], $response->getData(true)); } public function test_it_allows_reserved_ip_when_external_outposts_disabled(): void { config(['uptime.allow_external_outposts' => false]); $middleware = new ExternalOutpostMiddleware; $request = Request::create('/test', 'GET'); $request->server->set('REMOTE_ADDR', '169.254.1.1'); $response = $middleware->handle($request, function ($req) { return response()->json(['success' => true]); }); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals(['success' => true], $response->getData(true)); } public function test_it_allows_ipv6_private_address(): void { config(['uptime.allow_external_outposts' => false]); $middleware = new ExternalOutpostMiddleware; $request = Request::create('/test', 'GET'); $request->server->set('REMOTE_ADDR', 'fd00::1'); $response = $middleware->handle($request, function ($req) { return response()->json(['success' => true]); }); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals(['success' => true], $response->getData(true)); } public function test_it_denies_ipv6_public_address_when_external_outposts_disabled(): void { config(['uptime.allow_external_outposts' => false]); $middleware = new ExternalOutpostMiddleware; $request = Request::create('/test', 'GET'); $request->server->set('REMOTE_ADDR', '2001:4860:4860::8888'); $response = $middleware->handle($request, function ($req) { return response()->json(['success' => true]); }); $this->assertEquals(403, $response->getStatusCode()); $this->assertEquals(['message' => 'External outposts are not allowed.'], $response->getData(true)); } public function test_it_allows_ipv6_public_address_when_external_outposts_enabled(): void { config(['uptime.allow_external_outposts' => true]); $middleware = new ExternalOutpostMiddleware; $request = Request::create('/test', 'GET'); $request->server->set('REMOTE_ADDR', '2001:4860:4860::8888'); $response = $middleware->handle($request, function ($req) { return response()->json(['success' => true]); }); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals(['success' => true], $response->getData(true)); } } ================================================ FILE: packages/uptime/tests/Unit/FetchGeolocationTest.php ================================================ mock(ResolveRecord::class, function (MockInterface $mock) { $mock->shouldReceive('resolve')->andReturn('93.184.216.34'); }); Http::fake([ 'https://free.freeipapi.com/api/json/*' => Http::response([ 'countryCode' => 'US', 'latitude' => 40.7128, 'longitude' => -74.0060, ]), ]); $fetchGeolocation = app(FetchGeolocation::class); $result = $fetchGeolocation->fetch('example.com'); $this->assertNotNull($result); $this->assertEquals('US', $result['country']); $this->assertEquals(40.7128, $result['latitude']); $this->assertEquals(-74.0060, $result['longitude']); } public function test_it_extracts_hostname_from_url(): void { $this->mock(ResolveRecord::class, function (MockInterface $mock) { $mock->shouldReceive('resolve')->andReturn('93.184.216.34'); }); Http::fake([ 'https://free.freeipapi.com/api/json/93.184.216.34' => Http::response([ 'countryCode' => 'UK', 'latitude' => 51.5074, 'longitude' => -0.1278, ]), ]); $fetchGeolocation = app(FetchGeolocation::class); $result = $fetchGeolocation->fetch('https://example.com/path/to/resource'); $this->assertNotNull($result); $this->assertEquals('UK', $result['country']); } public function test_it_extracts_hostname_from_host_port_format(): void { Http::fake([ 'https://free.freeipapi.com/api/json/192.168.1.1' => Http::response([ 'countryCode' => 'DE', 'latitude' => 52.5200, 'longitude' => 13.4050, ]), ]); $fetchGeolocation = app(FetchGeolocation::class); $result = $fetchGeolocation->fetch('192.168.1.1:8080'); $this->assertNotNull($result); $this->assertEquals('DE', $result['country']); } public function test_it_returns_null_on_api_failure(): void { $this->mock(ResolveRecord::class, function (MockInterface $mock) { $mock->shouldReceive('resolve')->andReturn('93.184.216.34'); }); Http::fake([ 'https://free.freeipapi.com/api/json/*' => Http::response([], 500), ]); $fetchGeolocation = app(FetchGeolocation::class); $result = $fetchGeolocation->fetch('example.com'); $this->assertNull($result); } public function test_it_returns_null_on_exception(): void { $this->mock(ResolveRecord::class, function (MockInterface $mock) { $mock->shouldReceive('resolve')->andReturn('93.184.216.34'); }); Http::fake([ 'https://free.freeipapi.com/api/json/*' => function () { throw new \Exception('Network error'); }, ]); $fetchGeolocation = app(FetchGeolocation::class); $result = $fetchGeolocation->fetch('example.com'); $this->assertNull($result); } } ================================================ FILE: packages/uptime/tests/Unit/GenerateOutpostCertificateTest.php ================================================ delete([ 'certificates/root-ca.key', 'certificates/root-ca.crt', ]); } public function test_it_generates_root_ca_certificate(): void { $generator = new GenerateRootCertificate; $this->assertFalse($generator->exists()); $generator->generate(); $this->assertTrue($generator->exists()); // Verify the certificate is valid $cert = $generator->getRootCertificate(); $this->assertStringContainsString('BEGIN CERTIFICATE', $cert); // Verify the private key is valid $key = $generator->getRootPrivateKey(); $this->assertStringContainsString('BEGIN PRIVATE KEY', $key); } public function test_it_generates_outpost_certificate(): void { $rootGenerator = new GenerateRootCertificate; $rootGenerator->generate(); $outpostGenerator = new GenerateOutpostCertificate($rootGenerator); $certificate = $outpostGenerator->generate('test-outpost-192.168.1.1-8080', '192.168.1.1', 30); $this->assertArrayHasKey('certificate', $certificate); $this->assertArrayHasKey('private_key', $certificate); $this->assertArrayHasKey('root_certificate', $certificate); // Verify the certificate is valid $this->assertStringContainsString('BEGIN CERTIFICATE', $certificate['certificate']); $this->assertStringContainsString('BEGIN PRIVATE KEY', $certificate['private_key']); $this->assertStringContainsString('BEGIN CERTIFICATE', $certificate['root_certificate']); // Verify the certificate can be parsed $certResource = openssl_x509_read($certificate['certificate']); $this->assertNotFalse($certResource); $certData = openssl_x509_parse($certResource); $this->assertNotFalse($certData); $this->assertEquals('test-outpost-192.168.1.1-8080', $certData['subject']['CN']); } protected function tearDown(): void { // Clean up certificates after test Storage::disk('local')->delete([ 'certificates/root-ca.key', 'certificates/root-ca.crt', ]); parent::tearDown(); } } ================================================ FILE: packages/uptime/tests/Unit/OutpostAuthMiddlewareTest.php ================================================ 'valid-token']); $middleware = new OutpostAuthMiddleware; $request = Request::create('/test', 'GET'); $request->headers->set('X-Outpost-Token', 'valid-token'); $response = $middleware->handle($request, function ($req) { return response()->json(['success' => true]); }); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals(['success' => true], $response->getData(true)); } public function test_it_denies_request_with_invalid_token(): void { config(['uptime.outpost_token' => 'valid-token']); $middleware = new OutpostAuthMiddleware; $request = Request::create('/test', 'GET'); $request->headers->set('X-Outpost-Token', 'invalid-token'); $response = $middleware->handle($request, function ($req) { return response()->json(['success' => true]); }); $this->assertEquals(401, $response->getStatusCode()); $this->assertEquals(['message' => 'Unauthorized'], $response->getData(true)); } public function test_it_denies_request_without_token(): void { config(['uptime.outpost_token' => 'valid-token']); $middleware = new OutpostAuthMiddleware; $request = Request::create('/test', 'GET'); $response = $middleware->handle($request, function ($req) { return response()->json(['success' => true]); }); $this->assertEquals(401, $response->getStatusCode()); $this->assertEquals(['message' => 'Unauthorized'], $response->getData(true)); } } ================================================ FILE: packages/uptime/tests/Unit/RegisterOutpostTest.php ================================================ Http::response([ 'countryCode' => 'US', 'latitude' => 40.7128, 'longitude' => -74.0060, ]), ]); $registerOutpost = app(RegisterOutpost::class); $outpost = $registerOutpost->register('1.2.3.4', '192.168.1.1', 8080); $this->assertInstanceOf(Outpost::class, $outpost); $this->assertEquals('1.2.3.4', $outpost->external_ip); $this->assertEquals('192.168.1.1', $outpost->ip); $this->assertEquals(8080, $outpost->port); $this->assertEquals('US', $outpost->country); $this->assertEquals(40.7128, $outpost->latitude); $this->assertEquals(-74.0060, $outpost->longitude); $this->assertEquals(OutpostStatus::Available, $outpost->status); } public function test_it_updates_existing_outpost_with_country(): void { $existingOutpost = Outpost::query()->create([ 'ip' => '192.168.1.1', 'port' => 8080, 'external_ip' => '1.2.3.4', 'status' => OutpostStatus::Unavailable, 'country' => 'US', 'latitude' => 40.7128, 'longitude' => -74.0060, 'last_available_at' => now()->subHour(), ]); Http::fake(); $registerOutpost = app(RegisterOutpost::class); $outpost = $registerOutpost->register('1.2.3.5', '192.168.1.1', 8080); $this->assertEquals($existingOutpost->id, $outpost->id); $this->assertEquals('1.2.3.5', $outpost->external_ip); $this->assertEquals(OutpostStatus::Available, $outpost->status); $this->assertEquals('US', $outpost->country); // Should not have made an HTTP request since country already exists Http::assertNothingSent(); } public function test_it_fetches_geolocation_for_existing_outpost_without_country(): void { $existingOutpost = Outpost::query()->create([ 'ip' => '192.168.1.1', 'port' => 8080, 'external_ip' => '1.2.3.4', 'status' => OutpostStatus::Unavailable, 'country' => null, 'last_available_at' => now()->subHour(), ]); Http::fake([ 'https://free.freeipapi.com/api/json/*' => Http::response([ 'countryCode' => 'UK', 'latitude' => 51.5074, 'longitude' => -0.1278, ]), ]); $registerOutpost = app(RegisterOutpost::class); $outpost = $registerOutpost->register('1.2.3.5', '192.168.1.1', 8080); $this->assertEquals($existingOutpost->id, $outpost->id); $this->assertEquals('UK', $outpost->country); $this->assertEquals(51.5074, $outpost->latitude); $this->assertEquals(-0.1278, $outpost->longitude); Http::assertSent(function ($request) { return str_contains($request->url(), 'free.freeipapi.com'); }); } public function test_it_handles_geolocation_fetch_failure_gracefully(): void { Http::fake([ 'https://free.freeipapi.com/api/json/*' => Http::response([], 500), ]); $registerOutpost = app(RegisterOutpost::class); $outpost = $registerOutpost->register('1.2.3.4', '192.168.1.1', 8080); $this->assertInstanceOf(Outpost::class, $outpost); $this->assertEquals('1.2.3.4', $outpost->external_ip); $this->assertNull($outpost->country); $this->assertNull($outpost->latitude); $this->assertNull($outpost->longitude); $this->assertEquals(OutpostStatus::Available, $outpost->status); } public function test_it_registers_outpost_with_manual_location_when_geoip_disabled(): void { Http::fake(); $registerOutpost = app(RegisterOutpost::class); $outpost = $registerOutpost->register( externalIp: '5.6.7.8', ip: '10.0.0.1', port: 9000, geoipAutomatic: false, country: 'ca', latitude: 45.1234, longitude: -75.9876, ); $this->assertInstanceOf(Outpost::class, $outpost); $this->assertEquals('5.6.7.8', $outpost->external_ip); $this->assertEquals('10.0.0.1', $outpost->ip); $this->assertEquals(9000, $outpost->port); $this->assertEquals('CA', $outpost->country); $this->assertEquals(45.1234, $outpost->latitude); $this->assertEquals(-75.9876, $outpost->longitude); $this->assertEquals(OutpostStatus::Available, $outpost->status); $this->assertFalse((bool) $outpost->geoip_automatic); Http::assertNothingSent(); } public function test_it_updates_existing_outpost_with_manual_location_when_geoip_disabled(): void { $existingOutpost = Outpost::query()->create([ 'ip' => '172.16.0.1', 'port' => 7070, 'external_ip' => '2.2.2.2', 'status' => OutpostStatus::Unavailable, 'country' => 'US', 'latitude' => 10.0, 'longitude' => 20.0, 'geoip_automatic' => true, 'last_available_at' => now()->subDay(), ]); Http::fake(); $registerOutpost = app(RegisterOutpost::class); $outpost = $registerOutpost->register( externalIp: '9.9.9.9', ip: '172.16.0.1', port: 7070, geoipAutomatic: false, country: 'br', latitude: -23.5505, longitude: -46.6333, ); $this->assertEquals($existingOutpost->id, $outpost->id); $this->assertEquals('9.9.9.9', $outpost->external_ip); $this->assertEquals('BR', $outpost->country); $this->assertEquals(-23.5505, $outpost->latitude); $this->assertEquals(-46.6333, $outpost->longitude); $this->assertEquals(OutpostStatus::Available, $outpost->status); $this->assertFalse((bool) $outpost->geoip_automatic); Http::assertNothingSent(); } } ================================================ FILE: packages/users/.gitignore ================================================ vendor composer.lock .phpunit.result.cache ================================================ FILE: packages/users/composer.json ================================================ { "name": "vigilant/users", "description": "Vigilant Users", "type": "package", "license": "AGPL", "authors": [ { "name": "Vincent Boon", "email": "info@vincentbean.com", "role": "Developer" } ], "require": { "php": "^8.3", "laravel/framework": "^12.0", "laravel/jetstream": "^5.0", "laravel/sanctum": "^v4.0" }, "require-dev": { "laravel/pint": "^1.6", "larastan/larastan": "^3.0", "orchestra/testbench": "^10.0", "phpstan/phpstan-mockery": "^2.0", "phpunit/phpunit": "^11.0", "vigilant/core": "@dev" }, "autoload": { "psr-4": { "Vigilant\\Users\\": "src" } }, "autoload-dev": { "psr-4": { "Vigilant\\Users\\Tests\\": "tests", "Vigilant\\Users\\Database\\Factories\\": "database/factories" } }, "scripts": { "test": "phpunit", "analyse": "phpstan", "style": "pint --test", "quality": [ "@test", "@analyse" ] }, "config": { "sort-packages": true, "allow-plugins": { "php-http/discovery": true } }, "extra": { "laravel": { "providers": [ "Vigilant\\Users\\ServiceProvider" ] } }, "minimum-stability": "dev", "prefer-stable": true, "repositories": [ { "type": "path", "url": "../*" } ] } ================================================ FILE: packages/users/config/users.php ================================================ 'default', ]; ================================================ FILE: packages/users/database/factories/TeamFactory.php ================================================ */ class TeamFactory extends Factory { protected $model = Team::class; /** * Define the model's default state. * * @return array */ public function definition(): array { return [ 'name' => $this->faker->unique()->company(), 'user_id' => 1, 'personal_team' => true, ]; } } ================================================ FILE: packages/users/database/factories/UserFactory.php ================================================ */ class UserFactory extends Factory { protected $model = User::class; /** * Define the model's default state. * * @return array */ public function definition(): array { return [ 'name' => $this->faker->name(), 'email' => $this->faker->unique()->safeEmail(), 'email_verified_at' => now(), 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password 'two_factor_secret' => null, 'two_factor_recovery_codes' => null, 'remember_token' => Str::random(10), 'profile_photo_path' => null, 'current_team_id' => null, ]; } /** * Indicate that the model's email address should be unverified. */ public function unverified(): static { return $this->state(function (array $attributes) { return [ 'email_verified_at' => null, ]; }); } /** * Indicate that the user should have a personal team. */ public function withPersonalTeam(?callable $callback = null): static { if (! Features::hasTeamFeatures()) { return $this->state([]); } return $this->has( Team::factory() ->state(fn (array $attributes, User $user) => [ 'name' => $user->name.'\'s Team', 'user_id' => $user->id, 'personal_team' => true, ]) ->when(is_callable($callback), $callback), 'ownedTeams' ); } } ================================================ FILE: packages/users/database/migrations/2014_10_12_000000_create_users_table.php ================================================ id(); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->rememberToken(); $table->foreignId('current_team_id')->nullable(); $table->string('profile_photo_path', 2048)->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('users'); } }; ================================================ FILE: packages/users/database/migrations/2014_10_12_100000_create_password_reset_tokens_table.php ================================================ string('email')->primary(); $table->string('token'); $table->timestamp('created_at')->nullable(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('password_reset_tokens'); } }; ================================================ FILE: packages/users/database/migrations/2014_10_12_200000_add_two_factor_columns_to_users_table.php ================================================ text('two_factor_secret') ->after('password') ->nullable(); $table->text('two_factor_recovery_codes') ->after('two_factor_secret') ->nullable(); if (Fortify::confirmsTwoFactorAuthentication()) { $table->timestamp('two_factor_confirmed_at') ->after('two_factor_recovery_codes') ->nullable(); } }); } /** * Reverse the migrations. */ public function down(): void { Schema::table('users', function (Blueprint $table) { $table->dropColumn(array_merge([ 'two_factor_secret', 'two_factor_recovery_codes', ], Fortify::confirmsTwoFactorAuthentication() ? [ 'two_factor_confirmed_at', ] : [])); }); } }; ================================================ FILE: packages/users/database/migrations/2020_05_21_100000_create_teams_table.php ================================================ id(); $table->foreignId('user_id')->index(); $table->string('name'); $table->boolean('personal_team'); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('teams'); } }; ================================================ FILE: packages/users/database/migrations/2020_05_21_200000_create_team_user_table.php ================================================ id(); $table->foreignId('team_id'); $table->foreignId('user_id'); $table->string('role')->nullable(); $table->timestamps(); $table->unique(['team_id', 'user_id']); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('team_user'); } }; ================================================ FILE: packages/users/database/migrations/2020_05_21_300000_create_team_invitations_table.php ================================================ id(); $table->foreignId('team_id')->constrained()->cascadeOnDelete(); $table->string('email'); $table->string('role')->nullable(); $table->timestamps(); $table->unique(['team_id', 'email']); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('team_invitations'); } }; ================================================ FILE: packages/users/database/migrations/2024_05_18_100000_team_timezone_field.php ================================================ string('timezone')->after('personal_team')->default('UTC'); }); } public function down(): void { Schema::dropColumns('teams', ['timezone']); } }; ================================================ FILE: packages/users/phpstan.neon ================================================ includes: - ./vendor/larastan/larastan/extension.neon - ./vendor/phpstan/phpstan-mockery/extension.neon parameters: paths: - src - tests level: 8 ignoreErrors: - identifier: missingType.iterableValue - identifier: missingType.generics ================================================ FILE: packages/users/phpunit.xml ================================================ ./tests/* ./src ================================================ FILE: packages/users/routes/auth.php ================================================ name('login.socialite'); Route::get('authenticate/callback/{provider}', [SocialiteController::class, 'callback'])->name('login.socialite.callback'); ================================================ FILE: packages/users/routes/web.php ================================================ user(); abort_if($user->hasVerifiedEmail(), 401, 'E-mail already verified'); /** @var view-string $view */ $view = 'auth.verify-email'; return view($view); })->middleware('auth')->name('verification.notice'); Route::get('/email/verify/{id}/{hash}', function (EmailVerificationRequest $request) { $request->fulfill(); return redirect()->route('onboard'); })->middleware(['auth', 'signed'])->name('verification.verify'); Route::post('/email/verification-notification', function (Request $request) { $request->user()->sendEmailVerificationNotification(); return back()->with('message', 'Verification link sent!'); })->middleware(['auth', 'throttle:6,1'])->name('verification.send'); ================================================ FILE: packages/users/src/Actions/Fortify/CreateNewUser.php ================================================ $input */ public function create(array $input, array $optional = []): User { $rules = [ 'name' => ['required', 'string', 'max:255'], 'email' => ['required', 'string', 'email', 'max:255', 'unique:users', new RegistrationEnabledValidator], 'password' => $this->passwordRules(), 'terms' => Jetstream::hasTermsAndPrivacyPolicyFeature() ? ['accepted', 'required'] : '', ]; if ($optional !== []) { foreach ($optional as $key) { unset($rules[$key]); } } Validator::make($input, $rules)->validate(); return DB::transaction(function () use ($input) { return tap(User::create([ 'name' => $input['name'], 'email' => $input['email'], 'password' => Hash::make($input['password']), ]), function (User $user) { $this->createTeam($user); }); }); } /** * Create a personal team for the user. */ protected function createTeam(User $user): void { $user->ownedTeams()->save(Team::forceCreate([ 'user_id' => $user->id, 'name' => explode(' ', $user->name, 2)[0]."'s Team", 'personal_team' => true, ])); } } ================================================ FILE: packages/users/src/Actions/Fortify/PasswordValidationRules.php ================================================ */ protected function passwordRules(): array { return ['required', 'string', Password::default(), 'confirmed']; } } ================================================ FILE: packages/users/src/Actions/Fortify/ResetUserPassword.php ================================================ $input */ public function reset(User $user, array $input): void { Validator::make($input, [ 'password' => $this->passwordRules(), ])->validate(); $user->forceFill([ 'password' => Hash::make($input['password']), ])->save(); } } ================================================ FILE: packages/users/src/Actions/Fortify/UpdateUserPassword.php ================================================ $input */ public function update(User $user, array $input): void { Validator::make($input, [ 'current_password' => ['required', 'string', 'current_password:web'], 'password' => $this->passwordRules(), ], [ 'current_password.current_password' => __('The provided password does not match your current password.'), ])->validateWithBag('updatePassword'); $user->forceFill([ 'password' => Hash::make($input['password']), ])->save(); } } ================================================ FILE: packages/users/src/Actions/Fortify/UpdateUserProfileInformation.php ================================================ $input */ public function update(User $user, array $input): void { Validator::make($input, [ 'name' => ['required', 'string', 'max:255'], 'email' => ['required', 'email', 'max:255', Rule::unique('users')->ignore($user->id)], 'photo' => ['nullable', 'mimes:jpg,jpeg,png', 'max:1024'], ])->validateWithBag('updateProfileInformation'); if (isset($input['photo'])) { $user->updateProfilePhoto($input['photo']); } if ($input['email'] !== $user->email && $user instanceof MustVerifyEmail) { // @phpstan-ignore-line $this->updateVerifiedUser($user, $input); } else { $user->forceFill([ 'name' => $input['name'], 'email' => $input['email'], ])->save(); } } /** * Update the given verified user's profile information. * * @param array $input */ protected function updateVerifiedUser(User $user, array $input): void { $user->forceFill([ 'name' => $input['name'], 'email' => $input['email'], 'email_verified_at' => null, ])->save(); $user->sendEmailVerificationNotification(); } } ================================================ FILE: packages/users/src/Actions/Jetstream/AddTeamMember.php ================================================ authorize('addTeamMember', $team); $this->validate($team, $email, $role); $newTeamMember = Jetstream::findUserByEmailOrFail($email); AddingTeamMember::dispatch($team, $newTeamMember); $team->users()->attach( $newTeamMember, ['role' => $role] ); TeamMemberAdded::dispatch($team, $newTeamMember); } /** * Validate the add member operation. */ protected function validate(Team $team, string $email, ?string $role): void { Validator::make([ 'email' => $email, 'role' => $role, ], $this->rules(), [ 'email.exists' => __('We were unable to find a registered user with this email address.'), ])->after( $this->ensureUserIsNotAlreadyOnTeam($team, $email) )->validateWithBag('addTeamMember'); } /** * Get the validation rules for adding a team member. * * @return array */ protected function rules(): array { return array_filter([ 'email' => ['required', 'email', 'exists:users'], 'role' => Jetstream::hasRoles() ? ['required', 'string', new Role] : null, ]); } /** * Ensure that the user is not already on the team. */ protected function ensureUserIsNotAlreadyOnTeam(Team $team, string $email): Closure { return function ($validator) use ($team, $email) { $validator->errors()->addIf( $team->hasUserWithEmail($email), 'email', __('This user already belongs to the team.') ); }; } } ================================================ FILE: packages/users/src/Actions/Jetstream/CreateTeam.php ================================================ $input */ public function create(User $user, array $input): Team { Gate::forUser($user)->authorize('create', Jetstream::newTeamModel()); Validator::make($input, [ 'name' => ['required', 'string', 'max:255'], ])->validateWithBag('createTeam'); AddingTeam::dispatch($user); $user->switchTeam($team = $user->ownedTeams()->create([ 'name' => $input['name'], 'personal_team' => false, ])); /** @var Team $team */ return $team; } } ================================================ FILE: packages/users/src/Actions/Jetstream/DeleteTeam.php ================================================ purge(); } } ================================================ FILE: packages/users/src/Actions/Jetstream/DeleteUser.php ================================================ deletesTeams = $deletesTeams; } /** * Delete the given user. */ public function delete(User $user): void { DB::transaction(function () use ($user) { $this->deleteTeams($user); $user->deleteProfilePhoto(); $user->tokens->each->delete(); $user->delete(); }); } /** * Delete the teams and team associations attached to the user. */ protected function deleteTeams(User $user): void { $user->teams()->detach(); $user->ownedTeams->each(function (Team $team): void { // @phpstan-ignore-line $this->deletesTeams->delete($team); }); } } ================================================ FILE: packages/users/src/Actions/Jetstream/InviteTeamMember.php ================================================ authorize('addTeamMember', $team); $this->validate($team, $email, $role); InvitingTeamMember::dispatch($team, $email, $role); /** @var \Laravel\Jetstream\TeamInvitation $invitation */ $invitation = $team->teamInvitations()->create([ 'email' => $email, 'role' => $role, ]); Mail::to($email)->send(new TeamInvitation($invitation)); } /** * Validate the invite member operation. */ protected function validate(Team $team, string $email, ?string $role): void { Validator::make([ 'email' => $email, 'role' => $role, ], $this->rules($team), [ 'email.unique' => __('This user has already been invited to the team.'), ])->after( $this->ensureUserIsNotAlreadyOnTeam($team, $email) )->validateWithBag('addTeamMember'); } /** * Get the validation rules for inviting a team member. * * @return array */ protected function rules(Team $team): array { return array_filter([ 'email' => [ 'required', 'email', Rule::unique('team_invitations')->where(function (Builder $query) use ($team) { $query->where('team_id', $team->id); }), ], 'role' => Jetstream::hasRoles() ? ['required', 'string', new Role] : null, ]); } /** * Ensure that the user is not already on the team. */ protected function ensureUserIsNotAlreadyOnTeam(Team $team, string $email): Closure { return function ($validator) use ($team, $email) { $validator->errors()->addIf( $team->hasUserWithEmail($email), 'email', __('This user already belongs to the team.') ); }; } } ================================================ FILE: packages/users/src/Actions/Jetstream/RemoveTeamMember.php ================================================ authorize($user, $team, $teamMember); $this->ensureUserDoesNotOwnTeam($teamMember, $team); $team->removeUser($teamMember); // @phpstan-ignore-line - Jetstream docblock TeamMemberRemoved::dispatch($team, $teamMember); } /** * Authorize that the user can remove the team member. */ protected function authorize(User $user, Team $team, User $teamMember): void { if (! Gate::forUser($user)->check('removeTeamMember', $team) && $user->id !== $teamMember->id) { throw new AuthorizationException; } } /** * Ensure that the currently authenticated user does not own the team. */ protected function ensureUserDoesNotOwnTeam(User $teamMember, Team $team): void { if ($teamMember->id === $team->owner?->id) { throw ValidationException::withMessages([ 'team' => [__('You may not leave a team that you created.')], ])->errorBag('removeTeamMember'); } } } ================================================ FILE: packages/users/src/Actions/Jetstream/UpdateTeamName.php ================================================ $input */ public function update(User $user, Team $team, array $input): void { Gate::forUser($user)->authorize('update', $team); Validator::make($input, [ 'name' => ['required', 'string', 'max:255'], 'timezone' => ['required', 'string', 'max:255', 'timezone:all'], ])->validateWithBag('updateTeamName'); $team->forceFill([ 'name' => $input['name'], 'timezone' => $input['timezone'], ])->save(); } } ================================================ FILE: packages/users/src/Http/Controllers/SocialiteController.php ================================================ redirect(); // @phpstan-ignore-line } public function callback(string $provider, CreateNewUser $creator): RedirectResponse { abort_if(! in_array($provider, ['google']), 404); $socialiteUser = Socialite::driver($provider)->user(); // @phpstan-ignore-line $user = User::query() ->where('email', '=', $socialiteUser->getEmail()) ->first(); if ($user === null) { $user = $creator->create([ 'name' => $socialiteUser->getName(), 'email' => $socialiteUser->getEmail(), 'password' => str()->random(32), ], ['terms', 'password']); } Auth::login($user); return response()->redirectToRoute('sites'); } } ================================================ FILE: packages/users/src/Http/Middleware/EnsureEmailIsVerified.php ================================================ user() === null) { return $next($request); } if ($request->user() instanceof MustVerifyEmail && ! $request->user()->hasVerifiedEmail()) { if ($request->expectsJson()) { abort(403, 'Your email address is not verified.'); } else { return Redirect::guest(URL::route($redirectToRoute ?: 'verification.notice')); } } return $next($request); } } ================================================ FILE: packages/users/src/Http/Middleware/NoUserMiddleware.php ================================================ routeIs('register') || ($request->isMethod('POST') && str_ends_with($request->url(), 'register')); if ($isRegisterRoute || auth()->check()) { return $next($request); } $userCount = User::query()->count(); if ($userCount === 0) { return redirect()->route('register'); } return $next($request); } } ================================================ FILE: packages/users/src/Models/Membership.php ================================================ */ protected $casts = [ 'personal_team' => 'boolean', ]; protected $fillable = [ 'name', 'personal_team', ]; /** * The event map for the model. * * @var array */ protected $dispatchesEvents = [ 'created' => TeamCreated::class, 'updated' => TeamUpdated::class, 'deleted' => TeamDeleted::class, ]; protected static function newFactory(): TeamFactory { return TeamFactory::new(); } } ================================================ FILE: packages/users/src/Models/TeamInvitation.php ================================================ */ protected $fillable = [ 'email', 'role', ]; /** * Get the team that the invitation belongs to. */ public function team(): BelongsTo { return $this->belongsTo(Team::class); } } ================================================ FILE: packages/users/src/Models/User.php ================================================ */ protected $casts = [ 'email_verified_at' => 'datetime', ]; protected $appends = [ 'profile_photo_url', ]; public function sendEmailVerificationNotification(): void { if (ce()) { $this->markEmailAsVerified(); return; } $this->notify(new VerifyEmail); } protected static function newFactory(): UserFactory { return UserFactory::new(); } } ================================================ FILE: packages/users/src/Notifications/VerifyEmail.php ================================================ team_id = $teamService->team()?->id; } } ================================================ FILE: packages/users/src/Policies/TeamPolicy.php ================================================ belongsToTeam($team); } /** * Determine whether the user can create models. */ public function create(User $user): bool { return true; } /** * Determine whether the user can update the model. */ public function update(User $user, Team $team): bool { return $user->ownsTeam($team); } /** * Determine whether the user can add team members. */ public function addTeamMember(User $user, Team $team): bool { return $user->ownsTeam($team); } /** * Determine whether the user can update team member permissions. */ public function updateTeamMember(User $user, Team $team): bool { return $user->ownsTeam($team); } /** * Determine whether the user can remove team members. */ public function removeTeamMember(User $user, Team $team): bool { return $user->ownsTeam($team); } /** * Determine whether the user can delete the model. */ public function delete(User $user, Team $team): bool { return $user->ownsTeam($team); } } ================================================ FILE: packages/users/src/ServiceProvider.php ================================================ registerConfig(); } protected function registerConfig(): static { $this->mergeConfigFrom(__DIR__.'/../config/users.php', 'users'); return $this; } public function boot(): void { $this ->bootServices() ->bootRoutes() ->bootConfig() ->bootMigrations() ->bootCommands() ->bootPolicies(); } protected function bootServices(): static { app()->singleton(TeamService::class); return $this; } protected function bootRoutes(): static { if (! $this->app->routesAreCached()) { Route::middleware(['web', 'auth']) ->group(fn () => $this->loadRoutesFrom(__DIR__.'/../routes/web.php')); Route::middleware(['web']) ->group(fn () => $this->loadRoutesFrom(__DIR__.'/../routes/auth.php')); } return $this; } protected function bootConfig(): static { $this->publishes([ __DIR__.'/../config/users.php' => config_path('users.php'), ], 'config'); return $this; } protected function bootMigrations(): static { $this->loadMigrationsFrom(__DIR__.'/../database/migrations'); return $this; } protected function bootCommands(): static { if ($this->app->runningInConsole()) { $this->commands([ ]); } return $this; } protected function bootPolicies(): static { if (ce()) { Gate::policy(Team::class, TeamPolicy::class); } return $this; } } ================================================ FILE: packages/users/src/Validators/RegistrationEnabledValidator.php ================================================ count(); if ($userCount > 0) { $fail(__('Registration disabled, ask your administrator to create new accounts')); } } } ================================================ FILE: packages/users/testbench.yaml ================================================ providers: - Vigilant\Users\ServiceProvider ================================================ FILE: packages/users/tests/TestCase.php ================================================ set('database.default', 'testbench'); $app['config']->set('database.connections.testbench', [ 'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '', ]); } } ================================================ FILE: phpunit.xml ================================================ tests/Unit tests/Feature app ================================================ FILE: postcss.config.js ================================================ export default { plugins: { '@tailwindcss/postcss': {}, }, }; ================================================ FILE: public/.htaccess ================================================ Options -MultiViews -Indexes RewriteEngine On # Handle Authorization Header RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} (.+)/$ RewriteRule ^ %1 [L,R=301] # Send Requests To Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] ================================================ FILE: public/index.php ================================================ make(Kernel::class); $response = $kernel->handle( $request = Request::capture() )->send(); $kernel->terminate($request, $response); ================================================ FILE: public/robots.txt ================================================ User-agent: * Disallow: ================================================ FILE: public/site.webmanifest ================================================ {"name":"","short_name":"","icons":[{"src":"/android-chrome-192x192.png","sizes":"192x192","type":"image/png"},{"src":"/android-chrome-512x512.png","sizes":"512x512","type":"image/png"}],"theme_color":"#ffffff","background_color":"#ffffff","display":"standalone"} ================================================ FILE: resources/css/app.css ================================================ @import './tailwind.sources.css'; @import 'tailwindcss'; @plugin '@tailwindcss/forms'; @plugin '@tailwindcss/typography'; @custom-variant dark (&:is(.dark, .dark *)); @theme { /* Base Colors (Grayscale) */ --color-base-black: #0A0A0F; --color-base-950: #131318; --color-base-900: #1A1A24; --color-base-850: #232333; --color-base-800: #2D2D42; --color-base-700: #444459; --color-base-600: #5C5C75; --color-base-500: #7A7A94; --color-base-400: #A8A8C0; --color-base-300: #C8C8DC; --color-base-200: #D8D8E8; --color-base-150: #E8E8F4; --color-base-100: #F4F4FA; --color-base-50: #FAFAFF; --color-base-paper: #FAFAFF; /* Accent Colors - Red (Primary CTA) */ --color-red: #EF4444; --color-red-light: #F87171; --color-red-dark: #DC2626; /* Accent Colors - Orange (Secondary CTA) */ --color-orange: #F97316; --color-orange-light: #FB923C; --color-orange-dark: #EA580C; /* Accent Colors - Yellow (Warning) */ --color-yellow: #F59E0B; --color-yellow-light: #FBBF24; --color-yellow-dark: #D97706; /* Accent Colors - Green (Success) */ --color-green: #10B981; --color-green-light: #34D399; --color-green-dark: #059669; /* Accent Colors - Cyan */ --color-cyan: #06B6D4; --color-cyan-light: #22D3EE; --color-cyan-dark: #0891B2; /* Accent Colors - Blue */ --color-blue: #3B82F6; --color-blue-light: #60A5FA; --color-blue-dark: #2563EB; /* Accent Colors - Indigo */ --color-indigo: #6366F1; --color-indigo-light: #818CF8; --color-indigo-dark: #4F46E5; /* Accent Colors - Purple */ --color-purple: #8B5CF6; --color-purple-light: #A78BFA; --color-purple-dark: #7C3AED; /* Accent Colors - Magenta */ --color-magenta: #EC4899; --color-magenta-light: #F472B6; --color-magenta-dark: #DB2777; --font-sans: Figtree, ui-sans-serif, system-ui, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; } /* The default border color has changed to `currentcolor` in Tailwind CSS v4, so we've added these compatibility styles to make sure everything still looks the same as it did with Tailwind CSS v3. If we ever want to remove these styles, we need to add an explicit border color utility to any element that depends on these defaults. */ @layer base { *, ::after, ::before, ::backdrop, ::file-selector-button { border-color: var(--color-gray-200, currentcolor); } /* Ensure all buttons have pointer cursor on hover unless disabled */ button:not(:disabled), [type="button"]:not(:disabled), [type="submit"]:not(:disabled), [type="reset"]:not(:disabled) { cursor: pointer; } button:disabled, [type="button"]:disabled, [type="submit"]:disabled, [type="reset"]:disabled { cursor: not-allowed; } /* Vertical gradient animation */ @keyframes gradient-y { 0%, 100% { background-position: 0% 0%; } 50% { background-position: 0% 100%; } } .animate-gradient-y { background-size: 100% 200%; animation: gradient-y 6s ease infinite; } /* Horizontal gradient shift animation for CTA buttons */ @keyframes gradient-shift { 0%, 100% { background-position: 0% 50%; } 50% { background-position: 100% 50%; } } .animate-gradient-shift { animation: gradient-shift 3s ease infinite; } /* Background size for animated gradients */ .bg-300\% { background-size: 300% 300%; } /* Pulse glow animation for decorative elements */ @keyframes pulse-glow { 0%, 100% { opacity: 0.3; transform: scale(1); } 50% { opacity: 0.5; transform: scale(1.05); } } .animate-pulse-glow { animation: pulse-glow 4s ease-in-out infinite; } /* Float animation for decorative elements */ @keyframes float { 0%, 100% { transform: translateY(0px); } 50% { transform: translateY(-10px); } } .animate-float { animation: float 6s ease-in-out infinite; } /* Bell swing animation for notification bell */ @keyframes bell-swing { 0%, 100% { transform: rotate(0deg); transform-origin: top center; } 10%, 30%, 50%, 70%, 90% { transform: rotate(8deg); transform-origin: top center; } 20%, 40%, 60%, 80% { transform: rotate(-8deg); transform-origin: top center; } } .animate-bell-swing { animation: bell-swing 0.8s ease-in-out; } /* Bell swing on hover */ .notification-bell:hover svg { animation: bell-swing 0.8s ease-in-out; } /* Fade in up animation for initial page load */ @keyframes fadeInUp { from { opacity: 0; transform: translateY(1rem); } to { opacity: 1; transform: translateY(0); } } } [x-cloak] { display: none; } .tooltip { @apply invisible absolute; } .has-tooltip { @apply relative; } .has-tooltip:hover .tooltip { @apply visible z-50; } .tooltip-left { @apply right-full mr-2 top-1/2 transform -translate-y-1/2 whitespace-nowrap; } button:disabled { @apply cursor-not-allowed; } .font-header { font-family: "Audiowide", sans-serif; font-weight: 400; font-style: normal; } .font-text { font-family: "Noto Sans", sans-serif; font-optical-sizing: auto; font-weight: 400; font-style: normal; font-variation-settings: "wdth" 100; } select:not([multiple]) option { @apply bg-gray-950; } /* Safelist for dynamic color classes used in modal headers and other components */ @layer utilities { .bg-red\/10 { background-color: rgb(239 68 68 / 0.1); } .bg-blue\/10 { background-color: rgb(59 130 246 / 0.1); } .bg-green\/10 { background-color: rgb(16 185 129 / 0.1); } .bg-yellow\/10 { background-color: rgb(245 158 11 / 0.1); } .bg-purple\/10 { background-color: rgb(139 92 246 / 0.1); } .border-red\/30 { border-color: rgb(239 68 68 / 0.3); } .border-blue\/30 { border-color: rgb(59 130 246 / 0.3); } .border-green\/30 { border-color: rgb(16 185 129 / 0.3); } .border-yellow\/30 { border-color: rgb(245 158 11 / 0.3); } .border-purple\/30 { border-color: rgb(139 92 246 / 0.3); } .text-red { color: rgb(239 68 68); } .text-blue { color: rgb(59 130 246); } .text-green { color: rgb(16 185 129); } .text-yellow { color: rgb(245 158 11); } .text-purple { color: rgb(139 92 246); } } ================================================ FILE: resources/css/tailwind.sources.css ================================================ /* * This file is auto-generated by scripts/generate-tailwind-sources.mjs. * Do not edit this file manually. */ @source '../../packages/certificates/resources/views/**/*.blade.php'; @source '../../packages/crawler/resources/views/**/*.blade.php'; @source '../../packages/cve/resources/views/**/*.blade.php'; @source '../../packages/dns/resources/views/**/*.blade.php'; @source '../../packages/frontend/resources/views/**/*.blade.php'; @source '../../packages/healthchecks/resources/views/**/*.blade.php'; @source '../../packages/lighthouse/resources/views/**/*.blade.php'; @source '../../packages/notifications/resources/views/**/*.blade.php'; @source '../../packages/onboarding/resources/views/**/*.blade.php'; @source '../../packages/settings/resources/views/**/*.blade.php'; @source '../../packages/sites/resources/views/**/*.blade.php'; @source '../../packages/uptime/resources/views/**/*.blade.php'; @source '../../vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php'; @source '../../vendor/laravel/jetstream/**/*.blade.php'; @source '../../vendor/ramonrietdijk/livewire-tables/resources/**/*.blade.php'; @source '../views/**/*.blade.php'; ================================================ FILE: resources/js/app.js ================================================ import './bootstrap'; import Chart from 'chart.js/auto'; Chart.defaults.color = 'rgb(209, 213, 219)'; window.Chart = Chart; // Translate Livewire navigate events to Alpine-compatible state document.addEventListener('livewire:navigate', () => { window.dispatchEvent(new CustomEvent('navigation-start')); }); document.addEventListener('livewire:navigated', () => { window.dispatchEvent(new CustomEvent('navigation-end')); }); ================================================ FILE: resources/js/bootstrap.js ================================================ /** * We'll load the axios HTTP library which allows us to easily issue requests * to our Laravel back-end. This library automatically handles sending the * CSRF token as a header based on the value of the "XSRF" token cookie. */ import axios from 'axios'; window.axios = axios; window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; /** * Echo exposes an expressive API for subscribing to channels and listening * for events that are broadcast by Laravel. Echo and event broadcasting * allows your team to easily build robust real-time web applications. */ // import Echo from 'laravel-echo'; // import Pusher from 'pusher-js'; // window.Pusher = Pusher; // window.Echo = new Echo({ // broadcaster: 'pusher', // key: import.meta.env.VITE_PUSHER_APP_KEY, // cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER ?? 'mt1', // wsHost: import.meta.env.VITE_PUSHER_HOST ? import.meta.env.VITE_PUSHER_HOST : `ws-${import.meta.env.VITE_PUSHER_APP_CLUSTER}.pusher.com`, // wsPort: import.meta.env.VITE_PUSHER_PORT ?? 80, // wssPort: import.meta.env.VITE_PUSHER_PORT ?? 443, // forceTLS: (import.meta.env.VITE_PUSHER_SCHEME ?? 'https') === 'https', // enabledTransports: ['ws', 'wss'], // }); ================================================ FILE: resources/lang/en/validation.php ================================================ [ 'settings.webhook_url' => 'webhook URL', 'settings.to' => 'email address', 'settings.server' => 'server', 'settings.topic' => 'topic', ], ]; ================================================ FILE: resources/markdown/policy.md ================================================ # Privacy Policy Edit this file to define the privacy policy for your application. ================================================ FILE: resources/markdown/terms.md ================================================ # Terms of Service Edit this file to define the terms of service for your application. ================================================ FILE: resources/navigation.php ================================================ icon('tni-area-chart-alt-o'); ================================================ FILE: resources/views/api/api-token-manager.blade.php ================================================
{{ __('Create API Token') }} {{ __('API tokens allow third-party services to authenticate with our application on your behalf.') }}
@if (Laravel\Jetstream\Jetstream::hasPermissions())
@foreach (Laravel\Jetstream\Jetstream::$permissions as $permission) @endforeach
@endif
{{ __('Created.') }} {{ __('Create') }}
@if ($this->user->tokens->isNotEmpty())
{{ __('Manage API Tokens') }} {{ __('You may delete any of your existing tokens if they are no longer needed.') }}
@foreach ($this->user->tokens->sortBy('name') as $token)
{{ $token->name }}
@if ($token->last_used_at)
{{ __('Last used') }} {{ $token->last_used_at->diffForHumans() }}
@endif @if (Laravel\Jetstream\Jetstream::hasPermissions()) @endif
@endforeach
@endif {{ __('API Token') }}
{{ __('Please copy your new API token. For your security, it won\'t be shown again.') }}
{{ __('Close') }}
{{ __('API Token Permissions') }}
@foreach (Laravel\Jetstream\Jetstream::$permissions as $permission) @endforeach
{{ __('Cancel') }} {{ __('Save') }}
{{ __('Delete API Token') }} {{ __('Are you sure you would like to delete this API token?') }} {{ __('Cancel') }} {{ __('Delete') }}
================================================ FILE: resources/views/api/index.blade.php ================================================

{{ __('API Tokens') }}

@livewire('api.api-token-manager')
================================================ FILE: resources/views/auth/confirm-password.blade.php ================================================
{{ __('This is a secure area of the application. Please confirm your password before continuing.') }}
@csrf
================================================ FILE: resources/views/auth/forgot-password.blade.php ================================================
{{ __('Forgot your password? No problem. Just let us know your email address and we will email you a password reset link that will allow you to choose a new one.') }}
@if (session('status'))
{{ session('status') }}
@endif
@csrf
================================================ FILE: resources/views/auth/login.blade.php ================================================ @if (session('status'))
{{ session('status') }}
@endif
@csrf
@if (Route::has('password.request')) {{ __('Forgot password?') }} @endif @if (!ce()) | {{ __('Create account') }} @endif
@if (config('services.google.enabled')) @endif
================================================ FILE: resources/views/auth/register.blade.php ================================================

{{ __('Create your account') }}

{{ __('Join us and start monitoring today') }}

@csrf
@if (Laravel\Jetstream\Jetstream::hasTermsAndPrivacyPolicyFeature())
{!! __('I agree to the :terms_of_service and :privacy_policy', [ 'terms_of_service' => '' . __('Terms of Service') . '' . '', 'privacy_policy' => '' . __('Privacy Policy') . '' . '', ]) !!}
@else @endif
@if (config('services.google.enabled')) @endif
================================================ FILE: resources/views/auth/reset-password.blade.php ================================================
@csrf
================================================ FILE: resources/views/auth/two-factor-challenge.blade.php ================================================
{{ __('Please confirm access to your account by entering the authentication code provided by your authenticator application.') }}
{{ __('Please confirm access to your account by entering one of your emergency recovery codes.') }}
@csrf
================================================ FILE: resources/views/auth/verify-email.blade.php ================================================
{{ __('Before continuing, could you verify your email address by clicking on the link we just emailed to you? If you didn\'t receive the email, we will gladly send you another.') }}
@if (session('status') == 'verification-link-sent')
{{ __('A new verification link has been sent to the email address you provided in your profile settings.') }}
@endif
@csrf
@csrf
================================================ FILE: resources/views/components/action-message.blade.php ================================================ @props(['on'])
merge(['class' => 'text-sm text-gray-600']) }}> {{ $slot->isEmpty() ? 'Saved.' : $slot }}
================================================ FILE: resources/views/components/action-section.blade.php ================================================
merge(['class' => 'md:grid md:grid-cols-3 md:gap-8']) }}> {{ $title }} {{ $description }}
{{ $content }}
================================================ FILE: resources/views/components/alert.blade.php ================================================
{{-- Same alerts as the components just rendered via a JS event --}}

@if (session('alert')) @php($type = session('alert-type')) @endif
================================================ FILE: resources/views/components/alerts/danger.blade.php ================================================

{{ $title }}

@if (!blank($message ?? ''))

{{ $message }}

@endif
{{ $slot }}
================================================ FILE: resources/views/components/alerts/info.blade.php ================================================

{{ $title }}

@if (!blank($message ?? ''))

{{ $message }}

@endif
{{ $slot }}
================================================ FILE: resources/views/components/alerts/success.blade.php ================================================

{{ $title }}

@if (!blank($message ?? ''))

{{ $message }}

@endif
{{ $slot }}
================================================ FILE: resources/views/components/alerts/warning.blade.php ================================================

{{ $title }}

@if (!blank($message ?? ''))

{{ $message }}

@endif
{{ $slot }}
================================================ FILE: resources/views/components/application-logo.blade.php ================================================ ================================================ FILE: resources/views/components/application-mark.blade.php ================================================ ================================================ FILE: resources/views/components/authentication-card-logo.blade.php ================================================ ================================================ FILE: resources/views/components/authentication-card.blade.php ================================================
{{ $logo }}
{{ $slot }}
================================================ FILE: resources/views/components/banner.blade.php ================================================ @props(['style' => session('flash.bannerStyle', 'success'), 'message' => session('flash.banner')]) ================================================ FILE: resources/views/components/button.blade.php ================================================ ================================================ FILE: resources/views/components/card.blade.php ================================================ @props(['padding' => true])
merge(['class' => 'border border-base-700 shadow-xl rounded-xl overflow-hidden backdrop-blur-sm relative ' . ($padding ? 'px-6 py-8 sm:p-8' : '')]) }}>
{{ $slot }}
================================================ FILE: resources/views/components/checkbox.blade.php ================================================ merge(['class' => 'rounded-sm bg-base-800 border-base-700 text-red focus:ring-red focus:ring-offset-base-900']) !!}> ================================================ FILE: resources/views/components/confirmation-modal.blade.php ================================================ @props(['id' => null, 'maxWidth' => null])

{{ $title }}

{{ $content }}
{{ $footer }}
================================================ FILE: resources/views/components/confirms-password.blade.php ================================================ @props(['title' => __('Confirm Password'), 'content' => __('For your security, please confirm your password to continue.'), 'button' => __('Confirm')]) @php $confirmableId = md5($attributes->wire('then')); @endphp wire('then') }} x-data x-ref="span" x-on:click="$wire.startConfirmingPassword('{{ $confirmableId }}')" x-on:password-confirmed.window="setTimeout(() => $event.detail.id === '{{ $confirmableId }}' && $refs.span.dispatchEvent(new CustomEvent('then', { bubbles: false })), 250);" > {{ $slot }} @once {{ $title }} {{ $content }}
{{ __('Cancel') }} {{ $button }}
@endonce ================================================ FILE: resources/views/components/create-button-dropdown.blade.php ================================================ @props(['model']) @can('create', $model)
  • merge(['class' => 'cursor-pointer text-base-100 text-sm font-medium p-3 transition-all hover:bg-gradient-to-r hover:from-red/20 hover:to-orange/20 rounded-lg']) }} wire:navigate.hover>
    {{ $slot }}
  • @else
  • merge(['class' => 'cursor-not-allowed text-base-400 text-sm p-3 transition-all opacity-60'])->except(['href']) }} x-on:click="open = false; alert('@lang('Your current plan does not allow to create this resource')')">
    @svg('tni-x-circle-o', 'size-5 text-red') {{ $slot }}
  • @endcan ================================================ FILE: resources/views/components/create-button.blade.php ================================================ @props(['model']) @can('create', $model) merge(['class' => 'bg-gradient-to-r from-red via-orange to-red bg-[length:200%] bg-left hover:bg-right transition-[background-position] duration-300 border-transparent']) }} wire:navigate.hover> {{ $slot }} @else merge(['class' => 'bg-base-700/50 hover:bg-base-600/50 cursor-not-allowed has-tooltip opacity-60 border-base-600/50'])->except(['href']) }} disabled> @lang('Your current plan does not allow to create this resource') {{ $slot }} @endcan ================================================ FILE: resources/views/components/danger-button.blade.php ================================================ ================================================ FILE: resources/views/components/dialog-modal.blade.php ================================================ @props(['id' => null, 'maxWidth' => null])
    {{ $title }}
    {{ $content }}
    {{ $footer }}
    ================================================ FILE: resources/views/components/dropdown-link.blade.php ================================================ merge(['class' => 'block w-full px-4 py-2 text-start text-sm leading-5 text-base-100 hover:bg-red focus:outline-hidden focus:bg-base-800 transition duration-150 ease-in-out']) }}>{{ $slot }} ================================================ FILE: resources/views/components/dropdown.blade.php ================================================ @props(['align' => 'right', 'width' => '48', 'contentClasses' => 'py-1 bg-black', 'dropdownClasses' => '']) @php switch ($align) { case 'left': $alignmentClasses = 'ltr:origin-top-left rtl:origin-top-right start-0'; break; case 'top': $alignmentClasses = 'origin-top'; break; case 'none': case 'false': $alignmentClasses = ''; break; case 'right': default: $alignmentClasses = 'ltr:origin-top-right rtl:origin-top-left end-0'; break; } switch ($width) { case '48': $width = 'w-48'; break; } @endphp
    {{ $trigger }}
    ================================================ FILE: resources/views/components/form/button.blade.php ================================================ @php $tag = isset($href) ? 'a' : 'button'; // Define color variants based on classes $hasBlue = str_contains($attributes->get('class', ''), 'bg-blue'); $hasRed = str_contains($attributes->get('class', ''), 'bg-red'); $hasGradient = str_contains($attributes->get('class', ''), 'gradient'); // Default classes for neutral buttons (no color specified) $defaultClasses = 'bg-base-900/50 border-base-800/50 hover:bg-base-800/50 hover:border-base-700'; // Color-specific classes $blueClasses = 'bg-base-900/50 border-blue/50 text-blue hover:bg-blue/10 hover:border-blue hover:text-blue-light'; $redClasses = 'bg-red/10 border-red/50 text-red hover:bg-red/20 hover:border-red hover:text-red-light'; $gradientClasses = 'border-transparent'; // Determine which classes to use $colorClasses = $defaultClasses; if ($hasBlue) { $colorClasses = $blueClasses; } elseif ($hasRed) { $colorClasses = $redClasses; } elseif ($hasGradient) { $colorClasses = $gradientClasses; } @endphp <{{ $tag }} {{ $attributes->merge(['class' => "inline-flex items-center justify-center gap-2 rounded-lg px-4 py-2.5 text-sm font-semibold text-base-100 border transition-all duration-300 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-red cursor-pointer {$colorClasses}"]) }}> {{ $slot }} ================================================ FILE: resources/views/components/form/checkbox.blade.php ================================================ @props(['field', 'name', 'placeholder', 'description' => ''])
    @if($description) {{ $description }} @endif
    @error($field) {{ $message }} @enderror
    ================================================ FILE: resources/views/components/form/dropdown-button.blade.php ================================================ @php $tag = $attributes->has('href') ? 'a' : 'button'; $typeAttr = $tag === 'button' ? 'type="button"' : ''; @endphp <{{ $tag }} {{ $attributes->merge(['class' => 'group flex items-center gap-3 w-full px-4 py-2.5 text-sm font-medium text-base-300 hover:text-base-100 hover:bg-base-900/50 transition-all duration-200 border-b border-base-800/30 last:border-b-0']) }} {!! $typeAttr !!}> {{ $slot }} ================================================ FILE: resources/views/components/form/header.blade.php ================================================
    merge(['class' => 'mb-8 pb-6 border-b border-base-700/50 relative']) }}>

    {{ $slot }}

    ================================================ FILE: resources/views/components/form/number.blade.php ================================================ @props(['field', 'name', 'placeholder' => null, 'description' => ''])
    @if($description) {{ $description }} @endif
    class(['flex-1 border-0 bg-transparent py-2.5 px-3 text-base-100 focus:ring-0 sm:text-sm sm:leading-6 placeholder:text-base-500']) }}>
    @error($field) {{ $message }} @enderror
    ================================================ FILE: resources/views/components/form/password.blade.php ================================================ @props(['field', 'name', 'placeholder', 'description' => ''])
    @if($description) {{ $description }} @endif
    @error($field) {{ $message }} @enderror
    ================================================ FILE: resources/views/components/form/select.blade.php ================================================ @props(['field', 'name' => '', 'placeholder', 'description' => '', 'inline' => false]) @if(!$inline && !blank($name))
    @if($description) {{ $description }} @endif
    @endif @error($field) {{ $message }} @enderror @if(!$inline && !blank($name))
    @endif ================================================ FILE: resources/views/components/form/submit-button.blade.php ================================================
    {{ $slot }}
    ================================================ FILE: resources/views/components/form/text-list.blade.php ================================================ @props(['field', 'items' => [], 'name' => '', 'placeholder', 'description' => '', 'live' => true])
    @if(!blank($name))
    @if($description) {{ $description }} @endif
    @endif
    @error($field) @lang($message) @enderror
    ================================================ FILE: resources/views/components/form/text.blade.php ================================================ @props(['field', 'name' => '', 'placeholder', 'description' => '', 'live' => true])
    @if(!blank($name))
    @if($description) {{ $description }} @endif
    @endif
    merge(['class' => 'flex-1 border-0 bg-transparent py-2.5 px-3 text-base-100 focus:ring-0 sm:text-sm sm:leading-6 disabled:bg-base-950 placeholder:text-base-500 [&:-webkit-autofill]:!text-base-100 [&:-webkit-autofill]:[-webkit-text-fill-color:rgb(var(--color-base-100))]']) }} placeholder="{{ $placeholder ?? '' }}">
    @error($field) {{ $message }} @enderror
    ================================================ FILE: resources/views/components/form/textarea.blade.php ================================================ @props(['field', 'name' => '', 'placeholder' => '', 'description' => '', 'rows' => 4, 'live' => true, 'xRef' => null])
    @if(!blank($name))
    @if($description) {{ $description }} @endif
    @endif
    @error($field) {{ $message }} @enderror
    ================================================ FILE: resources/views/components/form/time.blade.php ================================================ @props(['field', 'name', 'description' => '', 'step' => '300'])
    @if($description) {{ $description }} @endif
    merge(['class' => 'flex-1 border-0 bg-transparent py-2.5 px-3 text-base-100 focus:ring-0 sm:text-sm sm:leading-6 disabled:bg-base-950']) }}>
    @error($field) {{ $message }} @enderror
    ================================================ FILE: resources/views/components/form-section.blade.php ================================================ @props(['submit'])
    merge(['class' => 'md:grid md:grid-cols-3 md:gap-8']) }}> {{ $title }} {{ $description }}
    {{ $form }}
    @if (isset($actions))
    {{ $actions }}
    @endif
    ================================================ FILE: resources/views/components/input-error.blade.php ================================================ @props(['for']) @error($for)

    merge(['class' => 'text-sm text-red-600']) }}>{{ $message }}

    @enderror ================================================ FILE: resources/views/components/input.blade.php ================================================ @props(['disabled' => false])
    merge(['class' => 'flex-1 border-0 bg-transparent py-2.5 px-3 text-base-100 focus:ring-0 sm:text-sm sm:leading-6 placeholder:text-base-500']) !!}>
    ================================================ FILE: resources/views/components/label.blade.php ================================================ @props(['value']) ================================================ FILE: resources/views/components/layout/sidebar/menu.blade.php ================================================ ================================================ FILE: resources/views/components/layout/sidebar/mobile-menu.blade.php ================================================ ================================================ FILE: resources/views/components/layout/sidebar.blade.php ================================================
    ================================================ FILE: resources/views/components/layout/topbar.blade.php ================================================
    @if (Laravel\Jetstream\Jetstream::hasTeamFeatures() && Auth::user() !== null)
    @endif @lang('View notifications')
    ================================================ FILE: resources/views/components/layout/user-profile-dropdown.blade.php ================================================ ================================================ FILE: resources/views/components/modal.blade.php ================================================ @props(['id', 'maxWidth']) @php $id = $id ?? md5($attributes->wire('model')); $maxWidth = [ 'sm' => 'sm:max-w-sm', 'md' => 'sm:max-w-md', 'lg' => 'sm:max-w-lg', 'xl' => 'sm:max-w-xl', '2xl' => 'sm:max-w-2xl', ][$maxWidth ?? '2xl']; @endphp ================================================ FILE: resources/views/components/nav-link.blade.php ================================================ @props(['active']) @php $classes = ($active ?? false) ? 'inline-flex items-center px-1 pt-1 border-b-2 border-indigo text-sm font-medium leading-5 text-base-50 focus:outline-hidden focus:border-indigo-light transition duration-150 ease-in-out' : 'inline-flex items-center px-1 pt-1 border-b-2 border-transparent text-sm font-medium leading-5 text-base-400 hover:text-base-200 hover:border-base-700 focus:outline-hidden focus:text-base-200 focus:border-base-700 transition duration-150 ease-in-out'; @endphp merge(['class' => $classes]) }}> {{ $slot }} ================================================ FILE: resources/views/components/page-header.blade.php ================================================ @props(['title', 'back']) @section('title', $title)
    merge(['class' => 'relative mb-4 sm:mb-6']) }}>
    ================================================ FILE: resources/views/components/password-group.blade.php ================================================ @props([ 'passwordName' => 'password', 'passwordConfirmationName' => null, 'passwordId' => null, 'passwordConfirmationId' => null, 'passwordLabel' => null, 'passwordConfirmationLabel' => null, 'passwordPlaceholder' => '••••••••', 'passwordConfirmationPlaceholder' => null, 'passwordAutocomplete' => 'new-password', 'passwordConfirmationAutocomplete' => 'new-password', 'passwordModel' => null, 'passwordConfirmationModel' => null, ]) @php $passwordConfirmationName ??= $passwordName . '_confirmation'; $passwordId ??= $passwordName; $passwordConfirmationId ??= $passwordConfirmationName; $passwordLabel ??= __('Password'); $passwordConfirmationLabel ??= __('Confirm Password'); $passwordConfirmationPlaceholder ??= __('Confirm password'); @endphp
    class('space-y-6') }} x-data="{ showPasswordStrength: false, passwordStrength: 0, passwordValue: '', confirmationMatches: false, updateStrength(value) { this.passwordValue = value ?? ''; let strength = 0; if (this.passwordValue.length >= 8) strength++; if (/[a-z]/.test(this.passwordValue) && /[A-Z]/.test(this.passwordValue)) strength++; if (/\d/.test(this.passwordValue)) strength++; if (/[^a-zA-Z\d]/.test(this.passwordValue)) strength++; this.passwordStrength = strength; this.updateMatch(); }, updateMatch(value = null) { const confirmValue = value ?? (this.$refs.passwordConfirm?.value ?? ''); this.confirmationMatches = confirmValue.length > 0 && confirmValue === this.passwordValue; } }">

    {{ __('Enter a password') }} {{ __('Weak password') }} {{ __('Fair password') }} {{ __('Good password') }} {{ __('Strong password! 🎉') }}

    @error($passwordName)

    {{ $message }}

    @enderror
    @error($passwordConfirmationName)

    {{ $message }}

    @enderror
    ================================================ FILE: resources/views/components/responsive-nav-link.blade.php ================================================ @props(['active']) @php $classes = ($active ?? false) ? 'block w-full ps-3 pe-4 py-2 border-l-4 border-indigo text-start text-base font-medium text-indigo-light bg-base-900 focus:outline-hidden focus:text-indigo-light focus:bg-base-850 focus:border-indigo transition duration-150 ease-in-out' : 'block w-full ps-3 pe-4 py-2 border-l-4 border-transparent text-start text-base font-medium text-base-400 hover:text-base-200 hover:bg-base-900 hover:border-base-700 focus:outline-hidden focus:text-base-200 focus:bg-base-900 focus:border-base-700 transition duration-150 ease-in-out'; @endphp merge(['class' => $classes]) }}> {{ $slot }} ================================================ FILE: resources/views/components/secondary-button.blade.php ================================================ ================================================ FILE: resources/views/components/section-border.blade.php ================================================ ================================================ FILE: resources/views/components/section-title.blade.php ================================================

    {{ $title }}

    {{ $description }}

    {{ $aside ?? '' }}
    ================================================ FILE: resources/views/components/switchable-team.blade.php ================================================ @props(['team', 'component' => 'dropdown-link'])
    @method('PUT') @csrf
    @if (Auth::user()->isCurrentTeam($team)) @endif
    {{ $team->name }}
    ================================================ FILE: resources/views/components/validation-errors.blade.php ================================================ @if ($errors->any())
    merge(['class' => 'bg-red/10 border border-red/30 rounded-lg px-4 py-3']) }}>
    {{ __('Whoops! Something went wrong.') }}
      @foreach ($errors->all() as $error)
    • {{ $error }}
    • @endforeach
    @endif ================================================ FILE: resources/views/dashboard.blade.php ================================================ ================================================ FILE: resources/views/emails/team-invitation.blade.php ================================================ @component('mail::message') {{ __('You have been invited to join the :team team!', ['team' => $invitation->team->name]) }} @if (Laravel\Fortify\Features::enabled(Laravel\Fortify\Features::registration())) {{ __('If you do not have an account, you may create one by clicking the button below. After creating an account, you may click the invitation acceptance button in this email to accept the team invitation:') }} @component('mail::button', ['url' => route('register')]) {{ __('Create Account') }} @endcomponent {{ __('If you already have an account, you may accept this invitation by clicking the button below:') }} @else {{ __('You may accept this invitation by clicking the button below:') }} @endif @component('mail::button', ['url' => $acceptUrl]) {{ __('Accept Invitation') }} @endcomponent {{ __('If you did not expect to receive an invitation to this team, you may discard this email.') }} @endcomponent ================================================ FILE: resources/views/errors/401.blade.php ================================================ @extends('errors.layout') @section('title', __('Unauthorized')) @section('code', '401') @section('message', __($exception->getMessage() ?: 'Unauthorized')) ================================================ FILE: resources/views/errors/402.blade.php ================================================ @extends('errors.minimal') @section('title', __('Payment Required')) @section('code', '402') @section('message', __('Payment Required')) ================================================ FILE: resources/views/errors/403.blade.php ================================================ @extends('errors.layout') @section('title', __('Forbidden')) @section('code', '403') @section('message', __($exception->getMessage() ?: 'You do not have permission to access this resource')) ================================================ FILE: resources/views/errors/404.blade.php ================================================ @extends('errors.layout') @section('title', __('Not Found')) @section('code', '404') @section('message', __('Not Found')) ================================================ FILE: resources/views/errors/419.blade.php ================================================ @extends('errors.layout') @section('title', __('Page Expired')) @section('code', '419') @section('message', __('Page Expired')) ================================================ FILE: resources/views/errors/429.blade.php ================================================ @extends('errors.layout') @section('title', __('Too Many Requests')) @section('code', '429') @section('message', __('Too Many Requests')) ================================================ FILE: resources/views/errors/500.blade.php ================================================ @extends('errors.minimal') @section('title', __('Server Error')) @section('code', '500') @section('message', __('Something has gone wrong')) ================================================ FILE: resources/views/errors/503.blade.php ================================================ @extends('errors.minimal') @section('title', __('Service Unavailable')) @section('code', '503') @section('message', __('Vigilant is currently unavailable')) ================================================ FILE: resources/views/errors/layout.blade.php ================================================

    @yield('code')

    @yield('title')

    @yield('message')

    ================================================ FILE: resources/views/errors/minimal.blade.php ================================================ @yield('title') @vite(['resources/css/app.css'])

    @yield('code')

    @yield('title')

    @yield('message')

    ================================================ FILE: resources/views/layouts/app.blade.php ================================================ @yield('title', '') - Vigilant @vite(['resources/css/app.css', 'resources/js/app.js']) @livewireStyles @stack('head')
    @if (isset($header))
    {{ $header }}
    @endif
    {{ $slot }}
    @stack('modals') @stack('scripts') @livewireScripts @if (!ce()) @endif ================================================ FILE: resources/views/layouts/guest.blade.php ================================================ {{ config('app.name', 'Laravel') }} @vite(['resources/css/app.css', 'resources/js/app.js']) @livewireStyles
    {{ $slot }}
    @livewireScripts @if (!ce()) @endif ================================================ FILE: resources/views/policy.blade.php ================================================
    {!! $policy !!}
    ================================================ FILE: resources/views/profile/delete-user-form.blade.php ================================================ {{ __('Delete Account') }} {{ __('Permanently delete your account.') }}
    {{ __('Once your account is deleted, all of its resources and data will be permanently deleted. Before deleting your account, please download any data or information that you wish to retain.') }}
    {{ __('Delete Account') }}
    {{ __('Delete Account') }} {{ __('Are you sure you want to delete your account? Once your account is deleted, all of its resources and data will be permanently deleted. Please enter your password to confirm you would like to permanently delete your account.') }}
    {{ __('Cancel') }} {{ __('Delete Account') }}
    ================================================ FILE: resources/views/profile/logout-other-browser-sessions-form.blade.php ================================================ {{ __('Browser Sessions') }} {{ __('Manage and log out your active sessions on other browsers and devices.') }}
    {{ __('If necessary, you may log out of all of your other browser sessions across all of your devices. Some of your recent sessions are listed below; however, this list may not be exhaustive. If you feel your account has been compromised, you should also update your password.') }}
    @if (count($this->sessions) > 0)
    @foreach ($this->sessions as $session)
    @if ($session->agent->isDesktop()) @else @endif
    {{ $session->agent->platform() ? $session->agent->platform() : __('Unknown') }} - {{ $session->agent->browser() ? $session->agent->browser() : __('Unknown') }}
    {{ $session->ip_address }}, @if ($session->is_current_device) {{ __('This device') }} @else {{ __('Last active') }} {{ $session->last_active }} @endif
    @endforeach
    @endif
    {{ __('Log Out Other Browser Sessions') }} {{ __('Done.') }}
    {{ __('Log Out Other Browser Sessions') }} {{ __('Please enter your password to confirm you would like to log out of your other browser sessions across all of your devices.') }}
    {{ __('Cancel') }} {{ __('Log Out Other Browser Sessions') }}
    ================================================ FILE: resources/views/profile/two-factor-authentication-form.blade.php ================================================ {{ __('Two Factor Authentication') }} {{ __('Add additional security to your account using two factor authentication.') }}

    @if ($this->enabled) @if ($showingConfirmation) {{ __('Finish enabling two factor authentication.') }} @else {{ __('You have enabled two factor authentication.') }} @endif @else {{ __('You have not enabled two factor authentication.') }} @endif

    {{ __('When two factor authentication is enabled, you will be prompted for a secure, random token during authentication. You may retrieve this token from your phone\'s Google Authenticator application.') }}

    @if ($this->enabled) @if ($showingQrCode)

    @if ($showingConfirmation) {{ __('To finish enabling two factor authentication, scan the following QR code using your phone\'s authenticator application or enter the setup key and provide the generated OTP code.') }} @else {{ __('Two factor authentication is now enabled. Scan the following QR code using your phone\'s authenticator application or enter the setup key.') }} @endif

    {!! $this->user->twoFactorQrCodeSvg() !!}

    {{ __('Setup Key') }}: {{ decrypt($this->user->two_factor_secret) }}

    @if ($showingConfirmation)
    @endif @endif @if ($showingRecoveryCodes)

    {{ __('Store these recovery codes in a secure password manager. They can be used to recover access to your account if your two factor authentication device is lost.') }}

    @foreach (json_decode(decrypt($this->user->two_factor_recovery_codes), true) as $code)
    {{ $code }}
    @endforeach
    @endif @endif
    @if (! $this->enabled) {{ __('Enable') }} @else @if ($showingRecoveryCodes) {{ __('Regenerate Recovery Codes') }} @elseif ($showingConfirmation) {{ __('Confirm') }} @else {{ __('Show Recovery Codes') }} @endif @if ($showingConfirmation) {{ __('Cancel') }} @else {{ __('Disable') }} @endif @endif
    ================================================ FILE: resources/views/profile/update-password-form.blade.php ================================================ {{ __('Update Password') }} {{ __('Ensure your account is using a long, random password to stay secure.') }}
    {{ __('Saved.') }} {{ __('Save') }}
    ================================================ FILE: resources/views/profile/update-profile-information-form.blade.php ================================================
    @if (Laravel\Jetstream\Jetstream::managesProfilePhotos())
    {{ $this->user->name }}
    {{ __('Select A New Photo') }} @if ($this->user->profile_photo_path) {{ __('Remove Photo') }} @endif
    @endif {{--
    --}} {{-- --}} {{-- --}} {{-- --}} {{--
    --}}
    @if (Laravel\Fortify\Features::enabled(Laravel\Fortify\Features::emailVerification()) && ! $this->user->hasVerifiedEmail())

    {{ __('Your email address is unverified.') }}

    @if ($this->verificationLinkSent)

    {{ __('A new verification link has been sent to your email address.') }}

    @endif @endif
    {{ __('Saved.') }}
    ================================================ FILE: resources/views/teams/create-team-form.blade.php ================================================ {{ __('Team Details') }} {{ __('Create a new team to separate Vigilant\'s components') }}
    {{ $this->user->name }}
    {{ $this->user->email }}
    {{ __('Create') }}
    ================================================ FILE: resources/views/teams/create.blade.php ================================================
    @livewire('teams.create-team-form')
    ================================================ FILE: resources/views/teams/delete-team-form.blade.php ================================================ {{ __('Delete Team') }} {{ __('Permanently delete this team.') }}
    {{ __('Once a team is deleted, all of its resources and data will be permanently deleted. Before deleting this team, please download any data or information regarding this team that you wish to retain.') }}
    {{ __('This action is non-reverable, all data will be lost.') }}
    {{ __('Delete Team') }}
    {{ __('Delete Team') }} {{ __('Are you sure you want to delete this team? Once a team is deleted, all of its resources and data will be permanently deleted.') }} {{ __('Cancel') }} {{ __('Delete Team') }}
    ================================================ FILE: resources/views/teams/show.blade.php ================================================
    @livewire('teams.update-team-name-form', ['team' => $team]) @livewire('teams.team-member-manager', ['team' => $team]) @if (Gate::check('delete', $team) && ! $team->personal_team)
    @livewire('teams.delete-team-form', ['team' => $team])
    @endif
    ================================================ FILE: resources/views/teams/team-member-manager.blade.php ================================================
    @if (Gate::check('addTeamMember', $team))
    {{ __('Add Team Member') }} {{ __('Add a new team member to your team, allowing them to collaborate with you.') }}
    {{ __('Please provide the email address of the person you would like to add to this team.') }}
    @if (count($this->roles) > 0)
    @foreach ($this->roles as $index => $role) @endforeach
    @endif
    {{ __('Added.') }} {{ __('Add') }}
    @endif @if ($team->teamInvitations->isNotEmpty() && Gate::check('addTeamMember', $team))
    {{ __('Pending Team Invitations') }} {{ __('These people have been invited to your team and have been sent an invitation email. They may join the team by accepting the email invitation.') }}
    @foreach ($team->teamInvitations as $invitation)
    {{ $invitation->email }}
    @if (Gate::check('removeTeamMember', $team)) @endif
    @endforeach
    @endif @if ($team->users->isNotEmpty())
    {{ __('Team Members') }} {{ __('All of the people that are part of this team.') }}
    @foreach ($team->users->sortBy('name') as $user)
    {{ $user->name }}
    {{ $user->name }}
    @if (Gate::check('updateTeamMember', $team) && Laravel\Jetstream\Jetstream::hasRoles()) @elseif (Laravel\Jetstream\Jetstream::hasRoles())
    {{ Laravel\Jetstream\Jetstream::findRole($user->membership->role)->name }}
    @endif @if ($this->user->id === $user->id) @elseif (Gate::check('removeTeamMember', $team)) @endif
    @endforeach
    @endif {{ __('Manage Role') }}
    @foreach ($this->roles as $index => $role) @endforeach
    {{ __('Cancel') }} {{ __('Save') }}
    {{ __('Leave Team') }} {{ __('Are you sure you would like to leave this team?') }} {{ __('Cancel') }} {{ __('Leave') }} {{ __('Remove Team Member') }} {{ __('Are you sure you would like to remove this person from the team?') }} {{ __('Cancel') }} {{ __('Remove') }}
    ================================================ FILE: resources/views/teams/update-team-name-form.blade.php ================================================ {{ __('Team Information') }} {{ __('Update the team name and timezone') }}
    {{ $team->owner->name }}
    {{ $team->owner->email }}
    @foreach(DateTimeZone::listIdentifiers() as $timezone) @endforeach
    @if (Gate::check('update', $team)) {{ __('Saved.') }} {{ __('Save') }} @endif
    ================================================ FILE: resources/views/terms.blade.php ================================================
    {!! $terms !!}
    ================================================ FILE: resources/views/vendor/livewire-table/columns/buttons/copy.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/columns/content/action.blade.php ================================================ @php($actions = $this->resolveActions()->standalone(false)->canBeRun($model))
    @foreach($actions as $action) @if($action->isScript()) @else @endif @endforeach
    ================================================ FILE: resources/views/vendor/livewire-table/columns/content/boolean.blade.php ================================================
    @if($value === null)
    @elseif($value)
    @else
    @endif
    ================================================ FILE: resources/views/vendor/livewire-table/columns/content/default.blade.php ================================================
    @if($value === null) @elseif($column->isRaw()) {!! $value !!} @else {{ $value }} @endif
    ================================================ FILE: resources/views/vendor/livewire-table/columns/content/image.blade.php ================================================
    @if($value) {{ $column->label() }} @endif
    ================================================ FILE: resources/views/vendor/livewire-table/columns/footer/default.blade.php ================================================
    @if(($content = $column->getFooterContent()) !== null) {!! $content !!} @else   @endif
    ================================================ FILE: resources/views/vendor/livewire-table/columns/header/default.blade.php ================================================ @if($column->isSortable()) @else {{ $column->label() }} @endif ================================================ FILE: resources/views/vendor/livewire-table/columns/search/boolean.blade.php ================================================
    ================================================ FILE: resources/views/vendor/livewire-table/columns/search/date.blade.php ================================================
    ================================================ FILE: resources/views/vendor/livewire-table/columns/search/default.blade.php ================================================
    ================================================ FILE: resources/views/vendor/livewire-table/columns/search/select.blade.php ================================================
    @foreach($column->getOptions() as $key => $value) @if(is_array($value)) @foreach($value as $key2 => $value2) @endforeach @else @endif @endforeach
    ================================================ FILE: resources/views/vendor/livewire-table/components/button.blade.php ================================================ @props(['size' => 'md', 'active' => false, 'dot' => false]) ================================================ FILE: resources/views/vendor/livewire-table/components/dropdown/content.blade.php ================================================ {{ $slot }} ================================================ FILE: resources/views/vendor/livewire-table/components/dropdown/divider.blade.php ================================================
    class('divide-y-1 divide-solid divide-base-700') }}> {{ $slot }}
    ================================================ FILE: resources/views/vendor/livewire-table/components/dropdown/footer.blade.php ================================================

    class('px-4 py-2 text-sm transition-all duration-200 text-base-400') }}> {{ $slot }}

    ================================================ FILE: resources/views/vendor/livewire-table/components/dropdown/header.blade.php ================================================ @props(['label', 'icon', 'navigate' => null])
    {{ $slot }}
    ================================================ FILE: resources/views/vendor/livewire-table/components/dropdown/index.blade.php ================================================ @props(['body', 'current'])
    {{ $slot }}
    {{ $body }}
    ================================================ FILE: resources/views/vendor/livewire-table/components/dropdown/menu/index.blade.php ================================================ @if($slot->hasActualContent())
      class('py-1 transition') }}> {{ $slot }}
    @endif ================================================ FILE: resources/views/vendor/livewire-table/components/dropdown/menu/item.blade.php ================================================ @props(['label', 'icon' => null, 'navigate' => null, 'dot' => false])
  • ================================================ FILE: resources/views/vendor/livewire-table/components/dropdown/section.blade.php ================================================ @props(['section'])
    merge([ 'x-data' => Js::from(['section' => $section]), 'x-show' => 'current === section', ])->class([ 'flex flex-col', ]) }} > {{ $slot }}
    ================================================ FILE: resources/views/vendor/livewire-table/components/form/checkbox.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/components/form/group.blade.php ================================================ @props(['label'])
    ================================================ FILE: resources/views/vendor/livewire-table/components/form/input.blade.php ================================================ @props(['size' => 'md']) class([ 'w-full rounded-lg border transition-all duration-200', 'focus:outline-none focus:ring-2 focus:ring-red/50 focus:z-10', 'bg-base-800 hover:bg-base-700 active:bg-base-700', 'border-base-700 hover:border-base-600 focus:border-red', 'text-base-100 placeholder:text-base-400', 'px-3 py-2' => $size === 'md', 'px-2 py-1' => $size === 'sm', ]) }} /> ================================================ FILE: resources/views/vendor/livewire-table/components/form/select.blade.php ================================================ @props(['size' => 'md']) ================================================ FILE: resources/views/vendor/livewire-table/components/icon.blade.php ================================================ @props(['icon']) class('block') }}> @include('livewire-table::icons.'.$icon) ================================================ FILE: resources/views/vendor/livewire-table/components/notification/button.blade.php ================================================ @props(['variant' => 'info']) ================================================ FILE: resources/views/vendor/livewire-table/components/notification/index.blade.php ================================================ @props(['icon', 'label'])

    {{ $label }}

    {{ $slot }}
    ================================================ FILE: resources/views/vendor/livewire-table/components/table/index.blade.php ================================================ class('w-full relative') }}> {{ $slot }}
    ================================================ FILE: resources/views/vendor/livewire-table/components/table/message.blade.php ================================================

    class('px-3 py-20 text-center text-base-300 transition-all duration-200') }}> {{ $slot }}

    ================================================ FILE: resources/views/vendor/livewire-table/components/table/tbody.blade.php ================================================ {{ $slot }} ================================================ FILE: resources/views/vendor/livewire-table/components/table/td.blade.php ================================================ class('px-4 py-4 text-base-200 max-w-0') }}>{{ $slot }} ================================================ FILE: resources/views/vendor/livewire-table/components/table/tfoot.blade.php ================================================ class('bg-base-900 border-t border-base-700 sticky bottom-0 shadow-lg z-20 transition-all duration-200') }}> {{ $slot }} ================================================ FILE: resources/views/vendor/livewire-table/components/table/th.blade.php ================================================ class('px-4 py-2 text-left text-sm font-semibold text-base-100 uppercase tracking-wider transition-all duration-200') }}> {{ $slot }} ================================================ FILE: resources/views/vendor/livewire-table/components/table/thead.blade.php ================================================ class('bg-base-850 border-b-2 border-base-700 sticky top-0 shadow-lg z-20 transition-all duration-200') }}> {{ $slot }} ================================================ FILE: resources/views/vendor/livewire-table/components/table/tr.blade.php ================================================ {{ $slot }} ================================================ FILE: resources/views/vendor/livewire-table/filters/boolean.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/filters/date.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/filters/filter.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/filters/select.blade.php ================================================ @if($filter->isMultiple()) @foreach($filter->getOptions() as $key => $value) @if(is_array($value)) @foreach($value as $key2 => $value2) @endforeach @else @endif @endforeach @else @foreach($filter->getOptions() as $key => $value) @if(is_array($value)) @foreach($value as $key2 => $value2) @endforeach @else @endif @endforeach @endif ================================================ FILE: resources/views/vendor/livewire-table/icons/arrow-path.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/icons/backspace.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/icons/check-circle.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/icons/check.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/icons/chevron-down.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/icons/chevron-left.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/icons/chevron-right.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/icons/chevron-up-down.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/icons/chevron-up.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/icons/clipboard-document-check.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/icons/clipboard-document.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/icons/clock.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/icons/cog-6-tooth.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/icons/ellipsis-vertical.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/icons/eye.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/icons/funnel.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/icons/information-circle.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/icons/list-bullet.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/icons/magnifying-glass.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/icons/min.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/icons/play.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/icons/plus.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/icons/queue-list.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/icons/view-columns.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/icons/x-mark.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/livewire/livewire-table.blade.php ================================================
    deferLoading) wire:init="init" @endif @if(strlen($polling = $this->polling()) > 0) wire:poll.{{ $polling }} @endif >
    @include('livewire-table::toolbar.toolbar')
    @include('livewire-table::table.table')
    {{ $paginator->onEachSide(1)->links('livewire-table::pagination.pagination') }}
    ================================================ FILE: resources/views/vendor/livewire-table/pagination/pagination.blade.php ================================================ @php if (! isset($scrollTo)) { $scrollTo = 'body'; } $scrollIntoViewJsSnippet = ($scrollTo !== false) ? << @if($paginator->hasPages()) @endif
    ================================================ FILE: resources/views/vendor/livewire-table/table/table.blade.php ================================================ @php($columns = $this->resolveColumns()) @if($this->canSelect()) @endif @foreach($columns as $column) @continue(! in_array($column->code(), $this->columns)) {{ $column->renderHeader() }} @endforeach @if($this->canSearch()) @if($this->canSelect()) @endif @foreach($columns as $column) @continue(! in_array($column->code(), $this->columns)) @if($column->isSearchable()) {{ $column->renderSearch() }} @endif @endforeach @endif @if($this->deferLoading && ! $this->initialized) @for($i = 0; $i < $this->perPage(); $i++) @if($this->canSelect()) @endif @foreach($columns as $column) @continue(! in_array($column->code(), $this->columns))
    @endforeach
    @endfor @else @forelse($paginator->items() as $item) isReordering()) draggable="true" x-on:dragstart="e => e.dataTransfer.setData('key', item)" x-on:dragover.prevent="" x-on:drop="e => { $wire.call( 'reorderItem', e.dataTransfer.getData('key'), item, e.target.offsetHeight / 2 > e.offsetY ) }" @endif > @if($this->canSelect()) @endif @foreach($columns as $column) @continue(! in_array($column->code(), $this->columns)) true, 'select-none cursor-pointer' => $column->isClickable() || $this->isReordering(), ]) @if($column->isClickable() && ! $this->isReordering()) @if(($link = $this->link($item)) !== null) @if($this->useNavigate) x-on:click.prevent="Livewire.navigate(@js($link))" @else x-on:click.prevent="window.location.href = @js($link)" @endif @elseif($this->canSelect()) x-on:click="$refs.checkbox.click()" @endif @endif > @includeWhen($column->isCopyable(), 'livewire-table::columns.buttons.copy')
    {{ $column->render($item) }}
    @endforeach @empty @lang('No results') @endforelse @endif
    @if($this->canSelect()) @endif @foreach($columns as $column) @continue(! in_array($column->code(), $this->columns)) {{ $column->renderFooter() }} @endforeach
    ================================================ FILE: resources/views/vendor/livewire-table/toolbar/buttons/clear-search.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/toolbar/buttons/reordering.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/toolbar/dropdowns/actions.blade.php ================================================ @include('livewire-table::toolbar.dropdowns.sections.actions') ================================================ FILE: resources/views/vendor/livewire-table/toolbar/dropdowns/configuration.blade.php ================================================ @php($columns = $this->resolveColumns()) @php($filters = $this->resolveFilters()) @include('livewire-table::toolbar.dropdowns.sections.configuration') @includeWhen($columns->isNotEmpty(), 'livewire-table::toolbar.dropdowns.sections.columns') @includeWhen($filters->isNotEmpty(), 'livewire-table::toolbar.dropdowns.sections.filters') @includeWhen($this->hasSoftDeletes(), 'livewire-table::toolbar.dropdowns.sections.trashed') @include('livewire-table::toolbar.dropdowns.sections.results') @includeWhen(count($pollingOptions) > 0, 'livewire-table::toolbar.dropdowns.sections.polling') ================================================ FILE: resources/views/vendor/livewire-table/toolbar/dropdowns/sections/actions.blade.php ================================================ @php($actions = $this->resolveActions()) @php($standaloneActions = $actions->standalone()) @if($standaloneActions->isNotEmpty()) @foreach($standaloneActions as $standaloneAction) @if($standaloneAction->isScript()) @else @endif @endforeach @endif @php($bulkActions = $actions->bulk()) @if($bulkActions->isNotEmpty()) @foreach($bulkActions as $bulkAction) @if($bulkAction->isScript()) @else @endif @endforeach @endif ================================================ FILE: resources/views/vendor/livewire-table/toolbar/dropdowns/sections/columns.blade.php ================================================ @php($columns = $this->resolveColumns()) @foreach($columns as $column)
  • @endforeach
    @lang('Select the columns you want to see. Drag them to change order.')
    ================================================ FILE: resources/views/vendor/livewire-table/toolbar/dropdowns/sections/configuration.blade.php ================================================ @php($columns = $this->resolveColumns()) @php($filters = $this->resolveFilters()) @if($columns->isNotEmpty()) @endif @if($filters->isNotEmpty()) @endif @if($this->hasSoftDeletes()) @endif @if(count($pollingOptions) > 0) @endif ================================================ FILE: resources/views/vendor/livewire-table/toolbar/dropdowns/sections/filters.blade.php ================================================ @php($filters = $this->resolveFilters()) @if($this->canClearFilters()) @endif @foreach($filters as $filter)
    {{ $filter->render() }}
    @endforeach @lang('Enable filters to narrow down your results.')
    ================================================ FILE: resources/views/vendor/livewire-table/toolbar/dropdowns/sections/polling.blade.php ================================================ @foreach($pollingOptions as $key => $value) @endforeach @lang('Automatically refresh the table with the given interval.') ================================================ FILE: resources/views/vendor/livewire-table/toolbar/dropdowns/sections/results.blade.php ================================================ @foreach($perPageOptions as $perPage) @endforeach @lang('Change the amount of visible records in the table.') ================================================ FILE: resources/views/vendor/livewire-table/toolbar/dropdowns/sections/suggestions.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/toolbar/dropdowns/sections/trashed.blade.php ================================================ @lang('Configure what type of records should be shown in the table.') ================================================ FILE: resources/views/vendor/livewire-table/toolbar/dropdowns/suggestions.blade.php ================================================ @include('livewire-table::toolbar.dropdowns.sections.suggestions') ================================================ FILE: resources/views/vendor/livewire-table/toolbar/loader.blade.php ================================================
    ================================================ FILE: resources/views/vendor/livewire-table/toolbar/notification.blade.php ================================================
    @if($this->isReordering()) @else @endif
    ================================================ FILE: resources/views/vendor/livewire-table/toolbar/search.blade.php ================================================ ================================================ FILE: resources/views/vendor/livewire-table/toolbar/toolbar.blade.php ================================================ @php($actions = $this->resolveActions())
    @include('livewire-table::toolbar.loader') @includeWhen($this->canSearch(), 'livewire-table::toolbar.search') @includeWhen($this->canClearSearch(), 'livewire-table::toolbar.buttons.clear-search') @include('livewire-table::toolbar.notification')
    @includeWhen($this->useReordering, 'livewire-table::toolbar.buttons.reordering') @includeWhen($actions->isNotEmpty(), 'livewire-table::toolbar.dropdowns.actions') @include('livewire-table::toolbar.dropdowns.configuration')
    ================================================ FILE: resources/views/vendor/mail/html/button.blade.php ================================================ @props([ 'url', 'color' => 'primary', 'align' => 'center', ]) @php $baseStyle = 'display:inline-block;padding:14px 34px;font-weight:600;font-size:15px;text-decoration:none;border-radius:999px;letter-spacing:0.02em;text-transform:none;border:0;'; $palettes = [ 'primary' => 'color:#FAFAFF;background-color:#EF4444;background-image:linear-gradient(120deg,#EF4444 0%,#F97316 50%,#EF4444 100%);', 'success' => 'color:#FAFAFF;background-color:#10B981;background-image:linear-gradient(120deg,#10B981 0%,#34D399 100%);', 'error' => 'color:#FAFAFF;background-color:#DC2626;background-image:linear-gradient(120deg,#DC2626 0%,#EF4444 100%);', 'secondary' => 'color:#F4F4FA;background-color:transparent;border:1px solid #444459;', ]; $buttonStyle = $baseStyle . ($palettes[$color] ?? $palettes['primary']); @endphp ================================================ FILE: resources/views/vendor/mail/html/footer.blade.php ================================================ {{ Illuminate\Mail\Markdown::parse($slot) }} ================================================ FILE: resources/views/vendor/mail/html/header.blade.php ================================================ @props(['url']) ================================================ FILE: resources/views/vendor/mail/html/layout.blade.php ================================================ {{ config('app.name') }} ================================================ FILE: resources/views/vendor/mail/html/message.blade.php ================================================ {{-- Header --}} {{-- Body --}} {{ $slot }} {{-- Subcopy --}} @isset($subcopy) {{ $subcopy }} @endisset {{-- Footer --}}

    © {{ date('Y') }} {{ config('app.name') }}. {{ __('All rights reserved.') }}

    ================================================ FILE: resources/views/vendor/mail/html/panel.blade.php ================================================ ================================================ FILE: resources/views/vendor/mail/html/subcopy.blade.php ================================================ ================================================ FILE: resources/views/vendor/mail/html/table.blade.php ================================================
    {{ Illuminate\Mail\Markdown::parse($slot) }}
    ================================================ FILE: resources/views/vendor/mail/html/themes/default.css ================================================ /* Base */ body, body *:not(html):not(style):not(br):not(tr):not(code) { box-sizing: border-box; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol'; position: relative; } body { -webkit-text-size-adjust: none; background-color: #100F0F; color: #E6E4D9; height: 100%; line-height: 1.4; margin: 0; padding: 0; width: 100% !important; } p, ul, ol, blockquote { line-height: 1.4; text-align: left; } a { color: #3869d4; } a img { border: none; } /* Typography */ h1 { color: #FFFCF0; font-size: 18px; font-weight: bold; margin-top: 0; text-align: left; } h2 { font-size: 16px; font-weight: bold; margin-top: 0; text-align: left; } h3 { font-size: 14px; font-weight: bold; margin-top: 0; text-align: left; } p { font-size: 16px; line-height: 1.5em; margin-top: 0; text-align: left; } p.sub { font-size: 12px; } img { max-width: 100%; } /* Layout */ .wrapper { -premailer-cellpadding: 0; -premailer-cellspacing: 0; -premailer-width: 100%; background-color: #edf2f7; margin: 0; padding: 0; width: 100%; } .content { -premailer-cellpadding: 0; -premailer-cellspacing: 0; -premailer-width: 100%; margin: 0; padding: 0; width: 100%; background-color: #100F0F; } /* Header */ .header { padding: 25px 0; text-align: center; } .header a { color: #3d4852; font-size: 19px; font-weight: bold; text-decoration: none; } /* Logo */ .logo { height: 75px; max-height: 75px; width: 200px; } /* Body */ .body { -premailer-cellpadding: 0; -premailer-cellspacing: 0; -premailer-width: 100%; background-color: #100F0F; border-bottom: 1px solid #edf2f7; border-top: 1px solid #edf2f7; margin: 0; padding: 0; width: 100%; } .inner-body { -premailer-cellpadding: 0; -premailer-cellspacing: 0; -premailer-width: 570px; background-color: #ffffff; border-color: #e8e5ef; border-radius: 2px; border-width: 1px; box-shadow: 0 2px 0 rgba(0, 0, 150, 0.025), 2px 4px 0 rgba(0, 0, 150, 0.015); margin: 0 auto; padding: 0; width: 570px; } /* Subcopy */ .subcopy { border-top: 1px solid #e8e5ef; margin-top: 25px; padding-top: 25px; } .subcopy p { font-size: 14px; } /* Footer */ .footer { -premailer-cellpadding: 0; -premailer-cellspacing: 0; -premailer-width: 570px; margin: 0 auto; padding: 0; text-align: center; width: 570px; } .footer p { color: #b0adc5; font-size: 12px; text-align: center; } .footer a { color: #b0adc5; text-decoration: underline; } /* Tables */ .table table { -premailer-cellpadding: 0; -premailer-cellspacing: 0; -premailer-width: 100%; margin: 30px auto; width: 100%; } .table th { border-bottom: 1px solid #edeff2; margin: 0; padding-bottom: 8px; } .table td { color: #74787e; font-size: 15px; line-height: 18px; margin: 0; padding: 10px 0; } .content-cell { max-width: 100vw; padding: 32px; background-color: #282726; } /* Buttons */ .action { -premailer-cellpadding: 0; -premailer-cellspacing: 0; -premailer-width: 100%; margin: 30px auto; padding: 0; text-align: center; width: 100%; float: unset; } .button { -webkit-text-size-adjust: none; border-radius: 4px; color: #fff; display: inline-block; overflow: hidden; text-decoration: none; } .button-blue, .button-primary { background-color: #AF3029; border-bottom: 8px solid #AF3029; border-left: 18px solid #AF3029; border-right: 18px solid #AF3029; border-top: 8px solid #AF3029; } .button-green, .button-success { background-color: #48bb78; border-bottom: 8px solid #48bb78; border-left: 18px solid #48bb78; border-right: 18px solid #48bb78; border-top: 8px solid #48bb78; } .button-red, .button-error { background-color: #e53e3e; border-bottom: 8px solid #e53e3e; border-left: 18px solid #e53e3e; border-right: 18px solid #e53e3e; border-top: 8px solid #e53e3e; } /* Panels */ .panel { border-left: #2d3748 solid 4px; margin: 21px 0; } .panel-content { background-color: #282726; color: #E6E4D9; padding: 16px; } .panel-content p { color: #E6E4D9; } .panel-item { padding: 0; } .panel-item p:last-of-type { margin-bottom: 0; padding-bottom: 0; } /* Utilities */ .break-all { word-break: break-all; } ================================================ FILE: resources/views/vendor/mail/text/button.blade.php ================================================ {{ $slot }}: {{ $url }} ================================================ FILE: resources/views/vendor/mail/text/footer.blade.php ================================================ {{ $slot }} ================================================ FILE: resources/views/vendor/mail/text/header.blade.php ================================================ {{ $slot }}: {{ $url }} ================================================ FILE: resources/views/vendor/mail/text/layout.blade.php ================================================ {!! strip_tags($header ?? '') !!} {!! strip_tags($slot) !!} @isset($subcopy) {!! strip_tags($subcopy) !!} @endisset {!! strip_tags($footer ?? '') !!} ================================================ FILE: resources/views/vendor/mail/text/message.blade.php ================================================ {{-- Header --}} {{ config('app.name') }} {{-- Body --}} {{ $slot }} {{-- Subcopy --}} @isset($subcopy) {{ $subcopy }} @endisset {{-- Footer --}} © {{ date('Y') }} {{ config('app.name') }}. @lang('All rights reserved.') ================================================ FILE: resources/views/vendor/mail/text/panel.blade.php ================================================ {{ $slot }} ================================================ FILE: resources/views/vendor/mail/text/subcopy.blade.php ================================================ {{ $slot }} ================================================ FILE: resources/views/vendor/mail/text/table.blade.php ================================================ {{ $slot }} ================================================ FILE: routes/api.php ================================================ get('/user', function (Request $request) { return $request->user(); }); ================================================ FILE: routes/channels.php ================================================ id === (int) $id; }); ================================================ FILE: routes/console.php ================================================ comment(Inspiring::quote()); })->purpose('Display an inspiring quote'); ================================================ FILE: routes/web.php ================================================ group(function () { Route::get('/', fn () => response()->redirectToRoute('sites')); Route::fallback(fn () => abort(404)); }); ================================================ FILE: scripts/generate-tailwind-sources.mjs ================================================ import { promises as fs } from 'node:fs'; import path from 'node:path'; const projectRoot = path.resolve(process.cwd()); const cssDir = path.join(projectRoot, 'resources', 'css'); const packagesDir = path.join(projectRoot, 'packages'); const outputFile = path.join(cssDir, 'tailwind.sources.css'); const STATIC_SOURCES = [ "../views/**/*.blade.php", "../../vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php", "../../vendor/laravel/jetstream/resources/views/**/*.blade.php", "../../vendor/laravel/jetstream/stubs/livewire/resources/views/**/*.blade.php", "../../vendor/ramonrietdijk/livewire-tables/resources/views/**/*.blade.php", ]; const IGNORED_DIRS = new Set(['.', '..', 'vendor', 'node_modules']); async function directoryExists(targetPath) { try { const stat = await fs.stat(targetPath); return stat.isDirectory(); } catch { return false; } } async function collectPackageViewsSources() { const sources = []; if (!await directoryExists(packagesDir)) { return sources; } const entries = await fs.readdir(packagesDir, { withFileTypes: true }).catch(() => []); for (const entry of entries) { if (!entry.isDirectory() && !entry.isSymbolicLink()) continue; if (IGNORED_DIRS.has(entry.name) || entry.name.startsWith('.')) continue; const pkgPath = path.join(packagesDir, entry.name); // Check for direct views: packages/*/views const directViewsDir = path.join(pkgPath, 'views'); if (await directoryExists(directViewsDir)) { const relativePath = path.relative(cssDir, directViewsDir).replace(/\\/g, '/'); sources.push(`${relativePath}/**/*.blade.php`); } // Check for resources/views: packages/*/resources/views const resourcesViewsDir = path.join(pkgPath, 'resources', 'views'); if (await directoryExists(resourcesViewsDir)) { const relativePath = path.relative(cssDir, resourcesViewsDir).replace(/\\/g, '/'); sources.push(`${relativePath}/**/*.blade.php`); } // Check for nested packages: packages/saas/*/views const nestedPackagesDir = path.join(pkgPath, 'packages'); if (await directoryExists(nestedPackagesDir)) { const nestedEntries = await fs.readdir(nestedPackagesDir, { withFileTypes: true }).catch(() => []); for (const nestedEntry of nestedEntries) { if (!nestedEntry.isDirectory() && !nestedEntry.isSymbolicLink()) continue; if (IGNORED_DIRS.has(nestedEntry.name) || nestedEntry.name.startsWith('.')) continue; const nestedPkgPath = path.join(nestedPackagesDir, nestedEntry.name); // Check for direct views in nested package const nestedDirectViewsDir = path.join(nestedPkgPath, 'views'); if (await directoryExists(nestedDirectViewsDir)) { const relativePath = path.relative(cssDir, nestedDirectViewsDir).replace(/\\/g, '/'); sources.push(`${relativePath}/**/*.blade.php`); } // Check for resources/views in nested package const nestedResourcesViewsDir = path.join(nestedPkgPath, 'resources', 'views'); if (await directoryExists(nestedResourcesViewsDir)) { const relativePath = path.relative(cssDir, nestedResourcesViewsDir).replace(/\\/g, '/'); sources.push(`${relativePath}/**/*.blade.php`); } } } } return sources; } async function collectAllSources() { const dynamicSources = new Set(); const packageSources = await collectPackageViewsSources(); packageSources.forEach((source) => dynamicSources.add(source)); STATIC_SOURCES.forEach((source) => dynamicSources.add(source)); return Array.from(dynamicSources).sort((a, b) => a.localeCompare(b)); } function buildFileContent(sources) { const header = [ '/*', ' * This file is auto-generated by scripts/generate-tailwind-sources.mjs.', ' * Do not edit this file manually.', ' */', '', ].join('\n'); const lines = sources.map((pattern) => `@source '${pattern}';`); return `${header}${lines.join('\n')}\n`; } async function main() { const sources = await collectAllSources(); const fileContent = buildFileContent(sources); await fs.writeFile(outputFile, fileContent, 'utf8'); } main().catch((error) => { console.error('Failed to generate Tailwind sources:', error); process.exitCode = 1; }); ================================================ FILE: scripts/package-quality.sh ================================================ #!/bin/sh if [ -n "$1" ]; then dirs="./packages/$1" else dirs="./packages/*" fi for dir in $dirs do echo 'Checking ' $dir [ -f "$dir/composer.lock" ] && rm "$dir/composer.lock" composer install --working-dir=$dir --quiet || exit 1 composer quality --working-dir=$dir || exit 1 rm -rf "$dir/vendor" rm "$dir/composer.lock" done ================================================ FILE: storage/app/.gitignore ================================================ * !public/ !.gitignore ================================================ FILE: storage/framework/.gitignore ================================================ compiled.php config.php down events.scanned.php maintenance.php routes.php routes.scanned.php schedule-* services.json ================================================ FILE: storage/framework/cache/.gitignore ================================================ * !data/ !.gitignore ================================================ FILE: storage/framework/sessions/.gitignore ================================================ * !.gitignore ================================================ FILE: storage/framework/testing/.gitignore ================================================ * !.gitignore ================================================ FILE: storage/framework/views/.gitignore ================================================ * !.gitignore ================================================ FILE: storage/logs/.gitignore ================================================ * !.gitignore ================================================ FILE: tests/Browser/Notifications/ChannelsFormTest.php ================================================ browse(function (Browser $browser) { $browser->login() ->visit(route('notifications.channels')) ->click('@channel-add-button') ->assertSee('Choose the notification channel') // Help text of channel dropdown ->select('#form\.channel', NtfyChannel::class) ->pause(250) ->type('#settings\.server', 'https://ntfy.govigilant.io') ->type('#settings\.topic', 'topic') ->pause(1000) ->click('@submit-button') ->pause(250); /** @var ?Channel $channel */ $channel = Channel::query()->first(); $this->assertNotNull($channel); $this->assertEquals(NtfyChannel::class, $channel->channel); $this->assertEquals(['server' => 'https://ntfy.govigilant.io', 'topic' => 'topic'], $channel->settings); }); } } ================================================ FILE: tests/Browser/Notifications/ChannelsIndexTest.php ================================================ browse(function (Browser $browser) { $this->user(); Channel::query()->create([ 'channel' => NtfyChannel::class, 'settings' => [], ]); $browser->login() ->visit(route('notifications.channels')) ->assertSee('Ntfy'); }); } } ================================================ FILE: tests/Browser/Notifications/NotificationsFormTest.php ================================================ browse(function (Browser $browser) { $browser->login() ->visit(route('notifications')) ->click('@trigger-add-button') ->assertSee('Choose the event that triggers this notification') // Help text of the trigger dropdown ->type('#form\.name', 'Test Notification') ->select('#form\.notification', DowntimeStartNotification::class) ->check('#form\.all_channels') ->clickAndWaitForReload('@submit-button') ->assertPathContains('notifications/edit') ->assertSee('Site downtime detected'); }); } } ================================================ FILE: tests/Browser/Notifications/NotificationsIndexTest.php ================================================ browse(function (Browser $browser) { $this->user(); Trigger::query()->create([ 'enabled' => true, 'name' => 'Downtime', 'notification' => DowntimeStartNotification::class, 'conditions' => [], ]); $browser->login() ->visit(route('notifications')) ->waitForText(DowntimeStartNotification::$name, 5); }); } } ================================================ FILE: tests/Browser/Pages/HomePage.php ================================================ */ public function elements(): array { return [ '@element' => '#selector', ]; } } ================================================ FILE: tests/Browser/Pages/Page.php ================================================ */ public static function siteElements(): array { return [ '@element' => '#selector', ]; } } ================================================ FILE: tests/Browser/Sites/SitesFormTest.php ================================================ browse(function (Browser $browser) { $browser->login() ->visit(route('sites')) ->click('@site-add-button') ->assertSee('The URL of the site that you want to add.') // Help text of URL field ->click('@submit-button') ->waitForText('field is required') ->assertSee('field is required') ->type('#form\.url', 'invalid value') ->click('@submit-button') ->waitForText('must be a valid URL', 5) ->assertSee('must be a valid URL') ->type('#form\.url', 'https://govigilant.io') ->click('@submit-button') ->pause(250); /** @var ?Site $createdSite */ $createdSite = Site::query()->firstWhere('url', '=', 'https://govigilant.io'); $this->assertNotNull($createdSite); }); } #[Test] public function it_can_add_uptime_monitor_via_tab(): void { $this->browse(function (Browser $browser) { $this->user(); /** @var Site $site */ $site = Site::query()->create([ 'url' => 'https://govigilant.io', ]); $browser->login() ->visit(route('site.edit', ['site' => $site])) ->waitFor('@uptime-tab-enabled') ->check('@uptime-tab-enabled') ->waitForText('Friendly name for this monitor') ->click('@submit-button') ->pause(250) ->visit(route('uptime')) ->pause(250) ->assertSee('https://govigilant.io'); }); } } ================================================ FILE: tests/Browser/Sites/SitesIndexTest.php ================================================ browse(function (Browser $browser) { $this->user(); Site::query()->create([ 'team_id' => 1, 'url' => 'https://govigilant.io', ]); $browser->login() ->visit(route('sites')) ->assertSee('https://govigilant.io'); }); } } ================================================ FILE: tests/Browser/Uptime/UptimeFormTest.php ================================================ browse(function (Browser $browser) { $browser->login() ->visit(route('uptime')) ->click('@monitor-add-button') ->assertSee('Friendly name for this monitor') // Help text of name field ->type('#form\.name', 'Test Monitor') ->select('#form\.type', 'ping') ->pause(500) ->type('#form\.settings\.host', 'govigilant.io') ->type('#form\.settings\.port', 22) ->select('#form\.interval', '* * * * */2') ->type('#form\.retries', 5) ->type('#form\.timeout', 10) ->clickAndWaitForReload('@submit-button') ->assertUrlIs(route('uptime')) ->assertSee('Test Monitor'); }); } } ================================================ FILE: tests/Browser/Uptime/UptimeIndexTest.php ================================================ browse(function (Browser $browser) { $this->user(); Monitor::query()->create([ 'name' => 'Test Monitor', 'type' => Type::Http, 'settings' => [ 'host' => 'https://govigilant.io', ], 'interval' => '* * * * *', 'timeout' => 60, 'retries' => 3, ]); $browser->login() ->visit(route('uptime')) ->assertSee('Test Monitor'); }); } } ================================================ FILE: tests/Browser/console/.gitignore ================================================ * !.gitignore ================================================ FILE: tests/Browser/screenshots/.gitignore ================================================ * !.gitignore ================================================ FILE: tests/Browser/source/.gitignore ================================================ * !.gitignore ================================================ FILE: tests/CreatesApplication.php ================================================ make(Kernel::class)->bootstrap(); return $app; } } ================================================ FILE: tests/DuskTestCase.php ================================================ addArguments(collect([ $this->shouldStartMaximized() ? '--start-maximized' : '--window-size=1920,1080', ])->unless($this->hasHeadlessDisabled(), function (Collection $items) { return $items->merge([ '--disable-gpu', '--headless=new', ]); })->all()); return RemoteWebDriver::create( $_ENV['DUSK_DRIVER_URL'] ?? 'http://localhost:9515', DesiredCapabilities::chrome()->setCapability( ChromeOptions::CAPABILITY, $options ) ); } /** * Determine whether the Dusk command has disabled headless mode. */ protected function hasHeadlessDisabled(): bool { return isset($_SERVER['DUSK_HEADLESS_DISABLED']) || isset($_ENV['DUSK_HEADLESS_DISABLED']); } /** * Determine if the browser window should start maximized. */ protected function shouldStartMaximized(): bool { return isset($_SERVER['DUSK_START_MAXIMIZED']) || isset($_ENV['DUSK_START_MAXIMIZED']); } protected function user(): User { /** @var User $user */ $user = User::query()->firstOrCreate([ 'email' => 'tester@govigilant.io', ], [ 'name' => 'Tester', 'password' => bcrypt('password'), 'current_team_id' => 1, ]); if ($user->currentTeam === null) { /** @var CreateTeam $createTeam */ $createTeam = app(CreateTeam::class); $team = $createTeam->create($user, [ 'name' => 'Tester\'s Team', ]); $team->users()->attach($user); } Auth::login($user); return $user; } } ================================================ FILE: tests/Feature/.gitkeep ================================================ ================================================ FILE: tests/TestCase.php ================================================