repotoire 0.9.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
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
//! Insecure Random Detector
//!
//! Graph-enhanced detection of insecure random:
//! - Trace random values through function calls to security contexts
//! - Check if random is used for IDs, tokens, or passwords
//! - Language-specific secure alternatives

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

static INSECURE_RANDOM: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"(?i)(Math\.random\(\)|random\.random\(\)|random\.randint|rand\(\)|srand\(|mt_rand|lcg_value|uniqid)").expect("valid regex")
});

/// Get secure alternative for each language
fn get_secure_alternative(ext: &str) -> &'static str {
    match ext {
        "py" => {
            "```python\n\
                 import secrets\n\
                 \n\
                 # For tokens/passwords\n\
                 token = secrets.token_urlsafe(32)\n\
                 \n\
                 # For random integers\n\
                 num = secrets.randbelow(100)\n\
                 \n\
                 # For random bytes\n\
                 data = secrets.token_bytes(16)\n\
                 ```"
        }
        "js" | "ts" => {
            "```javascript\n\
                        // Node.js\n\
                        const crypto = require('crypto');\n\
                        const token = crypto.randomBytes(32).toString('hex');\n\
                        \n\
                        // Browser\n\
                        const array = new Uint8Array(32);\n\
                        crypto.getRandomValues(array);\n\
                        ```"
        }
        "java" => {
            "```java\n\
                   import java.security.SecureRandom;\n\
                   \n\
                   SecureRandom random = new SecureRandom();\n\
                   byte[] bytes = new byte[32];\n\
                   random.nextBytes(bytes);\n\
                   ```"
        }
        "go" => {
            "```go\n\
                 import \"crypto/rand\"\n\
                 \n\
                 bytes := make([]byte, 32)\n\
                 rand.Read(bytes)\n\
                 ```"
        }
        "php" => {
            "```php\n\
                  // PHP 7+\n\
                  $bytes = random_bytes(32);\n\
                  $token = bin2hex($bytes);\n\
                  ```"
        }
        "rb" => {
            "```ruby\n\
                 require 'securerandom'\n\
                 \n\
                 token = SecureRandom.hex(32)\n\
                 ```"
        }
        "c" | "cpp" => {
            "```c\n\
                        // Linux\n\
                        #include <sys/random.h>\n\
                        getrandom(buffer, size, 0);\n\
                        \n\
                        // Or read from /dev/urandom\n\
                        ```"
        }
        _ => "Use your platform's cryptographic random number generator.",
    }
}

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

impl InsecureRandomDetector {
    crate::detectors::detector_new!(50);

