From 21b247311a9f4bc5006efdc23f5daf99d6109065 Mon Sep 17 00:00:00 2001 From: Wouter van Wijk Date: Tue, 17 Nov 2026 15:10:33 +0100 Subject: [PATCH 1/9] Add a rule-based inspection summary (key findings) Co-Authored-By: Claude Opus 5.5 --- lib/services/derive/inspection_summary.dart | 343 ++++++++++++++++++++ test/derive/inspection_summary_test.dart | 173 ++++++++++ 2 files changed, 516 insertions(+) create mode 100644 lib/services/derive/inspection_summary.dart create mode 100644 test/derive/inspection_summary_test.dart diff --git a/lib/services/derive/inspection_summary.dart b/lib/services/derive/inspection_summary.dart new file mode 100644 index 0000000..eab900d --- /dev/null +++ b/lib/services/derive/inspection_summary.dart @@ -0,0 +1,343 @@ +import '../../models/app_tab.dart'; +import '../../models/inspection/observed.dart'; +import '../../models/inspection/page_inspection.dart'; +import '../../models/inspection/server_snapshot.dart'; +import '../../utils/site.dart'; +import '../detection/engine.dart'; +import '../sovereignty_service.dart'; +import 'block_page.dart'; +import 'cookies_view.dart'; +import 'detections_view.dart'; +import 'divergences.dart'; +import 'page_size.dart'; +import 'page_weight.dart'; +import 'probe_general.dart'; +import 'security_audit.dart'; + +/// Product thresholds (no external norm), in one place. +const kHeadersPoor = 50; +const kHeadersGood = 80; +const kWeightHeavy = 5 * 1024 * 1024; +const kWeightNotable = 2 * 1024 * 1024; +const kFrameShareNotable = 0.20; + +enum FindingSeverity { high, medium, low, info } + +class Finding { + final String id; + final FindingSeverity severity; + + /// One line, complete on its own. + final String title; + + /// [AppTab.tag] of the tab with the detail. + final String? tab; + + const Finding(this.id, this.severity, this.title, {this.tab}); + + Map toJson() => + {'id': id, 'severity': severity.name, 'title': title, 'tab': tab}; +} + +class SummaryInputs { + final PageInspection inspection; + final Observed general; + final Observed security; + final Observed cookies; + final DetectionsView detections; + final Observed sovereignty; + final BlockPage? blockPage; + final List divergences; + + const SummaryInputs({ + required this.inspection, + required this.general, + required this.security, + required this.cookies, + required this.detections, + required this.sovereignty, + required this.blockPage, + required this.divergences, + }); +} + +const List summaryFactKeys = [ + 'url', 'finalUrl', 'status', 'blocked', 'requests', 'thirdPartyHosts', + 'transferBytes', 'transferIsLowerBound', 'trackers', 'trackerNames', + 'consentTool', 'cookies', 'advertisingCookies', 'analyticsCookies', + 'securityHeadersPct', 'cspScore', 'certValidUntil', + 'sovereigntyScore', 'sovereigntyGrade', 'sovereigntyCoverage', +]; + +class InspectionSummary { + /// Sorted by severity, then rule order. + final List findings; + + /// Keys in [summaryFactKeys]; null = unknown. + final Map facts; + + const InspectionSummary(this.findings, this.facts); + + List get top => findings.take(5).toList(); + + Map toJson() => { + 'findings': [for (final f in findings) f.toJson()], + 'facts': facts, + }; +} + +T? _value(Observed o) => o is Present ? o.value : null; + +InspectionSummary deriveSummary(SummaryInputs i) { + final p = i.inspection; + final general = _value(i.general); + final status = general == null ? null : _value(general.status); + final security = _value(i.security); + final audit = security == null ? null : _value(security.audit); + final csp = security == null ? null : _value(security.csp); + final cert = security == null ? null : _value(security.certificate); + final cookies = _value(i.cookies); + final report = _value(i.sovereignty); + final server = _value(p.server); + final browser = _value(p.browser); + final resources = browser == null ? null : _value(browser.resources); + final blocked = i.blockPage != null; + + final finalUrl = status == null ? null : _value(status.finalUrl); + final pageUrl = finalUrl ?? browser?.url; + final pageHost = pageUrl?.host; + + final weight = blocked ? null : derivePageWeight(p); + final trackers = blocked + ? null + : (i.detections.detections.isNotEmpty || i.detections.complete + ? [ + for (final d in i.detections.detections) + if (d.category.isTracking && !d.hintOnly) d + ] + : null); + final consent = blocked + ? null + : i.detections.detections + .where((d) => d.category == DetectionCategory.consent) + .firstOrNull; + final thirdHosts = (resources == null || pageHost == null || blocked) + ? null + : { + for (final r in resources) + if (Uri.tryParse(r.url)?.host case final h? + when h.isNotEmpty && !sameSite(h, pageHost)) + h.toLowerCase() + }; + + final findings = [ + ..._blockPage(i.blockPage), + ..._invalidCertAccepted(server), + ..._noHttps(finalUrl ?? browser?.url), + ..._certExpired(cert), + ..._certHost(cert), + ..._preConsent(blocked, consent, trackers), + ..._trackers(blocked, trackers), + ..._adCookies(blocked, cookies), + ..._certExpiring(cert), + ..._securityHeaders(audit), + ..._pageWeight(weight), + ..._sovereignty(report), + ..._cspWeak(csp), + ..._divergences(i.divergences), + ..._thirdParties(thirdHosts), + ]; + // Dart's List.sort is not stable; sort by (severity, rule order). + final order = {for (var n = 0; n < findings.length; n++) findings[n]: n}; + findings.sort((a, b) { + final bySeverity = a.severity.index.compareTo(b.severity.index); + return bySeverity != 0 ? bySeverity : order[a]!.compareTo(order[b]!); + }); + + final facts = { + 'url': switch (p.target) { + UrlTarget(:final url) => url.toString(), + _ => null, + }, + 'finalUrl': pageUrl?.toString(), + 'status': status?.last.status, + 'blocked': blocked ? true : (browser != null ? false : null), + 'requests': blocked ? null : resources?.length, + 'thirdPartyHosts': thirdHosts?.length, + 'transferBytes': weight?.transfer, + 'transferIsLowerBound': + weight?.transfer == null ? null : weight!.transferLowerBound, + 'trackers': trackers?.length, + 'trackerNames': trackers == null ? null : [for (final d in trackers) d.name], + 'consentTool': consent?.name, + 'cookies': blocked ? null : cookies?.total, + 'advertisingCookies': blocked ? null : cookies?.advertisingCount, + 'analyticsCookies': blocked ? null : cookies?.analyticsCount, + 'securityHeadersPct': audit?.percentage, + 'cspScore': csp?.score, + 'certValidUntil': cert?.validUntil, + 'sovereigntyScore': report?.score, + 'sovereigntyGrade': report?.grade, + 'sovereigntyCoverage': + report == null ? null : (report.coverage * 100).round(), + }; + return InspectionSummary(findings, facts); +} + +List _blockPage(BlockPage? b) => b == null + ? const [] + : [ + Finding('block-page', FindingSeverity.high, + 'Not the site: ${b.detail}', + tab: AppTab.browser.tag) + ]; + +List _invalidCertAccepted(ServerSnapshot? s) => + s != null && s.acceptedInvalidCertificate + ? [ + Finding('invalid-cert-accepted', FindingSeverity.high, + 'Loaded with an untrusted certificate (accepted by the user)', + tab: AppTab.security.tag) + ] + : const []; + +List _noHttps(Uri? url) => url != null && url.scheme == 'http' + ? [ + Finding('no-https', FindingSeverity.high, + 'No HTTPS: the page is served over plain HTTP', + tab: AppTab.security.tag) + ] + : const []; + +List _certExpired(CertificateModel? c) => c != null && + c.validityExpired + ? [ + Finding('cert-expired', FindingSeverity.high, + 'Certificate expired (${c.validUntil})', + tab: AppTab.security.tag) + ] + : const []; + +List _certHost(CertificateModel? c) => c != null && !c.hostMatches + ? [ + Finding('cert-host', FindingSeverity.high, + 'Certificate does not match the host', + tab: AppTab.security.tag) + ] + : const []; + +bool _active(Detection d) => d.requests > 0 || d.cookies.isNotEmpty; + +List _preConsent( + bool blocked, Detection? consent, List? trackers) { + if (blocked || consent == null || trackers == null) return const []; + final n = trackers.where(_active).length; + if (n == 0) return const []; + return [ + Finding('pre-consent', FindingSeverity.high, + 'Tracking before consent: $n tracker(s) active while ${consent.name} is present', + tab: AppTab.privacy.tag) + ]; +} + +List _trackers(bool blocked, List? trackers) { + if (blocked || trackers == null || trackers.isEmpty) return const []; + final names = trackers.take(3).map((d) => d.name).join(', '); + final more = trackers.length > 3 ? ' (+${trackers.length - 3})' : ''; + final high = trackers.any((d) => d.category.tracking >= 4); + return [ + Finding('trackers', high ? FindingSeverity.high : FindingSeverity.medium, + '${trackers.length} tracker(s): $names$more', + tab: AppTab.privacy.tag) + ]; +} + +List _adCookies(bool blocked, CookiesModel? c) => + !blocked && c != null && c.advertisingCount > 0 + ? [ + Finding('ad-cookies', FindingSeverity.medium, + '${c.advertisingCount} advertising cookie(s) set without a consent choice', + tab: AppTab.cookies.tag) + ] + : const []; + +List _certExpiring(CertificateModel? c) => c != null && + !c.validityExpired && + (c.validityTone == CertTone.warn || c.validityTone == CertTone.bad) + ? [ + Finding('cert-expiring', FindingSeverity.medium, + 'Certificate: ${c.validityLabel}', + tab: AppTab.security.tag) + ] + : const []; + +List _securityHeaders(SecurityAudit? a) { + final pct = a?.percentage; + if (a == null || pct == null || pct >= kHeadersGood) return const []; + final missing = a.checks + .where((c) => c.applicable && !c.passing) + .map((c) => c.label) + .join(', '); + return [ + Finding('security-headers', + pct < kHeadersPoor ? FindingSeverity.medium : FindingSeverity.low, + 'Security headers: $pct% (missing: $missing)', + tab: AppTab.security.tag) + ]; +} + +List _pageWeight(PageWeight? w) { + final t = w?.transfer; + if (w == null || t == null || t <= kWeightNotable) return const []; + final frames = w.breakdown['thirdPartyFrames']?.transfer; + final share = frames == null ? 0.0 : frames / t; + final frameText = share >= kFrameShareNotable + ? ', ${(share * 100).round()}% in third-party iframes' + : ''; + return [ + Finding('page-weight', + t > kWeightHeavy ? FindingSeverity.medium : FindingSeverity.low, + 'Page weight ${formatDownloadSize(t, prefix: w.transferPrefix)}$frameText', + tab: AppTab.size.tag) + ]; +} + +List _sovereignty(SovereigntyReport? r) { + final grade = r?.grade; + if (r == null || grade == null || (grade != 'Poor' && grade != 'Fair')) { + return const []; + } + return [ + Finding('sovereignty', + grade == 'Poor' ? FindingSeverity.medium : FindingSeverity.low, + 'Sovereignty: ${r.score} ($grade), coverage ${(r.coverage * 100).round()}%', + tab: AppTab.sovereignty.tag) + ]; +} + +List _cspWeak(CspModel? csp) { + final s = csp?.score; + return s != null && s < 50 + ? [ + Finding('csp-weak', FindingSeverity.low, + 'Content-Security-Policy is weak (score $s)', + tab: AppTab.security.tag) + ] + : const []; +} + +List _divergences(List ds) => [ + for (final d in ds) + if (!d.lowSeverity) + Finding('divergence', FindingSeverity.low, d.message, + tab: AppTab.probe.tag) + ]; + +List _thirdParties(Set? hosts) => + hosts == null || hosts.isEmpty + ? const [] + : [ + Finding('third-parties', FindingSeverity.info, + '${hosts.length} third-party host(s) contacted', + tab: AppTab.timeline.tag) + ]; diff --git a/test/derive/inspection_summary_test.dart b/test/derive/inspection_summary_test.dart new file mode 100644 index 0000000..8989d96 --- /dev/null +++ b/test/derive/inspection_summary_test.dart @@ -0,0 +1,173 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:view_source_vibe/models/inspection/observed.dart'; +import 'package:view_source_vibe/models/inspection/page_inspection.dart'; +import 'package:view_source_vibe/services/derive/block_page.dart'; +import 'package:view_source_vibe/services/derive/cookies_view.dart'; +import 'package:view_source_vibe/services/derive/detections_view.dart'; +import 'package:view_source_vibe/services/derive/divergences.dart'; +import 'package:view_source_vibe/services/derive/inspection_summary.dart'; +import 'package:view_source_vibe/services/derive/probe_general.dart'; +import 'package:view_source_vibe/services/derive/security_audit.dart'; +import 'package:view_source_vibe/services/detection/engine.dart'; +import 'package:view_source_vibe/services/sovereignty_service.dart'; + +import '../fixtures/inspection/bot_blocked.dart'; +import '../fixtures/inspection/builders.dart'; +import '../fixtures/inspection/full_page.dart'; +import '../fixtures/inspection/trackers.dart'; + +SummaryInputs inputsFor( + PageInspection p, { + List detections = const [], + BlockPage? blockPage, + Observed? security, + Observed? sovereignty, + List divergences = const [], +}) { + final complete = p.target is! NoTarget; + return SummaryInputs( + inspection: p, + general: deriveGeneral(p, divergences: divergences), + security: security ?? deriveSecurity(p, now: DateTime.utc(2026, 1, 1)), + cookies: deriveCookiesView(p, now: DateTime.utc(2026, 1, 1)), + detections: DetectionsView( + detections: detections, + scanning: false, + failure: null, + sources: CheckedSources(complete ? const ['server HTML'] : const [], + const [], false), + ), + sovereignty: sovereignty ?? + const Unavailable(UnavailableReason.notApplicable, 'none'), + blockPage: blockPage, + divergences: divergences, + ); +} + +Detection det(String name, {int requests = 0}) => + Detection(entityNamed(name)!)..requests = requests; + +Observed securityWith(List checks) => Present( + SecurityModel( + audit: Present(SecurityAudit(checks, const []), + source: DataSource.server), + csp: const Unavailable(UnavailableReason.notApplicable), + certificate: const Unavailable(UnavailableReason.notApplicable), + tlsWarning: null, + ), + source: DataSource.server); + +void main() { + test('trackers are reported with names and severity', () { + final s = deriveSummary(inputsFor(trackerPage(), detections: [ + det('Google Ads', requests: 2), + det('Google Analytics', requests: 1), + ])); + final f = s.findings.firstWhere((f) => f.id == 'trackers'); + expect(f.severity, FindingSeverity.high); + expect(f.title, '2 tracker(s): Google Ads, Google Analytics'); + expect(f.tab, 'privacy'); + expect(s.facts['trackers'], 2); + expect(s.facts['trackerNames'], ['Google Ads', 'Google Analytics']); + }); + + test('more than three trackers are cut with a count', () { + final s = deriveSummary(inputsFor(trackerPage(), detections: [ + det('Google Ads', requests: 1), + det('Meta Pixel', requests: 1), + det('Hotjar', requests: 1), + det('Google Analytics', requests: 1), + det('Microsoft Clarity', requests: 1), + ])); + final f = s.findings.firstWhere((f) => f.id == 'trackers'); + expect(f.title, '5 tracker(s): Google Ads, Meta Pixel, Hotjar (+2)'); + }); + + test('tracking with a consent tool present is pre-consent tracking', () { + final s = deriveSummary(inputsFor(trackerPage(), detections: [ + det('Google Ads', requests: 2), + det('Cookiebot', requests: 1), + ])); + final f = s.findings.firstWhere((f) => f.id == 'pre-consent'); + expect(f.severity, FindingSeverity.high); + expect(f.title, contains('Cookiebot')); + expect(s.facts['consentTool'], 'Cookiebot'); + }); + + test('a block page hides content findings', () { + final s = deriveSummary(inputsFor(botBlocked(), + blockPage: const BlockPage(status: 403, byMarker: true), + detections: [det('Google Ads', requests: 2)])); + expect(s.findings.first.id, 'block-page'); + expect(s.findings.first.title, startsWith('Not the site: ')); + expect(s.findings.map((f) => f.id), isNot(contains('trackers'))); + expect(s.facts['blocked'], isTrue); + expect(s.facts['trackers'], isNull); + }); + + test('unknown facts are null, never 0', () { + final s = deriveSummary(inputsFor(const PageInspection.empty())); + expect(s.findings, isEmpty); + expect(s.facts.keys, summaryFactKeys); + expect(s.facts['requests'], isNull); + expect(s.facts['securityHeadersPct'], isNull); + expect(s.facts['trackers'], isNull); + expect(s.facts['blocked'], isNull); + }); + + test('findings are sorted by severity, then rule order', () { + final s = deriveSummary(inputsFor(trackerPage(), + detections: [det('Google Ads', requests: 1)], + security: securityWith(const [ + SecurityCheck('HSTS', true, false, ''), + SecurityCheck('CSP', true, false, ''), + ]))); + final ids = s.findings.map((f) => f.id).toList(); + expect(ids, containsAll(['trackers', 'security-headers'])); + final sev = s.findings.map((f) => f.severity.index).toList(); + expect(sev, [...sev]..sort()); + expect(s.top.length, lessThanOrEqualTo(5)); + }); + + test('security headers name what is missing', () { + final s = deriveSummary(inputsFor(fullPage(), + security: securityWith(const [ + SecurityCheck('HSTS', true, false, ''), + SecurityCheck('CSP', true, false, ''), + SecurityCheck('Frames', true, true, ''), + SecurityCheck('No Sniff', true, true, ''), + SecurityCheck('Referrer', true, true, ''), + SecurityCheck('Permissions', true, true, ''), + ]))); + final f = s.findings.firstWhere((f) => f.id == 'security-headers'); + expect(f.title, 'Security headers: 67% (missing: HSTS, CSP)'); + expect(f.severity, FindingSeverity.low); + expect(s.facts['securityHeadersPct'], 67); + }); + + test('titles never say unknown and toJson is plain data', () { + final s = deriveSummary(inputsFor(trackerPage(), + detections: [det('Google Ads', requests: 1)])); + for (final f in s.findings) { + expect(f.title.toLowerCase(), isNot(contains('unknown'))); + } + final j = s.toJson(); + expect((j['findings'] as List).first, isA>()); + expect((j['facts'] as Map).keys, summaryFactKeys); + }); + + test('plain http is a high finding', () { + final p = urlInspection( + url: 'http://old.example.org/', + serverResult: server(serverSnapshot( + url: 'http://old.example.org/', + hops: [hop('http://old.example.org/', 200)], + body: '')), + browserResult: const Pending(), + ); + final s = deriveSummary(inputsFor(p)); + expect(s.findings.first.id, 'no-https'); + expect(s.facts['finalUrl'], 'http://old.example.org/'); + expect(s.facts['status'], 200); + }); +} From 735f423f54752d8421d121e897431c770fb03df0 Mon Sep 17 00:00:00 2001 From: Wouter van Wijk Date: Tue, 17 Nov 2026 17:04:32 +0100 Subject: [PATCH 2/9] Export: key findings in report.html and analysis/summary.json Co-Authored-By: Claude Opus 5.5 --- lib/services/html_service.dart | 13 +++++++++++ lib/services/inspection_export_service.dart | 15 +++++++++++++ test/inspection_export_service_test.dart | 25 +++++++++++++++++++++ 3 files changed, 53 insertions(+) diff --git a/lib/services/html_service.dart b/lib/services/html_service.dart index 4a982b2..0dc8c56 100644 --- a/lib/services/html_service.dart +++ b/lib/services/html_service.dart @@ -36,6 +36,7 @@ import 'package:view_source_vibe/services/derive/detections_view.dart'; import 'package:view_source_vibe/services/derive/divergences.dart'; import 'package:view_source_vibe/services/derive/block_page.dart'; import 'package:view_source_vibe/services/derive/header_insights.dart'; +import 'package:view_source_vibe/services/derive/inspection_summary.dart'; import 'package:view_source_vibe/services/derive/probe_general.dart'; import 'package:view_source_vibe/services/derive/request_timeline.dart'; import 'package:view_source_vibe/services/derive/security_audit.dart'; @@ -824,6 +825,18 @@ class HtmlService extends ChangeNotifier { return _divergences!; } + /// The key findings and facts of the current inspection. Not cached. + InspectionSummary get summary => deriveSummary(SummaryInputs( + inspection: store.current, + general: generalView, + security: securityView, + cookies: cookiesView, + detections: detectionsView, + sovereignty: sovereigntyState, + blockPage: blockPage, + divergences: divergences, + )); + Observed? _general; ({ InspectionTarget target, diff --git a/lib/services/inspection_export_service.dart b/lib/services/inspection_export_service.dart index ea74b2d..bc3ab43 100644 --- a/lib/services/inspection_export_service.dart +++ b/lib/services/inspection_export_service.dart @@ -8,6 +8,7 @@ import 'package:view_source_vibe/models/inspection/browser_snapshot.dart'; import 'package:view_source_vibe/models/inspection/observed.dart'; import 'package:view_source_vibe/models/inspection/page_inspection.dart'; import 'package:view_source_vibe/services/derive/cookies_view.dart'; +import 'package:view_source_vibe/services/derive/inspection_summary.dart'; import 'package:view_source_vibe/services/derive/metadata_view.dart'; import 'package:view_source_vibe/services/derive/observed_text.dart'; import 'package:view_source_vibe/services/derive/probe_general.dart'; @@ -182,11 +183,14 @@ class InspectionExportService { final sovereigntyJson = observedJson(sovereignty, (r) => r.toJson(), source: DataSource.server, provenance: Provenance.derived); + final summary = htmlService.summary; + addJson('manifest.json', manifest); addString( 'report.html', _buildHtmlReport( manifest: manifest, + summary: summary, general: general, security: security, cookies: cookies, @@ -219,6 +223,7 @@ class InspectionExportService { addJson('network/redirects.json', redirectsJson); addJson('network/timeline.json', timelineJson); addJson('analysis/sovereignty.json', sovereigntyJson); + addJson('analysis/summary.json', summary.toJson()); addJson('analysis/metadata.json', metadataJson); addJson('analysis/detections.json', detectionsJson); @@ -349,6 +354,7 @@ class InspectionExportService { static String _buildHtmlReport({ required Map manifest, + required InspectionSummary summary, required Observed general, required Observed security, required Observed cookies, @@ -523,6 +529,15 @@ class InspectionExportService { ${_metricCard('App request status', status == null ? unknownText(general) : _obs(status, (s) => s.finalStatusText))} +

