react-perf-analyzer 0.5.1

React performance + security scanner. Finds perf anti-patterns, XSS, secrets, and CVEs. Single binary, zero config, SARIF output.
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
/// orchestrator.rs — Run external tools and merge results into our Issue type.
///
/// We own React-specific rules. Everything else is delegated:
///   - oxlint  → general JS/TS lint rules (400+)
///   - cargo-audit → Rust dependency CVEs
///
/// Both are invoked as subprocesses with JSON output, then parsed into
/// the same `Issue` type used by our own rules so the HTML report can
/// show everything in one unified view.
///
/// Design principles:
///   - Print "Running <tool>..." before each subprocess so the user sees progress
///   - If a tool is not in PATH → silently skip, print hint to stderr
///   - If a tool fails → print warning, return empty Vec (never crash)
///   - All subprocess output is captured; nothing bleeds to stdout
use std::io::Write as _;
use std::path::Path;
use std::process::Command;
use std::time::Instant;

use crate::rules::{Issue, IssueCategory, IssueSource, Severity};

// ─── Orchestrator result ──────────────────────────────────────────────────────

pub struct OrchestratorResult {
    /// All issues from all external tools combined.
    pub issues: Vec<Issue>,
    /// Tools that were skipped (not installed) or failed.
    pub tools_skipped: Vec<(&'static str, String)>,
}

/// Maximum number of JS/TS files before we skip oxlint.
///
/// oxlint is great for project-sized scans but becomes unwieldy on monorepos
/// with tens-of-thousands of files — it can OOM, produce non-JSON output, or
/// just be very slow. Above this threshold we skip it and tell the user to
/// scope the scan more tightly.
const OXLINT_FILE_LIMIT: usize = 5_000;

/// Run all available external tools against `path` and return merged results.
/// `js_file_count` is the number of JS/TS files already discovered so we can
/// decide whether to run oxlint on the whole directory.
pub fn run_external_tools(path: &Path) -> OrchestratorResult {
    let mut all_issues: Vec<Issue> = vec![];
    let mut tools_skipped: Vec<(&'static str, String)> = vec![];

    // ── oxlint ────────────────────────────────────────────────────────────────
    // Count JS/TS files under path to guard against monorepo blowup.
    let js_count = count_js_files(path);

    if js_count > OXLINT_FILE_LIMIT {
        eprint!(
            "\r  ⚠  oxlint skipped — {js_count} JS/TS files exceeds limit ({OXLINT_FILE_LIMIT}){}\n",
            " ".repeat(5)
        );
        tools_skipped.push((
            "oxlint",
            format!(
                "skipped on large repos (>{OXLINT_FILE_LIMIT} files). \
                 Scope the scan: react-perf-analyzer ./src/components --no-external false"
            ),
        ));
    } else {
        eprint!("  🔍 Running oxlint ({js_count} files)...");
        let _ = std::io::stderr().flush();
        let t = Instant::now();

        match run_oxlint(path) {
            ToolResult::Ok(issues) => {
                let elapsed_ms = t.elapsed().as_millis();
                let count = issues.len();
                eprint!(
                    "\r  ✅ oxlint — {count} issue(s) in {elapsed_ms}ms{}\n",
                    " ".repeat(20)
                );
                all_issues.extend(issues);
            }
            ToolResult::NotInstalled => {
                eprint!("\r  ⚠  oxlint not found{}\n", " ".repeat(30));
                tools_skipped.push(("oxlint", "not found — install: npm i -g oxlint".into()));
            }
            ToolResult::Failed(msg) => {
                eprint!("\r  ⚠  oxlint failed{}\n", " ".repeat(30));
                tools_skipped.push(("oxlint", format!("failed: {msg}")));
            }
        }
    } // end oxlint else-block

    // ── cargo-audit ───────────────────────────────────────────────────────────
    // Only runs if a Cargo.lock file exists in the scanned path.
    if path.join("Cargo.lock").exists() {
        eprint!("  🔍 Running cargo-audit...");
        let _ = std::io::stderr().flush();
        let t = Instant::now();

        match run_cargo_audit(path) {
            ToolResult::Ok(issues) => {
                let elapsed_ms = t.elapsed().as_millis();
                let count = issues.len();
                eprint!(
                    "\r  ✅ cargo-audit — {count} issue(s) in {elapsed_ms}ms{}\n",
                    " ".repeat(10)
                );
                all_issues.extend(issues);
            }
            ToolResult::NotInstalled => {
                eprint!("\r  ⚠  cargo-audit not found{}\n", " ".repeat(20));
                tools_skipped.push((
                    "cargo-audit",
                    "not found — install: cargo install cargo-audit".into(),
                ));
            }
            ToolResult::Failed(msg) => {
                eprint!("\r  ⚠  cargo-audit failed{}\n", " ".repeat(20));
                tools_skipped.push(("cargo-audit", format!("failed: {msg}")));
            }
        }
    }

    OrchestratorResult {
        issues: all_issues,
        tools_skipped,
    }
}

// ─── Internal result type ─────────────────────────────────────────────────────

enum ToolResult {
    Ok(Vec<Issue>),
    NotInstalled,
    Failed(String),
}

// ─── oxlint ───────────────────────────────────────────────────────────────────

/// Run `oxlint --format json <path>` and parse the output.
///
/// oxlint JSON schema (relevant fields):
/// ```json
/// {
///   "diagnostics": [
///     {
///       "message": "...",
///       "code": "eslint(no-unused-vars)",
///       "severity": "warning",
///       "filename": "src/foo.ts",
///       "labels": [{ "span": { "line": 12, "column": 5 } }]
///     }
///   ]
/// }
/// ```
fn run_oxlint(path: &Path) -> ToolResult {
    let path_str = match path.to_str() {
        Some(s) => s,
        None => return ToolResult::Failed("invalid path".into()),
    };

    let output = Command::new("oxlint")
        .args(["--format", "json", path_str])
        .output();

    let output = match output {
        Ok(o) => o,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            // Try npx fallback
            let npx_args = ["oxlint", "--format", "json", path_str];
            match Command::new("npx").args(npx_args).output() {
                Ok(o) => o,
                Err(_) => return ToolResult::NotInstalled,
            }
        }
        Err(e) => return ToolResult::Failed(e.to_string()),
    };

    // oxlint exits 1 when issues are found — that's normal, not an error.
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    // Empty stdout: check if stderr says "not found" vs a real failure.
    if stdout.trim().is_empty() {
        if stderr.contains("not found")
            || stderr.contains("Cannot find")
            || stderr.contains("command not found")
        {
            return ToolResult::NotInstalled;
        }
        // Truly empty output = no issues (e.g. all files filtered out).
        return ToolResult::Ok(vec![]);
    }

    // oxlint sometimes writes progress/warning lines to stdout before the JSON.
    // Find the first '{' to skip any non-JSON prefix.
    let json_start = stdout.find('{').unwrap_or(0);
    let json_str = &stdout[json_start..];

    if json_str.trim().is_empty() {
        return ToolResult::Ok(vec![]);
    }

    parse_oxlint_json(json_str, path)
}

fn parse_oxlint_json(json: &str, base_path: &Path) -> ToolResult {
    // Parse with serde_json into a flexible Value first.
    let value: serde_json::Value = match serde_json::from_str(json) {
        Ok(v) => v,
        Err(e) => return ToolResult::Failed(format!("JSON parse error: {e}")),
    };

    let diagnostics = match value.get("diagnostics").and_then(|d| d.as_array()) {
        Some(d) => d,
        None => return ToolResult::Ok(vec![]),
    };

    let mut issues = vec![];

    for diag in diagnostics {
        let message = diag
            .get("message")
            .and_then(|m| m.as_str())
            .unwrap_or("")
            .to_string();

        let rule = diag
            .get("code")
            .and_then(|c| c.as_str())
            .unwrap_or("oxlint")
            // Strip the "eslint(...)" wrapper → keep just the rule name
            .trim_start_matches("eslint(")
            .trim_start_matches("oxc(")
            .trim_end_matches(')')
            .to_string();

        let severity_str = diag
            .get("severity")
            .and_then(|s| s.as_str())
            .unwrap_or("warning");

        let severity = match severity_str {
            "error" => Severity::High,
            _ => Severity::Low,
        };

        let filename = diag.get("filename").and_then(|f| f.as_str()).unwrap_or("");

        // Resolve file path relative to base_path if needed.
        let file_path = if std::path::Path::new(filename).is_absolute() {
            std::path::PathBuf::from(filename)
        } else {
            base_path.join(filename)
        };

        // Location from first label's span.
        let (line, column) = diag
            .get("labels")
            .and_then(|l| l.as_array())
            .and_then(|l| l.first())
            .and_then(|l| l.get("span"))
            .map(|span| {
                let line = span.get("line").and_then(|v| v.as_u64()).unwrap_or(1) as u32;
                let col = span.get("column").and_then(|v| v.as_u64()).unwrap_or(1) as u32;
                (line, col)
            })
            .unwrap_or((1, 1));

        if message.is_empty() || filename.is_empty() {
            continue;
        }

        issues.push(Issue {
            rule,
            message,
            file: file_path,
            line,
            column,
            severity,
            source: IssueSource::OxcLinter,
            category: IssueCategory::Performance, // oxlint mixes perf + style
        });
    }

    ToolResult::Ok(issues)
}

// ─── cargo-audit ──────────────────────────────────────────────────────────────

/// Run `cargo audit --json` and parse RUSTSEC advisories.
///
/// cargo-audit JSON schema (relevant fields):
/// ```json
/// {
///   "vulnerabilities": {
///     "list": [
///       {
///         "advisory": {
///           "id": "RUSTSEC-2024-0001",
///           "title": "...",
///           "description": "...",
///           "cvss": "CVSS:3.1/AV:N/.../7.5"
///         },
///         "package": {
///           "name": "...",
///           "version": "...",
///           "manifest_path": "/path/to/Cargo.toml"
///         }
///       }
///     ]
///   }
/// }
/// ```
fn run_cargo_audit(path: &Path) -> ToolResult {
    let output = Command::new("cargo")
        .args(["audit", "--json"])
        .current_dir(path)
        .output();

    let output = match output {
        Ok(o) => o,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return ToolResult::NotInstalled,
        Err(e) => return ToolResult::Failed(e.to_string()),
    };

    // cargo audit exits 1 when vulnerabilities are found — that's normal.
    let stdout = String::from_utf8_lossy(&output.stdout);

    if stdout.trim().is_empty() {
        return ToolResult::Ok(vec![]);
    }

    // Check for "no such command: audit" error (cargo-audit not installed).
    let stderr = String::from_utf8_lossy(&output.stderr);
    if stderr.contains("no such command") || stderr.contains("unknown subcommand") {
        return ToolResult::NotInstalled;
    }

    parse_cargo_audit_json(&stdout, path)
}

fn parse_cargo_audit_json(json: &str, base_path: &Path) -> ToolResult {
    let value: serde_json::Value = match serde_json::from_str(json) {
        Ok(v) => v,
        Err(e) => return ToolResult::Failed(format!("JSON parse error: {e}")),
    };

    let vuln_list = value
        .pointer("/vulnerabilities/list")
        .and_then(|l| l.as_array());

    let Some(vulns) = vuln_list else {
        return ToolResult::Ok(vec![]);
    };

    let mut issues = vec![];

    for vuln in vulns {
        let advisory = match vuln.get("advisory") {
            Some(a) => a,
            None => continue,
        };

        let id = advisory
            .get("id")
            .and_then(|v| v.as_str())
            .unwrap_or("RUSTSEC-UNKNOWN");

        let title = advisory
            .get("title")
            .and_then(|v| v.as_str())
            .unwrap_or("Unknown vulnerability");

        let pkg_name = vuln
            .pointer("/package/name")
            .and_then(|v| v.as_str())
            .unwrap_or("unknown");

        let pkg_version = vuln
            .pointer("/package/version")
            .and_then(|v| v.as_str())
            .unwrap_or("?");

        // Derive severity from CVSS score if available.
        let severity = advisory
            .get("cvss")
            .and_then(|c| c.as_str())
            .and_then(extract_cvss_score)
            .map(|score| {
                if score >= 9.0 {
                    Severity::Critical
                } else if score >= 7.0 {
                    Severity::High
                } else if score >= 4.0 {
                    Severity::Medium
                } else {
                    Severity::Low
                }
            })
            .unwrap_or(Severity::High); // default High when no CVSS

        // Point to Cargo.lock as the file location.
        let cargo_lock = base_path.join("Cargo.lock");

        issues.push(Issue {
            rule: id.to_string(),
            message: format!("{id}: {title} in {pkg_name} v{pkg_version}"),
            file: cargo_lock,
            line: 1,
            column: 1,
            severity,
            source: IssueSource::CargoAudit,
            category: IssueCategory::Dependency,
        });
    }

    ToolResult::Ok(issues)
}

/// Extract the numeric CVSS base score from a CVSS vector string.
/// Example: "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H" → None
/// (We look for the /score suffix some tools append, or default to None.)
fn extract_cvss_score(cvss: &str) -> Option<f64> {
    // Some tools append the score as the last component: ".../7.5"
    cvss.rsplit('/')
        .next()
        .and_then(|s| s.parse::<f64>().ok())
        .filter(|&s| s > 0.0 && s <= 10.0)
}

/// Count JS/TS/JSX/TSX files under `path` (walks the tree, respects the same
/// exclusion rules as `collect_files`). Used to guard oxlint against monorepos.
/// Returns quickly by stopping the count once `OXLINT_FILE_LIMIT` is exceeded.
fn count_js_files(path: &Path) -> usize {
    use walkdir::WalkDir;
    let mut count = 0usize;
    let extensions = ["js", "jsx", "ts", "tsx", "mjs", "cjs"];

    for entry in WalkDir::new(path)
        .follow_links(false)
        .into_iter()
        .filter_entry(|e| {
            let name = e.file_name().to_string_lossy();
            !matches!(
                name.as_ref(),
                "node_modules" | ".git" | "dist" | "build" | "target" | ".next" | "coverage"
            )
        })
        .flatten()
    {
        if entry.file_type().is_file() {
            if let Some(ext) = entry.path().extension() {
                if extensions.contains(&ext.to_string_lossy().as_ref()) {
                    count += 1;
                    // Short-circuit: no need to count beyond the limit.
                    if count > OXLINT_FILE_LIMIT {
                        return count;
                    }
                }
            }
        }
    }
    count
}