domain-check-lib 1.2.0

A fast, robust library for checking domain availability using RDAP and WHOIS protocols
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
//! RFC 10023 `_for-sale` records.
//!
//! A domain holder can publish `_for-sale.<domain> TXT "v=FORSALE1;..."` to
//! signal that a registered domain is available for purchase. The parser here
//! is pure; the DNS lookup is compiled only with the `forsale` feature.

use crate::error::DomainCheckError;
use crate::types::{CheckConfig, DomainResult};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use std::net::IpAddr;
use std::sync::{Arc, Mutex};
use std::time::Duration;

/// Leaf node name reserved by RFC 10023.
pub const NODE_NAME: &str = "_for-sale";

const VERSION_TAG: &str = "v=FORSALE1;";
/// Maximum octets for fcod/ftxt/fval content values (RFC 10023 §2.1).
const MAX_VALUE_LEN: usize = 239;

/// Parsed `_for-sale` RRset. Present means the domain is for sale,
/// even when every list is empty (RFC 10023 §2.1).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ForSaleInfo {
    /// `furi=` contact URIs.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub uris: Vec<ForSaleUri>,
    /// `fval=` asking prices. Indicative only.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub prices: Vec<ForSalePrice>,
    /// `ftxt=` free text, sanitized.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub texts: Vec<String>,
    /// `fcod=` codes, meaningful only to cooperating parties.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub codes: Vec<String>,
}

impl ForSaleInfo {
    /// True when a valid version tag was found but no usable content.
    pub fn is_empty(&self) -> bool {
        self.uris.is_empty()
            && self.prices.is_empty()
            && self.texts.is_empty()
            && self.codes.is_empty()
    }

    /// First URI with a recommended scheme (http, https, mailto, tel).
    pub fn first_trusted_uri(&self) -> Option<&ForSaleUri> {
        self.uris.iter().find(|u| u.trusted)
    }
}

/// A `furi=` value. Untrusted schemes are kept but must not be shown as links.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ForSaleUri {
    pub value: String,
    /// Lowercased scheme, e.g. "https".
    pub scheme: String,
    /// Scheme is one RFC 10023 recommends: http, https, mailto, tel.
    pub trusted: bool,
}

/// A `fval=` asking price. The amount stays a string to avoid rounding.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ForSalePrice {
    pub currency: String,
    pub amount: String,
}

impl std::fmt::Display for ForSalePrice {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} {}", self.currency, self.amount)
    }
}

/// Absolute DNS name to query for `domain`, or `None` where RFC 10023
/// does not apply (empty names and the `.arpa` infrastructure TLD, §2.6).
pub fn record_name(domain: &str) -> Option<String> {
    let domain = domain.trim_end_matches('.').to_ascii_lowercase();
    if domain.is_empty() || domain == "arpa" || domain.ends_with(".arpa") {
        return None;
    }
    // Trailing dot: never let resolver search domains be appended.
    Some(format!("{NODE_NAME}.{domain}."))
}

/// Parse the TXT RRset at `_for-sale.<domain>`.
///
/// Each item is one TXT record given as its character-strings. Returns `None`
/// when no record carries a valid version tag, meaning the domain is not for sale.
pub fn parse_txt_records(records: &[Vec<Vec<u8>>]) -> Option<ForSaleInfo> {
    let mut info = ForSaleInfo::default();
    let mut valid = false;
    let mut seen = HashSet::new();

    for record in records {
        // §2.4 says publishers must use a single character-string, but
        // processors should be lenient and join them (§3.2; confirmed by the
        // RFC author on issue #33). Join bytes first: a split can fall inside
        // a multi-byte UTF-8 character.
        let text = String::from_utf8_lossy(&record.concat()).into_owned();
        let Some(content) = text.strip_prefix(VERSION_TAG) else {
            continue;
        };
        valid = true;

        // Spaces after the version tag are tolerated (§3.6).
        let content = content.trim_start_matches(' ');
        if !seen.insert(content.to_string()) {
            continue;
        }

        // One pair per record and the value runs to the end (§3.5), so
        // never split on ';' — URIs may contain one.
        let Some((tag, value)) = content.split_once('=') else {
            continue;
        };
        match tag {
            "ftxt" => push_text(&mut info.texts, value),
            "fcod" => push_text(&mut info.codes, value),
            "fval" => info.prices.extend(parse_price(value)),
            "furi" => info.uris.extend(parse_uri(value)),
            // Future tags (§2.2.5): the record still marks the domain for sale.
            _ => {}
        }
    }

    if !valid {
        return None;
    }

    // An RRset has no inherent order; sort for stable output.
    info.texts.sort();
    info.codes.sort();
    info.uris.sort_by(|a, b| a.value.cmp(&b.value));
    info.prices
        .sort_by(|a, b| (&a.currency, &a.amount).cmp(&(&b.currency, &b.amount)));
    Some(info)
}

