devpulse 1.0.0

Developer diagnostics: HTTP timing, build artifact cleanup, environment health checks, port scanning, PATH analysis, and config format conversion
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
//! Developer environment variable inspector and PATH analyzer.
//!
//! Analyzes PATH entries (missing dirs, duplicates, tool locations),
//! shows dev tool environment variables, proxy settings, CI detection,
//! and `.env` file discovery with basic validation.

use std::collections::BTreeMap;
use std::io;
use std::path::Path;
use std::process::Command;
use std::time::SystemTime;

use walkdir::WalkDir;

use colored::Colorize;
use serde::Serialize;
use thiserror::Error;

/// Errors specific to the env module.
#[derive(Error, Debug)]
pub enum EnvError {
    /// IO error
    #[error("IO error: {0}")]
    Io(#[from] io::Error),
}

/// A single PATH entry with analysis.
#[derive(Debug, Serialize)]
pub struct PathEntry {
    /// 1-based index
    pub index: usize,
    /// The raw path string
    pub path: String,
    /// Whether the directory exists
    pub exists: bool,
    /// If a duplicate, index of the first occurrence
    pub duplicate_of: Option<usize>,
    /// Tools found in this directory
    pub tools: Vec<String>,
}

/// A discovered `.env` file with metadata.
#[derive(Debug, Serialize)]
pub struct DotenvFile {
    /// Path to the .env file
    pub path: String,
    /// Number of key=value pairs found
    pub key_count: usize,
    /// Whether the file is gitignored (heuristic)
    pub gitignored: bool,
    /// Keys that look like secrets (contain PASSWORD, SECRET, TOKEN, KEY, API)
    pub sensitive_keys: Vec<String>,
}

/// Git configuration key-value pair.
#[derive(Debug, Serialize, Clone)]
pub struct GitConfigEntry {
    /// Config key (e.g., "user.name")
    pub key: String,
    /// Config value (None if not set)
    pub value: Option<String>,
    /// Warning message if misconfigured
    pub warning: Option<String>,
}

/// SSH key file metadata.
#[derive(Debug, Serialize, Clone)]
pub struct SshKeyInfo {
    /// Filename (e.g., "id_ed25519.pub")
    pub filename: String,
    /// Key type (RSA, ED25519, ECDSA, DSA, etc.)
    pub key_type: String,
    /// Key size in bits (from comment or heuristic)
    pub bits: Option<u32>,
    /// Age in days since file was last modified
    pub age_days: Option<u64>,
    /// Warning if key is weak or old
    pub warning: Option<String>,
}

/// Full environment analysis result.
#[derive(Debug, Serialize)]
pub struct EnvReport {
    /// PATH entries with analysis
    pub path_entries: Vec<PathEntry>,
    /// Number of PATH issues (missing/duplicate)
    pub path_issues: usize,
    /// Dev tool environment variables (name -> value or null)
    pub dev_vars: BTreeMap<String, Option<String>>,
    /// Proxy environment variables
    pub proxy_vars: BTreeMap<String, Option<String>>,
    /// Detected CI environment (if any)
    pub ci_detected: Option<String>,
    /// Discovered .env files
    pub dotenv_files: Vec<DotenvFile>,
    /// Git configuration analysis
    pub git_config: Vec<GitConfigEntry>,
    /// SSH key audit results
    pub ssh_keys: Vec<SshKeyInfo>,
}

/// Common developer tools to look for in PATH directories.
const COMMON_TOOLS: &[&str] = &[
    "git", "node", "npm", "python", "python3", "cargo", "rustc", "docker", "java", "go", "code",
    "vim", "nvim",
];

/// Dev-relevant environment variable names to report.
const DEV_VARS: &[&str] = &[
    "CARGO_HOME",
    "RUSTUP_HOME",
    "GOPATH",
    "GOROOT",
    "JAVA_HOME",
    "NODE_PATH",
    "VIRTUAL_ENV",
    "CONDA_DEFAULT_ENV",
    "EDITOR",
    "VISUAL",
];

/// Proxy-related environment variable names.
const PROXY_VARS: &[&str] = &[
    "HTTP_PROXY",
    "HTTPS_PROXY",
    "NO_PROXY",
    "ALL_PROXY",
    "http_proxy",
    "https_proxy",
    "no_proxy",
    "all_proxy",
];

/// CI environment indicator variables.
const CI_VARS: &[(&str, &str)] = &[
    ("GITHUB_ACTIONS", "GitHub Actions"),
    ("GITLAB_CI", "GitLab CI"),
    ("JENKINS_URL", "Jenkins"),
    ("TF_BUILD", "Azure DevOps"),
    ("CIRCLECI", "CircleCI"),
    ("TRAVIS", "Travis CI"),
    ("CI", "Generic CI"),
];

/// Get the platform-specific PATH separator.
fn path_separator() -> char {
    if cfg!(windows) {
        ';'
    } else {
        ':'
    }
}

/// Check if a common tool executable exists in a directory.
fn find_tools_in_dir(dir: &Path) -> Vec<String> {
    let mut found = Vec::new();
    if !dir.is_dir() {
        return found;
    }

    for tool in COMMON_TOOLS {
        // Check both bare name and .exe on Windows
        let candidates = if cfg!(windows) {
            vec![
                format!("{tool}.exe"),
                format!("{tool}.cmd"),
                format!("{tool}.bat"),
                tool.to_string(),
            ]
        } else {
            vec![tool.to_string()]
        };

        for candidate in &candidates {
            if dir.join(candidate).exists() {
                found.push(tool.to_string());
                break;
            }
        }
    }

    found
}

/// Analyze the full environment.
fn analyze() -> EnvReport {
    // Analyze PATH
    let path_var = std::env::var("PATH").unwrap_or_default();
    let path_dirs: Vec<&str> = path_var.split(path_separator()).collect();

    let mut path_entries = Vec::new();
    let mut seen: BTreeMap<String, usize> = BTreeMap::new();
    let mut issues = 0;

    for (i, dir) in path_dirs.iter().enumerate() {
        let dir_str = dir.to_string();
        let idx = i + 1;
        let exists = Path::new(dir).is_dir();
        // Normalize case for duplicate detection on Windows (case-insensitive FS)
        // but preserve case-sensitivity on Linux/macOS
        #[cfg(windows)]
        let canonical = dir.to_lowercase();
        #[cfg(not(windows))]
        let canonical = dir_str.clone();

        let duplicate_of = seen.get(&canonical).copied();
        if duplicate_of.is_none() {
            seen.insert(canonical, idx);
        }

        let tools = if exists {
            find_tools_in_dir(Path::new(dir))
        } else {
            Vec::new()
        };

        if !exists || duplicate_of.is_some() {
            issues += 1;
        }

        path_entries.push(PathEntry {
            index: idx,
            path: dir_str,
            exists,
            duplicate_of,
            tools,
        });
    }

    // Dev tool variables
    let mut dev_vars = BTreeMap::new();
    for &var in DEV_VARS {
        dev_vars.insert(var.to_string(), std::env::var(var).ok());
    }

    // Shell/COMSPEC
    if cfg!(windows) {
        dev_vars.insert("COMSPEC".to_string(), std::env::var("COMSPEC").ok());
    } else {
        dev_vars.insert("SHELL".to_string(), std::env::var("SHELL").ok());
    }

    // Proxy variables
    let mut proxy_vars = BTreeMap::new();
    for &var in PROXY_VARS {
        let val = std::env::var(var).ok();
        if val.is_some() {
            proxy_vars.insert(var.to_string(), val);
        }
    }

    // CI detection
    let ci_detected = CI_VARS
        .iter()
        .find(|(var, _)| std::env::var(var).is_ok())
        .map(|(_, name)| name.to_string());

    // .env file discovery
    let dotenv_files = scan_dotenv_files();

    // Git configuration analysis
    let git_config = collect_git_config();

    // SSH key audit
    let ssh_keys = audit_ssh_keys();

    EnvReport {
        path_entries,
        path_issues: issues,
        dev_vars,
        proxy_vars,
        ci_detected,
        dotenv_files,
        git_config,
        ssh_keys,
    }
}

/// Secret-like patterns in env key names.
const SENSITIVE_PATTERNS: &[&str] = &[
    "PASSWORD", "SECRET", "TOKEN", "API_KEY", "APIKEY",
    "PRIVATE", "CREDENTIAL", "AUTH",
];

/// Scan the current directory tree (max 3 levels deep) for .env files.
fn scan_dotenv_files() -> Vec<DotenvFile> {
    let cwd = match std::env::current_dir() {
        Ok(d) => d,
        Err(_) => return Vec::new(),
    };

    let dotenv_names: &[&str] = &[
        ".env", ".env.local", ".env.development", ".env.production",
        ".env.staging", ".env.test", ".env.example",
    ];

    let mut files = Vec::new();

    let walker = WalkDir::new(&cwd)
        .max_depth(3)
        .follow_links(false)
        .into_iter()
        .filter_entry(|e| {
            let name = e.file_name().to_string_lossy();
            // Skip hidden dirs (except . prefixed env files) and common large dirs
            if e.file_type().is_dir() {
                return !matches!(name.as_ref(), "node_modules" | "target" | ".git" | "__pycache__" | ".venv" | "venv");
            }
            true
        });

    for entry in walker.flatten() {
        if !entry.file_type().is_file() {
            continue;
        }
        let name = entry.file_name().to_string_lossy();
        if !dotenv_names.iter().any(|&n| name == n) {
            continue;
        }

        let path = entry.path();
        let content = match std::fs::read_to_string(path) {
            Ok(c) => c,
            Err(_) => continue,
        };

        let mut key_count = 0usize;
        let mut sensitive_keys = Vec::new();

        for line in content.lines() {
            let trimmed = line.trim();
            if trimmed.is_empty() || trimmed.starts_with('#') {
                continue;
            }
            if let Some((key, _)) = trimmed.split_once('=') {
                let key = key.trim();
                key_count += 1;
                let upper = key.to_uppercase();
                if SENSITIVE_PATTERNS.iter().any(|p| upper.contains(p)) {
                    sensitive_keys.push(key.to_string());
                }
            }
        }

        // Heuristic: check if a .gitignore in the same or parent dir mentions .env
        let gitignored = check_gitignored(path);

        files.push(DotenvFile {
            path: path.display().to_string(),
            key_count,
            gitignored,
            sensitive_keys,
        });
    }

    files
}

/// Heuristic check: does a nearby .gitignore mention .env patterns?
fn check_gitignored(dotenv_path: &Path) -> bool {
    // Check .gitignore in same directory and parent
    let candidates = [
        dotenv_path.parent().map(|p| p.join(".gitignore")),
        dotenv_path.parent().and_then(|p| p.parent()).map(|p| p.join(".gitignore")),
    ];

    for candidate in candidates.iter().flatten() {
        if let Ok(content) = std::fs::read_to_string(candidate) {
            for line in content.lines() {
                let l = line.trim();
                if l == ".env" || l == ".env*" || l == ".env.*" || l == "*.env" {
                    return true;
                }
            }
        }
    }
    false
}

/// Git configuration keys to inspect.
const GIT_CONFIG_KEYS: &[&str] = &[
    "user.name",
    "user.email",
    "commit.gpgsign",
    "core.editor",
    "core.autocrlf",
    "credential.helper",
    "init.defaultBranch",
];

/// Collect important git configuration values.
fn collect_git_config() -> Vec<GitConfigEntry> {
    GIT_CONFIG_KEYS
        .iter()
        .map(|&key| {
            let value = Command::new("git")
                .args(["config", "--global", key])
                .output()
                .ok()
                .filter(|o| o.status.success())
                .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
                .filter(|s| !s.is_empty());

            let warning = match key {
                "user.name" if value.is_none() => {
                    Some("Git user.name not set — commits will have no author name".to_string())
                }
                "user.email" if value.is_none() => {
                    Some("Git user.email not set — commits will have no email".to_string())
                }
                "commit.gpgsign" => match &value {
                    Some(v) if v == "true" => None,
                    _ => Some("Commits are not GPG-signed".to_string()),
                },
                "credential.helper" if value.is_none() => {
                    Some("No credential helper — may be prompted for passwords".to_string())
                }
                _ => None,
            };

            GitConfigEntry {
                key: key.to_string(),
                value,
                warning,
            }
        })
        .collect()
}

/// Audit SSH keys in the user's ~/.ssh directory.
fn audit_ssh_keys() -> Vec<SshKeyInfo> {
    let ssh_dir = if cfg!(windows) {
        std::env::var("USERPROFILE")
            .map(|p| Path::new(&p).join(".ssh"))
            .ok()
    } else {
        std::env::var("HOME")
            .map(|p| Path::new(&p).join(".ssh"))
            .ok()
    };

    let ssh_dir = match ssh_dir {
        Some(d) if d.is_dir() => d,
        _ => return Vec::new(),
    };

    let mut keys = Vec::new();

    // Look for .pub files
    let entries = match std::fs::read_dir(&ssh_dir) {
        Ok(e) => e,
        Err(_) => return Vec::new(),
    };

    for entry in entries.flatten() {
        let path = entry.path();
        let name = entry.file_name().to_string_lossy().to_string();

        if !name.ends_with(".pub") {
            continue;
        }
        // Skip known_hosts, authorized_keys, config, etc.
        if name == "known_hosts.pub" || name == "authorized_keys.pub" {
            continue;
        }

        let content = match std::fs::read_to_string(&path) {
            Ok(c) => c,
            Err(_) => continue,
        };

        // Parse: "ssh-rsa AAAA... comment" or "ssh-ed25519 AAAA... comment"
        let parts: Vec<&str> = content.split_whitespace().collect();
        if parts.is_empty() {
            continue;
        }

        let key_type_raw = parts[0];
        let (key_type, bits) = match key_type_raw {
            "ssh-rsa" => {
                // Estimate RSA key size from base64-encoded public key length
                let key_len = parts.get(1).map(|k| k.len()).unwrap_or(0);
                // Rough heuristic: base64 chars * 6 / 8 ≈ bytes, RSA key ≈ modulus
                let estimated = match key_len {
                    0..=200 => 1024u32,
                    201..=400 => 2048,
                    401..=600 => 3072,
                    _ => 4096,
                };
                ("RSA".to_string(), Some(estimated))
            }
            "ssh-ed25519" => ("ED25519".to_string(), Some(256)),
            "ecdsa-sha2-nistp256" => ("ECDSA".to_string(), Some(256)),
            "ecdsa-sha2-nistp384" => ("ECDSA".to_string(), Some(384)),
            "ecdsa-sha2-nistp521" => ("ECDSA".to_string(), Some(521)),
            "ssh-dss" => ("DSA".to_string(), Some(1024)),
            other => (other.to_string(), None),
        };

        // File age
        let age_days = entry
            .metadata()
            .ok()
            .and_then(|m| m.modified().ok())
            .and_then(|modified| {
                SystemTime::now()
                    .duration_since(modified)
                    .ok()
                    .map(|d| d.as_secs() / 86400)
            });

        // Warnings
        let mut warnings = Vec::new();
        if key_type == "DSA" {
            warnings.push("DSA keys are deprecated and insecure".to_string());
        }
        if key_type == "RSA" {
            if let Some(b) = bits {
                if b < 3072 {
                    warnings.push(format!("RSA-{b} is below recommended minimum (3072)"));
                }
            }
        }
        if let Some(days) = age_days {
            if days > 730 {
                warnings.push(format!("Key is {} days old (>2 years) — consider rotating", days));
            }
        }

        let warning = if warnings.is_empty() {
            None
        } else {
            Some(warnings.join("; "))
        };

        keys.push(SshKeyInfo {
            filename: name,
            key_type,
            bits,
            age_days,
            warning,
        });
    }

    keys.sort_by(|a, b| a.filename.cmp(&b.filename));
    keys
}

/// Collect the full environment analysis without printing.
/// Used by the TUI dashboard.
pub fn collect_env() -> EnvReport {
    analyze()
}

/// Run the env command: analyze and display environment info.
pub fn run(filter: Option<&str>, json: bool) -> Result<(), EnvError> {
    let report = analyze();

    if json {
        let json_str = serde_json::to_string_pretty(&report).map_err(io::Error::other)?;
        println!("{json_str}");
        return Ok(());
    }

    let show_all = filter.is_none();
    let filter_lower = filter.map(|f| f.to_lowercase());

    // Header
    println!();
    println!(
        "  {} {} {} {} {}",
        "devpulse".bold(),
        "──".dimmed(),
        "Env".bold(),
        "──".dimmed(),
        "Developer Environment".dimmed()
    );
    println!();

    // PATH section
    if show_all || filter_lower.as_deref() == Some("path") {
        println!(
            "  {} ({} entries, {} issue(s)):",
            "PATH".bold(),
            report.path_entries.len(),
            report.path_issues
        );

        for entry in &report.path_entries {
            let idx = format!("{:>3}", entry.index);

            if !entry.exists {
                println!(
                    "  {}  {}  {}",
                    idx.dimmed(),
                    entry.path,
                    "[NOT FOUND]".red().bold()
                );
            } else if let Some(dup) = entry.duplicate_of {
                println!(
                    "  {}  {}  {}",
                    idx.dimmed(),
                    entry.path,
                    format!("[DUPLICATE of #{dup}]").yellow().bold()
                );
            } else if !entry.tools.is_empty() {
                println!(
                    "  {}  {}  {}",
                    idx.dimmed(),
                    entry.path,
                    entry.tools.join(", ").dimmed()
                );
            } else {
                println!("  {}  {}", idx.dimmed(), entry.path);
            }
        }
        println!();
    }

    // Dev tool variables
    if show_all || filter_lower.as_deref() == Some("dev") || filter_lower.as_deref() == Some("vars")
    {
        println!("  {}:", "Dev Tools".bold());
        for (key, val) in &report.dev_vars {
            match val {
                Some(v) => println!("    {:<20} {}", key, v),
                None => println!("    {:<20} {}", key, "— (not set)".dimmed()),
            }
        }
        println!();
    }

    // Proxy variables
    if show_all || filter_lower.as_deref() == Some("proxy") {
        print!("  {}: ", "Proxy".bold());
        if report.proxy_vars.is_empty() {
            println!("{}", "none configured".dimmed());
        } else {
            println!();
            for (key, val) in &report.proxy_vars {
                if let Some(v) = val {
                    println!("    {:<20} {}", key, v);
                }
            }
        }
        println!();
    }

    // CI detection
    if show_all || filter_lower.as_deref() == Some("ci") {
        print!("  {}: ", "CI".bold());
        match &report.ci_detected {
            Some(name) => println!("{}", name.green().bold()),
            None => println!("{}", "not detected".dimmed()),
        }
        println!();
    }

    // .env files
    if show_all || filter_lower.as_deref() == Some("dotenv") || filter_lower.as_deref() == Some(".env") {
        println!("  {}:", ".env Files".bold());
        if report.dotenv_files.is_empty() {
            println!("    {}", "none found".dimmed());
        } else {
            for df in &report.dotenv_files {
                let status = if !df.gitignored && !df.sensitive_keys.is_empty() {
                    format!("{}", " ⚠ NOT GITIGNORED".yellow().bold())
                } else if df.gitignored {
                    format!("{}", " ✓ gitignored".green())
                } else {
                    String::new()
                };

                println!(
                    "    {}  ({} keys){}",
                    df.path,
                    df.key_count,
                    status,
                );

                if !df.sensitive_keys.is_empty() {
                    println!(
                        "      {} {}",
                        "sensitive:".yellow(),
                        df.sensitive_keys.join(", ").yellow()
                    );
                }
            }
        }
        println!();
    }

    Ok(())
}

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

