Skip to main content

react_auditor/rules/security/
no_dangerously_set_innerhtml.rs

1use oxc_ast::ast::Program;
2use oxc_ast_visit::Visit;
3use oxc_semantic::Semantic;
4
5use crate::rules::{Rule, RuleFinding, RuleMeta, Severity};
6
7pub struct NoDangerouslySetInnerHtml;
8
9const RULE_META: RuleMeta = RuleMeta {
10    id: "no-dangerously-set-innerhtml",
11    default_severity: Severity::Error,
12    category: "security",
13    description: "Avoid `dangerouslySetInnerHTML`",
14};
15
16impl Rule for NoDangerouslySetInnerHtml {
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 = DangerousHtmlCollector {
23            findings: Vec::new(),
24            source: source_text,
25        };
26        collector.visit_program(program);
27        collector.findings
28    }
29}
30
31struct DangerousHtmlCollector<'a> {
32    findings: Vec<RuleFinding>,
33    source: &'a str,
34}
35
36impl<'a> Visit<'a> for DangerousHtmlCollector<'a> {
37    fn visit_jsx_opening_element(&mut self, el: &oxc_ast::ast::JSXOpeningElement<'a>) {
38        for attr_item in &el.attributes {
39            if let oxc_ast::ast::JSXAttributeItem::Attribute(attr) = attr_item {
40                let is_dangerous = matches!(&attr.name, oxc_ast::ast::JSXAttributeName::Identifier(id) if id.name.as_str() == "dangerouslySetInnerHTML");
41                if is_dangerous {
42                    let start = attr.span.start as usize;
43                    let line = self.source[..start].lines().count().max(1);
44                    let col = start - self.source[..start].rfind('\n').map(|i| i + 1).unwrap_or(0);
45                    self.findings.push(RuleFinding {
46                        line,
47                        column: col + 1,
48                        message: "Avoid `dangerouslySetInnerHTML` — sanitize HTML with DOMPurify if needed".to_string(),
49                    });
50                }
51            }
52        }
53    }
54}