seer-cli 0.56.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
//! The local-state commands — `watch`, `history` and `config` — for the CLI
//! and the REPL. Each produces a [`Listing`]: the prose a human reads plus
//! the data behind it, so `--format json|yaml` (and `-q`/`--fields` in the
//! CLI) get a structured document instead of the prose.

use seer_core::colors::CatppuccinExt;
use seer_core::output::{sanitize_line, OutputFormat};
use serde::Serialize;

use crate::ops::{load_history, load_watchlist, state_io, STORE_LOCK};

/// A local-state command's result: `text` for human (and markdown) output,
/// `data` for the structured formats.
pub struct Listing {
    pub text: String,
    pub data: serde_json::Value,
}

impl Listing {
    fn new<T: Serialize>(text: String, data: &T) -> Self {
        Self {
            text,
            // Serializing plain data structs cannot fail.
            data: serde_json::to_value(data).unwrap_or_default(),
        }
    }

    /// The listing in `format`: the data for JSON/YAML, the prose otherwise.
    pub fn render(&self, format: OutputFormat) -> String {
        crate::payload::structured(&self.data, format).unwrap_or_else(|| self.text.clone())
    }
}

/// One `watch add|remove` change, as the structured formats report it.
#[derive(Debug, Serialize, PartialEq, Eq)]
struct WatchChange {
    action: &'static str,
    domain: String,
    /// False when the domain was already (add) or not (remove) watched.
    changed: bool,
}

/// Runs `watch add|remove <domain>...` or `watch list`. `cmd` is how the user
/// invokes watch on this surface (`seer watch` in the CLI, `watch` in the
/// REPL), for the usage errors and the empty-list hint. Every domain is
/// validated before anything is saved, so one bad name changes nothing.
pub async fn watch_edit(action: &str, domains: &[String], cmd: &str) -> Result<Listing, String> {
    let adding = match action {
        "list" => {
            if let Some(extra) = domains.first() {
                return Err(format!("Unexpected argument: {extra}\nUsage: {cmd} list"));
            }
            return Ok(watchlist_listing(&load_watchlist().await?, cmd));
        }
        "add" => true,
        "remove" => false,
        other => {
            return Err(format!(
                "Unknown watch action: {}. Use: add, remove, list",
                other
            ))
        }
    };
    if domains.is_empty() {
        return Err(format!("Usage: {} {} <domain>...", cmd, action));
    }

    // Held from load to save (and moved into the write) so a concurrent
    // store edit cannot interleave; see `STORE_LOCK`.
    let store = STORE_LOCK.lock().await;
    let mut watchlist = load_watchlist().await?;
    let mut changes = Vec::with_capacity(domains.len());
    for domain in domains {
        let changed = if adding {
            watchlist
                .add(domain)
                .map_err(|e| format!("Invalid domain: {}", e))?
        } else {
            watchlist.remove(domain)
        };
        changes.push(WatchChange {
            action: if adding { "add" } else { "remove" },
            domain: domain.clone(),
            changed,
        });
    }
    if changes.iter().any(|c| c.changed) {
        state_io("save watchlist", move || {
            let _store = store;
            watchlist.save()
        })
        .await?;
    }
    let text = changes
        .iter()
        .map(|change| match (adding, change.changed) {
            (true, true) => format!("Added {} to watchlist", change.domain.ctp_green()),
            (true, false) => format!("{} is already in the watchlist", change.domain),
            (false, true) => format!("Removed {} from watchlist", change.domain.ctp_green()),
            (false, false) => format!("{} was not in the watchlist", change.domain),
        })
        .collect::<Vec<_>>()
        .join("\n");
    Ok(Listing::new(text, &changes))
}

/// The `watch list` listing, or the empty-watchlist hint (see [`watch_edit`]
/// for `cmd`); its data is the watchlist itself.
pub fn watchlist_listing(watchlist: &seer_core::Watchlist, cmd: &str) -> Listing {
    let text = if watchlist.domains.is_empty() {
        format!(
            "Watchlist is empty. Use '{} add <domain>' to add domains.",
            cmd
        )
    } else {
        let mut out = format!("Watchlist ({} domains):", watchlist.domains.len());
        for domain in &watchlist.domains {
            out.push_str(&format!("\n  - {}", domain));
        }
        out
    };
    Listing::new(text, watchlist)
}

/// What the check-all `watch` found.
pub enum WatchCheck {
    /// Nothing is watched: the empty-watchlist listing.
    Empty(Listing),
    Report(Box<seer_core::WatchReport>),
}

/// The check-all `watch`: every watched domain's expiry and health, with a
/// spinner while it runs.
pub async fn watch_check(config: &seer_core::SeerConfig, cmd: &str) -> Result<WatchCheck, String> {
    let watchlist = load_watchlist().await?;
    if watchlist.domains.is_empty() {
        return Ok(WatchCheck::Empty(watchlist_listing(&watchlist, cmd)));
    }
    let spinner =
        crate::display::Spinner::new(&format!("Checking {} domains", watchlist.domains.len()));
    let report = seer_core::check_watchlist_with_config(&watchlist.domains, config).await;
    spinner.finish();
    Ok(WatchCheck::Report(Box::new(report)))
}

