smart-tree 8.0.1

Smart Tree - An intelligent, AI-friendly directory visualization tool
Documentation
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
//! Security Scanner for detecting supply chain attack patterns
//!
//! Scans directories for malicious patterns including:
//! - IPFS/IPNS phone-home endpoints
//! - Fake cryptographic verification
//! - Dynamic npm package execution
//! - Known malicious package references

use anyhow::Result;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use walkdir::WalkDir;

/// Risk level for detected patterns
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum RiskLevel {
    Low,
    Medium,
    High,
    Critical,
}

impl std::fmt::Display for RiskLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RiskLevel::Low => write!(f, "LOW"),
            RiskLevel::Medium => write!(f, "MEDIUM"),
            RiskLevel::High => write!(f, "HIGH"),
            RiskLevel::Critical => write!(f, "CRITICAL"),
        }
    }
}

/// A detected security pattern
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityFinding {
    pub file_path: PathBuf,
    pub line_number: usize,
    pub pattern_name: String,
    pub matched_text: String,
    pub risk_level: RiskLevel,
    pub description: String,
}

/// Pattern definition for security scanning
struct Pattern {
    name: &'static str,
    regex: Regex,
    risk_level: RiskLevel,
    description: &'static str,
}

/// Security scanner configuration
pub struct SecurityScanner {
    patterns: Vec<Pattern>,
    /// Paths that indicate executable context (higher risk)
    executable_paths: Vec<&'static str>,
    /// Paths that indicate history/logs (lower risk)
    history_paths: Vec<&'static str>,
}

impl SecurityScanner {
    pub fn new() -> Self {
        let patterns = vec![
            // IPFS Gateway URLs - phone home endpoints
            Pattern {
                name: "IPFS Gateway",
                regex: Regex::new(r"https?://(ipfs\.io|dweb\.link|cloudflare-ipfs\.com|gateway\.pinata\.cloud|w3s\.link|4everland\.io)").unwrap(),
                risk_level: RiskLevel::High,
                description: "IPFS gateway URL detected - may fetch remote content",
            },
            // IPNS name patterns (mutable addressing)
            Pattern {
                name: "IPNS Name",
                regex: Regex::new(r"k51qzi5uqu5[a-z0-9]{40,}").unwrap(),
                risk_level: RiskLevel::Critical,
                description: "IPNS mutable name - content can be changed by key holder",
            },
            // Dynamic npm execution with volatile tags
            Pattern {
                name: "Dynamic NPX",
                regex: Regex::new(r"npx\s+[\w@/-]+@(alpha|beta|latest|next|canary)").unwrap(),
                risk_level: RiskLevel::High,
                description: "Dynamic npm execution - package content can change anytime",
            },
            // Known malicious packages
            Pattern {
                name: "Known Risk Package",
                regex: Regex::new(r"(claude-flow|agentic-flow|ruv-swarm|flow-nexus|hive-mind|superdisco|agent-booster)(@|\s|$|/)").unwrap(),
                risk_level: RiskLevel::Critical,
                description: "Known supply chain risk package with remote injection capability",
            },
            // Fake signature verification (length-only check)
            Pattern {
                name: "Fake Verification",
                regex: Regex::new(r"\.length\s*===?\s*(64|128|256)\s*[;)}]").unwrap(),
                risk_level: RiskLevel::Critical,
                description: "Fake cryptographic verification - checks length instead of signature",
            },
            // Registry signature without actual verification
            Pattern {
                name: "Unverified Signature",
                regex: Regex::new(r"registrySignature.*randomBytes|crypto\.randomBytes.*signature").unwrap(),
                risk_level: RiskLevel::Critical,
                description: "Random bytes used as signature - no actual verification",
            },
            // Pattern fetching from remote
            Pattern {
                name: "Remote Pattern Fetch",
                regex: Regex::new(r"fetch.*pattern|pattern.*fetch|loadPattern.*http|http.*loadPattern").unwrap(),
                risk_level: RiskLevel::High,
                description: "Remote pattern/behavior fetching detected",
            },
            // Silent failure patterns (never throw on verification)
            Pattern {
                name: "Silent Failure",
                regex: Regex::new(r"catch\s*\([^)]*\)\s*\{[^}]*return\s+(true|null|\[\]|\{\})[^}]*\}").unwrap(),
                risk_level: RiskLevel::Medium,
                description: "Silent failure on error - may hide security issues",
            },
            // Hooks that auto-execute
            Pattern {
                name: "Auto Hook",
                regex: Regex::new(r"(PreToolUse|PostToolUse|UserPromptSubmit|SessionStart).*npx").unwrap(),
                risk_level: RiskLevel::High,
                description: "Hook configured to auto-execute npm package",
            },
            // Bootstrap registries (hardcoded IPNS endpoints)
            Pattern {
                name: "Bootstrap Registry",
                regex: Regex::new(r"BOOTSTRAP_REGISTRIES|bootstrapRegistries|bootstrap.*registry").unwrap(),
                risk_level: RiskLevel::Critical,
                description: "Hardcoded bootstrap registry detected - potential phone-home mechanism",
            },
            // Fallback CID generation (fabricates fake CIDs)
            Pattern {
                name: "Fake CID Generation",
                regex: Regex::new(r"generateFallbackCID|fallbackCid|bafybei.*sha256").unwrap(),
                risk_level: RiskLevel::Critical,
                description: "Fake CID generation - breaks IPFS content-addressing trust",
            },
            // Genesis registry patterns
            Pattern {
                name: "Genesis Registry",
                regex: Regex::new(r"getGenesisRegistry|seraphine-genesis|genesis.*pattern").unwrap(),
                risk_level: RiskLevel::Critical,
                description: "Hardcoded genesis registry - guaranteed fallback payload",
            },
            // Pattern/behavior injection
            Pattern {
                name: "Behavior Injection",
                regex: Regex::new(r"coordination.*trajectories|routing.*patterns|swarm.*patterns").unwrap(),
                risk_level: RiskLevel::High,
                description: "Behavioral pattern injection - may modify AI reasoning",
            },
        ];

        Self {
            patterns,
            executable_paths: vec![
                "commands",
                "hooks",
                "scripts",
                "bin",
                ".claude/commands",
                "node_modules/.bin",
            ],
            history_paths: vec![
                "shell-snapshots",
                "history",
                "logs",
                ".bash_history",
                ".zsh_history",
            ],
        }
    }

