agent-search 0.8.0

Unified multi-provider search CLI for AI agents — 13 providers, 13 modes, email verification, one binary
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
use hickory_resolver::Resolver;
use owo_colors::OwoColorize;
use serde::Serialize;
use std::io::IsTerminal;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpStream;
use tokio::time::{timeout, Duration};

const SMTP_TIMEOUT: Duration = Duration::from_secs(10);
const GREYLIST_DELAY: Duration = Duration::from_secs(5);

const DISPOSABLE_DOMAINS: &[&str] = &[
    "mailinator.com",
    "guerrillamail.com",
    "tempmail.com",
    "throwaway.email",
    "yopmail.com",
    "sharklasers.com",
    "guerrillamailblock.com",
    "grr.la",
    "dispostable.com",
    "trashmail.com",
    "mailnesia.com",
    "maildrop.cc",
    "discard.email",
    "tempail.com",
    "fakeinbox.com",
    "mailcatch.com",
    "temp-mail.org",
    "10minutemail.com",
    "mohmal.com",
    "burnermail.io",
    "inboxkitten.com",
    "emailondeck.com",
    "getnada.com",
    "tempr.email",
    "tmail.ws",
    "tmpmail.net",
    "tmpmail.org",
    "harakirimail.com",
    "mailsac.com",
    "spamgourmet.com",
    "jetable.org",
    "trash-mail.com",
    "mytemp.email",
    "boun.cr",
    "filzmail.com",
    "mailexpire.com",
    "tempinbox.com",
    "spamfree24.org",
    "mailforspam.com",
    "safetymail.info",
    "trashymail.com",
    "mailtemp.info",
    "temporarymail.com",
    "tempomail.fr",
    "mintemail.com",
    "discardmail.com",
    "mailnull.com",
    "spamhereplease.com",
];

#[derive(Debug, Clone, Serialize)]
pub struct VerifyResult {
    pub email: String,
    pub verdict: String,
    pub smtp_code: u16,
    pub mx_host: String,
    pub is_catch_all: bool,
    pub is_disposable: bool,
    pub suggestion: String,
}

pub async fn verify_emails(
    emails: &[String],
) -> Result<Vec<VerifyResult>, crate::errors::SearchError> {
    // Don't panic if /etc/resolv.conf is unreadable (sandbox/container) — that
    // would abort with a backtrace and break the --json envelope contract.
    let resolver = Resolver::builder_tokio()
        .map_err(|e| crate::errors::SearchError::Resolver(e.to_string()))?
        .build()
        .map_err(|e| crate::errors::SearchError::Resolver(e.to_string()))?;

    let mut results = Vec::with_capacity(emails.len());
    for email in emails {
        results.push(verify_one(&resolver, email).await);
    }
    Ok(results)
}

