foxguard 0.3.2

Security scanner as fast as a linter. 118 built-in rules, 10 languages, sub-second scans.
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
use crate::rules::Rule;
use crate::{Finding, Language, Severity};
#[allow(unused_imports)]
use regex::Regex;

// ─── Helpers ──────────────────────────────────────────────────────────────────

fn get_source_line(source: &str, byte_offset: usize) -> String {
    let start = source[..byte_offset].rfind('\n').map_or(0, |p| p + 1);
    let end = source[byte_offset..]
        .find('\n')
        .map_or(source.len(), |p| byte_offset + p);
    source[start..end].to_string()
}

fn walk_tree(
    node: tree_sitter::Node,
    source: &str,
    callback: &mut dyn FnMut(tree_sitter::Node, &str),
) {
    callback(node, source);
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        walk_tree(child, source, callback);
    }
}

fn make_finding(
    rule_id: &str,
    severity: Severity,
    cwe: Option<&str>,
    description: &str,
    node: tree_sitter::Node,
    source: &str,
) -> Finding {
    let start = node.start_position();
    let end = node.end_position();
    Finding {
        rule_id: rule_id.to_string(),
        severity,
        cwe: cwe.map(|s| s.to_string()),
        description: description.to_string(),
        file: String::new(), // filled in by scanner
        line: start.row + 1,
        column: start.column + 1,
        end_line: end.row + 1,
        end_column: end.column + 1,
        snippet: get_source_line(source, node.start_byte()),
    }
}

// ─── Rule 1: no-eval ─────────────────────────────────────────────────────────

pub struct NoEval;

impl Rule for NoEval {
    fn id(&self) -> &str {
        "js/no-eval"
    }
    fn severity(&self) -> Severity {
        Severity::Critical
    }
    fn cwe(&self) -> Option<&str> {
        Some("CWE-95")
    }
    fn description(&self) -> &str {
        "Use of eval() allows arbitrary code execution"
    }
    fn language(&self) -> Language {
        Language::JavaScript
    }

    fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<Finding> {
        let mut findings = Vec::new();
        walk_tree(tree.root_node(), source, &mut |node, src| {
            // Look for call_expression where the function is `eval`
            if node.kind() == "call_expression" {
                if let Some(func) = node.child_by_field_name("function") {
                    let func_text = &src[func.byte_range()];
                    if func_text == "eval" {
                        findings.push(make_finding(
                            self.id(),
                            self.severity(),
                            self.cwe(),
                            self.description(),
                            node,
                            src,
                        ));
                    }
                }
            }
        });
        findings
    }
}

// ─── Rule 2: no-hardcoded-secret ─────────────────────────────────────────────

pub struct NoHardcodedSecret;

impl Rule for NoHardcodedSecret {
    fn id(&self) -> &str {
        "js/no-hardcoded-secret"
    }
    fn severity(&self) -> Severity {
        Severity::High
    }
    fn cwe(&self) -> Option<&str> {
        Some("CWE-798")
    }
    fn description(&self) -> &str {
        "Hardcoded secret or credential detected"
    }
    fn language(&self) -> Language {
        Language::JavaScript
    }

    fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<Finding> {
        let mut findings = Vec::new();
        let secret_pattern =
            Regex::new(r"(?i)(password|secret|api_?key|token|auth|credential|private_?key)")
                .unwrap();

        walk_tree(tree.root_node(), source, &mut |node, src| {
            // variable_declarator: const password = "hardcoded"
            if node.kind() == "variable_declarator" {
                if let (Some(name_node), Some(value_node)) = (
                    node.child_by_field_name("name"),
                    node.child_by_field_name("value"),
                ) {
                    let name = &src[name_node.byte_range()];
                    let value_kind = value_node.kind();
                    if secret_pattern.is_match(name)
                        && (value_kind == "string" || value_kind == "template_string")
                    {
                        let val = &src[value_node.byte_range()];
                        // Skip empty strings and short placeholders
                        let inner = val.trim_matches(|c| c == '"' || c == '\'' || c == '`');
                        if inner.len() >= 4 {
                            findings.push(make_finding(
                                self.id(),
                                self.severity(),
                                self.cwe(),
                                &format!(
                                    "Hardcoded secret in variable '{}' — avoid committing credentials",
                                    name
                                ),
                                node,
                                src,
                            ));
                        }
                    }
                }
            }

            // assignment_expression: obj.password = "hardcoded"
            if node.kind() == "assignment_expression" {
                if let (Some(left), Some(right)) = (
                    node.child_by_field_name("left"),
                    node.child_by_field_name("right"),
                ) {
                    let left_text = &src[left.byte_range()];
                    let right_kind = right.kind();
                    if secret_pattern.is_match(left_text)
                        && (right_kind == "string" || right_kind == "template_string")
                    {
                        let val = &src[right.byte_range()];
                        let inner = val.trim_matches(|c| c == '"' || c == '\'' || c == '`');
                        if inner.len() >= 4 {
                            findings.push(make_finding(
                                self.id(),
                                self.severity(),
                                self.cwe(),
                                &format!(
                                    "Hardcoded secret assigned to '{}' — use environment variables instead",
                                    left_text
                                ),
                                node,
                                src,
                            ));
                        }
                    }
                }
            }
        });
        findings
    }
}

// ─── Rule 3: no-sql-injection ────────────────────────────────────────────────

pub struct NoSqlInjection;

impl Rule for NoSqlInjection {
    fn id(&self) -> &str {
        "js/no-sql-injection"
    }
    fn severity(&self) -> Severity {
        Severity::Critical
    }
    fn cwe(&self) -> Option<&str> {
        Some("CWE-89")
    }
    fn description(&self) -> &str {
        "Potential SQL injection via string concatenation or template literal"
    }
    fn language(&self) -> Language {
        Language::JavaScript
    }

    fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<Finding> {
        let mut findings = Vec::new();
        let sql_pattern =
            Regex::new(r"(?i)(SELECT|INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|EXEC)\s").unwrap();

        walk_tree(tree.root_node(), source, &mut |node, src| {
            // Detect: query("SELECT * FROM users WHERE id = " + userId)
            if node.kind() == "binary_expression" {
                if let Some(op) = node.child_by_field_name("operator") {
                    if &src[op.byte_range()] == "+" {
                        if let Some(left) = node.child_by_field_name("left") {
                            let left_text = &src[left.byte_range()];
                            if (left.kind() == "string" || left.kind() == "template_string")
                                && sql_pattern.is_match(left_text)
                            {
                                findings.push(make_finding(
                                    self.id(),
                                    self.severity(),
                                    self.cwe(),
                                    "SQL query built with string concatenation — use parameterized queries",
                                    node,
                                    src,
                                ));
                            }
                        }
                    }
                }
            }

            // Detect template literals with SQL: `SELECT * FROM users WHERE id = ${id}`
            if node.kind() == "template_string" {
                let text = &src[node.byte_range()];
                if sql_pattern.is_match(text) {
                    // Check it has interpolation
                    let mut cursor = node.walk();
                    let has_substitution = node
                        .children(&mut cursor)
                        .any(|c| c.kind() == "template_substitution");
                    if has_substitution {
                        findings.push(make_finding(
                            self.id(),
                            self.severity(),
                            self.cwe(),
                            "SQL query built with template literal interpolation — use parameterized queries",
                            node,
                            src,
                        ));
                    }
                }
            }
        });
        findings
    }
}

// ─── Rule 4: no-xss-innerhtml ────────────────────────────────────────────────

pub struct NoXssInnerHtml;

impl Rule for NoXssInnerHtml {
    fn id(&self) -> &str {
        "js/no-xss-innerhtml"
    }
    fn severity(&self) -> Severity {
        Severity::High
    }
    fn cwe(&self) -> Option<&str> {
        Some("CWE-79")
    }
    fn description(&self) -> &str {
        "Assignment to innerHTML may lead to XSS"
    }
    fn language(&self) -> Language {
        Language::JavaScript
    }

    fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<Finding> {
        let mut findings = Vec::new();
        walk_tree(tree.root_node(), source, &mut |node, src| {
            // assignment_expression where left side ends with .innerHTML
            if node.kind() == "assignment_expression" {
                if let Some(left) = node.child_by_field_name("left") {
                    if left.kind() == "member_expression" {
                        if let Some(prop) = left.child_by_field_name("property") {
                            let prop_text = &src[prop.byte_range()];
                            if prop_text == "innerHTML" || prop_text == "outerHTML" {
                                // Check if right side is NOT a string literal (string literals are usually safe)
                                if let Some(right) = node.child_by_field_name("right") {
                                    if right.kind() != "string" {
                                        findings.push(make_finding(
                                            self.id(),
                                            self.severity(),
                                            self.cwe(),
                                            &format!(
                                                "Assignment to {} with dynamic content — use textContent or sanitize HTML",
                                                prop_text
                                            ),
                                            node,
                                            src,
                                        ));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        });
        findings
    }
}

// ─── Rule 5: no-command-injection ────────────────────────────────────────────

pub struct NoCommandInjection;

impl Rule for NoCommandInjection {
    fn id(&self) -> &str {
        "js/no-command-injection"
    }
    fn severity(&self) -> Severity {
        Severity::Critical
    }
    fn cwe(&self) -> Option<&str> {
        Some("CWE-78")
    }
    fn description(&self) -> &str {
        "Potential command injection via exec/spawn with dynamic input"
    }
    fn language(&self) -> Language {
        Language::JavaScript
    }

    fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<Finding> {
        let mut findings = Vec::new();
        let dangerous_fns = [
            "exec",
            "execSync",
            "spawn",
            "spawnSync",
            "execFile",
            "execFileSync",
        ];

        walk_tree(tree.root_node(), source, &mut |node, src| {
            if node.kind() == "call_expression" {
                if let Some(func) = node.child_by_field_name("function") {
                    let func_text = &src[func.byte_range()];

                    // Match child_process.exec(...) or exec(...)
                    let func_name = func_text.rsplit('.').next().unwrap_or(func_text);

                    if dangerous_fns.contains(&func_name) {
                        if let Some(args) = node.child_by_field_name("arguments") {
                            if let Some(first_arg) = args.named_child(0) {
                                let kind = first_arg.kind();
                                // Flag if the argument is not a plain string literal
                                // (template strings with substitution, identifiers, binary expressions, etc.)
                                let is_dynamic = match kind {
                                    "string" => false,
                                    "template_string" => {
                                        let mut cursor = first_arg.walk();
                                        let has_sub = first_arg
                                            .children(&mut cursor)
                                            .any(|c| c.kind() == "template_substitution");
                                        has_sub
                                    }
                                    _ => true,
                                };

                                if is_dynamic {
                                    findings.push(make_finding(
                                        self.id(),
                                        self.severity(),
                                        self.cwe(),
                                        &format!(
                                            "{}() called with dynamic argument — risk of command injection",
                                            func_name
                                        ),
                                        node,
                                        src,
                                    ));
                                }
                            }
                        }
                    }
                }
            }
        });
        findings
    }
}

// ─── Rule 6: no-document-write ──────────────────────────────────────────────

pub struct NoDocumentWrite;

impl Rule for NoDocumentWrite {
    fn id(&self) -> &str {
        "js/no-document-write"
    }
    fn severity(&self) -> Severity {
        Severity::High
    }
    fn cwe(&self) -> Option<&str> {
        Some("CWE-79")
    }
    fn description(&self) -> &str {
        "document.write() can lead to XSS vulnerabilities"
    }
    fn language(&self) -> Language {
        Language::JavaScript
    }

    fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<Finding> {
        let mut findings = Vec::new();
        walk_tree(tree.root_node(), source, &mut |node, src| {
            if node.kind() == "call_expression" {
                if let Some(func) = node.child_by_field_name("function") {
                    let func_text = &src[func.byte_range()];
                    if func_text == "document.write" || func_text == "document.writeln" {
                        findings.push(make_finding(
                            self.id(),
                            self.severity(),
                            self.cwe(),
                            "document.write() can inject arbitrary HTML — use DOM APIs instead",
                            node,
                            src,
                        ));
                    }
                }
            }
        });
        findings
    }
}

// ─── Rule 7: no-open-redirect ───────────────────────────────────────────────

pub struct NoOpenRedirect;

impl Rule for NoOpenRedirect {
    fn id(&self) -> &str {
        "js/no-open-redirect"
    }
    fn severity(&self) -> Severity {
        Severity::Medium
    }
    fn cwe(&self) -> Option<&str> {
        Some("CWE-601")
    }
    fn description(&self) -> &str {
        "Open redirect via assignment to window.location with user input"
    }
    fn language(&self) -> Language {
        Language::JavaScript
    }

    fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<Finding> {
        let mut findings = Vec::new();
        walk_tree(tree.root_node(), source, &mut |node, src| {
            if node.kind() == "assignment_expression" {
                if let Some(left) = node.child_by_field_name("left") {
                    let left_text = &src[left.byte_range()];
                    if left_text == "window.location"
                        || left_text == "window.location.href"
                        || left_text == "location.href"
                        || left_text == "document.location"
                        || left_text == "document.location.href"
                    {
                        if let Some(right) = node.child_by_field_name("right") {
                            // Flag if right side is not a string literal
                            if right.kind() != "string" {
                                findings.push(make_finding(
                                    self.id(),
                                    self.severity(),
                                    self.cwe(),
                                    "Assignment to window.location with dynamic value — risk of open redirect",
                                    node,
                                    src,
                                ));
                            }
                        }
                    }
                }
            }
        });
        findings
    }
}

// ─── Rule 8: no-weak-crypto ────────────────────────────────────────────────

pub struct NoWeakCrypto;

impl Rule for NoWeakCrypto {
    fn id(&self) -> &str {
        "js/no-weak-crypto"
    }
    fn severity(&self) -> Severity {
        Severity::Medium
    }
    fn cwe(&self) -> Option<&str> {
        Some("CWE-327")
    }
    fn description(&self) -> &str {
        "Use of weak cryptographic hash (MD5/SHA1)"
    }
    fn language(&self) -> Language {
        Language::JavaScript
    }

    fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<Finding> {
        let mut findings = Vec::new();
        walk_tree(tree.root_node(), source, &mut |node, src| {
            // Detect: createHash('md5') or createHash('sha1')
            if node.kind() == "call_expression" {
                if let Some(func) = node.child_by_field_name("function") {
                    let func_text = &src[func.byte_range()];
                    let func_name = func_text.rsplit('.').next().unwrap_or(func_text);
                    if func_name == "createHash" {
                        if let Some(args) = node.child_by_field_name("arguments") {
                            if let Some(first_arg) = args.named_child(0) {
                                if first_arg.kind() == "string" {
                                    let val = &src[first_arg.byte_range()];
                                    let inner = val.trim_matches(|c| c == '"' || c == '\'');
                                    if inner == "md5" || inner == "sha1" {
                                        findings.push(make_finding(
                                            self.id(),
                                            self.severity(),
                                            self.cwe(),
                                            &format!(
                                                "createHash('{}') uses a weak hash — use sha256 or stronger",
                                                inner
                                            ),
                                            node,
                                            src,
                                        ));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        });
        findings
    }
}

// ─── Rule 9: no-path-traversal ─────────────────────────────────────────────

pub struct NoPathTraversal;

impl Rule for NoPathTraversal {
    fn id(&self) -> &str {
        "js/no-path-traversal"
    }
    fn severity(&self) -> Severity {
        Severity::High
    }
    fn cwe(&self) -> Option<&str> {
        Some("CWE-22")
    }
    fn description(&self) -> &str {
        "Potential path traversal via fs operations with user input"
    }
    fn language(&self) -> Language {
        Language::JavaScript
    }

    fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<Finding> {
        let mut findings = Vec::new();
        let fs_fns = [
            "readFile",
            "readFileSync",
            "writeFile",
            "writeFileSync",
            "appendFile",
            "appendFileSync",
            "createReadStream",
            "createWriteStream",
            "readdir",
            "readdirSync",
            "unlink",
            "unlinkSync",
            "stat",
            "statSync",
            "access",
            "accessSync",
        ];

        walk_tree(tree.root_node(), source, &mut |node, src| {
            if node.kind() == "call_expression" {
                if let Some(func) = node.child_by_field_name("function") {
                    let func_text = &src[func.byte_range()];
                    let func_name = func_text.rsplit('.').next().unwrap_or(func_text);
                    if fs_fns.contains(&func_name) {
                        if let Some(args) = node.child_by_field_name("arguments") {
                            if let Some(first_arg) = args.named_child(0) {
                                // Flag if path argument uses concatenation or template
                                let kind = first_arg.kind();
                                if kind == "binary_expression" || kind == "template_string" {
                                    findings.push(make_finding(
                                        self.id(),
                                        self.severity(),
                                        self.cwe(),
                                        &format!(
                                            "{}() called with dynamic path — validate and sanitize to prevent path traversal",
                                            func_name
                                        ),
                                        node,
                                        src,
                                    ));
                                }
                            }
                        }
                    }

                    if func_name == "sendFile" || func_name == "download" {
                        if let Some(args) = node.child_by_field_name("arguments") {
                            if let Some(first_arg) = args.named_child(0) {
                                let is_dynamic = matches!(
                                    first_arg.kind(),
                                    "binary_expression"
                                        | "template_string"
                                        | "identifier"
                                        | "member_expression"
                                        | "subscript_expression"
                                        | "call_expression"
                                );
                                if is_dynamic {
                                    findings.push(make_finding(
                                        self.id(),
                                        self.severity(),
                                        self.cwe(),
                                        &format!(
                                            "{}() called with dynamic path — validate and sanitize to prevent path traversal",
                                            func_name
                                        ),
                                        node,
                                        src,
                                    ));
                                }
                            }
                        }
                    }
                }
            }
        });
        findings
    }
}

// ─── Rule 10: no-prototype-pollution ────────────────────────────────────────

pub struct NoSsrf;

impl Rule for NoSsrf {
    fn id(&self) -> &str {
        "js/no-ssrf"
    }
    fn severity(&self) -> Severity {
        Severity::High
    }
    fn cwe(&self) -> Option<&str> {
        Some("CWE-918")
    }
    fn description(&self) -> &str {
        "Potential SSRF via dynamic outbound request URL"
    }
    fn language(&self) -> Language {
        Language::JavaScript
    }

    fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<Finding> {
        let mut findings = Vec::new();
        let request_fns = [
            "fetch",
            "axios",
            "axios.get",
            "axios.post",
            "axios.put",
            "axios.delete",
            "axios.request",
            "got",
            "got.get",
            "got.post",
            "got.put",
            "got.delete",
            "superagent.get",
            "superagent.post",
            "http.get",
            "http.request",
            "https.get",
            "https.request",
        ];

        walk_tree(tree.root_node(), source, &mut |node, src| {
            if node.kind() != "call_expression" {
                return;
            }

            let Some(func) = node.child_by_field_name("function") else {
                return;
            };
            let func_text = &src[func.byte_range()];
            if !request_fns.contains(&func_text) {
                return;
            }

            let Some(args) = node.child_by_field_name("arguments") else {
                return;
            };
            let Some(first_arg) = args.named_child(0) else {
                return;
            };

            let is_dynamic = match first_arg.kind() {
                "string" => false,
                "object" => {
                    let arg_text = &src[first_arg.byte_range()];
                    arg_text.contains("url:")
                        && !arg_text.contains("url: \"")
                        && !arg_text.contains("url: '")
                }
                "template_string"
                | "binary_expression"
                | "identifier"
                | "member_expression"
                | "call_expression"
                | "subscript_expression" => true,
                _ => false,
            };

            if is_dynamic {
                findings.push(make_finding(
                    self.id(),
                    self.severity(),
                    self.cwe(),
                    &format!(
                        "{} called with dynamic URL — validate and allowlist outbound destinations to prevent SSRF",
                        func_text
                    ),
                    node,
                    src,
                ));
            }
        });

        findings
    }
}

// ─── Rule 10: no-prototype-pollution ────────────────────────────────────────

pub struct NoPrototypePollution;

impl Rule for NoPrototypePollution {
    fn id(&self) -> &str {
        "js/no-prototype-pollution"
    }
    fn severity(&self) -> Severity {
        Severity::High
    }
    fn cwe(&self) -> Option<&str> {
        Some("CWE-1321")
    }
    fn description(&self) -> &str {
        "Potential prototype pollution via dynamic property assignment"
    }
    fn language(&self) -> Language {
        Language::JavaScript
    }

    fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<Finding> {
        let mut findings = Vec::new();
        walk_tree(tree.root_node(), source, &mut |node, src| {
            // Detect: obj[key][subkey] = value where keys are identifiers (not literals)
            if node.kind() == "assignment_expression" {
                if let Some(left) = node.child_by_field_name("left") {
                    if left.kind() == "subscript_expression" {
                        if let Some(index) = left.child_by_field_name("index") {
                            // Flag if the index is a variable (not a string/number literal)
                            if index.kind() == "identifier" {
                                // Check if it's nested: obj[a][b] = value
                                if let Some(object) = left.child_by_field_name("object") {
                                    if object.kind() == "subscript_expression" {
                                        findings.push(make_finding(
                                            self.id(),
                                            self.severity(),
                                            self.cwe(),
                                            "Nested dynamic property assignment — risk of prototype pollution",
                                            node,
                                            src,
                                        ));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        });
        findings
    }
}

// ─── Rule 11: no-unsafe-regex ───────────────────────────────────────────────

pub struct NoUnsafeRegex;

impl Rule for NoUnsafeRegex {
    fn id(&self) -> &str {
        "js/no-unsafe-regex"
    }
    fn severity(&self) -> Severity {
        Severity::Medium
    }
    fn cwe(&self) -> Option<&str> {
        Some("CWE-1333")
    }
    fn description(&self) -> &str {
        "Potentially catastrophic backtracking regex pattern"
    }
    fn language(&self) -> Language {
        Language::JavaScript
    }

    fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<Finding> {
        let mut findings = Vec::new();
        // Patterns known to cause catastrophic backtracking: nested quantifiers
        let dangerous_pattern =
            Regex::new(r"(\([^)]*[+*][^)]*\)[+*]|\([^)]*\|[^)]*\)[+*])").unwrap();

        walk_tree(tree.root_node(), source, &mut |node, src| {
            // Detect regex literals: /pattern/
            if node.kind() == "regex" {
                let regex_text = &src[node.byte_range()];
                if dangerous_pattern.is_match(regex_text) {
                    findings.push(make_finding(
                        self.id(),
                        self.severity(),
                        self.cwe(),
                        "Regex with nested quantifiers may cause catastrophic backtracking (ReDoS)",
                        node,
                        src,
                    ));
                }
            }

            // Detect: new RegExp("pattern")
            if node.kind() == "new_expression" {
                if let Some(constructor) = node.child_by_field_name("constructor") {
                    let ctor_text = &src[constructor.byte_range()];
                    if ctor_text == "RegExp" {
                        if let Some(args) = node.child_by_field_name("arguments") {
                            if let Some(first_arg) = args.named_child(0) {
                                if first_arg.kind() == "string" {
                                    let pattern_text = &src[first_arg.byte_range()];
                                    if dangerous_pattern.is_match(pattern_text) {
                                        findings.push(make_finding(
                                            self.id(),
                                            self.severity(),
                                            self.cwe(),
                                            "RegExp with nested quantifiers may cause catastrophic backtracking (ReDoS)",
                                            node,
                                            src,
                                        ));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        });
        findings
    }
}

// ─── Rule 12: express-no-hardcoded-session-secret ─────────────────────────

pub struct ExpressNoHardcodedSessionSecret;

impl Rule for ExpressNoHardcodedSessionSecret {
    fn id(&self) -> &str {
        "js/express-no-hardcoded-session-secret"
    }
    fn severity(&self) -> Severity {
        Severity::High
    }
    fn cwe(&self) -> Option<&str> {
        Some("CWE-798")
    }
    fn description(&self) -> &str {
        "Hardcoded session secret in express-session configuration"
    }
    fn language(&self) -> Language {
        Language::JavaScript
    }

    fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<Finding> {
        let mut findings = Vec::new();
        walk_tree(tree.root_node(), source, &mut |node, src| {
            // Detect: session({ secret: "literal" }) — look for a pair with key "secret"
            // inside a call to session()
            if node.kind() == "pair" {
                if let (Some(key), Some(value)) = (
                    node.child_by_field_name("key"),
                    node.child_by_field_name("value"),
                ) {
                    let key_text = &src[key.byte_range()];
                    let key_inner = key_text.trim_matches(|c| c == '"' || c == '\'');
                    if key_inner == "secret" && value.kind() == "string" {
                        // Check the context: is this inside a call_expression that looks like session()?
                        // Walk up to check if we're in an arguments > object > call_expression chain
                        let val = &src[value.byte_range()];
                        let inner = val.trim_matches(|c| c == '"' || c == '\'');
                        if inner.len() >= 4 {
                            findings.push(make_finding(
                                self.id(),
                                self.severity(),
                                self.cwe(),
                                "Hardcoded session secret — use an environment variable instead",
                                node,
                                src,
                            ));
                        }
                    }
                }
            }
        });
        findings
    }
}

// ─── Rule 13: express-cookie-no-secure ────────────────────────────────────

pub struct ExpressCookieNoSecure;

impl Rule for ExpressCookieNoSecure {
    fn id(&self) -> &str {
        "js/express-cookie-no-secure"
    }
    fn severity(&self) -> Severity {
        Severity::Medium
    }
    fn cwe(&self) -> Option<&str> {
        Some("CWE-614")
    }
    fn description(&self) -> &str {
        "Cookie configuration missing secure flag"
    }
    fn language(&self) -> Language {
        Language::JavaScript
    }

    fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<Finding> {
        let mut findings = Vec::new();
        walk_tree(tree.root_node(), source, &mut |node, src| {
            // Look for object literals with a "cookie" key whose value is an object
            // that does NOT contain secure: true
            if node.kind() == "pair" {
                if let (Some(key), Some(value)) = (
                    node.child_by_field_name("key"),
                    node.child_by_field_name("value"),
                ) {
                    let key_text = &src[key.byte_range()];
                    let key_inner = key_text.trim_matches(|c| c == '"' || c == '\'');
                    if key_inner == "cookie" && value.kind() == "object" {
                        let obj_text = &src[value.byte_range()];
                        if !obj_text.contains("secure")
                            || obj_text.contains("secure: false")
                            || obj_text.contains("secure:false")
                        {
                            findings.push(make_finding(
                                self.id(),
                                self.severity(),
                                self.cwe(),
                                "Cookie configuration missing 'secure: true' — cookies may be sent over HTTP",
                                node,
                                src,
                            ));
                        }
                    }
                }
            }
        });
        findings
    }
}

// ─── Rule 14: express-cookie-no-httponly ───────────────────────────────────

pub struct ExpressCookieNoHttpOnly;

impl Rule for ExpressCookieNoHttpOnly {
    fn id(&self) -> &str {
        "js/express-cookie-no-httponly"
    }
    fn severity(&self) -> Severity {
        Severity::Medium
    }
    fn cwe(&self) -> Option<&str> {
        Some("CWE-1004")
    }
    fn description(&self) -> &str {
        "Cookie configuration missing httpOnly flag"
    }
    fn language(&self) -> Language {
        Language::JavaScript
    }

    fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<Finding> {
        let mut findings = Vec::new();
        walk_tree(tree.root_node(), source, &mut |node, src| {
            if node.kind() == "pair" {
                if let (Some(key), Some(value)) = (
                    node.child_by_field_name("key"),
                    node.child_by_field_name("value"),
                ) {
                    let key_text = &src[key.byte_range()];
                    let key_inner = key_text.trim_matches(|c| c == '"' || c == '\'');
                    if key_inner == "cookie" && value.kind() == "object" {
                        let obj_text = &src[value.byte_range()];
                        if !obj_text.contains("httpOnly")
                            || obj_text.contains("httpOnly: false")
                            || obj_text.contains("httpOnly:false")
                        {
                            findings.push(make_finding(
                                self.id(),
                                self.severity(),
                                self.cwe(),
                                "Cookie configuration missing 'httpOnly: true' — cookies accessible to JavaScript",
                                node,
                                src,
                            ));
                        }
                    }
                }
            }
        });
        findings
    }
}

// ─── Rule 15: express-cookie-no-samesite ──────────────────────────────────

pub struct ExpressCookieNoSameSite;

impl Rule for ExpressCookieNoSameSite {
    fn id(&self) -> &str {
        "js/express-cookie-no-samesite"
    }
    fn severity(&self) -> Severity {
        Severity::Medium
    }
    fn cwe(&self) -> Option<&str> {
        Some("CWE-352")
    }
    fn description(&self) -> &str {
        "Cookie configuration missing sameSite protection"
    }
    fn language(&self) -> Language {
        Language::JavaScript
    }

    fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<Finding> {
        let mut findings = Vec::new();
        walk_tree(tree.root_node(), source, &mut |node, src| {
            if node.kind() == "pair" {
                if let (Some(key), Some(value)) = (
                    node.child_by_field_name("key"),
                    node.child_by_field_name("value"),
                ) {
                    let key_text = &src[key.byte_range()];
                    let key_inner = key_text.trim_matches(|c| c == '"' || c == '\'');
                    if key_inner == "cookie" && value.kind() == "object" {
                        let obj_text = &src[value.byte_range()];
                        let has_same_site = obj_text.contains("sameSite");
                        let none_mode = obj_text.contains("sameSite: \"none\"")
                            || obj_text.contains("sameSite:'none'")
                            || obj_text.contains("sameSite: 'none'")
                            || obj_text.contains("sameSite:\"none\"")
                            || obj_text.contains("sameSite: false")
                            || obj_text.contains("sameSite:false");
                        if !has_same_site || none_mode {
                            findings.push(make_finding(
                                self.id(),
                                self.severity(),
                                self.cwe(),
                                "Cookie configuration missing a safe sameSite setting — set sameSite to 'lax' or 'strict'",
                                node,
                                src,
                            ));
                        }
                    }
                }
            }
        });
        findings
    }
}

// ─── Rule 16: express-session-saveuninitialized-true ──────────────────────

pub struct ExpressSessionSaveUninitializedTrue;

impl Rule for ExpressSessionSaveUninitializedTrue {
    fn id(&self) -> &str {
        "js/express-session-saveuninitialized-true"
    }
    fn severity(&self) -> Severity {
        Severity::Medium
    }
    fn cwe(&self) -> Option<&str> {
        Some("CWE-359")
    }
    fn description(&self) -> &str {
        "express-session configured with saveUninitialized: true"
    }
    fn language(&self) -> Language {
        Language::JavaScript
    }

    fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<Finding> {
        let mut findings = Vec::new();
        walk_tree(tree.root_node(), source, &mut |node, src| {
            if node.kind() != "pair" {
                return;
            }

            let (Some(key), Some(value)) = (
                node.child_by_field_name("key"),
                node.child_by_field_name("value"),
            ) else {
                return;
            };

            let key_text = &src[key.byte_range()];
            let key_inner = key_text.trim_matches(|c| c == '"' || c == '\'');
            let value_text = &src[value.byte_range()];
            if key_inner == "saveUninitialized" && value_text == "true" {
                findings.push(make_finding(
                    self.id(),
                    self.severity(),
                    self.cwe(),
                    "express-session saveUninitialized: true stores sessions before consent or login state is established",
                    node,
                    src,
                ));
            }
        });
        findings
    }
}

// ─── Rule 17: express-session-resave-true ─────────────────────────────────

pub struct ExpressSessionResaveTrue;

impl Rule for ExpressSessionResaveTrue {
    fn id(&self) -> &str {
        "js/express-session-resave-true"
    }
    fn severity(&self) -> Severity {
        Severity::Medium
    }
    fn cwe(&self) -> Option<&str> {
        Some("CWE-384")
    }
    fn description(&self) -> &str {
        "express-session configured with resave: true"
    }
    fn language(&self) -> Language {
        Language::JavaScript
    }

    fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<Finding> {
        let mut findings = Vec::new();
        walk_tree(tree.root_node(), source, &mut |node, src| {
            if node.kind() != "pair" {
                return;
            }

            let (Some(key), Some(value)) = (
                node.child_by_field_name("key"),
                node.child_by_field_name("value"),
            ) else {
                return;
            };

            let key_text = &src[key.byte_range()];
            let key_inner = key_text.trim_matches(|c| c == '"' || c == '\'');
            let value_text = &src[value.byte_range()];
            if key_inner == "resave" && value_text == "true" {
                findings.push(make_finding(
                    self.id(),
                    self.severity(),
                    self.cwe(),
                    "express-session resave: true can overwrite sessions unnecessarily — prefer resave: false unless your store requires it",
                    node,
                    src,
                ));
            }
        });
        findings
    }
}

// ─── Rule 18: express-direct-response-write ───────────────────────────────

pub struct ExpressDirectResponseWrite;

impl Rule for ExpressDirectResponseWrite {
    fn id(&self) -> &str {
        "js/express-direct-response-write"
    }
    fn severity(&self) -> Severity {
        Severity::High
    }
    fn cwe(&self) -> Option<&str> {
        Some("CWE-79")
    }
    fn description(&self) -> &str {
        "XSS via direct response write with user input"
    }
    fn language(&self) -> Language {
        Language::JavaScript
    }

    fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<Finding> {
        let mut findings = Vec::new();
        // Match user-controlled input objects
        let user_input_re = Regex::new(r"^req\.(params|query|body|headers)(\b|\[|\.)").unwrap();
        // Sanitization wrappers that neutralise XSS risk
        let sanitize_re = Regex::new(
            r"(?i)(escapeHtml|escape|sanitize|encode|encodeURIComponent|encodeURI|htmlEncode|xss|purify|DOMPurify|validator|parseInt|parseFloat|Number|String)\s*\("
        ).unwrap();

        walk_tree(tree.root_node(), source, &mut |node, src| {
            // Detect: res.send(req.query.foo), res.write(req.body.bar)
            if node.kind() == "call_expression" {
                if let Some(func) = node.child_by_field_name("function") {
                    if func.kind() == "member_expression" {
                        if let Some(obj) = func.child_by_field_name("object") {
                            let obj_text = &src[obj.byte_range()];
                            // Only flag res.send/write/end, not arbitrary objects
                            if obj_text != "res" && !obj_text.ends_with(".res") {
                                return;
                            }
                        }
                        if let Some(prop) = func.child_by_field_name("property") {
                            let prop_text = &src[prop.byte_range()];
                            if prop_text == "send" || prop_text == "write" {
                                if let Some(args) = node.child_by_field_name("arguments") {
                                    let args_text = &src[args.byte_range()];
                                    // Skip if any sanitization wrapper is present
                                    if sanitize_re.is_match(args_text) {
                                        return;
                                    }
                                    // Check each direct argument for user input
                                    let mut cursor = args.walk();
                                    for arg in args.children(&mut cursor) {
                                        // Skip punctuation (parens, commas)
                                        if arg.kind() == "("
                                            || arg.kind() == ")"
                                            || arg.kind() == ","
                                        {
                                            continue;
                                        }
                                        // Only flag when the argument is a direct member/subscript
                                        // expression starting with req.params/query/body/headers.
                                        // Binary expressions (concatenation), call expressions
                                        // (wrapping functions), and template literals are NOT
                                        // direct -- they mix or transform the input.
                                        let kind = arg.kind();
                                        if kind != "member_expression" && kind != "identifier" {
                                            continue;
                                        }
                                        let arg_text = &src[arg.byte_range()];
                                        if user_input_re.is_match(arg_text.trim()) {
                                            findings.push(make_finding(
                                                self.id(),
                                                self.severity(),
                                                self.cwe(),
                                                &format!(
                                                    "res.{}() called with user input — risk of reflected XSS, sanitize before sending",
                                                    prop_text
                                                ),
                                                node,
                                                src,
                                            ));
                                            break; // one finding per call
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        });
        findings
    }
}

// ─── Rule 19: jwt-hardcoded-secret ────────────────────────────────────────

pub struct JwtHardcodedSecret;

impl Rule for JwtHardcodedSecret {
    fn id(&self) -> &str {
        "js/jwt-hardcoded-secret"
    }
    fn severity(&self) -> Severity {
        Severity::High
    }
    fn cwe(&self) -> Option<&str> {
        Some("CWE-798")
    }
    fn description(&self) -> &str {
        "JWT signing or verification with a hardcoded secret"
    }
    fn language(&self) -> Language {
        Language::JavaScript
    }

    fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<Finding> {
        let mut findings = Vec::new();

        walk_tree(tree.root_node(), source, &mut |node, src| {
            if node.kind() != "call_expression" {
                return;
            }

            let Some(func) = node.child_by_field_name("function") else {
                return;
            };
            let func_text = &src[func.byte_range()];
            if func_text != "jwt.sign"
                && func_text != "jwt.verify"
                && func_text != "jsonwebtoken.sign"
                && func_text != "jsonwebtoken.verify"
            {
                return;
            }

            let Some(args) = node.child_by_field_name("arguments") else {
                return;
            };
            let Some(secret_arg) = args.named_child(1) else {
                return;
            };
            if secret_arg.kind() != "string" && secret_arg.kind() != "template_string" {
                return;
            }

            let secret = &src[secret_arg.byte_range()];
            let inner = secret.trim_matches(|c| c == '"' || c == '\'' || c == '`');
            if inner.len() < 4 {
                return;
            }

            findings.push(make_finding(
                self.id(),
                self.severity(),
                self.cwe(),
                "JWT secret is hardcoded — load signing keys from environment or a secrets manager",
                node,
                src,
            ));
        });

        findings
    }
}

// ─── Rule 20: jwt-none-algorithm ───────────────────────────────────────────

pub struct JwtNoneAlgorithm;

impl Rule for JwtNoneAlgorithm {
    fn id(&self) -> &str {
        "js/jwt-none-algorithm"
    }
    fn severity(&self) -> Severity {
        Severity::High
    }
    fn cwe(&self) -> Option<&str> {
        Some("CWE-347")
    }
    fn description(&self) -> &str {
        "JWT configured to use the 'none' algorithm"
    }
    fn language(&self) -> Language {
        Language::JavaScript
    }

    fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<Finding> {
        let mut findings = Vec::new();

        walk_tree(tree.root_node(), source, &mut |node, src| {
            if node.kind() != "call_expression" {
                return;
            }

            let Some(func) = node.child_by_field_name("function") else {
                return;
            };
            let func_text = &src[func.byte_range()];
            if func_text != "jwt.sign"
                && func_text != "jwt.verify"
                && func_text != "jsonwebtoken.sign"
                && func_text != "jsonwebtoken.verify"
            {
                return;
            }

            let Some(args) = node.child_by_field_name("arguments") else {
                return;
            };
            let Some(options_arg) = args.named_child(2) else {
                return;
            };
            if options_arg.kind() != "object" {
                return;
            }

            let options_text = &src[options_arg.byte_range()];
            let uses_none = options_text.contains("algorithm: \"none\"")
                || options_text.contains("algorithm:'none'")
                || options_text.contains("algorithm: 'none'")
                || options_text.contains("algorithm:\"none\"")
                || options_text.contains("algorithms: [\"none\"]")
                || options_text.contains("algorithms:['none']")
                || options_text.contains("algorithms: ['none']")
                || options_text.contains("algorithms:[\"none\"]");
            if !uses_none {
                return;
            }

            findings.push(make_finding(
                self.id(),
                self.severity(),
                self.cwe(),
                "JWT configured with algorithm 'none' — require a signed algorithm such as HS256 or RS256",
                node,
                src,
            ));
        });

        findings
    }
}

// ─── Rule 21: jwt-ignore-expiration ────────────────────────────────────────

pub struct JwtIgnoreExpiration;

impl Rule for JwtIgnoreExpiration {
    fn id(&self) -> &str {
        "js/jwt-ignore-expiration"
    }
    fn severity(&self) -> Severity {
        Severity::High
    }
    fn cwe(&self) -> Option<&str> {
        Some("CWE-613")
    }
    fn description(&self) -> &str {
        "JWT verification configured to ignore token expiration"
    }
    fn language(&self) -> Language {
        Language::JavaScript
    }

    fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<Finding> {
        let mut findings = Vec::new();

        walk_tree(tree.root_node(), source, &mut |node, src| {
            if node.kind() != "call_expression" {
                return;
            }

            let Some(func) = node.child_by_field_name("function") else {
                return;
            };
            let func_text = &src[func.byte_range()];
            if func_text != "jwt.verify" && func_text != "jsonwebtoken.verify" {
                return;
            }

            let Some(args) = node.child_by_field_name("arguments") else {
                return;
            };
            let Some(options_arg) = args.named_child(2) else {
                return;
            };
            if options_arg.kind() != "object" {
                return;
            }

            let options_text = &src[options_arg.byte_range()];
            let ignores_expiration = options_text.contains("ignoreExpiration: true")
                || options_text.contains("ignoreExpiration:true");
            if !ignores_expiration {
                return;
            }

            findings.push(make_finding(
                self.id(),
                self.severity(),
                self.cwe(),
                "JWT verification ignores expiration — reject expired tokens instead of setting ignoreExpiration: true",
                node,
                src,
            ));
        });

        findings
    }
}

// ─── Rule 22: jwt-decode-without-verify ────────────────────────────────────

pub struct JwtDecodeWithoutVerify;

impl Rule for JwtDecodeWithoutVerify {
    fn id(&self) -> &str {
        "js/jwt-decode-without-verify"
    }
    fn severity(&self) -> Severity {
        Severity::High
    }
    fn cwe(&self) -> Option<&str> {
        Some("CWE-347")
    }
    fn description(&self) -> &str {
        "JWT decoded without signature verification"
    }
    fn language(&self) -> Language {
        Language::JavaScript
    }

    fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<Finding> {
        let mut findings = Vec::new();

        walk_tree(tree.root_node(), source, &mut |node, src| {
            if node.kind() != "call_expression" {
                return;
            }

            let Some(func) = node.child_by_field_name("function") else {
                return;
            };
            let func_text = &src[func.byte_range()];
            if func_text != "jwt.decode" && func_text != "jsonwebtoken.decode" {
                return;
            }

            findings.push(make_finding(
                self.id(),
                self.severity(),
                self.cwe(),
                "JWT decoded without verification — use jwt.verify() when authenticity matters",
                node,
                src,
            ));
        });

        findings
    }
}

// ─── Rule 23: jwt-verify-missing-algorithms ───────────────────────────────

pub struct JwtVerifyMissingAlgorithms;

impl Rule for JwtVerifyMissingAlgorithms {
    fn id(&self) -> &str {
        "js/jwt-verify-missing-algorithms"
    }
    fn severity(&self) -> Severity {
        Severity::High
    }
    fn cwe(&self) -> Option<&str> {
        Some("CWE-347")
    }
    fn description(&self) -> &str {
        "JWT verification without an explicit algorithms allowlist"
    }
    fn language(&self) -> Language {
        Language::JavaScript
    }

    fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<Finding> {
        let mut findings = Vec::new();

        walk_tree(tree.root_node(), source, &mut |node, src| {
            if node.kind() != "call_expression" {
                return;
            }

            let Some(func) = node.child_by_field_name("function") else {
                return;
            };
            let func_text = &src[func.byte_range()];
            if func_text != "jwt.verify" && func_text != "jsonwebtoken.verify" {
                return;
            }

            let Some(args) = node.child_by_field_name("arguments") else {
                return;
            };

            let Some(options_arg) = args.named_child(2) else {
                findings.push(make_finding(
                    self.id(),
                    self.severity(),
                    self.cwe(),
                    "JWT verification does not restrict allowed algorithms — pass an explicit algorithms allowlist",
                    node,
                    src,
                ));
                return;
            };

            if options_arg.kind() != "object" {
                return;
            }

            let options_text = &src[options_arg.byte_range()];
            if !options_text.contains("algorithms") {
                findings.push(make_finding(
                    self.id(),
                    self.severity(),
                    self.cwe(),
                    "JWT verification does not restrict allowed algorithms — pass an explicit algorithms allowlist",
                    node,
                    src,
                ));
            }
        });

        findings
    }
}

// ─── Rule 24: no-cors-star ─────────────────────────────────────────────────

pub struct NoCorsStar;

impl Rule for NoCorsStar {
    fn id(&self) -> &str {
        "js/no-cors-star"
    }
    fn severity(&self) -> Severity {
        Severity::Medium
    }
    fn cwe(&self) -> Option<&str> {
        Some("CWE-942")
    }
    fn description(&self) -> &str {
        "CORS misconfiguration allowing all origins"
    }
    fn language(&self) -> Language {
        Language::JavaScript
    }

    fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<Finding> {
        let mut findings = Vec::new();
        walk_tree(tree.root_node(), source, &mut |node, src| {
            // Detect: setHeader("Access-Control-Allow-Origin", "*")
            if node.kind() == "call_expression" {
                if let Some(func) = node.child_by_field_name("function") {
                    let func_text = &src[func.byte_range()];
                    let func_name = func_text.rsplit('.').next().unwrap_or(func_text);
                    if func_name == "setHeader" || func_name == "set" || func_name == "header" {
                        if let Some(args) = node.child_by_field_name("arguments") {
                            let arg_count = args.named_child_count();
                            if arg_count >= 2 {
                                if let (Some(first), Some(second)) =
                                    (args.named_child(0), args.named_child(1))
                                {
                                    if first.kind() == "string" && second.kind() == "string" {
                                        let header_name = &src[first.byte_range()];
                                        let header_val = &src[second.byte_range()];
                                        let name_inner =
                                            header_name.trim_matches(|c| c == '"' || c == '\'');
                                        let val_inner =
                                            header_val.trim_matches(|c| c == '"' || c == '\'');
                                        if name_inner
                                            .eq_ignore_ascii_case("Access-Control-Allow-Origin")
                                            && val_inner == "*"
                                        {
                                            findings.push(make_finding(
                                                self.id(),
                                                self.severity(),
                                                self.cwe(),
                                                "Access-Control-Allow-Origin set to '*' — restrict to specific origins",
                                                node,
                                                src,
                                            ));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // Detect: { origin: "*" } in cors config objects
            if node.kind() == "pair" {
                if let (Some(key), Some(value)) = (
                    node.child_by_field_name("key"),
                    node.child_by_field_name("value"),
                ) {
                    let key_text = &src[key.byte_range()];
                    let key_inner = key_text.trim_matches(|c| c == '"' || c == '\'');
                    if key_inner == "origin" && value.kind() == "string" {
                        let val_text = &src[value.byte_range()];
                        let val_inner = val_text.trim_matches(|c| c == '"' || c == '\'');
                        if val_inner == "*" {
                            findings.push(make_finding(
                                self.id(),
                                self.severity(),
                                self.cwe(),
                                "CORS origin set to '*' — restrict to specific origins",
                                node,
                                src,
                            ));
                        }
                    }
                }
            }
        });
        findings
    }
}

// ─── Rule: no-unsafe-format-string ───────────────────────────────────────────

pub struct NoUnsafeFormatString;

impl Rule for NoUnsafeFormatString {
    fn id(&self) -> &str {
        "js/no-unsafe-format-string"
    }
    fn severity(&self) -> Severity {
        Severity::Medium
    }
    fn cwe(&self) -> Option<&str> {
        Some("CWE-134")
    }
    fn description(&self) -> &str {
        "Template literal with variables in console/logging function may enable log injection"
    }
    fn language(&self) -> Language {
        Language::JavaScript
    }

    fn check(&self, source: &str, tree: &tree_sitter::Tree) -> Vec<Finding> {
        let mut findings = Vec::new();

        walk_tree(tree.root_node(), source, &mut |node, src| {
            if node.kind() == "call_expression" {
                if let Some(func) = node.child_by_field_name("function") {
                    let func_text = &src[func.byte_range()];
                    // console.error, console.log, console.warn, console.info, util.format
                    if matches!(
                        func_text,
                        "console.error"
                            | "console.log"
                            | "console.warn"
                            | "console.info"
                            | "util.format"
                    ) {
                        if let Some(args) = node.child_by_field_name("arguments") {
                            let mut cursor = args.walk();
                            for arg in args.children(&mut cursor) {
                                if arg.kind() == "template_string" {
                                    // Check if template string has interpolation
                                    let mut has_interpolation = false;
                                    let mut inner_cursor = arg.walk();
                                    for child in arg.children(&mut inner_cursor) {
                                        if child.kind() == "template_substitution" {
                                            has_interpolation = true;
                                            break;
                                        }
                                    }
                                    if has_interpolation {
                                        findings.push(make_finding(
                                            self.id(),
                                            self.severity(),
                                            self.cwe(),
                                            "Template literal with variables in logging function — user-controlled values may forge log entries",
                                            node,
                                            src,
                                        ));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        });
        findings
    }
}