repotoire 0.8.0

Graph-powered code analysis CLI. 110 detectors for security, architecture, bus factor, and code quality.
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
//! Express Security Detector
//!
//! Graph-enhanced detection of Express.js security issues.
//! Uses graph to:
//! - Check middleware chain coverage
//! - Identify routes without authentication
//! - Trace error handling coverage

use crate::detectors::base::{Detector, DetectorConfig};
use crate::models::{deterministic_finding_id, Finding, Severity};
use anyhow::Result;
use regex::Regex;
use std::path::PathBuf;
use std::sync::LazyLock;
use tracing::info;

static EXPRESS_APP: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r#"express\(\)|require\(["']express["']\)|from ['"]express['"']"#)
        .expect("valid regex")
});
static ROUTE_HANDLER: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"\.(get|post|put|delete|patch|all|use)\s*\(").expect("valid regex")
});

/// Security features to check
struct SecurityFeatures {
    has_helmet: bool,
    has_cors: bool,
    has_rate_limit: bool,
    has_body_parser_limit: bool,
    #[allow(dead_code)] // Tracked for security audit completeness
    has_hpp: bool,
    has_csrf: bool,
    #[allow(dead_code)] // Tracked for security audit completeness
    has_compression: bool,
    route_count: usize,
    auth_middleware_count: usize,
}

impl SecurityFeatures {
    fn from_content(content: &str) -> Self {
        let lower = content.to_lowercase();
        Self {
            has_helmet: content.contains("helmet"),
            has_cors: content.contains("cors(") || content.contains("cors."),
            has_rate_limit: lower.contains("ratelimit")
                || lower.contains("rate-limit")
                || lower.contains("express-rate"),
            has_body_parser_limit: content.contains("limit:")
                || content.contains("bodyParser") && content.contains("limit"),
            has_hpp: content.contains("hpp"),
            has_csrf: lower.contains("csrf") || lower.contains("csurf"),
            has_compression: content.contains("compression"),
            route_count: ROUTE_HANDLER.find_iter(content).count(),
            auth_middleware_count: Self::count_auth_middleware(content),
        }
    }

    fn count_auth_middleware(content: &str) -> usize {
        let auth_patterns = [
            "passport.",
            "jwt.",
            "jsonwebtoken",
            "express-jwt",
            "isAuthenticated",
            "requireAuth",
            "authenticate",
            "authorize",
            "checkAuth",
            "verifyToken",
        ];
        auth_patterns
            .iter()
            .filter(|p| content.contains(*p))
            .count()
    }

    fn security_score(&self) -> f64 {
        let mut score = 0.0;
        let mut max_score = 0.0;

        // Helmet - critical
        max_score += 25.0;
        if self.has_helmet {
            score += 25.0;
        }

        // Rate limiting - critical for production
        max_score += 20.0;
        if self.has_rate_limit {
            score += 20.0;
        }

        // Body parser limits
        max_score += 15.0;
        if self.has_body_parser_limit {
            score += 15.0;
        }

        // CORS
        max_score += 10.0;
        if self.has_cors {
            score += 10.0;
        }

        // CSRF for non-API apps
        max_score += 10.0;
        if self.has_csrf {
            score += 10.0;
        }

        // Auth middleware
        max_score += 20.0;
        if self.auth_middleware_count > 0 {
            score += 20.0;
        }

        (score / max_score) * 100.0
    }
}

pub struct ExpressSecurityDetector {
    #[allow(dead_code)] // Part of detector pattern, used for file scanning
    repository_path: PathBuf,
    max_findings: usize,
}

impl ExpressSecurityDetector {
    crate::detectors::detector_new!(50);
}

