rma-analyzer 0.14.0

Code analysis and security scanning for Rust Monorepo Analyzer
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
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
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
//! JavaScript-specific security vulnerability DETECTION rules
//!
//! These rules DETECT dangerous patterns in JavaScript code for security auditing.
//! This is a security analysis tool - it detects but does not execute dangerous code.

use crate::rules::{Rule, create_finding, create_finding_with_confidence};
use rma_common::{Confidence, Finding, Language, Severity};
use rma_parser::ParsedFile;
use std::collections::HashSet;
use tree_sitter::Node;

/// DETECTS dangerous dynamic code execution patterns (security vulnerability detection)
/// This rule detects uses of dangerous APIs like the eval function and Function constructor
pub struct DynamicCodeExecutionRule;

impl Rule for DynamicCodeExecutionRule {
    fn id(&self) -> &str {
        "js/dynamic-code-execution"
    }

    fn description(&self) -> &str {
        "Detects dangerous code execution APIs that may lead to code injection"
    }

    fn applies_to(&self, lang: Language) -> bool {
        matches!(lang, Language::JavaScript | Language::TypeScript)
    }

    fn check(&self, parsed: &ParsedFile) -> Vec<Finding> {
        let mut findings = Vec::new();
        let mut cursor = parsed.tree.walk();

        // Only truly dangerous functions - NOT setTimeout/setInterval (handled by TimerStringRule)
        // NOTE: This is a DETECTION rule - we identify dangerous patterns, we don't execute them
        let dangerous_api_names = ["eval", "Function"];

        find_call_expressions(&mut cursor, |node: Node| {
            if let Some(func) = node.child_by_field_name("function")
                && let Ok(text) = func.utf8_text(parsed.content.as_bytes())
                && dangerous_api_names.contains(&text)
            {
                findings.push(create_finding(
                    self.id(),
                    &node,
                    &parsed.path,
                    &parsed.content,
                    Severity::Critical,
                    &format!(
                        "Detected dangerous {} call - potential code injection vulnerability",
                        text
                    ),
                    Language::JavaScript,
                ));
            }
        });
        findings
    }
}

/// DETECTS setTimeout/setInterval with string argument (behaves like code execution)
///
/// Only flags when the first argument is:
/// - A string literal ("code")
/// - A template literal (`code`)
/// - String concatenation ("code" + variable)
///
/// Does NOT flag when the first argument is:
/// - A function reference (foo)
/// - An arrow function (() => {})
/// - A function expression (function() {})
pub struct TimerStringRule;

impl Rule for TimerStringRule {
    fn id(&self) -> &str {
        "js/timer-string-eval"
    }

    fn description(&self) -> &str {
        "Detects setTimeout/setInterval with string argument which executes code dynamically"
    }

    fn applies_to(&self, lang: Language) -> bool {
        matches!(lang, Language::JavaScript | Language::TypeScript)
    }

    fn check(&self, parsed: &ParsedFile) -> Vec<Finding> {
        let mut findings = Vec::new();
        let mut cursor = parsed.tree.walk();

        find_call_expressions(&mut cursor, |node: Node| {
            if let Some(func) = node.child_by_field_name("function")
                && let Ok(text) = func.utf8_text(parsed.content.as_bytes())
                && (text == "setTimeout" || text == "setInterval")
                && let Some(args) = node.child_by_field_name("arguments")
                && let Some(first_arg) = args.named_child(0)
                && is_string_like_argument(&first_arg)
            {
                findings.push(create_finding(
                    self.id(),
                    &node,
                    &parsed.path,
                    &parsed.content,
                    Severity::Warning,
                    &format!(
                        "String passed to {} behaves like dynamic code execution; use a function instead.",
                        text
                    ),
                    Language::JavaScript,
                ));
            }
        });
        findings
    }
}

/// Check if a node is a string-like argument (string literal, template literal, or concatenation)
fn is_string_like_argument(node: &Node) -> bool {
    match node.kind() {
        // Direct string literal: "code"
        "string" | "string_fragment" => true,
        // Template literal: `code`
        "template_string" => true,
        // String concatenation: "code" + x
        "binary_expression" => {
            // Check if it's string concatenation (at least one operand is a string)
            if let Some(left) = node.child_by_field_name("left")
                && is_string_like_argument(&left)
            {
                return true;
            }
            if let Some(right) = node.child_by_field_name("right")
                && is_string_like_argument(&right)
            {
                return true;
            }
            false
        }
        _ => false,
    }
}

/// DETECTS dangerous HTML property WRITE patterns (XSS sink vulnerability detection)
///
/// Only flags WRITE/assignment patterns like:
/// - `el.innerHTML = userInput`
/// - `el.outerHTML = userInput`
///
/// READ patterns (e.g., `const x = el.innerHTML`) are handled by InnerHtmlReadRule
/// with lower severity since they don't directly cause XSS.
pub struct InnerHtmlRule;

impl InnerHtmlRule {
    /// Properties that can cause XSS when written to
    const DANGEROUS_PROPS: &'static [&'static str] = &["innerHTML", "outerHTML"];

    /// Check if a member_expression node is on the LEFT side of an assignment
    fn is_assignment_target(node: &Node) -> bool {
        if let Some(parent) = node.parent() {
            // Check if parent is an assignment_expression
            if parent.kind() == "assignment_expression" {
                // Check if this node is the left side
                if let Some(left) = parent.child_by_field_name("left") {
                    return left.id() == node.id();
                }
            }
            // Also check augmented assignment: el.innerHTML += x
            if parent.kind() == "augmented_assignment_expression"
                && let Some(left) = parent.child_by_field_name("left")
            {
                return left.id() == node.id();
            }
        }
        false
    }
}

impl Rule for InnerHtmlRule {
    fn id(&self) -> &str {
        "js/innerhtml-xss"
    }

    fn description(&self) -> &str {
        "Detects dangerous HTML property assignments (XSS sinks)"
    }

    fn applies_to(&self, lang: Language) -> bool {
        matches!(lang, Language::JavaScript | Language::TypeScript)
    }

    fn uses_flow(&self) -> bool {
        true
    }

    fn check(&self, parsed: &ParsedFile) -> Vec<Finding> {
        // Fallback without flow - flag all innerHTML assignments
        let mut findings = Vec::new();
        let mut cursor = parsed.tree.walk();

        find_member_expressions(&mut cursor, |node: Node| {
            if let Some(prop) = node.child_by_field_name("property")
                && let Ok(text) = prop.utf8_text(parsed.content.as_bytes())
                && Self::DANGEROUS_PROPS.contains(&text)
                && Self::is_assignment_target(&node)
            {
                findings.push(create_finding_with_confidence(
                    self.id(),
                    &node,
                    &parsed.path,
                    &parsed.content,
                    Severity::Error,
                    &format!(
                        "{} assignment detected - XSS sink. Sanitize input or use textContent.",
                        text
                    ),
                    Language::JavaScript,
                    Confidence::High,
                ));
            }
        });
        findings
    }

    fn check_with_flow(
        &self,
        parsed: &ParsedFile,
        flow: &crate::flow::FlowContext,
    ) -> Vec<Finding> {
        let mut findings = Vec::new();
        let mut cursor = parsed.tree.walk();

        find_member_expressions(&mut cursor, |node: Node| {
            if let Some(prop) = node.child_by_field_name("property")
                && let Ok(prop_text) = prop.utf8_text(parsed.content.as_bytes())
                && Self::DANGEROUS_PROPS.contains(&prop_text)
                && Self::is_assignment_target(&node)
            {
                // Get the parent assignment to check what's being assigned
                if let Some(parent) = node.parent() {
                    if let Some(right) = parent.child_by_field_name("right") {
                        let (severity, confidence, message) = Self::analyze_assignment_with_path(
                            &right,
                            parsed,
                            flow,
                            prop_text,
                            node.id(),
                        );

                        // Only emit findings for Warning or higher
                        if severity >= Severity::Warning {
                            findings.push(create_finding_with_confidence(
                                self.id(),
                                &node,
                                &parsed.path,
                                &parsed.content,
                                severity,
                                &message,
                                Language::JavaScript,
                                confidence,
                            ));
                        }
                    }
                }
            }
        });
        findings
    }
}