/// Runs `history [domain]` or `history --clear` (which empties all history,
/// so it takes no domain). `lookup_cmd` (`seer lookup` / `lookup`) names the
/// command in the empty-history hint. The data is the entries shown, as
/// [`crate::payload::Payload::History`].
pub async fn history(
    domain: Option<&str>,
    clear: bool,
    lookup_cmd: &str,
) -> Result<Listing, String> {
    if clear {
        if let Some(domain) = domain {
            return Err(format!(
                "--clear empties all lookup history, so it takes no domain (got '{domain}')"
            ));
        }
        crate::ops::clear_history().await?;
        return Ok(Listing::new(
            "Lookup history cleared".to_string(),
            &serde_json::json!({ "cleared": true }),
        ));
    }
    let history = load_history().await?;
    Ok(history_listing(&history, domain, lookup_cmd))
}

/// The `history` listing: one domain's lookups, or a per-domain summary
/// (see [`history`] for `lookup_cmd`). Stored values are remote text (and
/// the store is a plain file), so each goes through `sanitize_line`.
pub fn history_listing(
    history: &seer_core::LookupHistory,
    domain: Option<&str>,
    lookup_cmd: &str,
) -> Listing {
    let entries: Vec<seer_core::HistoryEntry> = match domain {
        Some(domain) => history.get(domain).into_iter().cloned().collect(),
        None => history.entries.values().flatten().cloned().collect(),
    };
    let data = crate::payload::Payload::History(entries);

    let Some(domain) = domain else {
        let total: usize = history.entries.values().map(Vec::len).sum();
        if total == 0 {
            let text = format!(
                "No lookup history. Run '{} <domain>' to build history.",
                lookup_cmd
            );
            return Listing::new(text, &data);
        }
        let mut out = format!(
            "Lookup history ({} entries across {} domains):",
            total,
            history.entries.len()
        );
        for (domain, entries) in &history.entries {
            out.push_str(&format!(
                "\n  {} ({} entries)",
                sanitize_line(domain),
                entries.len()
            ));
        }
        return Listing::new(out, &data);
    };

    let entries = history.get(domain);
    if entries.is_empty() {
        return Listing::new(format!("No history for {}", domain), &data);
    }
    let mut out = format!(
        "History for {} ({} entries):",
        domain.ctp_green(),
        entries.len()
    );
    for entry in entries {
        out.push_str(&format!(
            "\n  [{}] via {} - registrar: {}",
            entry.timestamp.format("%Y-%m-%d %H:%M"),
            entry.result.protocol().unwrap_or("availability"),
            sanitize_line(&entry.result.registrar().unwrap_or_else(|| "—".to_string()))
        ));
    }
    Listing::new(out, &data)
}

/// `seer config`: the effective configuration (as pretty JSON for humans,
/// as before).
pub fn config_show(config: &seer_core::SeerConfig) -> Listing {
    let text = serde_json::to_string_pretty(config).unwrap_or_default();
    Listing::new(text, config)
}

