vcon-server 0.4.15

Stores vCons encrypted at rest, on local disk or in an S3 bucket (as objects or Parquet files), and returns them to authorized readers.
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
//! The masked view of a vCon (`GET /vcons/{uuid}?view=masked`, and
//! `?view=masked` on the two legal reads): what it holds, without any name,
//! subject, full number, address or content, so a client can show a vCon
//! before anyone reveals a part of it.
//!
//! THIS MODULE IS THE ONE RULE. The console and the terminal UI both show
//! the view the server makes here; neither makes a summary of its own.
//! tests/data/masked-cases.json holds the cases the rule is tested against
//! here, and console-tests/tests/masked-view.spec.js shows each case's
//! summary through the console's display. A change to the rule is a change
//! to the cases.
//!
//! The view also lists the recordings the console plays (`recordings`), so
//! the console offers Play without receiving any content; their types and
//! size limit are the console player's (console/format.js), held equal by
//! tests here.
//!
//! The parts a reveal shows (`section`, `links`) are ported here from
//! console/format.js, for the terminal UI, which shows a reveal as the
//! console does.

use base64::engine::DecodePaddingMode;
use base64::engine::general_purpose::{GeneralPurpose, GeneralPurposeConfig};
use base64::{Engine, alphabet};
use serde::{Deserialize, Serialize, Serializer};
use serde_json::{Map, Value};
use time::{Date, Month, PrimitiveDateTime, Time, UtcOffset};

use crate::query::{self, BadQuery};
use crate::reveal::Part;

/// The query parameter that asks a read for a view of the vCon.
pub const PARAMETER: &str = "view";

/// The one view there is: the vCon masked.
pub const MASKED: &str = "masked";

/// Whether a read's query asks for the masked view. A query that does not
/// name the parameter is the read it always was.
///
/// # Errors
///
/// [`BadQuery`] if the query names the parameter and it is not exactly
/// `view=masked`, alone and once.
pub fn from_query(query: Option<&str>) -> Result<bool, BadQuery> {
    if !query::names(query, PARAMETER) {
        return Ok(false);
    }
    let read = query::pairs(query, &[PARAMETER])?;
    match read.get(PARAMETER).map(String::as_str) {
        Some(MASKED) => Ok(true),
        _ => Err(BadQuery),
    }
}

/// The form of each kind of body, and what the subject of an unread one is.
const UNSIGNED: &str = "unsigned";
const SIGNED: &str = "signed (JWS)";
const ENCRYPTED: &str = "encrypted (JWE)";
const NOT_JSON: &str = "not JSON";
const NOT_OBJECT: &str = "not a JSON object";
const NOT_READABLE: &str = "not readable";

/// The dialog types the vCon format names; any other is not shown.
const DIALOG_TYPES: [&str; 4] = ["recording", "text", "transfer", "incomplete"];

/// The fewest digits a number needs before its last four may be shown.
const MASKABLE_DIGITS: usize = 8;

/// The encodings under which a body is media, not text to read.
const MEDIA_ENCODINGS: [&str; 2] = ["base64url", "base64"];

/// The parts of a vCon that may hold a link, and what one item is called.
const LINKED: [(&str, &str); 3] = [
    ("dialog", "dialog"),
    ("attachments", "attachment"),
    ("analysis", "analysis"),
];

/// Base64url as a browser's `atob` reads it: no padding needed, and bits
/// after the last whole byte ignored.
const FORGIVING: GeneralPurpose = GeneralPurpose::new(
    &alphabet::URL_SAFE,
    GeneralPurposeConfig::new()
        .with_decode_padding_mode(DecodePaddingMode::Indifferent)
        .with_decode_allow_trailing_bits(true),
);

/// A value's items when it is an array, or none.
fn items(value: Option<&Value>) -> &[Value] {
    value.and_then(Value::as_array).map_or(&[], Vec::as_slice)
}

/// A field of an object when it is text.
fn text_field<'a>(object: &'a Map<String, Value>, name: &str) -> Option<&'a str> {
    object.get(name).and_then(Value::as_str)
}

/// Base64url JSON as an object, or none when it is anything else. A
/// leading byte order mark is dropped, as a browser's text decoder drops it.
fn decoded(value: Option<&Value>) -> Option<Map<String, Value>> {
    let text = value?.as_str()?;
    if text.is_empty()
        || !text
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
    {
        return None;
    }
    let bytes = FORGIVING.decode(text).ok()?;
    let text = std::str::from_utf8(&bytes).ok()?;
    match serde_json::from_str(text.strip_prefix('\u{feff}').unwrap_or(text)).ok()? {
        Value::Object(object) => Some(object),
        _ => None,
    }
}

/// The vCon object a body holds, for reading its parts: the body itself,
/// or a signed vCon's payload. None for an encrypted vCon and for anything
/// that is not a JSON object.
fn readable(text: &str) -> Option<Map<String, Value>> {
    let Ok(Value::Object(vcon)) = serde_json::from_str::<Value>(text) else {
        return None;
    };
    if vcon.contains_key("ciphertext") {
        return None;
    }
    if vcon.contains_key("payload") && vcon.contains_key("signatures") {
        return decoded(vcon.get("payload"));
    }
    Some(vcon)
}

/// A summary of nothing, in the given form.
fn empty(form: &str, subject: &str) -> Summary {
    Summary {
        form: form.to_owned(),
        created: String::new(),
        subject: subject.to_owned(),
        parties: Vec::new(),
        dialogs: 0,
        dialog: Vec::new(),
        seconds: 0.0,
        attachments: 0,
        analyses: 0,
        links: 0,
        signature: None,
        recordings: Vec::new(),
    }
}

/// The counts and masked parties of an unsigned vCon object.
fn counted(vcon: &Map<String, Value>, form: &str) -> Summary {
    let dialog = items(vcon.get("dialog"));
    let seconds = dialog
        .iter()
        .filter_map(|d| d.get("duration").and_then(Value::as_f64))
        .filter(|duration| *duration > 0.0)
        .fold(0.0, |sum, duration| sum + duration);
    let subject = match text_field(vcon, "subject") {
        Some(subject) if !subject.is_empty() => "present, hidden",
        _ => "none",
    };
    Summary {
        form: form.to_owned(),
        created: vcon.get("created_at").map(instant).unwrap_or_default(),
        subject: subject.to_owned(),
        parties: items(vcon.get("parties"))
            .iter()
            .enumerate()
            .map(|(index, party)| party_line(party, index))
            .collect(),
        dialogs: dialog.len(),
        dialog: dialog
            .iter()
            .enumerate()
            .map(|(index, d)| dialog_line(d, index))
            .collect(),
        seconds,
        attachments: items(vcon.get("attachments")).len(),
        analyses: items(vcon.get("analysis")).len(),
        links: links_of(vcon).len(),
        signature: None,
        recordings: recordings_within(vcon, AUDIO_LIMIT),
    }
}