fn push_text(list: &mut Vec<String>, value: &str) {
    if value.is_empty() || value.len() > MAX_VALUE_LEN {
        return;
    }
    let clean = sanitize(value);
    if !clean.is_empty() {
        list.push(clean);
    }
}

fn parse_price(value: &str) -> Option<ForSalePrice> {
    let value = value.trim();
    if value.len() < 2 || value.len() > MAX_VALUE_LEN {
        return None;
    }
    let split = value.find(|c: char| !c.is_ascii_uppercase())?;
    let (currency, amount) = value.split_at(split);
    let (int, frac) = match amount.split_once('.') {
        Some((i, f)) => (i, Some(f)),
        None => (amount, None),
    };
    let digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
    if currency.is_empty() || !digits(int) || frac.is_some_and(|f| !digits(f)) {
        return None;
    }
    Some(ForSalePrice {
        currency: currency.to_string(),
        amount: amount.to_string(),
    })
}

fn parse_uri(value: &str) -> Option<ForSaleUri> {
    let value = sanitize(value);
    // Spaces must be percent-encoded (§2.2.3).
    if value.contains(' ') {
        return None;
    }
    let (scheme, rest) = value.split_once(':')?;
    let mut chars = scheme.chars();
    let valid_scheme = chars.next().is_some_and(|c| c.is_ascii_alphabetic())
        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
    if !valid_scheme || rest.is_empty() {
        return None;
    }
    let scheme = scheme.to_ascii_lowercase();
    let trusted = match scheme.as_str() {
        "http" | "https" => rest
            .strip_prefix("//")
            .is_some_and(|r| !r.is_empty() && !r.starts_with('/')),
        "mailto" | "tel" => true,
        _ => false,
    };
    Some(ForSaleUri {
        value,
        scheme,
        trusted,
    })
}

/// Make holder-supplied text safe to print: no terminal escapes, no bidi
/// reordering, and no invisible characters that could hide text from a human
/// reader while an LLM still sees it (RFC 10023 §3.6, §4).
pub(crate) fn sanitize(value: &str) -> String {
    value
        .chars()
        .filter_map(|c| match c {
            '\t' | '\n' | '\r' | '\u{2028}' | '\u{2029}' => Some(' '),
            c if c.is_control() || is_bidi_control(c) || is_invisible(c) => None,
            c => Some(c),
        })
        .collect::<String>()
        .trim()
        .to_string()
}

/// Invisible format characters. Joiners (U+200C/U+200D) are kept because
/// emoji sequences and some scripts depend on them.
fn is_invisible(c: char) -> bool {
    matches!(
        c,
        '\u{00AD}' | '\u{180E}' | '\u{200B}' | '\u{2060}'..='\u{2064}' | '\u{FEFF}' | '\u{E0000}'..='\u{E007F}'
    )
}

fn is_bidi_control(c: char) -> bool {
    matches!(
        c,
        '\u{200E}' | '\u{200F}' | '\u{061C}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}'
    )
}

/// Upper bound for one `_for-sale` lookup; also capped by the check timeout.
const LOOKUP_TIMEOUT: Duration = Duration::from_secs(3);

/// Lookups that could not be answered (as opposed to "no record").
///
/// A failed lookup looks exactly like a domain that is not for sale, so
/// callers should tell the user when this is non-empty. See
/// [`DomainChecker::for_sale_failures`](crate::DomainChecker::for_sale_failures).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ForSaleFailures {
    /// Number of `_for-sale` lookups that failed
    pub count: usize,
    /// The most recent failure, including the DNS server(s) asked
    pub last_error: String,
}

/// Result of one `_for-sale` query.
#[cfg(feature = "forsale")]
#[derive(Debug)]
enum Outcome {
    Found(ForSaleInfo),
    NotForSale,
    Failed(String),
}