impl InnerHtmlRule {
    /// Analyze what's being assigned to innerHTML with path-sensitive taint analysis
    fn analyze_assignment_with_path(
        right: &Node,
        parsed: &ParsedFile,
        flow: &crate::flow::FlowContext,
        prop_name: &str,
        sink_node_id: usize,
    ) -> (Severity, Confidence, String) {
        use crate::flow::{TaintLevel, ValueOrigin};

        match right.kind() {
            // Static string literal → Low severity (probably safe)
            "string" => (
                Severity::Info,
                Confidence::High,
                format!("{} assigned from string literal - likely safe", prop_name),
            ),

            // Template string without interpolation → probably safe
            "template_string" => {
                let text = right.utf8_text(parsed.content.as_bytes()).unwrap_or("");
                // Check if it has interpolations (contains ${)
                if text.contains("${") {
                    (
                        Severity::Warning,
                        Confidence::Medium,
                        format!(
                            "{} assigned from template literal with interpolation - review for XSS",
                            prop_name
                        ),
                    )
                } else {
                    (
                        Severity::Info,
                        Confidence::High,
                        format!(
                            "{} assigned from static template literal - likely safe",
                            prop_name
                        ),
                    )
                }
            }

            // Variable → use path-sensitive taint analysis
            "identifier" => {
                let var_name = right.utf8_text(parsed.content.as_bytes()).unwrap_or("");

                // Use path-sensitive taint level
                let taint_level = flow.taint_level_at(var_name, sink_node_id);

                match taint_level {
                    TaintLevel::Full => (
                        Severity::Error,
                        Confidence::High,
                        format!(
                            "{} assigned from tainted variable '{}' - XSS vulnerability. Sanitize with DOMPurify or use textContent.",
                            prop_name, var_name
                        ),
                    ),
                    TaintLevel::Partial => (
                        Severity::Warning,
                        Confidence::Medium,
                        format!(
                            "{} assigned from '{}' which is tainted on some paths - ensure sanitization on all paths",
                            prop_name, var_name
                        ),
                    ),
                    TaintLevel::Clean => {
                        // Check if it was sanitized or is a literal
                        if flow.symbols.is_literal(var_name) {
                            (
                                Severity::Info,
                                Confidence::High,
                                format!(
                                    "{} assigned from '{}' (literal value) - safe",
                                    prop_name, var_name
                                ),
                            )
                        } else {
                            let origin = flow.symbols.origin_of(var_name);
                            match origin {
                                ValueOrigin::FunctionCall(ref func_name)
                                    if flow.config.is_sanitizer(func_name) =>
                                {
                                    (
                                        Severity::Info,
                                        Confidence::High,
                                        format!(
                                            "{} assigned from '{}' (sanitized by {}) - safe",
                                            prop_name, var_name, func_name
                                        ),
                                    )
                                }
                                ValueOrigin::FunctionCall(ref func_name) => (
                                    Severity::Warning,
                                    Confidence::Medium,
                                    format!(
                                        "{} assigned from '{}' (from function '{}') - review for XSS",
                                        prop_name, var_name, func_name
                                    ),
                                ),
                                ValueOrigin::Literal(_) => (
                                    Severity::Info,
                                    Confidence::High,
                                    format!(
                                        "{} assigned from '{}' (literal) - safe",
                                        prop_name, var_name
                                    ),
                                ),
                                _ => (
                                    Severity::Info,
                                    Confidence::Medium,
                                    format!(
                                        "{} assigned from '{}' (clean) - likely safe",
                                        prop_name, var_name
                                    ),
                                ),
                            }
                        }
                    }
                }
            }

            // Function call → check if it's a sanitizer
            "call_expression" => {
                if let Some(func_node) = right.child_by_field_name("function") {
                    let func_name = func_node.utf8_text(parsed.content.as_bytes()).unwrap_or("");

                    if flow.config.is_sanitizer(func_name) {
                        (
                            Severity::Info,
                            Confidence::High,
                            format!(
                                "{} assigned from sanitizer '{}' - safe",
                                prop_name, func_name
                            ),
                        )
                    } else if flow.config.is_source_function(func_name) {
                        (
                            Severity::Error,
                            Confidence::High,
                            format!(
                                "{} assigned directly from taint source '{}' - XSS vulnerability",
                                prop_name, func_name
                            ),
                        )
                    } else {
                        (
                            Severity::Warning,
                            Confidence::Medium,
                            format!(
                                "{} assigned from function call '{}' - review for XSS",
                                prop_name, func_name
                            ),
                        )
                    }
                } else {
                    (
                        Severity::Warning,
                        Confidence::Low,
                        format!("{} assigned from function call - review for XSS", prop_name),
                    )
                }
            }

            // Member expression → check if it's a taint source
            "member_expression" => {
                let member_path = right.utf8_text(parsed.content.as_bytes()).unwrap_or("");

                if flow.config.is_source_member(member_path) {
                    (
                        Severity::Error,
                        Confidence::High,
                        format!(
                            "{} assigned directly from taint source '{}' - XSS vulnerability",
                            prop_name, member_path
                        ),
                    )
                } else {
                    (
                        Severity::Warning,
                        Confidence::Medium,
                        format!(
                            "{} assigned from member access '{}' - review for XSS",
                            prop_name, member_path
                        ),
                    )
                }
            }

            // Binary expression (concatenation) → check for tainted parts
            "binary_expression" => (
                Severity::Warning,
                Confidence::Medium,
                format!(
                    "{} assigned from expression - review for XSS if any part is user-controlled",
                    prop_name
                ),
            ),

            // Other cases
            _ => (
                Severity::Warning,
                Confidence::Low,
                format!("{} assignment detected - review for XSS", prop_name),
            ),
        }
    }
}

/// DETECTS dangerous HTML property READ patterns (informational)
///
/// READ patterns like `const x = el.innerHTML` are flagged at INFO level
/// since reading doesn't directly cause XSS but may indicate patterns
/// worth reviewing (e.g., storing and later writing unsanitized content).
pub struct InnerHtmlReadRule;

impl Rule for InnerHtmlReadRule {
    fn id(&self) -> &str {
        "js/innerhtml-read"
    }

    fn description(&self) -> &str {
        "Detects dangerous HTML property read access (informational)"
    }

    fn applies_to(&self, lang: Language) -> bool {
        matches!(lang, Language::JavaScript | Language::TypeScript)
    }

    fn check(&self, parsed: &ParsedFile) -> Vec<Finding> {
        let mut findings = Vec::new();
        let mut cursor = parsed.tree.walk();

        find_member_expressions(&mut cursor, |node: Node| {
            if let Some(prop) = node.child_by_field_name("property")
                && let Ok(text) = prop.utf8_text(parsed.content.as_bytes())
                && InnerHtmlRule::DANGEROUS_PROPS.contains(&text)
                && !InnerHtmlRule::is_assignment_target(&node)
            {
                findings.push(create_finding_with_confidence(
                    self.id(),
                    &node,
                    &parsed.path,
                    &parsed.content,
                    Severity::Info,
                    &format!(
                        "{} read detected - review if content is later written unsanitized",
                        text
                    ),
                    Language::JavaScript,
                    Confidence::Low,
                ));
            }
        });
        findings
    }
}

/// DETECTS console.log statements (code quality issue detection)
pub struct ConsoleLogRule;

impl Rule for ConsoleLogRule {
    fn id(&self) -> &str {
        "js/console-log"
    }

    fn description(&self) -> &str {
        "Detects console.log statements that should be removed in production"
    }

    fn applies_to(&self, lang: Language) -> bool {
        matches!(lang, Language::JavaScript | Language::TypeScript)
    }

    fn check(&self, parsed: &ParsedFile) -> Vec<Finding> {
        let mut findings = Vec::new();
        let mut cursor = parsed.tree.walk();

        find_call_expressions(&mut cursor, |node: Node| {
            if let Some(func) = node.child_by_field_name("function")
                && let Ok(text) = func.utf8_text(parsed.content.as_bytes())
                && text.starts_with("console.")
            {
                findings.push(create_finding(
                    self.id(),
                    &node,
                    &parsed.path,
                    &parsed.content,
                    Severity::Info,
                    "console statement detected - consider removing for production",
                    Language::JavaScript,
                ));
            }
        });
        findings
    }
}

// =============================================================================
// PRIORITY 1: Additional Security Sinks
// =============================================================================

/// DETECTS javascript: URLs in JSX/HTML attributes (XSS vulnerability)
pub struct JsxScriptUrlRule;

impl Rule for JsxScriptUrlRule {
    fn id(&self) -> &str {
        "js/jsx-no-script-url"
    }

    fn description(&self) -> &str {
        "Detects javascript: URLs which can execute arbitrary code"
    }

    fn applies_to(&self, lang: Language) -> bool {
        matches!(lang, Language::JavaScript | Language::TypeScript)
    }

    fn check(&self, parsed: &ParsedFile) -> Vec<Finding> {
        let mut findings = Vec::new();
        let mut cursor = parsed.tree.walk();

        find_nodes_by_kind(&mut cursor, "string", |node: Node| {
            if let Ok(text) = node.utf8_text(parsed.content.as_bytes()) {
                // Use case-insensitive search without allocation
                if contains_ignore_case(text, "javascript:") {
                    findings.push(create_finding_with_confidence(
                        self.id(),
                        &node,
                        &parsed.path,
                        &parsed.content,
                        Severity::Critical,
                        "javascript: URL detected - XSS vulnerability. Use onClick handler instead.",
                        Language::JavaScript,
                        Confidence::High,
                    ));
                }
            }
        });
        findings
    }
}

/// Case-insensitive substring search without allocation
#[inline]
fn contains_ignore_case(haystack: &str, needle: &str) -> bool {
    haystack
        .as_bytes()
        .windows(needle.len())
        .any(|window| window.eq_ignore_ascii_case(needle.as_bytes()))
}

/// DETECTS React's dangerous HTML escape hatch
pub struct DangerousHtmlRule;

impl Rule for DangerousHtmlRule {
    fn id(&self) -> &str {
        "js/dangerous-html"
    }

    fn description(&self) -> &str {
        "Detects React props that bypass XSS protection"
    }

    fn applies_to(&self, lang: Language) -> bool {
        matches!(lang, Language::JavaScript | Language::TypeScript)
    }

    fn check(&self, parsed: &ParsedFile) -> Vec<Finding> {
        let mut findings = Vec::new();
        let mut seen_lines: std::collections::HashSet<usize> = std::collections::HashSet::new();
        let mut cursor = parsed.tree.walk();

        // The prop name we're looking for (React's raw HTML prop)
        const DANGEROUS_PROP: &str = "dangerouslySetInnerHTML";

        find_nodes_by_kind(&mut cursor, "property_identifier", |node: Node| {
            if let Ok(text) = node.utf8_text(parsed.content.as_bytes())
                && text == DANGEROUS_PROP
            {
                let line = node.start_position().row + 1;
                seen_lines.insert(line);
                findings.push(create_finding_with_confidence(
                    self.id(),
                    &node,
                    &parsed.path,
                    &parsed.content,
                    Severity::Warning,
                    "Raw HTML prop bypasses XSS protection - ensure content is sanitized",
                    Language::JavaScript,
                    Confidence::High,
                ));
            }
        });

        cursor = parsed.tree.walk();
        find_nodes_by_kind(&mut cursor, "jsx_attribute", |node: Node| {
            let line = node.start_position().row + 1;
            if let Ok(text) = node.utf8_text(parsed.content.as_bytes())
                && text.contains(DANGEROUS_PROP)
                && !seen_lines.contains(&line)
            // O(1) lookup instead of O(n)
            {
                seen_lines.insert(line);
                findings.push(create_finding_with_confidence(
                    self.id(),
                    &node,
                    &parsed.path,
                    &parsed.content,
                    Severity::Warning,
                    "Raw HTML prop bypasses XSS protection - ensure content is sanitized",
                    Language::JavaScript,
                    Confidence::High,
                ));
            }
        });
        findings
    }
}