/// Every link in a vCon object, with where it is.
fn links_of(vcon: &Map<String, Value>) -> Vec<Link> {
    let mut found = Vec::new();
    for (part, noun) in LINKED {
        for (index, item) in items(vcon.get(part)).iter().enumerate() {
            if let Some(url) = item.as_object().and_then(|item| text_field(item, "url"))
                && !url.is_empty()
            {
                found.push(Link {
                    place: format!("{noun} {}", index.saturating_add(1)),
                    url: url.to_owned(),
                });
            }
        }
    }
    found
}

/// A vCon's form and counts, its parties masked: the answer of the masked
/// view, with the fields and the words of the console's summary.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Summary {
    /// `unsigned`, `signed (JWS)`, `encrypted (JWE)`, `not JSON` or `not a
    /// JSON object`.
    pub form: String,
    /// When it was made, in UTC (see [`instant`]); empty when not a time.
    pub created: String,
    /// `present, hidden`, `none`, or `not readable`.
    pub subject: String,
    /// One line for each party, masked (see [`party_line`]).
    pub parties: Vec<String>,
    /// How many dialogs it holds.
    pub dialogs: usize,
    /// One line for each dialog, with no content (see [`dialog_line`]).
    pub dialog: Vec<String>,
    /// The sum of the dialogs' positive lengths, in seconds.
    #[serde(serialize_with = "as_js_number")]
    pub seconds: f64,
    /// How many attachments it holds.
    pub attachments: usize,
    /// How many analyses it holds.
    pub analyses: usize,
    /// How many links to outside the server it holds.
    pub links: usize,
    /// A signed vCon's first signature header, else none.
    pub signature: Option<Signature>,
    /// The dialogs that hold, inside the vCon, a recording of a type in
    /// [`AUDIO_TYPES`] or [`AUDIO_ALIASES`] and of at most [`AUDIO_LIMIT`]
    /// bytes: the recordings the console plays.
    #[serde(default)]
    pub recordings: Vec<Recording>,
}

/// A recording the console plays: the dialog that holds it, counted from
/// one, and the type it plays as, one of [`AUDIO_TYPES`]. No text of the
/// vCon is in it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Recording {
    /// The dialog's number, counted from one.
    pub dialog: usize,
    /// The type it plays as.
    #[serde(rename = "type")]
    pub r#type: String,
}

/// The most bytes of one recording the console plays: 100 MiB, as
/// `AUDIO_LIMIT` in console/format.js.
pub const AUDIO_LIMIT: u64 = 100 * 1024 * 1024;

/// The audio types the console plays, as `AUDIO_TYPES` in
/// console/format.js.
pub const AUDIO_TYPES: [&str; 4] = ["audio/wav", "audio/mpeg", "audio/ogg", "audio/opus"];

/// Other names producers give the types the console plays, each with the
/// type it is a name for, as `AUDIO_ALIASES` in console/format.js.
pub const AUDIO_ALIASES: [(&str, &str); 6] = [
    ("audio/x-wav", "audio/wav"),
    ("audio/wave", "audio/wav"),
    ("audio/vnd.wave", "audio/wav"),
    ("audio/x-mp3", "audio/mpeg"),
    ("audio/mp3", "audio/mpeg"),
    ("audio/x-ogg", "audio/ogg"),
];

/// The dialogs of `vcon` that hold, inside the vCon, a recording the
/// console plays, of at most `limit` bytes, read without decoding any, as
/// `offered` in console/format.js reads them before a Play.
fn recordings_within(vcon: &Map<String, Value>, limit: u64) -> Vec<Recording> {
    items(vcon.get("dialog"))
        .iter()
        .enumerate()
        .filter_map(|(index, dialog)| {
            let played = played_within(dialog.as_object()?, limit)?;
            Some(Recording {
                dialog: index + 1,
                r#type: played.to_owned(),
            })
        })
        .collect()
}

/// The type a dialog's recording plays as, when the dialog holds, inside
/// the vCon, an encoded recording of a type the console plays and of at
/// most `limit` bytes; else none.
fn played_within(dialog: &Map<String, Value>, limit: u64) -> Option<&'static str> {
    let body = dialog
        .get("body")?
        .as_str()
        .filter(|body| !body.is_empty())?;
    let encoding = dialog.get("encoding")?.as_str()?;
    if !MEDIA_ENCODINGS.contains(&encoding) {
        return None;
    }
    // As format.js: `mediatype` when the dialog names it, else `mimetype`,
    // the name older vCons use; without its parameters, in lower case.
    let declared = match dialog.get("mediatype") {
        Some(named) => named,
        None => dialog.get("mimetype")?,
    };
    let declared = declared
        .as_str()?
        .split(';')
        .next()
        .unwrap_or_default()
        .trim_matches(trimmed_by_javascript)
        .to_lowercase();
    let played = AUDIO_TYPES
        .into_iter()
        .find(|known| *known == declared)
        .or_else(|| {
            AUDIO_ALIASES
                .into_iter()
                .find(|(name, _)| *name == declared)
                .map(|(_, played)| played)
        })?;
    // The size format.js counts: three bytes for each four characters
    // (UTF-16 code units) of the body without its padding.
    let characters = body.trim_end_matches('=').encode_utf16().count() as u64;
    (characters * 3 / 4 <= limit).then_some(played)
}

/// The fields of a signature's protected header the view names; each is
/// empty when the header does not hold it as text.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Signature {
    /// The signing algorithm, such as `ES256`.
    pub alg: String,
    /// The id of the signing key.
    pub kid: String,
    /// The thumbprint of the signing certificate.
    pub x5t: String,
}