/// `seer config --init`: writes the default config file, refusing to
/// overwrite an existing one.
pub fn config_init() -> Result<Listing, String> {
    let path = seer_core::SeerConfig::config_path()
        .ok_or_else(|| "Could not determine home directory".to_string())?;
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .map_err(|e| format!("Could not create {}: {}", parent.display(), e))?;
    }
    // `create_new` refuses an existing file atomically — no check-then-write
    // window in which a concurrent init could be overwritten.
    let mut file = std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&path)
        .map_err(|e| match e.kind() {
            std::io::ErrorKind::AlreadyExists => {
                format!("Config file already exists at: {}", path.display())
            }
            _ => format!("Could not write {}: {}", path.display(), e),
        })?;
    std::io::Write::write_all(&mut file, seer_core::SeerConfig::default_toml().as_bytes())
        .map_err(|e| format!("Could not write {}: {}", path.display(), e))?;
    let shown = path.display().to_string();
    Ok(Listing::new(
        format!("Created config file at: {}", shown.ctp_green()),
        &serde_json::json!({ "created": shown }),
    ))
}

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

    #[tokio::test]
    async fn watch_edit_rejects_bad_actions_and_arity_before_io() {
        let err = watch_edit("bogus", &["a.com".into()], "watch")
            .await
            .err()
            .expect("bad action");
        assert!(err.starts_with("Unknown watch action: bogus"), "got: {err}");
        let err = watch_edit("add", &[], "seer watch")
            .await
            .err()
            .expect("no domain");
        assert_eq!(err, "Usage: seer watch add <domain>...");
        let err = watch_edit("remove", &[], "watch")
            .await
            .err()
            .expect("no domain");
        assert_eq!(err, "Usage: watch remove <domain>...");
        // `list` takes no domain; it used to be silently ignored.
        let err = watch_edit("list", &["a.com".into()], "watch")
            .await
            .err()
            .expect("extra argument");
        assert!(err.starts_with("Unexpected argument: a.com"), "got: {err}");
    }

    #[test]
    fn watchlist_listing_names_the_surface_command_when_empty() {
        let mut watchlist = seer_core::Watchlist::default();
        let listing = watchlist_listing(&watchlist, "seer watch");
        assert_eq!(
            listing.text,
            "Watchlist is empty. Use 'seer watch add <domain>' to add domains."
        );
        assert_eq!(
            listing.render(OutputFormat::Json),
            "{\n  \"domains\": []\n}"
        );
        watchlist.domains = vec!["a.com".into(), "b.com".into()];
        let listing = watchlist_listing(&watchlist, "watch");
        assert_eq!(listing.text, "Watchlist (2 domains):\n  - a.com\n  - b.com");
        assert_eq!(listing.render(OutputFormat::Human), listing.text);
        assert_eq!(listing.data["domains"][1], "b.com");
    }

    fn available(domain: &str) -> seer_core::LookupResult {
        seer_core::LookupResult::Available {
            data: Box::new(seer_core::AvailabilityResult {
                domain: domain.into(),
                available: true,
                confidence: "high".into(),
                method: "rdap".into(),
                details: None,
            }),
            rdap_error: "404".into(),
            whois_error: "no match".into(),
            whois_data: None,
        }
    }

    #[test]
    fn history_listing_covers_empty_summary_and_per_domain_views() {
        let mut history = seer_core::LookupHistory::default();
        assert_eq!(
            history_listing(&history, None, "lookup").text,
            "No lookup history. Run 'lookup <domain>' to build history."
        );
        assert_eq!(
            history_listing(&history, Some("a.com"), "lookup").text,
            "No history for a.com"
        );

        history.record("a.com", available("a.com"));
        assert_eq!(
            history_listing(&history, None, "seer lookup").text,
            "Lookup history (1 entries across 1 domains):\n  a.com (1 entries)"
        );
        let listing = history_listing(&history, Some("a.com"), "lookup").text;
        assert!(listing.contains("(1 entries):"), "got: {listing}");
        assert!(
            listing.ends_with("via availability - registrar: —"),
            "got: {listing}"
        );
    }

    /// `seer --format json history` printed the prose listing; the
    /// structured formats now carry the entries themselves.
    #[test]
    fn history_listing_data_is_the_entries_shown() {
        let mut history = seer_core::LookupHistory::default();
        history.record("a.com", available("a.com"));
        history.record("b.com", available("b.com"));

        let all = history_listing(&history, None, "lookup");
        let domains: Vec<&str> = all
            .data
            .as_array()
            .expect("an array of entries")
            .iter()
            .map(|entry| entry["domain"].as_str().expect("domain"))
            .collect();
        assert_eq!(domains, vec!["a.com", "b.com"]);

        let one = history_listing(&history, Some("b.com"), "lookup");
        let json: serde_json::Value =
            serde_json::from_str(&one.render(OutputFormat::Json)).expect("valid JSON");
        assert_eq!(json.as_array().map(Vec::len), Some(1));
        assert_eq!(json[0]["domain"], "b.com");
        assert!(one.render(OutputFormat::Yaml).contains("b.com"));
    }

    /// `history example.com --clear` used to clear ALL history, ignoring the
    /// domain; the combination is now an error, before any I/O.
    #[tokio::test]
    async fn history_clear_takes_no_domain() {
        let err = history(Some("example.com"), true, "lookup")
            .await
            .err()
            .expect("must be rejected");
        assert!(err.contains("takes no domain"), "got: {err}");
    }

    /// A registrar from a WHOIS server must not inject escapes or forge a
    /// history row of its own.
    #[test]
    fn history_listing_sanitizes_the_stored_registrar() {
        let mut history = seer_core::LookupHistory::default();
        let data = seer_core::WhoisResponse {
            domain: "a.com".into(),
            registrar: Some("R\u{1b}[31m\n  [2099-01-01 00:00] via rdap - registrar: Legit".into()),
            ..Default::default()
        };
        history.record(
            "a.com",
            seer_core::LookupResult::Whois {
                data,
                rdap_error: None,
                rdap_fallback: None,
                dns_nameservers: None,
            },
        );
        let text = history_listing(&history, Some("a.com"), "lookup").text;
        // The header colors the domain itself; only the entry is remote.
        let entry = text.lines().nth(1).expect("entry line");
        assert!(!entry.contains('\u{1b}'), "{entry:?}");
        assert_eq!(text.lines().count(), 2, "{text:?}");
    }

    #[test]
    fn config_show_keeps_pretty_json_for_humans_and_yaml_for_yaml() {
        let config = seer_core::SeerConfig::default();
        let listing = config_show(&config);
        assert_eq!(listing.render(OutputFormat::Human), listing.text);
        assert!(listing.text.trim_start().starts_with('{'));
        let yaml = listing.render(OutputFormat::Yaml);
        assert!(
            !yaml.trim_start().starts_with('{'),
            "YAML, not JSON: {yaml}"
        );
        assert!(yaml.contains("output_format"), "{yaml}");
    }
}