whoxydse 0.1.1

Discover related top-level domains using Whoxy API: historical WHOIS, reverse WHOIS, and DNS verification
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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
use crate::models::{DomainResult, HistoryResponse, ReverseWhoisResponse, WhoisResponse};
use anyhow::Result;
use colored::*;
use std::time::Duration;

const API_BASE_URL: &str = "https://api.whoxy.com";
const MAX_RETRIES: u32 = 3;
const RETRY_DELAY: Duration = Duration::from_secs(2);

/// Tracks which API endpoints are available/working
#[derive(Debug, Clone, Default)]
pub struct ApiAvailability {
    pub history_api: bool,
    pub reverse_whois_api: bool,
    /// Pivot attributes extracted from WHOIS during preflight
    pub whois_attributes: Option<crate::models::PivotAttributes>,
}

/// Client for interacting with Whoxy API
pub struct WhoxyClient {
    api_key: String,
    client: reqwest::Client,
    verbose: bool,
}

impl WhoxyClient {
    /// Create a new Whoxy API client
    pub fn new(api_key: String, verbose: bool) -> Self {
        let client = reqwest::Client::builder()
            .timeout(Duration::from_secs(30))
            .build()
            .expect("Failed to create HTTP client");

        Self {
            api_key,
            client,
            verbose,
        }
    }

    /// Log verbose request information
    fn log_request(&self, method: &str, url: &str) {
        if self.verbose {
            // Mask API key in URL for security
            let masked_url = url.replace(&self.api_key, "***API_KEY***");
            eprintln!("\n{} {} {}", 
                "🔵".bright_blue(), 
                method.bright_cyan().bold(),
                masked_url.bright_white()
            );
        }
    }

    /// Log verbose response information
    fn log_response(&self, status: u16, response_json: &str) {
        if self.verbose {
            eprintln!("{} Status: {}", "🟢".bright_green(), status.to_string().bright_green().bold());
            eprintln!("{} Response:", "📄".bright_yellow());
            
            // Pretty print JSON if possible, otherwise show raw
            if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(response_json) {
                if let Ok(pretty) = serde_json::to_string_pretty(&parsed) {
                    // Truncate very long responses
                    if pretty.len() > 2000 {
                        let truncated = &pretty[..2000];
                        eprintln!("{}", truncated.bright_black());
                        eprintln!("{} ... (truncated, {} more characters)", 
                            "".bright_yellow(), 
                            pretty.len() - 2000
                        );
                    } else {
                        eprintln!("{}", pretty.bright_black());
                    }
                } else {
                    // Fallback to raw if pretty print fails
                    self.log_response_raw(response_json);
                }
            } else {
                // Not valid JSON, show raw
                self.log_response_raw(response_json);
            }
        }
    }

    /// Log raw response (non-JSON or fallback)
    fn log_response_raw(&self, response_text: &str) {
        if self.verbose {
            if response_text.len() > 1000 {
                let truncated = &response_text[..1000];
                eprintln!("{}", truncated.bright_black());
                eprintln!("{} ... (truncated, {} more characters)", 
                    "".bright_yellow(), 
                    response_text.len() - 1000
                );
            } else {
                eprintln!("{}", response_text.bright_black());
            }
        }
    }

    /// Log verbose error information
    fn log_error(&self, error: &anyhow::Error) {
        if self.verbose {
            eprintln!("{} Error: {}", "🔴".bright_red(), error.to_string().bright_red());
        }
    }