/// A number as JSON writes it in JavaScript: a whole number without a
/// fraction, so `30` and not `30.0`.
fn as_js_number<S: Serializer>(value: &f64, to: S) -> Result<S::Ok, S::Error> {
    /// Below this every whole number is exact in a JavaScript number.
    const EXACT: f64 = 9_007_199_254_740_992.0;
    if value.fract() == 0.0 && value.abs() < EXACT {
        // The value is whole and within the exact range, so the
        // conversion keeps it.
        #[expect(clippy::cast_possible_truncation, reason = "whole and below 2^53")]
        to.serialize_i64(*value as i64)
    } else {
        to.serialize_f64(*value)
    }
}

/// A body as the text a browser reads from it: UTF-8, any byte that is not
/// replaced, and a leading byte order mark dropped.
#[must_use]
pub fn text_of(body: &[u8]) -> String {
    let text = String::from_utf8_lossy(body);
    text.strip_prefix('\u{feff}').unwrap_or(&text).to_owned()
}

/// What a vCon body holds, without any name, subject, full number or
/// address: its form, counts and masked parties. A signed vCon's payload is
/// read; an encrypted one is not decoded.
#[must_use]
pub fn summary(text: &str) -> Summary {
    let Ok(value) = serde_json::from_str::<Value>(text) else {
        return empty(NOT_JSON, NOT_READABLE);
    };
    let Value::Object(vcon) = value else {
        return empty(NOT_OBJECT, NOT_READABLE);
    };
    if vcon.contains_key("ciphertext") {
        return empty(ENCRYPTED, NOT_READABLE);
    }
    if vcon.contains_key("payload") && vcon.contains_key("signatures") {
        let header = items(vcon.get("signatures"))
            .first()
            .and_then(Value::as_object)
            .and_then(|first| decoded(first.get("protected")));
        let field = |name: &str| {
            header
                .as_ref()
                .and_then(|header| text_field(header, name))
                .unwrap_or_default()
                .to_owned()
        };
        let mut made = decoded(vcon.get("payload")).map_or_else(
            || empty(SIGNED, NOT_READABLE),
            |payload| counted(&payload, SIGNED),
        );
        made.signature = Some(Signature {
            alg: field("alg"),
            kid: field("kid"),
            x5t: field("x5t"),
        });
        return made;
    }
    counted(&vcon, UNSIGNED)
}

/// The numbers of an RFC 3339 date-time, `YYYY-MM-DDTHH:MM:SS`, any
/// fraction, then `Z` or `+HH:MM`/`-HH:MM` (either letter in either case):
/// year, month, day, hour, minute, second and the offset in minutes. None
/// for text of any other shape.
fn date_time_numbers(text: &str) -> Option<([u16; 6], i32)> {
    let bytes = text.as_bytes();
    let number = |from: usize, to: usize| -> Option<u16> {
        let digits = bytes.get(from..to)?;
        digits
            .iter()
            .all(u8::is_ascii_digit)
            .then(|| std::str::from_utf8(digits).ok()?.parse().ok())?
    };
    let at = |index: usize, wanted: &[u8]| bytes.get(index).is_some_and(|b| wanted.contains(b));
    if !(at(4, b"-") && at(7, b"-") && at(10, b"Tt") && at(13, b":") && at(16, b":")) {
        return None;
    }
    let fields = [
        number(0, 4)?,
        number(5, 7)?,
        number(8, 10)?,
        number(11, 13)?,
        number(14, 16)?,
        number(17, 19)?,
    ];
    let mut rest = 19;
    if at(rest, b".") {
        let digits = bytes
            .get(rest.saturating_add(1)..)?
            .iter()
            .take_while(|b| b.is_ascii_digit())
            .count();
        if digits == 0 {
            return None;
        }
        rest = rest.saturating_add(1).saturating_add(digits);
    }
    let zone = bytes.get(rest..)?;
    let offset = match zone {
        [b'Z' | b'z'] => 0,
        [sign @ (b'+' | b'-'), _, _, b':', _, _] => {
            let hours = number(rest.saturating_add(1), rest.saturating_add(3))?;
            let minutes = number(rest.saturating_add(4), rest.saturating_add(6))?;
            if hours > 23 || minutes > 59 {
                return None;
            }
            let minutes = i32::from(hours) * 60 + i32::from(minutes);
            if *sign == b'-' { -minutes } else { minutes }
        }
        _ => return None,
    };
    Some((fields, offset))
}

/// A vCon's time as `YYYY-MM-DD HH:MM:SS UTC+00:00`, or empty when it is
/// not an RFC 3339 date-time of a day that exists, in the years 1 to 9999
/// once in UTC. Text that is not a time is never shown.
#[must_use]
pub fn instant(value: &Value) -> String {
    let read = || {
        let (fields, offset) = date_time_numbers(value.as_str()?)?;
        let [year, month, day, hour, minute, second] = fields;
        let date = Date::from_calendar_date(
            i32::from(year),
            Month::try_from(u8::try_from(month).ok()?).ok()?,
            u8::try_from(day).ok()?,
        )
        .ok()?;
        let time = Time::from_hms(
            u8::try_from(hour).ok()?,
            u8::try_from(minute).ok()?,
            u8::try_from(second).ok()?,
        )
        .ok()?;
        let offset = UtcOffset::from_whole_seconds(offset.checked_mul(60)?).ok()?;
        let at = PrimitiveDateTime::new(date, time)
            .assume_offset(offset)
            .checked_to_offset(UtcOffset::UTC)?;
        (1..=9999).contains(&at.year()).then(|| {
            format!(
                "{:04}-{:02}-{:02} {:02}:{:02}:{:02} UTC+00:00",
                at.year(),
                u8::from(at.month()),
                at.day(),
                at.hour(),
                at.minute(),
                at.second()
            )
        })
    };
    read().unwrap_or_default()
}

/// A telephone number as its last four digits, or hidden whole.
#[must_use]
pub fn mask_tel(value: &Value) -> String {
    let digits: Vec<char> = value
        .as_str()
        .unwrap_or_default()
        .chars()
        .filter(char::is_ascii_digit)
        .collect();
    match digits.len().checked_sub(4) {
        Some(from) if digits.len() >= MASKABLE_DIGITS => {
            let last: String = digits.get(from..).unwrap_or_default().iter().collect();
            format!("number ending {last}")
        }
        _ => "number hidden".to_owned(),
    }
}

