flagrix 0.1.3 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -530,16 +530,24 @@ function getSeverityWeight(severity) {
530
530
  };
531
531
  return weights[severity];
532
532
  }
533
- function calculateRiskScore(findings) {
534
- let score = 0;
533
+ function calculateRawRiskScore(findings) {
534
+ const strongestBySignal = /* @__PURE__ */ new Map();
535
535
  for (const finding of findings) {
536
- score += getSeverityWeight(finding.severity);
536
+ const confidenceMultiplier = finding.confidence === "low" ? 0.25 : finding.confidence === "medium" ? 0.6 : 1;
537
+ const contribution = getSeverityWeight(finding.severity) * confidenceMultiplier;
538
+ const obfuscationHeuristic = finding.type === "OBFUSCATED_CODE" || finding.type === "CODE_INTEGRITY_ISSUE" && /minified|obfuscat/i.test(finding.description) || /^OBF_(?:BASE64|HEX|EVAL|NEW_FUNCTION|SETTIMEOUT|FROMCHARCODE|CHARCODE)/.test(finding.pattern ?? "");
539
+ const signal = obfuscationHeuristic ? "OBFUSCATION_HEURISTIC" : finding.pattern ?? finding.type;
540
+ strongestBySignal.set(signal, Math.max(strongestBySignal.get(signal) ?? 0, contribution));
537
541
  }
538
- return Math.min(1, score);
542
+ return [...strongestBySignal.values()].reduce((sum, contribution) => sum + contribution, 0);
543
+ }
544
+ function calculateRiskScore(findings) {
545
+ return Math.min(1, calculateRawRiskScore(findings));
539
546
  }
540
547
  function getRiskLevel(score, findings) {
541
- if (findings?.some((f) => f.severity === "critical"))
548
+ if (findings?.some((f) => f.severity === "critical" && (f.confidence ?? "high") === "high" || f.type === "SUSPICIOUS_DEPENDENCY" && (f.severity === "high" || f.severity === "critical") && (f.confidence ?? "high") === "high")) {
542
549
  return "high";
550
+ }
543
551
  if (score < RISK_THRESHOLDS.low)
544
552
  return "low";
545
553
  if (score < RISK_THRESHOLDS.high)
@@ -549,10 +557,10 @@ function getRiskLevel(score, findings) {
549
557
 
550
558
  // node_modules/@flagrix/scanner-core/dist/rules/rule-matcher.js
551
559
  var TEST_FILE_PATTERNS = [
552
- /__tests__\//i,
553
- /\/test\//i,
554
- /\/tests\//i,
555
- /\/spec\//i,
560
+ /(?:^|\/)__tests__\//i,
561
+ /(?:^|\/)tests?\//i,
562
+ /(?:^|\/)spec\//i,
563
+ /(?:^|\/)benchmarks?\//i,
556
564
  /\.test\.[jt]sx?$/i,
557
565
  /\.spec\.[jt]sx?$/i,
558
566
  /_test\.[jt]sx?$/i,
@@ -568,28 +576,99 @@ var TEST_FILE_PATTERNS = [
568
576
  function isTestFile(filePath) {
569
577
  return TEST_FILE_PATTERNS.some((pattern) => pattern.test(filePath));
570
578
  }
571
- function applyYaraRules(content, rules, filePath) {
579
+ var KEYBOARD_LISTENER = /(?:addEventListener\s*\(\s*['"](?:keydown|keypress|keyup)['"]|\.on(?:keydown|keypress|keyup)\s*=)/gi;
580
+ var KEY_VALUE = /\b[A-Za-z_$][\w$]*\.(?:key|code|keyCode|which)\b/gi;
581
+ var KEYBOARD_SINKS = [
582
+ /(?:fetch|axios\.(?:post|put|patch)|navigator\.sendBeacon|XMLHttpRequest|WebSocket)\b/gi,
583
+ /(?:localStorage|sessionStorage)\.setItem\s*\(/gi,
584
+ /(?:writeFile|writeFileSync|appendFile|appendFileSync)\s*\(/gi,
585
+ /\b(?:send|post|emit|upload|transmit|report|collect|capture|record|store|save)\w*\s*\([^)]*\b[A-Za-z_$][\w$]*\.(?:key|code|keyCode|which)\b/gi,
586
+ /(?:\+=|\.push\s*\()\s*\b[A-Za-z_$][\w$]*\.(?:key|code|keyCode|which)\b/gi
587
+ ];
588
+ var PLACEHOLDER_SECRET_WORDS = /(?:^|[-_.\s])(?:your|change|replace|example|dummy|placeholder|development|dev|test|sample|not[-_]?secret|changeme)(?:$|[-_.\s])/i;
589
+ function isObviousPlaceholderSecret(match) {
590
+ const quotedValue = match.match(/['"]([^'"]+)['"]\s*$/)?.[1];
591
+ if (!quotedValue)
592
+ return false;
593
+ return PLACEHOLDER_SECRET_WORDS.test(quotedValue);
594
+ }
595
+ function isDocumentedAwsExampleKey(match) {
596
+ return /\bAKIAIOSFODNN7EXAMPLE\b/.test(match);
597
+ }
598
+ var CASE_SENSITIVE_RULE_IDS = /* @__PURE__ */ new Set([
599
+ "HARDCODED_AWS_KEY",
600
+ "HARDCODED_GITHUB_TOKEN",
601
+ "HARDCODED_STRIPE_KEY",
602
+ "NETWORK_TELEGRAM_TOKEN"
603
+ ]);
604
+ function detectKeyboardCapture(content) {
605
+ const listeners = [...content.matchAll(KEYBOARD_LISTENER)];
606
+ for (const listener of listeners) {
607
+ const start = listener.index ?? 0;
608
+ const region = content.slice(start, start + 2e3);
609
+ if (!KEY_VALUE.test(region))
610
+ continue;
611
+ KEY_VALUE.lastIndex = 0;
612
+ const sink = KEYBOARD_SINKS.find((pattern) => {
613
+ pattern.lastIndex = 0;
614
+ return pattern.test(region);
615
+ });
616
+ if (sink) {
617
+ KEYBOARD_LISTENER.lastIndex = 0;
618
+ KEY_VALUE.lastIndex = 0;
619
+ sink.lastIndex = 0;
620
+ return { evidencePatterns: [KEYBOARD_LISTENER, KEY_VALUE, sink] };
621
+ }
622
+ }
623
+ KEYBOARD_LISTENER.lastIndex = 0;
624
+ KEY_VALUE.lastIndex = 0;
625
+ return null;
626
+ }
627
+ function applyYaraRules(content, rules, filePath, scopePath = filePath) {
572
628
  const findings = [];
573
- const isTest = isTestFile(filePath);
629
+ const isTest = isTestFile(scopePath);
574
630
  for (const rule of rules) {
575
631
  try {
576
- if (rule.fileExtensions && rule.fileExtensions.length > 0 && !rule.fileExtensions.some((ext) => filePath.endsWith(ext))) {
632
+ if (isTest)
633
+ continue;
634
+ if (rule.fileExtensions && rule.fileExtensions.length > 0 && !rule.fileExtensions.some((ext) => scopePath.endsWith(ext))) {
635
+ continue;
636
+ }
637
+ if (rule.fileNames && rule.fileNames.length > 0 && !rule.fileNames.includes(scopePath.split("/").pop() ?? scopePath)) {
577
638
  continue;
578
639
  }
579
- const regex = new RegExp(rule.pattern, "gi");
640
+ const regex = new RegExp(rule.pattern, CASE_SENSITIVE_RULE_IDS.has(rule.id) ? "g" : "gi");
580
641
  const matches2 = content.match(regex);
581
642
  const required = rule.minMatches && rule.minMatches > 1 ? rule.minMatches : 1;
582
643
  if (matches2 && matches2.length >= required) {
583
- if (isTest && rule.severity !== "critical") {
644
+ if (rule.id === "HARDCODED_AWS_KEY" && matches2.every(isDocumentedAwsExampleKey)) {
584
645
  continue;
585
646
  }
647
+ if (rule.id === "HARDCODED_API_KEY" && matches2.every(isObviousPlaceholderSecret)) {
648
+ findings.push({
649
+ severity: "low",
650
+ confidence: "high",
651
+ cloneBlocking: false,
652
+ type: "INSECURE_CONFIGURATION",
653
+ file: filePath,
654
+ pattern: rule.id,
655
+ description: "Predictable placeholder secret must be replaced before deployment",
656
+ evidence: collectEvidence(content, regex)
657
+ });
658
+ continue;
659
+ }
660
+ const contextName = rule.context ?? (rule.id === "EXFIL_KEYLOGGER" ? "keyboard-capture" : void 0);
661
+ const context = contextName === "keyboard-capture" ? detectKeyboardCapture(content) : null;
662
+ if (contextName && !context)
663
+ continue;
586
664
  findings.push({
587
665
  severity: rule.severity,
666
+ confidence: rule.confidence ?? "high",
588
667
  type: "MALWARE_SIGNATURE",
589
668
  file: filePath,
590
669
  pattern: rule.id,
591
670
  description: rule.description,
592
- evidence: collectEvidence(content, regex)
671
+ evidence: collectEvidence(content, context?.evidencePatterns ?? regex)
593
672
  });
594
673
  }
595
674
  } catch {
@@ -609,11 +688,44 @@ var PRIORITY_FILES = [
609
688
  ".yarnrc",
610
689
  "Makefile"
611
690
  ];
612
- var SCANNABLE_EXTENSIONS = [".js", ".ts", ".py", ".sh", ".ps1", ".bat", ".cmd"];
613
- var MAX_FILES_TO_SCAN = 50;
691
+ var SCANNABLE_EXTENSIONS = [
692
+ ".js",
693
+ ".jsx",
694
+ ".mjs",
695
+ ".cjs",
696
+ ".ts",
697
+ ".tsx",
698
+ ".py",
699
+ ".rb",
700
+ ".php",
701
+ ".go",
702
+ ".sh",
703
+ ".ps1",
704
+ ".psm1",
705
+ ".bat",
706
+ ".cmd",
707
+ ".vbs",
708
+ ".html",
709
+ ".htm"
710
+ ];
711
+ var MAX_FILES_TO_SCAN = 200;
712
+ var MAX_FILE_SIZE_BYTES = 1024 * 1024;
713
+ var MAX_SKIPPED_FILES_LISTED = 500;
614
714
  var NPM_DOWNLOAD_CACHE = /* @__PURE__ */ new Map();
615
715
  var NPM_CACHE_TTL_MS = 60 * 60 * 1e3;
616
716
  var NPM_HIGH_DOWNLOAD_THRESHOLD = 1e5;
717
+ function maskExceptInlineScripts(content) {
718
+ const masked = [...content].map((char) => char === "\n" || char === "\r" ? char : " ");
719
+ const script2 = /<script\b[^>]*>([\s\S]*?)<\/script\s*>/gi;
720
+ for (const match of content.matchAll(script2)) {
721
+ const body = match[1] ?? "";
722
+ const bodyOffset = (match.index ?? 0) + match[0].indexOf(body);
723
+ for (let index = 0; index < body.length; index++) {
724
+ masked[bodyOffset + index] = body[index];
725
+ }
726
+ }
727
+ return masked.join("");
728
+ }
617
729
  async function scanGitHubRepo(repo, options) {
618
730
  const findings = [];
619
731
  let filesScanned = 0;
@@ -656,10 +768,33 @@ async function scanGitHubRepo(repo, options) {
656
768
  throw await githubApiError(treeResponse);
657
769
  }
658
770
  const tree = await treeResponse.json();
659
- const filesToScan = tree.tree.filter((item) => item.type === "blob" && (PRIORITY_FILES.some((pf) => item.path.endsWith(pf)) || SCANNABLE_EXTENSIONS.some((ext) => item.path.endsWith(ext)))).slice(0, MAX_FILES_TO_SCAN);
771
+ const skippedFiles = [];
772
+ let skippedCount = 0;
773
+ const skip = (path, reason) => {
774
+ skippedCount++;
775
+ if (skippedFiles.length < MAX_SKIPPED_FILES_LISTED) {
776
+ skippedFiles.push({ path, reason });
777
+ }
778
+ };
779
+ const filesToScan = [];
780
+ for (const item of tree.tree) {
781
+ if (item.type !== "blob")
782
+ continue;
783
+ const eligible = PRIORITY_FILES.some((pf) => item.path.endsWith(pf)) || SCANNABLE_EXTENSIONS.some((ext) => item.path.endsWith(ext));
784
+ if (!eligible) {
785
+ skip(item.path, "unsupported-type");
786
+ } else if (item.size !== void 0 && item.size > MAX_FILE_SIZE_BYTES) {
787
+ skip(item.path, "too-large");
788
+ } else if (filesToScan.length >= MAX_FILES_TO_SCAN) {
789
+ skip(item.path, "over-file-limit");
790
+ } else {
791
+ filesToScan.push(item);
792
+ }
793
+ }
660
794
  const hiddenFiles = tree.tree.filter((item) => item.path.startsWith(".") && !item.path.startsWith(".github") && !item.path.startsWith(".git") && item.type === "blob");
661
795
  for (const hidden of hiddenFiles) {
662
- if (hidden.path.includes("backdoor") || hidden.path.includes("payload") || hidden.path.includes("shell")) {
796
+ const basename = hidden.path.split("/").pop() ?? hidden.path;
797
+ if (/^\.(?:backdoor|payload|reverse[-_]?shell)(?:\.|$)/i.test(basename)) {
663
798
  findings.push({
664
799
  severity: "high",
665
800
  type: "HIDDEN_FILE",
@@ -673,16 +808,22 @@ async function scanGitHubRepo(repo, options) {
673
808
  const yaraRules = options.signatures.yaraRules;
674
809
  const loadedRuleIds = new Set(yaraRules.map((r) => r.id));
675
810
  const fileContents = [];
811
+ const scannedFiles = [];
676
812
  for (const file of filesToScan) {
677
- filesScanned++;
678
813
  const contentUrl = `https://api.github.com/repos/${repo.owner}/${repo.repo}/contents/${file.path}?ref=${commitSha}`;
679
814
  const contentResponse = await fetch(contentUrl, { headers });
680
- if (!contentResponse.ok)
815
+ if (!contentResponse.ok) {
816
+ skip(file.path, "fetch-failed");
681
817
  continue;
818
+ }
819
+ filesScanned++;
820
+ scannedFiles.push(file.path);
682
821
  const fileData = await contentResponse.json();
683
822
  const content = atob(fileData.content || "");
684
- const isJsTs = /\.(?:js|ts)$/.test(file.path);
685
- let matchable = isJsTs ? maskRegexLiterals(content) : content;
823
+ const isHtml = /\.html?$/i.test(file.path);
824
+ const isJsTs = /\.(?:[cm]?js|ts|[jt]sx)$/i.test(file.path);
825
+ const scriptContent = isHtml ? maskExceptInlineScripts(content) : content;
826
+ let matchable = isJsTs || isHtml ? maskRegexLiterals(scriptContent) : scriptContent;
686
827
  if (isJsTs && isTestFile(file.path)) {
687
828
  matchable = maskStringLiterals(matchable);
688
829
  }
@@ -704,7 +845,8 @@ async function scanGitHubRepo(repo, options) {
704
845
  patternsMatched += pyFindings.length;
705
846
  }
706
847
  if (SCANNABLE_EXTENSIONS.some((ext) => file.path.endsWith(ext))) {
707
- const yaraFindings = applyYaraRules(matchable, yaraRules, file.path);
848
+ const ruleScopePath = isHtml ? `${file.path}.js` : file.path;
849
+ const yaraFindings = applyYaraRules(matchable, yaraRules, file.path, ruleScopePath);
708
850
  findings.push(...yaraFindings);
709
851
  patternsMatched += yaraFindings.length;
710
852
  const obfuscationFindings = detectObfuscation(matchable, file.path, loadedRuleIds);
@@ -753,10 +895,15 @@ async function scanGitHubRepo(repo, options) {
753
895
  const integrityFindings = await detectCodeIntegrityIssues(fileContents, allPaths, repo);
754
896
  findings.push(...integrityFindings);
755
897
  patternsMatched += integrityFindings.length;
898
+ const rawRiskScore = calculateRawRiskScore(findings);
756
899
  const riskScore = calculateRiskScore(findings);
757
900
  const riskLevel = getRiskLevel(riskScore, findings);
901
+ const cloneBlockingFindings = findings.filter((finding) => finding.cloneBlocking !== false);
902
+ const cloneRiskScore = calculateRiskScore(cloneBlockingFindings);
903
+ const cloneRiskLevel = getRiskLevel(cloneRiskScore, cloneBlockingFindings);
758
904
  return {
759
905
  riskScore,
906
+ rawRiskScore,
760
907
  riskLevel,
761
908
  factors: findings.map((f) => ({
762
909
  factor: f.type,
@@ -766,9 +913,17 @@ async function scanGitHubRepo(repo, options) {
766
913
  disclaimer: DEFAULT_DISCLAIMER,
767
914
  repo,
768
915
  commitSha,
769
- scanSummary: { filesScanned, patternsMatched, dependenciesChecked },
916
+ scanSummary: {
917
+ filesScanned,
918
+ patternsMatched,
919
+ dependenciesChecked,
920
+ scannedFiles,
921
+ skippedFiles,
922
+ skippedCount,
923
+ treeTruncated: tree.truncated
924
+ },
770
925
  findings,
771
- safeToClone: riskLevel === "low",
926
+ safeToClone: cloneRiskLevel === "low",
772
927
  scannedAt: /* @__PURE__ */ new Date()
773
928
  };
774
929
  } catch (error) {
@@ -780,11 +935,12 @@ async function scanPackageJson(content, maliciousPackages, filePath) {
780
935
  try {
781
936
  const pkg = JSON.parse(content);
782
937
  const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
783
- for (const [name] of Object.entries(allDeps)) {
938
+ for (const [name, declaredVersion] of Object.entries(allDeps)) {
784
939
  const malicious = maliciousPackages.find((m) => m.name === name);
785
- if (malicious) {
940
+ if (malicious && isAffectedPackageVersion(malicious, declaredVersion)) {
786
941
  findings.push({
787
942
  severity: malicious.severity,
943
+ confidence: "high",
788
944
  type: "SUSPICIOUS_DEPENDENCY",
789
945
  file: filePath,
790
946
  package: name,
@@ -812,6 +968,23 @@ async function scanPackageJson(content, maliciousPackages, filePath) {
812
968
  }
813
969
  return findings;
814
970
  }
971
+ function isAffectedPackageVersion(malicious, declaredVersion) {
972
+ const affected = malicious.versions ?? (malicious.version ? [malicious.version] : []);
973
+ if (affected.length === 0)
974
+ return true;
975
+ if (typeof declaredVersion !== "string")
976
+ return false;
977
+ let specifier = declaredVersion.trim();
978
+ if (specifier.startsWith("workspace:"))
979
+ specifier = specifier.slice("workspace:".length);
980
+ const npmAlias = specifier.match(/^npm:.+@([^@]+)$/);
981
+ if (npmAlias)
982
+ specifier = npmAlias[1];
983
+ return specifier.split(/\s*\|\|\s*/).some((part) => {
984
+ const normalized = part.trim().replace(/^[=v~^\s]+/, "");
985
+ return affected.includes(normalized);
986
+ });
987
+ }
815
988
  function checkPostinstallScripts(content, filePath) {
816
989
  const findings = [];
817
990
  try {
@@ -854,6 +1027,7 @@ function scanPythonDeps(content, maliciousPackages, filePath) {
854
1027
  if (malicious) {
855
1028
  findings.push({
856
1029
  severity: malicious.severity,
1030
+ confidence: "high",
857
1031
  type: "SUSPICIOUS_DEPENDENCY",
858
1032
  file: filePath,
859
1033
  package: name,
@@ -947,12 +1121,13 @@ function detectObfuscation(content, filePath, coveredRuleIds = /* @__PURE__ */ n
947
1121
  const maxLength = Math.max(...suspiciousLines.map((l) => l.length));
948
1122
  const linesWithMaliciousCode = suspiciousLines.filter((l) => l.hasMaliciousPattern);
949
1123
  const lineDetails = suspiciousLines.slice(0, 3).map((l) => `Line ${l.lineNum} (${l.length.toLocaleString()} chars${l.hasMaliciousPattern ? ", contains suspicious code" : ""})`).join(", ");
950
- const severity = linesWithMaliciousCode.length > 0 ? "critical" : "high";
1124
+ const severity = "medium";
951
1125
  const firstLine = lines[suspiciousLines[0].lineNum - 1];
952
1126
  const codeSnippet = extractCodeSnippet(firstLine);
953
1127
  const codeExplanation = explainSuspiciousCode(firstLine, "OBFUSCATED_CODE");
954
1128
  findings.push({
955
1129
  severity,
1130
+ confidence: linesWithMaliciousCode.length > 0 ? "medium" : "low",
956
1131
  type: "OBFUSCATED_CODE",
957
1132
  file: filePath,
958
1133
  line: suspiciousLines[0].lineNum,
@@ -1186,31 +1361,54 @@ function detectHardcodedSecrets(content, filePath, coveredRuleIds = /* @__PURE__
1186
1361
  if (isTestFile(filePath))
1187
1362
  return findings;
1188
1363
  const secretPatterns = [
1189
- { pattern: /(?:api[_-]?key|apikey)\s*[:=]\s*['"]([^'"]{20,})['"]/gi, type: "API Key", severity: "critical", ruleId: "HARDCODED_API_KEY" },
1190
- { pattern: /(?:secret[_-]?key|secret)\s*[:=]\s*['"]([^'"]{20,})['"]/gi, type: "Secret Key", severity: "critical", ruleId: "HARDCODED_API_KEY" },
1191
- { pattern: /(?:password|passwd|pwd)\s*[:=]\s*['"]([^'"]{8,})['"]/gi, type: "Password", severity: "critical", ruleId: null },
1192
- { pattern: /(?:token|auth[_-]?token)\s*[:=]\s*['"]([^'"]{20,})['"]/gi, type: "Auth Token", severity: "critical", ruleId: "HARDCODED_API_KEY" },
1193
- { pattern: /(?:private[_-]?key|privatekey)\s*[:=]\s*['"]([^'"]{20,})['"]/gi, type: "Private Key", severity: "critical", ruleId: "HARDCODED_API_KEY" },
1364
+ { pattern: /(?:api[_-]?key|apikey)\s*[:=]\s*['"]([^'"]{20,})['"]/gi, type: "API Key", severity: "high", ruleId: "HARDCODED_API_KEY" },
1365
+ { pattern: /(?:secret[_-]?key|secret)\s*[:=]\s*['"]([^'"]{20,})['"]/gi, type: "Secret Key", severity: "high", ruleId: "HARDCODED_API_KEY" },
1366
+ { pattern: /(?:password|passwd|pwd)\s*[:=]\s*['"]([^'"]{8,})['"]/gi, type: "Password", severity: "medium", ruleId: null },
1367
+ { pattern: /(?:token|auth[_-]?token)\s*[:=]\s*['"]([^'"]{20,})['"]/gi, type: "Auth Token", severity: "high", ruleId: "HARDCODED_API_KEY" },
1368
+ { pattern: /(?:private[_-]?key|privatekey)\s*[:=]\s*['"]([^'"]{20,})['"]/gi, type: "Private Key", severity: "high", ruleId: "HARDCODED_API_KEY" },
1194
1369
  { pattern: /AKIA[0-9A-Z]{16}/g, type: "AWS Access Key", severity: "critical", ruleId: "HARDCODED_AWS_KEY" },
1195
1370
  { pattern: /ghp_[a-zA-Z0-9]{36}/g, type: "GitHub Personal Access Token", severity: "critical", ruleId: "HARDCODED_GITHUB_TOKEN" },
1196
1371
  { pattern: /gho_[a-zA-Z0-9]{36}/g, type: "GitHub OAuth Token", severity: "critical", ruleId: "HARDCODED_GITHUB_TOKEN" },
1197
1372
  { pattern: /sk_live_[a-zA-Z0-9]{24,}/g, type: "Stripe Live Key", severity: "critical", ruleId: "HARDCODED_STRIPE_KEY" },
1198
- { pattern: /(?:mongodb|mongo)[+:\/\/]{0,6}[^@\s]+:[^@\s]+@/gi, type: "MongoDB Connection String", severity: "high", ruleId: "HARDCODED_DB_CONNECTION" },
1199
- { pattern: /postgres:\/\/[^@\s]+:[^@\s]+@/gi, type: "PostgreSQL Connection String", severity: "high", ruleId: "HARDCODED_DB_CONNECTION" }
1373
+ { pattern: /(?:mongodb|mongo)[+:\/\/]{0,6}[^@\s]+:[^@\s]+@/gi, type: "MongoDB Connection String", severity: "medium", ruleId: "HARDCODED_DB_CONNECTION" },
1374
+ { pattern: /postgres:\/\/[^@\s]+:[^@\s]+@/gi, type: "PostgreSQL Connection String", severity: "medium", ruleId: "HARDCODED_DB_CONNECTION" }
1200
1375
  ].filter(({ ruleId }) => !ruleId || !coveredRuleIds.has(ruleId));
1201
1376
  const foundSecrets = [];
1202
1377
  const matchedRegexes = [];
1378
+ const placeholderRegexes = [];
1203
1379
  for (const { pattern, type, severity } of secretPatterns) {
1204
1380
  const matches2 = content.match(pattern);
1205
1381
  if (matches2 && matches2.length > 0) {
1206
- foundSecrets.push({ type, match: matches2[0].substring(0, 50) + "...", severity });
1382
+ const genericSecret = ["API Key", "Secret Key", "Auth Token", "Private Key"].includes(type);
1383
+ const actionableMatches = type === "AWS Access Key" ? matches2.filter((match) => !isDocumentedAwsExampleKey(match)) : genericSecret ? matches2.filter((match) => !isObviousPlaceholderSecret(match)) : matches2;
1384
+ if (actionableMatches.length === 0) {
1385
+ placeholderRegexes.push(pattern);
1386
+ continue;
1387
+ }
1388
+ foundSecrets.push({
1389
+ type,
1390
+ match: actionableMatches[0].substring(0, 50) + "...",
1391
+ severity
1392
+ });
1207
1393
  matchedRegexes.push(pattern);
1208
1394
  }
1209
1395
  }
1396
+ if (placeholderRegexes.length > 0) {
1397
+ findings.push({
1398
+ severity: "low",
1399
+ confidence: "high",
1400
+ cloneBlocking: false,
1401
+ type: "INSECURE_CONFIGURATION",
1402
+ file: filePath,
1403
+ description: "Predictable placeholder secret must be replaced before deployment",
1404
+ evidence: collectEvidence(content, placeholderRegexes)
1405
+ });
1406
+ }
1210
1407
  if (foundSecrets.length > 0) {
1211
- const highestSeverity = foundSecrets.some((s) => s.severity === "critical") ? "critical" : "high";
1408
+ const highestSeverity = foundSecrets.some((s) => s.severity === "critical") ? "critical" : foundSecrets.some((s) => s.severity === "high") ? "high" : "medium";
1212
1409
  findings.push({
1213
1410
  severity: highestSeverity,
1411
+ confidence: highestSeverity === "critical" ? "high" : "medium",
1214
1412
  type: "HARDCODED_SECRETS",
1215
1413
  file: filePath,
1216
1414
  description: `Hardcoded credentials detected: ${foundSecrets.map((s) => s.type).join(", ")}`,
@@ -1229,7 +1427,7 @@ function detectNetworkPatterns(content, filePath, coveredRuleIds = /* @__PURE__
1229
1427
  // Valid public IPv4 only: each octet bounded 0–255, not embedded in a longer
1230
1428
  // dotted/number sequence (avoids flagging version strings like "1.2.3.4.5" or
1231
1429
  // impossible IPs like "999.999.999.999"), and excluding private/link-local ranges.
1232
- { pattern: /(?:https?:\/\/)?(?<![\d.])(?!(?:127\.|10\.|192\.168\.|169\.254\.|172\.(?:1[6-9]|2\d|3[01])\.))(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}(?![\d.])(?::\d{1,5})?/g, type: "Hardcoded IP Address", severity: "high" },
1430
+ { pattern: /(?:https?:\/\/)?(?<![\d.])(?!(?:0\.|127\.|10\.|192\.168\.|169\.254\.|172\.(?:1[6-9]|2\d|3[01])\.))(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}(?![\d.])(?::\d{1,5})?/g, type: "Hardcoded IP Address", severity: "medium", confidence: "low" },
1233
1431
  { pattern: /https?:\/\/discord(?:app)?\.com\/api\/webhooks\/\d+\/[a-zA-Z0-9_-]+/gi, type: "Discord Webhook", severity: "critical", ruleId: "NETWORK_DISCORD_WEBHOOK" },
1234
1432
  { pattern: /\d{8,10}:[a-zA-Z0-9_-]{35}/g, type: "Telegram Bot Token", severity: "high", ruleId: "NETWORK_TELEGRAM_TOKEN" },
1235
1433
  { pattern: /(?:pastebin\.com|hastebin\.com|paste\.ee)\/[a-zA-Z0-9]+/gi, type: "Pastebin URL", severity: "medium", ruleId: "NETWORK_PASTEBIN" },
@@ -1237,7 +1435,7 @@ function detectNetworkPatterns(content, filePath, coveredRuleIds = /* @__PURE__
1237
1435
  { pattern: /https?:\/\/[a-zA-Z0-9-]+\.(?:tk|ml|ga|cf|gq|onion|xyz)(?:\/|$)/gi, type: "Suspicious Domain TLD", severity: "high", ruleId: "NETWORK_SUSPICIOUS_TLD" },
1238
1436
  { pattern: /https?:\/\/[a-zA-Z0-9-]+\.ngrok\.io/gi, type: "Ngrok Tunnel", severity: "medium", ruleId: "NETWORK_NGROK_TUNNEL" }
1239
1437
  ].filter((p) => !("ruleId" in p) || !coveredRuleIds.has(p.ruleId));
1240
- for (const { pattern, type, severity } of suspiciousPatterns) {
1438
+ for (const { pattern, type, severity, confidence } of suspiciousPatterns) {
1241
1439
  const matches2 = content.match(pattern);
1242
1440
  if (matches2 && matches2.length > 0) {
1243
1441
  const validMatches = matches2.filter((m) => {
@@ -1248,6 +1446,7 @@ function detectNetworkPatterns(content, filePath, coveredRuleIds = /* @__PURE__
1248
1446
  if (validMatches.length > 0) {
1249
1447
  findings.push({
1250
1448
  severity,
1449
+ confidence: confidence ?? "high",
1251
1450
  type: "NETWORK_COMMUNICATION",
1252
1451
  file: filePath,
1253
1452
  description: `Suspicious network communication detected: ${type} (${validMatches.length} occurrence${validMatches.length > 1 ? "s" : ""})`,
@@ -1302,11 +1501,9 @@ function detectDataExfiltration(content, filePath, coveredRuleIds = /* @__PURE__
1302
1501
  return findings;
1303
1502
  const exfiltrationPatterns = [
1304
1503
  { pattern: /navigator\.clipboard\.read(?:Text)?\s*\(/gi, type: "Clipboard Access", severity: "high", ruleId: "EXFIL_CLIPBOARD" },
1305
- { pattern: /localStorage\.getItem|sessionStorage\.getItem/gi, type: "Storage Access", severity: "medium", ruleId: null },
1306
1504
  { pattern: /document\.cookie/gi, type: "Cookie Access", severity: "high", ruleId: "EXFIL_COOKIE" },
1307
- { pattern: /(?:addEventListener|on)\s*\(\s*['"](?:keydown|keypress|keyup)['"]/gi, type: "Keylogger Pattern", severity: "critical", ruleId: "EXFIL_KEYLOGGER" },
1308
1505
  { pattern: /(?:input|password|email)[\w-]*\.value/gi, type: "Form Data Access", severity: "medium", ruleId: null },
1309
- { pattern: /new\s+FormData\s*\([^)]*\)[\s\S]{0,100}(?:fetch|axios|XMLHttpRequest)/gi, type: "Form Data Transmission", severity: "high", ruleId: null }
1506
+ { pattern: /new\s+FormData\s*\([^)]*\)[\s\S]{0,100}(?:fetch|axios|XMLHttpRequest)/gi, type: "Form Data Transmission", severity: "medium", ruleId: null }
1310
1507
  ].filter(({ ruleId }) => !ruleId || !coveredRuleIds.has(ruleId));
1311
1508
  const detectedPatterns = [];
1312
1509
  const matchedRegexes = [];
@@ -1315,14 +1512,34 @@ function detectDataExfiltration(content, filePath, coveredRuleIds = /* @__PURE__
1315
1512
  if (pattern.test(content)) {
1316
1513
  detectedPatterns.push(type);
1317
1514
  matchedRegexes.push(pattern);
1318
- if (severity === "critical" || severity === "high" && highestSeverity !== "critical") {
1319
- highestSeverity = severity;
1320
- }
1515
+ if (severity === "high")
1516
+ highestSeverity = "high";
1517
+ }
1518
+ }
1519
+ const sensitiveStorageRead = /(?:localStorage|sessionStorage)\.getItem\s*\(\s*['"][^'"]*(?:token|secret|password|credential|session|auth|wallet|seed|private)[^'"]*['"]\s*\)/gi;
1520
+ for (const match of content.matchAll(sensitiveStorageRead)) {
1521
+ const start = match.index ?? 0;
1522
+ const region = content.slice(start, start + 2e3);
1523
+ const networkSink = /(?:fetch\s*\(|axios\.(?:post|put|patch)\s*\(|navigator\.sendBeacon\s*\(|XMLHttpRequest|WebSocket)/gi;
1524
+ if (networkSink.test(region)) {
1525
+ detectedPatterns.push("Sensitive Storage Transmission");
1526
+ matchedRegexes.push(sensitiveStorageRead, networkSink);
1527
+ highestSeverity = "high";
1528
+ break;
1529
+ }
1530
+ }
1531
+ if (!coveredRuleIds.has("EXFIL_KEYLOGGER")) {
1532
+ const keyboardCapture = detectKeyboardCapture(content);
1533
+ if (keyboardCapture) {
1534
+ detectedPatterns.push("Keyboard Capture and Transmission");
1535
+ matchedRegexes.push(...keyboardCapture.evidencePatterns);
1536
+ highestSeverity = "critical";
1321
1537
  }
1322
1538
  }
1323
1539
  if (detectedPatterns.length > 0) {
1324
1540
  findings.push({
1325
1541
  severity: highestSeverity,
1542
+ confidence: highestSeverity === "medium" ? "low" : "high",
1326
1543
  type: "DATA_EXFILTRATION",
1327
1544
  file: filePath,
1328
1545
  description: `Data exfiltration patterns detected: ${detectedPatterns.join(", ")}`,
@@ -1339,7 +1556,6 @@ function detectBackdoors(content, filePath, coveredRuleIds = /* @__PURE__ */ new
1339
1556
  { pattern: /exec\s*\(\s*(?:request|req)(?:\.|\.body|\.query)/gi, type: "Command Injection Endpoint", severity: "critical", ruleId: "BACKDOOR_RCE_ENDPOINT" },
1340
1557
  { pattern: /require\s*\(\s*(?:request|req)(?:\.|\.body|\.query)/gi, type: "Dynamic Require", severity: "critical", ruleId: "BACKDOOR_DYNAMIC_REQUIRE" },
1341
1558
  { pattern: /new\s+Function\s*\([^)]*(?:request|req)/gi, type: "Dynamic Function from Request", severity: "critical", ruleId: null },
1342
- { pattern: /(?:admin|debug|backdoor|shell)[\w]*\s*[:=]\s*(?:true|1|"[^"]*")\s*(?:\/\/|#)?\s*(?:TODO|FIXME|HACK)?/gi, type: "Debug/Admin Flag", severity: "high", ruleId: null },
1343
1559
  { pattern: /(?:password|auth)\s*(?:===?|==)\s*['"][^'"]{0,20}['"]\s*\)/gi, type: "Hardcoded Auth Bypass", severity: "critical", ruleId: "BACKDOOR_HARDCODED_AUTH" }
1344
1560
  ].filter(({ ruleId }) => !ruleId || !coveredRuleIds.has(ruleId));
1345
1561
  for (const { pattern, type, severity } of backdoorPatterns) {
@@ -1356,6 +1572,21 @@ function detectBackdoors(content, filePath, coveredRuleIds = /* @__PURE__ */ new
1356
1572
  });
1357
1573
  }
1358
1574
  }
1575
+ const exposedFlaskDebugger = /app\.run\s*\((?=[\s\S]{0,400}\bdebug\s*=\s*True)(?=[\s\S]{0,400}\bhost\s*=\s*['"]0\.0\.0\.0['"])[\s\S]{0,400}\)/gi;
1576
+ const flaskDebugEnabled = /\bdebug\s*=\s*True/gi;
1577
+ const wildcardBind = /\bhost\s*=\s*['"]0\.0\.0\.0['"]/gi;
1578
+ if (exposedFlaskDebugger.test(content)) {
1579
+ findings.push({
1580
+ severity: "low",
1581
+ confidence: "high",
1582
+ cloneBlocking: false,
1583
+ type: "INSECURE_CONFIGURATION",
1584
+ file: filePath,
1585
+ description: "Flask debugger is exposed on all network interfaces; disable debug mode before deployment",
1586
+ evidence: collectEvidence(content, [flaskDebugEnabled, wildcardBind]),
1587
+ codeExplanation: "Flask's interactive debugger can execute code and must not be exposed in production. This is a deployment configuration issue, not a repository backdoor."
1588
+ });
1589
+ }
1359
1590
  return findings;
1360
1591
  }
1361
1592
  function detectSupplyChainRisks(content, filePath) {
@@ -1404,14 +1635,14 @@ function detectSuspiciousFileAccess(content, filePath, coveredRuleIds = /* @__PU
1404
1635
  { pattern: /(?:fs\.read|readFileSync|readFile)\s*\([^)]*(?:\.ssh|\.aws|\.gnupg|\.docker|id_rsa|credentials)/gi, type: "SSH/AWS Credentials Access", severity: "critical", ruleId: "FILE_ACCESS_CREDENTIALS" },
1405
1636
  { pattern: /(?:fs\.read|readFileSync|readFile)\s*\([^)]*(?:etc\/passwd|etc\/shadow|\.bash_history|\.zsh_history)/gi, type: "System File Access", severity: "critical", ruleId: "FILE_ACCESS_SYSTEM" },
1406
1637
  { pattern: /(?:fs\.read|readFileSync|readFile)\s*\([^)]*(?:Chrome|Firefox|Safari|Edge)[\w\s/\\]*(?:Cookies|Login|History)/gi, type: "Browser Data Access", severity: "critical", ruleId: "FILE_ACCESS_BROWSER_DATA" },
1407
- { pattern: /(?:fs\.write|writeFileSync|writeFile)\s*\([^)]*(?:\/etc|\/sys|\/bin|C:\\\\Windows)/gi, type: "System Directory Write", severity: "critical", ruleId: null },
1408
- { pattern: /(?:fs\.unlink|unlinkSync|rmSync|rm\s+-rf)/gi, type: "File Deletion", severity: "medium", ruleId: null }
1638
+ { pattern: /(?:fs\.write|writeFileSync|writeFile)\s*\([^)]*(?:\/etc|\/sys|\/bin|C:\\\\Windows)/gi, type: "System Directory Write", severity: "medium", ruleId: null }
1409
1639
  ].filter(({ ruleId }) => !ruleId || !coveredRuleIds.has(ruleId));
1410
1640
  for (const { pattern, type, severity } of fileAccessPatterns) {
1411
1641
  const matches2 = content.match(pattern);
1412
1642
  if (matches2) {
1413
1643
  findings.push({
1414
1644
  severity,
1645
+ confidence: severity === "critical" ? "high" : "medium",
1415
1646
  type: "SUSPICIOUS_FILE_ACCESS",
1416
1647
  file: filePath,
1417
1648
  description: `Suspicious file access detected: ${type}`,
@@ -1421,6 +1652,18 @@ function detectSuspiciousFileAccess(content, filePath, coveredRuleIds = /* @__PU
1421
1652
  });
1422
1653
  }
1423
1654
  }
1655
+ const destructiveDeletion = /(?:rm\s+-rf\s+(?:["']?(?:\/|~|\$HOME)(?!\/?(?:tmp|var\/tmp)\b)|[^\n]*[?*])|(?:fs\.)?(?:unlink|unlinkSync|rmSync)\s*\([^\n)]*(?:\.ssh|\.aws|\.gnupg|\.docker|\/etc|\/usr|\/home|Users[\\/]))/gi;
1656
+ if (destructiveDeletion.test(content)) {
1657
+ findings.push({
1658
+ severity: "medium",
1659
+ confidence: "medium",
1660
+ type: "SUSPICIOUS_FILE_ACCESS",
1661
+ file: filePath,
1662
+ description: "Suspicious file access detected: Destructive File Deletion",
1663
+ codeExplanation: "\u{1F4C1} Deletes a broad or sensitive user/system path. Verify that the target cannot escape an application-owned directory.",
1664
+ evidence: collectEvidence(content, destructiveDeletion)
1665
+ });
1666
+ }
1424
1667
  return findings;
1425
1668
  }
1426
1669
  async function detectCodeIntegrityIssues(files, allPaths, _repo) {
@@ -1437,6 +1680,7 @@ async function detectCodeIntegrityIssues(files, allPaths, _repo) {
1437
1680
  if (shortVars / totalVars > 0.3) {
1438
1681
  findings.push({
1439
1682
  severity: "medium",
1683
+ confidence: "low",
1440
1684
  type: "CODE_INTEGRITY_ISSUE",
1441
1685
  file: file.path,
1442
1686
  description: "Minified/obfuscated code detected in source repository",
package/dist/cli.js CHANGED
@@ -11,7 +11,7 @@ import {
11
11
  scanGitHubRepo,
12
12
  scanGitHubUser,
13
13
  wantJson
14
- } from "./chunk-BOICDXGY.js";
14
+ } from "./chunk-YU3IO4GZ.js";
15
15
 
16
16
  // src/cli.ts
17
17
  import { parseArgs } from "util";
@@ -132,7 +132,7 @@ async function main() {
132
132
  }
133
133
  return runScanUser(target, { json: values.json, token: values.token });
134
134
  case "mcp": {
135
- const { runMcp } = await import("./mcp-CWPBDBCD.js");
135
+ const { runMcp } = await import("./mcp-A3JZBGAA.js");
136
136
  return runMcp();
137
137
  }
138
138
  default:
@@ -7,7 +7,7 @@ import {
7
7
  scanGitHubRepo,
8
8
  scanGitHubUser,
9
9
  securityScore
10
- } from "./chunk-BOICDXGY.js";
10
+ } from "./chunk-YU3IO4GZ.js";
11
11
 
12
12
  // src/commands/mcp.ts
13
13
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "flagrix",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "description": "Scan GitHub repos and profiles for malware before you clone — CLI and MCP server for the Flagrix scanner",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -43,6 +43,8 @@
43
43
  "test": "vitest run",
44
44
  "test:watch": "vitest",
45
45
  "typecheck": "tsc --noEmit",
46
+ "benchmark": "node benchmark/run.mjs",
47
+ "benchmark:pin": "node benchmark/pin-corpus.mjs",
46
48
  "sync-signatures": "node scripts/sync-signatures.mjs",
47
49
  "prepublishOnly": "npm run sync-signatures && npm run build && npm test"
48
50
  },
@@ -51,7 +53,7 @@
51
53
  "zod": "^3.24.0"
52
54
  },
53
55
  "devDependencies": {
54
- "@flagrix/scanner-core": "^0.1.3",
56
+ "@flagrix/scanner-core": "^0.3.0",
55
57
  "@types/node": "^20.0.0",
56
58
  "tsup": "^8.0.0",
57
59
  "typescript": "^5.0.0",