Key findings

+ ${summary.findings.isEmpty ? '
No findings from the checks that ran.
' : _table([ + for (final f in summary.findings) + [ + '${f.severity.name[0].toUpperCase()}${f.severity.name.substring(1)}', + f.title + ] + ], ['Severity', 'Finding'])} +

Included Files

${_pill('manifest.json')} diff --git a/test/inspection_export_service_test.dart b/test/inspection_export_service_test.dart index 53c729c..fa941ea 100644 --- a/test/inspection_export_service_test.dart +++ b/test/inspection_export_service_test.dart @@ -5,6 +5,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:view_source_vibe/services/derive/network_quiet.dart'; import 'package:view_source_vibe/models/html_file.dart'; import 'package:view_source_vibe/models/inspection/browser_snapshot.dart'; +import 'package:view_source_vibe/services/derive/inspection_summary.dart'; import 'package:view_source_vibe/services/html_service.dart'; import 'package:view_source_vibe/services/inspection_store.dart'; import 'package:view_source_vibe/services/inspection_export_service.dart'; @@ -63,6 +64,30 @@ void main() { } }); + test('the package carries the summary', () async { + final service = HtmlService(); + await service.loadFile( + HtmlFile( + name: 'example.html', + path: 'https://example.com', + content: 'Example' + 'Hello', + lastModified: DateTime.utc(2026, 4, 29), + size: 82, + isUrl: true, + ), + ); + final archive = ZipDecoder() + .decodeBytes(InspectionExportService().buildPackageBytes(service)); + final json = jsonDecode(utf8.decode( + archive.findFile('analysis/summary.json')!.content as List)) + as Map; + expect((json['facts'] as Map).keys, containsAll(summaryFactKeys)); + final report = + utf8.decode(archive.findFile('report.html')!.content as List); + expect(report, contains('

Key findings

')); + }); + test( 'adds the raw browser payload as debug/browser-payload.json and ' 'prints unknown sizes as unknown', () async { From f976d53fdc148b22453344d7f484b6b2e57b8a3a Mon Sep 17 00:00:00 2001 From: Wouter van Wijk Date: Tue, 17 Nov 2026 17:09:03 +0100 Subject: [PATCH 3/9] Batch: summary as JSON, CSV and HTML Co-Authored-By: Claude Opus 5.5 --- lib/services/batch_summary.dart | 141 ++++++++++++++++++++ lib/services/derive/inspection_summary.dart | 10 +- lib/services/inspection_export_service.dart | 28 +--- lib/services/report_css.dart | 23 ++++ test/services/batch_summary_test.dart | 77 +++++++++++ 5 files changed, 253 insertions(+), 26 deletions(-) create mode 100644 lib/services/batch_summary.dart create mode 100644 lib/services/report_css.dart create mode 100644 test/services/batch_summary_test.dart diff --git a/lib/services/batch_summary.dart b/lib/services/batch_summary.dart new file mode 100644 index 0000000..7bc0e93 --- /dev/null +++ b/lib/services/batch_summary.dart @@ -0,0 +1,141 @@ +import 'dart:convert'; + +import 'derive/inspection_summary.dart'; +import 'report_css.dart'; + +/// One visited site of a batch. +class BatchRow { + final Uri url; + + /// Also the package name: `sites/.zip`. + final String slug; + + /// 'done' | 'timed out' | 'failed' | 'cancelled' + final String state; + + /// Analyses unfinished at export. + final List pending; + final String? error; + + /// Null when nothing was exported. + final InspectionSummary? summary; + + const BatchRow({ + required this.url, + required this.slug, + required this.state, + this.pending = const [], + this.error, + this.summary, + }); + + String get package => 'sites/$slug.zip'; +} + +const _escape = HtmlEscape(HtmlEscapeMode.attribute); + +Map batchSummaryJson(List rows, + {required DateTime exportedAt}) => + { + 'format': 'view-source-vibe-batch', + 'formatVersion': 1, + 'exportedAt': exportedAt.toUtc().toIso8601String(), + 'unknownIs': 'null', + 'sites': [ + for (final r in rows) + { + 'url': r.url.toString(), + 'slug': r.slug, + 'package': r.package, + 'state': r.state, + 'pending': r.pending, + 'error': r.error, + 'summary': r.summary?.toJson(), + } + ], + }; + +/// One CSV cell. Text from a site cannot become a spreadsheet formula. +String csvCell(Object? value) { + if (value == null) return ''; + if (value is num || value is bool) return value.toString(); + var text = value is List ? value.join('; ') : value.toString(); + if (text.isNotEmpty && '=+-@\t\r'.contains(text[0])) text = "'$text"; + if (text.contains(RegExp(r'[,"\r\n]'))) { + text = '"${text.replaceAll('"', '""')}"'; + } + return text; +} + +String batchSummaryCsv(List rows) { + final lines = [ + [ + 'url', 'state', 'pending', 'error', ...summaryFactKeys, // + for (var i = 1; i <= 5; i++) 'finding$i', + ].join(','), + ]; + for (final r in rows) { + final s = r.summary; + final top = s?.top ?? const []; + lines.add([ + csvCell(r.url.toString()), + csvCell(r.state), + csvCell(r.pending), + csvCell(r.error), + for (final k in summaryFactKeys) csvCell(s?.facts[k]), + for (var i = 0; i < 5; i++) + csvCell(i < top.length + ? '${top[i].severity.label}: ${top[i].title}' + : null), + ].join(',')); + } + return '${lines.join('\r\n')}\r\n'; +} + +String batchSummaryHtml(List rows, {required DateTime exportedAt}) { + String e(Object? v) => _escape.convert('$v'); + final body = StringBuffer(); + for (final r in rows) { + final s = r.summary; + final String findings; + if (s == null) { + findings = '${e(r.state)}' + '${r.error == null ? '' : ': ${e(r.error)}'}'; + } else if (s.top.isEmpty) { + findings = 'No findings'; + } else { + findings = '
    ${[ + for (final f in s.top) + '
  • ${e(f.severity.label)} ${e(f.title)}
  • ' + ].join()}
'; + } + final pending = r.pending.isEmpty + ? '' + : '
Unfinished: ${e(r.pending.join(', '))}
'; + body.writeln('' + '${e(r.url)}' + '${e(r.state)}$pending' + '$findings' + ''); + } + return ''' + + + + + View Source Vibe batch summary + $reportCss + + +
+

Batch summary

+

${e(exportedAt.toUtc().toIso8601String())} · ${rows.length} sites

+ + + +$body +
SiteStateKey findings
+
+ +'''; +} diff --git a/lib/services/derive/inspection_summary.dart b/lib/services/derive/inspection_summary.dart index eab900d..47fdab3 100644 --- a/lib/services/derive/inspection_summary.dart +++ b/lib/services/derive/inspection_summary.dart @@ -21,7 +21,15 @@ const kWeightHeavy = 5 * 1024 * 1024; const kWeightNotable = 2 * 1024 * 1024; const kFrameShareNotable = 0.20; -enum FindingSeverity { high, medium, low, info } +enum FindingSeverity { + high('High'), + medium('Medium'), + low('Low'), + info('Info'); + + final String label; + const FindingSeverity(this.label); +} class Finding { final String id; diff --git a/lib/services/inspection_export_service.dart b/lib/services/inspection_export_service.dart index bc3ab43..fbd82d8 100644 --- a/lib/services/inspection_export_service.dart +++ b/lib/services/inspection_export_service.dart @@ -19,6 +19,7 @@ import 'package:view_source_vibe/services/html_service.dart'; import 'package:view_source_vibe/services/detection/engine.dart'; import 'package:view_source_vibe/services/inspection_export_data.dart'; import 'package:view_source_vibe/services/observed_json.dart'; +import 'package:view_source_vibe/services/report_css.dart'; import 'package:view_source_vibe/utils/line_diff.dart'; class InspectionExportService { @@ -533,7 +534,7 @@ class InspectionExportService { ${summary.findings.isEmpty ? '
No findings from the checks that ran.
' : _table([ for (final f in summary.findings) [ - '${f.severity.name[0].toUpperCase()}${f.severity.name.substring(1)}', + f.severity.label, f.title ] ], ['Severity', 'Finding'])} @@ -623,32 +624,9 @@ class InspectionExportService { ''' - .replaceFirst('CSS_PLACEHOLDER', _reportCss); + .replaceFirst('CSS_PLACEHOLDER', reportCss); } - static const _reportCss = r''''''; - static List> _metadataSummary(Map metadata) { const keys = [ 'title', diff --git a/lib/services/report_css.dart b/lib/services/report_css.dart new file mode 100644 index 0000000..f281f64 --- /dev/null +++ b/lib/services/report_css.dart @@ -0,0 +1,23 @@ +// Shared by report.html and the batch summary page. +const reportCss = r''''''; diff --git a/test/services/batch_summary_test.dart b/test/services/batch_summary_test.dart new file mode 100644 index 0000000..98681cf --- /dev/null +++ b/test/services/batch_summary_test.dart @@ -0,0 +1,77 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:view_source_vibe/services/batch_summary.dart'; +import 'package:view_source_vibe/services/derive/inspection_summary.dart'; + +InspectionSummary summaryWith(String title) => InspectionSummary( + [Finding('x', FindingSeverity.high, title, tab: 'security')], + {for (final k in summaryFactKeys) k: null}..['url'] = 'https://a.test/', + ); + +BatchRow rowFor(String url, {String? title}) => BatchRow( + url: Uri.parse(url), + slug: Uri.parse(url).host, + state: 'done', + pending: const [], + summary: summaryWith(title ?? 'Something'), + ); + +void main() { + final at = DateTime.utc(2026, 11, 15); + + test('csv cells from a site cannot become formulas', () { + expect(csvCell('=HYPERLINK("http://x")'), '"\'=HYPERLINK(""http://x"")"'); + expect(csvCell('@cmd'), "'@cmd"); + expect(csvCell('+1'), "'+1"); + expect(csvCell('\tx'), "'\tx"); + expect(csvCell(-5), '-5'); + expect(csvCell(true), 'true'); + expect(csvCell(null), ''); + expect(csvCell(['a', 'b']), 'a; b'); + expect(csvCell(['=a', 'b']), "'=a; b"); + expect(csvCell('a,b'), '"a,b"'); + }); + + test('csv has one row per site and a stable header', () { + final csv = + batchSummaryCsv([rowFor('https://a.test/'), rowFor('https://b.test/')]); + final lines = csv.trimRight().split('\r\n'); + expect(lines, hasLength(3)); + expect(lines.first, + startsWith('url,state,pending,error,url,finalUrl,status,')); + expect( + lines.first, endsWith('finding1,finding2,finding3,finding4,finding5')); + expect(lines[1], contains('High: Something')); + }); + + test('html escapes site text', () { + final html = batchSummaryHtml( + [rowFor('https://a.test/', title: '')], + exportedAt: at); + expect(html, contains('<script>')); + expect(html, isNot(contains('