/// Whether JavaScript's `trim` removes `c`: its white space and line
/// terminators, the byte order mark among them.
fn trimmed_by_javascript(c: char) -> bool {
    matches!(
        c,
        '\u{9}'..='\u{d}'
            | ' '
            | '\u{a0}'
            | '\u{1680}'
            | '\u{2000}'..='\u{200a}'
            | '\u{2028}'
            | '\u{2029}'
            | '\u{202f}'
            | '\u{205f}'
            | '\u{3000}'
            | '\u{feff}'
    )
}

/// An email address as its domain, or hidden whole.
#[must_use]
pub fn mask_mail(value: &Value) -> String {
    let Some(address) = value.as_str() else {
        return "address hidden".to_owned();
    };
    match address.rfind('@') {
        Some(at) if at > 0 => {
            let domain = address
                .get(at.saturating_add(1)..)
                .unwrap_or_default()
                .trim_matches(trimmed_by_javascript)
                .to_lowercase();
            if domain.is_empty() {
                "address hidden".to_owned()
            } else {
                format!("address at {domain}")
            }
        }
        _ => "address hidden".to_owned(),
    }
}

/// Party `index` (from 0) as a line that names what it holds and shows none
/// of it.
#[must_use]
pub fn party_line(party: &Value, index: usize) -> String {
    let label = format!("Party {}", index.saturating_add(1));
    let Some(party) = party.as_object() else {
        return format!("{label}: not an object");
    };
    let mut parts = Vec::new();
    if let Some(tel) = party.get("tel") {
        parts.push(mask_tel(tel));
    }
    if let Some(mailto) = party.get("mailto") {
        parts.push(mask_mail(mailto));
    }
    if party.contains_key("name") {
        parts.push("name hidden".to_owned());
    }
    if parts.is_empty() {
        format!("{label}: no number, address or name")
    } else {
        format!("{label}: {}", parts.join("; "))
    }
}

/// A value as a party's place in the parties list, if it is one: a whole
/// number, zero or more.
fn place(value: &Value) -> Option<f64> {
    value
        .as_f64()
        .filter(|number| number.fract() == 0.0 && *number >= 0.0)
}

/// A dialog's parties as their numbers, counted from one.
fn parties_of(parties: Option<&Value>) -> String {
    if let Some(one) = parties.and_then(place) {
        return format!("party {}", js_number(one + 1.0));
    }
    let places: Option<Vec<f64>> = parties
        .and_then(Value::as_array)
        .filter(|list| !list.is_empty())
        .and_then(|list| list.iter().map(place).collect());
    match places {
        Some(places) => {
            let numbers: Vec<String> = places.iter().map(|p| js_number(p + 1.0)).collect();
            format!("parties {}", numbers.join(", "))
        }
        None => "no parties".to_owned(),
    }
}

/// Dialog `index` (from 0) as a line with its type, start, length and
/// parties, and whether it has content, never the content or a link.
#[must_use]
pub fn dialog_line(dialog: &Value, index: usize) -> String {
    let label = format!("Dialog {}", index.saturating_add(1));
    let Some(dialog) = dialog.as_object() else {
        return format!("{label}: not an object");
    };
    let kind = text_field(dialog, "type")
        .filter(|kind| DIALOG_TYPES.contains(kind))
        .unwrap_or("other type");
    let start = dialog.get("start").map(instant).unwrap_or_default();
    let start = if start.is_empty() { "no start" } else { &start };
    let length = dialog
        .get("duration")
        .and_then(Value::as_f64)
        .filter(|duration| *duration > 0.0)
        .map_or_else(|| "no length".to_owned(), |d| format!("{} s", js_number(d)));
    let present = |name: &str| text_field(dialog, name).is_some_and(|text| !text.is_empty());
    let content = if present("body") {
        "content hidden"
    } else if present("url") {
        "content at a link outside the server"
    } else {
        "no content"
    };
    format!(
        "{label}: {kind}, {start}, {length}, {}; {content}",
        parties_of(dialog.get("parties"))
    )
}

/// A number as JavaScript writes it in text: `30`, `12.5`, `1e+21`.
#[must_use]
pub fn js_number(value: f64) -> String {
    if value == 0.0 {
        return "0".to_owned();
    }
    let size = value.abs();
    if size >= 1e21 || size < 1e-6 {
        let written = format!("{value:e}");
        return match written.split_once('e') {
            Some((digits, power)) if !power.starts_with('-') => format!("{digits}e+{power}"),
            _ => written,
        };
    }
    format!("{value}")
}

/// A link of a vCon: where it is (`dialog 1`, `attachment 2`, `analysis
/// 3`) and the address, which is never loaded.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Link {
    /// Where the link is, as `dialog 1`.
    pub place: String,
    /// Where it points.
    pub url: String,
}

/// Every link in a vCon body, in the order of the console; none when the
/// body cannot be read in parts.
#[must_use]
pub fn links(text: &str) -> Vec<Link> {
    readable(text)
        .map(|vcon| links_of(&vcon))
        .unwrap_or_default()
}

/// The most characters of a vCon shown at once: 2 MiB, as in the console.
pub const DISPLAY_LIMIT: usize = 2 * 1024 * 1024;

/// `text` cut at [`DISPLAY_LIMIT`] characters, and how many were left out.
#[must_use]
pub fn shown(text: &str) -> (&str, usize) {
    match text.char_indices().nth(DISPLAY_LIMIT) {
        Some((cut, _)) => {
            let (kept, left) = text.split_at(cut);
            (kept, left.chars().count())
        }
        None => (text, 0),
    }
}

/// Items as indented JSON, with inline media named by its size, not shown;
/// `none` for no items.
fn listed(value: Option<&Value>) -> String {
    let made = items(value);
    if made.is_empty() {
        return "none".to_owned();
    }
    let readable: Vec<Value> = made
        .iter()
        .map(|item| {
            let mut item = item.clone();
            if let Some(object) = item.as_object_mut()
                && let Some(encoding) = text_field(object, "encoding")
                    .filter(|encoding| MEDIA_ENCODINGS.contains(encoding))
                    .map(str::to_owned)
                && let Some(length) =
                    text_field(object, "body").map(|body| body.encode_utf16().count())
            {
                object.insert(
                    "body".to_owned(),
                    Value::String(format!("[{length} characters of {encoding}, not shown]")),
                );
            }
            item
        })
        .collect();
    let text = serde_json::to_string_pretty(&readable).unwrap_or_default();
    shown(&text).0.to_owned()
}

