zond-engine 0.16.0

The core networking library powering Zond. Raw packet injection, protocol parsing, service and OS fingerprinting, and asynchronous network scanning.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
//
// This file is part of Zond Engine, licensed under the GNU Affero General
// Public License, version 3 or later. See the LICENSE file for details, or
// <https://www.gnu.org/licenses/agpl-3.0.html>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

//! # HTML export
//!
//! The report as a page: one file, opened in a browser, read by a person.
//!
//! ## One file, and nothing outside it
//!
//! The stylesheet is inlined and there is no image, no font, no favicon and no
//! request of any kind to anywhere. A scan report travels as an email attachment,
//! as an artifact on a ticket, as a file on a share, and in each of those a
//! request to a CDN either fails and leaves the reader with unstyled text or
//! succeeds and tells a third party that the report was opened, when, and from
//! which address.
//!
//! ## No JavaScript at all
//!
//! None, not merely none from a third party. The places a security tool's output
//! is read are the places where scripts are blocked: a mail client, a restricted
//! documentation viewer, a browser with strict settings, a reviewer told never to
//! run a page built from an unknown network's data.
//!
//! Two consequences are worth stating. Sorting and filtering the host list are
//! not available; [`csv`](super::csv) exists for the person who wants to sort,
//! and it opens in the tool they would sort with. The light/dark switch is CSS:
//! the system preference decides through `prefers-color-scheme` and the control
//! in the masthead inverts it, with `:has()` doing the work. A browser too old
//! for `:has()` follows the system preference and hides a control that could not
//! have functioned.
//!
//! ## Printing is a first-class output
//!
//! There is no PDF exporter; a PDF crate costs more than a lightweight engine
//! should spend. An `@media print` stylesheet does the job instead, with
//! ink-cheap colours, no control that only exists to be clicked, and no host
//! split across a page boundary. `Ctrl-P` produces the document that goes in the
//! appendix.
//!
//! ## Escaping is the security control here
//!
//! A scan report is full of text the scanned network chose: hostnames, service
//! banners, certificate subjects, script output. Written into a page unescaped, a
//! device named `<script>…</script>` executes on whoever opens the report, the
//! same class of attack the CSV exporter neutralises for spreadsheets.
//!
//! Everything from the report goes through one escaping writer, shared with the
//! comparison page and living in `export::write` so there is one of it. It
//! escapes the five characters that carry markup and renders control characters
//! as their code point: a hostname containing U+202E reverses the text after it,
//! which is how a report is made to display one address while carrying another.
//! No report value is written into an attribute, so the exporter has one escaping
//! context and no way to pick the wrong one.
//!
//! ## What the page says, and what it leaves out
//!
//! The page renders the same [`schema`](super::schema) DTOs the JSON serializes,
//! so the two cannot disagree about a value, an ordering or a name. States,
//! protocols and stop reasons keep their wire spelling, so a reader who greps the
//! JSON for what they saw in the browser finds it.
//!
//! It parts company with the document twice.
//!
//! A field with no value is not shown. The JSON keeps every field so a parser
//! never has to tell absent from empty from unknown; a page spends the reader's
//! attention instead, and a host described by fourteen empty rows is a host
//! nobody reads.
//!
//! Not everything with a value is shown either. What earns a place is what
//! changes how the rest of the page should be read: an idle scan, since the port
//! states were inferred through a third party rather than seen; an evasion
//! profile, since the target answered an unusual packet; what the phase covered
//! and what it could not route to; and which document a phase was folded in from.
//! Instrumentation a consumer would graph stays in the document. A field added to
//! [`schema`](super::schema) faces the same question, and the answer may be no.

use std::borrow::Cow;
use std::fmt::Write as _;
use std::io::Write;
use std::time::SystemTime;

use crate::export::schema::{
    ENGINE_NAME, FindingDto, HostDto, PhaseDto, PortDto, ProbeStatsDto, SCHEMA_VERSION, SummaryDto,
    host_status_name, port_state_name, scan_kind_name, total_elapsed_us,
};
use crate::export::write::{TONE_FOUND, TONE_INERT, TONE_NONE, TONE_PARTIAL, Text, esc};
use crate::export::{ExportError, ExportOptions, Exporter, write};
use crate::format::time::rfc3339;
use crate::model::host::{Host, HostStatus};
use crate::model::port::{Port, PortState};
use crate::report::ScanReport;

/// The heading a report carries when the caller names none.
const DEFAULT_HEADING: &str = "Scan report";

/// How many columns a host's port table has.
const PORT_COLUMNS: usize = 7;

/// The tone a host status is drawn in.
fn host_tone(status: HostStatus) -> &'static str {
    match status {
        HostStatus::Up => TONE_FOUND,
        HostStatus::Filtered => TONE_PARTIAL,
        HostStatus::Down => TONE_INERT,
        HostStatus::Unknown => TONE_NONE,
    }
}

/// The tone a port state is drawn in.
fn port_tone(state: PortState) -> &'static str {
    match state {
        PortState::Open => TONE_FOUND,
        PortState::OpenFiltered
        | PortState::Filtered
        | PortState::Unfiltered
        | PortState::ClosedFiltered => TONE_PARTIAL,
        PortState::Closed => TONE_INERT,
        // The tone a host of unknown status is drawn in, for the same reason:
        // nothing was learned here, and a shade that reads as a finding would
        // give the bar a band that is about the scan rather than the network.
        PortState::Unasked => TONE_NONE,
    }
}

// ---------------------------------------------------------------------------
// The exporter
// ---------------------------------------------------------------------------

/// Writes a report as a single self-contained HTML page.
///
/// ```no_run
/// use std::fs::File;
/// use std::io::BufWriter;
/// use zond_engine::report::ScanReport;
/// use zond_engine::export::{ExportOptions, Exporter, HtmlExporter};
///
/// # fn example(report: &ScanReport) -> Result<(), Box<dyn std::error::Error>> {
/// let mut file = BufWriter::new(File::create("scan.html")?);
/// HtmlExporter::new(ExportOptions::new()).export(report, &mut file)?;
/// # Ok(())
/// # }
/// ```
///
/// The page is written incrementally, in many small writes, so a destination
/// that costs a syscall per write wants a [`BufWriter`] as above.
///
/// [`BufWriter`]: std::io::BufWriter
#[must_use]
#[derive(Debug, Clone, Default)]
pub struct HtmlExporter {
    options: ExportOptions,
    heading: Option<String>,
}

impl HtmlExporter {
    /// An exporter under the given options.
    pub fn new(options: ExportOptions) -> Self {
        Self {
            options,
            heading: None,
        }
    }

    /// Sets the report's heading, which is also the page's title.
    ///
    /// For a front end that knows what the scan was for, such as an engagement
    /// or a change number or a customer, which the engine never does.
    pub fn with_heading(mut self, heading: impl Into<String>) -> Self {
        self.heading = Some(heading.into());
        self
    }

    /// The options in force.
    pub fn options(&self) -> &ExportOptions {
        &self.options
    }

    /// The heading shown on the page.
    fn heading(&self) -> &str {
        self.heading.as_deref().unwrap_or(DEFAULT_HEADING)
    }

    /// The page's title.
    ///
    /// Carries the scan's date when the caller named nothing, because a tab and
    /// a printed page header are where several reports get told apart.
    fn title<'a>(&'a self, started_at: &str) -> Cow<'a, str> {
        match &self.heading {
            Some(heading) => Cow::Borrowed(heading.as_str()),
            None => {
                let day = started_at.split('T').next().unwrap_or(started_at);
                Cow::Owned(format!("zond scan report — {day}"))
            }
        }
    }
}

