seer-cli 0.21.0

Interactive CLI for Seer domain name utilities
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
use std::path::Path;

use seer_core::bulk::{BulkOperation, BulkResult, BulkResultData};

/// Maximum allowed size of a bulk input file, in bytes (1 MB).
pub const MAX_BULK_FILE_SIZE: u64 = 1024 * 1024;

/// Safely reads the contents of a bulk input file.
///
/// Guards against FIFOs, sockets, block/char devices, and directories by
/// requiring the path to point at a regular file. Also rejects files larger
/// than [`MAX_BULK_FILE_SIZE`] *before* attempting to read them, preventing
/// indefinite hangs on special files (e.g. paths created by `mkfifo`) that
/// would otherwise cause `read_to_string` to block forever.
pub fn read_bulk_input<P: AsRef<Path>>(path: P) -> Result<String, String> {
    let path = path.as_ref();
    let metadata = std::fs::metadata(path)
        .map_err(|e| format!("cannot stat input file {}: {}", path.display(), e))?;

    if !metadata.is_file() {
        return Err(format!(
            "input path is not a regular file: {}",
            path.display()
        ));
    }

    if metadata.len() > MAX_BULK_FILE_SIZE {
        return Err(format!(
            "input file exceeds {} byte limit: {} bytes",
            MAX_BULK_FILE_SIZE,
            metadata.len()
        ));
    }

    std::fs::read_to_string(path)
        .map_err(|e| format!("failed to read input file {}: {}", path.display(), e))
}

pub fn format_interval(minutes: f64) -> String {
    if minutes < 1.0 {
        format!("{}s", (minutes * 60.0) as u64)
    } else if minutes == 1.0 {
        "1m".to_string()
    } else {
        format!("{}m", minutes)
    }
}