    /// Check what the random value is used for
    fn analyze_usage(line: &str, surrounding: &str) -> (SecurityContext, String) {
        let combined = format!("{} {}", line, surrounding).to_lowercase();

        // Token/secret generation
        if combined.contains("token") || combined.contains("secret") || combined.contains("api_key")
        {
            return (
                SecurityContext::Token,
                "token/secret generation".to_string(),
            );
        }

        // Password/salt — "hash" alone is too broad (hashmap, hashCode, #hashtag);
        // require it alongside "password" or "salt" already covered above.
        if combined.contains("password")
            || combined.contains("salt")
            || combined.contains("password hash")
            || combined.contains("passwd")
        {
            return (
                SecurityContext::Password,
                "password/salt generation".to_string(),
            );
        }

        // Session/auth
        if combined.contains("session") || combined.contains("auth") || combined.contains("login") {
            return (
                SecurityContext::Session,
                "session/authentication".to_string(),
            );
        }

        // ID generation — only flag security-sensitive IDs, not trace/metric/display IDs
        if combined.contains("uuid") || combined.contains("identifier") {
            return (SecurityContext::ID, "ID generation".to_string());
        }
        // Security-sensitive ID patterns
        if (combined.contains("session_id")
            || combined.contains("sessionid")
            || combined.contains("user_id")
            || combined.contains("userid")
            || combined.contains("auth_id")
            || combined.contains("api_id"))
            && !combined.contains("trace")
            && !combined.contains("metric")
            && !combined.contains("display")
            && !combined.contains("record")
            && !combined.contains("internal")
            && !combined.contains("log")
        {
            return (SecurityContext::ID, "ID generation".to_string());
        }

        // Crypto — bare "key" is intentionally excluded: it matches cacheKey, fullKey,
        // mapKey, keyboard, monkey, .keys(), keyof, etc. and causes false positives
        // (e.g. cache-TTL jitter near redis.set(fullKey, ...)).
        // Only match unambiguous multi-word phrases that clearly indicate a crypto key.
        if combined.contains("crypto")
            || combined.contains("encrypt")
            || combined.contains("encryption key")
            || combined.contains("private key")
            || combined.contains("secret key")
            || combined.contains("signing key")
            || combined.contains("iv")
            || combined.contains("nonce")
        {
            return (
                SecurityContext::Crypto,
                "cryptographic operation".to_string(),
            );
        }

        // OTP/verification — use specific phrases only; bare "code" and bare "pin" are far
        // too broad (referralCode, errorCode, statusCode, encode/decode, zipcode, barcode,
        // pinned, spin, pinpoint would all false-positive).
        let is_otp = {
            // Bare "otp" is reasonably specific but guard against matching inside words
            // like "crypto" or "xotp" by requiring a word boundary (space, _, -, or start/end).
            let otp_word = combined.contains(" otp")
                || combined.contains("otp ")
                || combined.contains("otp_")
                || combined.contains("_otp")
                || combined.starts_with("otp")
                || combined.contains("\notp")
                || combined.contains("otpcode")
                || combined.contains("otp code")
                || combined.contains("otp_code");

            // "verification" alone is specific enough to keep
            let verification = combined.contains("verification");

            // Only fire on explicit multi-word "code" phrases that unambiguously mean OTP
            let code_phrase = combined.contains("verification code")
                || combined.contains("verificationcode")
                || combined.contains("one-time code")
                || combined.contains("one_time_code")
                || combined.contains("onetime code")
                || combined.contains("one-time-code")
                || combined.contains("confirmation code")
                || combined.contains("sms code")
                || combined.contains("login code")
                || combined.contains("signin code")
                || combined.contains("sign-in code")
                || combined.contains("mfa code");

            // 2FA / MFA signals
            let two_factor = combined.contains("2fa")
                || combined.contains("two-factor")
                || combined.contains("two_factor")
                || combined.contains("totp")
                || combined.contains("hotp");

            // Specific "pin" phrases — not bare "pin" (pinned, spin, pinpoint)
            let pin_phrase = combined.contains("pin code")
                || combined.contains("pincode")
                || combined.contains("pin_code")
                || combined.contains("enter pin")
                || combined.contains("enter your pin")
                || combined.contains("generate pin")
                || combined.contains("send pin");

            otp_word || verification || code_phrase || two_factor || pin_phrase
        };
        if is_otp {
            return (SecurityContext::OTP, "OTP/verification code".to_string());
        }

        (SecurityContext::Unknown, "unknown".to_string())
    }

    /// Find functions that use insecure random and are called by security-related code.
    /// Uses pre-built name→CodeNode map for O(1) lookup instead of O(N) graph scan.
    fn find_security_callers(
        graph: &dyn crate::graph::GraphQuery,
        func_name: &str,
        func_map: &std::collections::HashMap<String, crate::graph::store_models::CodeNode>,
    ) -> Vec<String> {
        let i = graph.interner();
        let mut security_callers = Vec::new();

        if let Some(func) = func_map.get(func_name) {
            let callers = graph.get_callers(func.qn(i));

            for caller in callers {
                let caller_lower = caller.node_name(i).to_lowercase();
                if caller_lower.contains("auth")
                    || caller_lower.contains("login")
                    || caller_lower.contains("token")
                    || caller_lower.contains("session")
                    || caller_lower.contains("password")
                    || caller_lower.contains("secret")
                {
                    security_callers.push(caller.node_name(i).to_string());
                }
            }
        }

        security_callers
    }
}

#[derive(PartialEq)]
enum SecurityContext {
    Token,
    Password,
    Session,
    ID,
    Crypto,
    OTP,
    Unknown,
}

