seer-core 0.48.0

Core library for Seer domain name utilities
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
use super::*;

impl MarkdownFormatter {
    pub(super) fn format_lookup(&self, result: &LookupResult) -> String {
        let mut output = Vec::new();

        let domain = result
            .domain_name()
            .unwrap_or_else(|| "Unknown".to_string());
        let source = match result {
            LookupResult::Rdap { .. } => "RDAP",
            LookupResult::Whois { .. } => "WHOIS",
            LookupResult::Available { .. } => "availability",
        };

        output.push(format!("## Lookup: {}", MdSafe(&domain)));
        output.push(String::new());
        output.push(format!("- **Source**: {}", source));

        match result {
            LookupResult::Rdap {
                data,
                whois_fallback,
            } => {
                if let Some(registrar) = data.get_registrar() {
                    output.push(format!("- **Registrar**: {}", MdSafe(&registrar)));
                }
                if let Some(registrant) = data.get_registrant() {
                    output.push(format!("- **Registrant**: {}", MdSafe(&registrant)));
                }
                if let Some(organization) = data.get_registrant_organization() {
                    output.push(format!("- **Organization**: {}", MdSafe(&organization)));
                }

                if let Some(created) = data.creation_date() {
                    output.push(format!("- **Created**: `{}`", created.format("%Y-%m-%d")));
                }
                if let Some(expires) = data.expiration_date() {
                    let days_until = days_until(expires);
                    output.push(format!(
                        "- **Expires**: `{}` ({} days)",
                        expires.format("%Y-%m-%d"),
                        days_until
                    ));
                }

                if !data.status.is_empty() {
                    output.push(format!(
                        "- **Status**: {}",
                        data.status
                            .iter()
                            .map(|s| format!("`{}`", MdSafe(s)))
                            .collect::<Vec<_>>()
                            .join(", ")
                    ));
                }

                let nameservers = data.nameserver_names();
                if !nameservers.is_empty() {
                    output.push(format!(
                        "- **Nameservers**: {}",
                        nameservers
                            .iter()
                            .map(|ns| format!("`{}`", MdSafe(ns)))
                            .collect::<Vec<_>>()
                            .join(", ")
                    ));
                }

                if data.is_dnssec_signed() {
                    output.push("- **DNSSEC**: signed".to_string());
                }

                // Contact sections from RDAP — after every domain-level
                // bullet, since a `###` heading scopes everything below it.
                if let Some(contact) = data.get_registrant_contact() {
                    self.format_rdap_contact(&mut output, "Registrant Contact", &contact);
                }
                if let Some(contact) = data.get_admin_contact() {
                    self.format_rdap_contact(&mut output, "Admin Contact", &contact);
                }
                if let Some(contact) = data.get_tech_contact() {
                    self.format_rdap_contact(&mut output, "Tech Contact", &contact);
                }

                // WHOIS fallback data: bullets first, then any fallback
                // contact sections (same heading-scope rule as above).
                if let Some(whois) = whois_fallback {
                    let mut extra = Vec::new();
                    let mut contacts = Vec::new();

                    if data.get_registrant().is_none() {
                        if let Some(ref registrant) = whois.registrant {
                            extra.push(format!("- **Registrant**: {}", MdSafe(registrant)));
                        }
                    }
                    if data.get_registrant_organization().is_none() {
                        if let Some(ref org) = whois.organization {
                            extra.push(format!("- **Organization**: {}", MdSafe(org)));
                        }
                    }

                    // Registrant contact from WHOIS fallback
                    let rdap_has_registrant = data
                        .get_registrant_contact()
                        .as_ref()
                        .is_some_and(|c| c.has_info());
                    if !rdap_has_registrant {
                        let has_whois_contact = whois.registrant_email.is_some()
                            || whois.registrant_phone.is_some()
                            || whois.registrant_address.is_some()
                            || whois.registrant_country.is_some();
                        if has_whois_contact {
                            contacts.push(String::new());
                            contacts.push("### Registrant Contact".to_string());
                            contacts.push(String::new());
                            if let Some(ref email) = whois.registrant_email {
                                contacts.push(format!("- **Email**: `{}`", MdSafe(email)));
                            }
                            if let Some(ref phone) = whois.registrant_phone {
                                contacts.push(format!("- **Phone**: {}", MdSafe(phone)));
                            }
                            if let Some(ref address) = whois.registrant_address {
                                contacts.push(format!("- **Address**: {}", MdSafe(address)));
                            }
                            if let Some(ref country) = whois.registrant_country {
                                contacts.push(format!("- **Country**: {}", MdSafe(country)));
                            }
                        }
                    }

                    // Admin contact from WHOIS fallback
                    let rdap_has_admin = data.get_admin_contact().is_some_and(|c| c.has_info());
                    if !rdap_has_admin {
                        let has_whois_admin = whois.admin_name.is_some()
                            || whois.admin_email.is_some()
                            || whois.admin_phone.is_some();
                        if has_whois_admin {
                            contacts.push(String::new());
                            contacts.push("### Admin Contact".to_string());
                            contacts.push(String::new());
                            if let Some(ref name) = whois.admin_name {
                                contacts.push(format!("- **Name**: {}", MdSafe(name)));
                            }
                            if let Some(ref org) = whois.admin_organization {
                                contacts.push(format!("- **Organization**: {}", MdSafe(org)));
                            }
                            if let Some(ref email) = whois.admin_email {
                                contacts.push(format!("- **Email**: `{}`", MdSafe(email)));
                            }
                            if let Some(ref phone) = whois.admin_phone {
                                contacts.push(format!("- **Phone**: {}", MdSafe(phone)));
                            }
                        }
                    }

                    // Tech contact from WHOIS fallback
                    let rdap_has_tech = data.get_tech_contact().is_some_and(|c| c.has_info());
                    if !rdap_has_tech {
                        let has_whois_tech = whois.tech_name.is_some()
                            || whois.tech_email.is_some()
                            || whois.tech_phone.is_some();
                        if has_whois_tech {
                            contacts.push(String::new());
                            contacts.push("### Tech Contact".to_string());
                            contacts.push(String::new());
                            if let Some(ref name) = whois.tech_name {
                                contacts.push(format!("- **Name**: {}", MdSafe(name)));
                            }
                            if let Some(ref org) = whois.tech_organization {
                                contacts.push(format!("- **Organization**: {}", MdSafe(org)));
                            }
                            if let Some(ref email) = whois.tech_email {
                                contacts.push(format!("- **Email**: `{}`", MdSafe(email)));
                            }
                            if let Some(ref phone) = whois.tech_phone {
                                contacts.push(format!("- **Phone**: {}", MdSafe(phone)));
                            }
                        }
                    }

                    if let Some(updated) = whois.updated_date {
                        extra.push(format!("- **Updated**: `{}`", updated.format("%Y-%m-%d")));
                    }

                    if !data.is_dnssec_signed() {
                        if let Some(ref dnssec) = whois.dnssec {
                            extra.push(format!("- **DNSSEC**: {}", MdSafe(dnssec)));
                        }
                    }

                    if !whois.whois_server.is_empty() {
                        extra.push(format!(
                            "- **WHOIS Server**: `{}`",
                            MdSafe(&whois.whois_server)
                        ));
                    }

                    if !extra.is_empty() || !contacts.is_empty() {
                        output.push(String::new());
                        output.push("### Additional WHOIS Data".to_string());
                        output.push(String::new());
                        output.extend(extra);
                        output.extend(contacts);
                    }
                }
            }
            LookupResult::Whois {
                data, rdap_error, ..
            } => {
                if let Some(ref error) = rdap_error {
                    output.push(format!("- **RDAP Error**: {}", MdSafe(error)));
                }

                if let Some(ref registrar) = data.registrar {
                    output.push(format!("- **Registrar**: {}", MdSafe(registrar)));
                }
                if let Some(ref registrant) = data.registrant {
                    output.push(format!("- **Registrant**: {}", MdSafe(registrant)));
                }
                if let Some(ref organization) = data.organization {
                    output.push(format!("- **Organization**: {}", MdSafe(organization)));
                }

                if let Some(created) = data.creation_date {
                    output.push(format!("- **Created**: `{}`", created.format("%Y-%m-%d")));
                }
                if let Some(expires) = data.expiration_date {
                    let days_until = days_until(expires);
                    output.push(format!(
                        "- **Expires**: `{}` ({} days)",
                        expires.format("%Y-%m-%d"),
                        days_until
                    ));
                }

                if !data.status.is_empty() {
                    output.push(format!(
                        "- **Status**: {}",
                        data.status
                            .iter()
                            .map(|s| format!("`{}`", MdSafe(s)))
                            .collect::<Vec<_>>()
                            .join(", ")
                    ));
                }

                if !data.nameservers.is_empty() {
                    output.push(format!(
                        "- **Nameservers**: {}",
                        data.nameservers
                            .iter()
                            .map(|ns| format!("`{}`", MdSafe(ns)))
                            .collect::<Vec<_>>()
                            .join(", ")
                    ));
                }

                if let Some(ref dnssec) = data.dnssec {
                    output.push(format!("- **DNSSEC**: {}", MdSafe(dnssec)));
                }

                // Contact subsections last, after every domain-level bullet.
                self.format_whois_contacts(&mut output, data);
            }
            LookupResult::Available {
                data,
                rdap_error,
                whois_error,
                whois_data,
            } => {
                // Branch on the stable verdict (which considers `available`),
                // not `confidence` alone: a confidence:"high" result still
                // means "registered" when available == false. Mirrors the
                // human formatter; without this a registered domain reached
                // via the availability fallback rendered as "AVAILABLE".
                let verdict = match data.verdict() {
                    "available" => "AVAILABLE",
                    "likely_available" => "MAY BE AVAILABLE",
                    "registered" => "REGISTERED",
                    "likely_registered" => "LIKELY REGISTERED",
                    _ => "UNKNOWN",
                };
                output.push(format!("- **Verdict**: {}", verdict));
                output.push(format!("- **Confidence**: {}", data.confidence));
                output.push(format!("- **Method**: {}", data.method));
                if let Some(ref details) = data.details {
                    output.push(format!("- **Details**: {}", MdSafe(details)));
                }
                if !rdap_error.is_empty() {
                    output.push(format!("- **RDAP Error**: {}", MdSafe(rdap_error)));
                }
                if !whois_error.is_empty() {
                    output.push(format!("- **WHOIS Error**: {}", MdSafe(whois_error)));
                }

                if let Some(w) = whois_data {
                    let mut bullets = Vec::new();
                    if !w.nameservers.is_empty() {
                        bullets.push(format!(
                            "- **Nameservers**: {}",
                            w.nameservers
                                .iter()
                                .map(|ns| format!("`{}`", MdSafe(ns)))
                                .collect::<Vec<_>>()
                                .join(", ")
                        ));
                    }
                    if !w.status.is_empty() {
                        bullets.push(format!(
                            "- **Status**: {}",
                            w.status
                                .iter()
                                .map(|s| format!("`{}`", MdSafe(s)))
                                .collect::<Vec<_>>()
                                .join(", ")
                        ));
                    }
                    if let Some(ref dnssec) = w.dnssec {
                        bullets.push(format!("- **DNSSEC**: {}", MdSafe(dnssec)));
                    }
                    if !w.whois_server.is_empty() {
                        bullets.push(format!("- **WHOIS Server**: `{}`", MdSafe(&w.whois_server)));
                    }
                    if !bullets.is_empty() {
                        output.push(String::new());
                        output.push("### Additional WHOIS data".to_string());
                        output.push(String::new());
                        output.extend(bullets);
                    }
                }
            }
        }

        output.join("\n")
    }