async fn verify_one(resolver: &hickory_resolver::TokioResolver, email: &str) -> VerifyResult {
    let email = email.trim().to_lowercase();

    // Step 1: Syntax check
    let parts: Vec<&str> = email.splitn(2, '@').collect();
    if parts.len() != 2 || parts[0].is_empty() || parts[1].is_empty() || !parts[1].contains('.') {
        return make_result(
            &email,
            "syntax_error",
            0,
            "",
            false,
            false,
            "Invalid email format.",
        );
    }
    let domain = parts[1];

    let is_disposable = DISPOSABLE_DOMAINS.contains(&domain);

    // Step 2: MX lookup
    let mx_host = match resolve_mx(resolver, domain).await {
        Some(host) => host,
        None => {
            return make_result(
                &email,
                "unreachable",
                0,
                "",
                false,
                is_disposable,
                &format!("No MX records found for domain '{domain}'."),
            );
        }
    };

    // Step 3: Catch-all probe — use a clearly-fake local part
    let catch_all_addr = format!("xvfy-probe-7f3a9b@{domain}");
    let is_catch_all = matches!(
        smtp_probe(&mx_host, &catch_all_addr).await,
        SmtpResult::Accepted(_)
    );

    // Step 4: Real probe
    let result = smtp_probe(&mx_host, &email).await;

    // Step 5: Interpret result
    match result {
        SmtpResult::Accepted(code) => {
            if is_catch_all {
                make_result(
                    &email,
                    "catch_all",
                    code,
                    &mx_host,
                    true,
                    is_disposable,
                    "Domain accepts all addresses. Email format likely valid but unverifiable.",
                )
            } else {
                make_result(
                    &email,
                    "valid",
                    code,
                    &mx_host,
                    false,
                    is_disposable,
                    "Mailbox exists and accepts mail.",
                )
            }
        }
        SmtpResult::Rejected(code) => make_result(
            &email,
            "invalid",
            code,
            &mx_host,
            is_catch_all,
            is_disposable,
            "Mailbox does not exist.",
        ),
        SmtpResult::Greylisted(code) => {
            // Retry once after delay
            tokio::time::sleep(GREYLIST_DELAY).await;
            match smtp_probe(&mx_host, &email).await {
                SmtpResult::Accepted(c) => {
                    if is_catch_all {
                        make_result(&email, "catch_all", c, &mx_host, true, is_disposable,
                            "Domain accepts all addresses. Email format likely valid but unverifiable.")
                    } else {
                        make_result(
                            &email,
                            "valid",
                            c,
                            &mx_host,
                            false,
                            is_disposable,
                            "Mailbox exists and accepts mail (passed greylist).",
                        )
                    }
                }
                SmtpResult::Rejected(c) => make_result(
                    &email,
                    "invalid",
                    c,
                    &mx_host,
                    is_catch_all,
                    is_disposable,
                    "Mailbox does not exist.",
                ),
                _ => make_result(
                    &email,
                    "unreachable",
                    code,
                    &mx_host,
                    is_catch_all,
                    is_disposable,
                    "Server greylisted the request and did not respond on retry.",
                ),
            }
        }
        SmtpResult::Timeout => make_result(
            &email,
            "timeout",
            0,
            &mx_host,
            is_catch_all,
            is_disposable,
            "SMTP server did not respond within timeout.",
        ),
        SmtpResult::Error(msg) => make_result(
            &email,
            "unreachable",
            0,
            &mx_host,
            is_catch_all,
            is_disposable,
            &format!("Connection failed: {msg}"),
        ),
    }
}

async fn resolve_mx(resolver: &hickory_resolver::TokioResolver, domain: &str) -> Option<String> {
    // hickory 0.26: mx_lookup returns a plain Lookup; MX rdata comes out of
    // the answer records.
    use hickory_resolver::proto::rr::RData;
    match resolver.mx_lookup(domain).await {
        Ok(lookup) => lookup
            .answers()
            .iter()
            .filter_map(|rec| match &rec.data {
                RData::MX(mx) => Some(mx),
                _ => None,
            })
            .min_by_key(|mx| mx.preference)
            .map(|mx| mx.exchange.to_string().trim_end_matches('.').to_string()),
        Err(_) => None,
    }
}

enum SmtpResult {
    Accepted(u16),
    Rejected(u16),
    Greylisted(u16),
    Timeout,
    Error(String),
}

async fn smtp_probe(mx_host: &str, email: &str) -> SmtpResult {
    let addr = format!("{mx_host}:25");

    let stream = match timeout(SMTP_TIMEOUT, TcpStream::connect(&addr)).await {
        Ok(Ok(s)) => s,
        Ok(Err(e)) => return SmtpResult::Error(e.to_string()),
        Err(_) => return SmtpResult::Timeout,
    };

    let (reader, mut writer) = stream.into_split();
    let mut reader = BufReader::new(reader);
    let mut line = String::new();

    // Read greeting
    if read_line(&mut reader, &mut line).await.is_err() {
        return SmtpResult::Error("No greeting".into());
    }

    // EHLO
    if send_cmd(&mut writer, &mut reader, &mut line, "EHLO verify.local\r\n")
        .await
        .is_err()
    {
        return SmtpResult::Error("EHLO failed".into());
    }

    // MAIL FROM
    if send_cmd(&mut writer, &mut reader, &mut line, "MAIL FROM:<>\r\n")
        .await
        .is_err()
    {
        return SmtpResult::Error("MAIL FROM failed".into());
    }

    // RCPT TO — this is the actual probe
    let rcpt = format!("RCPT TO:<{email}>\r\n");
    if timeout(SMTP_TIMEOUT, writer.write_all(rcpt.as_bytes()))
        .await
        .is_err()
    {
        return SmtpResult::Timeout;
    }
    line.clear();
    match timeout(SMTP_TIMEOUT, reader.read_line(&mut line)).await {
        Ok(Ok(_)) => {}
        _ => return SmtpResult::Timeout,
    }

    let code = parse_code(&line);

    // Always QUIT cleanly
    let _ = timeout(Duration::from_secs(2), writer.write_all(b"QUIT\r\n")).await;

    match code {
        250 | 251 => SmtpResult::Accepted(code),
        550..=554 => SmtpResult::Rejected(code),
        450 | 451 | 452 | 421 => SmtpResult::Greylisted(code),
        _ => SmtpResult::Rejected(code),
    }
}