/// Runs `_for-sale` lookups for results that are not AVAILABLE. Inactive
/// when not requested, when built without the `forsale` feature, or when
/// the system resolver configuration cannot be read.
#[derive(Clone)]
pub(crate) struct ForSaleLookup {
    #[cfg(feature = "forsale")]
    resolver: Option<hickory_resolver::TokioResolver>,
    /// The DNS servers in use, for error messages
    #[cfg_attr(not(feature = "forsale"), allow(dead_code))]
    servers: Arc<str>,
    #[cfg_attr(not(feature = "forsale"), allow(dead_code))]
    timeout: Duration,
    failures: Arc<Mutex<Option<ForSaleFailures>>>,
}

impl ForSaleLookup {
    /// `dns_server` replaces the operating system's resolvers.
    pub(crate) fn new(config: &CheckConfig, dns_server: Option<IpAddr>) -> Self {
        let timeout = config.timeout.min(LOOKUP_TIMEOUT);
        let failures = Arc::default();
        #[cfg(feature = "forsale")]
        {
            let (resolver, servers) = if config.check_for_sale {
                build_resolver(dns_server).map_or((None, "".into()), |(r, s)| (Some(r), s))
            } else {
                (None, "".into())
            };
            Self {
                resolver,
                servers,
                timeout,
                failures,
            }
        }
        #[cfg(not(feature = "forsale"))]
        {
            let _ = (config.check_for_sale, dns_server);
            Self {
                servers: "".into(),
                timeout,
                failures,
            }
        }
    }

    pub(crate) fn is_active(&self) -> bool {
        #[cfg(feature = "forsale")]
        {
            self.resolver.is_some()
        }
        #[cfg(not(feature = "forsale"))]
        {
            false
        }
    }

    /// Lookups that failed so far, if any.
    pub(crate) fn failures(&self) -> Option<ForSaleFailures> {
        self.failures.lock().ok()?.clone()
    }

    /// Attach for-sale info to a result that is not AVAILABLE. Never fails
    /// and never changes the availability verdict.
    pub(crate) async fn annotate(&self, result: &mut DomainResult) {
        if result.available != Some(true) {
            result.for_sale = self.lookup_domain(&result.domain).await;
        }
    }

    /// Turn a failed availability check into an UNKNOWN result when the
    /// domain publishes a `_for-sale` record (a record means it is
    /// registered, even when RDAP and WHOIS could not say so).
    pub(crate) async fn annotate_error(
        &self,
        domain: &str,
        error: DomainCheckError,
    ) -> Result<DomainResult, DomainCheckError> {
        if matches!(error, DomainCheckError::InvalidDomain { .. }) || !self.is_active() {
            return Err(error);
        }
        match self.lookup_domain(domain).await {
            Some(info) => Ok(DomainResult {
                domain: domain.to_string(),
                available: None,
                info: None,
                check_duration: None,
                method_used: crate::types::CheckMethod::Unknown,
                error_message: Some(error.to_string()),
                for_sale: Some(info),
            }),
            None => Err(error),
        }
    }

    async fn lookup_domain(&self, domain: &str) -> Option<ForSaleInfo> {
        #[cfg(feature = "forsale")]
        if let Some(resolver) = &self.resolver {
            match lookup(resolver, domain, self.timeout).await {
                Outcome::Found(info) => return Some(info),
                Outcome::NotForSale => {}
                Outcome::Failed(error) => self.record_failure(error),
            }
        }
        #[cfg(not(feature = "forsale"))]
        let _ = domain;
        None
    }

    #[cfg(feature = "forsale")]
    fn record_failure(&self, error: String) {
        if let Ok(mut failures) = self.failures.lock() {
            let entry = failures.get_or_insert(ForSaleFailures {
                count: 0,
                last_error: String::new(),
            });
            entry.count += 1;
            entry.last_error = format!("DNS server {}: {error}", self.servers);
        }
    }
}

/// Build a resolver for `dns_server`, or for the operating system's DNS
/// settings. Returns it with a printable list of the servers it will ask.
#[cfg(feature = "forsale")]
fn build_resolver(
    dns_server: Option<IpAddr>,
) -> Option<(hickory_resolver::TokioResolver, Arc<str>)> {
    use hickory_resolver::config::{NameServerConfig, ResolverConfig, ResolverOpts};
    use hickory_resolver::net::runtime::TokioRuntimeProvider;

    let (config, mut options) = match dns_server {
        Some(ip) => (
            ResolverConfig::from_name_servers(vec![NameServerConfig::udp_and_tcp(ip)]),
            ResolverOpts::default(),
        ),
        None => hickory_resolver::system_conf::read_system_conf().ok()?,
    };
    let mut servers: Vec<String> = config
        .name_servers()
        .iter()
        .map(|ns| ns.ip.to_string())
        .collect();
    servers.dedup();
    // hickory 0.26 gives up instead of retrying over TCP when two parallel
    // UDP queries both come back truncated, so large RRsets (e.g.
    // _for-sale.j78.nl) would silently go missing.
    options.num_concurrent_reqs = 1;
    let mut builder = hickory_resolver::TokioResolver::builder_with_config(
        config,
        TokioRuntimeProvider::default(),
    );
    *builder.options_mut() = options;
    Some((builder.build().ok()?, servers.join(", ").into()))
}