    /// Scan a directory for security patterns
    /// Unlike normal st, this IGNORES gitignore and scans everything
    pub fn scan_directory(&self, path: &Path) -> Result<Vec<SecurityFinding>> {
        let mut findings = Vec::new();

        // Walk directory without respecting gitignore
        for entry in WalkDir::new(path)
            .follow_links(false)
            .into_iter()
            .filter_map(|e| e.ok())
        {
            let file_path = entry.path();

            // Skip binary files and very large files
            if !self.should_scan_file(file_path) {
                continue;
            }

            // Read and scan file contents
            if let Ok(content) = fs::read_to_string(file_path) {
                self.scan_content(file_path, &content, &mut findings);
            }
        }

        // Sort by risk level (critical first)
        findings.sort_by(|a, b| b.risk_level.cmp(&a.risk_level));

        Ok(findings)
    }

    fn should_scan_file(&self, path: &Path) -> bool {
        // Skip binary extensions
        let skip_extensions = [
            "png", "jpg", "jpeg", "gif", "ico", "webp", "svg", "woff", "woff2", "ttf", "otf",
            "eot", "mp3", "mp4", "wav", "ogg", "webm", "zip", "tar", "gz", "bz2", "xz", "7z",
            "exe", "dll", "so", "dylib", "pdf", "doc", "docx", "xls", "xlsx", "pyc", "pyo",
            "class", "o", "a", "wasm", "mem8",
        ];

        if let Some(ext) = path.extension() {
            if skip_extensions.contains(&ext.to_string_lossy().to_lowercase().as_str()) {
                return false;
            }
        }

        // Skip very large files (>10MB)
        if let Ok(metadata) = fs::metadata(path) {
            if metadata.len() > 10 * 1024 * 1024 {
                return false;
            }
        }

        // Must be a file
        path.is_file()
    }

