diff --git a/integration_test/site_validation_test.dart b/integration_test/site_validation_test.dart index bd8b186..a213a7a 100644 --- a/integration_test/site_validation_test.dart +++ b/integration_test/site_validation_test.dart @@ -16,7 +16,7 @@ import 'package:integration_test/integration_test.dart'; import 'package:provider/provider.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:view_source_vibe/main.dart' as app; -import 'package:view_source_vibe/models/inspection/observed.dart'; +import 'package:view_source_vibe/services/batch_runner.dart'; import 'package:view_source_vibe/services/html_service.dart'; import 'package:view_source_vibe/services/inspection_export_service.dart'; @@ -40,17 +40,6 @@ const _restoreKeys = [ 'input_text', ]; -/// What is still unfinished, by name; empty when the page is ready. -List _pending(HtmlService s) => [ - if (s.isLoading) 'loading', - if (!s.store.current.browserSettled) 'browserSettled', - if (!s.detectionsView.complete) 'detections', - if (s.generalView is Pending) 'general', - if (s.securityView is Pending) 'security', - if (s.cookiesView is Pending) 'cookies', - if (s.sovereigntyState is Pending) 'sovereignty', - ]; - void main() { final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized(); binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.fullyLive; @@ -100,11 +89,11 @@ void main() { // Give the load a moment to start before polling for "done". await tester.pump(const Duration(seconds: 2)); while (clock.elapsed < _timeout) { - pending = _pending(html); + pending = pendingAnalyses(html); if (pending.isEmpty) break; await tester.pump(const Duration(milliseconds: 500)); } - pending = _pending(html); + pending = pendingAnalyses(html); if (_linger > 0) { await tester.pump(Duration(seconds: _linger)); // Collect once more (as when the page reports new resources) so diff --git a/lib/main.dart b/lib/main.dart index f310bb4..237e601 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,3 +1,4 @@ +import 'package:view_source_vibe/services/batch_runner.dart'; import 'package:material_ui/material_ui.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; @@ -345,6 +346,8 @@ void main() async { providers: [ ChangeNotifierProvider.value(value: inspectionStore), ChangeNotifierProvider.value(value: htmlService), + ChangeNotifierProvider( + create: (_) => BatchRunner(HtmlServiceBatchTarget(htmlService))), ChangeNotifierProvider.value(value: readerService), ChangeNotifierProvider.value(value: appSettings), ChangeNotifierProvider.value(value: appStateService), diff --git a/lib/screens/batch_screen.dart b/lib/screens/batch_screen.dart new file mode 100644 index 0000000..ad30758 --- /dev/null +++ b/lib/screens/batch_screen.dart @@ -0,0 +1,179 @@ +import 'package:file_picker/file_picker.dart'; +import 'package:flutter/foundation.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:provider/provider.dart'; +import 'package:universal_io/io.dart'; +import 'package:view_source_vibe/services/batch_input_store.dart'; +import 'package:view_source_vibe/services/batch_runner.dart'; +import 'package:view_source_vibe/services/derive/inspection_summary.dart'; +import 'package:view_source_vibe/services/unified_sharing_service.dart'; +import 'package:view_source_vibe/widgets/share_package_dialog.dart'; + +/// Paste a list of sites and start visiting them one by one. +class BatchScreen extends StatefulWidget { + const BatchScreen({super.key}); + + @override + State createState() => _BatchScreenState(); +} + +class _BatchScreenState extends State { + final _store = BatchInputStore(); + final _controller = TextEditingController(); + bool _clearSiteData = true; + bool _freshLoad = false; + + @override + void initState() { + super.initState(); + _store.load().then((text) { + if (mounted && _controller.text.isEmpty) { + setState(() => _controller.text = text); + } + }); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + void _start(List urls) { + context + .read() + .run(urls, + options: BatchOptions( + clearSiteData: _clearSiteData, freshLoad: _freshLoad)) + .ignore(); + Navigator.of(context).pop(); + } + + @override + Widget build(BuildContext context) { + final parsed = parseBatchInput(_controller.text); + final running = context.watch().running; + return Scaffold( + appBar: AppBar(title: const Text('Batch')), + body: ListView( + padding: const EdgeInsets.all(16), + children: [ + TextField( + controller: _controller, + minLines: 6, + maxLines: 12, + keyboardType: TextInputType.multiline, + autocorrect: false, + decoration: const InputDecoration( + hintText: 'One site per line', border: OutlineInputBorder()), + onChanged: (text) { + _store.save(text); + setState(() {}); + }, + ), + const SizedBox(height: 8), + Text('${parsed.urls.length} site(s)'), + if (parsed.rejected.isNotEmpty) + Text( + '${parsed.rejected.length} line(s) skipped: ' + '${parsed.rejected.take(3).join(', ')}', + style: TextStyle(color: Theme.of(context).colorScheme.error)), + SwitchListTile( + title: const Text('Clear site data before each site'), + value: _clearSiteData, + onChanged: (v) => setState(() => _clearSiteData = v), + ), + SwitchListTile( + title: const Text('Also measure a fresh load (slower)'), + value: _freshLoad, + onChanged: (v) => setState(() => _freshLoad = v), + ), + const SizedBox(height: 8), + Align( + alignment: Alignment.centerLeft, + child: FilledButton( + onPressed: parsed.urls.isEmpty || running + ? null + : () => _start(parsed.urls), + child: const Text('Start'), + ), + ), + ], + ), + ); + } +} + +/// One tile per site, and the zip to share or save. +class BatchResultsScreen extends StatelessWidget { + const BatchResultsScreen({super.key}); + + bool get _mobile => Platform.isIOS || Platform.isAndroid; + + Future _export(BuildContext context, BatchRunner runner) async { + final messenger = ScaffoldMessenger.of(context); + try { + if (_mobile && !await confirmSharePackage(context)) return; + final file = await runner.writeZip(); + if (file == null) { + messenger.showSnackBar(const SnackBar( + content: Text('No site finished: nothing to export'))); + return; + } + if (_mobile) { + await UnifiedSharingService.shareFile(file.path, + mimeType: 'application/zip'); + messenger + .showSnackBar(const SnackBar(content: Text('Batch zip shared'))); + return; + } + final savePath = await FilePicker.saveFile( + dialogTitle: 'Save Batch Zip', + fileName: file.uri.pathSegments.last, + bytes: Uint8List.fromList(await file.readAsBytes()), + ); + if (savePath == null) return; + messenger + .showSnackBar(SnackBar(content: Text('Batch zip saved: $savePath'))); + } catch (e) { + debugPrint('Batch export error: $e'); + messenger.showSnackBar(SnackBar(content: Text('Export failed: $e'))); + } + } + + @override + Widget build(BuildContext context) { + final runner = context.watch(); + final rows = runner.rows; + return Scaffold( + appBar: AppBar(title: Text('Batch results (${rows.length})')), + body: Column(children: [ + Expanded( + child: ListView(children: [ + for (final r in rows) + ListTile( + title: Text(r.url.host), + subtitle: Text([ + r.state + (r.error == null ? '' : ': ${r.error}'), + for (final f in r.summary?.top.take(3) ?? const []) + '${f.severity.label}: ${f.title}', + ].join('\n')), + isThreeLine: (r.summary?.top.isNotEmpty ?? false), + ), + ]), + ), + SafeArea( + child: Padding( + padding: const EdgeInsets.all(12), + child: FilledButton( + onPressed: runner.running || rows.isEmpty + ? null + : () => _export(context, runner), + child: Text(_mobile ? 'Share zip' : 'Save zip'), + ), + ), + ), + ]), + ); + } +} diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dart index a014ff0..a4f6784 100644 --- a/lib/screens/home_screen.dart +++ b/lib/screens/home_screen.dart @@ -10,6 +10,7 @@ import 'package:view_source_vibe/services/html_service.dart'; import 'package:view_source_vibe/models/app_tab.dart'; import 'package:view_source_vibe/models/html_file.dart'; import 'package:view_source_vibe/widgets/source_viewer.dart'; +import 'package:view_source_vibe/widgets/batch_banner.dart'; import 'package:view_source_vibe/widgets/toolbar.dart'; import 'package:view_source_vibe/widgets/url_input.dart'; import 'package:view_source_vibe/widgets/metadata_view.dart'; @@ -537,6 +538,7 @@ class HomeScreenState extends State with TickerProviderStateMixin { child: Column( children: [ UrlInput(key: urlInputKey), + const BatchBanner(), _buildTabGroupBar(context), const Divider(height: 1), Expanded( diff --git a/lib/services/batch_input_store.dart b/lib/services/batch_input_store.dart new file mode 100644 index 0000000..e21e33a --- /dev/null +++ b/lib/services/batch_input_store.dart @@ -0,0 +1,22 @@ +import 'package:shared_preferences/shared_preferences.dart'; + +/// Remembers the pasted list of sites between runs. +class BatchInputStore { + static const key = 'batch_urls'; + + Future load() async { + try { + return (await SharedPreferences.getInstance()).getString(key) ?? ''; + } catch (_) { + return ''; + } + } + + Future save(String text) async { + try { + await (await SharedPreferences.getInstance()).setString(key, text); + } catch (_) { + // Not remembering the list is not worth an error. + } + } +} diff --git a/lib/services/batch_runner.dart b/lib/services/batch_runner.dart new file mode 100644 index 0000000..d408dfb --- /dev/null +++ b/lib/services/batch_runner.dart @@ -0,0 +1,391 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:archive/archive_io.dart'; +import 'package:flutter/foundation.dart'; +import 'package:path/path.dart' as path; +import 'package:path_provider/path_provider.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/models/inspection/server_snapshot.dart'; +import 'package:view_source_vibe/services/batch_summary.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_export_service.dart'; +import 'package:view_source_vibe/services/site_data_cleaner.dart' as cleaner; + +/// Unfinished analyses by name; empty when the page is ready to export. A +/// finished detection scan that failed or checked nothing is not pending. +List pendingAnalyses(HtmlService s) => [ + if (s.isLoading) 'loading', + if (!s.store.current.browserSettled) 'browserSettled', + if (s.detectionsView.scanning) 'detections', + if (s.generalView is Pending) 'general', + if (s.securityView is Pending) 'security', + if (s.cookiesView is Pending) 'cookies', + if (s.sovereigntyState is Pending) 'sovereignty', + ]; + +final _schemePrefix = RegExp(r'^[a-zA-Z][a-zA-Z0-9+.-]*:(?!\d)'); + +/// One URL per line. Blank lines and lines starting with '#' are skipped; a +/// line without a scheme gets 'https://'. Only http/https with a host +/// survive (a line with whitespace inside it is rejected); duplicates (after +/// normalising) are dropped; at most [max] (the rest is rejected). +({List urls, List rejected}) parseBatchInput(String text, + {int max = 50}) { + final urls = []; + final rejected = []; + final seen = {}; + for (final raw in const LineSplitter().convert(text)) { + final line = raw.trim(); + if (line.isEmpty || line.startsWith('#')) continue; + final uri = RegExp(r'\s').hasMatch(line) + ? null + : Uri.tryParse(line.contains('://') || _schemePrefix.hasMatch(line) + ? line + : 'https://$line'); + if (uri == null || + (uri.scheme != 'http' && uri.scheme != 'https') || + uri.host.isEmpty) { + rejected.add(line); + continue; + } + final key = '${uri.scheme}://${uri.host}:${uri.port}' + '${uri.path.isEmpty ? '/' : uri.path}?${uri.query}'; + if (!seen.add(key)) continue; + if (urls.length >= max) { + rejected.add(line); + continue; + } + urls.add(uri); + } + return (urls: urls, rejected: rejected); +} + +class BatchOptions { + final bool clearSiteData; + final Duration timeout; + final Duration linger; + final bool freshLoad; + const BatchOptions({ + this.clearSiteData = true, + this.timeout = const Duration(seconds: 90), + this.linger = const Duration(seconds: 5), + this.freshLoad = false, + }); +} + +abstract interface class BatchTarget { + Future open(Uri url); + List pending(); + void collectLate(); + Future clearSiteData(Uri url); + Future measureFreshLoad(); + void watchSovereignty(bool watching); + + /// The app's own request or the browser got the page. + bool loaded(); + + /// Why the app's own request failed; null when it did not. + String? loadFailure(); + + /// The target still shows the page opened for [url] (the user did not + /// navigate elsewhere). + bool stillOn(Uri url); + InspectionSummary summary(); + List package(); +} + +class HtmlServiceBatchTarget implements BatchTarget { + final HtmlService service; + HtmlServiceBatchTarget(this.service); + + /// Store generation right after [open]. + int? _generation; + + @override + Future open(Uri url) async { + _generation = null; + await service.loadFromUrl(url.toString(), + switchToTab: HtmlService.browserTab); + _generation = service.store.current.generation; + } + + @override + List pending() => pendingAnalyses(service); + + @override + void collectLate() => service.onBrowserResourcesChanged(); + + @override + Future clearSiteData(Uri url) => cleaner.clearSiteData(url); + + @override + Future measureFreshLoad() => service.measureFreshLoad(); + + @override + void watchSovereignty(bool watching) => service.watchSovereignty(watching); + + @override + bool loaded() { + final p = service.store.current; + final server = p.server; + return (server is Present && + server.value.hops.isNotEmpty) || + p.browser is Present; + } + + @override + String? loadFailure() => switch (service.store.current.server) { + Failed(:final error) => error, + _ => null, + }; + + @override + bool stillOn(Uri url) { + final p = service.store.current; + final target = p.target; + return p.generation == _generation && + target is UrlTarget && + HtmlService.sameUrl(target.url, url); + } + + @override + InspectionSummary summary() => service.summary; + + @override + List package() => InspectionExportService().buildPackageBytes(service); +} + +/// Visits sites one by one through the live browser and exports each. +class BatchRunner extends ChangeNotifier { + final BatchTarget _target; + final Duration _poll; + + /// Wait after opening a page before polling, and after the late collect. + final Duration _settle; + final Duration _lateWait; + final Future Function() _workDirFactory; + + BatchRunner( + BatchTarget target, { + Duration poll = const Duration(milliseconds: 500), + Duration settle = const Duration(seconds: 2), + Duration lateWait = const Duration(seconds: 3), + Future Function()? workDir, + }) : _target = target, + _poll = poll, + _settle = settle, + _lateWait = lateWait, + _workDirFactory = workDir ?? _defaultWorkDir; + + static Future _defaultWorkDir() async { + final stamp = DateTime.now() + .toUtc() + .toIso8601String() + .replaceAll(RegExp(r'[^0-9]'), '') + .substring(0, 14); + final base = await getTemporaryDirectory(); + return Directory(path.join(base.path, 'batch-$stamp')) + .create(recursive: true); + } + + bool _running = false; + bool _cancelled = false; + int _index = 0; + int _total = 0; + Uri? _currentUrl; + List _currentPending = const []; + String _phase = ''; + String? _error; + Directory? _dir; + String? _stamp; + final List _rows = []; + final Set _slugs = {}; + + bool get running => _running; + int get index => _index; + int get total => _total; + Uri? get currentUrl => _currentUrl; + List get currentPending => _currentPending; + + /// Step of the current site: 'clearing', 'loading', 'waiting', + /// 'collecting', 'measuring' or 'exporting'. + String get phase => _phase; + List get rows => List.unmodifiable(_rows); + + /// Set when the run ended outside any site (e.g. no work directory). + String? get error => _error; + + /// Forgets the finished batch (hides the banner). + void dismiss() { + if (_running) return; + _rows.clear(); + _error = null; + _deleteWorkDir(); + notifyListeners(); + } + + void _deleteWorkDir() { + final dir = _dir; + _dir = null; + try { + if (dir != null && dir.existsSync()) dir.deleteSync(recursive: true); + } catch (_) {} + } + + void _setPhase(String phase) { + _phase = phase; + notifyListeners(); + } + + void cancel() { + if (_running) _cancelled = true; + } + + Future run(List urls, + {BatchOptions options = const BatchOptions()}) async { + if (_running) return; + _running = true; + _cancelled = false; + _error = null; + _rows.clear(); + _slugs.clear(); + _index = 0; + _total = urls.length; + _deleteWorkDir(); + _stamp = DateTime.now() + .toUtc() + .toIso8601String() + .replaceAll(RegExp(r'[^0-9]'), '') + .substring(0, 14); + notifyListeners(); + try { + _target.watchSovereignty(true); + final dir = _dir = await _workDirFactory(); + await Directory(path.join(dir.path, 'sites')).create(recursive: true); + for (var i = 0; i < urls.length && !_cancelled; i++) { + _index = i; + _currentUrl = urls[i]; + _currentPending = const []; + notifyListeners(); + final row = await _visit(urls[i], options, dir); + if (row == null) break; // cancelled mid-site + _rows.add(row); + notifyListeners(); + } + } catch (e) { + _error = e.toString(); + } finally { + try { + _target.watchSovereignty(false); + } catch (_) {} + _running = false; + _currentUrl = null; + _currentPending = const []; + _phase = ''; + notifyListeners(); + } + } + + String _uniqueSlug(Uri url) { + final base = inspectionSlug(url.toString()); + var slug = base; + for (var n = 2; !_slugs.add(slug); n++) { + slug = '$base-$n'; + } + return slug; + } + + /// Null when cancelled before the site was exported. + Future _visit(Uri url, BatchOptions o, Directory dir) async { + final slug = _uniqueSlug(url); + try { + if (o.clearSiteData) { + _setPhase('clearing'); + await _target.clearSiteData(url); + } + _setPhase('loading'); + await _target.open(url); + await Future.delayed(_settle); + final clock = Stopwatch()..start(); + var pending = _target.pending(); + while (pending.isNotEmpty && clock.elapsed < o.timeout && !_cancelled) { + _currentPending = pending; + _setPhase('waiting'); + await Future.delayed(_poll); + pending = _target.pending(); + } + if (_cancelled) return null; + _currentPending = const []; + _setPhase('collecting'); + await Future.delayed(o.linger); + _target.collectLate(); + await Future.delayed(_lateWait); + if (_cancelled) return null; + if (o.freshLoad) { + _setPhase('measuring'); + await _target.measureFreshLoad(); + } + _setPhase('exporting'); + // Everything below up to the write is read at one moment, no await. + if (!_target.stillOn(url)) { + return BatchRow( + url: url, + slug: slug, + state: 'failed', + error: 'navigated away during the batch'); + } + pending = _target.pending(); + final loaded = _target.loaded(); + final failure = loaded ? null : _target.loadFailure(); + final summary = _target.summary(); + final bytes = _target.package(); + await File(path.join(dir.path, 'sites', '$slug.zip')) + .writeAsBytes(bytes, flush: true); + return BatchRow( + url: url, + slug: slug, + state: !loaded ? 'failed' : (pending.isEmpty ? 'done' : 'timed out'), + pending: pending, + error: loaded ? null : (failure ?? 'the site did not load'), + summary: summary, + ); + } catch (e) { + return BatchRow( + url: url, slug: slug, state: 'failed', error: e.toString()); + } + } + + /// Writes the batch zip and returns it. Null when no site finished. + Future writeZip() async { + final dir = _dir; + if (dir == null || _rows.isEmpty) return null; + final now = DateTime.now().toUtc(); + // One name per run: a repeated export overwrites it. + final file = File(path.join(dir.path, 'viewsourcevibe-batch-$_stamp.zip')); + final rows = List.of(_rows); + final encoder = ZipFileEncoder()..create(file.path); + try { + void text(String name, String content) => + encoder.addArchiveFile(ArchiveFile.string(name, content)); + text('summary.html', batchSummaryHtml(rows, exportedAt: now)); + text('summary.csv', batchSummaryCsv(rows)); + text( + 'summary.json', + const JsonEncoder.withIndent(' ') + .convert(batchSummaryJson(rows, exportedAt: now))); + for (final r in rows) { + final f = File(path.join(dir.path, r.package)); + if (r.summary != null && f.existsSync()) { + // Stored: the nested zips are already compressed. + await encoder.addFile(f, r.package, ZipFileEncoder.store); + } + } + } finally { + await encoder.close(); + } + return file; + } +} diff --git a/lib/services/batch_summary.dart b/lib/services/batch_summary.dart new file mode 100644 index 0000000..728b3f2 --- /dev/null +++ b/lib/services/batch_summary.dart @@ -0,0 +1,144 @@ +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' + final String state; + + /// Analyses unfinished at export. + final List pending; + final String? error; + + /// Null when nothing was exported (then there is no package). + 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.summary == null ? null : 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 = [ + [ + 'requestedUrl', '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(', '))}
'; + final site = s == null + ? e(r.url) + : '${e(r.url)}'; + body.writeln('' + '$site' + '${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/divergences.dart b/lib/services/derive/divergences.dart index 32facdf..f0479ce 100644 --- a/lib/services/derive/divergences.dart +++ b/lib/services/derive/divergences.dart @@ -28,8 +28,10 @@ class Divergence { String _hostKey(Uri u) => u.host.toLowerCase(); +/// The path with a trailing slash ignored; an empty path is the root '/' +/// (as in `HtmlService.areUrlsEqual`). String _pathKey(Uri u) { - final p = u.path; + final p = u.path.isEmpty ? '/' : u.path; return p.length > 1 && p.endsWith('/') ? p.substring(0, p.length - 1) : p; } diff --git a/lib/services/derive/inspection_summary.dart b/lib/services/derive/inspection_summary.dart new file mode 100644 index 0000000..d6c97bd --- /dev/null +++ b/lib/services/derive/inspection_summary.dart @@ -0,0 +1,363 @@ +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('High'), + medium('Medium'), + low('Low'), + info('Info'); + + final String label; + const FindingSeverity(this.label); +} + +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 = [ + ..._notLoaded(p), + ..._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); +} + +bool _missing(Observed o) => o is Failed || o is Unavailable; + +/// Neither the app's own request nor the browser got the page. +List _notLoaded(PageInspection p) => + p.target is UrlTarget && _missing(p.server) && _missing(p.browser) + ? [ + Finding('not-loaded', FindingSeverity.high, 'The page did not load', + tab: AppTab.probe.tag) + ] + : const []; + +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, + '$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', + 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/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..ceb2530 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'; @@ -18,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 { @@ -182,11 +184,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 +224,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); @@ -317,7 +323,7 @@ class InspectionExportService { } static String _packageFilename(String source) { - final slug = _slugFor(source); + final slug = inspectionSlug(source); final stamp = DateTime.now() .toUtc() .toIso8601String() @@ -349,6 +355,7 @@ class InspectionExportService { static String _buildHtmlReport({ required Map manifest, + required InspectionSummary summary, required Observed general, required Observed security, required Observed cookies, @@ -523,6 +530,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.label, + f.title + ] + ], ['Severity', 'Finding'])} +

Included Files

${_pill('manifest.json')} @@ -608,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', @@ -788,20 +781,21 @@ class InspectionExportService { return const JsonEncoder.withIndent(' ').convert(_jsonSafe(value)); } - static String _slugFor(String value) { - final candidate = Uri.tryParse(value); - final source = candidate?.host.isNotEmpty == true - ? candidate!.host + candidate.path - : path.basename(value); - final slug = source - .toLowerCase() - .replaceAll(RegExp(r'[^a-z0-9]+'), '-') - .replaceAll(RegExp(r'^-+|-+$'), ''); - if (slug.isEmpty) return 'inspection'; - return slug.length > 64 ? slug.substring(0, 64) : slug; - } - static String _escape(Object? value) { return const HtmlEscape().convert(value?.toString() ?? ''); } } + +/// File-name-safe slug (`[a-z0-9-]`) for a URL or file name. +String inspectionSlug(String value) { + final candidate = Uri.tryParse(value); + final source = candidate?.host.isNotEmpty == true + ? candidate!.host + candidate.path + : path.basename(value); + final slug = source + .toLowerCase() + .replaceAll(RegExp(r'[^a-z0-9]+'), '-') + .replaceAll(RegExp(r'^-+|-+$'), ''); + if (slug.isEmpty) return 'inspection'; + return slug.length > 64 ? slug.substring(0, 64) : slug; +} 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/lib/widgets/batch_banner.dart b/lib/widgets/batch_banner.dart new file mode 100644 index 0000000..51bb2dc --- /dev/null +++ b/lib/widgets/batch_banner.dart @@ -0,0 +1,56 @@ +import 'package:material_ui/material_ui.dart'; +import 'package:provider/provider.dart'; +import 'package:view_source_vibe/screens/batch_screen.dart'; +import 'package:view_source_vibe/services/batch_runner.dart'; + +/// Progress of a batch above the tab bar; the result links once it is done. +class BatchBanner extends StatelessWidget { + const BatchBanner({super.key}); + + @override + Widget build(BuildContext context) { + final runner = context.watch(); + final String text; + final List actions; + if (runner.running) { + final phase = runner.phase == 'waiting' + ? 'waiting for ${runner.currentPending.join(', ')}' + : runner.phase; + text = 'Batch ${runner.index + 1}/${runner.total}' + ' · ${runner.currentUrl?.host ?? ''}' + '${phase.isEmpty ? '' : ' · $phase'}'; + actions = [ + TextButton(onPressed: runner.cancel, child: const Text('Cancel')) + ]; + } else if (runner.error != null || runner.rows.isNotEmpty) { + text = runner.error != null + ? 'Batch failed: ${runner.error}' + : 'Batch done: ${runner.rows.length} site(s)'; + actions = [ + if (runner.rows.isNotEmpty) + TextButton( + onPressed: () => Navigator.of(context).push(MaterialPageRoute( + builder: (_) => const BatchResultsScreen())), + child: const Text('Results')), + TextButton(onPressed: runner.dismiss, child: const Text('Dismiss')), + ]; + } else { + return const SizedBox.shrink(); + } + final scheme = Theme.of(context).colorScheme; + return Material( + color: scheme.secondaryContainer, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Row(children: [ + Expanded( + child: Text(text, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: scheme.onSecondaryContainer))), + ...actions, + ]), + ), + ); + } +} diff --git a/lib/widgets/toolbar.dart b/lib/widgets/toolbar.dart index 7d29c7d..8a6f2a6 100644 --- a/lib/widgets/toolbar.dart +++ b/lib/widgets/toolbar.dart @@ -8,6 +8,7 @@ import 'package:view_source_vibe/widgets/share_package_dialog.dart'; import 'package:file_picker/file_picker.dart'; import 'package:view_source_vibe/models/inspection/file_snapshot.dart'; import 'package:view_source_vibe/services/collectors/file_loader.dart'; +import 'package:view_source_vibe/screens/batch_screen.dart'; import 'package:view_source_vibe/screens/settings_screen.dart'; import 'package:universal_io/io.dart'; import 'package:flutter/services.dart'; @@ -261,6 +262,12 @@ class Toolbar extends StatelessWidget { ); }, ), + IconButton( + icon: const Icon(CupertinoIcons.list_bullet), + tooltip: 'Batch…', + onPressed: () => Navigator.of(context) + .push(MaterialPageRoute(builder: (_) => const BatchScreen())), + ), IconButton( icon: const Icon(CupertinoIcons.gear), tooltip: 'Settings', diff --git a/test/derive/divergences_test.dart b/test/derive/divergences_test.dart index 96270c7..204d96d 100644 --- a/test/derive/divergences_test.dart +++ b/test/derive/divergences_test.dart @@ -59,6 +59,21 @@ void main() { isEmpty); }); + test('an empty root path and "/" are the same page', () { + expect( + deriveDivergences(inspection( + server: serverSnap(url: 'https://example.com'), + browser: browserSnap(url: 'https://example.com/'))), + isEmpty); + expect( + deriveDivergences(inspection( + server: serverSnap(url: 'https://example.com'), + browser: browserSnap(url: 'https://www.example.com/'))) + .single + .kind, + DivergenceKind.redirectHost); + }); + test('www <-> non-www is a low-severity redirect-host divergence', () { final d = deriveDivergences(inspection( server: serverSnap(url: 'https://a.test/page'), diff --git a/test/derive/inspection_summary_test.dart b/test/derive/inspection_summary_test.dart new file mode 100644 index 0000000..f3a9b8c --- /dev/null +++ b/test/derive/inspection_summary_test.dart @@ -0,0 +1,200 @@ +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'; +import 'fixtures.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, '1 tracker(s) active while Cookiebot is present'); + expect(s.facts['consentTool'], 'Cookiebot'); + }); + + test('advertising cookies are counted, not judged', () { + const url = 'https://ads.test/'; + final s = deriveSummary(inputsFor(inspection( + server: serverSnap( + url: url, setCookies: ['_fbp=1; Secure', '_gcl_au=1; Secure']), + browser: browserSnap(url: url, cookies: const [])))); + final f = s.findings.firstWhere((f) => f.id == 'ad-cookies'); + expect(f.severity, FindingSeverity.medium); + expect(f.title, '2 advertising cookie(s) set'); + }); + + test('a page that did not load is a high finding', () { + final s = deriveSummary(inputsFor(PageInspection( + generation: 1, + target: UrlTarget(Uri.parse('https://dead.test/')), + server: const Failed('Failed host lookup'), + browser: const Unavailable(UnavailableReason.notApplicable, 'none'), + file: const Unavailable(UnavailableReason.notApplicable), + ))); + final f = s.findings.first; + expect(f.id, 'not-loaded'); + expect(f.severity, FindingSeverity.high); + expect(f.title, 'The page did not load'); + expect(f.tab, 'probe'); + }); + + 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); + }); +} 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 { diff --git a/test/services/batch_runner_test.dart b/test/services/batch_runner_test.dart new file mode 100644 index 0000000..a20bb98 --- /dev/null +++ b/test/services/batch_runner_test.dart @@ -0,0 +1,285 @@ +import 'dart:io'; + +import 'package:archive/archive.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:view_source_vibe/models/settings.dart'; +import 'package:view_source_vibe/services/batch_runner.dart'; +import 'package:view_source_vibe/services/html_service.dart'; +import 'package:view_source_vibe/services/inspection_store.dart'; +import '../support/fake_batch_target.dart'; +import 'html_service_lifecycle_test.dart' + show FakeServerFetcher, FakeBrowserLoader, okSnapshot; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory tmp; + const fast = + BatchOptions(timeout: Duration(milliseconds: 50), linger: Duration.zero); + + setUp(() => tmp = Directory.systemTemp.createTempSync('batch_runner_test')); + tearDown(() { + if (tmp.existsSync()) tmp.deleteSync(recursive: true); + }); + + BatchRunner runner(FakeBatchTarget t) => BatchRunner(t, + poll: const Duration(milliseconds: 1), + settle: Duration.zero, + lateWait: Duration.zero, + workDir: () async => tmp); + + test('sites are visited one by one, in order', () async { + final t = FakeBatchTarget(); + final r = runner(t); + await r.run([Uri.parse('https://a.test/'), Uri.parse('https://b.test/')], + options: fast); + expect(t.calls.where((c) => c.startsWith('open')), + ['open https://a.test/', 'open https://b.test/']); + expect(t.calls.indexOf('package https://a.test/'), + lessThan(t.calls.indexOf('open https://b.test/'))); + expect(r.rows.map((x) => x.state), ['done', 'done']); + expect(t.calls.first, 'watchSovereignty true'); + expect(t.calls.last, 'watchSovereignty false'); + expect(t.calls.indexOf('clear https://a.test/'), + lessThan(t.calls.indexOf('open https://a.test/'))); + }); + + test('a site that never settles is exported as timed out', () async { + final t = FakeBatchTarget()..pendingFor['slow.test'] = -1; + final r = runner(t); + await r.run([Uri.parse('https://slow.test/')], options: fast); + final row = r.rows.single; + expect(row.state, 'timed out'); + expect(row.pending, ['sovereignty']); + expect(row.summary, isNotNull); + expect(File('${tmp.path}/sites/${row.slug}.zip').existsSync(), isTrue); + }); + + test('a failing site does not stop the batch', () async { + final t = FakeBatchTarget()..failOpen.add('bad.test'); + final r = runner(t); + await r.run([Uri.parse('https://bad.test/'), Uri.parse('https://ok.test/')], + options: fast); + expect(r.rows.map((x) => x.state), ['failed', 'done']); + expect(r.rows.first.error, contains('cannot open bad.test')); + expect(r.rows.first.summary, isNull); + }); + + test('cancel keeps finished sites', () async { + final t = FakeBatchTarget()..pendingFor['b.test'] = -1; + t.onOpen = (u) { + if (u.host == 'b.test') { + Future.delayed(const Duration(milliseconds: 10), () => cancelNow()); + } + }; + final r = runner(t); + cancelNow = r.cancel; + await r.run([Uri.parse('https://a.test/'), Uri.parse('https://b.test/')], + options: const BatchOptions( + timeout: Duration(seconds: 30), linger: Duration.zero)); + expect(r.rows.length, 1); + expect(r.running, isFalse); + expect(t.calls.last, 'watchSovereignty false'); + expect(await r.writeZip(), isNotNull); + }); + + test('slugs are unique', () async { + final t = FakeBatchTarget(); + final r = runner(t); + await r.run([ + Uri.parse('https://example.com/a'), + Uri.parse('https://example.com/a?x=1'), + ], options: fast); + final slugs = r.rows.map((x) => x.slug).toList(); + expect(slugs[0], isNot(slugs[1])); + expect(slugs[1], endsWith('-2')); + }); + + test('the zip holds the summary and one package per site', () async { + final t = FakeBatchTarget(); + final r = runner(t); + await r.run([Uri.parse('https://a.test/'), Uri.parse('https://b.test/')], + options: fast); + final zip = + ZipDecoder().decodeBytes((await r.writeZip())!.readAsBytesSync()); + expect( + zip.files.map((f) => f.name), + containsAll([ + 'summary.html', + 'summary.csv', + 'summary.json', + 'sites/a-test.zip', + 'sites/b-test.zip' + ])); + }); + + test('writeZip is null when no site finished', () async { + expect(await runner(FakeBatchTarget()).writeZip(), isNull); + }); + + test('a failing work dir ends the run with an error', () async { + final t = FakeBatchTarget(); + final r = BatchRunner(t, workDir: () async => throw StateError('no disk')); + await r.run([Uri.parse('https://a.test/')], options: fast); + expect(r.running, isFalse); + expect(r.error, contains('no disk')); + expect(t.calls.last, 'watchSovereignty false'); + }); + + test('the row summary is the one of the exported package', () async { + final t = FakeBatchTarget()..note = 'at export'; + // The page changes right after the export (e.g. a late request). + t.onPackage = () => Future(() => t.note = 'later'); + final r = runner(t); + await r.run([Uri.parse('https://a.test/')], options: fast); + expect(r.rows.single.summary!.facts['finalUrl'], 'at export'); + }); + + test('state and pending are those at the moment of export', () async { + final t = FakeBatchTarget()..pendingFor['late.test'] = -1; + // Settles after the timeout, during the late collect. + t.onCollectLate = () => t.pendingFor['late.test'] = 0; + final r = runner(t); + await r.run([Uri.parse('https://late.test/')], options: fast); + expect(r.rows.single.state, 'done'); + expect(r.rows.single.pending, isEmpty); + }); + + test('a site that did not load is failed, not clean', () async { + final t = FakeBatchTarget()..notLoaded.add('dead.test'); + final r = runner(t); + await r.run([Uri.parse('https://dead.test/')], options: fast); + expect(r.rows.single.state, 'failed'); + expect(r.rows.single.error, 'the site did not load'); + expect(r.rows.single.summary, isNotNull); + }); + + test('a site that did not load names the server failure', () async { + final t = FakeBatchTarget() + ..notLoaded.add('dead.test') + ..loadFailures['dead.test'] = 'Failed host lookup'; + final r = runner(t); + await r.run([Uri.parse('https://dead.test/')], options: fast); + expect(r.rows.single.state, 'failed'); + expect(r.rows.single.error, 'Failed host lookup'); + }); + + test('navigating away during a site fails that row', () async { + final t = FakeBatchTarget()..navigatedAway.add('a.test'); + final r = runner(t); + await r.run([Uri.parse('https://a.test/'), Uri.parse('https://b.test/')], + options: fast); + expect(r.rows.map((x) => x.state), ['failed', 'done']); + expect(r.rows.first.error, 'navigated away during the batch'); + expect(r.rows.first.summary, isNull); + expect(t.calls, isNot(contains('package https://a.test/'))); + }); + + test('a new run and dismiss remove the previous work directory', () async { + final dirs = []; + final t = FakeBatchTarget(); + final r = BatchRunner(t, + poll: const Duration(milliseconds: 1), + settle: Duration.zero, + lateWait: Duration.zero, + workDir: () async => + (dirs..add(Directory('${tmp.path}/run${dirs.length}'))).last); + await r.run([Uri.parse('https://a.test/')], options: fast); + final zip1 = await r.writeZip(); + final zip2 = await r.writeZip(); + expect(zip2!.path, zip1!.path); + expect(zip1.path, matches(RegExp(r'viewsourcevibe-batch-\d{14}\.zip$'))); + expect(dirs[0].listSync().whereType(), hasLength(1)); + await r.run([Uri.parse('https://b.test/')], options: fast); + expect(dirs[0].existsSync(), isFalse); + expect(dirs[1].existsSync(), isTrue); + r.dismiss(); + expect(dirs[1].existsSync(), isFalse); + }); + + test('a finished scan that failed or checked nothing is not pending', + () async { + final print = debugPrint; + debugPrint = (String? message, {int? wrapWidth}) {}; // the scan failure + addTearDown(() => debugPrint = print); + final fetcher = FakeServerFetcher(); + final service = HtmlService( + store: InspectionStore(), + detectionScanner: (texts) async => throw StateError('scan failed'), + serverFetcher: fetcher, + browserLoader: FakeBrowserLoader(), + metadataExtractor: (html, baseUrl, {headers}) async => {}, + )..setAppSettings(AppSettings()..useBrowserByDefault = false); + addTearDown(service.dispose); + final load = service.loadUrl('https://dead.test/'); + await pumpEventQueue(); + fetcher.pending.single.completeError(const SocketException('no host')); + await load.then((_) {}, onError: (_) {}); + service.detections; + await pumpEventQueue(); + expect(service.detectionsView.scanning, isFalse); + expect(service.detectionsView.complete, isFalse); + expect(pendingAnalyses(service), isNot(contains('detections'))); + }); + + group('HtmlServiceBatchTarget', () { + late FakeServerFetcher fetcher; + late HtmlService service; + late HtmlServiceBatchTarget target; + setUp(() { + fetcher = FakeServerFetcher(); + service = HtmlService( + store: InspectionStore(), + detectionScanner: (texts) async => [], + serverFetcher: fetcher, + browserLoader: FakeBrowserLoader(), + metadataExtractor: (html, baseUrl, {headers}) async => {}, + )..setAppSettings(AppSettings()..useBrowserByDefault = false); + target = HtmlServiceBatchTarget(service); + }); + tearDown(() => service.dispose()); + + test('a dead URL is not loaded and names the failure', () async { + final url = Uri.parse('https://dead.test/'); + final open = target.open(url); + await pumpEventQueue(); + fetcher.pending.single + .completeError(const SocketException('Failed host lookup')); + await open.then((_) {}, onError: (_) {}); + expect(target.loaded(), isFalse); + expect(target.loadFailure(), contains('Failed host lookup')); + }); + + test('a page loaded by the app is loaded and still on its URL', () async { + final url = Uri.parse('https://a.test/'); + final open = target.open(url); + await pumpEventQueue(); + fetcher.pending.single.complete(okSnapshot('https://a.test/', '

')); + await open; + expect(target.loaded(), isTrue); + expect(target.stillOn(url), isTrue); + final other = service.loadUrl('https://b.test/'); + await pumpEventQueue(); + fetcher.pending.last.complete(okSnapshot('https://b.test/', '

')); + await other; + expect(target.stillOn(url), isFalse); + }); + }); + + test('parseBatchInput', () { + final p = parseBatchInput('kvk.nl\n\n# comment\nhttps://kvk.nl/\n' + 'javascript:alert(1)\nfile:///etc/passwd\n http://a.test/x \nnot a url'); + expect( + p.urls.map((u) => u.toString()), ['https://kvk.nl', 'http://a.test/x']); + expect( + p.rejected, ['javascript:alert(1)', 'file:///etc/passwd', 'not a url']); + }); + + test('parseBatchInput caps the list and keeps ports', () { + final p = parseBatchInput('a.test:8080\nb.test\nc.test', max: 2); + expect(p.urls.map((u) => u.toString()), + ['https://a.test:8080', 'https://b.test']); + }); +} + +void Function() cancelNow = () {}; diff --git a/test/services/batch_summary_test.dart b/test/services/batch_summary_test.dart new file mode 100644 index 0000000..869ec4d --- /dev/null +++ b/test/services/batch_summary_test.dart @@ -0,0 +1,79 @@ +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('requestedUrl,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('