pub fn bulk_results_to_csv(results: &[BulkResult], operation: &str) -> String {
    let mut csv = String::new();

    // Write header based on operation type
    match operation {
        "status" => {
            csv.push_str("domain,success,http_status,http_status_text,title,ssl_issuer,ssl_valid_until,ssl_days_remaining,domain_expires,domain_days_remaining,registrar,dns_resolves,dns_a_records,dns_aaaa_records,dns_cname,dns_nameservers,duration_ms,error\n");
        }
        "lookup" | "whois" | "rdap" => {
            csv.push_str("domain,success,registrar,created,expires,updated,duration_ms,error\n");
        }
        "dig" | "dns" => {
            csv.push_str("domain,success,record_type,records,duration_ms,error\n");
        }
        "propagation" | "prop" => {
            csv.push_str(
                "domain,success,propagation_pct,servers_total,servers_responded,duration_ms,error\n",
            );
        }
        "avail" => {
            csv.push_str("domain,success,available,confidence,method,details,duration_ms,error\n");
        }
        "info" => {
            csv.push_str("domain,success,source,registrar,registrant,organization,created,expires,updated,nameservers,status,dnssec,registrant_email,registrant_phone,registrant_address,registrant_country,admin_name,admin_organization,admin_email,admin_phone,tech_name,tech_organization,tech_email,tech_phone,whois_server,rdap_url,duration_ms,error\n");
        }
        _ => {
            csv.push_str("domain,success,duration_ms,error\n");
        }
    }

    // Write data rows
    for result in results {
        let domain = escape_csv_field(&get_domain_from_operation(&result.operation));
        let success = result.success;
        let duration_ms = result.duration_ms;
        let error = escape_csv_field(result.error.as_deref().unwrap_or(""));

        match operation {
            "status" => {
                let (
                    http_status,
                    http_text,
                    title,
                    ssl_issuer,
                    ssl_valid_until,
                    ssl_days,
                    domain_expires,
                    domain_days,
                    registrar,
                ) = if let Some(BulkResultData::Status(ref s)) = result.data {
                    (
                        s.http_status
                            .map(|v: u16| v.to_string())
                            .unwrap_or_default(),
                        s.http_status_text.clone().unwrap_or_default(),
                        s.title.clone().unwrap_or_default(),
                        s.certificate
                            .as_ref()
                            .map(|c| c.issuer.clone())
                            .unwrap_or_default(),
                        s.certificate
                            .as_ref()
                            .map(|c| c.valid_until.format("%Y-%m-%d").to_string())
                            .unwrap_or_default(),
                        s.certificate
                            .as_ref()
                            .map(|c| c.days_until_expiry.to_string())
                            .unwrap_or_default(),
                        s.domain_expiration
                            .as_ref()
                            .map(|d| d.expiration_date.format("%Y-%m-%d").to_string())
                            .unwrap_or_default(),
                        s.domain_expiration
                            .as_ref()
                            .map(|d| d.days_until_expiry.to_string())
                            .unwrap_or_default(),
                        s.domain_expiration
                            .as_ref()
                            .and_then(|d| d.registrar.clone())
                            .unwrap_or_default(),
                    )
                } else {
                    Default::default()
                };
                let (dns_resolves, dns_a, dns_aaaa, dns_cname, dns_ns) =
                    if let Some(BulkResultData::Status(ref s)) = result.data {
                        (
                            s.dns_resolution
                                .as_ref()
                                .map(|d| d.resolves.to_string())
                                .unwrap_or_default(),
                            s.dns_resolution
                                .as_ref()
                                .map(|d| d.a_records.join(";"))
                                .unwrap_or_default(),
                            s.dns_resolution
                                .as_ref()
                                .map(|d| d.aaaa_records.join(";"))
                                .unwrap_or_default(),
                            s.dns_resolution
                                .as_ref()
                                .and_then(|d| d.cname_target.clone())
                                .unwrap_or_default(),
                            s.dns_resolution
                                .as_ref()
                                .map(|d| d.nameservers.join(";"))
                                .unwrap_or_default(),
                        )
                    } else {
                        Default::default()
                    };
                csv.push_str(&format!(
                    "{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}\n",
                    domain,
                    success,
                    http_status,
                    escape_csv_field(&http_text),
                    escape_csv_field(&title),
                    escape_csv_field(&ssl_issuer),
                    ssl_valid_until,
                    ssl_days,
                    domain_expires,
                    domain_days,
                    escape_csv_field(&registrar),
                    dns_resolves,
                    escape_csv_field(&dns_a),
                    escape_csv_field(&dns_aaaa),
                    escape_csv_field(&dns_cname),
                    escape_csv_field(&dns_ns),
                    duration_ms,
                    error
                ));
            }
            "lookup" => {
                let (registrar, created, expires, updated) = if let Some(ref data) = result.data {
                    match data {
                        BulkResultData::Lookup(seer_core::lookup::LookupResult::Rdap {
                            data: r,
                            ..
                        }) => extract_rdap_dates(r),
                        BulkResultData::Lookup(seer_core::lookup::LookupResult::Whois {
                            data: w,
                            ..
                        }) => (
                            w.registrar.clone().unwrap_or_default(),
                            w.creation_date
                                .map(|d| d.format("%Y-%m-%d").to_string())
                                .unwrap_or_default(),
                            w.expiration_date
                                .map(|d| d.format("%Y-%m-%d").to_string())
                                .unwrap_or_default(),
                            w.updated_date
                                .map(|d| d.format("%Y-%m-%d").to_string())
                                .unwrap_or_default(),
                        ),
                        _ => Default::default(),
                    }
                } else {
                    Default::default()
                };
                csv.push_str(&format!(
                    "{},{},{},{},{},{},{},{}\n",
                    domain,
                    success,
                    escape_csv_field(&registrar),
                    created,
                    expires,
                    updated,
                    duration_ms,
                    error
                ));
            }
            "whois" => {
                let (registrar, created, expires, updated) =
                    if let Some(BulkResultData::Whois(ref w)) = result.data {
                        (
                            w.registrar.clone().unwrap_or_default(),
                            w.creation_date
                                .map(|d| d.format("%Y-%m-%d").to_string())
                                .unwrap_or_default(),
                            w.expiration_date
                                .map(|d| d.format("%Y-%m-%d").to_string())
                                .unwrap_or_default(),
                            w.updated_date
                                .map(|d| d.format("%Y-%m-%d").to_string())
                                .unwrap_or_default(),
                        )
                    } else {
                        Default::default()
                    };
                csv.push_str(&format!(
                    "{},{},{},{},{},{},{},{}\n",
                    domain,
                    success,
                    escape_csv_field(&registrar),
                    created,
                    expires,
                    updated,
                    duration_ms,
                    error
                ));
            }
            "rdap" => {
                let (registrar, created, expires, updated) =
                    if let Some(BulkResultData::Rdap(ref r)) = result.data {
                        extract_rdap_dates(r)
                    } else {
                        Default::default()
                    };
                csv.push_str(&format!(
                    "{},{},{},{},{},{},{},{}\n",
                    domain,
                    success,
                    escape_csv_field(&registrar),
                    created,
                    expires,
                    updated,
                    duration_ms,
                    error
                ));
            }
            "dig" | "dns" => {
                let (record_type, records) =
                    if let Some(BulkResultData::Dns(ref recs)) = result.data {
                        let rt = recs
                            .first()
                            .map(|r| r.record_type.to_string())
                            .unwrap_or_default();
                        let vals: Vec<String> = recs
                            .iter()
                            .map(seer_core::DnsRecord::format_short)
                            .collect();
                        (rt, vals.join("; "))
                    } else {
                        Default::default()
                    };
                csv.push_str(&format!(
                    "{},{},{},{},{},{}\n",
                    domain,
                    success,
                    record_type,
                    escape_csv_field(&records),
                    duration_ms,
                    error
                ));
            }
            "propagation" | "prop" => {
                let (pct, total, responded) =
                    if let Some(BulkResultData::Propagation(ref p)) = result.data {
                        let total = p.results.len();
                        let responded = p.results.iter().filter(|r| r.success).count();
                        let pct = if total > 0 {
                            (responded as f64 / total as f64) * 100.0
                        } else {
                            0.0
                        };
                        (
                            format!("{:.1}", pct),
                            total.to_string(),
                            responded.to_string(),
                        )
                    } else {
                        Default::default()
                    };
                csv.push_str(&format!(
                    "{},{},{},{},{},{},{}\n",
                    domain, success, pct, total, responded, duration_ms, error
                ));
            }
            "avail" => {
                let (available, confidence, method, details) =
                    if let Some(BulkResultData::Avail(ref a)) = result.data {
                        (
                            a.available.to_string(),
                            a.confidence.clone(),
                            a.method.clone(),
                            a.details.clone().unwrap_or_default(),
                        )
                    } else {
                        Default::default()
                    };
                csv.push_str(&format!(
                    "{},{},{},{},{},{},{},{}\n",
                    domain,
                    success,
                    available,
                    confidence,
                    method,
                    escape_csv_field(&details),
                    duration_ms,
                    error
                ));
            }
            "info" => {
                if let Some(BulkResultData::Info(ref info)) = result.data {
                    csv.push_str(&format!(
                        "{},{},{:?},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}\n",
                        domain,
                        success,
                        info.source,
                        escape_csv_field(info.registrar.as_deref().unwrap_or("")),
                        escape_csv_field(info.registrant.as_deref().unwrap_or("")),
                        escape_csv_field(info.organization.as_deref().unwrap_or("")),
                        info.creation_date.map(|d| d.format("%Y-%m-%d").to_string()).unwrap_or_default(),
                        info.expiration_date.map(|d| d.format("%Y-%m-%d").to_string()).unwrap_or_default(),
                        info.updated_date.map(|d| d.format("%Y-%m-%d").to_string()).unwrap_or_default(),
                        escape_csv_field(&info.nameservers.join(";")),
                        escape_csv_field(&info.status.join(";")),
                        escape_csv_field(info.dnssec.as_deref().unwrap_or("")),
                        escape_csv_field(info.registrant_email.as_deref().unwrap_or("")),
                        escape_csv_field(info.registrant_phone.as_deref().unwrap_or("")),
                        escape_csv_field(info.registrant_address.as_deref().unwrap_or("")),
                        escape_csv_field(info.registrant_country.as_deref().unwrap_or("")),
                        escape_csv_field(info.admin_name.as_deref().unwrap_or("")),
                        escape_csv_field(info.admin_organization.as_deref().unwrap_or("")),
                        escape_csv_field(info.admin_email.as_deref().unwrap_or("")),
                        escape_csv_field(info.admin_phone.as_deref().unwrap_or("")),
                        escape_csv_field(info.tech_name.as_deref().unwrap_or("")),
                        escape_csv_field(info.tech_organization.as_deref().unwrap_or("")),
                        escape_csv_field(info.tech_email.as_deref().unwrap_or("")),
                        escape_csv_field(info.tech_phone.as_deref().unwrap_or("")),
                        escape_csv_field(info.whois_server.as_deref().unwrap_or("")),
                        escape_csv_field(info.rdap_url.as_deref().unwrap_or("")),
                        duration_ms,
                        error
                    ));
                } else {
                    csv.push_str(&format!(
                        "{},{},,,,,,,,,,,,,,,,,,,,,,,,,{},{}\n",
                        domain, success, duration_ms, error
                    ));
                }
            }
            _ => {
                csv.push_str(&format!(
                    "{},{},{},{}\n",
                    domain, success, duration_ms, error
                ));
            }
        }
    }

    csv
}