    /// Scan content for security patterns (public API)
    /// Returns findings for a single file's content
    pub fn scan_file_content(&self, file_path: &Path, content: &str) -> Vec<SecurityFinding> {
        let mut findings = Vec::new();
        self.scan_content(file_path, content, &mut findings);
        findings
    }

    fn scan_content(&self, file_path: &Path, content: &str, findings: &mut Vec<SecurityFinding>) {
        let path_str = file_path.to_string_lossy();

        // Determine if this is an executable context, documentation, or history
        let is_executable = self.executable_paths.iter().any(|p| path_str.contains(p));
        let is_history = self.history_paths.iter().any(|p| path_str.contains(p));
        let is_documentation = matches!(
            file_path.extension().and_then(|e| e.to_str()),
            Some("txt" | "md" | "rst" | "adoc" | "org")
        ) || path_str.contains("docs/") || path_str.contains("doc/");

        for (line_number, line) in content.lines().enumerate() {
            for pattern in &self.patterns {
                if let Some(m) = pattern.regex.find(line) {
                    // Adjust risk based on context
                    let adjusted_risk = if is_documentation {
                        // Documentation/notes just *mention* packages — not a real threat
                        match pattern.risk_level {
                            RiskLevel::Critical => RiskLevel::Low,
                            RiskLevel::High => RiskLevel::Low,
                            _ => continue, // skip Medium/Low entirely for docs
                        }
                    } else if is_history {
                        // History files are lower risk
                        match pattern.risk_level {
                            RiskLevel::Critical => RiskLevel::Medium,
                            RiskLevel::High => RiskLevel::Low,
                            other => other,
                        }
                    } else if is_executable {
                        // Executable context keeps or elevates risk
                        pattern.risk_level
                    } else {
                        pattern.risk_level
                    };

                    findings.push(SecurityFinding {
                        file_path: file_path.to_path_buf(),
                        line_number: line_number + 1,
                        pattern_name: pattern.name.to_string(),
                        matched_text: m.as_str().to_string(),
                        risk_level: adjusted_risk,
                        description: pattern.description.to_string(),
                    });
                }
            }
        }
    }