impl Detector for ExpressSecurityDetector {
    fn name(&self) -> &'static str {
        "express-security"
    }
    fn description(&self) -> &'static str {
        "Detects Express.js security issues"
    }

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

    fn file_extensions(&self) -> &'static [&'static str] {
        &["js", "ts"]
    }

    fn content_requirements(&self) -> crate::detectors::detector_context::ContentFlags {
        crate::detectors::detector_context::ContentFlags::HAS_EXPRESS
    }

    fn detect(
        &self,
        ctx: &crate::detectors::analysis_context::AnalysisContext,
    ) -> Result<Vec<Finding>> {
        let files = &ctx.as_file_provider();
        // Codebase-level pre-filter: skip if no file uses Express
        let has_express = files
            .files_with_extensions(&["js", "ts"])
            .iter()
            .any(|p| files.content(p).is_some_and(|c| c.contains("express")));
        if !has_express {
            return Ok(vec![]);
        }

        let mut findings = vec![];

        for path in files.files_with_extensions(&["js", "ts", "mjs"]) {
            if findings.len() >= self.max_findings {
                break;
            }

            let path_str = path.to_string_lossy().to_string();

            // Skip test files
            if crate::detectors::base::is_test_path(&path_str) {
                continue;
            }

            if let Some(content) = files.content(path) {
                // Check if this is an Express app
                if !EXPRESS_APP.is_match(&content) {
                    continue;
                }

                let features = SecurityFeatures::from_content(&content);
                let security_score = features.security_score();

                // Build app-level notes
                let mut app_notes = Vec::new();
                app_notes.push(format!("📊 Security Score: {:.0}%", security_score));
                app_notes.push(format!("🛣️ Routes: {}", features.route_count));

                let mut missing = Vec::new();
                if !features.has_helmet {
                    missing.push("helmet");
                }
                if !features.has_rate_limit {
                    missing.push("rate-limit");
                }
                if !features.has_body_parser_limit {
                    missing.push("body-parser-limit");
                }
                if features.auth_middleware_count == 0 {
                    missing.push("auth-middleware");
                }

                if !missing.is_empty() {
                    app_notes.push(format!("❌ Missing: {}", missing.join(", ")));
                }

                let context_notes = format!("\n\n**App Analysis:**\n{}", app_notes.join("\n"));

                // Helmet finding
                if !features.has_helmet {
                    let severity = if features.route_count > 5 {
                        Severity::High // Bigger app = more important
                    } else {
                        Severity::Medium
                    };

                    findings.push(Finding {
                        id: String::new(),
                        detector: "ExpressSecurityDetector".to_string(),
                        severity,
                        title: "Express app missing helmet".to_string(),
                        description: format!(
                            "Helmet sets important security headers to protect against common attacks.{}",
                            context_notes
                        ),
                        affected_files: vec![path.to_path_buf()],
                        line_start: Some(1),
                        line_end: Some(1),
                        suggested_fix: Some(
                            "Install and use helmet:\n\
                             ```bash\n\
                             npm install helmet\n\
                             ```\n\
                             ```javascript\n\
                             const helmet = require('helmet');\n\
                             app.use(helmet());\n\
                             \n\
                             // Or with custom config:\n\
                             app.use(helmet({\n\
                               contentSecurityPolicy: {\n\
                                 directives: {\n\
                                   defaultSrc: [\"'self'\"],\n\
                                   scriptSrc: [\"'self'\", \"trusted-cdn.com\"],\n\
                                 },\n\
                               },\n\
                             }));\n\
                             ```".to_string()
                        ),
                        estimated_effort: Some("10 minutes".to_string()),
                        category: Some("security".to_string()),
                        cwe_id: Some("CWE-693".to_string()),
                        why_it_matters: Some(
                            "Without helmet, your app is missing:\n\
                             • X-Content-Type-Options (prevents MIME sniffing)\n\
                             • X-Frame-Options (prevents clickjacking)\n\
                             • X-XSS-Protection (legacy XSS filter)\n\
                             • Strict-Transport-Security (enforces HTTPS)\n\
                             • Content-Security-Policy (prevents XSS)".to_string()
                        ),
                        ..Default::default()
                    });
                }

                // Rate limiting finding
                if !features.has_rate_limit {
                    let severity = if features.route_count > 5 {
                        Severity::Medium
                    } else {
                        Severity::Low
                    };

                    findings.push(Finding {
                        id: String::new(),
                        detector: "ExpressSecurityDetector".to_string(),
                        severity,
                        title: "Express app missing rate limiting".to_string(),
                        description: format!(
                            "Rate limiting prevents brute force attacks and DoS.{}",
                            context_notes
                        ),
                        affected_files: vec![path.to_path_buf()],
                        line_start: Some(1),
                        line_end: Some(1),
                        suggested_fix: Some(
                            "Install and use express-rate-limit:\n\
                             ```bash\n\
                             npm install express-rate-limit\n\
                             ```\n\
                             ```javascript\n\
                             const rateLimit = require('express-rate-limit');\n\
                             \n\
                             const limiter = rateLimit({\n\
                               windowMs: 15 * 60 * 1000, // 15 minutes\n\
                               max: 100, // limit each IP to 100 requests per windowMs\n\
                               message: 'Too many requests, please try again later.',\n\
                             });\n\
                             \n\
                             app.use(limiter);\n\
                             \n\
                             // Stricter limits for auth endpoints\n\
                             const authLimiter = rateLimit({\n\
                               windowMs: 15 * 60 * 1000,\n\
                               max: 5,\n\
                             });\n\
                             app.use('/api/auth', authLimiter);\n\
                             ```"
                            .to_string(),
                        ),
                        estimated_effort: Some("15 minutes".to_string()),
                        category: Some("security".to_string()),
                        cwe_id: Some("CWE-770".to_string()),
                        why_it_matters: Some(
                            "Without rate limiting, attackers can:\n\
                             • Brute force passwords\n\
                             • Scrape data at scale\n\
                             • DoS your API\n\
                             • Abuse expensive endpoints"
                                .to_string(),
                        ),
                        ..Default::default()
                    });
                }

                // Body parser limit finding
                if !features.has_body_parser_limit {
                    findings.push(Finding {
                        id: String::new(),
                        detector: "ExpressSecurityDetector".to_string(),
                        severity: Severity::Low,
                        title: "No body size limit configured".to_string(),
                        description: "Large request bodies can be used for DoS attacks."
                            .to_string(),
                        affected_files: vec![path.to_path_buf()],
                        line_start: Some(1),
                        line_end: Some(1),
                        suggested_fix: Some(
                            "Set body size limits:\n\
                             ```javascript\n\
                             app.use(express.json({ limit: '10kb' }));\n\
                             app.use(express.urlencoded({ limit: '10kb', extended: true }));\n\
                             ```"
                            .to_string(),
                        ),
                        estimated_effort: Some("5 minutes".to_string()),
                        category: Some("security".to_string()),
                        cwe_id: Some("CWE-400".to_string()),
                        why_it_matters: Some(
                            "Large payloads can exhaust server memory.".to_string(),
                        ),
                        ..Default::default()
                    });
                }

                // Check for error handling
                let has_error_handler = content.contains("err, req, res, next")
                    || content.contains("error, req, res, next")
                    || content.contains("err: Error");

                if !has_error_handler && features.route_count > 3 {
                    findings.push(Finding {
                        id: String::new(),
                        detector: "ExpressSecurityDetector".to_string(),
                        severity: Severity::Medium,
                        title: "No global error handler".to_string(),
                        description: format!(
                            "Express apps should have a global error handler to prevent stack traces from leaking.{}",
                            context_notes
                        ),
                        affected_files: vec![path.to_path_buf()],
                        line_start: Some(1),
                        line_end: Some(1),
                        suggested_fix: Some(
                            "Add a global error handler:\n\
                             ```javascript\n\
                             // Error handler must be the LAST middleware\n\
                             app.use((err, req, res, next) => {\n\
                               console.error(err.stack);\n\
                               res.status(500).json({\n\
                                 error: process.env.NODE_ENV === 'production' \n\
                                   ? 'Internal server error' \n\
                                   : err.message\n\
                               });\n\
                             });\n\
                             ```".to_string()
                        ),
                        estimated_effort: Some("10 minutes".to_string()),
                        category: Some("security".to_string()),
                        cwe_id: Some("CWE-209".to_string()),
                        why_it_matters: Some("Unhandled errors leak stack traces and internal details.".to_string()),
                        ..Default::default()
                    });
                }

                // Check for auth on routes
                if features.auth_middleware_count == 0 && features.route_count > 5 {
                    findings.push(Finding {
                        id: String::new(),
                        detector: "ExpressSecurityDetector".to_string(),
                        severity: Severity::Medium,
                        title: "No authentication middleware detected".to_string(),
                        description: format!(
                            "This Express app has {} routes but no apparent authentication.{}",
                            features.route_count, context_notes
                        ),
                        affected_files: vec![path.to_path_buf()],
                        line_start: Some(1),
                        line_end: Some(1),
                        suggested_fix: Some(
                            "Consider adding authentication:\n\
                             ```javascript\n\
                             // Using Passport.js\n\
                             const passport = require('passport');\n\
                             app.use(passport.initialize());\n\
                             app.use('/api/protected', passport.authenticate('jwt'));\n\
                             \n\
                             // Or custom middleware\n\
                             const requireAuth = (req, res, next) => {\n\
                               if (!req.user) return res.status(401).json({ error: 'Unauthorized' });\n\
                               next();\n\
                             };\n\
                             ```".to_string()
                        ),
                        estimated_effort: Some("1-2 hours".to_string()),
                        category: Some("security".to_string()),
                        cwe_id: Some("CWE-306".to_string()),
                        why_it_matters: Some("APIs without authentication are open to abuse.".to_string()),
                        ..Default::default()
                    });
                }
            }
        }

        info!(
            "ExpressSecurityDetector found {} findings (graph-aware)",
            findings.len()
        );
        Ok(findings)
    }
}