impl Exporter for HtmlExporter {
    fn export(&self, report: &ScanReport, out: &mut dyn Write) -> Result<(), ExportError> {
        let started_at = rfc3339(report.started_at());
        let generated_at = rfc3339(SystemTime::now());
        let summary = SummaryDto::new(&report.summary());
        let phases: Vec<PhaseDto<'_>> = report
            .phases()
            .iter()
            .map(|phase| PhaseDto::new(phase, &self.options))
            .collect();
        let elapsed_us = total_elapsed_us(&phases);

        write::head(out, &self.title(&started_at))?;
        write_masthead(out, self.heading(), report, &started_at, elapsed_us)?;
        write_notices(out, report, &phases, &self.options)?;
        write_tiles(out, &summary, &phases)?;
        write_distributions(out, &summary)?;
        write_hosts(out, report, &self.options)?;
        write_scan_detail(out, &phases)?;
        write_colophon(out, report, &generated_at)?;

        write::foot(out)?;
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// The document
// ---------------------------------------------------------------------------

/// What produced the findings, where that is not the build that wrote the page.
///
/// The two were once printed as one, which read as `zond-engine nmap 7.94` on a
/// page exported from an imported scan. They are separate facts and the page has
/// room for both, and says nothing extra where the engine that scanned is the
/// engine that wrote.
fn findings_from(report: &ScanReport) -> String {
    if report.engine_version() == crate::report::ENGINE_VERSION {
        return String::new();
    }

    format!(" · findings from {}", Text(report.engine_version()))
}

/// A one-line description of the scan, under the shared masthead.
///
/// The description states no total the schema does not define. A figure that
/// appears nowhere else is a figure nobody can check.
fn write_masthead(
    out: &mut dyn Write,
    heading: &str,
    report: &ScanReport,
    started_at: &str,
    elapsed_us: u64,
) -> Result<(), ExportError> {
    let count = report.phases().len();
    let kinds: Vec<String> = report
        .phases()
        .iter()
        .map(|phase| esc(scan_kind_name(phase.kind())))
        .collect();

    let subtitle = format!(
        "{kinds} · started {started_at} · {elapsed} · {count} {word}",
        kinds = kinds.join(" + "),
        started_at = Text(started_at),
        elapsed = duration(elapsed_us),
        word = plural(count, "phase", "phases"),
    );

    write::masthead(out, heading, &subtitle)
}

/// The things that change how the rest of the page should be read.
///
/// Each is a fact about the report rather than about the network, and each makes
/// the findings mean something other than they appear to: a partial scan did not
/// finish, an unprivileged one saw less, an idle scan never saw a verdict at
/// all, an evasion profile asked the question differently, and a redacted one is
/// not showing everything it knows.
fn write_notices(
    out: &mut dyn Write,
    report: &ScanReport,
    phases: &[PhaseDto<'_>],
    options: &ExportOptions,
) -> Result<(), ExportError> {
    // Only phases this engine measured and found unprivileged. Counting `None`
    // as unprivileged put this engine's advice about raw sockets under another
    // scanner's findings.
    let unprivileged = phases
        .iter()
        .filter(|phase| phase.privileged == Some(false))
        .count();
    let idle = phases
        .iter()
        .any(|phase| phase.settings.idle_scan.is_some());
    let evaded = phases.iter().any(|phase| phase.settings.evasion.is_some());
    // A privileged phase that reached some of its targets by connect, which the
    // count above does not see and which is the same caveat about those targets.
    let connected = phases
        .iter()
        .any(|phase| !phase.reached_by_connect.is_empty());

    if !report.is_partial()
        && unprivileged == 0
        && !connected
        && !idle
        && !evaded
        && !options.redaction.is_active()
    {
        return Ok(());
    }

    writeln!(out, "<p class=\"notices\">")?;

    if idle {
        write::notice(
            out,
            true,
            "idle scan",
            "no port state here was seen directly; each was inferred from a third party's IP identification counter, which a busy zombie makes unreliable",
        )?;
    }
    if evaded {
        write::notice(
            out,
            true,
            "evasion",
            "the probes were altered before they went out, so a state here says how the target answered an unusual packet rather than an ordinary one",
        )?;
    }

    if report.is_partial() {
        write::notice(
            out,
            true,
            "partial",
            "a strategy did not run to completion, so these findings are narrower than the scan asked for",
        )?;
    }
    if unprivileged > 0 {
        write::notice(
            out,
            true,
            "unprivileged",
            "raw probes were unavailable; those targets were reached over plain connect attempts, which see less",
        )?;
    }
    if connected {
        write::notice(
            out,
            true,
            "by connect",
            "some targets were out of reach of this machine's raw probes and were reached over plain connect attempts, which see less; each phase lists them",
        )?;
    }
    if options.redaction.is_active() {
        write::notice(
            out,
            false,
            "redacted",
            "hostnames, hardware addresses and certificate subjects are masked in this copy",
        )?;
    }

    writeln!(out, "</p>")?;
    Ok(())
}

/// The four figures somebody reads before they read anything else.
fn write_tiles(
    out: &mut dyn Write,
    summary: &SummaryDto,
    phases: &[PhaseDto<'_>],
) -> Result<(), ExportError> {
    writeln!(out, "<section class=\"tiles\">")?;

    write::tile(out, summary.hosts_total, "hosts", &ranges_note(phases))?;
    write::tile(
        out,
        summary.hosts_alive,
        "alive",
        &esc("up or filtered — confirmed present"),
    )?;
    write::tile(
        out,
        summary.ports_open,
        "open ports",
        &format!("of {} recorded", summary.ports_total),
    )?;
    write::tile(
        out,
        summary.services_identified,
        "services",
        &esc("identified by fingerprinting"),
    )?;

    writeln!(out, "</section>")?;
    Ok(())
}

/// What the phases covered, as escaped markup, for the hosts tile.
fn ranges_note(phases: &[PhaseDto<'_>]) -> String {
    let ranges: Vec<String> = phases
        .iter()
        .flat_map(|phase| phase.targets.ranges.iter())
        .map(|range| format!("{}–{}", esc(&range.start), esc(&range.end)))
        .collect();

    match ranges.len() {
        0 => String::new(),
        1..=2 => ranges.join(", "),
        count => format!("{}, and {} more", ranges[0], count - 1),
    }
}

/// The two distributions behind the headline figures.
///
/// A stacked meter and a legend listing every category, including the ones
/// nothing landed in, as the JSON summary does. A reader learns something from
/// `filtered: 0` and nothing from a category that is missing.
fn write_distributions(out: &mut dyn Write, summary: &SummaryDto) -> Result<(), ExportError> {
    let statuses = &summary.hosts_by_status;
    let states = &summary.ports_by_state;

    writeln!(out, "<section class=\"distributions\">")?;

    distribution(
        out,
        "Host status",
        summary.hosts_total,
        &[
            status_slice(HostStatus::Up, statuses.up),
            status_slice(HostStatus::Filtered, statuses.filtered),
            status_slice(HostStatus::Down, statuses.down),
            status_slice(HostStatus::Unknown, statuses.unknown),
        ],
    )?;

    distribution(
        out,
        "Port state",
        summary.ports_total,
        &[
            state_slice(PortState::Open, states.open),
            state_slice(PortState::OpenFiltered, states.open_filtered),
            state_slice(PortState::Closed, states.closed),
            state_slice(PortState::Unfiltered, states.unfiltered),
            state_slice(PortState::Filtered, states.filtered),
            state_slice(PortState::ClosedFiltered, states.closed_filtered),
            state_slice(PortState::Unasked, states.unasked),
        ],
    )?;

    writeln!(out, "</section>")?;
    Ok(())
}

/// One category of a distribution: its wire name, its tone, and its count.
struct Slice {
    label: &'static str,
    tone: &'static str,
    count: usize,
}

/// One band of the host-status bar: its label, its tone class, and how many
/// hosts fall in it.
fn status_slice(status: HostStatus, count: usize) -> Slice {
    Slice {
        label: host_status_name(status),
        tone: host_tone(status),
        count,
    }
}

/// [`status_slice`] for port states, which are counted across every host rather
/// than per host.
fn state_slice(state: PortState, count: usize) -> Slice {
    Slice {
        label: port_state_name(state),
        tone: port_tone(state),
        count,
    }
}

/// Writes one proportional bar and its legend.
///
/// The widths are computed from counts, which is why they are the only numbers on
/// this page interpolated into an attribute: a percentage this function derived
/// cannot carry a value the scanned network chose.
fn distribution(
    out: &mut dyn Write,
    title: &str,
    total: usize,
    slices: &[Slice],
) -> Result<(), ExportError> {
    writeln!(
        out,
        "<div class=\"dist\">\n<h2 class=\"dist-title\">{title}</h2>",
        title = Text(title),
    )?;

    let empty = if total == 0 { " meter-empty" } else { "" };
    write!(out, "<div class=\"meter{empty}\">")?;
    for slice in slices.iter().filter(|slice| slice.count > 0) {
        write!(
            out,
            "<span class=\"seg {tone}\" style=\"width:{width:.3}%\"></span>",
            tone = slice.tone,
            width = percent(slice.count, total),
        )?;
    }
    writeln!(out, "</div>\n<ul class=\"legend\">")?;

    for slice in slices {
        let zero = if slice.count == 0 { " legend-zero" } else { "" };
        writeln!(
            out,
            "<li class=\"legend-item{zero}\"><span class=\"swatch {tone}\"></span><span class=\"legend-label\">{label}</span><span class=\"legend-value\">{count}</span></li>",
            tone = slice.tone,
            label = Text(slice.label),
            count = slice.count,
        )?;
    }

    writeln!(out, "</ul>\n</div>")?;
    Ok(())
}

// ---------------------------------------------------------------------------
// Hosts
// ---------------------------------------------------------------------------

/// The hosts section: the heading, the count, and one block per host.
fn write_hosts(
    out: &mut dyn Write,
    report: &ScanReport,
    options: &ExportOptions,
) -> Result<(), ExportError> {
    writeln!(
        out,
        "<section class=\"section\">\n<h2 class=\"section-title\">Hosts <span class=\"section-count\">{count}</span></h2>",
        count = report.host_count(),
    )?;

    if report.host_count() == 0 {
        writeln!(out, "<p class=\"empty\">no hosts recorded</p>")?;
    }

    for host in report.hosts() {
        write_host(out, host, options)?;
    }

    writeln!(out, "</section>")?;
    Ok(())
}

/// One host: its identity, what it was found to be, and its ports.
///
/// Every value below comes through `HostDto`, which is where redaction is applied
/// and where each string is wrapped in the one escaper this page has.
fn write_host(
    out: &mut dyn Write,
    host: &Host,
    options: &ExportOptions,
) -> Result<(), ExportError> {
    let dto = HostDto::new(host, options);

    write!(
        out,
        "<article class=\"host\">\n<header class=\"host-head\"><span class=\"host-ip\">{ip}</span>",
        ip = Text(&dto.primary_ip),
    )?;
    if let Some(hostname) = &dto.hostname {
        write!(out, "<span class=\"host-name\">{}</span>", Text(hostname))?;
    }
    write!(
        out,
        "<span class=\"tag {tone}\">{status}</span>",
        tone = host_tone(host.status()),
        status = Text(dto.status),
    )?;
    for role in &dto.roles {
        write!(out, "<span class=\"tag tag-role\">{}</span>", Text(role))?;
    }
    writeln!(out, "</header>\n<div class=\"host-body\">")?;

    write_host_facts(out, &dto)?;
    write_ports(out, host, &dto)?;

    writeln!(out, "</div>\n</article>")?;
    Ok(())
}

/// Everything known about the host that is not one of its ports.
fn write_host_facts(out: &mut dyn Write, dto: &HostDto<'_>) -> Result<(), ExportError> {
    writeln!(out, "<dl class=\"facts\">")?;

    if !dto.findings.is_empty() {
        let mut findings = String::new();
        write_finding_facts(&mut findings, &dto.findings);
        write!(out, "{findings}")?;
    }

    if dto.ips.len() > 1 {
        let addresses: Vec<String> = dto.ips.iter().map(|ip| esc(ip)).collect();
        fact(out, "addresses", &addresses.join(", "))?;
    }

    if let Some(os) = &dto.os {
        let mut detail = vec![format!("{}% confidence", os.accuracy)];
        if let Some(family) = os.family {
            detail.push(esc(family));
        }
        if let Some(vendor) = os.vendor {
            detail.push(esc(vendor));
        }
        let name = match os.generation {
            Some(generation) => format!("{} {}", esc(os.name), esc(generation)),
            None => esc(os.name),
        };
        fact(out, "os", &format!("{name}{}", dim(&detail)))?;
    }

    if !dto.ip_protocols.is_empty() {
        // The two verdicts a reader acts on. Listing the silent ones as well
        // would put a dozen `open_filtered` rows on every host and bury the two
        // lines that mean something, and silence is what the count says.
        let named = |state: &str| -> Vec<String> {
            dto.ip_protocols
                .iter()
                .filter(|entry| entry.state == state)
                .map(|entry| match entry.name {
                    Some(name) => esc(name),
                    None => entry.protocol.to_string(),
                })
                .collect()
        };

        let accepted = named("open");
        let refused = named("closed");
        let mut detail = Vec::new();
        if !refused.is_empty() {
            detail.push(format!("refuses {}", refused.join(", ")));
        }
        detail.push(format!("{} asked about", dto.ip_protocols.len()));

        let value = match accepted.is_empty() {
            false => accepted.join(", "),
            // Not a failure and worth saying plainly. Most protocols answer an
            // unsolicited header with nothing whether or not the stack
            // implements them, so silence everywhere is the ordinary result.
            true => "none answered".to_string(),
        };
        fact(out, "ip protocols", &format!("{value}{}", dim(&detail)))?;
    }

    if let Some(hardware) = &dto.hardware {
        let mut value = hardware.mac.as_deref().map(esc).unwrap_or_default();
        let mut detail = Vec::new();
        if let Some(vendor) = hardware.vendor {
            detail.push(esc(vendor));
        }
        if hardware.macs.len() > 1 {
            detail.push(format!("{} addresses seen", hardware.macs.len()));
        }
        value.push_str(&dim(&detail));
        fact(out, "hardware", &value)?;
    }

    let telemetry = &dto.telemetry;
    if let Some(median) = telemetry.rtt_median_us {
        let mut detail = Vec::new();
        if let (Some(min), Some(max)) = (telemetry.rtt_min_us, telemetry.rtt_max_us) {
            detail.push(format!("{} – {}", duration(min), duration(max)));
        }
        if let Some(jitter) = telemetry.jitter_us {
            detail.push(format!("jitter {}", duration(jitter)));
        }
        detail.push(format!(
            "{} {}",
            telemetry.samples,
            plural(telemetry.samples, "sample", "samples")
        ));
        fact(
            out,
            "rtt",
            &format!("{} median{}", duration(median), dim(&detail)),
        )?;
    }

    if !dto.path.is_empty() {
        // One line per router, distance first, so a gap where a router declined
        // to answer reads as a gap rather than as a shorter path. An inherited
        // hop says so: it is a claim about a router this host never met. A
        // withheld one is not a gap, since its router answered, so it reads as
        // what it is rather than as the `*` of a router that stayed quiet.
        let mut path = String::new();
        for hop in &dto.path {
            let address = match hop.address.as_deref() {
                Some(address) => address,
                None if hop.withheld => "excluded",
                None => "*",
            };
            let mut detail = Vec::new();
            if let Some(rtt) = hop.rtt_us {
                detail.push(duration(rtt));
            }
            if hop.inferred {
                detail.push("from another trace".to_string());
            }
            let _ = write!(
                path,
                "<div>{:>2}. {}{}</div>",
                hop.distance,
                esc(address),
                dim(&detail)
            );
        }
        fact(out, "path", &path)?;
    }

    // Who sent a piece of evidence qualifies it: a middlebox's word about a host
    // is not the host's own, and a page that dropped the difference would
    // present one as the other. A withheld sender says so rather than reading
    // as the host.
    let mut evidence = String::new();
    for reason in &dto.reasons {
        let mut detail: Vec<String> = reason.details.map(esc).into_iter().collect();
        match &reason.source_ip {
            Some(source) => detail.push(format!("via {}", esc(source))),
            None if reason.source_withheld => detail.push("via an excluded address".to_owned()),
            None => {}
        }
        let _ = write!(
            evidence,
            "<div>{}{}</div>",
            Text(&reason.protocol),
            dim(&detail)
        );
    }
    fact(out, "evidence", &evidence)?;

    fact(
        out,
        "seen",
        &format!(
            "{}{}",
            esc(&dto.first_seen),
            dim(&[format!("last {}", esc(&dto.last_seen))])
        ),
    )?;

    writeln!(out, "</dl>")?;
    Ok(())
}

/// A host's port table, or the line that says it has none.
fn write_ports(out: &mut dyn Write, host: &Host, dto: &HostDto<'_>) -> Result<(), ExportError> {
    if dto.ports.is_empty() {
        writeln!(out, "<p class=\"empty\">no ports recorded</p>")?;
        return Ok(());
    }

    writeln!(
        out,
        "<div class=\"scroll\">\n<table class=\"table\">\n<thead><tr><th>port</th><th>state</th><th>service</th><th>product</th><th>version</th><th class=\"num\">rtt</th><th>evidence</th></tr></thead>\n<tbody>"
    )?;

    // `HostDto` builds its ports from the host's, in order, so the two are one
    // sequence. Pairing them lets a row carry the document's values and take its
    // colour from the state itself.
    for (port, port_dto) in host.ports().zip(dto.ports.iter()) {
        debug_assert_eq!(
            port.number(),
            port_dto.port,
            "the rendered ports and the host's ports have diverged"
        );
        write_port(out, port, port_dto)?;
    }

    writeln!(out, "</tbody>\n</table>\n</div>")?;
    Ok(())
}

/// One row of a host's port table, and the detail block that expands under it.
fn write_port(out: &mut dyn Write, port: &Port, dto: &PortDto<'_>) -> Result<(), ExportError> {
    let service = dto.service.as_ref();
    let discovery = dto.discovery.as_ref();

    write!(
        out,
        "<tr><td class=\"mono\">{number}/{protocol}</td><td><span class=\"tag {tone}\">{state}</span></td>",
        number = dto.port,
        protocol = Text(dto.protocol),
        tone = port_tone(port.state()),
        state = Text(dto.state),
    )?;

    write!(
        out,
        "<td>{}</td>",
        service.map(|service| esc(service.name)).unwrap_or_default()
    )?;
    write!(
        out,
        "<td>{}</td>",
        service
            .and_then(|service| service.product)
            .map(esc)
            .unwrap_or_default()
    )?;

    let version = service
        .map(|service| {
            let mut text = service.version.map(esc).unwrap_or_default();
            if let Some(extra) = service.extrainfo {
                text.push_str(&dim(&[esc(extra)]));
            }
            text
        })
        .unwrap_or_default();
    write!(out, "<td>{version}</td>")?;

    write!(
        out,
        "<td class=\"num\">{}</td>",
        discovery
            .and_then(|discovery| discovery.rtt_us)
            .map(duration)
            .unwrap_or_default()
    )?;
    writeln!(
        out,
        "<td>{}</td></tr>",
        discovery
            .map(|discovery| esc(&discovery.reason))
            .unwrap_or_default()
    )?;

    write_port_detail(out, dto)
}

/// Appends a subject's findings to a fact list, worst-first.
///
/// Every attacker-influenced field it shows, meaning the title, the excerpt, the
/// remediation and any URL reference, is written as element content through
/// [`Text`] or [`esc`] and never into an attribute, so a markup-bearing banner is
/// inert on the page. The classes it reuses are the stylesheet's own, which the
/// class-name test holds it to.
fn write_finding_facts(facts: &mut String, findings: &[FindingDto<'_>]) {
    for finding in findings {
        let mut detail = vec![Text(finding.confidence).to_string()];
        if !finding.references.is_empty() {
            let references: Vec<String> =
                finding.references.iter().map(|r| esc(&r.value)).collect();
            detail.push(references.join(", "));
        }
        let _ = write!(
            facts,
            "<dt>{severity}</dt><dd>{title}{detail}",
            severity = Text(finding.severity),
            title = Text(finding.title),
            detail = dim(&detail),
        );
        if let Some(excerpt) = finding.excerpt {
            let _ = write!(facts, "<div class=\"mono\">{}</div>", Text(excerpt));
        }
        if let Some(remediation) = finding.remediation {
            let _ = write!(facts, "<div>{}</div>", Text(remediation));
        }
        facts.push_str("</dd>");
    }
}

/// The second row a port gets when there is more to say than fits in a column.
fn write_port_detail(out: &mut dyn Write, dto: &PortDto<'_>) -> Result<(), ExportError> {
    let mut facts = String::new();

    // Findings lead. The worst thing about a port is the first thing to read.
    write_finding_facts(&mut facts, &dto.findings);

    if let Some(service) = &dto.service {
        let cpes: Vec<String> = service.cpes.iter().map(|cpe| esc(cpe)).collect();
        let _ = write!(
            facts,
            "<dt>service</dt><dd>{}% confidence{}</dd>",
            service.confidence,
            dim(&[cpes.join(", ")])
        );
    }

    if let Some(security) = &dto.security {
        let mut detail = Vec::new();
        if let Some(cipher) = security.cipher_suite {
            detail.push(esc(cipher));
        }
        if !security.alpn.is_empty() {
            let alpn: Vec<String> = security.alpn.iter().map(|name| esc(name)).collect();
            detail.push(alpn.join(" "));
        }
        let _ = write!(
            facts,
            "<dt>tls</dt><dd>{}{}</dd>",
            security.tls_version.map(esc).unwrap_or_default(),
            dim(&detail)
        );

        // What the endpoint accepts, which is the finding a single negotiated
        // version cannot carry: one line per version, worst suite first, so a
        // reader scanning the page sees the withdrawn version and the broken
        // cipher without opening anything.
        for accepted in &security.accepts {
            let mut detail = Vec::new();
            if accepted.deprecated {
                detail.push(esc("withdrawn"));
            }
            let insecure = accepted
                .suites
                .iter()
                .filter(|suite| suite.strength != "strong")
                .count();
            if insecure > 0 {
                detail.push(format!(
                    "{insecure} of {} below strong",
                    accepted.suites.len()
                ));
            }
            if !accepted.unrecognised.is_empty() {
                detail.push(format!("{} unnamed", accepted.unrecognised.len()));
            }
            // A walk cut short found a floor, and a reader comparing two
            // endpoints has to know which of their lists is one.
            if let Some(unfinished) = security
                .unfinished
                .iter()
                .find(|unfinished| unfinished.version == accepted.version)
            {
                detail.push(format!("incomplete, {}", esc(unfinished.interruption)));
            }

            let suites: Vec<String> = accepted
                .suites
                .iter()
                .map(|suite| match suite.faults.is_empty() {
                    true => esc(suite.name),
                    false => format!("{} ({})", esc(suite.name), esc(&suite.faults.join(", "))),
                })
                .collect();

            let _ = write!(
                facts,
                "<dt>accepts</dt><dd>{}{}<br>{}</dd>",
                esc(accepted.version),
                dim(&detail),
                dim(&[suites.join(" · ")])
            );
        }

        // A version whose walk ended before the endpoint said anything about
        // it is neither accepted nor refused, and a page that left it out would
        // be read as the second.
        for unfinished in security.unfinished.iter().filter(|unfinished| {
            !security
                .accepts
                .iter()
                .any(|accepted| accepted.version == unfinished.version)
        }) {
            let _ = write!(
                facts,
                "<dt>unsettled</dt><dd>{}{}</dd>",
                esc(unfinished.version),
                dim(&[esc(unfinished.interruption)])
            );
        }

        if let Some(certificate) = &security.certificate {
            let mut detail = vec![format!("issued by {}", esc(certificate.issuer))];
            if !certificate.sans.is_empty() {
                let sans: Vec<String> = certificate.sans.iter().map(|san| esc(san)).collect();
                detail.push(format!("also {}", sans.join(", ")));
            }
            detail.push(format!(
                "{} {}-bit",
                esc(certificate.pubkey_type),
                certificate.pubkey_bits
            ));

            let _ = write!(
                facts,
                "<dt>certificate</dt><dd>{}{}</dd>",
                esc(&certificate.common_name),
                dim(&detail)
            );
            let _ = write!(
                facts,
                "<dt>validity</dt><dd>{} – {}</dd>",
                esc(&certificate.validity_start),
                esc(&certificate.validity_end)
            );
            let _ = write!(
                facts,
                "<dt>fingerprint</dt><dd>{}</dd>",
                esc(certificate.fingerprint_sha256)
            );
        }
    }

    if let Some(discovery) = &dto.discovery {
        let mut detail = Vec::new();
        if let Some(ttl) = discovery.ttl {
            detail.push(format!("ttl {ttl}"));
        }
        if let Some(source) = &discovery.source_ip {
            detail.push(format!("answered on {}", esc(source)));
        }
        let _ = write!(
            facts,
            "<dt>probe</dt><dd>{}{}</dd>",
            esc(&discovery.timestamp),
            dim(&detail)
        );
    }

    if facts.is_empty() {
        return Ok(());
    }

    writeln!(
        out,
        "<tr class=\"port-detail\"><td colspan=\"{PORT_COLUMNS}\"><dl class=\"facts\">{facts}</dl></td></tr>"
    )?;
    Ok(())
}

// ---------------------------------------------------------------------------
// Scan detail
// ---------------------------------------------------------------------------

/// What the scan did, as opposed to what it found.
///
/// Last on the page rather than first, since a reader opens a report for the
/// hosts. This is the section that says how far the host list can be trusted.
fn write_scan_detail(out: &mut dyn Write, phases: &[PhaseDto<'_>]) -> Result<(), ExportError> {
    writeln!(
        out,
        "<section class=\"section\">\n<h2 class=\"section-title\">Scan detail <span class=\"section-count\">{count} {word}</span></h2>",
        count = phases.len(),
        word = plural(phases.len(), "phase", "phases"),
    )?;

    for phase in phases {
        write_phase(out, phase)?;
    }

    writeln!(out, "</section>")?;
    Ok(())
}

/// One phase: what it covered, what it ran under, what failed, and what each
/// scanner in it sent and saw.
///
/// The longest writer on the page, because a phase is the part of the report that
/// says whether its own silence is evidence.
fn write_phase(out: &mut dyn Write, phase: &PhaseDto<'_>) -> Result<(), ExportError> {
    let privilege = match phase.privileged {
        Some(true) => "privileged",
        Some(false) => "unprivileged",
        // Three states, because a phase read out of another scanner's document
        // is not a phase that ran unprivileged.
        None => "privilege not recorded",
    };

    writeln!(
        out,
        "<article class=\"phase\">\n<header class=\"phase-head\"><span class=\"phase-kind\">{kind}</span><span class=\"dim\">{started} · {elapsed} · {privilege}</span></header>\n<dl class=\"facts\">",
        kind = Text(phase.kind),
        started = Text(&phase.started_at),
        elapsed = duration(phase.elapsed_us),
    )?;

    let scope = &phase.targets;
    let mut targets = vec![format!(
        "{} {}",
        esc(&scope.addresses),
        plural_str(&scope.addresses, "address", "addresses")
    )];
    if let Some(probes) = &scope.probes {
        targets.push(format!(
            "{} {}",
            esc(probes),
            plural_str(probes, "probe", "probes")
        ));
    }
    if !scope.protocols.is_empty() {
        targets.push(scope.protocols.join(", "));
    }
    fact(out, "targets", &targets.join(" · "))?;

    let ranges: Vec<String> = scope
        .ranges
        .iter()
        .map(|range| format!("{}–{}", esc(&range.start), esc(&range.end)))
        .collect();
    fact(out, "ranges", &ranges.join("<br>"))?;

    // A sweep of a segment reaches every host on it, which is coverage no range
    // expresses. Listening reaches nothing, since a machine quiet during the
    // window is indistinguishable from one that is not there, so the two are
    // separate rows.
    if !scope.links.is_empty() {
        let links: Vec<String> = scope.links.iter().map(|name| esc(name)).collect();
        fact(out, "links swept", &links.join(", "))?;
    }
    if !scope.listened.is_empty() {
        let listened: Vec<String> = scope.listened.iter().map(|name| esc(name)).collect();
        fact(
            out,
            "links listened on",
            &format!(
                "{}{}",
                listened.join(", "),
                dim(&[esc("not coverage: silence here is not absence")])
            ),
        )?;
    }

    // Which ports were walked, and whether the same ones for every address.
    // Without it, a port absent from a host could be closed or unasked.
    if let Some(ports) = &scope.ports {
        let spec = if ports.spec.is_empty() {
            String::new()
        } else {
            dim(&[esc(&ports.spec)])
        };
        fact(out, "ports", &format!("{}{spec}", esc(ports.kind)))?;
    }

    // Only when a policy was set. "excluded: nothing" on every report trains a
    // reader to skip the row on the one where it says something.
    if !scope.excluded.is_empty() {
        let excluded: Vec<String> = scope
            .excluded
            .iter()
            .map(|range| format!("{}–{}", esc(&range.start), esc(&range.end)))
            .collect();
        fact(
            out,
            "excluded",
            &format!(
                "{}<br><span class=\"dim\">{} {} withheld</span>",
                excluded.join("<br>"),
                esc(&scope.withheld),
                plural_str(&scope.withheld, "address", "addresses"),
            ),
        )?;
    }

    let retry = &phase.settings.retry;
    let mut budget = vec![esc(retry.effort)];
    if let Some(attempts) = retry.max_attempts {
        budget.push(format!("{attempts} attempts"));
    }
    if let Some(scale) = retry.timeout_scale {
        budget.push(format!("timeout ×{scale}"));
    }
    if retry.dampen_silent_hosts {
        budget.push("silent hosts dampened".to_string());
    }
    fact(out, "retry", &budget.join(" · "))?;

    let settings = &phase.settings;
    // Both bounds or neither, named as bounds rather than as one rate. A page
    // saying "500 probes/s" where a floor was set reads as the pace the scan
    // ran at, which is the one thing a bound never promises.
    let rate = match (settings.min_probe_rate, settings.max_probe_rate) {
        (Some(min), Some(max)) => format!("min {min} · max {max} probes/s"),
        (Some(min), None) => format!("min {min} probes/s"),
        (None, Some(max)) => format!("max {max} probes/s"),
        (None, None) => "scanner default rate".to_string(),
    };
    let dns = if settings.dns_enabled {
        "dns enabled"
    } else {
        "dns disabled"
    };
    // The two wall-clock bounds, on their own line rather than folded into the
    // wire fact: each of them is a reason the page below may be short, and a
    // reader working out why a host has three ports should not have to find
    // that at the end of a run-on sentence about send modes.
    let bounds: Vec<String> = [
        settings
            .host_timeout_us
            .map(|us| format!("per host {}", duration(us))),
        settings
            .scan_timeout_us
            .map(|us| format!("whole scan {}", duration(us))),
        // A gap, not a budget, and it belongs on this line anyway: it is the
        // third reason the page below may have taken as long as it did.
        settings
            .host_probe_interval_us
            .map(|us| format!("{} between probes at one host", duration(us))),
    ]
    .into_iter()
    .flatten()
    .collect();
    // The technique leads: `closed` from a SYN scan and `closed` from a FIN
    // scan are different findings, and the port table means nothing without it.
    fact(
        out,
        "wire",
        &format!(
            "{} · sctp {} · send {} · {rate} · {dns} · os {} · service {} · detection {}",
            esc(settings.tcp_technique),
            esc(settings.sctp_technique),
            esc(settings.send_mode),
            esc(settings.os_detection),
            esc(settings.service_detection),
            esc(settings.detection),
        ),
    )?;

    if !bounds.is_empty() {
        fact(out, "time limit", &bounds.join(" · "))?;
    }

    // The two settings that change what a state means, repeated from the notice
    // at the top because that notice was about every phase and a reader who has
    // scrolled this far is looking at one.
    if let Some(idle) = &settings.idle_scan {
        let port = idle
            .zombie_port
            .map(|port| format!("port {port}"))
            .unwrap_or_default();
        fact(
            out,
            "idle scan",
            &format!(
                "{}{}",
                esc(&idle.zombie),
                dim(&[port, esc("states inferred, not seen")])
            ),
        )?;
    }
    if let Some(evasion) = &settings.evasion {
        fact(out, "evasion", &evasion_detail(evasion))?;
    }

    // Addresses the caller named that nothing was sent to. No probe left this
    // machine for them, so the report says nothing about what is there.
    if !phase.unroutable.is_empty() {
        let addresses: Vec<String> = phase.unroutable.iter().map(|ip| esc(ip)).collect();
        fact(
            out,
            "no route",
            &format!(
                "{}{}",
                addresses.join(", "),
                dim(&[esc("named, never probed")])
            ),
        )?;
    }

    // Addresses the scan started on and left before it had finished. Their
    // ports are on the page carrying the scan's silence verdict, so without
    // this line they read as quiet machines.
    if !phase.timed_out.is_empty() {
        let addresses: Vec<String> = phase.timed_out.iter().map(|ip| esc(ip)).collect();
        fact(
            out,
            "out of time",
            &format!(
                "{}{}",
                addresses.join(", "),
                dim(&[esc("left part-scanned")])
            ),
        )?;
    }

    // Addresses a privileged phase reached the unprivileged way. Their results
    // sit beside raw ones under a phase headed privileged, and this line is
    // what tells the two apart.
    if !phase.reached_by_connect.is_empty() {
        let ranges: Vec<String> = phase
            .reached_by_connect
            .iter()
            .map(|range| match range.start == range.end {
                true => esc(&range.start),
                false => format!("{}–{}", esc(&range.start), esc(&range.end)),
            })
            .collect();
        fact(
            out,
            "by connect",
            &format!(
                "{}{}",
                ranges.join(", "),
                dim(&[esc("out of reach of raw probes")])
            ),
        )?;
    }

    // For a merged report: which document this phase came out of. Without it a
    // page shows one scan's phases beside another's with nothing to tell them
    // apart.
    if let Some(origin) = &phase.origin {
        let label = origin.label.map(esc).into_iter().collect::<Vec<_>>();
        fact(
            out,
            "read from",
            &format!("{}{}", esc(origin.engine_version), dim(&label)),
        )?;
    }

    writeln!(out, "</dl>")?;

    write_attachments(out, &phase.attachments)?;

    if !phase.failures.is_empty() {
        writeln!(
            out,
            "<div class=\"block\">\n<div class=\"block-title\">failures</div>\n<div class=\"scroll\">\n<table class=\"table\">\n<thead><tr><th>scanner</th><th>reason</th><th>at</th></tr></thead>\n<tbody>"
        )?;
        for failure in &phase.failures {
            writeln!(
                out,
                "<tr><td class=\"mono\">{scanner}</td><td>{reason}</td><td class=\"mono\">{at}</td></tr>",
                scanner = Text(failure.scanner),
                reason = Text(failure.reason),
                at = Text(&failure.at),
            )?;
        }
        writeln!(out, "</tbody>\n</table>\n</div>\n</div>")?;
    }

    for stats in &phase.probe_stats {
        write_probe_stats(out, stats)?;
    }

    writeln!(out, "</article>")?;
    Ok(())
}

/// What a scan changed about the packets it sent, as one line.
///
/// Every field is present only for a technique the scan used, so what this
/// renders is the profile and nothing about the ones it did not touch.
fn evasion_detail(evasion: &crate::export::schema::EvasionDto) -> String {
    let mut parts: Vec<String> = Vec::new();

    if let Some(port) = evasion.source_port {
        parts.push(format!("from port {port}"));
    }
    if let Some(ttl) = evasion.ttl {
        parts.push(format!("ttl {ttl}"));
    }
    if let Some(padding) = evasion.padding {
        parts.push(format!("{padding} bytes of padding"));
    }
    if evasion.bad_tcp_checksum {
        parts.push("wrong TCP checksum".to_string());
    }
    if let Some(mac) = &evasion.spoof_mac {
        parts.push(format!("spoofing {}", esc(mac)));
    }
    if let Some(bytes) = evasion.fragment {
        parts.push(format!("fragmented to {bytes} bytes"));
    }
    if let Some(flags) = &evasion.flags {
        parts.push(format!("flags {}", esc(flags)));
    }
    if !evasion.decoys.is_empty() {
        let decoys: Vec<String> = evasion.decoys.iter().map(|ip| esc(ip)).collect();
        parts.push(format!("decoys {}", decoys.join(", ")));
    }

    parts.join(" · ")
}

/// Where the machine that ran this phase was plugged in.
///
/// A finding of its own rather than a row among the settings. It says nothing
/// about any host and everything about where the scan was standing when it
/// looked, which the host list cannot answer. Empty on an unmanaged network, and
/// never a claim that the machine is attached to nothing.
fn write_attachments(
    out: &mut dyn Write,
    attachments: &[crate::export::schema::AttachmentDto<'_>],
) -> Result<(), ExportError> {
    if attachments.is_empty() {
        return Ok(());
    }

    writeln!(
        out,
        "<div class=\"block\">\n<div class=\"block-title\">where this ran from</div>\n<div class=\"scroll\">\n<table class=\"table\">\n<thead><tr><th>link</th><th>device</th><th>port</th><th>vlan</th><th>seen</th></tr></thead>\n<tbody>"
    )?;

    for attachment in attachments {
        let device = match (&attachment.device_name, &attachment.device_mac) {
            (Some(name), Some(mac)) => format!("{}{}", Text(name), dim(&[esc(mac)])),
            (Some(name), None) => Text(name).to_string(),
            (None, Some(mac)) => esc(mac),
            (None, None) => String::new(),
        };

        writeln!(
            out,
            "<tr><td class=\"mono\">{link}</td><td>{device}{source}</td><td class=\"mono\">{port}</td><td class=\"num\">{vlan}</td><td class=\"mono\">{seen}</td></tr>",
            link = Text(attachment.link),
            source = dim(&[esc(attachment.source)]),
            port = attachment.port.map(esc).unwrap_or_default(),
            vlan = attachment
                .native_vlan
                .map(|vlan| vlan.to_string())
                .unwrap_or_default(),
            seen = Text(&attachment.observed_at),
        )?;
    }

    writeln!(out, "</tbody>\n</table>\n</div>\n</div>")?;
    Ok(())
}

/// What one scanner observed about its own run.
fn write_probe_stats(out: &mut dyn Write, stats: &ProbeStatsDto) -> Result<(), ExportError> {
    writeln!(
        out,
        "<div class=\"block\">\n<div class=\"block-title\">{scanner} · {targets} targets</div>\n<dl class=\"facts\">",
        scanner = Text(stats.scanner),
        targets = Text(&stats.targets),
    )?;

    let completion = if stats.complete {
        "finished what it had to do"
    } else {
        "cut short"
    };
    fact(
        out,
        "stopped",
        &format!(
            "{}{}",
            esc(stats.stop_reason),
            dim(&[
                esc(completion),
                format!("after {}", duration(stats.elapsed_us)),
            ])
        ),
    )?;

    let mut sends = vec![format!("{} attempted", stats.sends_attempted)];
    if stats.sends_failed > 0 {
        sends.push(format!("{} refused by the sender", stats.sends_failed));
    }
    fact(out, "probes", &sends.join(" · "))?;

    let mut seen = vec![format!("{} seen", stats.segments_seen)];
    if stats.segments_off_target > 0 {
        seen.push(format!("{} off target", stats.segments_off_target));
    }
    if stats.replies_without_rtt > 0 {
        seen.push(format!(
            "{} without a round trip",
            stats.replies_without_rtt
        ));
    }
    fact(out, "segments", &seen.join(" · "))?;

    let mut timing = Vec::new();
    if let Some(first) = stats.first_reply_us {
        timing.push(format!("first at {}", duration(first)));
    }
    if let Some(last) = stats.last_reply_us {
        timing.push(format!("last at {}", duration(last)));
    }
    fact(
        out,
        "hosts found",
        &format!("{}{}", stats.hosts_found, dim(&timing)),
    )?;

    if let Some(capture) = &stats.capture {
        let mut counts = vec![format!("{} received", capture.received)];
        if capture.dropped > 0 {
            counts.push(format!("{} dropped by the buffer", capture.dropped));
        }
        if capture.if_dropped > 0 {
            counts.push(format!("{} dropped by the interface", capture.if_dropped));
        }
        // Last, and phrased as a link rather than a number, because it is the
        // one entry here that says the counts beside it describe less of the
        // network than they look like they do.
        if capture.stopped_early > 0 {
            counts.push(match capture.stopped_early {
                1 => "one capture stopped early and heard nothing after".to_string(),
                many => format!("{many} captures stopped early and heard nothing after"),
            });
        }
        fact(out, "capture", &counts.join(" · "))?;
    }

    writeln!(out, "</dl>")?;

    let attempts: Vec<(String, u64)> = stats
        .answered_on
        .iter()
        .map(|entry| {
            let label = if entry.or_later {
                format!("{}+", entry.attempt)
            } else {
                entry.attempt.to_string()
            };
            (label, entry.count)
        })
        .collect();
    histogram(
        out,
        "hosts by attempt",
        &attempts,
        stats.answered_unattributed,
    )?;

    let buckets: Vec<(String, u64)> = stats
        .found_at
        .iter()
        .map(|bucket| {
            let label = match bucket.le_ms {
                Some(bound) => format!("≤ {bound} ms"),
                None => "slower".to_string(),
            };
            (label, bucket.count)
        })
        .collect();
    histogram(out, "hosts by discovery time", &buckets, 0)?;

    writeln!(out, "</div>")?;
    Ok(())
}

/// A row of labelled counts, drawn as bars against the largest of them.
///
/// Against the largest rather than the total. One bucket usually holds nearly
/// everything, and scaling to the total draws the rest as invisible lines.
fn histogram(
    out: &mut dyn Write,
    title: &str,
    rows: &[(String, u64)],
    unattributed: u64,
) -> Result<(), ExportError> {
    let peak = rows.iter().map(|(_, count)| *count).max().unwrap_or(0);
    if peak == 0 && unattributed == 0 {
        return Ok(());
    }

    writeln!(
        out,
        "<div class=\"block-title\">{title}</div>\n<table class=\"hist\">\n<tbody>",
        title = Text(title),
    )?;

    for (label, count) in rows {
        histogram_row(out, label, *count, peak)?;
    }
    if unattributed > 0 {
        histogram_row(out, "unmatched", unattributed, peak)?;
    }

    writeln!(out, "</tbody>\n</table>")?;
    Ok(())
}

/// One bar of a histogram, scaled against the tallest in it. A `peak` of zero
/// draws an empty bar rather than dividing by it.
fn histogram_row(
    out: &mut dyn Write,
    label: &str,
    count: u64,
    peak: u64,
) -> Result<(), ExportError> {
    let width = if peak == 0 {
        0.0
    } else {
        count as f64 * 100.0 / peak as f64
    };
    let zero = if count == 0 { " bar-zero" } else { "" };

    writeln!(
        out,
        "<tr><th>{label}</th><td><span class=\"bar-track\"><span class=\"bar{zero}\" style=\"width:{width:.3}%\"></span></span></td><td class=\"num\">{count}</td></tr>",
        label = Text(label),
    )?;
    Ok(())
}

// ---------------------------------------------------------------------------
// Colophon
// ---------------------------------------------------------------------------

/// The footer: which engine wrote the page, against which schema, and when.
///
/// The engine attribution is a value on a merged report, taken from whatever
/// wrote the document that was folded in, so it is escaped like any other string
/// the page did not author.
fn write_colophon(
    out: &mut dyn Write,
    report: &ScanReport,
    generated_at: &str,
) -> Result<(), ExportError> {
    writeln!(
        out,
        r#"<footer class="colophon">
<div>{engine} {version}{findings} · schema {schema} · generated {generated}</div>
<div>self-contained: no scripts, no external requests</div>
</footer>"#,
        engine = ENGINE_NAME,
        version = crate::report::ENGINE_VERSION,
        findings = findings_from(report),
        schema = SCHEMA_VERSION,
        generated = Text(generated_at),
    )?;
    Ok(())
}

// ---------------------------------------------------------------------------
// Rendering helpers
// ---------------------------------------------------------------------------

/// One label/value row of a fact list. `value` is markup the caller escaped.
///
/// A row with nothing in it is not written, which is the difference between this
/// page and the document it renders.
fn fact(out: &mut dyn Write, key: &str, value: &str) -> Result<(), ExportError> {
    if value.is_empty() {
        return Ok(());
    }
    writeln!(out, "<dt>{key}</dt><dd>{value}</dd>", key = Text(key))?;
    Ok(())
}

/// The secondary half of a value: present, but not what the eye should land on.
///
/// Renders to nothing at all when there is nothing to say, so a caller can
/// append it unconditionally.
fn dim(parts: &[String]) -> String {
    let parts: Vec<&str> = parts
        .iter()
        .map(String::as_str)
        .filter(|part| !part.is_empty())
        .collect();

    if parts.is_empty() {
        return String::new();
    }
    format!(" <span class=\"dim\">{}</span>", parts.join(" · "))
}

/// Renders microseconds the way somebody reads them.
///
/// The document keeps every duration in microseconds so a machine never has to
/// guess a unit. A person reading `677669 µs` has to do arithmetic to learn the
/// scan took two thirds of a second, so the page does it for them, to three
/// significant figures.
fn duration(micros: u64) -> String {
    match micros {
        0..1_000 => format!("{micros} µs"),
        1_000..1_000_000 => format!("{:.2} ms", micros as f64 / 1_000.0),
        1_000_000..60_000_000 => format!("{:.2} s", micros as f64 / 1_000_000.0),
        _ => {
            let seconds = micros / 1_000_000;
            format!("{} min {} s", seconds / 60, seconds % 60)
        }
    }
}

/// A share of a whole, as a percentage. Nothing of nothing is nothing.
fn percent(part: usize, total: usize) -> f64 {
    if total == 0 {
        return 0.0;
    }
    part as f64 * 100.0 / total as f64
}

/// Picks a noun's form for a count.
fn plural(count: usize, one: &'static str, many: &'static str) -> &'static str {
    if count == 1 { one } else { many }
}

/// Picks a noun's form for a count too large for a `usize`: the address and probe
/// totals, which are decimal strings because an IPv6 sweep's does not fit
/// anything narrower.
fn plural_str(count: &str, one: &'static str, many: &'static str) -> &'static str {
    if count == "1" { one } else { many }
}

// ╔════════════════════════════════════════════╗
// ║ ████████╗███████╗███████╗████████╗███████╗ ║
// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
// ║    ██║   ███████╗███████║   ██║   ███████║ ║
// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
// ╚════════════════════════════════════════════╝

#[cfg(test)]
mod tests {
    use super::*;
    use crate::export::write::STYLE;
    use crate::export::{Redaction, fixture};

    fn page(exporter: &HtmlExporter) -> String {
        let mut bytes = Vec::new();
        exporter
            .export(&fixture::report(), &mut bytes)
            .expect("the export succeeds");
        String::from_utf8(bytes).expect("utf-8")
    }

    fn default_page() -> String {
        page(&HtmlExporter::new(ExportOptions::new()))
    }

    /// Every class the exporter wrote, in the order it wrote them.
    fn classes(page: &str) -> Vec<String> {
        let mut found = Vec::new();
        let mut rest = page;

        while let Some(start) = rest.find("class=\"") {
            rest = &rest[start + "class=\"".len()..];
            let end = rest.find('"').expect("an unterminated class attribute");
            for class in rest[..end].split_whitespace() {
                found.push(class.to_string());
            }
            rest = &rest[end..];
        }
        found
    }

    /// What a browser needs before it will render anything at all, and the
    /// property that makes this format worth having.
    #[test]
    fn the_page_is_one_self_contained_document() {
        let page = default_page();

        assert!(page.starts_with("<!doctype html>"));
        assert!(page.trim_end().ends_with("</html>"));
        assert!(page.contains("<meta charset=\"utf-8\">"));

        for outside in ["<script", "http://", "https://", "<img", "@import", "url("] {
            assert!(
                !page.contains(outside),
                "the page reaches outside itself: {outside}"
            );
        }
    }

    /// A class the stylesheet does not define renders as nothing, and the file
    /// that would have said so is not this one.
    #[test]
    fn every_class_written_is_a_class_the_stylesheet_styles() {
        for class in classes(&default_page()) {
            assert!(
                STYLE.contains(&format!(".{class}")),
                "nothing styles .{class}"
            );
        }
    }

    /// The tones are where a new enum variant could reach the page unstyled. The
    /// compiler checks the match; nothing checks that the stylesheet kept up.
    #[test]
    fn every_state_has_a_tone_the_stylesheet_defines() {
        let statuses = [
            HostStatus::Up,
            HostStatus::Filtered,
            HostStatus::Down,
            HostStatus::Unknown,
        ];
        let states = [
            PortState::Open,
            PortState::OpenFiltered,
            PortState::Closed,
            PortState::Unfiltered,
            PortState::Filtered,
            PortState::ClosedFiltered,
        ];

        for status in statuses {
            let tone = host_tone(status);
            assert!(
                STYLE.contains(&format!(".{tone}")),
                "nothing styles .{tone}"
            );
        }
        for state in states {
            let tone = port_tone(state);
            assert!(
                STYLE.contains(&format!(".{tone}")),
                "nothing styles .{tone}"
            );
        }
    }

    /// The findings, in the places a reader looks for them.
    #[test]
    fn the_page_shows_what_the_scan_found() {
        let page = default_page();

        assert!(page.contains("203.0.113.1"));
        assert!(page.contains("router.local"));
        assert!(page.contains("22/tcp"));
        assert!(page.contains("OpenSSH"));
        assert!(page.contains("8.9p1"));
        assert!(page.contains("Raspberry Pi Trading Ltd"));
        // The certificate, whose subject is the one field on a port that names
        // a machine.
        assert!(page.contains("Local CA"));
        // The instrumentation, without which a sweep that ran out of time reads
        // exactly like one that finished.
        assert!(page.contains("deadline_expired"));
        assert!(page.contains("raw socket unavailable"));
    }

    /// The facts that change what a state on this page means have to be on the
    /// page.
    ///
    /// The page renders a subset of the document on purpose, and that subset was
    /// drawn before several of these fields existed. An idle scan and an evasion
    /// profile both change what every port state underneath them says, and
    /// neither reached the page.
    #[test]
    fn what_changes_the_meaning_of_a_state_reaches_the_page() {
        let page = default_page();

        for expected in [
            // The two notices, at the top where they are read first.
            "idle scan",
            "evasion",
            "inferred from a third party",
            "altered before they went out",
            // And the per-phase detail, for a reader who has scrolled to one.
            "detection ",
            "where this ran from",
        ] {
            assert!(page.contains(expected), "the page never says {expected:?}");
        }
    }

    /// A router whose address was withheld reads as excluded, and not as the
    /// `*` of a router that stayed quiet: that one answered, and a page drawing
    /// it as silence would say it had not.
    #[test]
    fn a_withheld_router_is_not_drawn_as_silence() {
        let page = default_page();

        assert!(page.contains("<div> 4. excluded"), "{page}");
        assert!(
            page.contains("<div> 2. *"),
            "a silent router still reads as one"
        );
    }

    /// Evidence a middlebox sent names it, and evidence from a withheld one
    /// says it came second-hand. Drawn bare, either would read as the host
    /// answering for itself, which is the claim neither makes.
    #[test]
    fn second_hand_evidence_says_who_sent_it() {
        let page = default_page();

        assert!(
            page.contains("unreachable, from the path · via 198.51.100.1"),
            "{page}"
        );
        assert!(
            page.contains("unreachable · via an excluded address"),
            "{page}"
        );
    }

    /// An enumeration that did not finish says so beside what it found.
    ///
    /// Without it, a version the endpoint stopped answering about reads as one
    /// it refused, and a list of suites cut short reads as the whole of them.
    #[test]
    fn an_unfinished_enumeration_says_so_on_the_page() {
        let page = default_page();

        assert!(
            page.contains("<dt>unsettled</dt><dd>TLSv1.1"),
            "a version never settled is named"
        );
        assert!(
            page.contains("incomplete, stopped"),
            "an accepted version whose walk was cut short says so"
        );
    }

    /// A phase that did none of it says none of it, or the notices become a band
    /// every report carries and nobody reads.
    #[test]
    fn an_ordinary_scan_carries_none_of_those_notices() {
        let mut plain = Vec::new();
        HtmlExporter::new(ExportOptions::new())
            .export(&crate::export::fixture::compared().0, &mut plain)
            .expect("the page writes");
        let page = String::from_utf8(plain).expect("valid UTF-8");

        assert!(!page.contains("idle scan"));
        assert!(!page.contains("altered before they went out"));
        assert!(!page.contains("where this ran from"));
    }

    /// A report that is narrower than the scan asked for has to say so where
    /// somebody will see it, which means above the findings.
    #[test]
    fn a_narrowed_report_says_so_before_the_findings() {
        let page = default_page();
        let notice = page.find(">partial<").expect("a partial notice");
        let hosts = page.find("Hosts <span").expect("a host section");

        assert!(notice < hosts, "the notice sits below the findings");
    }

    /// States keep the spelling the JSON gives them, so a reader who greps the
    /// document for what the page showed them finds it.
    #[test]
    fn states_are_spelled_the_way_the_document_spells_them() {
        let page = default_page();

        assert!(page.contains(">open<"));
        assert!(page.contains(">up<"));
        assert!(page.contains(">filtered<"));
        assert!(page.contains(">tcp_syn_ack<"));
    }

    /// Redaction is chosen when the report is written, and the page has to
    /// honour it everywhere the JSON does.
    #[test]
    fn redaction_reaches_the_page() {
        let page = page(&HtmlExporter::new(
            ExportOptions::new().with_redaction(Redaction::Standard),
        ));

        assert!(!page.contains("router.local"));
        assert!(page.contains("roXXXXXal"));
        assert!(page.contains("2c:cf:67:XX:XX:XX"));
        // The vendor comes from the OUI, which masking preserves.
        assert!(page.contains("Raspberry Pi Trading Ltd"));
        // And the reader is told this copy is masked.
        assert!(page.contains(">redacted<"));
    }

    /// A discovery sweep finds hosts and no ports. The host still has to appear,
    /// saying there was nothing on it.
    #[test]
    fn a_host_with_no_ports_still_appears() {
        let page = default_page();

        assert!(page.contains("203.0.113.9"));
        assert!(page.contains("no ports recorded"));
    }

    #[test]
    fn a_caller_can_name_the_report() {
        let page = page(&HtmlExporter::new(ExportOptions::new()).with_heading("Acme Q3 audit"));

        assert!(page.contains("<title>Acme Q3 audit</title>"));
        assert!(page.contains("<h1>Acme Q3 audit</h1>"));
        assert!(default_page().contains("<title>zond scan report — "));
    }

    #[test]
    fn durations_are_rendered_for_a_person() {
        assert_eq!(duration(0), "0 µs");
        assert_eq!(duration(999), "999 µs");
        assert_eq!(duration(1_450), "1.45 ms");
        assert_eq!(duration(677_669), "677.67 ms");
        assert_eq!(duration(1_500_000), "1.50 s");
        assert_eq!(duration(3_723_000_000), "62 min 3 s");
    }

    #[test]
    fn a_share_of_nothing_is_not_a_division_by_zero() {
        assert_eq!(percent(0, 0), 0.0);
        assert_eq!(percent(1, 4), 25.0);
    }

    #[test]
    fn a_failing_destination_surfaces_as_an_error() {
        struct Full;

        impl Write for Full {
            fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
                Err(std::io::Error::new(
                    std::io::ErrorKind::StorageFull,
                    "no space left on device",
                ))
            }

            fn flush(&mut self) -> std::io::Result<()> {
                Ok(())
            }
        }

        let error = HtmlExporter::new(ExportOptions::new())
            .export(&fixture::report(), &mut Full)
            .expect_err("a full disk fails the export");

        assert!(matches!(error, ExportError::Io(_)), "got {error:?}");
    }

    /// Every attacker-controlled string in a report reaches the page escaped,
    /// not only the hostname somebody thought to write a test for.
    ///
    /// The two above check that `esc` escapes. Neither would notice a new
    /// `PortDto` field written straight into the markup, since neither renders a
    /// page. This one puts one payload in every string the schema carries,
    /// renders the whole document, and asserts the payload never survives intact.
    ///
    /// What it cannot catch is a field the fixture does not set, so a string
    /// added to the schema has to reach
    /// [`fixture::hostile`](crate::export::fixture::hostile) too.
    #[test]
    fn no_field_of_a_hostile_report_reaches_the_page_unescaped() {
        let mut bytes = Vec::new();
        HtmlExporter::new(ExportOptions::new())
            .export(&fixture::hostile(), &mut bytes)
            .expect("the page renders");
        let page = String::from_utf8(bytes).expect("utf-8");

        assert!(
            page.contains("&lt;script&gt;"),
            "the payload should be present, escaped - otherwise this test proves \
             nothing about a document that simply dropped it"
        );
        assert!(
            !page.contains("<script>"),
            "a scanned host's own banner opened a script tag in the report"
        );
        assert!(
            !page.contains(fixture::HOSTILE),
            "the payload survived intact somewhere on the page"
        );
        // The bidi override reorders everything after it and is invisible while
        // doing so, which is the whole reason it is neutralized rather than
        // merely escaped.
        assert!(
            !page.contains('\u{202e}'),
            "a right-to-left override reached the page and will reorder it"
        );
    }
}