react_auditor/rules/security/
no_eval.rs1use oxc_ast::ast::Program;
2use oxc_ast_visit::Visit;
3use oxc_semantic::Semantic;
4
5use crate::rules::{Rule, RuleFinding, RuleMeta, Severity};
6
7pub struct NoEval;
8
9const RULE_META: RuleMeta = RuleMeta {
10 id: "no-eval",
11 default_severity: Severity::Error,
12 category: "security",
13 description: "No eval, Function(), or setTimeout with string args",
14};
15
16impl Rule for NoEval {
17 fn meta(&self) -> &RuleMeta {
18 &RULE_META
19 }
20
21 fn run(&self, program: &Program, _semantic: &Semantic, source_text: &str) -> Vec<RuleFinding> {
22 let mut collector = EvalCollector {
23 findings: Vec::new(),
24 source: source_text,
25 };
26 collector.visit_program(program);
27 collector.findings
28 }
29}
30
31struct EvalCollector<'a> {
32 findings: Vec<RuleFinding>,
33 source: &'a str,
34}
35
36impl<'a> Visit<'a> for EvalCollector<'a> {
37 fn visit_call_expression(&mut self, expr: &oxc_ast::ast::CallExpression<'a>) {
38 if let oxc_ast::ast::Expression::Identifier(ident) = &expr.callee {
39 let name = ident.name.as_str();
40 if name == "eval" {
41 let start = expr.span.start as usize;
42 let line = self.source[..start].lines().count().max(1);
43 let col = start - self.source[..start].rfind('\n').map(|i| i + 1).unwrap_or(0);
44 self.findings.push(RuleFinding {
45 line,
46 column: col + 1,
47 message: "Unexpected `eval()` — security risk".to_string(),
48 });
49 }
50 } else if let Some(member) = expr.callee.as_member_expression() {
51 let name = member.static_property_name().unwrap_or("");
52 let is_dynamic = name == "Function"
53 || name == "constructor"
54 || name == "setTimeout"
55 || name == "setInterval";
56 if is_dynamic {
57 let obj = member.object();
58 if let oxc_ast::ast::Expression::Identifier(ident) = obj
59 && (ident.name.as_str() == "window" || ident.name.as_str() == "globalThis")
60 {
61 let start = expr.span.start as usize;
62 let line = self.source[..start].lines().count().max(1);
63 let col = start - self.source[..start].rfind('\n').map(|i| i + 1).unwrap_or(0);
64 self.findings.push(RuleFinding {
65 line,
66 column: col + 1,
67 message: format!("Unexpected dynamic code execution via `{}`", name),
68 });
69 }
70 }
71 }
72 }
73}