use chrono::{DateTime, TimeDelta, Utc};
use colored::ColoredString;
use super::OutputFormatter;
pub(super) use super::contact::{self, Contact, FlatContacts};
pub(super) use super::days_until;
pub(super) use super::grouping::render_grouped;
pub(super) use crate::caa::{CaaPolicy, IssuerCaaMatch};
pub(super) use crate::colors::CatppuccinExt;
pub(super) use crate::dns::{DnsRecord, FollowIteration, FollowResult, PropagationResult};
pub(super) use crate::lookup::LookupResult;
pub(super) use crate::rdap::{ContactInfo, RdapResponse};
pub(super) use crate::status::StatusResponse;
pub(super) use crate::whois::WhoisResponse;
pub(super) use colored::Colorize;
mod delegation;
mod diff;
mod dns;
mod domain_info;
mod lookup;
mod propagation;
mod rdap;
mod security;
mod status;
mod whois;
static_regex! {
ANSI_ESCAPE_RE = r"\x1b\[[0-9;]*[a-zA-Z]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[A-Z@-_]";
}
pub(super) fn sanitize_display(s: &str) -> String {
ANSI_ESCAPE_RE
.replace_all(s, "")
.chars()
.filter(|&c| c == '\n' || c == '\t' || !c.is_control())
.collect()
}
pub(crate) fn format_duration(duration: TimeDelta) -> String {
let total_secs = duration.num_seconds();
if total_secs < 60 {
format!("{}s", total_secs)
} else if total_secs < 3600 {
let mins = total_secs / 60;
let secs = total_secs % 60;
format!("{}m {}s", mins, secs)
} else {
let hours = total_secs / 3600;
let mins = (total_secs % 3600) / 60;
format!("{}h {}m", hours, mins)
}
}
pub(super) fn detail_views(contacts: &[Option<ContactInfo>; 3]) -> [Contact<'_>; 3] {
let [registrant, admin, tech] = contact::rdap_views(contacts);
[registrant.without_identity(), admin, tech]
}
pub struct HumanFormatter {
use_colors: bool,
}
impl Default for HumanFormatter {
fn default() -> Self {
Self::new()
}
}
impl HumanFormatter {
pub fn new() -> Self {
Self { use_colors: true }
}
pub fn without_colors(mut self) -> Self {
self.use_colors = false;
self
}
fn paint(&self, text: &str, style: impl FnOnce(&str) -> ColoredString) -> String {
if self.use_colors {
style(text).to_string()
} else {
text.to_string()
}
}
fn label(&self, text: &str) -> String {
self.paint(text, |t| t.sky().bold())
}
fn value(&self, text: &str) -> String {
self.paint(text, |t| t.ctp_white())
}
fn success(&self, text: &str) -> String {
self.paint(text, |t| t.ctp_green().bold())
}
fn warning(&self, text: &str) -> String {
self.paint(text, |t| t.ctp_yellow().bold())
}
fn error(&self, text: &str) -> String {
self.paint(text, |t| t.ctp_red().bold())
}
fn dim(&self, text: &str) -> String {
self.paint(text, |t| t.overlay1())
}
fn rows<'a>(&'a self, out: &'a mut Vec<String>, indent: &str) -> Rows<'a> {
Rows {
f: self,
out,
indent: indent.to_string(),
}
}
fn header(&self, text: &str) -> String {
let width = text.chars().count();
if self.use_colors {
format!(
"\n{}\n{}",
text.lavender().bold(),
"─".repeat(width).subtext0()
)
} else {
format!("\n{}\n{}", text, "-".repeat(width))
}
}
fn render_caa_block(&self, caa: &CaaPolicy, indent: &str) -> Vec<String> {
let mut out = Vec::new();
let mut block = self.rows(&mut out, indent);
let mut rows = block.section("CAA Policy");
if !caa.has_policy {
let line = format!(
"{}{}",
rows.indent,
self.value("No CAA records (any CA may issue)")
);
rows.push(line);
} else {
rows.opt("Found at", &caa.effective_domain);
for r in &caa.records {
let line = format!(
"{}{} {} \"{}\"",
rows.indent,
self.value(&r.flags.to_string()),
self.label(&r.tag),
sanitize_display(&r.value)
);
rows.push(line);
}
}
if let Some(m) = caa.issuer_match {
let rendered = match m {
IssuerCaaMatch::NoPolicy => self.value("no policy — any CA permitted"),
IssuerCaaMatch::Permitted => self.success("issuer permitted by current CAA policy"),
IssuerCaaMatch::Mismatch => self
.warning("issuer not in current CAA policy (informational — see note below)"),
IssuerCaaMatch::Indeterminate => {
self.warning("CAA present but no issue/issuewild tags")
}
};
rows.kv("Issuer vs CAA", rendered);
}
out
}
fn push_caa_note_footer(&self, out: &mut Vec<String>, caa: &CaaPolicy) {
out.push(String::new());
out.push(format!("note: {}", caa.note));
}
fn format_expiry_status(&self, expiry_str: &str, days_until: i64) -> String {
if days_until < 0 {
self.error(&format!(
"{} (expired {} days ago)",
expiry_str, -days_until
))
} else if days_until < 30 {
self.error(&format!("{} (expires in {} days!)", expiry_str, days_until))
} else if days_until < 90 {
self.warning(&format!("{} (expires in {} days)", expiry_str, days_until))
} else {
self.success(&format!("{} (expires in {} days)", expiry_str, days_until))
}
}
}
struct Rows<'a> {
f: &'a HumanFormatter,
out: &'a mut Vec<String>,
indent: String,
}
impl Rows<'_> {
fn push(&mut self, line: String) {
self.out.push(line);
}
fn extend(&mut self, lines: Vec<String>) {
self.out.extend(lines);
}
fn blank(&mut self) {
self.out.push(String::new());
}
fn kv(&mut self, label: &str, styled: String) {
let label = self.f.label(label);
self.out.push(format!("{}{label}: {styled}", self.indent));
}
fn text(&mut self, label: &str, text: &str) {
let value = self.f.value(&sanitize_display(text));
self.kv(label, value);
}
fn opt(&mut self, label: &str, text: &Option<String>) {
if let Some(text) = text {
self.text(label, text);
}
}
fn date(&mut self, label: &str, date: Option<DateTime<Utc>>) {
if let Some(date) = date {
let value = self.f.value(&date.format("%Y-%m-%d").to_string());
self.kv(label, value);
}
}
fn expires(&mut self, date: Option<DateTime<Utc>>) {
if let Some(date) = date {
let status = self
.f
.format_expiry_status(&date.format("%Y-%m-%d").to_string(), days_until(date));
self.kv("Expires", status);
}
}
fn list(&mut self, label: &str, items: &[String]) {
if items.is_empty() {
return;
}
let label = self.f.label(label);
self.out.push(format!("{}{label}:", self.indent));
for item in items {
let item = self.f.value(&sanitize_display(item));
self.out.push(format!("{} - {item}", self.indent));
}
}
fn at(&mut self, indent: &str) -> Rows<'_> {
self.f.rows(self.out, indent)
}
fn section(&mut self, label: &str) -> Rows<'_> {
let heading = self.f.label(label);
self.out.push(format!("\n{}{heading}:", self.indent));
let indent = format!("{} ", self.indent);
self.at(&indent)
}
fn contact(&mut self, role: &str, contact: Contact<'_>) {
if contact.is_empty() {
return;
}
let mut rows = self.section(&format!("{role} Contact"));
for (label, field) in contact.fields() {
rows.opt(label, field);
}
}
fn contacts(&mut self, contacts: [Contact<'_>; 3]) {
for (role, c) in contact::ROLES.into_iter().zip(contacts) {
self.contact(role, c);
}
}
}
with_report_methods!(impl_forwarding!(HumanFormatter;));
#[cfg(test)]
mod tests {
use super::*;
fn formatter() -> HumanFormatter {
HumanFormatter::new().without_colors()
}
#[test]
fn expired_shows_days_ago() {
let f = formatter();
let out = f.format_expiry_status("2024-01-01", -3);
assert!(out.contains("expired 3 days ago"), "got: {}", out);
assert!(!out.contains("-3"), "got: {}", out);
}
#[test]
fn expiring_soon_shows_expires_in() {
let f = formatter();
let out = f.format_expiry_status("2026-05-01", 15);
assert!(out.contains("expires in 15 days"), "got: {}", out);
assert!(!out.contains("days ago"), "got: {}", out);
}
#[test]
fn warning_window_uses_expires_in() {
let f = formatter();
let out = f.format_expiry_status("2026-07-01", 60);
assert!(out.contains("expires in 60 days"), "got: {}", out);
assert!(!out.contains("!"), "got: {}", out);
}
#[test]
fn healthy_expiry_uses_expires_in() {
let f = formatter();
let out = f.format_expiry_status("2027-01-01", 300);
assert!(out.contains("expires in 300 days"), "got: {}", out);
assert!(!out.contains("!"), "got: {}", out);
}
#[test]
fn expired_one_day_is_pluralized_simply() {
let f = formatter();
let out = f.format_expiry_status("2024-01-01", -1);
assert!(out.contains("expired 1 days ago"), "got: {}", out);
}
#[test]
fn boundary_30_days_is_warning_not_error() {
let f = formatter();
let out = f.format_expiry_status("2026-05-15", 30);
assert!(out.contains("expires in 30 days"), "got: {}", out);
assert!(!out.contains("!"), "got: {}", out);
}
#[test]
fn sanitize_display_strips_bare_control_chars_keeps_newline_tab() {
let evil = "a\rb\x08c\x07d\u{009b}e";
let clean = sanitize_display(evil);
for bad in ['\r', '\x08', '\x07', '\u{009b}', '\u{001b}'] {
assert!(
!clean.contains(bad),
"{bad:?} must be stripped from {clean:?}"
);
}
assert!(
clean.contains('a') && clean.contains('e'),
"text kept: {clean:?}"
);
assert_eq!(
sanitize_display("line1\nline2\tcol"),
"line1\nline2\tcol",
"newline and tab must be preserved"
);
}
#[test]
fn sanitize_display_strips_osc_with_st_terminator() {
let clean = sanitize_display("\x1b]0;malicious title\x1b\\visible");
assert_eq!(
clean, "visible",
"OSC+ST sequence must be fully removed: {clean:?}"
);
assert!(!clean.contains('\x1b'));
assert_eq!(sanitize_display("\x1b[31mred\x1b[0m"), "red");
}
#[test]
fn domain_info_renders_registrar_detail_and_lifecycle_fields() {
let whois = WhoisResponse::parse(
"example.com",
"whois.test",
"Registrar: Example Registrar\n\
Creation Date: 2020-01-01T00:00:00Z\n\
Registry Expiry Date: 2099-01-01T00:00:00Z\n\
Domain Status: clientTransferProhibited\n",
);
let mut info =
crate::domain_info::DomainInfo::from_sources("example.com", None, Some(&whois));
info.registrar_abuse_email = Some("abuse@registrar.test".to_string());
info.registrar_abuse_phone = Some("+1.5555550100".to_string());
info.registrar_iana_id = Some("9999".to_string());
info.registrar_url = Some("https://registrar.test".to_string());
assert!(info.days_until_expiration.is_some(), "lifecycle computed");
assert!(!info.status_descriptions.is_empty(), "status decoded");
let out = formatter().format_domain_info(&info);
for needle in [
"Registrar Detail",
"abuse@registrar.test",
"+1.5555550100",
"9999",
"https://registrar.test",
"Days Until Expiry",
"Domain Age",
"Expiry Status",
"clientTransferProhibited:",
] {
assert!(out.contains(needle), "missing {needle:?} in:\n{out}");
}
}
#[test]
fn domain_info_sanitizes_nameserver_and_status_fields() {
let whois = WhoisResponse::parse(
"evil.example",
"whois.test",
"Name Server: ns1.evil\x1b[31mhidden\n\
Domain Status: ok\x1b]0;pwn\x07\n\
Registrar: Test Registrar\n\
Creation Date: 2020-01-01T00:00:00Z\n",
);
let info = crate::domain_info::DomainInfo::from_sources("evil.example", None, Some(&whois));
let out = formatter().format_domain_info(&info);
assert!(
!out.contains('\x1b'),
"ESC must not reach terminal: {out:?}"
);
assert!(
!out.contains('\x07'),
"BEL must not reach terminal: {out:?}"
);
}
}