impl crate::detectors::RegisteredDetector for ExpressSecurityDetector {
    fn create(init: &crate::detectors::DetectorInit) -> std::sync::Arc<dyn Detector> {
        std::sync::Arc::new(Self::new(init.repo_path))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::builder::GraphBuilder;

    #[test]
    fn test_detects_missing_helmet() {
        let store = GraphBuilder::new().freeze();
        let detector = ExpressSecurityDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("app.js", "const express = require('express');\nconst app = express();\n\napp.get('/api/users', (req, res) => {\n  res.json({ users: [] });\n});\n\napp.post('/api/users', (req, res) => {\n  res.json({ created: true });\n});\n\napp.listen(3000);\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");

        assert!(!findings.is_empty(), "Should detect security issues");
        assert!(
            findings.iter().any(|f| f.title.contains("helmet")),
            "Should detect missing helmet. Titles: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_secure_express_fewer_findings() {
        let store = GraphBuilder::new().freeze();
        let detector = ExpressSecurityDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("server.js", "const express = require('express');\nconst helmet = require('helmet');\nconst cors = require('cors');\nconst rateLimit = require('express-rate-limit');\n\nconst app = express();\napp.use(helmet());\napp.use(cors());\napp.use(rateLimit({ windowMs: 15 * 60 * 1000, max: 100 }));\napp.use(express.json({ limit: '10kb' }));\n\napp.get('/api/data', (req, res) => {\n  res.json({ ok: true });\n});\n\napp.listen(3000);\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");

        // Should NOT flag helmet, cors, rate-limit, or body-parser-limit
        assert!(
            !findings.iter().any(|f| f.title.contains("helmet")),
            "Should not flag helmet when present"
        );
        assert!(
            !findings.iter().any(|f| f.title.contains("rate limiting")),
            "Should not flag rate limiting when present"
        );
        assert!(
            !findings.iter().any(|f| f.title.contains("body size limit")),
            "Should not flag body size limit when present"
        );
    }

    #[test]
    fn test_non_express_file_no_findings() {
        let store = GraphBuilder::new().freeze();
        let detector = ExpressSecurityDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("utils.js", "function add(a, b) {\n  return a + b;\n}\n\nfunction multiply(a, b) {\n  return a * b;\n}\n\nmodule.exports = { add, multiply };\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");

        assert!(
            findings.is_empty(),
            "Non-Express file should produce no findings, got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_express_app_without_helmet_or_rate_limit() {
        // An Express app with many routes but no helmet or rate limiting
        // should produce findings for both.
        let store = GraphBuilder::new().freeze();
        let detector = ExpressSecurityDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![(
            "server.js",
            "const express = require('express');\nconst app = express();\n\napp.get('/api/users', (req, res) => res.json([]));\napp.post('/api/users', (req, res) => res.json({}));\napp.get('/api/posts', (req, res) => res.json([]));\napp.put('/api/posts/:id', (req, res) => res.json({}));\napp.delete('/api/posts/:id', (req, res) => res.json({}));\napp.get('/api/comments', (req, res) => res.json([]));\n\napp.listen(3000);\n",
        )]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.iter().any(|f| f.title.contains("helmet")),
            "Should flag missing helmet. Titles: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
        assert!(
            findings.iter().any(|f| f.title.contains("rate limiting")),
            "Should flag missing rate limiting for app with >5 routes. Titles: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_express_with_helmet_no_helmet_finding() {
        // An Express app with helmet() installed should NOT produce a helmet finding.
        let store = GraphBuilder::new().freeze();
        let detector = ExpressSecurityDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![(
            "app.js",
            "const express = require('express');\nconst helmet = require('helmet');\nconst app = express();\napp.use(helmet());\n\napp.get('/api/data', (req, res) => res.json({ ok: true }));\napp.listen(3000);\n",
        )]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.iter().any(|f| f.title.contains("helmet")),
            "Should NOT flag helmet when it is installed. Titles: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_express_with_cors_has_cors_detected() {
        // An Express app using cors() should have has_cors = true,
        // so the security score includes CORS points.
        let store = GraphBuilder::new().freeze();
        let detector = ExpressSecurityDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![(
            "app.js",
            "const express = require('express');\nconst cors = require('cors');\nconst app = express();\napp.use(cors({ origin: 'https://example.com' }));\n\napp.get('/api/data', (req, res) => res.json({ ok: true }));\napp.listen(3000);\n",
        )]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        // CORS is detected, so it shouldn't appear in "missing" list.
        // The detector doesn't produce a specific "CORS" finding — it only tracks
        // CORS presence for the security score. Verify no CORS-related finding exists.
        assert!(
            !findings
                .iter()
                .any(|f| f.title.to_lowercase().contains("cors")),
            "Should not produce a CORS finding when cors middleware is present. Titles: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_express_missing_error_handler_with_many_routes() {
        // An Express app with >3 routes and no error handler should be flagged.
        let store = GraphBuilder::new().freeze();
        let detector = ExpressSecurityDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![(
            "app.js",
            "const express = require('express');\nconst app = express();\n\napp.get('/a', (req, res) => res.json({}));\napp.get('/b', (req, res) => res.json({}));\napp.get('/c', (req, res) => res.json({}));\napp.get('/d', (req, res) => res.json({}));\n\napp.listen(3000);\n",
        )]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.iter().any(|f| f.title.contains("error handler")),
            "Should detect missing global error handler for app with >3 routes. Titles: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_express_with_error_handler_no_error_finding() {
        // An Express app with a proper error handler should not produce that finding.
        let store = GraphBuilder::new().freeze();
        let detector = ExpressSecurityDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![(
            "app.js",
            "const express = require('express');\nconst app = express();\n\napp.get('/a', (req, res) => res.json({}));\napp.get('/b', (req, res) => res.json({}));\napp.get('/c', (req, res) => res.json({}));\napp.get('/d', (req, res) => res.json({}));\n\napp.use((err, req, res, next) => {\n  console.error(err.stack);\n  res.status(500).json({ error: 'Internal server error' });\n});\n\napp.listen(3000);\n",
        )]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.iter().any(|f| f.title.contains("error handler")),
            "Should NOT flag error handler when one is present. Titles: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }
}