/// Escapes a CSV field for safe output, following RFC 4180 with Excel formula
/// injection protection.
///
/// # Anti-formula protection
/// Fields starting with `=`, `+`, `-`, `@`, `\t`, or `\r` are prefixed with a
/// single quote (`'`) to prevent formula injection in Excel and LibreOffice.
/// This prefix is a display convention specific to spreadsheet applications and
/// will appear as a literal character in non-spreadsheet CSV parsers.
///
/// For programmatic CSV consumption (non-spreadsheet), consider using the
/// `--format json` output instead which does not apply this transformation.
pub fn escape_csv_field(s: &str) -> String {
    // Protect against CSV injection by prefixing formula-starting characters with a single quote
    // This prevents Excel/Sheets from interpreting the content as a formula
    let s = if s.starts_with('=')
        || s.starts_with('+')
        || s.starts_with('-')
        || s.starts_with('@')
        || s.starts_with('\t')
        || s.starts_with('\r')
    {
        format!("'{}", s)
    } else {
        s.to_string()
    };

    // RFC 4180 quoting: if the field contains a comma, double-quote, or newline,
    // wrap it in double quotes and escape internal double-quotes by doubling them.
    if s.contains([',', '"', '\n', '\r']) {
        format!("\"{}\"", s.replace('"', "\"\""))
    } else {
        s
    }
}