/// DETECTS debugger statements
pub struct DebuggerStatementRule;

impl Rule for DebuggerStatementRule {
    fn id(&self) -> &str {
        "js/no-debugger"
    }

    fn description(&self) -> &str {
        "Detects debugger statements that should not be in production code"
    }

    fn applies_to(&self, lang: Language) -> bool {
        matches!(lang, Language::JavaScript | Language::TypeScript)
    }

    fn check(&self, parsed: &ParsedFile) -> Vec<Finding> {
        let mut findings = Vec::new();
        let mut cursor = parsed.tree.walk();

        find_nodes_by_kind(&mut cursor, "debugger_statement", |node: Node| {
            findings.push(create_finding(
                self.id(),
                &node,
                &parsed.path,
                &parsed.content,
                Severity::Warning,
                "debugger statement detected - remove before production",
                Language::JavaScript,
            ));
        });
        findings
    }
}

/// DETECTS alert/confirm/prompt
pub struct NoAlertRule;

impl Rule for NoAlertRule {
    fn id(&self) -> &str {
        "js/no-alert"
    }

    fn description(&self) -> &str {
        "Detects alert/confirm/prompt which should not be used in production"
    }

    fn applies_to(&self, lang: Language) -> bool {
        matches!(lang, Language::JavaScript | Language::TypeScript)
    }

    fn check(&self, parsed: &ParsedFile) -> Vec<Finding> {
        let mut findings = Vec::new();
        let mut cursor = parsed.tree.walk();

        let dialog_functions = ["alert", "confirm", "prompt"];

        find_call_expressions(&mut cursor, |node: Node| {
            if let Some(func) = node.child_by_field_name("function")
                && let Ok(text) = func.utf8_text(parsed.content.as_bytes())
                && dialog_functions.contains(&text)
            {
                findings.push(create_finding(
                    self.id(),
                    &node,
                    &parsed.path,
                    &parsed.content,
                    Severity::Warning,
                    &format!("{}() detected - use a proper UI component instead", text),
                    Language::JavaScript,
                ));
            }
        });
        findings
    }
}

// =============================================================================
// PRIORITY 2: Correctness Rules
// =============================================================================

/// DETECTS == and != instead of === and !==
pub struct StrictEqualityRule;

impl Rule for StrictEqualityRule {
    fn id(&self) -> &str {
        "js/eqeqeq"
    }

    fn description(&self) -> &str {
        "Detects == and != which can cause type coercion bugs"
    }

    fn applies_to(&self, lang: Language) -> bool {
        matches!(lang, Language::JavaScript | Language::TypeScript)
    }

    fn check(&self, parsed: &ParsedFile) -> Vec<Finding> {
        let mut findings = Vec::new();
        let mut cursor = parsed.tree.walk();

        find_nodes_by_kind(&mut cursor, "binary_expression", |node: Node| {
            if let Some(op) = node.child_by_field_name("operator")
                && let Ok(op_text) = op.utf8_text(parsed.content.as_bytes())
            {
                let (is_loose, suggestion) = match op_text {
                    "==" => (true, "==="),
                    "!=" => (true, "!=="),
                    _ => (false, ""),
                };

                if is_loose {
                    // Skip null checks: x == null is a common pattern
                    if let Some(right) = node.child_by_field_name("right")
                        && let Ok(right_text) = right.utf8_text(parsed.content.as_bytes())
                        && (right_text == "null" || right_text == "undefined")
                    {
                        return;
                    }
                    if let Some(left) = node.child_by_field_name("left")
                        && let Ok(left_text) = left.utf8_text(parsed.content.as_bytes())
                        && (left_text == "null" || left_text == "undefined")
                    {
                        return;
                    }

                    findings.push(create_finding_with_confidence(
                        self.id(),
                        &node,
                        &parsed.path,
                        &parsed.content,
                        Severity::Warning,
                        &format!(
                            "Use {} instead of {} to avoid type coercion",
                            suggestion, op_text
                        ),
                        Language::JavaScript,
                        Confidence::High,
                    ));
                }
            }
        });
        findings
    }
}

/// DETECTS assignment in conditions (if/while/for/do-while)
///
/// Only flags assignments inside actual control flow conditions, NOT:
/// - Ternary expressions in JSX/template literals (these are intentional)
/// - Assignments wrapped in parentheses and compared (intentional pattern)
pub struct NoConditionAssignRule;

impl Rule for NoConditionAssignRule {
    fn id(&self) -> &str {
        "js/no-cond-assign"
    }

    fn description(&self) -> &str {
        "Detects assignments in conditions which are usually bugs"
    }

    fn applies_to(&self, lang: Language) -> bool {
        matches!(lang, Language::JavaScript | Language::TypeScript)
    }

    fn check(&self, parsed: &ParsedFile) -> Vec<Finding> {
        let mut findings = Vec::new();
        let mut cursor = parsed.tree.walk();

        // Only check actual control flow statements, NOT ternary expressions
        // Ternaries in JSX/template literals are intentional and not bugs
        find_nodes_by_kinds(
            &mut cursor,
            &[
                "if_statement",
                "while_statement",
                "do_statement",
                "for_statement",
            ],
            |node: Node| {
                if let Some(condition) = node.child_by_field_name("condition") {
                    check_assignment_in_condition(&condition, parsed, self.id(), &mut findings);
                }
            },
        );

        findings
    }
}

/// Check for assignment expressions in a condition
/// Skips intentional patterns like: if ((match = regex.exec(str)) !== null)
fn check_assignment_in_condition(
    node: &Node,
    parsed: &ParsedFile,
    rule_id: &str,
    findings: &mut Vec<Finding>,
) {
    let mut cursor = node.walk();
    loop {
        let current = cursor.node();
        if current.kind() == "assignment_expression" {
            // Skip if the assignment is part of a comparison (intentional pattern)
            // e.g., if ((x = getValue()) !== null)
            let is_intentional = is_intentional_assignment(&current, parsed);

            if !is_intentional {
                findings.push(create_finding_with_confidence(
                    rule_id,
                    &current,
                    &parsed.path,
                    &parsed.content,
                    Severity::Error,
                    "Assignment in condition - did you mean === ?",
                    Language::JavaScript,
                    Confidence::High,
                ));
            }
        }

        if cursor.goto_first_child() {
            continue;
        }
        loop {
            if cursor.goto_next_sibling() {
                break;
            }
            if !cursor.goto_parent() || cursor.node().id() == node.id() {
                return;
            }
        }
    }
}

/// Check if an assignment is intentional (wrapped in parens and compared)
fn is_intentional_assignment(node: &Node, parsed: &ParsedFile) -> bool {
    // Pattern: ((x = getValue()) !== null)
    // Check if parent is parenthesized_expression and grandparent is binary_expression with comparison
    if let Some(parent) = node.parent()
        && parent.kind() == "parenthesized_expression"
        && let Some(grandparent) = parent.parent()
        && grandparent.kind() == "binary_expression"
        && let Ok(text) = grandparent.utf8_text(parsed.content.as_bytes())
    {
        return text.contains("===")
            || text.contains("!==")
            || text.contains("== ")
            || text.contains("!= ");
    }
    false
}

/// DETECTS constant conditions
pub struct NoConstantConditionRule;

impl Rule for NoConstantConditionRule {
    fn id(&self) -> &str {
        "js/no-constant-condition"
    }

    fn description(&self) -> &str {
        "Detects constant conditions which indicate dead code or infinite loops"
    }

    fn applies_to(&self, lang: Language) -> bool {
        matches!(lang, Language::JavaScript | Language::TypeScript)
    }

    fn check(&self, parsed: &ParsedFile) -> Vec<Finding> {
        let mut findings = Vec::new();
        let mut cursor = parsed.tree.walk();

        find_nodes_by_kind(&mut cursor, "if_statement", |node: Node| {
            if let Some(condition) = node.child_by_field_name("condition")
                && is_constant_cond(&condition)
            {
                findings.push(create_finding_with_confidence(
                    self.id(),
                    &condition,
                    &parsed.path,
                    &parsed.content,
                    Severity::Warning,
                    "Constant condition - code path always/never taken",
                    Language::JavaScript,
                    Confidence::High,
                ));
            }
        });

        findings
    }
}

fn is_constant_cond(node: &Node) -> bool {
    match node.kind() {
        "true" | "false" | "number" | "null" => true,
        "parenthesized_expression" => node
            .named_child(0)
            .map(|n| is_constant_cond(&n))
            .unwrap_or(false),
        _ => false,
    }
}

/// DETECTS invalid typeof comparisons
pub struct ValidTypeofRule;

impl Rule for ValidTypeofRule {
    fn id(&self) -> &str {
        "js/valid-typeof"
    }

    fn description(&self) -> &str {
        "Detects invalid typeof comparison strings"
    }

    fn applies_to(&self, lang: Language) -> bool {
        matches!(lang, Language::JavaScript | Language::TypeScript)
    }

    fn check(&self, parsed: &ParsedFile) -> Vec<Finding> {
        let mut findings = Vec::new();
        let mut cursor = parsed.tree.walk();

        let valid_types = [
            "undefined",
            "object",
            "boolean",
            "number",
            "string",
            "function",
            "symbol",
            "bigint",
        ];

        find_nodes_by_kind(&mut cursor, "binary_expression", |node: Node| {
            // Get left and right operands
            let left = node.child_by_field_name("left");
            let right = node.child_by_field_name("right");

            // Check if this is actually a typeof comparison:
            // typeof x === "string" or "string" === typeof x
            let (typeof_side, string_side) = match (&left, &right) {
                (Some(l), Some(r)) if is_typeof_expression(l) => (Some(l), Some(r)),
                (Some(l), Some(r)) if is_typeof_expression(r) => (Some(r), Some(l)),
                _ => (None, None),
            };

            // Only proceed if we have a typeof expression on one side
            if typeof_side.is_none() {
                return;
            }

            // Check if the other side is a string literal
            if let Some(str_node) = string_side
                && str_node.kind() == "string"
                && let Ok(str_text) = str_node.utf8_text(parsed.content.as_bytes())
            {
                let inner = str_text.trim_matches(|c| c == '"' || c == '\'' || c == '`');
                if !valid_types.contains(&inner) {
                    findings.push(create_finding_with_confidence(
                        self.id(),
                        str_node,
                        &parsed.path,
                        &parsed.content,
                        Severity::Error,
                        &format!("Invalid typeof comparison: '{}' is not a valid type", inner),
                        Language::JavaScript,
                        Confidence::High,
                    ));
                }
            }
        });
        findings
    }
}

