1use std::path::PathBuf;
7
8use chrono::{DateTime, Utc};
9use serde::{Deserialize, Serialize};
10
11use crate::error::{Result, SeerError};
12use crate::status::StatusClient;
13
14#[derive(Debug, Clone, Default, Serialize, Deserialize)]
16pub struct Watchlist {
17 #[serde(default)]
18 pub domains: Vec<String>,
19}
20
21#[derive(Debug, Clone, Serialize, Deserialize)]
23pub struct WatchResult {
24 pub domain: String,
25 pub ssl_days_remaining: Option<i64>,
26 pub domain_days_remaining: Option<i64>,
27 pub registrar: Option<String>,
28 pub http_status: Option<u16>,
29 pub issues: Vec<String>,
30}
31
32#[derive(Debug, Clone, Serialize, Deserialize)]
34pub struct WatchReport {
35 pub checked_at: DateTime<Utc>,
36 pub results: Vec<WatchResult>,
37 pub total: usize,
38 pub warnings: usize,
39 pub critical: usize,
40}
41
42impl Watchlist {
43 pub fn path() -> Option<PathBuf> {
45 dirs::home_dir().map(|h| h.join(".seer").join("watchlist.toml"))
46 }
47
48 pub fn load() -> Self {
55 let Some(path) = Self::path() else {
56 return Self::default();
57 };
58 Self::load_from_path(&path)
59 }
60
61 pub(crate) fn load_from_path(path: &std::path::Path) -> Self {
65 if !path.exists() {
66 return Self::default();
67 }
68 match std::fs::read_to_string(path) {
69 Ok(content) => match toml::from_str::<Watchlist>(&content) {
70 Ok(w) => w,
71 Err(e) => {
72 let backup = path.with_extension("corrupt");
73 if let Err(rename_err) = std::fs::rename(path, &backup) {
74 tracing::error!(
75 path = %path.display(),
76 error = %rename_err,
77 "failed to back up corrupt watchlist",
78 );
79 } else {
80 tracing::warn!(
81 path = %path.display(),
82 backup = %backup.display(),
83 error = %e,
84 "watchlist file corrupt; moved to backup",
85 );
86 }
87 Watchlist::default()
88 }
89 },
90 Err(_) => Self::default(),
91 }
92 }
93
94 pub fn save(&self) -> Result<()> {
103 let path = Self::path()
104 .ok_or_else(|| SeerError::ConfigError("Cannot determine home directory".to_string()))?;
105 if let Some(parent) = path.parent() {
106 std::fs::create_dir_all(parent).map_err(|e| SeerError::ConfigError(e.to_string()))?;
107 #[cfg(unix)]
108 {
109 use std::os::unix::fs::PermissionsExt;
110 let _ = std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700));
111 }
112 }
113 let content =
114 toml::to_string_pretty(self).map_err(|e| SeerError::ConfigError(e.to_string()))?;
115 let tmp_path = path.with_extension(format!("toml.{}.tmp", std::process::id()));
116 std::fs::write(&tmp_path, content).map_err(|e| SeerError::ConfigError(e.to_string()))?;
117 #[cfg(unix)]
118 {
119 use std::os::unix::fs::PermissionsExt;
120 let _ = std::fs::set_permissions(&tmp_path, std::fs::Permissions::from_mode(0o600));
121 }
122 std::fs::rename(&tmp_path, &path).map_err(|e| {
123 let _ = std::fs::remove_file(&tmp_path);
124 SeerError::ConfigError(e.to_string())
125 })?;
126 Ok(())
127 }
128
129 pub fn add(&mut self, domain: &str) -> Result<bool> {
131 let domain = crate::validation::normalize_domain(domain)?;
132 if self.domains.contains(&domain) {
133 return Ok(false);
134 }
135 self.domains.push(domain);
136 self.domains.sort();
137 Ok(true)
138 }
139
140 pub fn remove(&mut self, domain: &str) -> bool {
142 let domain =
143 crate::validation::normalize_domain(domain).unwrap_or_else(|_| domain.to_lowercase());
144 let len_before = self.domains.len();
145 self.domains.retain(|d| d != &domain);
146 self.domains.len() < len_before
147 }
148}
149
150pub async fn check_watchlist(domains: &[String]) -> WatchReport {
152 use futures::stream::{self, StreamExt};
153
154 let client = StatusClient::new();
155
156 let results: Vec<WatchResult> = stream::iter(domains)
157 .map(|domain| {
158 let client = &client;
159 async move {
160 let mut watch_result = WatchResult {
161 domain: domain.clone(),
162 ssl_days_remaining: None,
163 domain_days_remaining: None,
164 registrar: None,
165 http_status: None,
166 issues: vec![],
167 };
168
169 match client.check(domain).await {
170 Ok(status) => {
171 watch_result.http_status = status.http_status;
172
173 if let Some(ref cert) = status.certificate {
174 watch_result.ssl_days_remaining = Some(cert.days_until_expiry);
175 if cert.days_until_expiry < 30 {
176 watch_result.issues.push(format!(
177 "SSL expires in {} days",
178 cert.days_until_expiry
179 ));
180 }
181 if !cert.is_valid {
182 watch_result
183 .issues
184 .push("SSL certificate invalid".to_string());
185 }
186 }
187
188 if let Some(ref exp) = status.domain_expiration {
189 watch_result.domain_days_remaining = Some(exp.days_until_expiry);
190 watch_result.registrar = exp.registrar.clone();
191 if exp.days_until_expiry < 90 {
192 watch_result.issues.push(format!(
193 "Domain expires in {} days",
194 exp.days_until_expiry
195 ));
196 }
197 }
198
199 if let Some(status_code) = status.http_status {
200 if !(200..300).contains(&status_code) {
201 watch_result
202 .issues
203 .push(format!("HTTP status {}", status_code));
204 }
205 }
206 }
207 Err(e) => {
208 watch_result.issues.push(format!("Check failed: {}", e));
209 }
210 }
211
212 watch_result
213 }
214 })
215 .buffer_unordered(10)
216 .collect()
217 .await;
218
219 let total = results.len();
220 let critical = results
227 .iter()
228 .filter(|r| {
229 let bad_ssl = r.ssl_days_remaining.is_some_and(|d| d < 30);
230 let bad_domain = r.domain_days_remaining.is_some_and(|d| d < 30);
231 let bad_issue = r
232 .issues
233 .iter()
234 .any(|i| i.contains("invalid") || i.contains("failed"));
235 bad_ssl || bad_domain || bad_issue
236 })
237 .count();
238 let warnings = results.iter().filter(|r| !r.issues.is_empty()).count();
239
240 WatchReport {
241 checked_at: Utc::now(),
242 results,
243 total,
244 warnings,
245 critical,
246 }
247}
248
249#[cfg(test)]
250mod tests {
251 use super::*;
252
253 #[test]
254 fn test_watchlist_default() {
255 let wl = Watchlist::default();
256 assert!(wl.domains.is_empty());
257 }
258
259 #[test]
260 fn test_watchlist_add_remove() {
261 let mut wl = Watchlist::default();
262 assert!(wl.add("example.com").unwrap());
263 assert!(!wl.add("example.com").unwrap()); assert_eq!(wl.domains.len(), 1);
265
266 assert!(wl.add("test.org").unwrap());
267 assert_eq!(wl.domains.len(), 2);
268 assert_eq!(wl.domains[0], "example.com");
270 assert_eq!(wl.domains[1], "test.org");
271
272 assert!(wl.remove("example.com"));
273 assert!(!wl.remove("example.com")); assert_eq!(wl.domains.len(), 1);
275 }
276
277 #[test]
278 fn test_watchlist_add_normalizes_case() {
279 let mut wl = Watchlist::default();
280 wl.add("EXAMPLE.COM").unwrap();
281 assert_eq!(wl.domains[0], "example.com");
282 }
283
284 #[test]
285 fn test_watchlist_serialization() {
286 let mut wl = Watchlist::default();
287 wl.add("a.com").unwrap();
288 wl.add("b.org").unwrap();
289 let toml_str = toml::to_string_pretty(&wl).unwrap();
290 assert!(toml_str.contains("a.com"));
291 assert!(toml_str.contains("b.org"));
292
293 let parsed: Watchlist = toml::from_str(&toml_str).unwrap();
294 assert_eq!(parsed.domains.len(), 2);
295 }
296
297 fn unique_temp_watchlist_path(tag: &str) -> PathBuf {
299 let mut dir = std::env::temp_dir();
300 dir.push(format!(
301 "seer-watchlist-test-{}-{}",
302 tag,
303 std::process::id()
304 ));
305 let _ = std::fs::create_dir_all(&dir);
306 dir.push("watchlist.toml");
307 dir
308 }
309
310 #[test]
311 fn load_from_path_returns_default_and_backs_up_corrupt_file() {
312 let path = unique_temp_watchlist_path("corrupt");
313 let backup = path.with_extension("corrupt");
314
315 let _ = std::fs::remove_file(&path);
316 let _ = std::fs::remove_file(&backup);
317
318 std::fs::write(&path, b"domains = not-an-array-\n").expect("seed corrupt watchlist file");
320
321 let loaded = Watchlist::load_from_path(&path);
322 assert!(
323 loaded.domains.is_empty(),
324 "corrupt watchlist must load as empty default"
325 );
326 assert!(
327 !path.exists(),
328 "original corrupt file should have been renamed away"
329 );
330 assert!(
331 backup.exists(),
332 "backup .corrupt file should exist at {}",
333 backup.display()
334 );
335
336 let _ = std::fs::remove_file(&backup);
337 if let Some(parent) = path.parent() {
338 let _ = std::fs::remove_dir_all(parent);
339 }
340 }
341
342 #[test]
343 fn load_from_path_returns_default_when_missing() {
344 let path = unique_temp_watchlist_path("missing");
345 let _ = std::fs::remove_file(&path);
346
347 let loaded = Watchlist::load_from_path(&path);
348 assert!(loaded.domains.is_empty());
349
350 if let Some(parent) = path.parent() {
351 let _ = std::fs::remove_dir_all(parent);
352 }
353 }
354
355 #[test]
356 fn test_watch_result_serialization() {
357 let result = WatchResult {
358 domain: "example.com".to_string(),
359 ssl_days_remaining: Some(45),
360 domain_days_remaining: Some(120),
361 registrar: Some("Test Registrar".to_string()),
362 http_status: Some(200),
363 issues: vec![],
364 };
365 let json = serde_json::to_string(&result).unwrap();
366 assert!(json.contains("example.com"));
367 assert!(json.contains("45"));
368 }
369}