pub fn get_domain_from_operation(op: &BulkOperation) -> String {
    match op {
        BulkOperation::Whois { domain } => domain.clone(),
        BulkOperation::Rdap { domain } => domain.clone(),
        BulkOperation::Dns { domain, .. } => domain.clone(),
        BulkOperation::Propagation { domain, .. } => domain.clone(),
        BulkOperation::Lookup { domain } => domain.clone(),
        BulkOperation::Status { domain } => domain.clone(),
        BulkOperation::Avail { domain } => domain.clone(),
        BulkOperation::Info { domain } => domain.clone(),
    }
}

pub fn extract_rdap_dates(r: &seer_core::rdap::RdapResponse) -> (String, String, String, String) {
    let registrar = r.get_registrar().unwrap_or_default();

    let created = r
        .creation_date()
        .map(|d| d.format("%Y-%m-%d").to_string())
        .unwrap_or_default();

    let expires = r
        .expiration_date()
        .map(|d| d.format("%Y-%m-%d").to_string())
        .unwrap_or_default();

    let updated = r
        .last_updated()
        .map(|d| d.format("%Y-%m-%d").to_string())
        .unwrap_or_default();

    (registrar, created, expires, updated)
}

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

    #[test]
    fn read_bulk_input_rejects_directory() {
        // A directory is a readable filesystem entry but not a regular file;
        // the metadata guard must reject it so we don't hit `read_to_string`
        // on something that is not a plain file.
        let dir = std::env::temp_dir();
        let md = std::fs::metadata(&dir).expect("temp dir should exist");
        assert!(!md.is_file(), "temp dir should not be a regular file");

        let err = read_bulk_input(&dir).expect_err("directory must be rejected");
        assert!(
            err.contains("not a regular file"),
            "unexpected error message: {err}"
        );
    }

    #[test]
    fn read_bulk_input_rejects_missing_path() {
        let missing = std::env::temp_dir().join("seer-bulk-input-does-not-exist-xyzzy");
        // Best-effort cleanup in case a stray entry exists.
        let _ = std::fs::remove_file(&missing);

        let err = read_bulk_input(&missing).expect_err("missing path must error");
        assert!(
            err.contains("cannot stat"),
            "unexpected error message: {err}"
        );
    }

    #[test]
    fn read_bulk_input_reads_regular_file() {
        let path = std::env::temp_dir().join("seer-bulk-input-regular-file.txt");
        std::fs::write(&path, "example.com\n").expect("write temp file");

        let content = read_bulk_input(&path).expect("regular file should be readable");
        assert_eq!(content, "example.com\n");

        let _ = std::fs::remove_file(&path);
    }

    #[cfg(unix)]
    #[test]
    fn read_bulk_input_rejects_fifo() {
        use std::os::unix::fs::FileTypeExt;
        use std::process::Command;

        let path =
            std::env::temp_dir().join(format!("seer-bulk-input-fifo-{}", std::process::id()));
        // Clean any leftover from a previous run.
        let _ = std::fs::remove_file(&path);

        // Create a FIFO via the system `mkfifo` binary. This keeps the test
        // dependency-free (no `nix`, no `libc` dev-dep) while still exercising
        // the exact filesystem type that motivated the hardening.
        let status = Command::new("mkfifo").arg(&path).status();
        let ok = match status {
            Ok(s) => s.success(),
            Err(_) => false,
        };
        if !ok {
            eprintln!("skipping FIFO test: mkfifo binary unavailable or failed");
            return;
        }

        let md = std::fs::metadata(&path).expect("stat fifo");
        assert!(md.file_type().is_fifo(), "expected a FIFO");
        assert!(
            !md.is_file(),
            "FIFO must not be classified as a regular file"
        );

        let err = read_bulk_input(&path).expect_err("FIFO must be rejected");
        assert!(
            err.contains("not a regular file"),
            "unexpected error message: {err}"
        );

        let _ = std::fs::remove_file(&path);
    }
}