impl Detector for InsecureRandomDetector {
    fn name(&self) -> &'static str {
        "insecure-random"
    }
    fn description(&self) -> &'static str {
        "Detects insecure random for security purposes"
    }

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

    fn file_extensions(&self) -> &'static [&'static str] {
        &["py", "js", "ts", "jsx", "tsx", "rb", "java", "go"]
    }

    fn detect(
        &self,
        ctx: &crate::detectors::analysis_context::AnalysisContext,
    ) -> Result<Vec<Finding>> {
        let graph = ctx.graph;
        let files = &ctx.as_file_provider();
        let _i = graph.interner();
        let mut findings = vec![];

        // Lazily build name→CodeNode map for O(1) lookup in find_security_callers.
        // Only populated on first use (most runs on large codebases find 0 matches).
        let mut func_map: Option<
            std::collections::HashMap<String, crate::graph::store_models::CodeNode>,
        > = None;

        for path in
            files.files_with_extensions(&["py", "js", "ts", "java", "go", "rb", "php", "c", "cpp"])
        {
            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;
            }

            let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");

            // Cheap pre-filter: skip files without random-related patterns
            let raw = match files.content(path) {
                Some(c) => c,
                None => continue,
            };
            if !raw.contains("random")
                && !raw.contains("rand(")
                && !raw.contains("srand(")
                && !raw.contains("mt_rand")
                && !raw.contains("lcg_value")
                && !raw.contains("uniqid")
            {
                continue;
            }

            if let Some(content) = files.masked_content(path) {
                let lines: Vec<&str> = content.lines().collect();

                for (i, line) in lines.iter().enumerate() {
                    let prev_line = if i > 0 { Some(lines[i - 1]) } else { None };
                    if crate::detectors::is_line_suppressed(line, prev_line) {
                        continue;
                    }

                    if INSECURE_RANDOM.is_match(line) {
                        let start = i.saturating_sub(5);
                        let end = (i + 5).min(lines.len());
                        let surrounding = lines[start..end].join(" ");

                        let (context, usage) = Self::analyze_usage(line, &surrounding);
                        let containing_func =
                            graph.find_function_at(&path_str, (i + 1) as u32).map(|f| {
                                f.node_name(crate::graph::interner::global_interner())
                                    .to_string()
                            });

                        // Check if function is called by security code
                        let security_callers = if let Some(ref func) = containing_func {
                            let map = func_map.get_or_insert_with(|| {
                                graph
                                    .get_functions()
                                    .into_iter()
                                    .map(|f| {
                                        (
                                            f.node_name(crate::graph::interner::global_interner())
                                                .to_string(),
                                            f,
                                        )
                                    })
                                    .collect()
                            });
                            Self::find_security_callers(graph, func, map)
                        } else {
                            vec![]
                        };

                        // Only flag if in security context
                        if context == SecurityContext::Unknown && security_callers.is_empty() {
                            continue;
                        }

                        // For ID context: only flag if it looks like a *security-critical* ID
                        // (session ID, CSRF token, auth token). Skip trace IDs, metric IDs,
                        // display IDs, record IDs, game logic IDs — these don't need crypto-secure random.
                        if context == SecurityContext::ID && security_callers.is_empty() {
                            let line_lower = line.to_lowercase();
                            let is_safe_id = line_lower.contains("traceid")
                                || line_lower.contains("trace_id")
                                || line_lower.contains("metricid")
                                || line_lower.contains("metric_id")
                                || line_lower.contains("displayid")
                                || line_lower.contains("display_id")
                                || line_lower.contains("recordid")
                                || line_lower.contains("record_id")
                                || line_lower.contains("gameid")
                                || line_lower.contains("game_id")
                                || line_lower.contains("itemid")
                                || line_lower.contains("item_id")
                                // session and auth IDs are security-critical; keep flagging those
                                ;
                            // Also skip if it's clearly a non-security random use:
                            // e.g. Math.random() for game logic, UI jitter, test data
                            let is_game_or_ui = line_lower.contains("game")
                                || line_lower.contains("jitter")
                                || line_lower.contains("color")
                                || line_lower.contains("animation")
                                || line_lower.contains("position")
                                || line_lower.contains("offset")
                                || line_lower.contains("delay");
                            if is_safe_id || is_game_or_ui {
                                continue;
                            }
                        }

                        // Calculate severity
                        let severity = match context {
                            SecurityContext::Crypto | SecurityContext::Password => {
                                Severity::Critical
                            }
                            SecurityContext::Token
                            | SecurityContext::Session
                            | SecurityContext::OTP => Severity::High,
                            SecurityContext::ID => Severity::Medium,
                            SecurityContext::Unknown if !security_callers.is_empty() => {
                                Severity::High
                            }
                            _ => Severity::Medium,
                        };

                        // Build notes
                        let mut notes = Vec::new();
                        notes.push(format!("🎯 Used for: {}", usage));
                        if let Some(func) = &containing_func {
                            notes.push(format!("📦 In function: `{}`", func));
                        }
                        if !security_callers.is_empty() {
                            notes.push(format!(
                                "⚠️ Called by security functions: {}",
                                security_callers.join(", ")
                            ));
                        }

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

                        let random_func = INSECURE_RANDOM
                            .find(line)
                            .map(|m| m.as_str())
                            .unwrap_or("random");

                        findings.push(Finding {
                            id: String::new(),
                            detector: "InsecureRandomDetector".to_string(),
                            severity,
                            title: format!("Insecure `{}` used for {}", random_func, usage),
                            description: format!(
                                "`{}` is not cryptographically secure and can be predicted by attackers.{}",
                                random_func, context_notes
                            ),
                            affected_files: vec![path.to_path_buf()],
                            line_start: Some((i + 1) as u32),
                            line_end: Some((i + 1) as u32),
                            suggested_fix: Some(format!(
                                "Use a cryptographically secure random number generator:\n\n{}",
                                get_secure_alternative(ext)
                            )),
                            estimated_effort: Some("15 minutes".to_string()),
                            category: Some("security".to_string()),
                            cwe_id: Some("CWE-330".to_string()),
                            why_it_matters: Some(
                                "Insecure random number generators (like Math.random or random.random) \
                                 use predictable algorithms. Attackers can often guess the output and \
                                 forge tokens, guess passwords, or bypass authentication.".to_string()
                            ),
                            ..Default::default()
                        });
                    }
                }
            }
        }

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