    /// Generate a summary report
    pub fn generate_report(&self, findings: &[SecurityFinding]) -> String {
        let mut report = String::new();

        report.push_str("\n\u{1F50D} Security Scan Results\n");
        report.push_str("═══════════════════════════════════════════════════════════════\n\n");

        if findings.is_empty() {
            report.push_str("\u{2705} No security patterns detected.\n");
            return report;
        }

        // Count by risk level
        let mut by_risk: HashMap<RiskLevel, Vec<&SecurityFinding>> = HashMap::new();
        for finding in findings {
            by_risk.entry(finding.risk_level).or_default().push(finding);
        }

        // Summary
        report.push_str("\u{1F4CA} Summary:\n");
        for level in [
            RiskLevel::Critical,
            RiskLevel::High,
            RiskLevel::Medium,
            RiskLevel::Low,
        ] {
            if let Some(findings) = by_risk.get(&level) {
                let icon = match level {
                    RiskLevel::Critical => "\u{1F6A8}",
                    RiskLevel::High => "\u{26A0}\u{FE0F}",
                    RiskLevel::Medium => "\u{1F7E1}",
                    RiskLevel::Low => "\u{1F535}",
                };
                report.push_str(&format!(
                    "  {} {}: {} findings\n",
                    icon,
                    level,
                    findings.len()
                ));
            }
        }
        report.push('\n');

        // Detailed findings by risk level
        for level in [
            RiskLevel::Critical,
            RiskLevel::High,
            RiskLevel::Medium,
            RiskLevel::Low,
        ] {
            if let Some(findings) = by_risk.get(&level) {
                let header = match level {
                    RiskLevel::Critical => "\u{1F6A8} CRITICAL RISK",
                    RiskLevel::High => "\u{26A0}\u{FE0F} HIGH RISK",
                    RiskLevel::Medium => "\u{1F7E1} MEDIUM RISK",
                    RiskLevel::Low => "\u{1F535} LOW RISK",
                };
                report.push_str(&format!("\n{}\n", header));
                report.push_str(&"-".repeat(60));
                report.push('\n');

                // Group by pattern name
                let mut by_pattern: HashMap<&str, Vec<&&SecurityFinding>> = HashMap::new();
                for finding in findings {
                    by_pattern
                        .entry(&finding.pattern_name)
                        .or_default()
                        .push(finding);
                }

                for (pattern_name, pattern_findings) in by_pattern {
                    report.push_str(&format!(
                        "\n  \u{1F50E} {} ({} occurrences)\n",
                        pattern_name,
                        pattern_findings.len()
                    ));
                    report.push_str(&format!("     {}\n", pattern_findings[0].description));

                    // Show first 5 files
                    for (i, finding) in pattern_findings.iter().take(5).enumerate() {
                        let short_path = finding.file_path.to_string_lossy();
                        // Truncate long paths
                        let display_path = if short_path.len() > 60 {
                            format!("...{}", &short_path[short_path.len() - 57..])
                        } else {
                            short_path.to_string()
                        };
                        report.push_str(&format!(
                            "     {}. {}:{}\n",
                            i + 1,
                            display_path,
                            finding.line_number
                        ));
                        report.push_str(&format!(
                            "        Match: {}\n",
                            truncate(&finding.matched_text, 50)
                        ));
                    }
                    if pattern_findings.len() > 5 {
                        report.push_str(&format!(
                            "     ... and {} more\n",
                            pattern_findings.len() - 5
                        ));
                    }
                }
            }
        }

        // Recommendations
        report.push_str("\n\n\u{1F6E1}\u{FE0F} Recommendations:\n");
        report.push_str("═══════════════════════════════════════════════════════════════\n");

        if by_risk.contains_key(&RiskLevel::Critical) || by_risk.contains_key(&RiskLevel::High) {
            report.push_str("  1. Run: st --ai-install --cleanup\n");
            report.push_str("     To review and remove untrusted MCP integrations\n\n");
            report.push_str("  2. Manually audit ~/.claude/settings.json\n");
            report.push_str("     Remove any hooks referencing suspicious packages\n\n");
            report.push_str("  3. Delete ~/.claude/commands/ directories with risky content\n");
            report.push_str("     These are active skills that execute on slash commands\n\n");
            report.push_str("  4. DO NOT reinstall the flagged packages from npm\n");
            report.push_str("     They will re-add themselves to your configuration\n");
        } else {
            report.push_str("  No critical actions required.\n");
            report.push_str("  Continue monitoring for new patterns.\n");
        }

        report
    }
}

impl Default for SecurityScanner {
    fn default() -> Self {
        Self::new()
    }
}