/// Check if a node is a typeof unary expression
fn is_typeof_expression(node: &Node) -> bool {
    // typeof produces a "unary_expression" in tree-sitter-javascript
    // with the operator as "typeof"
    if node.kind() == "unary_expression" {
        // Check if first child is "typeof" operator
        if let Some(first_child) = node.child(0) {
            return first_child.kind() == "typeof";
        }
    }
    false
}

/// DETECTS with statements
pub struct NoWithRule;

impl Rule for NoWithRule {
    fn id(&self) -> &str {
        "js/no-with"
    }

    fn description(&self) -> &str {
        "Detects with statements which are deprecated"
    }

    fn applies_to(&self, lang: Language) -> bool {
        matches!(lang, Language::JavaScript | Language::TypeScript)
    }

    fn check(&self, parsed: &ParsedFile) -> Vec<Finding> {
        let mut findings = Vec::new();
        let mut cursor = parsed.tree.walk();

        find_nodes_by_kind(&mut cursor, "with_statement", |node: Node| {
            findings.push(create_finding_with_confidence(
                self.id(),
                &node,
                &parsed.path,
                &parsed.content,
                Severity::Error,
                "with statement is deprecated and forbidden in strict mode",
                Language::JavaScript,
                Confidence::High,
            ));
        });
        findings
    }
}

/// DETECTS document.write
pub struct NoDocumentWriteRule;

impl Rule for NoDocumentWriteRule {
    fn id(&self) -> &str {
        "js/no-document-write"
    }

    fn description(&self) -> &str {
        "Detects document.write which can cause security and performance issues"
    }

    fn applies_to(&self, lang: Language) -> bool {
        matches!(lang, Language::JavaScript | Language::TypeScript)
    }

    fn check(&self, parsed: &ParsedFile) -> Vec<Finding> {
        let mut findings = Vec::new();
        let mut cursor = parsed.tree.walk();

        find_call_expressions(&mut cursor, |node: Node| {
            if let Some(func) = node.child_by_field_name("function")
                && let Ok(text) = func.utf8_text(parsed.content.as_bytes())
                && (text == "document.write" || text == "document.writeln")
            {
                findings.push(create_finding_with_confidence(
                    self.id(),
                    &node,
                    &parsed.path,
                    &parsed.content,
                    Severity::Warning,
                    "document.write blocks rendering - use DOM manipulation instead",
                    Language::JavaScript,
                    Confidence::High,
                ));
            }
        });
        findings
    }
}

fn find_call_expressions<F>(cursor: &mut tree_sitter::TreeCursor, mut callback: F)
where
    F: FnMut(Node),
{
    loop {
        let node = cursor.node();
        if node.kind() == "call_expression" {
            callback(node);
        }

        if cursor.goto_first_child() {
            continue;
        }

        loop {
            if cursor.goto_next_sibling() {
                break;
            }
            if !cursor.goto_parent() {
                return;
            }
        }
    }
}

fn find_member_expressions<F>(cursor: &mut tree_sitter::TreeCursor, mut callback: F)
where
    F: FnMut(Node),
{
    loop {
        let node = cursor.node();
        if node.kind() == "member_expression" {
            callback(node);
        }

        if cursor.goto_first_child() {
            continue;
        }

        loop {
            if cursor.goto_next_sibling() {
                break;
            }
            if !cursor.goto_parent() {
                return;
            }
        }
    }
}

fn find_nodes_by_kind<F>(cursor: &mut tree_sitter::TreeCursor, kind: &str, mut callback: F)
where
    F: FnMut(Node),
{
    loop {
        let node = cursor.node();
        if node.kind() == kind {
            callback(node);
        }

        if cursor.goto_first_child() {
            continue;
        }

        loop {
            if cursor.goto_next_sibling() {
                break;
            }
            if !cursor.goto_parent() {
                return;
            }
        }
    }
}

/// Find nodes matching any of the given kinds in a single tree traversal
fn find_nodes_by_kinds<F>(cursor: &mut tree_sitter::TreeCursor, kinds: &[&str], mut callback: F)
where
    F: FnMut(Node),
{
    // Use HashSet for O(1) lookups
    let kinds_set: HashSet<&str> = kinds.iter().copied().collect();

    loop {
        let node = cursor.node();
        if kinds_set.contains(node.kind()) {
            callback(node);
        }

        if cursor.goto_first_child() {
            continue;
        }

        loop {
            if cursor.goto_next_sibling() {
                break;
            }
            if !cursor.goto_parent() {
                return;
            }
        }
    }
}

// =============================================================================
// PRIORITY 3: Additional Security Rules
// =============================================================================

/// DETECTS prototype pollution vulnerabilities
///
/// Detects patterns that can lead to prototype pollution:
/// - `Object.assign({}, userInput)` - can pollute if userInput has __proto__
/// - `_.merge`, `_.extend`, `_.defaultsDeep` with user-controlled objects
/// - `obj[userInput] = value` - computed property assignment
pub struct PrototypePollutionRule;

impl Rule for PrototypePollutionRule {
    fn id(&self) -> &str {
        "js/prototype-pollution"
    }

    fn description(&self) -> &str {
        "Detects patterns that may lead to prototype pollution vulnerabilities"
    }

    fn applies_to(&self, lang: Language) -> bool {
        matches!(lang, Language::JavaScript | Language::TypeScript)
    }

    fn check(&self, parsed: &ParsedFile) -> Vec<Finding> {
        let mut findings = Vec::new();
        let mut cursor = parsed.tree.walk();

        // Dangerous merge/extend functions from lodash and similar libraries
        let dangerous_merge_functions = [
            "merge",
            "extend",
            "defaultsDeep",
            "assign",
            "deepExtend",
            "deepMerge",
        ];

        // Check for dangerous function calls
        find_call_expressions(&mut cursor, |node: Node| {
            if let Some(func) = node.child_by_field_name("function")
                && let Ok(func_text) = func.utf8_text(parsed.content.as_bytes())
            {
                // Check for Object.assign with empty object as first arg
                if func_text == "Object.assign" {
                    if let Some(args) = node.child_by_field_name("arguments")
                        && let Some(first_arg) = args.named_child(0)
                        && let Ok(first_text) = first_arg.utf8_text(parsed.content.as_bytes())
                        && (first_text == "{}" || first_text.starts_with("{ }"))
                    {
                        findings.push(create_finding_with_confidence(
                            self.id(),
                            &node,
                            &parsed.path,
                            &parsed.content,
                            Severity::Warning,
                            "Object.assign with empty target - may be vulnerable to prototype pollution if source is user-controlled",
                            Language::JavaScript,
                            Confidence::Medium,
                        ));
                    }
                }

                // Check for lodash-style merge functions: _.merge, _.extend, etc.
                if func.kind() == "member_expression" {
                    if let Some(prop) = func.child_by_field_name("property")
                        && let Ok(prop_text) = prop.utf8_text(parsed.content.as_bytes())
                        && dangerous_merge_functions.contains(&prop_text)
                    {
                        // Check if it's from a common utility library (_, lodash, etc.)
                        if let Some(obj) = func.child_by_field_name("object")
                            && let Ok(obj_text) = obj.utf8_text(parsed.content.as_bytes())
                            && (obj_text == "_"
                                || obj_text == "lodash"
                                || obj_text == "underscore"
                                || obj_text == "jQuery"
                                || obj_text == "$")
                        {
                            findings.push(create_finding_with_confidence(
                                self.id(),
                                &node,
                                &parsed.path,
                                &parsed.content,
                                Severity::Warning,
                                &format!(
                                    "{}.{}() can cause prototype pollution if merging user-controlled objects - use a safe merge or validate input",
                                    obj_text, prop_text
                                ),
                                Language::JavaScript,
                                Confidence::Medium,
                            ));
                        }
                    }
                }
            }
        });

        // Check for computed property assignment: obj[userInput] = value
        cursor = parsed.tree.walk();
        find_nodes_by_kind(&mut cursor, "subscript_expression", |node: Node| {
            // Check if this is on the left side of an assignment
            if let Some(parent) = node.parent()
                && (parent.kind() == "assignment_expression"
                    || parent.kind() == "augmented_assignment_expression")
                && let Some(left) = parent.child_by_field_name("left")
                && left.id() == node.id()
            {
                // Get the index expression
                if let Some(index) = node.child_by_field_name("index")
                    && index.kind() == "identifier"
                {
                    // It's a variable being used as a property key
                    findings.push(create_finding_with_confidence(
                        self.id(),
                        &node,
                        &parsed.path,
                        &parsed.content,
                        Severity::Warning,
                        "Computed property assignment with variable key - may allow prototype pollution if key is user-controlled (e.g., '__proto__')",
                        Language::JavaScript,
                        Confidence::Medium,
                    ));
                }
            }
        });

        findings
    }
}

/// DETECTS ReDoS (Regular Expression Denial of Service) vulnerabilities
///
/// Detects regex patterns with nested quantifiers that can cause catastrophic backtracking:
/// - `(a+)+`, `(a*)*`, `(a|a)*` - nested quantifiers
/// - `new RegExp(userInput)` - dynamic regex from user input
pub struct RedosRule;