    pub(super) fn format_availability(
        &self,
        result: &crate::availability::AvailabilityResult,
    ) -> String {
        let mut output = Vec::new();

        output.push(format!("## Availability: {}", MdSafe(&result.domain)));
        output.push(String::new());

        let avail_str = if result.available {
            "**AVAILABLE**"
        } else {
            "**TAKEN**"
        };
        output.push(format!("- **Result**: {}", avail_str));
        output.push(format!("- **Confidence**: {}", result.confidence));
        output.push(format!("- **Method**: {}", result.method));
        if let Some(ref details) = result.details {
            output.push(format!("- **Details**: {}", MdSafe(details)));
        }

        output.join("\n")
    }
}

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

    #[test]
    fn test_markdown_format_availability() {
        let result = crate::availability::AvailabilityResult {
            domain: "test.com".to_string(),
            available: true,
            confidence: "high".to_string(),
            method: "RDAP+WHOIS".to_string(),
            details: Some("Domain not found".to_string()),
        };
        let formatter = MarkdownFormatter::new();
        let output = formatter.format_availability(&result);
        assert!(output.contains("## Availability: test.com"));
        assert!(output.contains("**AVAILABLE**"));
        assert!(output.contains("high"));
    }

    #[test]
    fn format_lookup_registered_high_confidence_does_not_say_available() {
        // Regression: the Available arm branched on `confidence` alone, so a
        // confidently-*registered* domain (available:false, confidence:"high")
        // rendered as "AVAILABLE". It must say REGISTERED — the same fix the
        // human formatter already carries. This is the markdown rendering of
        // the dns_present "registered" verdict (e.g. zac.email).
        let result = LookupResult::Available {
            data: Box::new(crate::availability::AvailabilityResult {
                domain: "zac.email".to_string(),
                available: false,
                confidence: "high".to_string(),
                method: "dns_present".to_string(),
                details: Some("Domain is registered (delegated in DNS).".to_string()),
            }),
            rdap_error: String::new(),
            whois_error: String::new(),
            whois_data: None,
        };
        let out = MarkdownFormatter::new().format_lookup(&result);
        assert!(
            out.contains("REGISTERED"),
            "must render REGISTERED:\n{}",
            out
        );
        assert!(
            !out.contains("AVAILABLE"),
            "must not render AVAILABLE for a registered domain:\n{}",
            out
        );
    }

    /// Asserts every `fields` bullet appears in `out` before `heading`.
    fn assert_fields_before(out: &str, heading: &str, fields: &[&str]) {
        let heading_at = out
            .find(heading)
            .unwrap_or_else(|| panic!("{heading:?} missing:\n{out}"));
        for field in fields {
            let at = out
                .find(field)
                .unwrap_or_else(|| panic!("{field:?} missing:\n{out}"));
            assert!(
                at < heading_at,
                "{field:?} rendered under {heading:?}:\n{out}"
            );
        }
    }

    fn whois_with_contacts() -> WhoisResponse {
        WhoisResponse::parse(
            "example.com",
            "whois.test",
            "Registrar: Mock Registrar\n\
             Creation Date: 2010-03-15T04:00:00Z\n\
             Updated Date: 2024-02-01T09:30:00Z\n\
             Registry Expiry Date: 2099-03-15T04:00:00Z\n\
             Registrant Country: US\n\
             Admin Name: Jane Admin\n\
             Name Server: ns1.example.com\n\
             Domain Status: ok\n\
             DNSSEC: unsigned\n",
        )
    }

    #[test]
    fn format_lookup_whois_domain_fields_precede_contact_sections() {
        // Contact `###` subsections were emitted before the domain-level
        // bullets, which then rendered as part of the last contact section.
        let result = LookupResult::Whois {
            data: whois_with_contacts(),
            rdap_error: None,
            rdap_fallback: None,
        };
        let out = MarkdownFormatter::new().format_lookup(&result);
        assert_fields_before(
            &out,
            "\n###",
            &[
                "- **Created**",
                "- **Expires**",
                "- **Status**",
                "- **Nameservers**",
                "- **DNSSEC**",
            ],
        );
        assert!(out.contains("### Registrant Contact"), "got:\n{out}");
        assert!(out.contains("### Admin Contact"), "got:\n{out}");
    }

    #[test]
    fn format_lookup_rdap_fallback_bullets_precede_contact_sections() {
        let rdap: RdapResponse = serde_json::from_value(serde_json::json!({
            "ldhName": "example.com",
            "status": ["active"],
            "events": [
                {"eventAction": "registration", "eventDate": "2010-03-15T04:00:00Z"}
            ],
            "entities": [{
                "objectClassName": "entity",
                "handle": "TECH-1",
                "roles": ["technical"],
                "vcardArray": ["vcard", [["email", {}, "text", "tech@example.com"]]]
            }]
        }))
        .unwrap();
        let result = LookupResult::Rdap {
            data: Box::new(rdap),
            whois_fallback: Some(whois_with_contacts()),
        };
        let out = MarkdownFormatter::new().format_lookup(&result);
        // RDAP domain bullets precede the RDAP contact section...
        assert_fields_before(&out, "### Tech Contact", &["- **Created**", "- **Status**"]);
        // ...and the WHOIS fallback bullets precede the fallback contacts.
        assert_fields_before(
            &out,
            "### Registrant Contact",
            &[
                "### Additional WHOIS Data",
                "- **Updated**",
                "- **WHOIS Server**",
            ],
        );
        assert!(out.contains("### Admin Contact"), "fallback admin:\n{out}");
    }
}