fn truncate(s: &str, max_len: usize) -> String {
    if s.len() > max_len {
        format!("{}...", &s[..max_len - 3])
    } else {
        s.to_string()
    }
}

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

    #[test]
    fn test_ipfs_detection() {
        let scanner = SecurityScanner::new();
        let content = r#"const url = "https://ipfs.io/ipfs/QmTest";"#;
        let mut findings = Vec::new();
        scanner.scan_content(Path::new("test.js"), content, &mut findings);
        assert!(!findings.is_empty());
        assert_eq!(findings[0].pattern_name, "IPFS Gateway");
    }

    #[test]
    fn test_claude_flow_detection() {
        let scanner = SecurityScanner::new();
        let content = "npx claude-flow@alpha swarm init";
        let mut findings = Vec::new();
        scanner.scan_content(Path::new("test.md"), content, &mut findings);
        assert!(findings
            .iter()
            .any(|f| f.pattern_name == "Known Risk Package"));
    }

    #[test]
    fn test_fake_verification_detection() {
        let scanner = SecurityScanner::new();
        let content = "return signature.length === 64;";
        let mut findings = Vec::new();
        scanner.scan_content(Path::new("verify.ts"), content, &mut findings);
        assert!(findings
            .iter()
            .any(|f| f.pattern_name == "Fake Verification"));
    }

    #[test]
    fn test_additional_malicious_packages() {
        let scanner = SecurityScanner::new();
        let content = "npm install hive-mind flow-nexus ruv-swarm";
        let mut findings = Vec::new();
        scanner.scan_content(Path::new("test.sh"), content, &mut findings);
        assert!(findings
            .iter()
            .any(|f| f.pattern_name == "Known Risk Package"));
    }

    #[test]
    fn test_additional_ipfs_gateways() {
        let scanner = SecurityScanner::new();
        let test_cases = vec![
            "https://4everland.io/ipfs/Qm123",
            "https://cloudflare-ipfs.com/ipfs/Qm456",
            "https://gateway.pinata.cloud/ipfs/Qm789",
            "https://w3s.link/ipfs/QmAbc",
        ];
        for content in test_cases {
            let mut findings = Vec::new();
            scanner.scan_content(Path::new("test.ts"), content, &mut findings);
            assert!(
                findings.iter().any(|f| f.pattern_name == "IPFS Gateway"),
                "Failed to detect IPFS gateway in: {}",
                content
            );
        }
    }

    #[test]
    fn test_volatile_npm_tags() {
        let scanner = SecurityScanner::new();
        let content = "npx some-package@canary run-command";
        let mut findings = Vec::new();
        scanner.scan_content(Path::new("test.sh"), content, &mut findings);
        assert!(findings.iter().any(|f| f.pattern_name == "Dynamic NPX"));
    }

    #[test]
    fn test_bootstrap_registry_detection() {
        let scanner = SecurityScanner::new();
        let content = r#"
            export const BOOTSTRAP_REGISTRIES = [
                { name: 'test', ipnsName: 'k51...' }
            ];
        "#;
        let mut findings = Vec::new();
        scanner.scan_content(Path::new("registry.ts"), content, &mut findings);
        assert!(findings
            .iter()
            .any(|f| f.pattern_name == "Bootstrap Registry"));
    }

    #[test]
    fn test_fake_cid_generation() {
        let scanner = SecurityScanner::new();
        let content = r#"
            const fallbackCid = generateFallbackCID(ipnsName);
            const hash = crypto.createHash('sha256').update(input).digest();
        "#;
        let mut findings = Vec::new();
        scanner.scan_content(Path::new("discovery.ts"), content, &mut findings);
        assert!(findings
            .iter()
            .any(|f| f.pattern_name == "Fake CID Generation"));
    }

    #[test]
    fn test_genesis_registry_detection() {
        let scanner = SecurityScanner::new();
        let content = r#"
            private getGenesisRegistry(cid: string) {
                return { id: 'seraphine-genesis-v1', ... };
            }
        "#;
        let mut findings = Vec::new();
        scanner.scan_content(Path::new("discovery.ts"), content, &mut findings);
        assert!(findings
            .iter()
            .any(|f| f.pattern_name == "Genesis Registry"));
    }

    #[test]
    fn test_behavior_injection_detection() {
        let scanner = SecurityScanner::new();
        let content = r#"
            const patterns = {
                "coordination trajectories": [...],
                "routing patterns": [...]
            };
        "#;
        let mut findings = Vec::new();
        scanner.scan_content(Path::new("patterns.ts"), content, &mut findings);
        assert!(findings
            .iter()
            .any(|f| f.pattern_name == "Behavior Injection"));
    }

    #[test]
    fn test_auto_hook_detection() {
        let scanner = SecurityScanner::new();
        let content = r#"
            "hooks": {
                "PreToolUse": ["npx claude-flow@alpha ..."],
                "SessionStart": ["npx agentic-flow@beta ..."]
            }
        "#;
        let mut findings = Vec::new();
        scanner.scan_content(Path::new("settings.json"), content, &mut findings);
        assert!(findings.iter().any(|f| f.pattern_name == "Auto Hook"));
    }
}