    /// Perform preflight check to test API key validity and extract WHOIS data
    /// Tests History API, Reverse WHOIS API, and performs WHOIS lookup for identifiers
    pub async fn preflight_check(&self, test_domain: &str) -> ApiAvailability {
        let mut availability = ApiAvailability::default();

        // Test History API
        let history_url = format!("{}?key={}&history={}", API_BASE_URL, self.api_key, test_domain);
        match self.execute_request_with_retry::<HistoryResponse>(&history_url).await {
            Ok(response) => {
                // Check if it's a real API key/account error vs just no history found
                // Status 1 = success, Status 0 with "Zero Account Balance" = account issue
                if response.status == 1 {
                    availability.history_api = true;
                } else if Self::is_api_key_failure(&response) {
                    // Account balance or API key issue - mark as unavailable
                    availability.history_api = false;
                } else if response.status == 0 && response.history.is_empty() {
                    // Status 0 with empty history might be "no history found" (still valid API)
                    // Only mark as available if we don't detect account/key issues
                    if !Self::is_api_key_failure(&response) {
                        availability.history_api = true;
                    }
                }
            }
            Err(e) => {
                // Check if error message indicates API key issue
                let error_msg = e.to_string().to_lowercase();
                if !error_msg.contains("api key") && !error_msg.contains("invalid key") {
                    // Might be network error, but assume API might work
                    // We'll find out when we actually try to use it
                }
            }
        }

        // Test Reverse WHOIS API separately
        // Use a minimal test query to verify the API key works for reverse WHOIS
        // We'll use a company name that's unlikely to exist to minimize cost
        let test_company = "TEST_COMPANY_PREFLIGHT_CHECK_XYZ123";
        let reverse_test_url = format!(
            "{}?key={}&reverse=whois&company={}",
            API_BASE_URL, self.api_key, urlencoding::encode(test_company).to_string()
        );
        // execute_request_with_retry will log the request/response if verbose is enabled
        match self.execute_request_with_retry::<ReverseWhoisResponse>(&reverse_test_url).await {
            Ok(mut response) => {
                // Post-process to extract domains from search_result if needed
                response.post_process();
                
                // Check if it's a real API key/account error vs just no results found
                if response.status == 1 {
                    // Success - API works
                    availability.reverse_whois_api = true;
                } else if Self::is_api_key_failure_reverse(&response) {
                    // Account balance or API key issue - mark as unavailable
                    availability.reverse_whois_api = false;
                } else if response.status == 0 {
                    // Status 0 might mean "no results" (still valid API) or account issue
                    // Check status_reason for account balance issues
                    if let Some(ref reason) = response.status_reason {
                        let reason_lower = reason.to_lowercase();
                        if reason_lower.contains("zero account balance") 
                            || reason_lower.contains("insufficient") 
                            || reason_lower.contains("account balance") {
                            availability.reverse_whois_api = false;
                        } else {
                            // No results found, but API is working
                            availability.reverse_whois_api = true;
                        }
                    } else {
                        // No status_reason, assume API works (might just be no results)
                        availability.reverse_whois_api = true;
                    }
                }
            }
            Err(_e) => {
                // Network error or other issue - assume API might work, we'll find out when we use it
                // Don't mark as unavailable based on network errors
                // execute_request_with_retry already logs errors if verbose is enabled
            }
        }

        // Perform WHOIS lookup to extract identifiers for reverse WHOIS (system whois command)
        availability.whois_attributes = Some(self.fetch_whois_attributes(test_domain).await);

        availability
    }

    /// Fetch WHOIS attributes using the system whois command
    async fn fetch_whois_attributes(&self, domain: &str) -> crate::models::PivotAttributes {
        self.fetch_whois_standard(domain).await
    }

    /// Fetch WHOIS using the system whois command
    async fn fetch_whois_standard(&self, domain: &str) -> crate::models::PivotAttributes {
        use tokio::task;
        
        let domain_clone = domain.to_string();
        match task::spawn_blocking(move || {
            // Use whois command-line tool via std::process
            std::process::Command::new("whois")
                .arg(&domain_clone)
                .output()
        }).await {
            Ok(Ok(output)) if output.status.success() => {
                // Parse WHOIS text to extract identifiers
                let whois_text = String::from_utf8_lossy(&output.stdout);
                self.parse_whois_text(&whois_text)
            }
            Ok(Ok(_)) => {
                if self.verbose {
                    eprintln!("{} Standard WHOIS lookup returned non-zero exit code", "".bright_yellow());
                }
                crate::models::PivotAttributes::default()
            }
            Ok(Err(e)) => {
                if self.verbose {
                    eprintln!("{} Standard WHOIS lookup failed: {}", "".bright_yellow(), e);
                }
                crate::models::PivotAttributes::default()
            }
            Err(e) => {
                if self.verbose {
                    eprintln!("{} WHOIS task failed: {}", "".bright_yellow(), e);
                }
                crate::models::PivotAttributes::default()
            }
        }
    }