/// Errors caused by the queried domain's own DNS (SERVFAIL: broken
/// delegation or DNSSEC), not by the user's resolver. Nothing to report:
/// such a domain cannot publish a readable record anyway.
#[cfg(feature = "forsale")]
fn is_domain_side_error(error: &hickory_resolver::net::NetError) -> bool {
    use hickory_resolver::net::{DnsError, NetError};
    use hickory_resolver::proto::op::ResponseCode;

    matches!(
        error,
        NetError::Dns(DnsError::ResponseCode(ResponseCode::ServFail))
    )
}

#[cfg(all(test, feature = "forsale"))]
impl ForSaleLookup {
    /// Test-only: a lookup that queries a single, specific nameserver.
    fn with_nameserver(ip: IpAddr, timeout: Duration) -> Self {
        let config = CheckConfig::default()
            .with_for_sale(true)
            .with_timeout(timeout);
        Self::new(&config, Some(ip))
    }
}

#[cfg(feature = "forsale")]
async fn lookup(
    resolver: &hickory_resolver::TokioResolver,
    domain: &str,
    timeout: Duration,
) -> Outcome {
    use hickory_resolver::proto::rr::RData;

    let Some(name) = record_name(domain) else {
        return Outcome::NotForSale;
    };
    let answer = match tokio::time::timeout(timeout, resolver.txt_lookup(name.as_str())).await {
        Err(_) => return Outcome::Failed(format!("no answer within {timeout:?}")),
        Ok(Err(e)) if e.is_no_records_found() || e.is_nx_domain() || is_domain_side_error(&e) => {
            return Outcome::NotForSale
        }
        Ok(Err(e)) => return Outcome::Failed(e.to_string()),
        Ok(Ok(answer)) => answer,
    };
    let records: Vec<Vec<Vec<u8>>> = answer
        .answers()
        .iter()
        .filter_map(|record| match &record.data {
            RData::TXT(txt) => Some(txt.txt_data.iter().map(|s| s.to_vec()).collect()),
            _ => None,
        })
        .collect();
    match parse_txt_records(&records) {
        Some(info) => Outcome::Found(info),
        None => Outcome::NotForSale,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn rec(s: &str) -> Vec<Vec<u8>> {
        vec![s.as_bytes().to_vec()]
    }
    fn parse(records: &[&str]) -> Option<ForSaleInfo> {
        let rs: Vec<Vec<Vec<u8>>> = records.iter().map(|s| rec(s)).collect();
        parse_txt_records(&rs)
    }

    // ── version tag (§2.1) — variants published at _for-sale.forsale.testdns.nl ──
    #[test]
    fn version_tag_variants() {
        assert!(parse(&["v=FORSALE1;"]).is_some());
        assert!(parse(&["v=FORSALE1"]).is_none());
        assert!(parse(&["v=FORSALE"]).is_none());
        assert!(parse(&["v=FORSALE;"]).is_none());
        assert!(parse(&["v=FORSALE0;"]).is_none());
        assert!(parse(&["V=FORSALE1;"]).is_none(), "case-sensitive");
        assert!(parse(&["v=FORSALE10;"]).is_none());
        assert!(parse(&[" v=FORSALE1;"]).is_none(), "must start the record");
    }

    #[test]
    fn empty_rrset_is_not_for_sale() {
        assert!(parse(&[]).is_none());
        assert!(parse(&["v=spf1 -all", "I am for sale"]).is_none());
    }

    #[test]
    fn version_only_is_for_sale_and_empty() {
        let info = parse(&["v=FORSALE1;"]).unwrap();
        assert!(info.is_empty());
    }

    #[test]
    fn invalid_or_unknown_content_still_for_sale() {
        for r in [
            "v=FORSALE1;fcod=",
            "v=FORSALE1;foo=bar",
            "v=FORSALE1;garbage",
            "v=FORSALE1;fval=cheap",
        ] {
            let info = parse(&[r]).unwrap_or_else(|| panic!("{r} should be for sale"));
            assert!(info.is_empty(), "{r}");
        }
    }

    #[test]
    fn spaces_after_version_tolerated() {
        let info = parse(&["v=FORSALE1;   ftxt=hello"]).unwrap();
        assert_eq!(info.texts, vec!["hello"]);
    }

    #[test]
    fn records_without_version_are_ignored_alongside_valid() {
        let info = parse(&[
            "This line is not part of the ForSale record.",
            "v=FORSALE1;ftxt=hi",
        ])
        .unwrap();
        assert_eq!(info.texts, vec!["hi"]);
    }

    // ── RRset rules (§2.4) ──
    #[test]
    fn multi_string_record_is_concatenated() {
        // §2.4 forbids publishing these, but processors should be lenient (§3.2):
        // a domain clearly offered for sale must still be flagged.
        let split = vec![
            b"v=FORSALE1;".to_vec(),
            b"ftxt=foo".to_vec(),
            b" bar".to_vec(),
        ];
        let info = parse_txt_records(&[split]).unwrap();
        assert_eq!(info.texts, vec!["foo bar"]);
    }

    #[test]
    fn multi_string_split_inside_utf8_character() {
        // j78.nl splits a multi-byte character across strings; join bytes before decoding.
        let s = "v=FORSALE1;ftxt=𝙷i".as_bytes();
        let (a, b) = s.split_at(18); // inside the 4-byte 𝙷
        let info = parse_txt_records(&[vec![a.to_vec(), b.to_vec()]]).unwrap();
        assert_eq!(info.texts, vec!["𝙷i"]);
    }

    #[test]
    fn two_tags_in_one_record_is_for_sale_without_details() {
        // Published at _for-sale.nohats.ca: fval swallows the rest of the record.
        let info = parse(&["v=FORSALE1;fval=USD1000000;furi=mailto:forsale31337@nohats.ca?subject=I want to buy nohats.ca"]).unwrap();
        assert!(info.is_empty());
    }

    #[test]
    fn duplicates_are_collapsed_and_output_sorted() {
        let info = parse(&[
            "v=FORSALE1;ftxt=b",
            "v=FORSALE1;ftxt=a",
            "v=FORSALE1;ftxt=b",
            "v=FORSALE1;fval=USD5",
            "v=FORSALE1;fval=EUR9",
        ])
        .unwrap();
        assert_eq!(info.texts, vec!["a", "b"]);
        assert_eq!(info.prices[0].currency, "EUR");
        assert_eq!(info.prices[1].currency, "USD");
    }

    // ── tag parsing (§2.2, §3.5) ──
    #[test]
    fn all_tags_parse() {
        let info = parse(&[
            "v=FORSALE1;furi=https://example.nl/for-sale.txt",
            "v=FORSALE1;fval=EUR100000000",
            "v=FORSALE1;ftxt=See the URL for important information!",
            "v=FORSALE1;fcod=NLFS-NGYyYjEyZWY",
        ])
        .unwrap();
        assert_eq!(info.uris[0].value, "https://example.nl/for-sale.txt");
        assert!(info.uris[0].trusted);
        assert_eq!(info.prices[0].to_string(), "EUR 100000000");
        assert_eq!(info.texts[0], "See the URL for important information!");
        assert_eq!(info.codes[0], "NLFS-NGYyYjEyZWY");
    }

    #[test]
    fn value_runs_to_end_of_record() {
        let info = parse(&["v=FORSALE1;fcod=TRIP-confusing;ftxt=dont_do_this"]).unwrap();
        assert_eq!(info.codes, vec!["TRIP-confusing;ftxt=dont_do_this"]);
        assert!(info.texts.is_empty());
        let info = parse(&["v=FORSALE1;furi=https://x.example/a;b=c?d=e"]).unwrap();
        assert_eq!(info.uris[0].value, "https://x.example/a;b=c?d=e");
    }

    #[test]
    fn unicode_text_kept() {
        let info = parse(&["v=FORSALE1;ftxt=🤓"]).unwrap();
        assert_eq!(info.texts, vec!["🤓"]);
    }

    #[test]
    fn invalid_utf8_replaced() {
        let bad = vec![[b"v=FORSALE1;ftxt=a".as_slice(), &[0xFF], b"b"].concat()];
        let info = parse_txt_records(&[bad]).unwrap();
        assert_eq!(info.texts, vec!["a\u{FFFD}b"]);
    }

    #[test]
    fn value_length_limits() {
        let ok = format!("v=FORSALE1;ftxt={}", "a".repeat(239));
        let too_long = format!("v=FORSALE1;ftxt={}", "a".repeat(240));
        assert_eq!(parse(&[&ok]).unwrap().texts.len(), 1);
        assert!(parse(&[&too_long]).unwrap().texts.is_empty());
    }

    // ── fval (§2.2.4) ──
    #[test]
    fn fval_rules() {
        let p = |v: &str| parse(&[&format!("v=FORSALE1;fval={v}")]).unwrap().prices;
        assert_eq!(p("EUR999")[0].amount, "999");
        assert_eq!(p("BTC0.00010")[0].amount, "0.00010");
        assert_eq!(p(" USD5 ")[0].currency, "USD");
        for bad in [
            "eur999", "EUR", "999", "EUR9.", "EUR.5", "EUR 999", "EUR9,99", "E",
        ] {
            assert!(p(bad).is_empty(), "{bad} should be rejected");
        }
    }

    // ── furi (§2.2.3) ──
    #[test]
    fn furi_trust() {
        let u = |v: &str| parse(&[&format!("v=FORSALE1;furi={v}")]).unwrap().uris;
        assert!(u("https://a.example/")[0].trusted);
        assert!(u("http://a.example")[0].trusted);
        assert!(u("mailto:sales@example.com")[0].trusted);
        assert!(u("tel:+31123456789")[0].trusted);
        let ftp = u("ftp://a.example/");
        assert!(!ftp[0].trusted);
        assert_eq!(ftp[0].scheme, "ftp");
        assert!(!u("javascript:alert(1)")[0].trusted);
        assert_eq!(u("HTTPS://A.example")[0].scheme, "https");
        for bad in [
            "https:///nohost",
            "not a uri",
            "https://a b",
            "noscheme",
            "1http://x",
            ":x",
        ] {
            let uris = u(bad);
            assert!(uris.iter().all(|x| !x.trusted), "{bad} must not be trusted");
        }
        assert!(u("not a uri").is_empty());
        assert!(u("noscheme").is_empty());
    }

    // ── sanitize (§3.6, §4) ──
    #[test]
    fn sanitize_strips_terminal_escapes() {
        assert_eq!(sanitize("a\u{1b}[31mred\u{1b}[0m"), "a[31mred[0m");
        assert_eq!(sanitize("x\u{9b}31my"), "x31my");
        assert_eq!(sanitize("bell\u{7}"), "bell");
        assert_eq!(sanitize("a\tb\nc\rd"), "a b c d");
    }

    #[test]
    fn sanitize_strips_bidi_controls() {
        assert_eq!(sanitize("abc\u{202E}fed"), "abcfed");
        assert_eq!(sanitize("\u{2066}x\u{2069}\u{200F}\u{061C}"), "x");
    }

    #[test]
    fn sanitize_strips_invisible_format_characters() {
        // Unicode tag characters ("ASCII smuggling") hide text from humans but not LLMs.
        let smuggled: String = "Great"
            .chars()
            .chain(
                "ignore previous"
                    .chars()
                    .map(|c| char::from_u32(0xE0000 + c as u32).unwrap()),
            )
            .collect();
        assert_eq!(sanitize(&smuggled), "Great");
        assert_eq!(
            sanitize("a\u{200B}b\u{2060}c\u{FEFF}d\u{00AD}e\u{180E}f"),
            "abcdef"
        );
        assert_eq!(sanitize("line\u{2028}para\u{2029}end"), "line para end");
        // Joiners stay: they shape emoji sequences and some scripts.
        assert_eq!(sanitize("👩\u{200D}💻"), "👩\u{200D}💻");
        assert_eq!(sanitize("می\u{200C}خواهم"), "می\u{200C}خواهم");
    }

    #[test]
    fn text_that_sanitizes_to_empty_is_dropped() {
        let info = parse(&["v=FORSALE1;ftxt=\u{1b}\u{7}"]).unwrap();
        assert!(info.texts.is_empty());
    }

    // ── record_name (§2.6) ──
    #[test]
    fn record_name_rules() {
        assert_eq!(
            record_name("example.com").as_deref(),
            Some("_for-sale.example.com.")
        );
        assert_eq!(
            record_name("Example.COM.").as_deref(),
            Some("_for-sale.example.com.")
        );
        assert_eq!(record_name("51.198.in-addr.arpa"), None);
        assert_eq!(record_name("arpa"), None);
        assert_eq!(record_name(""), None);
        assert_eq!(record_name("."), None);
    }

    #[test]
    fn json_shape_omits_empty_lists() {
        let info = parse(&["v=FORSALE1;fval=EUR5"]).unwrap();
        let json = serde_json::to_value(&info).unwrap();
        assert_eq!(
            json,
            serde_json::json!({"prices":[{"currency":"EUR","amount":"5"}]})
        );
        let empty = serde_json::to_value(parse(&["v=FORSALE1;"]).unwrap()).unwrap();
        assert_eq!(empty, serde_json::json!({}));
    }

    // ── ForSaleLookup (no network) ──
    #[cfg(feature = "forsale")]
    fn taken(domain: &str) -> crate::types::DomainResult {
        crate::types::DomainResult {
            domain: domain.to_string(),
            available: Some(false),
            info: None,
            check_duration: None,
            method_used: crate::types::CheckMethod::Rdap,
            error_message: None,
            for_sale: None,
        }
    }

    #[test]
    fn lookup_inactive_when_not_requested() {
        let lookup = ForSaleLookup::new(&crate::types::CheckConfig::default(), None);
        assert!(!lookup.is_active());
    }

    #[cfg(not(feature = "forsale"))]
    #[test]
    fn lookup_inactive_without_feature() {
        let config = crate::types::CheckConfig::default().with_for_sale(true);
        assert!(!ForSaleLookup::new(&config, None).is_active());
    }

    #[cfg(feature = "forsale")]
    #[tokio::test]
    async fn annotate_skips_available_results() {
        let config = crate::types::CheckConfig::default().with_for_sale(true);
        let lookup = ForSaleLookup::new(&config, None);
        let mut r = taken("example.nl");
        r.available = Some(true);
        lookup.annotate(&mut r).await;
        assert!(r.for_sale.is_none());
    }

    /// UNKNOWN results (RDAP and WHOIS both failed) still get the lookup:
    /// a record means the domain is registered and for sale (#39).
    #[cfg(feature = "forsale")]
    #[tokio::test]
    async fn annotate_looks_up_unknown_results() {
        let config = crate::types::CheckConfig::default().with_for_sale(true);
        let lookup = ForSaleLookup::new(&config, None);
        let mut r = taken("example.nl");
        r.available = None;
        lookup.annotate(&mut r).await;
        assert!(r.for_sale.is_some(), "example.nl publishes _for-sale");
        assert_eq!(r.available, None, "status must not change");
    }

    #[cfg(feature = "forsale")]
    #[tokio::test]
    async fn failed_check_with_record_becomes_unknown_for_sale() {
        let config = crate::types::CheckConfig::default().with_for_sale(true);
        let lookup = ForSaleLookup::new(&config, None);
        let err = DomainCheckError::whois("example.nl", "WHOIS server refused the query");
        let r = lookup
            .annotate_error("example.nl", err)
            .await
            .expect("record turns the error into a result");
        assert_eq!(r.available, None);
        assert!(r.for_sale.is_some());
        assert!(r.error_message.is_some(), "the original error is kept");
    }

    #[cfg(feature = "forsale")]
    #[tokio::test]
    async fn failed_check_without_record_stays_an_error() {
        let config = crate::types::CheckConfig::default().with_for_sale(true);
        let lookup = ForSaleLookup::new(&config, None);
        let err = DomainCheckError::whois("google.com", "boom");
        assert!(lookup.annotate_error("google.com", err).await.is_err());
        let invalid = DomainCheckError::invalid_domain("bad..name", "empty label");
        assert!(matches!(
            lookup.annotate_error("bad..name", invalid).await,
            Err(DomainCheckError::InvalidDomain { .. })
        ));
    }

    #[cfg(feature = "forsale")]
    #[tokio::test]
    async fn no_record_is_not_a_failure() {
        let config = crate::types::CheckConfig::default().with_for_sale(true);
        let lookup = ForSaleLookup::new(&config, None);
        let mut r = taken("google.com");
        lookup.annotate(&mut r).await;
        assert!(r.for_sale.is_none());
        assert_eq!(lookup.failures(), None);
    }

    /// Exercises DNS + parsing directly, independent of RDAP (which SIDN rate-limits).
    #[cfg(feature = "forsale")]
    #[tokio::test]
    async fn dns_lookup_example_nl_without_rdap() {
        let config = crate::types::CheckConfig::default().with_for_sale(true);
        let for_sale = ForSaleLookup::new(&config, None);
        let resolver = for_sale.resolver.as_ref().expect("system resolver");
        let Outcome::Found(info) = lookup(resolver, "example.nl", LOOKUP_TIMEOUT).await else {
            panic!("_for-sale.example.nl is published by SIDN");
        };
        assert!(info.prices.iter().any(|p| p.to_string() == "EUR 100000000"));
        assert!(info.first_trusted_uri().is_some());
        assert!(!info.codes.is_empty());
    }

    /// A nameserver that never answers (TEST-NET-1): the lookup must give up
    /// at our timeout and leave the verdict untouched.
    #[cfg(feature = "forsale")]
    #[tokio::test]
    async fn hanging_resolver_is_capped_and_verdict_unchanged() {
        let timeout = std::time::Duration::from_millis(500);
        let for_sale = ForSaleLookup::with_nameserver("192.0.2.1".parse().unwrap(), timeout);
        assert!(for_sale.is_active());
        let mut r = taken("example.nl");
        r.error_message = Some("kept".into());
        let start = std::time::Instant::now();
        for_sale.annotate(&mut r).await;
        assert!(
            start.elapsed() < std::time::Duration::from_secs(2),
            "lookup took {:?}",
            start.elapsed()
        );
        assert!(r.for_sale.is_none());
        assert_eq!(r.available, Some(false));
        assert_eq!(r.method_used, crate::types::CheckMethod::Rdap);
        assert_eq!(r.error_message.as_deref(), Some("kept"));

        // The failure is reported, not mistaken for "no record".
        let failures = for_sale.failures().expect("timeout is a failure");
        assert_eq!(failures.count, 1);
        assert!(failures.last_error.contains("192.0.2.1"), "{failures:?}");
    }

    /// SERVFAIL for one name means that domain's own DNS is broken (e.g.
    /// _for-sale.mybrand.org); the user's resolver is fine, so it is not a
    /// lookup failure to warn about. REFUSED is the resolver refusing us.
    #[cfg(feature = "forsale")]
    #[test]
    fn servfail_is_the_domains_problem_not_the_resolvers() {
        use hickory_resolver::net::{DnsError, NetError};
        use hickory_resolver::proto::op::ResponseCode;

        let servfail = NetError::Dns(DnsError::ResponseCode(ResponseCode::ServFail));
        assert!(is_domain_side_error(&servfail));
        let refused = NetError::Dns(DnsError::ResponseCode(ResponseCode::Refused));
        assert!(!is_domain_side_error(&refused));
        assert!(!is_domain_side_error(&NetError::Timeout));
    }

    #[cfg(feature = "forsale")]
    #[tokio::test]
    async fn failures_are_shared_between_clones() {
        let timeout = std::time::Duration::from_millis(200);
        let for_sale = ForSaleLookup::with_nameserver("192.0.2.1".parse().unwrap(), timeout);
        let clone = for_sale.clone();
        clone.annotate(&mut taken("a.example")).await;
        for_sale.annotate(&mut taken("b.example")).await;
        assert_eq!(for_sale.failures().map(|f| f.count), Some(2));
    }

    /// _for-sale.j78.nl is ~1.6 KB: too big for UDP, so the resolver must
    /// fall back to TCP. hickory 0.26 gives up when parallel queries both
    /// come back truncated, so lookups must use one nameserver at a time.
    #[cfg(feature = "forsale")]
    #[tokio::test]
    async fn dns_lookup_large_rrset_falls_back_to_tcp() {
        let config = crate::types::CheckConfig::default().with_for_sale(true);
        let for_sale = ForSaleLookup::new(&config, None);
        let resolver = for_sale.resolver.as_ref().expect("system resolver");
        // Generous timeout: this checks that TCP fallback works, not how fast
        // the runner's resolver is (CI macOS needed more than 3s).
        let outcome = lookup(resolver, "j78.nl", std::time::Duration::from_secs(15)).await;
        // GitHub's macOS runners don't answer DNS over TCP at all (the lookup
        // hangs until the timeout), so there is nothing to test there.
        if matches!(outcome, Outcome::Failed(_))
            && cfg!(target_os = "macos")
            && std::env::var_os("CI").is_some()
        {
            eprintln!("skipped: CI resolver does not answer DNS over TCP");
            return;
        }
        let Outcome::Found(info) = outcome else {
            panic!("_for-sale.j78.nl is published by SIDN, got {outcome:?}");
        };
        assert!(info.prices.iter().any(|p| p.to_string() == "EUR 300000"));
    }
}