Skip to main content

vcon_server/
masked.rs

1//! The masked view of a vCon (`GET /vcons/{uuid}?view=masked`, and
2//! `?view=masked` on the two legal reads): what it holds, without any name,
3//! subject, full number, address or content, so a client can show a vCon
4//! before anyone reveals a part of it.
5//!
6//! THIS MODULE IS THE ONE RULE. The console and the terminal UI both show
7//! the view the server makes here; neither makes a summary of its own.
8//! tests/data/masked-cases.json holds the cases the rule is tested against
9//! here, and console-tests/tests/masked-view.spec.js shows each case's
10//! summary through the console's display. A change to the rule is a change
11//! to the cases.
12//!
13//! The view also lists the recordings the console plays (`recordings`), so
14//! the console offers Play without receiving any content; their types and
15//! size limit are the console player's (console/format.js), held equal by
16//! tests here.
17//!
18//! The parts a reveal shows (`section`, `links`) are ported here from
19//! console/format.js, for the terminal UI, which shows a reveal as the
20//! console does.
21
22use base64::engine::DecodePaddingMode;
23use base64::engine::general_purpose::{GeneralPurpose, GeneralPurposeConfig};
24use base64::{Engine, alphabet};
25use serde::{Deserialize, Serialize, Serializer};
26use serde_json::{Map, Value};
27use time::{Date, Month, PrimitiveDateTime, Time, UtcOffset};
28
29use crate::query::{self, BadQuery};
30use crate::reveal::Part;
31
32/// The query parameter that asks a read for a view of the vCon.
33pub const PARAMETER: &str = "view";
34
35/// The one view there is: the vCon masked.
36pub const MASKED: &str = "masked";
37
38/// Whether a read's query asks for the masked view. A query that does not
39/// name the parameter is the read it always was.
40///
41/// # Errors
42///
43/// [`BadQuery`] if the query names the parameter and it is not exactly
44/// `view=masked`, alone and once.
45pub fn from_query(query: Option<&str>) -> Result<bool, BadQuery> {
46    if !query::names(query, PARAMETER) {
47        return Ok(false);
48    }
49    let read = query::pairs(query, &[PARAMETER])?;
50    match read.get(PARAMETER).map(String::as_str) {
51        Some(MASKED) => Ok(true),
52        _ => Err(BadQuery),
53    }
54}
55
56/// The form of each kind of body, and what the subject of an unread one is.
57const UNSIGNED: &str = "unsigned";
58const SIGNED: &str = "signed (JWS)";
59const ENCRYPTED: &str = "encrypted (JWE)";
60const NOT_JSON: &str = "not JSON";
61const NOT_OBJECT: &str = "not a JSON object";
62const NOT_READABLE: &str = "not readable";
63
64/// The dialog types the vCon format names; any other is not shown.
65const DIALOG_TYPES: [&str; 4] = ["recording", "text", "transfer", "incomplete"];
66
67/// The fewest digits a number needs before its last four may be shown.
68const MASKABLE_DIGITS: usize = 8;
69
70/// The encodings under which a body is media, not text to read.
71const MEDIA_ENCODINGS: [&str; 2] = ["base64url", "base64"];
72
73/// The parts of a vCon that may hold a link, and what one item is called.
74const LINKED: [(&str, &str); 3] = [
75    ("dialog", "dialog"),
76    ("attachments", "attachment"),
77    ("analysis", "analysis"),
78];
79
80/// Base64url as a browser's `atob` reads it: no padding needed, and bits
81/// after the last whole byte ignored.
82const FORGIVING: GeneralPurpose = GeneralPurpose::new(
83    &alphabet::URL_SAFE,
84    GeneralPurposeConfig::new()
85        .with_decode_padding_mode(DecodePaddingMode::Indifferent)
86        .with_decode_allow_trailing_bits(true),
87);
88
89/// A value's items when it is an array, or none.
90fn items(value: Option<&Value>) -> &[Value] {
91    value.and_then(Value::as_array).map_or(&[], Vec::as_slice)
92}
93
94/// A field of an object when it is text.
95fn text_field<'a>(object: &'a Map<String, Value>, name: &str) -> Option<&'a str> {
96    object.get(name).and_then(Value::as_str)
97}
98
99/// Base64url JSON as an object, or none when it is anything else. A
100/// leading byte order mark is dropped, as a browser's text decoder drops it.
101fn decoded(value: Option<&Value>) -> Option<Map<String, Value>> {
102    let text = value?.as_str()?;
103    if text.is_empty()
104        || !text
105            .bytes()
106            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
107    {
108        return None;
109    }
110    let bytes = FORGIVING.decode(text).ok()?;
111    let text = std::str::from_utf8(&bytes).ok()?;
112    match serde_json::from_str(text.strip_prefix('\u{feff}').unwrap_or(text)).ok()? {
113        Value::Object(object) => Some(object),
114        _ => None,
115    }
116}
117
118/// The vCon object a body holds, for reading its parts: the body itself,
119/// or a signed vCon's payload. None for an encrypted vCon and for anything
120/// that is not a JSON object.
121fn readable(text: &str) -> Option<Map<String, Value>> {
122    let Ok(Value::Object(vcon)) = serde_json::from_str::<Value>(text) else {
123        return None;
124    };
125    if vcon.contains_key("ciphertext") {
126        return None;
127    }
128    if vcon.contains_key("payload") && vcon.contains_key("signatures") {
129        return decoded(vcon.get("payload"));
130    }
131    Some(vcon)
132}
133
134/// A summary of nothing, in the given form.
135fn empty(form: &str, subject: &str) -> Summary {
136    Summary {
137        form: form.to_owned(),
138        created: String::new(),
139        subject: subject.to_owned(),
140        parties: Vec::new(),
141        dialogs: 0,
142        dialog: Vec::new(),
143        seconds: 0.0,
144        attachments: 0,
145        analyses: 0,
146        links: 0,
147        signature: None,
148        recordings: Vec::new(),
149    }
150}
151
152/// The counts and masked parties of an unsigned vCon object.
153fn counted(vcon: &Map<String, Value>, form: &str) -> Summary {
154    let dialog = items(vcon.get("dialog"));
155    let seconds = dialog
156        .iter()
157        .filter_map(|d| d.get("duration").and_then(Value::as_f64))
158        .filter(|duration| *duration > 0.0)
159        .fold(0.0, |sum, duration| sum + duration);
160    let subject = match text_field(vcon, "subject") {
161        Some(subject) if !subject.is_empty() => "present, hidden",
162        _ => "none",
163    };
164    Summary {
165        form: form.to_owned(),
166        created: vcon.get("created_at").map(instant).unwrap_or_default(),
167        subject: subject.to_owned(),
168        parties: items(vcon.get("parties"))
169            .iter()
170            .enumerate()
171            .map(|(index, party)| party_line(party, index))
172            .collect(),
173        dialogs: dialog.len(),
174        dialog: dialog
175            .iter()
176            .enumerate()
177            .map(|(index, d)| dialog_line(d, index))
178            .collect(),
179        seconds,
180        attachments: items(vcon.get("attachments")).len(),
181        analyses: items(vcon.get("analysis")).len(),
182        links: links_of(vcon).len(),
183        signature: None,
184        recordings: recordings_within(vcon, AUDIO_LIMIT),
185    }
186}
187
188/// Every link in a vCon object, with where it is.
189fn links_of(vcon: &Map<String, Value>) -> Vec<Link> {
190    let mut found = Vec::new();
191    for (part, noun) in LINKED {
192        for (index, item) in items(vcon.get(part)).iter().enumerate() {
193            if let Some(url) = item.as_object().and_then(|item| text_field(item, "url"))
194                && !url.is_empty()
195            {
196                found.push(Link {
197                    place: format!("{noun} {}", index.saturating_add(1)),
198                    url: url.to_owned(),
199                });
200            }
201        }
202    }
203    found
204}
205
206/// A vCon's form and counts, its parties masked: the answer of the masked
207/// view, with the fields and the words of the console's summary.
208#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
209pub struct Summary {
210    /// `unsigned`, `signed (JWS)`, `encrypted (JWE)`, `not JSON` or `not a
211    /// JSON object`.
212    pub form: String,
213    /// When it was made, in UTC (see [`instant`]); empty when not a time.
214    pub created: String,
215    /// `present, hidden`, `none`, or `not readable`.
216    pub subject: String,
217    /// One line for each party, masked (see [`party_line`]).
218    pub parties: Vec<String>,
219    /// How many dialogs it holds.
220    pub dialogs: usize,
221    /// One line for each dialog, with no content (see [`dialog_line`]).
222    pub dialog: Vec<String>,
223    /// The sum of the dialogs' positive lengths, in seconds.
224    #[serde(serialize_with = "as_js_number")]
225    pub seconds: f64,
226    /// How many attachments it holds.
227    pub attachments: usize,
228    /// How many analyses it holds.
229    pub analyses: usize,
230    /// How many links to outside the server it holds.
231    pub links: usize,
232    /// A signed vCon's first signature header, else none.
233    pub signature: Option<Signature>,
234    /// The dialogs that hold, inside the vCon, a recording of a type in
235    /// [`AUDIO_TYPES`] or [`AUDIO_ALIASES`] and of at most [`AUDIO_LIMIT`]
236    /// bytes: the recordings the console plays.
237    #[serde(default)]
238    pub recordings: Vec<Recording>,
239}
240
241/// A recording the console plays: the dialog that holds it, counted from
242/// one, and the type it plays as, one of [`AUDIO_TYPES`]. No text of the
243/// vCon is in it.
244#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
245pub struct Recording {
246    /// The dialog's number, counted from one.
247    pub dialog: usize,
248    /// The type it plays as.
249    #[serde(rename = "type")]
250    pub r#type: String,
251}
252
253/// The most bytes of one recording the console plays: 100 MiB, as
254/// `AUDIO_LIMIT` in console/format.js.
255pub const AUDIO_LIMIT: u64 = 100 * 1024 * 1024;
256
257/// The audio types the console plays, as `AUDIO_TYPES` in
258/// console/format.js.
259pub const AUDIO_TYPES: [&str; 4] = ["audio/wav", "audio/mpeg", "audio/ogg", "audio/opus"];
260
261/// Other names producers give the types the console plays, each with the
262/// type it is a name for, as `AUDIO_ALIASES` in console/format.js.
263pub const AUDIO_ALIASES: [(&str, &str); 6] = [
264    ("audio/x-wav", "audio/wav"),
265    ("audio/wave", "audio/wav"),
266    ("audio/vnd.wave", "audio/wav"),
267    ("audio/x-mp3", "audio/mpeg"),
268    ("audio/mp3", "audio/mpeg"),
269    ("audio/x-ogg", "audio/ogg"),
270];
271
272/// The dialogs of `vcon` that hold, inside the vCon, a recording the
273/// console plays, of at most `limit` bytes, read without decoding any, as
274/// `offered` in console/format.js reads them before a Play.
275fn recordings_within(vcon: &Map<String, Value>, limit: u64) -> Vec<Recording> {
276    items(vcon.get("dialog"))
277        .iter()
278        .enumerate()
279        .filter_map(|(index, dialog)| {
280            let played = played_within(dialog.as_object()?, limit)?;
281            Some(Recording {
282                dialog: index + 1,
283                r#type: played.to_owned(),
284            })
285        })
286        .collect()
287}
288
289/// The type a dialog's recording plays as, when the dialog holds, inside
290/// the vCon, an encoded recording of a type the console plays and of at
291/// most `limit` bytes; else none.
292fn played_within(dialog: &Map<String, Value>, limit: u64) -> Option<&'static str> {
293    let body = dialog
294        .get("body")?
295        .as_str()
296        .filter(|body| !body.is_empty())?;
297    let encoding = dialog.get("encoding")?.as_str()?;
298    if !MEDIA_ENCODINGS.contains(&encoding) {
299        return None;
300    }
301    // As format.js: `mediatype` when the dialog names it, else `mimetype`,
302    // the name older vCons use; without its parameters, in lower case.
303    let declared = match dialog.get("mediatype") {
304        Some(named) => named,
305        None => dialog.get("mimetype")?,
306    };
307    let declared = declared
308        .as_str()?
309        .split(';')
310        .next()
311        .unwrap_or_default()
312        .trim_matches(trimmed_by_javascript)
313        .to_lowercase();
314    let played = AUDIO_TYPES
315        .into_iter()
316        .find(|known| *known == declared)
317        .or_else(|| {
318            AUDIO_ALIASES
319                .into_iter()
320                .find(|(name, _)| *name == declared)
321                .map(|(_, played)| played)
322        })?;
323    // The size format.js counts: three bytes for each four characters
324    // (UTF-16 code units) of the body without its padding.
325    let characters = body.trim_end_matches('=').encode_utf16().count() as u64;
326    (characters * 3 / 4 <= limit).then_some(played)
327}
328
329/// The fields of a signature's protected header the view names; each is
330/// empty when the header does not hold it as text.
331#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
332pub struct Signature {
333    /// The signing algorithm, such as `ES256`.
334    pub alg: String,
335    /// The id of the signing key.
336    pub kid: String,
337    /// The thumbprint of the signing certificate.
338    pub x5t: String,
339}
340
341/// A number as JSON writes it in JavaScript: a whole number without a
342/// fraction, so `30` and not `30.0`.
343fn as_js_number<S: Serializer>(value: &f64, to: S) -> Result<S::Ok, S::Error> {
344    /// Below this every whole number is exact in a JavaScript number.
345    const EXACT: f64 = 9_007_199_254_740_992.0;
346    if value.fract() == 0.0 && value.abs() < EXACT {
347        // The value is whole and within the exact range, so the
348        // conversion keeps it.
349        #[expect(clippy::cast_possible_truncation, reason = "whole and below 2^53")]
350        to.serialize_i64(*value as i64)
351    } else {
352        to.serialize_f64(*value)
353    }
354}
355
356/// A body as the text a browser reads from it: UTF-8, any byte that is not
357/// replaced, and a leading byte order mark dropped.
358#[must_use]
359pub fn text_of(body: &[u8]) -> String {
360    let text = String::from_utf8_lossy(body);
361    text.strip_prefix('\u{feff}').unwrap_or(&text).to_owned()
362}
363
364/// What a vCon body holds, without any name, subject, full number or
365/// address: its form, counts and masked parties. A signed vCon's payload is
366/// read; an encrypted one is not decoded.
367#[must_use]
368pub fn summary(text: &str) -> Summary {
369    let Ok(value) = serde_json::from_str::<Value>(text) else {
370        return empty(NOT_JSON, NOT_READABLE);
371    };
372    let Value::Object(vcon) = value else {
373        return empty(NOT_OBJECT, NOT_READABLE);
374    };
375    if vcon.contains_key("ciphertext") {
376        return empty(ENCRYPTED, NOT_READABLE);
377    }
378    if vcon.contains_key("payload") && vcon.contains_key("signatures") {
379        let header = items(vcon.get("signatures"))
380            .first()
381            .and_then(Value::as_object)
382            .and_then(|first| decoded(first.get("protected")));
383        let field = |name: &str| {
384            header
385                .as_ref()
386                .and_then(|header| text_field(header, name))
387                .unwrap_or_default()
388                .to_owned()
389        };
390        let mut made = decoded(vcon.get("payload")).map_or_else(
391            || empty(SIGNED, NOT_READABLE),
392            |payload| counted(&payload, SIGNED),
393        );
394        made.signature = Some(Signature {
395            alg: field("alg"),
396            kid: field("kid"),
397            x5t: field("x5t"),
398        });
399        return made;
400    }
401    counted(&vcon, UNSIGNED)
402}
403
404/// The numbers of an RFC 3339 date-time, `YYYY-MM-DDTHH:MM:SS`, any
405/// fraction, then `Z` or `+HH:MM`/`-HH:MM` (either letter in either case):
406/// year, month, day, hour, minute, second and the offset in minutes. None
407/// for text of any other shape.
408fn date_time_numbers(text: &str) -> Option<([u16; 6], i32)> {
409    let bytes = text.as_bytes();
410    let number = |from: usize, to: usize| -> Option<u16> {
411        let digits = bytes.get(from..to)?;
412        digits
413            .iter()
414            .all(u8::is_ascii_digit)
415            .then(|| std::str::from_utf8(digits).ok()?.parse().ok())?
416    };
417    let at = |index: usize, wanted: &[u8]| bytes.get(index).is_some_and(|b| wanted.contains(b));
418    if !(at(4, b"-") && at(7, b"-") && at(10, b"Tt") && at(13, b":") && at(16, b":")) {
419        return None;
420    }
421    let fields = [
422        number(0, 4)?,
423        number(5, 7)?,
424        number(8, 10)?,
425        number(11, 13)?,
426        number(14, 16)?,
427        number(17, 19)?,
428    ];
429    let mut rest = 19;
430    if at(rest, b".") {
431        let digits = bytes
432            .get(rest.saturating_add(1)..)?
433            .iter()
434            .take_while(|b| b.is_ascii_digit())
435            .count();
436        if digits == 0 {
437            return None;
438        }
439        rest = rest.saturating_add(1).saturating_add(digits);
440    }
441    let zone = bytes.get(rest..)?;
442    let offset = match zone {
443        [b'Z' | b'z'] => 0,
444        [sign @ (b'+' | b'-'), _, _, b':', _, _] => {
445            let hours = number(rest.saturating_add(1), rest.saturating_add(3))?;
446            let minutes = number(rest.saturating_add(4), rest.saturating_add(6))?;
447            if hours > 23 || minutes > 59 {
448                return None;
449            }
450            let minutes = i32::from(hours) * 60 + i32::from(minutes);
451            if *sign == b'-' { -minutes } else { minutes }
452        }
453        _ => return None,
454    };
455    Some((fields, offset))
456}
457
458/// A vCon's time as `YYYY-MM-DD HH:MM:SS UTC+00:00`, or empty when it is
459/// not an RFC 3339 date-time of a day that exists, in the years 1 to 9999
460/// once in UTC. Text that is not a time is never shown.
461#[must_use]
462pub fn instant(value: &Value) -> String {
463    let read = || {
464        let (fields, offset) = date_time_numbers(value.as_str()?)?;
465        let [year, month, day, hour, minute, second] = fields;
466        let date = Date::from_calendar_date(
467            i32::from(year),
468            Month::try_from(u8::try_from(month).ok()?).ok()?,
469            u8::try_from(day).ok()?,
470        )
471        .ok()?;
472        let time = Time::from_hms(
473            u8::try_from(hour).ok()?,
474            u8::try_from(minute).ok()?,
475            u8::try_from(second).ok()?,
476        )
477        .ok()?;
478        let offset = UtcOffset::from_whole_seconds(offset.checked_mul(60)?).ok()?;
479        let at = PrimitiveDateTime::new(date, time)
480            .assume_offset(offset)
481            .checked_to_offset(UtcOffset::UTC)?;
482        (1..=9999).contains(&at.year()).then(|| {
483            format!(
484                "{:04}-{:02}-{:02} {:02}:{:02}:{:02} UTC+00:00",
485                at.year(),
486                u8::from(at.month()),
487                at.day(),
488                at.hour(),
489                at.minute(),
490                at.second()
491            )
492        })
493    };
494    read().unwrap_or_default()
495}
496
497/// A telephone number as its last four digits, or hidden whole.
498#[must_use]
499pub fn mask_tel(value: &Value) -> String {
500    let digits: Vec<char> = value
501        .as_str()
502        .unwrap_or_default()
503        .chars()
504        .filter(char::is_ascii_digit)
505        .collect();
506    match digits.len().checked_sub(4) {
507        Some(from) if digits.len() >= MASKABLE_DIGITS => {
508            let last: String = digits.get(from..).unwrap_or_default().iter().collect();
509            format!("number ending {last}")
510        }
511        _ => "number hidden".to_owned(),
512    }
513}
514
515/// Whether JavaScript's `trim` removes `c`: its white space and line
516/// terminators, the byte order mark among them.
517fn trimmed_by_javascript(c: char) -> bool {
518    matches!(
519        c,
520        '\u{9}'..='\u{d}'
521            | ' '
522            | '\u{a0}'
523            | '\u{1680}'
524            | '\u{2000}'..='\u{200a}'
525            | '\u{2028}'
526            | '\u{2029}'
527            | '\u{202f}'
528            | '\u{205f}'
529            | '\u{3000}'
530            | '\u{feff}'
531    )
532}
533
534/// An email address as its domain, or hidden whole.
535#[must_use]
536pub fn mask_mail(value: &Value) -> String {
537    let Some(address) = value.as_str() else {
538        return "address hidden".to_owned();
539    };
540    match address.rfind('@') {
541        Some(at) if at > 0 => {
542            let domain = address
543                .get(at.saturating_add(1)..)
544                .unwrap_or_default()
545                .trim_matches(trimmed_by_javascript)
546                .to_lowercase();
547            if domain.is_empty() {
548                "address hidden".to_owned()
549            } else {
550                format!("address at {domain}")
551            }
552        }
553        _ => "address hidden".to_owned(),
554    }
555}
556
557/// Party `index` (from 0) as a line that names what it holds and shows none
558/// of it.
559#[must_use]
560pub fn party_line(party: &Value, index: usize) -> String {
561    let label = format!("Party {}", index.saturating_add(1));
562    let Some(party) = party.as_object() else {
563        return format!("{label}: not an object");
564    };
565    let mut parts = Vec::new();
566    if let Some(tel) = party.get("tel") {
567        parts.push(mask_tel(tel));
568    }
569    if let Some(mailto) = party.get("mailto") {
570        parts.push(mask_mail(mailto));
571    }
572    if party.contains_key("name") {
573        parts.push("name hidden".to_owned());
574    }
575    if parts.is_empty() {
576        format!("{label}: no number, address or name")
577    } else {
578        format!("{label}: {}", parts.join("; "))
579    }
580}
581
582/// A value as a party's place in the parties list, if it is one: a whole
583/// number, zero or more.
584fn place(value: &Value) -> Option<f64> {
585    value
586        .as_f64()
587        .filter(|number| number.fract() == 0.0 && *number >= 0.0)
588}
589
590/// A dialog's parties as their numbers, counted from one.
591fn parties_of(parties: Option<&Value>) -> String {
592    if let Some(one) = parties.and_then(place) {
593        return format!("party {}", js_number(one + 1.0));
594    }
595    let places: Option<Vec<f64>> = parties
596        .and_then(Value::as_array)
597        .filter(|list| !list.is_empty())
598        .and_then(|list| list.iter().map(place).collect());
599    match places {
600        Some(places) => {
601            let numbers: Vec<String> = places.iter().map(|p| js_number(p + 1.0)).collect();
602            format!("parties {}", numbers.join(", "))
603        }
604        None => "no parties".to_owned(),
605    }
606}
607
608/// Dialog `index` (from 0) as a line with its type, start, length and
609/// parties, and whether it has content, never the content or a link.
610#[must_use]
611pub fn dialog_line(dialog: &Value, index: usize) -> String {
612    let label = format!("Dialog {}", index.saturating_add(1));
613    let Some(dialog) = dialog.as_object() else {
614        return format!("{label}: not an object");
615    };
616    let kind = text_field(dialog, "type")
617        .filter(|kind| DIALOG_TYPES.contains(kind))
618        .unwrap_or("other type");
619    let start = dialog.get("start").map(instant).unwrap_or_default();
620    let start = if start.is_empty() { "no start" } else { &start };
621    let length = dialog
622        .get("duration")
623        .and_then(Value::as_f64)
624        .filter(|duration| *duration > 0.0)
625        .map_or_else(|| "no length".to_owned(), |d| format!("{} s", js_number(d)));
626    let present = |name: &str| text_field(dialog, name).is_some_and(|text| !text.is_empty());
627    let content = if present("body") {
628        "content hidden"
629    } else if present("url") {
630        "content at a link outside the server"
631    } else {
632        "no content"
633    };
634    format!(
635        "{label}: {kind}, {start}, {length}, {}; {content}",
636        parties_of(dialog.get("parties"))
637    )
638}
639
640/// A number as JavaScript writes it in text: `30`, `12.5`, `1e+21`.
641#[must_use]
642pub fn js_number(value: f64) -> String {
643    if value == 0.0 {
644        return "0".to_owned();
645    }
646    let size = value.abs();
647    if size >= 1e21 || size < 1e-6 {
648        let written = format!("{value:e}");
649        return match written.split_once('e') {
650            Some((digits, power)) if !power.starts_with('-') => format!("{digits}e+{power}"),
651            _ => written,
652        };
653    }
654    format!("{value}")
655}
656
657/// A link of a vCon: where it is (`dialog 1`, `attachment 2`, `analysis
658/// 3`) and the address, which is never loaded.
659#[derive(Debug, Clone, PartialEq, Eq)]
660pub struct Link {
661    /// Where the link is, as `dialog 1`.
662    pub place: String,
663    /// Where it points.
664    pub url: String,
665}
666
667/// Every link in a vCon body, in the order of the console; none when the
668/// body cannot be read in parts.
669#[must_use]
670pub fn links(text: &str) -> Vec<Link> {
671    readable(text)
672        .map(|vcon| links_of(&vcon))
673        .unwrap_or_default()
674}
675
676/// The most characters of a vCon shown at once: 2 MiB, as in the console.
677pub const DISPLAY_LIMIT: usize = 2 * 1024 * 1024;
678
679/// `text` cut at [`DISPLAY_LIMIT`] characters, and how many were left out.
680#[must_use]
681pub fn shown(text: &str) -> (&str, usize) {
682    match text.char_indices().nth(DISPLAY_LIMIT) {
683        Some((cut, _)) => {
684            let (kept, left) = text.split_at(cut);
685            (kept, left.chars().count())
686        }
687        None => (text, 0),
688    }
689}
690
691/// Items as indented JSON, with inline media named by its size, not shown;
692/// `none` for no items.
693fn listed(value: Option<&Value>) -> String {
694    let made = items(value);
695    if made.is_empty() {
696        return "none".to_owned();
697    }
698    let readable: Vec<Value> = made
699        .iter()
700        .map(|item| {
701            let mut item = item.clone();
702            if let Some(object) = item.as_object_mut()
703                && let Some(encoding) = text_field(object, "encoding")
704                    .filter(|encoding| MEDIA_ENCODINGS.contains(encoding))
705                    .map(str::to_owned)
706                && let Some(length) =
707                    text_field(object, "body").map(|body| body.encode_utf16().count())
708            {
709                object.insert(
710                    "body".to_owned(),
711                    Value::String(format!("[{length} characters of {encoding}, not shown]")),
712                );
713            }
714            item
715        })
716        .collect();
717    let text = serde_json::to_string_pretty(&readable).unwrap_or_default();
718    shown(&text).0.to_owned()
719}
720
721/// One part of a vCon body as text, as the console shows a reveal of it:
722/// the parties, the dialog or the analysis as indented JSON with inline
723/// media named by its size, or the subject. None for any other part and for
724/// a body that cannot be read in parts.
725#[must_use]
726pub fn section(text: &str, part: Part) -> Option<String> {
727    let vcon = readable(text)?;
728    match part {
729        Part::Parties => Some(listed(vcon.get("parties"))),
730        Part::Dialog => Some(listed(vcon.get("dialog"))),
731        Part::Analysis => Some(listed(vcon.get("analysis"))),
732        Part::Subject => Some(
733            text_field(&vcon, "subject")
734                .filter(|subject| !subject.is_empty())
735                .unwrap_or("none")
736                .to_owned(),
737        ),
738        Part::Links | Part::All | Part::Audio => None,
739    }
740}
741
742#[cfg(test)]
743mod tests {
744    use serde_json::json;
745
746    use super::*;
747
748    /// The cases of the rule; the console's display is tested against them
749    /// too (console-tests/tests/masked-view.spec.js).
750    const CASES: &str = include_str!("../tests/data/masked-cases.json");
751
752    fn cases() -> Vec<(String, String, Value)> {
753        let cases: Vec<Value> = serde_json::from_str(CASES).expect("the cases are JSON");
754        cases
755            .into_iter()
756            .map(|case| {
757                (
758                    case["name"].as_str().expect("a name").to_owned(),
759                    case["body"].as_str().expect("a body").to_owned(),
760                    case["summary"].clone(),
761                )
762            })
763            .collect()
764    }
765
766    fn masked(vcon: &Value) -> Summary {
767        summary(&vcon.to_string())
768    }
769
770    // Success.
771
772    #[test]
773    fn each_case_is_summarized_as_the_case_states() {
774        let cases = cases();
775        assert!(cases.len() > 20, "there are cases to compare");
776        for (name, body, wanted) in cases {
777            let made = serde_json::to_value(summary(&body)).expect("a summary is JSON");
778            assert_eq!(made, wanted, "the case {name}");
779        }
780    }
781
782    #[test]
783    fn view_masked_alone_asks_for_the_masked_view() {
784        assert_eq!(from_query(Some("view=masked")), Ok(true), "the view");
785    }
786
787    #[test]
788    fn a_read_without_the_parameter_is_not_the_masked_view() {
789        for query in [None, Some(""), Some("reveal=all"), Some("viewed=masked")] {
790            assert_eq!(from_query(query), Ok(false), "{query:?}");
791        }
792    }
793
794    #[test]
795    fn a_number_shows_its_last_four_digits() {
796        assert_eq!(
797            mask_tel(&json!("+1 212 555 0142")),
798            "number ending 0142",
799            "masked"
800        );
801    }
802
803    #[test]
804    fn an_address_shows_its_domain_in_lower_case() {
805        assert_eq!(
806            mask_mail(&json!("ada@Example.COM")),
807            "address at example.com",
808            "masked"
809        );
810    }
811
812    #[test]
813    fn a_party_line_names_number_address_and_name_in_that_order() {
814        let party =
815            json!({"name": "Ada Example", "mailto": "ada@example.com", "tel": "+12125550142"});
816        assert_eq!(
817            party_line(&party, 2),
818            "Party 3: number ending 0142; address at example.com; name hidden",
819            "the line"
820        );
821    }
822
823    #[test]
824    fn a_dialog_line_shows_type_start_length_and_parties_and_no_content() {
825        let dialog = json!({"type": "text", "start": "2026-11-10T09:15:05Z", "duration": 30,
826            "parties": [0, 1], "body": "Ada said hello"});
827        let line = dialog_line(&dialog, 0);
828        assert_eq!(
829            line,
830            "Dialog 1: text, 2026-11-10 09:15:05 UTC+00:00, 30 s, parties 1, 2; content hidden",
831            "the line"
832        );
833        assert!(!line.contains("hello"), "no content");
834    }
835
836    #[test]
837    fn a_time_with_an_offset_is_shown_in_utc() {
838        assert_eq!(
839            instant(&json!("2026-11-10T11:15:00+02:00")),
840            "2026-11-10 09:15:00 UTC+00:00",
841            "in UTC"
842        );
843    }
844
845    #[test]
846    fn a_whole_number_of_seconds_is_written_without_a_fraction() {
847        let made =
848            serde_json::to_string(&masked(&json!({"dialog": [{"duration": 30}]}))).expect("JSON");
849        assert!(made.contains(r#""seconds":30,"#), "{made}");
850    }
851
852    #[test]
853    fn numbers_are_written_as_javascript_writes_them() {
854        for (number, text) in [
855            (30.0, "30"),
856            (12.5, "12.5"),
857            (1e21, "1e+21"),
858            (1e-7, "1e-7"),
859            (1.5e-7, "1.5e-7"),
860            (1e20, "100000000000000000000"),
861            (0.1 + 0.2, "0.30000000000000004"),
862        ] {
863            assert_eq!(js_number(number), text, "{number}");
864        }
865    }
866
867    #[test]
868    fn a_signed_vcons_header_names_its_algorithm_key_and_thumbprint() {
869        let cases = cases();
870        let (_, body, _) = cases
871            .iter()
872            .find(|(name, _, _)| name == "a signed vCon")
873            .expect("the signed case");
874        let made = summary(body);
875        assert_eq!(made.form, "signed (JWS)", "the form");
876        assert_eq!(
877            made.signature,
878            Some(Signature {
879                alg: "ES256".to_owned(),
880                kid: "key-1".to_owned(),
881                x5t: "x5t-example".to_owned()
882            }),
883            "the header"
884        );
885    }
886
887    #[test]
888    fn links_say_where_they_are_in_the_consoles_order() {
889        let vcon = json!({"analysis": [{"url": "https://a.example.com/t"}],
890            "dialog": [{"url": "https://media.example.com/a.wav"}, {"body": "x"}],
891            "attachments": [{}, {"url": "https://files.example.com/x.pdf"}]});
892        let found: Vec<(String, String)> = links(&vcon.to_string())
893            .into_iter()
894            .map(|link| (link.place, link.url))
895            .collect();
896        assert_eq!(
897            found,
898            [
899                (
900                    "dialog 1".to_owned(),
901                    "https://media.example.com/a.wav".to_owned()
902                ),
903                (
904                    "attachment 2".to_owned(),
905                    "https://files.example.com/x.pdf".to_owned()
906                ),
907                (
908                    "analysis 1".to_owned(),
909                    "https://a.example.com/t".to_owned()
910                ),
911            ],
912            "the links"
913        );
914    }
915
916    #[test]
917    fn a_section_shows_the_part_with_inline_media_named_by_its_size() {
918        let vcon = json!({"dialog": [{"type": "recording", "encoding": "base64url", "body": "AAAABBBB"}],
919            "subject": "Renewal", "parties": [{"name": "Ada Example"}]});
920        let text = vcon.to_string();
921        let dialog = section(&text, Part::Dialog).expect("a dialog section");
922        assert!(
923            dialog.contains("[8 characters of base64url, not shown]"),
924            "{dialog}"
925        );
926        assert!(!dialog.contains("AAAABBBB"), "{dialog}");
927        assert_eq!(
928            section(&text, Part::Subject).as_deref(),
929            Some("Renewal"),
930            "the subject"
931        );
932        let parties = section(&text, Part::Parties).expect("a parties section");
933        assert!(parties.contains("Ada Example"), "{parties}");
934    }
935
936    // Failure.
937
938    #[test]
939    fn a_view_other_than_masked_is_refused() {
940        for query in ["view=whole", "view=MASKED", "view=masked2", "view="] {
941            assert_eq!(from_query(Some(query)), Err(BadQuery), "{query}");
942        }
943    }
944
945    #[test]
946    fn the_view_given_twice_is_refused() {
947        for query in ["view=masked&view=masked", "view=masked&view=whole"] {
948            assert_eq!(from_query(Some(query)), Err(BadQuery), "{query}");
949        }
950    }
951
952    /// The masked view and a reveal are two answers: one read cannot ask
953    /// for both.
954    #[test]
955    fn the_view_beside_a_reveal_or_another_parameter_is_refused() {
956        for query in [
957            "view=masked&reveal=all",
958            "reveal=parties&view=masked",
959            "limit=3&view=masked",
960        ] {
961            assert_eq!(from_query(Some(query)), Err(BadQuery), "{query}");
962        }
963    }
964
965    #[test]
966    fn the_parameter_with_no_value_is_refused() {
967        for query in ["view", "view&x=1"] {
968            assert_eq!(from_query(Some(query)), Err(BadQuery), "{query}");
969        }
970    }
971
972    #[test]
973    fn text_that_is_not_json_is_not_read() {
974        let made = summary("{\"subject\":");
975        assert_eq!(
976            (made.form.as_str(), made.subject.as_str()),
977            ("not JSON", "not readable"),
978            "not read"
979        );
980    }
981
982    #[test]
983    fn an_encrypted_vcon_is_not_decoded() {
984        let made =
985            masked(&json!({"ciphertext": "x", "subject": "Renewal", "parties": [{"name": "Ada"}]}));
986        assert_eq!(made.form, "encrypted (JWE)", "the form");
987        assert!(made.parties.is_empty(), "no party is read");
988    }
989
990    #[test]
991    fn a_number_too_short_or_not_text_is_hidden_whole() {
992        for value in [
993            json!("555-0101"),
994            json!(2_125_550_142_u64),
995            json!(null),
996            json!(""),
997        ] {
998            assert_eq!(mask_tel(&value), "number hidden", "{value}");
999        }
1000    }
1001
1002    #[test]
1003    fn an_address_without_a_local_part_or_a_domain_is_hidden_whole() {
1004        for value in [
1005            json!("@example.com"),
1006            json!("ada@"),
1007            json!("ada@  "),
1008            json!("ada"),
1009            json!(7),
1010        ] {
1011            assert_eq!(mask_mail(&value), "address hidden", "{value}");
1012        }
1013    }
1014
1015    #[test]
1016    fn text_that_is_not_a_date_time_is_never_shown() {
1017        for value in [
1018            "Ada called about her account",
1019            "1",
1020            "Jan 2 2026",
1021            "2026-11-10T09:15Z",
1022            "2026-11-10 09:15:00Z",
1023            "2026-11-10T09:15:00",
1024            "2026-11-10T09:15:00.Z",
1025            "x UTC+00:00",
1026        ] {
1027            assert_eq!(instant(&json!(value)), "", "{value}");
1028        }
1029    }
1030
1031    #[test]
1032    fn a_day_hour_second_or_offset_that_does_not_exist_is_no_time() {
1033        for value in [
1034            "2026-02-30T00:00:00Z",
1035            "2026-13-01T00:00:00Z",
1036            "2026-01-01T24:00:00Z",
1037            "2026-01-01T00:60:00Z",
1038            "2026-01-01T23:59:60Z",
1039            "2026-01-01T00:00:00+24:00",
1040            "2026-01-01T00:00:00+01:60",
1041        ] {
1042            assert_eq!(instant(&json!(value)), "", "{value}");
1043        }
1044    }
1045
1046    #[test]
1047    fn a_party_or_dialog_that_is_not_an_object_is_named_and_not_read() {
1048        assert_eq!(
1049            party_line(&json!("Ada Example"), 0),
1050            "Party 1: not an object",
1051            "party"
1052        );
1053        assert_eq!(
1054            dialog_line(&json!(["hello"]), 1),
1055            "Dialog 2: not an object",
1056            "dialog"
1057        );
1058    }
1059
1060    #[test]
1061    fn a_body_that_cannot_be_read_in_parts_has_no_section_and_no_links() {
1062        for text in ["{\"ciphertext\":\"x\"}", "[1]", "not JSON"] {
1063            assert_eq!(section(text, Part::Parties), None, "{text}");
1064            assert_eq!(links(text), [], "{text}");
1065        }
1066    }
1067
1068    #[test]
1069    fn only_the_four_parts_have_a_section() {
1070        let text = json!({"subject": "Renewal"}).to_string();
1071        for part in [Part::Links, Part::All, Part::Audio] {
1072            assert_eq!(section(&text, part), None, "{part:?}");
1073        }
1074    }
1075
1076    // Edge.
1077
1078    #[test]
1079    fn an_encoded_parameter_is_the_parameter() {
1080        for query in ["%76iew=masked", "view=%6Dasked", "vi%65w=mask%65d"] {
1081            assert_eq!(from_query(Some(query)), Ok(true), "{query}");
1082        }
1083    }
1084
1085    #[test]
1086    fn an_empty_piece_beside_the_view_names_nothing() {
1087        for query in ["view=masked&", "&view=masked", "&&view=masked&&"] {
1088            assert_eq!(from_query(Some(query)), Ok(true), "{query}");
1089        }
1090    }
1091
1092    #[test]
1093    fn a_fraction_of_a_second_is_dropped_not_rounded() {
1094        assert_eq!(
1095            instant(&json!("2026-11-10T09:15:00.999999999Z")),
1096            "2026-11-10 09:15:00 UTC+00:00",
1097            "dropped"
1098        );
1099    }
1100
1101    #[test]
1102    fn lower_case_t_and_z_are_read() {
1103        assert_eq!(
1104            instant(&json!("2026-11-10t09:15:00z")),
1105            "2026-11-10 09:15:00 UTC+00:00",
1106            "read"
1107        );
1108    }
1109
1110    #[test]
1111    fn a_time_outside_the_years_1_to_9999_in_utc_is_no_time() {
1112        for value in [
1113            "9999-12-31T23:30:00-01:00",
1114            "0001-01-01T00:30:00+01:00",
1115            "0000-06-01T00:00:00Z",
1116        ] {
1117            assert_eq!(instant(&json!(value)), "", "{value}");
1118        }
1119        assert_eq!(
1120            instant(&json!("0001-01-01T00:00:00Z")),
1121            "0001-01-01 00:00:00 UTC+00:00",
1122            "year 1"
1123        );
1124        assert_eq!(
1125            instant(&json!("9999-12-31T23:59:59Z")),
1126            "9999-12-31 23:59:59 UTC+00:00",
1127            "year 9999"
1128        );
1129    }
1130
1131    #[test]
1132    fn a_leap_day_is_a_day() {
1133        assert_eq!(
1134            instant(&json!("2024-02-29T12:00:00Z")),
1135            "2024-02-29 12:00:00 UTC+00:00",
1136            "2024"
1137        );
1138        assert_eq!(instant(&json!("2026-02-29T12:00:00Z")), "", "2026 has none");
1139    }
1140
1141    #[test]
1142    fn a_place_written_with_a_fraction_of_zero_is_a_place() {
1143        let line = dialog_line(&json!({"type": "text", "parties": [0.0, 2.0]}), 0);
1144        assert!(line.contains("parties 1, 3"), "{line}");
1145        let line = dialog_line(&json!({"type": "text", "parties": [0, 1.5]}), 0);
1146        assert!(line.contains("no parties"), "{line}");
1147    }
1148
1149    #[test]
1150    fn a_body_with_a_byte_order_mark_is_read_as_a_browser_reads_it() {
1151        let text = text_of(b"\xef\xbb\xbf{\"subject\":\"Renewal\"}");
1152        assert_eq!(
1153            summary(&text).subject,
1154            "present, hidden",
1155            "the mark is dropped"
1156        );
1157        assert_eq!(
1158            text_of(b"{\"a\":\"\xff\"}"),
1159            "{\"a\":\"\u{fffd}\"}",
1160            "a bad byte is replaced"
1161        );
1162    }
1163
1164    #[test]
1165    fn a_domain_loses_the_spaces_javascript_trims() {
1166        for value in [
1167            "ada@ example.com\u{a0}",
1168            "ada@\u{feff}example.com",
1169            "ada@\texample.com\n",
1170        ] {
1171            assert_eq!(
1172                mask_mail(&json!(value)),
1173                "address at example.com",
1174                "{value:?}"
1175            );
1176        }
1177    }
1178
1179    #[test]
1180    fn digits_are_counted_across_punctuation_and_only_ascii_digits_count() {
1181        assert_eq!(
1182            mask_tel(&json!("+1 (212) 555-0199")),
1183            "number ending 0199",
1184            "punctuation"
1185        );
1186        assert_eq!(
1187            mask_tel(&json!("\u{661}\u{662}\u{663}\u{664}5550199")),
1188            "number hidden",
1189            "Arabic-Indic digits"
1190        );
1191    }
1192
1193    #[test]
1194    fn the_summary_holds_no_name_subject_number_or_address() {
1195        let vcon = json!({"subject": "Ada's divorce", "created_at": "Ada's birthday",
1196            "parties": [{"name": "Ada Example", "tel": "+12125550142", "mailto": "ada@example.com"}],
1197            "dialog": [{"type": "text", "start": "Ada's call", "body": "Ada said hello"}]});
1198        let made = serde_json::to_string(&masked(&vcon)).expect("JSON");
1199        for hidden in ["Ada", "divorce", "2125550142", "ada@", "hello"] {
1200            assert!(!made.contains(hidden), "{hidden} in {made}");
1201        }
1202    }
1203
1204    #[test]
1205    fn a_long_text_is_cut_at_the_limit_and_says_what_was_left_out() {
1206        let text = "x".repeat(DISPLAY_LIMIT + 5);
1207        let (kept, left) = shown(&text);
1208        assert_eq!((kept.len(), left), (DISPLAY_LIMIT, 5), "cut");
1209        assert_eq!(shown("short"), ("short", 0), "kept whole");
1210    }
1211
1212    #[test]
1213    fn a_summary_read_back_is_the_summary() {
1214        let made =
1215            masked(&json!({"dialog": [{"duration": 12.5}], "parties": [{"tel": "+12125550142"}]}));
1216        let text = serde_json::to_string(&made).expect("JSON");
1217        let back: Summary = serde_json::from_str(&text).expect("read back");
1218        assert_eq!(back, made, "the same");
1219    }
1220
1221    #[test]
1222    fn an_empty_list_section_says_none() {
1223        let text = json!({"analysis": []}).to_string();
1224        assert_eq!(
1225            section(&text, Part::Analysis).as_deref(),
1226            Some("none"),
1227            "no analysis"
1228        );
1229        assert_eq!(
1230            section(&text, Part::Subject).as_deref(),
1231            Some("none"),
1232            "no subject"
1233        );
1234    }
1235
1236    // The recordings the console plays, listed by the view.
1237
1238    /// A dialog holding `body` as an inline recording declared as `type`.
1239    fn inline(body: &str, declared: &str) -> Value {
1240        json!({"type": "recording", "body": body, "encoding": "base64url", "mediatype": declared})
1241    }
1242
1243    fn listed(dialogs: &[Value], limit: u64) -> Vec<Recording> {
1244        let vcon = json!({ "dialog": dialogs });
1245        recordings_within(vcon.as_object().expect("an object"), limit)
1246    }
1247
1248    fn recording(dialog: usize, played: &str) -> Recording {
1249        Recording {
1250            dialog,
1251            r#type: played.to_owned(),
1252        }
1253    }
1254
1255    #[test]
1256    fn a_recording_the_console_plays_is_listed_by_its_dialog_number() {
1257        let made = masked(&json!({"dialog": [{"type": "text"}, inline("AAAA", "audio/wav")]}));
1258        assert_eq!(
1259            made.recordings,
1260            vec![recording(2, "audio/wav")],
1261            "the second dialog"
1262        );
1263    }
1264
1265    #[test]
1266    fn a_recording_is_listed_as_the_type_it_plays_as_not_the_name_it_was_given() {
1267        for (declared, played) in [
1268            ("audio/x-wav", "audio/wav"),
1269            ("audio/wave", "audio/wav"),
1270            ("audio/vnd.wave", "audio/wav"),
1271            ("audio/x-mp3", "audio/mpeg"),
1272            ("audio/mp3", "audio/mpeg"),
1273            ("audio/x-ogg", "audio/ogg"),
1274            ("audio/opus", "audio/opus"),
1275        ] {
1276            assert_eq!(
1277                listed(&[inline("AAAA", declared)], 100),
1278                vec![recording(1, played)],
1279                "{declared}"
1280            );
1281        }
1282    }
1283
1284    #[test]
1285    fn a_recording_of_the_size_limit_is_listed() {
1286        // Four characters of base64 are three bytes.
1287        assert_eq!(
1288            listed(&[inline("AAAA", "audio/wav")], 3),
1289            vec![recording(1, "audio/wav")],
1290            "at the limit"
1291        );
1292    }
1293
1294    #[test]
1295    fn the_padding_of_a_body_is_not_counted_in_its_size() {
1296        // "AAA=" is two bytes once its padding is dropped.
1297        assert_eq!(
1298            listed(&[inline("AAA=", "audio/wav")], 2),
1299            vec![recording(1, "audio/wav")],
1300            "two bytes"
1301        );
1302    }
1303
1304    #[test]
1305    fn the_view_lists_the_recordings_up_to_the_consoles_limit() {
1306        assert_eq!(AUDIO_LIMIT, 100 * 1024 * 1024, "100 MiB");
1307        let console = include_str!("../console/format.js");
1308        assert!(
1309            console.contains("export const AUDIO_LIMIT = 100 * 1024 * 1024;"),
1310            "format.js plays the same size"
1311        );
1312    }
1313
1314    #[test]
1315    fn the_view_lists_the_types_and_names_the_console_plays() {
1316        let console = include_str!("../console/format.js");
1317        let types = AUDIO_TYPES
1318            .iter()
1319            .map(|t| format!("\"{t}\""))
1320            .collect::<Vec<_>>()
1321            .join(", ");
1322        assert!(
1323            console.contains(&format!(
1324                "export const AUDIO_TYPES = Object.freeze([{types}]);"
1325            )),
1326            "format.js plays {types}"
1327        );
1328        for (name, played) in AUDIO_ALIASES {
1329            assert!(
1330                console.contains(&format!("  \"{name}\": \"{played}\",\n")),
1331                "format.js plays {name} as {played}"
1332            );
1333        }
1334        assert_eq!(
1335            console.matches("\": \"audio/").count(),
1336            AUDIO_ALIASES.len(),
1337            "format.js has no other name"
1338        );
1339    }
1340
1341    #[test]
1342    fn a_summary_without_recordings_reads_back_with_none() {
1343        let mut made = serde_json::to_value(masked(&json!({}))).expect("JSON");
1344        made.as_object_mut()
1345            .expect("an object")
1346            .remove("recordings");
1347        let back: Summary = serde_json::from_value(made).expect("read back");
1348        assert!(back.recordings.is_empty(), "none");
1349    }
1350
1351    #[test]
1352    fn a_recording_reads_back_as_the_same_recording() {
1353        let made = masked(&json!({"dialog": [inline("AAAA", "audio/ogg")]}));
1354        let text = serde_json::to_string(&made).expect("JSON");
1355        assert!(
1356            text.contains(r#""recordings":[{"dialog":1,"type":"audio/ogg"}]"#),
1357            "{text}"
1358        );
1359        let back: Summary = serde_json::from_str(&text).expect("read back");
1360        assert_eq!(back, made, "the same");
1361    }
1362
1363    #[test]
1364    fn a_recording_over_the_size_limit_is_not_listed() {
1365        assert_eq!(
1366            listed(&[inline("AAAA", "audio/wav")], 2),
1367            vec![],
1368            "one byte over"
1369        );
1370    }
1371
1372    #[test]
1373    fn a_recording_kept_at_a_link_is_not_listed() {
1374        let dialog = json!({"type": "recording", "url": "https://media.example.com/a.wav", "mediatype": "audio/wav"});
1375        assert_eq!(listed(&[dialog], 100), vec![], "at a link");
1376    }
1377
1378    #[test]
1379    fn a_body_that_is_not_encoded_media_is_not_listed() {
1380        for encoding in [
1381            json!("none"),
1382            json!("json"),
1383            json!(""),
1384            json!(null),
1385            json!(64),
1386        ] {
1387            let dialog = json!({"body": "AAAA", "encoding": encoding, "mediatype": "audio/wav"});
1388            assert_eq!(listed(&[dialog], 100), vec![], "{encoding}");
1389        }
1390    }
1391
1392    #[test]
1393    fn a_body_that_is_not_text_is_not_listed() {
1394        for body in [json!(null), json!(7), json!(["AAAA"]), json!("")] {
1395            let dialog = json!({"body": body, "encoding": "base64", "mediatype": "audio/wav"});
1396            assert_eq!(listed(&[dialog], 100), vec![], "{body}");
1397        }
1398    }
1399
1400    #[test]
1401    fn a_type_the_console_does_not_play_is_not_listed() {
1402        for declared in [
1403            "video/mp4",
1404            "application/ogg",
1405            "audio/flac",
1406            "audio",
1407            "",
1408            "  ",
1409        ] {
1410            assert_eq!(
1411                listed(&[inline("AAAA", declared)], 100),
1412                vec![],
1413                "{declared:?}"
1414            );
1415        }
1416    }
1417
1418    #[test]
1419    fn a_recording_that_declares_no_type_is_not_listed() {
1420        let dialog = json!({"body": "AAAA", "encoding": "base64url"});
1421        assert_eq!(listed(&[dialog], 100), vec![], "no type");
1422    }
1423
1424    #[test]
1425    fn a_media_type_that_is_not_text_hides_the_older_name() {
1426        // As in format.js: `mediatype` is read when present, so `mimetype`
1427        // is not read in its place.
1428        let dialog = json!({"body": "AAAA", "encoding": "base64url", "mediatype": 7, "mimetype": "audio/wav"});
1429        assert_eq!(listed(&[dialog], 100), vec![], "no type");
1430    }
1431
1432    #[test]
1433    fn an_encrypted_or_unreadable_vcon_lists_no_recording() {
1434        for text in [
1435            json!({"ciphertext": "x", "dialog": [inline("AAAA", "audio/wav")]}).to_string(),
1436            "not JSON".to_owned(),
1437            "[]".to_owned(),
1438        ] {
1439            assert_eq!(summary(&text).recordings, vec![], "{text}");
1440        }
1441    }
1442
1443    #[test]
1444    fn the_older_name_of_the_media_type_is_read_when_there_is_no_media_type() {
1445        let dialog = json!({"body": "AAAA", "encoding": "base64", "mimetype": "audio/mpeg"});
1446        assert_eq!(
1447            listed(&[dialog], 100),
1448            vec![recording(1, "audio/mpeg")],
1449            "mimetype"
1450        );
1451    }
1452
1453    #[test]
1454    fn a_type_is_read_in_any_case_without_its_parameters() {
1455        for declared in ["AUDIO/WAV", " audio/wav ; codecs=1", "Audio/Wav;rate=8000"] {
1456            assert_eq!(
1457                listed(&[inline("AAAA", declared)], 100),
1458                vec![recording(1, "audio/wav")],
1459                "{declared:?}"
1460            );
1461        }
1462    }
1463
1464    #[test]
1465    fn a_parameter_of_the_type_never_reaches_the_view() {
1466        let made = masked(&json!({"dialog": [inline("AAAA", "audio/wav; name=Ada Example")]}));
1467        let text = serde_json::to_string(&made).expect("JSON");
1468        assert!(!text.contains("Ada"), "{text}");
1469        assert_eq!(made.recordings, vec![recording(1, "audio/wav")], "listed");
1470    }
1471
1472    #[test]
1473    fn dialogs_that_are_not_objects_keep_the_numbers_of_the_others() {
1474        assert_eq!(
1475            listed(&[json!("x"), json!(null), inline("AAAA", "audio/wav")], 100),
1476            vec![recording(3, "audio/wav")],
1477            "the third dialog"
1478        );
1479    }
1480
1481    #[test]
1482    fn a_dialog_list_that_is_not_a_list_lists_no_recording() {
1483        let made = masked(&json!({"dialog": inline("AAAA", "audio/wav")}));
1484        assert_eq!(made.recordings, vec![], "not a list");
1485    }
1486}