impl RedosRule {
    /// Check if a regex pattern contains potentially vulnerable nested quantifiers
    fn has_nested_quantifiers(pattern: &str) -> bool {
        // Simple heuristic: look for patterns like (x+)+, (x*)+, (x+)*, (x*)*, (x|x)+
        // This is a simplified check - a full analysis would require regex parsing

        let quantifiers = ['+', '*', '?'];
        let mut in_group = 0;
        let mut group_has_quantifier = false;
        let chars: Vec<char> = pattern.chars().collect();

        for i in 0..chars.len() {
            let c = chars[i];
            match c {
                '(' => {
                    in_group += 1;
                    group_has_quantifier = false;
                }
                ')' => {
                    if in_group > 0 {
                        in_group -= 1;
                        // Check if followed by a quantifier
                        if i + 1 < chars.len() && quantifiers.contains(&chars[i + 1]) {
                            if group_has_quantifier {
                                return true; // Nested quantifiers!
                            }
                        }
                    }
                }
                '+' | '*' => {
                    if in_group > 0 {
                        group_has_quantifier = true;
                    }
                }
                '|' => {
                    // Check for alternation with repetition like (a|a)+
                    // This is a simplified check
                    if in_group > 0 {
                        group_has_quantifier = true;
                    }
                }
                _ => {}
            }
        }

        // Also check for common dangerous patterns
        let dangerous_patterns = [
            "(.*)*",
            "(.+)+",
            "(.*)+",
            "(.+)*",
            "(a+)+",
            "(a*)+",
            "(a+)*",
            "(a*)*",
            "([^\"]+)+",
            "(\\s*)*",
            "(\\s+)+",
            "(\\d+)+",
            "(\\w+)+",
        ];

        for dangerous in dangerous_patterns {
            if pattern.contains(dangerous) {
                return true;
            }
        }

        false
    }
}

impl Rule for RedosRule {
    fn id(&self) -> &str {
        "js/redos-vulnerable"
    }

    fn description(&self) -> &str {
        "Detects regex patterns vulnerable to ReDoS (catastrophic backtracking)"
    }

    fn applies_to(&self, lang: Language) -> bool {
        matches!(lang, Language::JavaScript | Language::TypeScript)
    }

    fn check(&self, parsed: &ParsedFile) -> Vec<Finding> {
        let mut findings = Vec::new();
        let mut cursor = parsed.tree.walk();

        // Check regex literals
        find_nodes_by_kind(&mut cursor, "regex", |node: Node| {
            if let Ok(pattern) = node.utf8_text(parsed.content.as_bytes()) {
                if Self::has_nested_quantifiers(pattern) {
                    findings.push(create_finding_with_confidence(
                        self.id(),
                        &node,
                        &parsed.path,
                        &parsed.content,
                        Severity::Warning,
                        "Regex with nested quantifiers may be vulnerable to ReDoS - consider using atomic groups or possessive quantifiers",
                        Language::JavaScript,
                        Confidence::Medium,
                    ));
                }
            }
        });

        // Check new RegExp() with variable input
        cursor = parsed.tree.walk();
        find_nodes_by_kind(&mut cursor, "new_expression", |node: Node| {
            if let Some(constructor) = node.child_by_field_name("constructor")
                && let Ok(ctor_text) = constructor.utf8_text(parsed.content.as_bytes())
                && ctor_text == "RegExp"
            {
                if let Some(args) = node.child_by_field_name("arguments")
                    && let Some(first_arg) = args.named_child(0)
                {
                    match first_arg.kind() {
                        "identifier" | "member_expression" | "call_expression" => {
                            // Variable or function call used as regex pattern
                            findings.push(create_finding_with_confidence(
                                self.id(),
                                &node,
                                &parsed.path,
                                &parsed.content,
                                Severity::Warning,
                                "new RegExp() with dynamic input may be vulnerable to ReDoS if pattern is user-controlled - validate and escape input",
                                Language::JavaScript,
                                Confidence::Medium,
                            ));
                        }
                        "string" | "template_string" => {
                            // Check the string pattern itself
                            if let Ok(pattern) = first_arg.utf8_text(parsed.content.as_bytes()) {
                                if Self::has_nested_quantifiers(pattern) {
                                    findings.push(create_finding_with_confidence(
                                        self.id(),
                                        &node,
                                        &parsed.path,
                                        &parsed.content,
                                        Severity::Warning,
                                        "RegExp with nested quantifiers may be vulnerable to ReDoS",
                                        Language::JavaScript,
                                        Confidence::Medium,
                                    ));
                                }
                            }
                        }
                        _ => {}
                    }
                }
            }
        });

        findings
    }
}

/// DETECTS missing security headers in Express apps
///
/// Detects Express apps that may be missing security headers:
/// - No `helmet()` middleware
/// - Missing common security middleware
pub struct MissingSecurityHeadersRule;

impl MissingSecurityHeadersRule {
    /// Check if the file imports or requires helmet
    fn has_helmet_import(parsed: &ParsedFile) -> bool {
        let content = &parsed.content;
        content.contains("require('helmet')")
            || content.contains("require(\"helmet\")")
            || content.contains("from 'helmet'")
            || content.contains("from \"helmet\"")
    }

    /// Check if helmet() is called in the file
    fn has_helmet_usage(parsed: &ParsedFile) -> bool {
        let content = &parsed.content;
        content.contains("helmet()")
            || content.contains("helmet.contentSecurityPolicy")
            || content.contains("helmet.hsts")
    }
}

impl Rule for MissingSecurityHeadersRule {
    fn id(&self) -> &str {
        "js/missing-security-headers"
    }

    fn description(&self) -> &str {
        "Detects Express apps that may be missing security headers (helmet middleware)"
    }

    fn applies_to(&self, lang: Language) -> bool {
        matches!(lang, Language::JavaScript | Language::TypeScript)
    }

    fn check(&self, parsed: &ParsedFile) -> Vec<Finding> {
        let mut findings = Vec::new();
        let mut cursor = parsed.tree.walk();

        // First, check if this looks like an Express app
        let content = &parsed.content;
        let is_express_app = content.contains("express()")
            || content.contains("require('express')")
            || content.contains("require(\"express\")")
            || content.contains("from 'express'")
            || content.contains("from \"express\"");

        if !is_express_app {
            return findings;
        }

        // Check if helmet is imported and used
        let has_helmet = Self::has_helmet_import(parsed) && Self::has_helmet_usage(parsed);

        if !has_helmet {
            // Find the express() call to report the finding
            find_call_expressions(&mut cursor, |node: Node| {
                if let Some(func) = node.child_by_field_name("function")
                    && let Ok(func_text) = func.utf8_text(parsed.content.as_bytes())
                    && func_text == "express"
                {
                    findings.push(create_finding_with_confidence(
                        self.id(),
                        &node,
                        &parsed.path,
                        &parsed.content,
                        Severity::Info,
                        "Express app without helmet() middleware - consider adding helmet for security headers (CSP, HSTS, X-Frame-Options, etc.)",
                        Language::JavaScript,
                        Confidence::Low,
                    ));
                }
            });
        }

        findings
    }
}

/// DETECTS Express-specific security issues
///
/// Detects common Express security misconfigurations:
/// - `express.json()` without size limits
/// - `cors()` with `origin: '*'` (overly permissive)
/// - Auth routes without rate limiting
pub struct ExpressSecurityRule;

impl ExpressSecurityRule {
    /// Common auth route patterns
    const AUTH_ROUTES: &'static [&'static str] = &[
        "/login",
        "/signin",
        "/auth",
        "/register",
        "/signup",
        "/password",
        "/reset",
        "/forgot",
        "/api/auth",
        "/api/login",
    ];

    /// Check if a string looks like an auth route
    fn is_auth_route(route: &str) -> bool {
        let route_lower = route.to_lowercase();
        Self::AUTH_ROUTES
            .iter()
            .any(|auth| route_lower.contains(auth))
    }
}

impl Rule for ExpressSecurityRule {
    fn id(&self) -> &str {
        "js/express-security"
    }

    fn description(&self) -> &str {
        "Detects Express-specific security issues (body parser limits, CORS, rate limiting)"
    }

    fn applies_to(&self, lang: Language) -> bool {
        matches!(lang, Language::JavaScript | Language::TypeScript)
    }