async fn read_line(
    reader: &mut BufReader<tokio::net::tcp::OwnedReadHalf>,
    line: &mut String,
) -> Result<(), ()> {
    line.clear();
    match timeout(SMTP_TIMEOUT, reader.read_line(line)).await {
        Ok(Ok(n)) if n > 0 => {
            // Read continuation lines (250-...)
            while line.len() >= 4 && line.as_bytes().get(3) == Some(&b'-') {
                let mut cont = String::new();
                match timeout(SMTP_TIMEOUT, reader.read_line(&mut cont)).await {
                    Ok(Ok(n)) if n > 0 => line.push_str(&cont),
                    _ => break,
                }
            }
            Ok(())
        }
        _ => Err(()),
    }
}

async fn send_cmd(
    writer: &mut tokio::net::tcp::OwnedWriteHalf,
    reader: &mut BufReader<tokio::net::tcp::OwnedReadHalf>,
    line: &mut String,
    cmd: &str,
) -> Result<u16, ()> {
    match timeout(SMTP_TIMEOUT, writer.write_all(cmd.as_bytes())).await {
        Ok(Ok(_)) => {}
        _ => return Err(()),
    }
    read_line(reader, line).await?;
    let code = parse_code(line);
    if code >= 400 {
        Err(())
    } else {
        Ok(code)
    }
}

fn parse_code(line: &str) -> u16 {
    line.get(..3).and_then(|s| s.parse().ok()).unwrap_or(0)
}

fn make_result(
    email: &str,
    verdict: &str,
    smtp_code: u16,
    mx_host: &str,
    is_catch_all: bool,
    is_disposable: bool,
    suggestion: &str,
) -> VerifyResult {
    VerifyResult {
        email: email.to_string(),
        verdict: verdict.to_string(),
        smtp_code,
        mx_host: mx_host.to_string(),
        is_catch_all,
        is_disposable,
        suggestion: suggestion.to_string(),
    }
}

pub fn render_table(results: &[VerifyResult]) {
    let use_color = std::io::stdout().is_terminal();

    if use_color {
        eprintln!("\n{}  Email Verification\n", "search".bold().cyan());
    }

    for r in results {
        let verdict_display = if use_color {
            match r.verdict.as_str() {
                "valid" => format!("{}", "VALID".green().bold()),
                "invalid" => format!("{}", "INVALID".red().bold()),
                "catch_all" => format!("{}", "CATCH-ALL".yellow().bold()),
                "unreachable" => format!("{}", "UNREACHABLE".red()),
                "timeout" => format!("{}", "TIMEOUT".yellow()),
                "syntax_error" => format!("{}", "SYNTAX ERROR".red()),
                _ => r.verdict.clone(),
            }
        } else {
            r.verdict.to_uppercase()
        };

        let email_display = if use_color {
            r.email.bold().to_string()
        } else {
            r.email.clone()
        };

        println!("  {} -> {}", email_display, verdict_display);
        if !r.mx_host.is_empty() {
            if use_color {
                println!("    {} {}", "MX:".dimmed(), r.mx_host.dimmed());
            } else {
                println!("    MX: {}", r.mx_host);
            }
        }
        if use_color {
            println!("    {}", r.suggestion.dimmed());
        } else {
            println!("    {}", r.suggestion);
        }
        println!();
    }

    let valid = results.iter().filter(|r| r.verdict == "valid").count();
    let total = results.len();
    if use_color {
        eprintln!("  {}/{} verified as valid", valid.to_string().bold(), total);
    } else {
        eprintln!("  {}/{} verified as valid", valid, total);
    }
    eprintln!();
}