    /// Parse raw WHOIS text to extract pivotable attributes
    fn parse_whois_text(&self, whois_text: &str) -> crate::models::PivotAttributes {
        let mut attrs = crate::models::PivotAttributes::default();

        // Extract emails using regex
        let email_regex = regex::Regex::new(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b").unwrap();
        for email_match in email_regex.find_iter(whois_text) {
            let email = email_match.as_str().trim().to_lowercase();
            // Filter out common placeholder emails
            if !email.contains("example.com") 
                && !email.contains("placeholder") 
                && !email.contains("privacy") 
                && !email.contains("whois") {
                attrs.add_email(email);
            }
        }

        // Extract registrant/admin/tech names and organizations
        // Look for common WHOIS field patterns
        let lines: Vec<&str> = whois_text.lines().collect();
        
        for line in lines {
            let line_lower = line.to_lowercase();
            let line_trimmed = line_lower.trim();
            
            // Extract name
            if line_trimmed.starts_with("name:") || line_trimmed.starts_with("registrant name:") 
                || line_trimmed.starts_with("admin name:") || line_trimmed.starts_with("tech name:") {
                if let Some(name_part) = line.split(':').nth(1) {
                    let name = name_part.trim().to_string();
                    if !name.is_empty() && name.len() > 2 {
                        attrs.add_name(name);
                    }
                }
            }
            
            // Extract organization/company
            if line_trimmed.contains("organization:") || line_trimmed.contains("org:") 
                || line_trimmed.contains("company:") || line_trimmed.contains("registrant organization:") {
                if let Some(org_part) = line.split(':').nth(1) {
                    let org = org_part.trim().to_string();
                    if !org.is_empty() && org.len() > 2 {
                        attrs.add_company(org);
                    }
                }
            }
        }

        attrs
    }

    /// Check if API response indicates a key failure or account issue
    pub fn is_api_key_failure(response: &HistoryResponse) -> bool {
        // Check status_reason for account balance issues
        if let Some(ref reason) = response.status_reason {
            let reason_lower = reason.to_lowercase();
            if reason_lower.contains("zero account balance")
                || reason_lower.contains("insufficient")
                || reason_lower.contains("balance")
                || reason_lower.contains("payment") {
                return true;
            }
        }
        
        // Check for API key related errors in error message
        if let Some(ref error) = response.error {
            let error_lower = error.to_lowercase();
            return error_lower.contains("api key") 
                || error_lower.contains("invalid key")
                || error_lower.contains("authentication")
                || error_lower.contains("unauthorized")
                || error_lower.contains("invalid api")
                || error_lower.contains("api key required");
        }
        // Also check error codes that indicate auth issues
        if let Some(code) = response.error_code {
            return code == 401 || code == 403;
        }
        // If status is 0 or negative and we have no history, might be API key issue
        // But status != 1 alone doesn't mean API key failure (could be no history found)
        false
    }

    fn is_api_key_failure_reverse(response: &ReverseWhoisResponse) -> bool {
        // Check status_reason for account balance issues
        if let Some(ref reason) = response.status_reason {
            let reason_lower = reason.to_lowercase();
            if reason_lower.contains("zero account balance") 
                || reason_lower.contains("insufficient") 
                || reason_lower.contains("account balance") {
                return true;
            }
        }
        // Check for API key related errors in error message
        if let Some(ref error) = response.error {
            let error_lower = error.to_lowercase();
            return error_lower.contains("api key") 
                || error_lower.contains("invalid key")
                || error_lower.contains("authentication")
                || error_lower.contains("unauthorized")
                || error_lower.contains("invalid api")
                || error_lower.contains("api key required");
        }
        // Also check error codes that indicate auth issues
        if let Some(code) = response.error_code {
            return code == 401 || code == 403;
        }
        // Status <= 0 might indicate error, but not necessarily API key failure
        false
    }

    /// Fetch current WHOIS record for a domain
    pub async fn get_whois(&self, domain: &str) -> Result<WhoisResponse> {
        let url = format!("{}?key={}&whois={}", API_BASE_URL, self.api_key, domain);
        self.execute_request_with_retry(&url).await
    }

    /// Fetch WHOIS history for a domain
    pub async fn get_whois_history(&self, domain: &str) -> Result<HistoryResponse> {
        let url = format!("{}?key={}&history={}", API_BASE_URL, self.api_key, domain);
        self.execute_request_with_retry(&url).await
    }

    /// Perform reverse WHOIS lookup by name
    pub async fn reverse_whois_by_name(&self, name: &str) -> Result<ReverseWhoisResponse> {
        let encoded_name = urlencoding::encode(name).to_string();
        let url = format!(
            "{}?key={}&reverse=whois&name={}",
            API_BASE_URL, self.api_key, encoded_name
        );

        self.reverse_whois_with_fallback(&url, "name", name).await
    }

    /// Perform reverse WHOIS lookup by email
    pub async fn reverse_whois_by_email(&self, email: &str) -> Result<ReverseWhoisResponse> {
        let encoded_email = urlencoding::encode(email).to_string();
        let url = format!(
            "{}?key={}&reverse=whois&email={}",
            API_BASE_URL, self.api_key, encoded_email
        );

        self.reverse_whois_with_fallback(&url, "email", email).await
    }

    /// Perform reverse WHOIS lookup by company
    pub async fn reverse_whois_by_company(&self, company: &str) -> Result<ReverseWhoisResponse> {
        let encoded_company = urlencoding::encode(company).to_string();
        let url = format!(
            "{}?key={}&reverse=whois&company={}",
            API_BASE_URL, self.api_key, encoded_company
        );

        self.reverse_whois_with_fallback(&url, "company", company).await
    }

    /// Perform reverse WHOIS lookup by keyword (searches domain names starting with keyword)
    pub async fn reverse_whois_by_keyword(&self, keyword: &str) -> Result<ReverseWhoisResponse> {
        let encoded_keyword = urlencoding::encode(keyword).to_string();
        let url = format!(
            "{}?key={}&reverse=whois&keyword={}",
            API_BASE_URL, self.api_key, encoded_keyword
        );

        self.reverse_whois_with_fallback(&url, "keyword", keyword).await
    }

    /// Perform reverse WHOIS lookup with pagination.
    /// Uses mini mode (1000 results per page, domain list only) to minimize API calls.
    /// page: 1-indexed; per_page: up to 1000 when mode=mini.
    pub async fn reverse_whois_paginated(
        &self,
        identifier_type: &str,
        value: &str,
        page: i32,
        per_page: Option<i32>,
        mini_mode: bool,
    ) -> Result<ReverseWhoisResponse> {
        let encoded_value = urlencoding::encode(value).to_string();
        let per_page_val = if mini_mode {
            per_page.unwrap_or(1000).min(1000) // Mini mode: up to 1000 per page
        } else {
            per_page.unwrap_or(100).min(100)
        };
        let mut url = format!(
            "{}?key={}&reverse=whois&{}={}&page={}&per_page={}",
            API_BASE_URL, self.api_key, identifier_type, encoded_value, page, per_page_val
        );
        if mini_mode {
            url.push_str("&mode=mini");
        }

        self.reverse_whois_with_fallback(&url, identifier_type, value).await
    }

    /// Perform reverse WHOIS lookup and fetch all pages using mini mode (1000 per page).
    /// Returns all domains for the given identifier; uses total_domains from API to stop.
    pub async fn reverse_whois_all_pages(
        &self,
        identifier_type: &str,
        value: &str,
    ) -> Result<Vec<DomainResult>> {
        const PER_PAGE: i32 = 1000; // Mini mode allows 1000 per page
        let mut all_domains = Vec::new();
        let mut page = 1;

        loop {
            let response = self
                .reverse_whois_paginated(identifier_type, value, page, Some(PER_PAGE), true)
                .await?;

            if response.status != 1 {
                break;
            }

            let domains_count = response.domains.len();
            all_domains.extend(response.domains);

            let total = response.total_domains.unwrap_or(0);
            let fetched = all_domains.len() as i32;

            if fetched >= total || domains_count == 0 {
                break;
            }

            page += 1;
        }

        Ok(all_domains)
    }

    /// Helper to perform reverse WHOIS lookup
    async fn reverse_whois_with_fallback(
        &self,
        url: &str,
        _identifier_type: &str,
        _value: &str,
    ) -> Result<ReverseWhoisResponse> {
        let mut response = self.execute_request_with_retry::<ReverseWhoisResponse>(url).await?;
        response.post_process();
        Ok(response)
    }

    /// Execute HTTP request with retry logic
    async fn execute_request_with_retry<T>(&self, url: &str) -> Result<T>
    where
        T: for<'de> serde::Deserialize<'de>,
    {
        let mut last_error = None;

        for attempt in 0..=MAX_RETRIES {
            if attempt > 0 && self.verbose {
                eprintln!("{} Retry attempt {}/{}", "🔄".bright_yellow(), attempt, MAX_RETRIES);
            }

            self.log_request("GET", url);

            match self.client.get(url).send().await {
                Ok(response) => {
                    let status = response.status().as_u16();
                    let is_success = response.status().is_success();
                    // Get response text first to check for errors
                    let response_text = response.text().await.unwrap_or_default();
                    
                    // Log response
                    if is_success {
                        self.log_response(status, &response_text);
                    } else {
                        if self.verbose {
                            eprintln!("{} HTTP Error Status: {}", "🔴".bright_red(), status);
                            eprintln!("{} Response Body:", "📄".bright_yellow());
                            self.log_response_raw(&response_text);
                        }
                    }
                    
                    if is_success {
                        // Try to parse as JSON
                        match serde_json::from_str::<T>(&response_text) {
                            Ok(data) => {
                                return Ok(data);
                            }
                            Err(e) => {
                                if self.verbose {
                                    eprintln!("{} JSON Parse Error: {}", "".bright_yellow(), e);
                                }
                                
                                // If JSON parsing fails but status is 200, might be HTML error page
                                // Check if it looks like an API key error
                                let text_lower = response_text.to_lowercase();
                                if text_lower.contains("api key") || text_lower.contains("invalid key") {
                                    last_error = Some(anyhow::anyhow!("API key error: {}", response_text));
                                    break; // Don't retry API key errors
                                }
                                last_error = Some(anyhow::anyhow!("JSON parsing error: {}", e));
                                if attempt < MAX_RETRIES {
                                    tokio::time::sleep(RETRY_DELAY).await;
                                    continue;
                                }
                            }
                        }
                    } else if status == 429 {
                        if self.verbose {
                            eprintln!("{} Rate Limited (429)", "".bright_yellow());
                        }
                        // Rate limited - wait longer before retry
                        let wait_time = RETRY_DELAY * (attempt + 1) as u32;
                        if attempt < MAX_RETRIES {
                            tokio::time::sleep(wait_time).await;
                            continue;
                        }
                        return Err(anyhow::anyhow!("Rate limited after {} retries", MAX_RETRIES));
                    } else {
                        // Try to parse as JSON even on error status - API might return JSON error
                        if let Ok(data) = serde_json::from_str::<T>(&response_text) {
                            return Ok(data);
                        }
                        return Err(anyhow::anyhow!(
                            "API error (status {}): {}",
                            status,
                            response_text
                        ));
                    }
                }
                Err(e) => {
                    self.log_error(&anyhow::anyhow!("Network error: {}", e));
                    last_error = Some(anyhow::anyhow!("Network error: {}", e));
                    if attempt < MAX_RETRIES {
                        tokio::time::sleep(RETRY_DELAY).await;
                        continue;
                    }
                }
            }
        }

        let final_error = last_error.unwrap_or_else(|| {
            anyhow::anyhow!("Request failed after {} retries", MAX_RETRIES)
        });
        self.log_error(&final_error);
        Err(final_error)
    }
}