    fn check(&self, parsed: &ParsedFile) -> Vec<Finding> {
        let mut findings = Vec::new();
        let mut cursor = parsed.tree.walk();

        let content = &parsed.content;

        // Check if this is an Express file
        let is_express_file = content.contains("express")
            || content.contains("app.use")
            || content.contains("app.get")
            || content.contains("app.post")
            || content.contains("router.");

        if !is_express_file {
            return findings;
        }

        // Track if rate limiting is present
        let has_rate_limiter = content.contains("rateLimit")
            || content.contains("rate-limit")
            || content.contains("express-rate-limit")
            || content.contains("express-slow-down")
            || content.contains("rateLimiter");

        find_call_expressions(&mut cursor, |node: Node| {
            if let Some(func) = node.child_by_field_name("function")
                && let Ok(func_text) = func.utf8_text(parsed.content.as_bytes())
            {
                // Check for express.json() without limit
                if func_text == "express.json" || func_text == "bodyParser.json" {
                    let mut has_limit = false;
                    if let Some(args) = node.child_by_field_name("arguments")
                        && let Some(options) = args.named_child(0)
                        && let Ok(options_text) = options.utf8_text(parsed.content.as_bytes())
                    {
                        has_limit = options_text.contains("limit");
                    }

                    if !has_limit {
                        findings.push(create_finding_with_confidence(
                            self.id(),
                            &node,
                            &parsed.path,
                            &parsed.content,
                            Severity::Warning,
                            "express.json() without size limit - add { limit: '100kb' } to prevent large payload attacks",
                            Language::JavaScript,
                            Confidence::Medium,
                        ));
                    }
                }

                // Check for express.urlencoded() without limit
                if func_text == "express.urlencoded" || func_text == "bodyParser.urlencoded" {
                    let mut has_limit = false;
                    if let Some(args) = node.child_by_field_name("arguments")
                        && let Some(options) = args.named_child(0)
                        && let Ok(options_text) = options.utf8_text(parsed.content.as_bytes())
                    {
                        has_limit = options_text.contains("limit");
                    }

                    if !has_limit {
                        findings.push(create_finding_with_confidence(
                            self.id(),
                            &node,
                            &parsed.path,
                            &parsed.content,
                            Severity::Warning,
                            "express.urlencoded() without size limit - add { limit: '100kb' } to prevent large payload attacks",
                            Language::JavaScript,
                            Confidence::Medium,
                        ));
                    }
                }

                // Check for cors() with origin: '*'
                if func_text == "cors" {
                    if let Some(args) = node.child_by_field_name("arguments")
                        && let Some(options) = args.named_child(0)
                        && let Ok(options_text) = options.utf8_text(parsed.content.as_bytes())
                    {
                        if options_text.contains("origin: '*'")
                            || options_text.contains("origin: \"*\"")
                            || options_text.contains("origin:'*'")
                            || options_text.contains("origin:\"*\"")
                        {
                            findings.push(create_finding_with_confidence(
                                self.id(),
                                &node,
                                &parsed.path,
                                &parsed.content,
                                Severity::Warning,
                                "CORS with origin: '*' allows any domain - specify allowed origins for production",
                                Language::JavaScript,
                                Confidence::Medium,
                            ));
                        }
                    }
                }

                // Check for auth routes without rate limiting
                if !has_rate_limiter {
                    // Check app.post('/login', ...) style routes
                    if func_text == "app.post"
                        || func_text == "router.post"
                        || func_text == "app.put"
                        || func_text == "router.put"
                    {
                        if let Some(args) = node.child_by_field_name("arguments")
                            && let Some(route_arg) = args.named_child(0)
                            && let Ok(route) = route_arg.utf8_text(parsed.content.as_bytes())
                            && Self::is_auth_route(route)
                        {
                            findings.push(create_finding_with_confidence(
                                self.id(),
                                &node,
                                &parsed.path,
                                &parsed.content,
                                Severity::Warning,
                                &format!(
                                    "Auth route {} without rate limiting - add express-rate-limit to prevent brute force attacks",
                                    route
                                ),
                                Language::JavaScript,
                                Confidence::Medium,
                            ));
                        }
                    }
                }
            }
        });

        findings
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::rules::Rule;
    use rma_common::RmaConfig;
    use rma_parser::ParserEngine;
    use std::path::Path;

    fn parse_js(content: &str) -> ParsedFile {
        let config = RmaConfig::default();
        let parser = ParserEngine::new(config);
        parser.parse_file(Path::new("test.js"), content).unwrap()
    }

    #[test]
    fn test_timer_arrow_function_not_flagged() {
        // setTimeout(() => foo(), 100) should NOT be flagged
        let content = r#"setTimeout(() => foo(), 100);"#;
        let parsed = parse_js(content);
        let rule = TimerStringRule;
        let findings = rule.check(&parsed);
        assert!(findings.is_empty(), "Arrow function should not be flagged");
    }

    #[test]
    fn test_timer_function_reference_not_flagged() {
        // setTimeout(foo, 100) should NOT be flagged
        let content = r#"setTimeout(foo, 100);"#;
        let parsed = parse_js(content);
        let rule = TimerStringRule;
        let findings = rule.check(&parsed);
        assert!(
            findings.is_empty(),
            "Function reference should not be flagged"
        );
    }

    #[test]
    fn test_timer_string_literal_flagged() {
        // setTimeout("foo()", 100) SHOULD be flagged
        let content = r#"setTimeout("foo()", 100);"#;
        let parsed = parse_js(content);
        let rule = TimerStringRule;
        let findings = rule.check(&parsed);
        assert_eq!(findings.len(), 1, "String literal should be flagged");
        assert!(findings[0].message.contains("String passed to setTimeout"));
        assert_eq!(findings[0].severity, Severity::Warning);
    }

    #[test]
    fn test_setinterval_string_flagged() {
        // setInterval("alert(1)", 100) SHOULD be flagged
        let content = r#"setInterval("alert(1)", 100);"#;
        let parsed = parse_js(content);
        let rule = TimerStringRule;
        let findings = rule.check(&parsed);
        assert_eq!(
            findings.len(),
            1,
            "setInterval with string should be flagged"
        );
        assert!(findings[0].message.contains("String passed to setInterval"));
    }

    #[test]
    fn test_timer_template_literal_flagged() {
        // setTimeout(`foo()`, 100) SHOULD be flagged
        let content = "setTimeout(`foo()`, 100);";
        let parsed = parse_js(content);
        let rule = TimerStringRule;
        let findings = rule.check(&parsed);
        assert_eq!(findings.len(), 1, "Template literal should be flagged");
    }

    #[test]
    fn test_timer_function_expression_not_flagged() {
        // setTimeout(function() { foo(); }, 100) should NOT be flagged
        let content = r#"setTimeout(function() { foo(); }, 100);"#;
        let parsed = parse_js(content);
        let rule = TimerStringRule;
        let findings = rule.check(&parsed);
        assert!(
            findings.is_empty(),
            "Function expression should not be flagged"
        );
    }

    // =========================================================================
    // innerHTML WRITE vs READ tests
    // =========================================================================

    #[test]
    fn test_innerhtml_write_flagged_as_xss() {
        // el.innerHTML = x SHOULD be flagged as XSS sink (Error severity)
        let content = r#"document.getElementById("foo").innerHTML = userInput;"#;
        let parsed = parse_js(content);
        let rule = InnerHtmlRule;
        let findings = rule.check(&parsed);
        assert_eq!(findings.len(), 1, "innerHTML assignment should be flagged");
        assert_eq!(findings[0].rule_id, "js/innerhtml-xss");
        assert_eq!(findings[0].severity, Severity::Error);
        assert!(findings[0].message.contains("assignment"));
    }

    #[test]
    fn test_innerhtml_augmented_assignment_flagged() {
        // el.innerHTML += x SHOULD be flagged as XSS sink
        let content = r#"el.innerHTML += "<div>more</div>";"#;
        let parsed = parse_js(content);
        let rule = InnerHtmlRule;
        let findings = rule.check(&parsed);
        assert_eq!(
            findings.len(),
            1,
            "innerHTML augmented assignment should be flagged"
        );
        assert_eq!(findings[0].severity, Severity::Error);
    }

    #[test]
    fn test_innerhtml_read_not_flagged_by_xss_rule() {
        // const x = el.innerHTML should NOT be flagged by the XSS rule
        let content = r#"const content = document.body.innerHTML;"#;
        let parsed = parse_js(content);
        let rule = InnerHtmlRule;
        let findings = rule.check(&parsed);
        assert!(
            findings.is_empty(),
            "innerHTML read should not be flagged by XSS rule"
        );
    }

    #[test]
    fn test_innerhtml_read_flagged_by_read_rule() {
        // const x = el.innerHTML SHOULD be flagged by the read rule (Info severity)
        let content = r#"const content = document.body.innerHTML;"#;
        let parsed = parse_js(content);
        let rule = InnerHtmlReadRule;
        let findings = rule.check(&parsed);
        assert_eq!(
            findings.len(),
            1,
            "innerHTML read should be flagged by read rule"
        );
        assert_eq!(findings[0].rule_id, "js/innerhtml-read");
        assert_eq!(findings[0].severity, Severity::Info);
    }

    #[test]
    fn test_innerhtml_write_not_flagged_by_read_rule() {
        // el.innerHTML = x should NOT be flagged by the read rule
        let content = r#"el.innerHTML = "<div>test</div>";"#;
        let parsed = parse_js(content);
        let rule = InnerHtmlReadRule;
        let findings = rule.check(&parsed);
        assert!(
            findings.is_empty(),
            "innerHTML write should not be flagged by read rule"
        );
    }

    #[test]
    fn test_outerhtml_write_flagged() {
        // el.outerHTML = x SHOULD be flagged as XSS sink
        let content = r#"el.outerHTML = template;"#;
        let parsed = parse_js(content);
        let rule = InnerHtmlRule;
        let findings = rule.check(&parsed);
        assert_eq!(findings.len(), 1, "outerHTML assignment should be flagged");
        assert!(findings[0].message.contains("outerHTML"));
    }

    #[test]
    fn test_innerhtml_in_function_argument_is_read() {
        // sanitize(el.innerHTML) is a READ, not a write
        let content = r#"const safe = sanitize(el.innerHTML);"#;
        let parsed = parse_js(content);

        let xss_rule = InnerHtmlRule;
        let xss_findings = xss_rule.check(&parsed);
        assert!(
            xss_findings.is_empty(),
            "Function arg should not be XSS sink"
        );

        let read_rule = InnerHtmlReadRule;
        let read_findings = read_rule.check(&parsed);
        assert_eq!(
            read_findings.len(),
            1,
            "Function arg should be flagged as read"
        );
    }

    // =========================================================================
    // New rules tests
    // =========================================================================

    #[test]
    fn test_jsx_script_url_flagged() {
        let content = r#"<a href="javascript:void(0)">Click</a>"#;
        let parsed = parse_js(content);
        let rule = JsxScriptUrlRule;
        let findings = rule.check(&parsed);
        assert_eq!(findings.len(), 1, "javascript: URL should be flagged");
        assert_eq!(findings[0].severity, Severity::Critical);
    }

    #[test]
    fn test_debugger_flagged() {
        let content = "function test() { debugger; return 1; }";
        let parsed = parse_js(content);
        let rule = DebuggerStatementRule;
        let findings = rule.check(&parsed);
        assert_eq!(findings.len(), 1, "debugger should be flagged");
        assert_eq!(findings[0].severity, Severity::Warning);
    }

    #[test]
    fn test_alert_flagged() {
        let content = r#"alert("Hello!");"#;
        let parsed = parse_js(content);
        let rule = NoAlertRule;
        let findings = rule.check(&parsed);
        assert_eq!(findings.len(), 1, "alert should be flagged");
    }

    #[test]
    fn test_strict_equality_loose_flagged() {
        let content = "if (x == 5) { foo(); }";
        let parsed = parse_js(content);
        let rule = StrictEqualityRule;
        let findings = rule.check(&parsed);
        assert_eq!(findings.len(), 1, "== should be flagged");
        assert!(findings[0].message.contains("==="));
    }

    #[test]
    fn test_strict_equality_null_check_allowed() {
        let content = "if (x == null) { return; }";
        let parsed = parse_js(content);
        let rule = StrictEqualityRule;
        let findings = rule.check(&parsed);
        assert!(findings.is_empty(), "== null should not be flagged");
    }

    #[test]
    fn test_condition_assignment_flagged() {
        let content = "if (x = 5) { foo(); }";
        let parsed = parse_js(content);
        let rule = NoConditionAssignRule;
        let findings = rule.check(&parsed);
        assert_eq!(
            findings.len(),
            1,
            "Assignment in condition should be flagged"
        );
        assert_eq!(findings[0].severity, Severity::Error);
    }

    #[test]
    fn test_condition_assignment_intentional_not_flagged() {
        // Intentional pattern: assignment in parens compared to null
        let content = "while ((match = regex.exec(str)) !== null) { process(match); }";
        let parsed = parse_js(content);
        let rule = NoConditionAssignRule;
        let findings = rule.check(&parsed);
        assert!(
            findings.is_empty(),
            "Intentional assignment pattern should not be flagged"
        );
    }

    #[test]
    fn test_ternary_in_jsx_not_flagged() {
        // Ternary expressions in JSX/template literals are intentional, not bugs
        let content = r#"const el = <div className={`px-2 ${isActive ? "active" : ""}`} />;"#;
        let parsed = parse_js(content);
        let rule = NoConditionAssignRule;
        let findings = rule.check(&parsed);
        assert!(findings.is_empty(), "Ternary in JSX should not be flagged");
    }

    #[test]
    fn test_constant_condition_flagged() {
        let content = "if (true) { foo(); }";
        let parsed = parse_js(content);
        let rule = NoConstantConditionRule;
        let findings = rule.check(&parsed);
        assert_eq!(findings.len(), 1, "Constant condition should be flagged");
    }

    #[test]
    fn test_valid_typeof_invalid_flagged() {
        let content = r#"if (typeof x === "strng") { }"#;
        let parsed = parse_js(content);
        let rule = ValidTypeofRule;
        let findings = rule.check(&parsed);
        assert_eq!(findings.len(), 1, "Invalid typeof string should be flagged");
    }

    #[test]
    fn test_valid_typeof_valid_ok() {
        let content = r#"if (typeof x === "string") { }"#;
        let parsed = parse_js(content);
        let rule = ValidTypeofRule;
        let findings = rule.check(&parsed);
        assert!(findings.is_empty(), "Valid typeof should not be flagged");
    }

    #[test]
    fn test_valid_typeof_jsx_classname_not_flagged() {
        // JSX className strings should NOT be flagged as invalid typeof comparisons
        // This was a false positive: className="h-3 w-3" was incorrectly flagged
        let content = r#"<X className="h-3 w-3" />"#;
        let parsed = parse_js(content);
        let rule = ValidTypeofRule;
        let findings = rule.check(&parsed);
        assert!(
            findings.is_empty(),
            "JSX className should not be flagged as typeof comparison"
        );
    }

    #[test]
    fn test_valid_typeof_jsx_with_ternary_not_flagged() {
        // JSX with ternary and typeof elsewhere should not false-positive on className
        let content = r#"
            function Component({ activeTab }) {
                return (
                    <div className="border-b px-2">
                        <Tabs value={activeTab} onValueChange={(v) => {
                            setActiveTab(v as typeof activeTab);
                        }}>
                            <TabsList className="h-9 bg-transparent p-0" />
                        </Tabs>
                    </div>
                );
            }
        "#;
        let parsed = parse_js(content);
        let rule = ValidTypeofRule;
        let findings = rule.check(&parsed);
        // Should not flag className strings as invalid typeof comparisons
        let false_positives: Vec<_> = findings
            .iter()
            .filter(|f| {
                f.message.contains("border-b")
                    || f.message.contains("h-9")
                    || f.message.contains("h-3")
            })
            .collect();
        assert!(
            false_positives.is_empty(),
            "Should not flag className strings: {:?}",
            false_positives
        );
    }

    // =========================================================================
    // Prototype Pollution tests
    // =========================================================================

    #[test]
    fn test_prototype_pollution_object_assign_empty_target() {
        let content = r#"const merged = Object.assign({}, userInput);"#;
        let parsed = parse_js(content);
        let rule = PrototypePollutionRule;
        let findings = rule.check(&parsed);
        assert_eq!(
            findings.len(),
            1,
            "Object.assign with empty target should be flagged"
        );
        assert!(findings[0].message.contains("prototype pollution"));
        assert_eq!(findings[0].severity, Severity::Warning);
    }

    #[test]
    fn test_prototype_pollution_object_assign_existing_target_ok() {
        let content = r#"const merged = Object.assign(existingObj, userInput);"#;
        let parsed = parse_js(content);
        let rule = PrototypePollutionRule;
        let findings = rule.check(&parsed);
        assert!(
            findings.is_empty(),
            "Object.assign with existing target should not be flagged"
        );
    }

    #[test]
    fn test_prototype_pollution_lodash_merge() {
        let content = r#"const merged = _.merge(target, userInput);"#;
        let parsed = parse_js(content);
        let rule = PrototypePollutionRule;
        let findings = rule.check(&parsed);
        assert_eq!(findings.len(), 1, "_.merge should be flagged");
        assert!(findings[0].message.contains("prototype pollution"));
    }

    #[test]
    fn test_prototype_pollution_lodash_extend() {
        let content = r#"lodash.extend(config, options);"#;
        let parsed = parse_js(content);
        let rule = PrototypePollutionRule;
        let findings = rule.check(&parsed);
        assert_eq!(findings.len(), 1, "lodash.extend should be flagged");
    }

    #[test]
    fn test_prototype_pollution_computed_property_assignment() {
        let content = r#"obj[key] = value;"#;
        let parsed = parse_js(content);
        let rule = PrototypePollutionRule;
        let findings = rule.check(&parsed);
        assert_eq!(
            findings.len(),
            1,
            "Computed property assignment should be flagged"
        );
        assert!(findings[0].message.contains("Computed property assignment"));
    }

    #[test]
    fn test_prototype_pollution_static_property_ok() {
        let content = r#"obj.name = value;"#;
        let parsed = parse_js(content);
        let rule = PrototypePollutionRule;
        let findings = rule.check(&parsed);
        assert!(
            findings.is_empty(),
            "Static property assignment should not be flagged"
        );
    }

    // =========================================================================
    // ReDoS tests
    // =========================================================================

    #[test]
    fn test_redos_nested_quantifier_literal() {
        let content = r#"const re = /(a+)+$/;"#;
        let parsed = parse_js(content);
        let rule = RedosRule;
        let findings = rule.check(&parsed);
        assert_eq!(
            findings.len(),
            1,
            "Nested quantifier regex should be flagged"
        );
        assert!(findings[0].message.contains("ReDoS"));
    }

    #[test]
    fn test_redos_star_plus_pattern() {
        let content = r#"const re = /(.+)+/;"#;
        let parsed = parse_js(content);
        let rule = RedosRule;
        let findings = rule.check(&parsed);
        assert_eq!(
            findings.len(),
            1,
            "(.+)+ pattern should be flagged as ReDoS vulnerable"
        );
    }

    #[test]
    fn test_redos_new_regexp_variable() {
        let content = r#"const re = new RegExp(userPattern);"#;
        let parsed = parse_js(content);
        let rule = RedosRule;
        let findings = rule.check(&parsed);
        assert_eq!(
            findings.len(),
            1,
            "new RegExp with variable should be flagged"
        );
        assert!(findings[0].message.contains("dynamic input"));
    }

    #[test]
    fn test_redos_new_regexp_dangerous_string() {
        let content = r#"const re = new RegExp("(a+)+");"#;
        let parsed = parse_js(content);
        let rule = RedosRule;
        let findings = rule.check(&parsed);
        assert_eq!(
            findings.len(),
            1,
            "new RegExp with dangerous string should be flagged"
        );
    }

    #[test]
    fn test_redos_safe_regex_ok() {
        let content = r#"const re = /^[a-z]+$/;"#;
        let parsed = parse_js(content);
        let rule = RedosRule;
        let findings = rule.check(&parsed);
        assert!(findings.is_empty(), "Safe regex should not be flagged");
    }

    // =========================================================================
    // Missing Security Headers tests
    // =========================================================================

    #[test]
    fn test_missing_csp_express_without_helmet() {
        let content = r#"
            const express = require('express');
            const app = express();
            app.get('/', (req, res) => res.send('Hello'));
        "#;
        let parsed = parse_js(content);
        let rule = MissingSecurityHeadersRule;
        let findings = rule.check(&parsed);
        assert_eq!(
            findings.len(),
            1,
            "Express app without helmet should be flagged"
        );
        assert!(findings[0].message.contains("helmet"));
        assert_eq!(findings[0].severity, Severity::Info);
    }

    #[test]
    fn test_missing_csp_express_with_helmet_ok() {
        let content = r#"
            const express = require('express');
            const helmet = require('helmet');
            const app = express();
            app.use(helmet());
            app.get('/', (req, res) => res.send('Hello'));
        "#;
        let parsed = parse_js(content);
        let rule = MissingSecurityHeadersRule;
        let findings = rule.check(&parsed);
        assert!(
            findings.is_empty(),
            "Express app with helmet should not be flagged"
        );
    }

    #[test]
    fn test_missing_csp_non_express_ok() {
        let content = r#"
            const http = require('http');
            http.createServer((req, res) => res.end('Hello'));
        "#;
        let parsed = parse_js(content);
        let rule = MissingSecurityHeadersRule;
        let findings = rule.check(&parsed);
        assert!(
            findings.is_empty(),
            "Non-Express app should not be flagged by this rule"
        );
    }

    // =========================================================================
    // Express Security tests
    // =========================================================================

    #[test]
    fn test_express_json_without_limit() {
        let content = r#"
            const app = express();
            app.use(express.json());
        "#;
        let parsed = parse_js(content);
        let rule = ExpressSecurityRule;
        let findings = rule.check(&parsed);
        assert_eq!(
            findings.len(),
            1,
            "express.json() without limit should be flagged"
        );
        assert!(findings[0].message.contains("limit"));
    }

    #[test]
    fn test_express_json_with_limit_ok() {
        let content = r#"
            const app = express();
            app.use(express.json({ limit: '100kb' }));
        "#;
        let parsed = parse_js(content);
        let rule = ExpressSecurityRule;
        let findings = rule.check(&parsed);
        let json_findings: Vec<_> = findings
            .iter()
            .filter(|f| f.message.contains("express.json"))
            .collect();
        assert!(
            json_findings.is_empty(),
            "express.json() with limit should not be flagged"
        );
    }

    #[test]
    fn test_express_cors_wildcard_origin() {
        let content = r#"
            const app = express();
            app.use(cors({ origin: '*' }));
        "#;
        let parsed = parse_js(content);
        let rule = ExpressSecurityRule;
        let findings = rule.check(&parsed);
        let cors_findings: Vec<_> = findings
            .iter()
            .filter(|f| f.message.contains("CORS"))
            .collect();
        assert_eq!(
            cors_findings.len(),
            1,
            "cors with origin: '*' should be flagged"
        );
    }

    #[test]
    fn test_express_cors_specific_origin_ok() {
        let content = r#"
            const app = express();
            app.use(cors({ origin: 'https://example.com' }));
        "#;
        let parsed = parse_js(content);
        let rule = ExpressSecurityRule;
        let findings = rule.check(&parsed);
        let cors_findings: Vec<_> = findings
            .iter()
            .filter(|f| f.message.contains("CORS"))
            .collect();
        assert!(
            cors_findings.is_empty(),
            "cors with specific origin should not be flagged"
        );
    }

    #[test]
    fn test_express_auth_route_without_rate_limit() {
        let content = r#"
            const app = express();
            app.post('/login', (req, res) => { /* ... */ });
        "#;
        let parsed = parse_js(content);
        let rule = ExpressSecurityRule;
        let findings = rule.check(&parsed);
        let auth_findings: Vec<_> = findings
            .iter()
            .filter(|f| f.message.contains("rate limit"))
            .collect();
        assert_eq!(
            auth_findings.len(),
            1,
            "Auth route without rate limiting should be flagged"
        );
    }

    #[test]
    fn test_express_auth_route_with_rate_limit_ok() {
        let content = r#"
            const rateLimit = require('express-rate-limit');
            const limiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 100 });
            const app = express();
            app.use(limiter);
            app.post('/login', (req, res) => { /* ... */ });
        "#;
        let parsed = parse_js(content);
        let rule = ExpressSecurityRule;
        let findings = rule.check(&parsed);
        let auth_findings: Vec<_> = findings
            .iter()
            .filter(|f| f.message.contains("rate limit"))
            .collect();
        assert!(
            auth_findings.is_empty(),
            "Auth route with rate limiting should not be flagged"
        );
    }

    #[test]
    fn test_express_router_auth_route() {
        let content = r#"
            const router = express.Router();
            router.post('/api/auth/login', authController.login);
        "#;
        let parsed = parse_js(content);
        let rule = ExpressSecurityRule;
        let findings = rule.check(&parsed);
        let auth_findings: Vec<_> = findings
            .iter()
            .filter(|f| f.message.contains("rate limit"))
            .collect();
        assert_eq!(
            auth_findings.len(),
            1,
            "Router auth route without rate limiting should be flagged"
        );
    }

    // =========================================================================
    // Additional ReDoS tests (Phase 5 coverage)
    // =========================================================================

    #[test]
    fn test_redos_alternation_in_group_flagged() {
        // Alternation with overlapping patterns in a group
        let content = r#"const re = /^(a|a)+$/;"#;
        let parsed = parse_js(content);
        let rule = RedosRule;
        let findings = rule.check(&parsed);
        assert_eq!(
            findings.len(),
            1,
            "Overlapping alternation should be flagged"
        );
    }

    #[test]
    fn test_redos_star_star_pattern_flagged() {
        let content = r#"const re = /(.*)*$/;"#;
        let parsed = parse_js(content);
        let rule = RedosRule;
        let findings = rule.check(&parsed);
        assert_eq!(
            findings.len(),
            1,
            "(.*)*$ pattern should be flagged as ReDoS"
        );
    }

    #[test]
    fn test_redos_simple_character_class_ok() {
        // Simple non-nested regex should not be flagged
        let content = r#"const re = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9.-]+$/;"#;
        let parsed = parse_js(content);
        let rule = RedosRule;
        let findings = rule.check(&parsed);
        assert!(
            findings.is_empty(),
            "Simple character class regex should not be flagged"
        );
    }

    #[test]
    fn test_redos_fixed_quantifier_ok() {
        // Fixed quantifiers are not vulnerable
        let content = r#"const re = /^[a-z]{3,10}$/;"#;
        let parsed = parse_js(content);
        let rule = RedosRule;
        let findings = rule.check(&parsed);
        assert!(
            findings.is_empty(),
            "Fixed quantifier regex should not be flagged"
        );
    }

    #[test]
    fn test_redos_word_boundary_ok() {
        // Word boundary patterns are typically safe
        let content = r#"const re = /\b\w+\b/g;"#;
        let parsed = parse_js(content);
        let rule = RedosRule;
        let findings = rule.check(&parsed);
        assert!(
            findings.is_empty(),
            "Word boundary regex should not be flagged"
        );
    }

    // =========================================================================
    // Additional Missing Security Headers tests (Phase 5 coverage)
    // =========================================================================

    #[test]
    fn test_missing_headers_fastify_without_helmet() {
        let content = r#"
            const fastify = require('fastify')();
            fastify.get('/', async (request, reply) => 'Hello');
        "#;
        let parsed = parse_js(content);
        let rule = MissingSecurityHeadersRule;
        let findings = rule.check(&parsed);
        // Note: This rule currently focuses on Express, so fastify may not trigger
        // Adding this test to verify the boundary case
        assert!(
            findings.is_empty() || findings[0].message.contains("security headers"),
            "Non-Express framework should handle gracefully"
        );
    }

    #[test]
    fn test_missing_headers_express_import_style() {
        let content = r#"
            import express from 'express';
            const app = express();
            app.get('/api', (req, res) => res.json({ status: 'ok' }));
        "#;
        let parsed = parse_js(content);
        let rule = MissingSecurityHeadersRule;
        let findings = rule.check(&parsed);
        assert_eq!(
            findings.len(),
            1,
            "ES module import Express without helmet should be flagged"
        );
    }

    #[test]
    fn test_missing_headers_express_with_manual_csp() {
        let content = r#"
            const express = require('express');
            const app = express();
            app.use((req, res, next) => {
                res.setHeader('Content-Security-Policy', "default-src 'self'");
                next();
            });
            app.get('/', (req, res) => res.send('Hello'));
        "#;
        let parsed = parse_js(content);
        let rule = MissingSecurityHeadersRule;
        let findings = rule.check(&parsed);
        // This still may flag because we specifically look for helmet
        // But it's a valid pattern to document
        assert!(
            findings.len() <= 1,
            "Manual CSP header setting is an alternative to helmet"
        );
    }

    // =========================================================================
    // Additional Prototype Pollution tests (Phase 5 coverage)
    // =========================================================================

    #[test]
    fn test_prototype_pollution_deep_merge_function() {
        // Deep merge functions are risky for prototype pollution
        let content = r#"function deepMerge(target, source) { return _.merge(target, source); }"#;
        let parsed = parse_js(content);
        let rule = PrototypePollutionRule;
        let findings = rule.check(&parsed);
        assert_eq!(
            findings.len(),
            1,
            "_.merge in deep merge function should be flagged"
        );
    }

    #[test]
    fn test_prototype_pollution_jquery_extend_deep() {
        // Deep extend with first arg true is dangerous
        let content = r#"jQuery.extend(true, target, userInput);"#;
        let parsed = parse_js(content);
        let rule = PrototypePollutionRule;
        let findings = rule.check(&parsed);
        assert_eq!(findings.len(), 1, "jQuery.extend deep should be flagged");
    }

    #[test]
    fn test_prototype_pollution_safe_object_create_ok() {
        // Object.create(null) creates prototype-less object
        let content = r#"const obj = Object.create(null);"#;
        let parsed = parse_js(content);
        let rule = PrototypePollutionRule;
        let findings = rule.check(&parsed);
        assert!(
            findings.is_empty(),
            "Object.create(null) should not be flagged"
        );
    }

    // =========================================================================
    // Additional Express Security tests (Phase 5 coverage)
    // =========================================================================

    #[test]
    fn test_express_urlencoded_without_limit() {
        let content = r#"
            const app = express();
            app.use(express.urlencoded({ extended: true }));
        "#;
        let parsed = parse_js(content);
        let rule = ExpressSecurityRule;
        let findings = rule.check(&parsed);
        let body_findings: Vec<_> = findings
            .iter()
            .filter(|f| f.message.contains("limit") || f.message.contains("body"))
            .collect();
        assert!(
            !body_findings.is_empty(),
            "express.urlencoded without limit should be flagged"
        );
    }

    #[test]
    fn test_express_body_parser_with_limit_ok() {
        let content = r#"
            const bodyParser = require('body-parser');
            const app = express();
            app.use(bodyParser.json({ limit: '1mb' }));
        "#;
        let parsed = parse_js(content);
        let rule = ExpressSecurityRule;
        let findings = rule.check(&parsed);
        let body_findings: Vec<_> = findings
            .iter()
            .filter(|f| f.message.contains("body-parser") && f.message.contains("limit"))
            .collect();
        assert!(
            body_findings.is_empty(),
            "body-parser with limit should not be flagged"
        );
    }

    #[test]
    fn test_express_signup_route_without_rate_limit() {
        let content = r#"
            const app = express();
            app.post('/signup', (req, res) => { /* create user */ });
        "#;
        let parsed = parse_js(content);
        let rule = ExpressSecurityRule;
        let findings = rule.check(&parsed);
        let auth_findings: Vec<_> = findings
            .iter()
            .filter(|f| f.message.contains("rate limit"))
            .collect();
        assert_eq!(
            auth_findings.len(),
            1,
            "Signup route without rate limiting should be flagged"
        );
    }
}