    #[test]
    fn test_path_separator() {
        let sep = path_separator();
        if cfg!(windows) {
            assert_eq!(sep, ';');
        } else {
            assert_eq!(sep, ':');
        }
    }

    #[test]
    fn test_analyze_returns_report() {
        let report = analyze();
        // PATH should have at least one entry on any system
        assert!(!report.path_entries.is_empty());
    }

    #[test]
    fn test_env_report_serialization() {
        let report = EnvReport {
            path_entries: vec![PathEntry {
                index: 1,
                path: "/usr/bin".to_string(),
                exists: true,
                duplicate_of: None,
                tools: vec!["git".to_string()],
            }],
            path_issues: 0,
            dev_vars: BTreeMap::new(),
            proxy_vars: BTreeMap::new(),
            ci_detected: None,
            dotenv_files: Vec::new(),
            git_config: Vec::new(),
            ssh_keys: Vec::new(),
        };
        let json = serde_json::to_string(&report).unwrap();
        assert!(json.contains("path_entries"));
        assert!(json.contains("/usr/bin"));
    }

    #[test]
    fn test_ci_vars_constant() {
        // Verify CI_VARS has expected entries
        assert!(CI_VARS.iter().any(|(var, _)| *var == "GITHUB_ACTIONS"));
        assert!(CI_VARS.iter().any(|(var, _)| *var == "CI"));
    }
}