/// One part of a vCon body as text, as the console shows a reveal of it:
/// the parties, the dialog or the analysis as indented JSON with inline
/// media named by its size, or the subject. None for any other part and for
/// a body that cannot be read in parts.
#[must_use]
pub fn section(text: &str, part: Part) -> Option<String> {
    let vcon = readable(text)?;
    match part {
        Part::Parties => Some(listed(vcon.get("parties"))),
        Part::Dialog => Some(listed(vcon.get("dialog"))),
        Part::Analysis => Some(listed(vcon.get("analysis"))),
        Part::Subject => Some(
            text_field(&vcon, "subject")
                .filter(|subject| !subject.is_empty())
                .unwrap_or("none")
                .to_owned(),
        ),
        Part::Links | Part::All | Part::Audio => None,
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    /// The cases of the rule; the console's display is tested against them
    /// too (console-tests/tests/masked-view.spec.js).
    const CASES: &str = include_str!("../tests/data/masked-cases.json");

    fn cases() -> Vec<(String, String, Value)> {
        let cases: Vec<Value> = serde_json::from_str(CASES).expect("the cases are JSON");
        cases
            .into_iter()
            .map(|case| {
                (
                    case["name"].as_str().expect("a name").to_owned(),
                    case["body"].as_str().expect("a body").to_owned(),
                    case["summary"].clone(),
                )
            })
            .collect()
    }

    fn masked(vcon: &Value) -> Summary {
        summary(&vcon.to_string())
    }

    // Success.

    #[test]
    fn each_case_is_summarized_as_the_case_states() {
        let cases = cases();
        assert!(cases.len() > 20, "there are cases to compare");
        for (name, body, wanted) in cases {
            let made = serde_json::to_value(summary(&body)).expect("a summary is JSON");
            assert_eq!(made, wanted, "the case {name}");
        }
    }

    #[test]
    fn view_masked_alone_asks_for_the_masked_view() {
        assert_eq!(from_query(Some("view=masked")), Ok(true), "the view");
    }

    #[test]
    fn a_read_without_the_parameter_is_not_the_masked_view() {
        for query in [None, Some(""), Some("reveal=all"), Some("viewed=masked")] {
            assert_eq!(from_query(query), Ok(false), "{query:?}");
        }
    }

    #[test]
    fn a_number_shows_its_last_four_digits() {
        assert_eq!(
            mask_tel(&json!("+1 212 555 0142")),
            "number ending 0142",
            "masked"
        );
    }

    #[test]
    fn an_address_shows_its_domain_in_lower_case() {
        assert_eq!(
            mask_mail(&json!("ada@Example.COM")),
            "address at example.com",
            "masked"
        );
    }

    #[test]
    fn a_party_line_names_number_address_and_name_in_that_order() {
        let party =
            json!({"name": "Ada Example", "mailto": "ada@example.com", "tel": "+12125550142"});
        assert_eq!(
            party_line(&party, 2),
            "Party 3: number ending 0142; address at example.com; name hidden",
            "the line"
        );
    }

    #[test]
    fn a_dialog_line_shows_type_start_length_and_parties_and_no_content() {
        let dialog = json!({"type": "text", "start": "2026-11-10T09:15:05Z", "duration": 30,
            "parties": [0, 1], "body": "Ada said hello"});
        let line = dialog_line(&dialog, 0);
        assert_eq!(
            line,
            "Dialog 1: text, 2026-11-10 09:15:05 UTC+00:00, 30 s, parties 1, 2; content hidden",
            "the line"
        );
        assert!(!line.contains("hello"), "no content");
    }

    #[test]
    fn a_time_with_an_offset_is_shown_in_utc() {
        assert_eq!(
            instant(&json!("2026-11-10T11:15:00+02:00")),
            "2026-11-10 09:15:00 UTC+00:00",
            "in UTC"
        );
    }

    #[test]
    fn a_whole_number_of_seconds_is_written_without_a_fraction() {
        let made =
            serde_json::to_string(&masked(&json!({"dialog": [{"duration": 30}]}))).expect("JSON");
        assert!(made.contains(r#""seconds":30,"#), "{made}");
    }

    #[test]
    fn numbers_are_written_as_javascript_writes_them() {
        for (number, text) in [
            (30.0, "30"),
            (12.5, "12.5"),
            (1e21, "1e+21"),
            (1e-7, "1e-7"),
            (1.5e-7, "1.5e-7"),
            (1e20, "100000000000000000000"),
            (0.1 + 0.2, "0.30000000000000004"),
        ] {
            assert_eq!(js_number(number), text, "{number}");
        }
    }

    #[test]
    fn a_signed_vcons_header_names_its_algorithm_key_and_thumbprint() {
        let cases = cases();
        let (_, body, _) = cases
            .iter()
            .find(|(name, _, _)| name == "a signed vCon")
            .expect("the signed case");
        let made = summary(body);
        assert_eq!(made.form, "signed (JWS)", "the form");
        assert_eq!(
            made.signature,
            Some(Signature {
                alg: "ES256".to_owned(),
                kid: "key-1".to_owned(),
                x5t: "x5t-example".to_owned()
            }),
            "the header"
        );
    }

    #[test]
    fn links_say_where_they_are_in_the_consoles_order() {
        let vcon = json!({"analysis": [{"url": "https://a.example.com/t"}],
            "dialog": [{"url": "https://media.example.com/a.wav"}, {"body": "x"}],
            "attachments": [{}, {"url": "https://files.example.com/x.pdf"}]});
        let found: Vec<(String, String)> = links(&vcon.to_string())
            .into_iter()
            .map(|link| (link.place, link.url))
            .collect();
        assert_eq!(
            found,
            [
                (
                    "dialog 1".to_owned(),
                    "https://media.example.com/a.wav".to_owned()
                ),
                (
                    "attachment 2".to_owned(),
                    "https://files.example.com/x.pdf".to_owned()
                ),
                (
                    "analysis 1".to_owned(),
                    "https://a.example.com/t".to_owned()
                ),
            ],
            "the links"
        );
    }

    #[test]
    fn a_section_shows_the_part_with_inline_media_named_by_its_size() {
        let vcon = json!({"dialog": [{"type": "recording", "encoding": "base64url", "body": "AAAABBBB"}],
            "subject": "Renewal", "parties": [{"name": "Ada Example"}]});
        let text = vcon.to_string();
        let dialog = section(&text, Part::Dialog).expect("a dialog section");
        assert!(
            dialog.contains("[8 characters of base64url, not shown]"),
            "{dialog}"
        );
        assert!(!dialog.contains("AAAABBBB"), "{dialog}");
        assert_eq!(
            section(&text, Part::Subject).as_deref(),
            Some("Renewal"),
            "the subject"
        );
        let parties = section(&text, Part::Parties).expect("a parties section");
        assert!(parties.contains("Ada Example"), "{parties}");
    }

    // Failure.

    #[test]
    fn a_view_other_than_masked_is_refused() {
        for query in ["view=whole", "view=MASKED", "view=masked2", "view="] {
            assert_eq!(from_query(Some(query)), Err(BadQuery), "{query}");
        }
    }

    #[test]
    fn the_view_given_twice_is_refused() {
        for query in ["view=masked&view=masked", "view=masked&view=whole"] {
            assert_eq!(from_query(Some(query)), Err(BadQuery), "{query}");
        }
    }

    /// The masked view and a reveal are two answers: one read cannot ask
    /// for both.
    #[test]
    fn the_view_beside_a_reveal_or_another_parameter_is_refused() {
        for query in [
            "view=masked&reveal=all",
            "reveal=parties&view=masked",
            "limit=3&view=masked",
        ] {
            assert_eq!(from_query(Some(query)), Err(BadQuery), "{query}");
        }
    }

    #[test]
    fn the_parameter_with_no_value_is_refused() {
        for query in ["view", "view&x=1"] {
            assert_eq!(from_query(Some(query)), Err(BadQuery), "{query}");
        }
    }

    #[test]
    fn text_that_is_not_json_is_not_read() {
        let made = summary("{\"subject\":");
        assert_eq!(
            (made.form.as_str(), made.subject.as_str()),
            ("not JSON", "not readable"),
            "not read"
        );
    }

    #[test]
    fn an_encrypted_vcon_is_not_decoded() {
        let made =
            masked(&json!({"ciphertext": "x", "subject": "Renewal", "parties": [{"name": "Ada"}]}));
        assert_eq!(made.form, "encrypted (JWE)", "the form");
        assert!(made.parties.is_empty(), "no party is read");
    }

    #[test]
    fn a_number_too_short_or_not_text_is_hidden_whole() {
        for value in [
            json!("555-0101"),
            json!(2_125_550_142_u64),
            json!(null),
            json!(""),
        ] {
            assert_eq!(mask_tel(&value), "number hidden", "{value}");
        }
    }

    #[test]
    fn an_address_without_a_local_part_or_a_domain_is_hidden_whole() {
        for value in [
            json!("@example.com"),
            json!("ada@"),
            json!("ada@  "),
            json!("ada"),
            json!(7),
        ] {
            assert_eq!(mask_mail(&value), "address hidden", "{value}");
        }
    }

    #[test]
    fn text_that_is_not_a_date_time_is_never_shown() {
        for value in [
            "Ada called about her account",
            "1",
            "Jan 2 2026",
            "2026-11-10T09:15Z",
            "2026-11-10 09:15:00Z",
            "2026-11-10T09:15:00",
            "2026-11-10T09:15:00.Z",
            "x UTC+00:00",
        ] {
            assert_eq!(instant(&json!(value)), "", "{value}");
        }
    }

    #[test]
    fn a_day_hour_second_or_offset_that_does_not_exist_is_no_time() {
        for value in [
            "2026-02-30T00:00:00Z",
            "2026-13-01T00:00:00Z",
            "2026-01-01T24:00:00Z",
            "2026-01-01T00:60:00Z",
            "2026-01-01T23:59:60Z",
            "2026-01-01T00:00:00+24:00",
            "2026-01-01T00:00:00+01:60",
        ] {
            assert_eq!(instant(&json!(value)), "", "{value}");
        }
    }

    #[test]
    fn a_party_or_dialog_that_is_not_an_object_is_named_and_not_read() {
        assert_eq!(
            party_line(&json!("Ada Example"), 0),
            "Party 1: not an object",
            "party"
        );
        assert_eq!(
            dialog_line(&json!(["hello"]), 1),
            "Dialog 2: not an object",
            "dialog"
        );
    }

    #[test]
    fn a_body_that_cannot_be_read_in_parts_has_no_section_and_no_links() {
        for text in ["{\"ciphertext\":\"x\"}", "[1]", "not JSON"] {
            assert_eq!(section(text, Part::Parties), None, "{text}");
            assert_eq!(links(text), [], "{text}");
        }
    }

    #[test]
    fn only_the_four_parts_have_a_section() {
        let text = json!({"subject": "Renewal"}).to_string();
        for part in [Part::Links, Part::All, Part::Audio] {
            assert_eq!(section(&text, part), None, "{part:?}");
        }
    }

    // Edge.

    #[test]
    fn an_encoded_parameter_is_the_parameter() {
        for query in ["%76iew=masked", "view=%6Dasked", "vi%65w=mask%65d"] {
            assert_eq!(from_query(Some(query)), Ok(true), "{query}");
        }
    }

    #[test]
    fn an_empty_piece_beside_the_view_names_nothing() {
        for query in ["view=masked&", "&view=masked", "&&view=masked&&"] {
            assert_eq!(from_query(Some(query)), Ok(true), "{query}");
        }
    }

    #[test]
    fn a_fraction_of_a_second_is_dropped_not_rounded() {
        assert_eq!(
            instant(&json!("2026-11-10T09:15:00.999999999Z")),
            "2026-11-10 09:15:00 UTC+00:00",
            "dropped"
        );
    }

    #[test]
    fn lower_case_t_and_z_are_read() {
        assert_eq!(
            instant(&json!("2026-11-10t09:15:00z")),
            "2026-11-10 09:15:00 UTC+00:00",
            "read"
        );
    }

    #[test]
    fn a_time_outside_the_years_1_to_9999_in_utc_is_no_time() {
        for value in [
            "9999-12-31T23:30:00-01:00",
            "0001-01-01T00:30:00+01:00",
            "0000-06-01T00:00:00Z",
        ] {
            assert_eq!(instant(&json!(value)), "", "{value}");
        }
        assert_eq!(
            instant(&json!("0001-01-01T00:00:00Z")),
            "0001-01-01 00:00:00 UTC+00:00",
            "year 1"
        );
        assert_eq!(
            instant(&json!("9999-12-31T23:59:59Z")),
            "9999-12-31 23:59:59 UTC+00:00",
            "year 9999"
        );
    }

    #[test]
    fn a_leap_day_is_a_day() {
        assert_eq!(
            instant(&json!("2024-02-29T12:00:00Z")),
            "2024-02-29 12:00:00 UTC+00:00",
            "2024"
        );
        assert_eq!(instant(&json!("2026-02-29T12:00:00Z")), "", "2026 has none");
    }

    #[test]
    fn a_place_written_with_a_fraction_of_zero_is_a_place() {
        let line = dialog_line(&json!({"type": "text", "parties": [0.0, 2.0]}), 0);
        assert!(line.contains("parties 1, 3"), "{line}");
        let line = dialog_line(&json!({"type": "text", "parties": [0, 1.5]}), 0);
        assert!(line.contains("no parties"), "{line}");
    }

    #[test]
    fn a_body_with_a_byte_order_mark_is_read_as_a_browser_reads_it() {
        let text = text_of(b"\xef\xbb\xbf{\"subject\":\"Renewal\"}");
        assert_eq!(
            summary(&text).subject,
            "present, hidden",
            "the mark is dropped"
        );
        assert_eq!(
            text_of(b"{\"a\":\"\xff\"}"),
            "{\"a\":\"\u{fffd}\"}",
            "a bad byte is replaced"
        );
    }

    #[test]
    fn a_domain_loses_the_spaces_javascript_trims() {
        for value in [
            "ada@ example.com\u{a0}",
            "ada@\u{feff}example.com",
            "ada@\texample.com\n",
        ] {
            assert_eq!(
                mask_mail(&json!(value)),
                "address at example.com",
                "{value:?}"
            );
        }
    }

    #[test]
    fn digits_are_counted_across_punctuation_and_only_ascii_digits_count() {
        assert_eq!(
            mask_tel(&json!("+1 (212) 555-0199")),
            "number ending 0199",
            "punctuation"
        );
        assert_eq!(
            mask_tel(&json!("\u{661}\u{662}\u{663}\u{664}5550199")),
            "number hidden",
            "Arabic-Indic digits"
        );
    }

    #[test]
    fn the_summary_holds_no_name_subject_number_or_address() {
        let vcon = json!({"subject": "Ada's divorce", "created_at": "Ada's birthday",
            "parties": [{"name": "Ada Example", "tel": "+12125550142", "mailto": "ada@example.com"}],
            "dialog": [{"type": "text", "start": "Ada's call", "body": "Ada said hello"}]});
        let made = serde_json::to_string(&masked(&vcon)).expect("JSON");
        for hidden in ["Ada", "divorce", "2125550142", "ada@", "hello"] {
            assert!(!made.contains(hidden), "{hidden} in {made}");
        }
    }

    #[test]
    fn a_long_text_is_cut_at_the_limit_and_says_what_was_left_out() {
        let text = "x".repeat(DISPLAY_LIMIT + 5);
        let (kept, left) = shown(&text);
        assert_eq!((kept.len(), left), (DISPLAY_LIMIT, 5), "cut");
        assert_eq!(shown("short"), ("short", 0), "kept whole");
    }

    #[test]
    fn a_summary_read_back_is_the_summary() {
        let made =
            masked(&json!({"dialog": [{"duration": 12.5}], "parties": [{"tel": "+12125550142"}]}));
        let text = serde_json::to_string(&made).expect("JSON");
        let back: Summary = serde_json::from_str(&text).expect("read back");
        assert_eq!(back, made, "the same");
    }

    #[test]
    fn an_empty_list_section_says_none() {
        let text = json!({"analysis": []}).to_string();
        assert_eq!(
            section(&text, Part::Analysis).as_deref(),
            Some("none"),
            "no analysis"
        );
        assert_eq!(
            section(&text, Part::Subject).as_deref(),
            Some("none"),
            "no subject"
        );
    }

    // The recordings the console plays, listed by the view.

    /// A dialog holding `body` as an inline recording declared as `type`.
    fn inline(body: &str, declared: &str) -> Value {
        json!({"type": "recording", "body": body, "encoding": "base64url", "mediatype": declared})
    }

    fn listed(dialogs: &[Value], limit: u64) -> Vec<Recording> {
        let vcon = json!({ "dialog": dialogs });
        recordings_within(vcon.as_object().expect("an object"), limit)
    }

    fn recording(dialog: usize, played: &str) -> Recording {
        Recording {
            dialog,
            r#type: played.to_owned(),
        }
    }

    #[test]
    fn a_recording_the_console_plays_is_listed_by_its_dialog_number() {
        let made = masked(&json!({"dialog": [{"type": "text"}, inline("AAAA", "audio/wav")]}));
        assert_eq!(
            made.recordings,
            vec![recording(2, "audio/wav")],
            "the second dialog"
        );
    }

    #[test]
    fn a_recording_is_listed_as_the_type_it_plays_as_not_the_name_it_was_given() {
        for (declared, played) in [
            ("audio/x-wav", "audio/wav"),
            ("audio/wave", "audio/wav"),
            ("audio/vnd.wave", "audio/wav"),
            ("audio/x-mp3", "audio/mpeg"),
            ("audio/mp3", "audio/mpeg"),
            ("audio/x-ogg", "audio/ogg"),
            ("audio/opus", "audio/opus"),
        ] {
            assert_eq!(
                listed(&[inline("AAAA", declared)], 100),
                vec![recording(1, played)],
                "{declared}"
            );
        }
    }

    #[test]
    fn a_recording_of_the_size_limit_is_listed() {
        // Four characters of base64 are three bytes.
        assert_eq!(
            listed(&[inline("AAAA", "audio/wav")], 3),
            vec![recording(1, "audio/wav")],
            "at the limit"
        );
    }

    #[test]
    fn the_padding_of_a_body_is_not_counted_in_its_size() {
        // "AAA=" is two bytes once its padding is dropped.
        assert_eq!(
            listed(&[inline("AAA=", "audio/wav")], 2),
            vec![recording(1, "audio/wav")],
            "two bytes"
        );
    }

    #[test]
    fn the_view_lists_the_recordings_up_to_the_consoles_limit() {
        assert_eq!(AUDIO_LIMIT, 100 * 1024 * 1024, "100 MiB");
        let console = include_str!("../console/format.js");
        assert!(
            console.contains("export const AUDIO_LIMIT = 100 * 1024 * 1024;"),
            "format.js plays the same size"
        );
    }

    #[test]
    fn the_view_lists_the_types_and_names_the_console_plays() {
        let console = include_str!("../console/format.js");
        let types = AUDIO_TYPES
            .iter()
            .map(|t| format!("\"{t}\""))
            .collect::<Vec<_>>()
            .join(", ");
        assert!(
            console.contains(&format!(
                "export const AUDIO_TYPES = Object.freeze([{types}]);"
            )),
            "format.js plays {types}"
        );
        for (name, played) in AUDIO_ALIASES {
            assert!(
                console.contains(&format!("  \"{name}\": \"{played}\",\n")),
                "format.js plays {name} as {played}"
            );
        }
        assert_eq!(
            console.matches("\": \"audio/").count(),
            AUDIO_ALIASES.len(),
            "format.js has no other name"
        );
    }

    #[test]
    fn a_summary_without_recordings_reads_back_with_none() {
        let mut made = serde_json::to_value(masked(&json!({}))).expect("JSON");
        made.as_object_mut()
            .expect("an object")
            .remove("recordings");
        let back: Summary = serde_json::from_value(made).expect("read back");
        assert!(back.recordings.is_empty(), "none");
    }

    #[test]
    fn a_recording_reads_back_as_the_same_recording() {
        let made = masked(&json!({"dialog": [inline("AAAA", "audio/ogg")]}));
        let text = serde_json::to_string(&made).expect("JSON");
        assert!(
            text.contains(r#""recordings":[{"dialog":1,"type":"audio/ogg"}]"#),
            "{text}"
        );
        let back: Summary = serde_json::from_str(&text).expect("read back");
        assert_eq!(back, made, "the same");
    }

    #[test]
    fn a_recording_over_the_size_limit_is_not_listed() {
        assert_eq!(
            listed(&[inline("AAAA", "audio/wav")], 2),
            vec![],
            "one byte over"
        );
    }

    #[test]
    fn a_recording_kept_at_a_link_is_not_listed() {
        let dialog = json!({"type": "recording", "url": "https://media.example.com/a.wav", "mediatype": "audio/wav"});
        assert_eq!(listed(&[dialog], 100), vec![], "at a link");
    }

    #[test]
    fn a_body_that_is_not_encoded_media_is_not_listed() {
        for encoding in [
            json!("none"),
            json!("json"),
            json!(""),
            json!(null),
            json!(64),
        ] {
            let dialog = json!({"body": "AAAA", "encoding": encoding, "mediatype": "audio/wav"});
            assert_eq!(listed(&[dialog], 100), vec![], "{encoding}");
        }
    }

    #[test]
    fn a_body_that_is_not_text_is_not_listed() {
        for body in [json!(null), json!(7), json!(["AAAA"]), json!("")] {
            let dialog = json!({"body": body, "encoding": "base64", "mediatype": "audio/wav"});
            assert_eq!(listed(&[dialog], 100), vec![], "{body}");
        }
    }

    #[test]
    fn a_type_the_console_does_not_play_is_not_listed() {
        for declared in [
            "video/mp4",
            "application/ogg",
            "audio/flac",
            "audio",
            "",
            "  ",
        ] {
            assert_eq!(
                listed(&[inline("AAAA", declared)], 100),
                vec![],
                "{declared:?}"
            );
        }
    }

    #[test]
    fn a_recording_that_declares_no_type_is_not_listed() {
        let dialog = json!({"body": "AAAA", "encoding": "base64url"});
        assert_eq!(listed(&[dialog], 100), vec![], "no type");
    }

    #[test]
    fn a_media_type_that_is_not_text_hides_the_older_name() {
        // As in format.js: `mediatype` is read when present, so `mimetype`
        // is not read in its place.
        let dialog = json!({"body": "AAAA", "encoding": "base64url", "mediatype": 7, "mimetype": "audio/wav"});
        assert_eq!(listed(&[dialog], 100), vec![], "no type");
    }

    #[test]
    fn an_encrypted_or_unreadable_vcon_lists_no_recording() {
        for text in [
            json!({"ciphertext": "x", "dialog": [inline("AAAA", "audio/wav")]}).to_string(),
            "not JSON".to_owned(),
            "[]".to_owned(),
        ] {
            assert_eq!(summary(&text).recordings, vec![], "{text}");
        }
    }

    #[test]
    fn the_older_name_of_the_media_type_is_read_when_there_is_no_media_type() {
        let dialog = json!({"body": "AAAA", "encoding": "base64", "mimetype": "audio/mpeg"});
        assert_eq!(
            listed(&[dialog], 100),
            vec![recording(1, "audio/mpeg")],
            "mimetype"
        );
    }

    #[test]
    fn a_type_is_read_in_any_case_without_its_parameters() {
        for declared in ["AUDIO/WAV", " audio/wav ; codecs=1", "Audio/Wav;rate=8000"] {
            assert_eq!(
                listed(&[inline("AAAA", declared)], 100),
                vec![recording(1, "audio/wav")],
                "{declared:?}"
            );
        }
    }

    #[test]
    fn a_parameter_of_the_type_never_reaches_the_view() {
        let made = masked(&json!({"dialog": [inline("AAAA", "audio/wav; name=Ada Example")]}));
        let text = serde_json::to_string(&made).expect("JSON");
        assert!(!text.contains("Ada"), "{text}");
        assert_eq!(made.recordings, vec![recording(1, "audio/wav")], "listed");
    }

    #[test]
    fn dialogs_that_are_not_objects_keep_the_numbers_of_the_others() {
        assert_eq!(
            listed(&[json!("x"), json!(null), inline("AAAA", "audio/wav")], 100),
            vec![recording(3, "audio/wav")],
            "the third dialog"
        );
    }

    #[test]
    fn a_dialog_list_that_is_not_a_list_lists_no_recording() {
        let made = masked(&json!({"dialog": inline("AAAA", "audio/wav")}));
        assert_eq!(made.recordings, vec![], "not a list");
    }
}