impl crate::detectors::RegisteredDetector for InsecureRandomDetector {
    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_insecure_random_in_security_context() {
        let store = GraphBuilder::new().freeze();
        let detector = InsecureRandomDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
            ("auth.py", "import random\n\ndef generate_token():\n    token = random.random()\n    return str(token)\n"),
        ]);
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "Should detect random.random() used for token generation"
        );
        assert!(
            findings.iter().any(|f| f.title.contains("random.random()")),
            "Finding should mention random.random(). Titles: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_no_finding_for_non_security_random() {
        let store = GraphBuilder::new().freeze();
        let detector = InsecureRandomDetector::new("/mock/repo");
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![(
                "simulation.py",
                "import random\n\ndef roll_dice():\n    return random.randint(1, 6)\n",
            )],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.is_empty(),
            "Should not flag random used in non-security context, but got: {:?}",
            findings.iter().map(|f| &f.title).collect::<Vec<_>>()
        );
    }

    /// Regression test: cache-TTL jitter near `fullKey` / `cacheKey` must NOT be flagged.
    /// The surrounding code mentions `redis.set(fullKey, ...)` which contains "key",
    /// and the bare-"key" trigger caused this to be classified as Crypto/Critical.
    #[test]
    fn test_no_finding_for_cache_ttl_jitter_near_cache_key() {
        let store = GraphBuilder::new().freeze();
        let detector = InsecureRandomDetector::new("/mock/repo");
        // Mirrors the real-world pattern that caused the false positive:
        // Math.random() used for TTL jitter, surrounded by lines referencing cacheKey/fullKey.
        let content = "\
const CACHE_TTL = 3600;\n\
\n\
async function cacheSet(fullKey, value) {\n\
  // Add jitter: +/- 10% to prevent thundering herd\n\
  const jitter = Math.floor(CACHE_TTL * 0.1 * (Math.random() * 2 - 1));\n\
  const ttl = CACHE_TTL + jitter;\n\
  await redis.set(fullKey, JSON.stringify(value), 'EX', ttl);\n\
}\n";
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("cache.js", content)],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            findings.is_empty(),
            "Should NOT flag Math.random() used for cache-TTL jitter near cacheKey/fullKey, but got: {:?}",
            findings.iter().map(|f| format!("{} ({:?})", f.title, f.severity)).collect::<Vec<_>>()
        );
    }

    /// Token/session contexts must still produce findings.
    #[test]
    fn test_still_flags_token_and_session_contexts() {
        let store = GraphBuilder::new().freeze();
        let detector = InsecureRandomDetector::new("/mock/repo");
        let content = "\
function generateSessionId() {\n\
  const session = Math.random().toString(36);\n\
  return session;\n\
}\n";
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("auth.js", content)],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "Should flag Math.random() used for session ID generation"
        );
    }

    /// Explicit crypto context (nonce / encrypt) must still fire.
    #[test]
    fn test_still_flags_explicit_crypto_context() {
        let store = GraphBuilder::new().freeze();
        let detector = InsecureRandomDetector::new("/mock/repo");
        let content = "\
function generateNonce() {\n\
  const nonce = Math.random().toString(16);\n\
  return nonce;\n\
}\n";
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("crypto_util.js", content)],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "Should flag Math.random() used near nonce (crypto context)"
        );
    }

    /// Unambiguous "encrypt" in a variable name must still trigger Crypto context.
    /// Note: analyze_usage operates on *masked* content (comments are blanked), so
    /// context must come from code — variable names, identifiers — not from comments.
    #[test]
    fn test_still_flags_encrypt_variable_name() {
        let store = GraphBuilder::new().freeze();
        let detector = InsecureRandomDetector::new("/mock/repo");
        // "encryptionKey" in the variable name contains "encrypt", which is
        // a distinctive Crypto signal and survives comment-masking.
        let content = "\
const encryptionKey = Math.random().toString(36);\n";
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("keygen.js", content)],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "Should flag Math.random() assigned to 'encryptionKey' (contains 'encrypt')"
        );
    }

    /// Token used for auth must produce a finding (regression guard for token path).
    #[test]
    fn test_still_flags_token_generation() {
        let store = GraphBuilder::new().freeze();
        let detector = InsecureRandomDetector::new("/mock/repo");
        let content = "\
const token = Math.random().toString(36).slice(2);\n";
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("token.js", content)],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "Should flag Math.random() assigned to 'token'"
        );
    }

    /// Regression test: Math.random() for a vanity waitlist display position near
    /// `referralCode` must NOT be classified as OTP/High.
    /// Reproduces the real-world FP from useReferral.ts:
    ///   `const referralCode = user.code; ... return 2847 + Math.floor(Math.random() * 3) + 1`
    #[test]
    fn test_no_finding_for_waitlist_position_near_referral_code() {
        let store = GraphBuilder::new().freeze();
        let detector = InsecureRandomDetector::new("/mock/repo");
        // The `referralCode` identifier (containing bare "code") is nearby but this is
        // a vanity UI display number, not an OTP or security-sensitive value.
        let content = "\
import { useUser } from './hooks';\n\
\n\
export function useReferral() {\n\
  const user = useUser();\n\
  const referralCode = user.referral_code;\n\
\n\
  function computeWaitlistPosition() {\n\
    // Vanity display number — not security-sensitive\n\
    return 2847 + Math.floor(Math.random() * 3) + 1;\n\
  }\n\
\n\
  return { referralCode, waitlistPosition: computeWaitlistPosition() };\n\
}\n";
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("useReferral.ts", content)],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        // Must produce no OTP/High finding — `referralCode` must not trigger OTP context
        let otp_findings: Vec<_> = findings
            .iter()
            .filter(|f| f.title.contains("OTP") || f.title.contains("verification"))
            .collect();
        assert!(
            otp_findings.is_empty(),
            "Should NOT flag Math.random() near `referralCode` as OTP/High. Got: {:?}",
            otp_findings
                .iter()
                .map(|f| format!("{} ({:?})", f.title, f.severity))
                .collect::<Vec<_>>()
        );
    }

    /// True-positive: Math.random() used to generate an actual OTP that is sent to the user.
    /// `sendVerificationCode(otp)` nearby — must still produce a High finding.
    #[test]
    fn test_still_flags_genuine_otp_generation() {
        let store = GraphBuilder::new().freeze();
        let detector = InsecureRandomDetector::new("/mock/repo");
        let content = "\
function generateOtp() {\n\
  const otp = Math.floor(Math.random() * 1000000);\n\
  sendVerificationCode(otp);\n\
  return otp;\n\
}\n";
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("otp.js", content)],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "Should flag Math.random() used for a genuine OTP (near sendVerificationCode and 'otp' identifier)"
        );
        // Severity must be High (OTP context)
        assert!(
            findings
                .iter()
                .any(|f| f.severity == crate::models::Severity::High),
            "OTP finding should be High severity. Got: {:?}",
            findings
                .iter()
                .map(|f| format!("{} ({:?})", f.title, f.severity))
                .collect::<Vec<_>>()
        );
    }

    /// True-positive: variable named `otpCode` (multi-word OTP phrase) near Math.random()
    /// must still flag, because `otpcode` is in our specific-phrase list.
    #[test]
    fn test_still_flags_otp_code_identifier() {
        let store = GraphBuilder::new().freeze();
        let detector = InsecureRandomDetector::new("/mock/repo");
        let content = "\
function generateOtpCode() {\n\
  const otpCode = Math.floor(Math.random() * 999999);\n\
  return otpCode;\n\
}\n";
        let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
            &store,
            vec![("mfa.ts", content)],
        );
        let findings = detector.detect(&ctx).expect("detection should succeed");
        assert!(
            !findings.is_empty(),
            "Should flag Math.random() near `otpCode` identifier"
        );
    }
}