deepscan-cli 1.2.1 → 1.3.0
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.
- package/README.md +3 -2
- package/dist/bin/deepscan.js +3 -2
- package/dist/bin/deepscan.js.map +1 -1
- package/dist/{chunk-4TWV5TES.js → chunk-ZP6AOU5P.js} +2699 -622
- package/dist/chunk-ZP6AOU5P.js.map +1 -0
- package/dist/index.d.ts +101 -0
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/rules/built-in/operations.yml +120 -0
- package/dist/chunk-4TWV5TES.js.map +0 -1
|
@@ -334,7 +334,7 @@ var RuleEngine = class {
|
|
|
334
334
|
return ["injection", "xss", "secrets", "auth", "crypto", "file-ops", "api-security"].includes(category);
|
|
335
335
|
}
|
|
336
336
|
if (scannerType === "ops") {
|
|
337
|
-
return ["oom-memory", "timeout-resilience", "resource-leaks", "ops-performance"].includes(category);
|
|
337
|
+
return ["oom-memory", "timeout-resilience", "resource-leaks", "ops-performance", "db-operations"].includes(category);
|
|
338
338
|
}
|
|
339
339
|
return ["complexity", "duplication", "code-smells", "naming", "metrics"].includes(category);
|
|
340
340
|
});
|
|
@@ -478,7 +478,7 @@ var DEEPSCAN_VERSION = readPackageVersion();
|
|
|
478
478
|
|
|
479
479
|
// src/core/pipeline.ts
|
|
480
480
|
import { createHash as createHash2 } from "crypto";
|
|
481
|
-
import { resolve as
|
|
481
|
+
import { resolve as resolve8 } from "path";
|
|
482
482
|
import { consola as consola6 } from "consola";
|
|
483
483
|
|
|
484
484
|
// src/core/file-discovery.ts
|
|
@@ -510,18 +510,29 @@ var LANGUAGES = [
|
|
|
510
510
|
],
|
|
511
511
|
taintSinks: [
|
|
512
512
|
{ pattern: "eval($TAINTED)", type: "code_injection", description: "eval() call" },
|
|
513
|
+
{ pattern: "vm.runInContext($TAINTED)", type: "code_injection", description: "vm.runInContext() call" },
|
|
513
514
|
{ pattern: "innerHTML", type: "xss", description: "innerHTML assignment" },
|
|
514
515
|
{ pattern: "document.write($TAINTED)", type: "xss", description: "document.write" },
|
|
515
516
|
{ pattern: "exec($TAINTED)", type: "command_injection", description: "child_process.exec" },
|
|
516
517
|
{ pattern: "execSync($TAINTED)", type: "command_injection", description: "child_process.execSync" },
|
|
517
518
|
{ pattern: "query($TAINTED)", type: "sql_injection", description: "SQL query" },
|
|
518
|
-
{ pattern: "raw($TAINTED)", type: "sql_injection", description: "Raw SQL query" }
|
|
519
|
+
{ pattern: "raw($TAINTED)", type: "sql_injection", description: "Raw SQL query" },
|
|
520
|
+
{ pattern: "fetch($TAINTED)", type: "ssrf", description: "fetch() HTTP request" },
|
|
521
|
+
{ pattern: "axios.get($TAINTED)", type: "ssrf", description: "axios.get() HTTP request" },
|
|
522
|
+
{ pattern: "axios.post($TAINTED)", type: "ssrf", description: "axios.post() HTTP request" },
|
|
523
|
+
{ pattern: "res.redirect($TAINTED)", type: "open_redirect", description: "Express res.redirect()" },
|
|
524
|
+
{ pattern: "res.sendFile($TAINTED)", type: "path_traversal", description: "Express res.sendFile()" },
|
|
525
|
+
{ pattern: "fs.readFile($TAINTED)", type: "path_traversal", description: "fs.readFile()" },
|
|
526
|
+
{ pattern: "fs.readFileSync($TAINTED)", type: "path_traversal", description: "fs.readFileSync()" }
|
|
519
527
|
],
|
|
520
528
|
sanitizers: [
|
|
521
|
-
{ pattern: "encodeURIComponent($X)", cleanses: ["xss"], description: "URL encoding" },
|
|
529
|
+
{ pattern: "encodeURIComponent($X)", cleanses: ["xss", "open_redirect"], description: "URL encoding" },
|
|
522
530
|
{ pattern: "escape($X)", cleanses: ["xss", "sql_injection"], description: "Generic escape" },
|
|
523
531
|
{ pattern: "DOMPurify.sanitize($X)", cleanses: ["xss"], description: "DOMPurify sanitizer" },
|
|
524
|
-
{ pattern: "parseInt($X)", cleanses: ["sql_injection", "xss"], description: "Integer parsing" }
|
|
532
|
+
{ pattern: "parseInt($X)", cleanses: ["sql_injection", "xss", "nosql_injection"], description: "Integer parsing" },
|
|
533
|
+
{ pattern: "path.basename($X)", cleanses: ["path_traversal"], description: "Basename sanitization" },
|
|
534
|
+
{ pattern: "String($X)", cleanses: ["nosql_injection"], description: "String coercion" },
|
|
535
|
+
{ pattern: "Number($X)", cleanses: ["nosql_injection", "sql_injection"], description: "Numeric coercion" }
|
|
525
536
|
],
|
|
526
537
|
namingConventions: {
|
|
527
538
|
variables: "camelCase",
|
|
@@ -546,13 +557,24 @@ var LANGUAGES = [
|
|
|
546
557
|
],
|
|
547
558
|
taintSinks: [
|
|
548
559
|
{ pattern: "eval($TAINTED)", type: "code_injection", description: "eval() call" },
|
|
560
|
+
{ pattern: "vm.runInContext($TAINTED)", type: "code_injection", description: "vm.runInContext() call" },
|
|
549
561
|
{ pattern: "innerHTML", type: "xss", description: "innerHTML assignment" },
|
|
550
562
|
{ pattern: "exec($TAINTED)", type: "command_injection", description: "child_process.exec" },
|
|
551
|
-
{ pattern: "query($TAINTED)", type: "sql_injection", description: "SQL query" }
|
|
563
|
+
{ pattern: "query($TAINTED)", type: "sql_injection", description: "SQL query" },
|
|
564
|
+
{ pattern: "fetch($TAINTED)", type: "ssrf", description: "fetch() HTTP request" },
|
|
565
|
+
{ pattern: "axios.get($TAINTED)", type: "ssrf", description: "axios.get() HTTP request" },
|
|
566
|
+
{ pattern: "axios.post($TAINTED)", type: "ssrf", description: "axios.post() HTTP request" },
|
|
567
|
+
{ pattern: "res.redirect($TAINTED)", type: "open_redirect", description: "Express res.redirect()" },
|
|
568
|
+
{ pattern: "res.sendFile($TAINTED)", type: "path_traversal", description: "Express res.sendFile()" },
|
|
569
|
+
{ pattern: "fs.readFile($TAINTED)", type: "path_traversal", description: "fs.readFile()" },
|
|
570
|
+
{ pattern: "fs.readFileSync($TAINTED)", type: "path_traversal", description: "fs.readFileSync()" }
|
|
552
571
|
],
|
|
553
572
|
sanitizers: [
|
|
554
|
-
{ pattern: "encodeURIComponent($X)", cleanses: ["xss"], description: "URL encoding" },
|
|
555
|
-
{ pattern: "parseInt($X)", cleanses: ["sql_injection", "xss"], description: "Integer parsing" }
|
|
573
|
+
{ pattern: "encodeURIComponent($X)", cleanses: ["xss", "open_redirect"], description: "URL encoding" },
|
|
574
|
+
{ pattern: "parseInt($X)", cleanses: ["sql_injection", "xss", "nosql_injection"], description: "Integer parsing" },
|
|
575
|
+
{ pattern: "path.basename($X)", cleanses: ["path_traversal"], description: "Basename sanitization" },
|
|
576
|
+
{ pattern: "String($X)", cleanses: ["nosql_injection"], description: "String coercion" },
|
|
577
|
+
{ pattern: "Number($X)", cleanses: ["nosql_injection", "sql_injection"], description: "Numeric coercion" }
|
|
556
578
|
],
|
|
557
579
|
namingConventions: {
|
|
558
580
|
variables: "camelCase",
|
|
@@ -586,13 +608,18 @@ var LANGUAGES = [
|
|
|
586
608
|
{ pattern: "subprocess.call($TAINTED)", type: "command_injection", description: "Subprocess call" },
|
|
587
609
|
{ pattern: "cursor.execute($TAINTED)", type: "sql_injection", description: "SQL query" },
|
|
588
610
|
{ pattern: "open($TAINTED)", type: "path_traversal", description: "File open" },
|
|
589
|
-
{ pattern: "pickle.loads($TAINTED)", type: "deserialization", description: "Pickle deserialization" }
|
|
611
|
+
{ pattern: "pickle.loads($TAINTED)", type: "deserialization", description: "Pickle deserialization" },
|
|
612
|
+
{ pattern: "requests.get($TAINTED)", type: "ssrf", description: "requests.get() HTTP request" },
|
|
613
|
+
{ pattern: "requests.post($TAINTED)", type: "ssrf", description: "requests.post() HTTP request" },
|
|
614
|
+
{ pattern: "urllib.request.urlopen($TAINTED)", type: "ssrf", description: "urlopen() HTTP request" },
|
|
615
|
+
{ pattern: "redirect($TAINTED)", type: "open_redirect", description: "Flask/Django redirect()" }
|
|
590
616
|
],
|
|
591
617
|
sanitizers: [
|
|
592
618
|
{ pattern: "bleach.clean($X)", cleanses: ["xss"], description: "Bleach HTML sanitizer" },
|
|
593
619
|
{ pattern: "escape($X)", cleanses: ["xss"], description: "HTML escape" },
|
|
594
620
|
{ pattern: "int($X)", cleanses: ["sql_injection"], description: "Integer conversion" },
|
|
595
|
-
{ pattern: "shlex.quote($X)", cleanses: ["command_injection"], description: "Shell quoting" }
|
|
621
|
+
{ pattern: "shlex.quote($X)", cleanses: ["command_injection"], description: "Shell quoting" },
|
|
622
|
+
{ pattern: "os.path.basename($X)", cleanses: ["path_traversal"], description: "Basename sanitization" }
|
|
596
623
|
],
|
|
597
624
|
namingConventions: {
|
|
598
625
|
variables: "snake_case",
|
|
@@ -665,12 +692,17 @@ var LANGUAGES = [
|
|
|
665
692
|
{ pattern: "template.HTML($TAINTED)", type: "xss", description: "Unescaped HTML" },
|
|
666
693
|
{ pattern: "os.Open($TAINTED)", type: "path_traversal", description: "File open" },
|
|
667
694
|
{ pattern: "os.ReadFile($TAINTED)", type: "path_traversal", description: "File read" },
|
|
668
|
-
{ pattern: "
|
|
695
|
+
{ pattern: "os.WriteFile($TAINTED)", type: "path_traversal", description: "File write" },
|
|
696
|
+
{ pattern: "os.Create($TAINTED)", type: "path_traversal", description: "File create" },
|
|
697
|
+
{ pattern: "ioutil.ReadFile($TAINTED)", type: "path_traversal", description: "File read" },
|
|
698
|
+
{ pattern: "http.Get($TAINTED)", type: "ssrf", description: "http.Get() SSRF" },
|
|
699
|
+
{ pattern: "http.Redirect($TAINTED)", type: "open_redirect", description: "http.Redirect() Open Redirect" }
|
|
669
700
|
],
|
|
670
701
|
sanitizers: [
|
|
671
702
|
{ pattern: "template.HTMLEscapeString($X)", cleanses: ["xss"], description: "HTML escaping" },
|
|
672
703
|
{ pattern: "url.QueryEscape($X)", cleanses: ["xss"], description: "URL escaping" },
|
|
673
|
-
{ pattern: "strconv.Atoi($X)", cleanses: ["sql_injection"], description: "String to int" }
|
|
704
|
+
{ pattern: "strconv.Atoi($X)", cleanses: ["sql_injection"], description: "String to int" },
|
|
705
|
+
{ pattern: "filepath.Base($X)", cleanses: ["path_traversal"], description: "Basename sanitization" }
|
|
674
706
|
],
|
|
675
707
|
namingConventions: {
|
|
676
708
|
variables: "camelCase",
|
|
@@ -786,15 +818,18 @@ var LANGUAGES = [
|
|
|
786
818
|
{ pattern: "mysqli_query($TAINTED)", type: "sql_injection", description: "MySQLi query" },
|
|
787
819
|
{ pattern: "echo $TAINTED", type: "xss", description: "Echo output" },
|
|
788
820
|
{ pattern: "include($TAINTED)", type: "file_inclusion", description: "File inclusion" },
|
|
821
|
+
{ pattern: "require($TAINTED)", type: "file_inclusion", description: "File inclusion" },
|
|
789
822
|
{ pattern: "file_get_contents($TAINTED)", type: "path_traversal", description: "File read" },
|
|
790
|
-
{ pattern: "unserialize($TAINTED)", type: "deserialization", description: "PHP unserialize" }
|
|
823
|
+
{ pattern: "unserialize($TAINTED)", type: "deserialization", description: "PHP unserialize" },
|
|
824
|
+
{ pattern: "header($TAINTED)", type: "open_redirect", description: "HTTP redirect header" }
|
|
791
825
|
],
|
|
792
826
|
sanitizers: [
|
|
793
827
|
{ pattern: "htmlspecialchars($X)", cleanses: ["xss"], description: "HTML encoding" },
|
|
794
828
|
{ pattern: "mysqli_real_escape_string($X)", cleanses: ["sql_injection"], description: "SQL escaping" },
|
|
795
|
-
{ pattern: "intval($X)", cleanses: ["sql_injection", "command_injection", "xss", "path_traversal", "code_injection"], description: "Integer conversion" },
|
|
829
|
+
{ pattern: "intval($X)", cleanses: ["sql_injection", "command_injection", "xss", "path_traversal", "code_injection", "file_inclusion"], description: "Integer conversion" },
|
|
796
830
|
{ pattern: "escapeshellarg($X)", cleanses: ["command_injection"], description: "Shell arg escaping" },
|
|
797
|
-
{ pattern: "escapeshellcmd($X)", cleanses: ["command_injection"], description: "Shell cmd escaping" }
|
|
831
|
+
{ pattern: "escapeshellcmd($X)", cleanses: ["command_injection"], description: "Shell cmd escaping" },
|
|
832
|
+
{ pattern: "basename($X)", cleanses: ["path_traversal", "file_inclusion"], description: "Basename sanitization" }
|
|
798
833
|
],
|
|
799
834
|
namingConventions: {
|
|
800
835
|
variables: "camelCase",
|
|
@@ -1037,11 +1072,11 @@ var LOCK_FILES = /* @__PURE__ */ new Set([
|
|
|
1037
1072
|
"packages.lock.json",
|
|
1038
1073
|
"go.sum"
|
|
1039
1074
|
]);
|
|
1040
|
-
var VENDOR_DIR_PATTERN = /(?:^|[\\/])(?:vendor|third[_-]?party|bower_components|externals?|static[\\/]js[\\/]libs|assets[\\/]javascripts[\\/](?:date-picker|plugins))[\\/]/i;
|
|
1041
|
-
var KNOWN_VENDOR_FILES_PATTERN = /(?:^(?:jquery|lodash|underscore|backbone|angular|react\.production|vue\.global|bootstrap|popper|moment(?:\.min)?|d3|select2|sweetalert|highlight|firebug|ace|require|lte-ie7|prettify|modernizr)(?:[\.-][\w.]+)?\.js$|^(?:gmock-gtest-all|gtest-all)\.(?:cc|cpp)$)/i;
|
|
1075
|
+
var VENDOR_DIR_PATTERN = /(?:^|[\\/])(?:vendor|third[_-]?party|bower_components|externals?|static[\\/]js[\\/]libs|public[\\/]libs?|assets[\\/]javascripts[\\/](?:date-picker|plugins))[\\/]/i;
|
|
1076
|
+
var KNOWN_VENDOR_FILES_PATTERN = /(?:^(?:jquery|lodash|underscore|backbone|angular|react\.production|vue\.global|bootstrap|popper|moment(?:\.min)?|d3|select2|sweetalert|highlight|prism|firebug|ace|require|lte-ie7|prettify|modernizr)(?:[\.-][\w.]+)?\.js$|^(?:gmock-gtest-all|gtest-all)\.(?:cc|cpp)$)/i;
|
|
1042
1077
|
var MINIFIED_PATTERN = /\.(?:min|bundle|chunk)\.(?:js|css)$/i;
|
|
1043
1078
|
var TEST_PATH_PATTERN = /(?:^|[\\/])(?:tests?|__tests__|spec|__spec__|fixtures?|mocks?|__mocks__|e2e|integration|cypress|playwright|scratch|benchmarks?)[\\/]/i;
|
|
1044
|
-
var TEST_FILE_PATTERN = /(?:\.(?:test|spec|mock|fixture|e2e|cy)\.|^(?:test[_-][\w.-]+|[\w.-]+[_-](?:test|spec))\.(?:[cm]?[jt]sx?|py|go|rb|php|java)$)/i;
|
|
1079
|
+
var TEST_FILE_PATTERN = /(?:\.(?:test|spec|mock|fixture|e2e|cy)\.|^(?:test[_-][\w.-]+|[\w.-]+[_-](?:test|spec))\.(?:[cm]?[jt]sx?|py|go|rb|php|java|kt|kts|swift|cs|rs)$)/i;
|
|
1045
1080
|
function classifyFile(relPath, name) {
|
|
1046
1081
|
return {
|
|
1047
1082
|
isLockFile: LOCK_FILES.has(name),
|
|
@@ -1711,6 +1746,1006 @@ var ASTParser = class {
|
|
|
1711
1746
|
}
|
|
1712
1747
|
};
|
|
1713
1748
|
|
|
1749
|
+
// src/core/code-model.ts
|
|
1750
|
+
var REQUEST_DESTRUCTURED_KEYS = /* @__PURE__ */ new Set(["params", "query", "body", "headers", "cookies"]);
|
|
1751
|
+
var SCOPE_AST_TYPES = /* @__PURE__ */ new Set([
|
|
1752
|
+
"function_declaration",
|
|
1753
|
+
"arrow_function",
|
|
1754
|
+
"function_expression",
|
|
1755
|
+
"method_definition",
|
|
1756
|
+
"function_definition",
|
|
1757
|
+
"method_declaration",
|
|
1758
|
+
"func_literal"
|
|
1759
|
+
]);
|
|
1760
|
+
var CALL_AST_TYPES = /* @__PURE__ */ new Set(["call_expression", "call", "method_invocation"]);
|
|
1761
|
+
var CONTROL_KEYWORDS = /* @__PURE__ */ new Set([
|
|
1762
|
+
"if",
|
|
1763
|
+
"else",
|
|
1764
|
+
"for",
|
|
1765
|
+
"while",
|
|
1766
|
+
"do",
|
|
1767
|
+
"switch",
|
|
1768
|
+
"case",
|
|
1769
|
+
"catch",
|
|
1770
|
+
"with",
|
|
1771
|
+
"return",
|
|
1772
|
+
"throw",
|
|
1773
|
+
"typeof",
|
|
1774
|
+
"instanceof",
|
|
1775
|
+
"new",
|
|
1776
|
+
"await",
|
|
1777
|
+
"function",
|
|
1778
|
+
"async",
|
|
1779
|
+
"class",
|
|
1780
|
+
"import",
|
|
1781
|
+
"export",
|
|
1782
|
+
"super",
|
|
1783
|
+
"this"
|
|
1784
|
+
]);
|
|
1785
|
+
var STRING_LITERAL_RE = /^(?:'[^'\\]*(?:\\.[^'\\]*)*'|"[^"\\]*(?:\\.[^"\\]*)*"|`[^`\\$]*(?:\\.[^`\\$]*)*`|-?\d+(?:\.\d+)?|true|false|null|undefined|None|True|False)$/;
|
|
1786
|
+
function classifyArgText(raw) {
|
|
1787
|
+
const trimmed = raw.trim();
|
|
1788
|
+
if (!trimmed) return { isLiteral: true, hasInterpolation: false };
|
|
1789
|
+
const isLiteral = STRING_LITERAL_RE.test(trimmed);
|
|
1790
|
+
const hasInterpolation = !isLiteral && (/\$\{[^}]+\}/.test(trimmed) || /\+\s*[a-zA-Z_$]/.test(trimmed) || /[a-zA-Z_$]\s*\+/.test(trimmed) || /%\s*(?:\(|[a-zA-Z_])/.test(trimmed) || /\.format\s*\(/.test(trimmed) || /\bf["']/.test(trimmed) || /\$[a-zA-Z_]/.test(trimmed));
|
|
1791
|
+
return { isLiteral, hasInterpolation };
|
|
1792
|
+
}
|
|
1793
|
+
function splitBalancedArgs(argText, baseStartLine) {
|
|
1794
|
+
const args = [];
|
|
1795
|
+
const len = argText.length;
|
|
1796
|
+
let current = "";
|
|
1797
|
+
let argStartLine = baseStartLine;
|
|
1798
|
+
let curLine = baseStartLine;
|
|
1799
|
+
let parenDepth = 0;
|
|
1800
|
+
let braceDepth = 0;
|
|
1801
|
+
let bracketDepth = 0;
|
|
1802
|
+
let inSingle = false;
|
|
1803
|
+
let inDouble = false;
|
|
1804
|
+
let inBacktick = false;
|
|
1805
|
+
const pushCurrent = (endLine) => {
|
|
1806
|
+
const trimmed = current.trim();
|
|
1807
|
+
if (trimmed.length > 0) {
|
|
1808
|
+
const { isLiteral, hasInterpolation } = classifyArgText(trimmed);
|
|
1809
|
+
args.push({
|
|
1810
|
+
text: trimmed,
|
|
1811
|
+
isLiteral,
|
|
1812
|
+
hasInterpolation,
|
|
1813
|
+
startLine: argStartLine,
|
|
1814
|
+
endLine
|
|
1815
|
+
});
|
|
1816
|
+
}
|
|
1817
|
+
current = "";
|
|
1818
|
+
};
|
|
1819
|
+
for (let i = 0; i < len; i++) {
|
|
1820
|
+
const ch = argText[i];
|
|
1821
|
+
if (ch === "\n") {
|
|
1822
|
+
curLine++;
|
|
1823
|
+
}
|
|
1824
|
+
if (inSingle) {
|
|
1825
|
+
current += ch;
|
|
1826
|
+
if (ch === "\\" && i + 1 < len) {
|
|
1827
|
+
current += argText[++i];
|
|
1828
|
+
continue;
|
|
1829
|
+
}
|
|
1830
|
+
if (ch === "'") inSingle = false;
|
|
1831
|
+
continue;
|
|
1832
|
+
}
|
|
1833
|
+
if (inDouble) {
|
|
1834
|
+
current += ch;
|
|
1835
|
+
if (ch === "\\" && i + 1 < len) {
|
|
1836
|
+
current += argText[++i];
|
|
1837
|
+
continue;
|
|
1838
|
+
}
|
|
1839
|
+
if (ch === '"') inDouble = false;
|
|
1840
|
+
continue;
|
|
1841
|
+
}
|
|
1842
|
+
if (inBacktick) {
|
|
1843
|
+
current += ch;
|
|
1844
|
+
if (ch === "\\" && i + 1 < len) {
|
|
1845
|
+
current += argText[++i];
|
|
1846
|
+
continue;
|
|
1847
|
+
}
|
|
1848
|
+
if (ch === "`") inBacktick = false;
|
|
1849
|
+
continue;
|
|
1850
|
+
}
|
|
1851
|
+
if (ch === "'") {
|
|
1852
|
+
inSingle = true;
|
|
1853
|
+
current += ch;
|
|
1854
|
+
continue;
|
|
1855
|
+
}
|
|
1856
|
+
if (ch === '"') {
|
|
1857
|
+
inDouble = true;
|
|
1858
|
+
current += ch;
|
|
1859
|
+
continue;
|
|
1860
|
+
}
|
|
1861
|
+
if (ch === "`") {
|
|
1862
|
+
inBacktick = true;
|
|
1863
|
+
current += ch;
|
|
1864
|
+
continue;
|
|
1865
|
+
}
|
|
1866
|
+
if (ch === "(") parenDepth++;
|
|
1867
|
+
else if (ch === ")" && parenDepth > 0) parenDepth--;
|
|
1868
|
+
else if (ch === "{") braceDepth++;
|
|
1869
|
+
else if (ch === "}" && braceDepth > 0) braceDepth--;
|
|
1870
|
+
else if (ch === "[") bracketDepth++;
|
|
1871
|
+
else if (ch === "]" && bracketDepth > 0) bracketDepth--;
|
|
1872
|
+
else if (ch === "," && parenDepth === 0 && braceDepth === 0 && bracketDepth === 0) {
|
|
1873
|
+
pushCurrent(curLine);
|
|
1874
|
+
argStartLine = curLine;
|
|
1875
|
+
continue;
|
|
1876
|
+
}
|
|
1877
|
+
if (!current.trim() && ch !== "\n" && ch !== " " && ch !== " " && ch !== "\r") {
|
|
1878
|
+
argStartLine = curLine;
|
|
1879
|
+
}
|
|
1880
|
+
current += ch;
|
|
1881
|
+
}
|
|
1882
|
+
pushCurrent(curLine);
|
|
1883
|
+
return args;
|
|
1884
|
+
}
|
|
1885
|
+
function parseParamList(rawParams) {
|
|
1886
|
+
const params = [];
|
|
1887
|
+
const destructuredReqParams = [];
|
|
1888
|
+
if (!rawParams.trim()) return { params, destructuredReqParams };
|
|
1889
|
+
const destructMatches = rawParams.matchAll(/\{([^}]+)\}(?:\s*:\s*Request\b)?/g);
|
|
1890
|
+
for (const dm of destructMatches) {
|
|
1891
|
+
const inner = dm[1];
|
|
1892
|
+
for (const part of inner.split(",")) {
|
|
1893
|
+
const key = part.trim().split(/\s*[:=]\s*/)[0].trim();
|
|
1894
|
+
if (REQUEST_DESTRUCTURED_KEYS.has(key)) {
|
|
1895
|
+
destructuredReqParams.push(key);
|
|
1896
|
+
}
|
|
1897
|
+
}
|
|
1898
|
+
}
|
|
1899
|
+
const strippedBraces = rawParams.replace(/\{[^}]*\}/g, "");
|
|
1900
|
+
for (const seg of strippedBraces.split(",")) {
|
|
1901
|
+
const clean = seg.trim().replace(/^\.\.\./, "").split(/\s*[:=]\s*/)[0].trim();
|
|
1902
|
+
if (!clean) continue;
|
|
1903
|
+
const parts = clean.split(/\s+/);
|
|
1904
|
+
let pName = parts[0];
|
|
1905
|
+
if (parts.length >= 2) {
|
|
1906
|
+
const first = parts[0];
|
|
1907
|
+
const last = parts[parts.length - 1];
|
|
1908
|
+
if (/^(?:string|int|bool|float\d*|byte|rune|error|interface\{\}|any|\*?\w+\.\w+|\[\]\w+)$/i.test(last) || last.startsWith("*") || last.startsWith("[")) {
|
|
1909
|
+
pName = first;
|
|
1910
|
+
} else {
|
|
1911
|
+
pName = last;
|
|
1912
|
+
}
|
|
1913
|
+
}
|
|
1914
|
+
if (pName && pName !== "_" && pName !== "self" && pName !== "this" && /^[a-zA-Z_$][\w$]*$/.test(pName)) {
|
|
1915
|
+
params.push(pName);
|
|
1916
|
+
}
|
|
1917
|
+
}
|
|
1918
|
+
return { params, destructuredReqParams };
|
|
1919
|
+
}
|
|
1920
|
+
function parseCalleeParts(calleeRaw) {
|
|
1921
|
+
const callee = calleeRaw.replace(/\s+/g, "").trim();
|
|
1922
|
+
const lastDot = callee.lastIndexOf(".");
|
|
1923
|
+
const lastScope = callee.lastIndexOf("::");
|
|
1924
|
+
const lastArrow = callee.lastIndexOf("->");
|
|
1925
|
+
const sepIdx = Math.max(lastDot, lastScope, lastArrow);
|
|
1926
|
+
if (sepIdx === -1) {
|
|
1927
|
+
return { callee, receiver: null, methodName: callee };
|
|
1928
|
+
}
|
|
1929
|
+
const sepLen = sepIdx === lastDot ? 1 : 2;
|
|
1930
|
+
const receiver = callee.slice(0, sepIdx) || null;
|
|
1931
|
+
const methodName = callee.slice(sepIdx + sepLen);
|
|
1932
|
+
return { callee, receiver, methodName };
|
|
1933
|
+
}
|
|
1934
|
+
function buildFromTree(content, filePath, language, tree) {
|
|
1935
|
+
const scopes = [];
|
|
1936
|
+
const callSites = [];
|
|
1937
|
+
const assignments = [];
|
|
1938
|
+
let nextScopeId = 1;
|
|
1939
|
+
const scopeStack = [0];
|
|
1940
|
+
function extractParamsFromAst(fnNode) {
|
|
1941
|
+
const paramsNode = fnNode.childForFieldName("parameters") || fnNode.childForFieldName("parameter");
|
|
1942
|
+
if (paramsNode) {
|
|
1943
|
+
return parseParamList(paramsNode.text.replace(/^\(|\)$/g, ""));
|
|
1944
|
+
}
|
|
1945
|
+
for (let i = 0; i < fnNode.childCount; i++) {
|
|
1946
|
+
const c = fnNode.child(i);
|
|
1947
|
+
if (c && c.type === "identifier") {
|
|
1948
|
+
return { params: [c.text], destructuredReqParams: [] };
|
|
1949
|
+
}
|
|
1950
|
+
}
|
|
1951
|
+
return { params: [], destructuredReqParams: [] };
|
|
1952
|
+
}
|
|
1953
|
+
function isExportedNode(node) {
|
|
1954
|
+
let cur = node.parent;
|
|
1955
|
+
let hops = 0;
|
|
1956
|
+
while (cur && hops < 3) {
|
|
1957
|
+
if (cur.type === "export_statement") return true;
|
|
1958
|
+
cur = cur.parent;
|
|
1959
|
+
hops++;
|
|
1960
|
+
}
|
|
1961
|
+
return false;
|
|
1962
|
+
}
|
|
1963
|
+
function walk(node) {
|
|
1964
|
+
let pushedScope = false;
|
|
1965
|
+
if (SCOPE_AST_TYPES.has(node.type)) {
|
|
1966
|
+
const id = nextScopeId++;
|
|
1967
|
+
const nameNode = node.childForFieldName("name");
|
|
1968
|
+
let name = nameNode?.text || "<anonymous>";
|
|
1969
|
+
if (name === "<anonymous>" && node.parent?.type === "variable_declarator") {
|
|
1970
|
+
const varId = node.parent.childForFieldName("name");
|
|
1971
|
+
if (varId) name = varId.text;
|
|
1972
|
+
}
|
|
1973
|
+
const { params, destructuredReqParams } = extractParamsFromAst(node);
|
|
1974
|
+
const startLine = node.startPosition.row + 1;
|
|
1975
|
+
const endLine = node.endPosition.row + 1;
|
|
1976
|
+
const headerSlice = node.text.slice(0, Math.min(node.text.length, 160));
|
|
1977
|
+
const isAsync = /^\s*(?:export\s+)?async\b/.test(headerSlice);
|
|
1978
|
+
const isExported = isExportedNode(node) || language === "python" && node.startPosition.column === 0;
|
|
1979
|
+
const isMethod = node.type === "method_definition" || node.type === "method_declaration";
|
|
1980
|
+
const isRepr = name === "__repr__" || name === "__str__";
|
|
1981
|
+
const isRouteHandler = destructuredReqParams.length > 0 || params.some((p) => /^(?:req|request|ctx|c)$/i.test(p)) || /\b(?:Request|Response|NextFunction|HttpRequest)\b/.test(headerSlice);
|
|
1982
|
+
scopes.push({
|
|
1983
|
+
id,
|
|
1984
|
+
name,
|
|
1985
|
+
params,
|
|
1986
|
+
destructuredReqParams,
|
|
1987
|
+
startLine,
|
|
1988
|
+
endLine,
|
|
1989
|
+
isAsync,
|
|
1990
|
+
isExported,
|
|
1991
|
+
isMethod,
|
|
1992
|
+
isRepr,
|
|
1993
|
+
isRouteHandler
|
|
1994
|
+
});
|
|
1995
|
+
scopeStack.push(id);
|
|
1996
|
+
pushedScope = true;
|
|
1997
|
+
}
|
|
1998
|
+
const currentScopeId = scopeStack[scopeStack.length - 1];
|
|
1999
|
+
if (CALL_AST_TYPES.has(node.type)) {
|
|
2000
|
+
const funcNode = node.childForFieldName("function") || node.childForFieldName("name") || node.children.find((c) => c.type === "identifier" || c.type === "member_expression");
|
|
2001
|
+
const argsNode = node.childForFieldName("arguments") || node.childForFieldName("argument_list");
|
|
2002
|
+
const objectNode = node.childForFieldName("object");
|
|
2003
|
+
const rawCallee = objectNode && funcNode ? `${objectNode.text}.${funcNode.text}` : funcNode?.text || "";
|
|
2004
|
+
if (rawCallee && argsNode) {
|
|
2005
|
+
const { callee, receiver, methodName } = parseCalleeParts(rawCallee);
|
|
2006
|
+
if (!CONTROL_KEYWORDS.has(methodName)) {
|
|
2007
|
+
const argList = [];
|
|
2008
|
+
for (let i = 0; i < argsNode.childCount; i++) {
|
|
2009
|
+
const c = argsNode.child(i);
|
|
2010
|
+
if (!c || c.type === "(" || c.type === ")" || c.type === ",") continue;
|
|
2011
|
+
const { isLiteral, hasInterpolation } = classifyArgText(c.text);
|
|
2012
|
+
argList.push({
|
|
2013
|
+
text: c.text,
|
|
2014
|
+
isLiteral,
|
|
2015
|
+
hasInterpolation,
|
|
2016
|
+
startLine: c.startPosition.row + 1,
|
|
2017
|
+
endLine: c.endPosition.row + 1
|
|
2018
|
+
});
|
|
2019
|
+
}
|
|
2020
|
+
callSites.push({
|
|
2021
|
+
callee,
|
|
2022
|
+
receiver,
|
|
2023
|
+
methodName,
|
|
2024
|
+
args: argList,
|
|
2025
|
+
startLine: node.startPosition.row + 1,
|
|
2026
|
+
endLine: node.endPosition.row + 1,
|
|
2027
|
+
startColumn: node.startPosition.column + 1,
|
|
2028
|
+
fullText: node.text.length > 2500 ? node.text.slice(0, 2500) : node.text,
|
|
2029
|
+
scopeId: currentScopeId
|
|
2030
|
+
});
|
|
2031
|
+
}
|
|
2032
|
+
}
|
|
2033
|
+
}
|
|
2034
|
+
if (node.type === "variable_declarator") {
|
|
2035
|
+
const left = node.childForFieldName("name");
|
|
2036
|
+
const right = node.childForFieldName("value");
|
|
2037
|
+
if (left && right) {
|
|
2038
|
+
const { targets, isDestructuring } = extractTargets(left.text);
|
|
2039
|
+
if (targets.length > 0) {
|
|
2040
|
+
assignments.push({
|
|
2041
|
+
targets,
|
|
2042
|
+
rhsText: right.text,
|
|
2043
|
+
startLine: node.startPosition.row + 1,
|
|
2044
|
+
endLine: node.endPosition.row + 1,
|
|
2045
|
+
scopeId: currentScopeId,
|
|
2046
|
+
isDestructuring
|
|
2047
|
+
});
|
|
2048
|
+
}
|
|
2049
|
+
}
|
|
2050
|
+
} else if (node.type === "assignment_expression" || node.type === "assignment" || node.type === "short_var_declaration") {
|
|
2051
|
+
const left = node.childForFieldName("left");
|
|
2052
|
+
const right = node.childForFieldName("right");
|
|
2053
|
+
if (left && right) {
|
|
2054
|
+
const { targets, isDestructuring } = extractTargets(left.text);
|
|
2055
|
+
if (targets.length > 0) {
|
|
2056
|
+
assignments.push({
|
|
2057
|
+
targets,
|
|
2058
|
+
rhsText: right.text,
|
|
2059
|
+
startLine: node.startPosition.row + 1,
|
|
2060
|
+
endLine: node.endPosition.row + 1,
|
|
2061
|
+
scopeId: currentScopeId,
|
|
2062
|
+
isDestructuring
|
|
2063
|
+
});
|
|
2064
|
+
}
|
|
2065
|
+
}
|
|
2066
|
+
}
|
|
2067
|
+
for (let i = 0; i < node.childCount; i++) {
|
|
2068
|
+
const child = node.child(i);
|
|
2069
|
+
if (child) walk(child);
|
|
2070
|
+
}
|
|
2071
|
+
if (pushedScope) {
|
|
2072
|
+
scopeStack.pop();
|
|
2073
|
+
}
|
|
2074
|
+
}
|
|
2075
|
+
walk(tree.rootNode);
|
|
2076
|
+
return { filePath, language, scopes, callSites, assignments };
|
|
2077
|
+
}
|
|
2078
|
+
function extractTargets(rawLeft) {
|
|
2079
|
+
const trimmed = rawLeft.trim();
|
|
2080
|
+
if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
|
|
2081
|
+
const inner = trimmed.slice(1, -1);
|
|
2082
|
+
const targets2 = [];
|
|
2083
|
+
for (const part of inner.split(",")) {
|
|
2084
|
+
const p = part.trim().split("=")[0].trim();
|
|
2085
|
+
if (!p) continue;
|
|
2086
|
+
const colonIdx = p.indexOf(":");
|
|
2087
|
+
const name = (colonIdx !== -1 ? p.slice(colonIdx + 1) : p).trim();
|
|
2088
|
+
if (/^[$a-zA-Z_][\w$]*$/.test(name)) {
|
|
2089
|
+
targets2.push(name);
|
|
2090
|
+
}
|
|
2091
|
+
}
|
|
2092
|
+
return { targets: targets2, isDestructuring: true };
|
|
2093
|
+
}
|
|
2094
|
+
if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
|
|
2095
|
+
const targets2 = trimmed.slice(1, -1).split(",").map((s) => s.trim().split("=")[0].trim()).filter((s) => /^[$a-zA-Z_][\w$]*$/.test(s));
|
|
2096
|
+
return { targets: targets2, isDestructuring: true };
|
|
2097
|
+
}
|
|
2098
|
+
const targets = trimmed.split(",").map((s) => s.trim()).filter((s) => /^[$a-zA-Z_][\w$]*$/.test(s) && s !== "_");
|
|
2099
|
+
return { targets, isDestructuring: targets.length > 1 };
|
|
2100
|
+
}
|
|
2101
|
+
function buildFallbackModel(content, filePath, language) {
|
|
2102
|
+
const scopes = [];
|
|
2103
|
+
const callSites = [];
|
|
2104
|
+
const assignments = [];
|
|
2105
|
+
const lines = content.split("\n");
|
|
2106
|
+
const funcDeclRe = /^\s*(export\s+)?(async\s+)?(?:function\s+([a-zA-Z_$][\w$]*)\s*\(([^)]*)\)|(?:public|private|protected|static|\s)*function\s+([a-zA-Z_]\w*)\s*\(([^)]*)\)|func\s+(?:\([^)]+\)\s*)?([a-zA-Z_]\w*)\s*\(([^)]*)\)|def\s+([a-zA-Z_]\w*)\s*\(([^)]*)\))/;
|
|
2107
|
+
const arrowDeclRe = /^\s*(export\s+)?(?:const|let|var)\s+([a-zA-Z_$][\w$]*)\s*=\s*(async\s+)?\(([^)]*)\)\s*(?::[^=>{]+)?=>\s*(?:\{|\(|return\b)/;
|
|
2108
|
+
let nextScopeId = 1;
|
|
2109
|
+
for (let i = 0; i < lines.length; i++) {
|
|
2110
|
+
const line = lines[i];
|
|
2111
|
+
const trimmed = line.trim();
|
|
2112
|
+
if (!trimmed || trimmed.startsWith("//") || trimmed.startsWith("#") || trimmed.startsWith("*")) continue;
|
|
2113
|
+
let name = "";
|
|
2114
|
+
let rawParams = "";
|
|
2115
|
+
let isExported = false;
|
|
2116
|
+
let isAsync = false;
|
|
2117
|
+
const fm = line.match(funcDeclRe);
|
|
2118
|
+
if (fm) {
|
|
2119
|
+
isExported = Boolean(fm[1]) || language === "python" && line.search(/\S/) === 0;
|
|
2120
|
+
isAsync = Boolean(fm[2]);
|
|
2121
|
+
name = fm[3] || fm[5] || fm[7] || fm[9] || "";
|
|
2122
|
+
rawParams = fm[4] ?? fm[6] ?? fm[8] ?? fm[10] ?? "";
|
|
2123
|
+
} else {
|
|
2124
|
+
const am = line.match(arrowDeclRe) || line.match(/^\s*return\s+(async\s+)?\(\s*(\{[^)]*\}(?:[^)]*)|[^)]*)\s*\)\s*(?::[^=>{]+)?=>\s*\{/);
|
|
2125
|
+
if (am) {
|
|
2126
|
+
if (line.match(arrowDeclRe)) {
|
|
2127
|
+
isExported = Boolean(am[1]);
|
|
2128
|
+
name = am[2];
|
|
2129
|
+
isAsync = Boolean(am[3]);
|
|
2130
|
+
rawParams = am[4] ?? "";
|
|
2131
|
+
} else {
|
|
2132
|
+
isAsync = Boolean(am[1]);
|
|
2133
|
+
name = "<handler>";
|
|
2134
|
+
rawParams = am[2] ?? "";
|
|
2135
|
+
}
|
|
2136
|
+
}
|
|
2137
|
+
}
|
|
2138
|
+
if (!name) continue;
|
|
2139
|
+
let endLine = i + 1;
|
|
2140
|
+
if (language === "python") {
|
|
2141
|
+
const baseIndent = line.length - line.trimStart().length;
|
|
2142
|
+
for (let j = i + 1; j < lines.length; j++) {
|
|
2143
|
+
const t = lines[j].trim();
|
|
2144
|
+
if (!t) continue;
|
|
2145
|
+
const ind = lines[j].length - lines[j].trimStart().length;
|
|
2146
|
+
if (ind <= baseIndent && !t.startsWith("#")) break;
|
|
2147
|
+
endLine = j + 1;
|
|
2148
|
+
}
|
|
2149
|
+
} else {
|
|
2150
|
+
let depth = 0;
|
|
2151
|
+
let seenOpen = false;
|
|
2152
|
+
for (let j = i; j < Math.min(lines.length, i + 250); j++) {
|
|
2153
|
+
for (let c = 0; c < lines[j].length; c++) {
|
|
2154
|
+
if (lines[j][c] === "{") {
|
|
2155
|
+
depth++;
|
|
2156
|
+
seenOpen = true;
|
|
2157
|
+
} else if (lines[j][c] === "}") {
|
|
2158
|
+
depth--;
|
|
2159
|
+
}
|
|
2160
|
+
}
|
|
2161
|
+
endLine = j + 1;
|
|
2162
|
+
if (seenOpen && depth <= 0) break;
|
|
2163
|
+
}
|
|
2164
|
+
}
|
|
2165
|
+
const { params, destructuredReqParams } = parseParamList(rawParams);
|
|
2166
|
+
scopes.push({
|
|
2167
|
+
id: nextScopeId++,
|
|
2168
|
+
name,
|
|
2169
|
+
params,
|
|
2170
|
+
destructuredReqParams,
|
|
2171
|
+
startLine: i + 1,
|
|
2172
|
+
endLine,
|
|
2173
|
+
isAsync,
|
|
2174
|
+
isExported,
|
|
2175
|
+
isMethod: false,
|
|
2176
|
+
isRepr: name === "__repr__" || name === "__str__",
|
|
2177
|
+
isRouteHandler: destructuredReqParams.length > 0 || params.some((p) => /^(?:req|request|ctx|c)$/i.test(p)) || /\b(?:Request|Response|NextFunction)\b/.test(rawParams)
|
|
2178
|
+
});
|
|
2179
|
+
}
|
|
2180
|
+
const scopeAt = (lineNum) => {
|
|
2181
|
+
let bestId = 0;
|
|
2182
|
+
let bestSpan = Infinity;
|
|
2183
|
+
for (const s of scopes) {
|
|
2184
|
+
if (lineNum >= s.startLine && lineNum <= s.endLine) {
|
|
2185
|
+
const span = s.endLine - s.startLine;
|
|
2186
|
+
if (span < bestSpan) {
|
|
2187
|
+
bestSpan = span;
|
|
2188
|
+
bestId = s.id;
|
|
2189
|
+
}
|
|
2190
|
+
}
|
|
2191
|
+
}
|
|
2192
|
+
return bestId;
|
|
2193
|
+
};
|
|
2194
|
+
const callStartRe = /([a-zA-Z_$][\w$]*(?:(?:\s*\.\s*|\s*->\s*|\s*::\s*)[a-zA-Z_$][\w$]*)*)\s*\(/g;
|
|
2195
|
+
const lineStarts = [0];
|
|
2196
|
+
for (let i = 0; i < content.length; i++) {
|
|
2197
|
+
if (content[i] === "\n") lineStarts.push(i + 1);
|
|
2198
|
+
}
|
|
2199
|
+
const offsetToLineCol = (offset) => {
|
|
2200
|
+
let lo = 0;
|
|
2201
|
+
let hi = lineStarts.length - 1;
|
|
2202
|
+
while (lo <= hi) {
|
|
2203
|
+
const mid = lo + hi >> 1;
|
|
2204
|
+
if (lineStarts[mid] <= offset) lo = mid + 1;
|
|
2205
|
+
else hi = mid - 1;
|
|
2206
|
+
}
|
|
2207
|
+
const lineIdx = Math.max(0, hi);
|
|
2208
|
+
return { line: lineIdx + 1, col: offset - lineStarts[lineIdx] + 1 };
|
|
2209
|
+
};
|
|
2210
|
+
let cm;
|
|
2211
|
+
while ((cm = callStartRe.exec(content)) !== null) {
|
|
2212
|
+
const rawCallee = cm[1];
|
|
2213
|
+
const parsedCallee = parseCalleeParts(rawCallee);
|
|
2214
|
+
let { receiver } = parsedCallee;
|
|
2215
|
+
const { callee, methodName } = parsedCallee;
|
|
2216
|
+
if (CONTROL_KEYWORDS.has(methodName)) continue;
|
|
2217
|
+
if (receiver === null && cm.index > 0) {
|
|
2218
|
+
let prevIdx = cm.index - 1;
|
|
2219
|
+
while (prevIdx > 0 && (content[prevIdx] === " " || content[prevIdx] === " ")) prevIdx--;
|
|
2220
|
+
if (content[prevIdx] === "." || content.slice(Math.max(0, prevIdx - 1), prevIdx + 1) === "->" || content.slice(Math.max(0, prevIdx - 1), prevIdx + 1) === "::") {
|
|
2221
|
+
receiver = "<expr>";
|
|
2222
|
+
}
|
|
2223
|
+
}
|
|
2224
|
+
const { line: startLine, col: startColumn } = offsetToLineCol(cm.index);
|
|
2225
|
+
const lineText = lines[startLine - 1] ?? "";
|
|
2226
|
+
const beforeMatch = lineText.slice(0, Math.max(0, startColumn - 1)).trimStart();
|
|
2227
|
+
if (beforeMatch.startsWith("//") || beforeMatch.startsWith("#") || beforeMatch.startsWith("*") || beforeMatch.startsWith("/*") || /\b(?:function|async|def|func|class)\s+$/.test(lineText.slice(0, Math.max(0, startColumn - 1)))) {
|
|
2228
|
+
continue;
|
|
2229
|
+
}
|
|
2230
|
+
const openIdx = cm.index + cm[0].length - 1;
|
|
2231
|
+
const maxEnd = Math.min(content.length, openIdx + 4e3);
|
|
2232
|
+
let depth = 1;
|
|
2233
|
+
let closeIdx = -1;
|
|
2234
|
+
let inS = false;
|
|
2235
|
+
let inD = false;
|
|
2236
|
+
let inB = false;
|
|
2237
|
+
for (let k = openIdx + 1; k < maxEnd; k++) {
|
|
2238
|
+
const ch = content[k];
|
|
2239
|
+
if (inS) {
|
|
2240
|
+
if (ch === "\\") k++;
|
|
2241
|
+
else if (ch === "'") inS = false;
|
|
2242
|
+
continue;
|
|
2243
|
+
}
|
|
2244
|
+
if (inD) {
|
|
2245
|
+
if (ch === "\\") k++;
|
|
2246
|
+
else if (ch === '"') inD = false;
|
|
2247
|
+
continue;
|
|
2248
|
+
}
|
|
2249
|
+
if (inB) {
|
|
2250
|
+
if (ch === "\\") k++;
|
|
2251
|
+
else if (ch === "`") inB = false;
|
|
2252
|
+
continue;
|
|
2253
|
+
}
|
|
2254
|
+
if (ch === "'") inS = true;
|
|
2255
|
+
else if (ch === '"') inD = true;
|
|
2256
|
+
else if (ch === "`") inB = true;
|
|
2257
|
+
else if (ch === "(") depth++;
|
|
2258
|
+
else if (ch === ")") {
|
|
2259
|
+
depth--;
|
|
2260
|
+
if (depth === 0) {
|
|
2261
|
+
closeIdx = k;
|
|
2262
|
+
break;
|
|
2263
|
+
}
|
|
2264
|
+
}
|
|
2265
|
+
}
|
|
2266
|
+
if (closeIdx === -1) continue;
|
|
2267
|
+
const endLine = offsetToLineCol(closeIdx).line;
|
|
2268
|
+
const argBody = content.slice(openIdx + 1, closeIdx);
|
|
2269
|
+
const args = splitBalancedArgs(argBody, startLine);
|
|
2270
|
+
const fullText = content.slice(cm.index, Math.min(closeIdx + 1, cm.index + 2500));
|
|
2271
|
+
callSites.push({
|
|
2272
|
+
callee,
|
|
2273
|
+
receiver,
|
|
2274
|
+
methodName,
|
|
2275
|
+
args,
|
|
2276
|
+
startLine,
|
|
2277
|
+
endLine,
|
|
2278
|
+
startColumn,
|
|
2279
|
+
fullText,
|
|
2280
|
+
scopeId: scopeAt(startLine)
|
|
2281
|
+
});
|
|
2282
|
+
}
|
|
2283
|
+
if (language === "php") {
|
|
2284
|
+
const phpIncludeRe = /\b(include|include_once|require|require_once)\s+(\$[a-zA-Z_]\w*(?:\[[^\]]+\])?)\s*;/g;
|
|
2285
|
+
let pm;
|
|
2286
|
+
while ((pm = phpIncludeRe.exec(content)) !== null) {
|
|
2287
|
+
const { line: startLine, col: startColumn } = offsetToLineCol(pm.index);
|
|
2288
|
+
const argText = pm[2];
|
|
2289
|
+
callSites.push({
|
|
2290
|
+
callee: pm[1],
|
|
2291
|
+
receiver: null,
|
|
2292
|
+
methodName: pm[1],
|
|
2293
|
+
args: [{ text: argText, isLiteral: false, hasInterpolation: false, startLine, endLine: startLine }],
|
|
2294
|
+
startLine,
|
|
2295
|
+
endLine: startLine,
|
|
2296
|
+
startColumn,
|
|
2297
|
+
fullText: pm[0],
|
|
2298
|
+
scopeId: scopeAt(startLine)
|
|
2299
|
+
});
|
|
2300
|
+
}
|
|
2301
|
+
}
|
|
2302
|
+
for (let i = 0; i < lines.length; i++) {
|
|
2303
|
+
const trimmed = lines[i].trim();
|
|
2304
|
+
if (!trimmed || trimmed.startsWith("//") || trimmed.startsWith("#") || trimmed.startsWith("*")) continue;
|
|
2305
|
+
const m = trimmed.match(
|
|
2306
|
+
/^(?:(?:const|let|var|final|auto|my|local|String|int|long|float|double|boolean|char|byte|[A-Z][\w.<>\[\]]*)\s+)?(\{[^}]+\}|\[[^\]]+\]|[$a-zA-Z_][\w$]*(?:\s*,\s*[$a-zA-Z_][\w$]*)*)(?:\s*:\s*[^=]+)?\s*(?::=|=)\s*(.+)$/
|
|
2307
|
+
);
|
|
2308
|
+
if (!m) continue;
|
|
2309
|
+
const rhsText = m[2].replace(/;$/, "").trim();
|
|
2310
|
+
if (rhsText.startsWith("=")) continue;
|
|
2311
|
+
const { targets, isDestructuring } = extractTargets(m[1]);
|
|
2312
|
+
if (targets.length === 0) continue;
|
|
2313
|
+
assignments.push({
|
|
2314
|
+
targets,
|
|
2315
|
+
rhsText,
|
|
2316
|
+
startLine: i + 1,
|
|
2317
|
+
endLine: i + 1,
|
|
2318
|
+
scopeId: scopeAt(i + 1),
|
|
2319
|
+
isDestructuring
|
|
2320
|
+
});
|
|
2321
|
+
}
|
|
2322
|
+
return { filePath, language, scopes, callSites, assignments };
|
|
2323
|
+
}
|
|
2324
|
+
function buildFileCodeModel(content, filePath, language, tree) {
|
|
2325
|
+
if (tree) {
|
|
2326
|
+
try {
|
|
2327
|
+
return buildFromTree(content, filePath, language, tree);
|
|
2328
|
+
} catch {
|
|
2329
|
+
}
|
|
2330
|
+
}
|
|
2331
|
+
return buildFallbackModel(content, filePath, language);
|
|
2332
|
+
}
|
|
2333
|
+
function getScopeAtLine(model, line) {
|
|
2334
|
+
let bestId = 0;
|
|
2335
|
+
let bestSpan = Infinity;
|
|
2336
|
+
for (const scope of model.scopes) {
|
|
2337
|
+
if (line >= scope.startLine && line <= scope.endLine) {
|
|
2338
|
+
const span = scope.endLine - scope.startLine;
|
|
2339
|
+
if (span < bestSpan) {
|
|
2340
|
+
bestSpan = span;
|
|
2341
|
+
bestId = scope.id;
|
|
2342
|
+
}
|
|
2343
|
+
}
|
|
2344
|
+
}
|
|
2345
|
+
return bestId;
|
|
2346
|
+
}
|
|
2347
|
+
|
|
2348
|
+
// src/core/project-graph.ts
|
|
2349
|
+
import { dirname as dirname4, extname as extname3, resolve as resolve6 } from "path";
|
|
2350
|
+
import { existsSync as existsSync5 } from "fs";
|
|
2351
|
+
var JS_TS_EXTS = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"];
|
|
2352
|
+
var SINK_RULES = [
|
|
2353
|
+
{
|
|
2354
|
+
sinkType: "command_injection",
|
|
2355
|
+
description: "OS command execution",
|
|
2356
|
+
match: (c) => {
|
|
2357
|
+
if (c.methodName === "exec" && (!c.receiver || /^(?:child_process|cp|shell|proc)$/i.test(c.receiver)) || c.callee === "execSync" || c.callee === "child_process.execSync" || c.callee === "os.system" || c.callee === "exec.Command" || c.callee === "exec.CommandContext" || c.callee === "shell_exec" || c.callee === "system" || c.callee === "passthru" || c.callee === "Runtime.exec" || c.callee === "subprocess.call") {
|
|
2358
|
+
return 0;
|
|
2359
|
+
}
|
|
2360
|
+
return -1;
|
|
2361
|
+
}
|
|
2362
|
+
},
|
|
2363
|
+
{
|
|
2364
|
+
sinkType: "code_injection",
|
|
2365
|
+
description: "Dynamic code evaluation",
|
|
2366
|
+
match: (c) => {
|
|
2367
|
+
if (c.methodName === "eval" && !c.receiver || /^(?:window|globalThis|global)\s*\.\s*eval$/.test(c.callee) || c.callee === "vm.runInContext" || c.callee === "vm.runInNewContext") {
|
|
2368
|
+
return 0;
|
|
2369
|
+
}
|
|
2370
|
+
return -1;
|
|
2371
|
+
}
|
|
2372
|
+
},
|
|
2373
|
+
{
|
|
2374
|
+
sinkType: "sql_injection",
|
|
2375
|
+
description: "SQL query execution",
|
|
2376
|
+
match: (c) => {
|
|
2377
|
+
if (/^(?:query|raw|execute|executeQuery|executeUpdate|Exec|Query|mysqli_query|mysql_query|pg_query)$/.test(c.methodName) && c.args.length > 0 && !c.args[0].isLiteral && // Require SQL keywords OR concatenation/interpolation in arg[0]
|
|
2378
|
+
/\b(?:SELECT|INSERT|UPDATE|DELETE|DROP)\b|\$\{|\+|%[sd]|`\s*\$|\.[a-zA-Z_$]/.test(c.args[0].text)) {
|
|
2379
|
+
return 0;
|
|
2380
|
+
}
|
|
2381
|
+
return -1;
|
|
2382
|
+
}
|
|
2383
|
+
},
|
|
2384
|
+
{
|
|
2385
|
+
sinkType: "ssrf",
|
|
2386
|
+
description: "Server-side HTTP request",
|
|
2387
|
+
match: (c) => {
|
|
2388
|
+
if (c.callee === "fetch" || c.callee === "http.Get" || c.callee === "requests.get" || c.callee === "requests.post" || c.callee === "urllib.request.urlopen" || /^axios\.(?:get|post|put|delete|request)$/.test(c.callee)) {
|
|
2389
|
+
return 0;
|
|
2390
|
+
}
|
|
2391
|
+
return -1;
|
|
2392
|
+
}
|
|
2393
|
+
},
|
|
2394
|
+
{
|
|
2395
|
+
sinkType: "path_traversal",
|
|
2396
|
+
description: "File system access",
|
|
2397
|
+
match: (c) => {
|
|
2398
|
+
if (/^(?:fs\.readFile|fs\.readFileSync|fs\.writeFile|fs\.writeFileSync|os\.Open|os\.ReadFile|os\.WriteFile|ioutil\.ReadFile|open|file_get_contents|readfile)$/.test(c.callee) || c.methodName === "sendFile") {
|
|
2399
|
+
return 0;
|
|
2400
|
+
}
|
|
2401
|
+
return -1;
|
|
2402
|
+
}
|
|
2403
|
+
},
|
|
2404
|
+
{
|
|
2405
|
+
sinkType: "file_inclusion",
|
|
2406
|
+
description: "Dynamic PHP file inclusion",
|
|
2407
|
+
match: (c, language) => {
|
|
2408
|
+
if (language === "php" && /^(?:include|include_once|require|require_once)$/.test(c.methodName)) {
|
|
2409
|
+
return 0;
|
|
2410
|
+
}
|
|
2411
|
+
return -1;
|
|
2412
|
+
}
|
|
2413
|
+
},
|
|
2414
|
+
{
|
|
2415
|
+
sinkType: "open_redirect",
|
|
2416
|
+
description: "HTTP redirect",
|
|
2417
|
+
match: (c) => {
|
|
2418
|
+
if (c.callee === "res.redirect" || c.callee === "redirect") return 0;
|
|
2419
|
+
if (c.callee === "http.Redirect") return 2;
|
|
2420
|
+
return -1;
|
|
2421
|
+
}
|
|
2422
|
+
}
|
|
2423
|
+
];
|
|
2424
|
+
var SANITIZER_CALL_RE = /\b(?:parseInt|Number|Boolean|intval|floatval|basename|filepath\.Base|escapeshellarg|escapeshellcmd|shlex\.quote|htmlspecialchars|escapeHtml|DOMPurify\.sanitize|encodeURIComponent|String)\s*\(/;
|
|
2425
|
+
function containsIdent(text, ident) {
|
|
2426
|
+
const esc = ident.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
2427
|
+
return new RegExp(`(?:^|[^a-zA-Z0-9_$])${esc}(?![a-zA-Z0-9_$])`).test(text);
|
|
2428
|
+
}
|
|
2429
|
+
function resolveRelativeModule(fromFile, specifier, knownFilesLower) {
|
|
2430
|
+
if (!specifier.startsWith(".")) return null;
|
|
2431
|
+
const base = resolve6(dirname4(fromFile), specifier);
|
|
2432
|
+
const candidates = [base];
|
|
2433
|
+
const cleanJs = base.replace(/\.(?:js|mjs|cjs)$/i, "");
|
|
2434
|
+
for (const ext of JS_TS_EXTS) {
|
|
2435
|
+
candidates.push(`${base}${ext}`);
|
|
2436
|
+
if (cleanJs !== base) candidates.push(`${cleanJs}${ext}`);
|
|
2437
|
+
}
|
|
2438
|
+
candidates.push(`${base}.py`, `${base}.php`);
|
|
2439
|
+
for (const ext of JS_TS_EXTS) {
|
|
2440
|
+
candidates.push(resolve6(base, `index${ext}`));
|
|
2441
|
+
}
|
|
2442
|
+
for (const cand of candidates) {
|
|
2443
|
+
const hit = knownFilesLower.get(cand.toLowerCase());
|
|
2444
|
+
if (hit) return hit;
|
|
2445
|
+
if (existsSync5(cand)) return cand;
|
|
2446
|
+
}
|
|
2447
|
+
return null;
|
|
2448
|
+
}
|
|
2449
|
+
var ProjectSymbolGraph = class {
|
|
2450
|
+
/** filePath.toLowerCase() -> functionName -> ExportedFunctionSummary */
|
|
2451
|
+
exportsByFile = /* @__PURE__ */ new Map();
|
|
2452
|
+
/** callerFile.toLowerCase() -> localCalleeName -> ImportEdge */
|
|
2453
|
+
importsByFile = /* @__PURE__ */ new Map();
|
|
2454
|
+
/** packageDir.toLowerCase() (Go) -> Map<funcName, ExportedFunctionSummary> */
|
|
2455
|
+
goPackageFuncs = /* @__PURE__ */ new Map();
|
|
2456
|
+
/** phpFile.toLowerCase() -> unsanitized $_GET/$_POST/$_REQUEST var assignments */
|
|
2457
|
+
phpTaintedSourcesByFile = /* @__PURE__ */ new Map();
|
|
2458
|
+
/** phpFile.toLowerCase() -> list of resolved included/module php files */
|
|
2459
|
+
phpIncludesByFile = /* @__PURE__ */ new Map();
|
|
2460
|
+
addExportedFunction(filePath, language, summary) {
|
|
2461
|
+
const key = filePath.toLowerCase();
|
|
2462
|
+
let map = this.exportsByFile.get(key);
|
|
2463
|
+
if (!map) {
|
|
2464
|
+
map = /* @__PURE__ */ new Map();
|
|
2465
|
+
this.exportsByFile.set(key, map);
|
|
2466
|
+
}
|
|
2467
|
+
map.set(summary.name, summary);
|
|
2468
|
+
if (language === "go") {
|
|
2469
|
+
const dirKey = dirname4(filePath).toLowerCase();
|
|
2470
|
+
let dirMap = this.goPackageFuncs.get(dirKey);
|
|
2471
|
+
if (!dirMap) {
|
|
2472
|
+
dirMap = /* @__PURE__ */ new Map();
|
|
2473
|
+
this.goPackageFuncs.set(dirKey, dirMap);
|
|
2474
|
+
}
|
|
2475
|
+
dirMap.set(summary.name, summary);
|
|
2476
|
+
}
|
|
2477
|
+
}
|
|
2478
|
+
addImportEdge(callerFile, localName, targetFile, exportedName) {
|
|
2479
|
+
const key = callerFile.toLowerCase();
|
|
2480
|
+
let map = this.importsByFile.get(key);
|
|
2481
|
+
if (!map) {
|
|
2482
|
+
map = /* @__PURE__ */ new Map();
|
|
2483
|
+
this.importsByFile.set(key, map);
|
|
2484
|
+
}
|
|
2485
|
+
map.set(localName, { targetFile, exportedName });
|
|
2486
|
+
}
|
|
2487
|
+
addPhpSourceVar(filePath, entry) {
|
|
2488
|
+
const key = filePath.toLowerCase();
|
|
2489
|
+
const arr = this.phpTaintedSourcesByFile.get(key) || [];
|
|
2490
|
+
arr.push(entry);
|
|
2491
|
+
this.phpTaintedSourcesByFile.set(key, arr);
|
|
2492
|
+
}
|
|
2493
|
+
addPhpInclude(callerFile, includedFile) {
|
|
2494
|
+
const key = callerFile.toLowerCase();
|
|
2495
|
+
const arr = this.phpIncludesByFile.get(key) || [];
|
|
2496
|
+
if (!arr.includes(includedFile)) {
|
|
2497
|
+
arr.push(includedFile);
|
|
2498
|
+
this.phpIncludesByFile.set(key, arr);
|
|
2499
|
+
}
|
|
2500
|
+
}
|
|
2501
|
+
/**
|
|
2502
|
+
* Resolve a call inside `callerFilePath` (either imported name `foo`, namespace `ns.foo`, or Go same-package `foo`).
|
|
2503
|
+
*/
|
|
2504
|
+
resolveImportedFunction(callerFilePath, calleeName) {
|
|
2505
|
+
const callerKey = callerFilePath.toLowerCase();
|
|
2506
|
+
const imports = this.importsByFile.get(callerKey);
|
|
2507
|
+
if (imports) {
|
|
2508
|
+
const direct = imports.get(calleeName);
|
|
2509
|
+
if (direct) {
|
|
2510
|
+
const targetMap = this.exportsByFile.get(direct.targetFile.toLowerCase());
|
|
2511
|
+
const hit = targetMap?.get(direct.exportedName) || targetMap?.get("default") || (direct.exportedName === "default" && targetMap?.size === 1 ? Array.from(targetMap.values())[0] : void 0);
|
|
2512
|
+
if (hit) return hit;
|
|
2513
|
+
}
|
|
2514
|
+
if (calleeName.includes(".")) {
|
|
2515
|
+
const [ns, member] = calleeName.split(".");
|
|
2516
|
+
const nsEdge = imports.get(ns);
|
|
2517
|
+
if (nsEdge) {
|
|
2518
|
+
const hit = this.exportsByFile.get(nsEdge.targetFile.toLowerCase())?.get(member);
|
|
2519
|
+
if (hit) return hit;
|
|
2520
|
+
}
|
|
2521
|
+
}
|
|
2522
|
+
}
|
|
2523
|
+
if (callerFilePath.toLowerCase().endsWith(".go") && !calleeName.includes(".")) {
|
|
2524
|
+
const dirMap = this.goPackageFuncs.get(dirname4(callerFilePath).toLowerCase());
|
|
2525
|
+
const goHit = dirMap?.get(calleeName);
|
|
2526
|
+
if (goHit && goHit.filePath.toLowerCase() !== callerKey) {
|
|
2527
|
+
return goHit;
|
|
2528
|
+
}
|
|
2529
|
+
}
|
|
2530
|
+
return null;
|
|
2531
|
+
}
|
|
2532
|
+
/**
|
|
2533
|
+
* Return tainted superglobal variables assigned inside PHP files included by `filePath`.
|
|
2534
|
+
*/
|
|
2535
|
+
getPhpCrossFileTaintedVars(filePath) {
|
|
2536
|
+
const includes = this.phpIncludesByFile.get(filePath.toLowerCase());
|
|
2537
|
+
if (!includes || includes.length === 0) return [];
|
|
2538
|
+
const results = [];
|
|
2539
|
+
for (const inc of includes) {
|
|
2540
|
+
const list = this.phpTaintedSourcesByFile.get(inc.toLowerCase());
|
|
2541
|
+
if (list) results.push(...list);
|
|
2542
|
+
}
|
|
2543
|
+
return results;
|
|
2544
|
+
}
|
|
2545
|
+
};
|
|
2546
|
+
function summarizeFunctionScope(scope, lines, language, filePath, callsInScope, assignsInScope) {
|
|
2547
|
+
if (scope.params.length === 0) return null;
|
|
2548
|
+
const passthroughSet = /* @__PURE__ */ new Set();
|
|
2549
|
+
const sinkHits = [];
|
|
2550
|
+
for (let pIdx = 0; pIdx < scope.params.length; pIdx++) {
|
|
2551
|
+
const param = scope.params[pIdx];
|
|
2552
|
+
const derived = /* @__PURE__ */ new Set([param]);
|
|
2553
|
+
for (const a of assignsInScope) {
|
|
2554
|
+
if (a.startLine < scope.startLine || a.startLine > scope.endLine) continue;
|
|
2555
|
+
if (SANITIZER_CALL_RE.test(a.rhsText)) continue;
|
|
2556
|
+
const matchesDerived = Array.from(derived).some((v) => containsIdent(a.rhsText, v));
|
|
2557
|
+
if (matchesDerived) {
|
|
2558
|
+
for (const t of a.targets) derived.add(t);
|
|
2559
|
+
}
|
|
2560
|
+
}
|
|
2561
|
+
const maxLine = Math.min(lines.length, scope.endLine);
|
|
2562
|
+
for (let ln = scope.startLine; ln <= maxLine; ln++) {
|
|
2563
|
+
const trimmed = lines[ln - 1].trim();
|
|
2564
|
+
if (/^return\b/.test(trimmed) && !SANITIZER_CALL_RE.test(trimmed)) {
|
|
2565
|
+
if (Array.from(derived).some((v) => containsIdent(trimmed, v))) {
|
|
2566
|
+
passthroughSet.add(pIdx);
|
|
2567
|
+
break;
|
|
2568
|
+
}
|
|
2569
|
+
}
|
|
2570
|
+
}
|
|
2571
|
+
for (const call of callsInScope) {
|
|
2572
|
+
if (SANITIZER_CALL_RE.test(call.fullText)) continue;
|
|
2573
|
+
for (const rule of SINK_RULES) {
|
|
2574
|
+
const argIdx = rule.match(call, language);
|
|
2575
|
+
if (argIdx < 0 || argIdx >= call.args.length) continue;
|
|
2576
|
+
const arg = call.args[argIdx];
|
|
2577
|
+
if (arg.isLiteral) continue;
|
|
2578
|
+
if (Array.from(derived).some((v) => containsIdent(arg.text, v))) {
|
|
2579
|
+
sinkHits.push({
|
|
2580
|
+
paramIndex: pIdx,
|
|
2581
|
+
sinkType: rule.sinkType,
|
|
2582
|
+
sinkLine: call.startLine,
|
|
2583
|
+
sinkSnippet: lines[call.startLine - 1]?.trim() || call.fullText.split("\n")[0],
|
|
2584
|
+
sinkDescription: rule.description
|
|
2585
|
+
});
|
|
2586
|
+
break;
|
|
2587
|
+
}
|
|
2588
|
+
}
|
|
2589
|
+
}
|
|
2590
|
+
}
|
|
2591
|
+
if (passthroughSet.size === 0 && sinkHits.length === 0) return null;
|
|
2592
|
+
return {
|
|
2593
|
+
name: scope.name,
|
|
2594
|
+
filePath,
|
|
2595
|
+
params: scope.params,
|
|
2596
|
+
startLine: scope.startLine,
|
|
2597
|
+
passthroughParamIndices: Array.from(passthroughSet),
|
|
2598
|
+
sinkHits
|
|
2599
|
+
};
|
|
2600
|
+
}
|
|
2601
|
+
function buildProjectGraph(files) {
|
|
2602
|
+
const graph = new ProjectSymbolGraph();
|
|
2603
|
+
const knownFilesLower = /* @__PURE__ */ new Map();
|
|
2604
|
+
const phpFilesByDir = /* @__PURE__ */ new Map();
|
|
2605
|
+
const eligible = files.filter(
|
|
2606
|
+
(f) => !f.isLockFile && !f.isVendorFile && !f.isMinified && !f.isTestFile && f.size <= 25e4 && f.language !== "unknown" && f.language !== "config" && f.language !== "yaml" && f.language !== "dockerfile" && !f.relativePath.toLowerCase().endsWith(".html")
|
|
2607
|
+
);
|
|
2608
|
+
for (const f of eligible) {
|
|
2609
|
+
knownFilesLower.set(f.path.toLowerCase(), f.path);
|
|
2610
|
+
if (f.language === "php") {
|
|
2611
|
+
const d = dirname4(f.path).toLowerCase();
|
|
2612
|
+
const list = phpFilesByDir.get(d) || [];
|
|
2613
|
+
list.push(f.path);
|
|
2614
|
+
phpFilesByDir.set(d, list);
|
|
2615
|
+
}
|
|
2616
|
+
}
|
|
2617
|
+
for (const f of eligible) {
|
|
2618
|
+
const content = readFileContent(f.path);
|
|
2619
|
+
if (!content) continue;
|
|
2620
|
+
if (f.language === "typescript" && /^\s*(?:<\?xml\b|<!DOCTYPE\s+TS\b|<TS\b)/i.test(content.slice(0, 256))) {
|
|
2621
|
+
continue;
|
|
2622
|
+
}
|
|
2623
|
+
const model = buildFileCodeModel(content, f.path, f.language, null);
|
|
2624
|
+
const lines = content.split("\n");
|
|
2625
|
+
for (const scope of model.scopes) {
|
|
2626
|
+
if (scope.name.startsWith("<")) continue;
|
|
2627
|
+
if ((f.language === "javascript" || f.language === "typescript") && !scope.isExported) {
|
|
2628
|
+
continue;
|
|
2629
|
+
}
|
|
2630
|
+
const callsInScope = model.callSites.filter((c) => c.scopeId === scope.id);
|
|
2631
|
+
const assignsInScope = model.assignments.filter((a) => a.scopeId === scope.id);
|
|
2632
|
+
const summary = summarizeFunctionScope(scope, lines, f.language, f.path, callsInScope, assignsInScope);
|
|
2633
|
+
if (summary) {
|
|
2634
|
+
graph.addExportedFunction(f.path, f.language, summary);
|
|
2635
|
+
}
|
|
2636
|
+
}
|
|
2637
|
+
if (f.language === "javascript" || f.language === "typescript") {
|
|
2638
|
+
const esImportRe = /\bimport\s+(?:(\*\s+as\s+[a-zA-Z_$][\w$]*|\{[^}]+\}|[a-zA-Z_$][\w$]*)\s+from\s+)?['"]([^'"]+)['"]/g;
|
|
2639
|
+
let im;
|
|
2640
|
+
while ((im = esImportRe.exec(content)) !== null) {
|
|
2641
|
+
const spec = im[1];
|
|
2642
|
+
const modPath = im[2];
|
|
2643
|
+
if (!spec || !modPath.startsWith(".")) continue;
|
|
2644
|
+
const targetFile = resolveRelativeModule(f.path, modPath, knownFilesLower);
|
|
2645
|
+
if (!targetFile) continue;
|
|
2646
|
+
if (spec.startsWith("* as ")) {
|
|
2647
|
+
const ns = spec.slice(5).trim();
|
|
2648
|
+
graph.addImportEdge(f.path, ns, targetFile, "*");
|
|
2649
|
+
} else if (spec.startsWith("{")) {
|
|
2650
|
+
for (const part of spec.slice(1, -1).split(",")) {
|
|
2651
|
+
const p = part.trim();
|
|
2652
|
+
if (!p) continue;
|
|
2653
|
+
const asMatch = p.match(/^([a-zA-Z_$][\w$]*)\s+as\s+([a-zA-Z_$][\w$]*)$/);
|
|
2654
|
+
if (asMatch) {
|
|
2655
|
+
graph.addImportEdge(f.path, asMatch[2], targetFile, asMatch[1]);
|
|
2656
|
+
} else {
|
|
2657
|
+
graph.addImportEdge(f.path, p, targetFile, p);
|
|
2658
|
+
}
|
|
2659
|
+
}
|
|
2660
|
+
} else {
|
|
2661
|
+
graph.addImportEdge(f.path, spec.trim(), targetFile, "default");
|
|
2662
|
+
}
|
|
2663
|
+
}
|
|
2664
|
+
const cjsRe = /(?:const|let|var)\s+(\{[^}]+\}|[a-zA-Z_$][\w$]*)\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
|
|
2665
|
+
while ((im = cjsRe.exec(content)) !== null) {
|
|
2666
|
+
const lhs = im[1].trim();
|
|
2667
|
+
const targetFile = resolveRelativeModule(f.path, im[2], knownFilesLower);
|
|
2668
|
+
if (!targetFile) continue;
|
|
2669
|
+
if (lhs.startsWith("{")) {
|
|
2670
|
+
for (const part of lhs.slice(1, -1).split(",")) {
|
|
2671
|
+
const p = part.trim();
|
|
2672
|
+
if (!p) continue;
|
|
2673
|
+
const colon = p.match(/^([a-zA-Z_$][\w$]*)\s*:\s*([a-zA-Z_$][\w$]*)$/);
|
|
2674
|
+
if (colon) {
|
|
2675
|
+
graph.addImportEdge(f.path, colon[2], targetFile, colon[1]);
|
|
2676
|
+
} else {
|
|
2677
|
+
graph.addImportEdge(f.path, p, targetFile, p);
|
|
2678
|
+
}
|
|
2679
|
+
}
|
|
2680
|
+
} else {
|
|
2681
|
+
graph.addImportEdge(f.path, lhs, targetFile, "*");
|
|
2682
|
+
}
|
|
2683
|
+
}
|
|
2684
|
+
} else if (f.language === "python") {
|
|
2685
|
+
const pyFromRe = /^from\s+(\.+[a-zA-Z0-9_.]*)\s+import\s+([^\n#]+)/gm;
|
|
2686
|
+
let pm;
|
|
2687
|
+
while ((pm = pyFromRe.exec(content)) !== null) {
|
|
2688
|
+
const relMod = pm[1];
|
|
2689
|
+
const dotsMatch = relMod.match(/^(\.+)(.*)$/);
|
|
2690
|
+
if (!dotsMatch) continue;
|
|
2691
|
+
const upLevels = dotsMatch[1].length - 1;
|
|
2692
|
+
let baseDir = dirname4(f.path);
|
|
2693
|
+
for (let u = 0; u < upLevels; u++) baseDir = dirname4(baseDir);
|
|
2694
|
+
const modSub = dotsMatch[2].replace(/\./g, "/");
|
|
2695
|
+
const cand = resolve6(baseDir, `${modSub}.py`).toLowerCase();
|
|
2696
|
+
const targetFile = knownFilesLower.get(cand);
|
|
2697
|
+
if (!targetFile) continue;
|
|
2698
|
+
for (const item of pm[2].split(",")) {
|
|
2699
|
+
const clean = item.trim();
|
|
2700
|
+
const asMatch = clean.match(/^(\w+)\s+as\s+(\w+)$/);
|
|
2701
|
+
if (asMatch) {
|
|
2702
|
+
graph.addImportEdge(f.path, asMatch[2], targetFile, asMatch[1]);
|
|
2703
|
+
} else if (/^\w+$/.test(clean)) {
|
|
2704
|
+
graph.addImportEdge(f.path, clean, targetFile, clean);
|
|
2705
|
+
}
|
|
2706
|
+
}
|
|
2707
|
+
}
|
|
2708
|
+
} else if (f.language === "php") {
|
|
2709
|
+
for (const assign of model.assignments) {
|
|
2710
|
+
if (/\$_(?:GET|POST|REQUEST)\b/.test(assign.rhsText) && !/\b(?:basename|in_array|intval)\s*\(/.test(assign.rhsText)) {
|
|
2711
|
+
for (const target of assign.targets) {
|
|
2712
|
+
if (target.startsWith("$")) {
|
|
2713
|
+
graph.addPhpSourceVar(f.path, {
|
|
2714
|
+
varName: target,
|
|
2715
|
+
sourceFile: f.path,
|
|
2716
|
+
sourceLine: assign.startLine,
|
|
2717
|
+
sourceSnippet: lines[assign.startLine - 1]?.trim() || assign.rhsText
|
|
2718
|
+
});
|
|
2719
|
+
}
|
|
2720
|
+
}
|
|
2721
|
+
}
|
|
2722
|
+
}
|
|
2723
|
+
const phpDir = dirname4(f.path);
|
|
2724
|
+
const staticIncRe = /\b(?:include|include_once|require|require_once)\s*(?:\(\s*|\s+)[^;'"\n]*['"]([^'"]+\.php)['"]/gi;
|
|
2725
|
+
let pim;
|
|
2726
|
+
while ((pim = staticIncRe.exec(content)) !== null) {
|
|
2727
|
+
const ref = pim[1].replace(/^[/\\]+/, "");
|
|
2728
|
+
const cand = resolve6(phpDir, ref).toLowerCase();
|
|
2729
|
+
const hit = knownFilesLower.get(cand);
|
|
2730
|
+
if (hit) graph.addPhpInclude(f.path, hit);
|
|
2731
|
+
}
|
|
2732
|
+
if (/\b(?:include|include_once|require|require_once)\b[^\n;]*\.php/.test(content) || /\bsource\/\{\$[^}]+\}\.php\b/i.test(content)) {
|
|
2733
|
+
const sourceSubdir = resolve6(phpDir, "source").toLowerCase();
|
|
2734
|
+
const siblingSources = phpFilesByDir.get(sourceSubdir);
|
|
2735
|
+
if (siblingSources) {
|
|
2736
|
+
for (const srcFile of siblingSources) {
|
|
2737
|
+
const nameLower = srcFile.toLowerCase();
|
|
2738
|
+
if (nameLower.endsWith(`${extname3(srcFile)}`) && !nameLower.endsWith("impossible.php")) {
|
|
2739
|
+
graph.addPhpInclude(f.path, srcFile);
|
|
2740
|
+
}
|
|
2741
|
+
}
|
|
2742
|
+
}
|
|
2743
|
+
}
|
|
2744
|
+
}
|
|
2745
|
+
}
|
|
2746
|
+
return graph;
|
|
2747
|
+
}
|
|
2748
|
+
|
|
1714
2749
|
// src/core/suppression.ts
|
|
1715
2750
|
var SUPPRESSION_REGEX = /(?:\/\/|#|--|\/\*)\s*deepscan-(disable-next-line|ignore-next-line|disable-line|ignore-line|disable|enable)(?:[:\s]+([a-zA-Z0-9_\-\s,\/*]+))?/i;
|
|
1716
2751
|
function parseSuppressions(content) {
|
|
@@ -1794,9 +2829,9 @@ function filterSuppressedFindings(findings, fileContent) {
|
|
|
1794
2829
|
}
|
|
1795
2830
|
|
|
1796
2831
|
// src/core/cache.ts
|
|
1797
|
-
import { readFileSync as readFileSync6, writeFileSync as writeFileSync2, mkdirSync as mkdirSync2, existsSync as
|
|
2832
|
+
import { readFileSync as readFileSync6, writeFileSync as writeFileSync2, mkdirSync as mkdirSync2, existsSync as existsSync6, rmSync } from "fs";
|
|
1798
2833
|
import { createHash } from "crypto";
|
|
1799
|
-
import { resolve as
|
|
2834
|
+
import { resolve as resolve7, dirname as dirname5 } from "path";
|
|
1800
2835
|
import { consola as consola5 } from "consola";
|
|
1801
2836
|
var ScanCache = class {
|
|
1802
2837
|
cachePath;
|
|
@@ -1807,7 +2842,7 @@ var ScanCache = class {
|
|
|
1807
2842
|
constructor(targetDir, enabled = true, customLocation, rulesHash = "") {
|
|
1808
2843
|
this.enabled = enabled;
|
|
1809
2844
|
this.rulesHash = rulesHash;
|
|
1810
|
-
this.cachePath = customLocation ?
|
|
2845
|
+
this.cachePath = customLocation ? resolve7(customLocation) : resolve7(targetDir, ".deepscan", "cache.json");
|
|
1811
2846
|
this.data = {
|
|
1812
2847
|
version: DEEPSCAN_VERSION,
|
|
1813
2848
|
rulesHash: this.rulesHash,
|
|
@@ -1826,7 +2861,7 @@ var ScanCache = class {
|
|
|
1826
2861
|
load() {
|
|
1827
2862
|
if (!this.enabled) return;
|
|
1828
2863
|
try {
|
|
1829
|
-
if (
|
|
2864
|
+
if (existsSync6(this.cachePath)) {
|
|
1830
2865
|
const raw = readFileSync6(this.cachePath, "utf-8");
|
|
1831
2866
|
const parsed = JSON.parse(raw);
|
|
1832
2867
|
if (this.rulesHash && parsed.rulesHash !== this.rulesHash) {
|
|
@@ -1881,8 +2916,8 @@ var ScanCache = class {
|
|
|
1881
2916
|
save() {
|
|
1882
2917
|
if (!this.enabled || !this.dirty) return;
|
|
1883
2918
|
try {
|
|
1884
|
-
const dir =
|
|
1885
|
-
if (!
|
|
2919
|
+
const dir = dirname5(this.cachePath);
|
|
2920
|
+
if (!existsSync6(dir)) {
|
|
1886
2921
|
mkdirSync2(dir, { recursive: true });
|
|
1887
2922
|
}
|
|
1888
2923
|
this.data.rulesHash = this.rulesHash;
|
|
@@ -1900,7 +2935,7 @@ var ScanCache = class {
|
|
|
1900
2935
|
this.data.entries = {};
|
|
1901
2936
|
this.dirty = false;
|
|
1902
2937
|
try {
|
|
1903
|
-
if (
|
|
2938
|
+
if (existsSync6(this.cachePath)) {
|
|
1904
2939
|
rmSync(this.cachePath, { force: true });
|
|
1905
2940
|
}
|
|
1906
2941
|
} catch {
|
|
@@ -1919,6 +2954,7 @@ var ScanPipeline = class {
|
|
|
1919
2954
|
findings = [];
|
|
1920
2955
|
seenLargeFileHashes = /* @__PURE__ */ new Set();
|
|
1921
2956
|
discoveredLockFiles = /* @__PURE__ */ new Set();
|
|
2957
|
+
projectGraph = null;
|
|
1922
2958
|
constructor(config) {
|
|
1923
2959
|
this.config = config;
|
|
1924
2960
|
this.ruleEngine = new RuleEngine(config);
|
|
@@ -1970,8 +3006,9 @@ var ScanPipeline = class {
|
|
|
1970
3006
|
return this.buildResult(targetPath, startTime, files.length);
|
|
1971
3007
|
}
|
|
1972
3008
|
this.discoveredLockFiles = new Set(
|
|
1973
|
-
files.filter((f) => f.isLockFile).map((f) =>
|
|
3009
|
+
files.filter((f) => f.isLockFile).map((f) => resolve8(f.path).toLowerCase())
|
|
1974
3010
|
);
|
|
3011
|
+
this.projectGraph = this.config.scanners.security.enabled && this.scanners.some((s) => s.type === "security") ? buildProjectGraph(files) : null;
|
|
1975
3012
|
let processed = 0;
|
|
1976
3013
|
const totalFiles = files.length;
|
|
1977
3014
|
const concurrency = Math.max(1, Math.min(32, this.config.parallel || 4));
|
|
@@ -2020,6 +3057,9 @@ var ScanPipeline = class {
|
|
|
2020
3057
|
async scanFile(file) {
|
|
2021
3058
|
const content = readFileContent(file.path);
|
|
2022
3059
|
if (!content) return;
|
|
3060
|
+
if (file.language === "typescript" && /^\s*(?:<\?xml\b|<!DOCTYPE\s+TS\b|<TS\b)/i.test(content.slice(0, 256))) {
|
|
3061
|
+
return;
|
|
3062
|
+
}
|
|
2023
3063
|
const contentHash = ScanCache.hashContent(content);
|
|
2024
3064
|
const cached = this.cache?.get(file.relativePath, contentHash);
|
|
2025
3065
|
if (cached) {
|
|
@@ -2035,6 +3075,8 @@ var ScanPipeline = class {
|
|
|
2035
3075
|
const rules = this.ruleEngine.getRulesForLanguage(file.language);
|
|
2036
3076
|
const skipAst = file.isLockFile || file.language === "dockerfile" || file.language === "yaml" || file.language === "config" || content.length > 25e4;
|
|
2037
3077
|
const tree = skipAst ? null : await this.astParser.parse(content, file.language, file.path);
|
|
3078
|
+
const buildModel = !skipAst && !file.isVendorFile && !file.isMinified && !file.isTestFile && file.language !== "unknown" && (this.config.scanners.security.enabled || Boolean(this.config.scanners.ops?.enabled));
|
|
3079
|
+
const codeModel = buildModel ? buildFileCodeModel(content, file.path, file.language, tree) : void 0;
|
|
2038
3080
|
const context = {
|
|
2039
3081
|
filePath: file.path,
|
|
2040
3082
|
content,
|
|
@@ -2043,7 +3085,9 @@ var ScanPipeline = class {
|
|
|
2043
3085
|
parser: this.astParser.getParser(),
|
|
2044
3086
|
config: this.config,
|
|
2045
3087
|
rules,
|
|
2046
|
-
discoveredLockFiles: this.discoveredLockFiles
|
|
3088
|
+
discoveredLockFiles: this.discoveredLockFiles,
|
|
3089
|
+
codeModel,
|
|
3090
|
+
projectGraph: this.projectGraph
|
|
2047
3091
|
};
|
|
2048
3092
|
const fileFindings = [];
|
|
2049
3093
|
for (const scanner of this.scanners) {
|
|
@@ -2057,6 +3101,7 @@ var ScanPipeline = class {
|
|
|
2057
3101
|
}
|
|
2058
3102
|
if (scanner.type === "security" || scanner.type === "ops" || scanner.type === "quality") {
|
|
2059
3103
|
if (file.isLockFile || file.isVendorFile || file.isMinified || file.language === "unknown") continue;
|
|
3104
|
+
if (file.isTestFile && file.language !== "config") continue;
|
|
2060
3105
|
}
|
|
2061
3106
|
if (scanner.type === "ops" || scanner.type === "quality") {
|
|
2062
3107
|
const lowerPath = file.path.toLowerCase();
|
|
@@ -2115,6 +3160,10 @@ var ScanPipeline = class {
|
|
|
2115
3160
|
const isGenericB = b.ruleId.startsWith("security/") || b.ruleId.startsWith("ops/");
|
|
2116
3161
|
if (isGenericA && !isGenericB) return 1;
|
|
2117
3162
|
if (!isGenericA && isGenericB) return -1;
|
|
3163
|
+
const isTaintA = a.ruleId.startsWith("SEC-TAINT-");
|
|
3164
|
+
const isTaintB = b.ruleId.startsWith("SEC-TAINT-");
|
|
3165
|
+
if (isTaintA && !isTaintB) return 1;
|
|
3166
|
+
if (!isTaintA && isTaintB) return -1;
|
|
2118
3167
|
const severityOrder = { critical: 0, high: 1, medium: 2, low: 3 };
|
|
2119
3168
|
const aSev = severityOrder[a.severity] ?? 4;
|
|
2120
3169
|
const bSev = severityOrder[b.severity] ?? 4;
|
|
@@ -2122,7 +3171,12 @@ var ScanPipeline = class {
|
|
|
2122
3171
|
if (sevDiff !== 0) return sevDiff;
|
|
2123
3172
|
return b.message.length - a.message.length;
|
|
2124
3173
|
});
|
|
2125
|
-
|
|
3174
|
+
const winner = group[0];
|
|
3175
|
+
if (!winner.taintFlow) {
|
|
3176
|
+
const withFlow = group.find((g) => g.taintFlow && g.taintFlow.length > 0);
|
|
3177
|
+
if (withFlow) winner.taintFlow = withFlow.taintFlow;
|
|
3178
|
+
}
|
|
3179
|
+
deduped.push(winner);
|
|
2126
3180
|
}
|
|
2127
3181
|
}
|
|
2128
3182
|
deduped.sort((a, b) => {
|
|
@@ -2172,10 +3226,10 @@ function generateFingerprint(ruleId, filePath, line, snippet) {
|
|
|
2172
3226
|
}
|
|
2173
3227
|
|
|
2174
3228
|
// src/core/baseline.ts
|
|
2175
|
-
import { existsSync as
|
|
2176
|
-
import { dirname as
|
|
3229
|
+
import { existsSync as existsSync7, mkdirSync as mkdirSync3, readFileSync as readFileSync7, writeFileSync as writeFileSync3 } from "fs";
|
|
3230
|
+
import { dirname as dirname6 } from "path";
|
|
2177
3231
|
function loadBaseline(filePath) {
|
|
2178
|
-
if (!
|
|
3232
|
+
if (!existsSync7(filePath)) {
|
|
2179
3233
|
throw new Error(`Baseline file not found: ${filePath}`);
|
|
2180
3234
|
}
|
|
2181
3235
|
const raw = JSON.parse(readFileSync7(filePath, "utf-8"));
|
|
@@ -2200,8 +3254,8 @@ function saveBaseline(filePath, findings) {
|
|
|
2200
3254
|
count: fingerprints.length,
|
|
2201
3255
|
fingerprints
|
|
2202
3256
|
};
|
|
2203
|
-
const dir =
|
|
2204
|
-
if (dir && !
|
|
3257
|
+
const dir = dirname6(filePath);
|
|
3258
|
+
if (dir && !existsSync7(dir)) {
|
|
2205
3259
|
mkdirSync3(dir, { recursive: true });
|
|
2206
3260
|
}
|
|
2207
3261
|
writeFileSync3(filePath, JSON.stringify(payload, null, 2), "utf-8");
|
|
@@ -2243,8 +3297,8 @@ function applyBaseline(result, baselineFingerprints) {
|
|
|
2243
3297
|
}
|
|
2244
3298
|
|
|
2245
3299
|
// src/config/loader.ts
|
|
2246
|
-
import { readFileSync as readFileSync8, existsSync as
|
|
2247
|
-
import { resolve as
|
|
3300
|
+
import { readFileSync as readFileSync8, existsSync as existsSync8 } from "fs";
|
|
3301
|
+
import { resolve as resolve9, dirname as dirname7 } from "path";
|
|
2248
3302
|
import yaml3 from "js-yaml";
|
|
2249
3303
|
import { consola as consola7 } from "consola";
|
|
2250
3304
|
var CONFIG_FILES = [
|
|
@@ -2263,7 +3317,7 @@ async function loadConfig(options) {
|
|
|
2263
3317
|
config = deepMerge(config, PRESETS[preset]);
|
|
2264
3318
|
consola7.debug(`Applied preset: ${preset}`);
|
|
2265
3319
|
}
|
|
2266
|
-
const searchDir = targetPath ?
|
|
3320
|
+
const searchDir = targetPath ? resolve9(targetPath) : process.cwd();
|
|
2267
3321
|
const detectedExcludes = detectEcosystemExcludes(searchDir);
|
|
2268
3322
|
if (detectedExcludes.length > 0) {
|
|
2269
3323
|
if (!config.paths) config.paths = { include: ["**/*"], exclude: [] };
|
|
@@ -2290,13 +3344,13 @@ async function loadConfig(options) {
|
|
|
2290
3344
|
}
|
|
2291
3345
|
async function loadProjectConfig(explicitPath, targetPath) {
|
|
2292
3346
|
if (explicitPath) {
|
|
2293
|
-
if (!
|
|
3347
|
+
if (!existsSync8(explicitPath)) {
|
|
2294
3348
|
consola7.warn(`Config file not found: ${explicitPath}`);
|
|
2295
3349
|
return null;
|
|
2296
3350
|
}
|
|
2297
3351
|
return parseConfigFile(explicitPath);
|
|
2298
3352
|
}
|
|
2299
|
-
const searchDir = targetPath ?
|
|
3353
|
+
const searchDir = targetPath ? resolve9(targetPath) : process.cwd();
|
|
2300
3354
|
const configPath = findConfigFile(searchDir);
|
|
2301
3355
|
if (configPath) {
|
|
2302
3356
|
return parseConfigFile(configPath);
|
|
@@ -2307,12 +3361,12 @@ function findConfigFile(startDir) {
|
|
|
2307
3361
|
let currentDir = startDir;
|
|
2308
3362
|
for (let i = 0; i < 10; i++) {
|
|
2309
3363
|
for (const fileName of CONFIG_FILES) {
|
|
2310
|
-
const filePath =
|
|
2311
|
-
if (
|
|
3364
|
+
const filePath = resolve9(currentDir, fileName);
|
|
3365
|
+
if (existsSync8(filePath)) {
|
|
2312
3366
|
return filePath;
|
|
2313
3367
|
}
|
|
2314
3368
|
}
|
|
2315
|
-
const parentDir =
|
|
3369
|
+
const parentDir = dirname7(currentDir);
|
|
2316
3370
|
if (parentDir === currentDir) break;
|
|
2317
3371
|
currentDir = parentDir;
|
|
2318
3372
|
}
|
|
@@ -2370,7 +3424,7 @@ function resolveEnvVars(obj) {
|
|
|
2370
3424
|
}
|
|
2371
3425
|
function detectEcosystemExcludes(targetPath) {
|
|
2372
3426
|
const excludes = [];
|
|
2373
|
-
if (
|
|
3427
|
+
if (existsSync8(resolve9(targetPath, "package.json")) || existsSync8(resolve9(targetPath, "package-lock.json")) || existsSync8(resolve9(targetPath, "yarn.lock")) || existsSync8(resolve9(targetPath, "pnpm-lock.yaml"))) {
|
|
2374
3428
|
excludes.push(
|
|
2375
3429
|
"dist/",
|
|
2376
3430
|
"**/dist/**",
|
|
@@ -2394,7 +3448,7 @@ function detectEcosystemExcludes(targetPath) {
|
|
|
2394
3448
|
"**/public/storage/**"
|
|
2395
3449
|
);
|
|
2396
3450
|
}
|
|
2397
|
-
if (
|
|
3451
|
+
if (existsSync8(resolve9(targetPath, "composer.json")) || existsSync8(resolve9(targetPath, "composer.lock")) || existsSync8(resolve9(targetPath, "artisan"))) {
|
|
2398
3452
|
excludes.push(
|
|
2399
3453
|
"vendor/",
|
|
2400
3454
|
"**/vendor/**",
|
|
@@ -2410,7 +3464,7 @@ function detectEcosystemExcludes(targetPath) {
|
|
|
2410
3464
|
"**/public/storage/**"
|
|
2411
3465
|
);
|
|
2412
3466
|
}
|
|
2413
|
-
if (
|
|
3467
|
+
if (existsSync8(resolve9(targetPath, "requirements.txt")) || existsSync8(resolve9(targetPath, "pyproject.toml")) || existsSync8(resolve9(targetPath, "Pipfile")) || existsSync8(resolve9(targetPath, "setup.py"))) {
|
|
2414
3468
|
excludes.push(
|
|
2415
3469
|
"__pycache__/",
|
|
2416
3470
|
"**/__pycache__/**",
|
|
@@ -2428,7 +3482,7 @@ function detectEcosystemExcludes(targetPath) {
|
|
|
2428
3482
|
"**/.tmp/**"
|
|
2429
3483
|
);
|
|
2430
3484
|
}
|
|
2431
|
-
if (
|
|
3485
|
+
if (existsSync8(resolve9(targetPath, "pom.xml")) || existsSync8(resolve9(targetPath, "build.gradle")) || existsSync8(resolve9(targetPath, "build.gradle.kts")) || existsSync8(resolve9(targetPath, "Directory.Build.props"))) {
|
|
2432
3486
|
excludes.push(
|
|
2433
3487
|
"target/",
|
|
2434
3488
|
"**/target/**",
|
|
@@ -2445,8 +3499,8 @@ function detectEcosystemExcludes(targetPath) {
|
|
|
2445
3499
|
import chalk from "chalk";
|
|
2446
3500
|
|
|
2447
3501
|
// src/reporters/base-reporter.ts
|
|
2448
|
-
import { writeFileSync as writeFileSync4, mkdirSync as mkdirSync4, existsSync as
|
|
2449
|
-
import { dirname as
|
|
3502
|
+
import { writeFileSync as writeFileSync4, mkdirSync as mkdirSync4, existsSync as existsSync9 } from "fs";
|
|
3503
|
+
import { dirname as dirname8 } from "path";
|
|
2450
3504
|
var BaseReporter = class {
|
|
2451
3505
|
/**
|
|
2452
3506
|
* Write the generated report to the specified file path.
|
|
@@ -2463,8 +3517,8 @@ var BaseReporter = class {
|
|
|
2463
3517
|
* if necessary.
|
|
2464
3518
|
*/
|
|
2465
3519
|
ensureDirectoryExists(filePath) {
|
|
2466
|
-
const dir =
|
|
2467
|
-
if (!
|
|
3520
|
+
const dir = dirname8(filePath);
|
|
3521
|
+
if (!existsSync9(dir)) {
|
|
2468
3522
|
mkdirSync4(dir, { recursive: true });
|
|
2469
3523
|
}
|
|
2470
3524
|
}
|
|
@@ -3663,6 +4717,19 @@ function isInCommentOrString(line, column) {
|
|
|
3663
4717
|
if (trimmed.startsWith("//") || trimmed.startsWith("#") || trimmed.startsWith("*") || trimmed.startsWith("/*")) {
|
|
3664
4718
|
return true;
|
|
3665
4719
|
}
|
|
4720
|
+
const targetIdx = column - 1;
|
|
4721
|
+
let i = 0;
|
|
4722
|
+
while (i < line.length && i < targetIdx) {
|
|
4723
|
+
const ch = line[i];
|
|
4724
|
+
if (ch === "'" || ch === '"' || ch === "`") {
|
|
4725
|
+
i = skipStringLiteral(line, i);
|
|
4726
|
+
continue;
|
|
4727
|
+
}
|
|
4728
|
+
if (ch === "/" && i + 1 < line.length && line[i + 1] === "/") {
|
|
4729
|
+
return true;
|
|
4730
|
+
}
|
|
4731
|
+
i++;
|
|
4732
|
+
}
|
|
3666
4733
|
return false;
|
|
3667
4734
|
}
|
|
3668
4735
|
function isPatternDefinitionContext(lineContent, column) {
|
|
@@ -3904,6 +4971,9 @@ function isSafeSqlInterpolation(content, filePath, lineNumber, lineContent) {
|
|
|
3904
4971
|
if (concatVars.length > 0 && concatVars.every((v) => /^[A-Z][A-Z0-9_]+$/.test(v))) {
|
|
3905
4972
|
return true;
|
|
3906
4973
|
}
|
|
4974
|
+
if (/\b(?:quote_name|quoteName|escapeId|escapeIdentifier|escapedDBName)\b/.test(lineContent) || /\b(?:CREATE\s+(?:UNIQUE\s+)?INDEX|DROP\s+(?:EXTENSION|COLLATION|DATABASE)|CREATE\s+DATABASE\s+IF\s+NOT\s+EXISTS)\b/i.test(lineContent)) {
|
|
4975
|
+
return true;
|
|
4976
|
+
}
|
|
3907
4977
|
const lines = content.split("\n");
|
|
3908
4978
|
const queryWindow = lines.slice(Math.max(0, lineNumber - 1), Math.min(lines.length, lineNumber + 6)).join("\n");
|
|
3909
4979
|
if (queryWindow.includes("${")) {
|
|
@@ -3911,7 +4981,7 @@ function isSafeSqlInterpolation(content, filePath, lineNumber, lineContent) {
|
|
|
3911
4981
|
const allSafeSqlInterp = interpMatches.length > 0 && interpMatches.every(
|
|
3912
4982
|
(expr) => /^(?:whereSql|whereClause|where|orderSql|orderBy|limitSql|joinSql|groupSql|havingSql|limIdx|offIdx|pIdx|paramIdx|idx|placeholder\w*|table|tableName|columns|fields|selectFields)$/i.test(
|
|
3913
4983
|
expr
|
|
3914
|
-
)
|
|
4984
|
+
) || /^(?:query|eventQuery|baseQuery|countQuery|subQuery|cteQuery)$/i.test(expr) && /\b(?:rawQuery|queryParams|params)\b/.test(queryWindow)
|
|
3915
4985
|
);
|
|
3916
4986
|
if (allSafeSqlInterp) return true;
|
|
3917
4987
|
}
|
|
@@ -3994,8 +5064,8 @@ var BaseScanner = class {
|
|
|
3994
5064
|
}
|
|
3995
5065
|
}
|
|
3996
5066
|
if (/process\.env\b|os\.environ|os\.getenv|System\.getenv|System\.getProperty|ENV\[|getenv\s*\(|\benv\s*\(/i.test(line)) {
|
|
3997
|
-
const
|
|
3998
|
-
if (!hasSecretEnvFallback && !
|
|
5067
|
+
const isHardcodedTokenPrefix2 = /^(?:AKIA|ABIA|ACCA|ASIA|ghp_|gho_|ghu_|ghs_|ghr_|xox[bpors]-|sk_live_|rk_live_|AIza|GOCSPX-|SG\.|sq0atp-|npm_|dapi|dop_v1_|shpat_)/.test(val);
|
|
5068
|
+
if (!hasSecretEnvFallback && !isHardcodedTokenPrefix2) {
|
|
3999
5069
|
continue;
|
|
4000
5070
|
}
|
|
4001
5071
|
}
|
|
@@ -4020,6 +5090,22 @@ var BaseScanner = class {
|
|
|
4020
5090
|
continue;
|
|
4021
5091
|
}
|
|
4022
5092
|
}
|
|
5093
|
+
const isHardcodedTokenPrefix = /^(?:AKIA|ABIA|ACCA|ASIA|ghp_|gho_|ghu_|ghs_|ghr_|xox[bpors]-|sk_live_|rk_live_|AIza|GOCSPX-|SG\.|sq0atp-|npm_|dapi|dop_v1_|shpat_)/.test(val);
|
|
5094
|
+
if (!hasSecretEnvFallback && !isHardcodedTokenPrefix && /(?:password|passwd|pwd|pass|secret|credential)\s*[:=]/i.test(val)) {
|
|
5095
|
+
if (/\b(?:placeholder|aria-label|helperText|hint)\s*=\s*["']/.test(line)) {
|
|
5096
|
+
continue;
|
|
5097
|
+
}
|
|
5098
|
+
const isDbConfig = /\b(?:createConnection|createPool|DataSource|DATABASE_URL|PGPASSWORD|DB_PASS|DB_PASSWORD|mysql|postgres|mongodb|redis)\b/i.test(line);
|
|
5099
|
+
if (!isDbConfig) {
|
|
5100
|
+
const lines = context.content.split("\n");
|
|
5101
|
+
const precedingWindow = lines.slice(Math.max(0, match.line - 26), match.line).join("\n");
|
|
5102
|
+
const devLoginGateRe = /\b(?:ENABLE_DEV_LOGIN|VITE_ENABLE_DEV_LOGIN|NEXT_PUBLIC_ENABLE_DEV_LOGIN|ALLOW_DEV_LOGIN|DEV_LOGIN|ENABLE_DEMO_LOGIN|DEMO_LOGIN_ENABLED)\b|NODE_ENV\s*(?:===?\s*['"](?:development|dev|local|test)['"]|!==?\s*['"]production['"])|\bimport\.meta\.env\.DEV\b/;
|
|
5103
|
+
const isJsxView = /\.(?:jsx|tsx)$/i.test(context.filePath);
|
|
5104
|
+
if (devLoginGateRe.test(precedingWindow) || isJsxView && devLoginGateRe.test(context.content)) {
|
|
5105
|
+
continue;
|
|
5106
|
+
}
|
|
5107
|
+
}
|
|
5108
|
+
}
|
|
4023
5109
|
if (!/^(?:AKIA|ASIA|ABIA|ACCA)[0-9A-Z]{16}$/i.test(val) && /(?:example|placeholder|your[_-]|\bchangeme\b|^["']?changeme\d*["']?$|change[_-]me|xxxx|TODO|FIXME|replace[_-]me|dummy)/i.test(val)) {
|
|
4024
5110
|
continue;
|
|
4025
5111
|
}
|
|
@@ -4188,6 +5274,11 @@ var BaseScanner = class {
|
|
|
4188
5274
|
continue;
|
|
4189
5275
|
}
|
|
4190
5276
|
}
|
|
5277
|
+
if (rule.id === "security/weak-auth") {
|
|
5278
|
+
if (/\btypeof\s+[\w.[\]?$]*\b(?:password|passwd|pwd|pass)\s*[!=]==?\s*["'](?:string|number|boolean|undefined|object|function|symbol|bigint)["']/i.test(match.lineContent) || /\b(?:type|name|field|kind|role)\s*[!=]==?\s*["'](?:password|passwd|pwd)["']/i.test(match.lineContent)) {
|
|
5279
|
+
continue;
|
|
5280
|
+
}
|
|
5281
|
+
}
|
|
4191
5282
|
const snippet = extractSnippet(context.content, match.line);
|
|
4192
5283
|
findings.push(
|
|
4193
5284
|
createFinding({
|
|
@@ -4220,271 +5311,108 @@ var BaseScanner = class {
|
|
|
4220
5311
|
};
|
|
4221
5312
|
|
|
4222
5313
|
// src/core/taint-tracker.ts
|
|
4223
|
-
|
|
4224
|
-
|
|
4225
|
-
|
|
4226
|
-
|
|
4227
|
-
|
|
4228
|
-
|
|
4229
|
-
|
|
4230
|
-
|
|
4231
|
-
|
|
4232
|
-
|
|
4233
|
-
|
|
4234
|
-
|
|
4235
|
-
|
|
4236
|
-
|
|
4237
|
-
};
|
|
4238
|
-
|
|
4239
|
-
addUnique(
|
|
4240
|
-
analyzeTaintFlowAST(
|
|
4241
|
-
tree,
|
|
4242
|
-
content,
|
|
4243
|
-
filePath,
|
|
4244
|
-
langConfig.taintSources,
|
|
4245
|
-
langConfig.taintSinks,
|
|
4246
|
-
langConfig.sanitizers
|
|
4247
|
-
)
|
|
4248
|
-
);
|
|
4249
|
-
}
|
|
4250
|
-
addUnique(
|
|
4251
|
-
analyzeTaintFlowRegex(
|
|
4252
|
-
content,
|
|
4253
|
-
filePath,
|
|
4254
|
-
langConfig.taintSources,
|
|
4255
|
-
langConfig.taintSinks,
|
|
4256
|
-
langConfig.sanitizers
|
|
4257
|
-
)
|
|
4258
|
-
);
|
|
4259
|
-
return combined;
|
|
5314
|
+
var FRONTEND_PATH_RE = /(?:^|[\\/])(?:public|frontend|client|admin_views|extension|src[\\/](?:components|pages|views|hooks|store|assets))[\\/]/i;
|
|
5315
|
+
var LOCAL_SCRIPT_PATH_RE = /(?:^|[\\/])(?:scripts?|tools?|bin|dev)[\\/]/i;
|
|
5316
|
+
var NOSQL_METHODS = /* @__PURE__ */ new Set([
|
|
5317
|
+
"find",
|
|
5318
|
+
"findOne",
|
|
5319
|
+
"findOneAndUpdate",
|
|
5320
|
+
"update",
|
|
5321
|
+
"updateOne",
|
|
5322
|
+
"updateMany",
|
|
5323
|
+
"deleteOne",
|
|
5324
|
+
"deleteMany",
|
|
5325
|
+
"remove"
|
|
5326
|
+
]);
|
|
5327
|
+
function containsVariable(expr, varName) {
|
|
5328
|
+
const escaped = varName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
5329
|
+
return new RegExp(`(?:^|[^a-zA-Z0-9_$])${escaped}(?![a-zA-Z0-9_$])`).test(expr);
|
|
4260
5330
|
}
|
|
4261
|
-
function
|
|
4262
|
-
|
|
4263
|
-
|
|
4264
|
-
|
|
4265
|
-
|
|
4266
|
-
startLine: node.startPosition.row + 1,
|
|
4267
|
-
startColumn: node.startPosition.column,
|
|
4268
|
-
endLine: node.endPosition.row + 1,
|
|
4269
|
-
endColumn: node.endPosition.column,
|
|
4270
|
-
snippet: node.text.split("\n")[0]
|
|
4271
|
-
});
|
|
4272
|
-
function traverse(node) {
|
|
4273
|
-
if (node.type === "variable_declarator") {
|
|
4274
|
-
const idNode = node.childForFieldName("name") || node.children.find((n) => n.type === "identifier");
|
|
4275
|
-
const valueNode = node.childForFieldName("value");
|
|
4276
|
-
if (idNode && valueNode) {
|
|
4277
|
-
checkAssignment(idNode, valueNode);
|
|
4278
|
-
}
|
|
4279
|
-
}
|
|
4280
|
-
if (node.type === "assignment_expression" || node.type === "assignment" || node.type === "short_var_declaration") {
|
|
4281
|
-
const leftNode = node.childForFieldName("left");
|
|
4282
|
-
const rightNode = node.childForFieldName("right");
|
|
4283
|
-
if (leftNode && rightNode) {
|
|
4284
|
-
checkAssignment(leftNode, rightNode);
|
|
4285
|
-
}
|
|
4286
|
-
}
|
|
4287
|
-
if (node.type === "call_expression" || node.type === "call") {
|
|
4288
|
-
const funcNode = node.childForFieldName("function");
|
|
4289
|
-
const argsNode = node.childForFieldName("arguments");
|
|
4290
|
-
if (funcNode && argsNode) {
|
|
4291
|
-
const funcName = funcNode.text;
|
|
4292
|
-
const matchedSink = sinks.find((s) => {
|
|
4293
|
-
const sName = s.pattern.replace(/\$TAINTED|\(|\)/g, "").replace(/[^a-zA-Z0-9_.]/g, "");
|
|
4294
|
-
if (sName === "exec") {
|
|
4295
|
-
return funcName === "exec" || /(?:child_process|cp|shell|proc)\s*\.\s*exec$/i.test(funcName);
|
|
4296
|
-
}
|
|
4297
|
-
if (sName === "eval") {
|
|
4298
|
-
return funcName === "eval" || /^(?:window|globalThis|global)\s*\.\s*eval$/.test(funcName);
|
|
4299
|
-
}
|
|
4300
|
-
return funcName === sName || funcName.endsWith(`.${sName}`);
|
|
4301
|
-
});
|
|
4302
|
-
if (matchedSink) {
|
|
4303
|
-
const realArgs = [];
|
|
4304
|
-
for (let i = 0; i < argsNode.childCount; i++) {
|
|
4305
|
-
const c = argsNode.child(i);
|
|
4306
|
-
if (c && c.type !== "(" && c.type !== ")" && c.type !== ",") {
|
|
4307
|
-
realArgs.push(c);
|
|
4308
|
-
}
|
|
4309
|
-
}
|
|
4310
|
-
if (matchedSink.type === "format_string" && realArgs.length > 0) {
|
|
4311
|
-
const firstArgText = realArgs[0].text.trim();
|
|
4312
|
-
if (/^["'`]/.test(firstArgText) || realArgs[0].type.includes("string")) {
|
|
4313
|
-
return;
|
|
4314
|
-
}
|
|
4315
|
-
}
|
|
4316
|
-
if (matchedSink.pattern.includes("prepareStatement") && realArgs.length > 0) {
|
|
4317
|
-
if (!realArgs[0].text.includes("+")) {
|
|
4318
|
-
return;
|
|
4319
|
-
}
|
|
4320
|
-
}
|
|
4321
|
-
for (const arg of realArgs) {
|
|
4322
|
-
const taintedArg = findTaintedVarInExpression(arg, taintedVars);
|
|
4323
|
-
if (taintedArg && !taintedArg.sanitized.has(matchedSink.type)) {
|
|
4324
|
-
results.push({
|
|
4325
|
-
hasTaintedSink: true,
|
|
4326
|
-
sourceType: taintedArg.sourceType,
|
|
4327
|
-
sinkType: matchedSink.type,
|
|
4328
|
-
flow: [
|
|
4329
|
-
...taintedArg.propagationPath,
|
|
4330
|
-
{
|
|
4331
|
-
location: getLocation(node),
|
|
4332
|
-
label: `Sink: ${matchedSink.description} (${matchedSink.type})`,
|
|
4333
|
-
kind: "sink"
|
|
4334
|
-
}
|
|
4335
|
-
]
|
|
4336
|
-
});
|
|
4337
|
-
}
|
|
4338
|
-
}
|
|
4339
|
-
}
|
|
4340
|
-
}
|
|
4341
|
-
}
|
|
4342
|
-
for (let i = 0; i < node.childCount; i++) {
|
|
4343
|
-
traverse(node.child(i));
|
|
4344
|
-
}
|
|
4345
|
-
}
|
|
4346
|
-
function checkAssignment(leftNode, rightNode) {
|
|
4347
|
-
const varName = leftNode.text.trim();
|
|
4348
|
-
const rightText = rightNode.text;
|
|
4349
|
-
const matchedSource = sources.find((s) => {
|
|
4350
|
-
const sName = s.pattern.replace(/\$TAINTED|\(|\)/g, "").replace(/[^a-zA-Z0-9_.$]/g, "");
|
|
4351
|
-
return sName.length > 0 && rightText.includes(sName);
|
|
4352
|
-
});
|
|
4353
|
-
if (matchedSource) {
|
|
4354
|
-
const initialSanitized = /* @__PURE__ */ new Set();
|
|
4355
|
-
for (const s of sanitizers) {
|
|
4356
|
-
const sName = s.pattern.replace(/\$TAINTED|\$X|\(|\)/g, "").replace(/[^a-zA-Z0-9_.]/g, "");
|
|
4357
|
-
if (sName.length > 0 && rightText.includes(sName)) {
|
|
4358
|
-
for (const c of s.cleanses) initialSanitized.add(c);
|
|
4359
|
-
}
|
|
4360
|
-
}
|
|
4361
|
-
taintedVars.set(varName, {
|
|
4362
|
-
id: `taint_${varName}`,
|
|
4363
|
-
sourceType: matchedSource.type,
|
|
4364
|
-
originLocation: getLocation(rightNode),
|
|
4365
|
-
currentVariable: varName,
|
|
4366
|
-
sanitized: initialSanitized,
|
|
4367
|
-
propagationPath: [
|
|
4368
|
-
{
|
|
4369
|
-
location: getLocation(rightNode),
|
|
4370
|
-
label: `Source: ${matchedSource.description}`,
|
|
4371
|
-
kind: "source"
|
|
4372
|
-
}
|
|
4373
|
-
]
|
|
4374
|
-
});
|
|
4375
|
-
return;
|
|
4376
|
-
}
|
|
4377
|
-
const taintedSource = findTaintedVarInExpression(rightNode, taintedVars);
|
|
4378
|
-
if (taintedSource) {
|
|
4379
|
-
const isSanitized = sanitizers.some((s) => {
|
|
4380
|
-
const sName = s.pattern.replace(/\$TAINTED|\$X|\(|\)/g, "").replace(/[^a-zA-Z0-9_.]/g, "");
|
|
4381
|
-
return sName.length > 0 && rightText.includes(sName);
|
|
4382
|
-
});
|
|
4383
|
-
if (!isSanitized) {
|
|
4384
|
-
taintedVars.set(varName, {
|
|
4385
|
-
...taintedSource,
|
|
4386
|
-
currentVariable: varName,
|
|
4387
|
-
propagationPath: [
|
|
4388
|
-
...taintedSource.propagationPath,
|
|
4389
|
-
{
|
|
4390
|
-
location: getLocation(leftNode),
|
|
4391
|
-
label: `Propagated to ${varName}`,
|
|
4392
|
-
kind: "propagator"
|
|
4393
|
-
}
|
|
4394
|
-
]
|
|
4395
|
-
});
|
|
4396
|
-
}
|
|
4397
|
-
}
|
|
5331
|
+
function matchesSourceToken(expr, tok) {
|
|
5332
|
+
if (!tok) return false;
|
|
5333
|
+
if (/^[a-zA-Z_]\w*$/.test(tok)) {
|
|
5334
|
+
const escaped = tok.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
5335
|
+
return new RegExp(`(?:^|[^a-zA-Z0-9_.])${escaped}(?![a-zA-Z0-9_])`).test(expr);
|
|
4398
5336
|
}
|
|
4399
|
-
|
|
4400
|
-
|
|
4401
|
-
|
|
4402
|
-
|
|
4403
|
-
|
|
4404
|
-
|
|
4405
|
-
|
|
4406
|
-
|
|
4407
|
-
found = map.get(n.text);
|
|
4408
|
-
return;
|
|
4409
|
-
}
|
|
4410
|
-
for (let i = 0; i < n.childCount; i++) walk(n.child(i));
|
|
5337
|
+
return expr.includes(tok);
|
|
5338
|
+
}
|
|
5339
|
+
function getSanitizerMatches(text, sanitizers) {
|
|
5340
|
+
const cleansed = /* @__PURE__ */ new Set();
|
|
5341
|
+
for (const s of sanitizers) {
|
|
5342
|
+
const sName = s.pattern.replace(/\$TAINTED|\$X|\(|\)/g, "").trim();
|
|
5343
|
+
if (sName.length > 0 && text.includes(sName)) {
|
|
5344
|
+
for (const c of s.cleanses) cleansed.add(c);
|
|
4411
5345
|
}
|
|
4412
|
-
walk(node);
|
|
4413
|
-
return found;
|
|
4414
5346
|
}
|
|
4415
|
-
|
|
4416
|
-
|
|
5347
|
+
return cleansed;
|
|
5348
|
+
}
|
|
5349
|
+
function makeLocation(filePath, line, snippet, column = 1) {
|
|
5350
|
+
return {
|
|
5351
|
+
file: filePath,
|
|
5352
|
+
startLine: line,
|
|
5353
|
+
startColumn: column,
|
|
5354
|
+
endLine: line,
|
|
5355
|
+
endColumn: Math.max(column, snippet.length),
|
|
5356
|
+
snippet
|
|
5357
|
+
};
|
|
4417
5358
|
}
|
|
4418
|
-
function
|
|
5359
|
+
function getScopeText(lines, model, scopeId) {
|
|
5360
|
+
if (scopeId === 0) return lines.join("\n");
|
|
5361
|
+
const scope = model.scopes.find((s) => s.id === scopeId);
|
|
5362
|
+
if (!scope) return lines.join("\n");
|
|
5363
|
+
return lines.slice(Math.max(0, scope.startLine - 1), Math.min(lines.length, scope.endLine)).join("\n");
|
|
5364
|
+
}
|
|
5365
|
+
function extractIntraFileHelpers(model, lines, sinks, sanitizers) {
|
|
4419
5366
|
const summaries = /* @__PURE__ */ new Map();
|
|
4420
|
-
const
|
|
4421
|
-
|
|
4422
|
-
const
|
|
4423
|
-
const m = trimmed.match(funcHeaderRegex);
|
|
4424
|
-
if (!m) continue;
|
|
4425
|
-
const funcName = m[1] || m[3] || m[5] || m[7];
|
|
4426
|
-
const rawParams = m[2] ?? m[4] ?? m[6] ?? m[8] ?? "";
|
|
4427
|
-
if (!funcName) continue;
|
|
4428
|
-
const params = rawParams.split(",").map((p) => p.trim()).filter(Boolean).map((p) => {
|
|
4429
|
-
const clean = p.replace(/^\.\.\./, "").split(/\s*[:=]\s*/)[0].trim();
|
|
4430
|
-
const parts = clean.split(/\s+/);
|
|
4431
|
-
if (parts.length >= 2) {
|
|
4432
|
-
const first = parts[0];
|
|
4433
|
-
const last = parts[parts.length - 1];
|
|
4434
|
-
if (/^(?:string|int|bool|float\d*|byte|rune|error|interface\{\}|any)$/i.test(last) || last.startsWith("[]") || last.startsWith("*")) {
|
|
4435
|
-
return first;
|
|
4436
|
-
}
|
|
4437
|
-
return last;
|
|
4438
|
-
}
|
|
4439
|
-
return parts[0];
|
|
4440
|
-
}).filter((p) => p && p !== "_" && p !== "self" && p !== "this");
|
|
4441
|
-
if (params.length === 0) continue;
|
|
4442
|
-
const endLine = Math.min(lines.length, i + 45);
|
|
5367
|
+
for (const scope of model.scopes) {
|
|
5368
|
+
if (scope.name.startsWith("<") || scope.params.length === 0) continue;
|
|
5369
|
+
const endLine = Math.min(lines.length, scope.endLine);
|
|
4443
5370
|
const passthroughParamIndices = /* @__PURE__ */ new Set();
|
|
4444
5371
|
const sinkHits = [];
|
|
4445
|
-
for (let pIdx = 0; pIdx < params.length; pIdx++) {
|
|
4446
|
-
const paramName = params[pIdx];
|
|
4447
|
-
const escapedParam = paramName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
4448
|
-
const paramRegex = new RegExp(`(?:^|[^a-zA-Z0-9_])${escapedParam}(?![a-zA-Z0-9_])`);
|
|
5372
|
+
for (let pIdx = 0; pIdx < scope.params.length; pIdx++) {
|
|
5373
|
+
const paramName = scope.params[pIdx];
|
|
4449
5374
|
const derivedVars = /* @__PURE__ */ new Set([paramName]);
|
|
4450
|
-
for (
|
|
4451
|
-
|
|
5375
|
+
for (const assign of model.assignments) {
|
|
5376
|
+
if (assign.scopeId !== scope.id) continue;
|
|
5377
|
+
if (getSanitizerMatches(assign.rhsText, sanitizers).size > 0) continue;
|
|
5378
|
+
if (Array.from(derivedVars).some((v) => containsVariable(assign.rhsText, v))) {
|
|
5379
|
+
for (const t of assign.targets) derivedVars.add(t);
|
|
5380
|
+
}
|
|
5381
|
+
}
|
|
5382
|
+
for (let ln = scope.startLine + 1; ln <= endLine; ln++) {
|
|
5383
|
+
const bodyLine = lines[ln - 1].trim();
|
|
4452
5384
|
if (!bodyLine || bodyLine.startsWith("//") || bodyLine.startsWith("#")) continue;
|
|
4453
|
-
if (
|
|
4454
|
-
const hasDerived = Array.from(derivedVars).some((v) =>
|
|
4455
|
-
const esc = v.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
4456
|
-
return new RegExp(`(?:^|[^a-zA-Z0-9_])${esc}(?![a-zA-Z0-9_])`).test(bodyLine);
|
|
4457
|
-
});
|
|
5385
|
+
if (getSanitizerMatches(bodyLine, sanitizers).size > 0) continue;
|
|
5386
|
+
const hasDerived = Array.from(derivedVars).some((v) => containsVariable(bodyLine, v));
|
|
4458
5387
|
if (!hasDerived) continue;
|
|
4459
|
-
|
|
4460
|
-
const sName = s.pattern.replace(/\$TAINTED|\$X|\(|\)/g, "").trim();
|
|
4461
|
-
return sName.length > 0 && bodyLine.includes(sName);
|
|
4462
|
-
});
|
|
4463
|
-
if (isSanitized) continue;
|
|
4464
|
-
const localAssign = bodyLine.match(/^(?:(?:const|let|var|final|auto)\s+)?(\$?[a-zA-Z_]\w*)\s*:?=\s*(.+)$/);
|
|
4465
|
-
if (localAssign) {
|
|
4466
|
-
derivedVars.add(localAssign[1]);
|
|
4467
|
-
}
|
|
4468
|
-
if (/^return\b/.test(bodyLine) || paramRegex.test(bodyLine) && j === endLine - 1) {
|
|
5388
|
+
if (/^return\b/.test(bodyLine) || ln === endLine && containsVariable(bodyLine, paramName)) {
|
|
4469
5389
|
passthroughParamIndices.add(pIdx);
|
|
4470
5390
|
}
|
|
5391
|
+
}
|
|
5392
|
+
for (const call of model.callSites) {
|
|
5393
|
+
if (call.scopeId !== scope.id) continue;
|
|
5394
|
+
if (getSanitizerMatches(call.fullText, sanitizers).size > 0) continue;
|
|
4471
5395
|
for (const sink of sinks) {
|
|
4472
|
-
if (
|
|
4473
|
-
|
|
4474
|
-
|
|
4475
|
-
|
|
4476
|
-
|
|
4477
|
-
|
|
4478
|
-
|
|
5396
|
+
if (matchCallSiteToSink(call, sink) >= 0) {
|
|
5397
|
+
const argIdx = matchCallSiteToSink(call, sink);
|
|
5398
|
+
const arg = call.args[argIdx];
|
|
5399
|
+
if (arg && !arg.isLiteral && Array.from(derivedVars).some((v) => containsVariable(arg.text, v))) {
|
|
5400
|
+
sinkHits.push({
|
|
5401
|
+
paramIndex: pIdx,
|
|
5402
|
+
sink,
|
|
5403
|
+
sinkLine: call.startLine,
|
|
5404
|
+
sinkSnippet: lines[call.startLine - 1]?.trim() || call.fullText.split("\n")[0]
|
|
5405
|
+
});
|
|
5406
|
+
}
|
|
4479
5407
|
}
|
|
4480
5408
|
}
|
|
4481
5409
|
}
|
|
4482
5410
|
}
|
|
4483
5411
|
if (passthroughParamIndices.size > 0 || sinkHits.length > 0) {
|
|
4484
|
-
summaries.set(
|
|
4485
|
-
name:
|
|
4486
|
-
params,
|
|
4487
|
-
startLine:
|
|
5412
|
+
summaries.set(scope.name, {
|
|
5413
|
+
name: scope.name,
|
|
5414
|
+
params: scope.params,
|
|
5415
|
+
startLine: scope.startLine,
|
|
4488
5416
|
endLine,
|
|
4489
5417
|
passthroughParamIndices,
|
|
4490
5418
|
sinkHits
|
|
@@ -4493,236 +5421,422 @@ function extractHelperFunctions(lines, sinks, sanitizers) {
|
|
|
4493
5421
|
}
|
|
4494
5422
|
return summaries;
|
|
4495
5423
|
}
|
|
4496
|
-
function
|
|
5424
|
+
function matchCallSiteToSink(call, sink) {
|
|
4497
5425
|
const sinkCall = sink.pattern.replace(/\(\$TAINTED\)|\$TAINTED|\$BUF,\s*/g, "").trim();
|
|
4498
|
-
if (!sinkCall) return
|
|
5426
|
+
if (!sinkCall) return -1;
|
|
4499
5427
|
if (sinkCall === "exec" || sinkCall.startsWith("exec(")) {
|
|
4500
|
-
if (
|
|
4501
|
-
|
|
5428
|
+
if (call.methodName !== "exec") return -1;
|
|
5429
|
+
if (call.receiver && !/^(?:child_process|cp|shell|proc)$/i.test(call.receiver)) {
|
|
5430
|
+
return -1;
|
|
4502
5431
|
}
|
|
4503
|
-
return
|
|
5432
|
+
return 0;
|
|
4504
5433
|
}
|
|
4505
5434
|
if (sinkCall === "eval" || sinkCall.startsWith("eval(")) {
|
|
4506
|
-
if (
|
|
4507
|
-
|
|
5435
|
+
if (call.methodName !== "eval") return -1;
|
|
5436
|
+
if (call.receiver && !/^(?:window|globalThis|global)$/i.test(call.receiver)) {
|
|
5437
|
+
return -1;
|
|
4508
5438
|
}
|
|
4509
|
-
return
|
|
5439
|
+
return 0;
|
|
4510
5440
|
}
|
|
4511
5441
|
if (sink.type === "format_string") {
|
|
4512
5442
|
const base = sinkCall.replace(/\($/, "").trim();
|
|
4513
|
-
|
|
4514
|
-
|
|
4515
|
-
return
|
|
5443
|
+
if (call.callee !== base && call.methodName !== base) return -1;
|
|
5444
|
+
if (call.args.length === 0 || call.args[0].isLiteral) return -1;
|
|
5445
|
+
return 0;
|
|
4516
5446
|
}
|
|
4517
5447
|
if (sinkCall.includes("prepareStatement")) {
|
|
4518
|
-
|
|
5448
|
+
if (call.methodName !== "prepareStatement") return -1;
|
|
5449
|
+
if (call.args.length === 0 || !call.args[0].text.includes("+")) return -1;
|
|
5450
|
+
return 0;
|
|
5451
|
+
}
|
|
5452
|
+
if (sink.type === "open_redirect" && call.callee === "http.Redirect") {
|
|
5453
|
+
return 2;
|
|
4519
5454
|
}
|
|
4520
5455
|
const baseName = sinkCall.replace(/\($/, "").replace(/^\./, "").trim();
|
|
4521
|
-
|
|
4522
|
-
if (
|
|
4523
|
-
|
|
5456
|
+
if (!baseName) return -1;
|
|
5457
|
+
if (baseName.includes(".")) {
|
|
5458
|
+
if (call.callee === baseName || call.callee.endsWith(`.${baseName}`)) {
|
|
5459
|
+
return 0;
|
|
5460
|
+
}
|
|
5461
|
+
return -1;
|
|
4524
5462
|
}
|
|
4525
|
-
|
|
4526
|
-
|
|
4527
|
-
|
|
4528
|
-
|
|
4529
|
-
return new RegExp(`(?:^|[^a-zA-Z0-9_])${escaped}(?![a-zA-Z0-9_])`).test(line);
|
|
5463
|
+
if (call.callee === baseName || call.methodName === baseName) {
|
|
5464
|
+
return 0;
|
|
5465
|
+
}
|
|
5466
|
+
return -1;
|
|
4530
5467
|
}
|
|
4531
|
-
function
|
|
4532
|
-
const
|
|
5468
|
+
function analyzeTaintFlow(content, filePath, language, tree, options) {
|
|
5469
|
+
const langConfig = getLanguageConfig(language);
|
|
5470
|
+
if (!langConfig || content.length < 10) return [];
|
|
5471
|
+
const model = options?.codeModel ?? buildFileCodeModel(content, filePath, language, tree ?? null);
|
|
4533
5472
|
const lines = content.split("\n");
|
|
4534
|
-
const
|
|
4535
|
-
const
|
|
4536
|
-
|
|
4537
|
-
|
|
5473
|
+
const includeEnv = Boolean(options?.includeEnvSources);
|
|
5474
|
+
const activeSources = langConfig.taintSources.filter((s) => {
|
|
5475
|
+
if (!includeEnv && s.type === "environment") return false;
|
|
5476
|
+
if (!includeEnv && (s.pattern === "document.location" || s.pattern === "window.location" || s.pattern === "localStorage.getItem" || s.pattern === "document.getElementById") && !FRONTEND_PATH_RE.test(filePath)) {
|
|
5477
|
+
return false;
|
|
5478
|
+
}
|
|
5479
|
+
return true;
|
|
5480
|
+
});
|
|
5481
|
+
const scopeMaps = /* @__PURE__ */ new Map();
|
|
5482
|
+
const getScopeMap = (scopeId) => {
|
|
5483
|
+
let m = scopeMaps.get(scopeId);
|
|
5484
|
+
if (!m) {
|
|
5485
|
+
m = /* @__PURE__ */ new Map();
|
|
5486
|
+
scopeMaps.set(scopeId, m);
|
|
5487
|
+
}
|
|
5488
|
+
return m;
|
|
5489
|
+
};
|
|
5490
|
+
if (language === "php" && options?.projectGraph) {
|
|
5491
|
+
const phpImported = options.projectGraph.getPhpCrossFileTaintedVars(filePath);
|
|
5492
|
+
const rootMap = getScopeMap(0);
|
|
5493
|
+
for (const entry of phpImported) {
|
|
5494
|
+
if (!rootMap.has(entry.varName)) {
|
|
5495
|
+
const srcLoc = makeLocation(entry.sourceFile, entry.sourceLine, entry.sourceSnippet);
|
|
5496
|
+
rootMap.set(entry.varName, {
|
|
5497
|
+
id: `taint_php_${entry.varName}`,
|
|
5498
|
+
sourceType: "user_input",
|
|
5499
|
+
originLocation: srcLoc,
|
|
5500
|
+
currentVariable: entry.varName,
|
|
5501
|
+
propagationPath: [
|
|
5502
|
+
{
|
|
5503
|
+
location: srcLoc,
|
|
5504
|
+
label: `Cross-file PHP source (${entry.varName}) from included file`,
|
|
5505
|
+
kind: "source"
|
|
5506
|
+
}
|
|
5507
|
+
],
|
|
5508
|
+
sanitized: /* @__PURE__ */ new Set()
|
|
5509
|
+
});
|
|
5510
|
+
}
|
|
5511
|
+
}
|
|
4538
5512
|
}
|
|
4539
|
-
for (const
|
|
4540
|
-
|
|
4541
|
-
|
|
5513
|
+
for (const scope of model.scopes) {
|
|
5514
|
+
if (scope.destructuredReqParams.length === 0) continue;
|
|
5515
|
+
const sMap = getScopeMap(scope.id);
|
|
5516
|
+
const snippet = lines[scope.startLine - 1]?.trim() || "";
|
|
5517
|
+
const loc = makeLocation(filePath, scope.startLine, snippet);
|
|
5518
|
+
for (const pName of scope.destructuredReqParams) {
|
|
5519
|
+
sMap.set(pName, {
|
|
5520
|
+
id: `taint_scope_${scope.id}_${pName}`,
|
|
5521
|
+
sourceType: "user_input",
|
|
5522
|
+
originLocation: loc,
|
|
5523
|
+
currentVariable: pName,
|
|
5524
|
+
propagationPath: [{ location: loc, label: `Source: Destructured route parameter (${pName})`, kind: "source" }],
|
|
5525
|
+
sanitized: /* @__PURE__ */ new Set()
|
|
5526
|
+
});
|
|
5527
|
+
}
|
|
4542
5528
|
}
|
|
4543
|
-
return results;
|
|
4544
|
-
}
|
|
4545
|
-
function findTaintSourcesRegex(lines, sources, sanitizers, filePath) {
|
|
4546
|
-
const taintedMap = /* @__PURE__ */ new Map();
|
|
4547
5529
|
for (let i = 0; i < lines.length; i++) {
|
|
4548
|
-
const
|
|
4549
|
-
if (!
|
|
4550
|
-
for (const source of
|
|
5530
|
+
const trimmed = lines[i].trim();
|
|
5531
|
+
if (!trimmed || trimmed.startsWith("//") || trimmed.startsWith("#")) continue;
|
|
5532
|
+
for (const source of activeSources) {
|
|
4551
5533
|
const token = source.pattern.replace("$TAINTED", "").replace("()", "");
|
|
4552
|
-
if (token
|
|
4553
|
-
|
|
4554
|
-
|
|
4555
|
-
|
|
4556
|
-
|
|
4557
|
-
|
|
4558
|
-
|
|
4559
|
-
|
|
4560
|
-
|
|
4561
|
-
const
|
|
4562
|
-
|
|
4563
|
-
|
|
4564
|
-
if (sName.length > 0 && line.includes(sName)) {
|
|
4565
|
-
for (const c of s.cleanses) initialSanitized.add(c);
|
|
4566
|
-
}
|
|
4567
|
-
}
|
|
4568
|
-
if (token.startsWith("@")) {
|
|
4569
|
-
const escapedToken = token.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
4570
|
-
const paramMatches = line.matchAll(
|
|
4571
|
-
new RegExp(`${escapedToken}(?:\\s*\\([^)]*\\))?\\s+(?:final\\s+)?(?:[\\w<>\\[\\],.?]+\\s+)+([a-zA-Z_]\\w*)`, "g")
|
|
4572
|
-
);
|
|
4573
|
-
let matchedAnnotation = false;
|
|
4574
|
-
for (const pm of paramMatches) {
|
|
4575
|
-
const pVar = pm[1];
|
|
4576
|
-
matchedAnnotation = true;
|
|
4577
|
-
taintedMap.set(pVar, {
|
|
4578
|
-
id: `taint_${i}_${pVar}`,
|
|
4579
|
-
sourceType: source.type,
|
|
4580
|
-
originLocation: loc,
|
|
4581
|
-
currentVariable: pVar,
|
|
4582
|
-
propagationPath: [{ location: loc, label: `Source: ${source.description}`, kind: "source" }],
|
|
4583
|
-
sanitized: new Set(initialSanitized)
|
|
4584
|
-
});
|
|
4585
|
-
}
|
|
4586
|
-
if (matchedAnnotation) continue;
|
|
4587
|
-
}
|
|
4588
|
-
const assignMatch = line.match(/^(?:(?:const|let|var|final|auto|my|local|\w+)\s+)?(\$?[a-zA-Z_]\w*)\s*:?=\s*.*$/);
|
|
4589
|
-
const varName = assignMatch ? assignMatch[1] : `__tainted_${i}`;
|
|
4590
|
-
taintedMap.set(varName, {
|
|
4591
|
-
id: `taint_${i}_${varName}`,
|
|
5534
|
+
if (!token.startsWith("@") || !trimmed.includes(token)) continue;
|
|
5535
|
+
const scopeId = getScopeAtLine(model, i + 1);
|
|
5536
|
+
const sMap = getScopeMap(scopeId);
|
|
5537
|
+
const loc = makeLocation(filePath, i + 1, trimmed);
|
|
5538
|
+
const escapedToken = token.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
5539
|
+
const paramMatches = trimmed.matchAll(
|
|
5540
|
+
new RegExp(`${escapedToken}(?:\\s*\\([^)]*\\))?\\s+(?:final\\s+)?(?:[\\w<>.?\\[\\]]+\\s+)+([a-zA-Z_]\\w*)`, "g")
|
|
5541
|
+
);
|
|
5542
|
+
for (const pm of paramMatches) {
|
|
5543
|
+
const pVar = pm[1];
|
|
5544
|
+
sMap.set(pVar, {
|
|
5545
|
+
id: `taint_annot_${i}_${pVar}`,
|
|
4592
5546
|
sourceType: source.type,
|
|
4593
5547
|
originLocation: loc,
|
|
4594
|
-
currentVariable:
|
|
5548
|
+
currentVariable: pVar,
|
|
4595
5549
|
propagationPath: [{ location: loc, label: `Source: ${source.description}`, kind: "source" }],
|
|
4596
|
-
sanitized:
|
|
5550
|
+
sanitized: getSanitizerMatches(trimmed, langConfig.sanitizers)
|
|
4597
5551
|
});
|
|
4598
5552
|
}
|
|
4599
5553
|
}
|
|
4600
5554
|
}
|
|
4601
|
-
|
|
4602
|
-
|
|
4603
|
-
|
|
4604
|
-
|
|
4605
|
-
|
|
4606
|
-
if (!
|
|
4607
|
-
const
|
|
4608
|
-
|
|
4609
|
-
const
|
|
4610
|
-
const
|
|
4611
|
-
|
|
4612
|
-
|
|
4613
|
-
|
|
4614
|
-
|
|
4615
|
-
|
|
4616
|
-
|
|
5555
|
+
for (const assign of model.assignments) {
|
|
5556
|
+
const matchedSource = activeSources.find((s) => {
|
|
5557
|
+
const tok = s.pattern.replace("$TAINTED", "").replace("()", "");
|
|
5558
|
+
return matchesSourceToken(assign.rhsText, tok);
|
|
5559
|
+
});
|
|
5560
|
+
if (!matchedSource) continue;
|
|
5561
|
+
const cleansed = getSanitizerMatches(assign.rhsText, langConfig.sanitizers);
|
|
5562
|
+
const sMap = getScopeMap(assign.scopeId);
|
|
5563
|
+
const snippet = lines[assign.startLine - 1]?.trim() || assign.rhsText;
|
|
5564
|
+
const loc = makeLocation(filePath, assign.startLine, snippet);
|
|
5565
|
+
for (const target of assign.targets) {
|
|
5566
|
+
sMap.set(target, {
|
|
5567
|
+
id: `taint_${assign.startLine}_${target}`,
|
|
5568
|
+
sourceType: matchedSource.type,
|
|
5569
|
+
originLocation: loc,
|
|
5570
|
+
currentVariable: target,
|
|
5571
|
+
propagationPath: [{ location: loc, label: `Source: ${matchedSource.description}`, kind: "source" }],
|
|
5572
|
+
sanitized: new Set(cleansed)
|
|
4617
5573
|
});
|
|
4618
|
-
|
|
5574
|
+
}
|
|
5575
|
+
}
|
|
5576
|
+
const findTaintedInExpr = (expr, scopeId) => {
|
|
5577
|
+
const sMap = scopeMaps.get(scopeId);
|
|
5578
|
+
if (sMap) {
|
|
5579
|
+
for (const tainted of sMap.values()) {
|
|
5580
|
+
if (containsVariable(expr, tainted.currentVariable)) {
|
|
5581
|
+
return tainted;
|
|
5582
|
+
}
|
|
5583
|
+
}
|
|
5584
|
+
}
|
|
5585
|
+
if (scopeId !== 0) {
|
|
5586
|
+
const rootMap = scopeMaps.get(0);
|
|
5587
|
+
if (rootMap) {
|
|
5588
|
+
for (const tainted of rootMap.values()) {
|
|
5589
|
+
if (containsVariable(expr, tainted.currentVariable)) {
|
|
5590
|
+
return tainted;
|
|
5591
|
+
}
|
|
5592
|
+
}
|
|
5593
|
+
}
|
|
5594
|
+
}
|
|
5595
|
+
for (const source of activeSources) {
|
|
5596
|
+
const tok = source.pattern.replace("$TAINTED", "").replace("()", "");
|
|
5597
|
+
if (matchesSourceToken(expr, tok)) {
|
|
5598
|
+
return {
|
|
5599
|
+
id: `inline_${tok}`,
|
|
5600
|
+
sourceType: source.type,
|
|
5601
|
+
originLocation: makeLocation(filePath, 1, expr.slice(0, 120)),
|
|
5602
|
+
currentVariable: tok,
|
|
5603
|
+
propagationPath: [
|
|
5604
|
+
{
|
|
5605
|
+
location: makeLocation(filePath, 1, expr.slice(0, 120)),
|
|
5606
|
+
label: `Source: ${source.description}`,
|
|
5607
|
+
kind: "source"
|
|
5608
|
+
}
|
|
5609
|
+
],
|
|
5610
|
+
sanitized: /* @__PURE__ */ new Set()
|
|
5611
|
+
};
|
|
5612
|
+
}
|
|
5613
|
+
}
|
|
5614
|
+
return null;
|
|
5615
|
+
};
|
|
5616
|
+
const helperSummaries = extractIntraFileHelpers(model, lines, langConfig.taintSinks, langConfig.sanitizers);
|
|
5617
|
+
for (let pass = 0; pass < 2; pass++) {
|
|
5618
|
+
for (const assign of model.assignments) {
|
|
5619
|
+
const sMap = getScopeMap(assign.scopeId);
|
|
5620
|
+
if (assign.targets.every((t) => sMap.has(t))) continue;
|
|
5621
|
+
const cleansed = getSanitizerMatches(assign.rhsText, langConfig.sanitizers);
|
|
5622
|
+
const taintedSrc = findTaintedInExpr(assign.rhsText, assign.scopeId);
|
|
5623
|
+
if (!taintedSrc) continue;
|
|
4619
5624
|
let viaHelper = null;
|
|
4620
5625
|
for (const [helperName, summary] of helperSummaries.entries()) {
|
|
4621
|
-
if (summary.passthroughParamIndices.size > 0 &&
|
|
5626
|
+
if (summary.passthroughParamIndices.size > 0 && assign.rhsText.includes(`${helperName}(`)) {
|
|
4622
5627
|
viaHelper = helperName;
|
|
4623
5628
|
break;
|
|
4624
5629
|
}
|
|
4625
5630
|
}
|
|
4626
|
-
|
|
4627
|
-
|
|
4628
|
-
|
|
4629
|
-
|
|
4630
|
-
|
|
4631
|
-
|
|
4632
|
-
|
|
4633
|
-
|
|
4634
|
-
taintedMap.set(newVar, {
|
|
4635
|
-
id: `taint_${i}_${newVar}`,
|
|
4636
|
-
sourceType: tainted.sourceType,
|
|
4637
|
-
originLocation: tainted.originLocation,
|
|
4638
|
-
currentVariable: newVar,
|
|
4639
|
-
propagationPath: [
|
|
4640
|
-
...tainted.propagationPath,
|
|
4641
|
-
{
|
|
4642
|
-
location: loc,
|
|
4643
|
-
label: viaHelper ? `Inter-procedural passthrough (${viaHelper}): ${tainted.currentVariable} \u2192 ${newVar}` : `Propagated: ${tainted.currentVariable} \u2192 ${newVar}`,
|
|
4644
|
-
kind: "propagator"
|
|
5631
|
+
if (!viaHelper && options?.projectGraph) {
|
|
5632
|
+
const rhsCall = model.callSites.find(
|
|
5633
|
+
(c) => c.startLine === assign.startLine && containsVariable(assign.rhsText, c.callee)
|
|
5634
|
+
);
|
|
5635
|
+
if (rhsCall) {
|
|
5636
|
+
const ext = options.projectGraph.resolveImportedFunction(filePath, rhsCall.callee);
|
|
5637
|
+
if (ext && ext.passthroughParamIndices.length > 0) {
|
|
5638
|
+
viaHelper = rhsCall.callee;
|
|
4645
5639
|
}
|
|
4646
|
-
|
|
4647
|
-
|
|
4648
|
-
|
|
4649
|
-
|
|
5640
|
+
}
|
|
5641
|
+
}
|
|
5642
|
+
const snippet = lines[assign.startLine - 1]?.trim() || assign.rhsText;
|
|
5643
|
+
const loc = makeLocation(filePath, assign.startLine, snippet);
|
|
5644
|
+
const mergedSanitized = /* @__PURE__ */ new Set([...taintedSrc.sanitized, ...cleansed]);
|
|
5645
|
+
for (const target of assign.targets) {
|
|
5646
|
+
if (sMap.has(target)) continue;
|
|
5647
|
+
sMap.set(target, {
|
|
5648
|
+
id: `taint_${assign.startLine}_${target}`,
|
|
5649
|
+
sourceType: taintedSrc.sourceType,
|
|
5650
|
+
originLocation: taintedSrc.originLocation,
|
|
5651
|
+
currentVariable: target,
|
|
5652
|
+
propagationPath: [
|
|
5653
|
+
...taintedSrc.propagationPath,
|
|
5654
|
+
{
|
|
5655
|
+
location: loc,
|
|
5656
|
+
label: viaHelper ? `Inter-procedural passthrough (${viaHelper}): ${taintedSrc.currentVariable} -> ${target}` : `Propagated: ${taintedSrc.currentVariable} -> ${target}`,
|
|
5657
|
+
kind: "propagator"
|
|
5658
|
+
}
|
|
5659
|
+
],
|
|
5660
|
+
sanitized: mergedSanitized
|
|
5661
|
+
});
|
|
5662
|
+
}
|
|
4650
5663
|
}
|
|
4651
5664
|
}
|
|
4652
|
-
}
|
|
4653
|
-
function findTaintSinksRegex(lines, tainted, sinks, sanitizers, helperSummaries, filePath) {
|
|
4654
5665
|
const results = [];
|
|
4655
|
-
|
|
4656
|
-
|
|
4657
|
-
|
|
4658
|
-
|
|
4659
|
-
|
|
4660
|
-
|
|
4661
|
-
|
|
4662
|
-
|
|
5666
|
+
const seenKeys = /* @__PURE__ */ new Set();
|
|
5667
|
+
const addResult = (res) => {
|
|
5668
|
+
const sinkLoc = res.flow[res.flow.length - 1]?.location;
|
|
5669
|
+
const key = `${res.sinkType}:${sinkLoc?.file ?? filePath}:${sinkLoc?.startLine ?? 0}`;
|
|
5670
|
+
if (!seenKeys.has(key)) {
|
|
5671
|
+
seenKeys.add(key);
|
|
5672
|
+
results.push(res);
|
|
5673
|
+
}
|
|
5674
|
+
};
|
|
5675
|
+
const hasHttpInputInFile = /\b(?:req\b|request\b|app\.(?:get|post|put|delete|use)|router\.|http\.createServer|WebSocket|socket\.on|@Controller|@Get|@Post|flask|fastapi)\b/i.test(
|
|
5676
|
+
content
|
|
5677
|
+
);
|
|
5678
|
+
const isLocalScript = LOCAL_SCRIPT_PATH_RE.test(filePath) && !hasHttpInputInFile;
|
|
5679
|
+
const isGuardedInScope = (sinkType, scopeId, call) => {
|
|
5680
|
+
const scopeTxt = getScopeText(lines, model, scopeId);
|
|
5681
|
+
const lineTxt = lines[call.startLine - 1] || call.fullText;
|
|
5682
|
+
if (sinkType === "command_injection" || sinkType === "code_injection") {
|
|
5683
|
+
if (isLocalScript) return true;
|
|
5684
|
+
if (/\bescapeshellarg\s*\(|\bshlex\.quote\s*\(|\bR\.exec\s*\(/.test(lineTxt)) return true;
|
|
5685
|
+
}
|
|
5686
|
+
if (sinkType === "ssrf") {
|
|
5687
|
+
if (FRONTEND_PATH_RE.test(filePath)) return true;
|
|
5688
|
+
if (/\b(?:startsWith|allowedHosts|whitelist|trusted|validateUrl)\b|\.hostname\s*===/.test(scopeTxt)) {
|
|
5689
|
+
return true;
|
|
5690
|
+
}
|
|
5691
|
+
if (/\b(?:getAxiosConfigWithProxy|this\.getConfig)\s*\(/.test(scopeTxt)) return true;
|
|
5692
|
+
}
|
|
5693
|
+
if (sinkType === "open_redirect") {
|
|
5694
|
+
if (call.methodName === "header" && !/location\s*:/i.test(call.args[0]?.text || "")) {
|
|
5695
|
+
return true;
|
|
5696
|
+
}
|
|
5697
|
+
if (/\.startsWith\s*\(\s*['"]\/['"]|\.origin\s*===/.test(scopeTxt)) return true;
|
|
5698
|
+
}
|
|
5699
|
+
if (sinkType === "path_traversal" || sinkType === "file_inclusion") {
|
|
5700
|
+
if (/\b(?:basename|filepath\.Base|os\.path\.basename)\s*\(|\.startsWith\s*\(|\bstrings\.HasPrefix\s*\(/.test(scopeTxt)) {
|
|
5701
|
+
return true;
|
|
5702
|
+
}
|
|
5703
|
+
}
|
|
5704
|
+
if (sinkType === "deserialization" && (language === "java" || language === "kotlin")) {
|
|
5705
|
+
if (/\b(?:setObjectInputFilter|ObjectInputFilter|resolveClass)\b/.test(content)) return true;
|
|
5706
|
+
}
|
|
5707
|
+
if (sinkType === "sql_injection") {
|
|
5708
|
+
if (isSafeSqlInterpolation(content, filePath, call.startLine, lineTxt)) return true;
|
|
5709
|
+
if (language === "ruby" && call.methodName === "where") {
|
|
5710
|
+
const firstArg = call.args[0]?.text.trim() || "";
|
|
5711
|
+
if (/^(?:\{\s*)?(?::[a-zA-Z_]\w*\s*=>|[a-zA-Z_]\w*\s*:(?!:))/.test(firstArg)) {
|
|
5712
|
+
return true;
|
|
4663
5713
|
}
|
|
4664
5714
|
}
|
|
4665
5715
|
}
|
|
4666
|
-
|
|
4667
|
-
|
|
4668
|
-
|
|
4669
|
-
|
|
4670
|
-
|
|
5716
|
+
return false;
|
|
5717
|
+
};
|
|
5718
|
+
for (const call of model.callSites) {
|
|
5719
|
+
const lineClears = getSanitizerMatches(call.fullText, langConfig.sanitizers);
|
|
5720
|
+
for (const sink of langConfig.taintSinks) {
|
|
5721
|
+
const argIdx = matchCallSiteToSink(call, sink);
|
|
5722
|
+
if (argIdx < 0 || argIdx >= call.args.length) continue;
|
|
5723
|
+
const arg = call.args[argIdx];
|
|
5724
|
+
if (arg.isLiteral && !arg.hasInterpolation) continue;
|
|
5725
|
+
if (lineClears.has(sink.type)) continue;
|
|
5726
|
+
const tainted = findTaintedInExpr(arg.text, call.scopeId);
|
|
5727
|
+
if (!tainted || tainted.sanitized.has(sink.type)) continue;
|
|
5728
|
+
if (isGuardedInScope(sink.type, call.scopeId, call)) continue;
|
|
5729
|
+
const sinkLoc = makeLocation(filePath, call.startLine, lines[call.startLine - 1]?.trim() || call.fullText.split("\n")[0], call.startColumn);
|
|
5730
|
+
addResult({
|
|
5731
|
+
hasTaintedSink: true,
|
|
5732
|
+
sourceType: tainted.sourceType,
|
|
5733
|
+
sinkType: sink.type,
|
|
5734
|
+
flow: [
|
|
5735
|
+
...tainted.propagationPath,
|
|
5736
|
+
{ location: sinkLoc, label: `Sink: ${sink.description}`, kind: "sink" }
|
|
5737
|
+
]
|
|
5738
|
+
});
|
|
5739
|
+
}
|
|
5740
|
+
if ((language === "javascript" || language === "typescript") && NOSQL_METHODS.has(call.methodName) && call.args.length > 0 && call.args[0].text.trim().startsWith("{")) {
|
|
5741
|
+
const filterText = call.args[0].text;
|
|
5742
|
+
const cleanedFilter = filterText.replace(/\b(?:String|Number|parseInt|Boolean|ObjectId)\s*\([^)]*\)/g, "");
|
|
5743
|
+
const tainted = findTaintedInExpr(cleanedFilter, call.scopeId);
|
|
5744
|
+
if (tainted && !tainted.sanitized.has("nosql_injection") && !lineClears.has("nosql_injection")) {
|
|
5745
|
+
const sinkLoc = makeLocation(filePath, call.startLine, lines[call.startLine - 1]?.trim() || call.fullText.split("\n")[0], call.startColumn);
|
|
5746
|
+
addResult({
|
|
4671
5747
|
hasTaintedSink: true,
|
|
4672
5748
|
sourceType: tainted.sourceType,
|
|
4673
|
-
sinkType:
|
|
5749
|
+
sinkType: "nosql_injection",
|
|
4674
5750
|
flow: [
|
|
4675
5751
|
...tainted.propagationPath,
|
|
4676
|
-
{
|
|
4677
|
-
location: {
|
|
4678
|
-
file: filePath,
|
|
4679
|
-
startLine: i + 1,
|
|
4680
|
-
startColumn: 0,
|
|
4681
|
-
endLine: i + 1,
|
|
4682
|
-
endColumn: line.length,
|
|
4683
|
-
snippet: line
|
|
4684
|
-
},
|
|
4685
|
-
label: `Sink: ${sink.description}`,
|
|
4686
|
-
kind: "sink"
|
|
4687
|
-
}
|
|
5752
|
+
{ location: sinkLoc, label: `Sink: NoSQL query filter (${call.callee})`, kind: "sink" }
|
|
4688
5753
|
]
|
|
4689
5754
|
});
|
|
4690
5755
|
}
|
|
4691
5756
|
}
|
|
4692
|
-
|
|
4693
|
-
|
|
4694
|
-
|
|
4695
|
-
|
|
4696
|
-
|
|
4697
|
-
|
|
4698
|
-
|
|
5757
|
+
const localHelper = helperSummaries.get(call.methodName);
|
|
5758
|
+
if (localHelper && (call.startLine < localHelper.startLine || call.startLine > localHelper.endLine)) {
|
|
5759
|
+
for (const hit of localHelper.sinkHits) {
|
|
5760
|
+
const arg = call.args[hit.paramIndex];
|
|
5761
|
+
if (!arg || arg.isLiteral) continue;
|
|
5762
|
+
const tainted = findTaintedInExpr(arg.text, call.scopeId);
|
|
5763
|
+
if (!tainted || tainted.sanitized.has(hit.sink.type)) continue;
|
|
5764
|
+
addResult({
|
|
4699
5765
|
hasTaintedSink: true,
|
|
4700
5766
|
sourceType: tainted.sourceType,
|
|
4701
5767
|
sinkType: hit.sink.type,
|
|
4702
5768
|
flow: [
|
|
4703
5769
|
...tainted.propagationPath,
|
|
4704
5770
|
{
|
|
4705
|
-
location:
|
|
4706
|
-
|
|
4707
|
-
startLine: i + 1,
|
|
4708
|
-
startColumn: 0,
|
|
4709
|
-
endLine: i + 1,
|
|
4710
|
-
endColumn: line.length,
|
|
4711
|
-
snippet: line
|
|
4712
|
-
},
|
|
4713
|
-
label: `Inter-procedural call to ${helperName}(${tainted.currentVariable})`,
|
|
5771
|
+
location: makeLocation(filePath, call.startLine, lines[call.startLine - 1]?.trim() || call.fullText),
|
|
5772
|
+
label: `Inter-procedural call to ${localHelper.name}(${tainted.currentVariable})`,
|
|
4714
5773
|
kind: "propagator"
|
|
4715
5774
|
},
|
|
4716
5775
|
{
|
|
4717
|
-
location:
|
|
4718
|
-
|
|
4719
|
-
|
|
4720
|
-
|
|
4721
|
-
|
|
4722
|
-
|
|
4723
|
-
|
|
5776
|
+
location: makeLocation(filePath, hit.sinkLine, hit.sinkSnippet),
|
|
5777
|
+
label: `Sink in ${localHelper.name}(): ${hit.sink.description}`,
|
|
5778
|
+
kind: "sink"
|
|
5779
|
+
}
|
|
5780
|
+
]
|
|
5781
|
+
});
|
|
5782
|
+
}
|
|
5783
|
+
}
|
|
5784
|
+
if (options?.projectGraph) {
|
|
5785
|
+
const extSummary = options.projectGraph.resolveImportedFunction(filePath, call.callee);
|
|
5786
|
+
if (extSummary && extSummary.sinkHits.length > 0) {
|
|
5787
|
+
for (const hit of extSummary.sinkHits) {
|
|
5788
|
+
const arg = call.args[hit.paramIndex];
|
|
5789
|
+
if (!arg || arg.isLiteral) continue;
|
|
5790
|
+
const tainted = findTaintedInExpr(arg.text, call.scopeId);
|
|
5791
|
+
if (!tainted || tainted.sanitized.has(hit.sinkType) || lineClears.has(hit.sinkType)) continue;
|
|
5792
|
+
if (isGuardedInScope(hit.sinkType, call.scopeId, call)) continue;
|
|
5793
|
+
addResult({
|
|
5794
|
+
hasTaintedSink: true,
|
|
5795
|
+
sourceType: tainted.sourceType,
|
|
5796
|
+
sinkType: hit.sinkType,
|
|
5797
|
+
flow: [
|
|
5798
|
+
...tainted.propagationPath,
|
|
5799
|
+
{
|
|
5800
|
+
location: makeLocation(filePath, call.startLine, lines[call.startLine - 1]?.trim() || call.fullText),
|
|
5801
|
+
label: `Cross-file call to ${extSummary.name}() in ${extSummary.filePath}`,
|
|
5802
|
+
kind: "propagator"
|
|
4724
5803
|
},
|
|
4725
|
-
|
|
5804
|
+
{
|
|
5805
|
+
location: makeLocation(extSummary.filePath, hit.sinkLine, hit.sinkSnippet),
|
|
5806
|
+
label: `Cross-file sink in ${extSummary.name}(): ${hit.sinkDescription}`,
|
|
5807
|
+
kind: "sink"
|
|
5808
|
+
}
|
|
5809
|
+
]
|
|
5810
|
+
});
|
|
5811
|
+
}
|
|
5812
|
+
}
|
|
5813
|
+
}
|
|
5814
|
+
}
|
|
5815
|
+
const nonCallSinks = langConfig.taintSinks.filter(
|
|
5816
|
+
(s) => s.pattern === "innerHTML" || s.pattern.startsWith("echo ")
|
|
5817
|
+
);
|
|
5818
|
+
if (nonCallSinks.length > 0) {
|
|
5819
|
+
for (let i = 0; i < lines.length; i++) {
|
|
5820
|
+
const line = lines[i].trim();
|
|
5821
|
+
if (!line || line.startsWith("//") || line.startsWith("#")) continue;
|
|
5822
|
+
const scopeId = getScopeAtLine(model, i + 1);
|
|
5823
|
+
const lineClears = getSanitizerMatches(line, langConfig.sanitizers);
|
|
5824
|
+
for (const sink of nonCallSinks) {
|
|
5825
|
+
if (sink.pattern === "innerHTML" && !/\.innerHTML\s*\+?=/.test(line)) continue;
|
|
5826
|
+
if (sink.pattern.startsWith("echo ") && !/\becho\s+/.test(line)) continue;
|
|
5827
|
+
if (lineClears.has(sink.type)) continue;
|
|
5828
|
+
const rhs = sink.pattern === "innerHTML" ? line.split(/\.innerHTML\s*\+?=/)[1] || "" : line.replace(/^\s*echo\s+/, "");
|
|
5829
|
+
const tainted = findTaintedInExpr(rhs, scopeId);
|
|
5830
|
+
if (!tainted || tainted.sanitized.has(sink.type)) continue;
|
|
5831
|
+
addResult({
|
|
5832
|
+
hasTaintedSink: true,
|
|
5833
|
+
sourceType: tainted.sourceType,
|
|
5834
|
+
sinkType: sink.type,
|
|
5835
|
+
flow: [
|
|
5836
|
+
...tainted.propagationPath,
|
|
5837
|
+
{
|
|
5838
|
+
location: makeLocation(filePath, i + 1, line),
|
|
5839
|
+
label: `Sink: ${sink.description}`,
|
|
4726
5840
|
kind: "sink"
|
|
4727
5841
|
}
|
|
4728
5842
|
]
|
|
@@ -4737,7 +5851,7 @@ function findTaintSinksRegex(lines, tainted, sinks, sanitizers, helperSummaries,
|
|
|
4737
5851
|
var SQL_CONCAT_PATTERNS = [
|
|
4738
5852
|
{
|
|
4739
5853
|
// query("SELECT * FROM users WHERE id = " + userId)
|
|
4740
|
-
regex: /(?:query|execute|exec|raw|prepare)\s*\(\s*["'
|
|
5854
|
+
regex: /(?:query|execute|exec|raw|prepare)\s*\(\s*(?:"(?:SELECT|INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|UNION|EXEC)\b[^"]*"|'(?:SELECT|INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|UNION|EXEC)\b[^']*'|`(?:SELECT|INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|UNION|EXEC)\b[^`]*`)\s*\+/i,
|
|
4741
5855
|
message: "SQL query built with string concatenation \u2013 vulnerable to SQL injection"
|
|
4742
5856
|
},
|
|
4743
5857
|
{
|
|
@@ -4767,7 +5881,7 @@ var SQL_CONCAT_PATTERNS = [
|
|
|
4767
5881
|
},
|
|
4768
5882
|
{
|
|
4769
5883
|
// f"SELECT * FROM users WHERE name = '{name}'" (Python f-string)
|
|
4770
|
-
regex: /f
|
|
5884
|
+
regex: /(?:f"\s*(?:SELECT\b[^"]*\bFROM|INSERT\s+INTO|UPDATE\s+\w+\s+SET|DELETE\s+FROM|DROP\s+(?:TABLE|DATABASE)|CREATE\s+(?:TABLE|DATABASE)|ALTER\s+TABLE)\b[^"]*\{[^}]+\}[^"]*"|f'\s*(?:SELECT\b[^']*\bFROM|INSERT\s+INTO|UPDATE\s+\w+\s+SET|DELETE\s+FROM|DROP\s+(?:TABLE|DATABASE)|CREATE\s+(?:TABLE|DATABASE)|ALTER\s+TABLE)\b[^']*\{[^}]+\}[^']*')/i,
|
|
4771
5885
|
message: "Python f-string used in SQL query \u2013 vulnerable to SQL injection"
|
|
4772
5886
|
},
|
|
4773
5887
|
{
|
|
@@ -4905,9 +6019,24 @@ var COMMAND_INJECTION_PATTERNS = [
|
|
|
4905
6019
|
message: "PHP command execution with dynamic variable concatenation \u2013 vulnerable to command injection. Use escapeshellarg()."
|
|
4906
6020
|
},
|
|
4907
6021
|
{
|
|
4908
|
-
// PHP eval() with dynamic concatenation or variable
|
|
4909
|
-
regex:
|
|
6022
|
+
// PHP eval() with dynamic concatenation or variable (skip $this->redis->eval(...) and method declarations)
|
|
6023
|
+
regex: /(?<!->|::|\bfunction\s+)\beval\s*\(\s*(?:['"][^'"]*['"]\s*\.\s*(?:file_get_contents|\$[a-zA-Z_]\w*)|\$[a-zA-Z_]\w*)/i,
|
|
4910
6024
|
message: "PHP eval() called with dynamic content \u2013 remote code execution risk"
|
|
6025
|
+
},
|
|
6026
|
+
{
|
|
6027
|
+
// Node.js vm.runInContext / vm.runInNewContext sandbox escape RCE
|
|
6028
|
+
regex: /\bvm\.runIn(?:New)?Context\s*\(/,
|
|
6029
|
+
message: "Node.js vm.runInContext/runInNewContext is not a security sandbox \u2013 untrusted input leads to Remote Code Execution"
|
|
6030
|
+
}
|
|
6031
|
+
];
|
|
6032
|
+
var NOSQL_INJECTION_PATTERNS = [
|
|
6033
|
+
{
|
|
6034
|
+
regex: /\.(?:find|findOne|findOneAndUpdate|update|updateOne|updateMany|deleteOne|deleteMany|remove)\s*\(\s*\{[^}]*:\s*req\.(?:body|query|params)\b/i,
|
|
6035
|
+
message: "MongoDB/NoSQL query passes unvalidated request object into filter \u2013 vulnerable to NoSQL operator injection (CWE-943)"
|
|
6036
|
+
},
|
|
6037
|
+
{
|
|
6038
|
+
regex: /\$where\s*:\s*(?![`"'][^`"']*["'`]\s*[,}])\S/i,
|
|
6039
|
+
message: "MongoDB $where operator with dynamic value \u2013 vulnerable to JavaScript/NoSQL injection (CWE-943)"
|
|
4911
6040
|
}
|
|
4912
6041
|
];
|
|
4913
6042
|
var LDAP_INJECTION_PATTERNS = [
|
|
@@ -5085,10 +6214,25 @@ function analyzeInjection(context) {
|
|
|
5085
6214
|
references: ["https://cheatsheetseries.owasp.org/cheatsheets/Deserialization_Cheat_Sheet.html"]
|
|
5086
6215
|
}
|
|
5087
6216
|
}));
|
|
5088
|
-
|
|
5089
|
-
|
|
5090
|
-
|
|
5091
|
-
|
|
6217
|
+
findings.push(...detectPatterns(context, NOSQL_INJECTION_PATTERNS, {
|
|
6218
|
+
ruleId: "SEC-INJ-007",
|
|
6219
|
+
category: "injection",
|
|
6220
|
+
subcategory: "nosql-injection",
|
|
6221
|
+
title: "NoSQL Operator Injection",
|
|
6222
|
+
severity: "high",
|
|
6223
|
+
confidence: "high",
|
|
6224
|
+
cwe: ["CWE-943"],
|
|
6225
|
+
owasp: ["A03:2021"],
|
|
6226
|
+
tags: ["nosql", "mongodb", "injection"],
|
|
6227
|
+
fix: {
|
|
6228
|
+
description: "Validate and coerce query inputs to expected scalar types (e.g. String(req.body.id)) or sanitize MongoDB $-prefixed operators.",
|
|
6229
|
+
references: ["https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/07-Input_Validation_Testing/05.6-Testing_for_NoSQL_Injection"]
|
|
6230
|
+
}
|
|
6231
|
+
}));
|
|
6232
|
+
return findings;
|
|
6233
|
+
}
|
|
6234
|
+
function detectPatterns(context, patterns, meta) {
|
|
6235
|
+
const findings = [];
|
|
5092
6236
|
const { content, filePath } = context;
|
|
5093
6237
|
for (const { regex, message } of patterns) {
|
|
5094
6238
|
const matches = matchPattern(content, regex);
|
|
@@ -5105,6 +6249,21 @@ function detectPatterns(context, patterns, meta) {
|
|
|
5105
6249
|
const isLocalScript = /(?:^|[\\/])(?:scripts?|tools?|bin|dev)[\\/]/i.test(filePath);
|
|
5106
6250
|
const hasNetworkInput = /\b(?:req\b|request\b|app\.(?:get|post|put|delete|use)|router\.|http\.createServer|WebSocket|socket\.on|@Controller|@Get|@Post|flask|fastapi)\b/i.test(content);
|
|
5107
6251
|
if (isLocalScript && !hasNetworkInput) continue;
|
|
6252
|
+
if (/\bescapeshellarg\s*\(/.test(match.lineContent) || /\bR\.exec\s*\(/.test(match.lineContent)) {
|
|
6253
|
+
continue;
|
|
6254
|
+
}
|
|
6255
|
+
if (/vm\.runIn(?:New)?Context\s*\(/.test(match.match)) {
|
|
6256
|
+
const lines = content.split("\n");
|
|
6257
|
+
const vmWin = lines.slice(Math.max(0, match.line - 11), Math.min(lines.length, match.line + 11)).join("\n");
|
|
6258
|
+
if (!/\b(?:req|request|body|query|params)\.|safeEval\b/.test(vmWin)) {
|
|
6259
|
+
continue;
|
|
6260
|
+
}
|
|
6261
|
+
}
|
|
6262
|
+
}
|
|
6263
|
+
if (meta.ruleId === "SEC-INJ-006" && (context.language === "java" || context.language === "kotlin")) {
|
|
6264
|
+
if (/\b(?:setObjectInputFilter|ObjectInputFilter|resolveClass)\b/.test(content)) {
|
|
6265
|
+
continue;
|
|
6266
|
+
}
|
|
5108
6267
|
}
|
|
5109
6268
|
const snippet = extractSnippet(content, match.line);
|
|
5110
6269
|
findings.push(
|
|
@@ -5242,7 +6401,7 @@ var XSS_PATTERNS = [
|
|
|
5242
6401
|
// ── DOM-based XSS patterns ──
|
|
5243
6402
|
{
|
|
5244
6403
|
// location.hash / location.search used in DOM operations
|
|
5245
|
-
regex: /(?:location\.(?:hash|search
|
|
6404
|
+
regex: /(?<![.\w$])(?:window\.)?location\.(?:hash|search)\s*(?:;|\))/i,
|
|
5246
6405
|
message: "DOM source (location/document) accessed \u2013 check for XSS if used in DOM sinks",
|
|
5247
6406
|
severity: "low",
|
|
5248
6407
|
confidence: "low",
|
|
@@ -5314,8 +6473,17 @@ var XSS_PATTERNS = [
|
|
|
5314
6473
|
cwe: ["CWE-79"]
|
|
5315
6474
|
},
|
|
5316
6475
|
{
|
|
5317
|
-
//
|
|
5318
|
-
regex:
|
|
6476
|
+
// PHP reflected XSS via HTML string appended with $_GET / $_POST / $_REQUEST
|
|
6477
|
+
regex: /\$[a-zA-Z_]\w*\s*\.?=\s*['"][^'"]*<[a-zA-Z]+[^>]*>[^'"]*['"]\s*\.\s*\$_(?:GET|POST|REQUEST)\b/i,
|
|
6478
|
+
message: "PHP HTML string concatenation with unescaped request input \u2013 reflected XSS risk",
|
|
6479
|
+
severity: "high",
|
|
6480
|
+
confidence: "high",
|
|
6481
|
+
subcategory: "reflected-xss",
|
|
6482
|
+
cwe: ["CWE-79"]
|
|
6483
|
+
},
|
|
6484
|
+
{
|
|
6485
|
+
// Flask/Python HTML response return with string formatting % (require real HTML tag name to skip __repr__ '<LazySettings ...>')
|
|
6486
|
+
regex: /return\s+['"][^'"]*<(?:div|span|p|a|h[1-6]|ul|ol|li|table|tr|td|th|form|input|button|select|option|textarea|script|style|img|iframe|body|html|head|title|pre|code|br|hr|b|i|u|strong|em|label|section|article|header|footer|nav|main|svg)\b[^>]*>[^'"]*['"]\s*%\s*[^;]+/i,
|
|
5319
6487
|
message: "Python string formatting with % used to return HTML response \u2013 reflected XSS risk",
|
|
5320
6488
|
severity: "high",
|
|
5321
6489
|
confidence: "medium",
|
|
@@ -5324,7 +6492,7 @@ var XSS_PATTERNS = [
|
|
|
5324
6492
|
},
|
|
5325
6493
|
{
|
|
5326
6494
|
// Flask/Python HTML response return with f-strings
|
|
5327
|
-
regex: /return\s+f['"][^'"]*<[
|
|
6495
|
+
regex: /return\s+f['"][^'"]*<(?:div|span|p|a|h[1-6]|ul|ol|li|table|tr|td|th|form|input|button|select|option|textarea|script|style|img|iframe|body|html|head|title|pre|code|br|hr|b|i|u|strong|em|label|section|article|header|footer|nav|main|svg)\b[^>]*>[^'"]*\{[^}]+\}[^'"]*['"]/i,
|
|
5328
6496
|
message: "Python f-string used to return HTML response \u2013 reflected XSS risk",
|
|
5329
6497
|
severity: "high",
|
|
5330
6498
|
confidence: "medium",
|
|
@@ -5333,7 +6501,7 @@ var XSS_PATTERNS = [
|
|
|
5333
6501
|
},
|
|
5334
6502
|
{
|
|
5335
6503
|
// Flask/Python HTML response return with .format()
|
|
5336
|
-
regex: /return\s+['"][^'"]*<[
|
|
6504
|
+
regex: /return\s+['"][^'"]*<(?:div|span|p|a|h[1-6]|ul|ol|li|table|tr|td|th|form|input|button|select|option|textarea|script|style|img|iframe|body|html|head|title|pre|code|br|hr|b|i|u|strong|em|label|section|article|header|footer|nav|main|svg)\b[^>]*>[^'"]*['"]\.format\s*\(/i,
|
|
5337
6505
|
message: "Python .format() used to return HTML response \u2013 reflected XSS risk",
|
|
5338
6506
|
severity: "high",
|
|
5339
6507
|
confidence: "medium",
|
|
@@ -5411,6 +6579,25 @@ function analyzeXSS(context) {
|
|
|
5411
6579
|
const precedingLines = content.split("\n").slice(startContext, lineIdx).join("\n");
|
|
5412
6580
|
const hasPrecedingSanitization = /(?:sanitizeHtml|DOMPurify|escapeHtml|escapeHTML|ensureHtmlContent|buildHtmlAndToc|sanitize|purify|htmlspecialchars|htmlentities)\s*\(/i.test(precedingLines);
|
|
5413
6581
|
const fileHasSanitizerImportOrDef = /(?:import\s+[^;]*\b(?:sanitizeHtml|DOMPurify|ensureHtmlContent|buildHtmlAndToc)\b|function\s+sanitizeHtml\b)/i.test(content);
|
|
6582
|
+
if (pattern.subcategory === "react-xss" && /<style\b/i.test(match.lineContent)) {
|
|
6583
|
+
const lines = content.split("\n");
|
|
6584
|
+
const styleWin = lines.slice(Math.max(0, match.line - 3), Math.min(lines.length, match.line + 3)).join("\n");
|
|
6585
|
+
if (!/\b(?:req|request|params|query|body|user|input)\b/i.test(styleWin)) {
|
|
6586
|
+
continue;
|
|
6587
|
+
}
|
|
6588
|
+
}
|
|
6589
|
+
if (context.language === "python") {
|
|
6590
|
+
const pyLines = content.split("\n");
|
|
6591
|
+
const prevPy = pyLines.slice(Math.max(0, match.line - 8), match.line).join("\n");
|
|
6592
|
+
if (/def\s+__(?:repr|str)__\s*\(/.test(prevPy)) {
|
|
6593
|
+
continue;
|
|
6594
|
+
}
|
|
6595
|
+
if (/mark_safe\s*\(/.test(match.lineContent)) {
|
|
6596
|
+
if (/(?:\.as_(?:ul|p|table)\s*\(|empty_value_display|\bformat_html\s*\(|\bescape\s*\()/i.test(match.lineContent)) {
|
|
6597
|
+
continue;
|
|
6598
|
+
}
|
|
6599
|
+
}
|
|
6600
|
+
}
|
|
5414
6601
|
if (pattern.subcategory === "react-xss" && pattern.severity === "medium" || pattern.subcategory === "dom-xss" && pattern.regex.source.includes("insertAdjacentHTML")) {
|
|
5415
6602
|
if (hasPrecedingSanitization) {
|
|
5416
6603
|
continue;
|
|
@@ -5457,6 +6644,9 @@ function analyzeXSS(context) {
|
|
|
5457
6644
|
if (pattern.subcategory === "template-xss" && ["c", "cpp", "rust", "go", "java", "csharp", "swift", "kotlin"].includes(context.language)) {
|
|
5458
6645
|
continue;
|
|
5459
6646
|
}
|
|
6647
|
+
if (context.language === "python" && pattern.message.includes("Handlebars")) {
|
|
6648
|
+
continue;
|
|
6649
|
+
}
|
|
5460
6650
|
if (pattern.subcategory === "reflected-xss" && filePath.toLowerCase().endsWith(".py")) {
|
|
5461
6651
|
const hasPythonWebFramework = /\b(?:flask|fastapi|django|bottle|tornado|aiohttp|starlette|sanic|falcon|pyramid|cherrypy|webapp2|HttpResponse|HTMLResponse|render_template|@app\.|@router\.|@bp\.|request\.)\b/i.test(content);
|
|
5462
6652
|
if (!hasPythonWebFramework) {
|
|
@@ -5944,7 +7134,8 @@ function analyzeSecrets(context) {
|
|
|
5944
7134
|
for (const pattern of API_KEY_PATTERNS) {
|
|
5945
7135
|
findings.push(...detectSecretPattern(content, filePath, pattern));
|
|
5946
7136
|
}
|
|
5947
|
-
|
|
7137
|
+
const isManualTestCertPath = /(?:^|[\\/])manual-test[^\\/]*[\\/]/i.test(filePath);
|
|
7138
|
+
if ((!inTestFile || context.language === "config") && !(inTestFile && context.language === "config") && !isManualTestCertPath) {
|
|
5948
7139
|
for (const pattern of PRIVATE_KEY_PATTERNS) {
|
|
5949
7140
|
findings.push(...detectSecretPattern(content, filePath, pattern));
|
|
5950
7141
|
}
|
|
@@ -5962,6 +7153,9 @@ function detectSecretPattern(source, filePath, pattern) {
|
|
|
5962
7153
|
if (trimmed.startsWith("//") || trimmed.startsWith("*") || trimmed.startsWith("#") || trimmed.startsWith("/*")) {
|
|
5963
7154
|
continue;
|
|
5964
7155
|
}
|
|
7156
|
+
if (isTestFile(filePath) && /(?:sk_live|rk_live)_(?:test|fake|mock|dummy|sample|example|1234|0000|xxxx|aaaa)/i.test(match.match)) {
|
|
7157
|
+
continue;
|
|
7158
|
+
}
|
|
5965
7159
|
if (/process\.env\b|os\.environ|os\.getenv|System\.getenv|ENV\[|\benv\s*\(/i.test(match.lineContent)) {
|
|
5966
7160
|
const hasSecretEnvFallback = /process\.env\.(?![A-Z0-9_]*_(?:TABLE|BROKER|TIMEOUT|TTL|EXPIRY|EXPIRES|DRIVER|GUARD|PROVIDER|COLUMN|FIELD|PATH|URL|URI|ENABLED|LENGTH|COUNT|ALGO|ALGORITHM)\b)[A-Z0-9_]*(?:PASSWORD|PASSWD|PASS|PWD|SECRET|TOKEN|PRIVATE_KEY)[A-Z0-9_]*\s*(?:\|\||\?\?)\s*["'][^"']{4,}["']/i.test(match.lineContent) || /\b(?:env|os\.getenv|getenv)\s*\(\s*["'](?![A-Z0-9_]*_(?:TABLE|BROKER|TIMEOUT|TTL|EXPIRY|EXPIRES|DRIVER|GUARD|PROVIDER|COLUMN|FIELD|PATH|URL|URI|ENABLED|LENGTH|COUNT|ALGO|ALGORITHM)\b)[A-Z0-9_]*(?:PASSWORD|PASSWD|PASS|PWD|SECRET|TOKEN|PRIVATE_KEY)[A-Z0-9_]*["']\s*,\s*["'][^"']{4,}["']\s*\)/i.test(match.lineContent);
|
|
5967
7161
|
const isHardcodedTokenPrefix = /^(?:AKIA|ABIA|ACCA|ASIA|ghp_|gho_|ghu_|ghs_|ghr_|xox[bpors]-|sk_live_|rk_live_|AIza|GOCSPX-|SG\.|sq0atp-|npm_|dapi|dop_v1_|shpat_)/.test(match.match);
|
|
@@ -5992,9 +7186,29 @@ function detectSecretPattern(source, filePath, pattern) {
|
|
|
5992
7186
|
}
|
|
5993
7187
|
}
|
|
5994
7188
|
if (pattern.subcategory === "hardcoded-password") {
|
|
7189
|
+
if (/\b(?:placeholder|aria-label|helperText|hint)\s*=\s*["']/.test(match.lineContent)) {
|
|
7190
|
+
continue;
|
|
7191
|
+
}
|
|
7192
|
+
const isEnvFallback = /process\.env\b|\b(?:env|os\.getenv|getenv)\s*\(/i.test(match.lineContent);
|
|
7193
|
+
const isDbConfig = /\b(?:createConnection|createPool|DataSource|DATABASE_URL|PGPASSWORD|DB_PASS|DB_PASSWORD|mysql|postgres|mongodb|redis)\b/i.test(match.lineContent);
|
|
7194
|
+
if (!isEnvFallback && !isDbConfig) {
|
|
7195
|
+
const lines = source.split("\n");
|
|
7196
|
+
const precedingWindow = lines.slice(Math.max(0, match.line - 26), match.line).join("\n");
|
|
7197
|
+
const devLoginGateRe = /\b(?:ENABLE_DEV_LOGIN|VITE_ENABLE_DEV_LOGIN|NEXT_PUBLIC_ENABLE_DEV_LOGIN|ALLOW_DEV_LOGIN|DEV_LOGIN|ENABLE_DEMO_LOGIN|DEMO_LOGIN_ENABLED)\b|NODE_ENV\s*(?:===?\s*['"](?:development|dev|local|test)['"]|!==?\s*['"]production['"])|\bimport\.meta\.env\.DEV\b/;
|
|
7198
|
+
const isJsxView = /\.(?:jsx|tsx)$/i.test(filePath);
|
|
7199
|
+
if (devLoginGateRe.test(precedingWindow) || isJsxView && devLoginGateRe.test(source)) {
|
|
7200
|
+
continue;
|
|
7201
|
+
}
|
|
7202
|
+
}
|
|
5995
7203
|
const secretValueMatch = match.match.match(/(?:\|\||\?\?|[=:,])\s*['"]([^'"]+)['"]\s*\)?$/);
|
|
5996
7204
|
if (secretValueMatch) {
|
|
5997
7205
|
const secretValue = secretValueMatch[1];
|
|
7206
|
+
if (/^(?:label|msg|message|error|errors|auth|form|field|ui|i18n|common|validation|placeholder|title|heading|button|aria)\.[a-z0-9_.-]+$/i.test(secretValue)) {
|
|
7207
|
+
continue;
|
|
7208
|
+
}
|
|
7209
|
+
if (/^(?:password|passwd|secret|token|credential|api_?key)$/i.test(secretValue) && /(?:Field(?:Type|Name)|MFAMethod|Column|Key|Prop|Attr|Type)[A-Z0-9_]*\s*[:=]/i.test(match.lineContent)) {
|
|
7210
|
+
continue;
|
|
7211
|
+
}
|
|
5998
7212
|
if (shannonEntropy(secretValue) < 2) {
|
|
5999
7213
|
continue;
|
|
6000
7214
|
}
|
|
@@ -6209,7 +7423,7 @@ var AUTH_PATTERNS = [
|
|
|
6209
7423
|
},
|
|
6210
7424
|
// ── Insecure session configuration ──
|
|
6211
7425
|
{
|
|
6212
|
-
regex: /(?:session|cookie)\s*(
|
|
7426
|
+
regex: /(?:session|cookie)\s*(?:\([^)]*\{[^}]*|:\s*\{[^}]*|\.)\s*(?:secure\s*[:=]\s*false)/i,
|
|
6213
7427
|
message: "Session cookie Secure flag set to false \u2013 cookie sent over HTTP",
|
|
6214
7428
|
severity: "high",
|
|
6215
7429
|
confidence: "high",
|
|
@@ -6218,7 +7432,7 @@ var AUTH_PATTERNS = [
|
|
|
6218
7432
|
cwe: ["CWE-614"]
|
|
6219
7433
|
},
|
|
6220
7434
|
{
|
|
6221
|
-
regex: /(?:session|cookie)\s*(
|
|
7435
|
+
regex: /(?:session|cookie)\s*(?:\([^)]*\{[^}]*|:\s*\{[^}]*|\.)\s*(?:httpOnly\s*[:=]\s*false)/i,
|
|
6222
7436
|
message: "Session cookie HttpOnly flag set to false \u2013 cookie accessible via JavaScript",
|
|
6223
7437
|
severity: "high",
|
|
6224
7438
|
confidence: "high",
|
|
@@ -6378,6 +7592,11 @@ function analyzeAuth(context) {
|
|
|
6378
7592
|
continue;
|
|
6379
7593
|
}
|
|
6380
7594
|
if (isPatternDefinitionContext(match.lineContent, match.column)) continue;
|
|
7595
|
+
if (pattern.ruleId === "SEC-AUTH-001") {
|
|
7596
|
+
if (/\btypeof\s+[\w.[\]?$]*\b(?:password|passwd|pwd|pass)\s*[!=]==?\s*["'](?:string|number|boolean|undefined|object|function|symbol|bigint)["']/i.test(match.lineContent) || /\b(?:type|name|field|kind|role)\s*[!=]==?\s*["'](?:password|passwd|pwd)["']/i.test(match.lineContent)) {
|
|
7597
|
+
continue;
|
|
7598
|
+
}
|
|
7599
|
+
}
|
|
6381
7600
|
if (pattern.ruleId === "SEC-AUTH-005" && /\bapp\.run\s*\([^)]*\bdebug\s*=\s*True\b/.test(match.lineContent) && !/host\s*=\s*["']0\.0\.0\.0["']/.test(match.lineContent)) {
|
|
6382
7601
|
const lines = content.split("\n");
|
|
6383
7602
|
const prevWindow = lines.slice(Math.max(0, match.line - 4), match.line - 1).join("\n");
|
|
@@ -6816,8 +8035,18 @@ var FILE_OPS_PATTERNS = [
|
|
|
6816
8035
|
cwe: ["CWE-22"]
|
|
6817
8036
|
},
|
|
6818
8037
|
{
|
|
6819
|
-
//
|
|
6820
|
-
regex:
|
|
8038
|
+
// Express res.sendFile(path.resolve(..., var)) when request params/query flow into handler without confinement
|
|
8039
|
+
regex: /\bres\.sendFile\s*\(\s*path\.(?:resolve|join)\s*\([^)]+\)/i,
|
|
8040
|
+
message: "res.sendFile(path.resolve/join) without directory confinement \u2013 potential path traversal risk",
|
|
8041
|
+
severity: "high",
|
|
8042
|
+
confidence: "high",
|
|
8043
|
+
subcategory: "path-traversal",
|
|
8044
|
+
ruleId: "SEC-FILE-001",
|
|
8045
|
+
cwe: ["CWE-22"]
|
|
8046
|
+
},
|
|
8047
|
+
{
|
|
8048
|
+
// PHP file inclusion (with or without parentheses, direct superglobal or variable)
|
|
8049
|
+
regex: /(?:include|require|include_once|require_once)\s*(?:\(\s*|\s+)(?:\$_(?:GET|POST|REQUEST)\b|\$[a-zA-Z_]\w*)/i,
|
|
6821
8050
|
message: "PHP file inclusion with user input \u2013 Local/Remote File Inclusion vulnerability",
|
|
6822
8051
|
severity: "critical",
|
|
6823
8052
|
confidence: "high",
|
|
@@ -6931,7 +8160,7 @@ var FILE_OPS_PATTERNS = [
|
|
|
6931
8160
|
},
|
|
6932
8161
|
{
|
|
6933
8162
|
// Go/Generic path traversal with variables in ReadFile/Open/etc.
|
|
6934
|
-
regex: /\b(?:ioutil\.|os\.)(?:ReadFile|Open|OpenFile|Create|Remove)\b\s*\(\s*[^'"`)]*\b(?:req|request|params|query|body|args|input|user|filename|uri|url)\b/i,
|
|
8163
|
+
regex: /\b(?:ioutil\.|os\.)(?:ReadFile|Open|OpenFile|Create|WriteFile|Remove)\b\s*\(\s*[^'"`)]*\b(?:req|request|params|query|body|args|input|user|filename|uri|url|payload)\b/i,
|
|
6935
8164
|
message: "File read/open using dynamic path \u2013 potential path traversal risk",
|
|
6936
8165
|
severity: "high",
|
|
6937
8166
|
confidence: "medium",
|
|
@@ -6958,8 +8187,20 @@ function analyzeFileOps(context) {
|
|
|
6958
8187
|
const matches = matchPattern(content, pattern.regex);
|
|
6959
8188
|
for (const match of matches) {
|
|
6960
8189
|
if (context.tree && isInSafeASTContext(context.tree, match.line, match.column)) continue;
|
|
6961
|
-
if (pattern.ruleId === "SEC-FILE-003"
|
|
6962
|
-
|
|
8190
|
+
if (pattern.ruleId === "SEC-FILE-003") {
|
|
8191
|
+
if (context.language === "dockerfile" || /\.(?:conf|cnf|ini|cfg|toml|service|socket)$/i.test(filePath) || /(?:^|[\\/])(?:dockerfile(?:\.[^/\\]+)?|[^/\\]+\.dockerfile|(?:docker-)?compose(?:\.[^/\\]+)?\.ya?ml)$/i.test(filePath)) {
|
|
8192
|
+
continue;
|
|
8193
|
+
}
|
|
8194
|
+
if (/['"`]\.\/tmp\/|unix:\/\/\/tmp\/|CURLOPT_UNIX_SOCKET_PATH/i.test(match.lineContent)) {
|
|
8195
|
+
continue;
|
|
8196
|
+
}
|
|
8197
|
+
if (context.language === "php" && /\btempnam\s*\(/i.test(match.lineContent)) {
|
|
8198
|
+
const phpLines = content.split("\n");
|
|
8199
|
+
const nextPhp = phpLines.slice(match.line - 1, Math.min(phpLines.length, match.line + 5)).join("\n");
|
|
8200
|
+
if (/\bchmod\s*\(/i.test(nextPhp)) {
|
|
8201
|
+
continue;
|
|
8202
|
+
}
|
|
8203
|
+
}
|
|
6963
8204
|
}
|
|
6964
8205
|
const trimmed = match.lineContent.trimStart();
|
|
6965
8206
|
if (trimmed.startsWith("//") || trimmed.startsWith("*") || trimmed.startsWith("#") || trimmed.startsWith("/*")) {
|
|
@@ -6967,16 +8208,31 @@ function analyzeFileOps(context) {
|
|
|
6967
8208
|
}
|
|
6968
8209
|
if (isPatternDefinitionContext(match.lineContent, match.column)) continue;
|
|
6969
8210
|
const isConfigFile = filePath.endsWith(".config.js") || filePath.endsWith(".config.ts") || filePath.includes("vite.config") || filePath.includes("webpack.") || filePath.includes("tailwind.");
|
|
6970
|
-
|
|
8211
|
+
const isPhpLfiPattern = pattern.cwe.includes("CWE-98");
|
|
8212
|
+
if (trimmed.startsWith("import ") || trimmed.startsWith("export ") || trimmed.startsWith("from ") || trimmed.includes("require(") || !isPhpLfiPattern && (trimmed.includes("require ") || trimmed.includes("require_once ") || trimmed.includes("include ") || trimmed.includes("include_once ")) || isConfigFile) {
|
|
6971
8213
|
continue;
|
|
6972
8214
|
}
|
|
8215
|
+
if (isPhpLfiPattern) {
|
|
8216
|
+
if (!/\$_(?:GET|POST|REQUEST)\b/.test(match.match)) {
|
|
8217
|
+
const varMatch = match.match.match(/\$([a-zA-Z_]\w*)$/);
|
|
8218
|
+
if (!varMatch) continue;
|
|
8219
|
+
const varName = varMatch[1];
|
|
8220
|
+
const phpLines = content.split("\n");
|
|
8221
|
+
const prePhp = phpLines.slice(Math.max(0, match.line - 16), match.line).join("\n");
|
|
8222
|
+
const assignsFromReq = new RegExp(`\\$${varName}\\s*=[^;\\n]*\\$_(?:GET|POST|REQUEST)\\b`).test(prePhp);
|
|
8223
|
+
const hasLfiGuard = /\b(?:basename|in_array)\s*\(/.test(prePhp);
|
|
8224
|
+
if (!assignsFromReq || hasLfiGuard) {
|
|
8225
|
+
continue;
|
|
8226
|
+
}
|
|
8227
|
+
}
|
|
8228
|
+
}
|
|
6973
8229
|
if (trimmed.includes("__DIR__") || trimmed.includes("__dirname") || trimmed.includes("__filename") || trimmed.includes("__FILE__") || trimmed.includes("import.meta.url")) {
|
|
6974
8230
|
if (!/(?:req|request|params|query|body|args|input|user|GET|POST|REQUEST)\b/i.test(trimmed)) {
|
|
6975
8231
|
continue;
|
|
6976
8232
|
}
|
|
6977
8233
|
}
|
|
6978
8234
|
if (pattern.ruleId === "SEC-FILE-001" && pattern.confidence === "low") {
|
|
6979
|
-
if (
|
|
8235
|
+
if (trimmed.startsWith("<") || !/\b(?:readFile|readFileSync|writeFile|writeFileSync|createReadStream|open|openSync|include|include_once|require|require_once|sendFile|send_file|path\.join|path\.resolve|filepath\.Join|os\.path\.join|fs\.)\b/i.test(match.lineContent) || /\b(?:base_path|storage_path|resource_path|app_path|config_path|database_path|public_path|envFilePath|dotenv|process\.cwd)\b/i.test(match.lineContent) || /\.env\b/.test(match.lineContent) || !(/\b(?:req|request|params|query|body|args|user_input|userInput)\b/i.test(match.lineContent) || /\$_(?:GET|POST|REQUEST)\b/.test(match.lineContent))) {
|
|
6980
8236
|
continue;
|
|
6981
8237
|
}
|
|
6982
8238
|
}
|
|
@@ -6985,15 +8241,27 @@ function analyzeFileOps(context) {
|
|
|
6985
8241
|
continue;
|
|
6986
8242
|
}
|
|
6987
8243
|
}
|
|
6988
|
-
|
|
8244
|
+
const isSendFilePathResolve = /res\.sendFile\s*\(\s*path\./i.test(match.match);
|
|
8245
|
+
if (isSendFilePathResolve) {
|
|
8246
|
+
const hasReqParamsInFile = /\b(?:params\.|req\.params|req\.query|req\.body)\b/.test(content);
|
|
8247
|
+
const hasConfinement = content.includes(".startsWith(") || content.includes("basename(");
|
|
8248
|
+
if (!hasReqParamsInFile || hasConfinement) {
|
|
8249
|
+
continue;
|
|
8250
|
+
}
|
|
8251
|
+
}
|
|
8252
|
+
if (/\bsend_file\b/.test(match.match) && /\bRails\.root\.join\s*\(\s*(?:["'][^"']*["']\s*(?:,\s*["'][^"']*["']\s*)*)\)/.test(match.lineContent)) {
|
|
8253
|
+
continue;
|
|
8254
|
+
}
|
|
8255
|
+
if (pattern.ruleId === "SEC-FILE-001" && pattern.confidence !== "low" && !isSendFilePathResolve && !isPhpLfiPattern) {
|
|
8256
|
+
const lines = content.split("\n");
|
|
8257
|
+
const nearby = lines.slice(Math.max(0, match.line - 15), Math.min(lines.length, match.line + 5)).join("\n");
|
|
8258
|
+
if (/\b(?:basename\s*\(|\.startsWith\s*\(|filepath\.Base\s*\(|strings\.HasPrefix\s*\()/.test(nearby)) {
|
|
8259
|
+
continue;
|
|
8260
|
+
}
|
|
6989
8261
|
const hasExplicitReqSource = /(?:\b(?:req\.|request\.|params\.|query\.|body\.|r\.URL)|\$_(?:GET|POST|REQUEST))/i.test(match.lineContent);
|
|
6990
8262
|
if (!hasExplicitReqSource) {
|
|
6991
|
-
const
|
|
6992
|
-
const
|
|
6993
|
-
if (/\b(?:basename\s*\(|\.startsWith\s*\()/.test(nearby)) {
|
|
6994
|
-
continue;
|
|
6995
|
-
}
|
|
6996
|
-
const windowHasHttpSources = /(?:\b(?:req\.|request\.|r\.URL|http\.Request|params\[)|\$_(?:GET|POST|REQUEST)\b|@(?:Query|Param|Body)\b)/i.test(nearby);
|
|
8263
|
+
const hasGoHttpPayload = context.language === "go" && /\bpayload\b/.test(match.lineContent) && content.includes('"net/http"');
|
|
8264
|
+
const windowHasHttpSources = hasGoHttpPayload || /(?:\b(?:req\.|request\.|r\.URL|http\.Request|params\[)|\$_(?:GET|POST|REQUEST)\b|@(?:Query|Param|Body)\b)/i.test(nearby);
|
|
6997
8265
|
if (!windowHasHttpSources) {
|
|
6998
8266
|
continue;
|
|
6999
8267
|
}
|
|
@@ -7096,7 +8364,7 @@ var API_SEC_PATTERNS = [
|
|
|
7096
8364
|
title: "Server-Side Request Forgery (SSRF)"
|
|
7097
8365
|
},
|
|
7098
8366
|
{
|
|
7099
|
-
regex: /fetch\s*\(\s*(?:req|request|params|query|body|args|input|user|url)\b/i,
|
|
8367
|
+
regex: /(?<![.\w$])fetch\s*\(\s*(?:req|request|params|query|body|args|input|user|url)\b/i,
|
|
7100
8368
|
message: "Fetch request with user-controlled URL \u2013 vulnerable to SSRF",
|
|
7101
8369
|
severity: "critical",
|
|
7102
8370
|
confidence: "high",
|
|
@@ -7231,7 +8499,7 @@ var API_SEC_PATTERNS = [
|
|
|
7231
8499
|
},
|
|
7232
8500
|
// ── Open Redirect ──
|
|
7233
8501
|
{
|
|
7234
|
-
regex: /\b(?:res\.redirect\s*\(\s*(?:req|request)\.(?:query|body|params)\b|redirect\s*\(\s*request\.(?:args|form|values|GET|POST)\b|redirect_to\s*\(?\s*params\[|http\.Redirect\s*\(\s*\w+\s*,\s*\w+\s*,\s*(?![`"'])(?:payload|redirectURL|target|url|in|r\.URL|r\.FormValue)\b)/i,
|
|
8502
|
+
regex: /\b(?:res\.redirect\s*\(\s*(?:(?:req|request)\.(?:query|body|params)\b|[a-zA-Z_$][\w$]*\s*\))|redirect\s*\(\s*request\.(?:args|form|values|GET|POST)\b|redirect_to\s*\(?\s*params\[|header\s*\(\s*['"]location\s*:\s*['"]\s*\.\s*\$_(?:GET|POST|REQUEST)\b|http\.Redirect\s*\(\s*\w+\s*,\s*\w+\s*,\s*(?![`"'])(?:payload|redirectURL|target|url|in|r\.URL|r\.FormValue)\b)/i,
|
|
7235
8503
|
message: "Unvalidated redirect using user-controlled input \u2013 vulnerable to Open Redirect phishing attacks (CWE-601)",
|
|
7236
8504
|
severity: "medium",
|
|
7237
8505
|
confidence: "high",
|
|
@@ -7267,7 +8535,7 @@ function analyzeAPISec(context) {
|
|
|
7267
8535
|
if (content.includes("startsWith") || content.includes("validate") || content.includes("whitelist") || content.includes("trusted")) {
|
|
7268
8536
|
continue;
|
|
7269
8537
|
}
|
|
7270
|
-
if (/(?:function\s+\w
|
|
8538
|
+
if (/(?:(?:function|async)\s+\w*\s*\(\s*(?:url|req|request)\b|\bfetch\s*\(\s*(?:url|req|request)(?:\s*:\s*[^)]+)?\)\s*(?::\s*[^{\n]+)?\{|\bfetch\s*=\s*(?:async\s*)?\()/i.test(trimmed)) {
|
|
7271
8539
|
continue;
|
|
7272
8540
|
}
|
|
7273
8541
|
if (/(?:^|[\\/])(?:public|frontend|client|admin_views|extension|src[\\/](?:components|pages|views|hooks|store|assets))[\\/]/i.test(filePath)) {
|
|
@@ -7276,11 +8544,29 @@ function analyzeAPISec(context) {
|
|
|
7276
8544
|
if (/\(\s*url\b/i.test(match.match)) {
|
|
7277
8545
|
const lines = content.split("\n");
|
|
7278
8546
|
const preceding = lines.slice(Math.max(0, match.line - 16), match.line - 1).join("\n");
|
|
7279
|
-
const isHardcodedOrConfigUrl = /(?:const|let|var)?\s*\burl\s*=\s*(?:[`"'](?:https?:\/\/|\/)|[a-zA-Z0-9_.]*(?:BASE|API|HOST|ENDPOINT|ORIGIN|URL|url|uri|config|env)[a-zA-Z0-9_.]*\s*(?:\+|`|\|\|))/i.test(preceding);
|
|
8547
|
+
const isHardcodedOrConfigUrl = /(?:const|let|var)?\s*\burl\s*=\s*(?:[`"'](?:https?:\/\/|\/)|[a-zA-Z0-9_.]*(?:BASE|API|HOST|ENDPOINT|ORIGIN|URL|url|uri|config|env)[a-zA-Z0-9_.]*\s*(?:\+|`|\|\|)|new\s+URL\s*\(\s*notification\.)/i.test(preceding);
|
|
8548
|
+
const isConfigHelperCall = /\b(?:getAxiosConfigWithProxy|this\.getConfig)\s*\(/.test(preceding);
|
|
7280
8549
|
const hasRequestInputInScope = /(?:req\.|(?<!urllib\.)\brequest\.(?!urlopen|Request|urlretrieve)\b|@Query|@Body|@Param|params\b|query\b|user_input|r\.URL|flask\.request)/i.test(
|
|
7281
8550
|
lines.slice(Math.max(0, match.line - 20), Math.min(lines.length, match.line + 2)).join("\n")
|
|
7282
8551
|
);
|
|
7283
|
-
if (isHardcodedOrConfigUrl || !hasRequestInputInScope) {
|
|
8552
|
+
if (isHardcodedOrConfigUrl || isConfigHelperCall && !/\breq\.|\brequest\.|\bparams\.|\bquery\.|\bbody\./i.test(preceding) || !hasRequestInputInScope) {
|
|
8553
|
+
continue;
|
|
8554
|
+
}
|
|
8555
|
+
}
|
|
8556
|
+
}
|
|
8557
|
+
if (pattern.ruleId === "SEC-API-003") {
|
|
8558
|
+
const localRedirectMatch = match.match.match(/\bres\.redirect\s*\(\s*([a-zA-Z_$][\w$]*)\s*\)/);
|
|
8559
|
+
if (localRedirectMatch) {
|
|
8560
|
+
const varName = localRedirectMatch[1];
|
|
8561
|
+
if (varName === "req" || varName === "request") {
|
|
8562
|
+
}
|
|
8563
|
+
const lines = content.split("\n");
|
|
8564
|
+
const preWin = lines.slice(Math.max(0, match.line - 12), match.line).join("\n");
|
|
8565
|
+
const varFromReqRe = new RegExp(
|
|
8566
|
+
`(?:const|let|var)\\s+${varName}\\b[^=]*=\\s*[^;\\n]*(?:req\\.|request\\.|query\\.|params\\.|body\\.)`
|
|
8567
|
+
);
|
|
8568
|
+
const hasStrictGuard = /\.startsWith\s*\(\s*['"]\/['"]|\.origin\s*===/.test(preWin);
|
|
8569
|
+
if (!varFromReqRe.test(preWin) || hasStrictGuard) {
|
|
7284
8570
|
continue;
|
|
7285
8571
|
}
|
|
7286
8572
|
}
|
|
@@ -7554,6 +8840,177 @@ function analyzeComposeFile(content, filePath) {
|
|
|
7554
8840
|
return findings;
|
|
7555
8841
|
}
|
|
7556
8842
|
|
|
8843
|
+
// src/scanners/security/analyzers/ast-structural.ts
|
|
8844
|
+
var TEST_OR_FIXTURE_PATH_RE = /(?:^|[\\/])(?:tests?|__tests__|spec|__spec__|fixtures?|mocks?|__mocks__|e2e|integration|cypress|playwright|scratch|benchmarks?)[\\/]/i;
|
|
8845
|
+
var NOSQL_MUTATING_OR_QUERY_METHODS = /* @__PURE__ */ new Set([
|
|
8846
|
+
"find",
|
|
8847
|
+
"findOne",
|
|
8848
|
+
"findOneAndUpdate",
|
|
8849
|
+
"update",
|
|
8850
|
+
"updateOne",
|
|
8851
|
+
"updateMany",
|
|
8852
|
+
"deleteOne",
|
|
8853
|
+
"deleteMany",
|
|
8854
|
+
"remove"
|
|
8855
|
+
]);
|
|
8856
|
+
var SQL_EXEC_METHODS = /* @__PURE__ */ new Set([
|
|
8857
|
+
"query",
|
|
8858
|
+
"execute",
|
|
8859
|
+
"raw",
|
|
8860
|
+
"executeQuery",
|
|
8861
|
+
"executeUpdate"
|
|
8862
|
+
]);
|
|
8863
|
+
var ANGULAR_TRUST_RE = /^bypassSecurityTrust(?:Html|Script|Url|ResourceUrl)$/;
|
|
8864
|
+
function analyzeAstStructural(context) {
|
|
8865
|
+
const findings = [];
|
|
8866
|
+
const { content, filePath, language } = context;
|
|
8867
|
+
if (content.length < 10 || TEST_OR_FIXTURE_PATH_RE.test(filePath)) {
|
|
8868
|
+
return findings;
|
|
8869
|
+
}
|
|
8870
|
+
const isJsTs = language === "javascript" || language === "typescript";
|
|
8871
|
+
const model = context.codeModel ?? buildFileCodeModel(content, filePath, language, context.tree);
|
|
8872
|
+
const seenKeys = /* @__PURE__ */ new Set();
|
|
8873
|
+
const pushUnique = (finding) => {
|
|
8874
|
+
const key = `${finding.ruleId}:${finding.location.startLine}`;
|
|
8875
|
+
if (seenKeys.has(key)) return;
|
|
8876
|
+
seenKeys.add(key);
|
|
8877
|
+
findings.push(finding);
|
|
8878
|
+
};
|
|
8879
|
+
for (const call of model.callSites) {
|
|
8880
|
+
if (isJsTs && call.endLine > call.startLine && NOSQL_MUTATING_OR_QUERY_METHODS.has(call.methodName) && call.args.length > 0) {
|
|
8881
|
+
const firstArg = call.args[0].text.trim();
|
|
8882
|
+
if (firstArg.startsWith("{")) {
|
|
8883
|
+
const sanitizedStripped = firstArg.replace(/\b(?:String|Number|parseInt|Boolean|ObjectId)\s*\([^)]*\)/g, "");
|
|
8884
|
+
if (/:\s*req\.(?:body|query|params)\b/i.test(sanitizedStripped)) {
|
|
8885
|
+
pushUnique(
|
|
8886
|
+
createFinding({
|
|
8887
|
+
ruleId: "SEC-INJ-007",
|
|
8888
|
+
scanner: "security",
|
|
8889
|
+
severity: "high",
|
|
8890
|
+
confidence: "high",
|
|
8891
|
+
category: "injection",
|
|
8892
|
+
subcategory: "nosql-injection",
|
|
8893
|
+
title: "Multi-line NoSQL Operator Injection",
|
|
8894
|
+
message: `Multi-line NoSQL query (${call.callee}) passes unvalidated request object into filter \u2013 vulnerable to operator injection (CWE-943).`,
|
|
8895
|
+
filePath,
|
|
8896
|
+
lineNumber: call.args[0].startLine,
|
|
8897
|
+
column: call.startColumn,
|
|
8898
|
+
snippet: extractSnippet(content, call.args[0].startLine),
|
|
8899
|
+
cwe: ["CWE-943"],
|
|
8900
|
+
owasp: ["A03:2021"],
|
|
8901
|
+
fix: {
|
|
8902
|
+
description: "Validate and coerce query values to scalar primitives (e.g. String(req.body.id)) or strip $-prefixed keys.",
|
|
8903
|
+
references: [
|
|
8904
|
+
"https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/07-Input_Validation_Testing/05.6-Testing_for_NoSQL_Injection"
|
|
8905
|
+
]
|
|
8906
|
+
},
|
|
8907
|
+
tags: ["nosql", "mongodb", "injection", "ast-structural"]
|
|
8908
|
+
})
|
|
8909
|
+
);
|
|
8910
|
+
}
|
|
8911
|
+
}
|
|
8912
|
+
}
|
|
8913
|
+
if (call.endLine > call.startLine && SQL_EXEC_METHODS.has(call.methodName) && call.args.length > 0 && !call.args[0].isLiteral) {
|
|
8914
|
+
const argText = call.args[0].text;
|
|
8915
|
+
const hasSqlKeyword = /\b(?:SELECT|INSERT\s+INTO|UPDATE\s+\w+\s+SET|DELETE\s+FROM|DROP\s+TABLE)\b/i.test(argText);
|
|
8916
|
+
const hasDynamicConcatOrInterp = /\$\{[^}]+\}|["'`]\s*\+\s*[a-zA-Z_]\w*|[a-zA-Z_]\w*\s*\+\s*["'`]/.test(argText);
|
|
8917
|
+
if (hasSqlKeyword && hasDynamicConcatOrInterp) {
|
|
8918
|
+
const lines = content.split("\n");
|
|
8919
|
+
const callLine = lines[call.startLine - 1] || call.fullText.split("\n")[0];
|
|
8920
|
+
if (!isSafeSqlInterpolation(content, filePath, call.startLine, callLine)) {
|
|
8921
|
+
pushUnique(
|
|
8922
|
+
createFinding({
|
|
8923
|
+
ruleId: "SEC-INJ-001",
|
|
8924
|
+
scanner: "security",
|
|
8925
|
+
severity: "critical",
|
|
8926
|
+
confidence: "high",
|
|
8927
|
+
category: "injection",
|
|
8928
|
+
subcategory: "sql-injection",
|
|
8929
|
+
title: "Multi-line SQL Injection",
|
|
8930
|
+
message: `Multi-line SQL query (${call.callee}) uses dynamic string interpolation or concatenation \u2013 vulnerable to SQL injection.`,
|
|
8931
|
+
filePath,
|
|
8932
|
+
lineNumber: call.args[0].startLine,
|
|
8933
|
+
column: call.startColumn,
|
|
8934
|
+
snippet: extractSnippet(content, call.args[0].startLine),
|
|
8935
|
+
cwe: ["CWE-89"],
|
|
8936
|
+
owasp: ["A03:2021"],
|
|
8937
|
+
fix: {
|
|
8938
|
+
description: "Use parameterized queries / prepared statements instead of interpolating values into SQL.",
|
|
8939
|
+
references: ["https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html"]
|
|
8940
|
+
},
|
|
8941
|
+
tags: ["sql", "injection", "ast-structural"]
|
|
8942
|
+
})
|
|
8943
|
+
);
|
|
8944
|
+
}
|
|
8945
|
+
}
|
|
8946
|
+
}
|
|
8947
|
+
if (isJsTs && ANGULAR_TRUST_RE.test(call.methodName) && call.args.length > 0 && !call.args[0].isLiteral) {
|
|
8948
|
+
pushUnique(
|
|
8949
|
+
createFinding({
|
|
8950
|
+
ruleId: "SEC-XSS-002",
|
|
8951
|
+
scanner: "security",
|
|
8952
|
+
severity: "high",
|
|
8953
|
+
confidence: "high",
|
|
8954
|
+
category: "xss",
|
|
8955
|
+
subcategory: "dom-xss",
|
|
8956
|
+
title: "Angular Sanitizer Bypass XSS",
|
|
8957
|
+
message: `${call.methodName}() explicitly bypasses Angular built-in XSS sanitization on a non-literal value (CWE-79).`,
|
|
8958
|
+
filePath,
|
|
8959
|
+
lineNumber: call.startLine,
|
|
8960
|
+
column: call.startColumn,
|
|
8961
|
+
snippet: extractSnippet(content, call.startLine),
|
|
8962
|
+
cwe: ["CWE-79"],
|
|
8963
|
+
owasp: ["A03:2021"],
|
|
8964
|
+
fix: {
|
|
8965
|
+
description: "Avoid DomSanitizer.bypassSecurityTrust* on untrusted input, or sanitize HTML first with DOMPurify.",
|
|
8966
|
+
references: ["https://angular.dev/best-practices/security#preventing-cross-site-scripting-xss"]
|
|
8967
|
+
},
|
|
8968
|
+
tags: ["xss", "angular", "ast-structural"]
|
|
8969
|
+
})
|
|
8970
|
+
);
|
|
8971
|
+
}
|
|
8972
|
+
}
|
|
8973
|
+
const lowerPath = filePath.toLowerCase();
|
|
8974
|
+
if (lowerPath.endsWith(".vue") || lowerPath.endsWith(".html")) {
|
|
8975
|
+
const lines = content.split("\n");
|
|
8976
|
+
const vHtmlRe = /\bv-html\s*=\s*["']([^"']+)["']/gi;
|
|
8977
|
+
for (let i = 0; i < lines.length; i++) {
|
|
8978
|
+
const line = lines[i];
|
|
8979
|
+
vHtmlRe.lastIndex = 0;
|
|
8980
|
+
let m;
|
|
8981
|
+
while ((m = vHtmlRe.exec(line)) !== null) {
|
|
8982
|
+
const expr = m[1].trim();
|
|
8983
|
+
if (!expr || /^['"]/.test(expr)) continue;
|
|
8984
|
+
if (/\b(?:sanitize|DOMPurify|escapeHtml|escapeHTML|purify)\b/i.test(expr)) continue;
|
|
8985
|
+
pushUnique(
|
|
8986
|
+
createFinding({
|
|
8987
|
+
ruleId: "SEC-XSS-002",
|
|
8988
|
+
scanner: "security",
|
|
8989
|
+
severity: "high",
|
|
8990
|
+
confidence: "medium",
|
|
8991
|
+
category: "xss",
|
|
8992
|
+
subcategory: "dom-xss",
|
|
8993
|
+
title: "Vue v-html Unescaped HTML Binding",
|
|
8994
|
+
message: `Vue v-html renders unescaped dynamic expression "${expr}" \u2013 XSS risk if untrusted input reaches this binding.`,
|
|
8995
|
+
filePath,
|
|
8996
|
+
lineNumber: i + 1,
|
|
8997
|
+
column: m.index + 1,
|
|
8998
|
+
snippet: extractSnippet(content, i + 1),
|
|
8999
|
+
cwe: ["CWE-79"],
|
|
9000
|
+
owasp: ["A03:2021"],
|
|
9001
|
+
fix: {
|
|
9002
|
+
description: "Sanitize HTML via DOMPurify before passing it to v-html, or use text interpolation {{ ... }}.",
|
|
9003
|
+
references: ["https://vuejs.org/guide/best-practices/security.html"]
|
|
9004
|
+
},
|
|
9005
|
+
tags: ["xss", "vue", "ast-structural"]
|
|
9006
|
+
})
|
|
9007
|
+
);
|
|
9008
|
+
}
|
|
9009
|
+
}
|
|
9010
|
+
}
|
|
9011
|
+
return findings;
|
|
9012
|
+
}
|
|
9013
|
+
|
|
7557
9014
|
// src/scanners/security/index.ts
|
|
7558
9015
|
var ANALYZERS = [
|
|
7559
9016
|
{ name: "injection", analyze: analyzeInjection },
|
|
@@ -7563,18 +9020,95 @@ var ANALYZERS = [
|
|
|
7563
9020
|
{ name: "crypto", analyze: analyzeCrypto },
|
|
7564
9021
|
{ name: "file-ops", analyze: analyzeFileOps },
|
|
7565
9022
|
{ name: "api-sec", analyze: analyzeAPISec },
|
|
7566
|
-
{ name: "iac", analyze: analyzeIaC }
|
|
9023
|
+
{ name: "iac", analyze: analyzeIaC },
|
|
9024
|
+
{ name: "ast-structural", analyze: analyzeAstStructural }
|
|
7567
9025
|
];
|
|
9026
|
+
var NON_PROD_TAINT_PATH_RE = /(?:^|[\\/])(?:tests?|__tests__|spec|__spec__|fixtures?|mocks?|__mocks__|e2e|integration|cypress|playwright|scratch|benchmarks?|samples?|playgrounds?|docs_src|scripts?|tools?)[\\/]/i;
|
|
7568
9027
|
var TAINT_METADATA = {
|
|
7569
|
-
code_injection: {
|
|
7570
|
-
|
|
7571
|
-
|
|
7572
|
-
|
|
7573
|
-
|
|
7574
|
-
|
|
7575
|
-
|
|
7576
|
-
|
|
7577
|
-
|
|
9028
|
+
code_injection: {
|
|
9029
|
+
ruleId: "SEC-TAINT-CMDI",
|
|
9030
|
+
category: "injection",
|
|
9031
|
+
severity: "critical",
|
|
9032
|
+
cwe: ["CWE-94"],
|
|
9033
|
+
title: "Code Injection via Taint Flow"
|
|
9034
|
+
},
|
|
9035
|
+
command_injection: {
|
|
9036
|
+
ruleId: "SEC-TAINT-CMDI",
|
|
9037
|
+
category: "injection",
|
|
9038
|
+
severity: "critical",
|
|
9039
|
+
cwe: ["CWE-78"],
|
|
9040
|
+
title: "Command Injection via Taint Flow"
|
|
9041
|
+
},
|
|
9042
|
+
sql_injection: {
|
|
9043
|
+
ruleId: "SEC-TAINT-SQLI",
|
|
9044
|
+
category: "injection",
|
|
9045
|
+
severity: "critical",
|
|
9046
|
+
cwe: ["CWE-89"],
|
|
9047
|
+
title: "SQL Injection via Taint Flow"
|
|
9048
|
+
},
|
|
9049
|
+
nosql_injection: {
|
|
9050
|
+
ruleId: "SEC-TAINT-NOSQL",
|
|
9051
|
+
category: "injection",
|
|
9052
|
+
severity: "high",
|
|
9053
|
+
cwe: ["CWE-943"],
|
|
9054
|
+
title: "NoSQL Operator Injection via Taint Flow"
|
|
9055
|
+
},
|
|
9056
|
+
xss: {
|
|
9057
|
+
ruleId: "SEC-TAINT-XSS",
|
|
9058
|
+
category: "xss",
|
|
9059
|
+
severity: "high",
|
|
9060
|
+
cwe: ["CWE-79"],
|
|
9061
|
+
title: "Cross-Site Scripting (XSS) via Taint Flow"
|
|
9062
|
+
},
|
|
9063
|
+
ssrf: {
|
|
9064
|
+
ruleId: "SEC-TAINT-SSRF",
|
|
9065
|
+
category: "api-security",
|
|
9066
|
+
severity: "critical",
|
|
9067
|
+
cwe: ["CWE-918"],
|
|
9068
|
+
title: "Server-Side Request Forgery (SSRF) via Taint Flow"
|
|
9069
|
+
},
|
|
9070
|
+
open_redirect: {
|
|
9071
|
+
ruleId: "SEC-TAINT-REDIRECT",
|
|
9072
|
+
category: "api-security",
|
|
9073
|
+
severity: "medium",
|
|
9074
|
+
cwe: ["CWE-601"],
|
|
9075
|
+
title: "Open Redirect via Taint Flow"
|
|
9076
|
+
},
|
|
9077
|
+
path_traversal: {
|
|
9078
|
+
ruleId: "SEC-TAINT-PATH",
|
|
9079
|
+
category: "file-ops",
|
|
9080
|
+
severity: "high",
|
|
9081
|
+
cwe: ["CWE-22"],
|
|
9082
|
+
title: "Path Traversal via Taint Flow"
|
|
9083
|
+
},
|
|
9084
|
+
file_inclusion: {
|
|
9085
|
+
ruleId: "SEC-TAINT-PATH",
|
|
9086
|
+
category: "file-ops",
|
|
9087
|
+
severity: "critical",
|
|
9088
|
+
cwe: ["CWE-98"],
|
|
9089
|
+
title: "File Inclusion via Taint Flow"
|
|
9090
|
+
},
|
|
9091
|
+
deserialization: {
|
|
9092
|
+
ruleId: "SEC-TAINT-DESER",
|
|
9093
|
+
category: "injection",
|
|
9094
|
+
severity: "critical",
|
|
9095
|
+
cwe: ["CWE-502"],
|
|
9096
|
+
title: "Insecure Deserialization via Taint Flow"
|
|
9097
|
+
},
|
|
9098
|
+
buffer_overflow: {
|
|
9099
|
+
ruleId: "SEC-TAINT-CMDI",
|
|
9100
|
+
category: "injection",
|
|
9101
|
+
severity: "high",
|
|
9102
|
+
cwe: ["CWE-120"],
|
|
9103
|
+
title: "Buffer Overflow via Taint Flow"
|
|
9104
|
+
},
|
|
9105
|
+
format_string: {
|
|
9106
|
+
ruleId: "SEC-TAINT-CMDI",
|
|
9107
|
+
category: "injection",
|
|
9108
|
+
severity: "high",
|
|
9109
|
+
cwe: ["CWE-134"],
|
|
9110
|
+
title: "Format String Vulnerability via Taint Flow"
|
|
9111
|
+
}
|
|
7578
9112
|
};
|
|
7579
9113
|
var SecurityScanner = class extends BaseScanner {
|
|
7580
9114
|
name = "SecurityScanner";
|
|
@@ -7605,35 +9139,47 @@ var SecurityScanner = class extends BaseScanner {
|
|
|
7605
9139
|
console.error(`[SecurityScanner] Error in ${analyzer.name} analyzer:`, error);
|
|
7606
9140
|
}
|
|
7607
9141
|
}
|
|
7608
|
-
if (context.
|
|
9142
|
+
if (!NON_PROD_TAINT_PATH_RE.test(context.filePath)) {
|
|
7609
9143
|
try {
|
|
7610
|
-
const taintResults = analyzeTaintFlow(
|
|
9144
|
+
const taintResults = analyzeTaintFlow(
|
|
9145
|
+
context.content,
|
|
9146
|
+
context.filePath,
|
|
9147
|
+
context.language,
|
|
9148
|
+
context.tree,
|
|
9149
|
+
{
|
|
9150
|
+
codeModel: context.codeModel,
|
|
9151
|
+
projectGraph: context.projectGraph,
|
|
9152
|
+
includeEnvSources: Boolean(context.config?.deep)
|
|
9153
|
+
}
|
|
9154
|
+
);
|
|
7611
9155
|
for (const res of taintResults) {
|
|
7612
9156
|
if (!res.hasTaintedSink || res.flow.length === 0) continue;
|
|
7613
9157
|
const sinkStep = res.flow[res.flow.length - 1];
|
|
7614
9158
|
const loc = sinkStep.location;
|
|
7615
9159
|
const meta = TAINT_METADATA[res.sinkType] || {
|
|
9160
|
+
ruleId: `SEC-TAINT-${res.sinkType.toUpperCase()}`,
|
|
9161
|
+
category: "injection",
|
|
7616
9162
|
severity: "high",
|
|
7617
9163
|
cwe: [],
|
|
7618
9164
|
title: `Taint Flow: ${res.sinkType.replace(/_/g, " ").toUpperCase()}`
|
|
7619
9165
|
};
|
|
7620
9166
|
const finding = createFinding({
|
|
7621
|
-
ruleId:
|
|
9167
|
+
ruleId: meta.ruleId,
|
|
7622
9168
|
scanner: "security",
|
|
7623
9169
|
severity: meta.severity,
|
|
7624
9170
|
confidence: "high",
|
|
7625
|
-
category:
|
|
9171
|
+
category: meta.category,
|
|
7626
9172
|
subcategory: res.sinkType,
|
|
7627
9173
|
title: meta.title,
|
|
7628
|
-
message: `Tainted data from source "${res.sourceType}" reaches sink "${res.sinkType}"
|
|
9174
|
+
message: `Tainted data from source "${res.sourceType}" reaches sink "${res.sinkType}" (${sinkStep.label}).`,
|
|
7629
9175
|
filePath: context.filePath,
|
|
7630
|
-
lineNumber: loc.startLine,
|
|
9176
|
+
lineNumber: loc.file === context.filePath ? loc.startLine : res.flow[Math.max(0, res.flow.length - 2)].location.startLine,
|
|
7631
9177
|
column: loc.startColumn,
|
|
7632
9178
|
snippet: loc.snippet,
|
|
7633
9179
|
cwe: meta.cwe,
|
|
7634
9180
|
owasp: ["A03:2021"],
|
|
7635
9181
|
fix: {
|
|
7636
|
-
description: `Sanitize the tainted value before passing it to ${res.sinkType}.`,
|
|
9182
|
+
description: `Sanitize or validate the tainted value before passing it to ${res.sinkType}.`,
|
|
7637
9183
|
references: []
|
|
7638
9184
|
},
|
|
7639
9185
|
tags: ["taint-flow", "security"]
|
|
@@ -7647,7 +9193,7 @@ var SecurityScanner = class extends BaseScanner {
|
|
|
7647
9193
|
}
|
|
7648
9194
|
if (context.rules.length > 0) {
|
|
7649
9195
|
const securityRules = context.rules.filter(
|
|
7650
|
-
(r) => r.category && ["injection", "xss", "secrets", "auth", "crypto", "file-ops", "api-security"].includes(r.category)
|
|
9196
|
+
(r) => !r.id.startsWith("security/") && r.category && ["injection", "xss", "secrets", "auth", "crypto", "file-ops", "api-security"].includes(r.category)
|
|
7651
9197
|
);
|
|
7652
9198
|
if (securityRules.length > 0) {
|
|
7653
9199
|
try {
|
|
@@ -7676,14 +9222,14 @@ var SecurityScanner = class extends BaseScanner {
|
|
|
7676
9222
|
};
|
|
7677
9223
|
|
|
7678
9224
|
// src/scanners/ops/analyzers/shared.ts
|
|
7679
|
-
var TEST_OR_SCRIPT_PATH_RE = /(?:^|[\\/])(?:tests?|__tests__|spec|__spec__|fixtures?|mocks?|__mocks__|e2e|integration|cypress|playwright|scratch|benchmarks?|seeds?|seeders?|migrations?|scripts?|tools?|bin)[\\/]/i;
|
|
9225
|
+
var TEST_OR_SCRIPT_PATH_RE = /(?:^|[\\/])(?:tests?|__tests__|spec|__spec__|fixtures?|mocks?|__mocks__|e2e|integration|cypress|playwright|scratch|benchmarks?|seeds?|seeders?|migrations?|knex_migrations|scripts?|tools?|bin|samples?|playgrounds?|docs_src|caddytest|types|extra[\\/](?:release|push-examples))[\\/]/i;
|
|
7680
9226
|
var TEST_FILE_RE = /(?:\.(?:test|spec|mock|fixture|e2e|cy)\.|(?:^|[\\/])(?:test[_-][\w.-]+|[\w.-]+[_-](?:test|spec))\.)/i;
|
|
7681
|
-
var
|
|
9227
|
+
var FRONTEND_PATH_RE2 = /(?:^|[\\/])(?:public|frontend|client|admin_views|extension|src[\\/](?:components|pages|views|hooks|store|assets))[\\/]/i;
|
|
7682
9228
|
function isTestOrScriptPath(filePath) {
|
|
7683
9229
|
return TEST_OR_SCRIPT_PATH_RE.test(filePath) || TEST_FILE_RE.test(filePath);
|
|
7684
9230
|
}
|
|
7685
9231
|
function isFrontendPath(filePath) {
|
|
7686
|
-
return
|
|
9232
|
+
return FRONTEND_PATH_RE2.test(filePath);
|
|
7687
9233
|
}
|
|
7688
9234
|
function isCommentLine(lineContent) {
|
|
7689
9235
|
const trimmed = lineContent.trimStart();
|
|
@@ -7805,8 +9351,94 @@ function getEnclosingScopeInfo(lines, lineNumber, lookback = 35) {
|
|
|
7805
9351
|
// src/scanners/ops/analyzers/oom-memory.ts
|
|
7806
9352
|
var PAGINATION_OR_BOUND_RE = /\b(?:limit|take|skip|offset|paginate|simplePaginate|cursorPaginate|pageable|PageRequest|pageSize|perPage|per_page|chunk|chunkById|batch|batchSize|FindInBatches|find_each|in_batches|yield_per|stream|setMaxResults|Paginator|paginate_queryset|findOne|findUnique|findFirst|findById|FirstOrDefault|SingleOrDefault|fetchone|aggregate|ROWNUM)\b|\bcursor\s*:|\.(?:cursor|first|lazy|iterator|count|exists|delete|update)\s*\(|\bFETCH\s+(?:FIRST|NEXT)\b|\bTOP\s+\d+\b|\[[^\]]*:[^\]]*\]/i;
|
|
7807
9353
|
var SINGLE_RECORD_SQL_WHERE_RE = /\bWHERE\b[\s\S]{0,120}?\b(?:[a-zA-Z_]\w*\.)?(?:id|uuid|guid|slug|email|username|user_id|code|token|key|_id)\b\s*=\s*/i;
|
|
7808
|
-
var SQL_AGGREGATE_RE = /\bSELECT\s+(?:DISTINCT\s+)?(?:COUNT|SUM|AVG|MIN|MAX)\s*\(/i;
|
|
7809
|
-
var
|
|
9354
|
+
var SQL_AGGREGATE_RE = /\bSELECT\s+(?:DISTINCT\s+)?(?:COUNT|SUM|AVG|MIN|MAX)\s*\(|\b(?:COUNT|SUM|AVG|MIN|MAX)\s*\([^)]*\)[\s\S]{0,1200}?\bGROUP\s+BY\b/i;
|
|
9355
|
+
var SQL_EXISTS_CHECK_RE = /\bSELECT\s+1\s+FROM\b[\s\S]{0,200}?\bWHERE\b[\s\S]{0,120}?=/i;
|
|
9356
|
+
var SQL_LIMIT_RE = /\b(?:LIMIT|ROWNUM)\b|\bFETCH\s+(?:FIRST|NEXT)\b|\bTOP\s+\d+\b/i;
|
|
9357
|
+
var SQL_SYSTEM_CATALOG_RE = /\b(?:USER_SDO_GEOM_METADATA|information_schema|pg_catalog|pg_tables|pg_class|pg_namespace|sqlite_master|geometry_columns|spatial_ref_sys|sys\.tables|ALL_TABLES|USER_TABLES)\b/i;
|
|
9358
|
+
var BOUNDED_USER_SCOPED_MODELS_RE = /\.(?:teamUser|backupCode|twoFactor(?:BackupCode)?|session|passkey|apiKey|device|role|permission|preference|setting)\.(?:findMany|findAll)\s*\(/i;
|
|
9359
|
+
function extractSqlBody(stmtWin) {
|
|
9360
|
+
for (let i = 0; i < stmtWin.length; i++) {
|
|
9361
|
+
const ch = stmtWin[i];
|
|
9362
|
+
if (ch !== "`" && ch !== '"' && ch !== "'") continue;
|
|
9363
|
+
const isTriple = (ch === '"' || ch === "'") && stmtWin.slice(i, i + 3) === ch.repeat(3);
|
|
9364
|
+
const delim = isTriple ? ch.repeat(3) : ch;
|
|
9365
|
+
let j = i + delim.length;
|
|
9366
|
+
while (j < stmtWin.length) {
|
|
9367
|
+
if (stmtWin[j] === "\\" && j + 1 < stmtWin.length) {
|
|
9368
|
+
j += 2;
|
|
9369
|
+
continue;
|
|
9370
|
+
}
|
|
9371
|
+
if (isTriple ? stmtWin.startsWith(delim, j) : stmtWin[j] === ch) {
|
|
9372
|
+
const body = stmtWin.slice(i + delim.length, j);
|
|
9373
|
+
if (/^\s*SELECT\b/i.test(body)) return body;
|
|
9374
|
+
i = j + delim.length - 1;
|
|
9375
|
+
break;
|
|
9376
|
+
}
|
|
9377
|
+
j++;
|
|
9378
|
+
}
|
|
9379
|
+
if (j >= stmtWin.length) {
|
|
9380
|
+
const body = stmtWin.slice(i + delim.length);
|
|
9381
|
+
if (/^\s*SELECT\b/i.test(body)) return body;
|
|
9382
|
+
break;
|
|
9383
|
+
}
|
|
9384
|
+
}
|
|
9385
|
+
return stmtWin;
|
|
9386
|
+
}
|
|
9387
|
+
function stripSubqueries(sql) {
|
|
9388
|
+
let out = "";
|
|
9389
|
+
let i = 0;
|
|
9390
|
+
while (i < sql.length) {
|
|
9391
|
+
const ch = sql[i];
|
|
9392
|
+
if (ch === "'") {
|
|
9393
|
+
out += ch;
|
|
9394
|
+
i++;
|
|
9395
|
+
while (i < sql.length) {
|
|
9396
|
+
out += sql[i];
|
|
9397
|
+
if (sql[i] === "\\" && i + 1 < sql.length) {
|
|
9398
|
+
i++;
|
|
9399
|
+
out += sql[i];
|
|
9400
|
+
i++;
|
|
9401
|
+
continue;
|
|
9402
|
+
}
|
|
9403
|
+
if (sql[i] === "'") {
|
|
9404
|
+
i++;
|
|
9405
|
+
break;
|
|
9406
|
+
}
|
|
9407
|
+
i++;
|
|
9408
|
+
}
|
|
9409
|
+
continue;
|
|
9410
|
+
}
|
|
9411
|
+
if (ch === "(" && /^\s*SELECT\b/i.test(sql.slice(i + 1, i + 32))) {
|
|
9412
|
+
let depth = 1;
|
|
9413
|
+
i++;
|
|
9414
|
+
while (i < sql.length && depth > 0) {
|
|
9415
|
+
if (sql[i] === "'") {
|
|
9416
|
+
i++;
|
|
9417
|
+
while (i < sql.length) {
|
|
9418
|
+
if (sql[i] === "\\" && i + 1 < sql.length) {
|
|
9419
|
+
i += 2;
|
|
9420
|
+
continue;
|
|
9421
|
+
}
|
|
9422
|
+
if (sql[i] === "'") {
|
|
9423
|
+
i++;
|
|
9424
|
+
break;
|
|
9425
|
+
}
|
|
9426
|
+
i++;
|
|
9427
|
+
}
|
|
9428
|
+
continue;
|
|
9429
|
+
}
|
|
9430
|
+
if (sql[i] === "(") depth++;
|
|
9431
|
+
else if (sql[i] === ")") depth--;
|
|
9432
|
+
i++;
|
|
9433
|
+
}
|
|
9434
|
+
out += "()";
|
|
9435
|
+
continue;
|
|
9436
|
+
}
|
|
9437
|
+
out += ch;
|
|
9438
|
+
i++;
|
|
9439
|
+
}
|
|
9440
|
+
return out;
|
|
9441
|
+
}
|
|
7810
9442
|
var NON_MODEL_PHP_FACADES = /* @__PURE__ */ new Set([
|
|
7811
9443
|
"Request",
|
|
7812
9444
|
"Input",
|
|
@@ -7856,8 +9488,8 @@ var NON_MODEL_PHP_FACADES = /* @__PURE__ */ new Set([
|
|
|
7856
9488
|
"Throwable"
|
|
7857
9489
|
]);
|
|
7858
9490
|
var EVICTION_OR_CAP_RE = /\b(?:delete|clear|shift|splice|pop|slice|LRU|LRUCache|TTLCache|WeakMap|WeakSet|evict|expire|ttl|maxSize|max_size|maxsize|MAX_|Caffeine|CacheBuilder|OrderedDict|maxsize)\b/;
|
|
7859
|
-
var CLIENT_LIMIT_SOURCE_RE = /\b(?:req\.query\.(?:limit|pageSize|perPage|per_page|take|size|count)|request\.args\.get\s*\(\s*['"](?:limit|page_size|per_page|size)['"]|request\.GET\.get\s*\(\s*['"](?:limit|page_size|per_page|size)['"]|\$request->(?:input|query)\s*\(\s*['"](?:limit|per_page|page_size|size)['"]|@RequestParam[^)]*\b(?:size|limit|pageSize)\b)/;
|
|
7860
|
-
var CLAMP_GUARD_RE = /\b(?:Math\.min|min\s*\(|clamp|MAX_LIMIT|MAX_PAGE|MAX_SIZE|\.max\s*\(|@Max|<=|>\s*(?:100|200|500|1000|MAX_))\b/i;
|
|
9491
|
+
var CLIENT_LIMIT_SOURCE_RE = /\b(?:req\.query\.(?:limit|pageSize|perPage|per_page|take|size|count)|(?:searchParams|url\.searchParams)\.get\s*\(\s*['"](?:limit|pageSize|page_size|perPage|per_page|take|size|count)['"]\s*\)|Query\s*\([^)]*\)|request\.args\.get\s*\(\s*['"](?:limit|page_size|per_page|size)['"]|request\.GET\.get\s*\(\s*['"](?:limit|page_size|per_page|size)['"]|\$request->(?:input|query)\s*\(\s*['"](?:limit|per_page|page_size|size)['"]|@RequestParam[^)]*\b(?:size|limit|pageSize)\b)/;
|
|
9492
|
+
var CLAMP_GUARD_RE = /\b(?:Math\.min|min\s*\(|clamp|MAX_LIMIT|MAX_PAGE|MAX_SIZE|\.max\s*\(|@Max|<=|>\s*(?:100|200|500|1000|MAX_)|le\s*=\s*\d+|lt\s*=\s*\d+)\b/i;
|
|
7861
9493
|
function analyzeOomMemory(context) {
|
|
7862
9494
|
const findings = [];
|
|
7863
9495
|
const { content, filePath, language } = context;
|
|
@@ -7875,7 +9507,7 @@ function analyzeOomMemory(context) {
|
|
|
7875
9507
|
createFinding({
|
|
7876
9508
|
ruleId: opts.ruleId,
|
|
7877
9509
|
scanner: "ops",
|
|
7878
|
-
severity: "high",
|
|
9510
|
+
severity: opts.severity ?? "high",
|
|
7879
9511
|
confidence: opts.confidence ?? "high",
|
|
7880
9512
|
category: "oom-memory",
|
|
7881
9513
|
subcategory: opts.subcategory,
|
|
@@ -7906,6 +9538,9 @@ function analyzeOomMemory(context) {
|
|
|
7906
9538
|
if (shouldSkipMatch(context, m.line, m.column, m.lineContent)) continue;
|
|
7907
9539
|
const stmtWin = getStatementWindow(lines, m.line, 12);
|
|
7908
9540
|
if (PAGINATION_OR_BOUND_RE.test(stmtWin)) continue;
|
|
9541
|
+
if (BOUNDED_USER_SCOPED_MODELS_RE.test(m.lineContent) && /\bwhere\s*:[\s\S]{0,120}?\b(?:userId|user_id|teamId|team_id)\b/.test(stmtWin)) {
|
|
9542
|
+
continue;
|
|
9543
|
+
}
|
|
7909
9544
|
pushFinding({
|
|
7910
9545
|
ruleId: "OPS-OOM-001",
|
|
7911
9546
|
line: m.line,
|
|
@@ -7924,7 +9559,7 @@ function analyzeOomMemory(context) {
|
|
|
7924
9559
|
for (const m of mongoMatches) {
|
|
7925
9560
|
if (shouldSkipMatch(context, m.line, m.column, m.lineContent)) continue;
|
|
7926
9561
|
const afterOpen = m.lineContent.slice(m.column - 1 + m.match.length).trimStart();
|
|
7927
|
-
if (/^(?:function\b|\(?[a-zA-Z_$][\w$]*\)?\s*=>|[a-zA-Z_$][\w$]*\s*\))/.test(afterOpen)) {
|
|
9562
|
+
if (/^(?:function\b|\(\s*[\{\[]|\(?[a-zA-Z_$][\w$]*\)?\s*=>|[a-zA-Z_$][\w$]*\s*\))/.test(afterOpen)) {
|
|
7928
9563
|
continue;
|
|
7929
9564
|
}
|
|
7930
9565
|
const stmtWin = getStatementWindow(lines, m.line, 10);
|
|
@@ -7940,15 +9575,36 @@ function analyzeOomMemory(context) {
|
|
|
7940
9575
|
fixDescription: "Chain .limit(pageSize).skip(offset), use cursor-based pagination, or stream via .cursor()."
|
|
7941
9576
|
});
|
|
7942
9577
|
}
|
|
9578
|
+
const supabaseMatches = matchPattern(content, /\.from\s*\(\s*['"][^'"]+['"]\s*\)/g);
|
|
9579
|
+
for (const m of supabaseMatches) {
|
|
9580
|
+
if (shouldSkipMatch(context, m.line, m.column, m.lineContent)) continue;
|
|
9581
|
+
const stmtWin = getStatementWindow(lines, m.line, 8);
|
|
9582
|
+
if (!/\.select\s*\(/.test(stmtWin)) continue;
|
|
9583
|
+
if (/\.(?:range|limit|single|maybeSingle|csv)\s*\(/.test(stmtWin) || /\bhead\s*:\s*true\b/.test(stmtWin) || /\.eq\s*\(\s*['"](?:id|uuid|guid|slug|email|user_id|_id)['"]/.test(stmtWin)) {
|
|
9584
|
+
continue;
|
|
9585
|
+
}
|
|
9586
|
+
pushFinding({
|
|
9587
|
+
ruleId: "OPS-OOM-001",
|
|
9588
|
+
line: m.line,
|
|
9589
|
+
column: m.column,
|
|
9590
|
+
subcategory: "unbounded-query",
|
|
9591
|
+
title: "Unbounded Supabase Query Without Range or Limit",
|
|
9592
|
+
message: "Supabase .from().select() executes without .range(), .limit(), or .single(), which can load all matching rows into memory.",
|
|
9593
|
+
cwe: ["CWE-400", "CWE-770"],
|
|
9594
|
+
fixDescription: "Chain .range(offset, offset + pageSize - 1) or .limit(pageSize), or use { head: true } for count-only queries."
|
|
9595
|
+
});
|
|
9596
|
+
}
|
|
7943
9597
|
}
|
|
7944
9598
|
const rawSqlMatches = matchPattern(
|
|
7945
9599
|
content,
|
|
7946
|
-
/(?:query|execute|select|
|
|
9600
|
+
/(?:\b(?:query|execute|select|Query|createQuery|createNativeQuery)|DB\s*::\s*select)\s*(?:<[^>\n]+>\s*)?\(/gi
|
|
7947
9601
|
);
|
|
7948
9602
|
for (const m of rawSqlMatches) {
|
|
7949
9603
|
if (shouldSkipMatch(context, m.line, m.column, m.lineContent)) continue;
|
|
7950
|
-
const stmtWin =
|
|
7951
|
-
if (
|
|
9604
|
+
const stmtWin = getParenCallWindow(lines, m.line, 50);
|
|
9605
|
+
if (!/[`"'][\s\n]*SELECT\b[\s\S]{1,3000}?\bFROM\b/i.test(stmtWin)) continue;
|
|
9606
|
+
const outerSql = stripSubqueries(extractSqlBody(stmtWin));
|
|
9607
|
+
if (SQL_LIMIT_RE.test(outerSql) || SQL_AGGREGATE_RE.test(outerSql) || SQL_EXISTS_CHECK_RE.test(outerSql) || SQL_SYSTEM_CATALOG_RE.test(outerSql) || /\bFROM\s*\(\s*\$\{[^}]+\}\s*\)/i.test(outerSql) || SINGLE_RECORD_SQL_WHERE_RE.test(outerSql) || /\b(?:paginate|simplePaginate|cursorPaginate|FindInBatches|yield_per|setMaxResults)\b/i.test(stmtWin)) {
|
|
7952
9608
|
continue;
|
|
7953
9609
|
}
|
|
7954
9610
|
pushFinding({
|
|
@@ -7957,7 +9613,7 @@ function analyzeOomMemory(context) {
|
|
|
7957
9613
|
column: m.column,
|
|
7958
9614
|
subcategory: "unbounded-query",
|
|
7959
9615
|
title: "Unbounded SQL SELECT Without LIMIT",
|
|
7960
|
-
message: "SQL SELECT query executes without LIMIT
|
|
9616
|
+
message: "SQL SELECT query executes without LIMIT or a unique-key WHERE filter; loading an entire table into memory can cause an OOM kill.",
|
|
7961
9617
|
cwe: ["CWE-400", "CWE-770"],
|
|
7962
9618
|
fixDescription: "Add LIMIT/OFFSET (or keyset pagination) to the SQL query or stream rows using a database cursor."
|
|
7963
9619
|
});
|
|
@@ -8298,13 +9954,13 @@ function analyzeOomMemory(context) {
|
|
|
8298
9954
|
}
|
|
8299
9955
|
const clientLimitAssignments = matchPattern(
|
|
8300
9956
|
content,
|
|
8301
|
-
/\b(?:const|let|var)?\s*(\$?[a-zA-Z_]\w*)\s
|
|
9957
|
+
/\b(?:const|let|var)?\s*(\$?[a-zA-Z_]\w*)\s*(?::\s*[a-zA-Z_[\]]+\s*)?=\s*[^\n]*(?:req\.query\.(?:limit|pageSize|perPage|per_page|take|size|count)|(?:searchParams|url\.searchParams)\.get\s*\(\s*['"](?:limit|pageSize|page_size|perPage|per_page|take|size|count)['"]\s*\)|Query\s*\([^)]*\)|request\.args\.get\s*\(\s*['"](?:limit|page_size|per_page|size)['"]|request\.GET\.get\s*\(\s*['"](?:limit|page_size|per_page|size)['"]|\$request->(?:input|query)\s*\(\s*['"](?:limit|per_page|page_size|size)['"])/g
|
|
8302
9958
|
);
|
|
8303
9959
|
const clampedVars = /* @__PURE__ */ new Set();
|
|
8304
9960
|
const rawLimitVars = /* @__PURE__ */ new Map();
|
|
8305
9961
|
for (const m of clientLimitAssignments) {
|
|
8306
9962
|
if (shouldSkipMatch(context, m.line, m.column, m.lineContent)) continue;
|
|
8307
|
-
const varMatch = m.match.match(/(?:const|let|var)?\s*(\$?[a-zA-Z_]\w*)\s
|
|
9963
|
+
const varMatch = m.match.match(/(?:const|let|var)?\s*(\$?[a-zA-Z_]\w*)\s*(?::\s*[a-zA-Z_[\]]+\s*)?=/);
|
|
8308
9964
|
if (!varMatch) continue;
|
|
8309
9965
|
const varName = varMatch[1];
|
|
8310
9966
|
const windowAfter = getForwardWindow(lines, m.line, 10);
|
|
@@ -8316,15 +9972,17 @@ function analyzeOomMemory(context) {
|
|
|
8316
9972
|
}
|
|
8317
9973
|
const paginationUsageMatches = matchPattern(
|
|
8318
9974
|
content,
|
|
8319
|
-
/(?:\.(?:limit|take|paginate|setMaxResults)\s*\(|PageRequest\.of\s*\([^,]+,|\b(?:limit|take)\s*:\s*|\bLIMIT\s+(?:\$\{
|
|
9975
|
+
/(?:\.(?:limit|take|paginate|setMaxResults)\s*\(|PageRequest\.of\s*\([^,]+,|\b(?:limit|take)\s*:\s*|\bLIMIT\s+(?:\$\{\s*[^}]+\}|\$\d+|\$|%s|\?))/gi
|
|
8320
9976
|
);
|
|
8321
9977
|
for (const m of paginationUsageMatches) {
|
|
8322
9978
|
if (shouldSkipMatch(context, m.line, m.column, m.lineContent)) continue;
|
|
8323
9979
|
const lineWin = m.lineContent;
|
|
8324
|
-
|
|
9980
|
+
const isSqlParamLimit = /^\s*LIMIT\b/i.test(m.match);
|
|
9981
|
+
const usageWin = isSqlParamLimit ? getStatementWindow(lines, m.line, 5) : lineWin;
|
|
9982
|
+
if (CLAMP_GUARD_RE.test(usageWin) || CLAMP_GUARD_RE.test(getPrecedingWindow(lines, m.line, 8))) {
|
|
8325
9983
|
continue;
|
|
8326
9984
|
}
|
|
8327
|
-
if (CLIENT_LIMIT_SOURCE_RE.test(
|
|
9985
|
+
if (CLIENT_LIMIT_SOURCE_RE.test(usageWin)) {
|
|
8328
9986
|
pushFinding({
|
|
8329
9987
|
ruleId: "OPS-OOM-003",
|
|
8330
9988
|
line: m.line,
|
|
@@ -8342,7 +10000,7 @@ function analyzeOomMemory(context) {
|
|
|
8342
10000
|
if (m.line >= assignLine && m.line - assignLine <= 15) {
|
|
8343
10001
|
const escapedVar = varName.replace(/\$/g, "\\$");
|
|
8344
10002
|
const varUseRe = new RegExp(`(?:^|[^\\w$])${escapedVar}(?:$|[^\\w$])`);
|
|
8345
|
-
const rhs =
|
|
10003
|
+
const rhs = usageWin.slice(Math.max(0, m.column - 1));
|
|
8346
10004
|
if (varUseRe.test(rhs)) {
|
|
8347
10005
|
pushFinding({
|
|
8348
10006
|
ruleId: "OPS-OOM-003",
|
|
@@ -8359,6 +10017,62 @@ function analyzeOomMemory(context) {
|
|
|
8359
10017
|
}
|
|
8360
10018
|
}
|
|
8361
10019
|
}
|
|
10020
|
+
const BATCH_CONTEXT_RE = /\b(?:batch|chunk|export|stream|cursor|migrate|backfill|FindInBatches|yield_per|in_batches|find_each|bulk|batchSize)\b/i;
|
|
10021
|
+
const hardcodedSqlLimitMatches = matchPattern(content, /\bLIMIT\s+(\d{3,})\b/gi);
|
|
10022
|
+
for (const m of hardcodedSqlLimitMatches) {
|
|
10023
|
+
if (shouldSkipMatch(context, m.line, m.column, m.lineContent)) continue;
|
|
10024
|
+
const numMatch = m.match.match(/(\d+)/);
|
|
10025
|
+
if (!numMatch) continue;
|
|
10026
|
+
const limitVal = parseInt(numMatch[1], 10);
|
|
10027
|
+
if (limitVal < 500) continue;
|
|
10028
|
+
const preWin = getPrecedingWindow(lines, m.line, 8);
|
|
10029
|
+
const stmtWin = `${preWin}
|
|
10030
|
+
${m.lineContent}
|
|
10031
|
+
${getForwardWindow(lines, m.line, 3)}`;
|
|
10032
|
+
if (BATCH_CONTEXT_RE.test(stmtWin)) continue;
|
|
10033
|
+
const hasSelectStar = /\bSELECT\s+\*(?:\s|,|$)/i.test(preWin + "\n" + m.lineContent);
|
|
10034
|
+
const hasOffsetOrCursor = /\bOFFSET\b/i.test(m.lineContent + "\n" + getForwardWindow(lines, m.line, 2)) || /\bcursor\b/i.test(stmtWin);
|
|
10035
|
+
if (limitVal < 1e3 && (!hasSelectStar || hasOffsetOrCursor)) continue;
|
|
10036
|
+
pushFinding({
|
|
10037
|
+
ruleId: "OPS-OOM-005",
|
|
10038
|
+
line: m.line,
|
|
10039
|
+
column: m.column,
|
|
10040
|
+
severity: "medium",
|
|
10041
|
+
confidence: "medium",
|
|
10042
|
+
subcategory: "excessive-query-limit",
|
|
10043
|
+
title: "Excessive Hardcoded Query Limit",
|
|
10044
|
+
message: `Query uses a large hardcoded LIMIT ${limitVal} without pagination/streaming, risking oversized JSON payloads, memory spikes, or silent truncation.`,
|
|
10045
|
+
cwe: ["CWE-400", "CWE-770"],
|
|
10046
|
+
fixDescription: "Replace large load-all limits with server-side pagination (e.g., LIMIT 25..100 with OFFSET or keyset cursor) or stream results in smaller batches."
|
|
10047
|
+
});
|
|
10048
|
+
}
|
|
10049
|
+
const hardcodedOrmLimitMatches = matchPattern(
|
|
10050
|
+
content,
|
|
10051
|
+
/(?:\.(?:limit|take|setMaxResults|Take)\s*\(\s*(\d{4,})\s*\)|\b(?:limit|take)\s*:\s*(\d{4,})\b)/g
|
|
10052
|
+
);
|
|
10053
|
+
for (const m of hardcodedOrmLimitMatches) {
|
|
10054
|
+
if (shouldSkipMatch(context, m.line, m.column, m.lineContent)) continue;
|
|
10055
|
+
const numMatch = m.match.match(/(\d{4,})/);
|
|
10056
|
+
if (!numMatch) continue;
|
|
10057
|
+
const limitVal = parseInt(numMatch[1], 10);
|
|
10058
|
+
if (limitVal < 1e3) continue;
|
|
10059
|
+
const contextWin = `${getPrecedingWindow(lines, m.line, 5)}
|
|
10060
|
+
${m.lineContent}
|
|
10061
|
+
${getForwardWindow(lines, m.line, 3)}`;
|
|
10062
|
+
if (BATCH_CONTEXT_RE.test(contextWin)) continue;
|
|
10063
|
+
pushFinding({
|
|
10064
|
+
ruleId: "OPS-OOM-005",
|
|
10065
|
+
line: m.line,
|
|
10066
|
+
column: m.column,
|
|
10067
|
+
severity: "medium",
|
|
10068
|
+
confidence: "medium",
|
|
10069
|
+
subcategory: "excessive-query-limit",
|
|
10070
|
+
title: "Excessive Hardcoded Query Limit",
|
|
10071
|
+
message: `ORM query uses a large hardcoded page/batch limit (${limitVal}), risking memory spikes, slow responses, and truncated UI datasets.`,
|
|
10072
|
+
cwe: ["CWE-400", "CWE-770"],
|
|
10073
|
+
fixDescription: "Use smaller paginated pages (e.g., 25-100 rows per request) or stream records in bounded batches."
|
|
10074
|
+
});
|
|
10075
|
+
}
|
|
8362
10076
|
if (!EVICTION_OR_CAP_RE.test(content)) {
|
|
8363
10077
|
const cacheDeclMatches = matchPattern(
|
|
8364
10078
|
content,
|
|
@@ -8845,10 +10559,22 @@ function analyzeResourceLeaks(context) {
|
|
|
8845
10559
|
|
|
8846
10560
|
// src/scanners/ops/analyzers/performance-ops.ts
|
|
8847
10561
|
var LOOP_START_RE = /^\s*(?:for\s*\(|for\s+(?:const|let|var|await)?\b.*\bof\b|for\s+[a-zA-Z_][\w,\s]*\bin\b|foreach\s*\(|while\s*\(|while\s+.*:|[\w$.]+\.forEach\s*\(\s*(?:async\b|\())/;
|
|
8848
|
-
var BATCH_LOOP_RE = /\b(?:chunk|batch|page|offset|cursor)\b|\+\=\s*(?:batch|chunk|size|limit|MAX|[2-9]\d)/i;
|
|
8849
|
-
var N_PLUS_ONE_CALL_RE = /(?:await\s+[\w$.]*\.(?:findUnique|findFirst|findOne|findById|findAll|findMany|find|query|execute)\s*\(|\bDB::select\s*\(
|
|
10562
|
+
var BATCH_LOOP_RE = /\b(?:chunk|batch|page|offset|cursor|attempt|retries|retry|maxRetries|maxAttempts)\b|\+\=\s*(?:batch|chunk|size|limit|MAX|[2-9]\d)/i;
|
|
10563
|
+
var N_PLUS_ONE_CALL_RE = /(?:await\s+[\w$.]*\.(?:findUnique|findFirst|findOne|findById|findAll|findMany|find|query|execute)\s*\(|\bDB::select\s*\(|\b[A-Z][a-zA-Z0-9_]*::find\s*\(|\.objects\.(?:get|filter)\s*\(|session\.query\s*\(|\w+Repository\.findBy\w*\s*\(|await\s+(?:fetch|axios\.(?:get|post|put|delete))\s*\(|\brequests\.(?:get|post)\s*\()/;
|
|
8850
10564
|
var CONCURRENCY_LIMITER_RE = /\b(?:pLimit|p-limit|pMap|p-map|bottleneck|semaphore|chunk|batch)\b|\.slice\s*\(\s*0\s*,/i;
|
|
8851
10565
|
var PROMISE_ALL_IO_RE = /\b(?:fetch|axios|query|find|create|update|delete|save|insert|send|readFile|writeFile|http|request|upload|download)\b/i;
|
|
10566
|
+
var DELIMITER_PREFIX_RE = /^(?:\[[^\]]*(?:[_.,:/\\]|(?<![a-zA-Z0-9])-(?![a-zA-Z0-9]))[^\]]*\]|\\[.,:/\\-]|[_.,:/\\-])(?![?*])/;
|
|
10567
|
+
function hasCatastrophicNestedQuantifier(regexBody) {
|
|
10568
|
+
if (regexBody.includes("</")) return false;
|
|
10569
|
+
const nestedRe = /\((?:\?:)?([^()\\]*[+*][^()\\]*)\)[+*]/g;
|
|
10570
|
+
let match;
|
|
10571
|
+
while ((match = nestedRe.exec(regexBody)) !== null) {
|
|
10572
|
+
const inner = match[1];
|
|
10573
|
+
if (DELIMITER_PREFIX_RE.test(inner)) continue;
|
|
10574
|
+
return true;
|
|
10575
|
+
}
|
|
10576
|
+
return false;
|
|
10577
|
+
}
|
|
8852
10578
|
function analyzeOpsPerformance(context) {
|
|
8853
10579
|
const findings = [];
|
|
8854
10580
|
const { content, filePath, language } = context;
|
|
@@ -8881,59 +10607,62 @@ function analyzeOpsPerformance(context) {
|
|
|
8881
10607
|
})
|
|
8882
10608
|
);
|
|
8883
10609
|
};
|
|
8884
|
-
|
|
8885
|
-
|
|
8886
|
-
|
|
8887
|
-
|
|
8888
|
-
|
|
8889
|
-
|
|
8890
|
-
|
|
8891
|
-
|
|
8892
|
-
|
|
8893
|
-
const
|
|
8894
|
-
|
|
8895
|
-
const
|
|
8896
|
-
|
|
8897
|
-
|
|
8898
|
-
|
|
8899
|
-
|
|
8900
|
-
|
|
8901
|
-
|
|
8902
|
-
|
|
8903
|
-
|
|
8904
|
-
|
|
8905
|
-
|
|
8906
|
-
for (let
|
|
8907
|
-
|
|
8908
|
-
|
|
8909
|
-
|
|
8910
|
-
|
|
8911
|
-
|
|
10610
|
+
if (language !== "c" && language !== "cpp" && language !== "rust") {
|
|
10611
|
+
const flaggedNPlusOneLines = /* @__PURE__ */ new Set();
|
|
10612
|
+
for (let i = 0; i < lines.length; i++) {
|
|
10613
|
+
const lineContent = lines[i];
|
|
10614
|
+
const lineNum = i + 1;
|
|
10615
|
+
if (!LOOP_START_RE.test(lineContent)) continue;
|
|
10616
|
+
if (shouldSkipMatch(context, lineNum, 1, lineContent)) continue;
|
|
10617
|
+
if (BATCH_LOOP_RE.test(lineContent)) continue;
|
|
10618
|
+
if (i > 0 && /\b(?:retries|retry|maxRetries|maxAttempts|backoff)\b/i.test(lines[i - 1])) continue;
|
|
10619
|
+
const bodyLines = [];
|
|
10620
|
+
if (language === "python") {
|
|
10621
|
+
const baseIndent = lineContent.length - lineContent.trimStart().length;
|
|
10622
|
+
for (let j = i + 1; j < Math.min(lines.length, i + 30); j++) {
|
|
10623
|
+
const nextLine = lines[j];
|
|
10624
|
+
if (nextLine.trim().length === 0) continue;
|
|
10625
|
+
const nextIndent = nextLine.length - nextLine.trimStart().length;
|
|
10626
|
+
if (nextIndent <= baseIndent) break;
|
|
10627
|
+
bodyLines.push({ lineNum: j + 1, text: nextLine });
|
|
10628
|
+
}
|
|
10629
|
+
} else {
|
|
10630
|
+
let depth = 0;
|
|
10631
|
+
let opened = false;
|
|
10632
|
+
for (let j = i; j < Math.min(lines.length, i + 30); j++) {
|
|
10633
|
+
const cur = lines[j];
|
|
10634
|
+
for (let c = 0; c < cur.length; c++) {
|
|
10635
|
+
if (cur[c] === "{") {
|
|
10636
|
+
depth++;
|
|
10637
|
+
opened = true;
|
|
10638
|
+
} else if (cur[c] === "}") {
|
|
10639
|
+
depth--;
|
|
10640
|
+
}
|
|
8912
10641
|
}
|
|
10642
|
+
if (j > i) bodyLines.push({ lineNum: j + 1, text: cur });
|
|
10643
|
+
if (opened && depth <= 0) break;
|
|
10644
|
+
if (!opened && j > i + 1) break;
|
|
8913
10645
|
}
|
|
8914
|
-
if (j > i) bodyLines.push({ lineNum: j + 1, text: cur });
|
|
8915
|
-
if (opened && depth <= 0) break;
|
|
8916
|
-
if (!opened && j > i + 1) break;
|
|
8917
10646
|
}
|
|
8918
|
-
|
|
8919
|
-
|
|
8920
|
-
|
|
8921
|
-
|
|
8922
|
-
|
|
8923
|
-
|
|
8924
|
-
|
|
8925
|
-
|
|
8926
|
-
|
|
8927
|
-
|
|
8928
|
-
|
|
8929
|
-
|
|
8930
|
-
|
|
8931
|
-
|
|
8932
|
-
|
|
8933
|
-
|
|
8934
|
-
|
|
8935
|
-
|
|
8936
|
-
}
|
|
10647
|
+
const bodyJoined = bodyLines.map((b) => b.text).join("\n");
|
|
10648
|
+
if (BATCH_LOOP_RE.test(bodyJoined)) continue;
|
|
10649
|
+
for (const entry of bodyLines) {
|
|
10650
|
+
if (flaggedNPlusOneLines.has(entry.lineNum)) continue;
|
|
10651
|
+
if (shouldSkipMatch(context, entry.lineNum, 1, entry.text)) continue;
|
|
10652
|
+
if (N_PLUS_ONE_CALL_RE.test(entry.text)) {
|
|
10653
|
+
flaggedNPlusOneLines.add(entry.lineNum);
|
|
10654
|
+
pushFinding({
|
|
10655
|
+
ruleId: "OPS-PERF-001",
|
|
10656
|
+
line: entry.lineNum,
|
|
10657
|
+
column: Math.max(1, entry.text.search(/\S/) + 1),
|
|
10658
|
+
severity: "high",
|
|
10659
|
+
subcategory: "n-plus-one-query",
|
|
10660
|
+
title: "N+1 Query or HTTP Call Inside Loop",
|
|
10661
|
+
message: "Database query or HTTP request executed inside a loop causes O(N) round trips, latency spikes, and connection pool saturation.",
|
|
10662
|
+
cwe: ["CWE-1050"],
|
|
10663
|
+
fixDescription: "Batch lookups outside the loop using WHERE id IN (...), JOINs, eager loading, or bulk API endpoints."
|
|
10664
|
+
});
|
|
10665
|
+
}
|
|
8937
10666
|
}
|
|
8938
10667
|
}
|
|
8939
10668
|
}
|
|
@@ -8985,25 +10714,371 @@ function analyzeOpsPerformance(context) {
|
|
|
8985
10714
|
}
|
|
8986
10715
|
}
|
|
8987
10716
|
}
|
|
8988
|
-
const
|
|
10717
|
+
const hasRegexLiterals = language === "javascript" || language === "typescript" || language === "ruby";
|
|
10718
|
+
const regexCtorRe = /(?:new\s+RegExp|re\.compile|Pattern\.compile|regexp\.MustCompile)\s*\(\s*r?(['"`])((?:\\.|(?!\1)[^\\\n])+)\1/g;
|
|
10719
|
+
for (let i = 0; i < lines.length; i++) {
|
|
10720
|
+
const lineContent = lines[i];
|
|
10721
|
+
const lineNum = i + 1;
|
|
10722
|
+
if (isCommentLine(lineContent)) continue;
|
|
10723
|
+
if (/^\s*(?:regex|pattern|message|description)\s*[:=]\s/.test(lineContent)) continue;
|
|
10724
|
+
let hitCol = null;
|
|
10725
|
+
if (hasRegexLiterals) {
|
|
10726
|
+
const ranges = findRegexLiteralRanges(lineContent);
|
|
10727
|
+
for (const [start, end] of ranges) {
|
|
10728
|
+
const body = lineContent.slice(start + 1, end);
|
|
10729
|
+
if (hasCatastrophicNestedQuantifier(body)) {
|
|
10730
|
+
hitCol = start + 1;
|
|
10731
|
+
break;
|
|
10732
|
+
}
|
|
10733
|
+
}
|
|
10734
|
+
}
|
|
10735
|
+
if (hitCol === null) {
|
|
10736
|
+
regexCtorRe.lastIndex = 0;
|
|
10737
|
+
let m;
|
|
10738
|
+
while ((m = regexCtorRe.exec(lineContent)) !== null) {
|
|
10739
|
+
if (hasCatastrophicNestedQuantifier(m[2])) {
|
|
10740
|
+
hitCol = m.index + 1;
|
|
10741
|
+
break;
|
|
10742
|
+
}
|
|
10743
|
+
}
|
|
10744
|
+
}
|
|
10745
|
+
if (hitCol !== null) {
|
|
10746
|
+
pushFinding({
|
|
10747
|
+
ruleId: "OPS-PERF-004",
|
|
10748
|
+
line: lineNum,
|
|
10749
|
+
column: hitCol,
|
|
10750
|
+
severity: "high",
|
|
10751
|
+
subcategory: "redos",
|
|
10752
|
+
title: "Catastrophic Backtracking Regex (ReDoS)",
|
|
10753
|
+
message: "Regular expression contains nested quantifiers (e.g., (a+)+) that can cause exponential backtracking and freeze worker threads on crafted input.",
|
|
10754
|
+
cwe: ["CWE-1333"],
|
|
10755
|
+
fixDescription: "Eliminate nested quantifiers, rewrite using non-overlapping character classes, or use a linear-time regex engine like RE2."
|
|
10756
|
+
});
|
|
10757
|
+
}
|
|
10758
|
+
}
|
|
10759
|
+
if (language !== "c" && language !== "cpp" && language !== "rust") {
|
|
10760
|
+
const rawSqlCalls = matchPattern(
|
|
10761
|
+
content,
|
|
10762
|
+
/(?:\b(?:query|execute|select|Query|createQuery|createNativeQuery)|DB\s*::\s*select)\s*(?:<[^>\n]+>\s*)?\(/gi
|
|
10763
|
+
);
|
|
10764
|
+
for (const m of rawSqlCalls) {
|
|
10765
|
+
if (shouldSkipMatch(context, m.line, m.column, m.lineContent)) continue;
|
|
10766
|
+
const stmtWin = getParenCallWindow(lines, m.line, 50);
|
|
10767
|
+
const correlatedMatches = stmtWin.match(
|
|
10768
|
+
/\(\s*SELECT\s+(?:COUNT|SUM|AVG|MIN|MAX)\s*\([^)]*\)[\s\S]{0,260}?\bFROM\b[\s\S]{0,260}?\bWHERE\b/gi
|
|
10769
|
+
);
|
|
10770
|
+
if (correlatedMatches && correlatedMatches.length >= 2) {
|
|
10771
|
+
pushFinding({
|
|
10772
|
+
ruleId: "OPS-PERF-005",
|
|
10773
|
+
line: m.line,
|
|
10774
|
+
column: m.column,
|
|
10775
|
+
severity: "medium",
|
|
10776
|
+
confidence: "medium",
|
|
10777
|
+
subcategory: "correlated-subquery",
|
|
10778
|
+
title: "Multiple Correlated SQL Subqueries (SQL N+1)",
|
|
10779
|
+
message: `SQL query executes ${correlatedMatches.length} inline correlated aggregate subqueries per row, causing O(N) repeated table/index scans as tables grow.`,
|
|
10780
|
+
cwe: ["CWE-1050"],
|
|
10781
|
+
fixDescription: "Replace inline correlated subqueries with pre-aggregated CTEs (WITH ... GROUP BY) joined via LEFT JOIN, or compute counts in a single grouped query."
|
|
10782
|
+
});
|
|
10783
|
+
}
|
|
10784
|
+
}
|
|
10785
|
+
}
|
|
10786
|
+
return findings;
|
|
10787
|
+
}
|
|
10788
|
+
|
|
10789
|
+
// src/scanners/ops/analyzers/db-ops.ts
|
|
10790
|
+
var EXTERNAL_IO_IN_TX_RE = /\b(?:fetch\s*\(|axios(?:\s*\.\s*(?:get|post|put|delete|patch|request))?\s*\(|requests\s*\.\s*(?:get|post|put|delete|patch|request)\s*\(|httpx\s*\.\s*(?:get|post|put|delete|patch|AsyncClient|Client)\b|urllib\.request\b|http\.(?:Get|Post|Do)\s*\(|(?:time\.)?[sS]leep\s*\(|Thread\.sleep\s*\(|usleep\s*\(|setTimeout\s*\(|sendMail\s*\(|generateContent\s*\(|(?:completions|messages|responses)\.create\s*\()/;
|
|
10791
|
+
var ROLLBACK_RE = /\bROLLBACK\b|\.\s*(?:rollback|rollBack|Rollback)\s*\(|->\s*rollBack\s*\(/i;
|
|
10792
|
+
var LOCK_TIMEOUT_GUARD_RE = /\b(?:NOWAIT|SKIP\s+LOCKED|lock_timeout|statement_timeout|innodb_lock_wait_timeout|SET\s+LOCAL\s+lock_timeout|LOCK_TIMEOUT)\b/i;
|
|
10793
|
+
var POOL_BOUND_OR_TIMEOUT_RE = /\b(?:max|maxPoolSize|connectionLimit|pool_size|max_size|max_overflow|MaxOpenConns|connectionTimeoutMillis|acquireTimeout(?:Millis)?|connectTimeout|idleTimeoutMillis|pool_timeout|statement_timeout|timeout)\b/i;
|
|
10794
|
+
function analyzeDbOps(context) {
|
|
10795
|
+
const findings = [];
|
|
10796
|
+
const { content, filePath, language } = context;
|
|
10797
|
+
if (content.length < 10 || isTestOrScriptPath(filePath) || isFrontendPath(filePath)) {
|
|
10798
|
+
return findings;
|
|
10799
|
+
}
|
|
10800
|
+
const lines = content.split("\n");
|
|
10801
|
+
const flaggedKeys = /* @__PURE__ */ new Set();
|
|
10802
|
+
const pushFinding = (opts) => {
|
|
10803
|
+
const key = `${opts.ruleId}:${opts.line}`;
|
|
10804
|
+
if (flaggedKeys.has(key)) return;
|
|
10805
|
+
flaggedKeys.add(key);
|
|
10806
|
+
findings.push(
|
|
10807
|
+
createFinding({
|
|
10808
|
+
ruleId: opts.ruleId,
|
|
10809
|
+
scanner: "ops",
|
|
10810
|
+
severity: opts.severity,
|
|
10811
|
+
confidence: opts.confidence ?? "high",
|
|
10812
|
+
category: "db-operations",
|
|
10813
|
+
subcategory: opts.subcategory,
|
|
10814
|
+
title: opts.title,
|
|
10815
|
+
message: opts.message,
|
|
10816
|
+
filePath,
|
|
10817
|
+
lineNumber: opts.line,
|
|
10818
|
+
column: opts.column,
|
|
10819
|
+
snippet: extractSnippet(content, opts.line),
|
|
10820
|
+
cwe: opts.cwe,
|
|
10821
|
+
owasp: ["A04:2021", "API4:2023"],
|
|
10822
|
+
fix: {
|
|
10823
|
+
description: opts.fixDescription,
|
|
10824
|
+
references: [
|
|
10825
|
+
"https://cwe.mitre.org/data/definitions/667.html",
|
|
10826
|
+
"https://cwe.mitre.org/data/definitions/404.html"
|
|
10827
|
+
]
|
|
10828
|
+
},
|
|
10829
|
+
tags: ["ops", "database", opts.subcategory]
|
|
10830
|
+
})
|
|
10831
|
+
);
|
|
10832
|
+
};
|
|
10833
|
+
const txCallbackMatches = matchPattern(
|
|
10834
|
+
content,
|
|
10835
|
+
/(?:\.\s*(?:\$?transaction|inTransaction)\s*\(|\bwith(?:[A-Z]\w*)?(?:Transaction|Db|UserContext|WorkspaceContext|SystemContext)\s*\()/g
|
|
10836
|
+
);
|
|
10837
|
+
for (const m of txCallbackMatches) {
|
|
10838
|
+
if (shouldSkipMatch(context, m.line, m.column, m.lineContent)) continue;
|
|
10839
|
+
const txWin = getParenCallWindow(lines, m.line, 60);
|
|
10840
|
+
if (!/(?:=>|\bfunction\b)/.test(txWin)) continue;
|
|
10841
|
+
if (EXTERNAL_IO_IN_TX_RE.test(txWin)) {
|
|
10842
|
+
pushFinding({
|
|
10843
|
+
ruleId: "OPS-DB-001",
|
|
10844
|
+
line: m.line,
|
|
10845
|
+
column: m.column,
|
|
10846
|
+
severity: "high",
|
|
10847
|
+
subcategory: "io-in-transaction",
|
|
10848
|
+
title: "External Network or Blocking I/O Inside DB Transaction",
|
|
10849
|
+
message: "Slow external HTTP requests or sleep calls execute inside an open database transaction, holding row locks and pinning a pool connection for the full network duration.",
|
|
10850
|
+
cwe: ["CWE-667", "CWE-400"],
|
|
10851
|
+
fixDescription: "Perform HTTP calls, webhooks, emails, and sleeps outside the database transaction (e.g., before starting the transaction or via an outbox/queue after COMMIT)."
|
|
10852
|
+
});
|
|
10853
|
+
}
|
|
10854
|
+
}
|
|
10855
|
+
if (language === "python") {
|
|
10856
|
+
const pyTxMatches = matchPattern(
|
|
10857
|
+
content,
|
|
10858
|
+
/\b(?:with|async\s+with)\s+[^\n]*(?:transaction\.atomic|session\.begin|conn\.begin)\s*\(/g
|
|
10859
|
+
);
|
|
10860
|
+
for (const m of pyTxMatches) {
|
|
10861
|
+
if (shouldSkipMatch(context, m.line, m.column, m.lineContent)) continue;
|
|
10862
|
+
const baseIndent = m.lineContent.search(/\S/);
|
|
10863
|
+
const bodyLines = [];
|
|
10864
|
+
for (let i = m.line; i < Math.min(lines.length, m.line + 50); i++) {
|
|
10865
|
+
const line = lines[i];
|
|
10866
|
+
if (line.trim() === "" || line.trim().startsWith("#")) {
|
|
10867
|
+
bodyLines.push(line);
|
|
10868
|
+
continue;
|
|
10869
|
+
}
|
|
10870
|
+
if (line.search(/\S/) <= baseIndent) break;
|
|
10871
|
+
bodyLines.push(line);
|
|
10872
|
+
}
|
|
10873
|
+
if (EXTERNAL_IO_IN_TX_RE.test(bodyLines.join("\n"))) {
|
|
10874
|
+
pushFinding({
|
|
10875
|
+
ruleId: "OPS-DB-001",
|
|
10876
|
+
line: m.line,
|
|
10877
|
+
column: m.column,
|
|
10878
|
+
severity: "high",
|
|
10879
|
+
subcategory: "io-in-transaction",
|
|
10880
|
+
title: "External Network or Blocking I/O Inside DB Transaction",
|
|
10881
|
+
message: "External network or sleep I/O occurs inside a database transaction block, prolonging lock contention and exhausting DB connections under load.",
|
|
10882
|
+
cwe: ["CWE-667", "CWE-400"],
|
|
10883
|
+
fixDescription: "Move HTTP requests and sleeps outside the transaction context manager (commit first, then trigger external side effects)."
|
|
10884
|
+
});
|
|
10885
|
+
}
|
|
10886
|
+
}
|
|
10887
|
+
}
|
|
10888
|
+
const manualBeginMatches = matchPattern(
|
|
10889
|
+
content,
|
|
10890
|
+
/(?:\.(?:query|execute|exec)\s*\(\s*[`"']\s*(?:BEGIN(?:\s+TRANSACTION)?|START\s+TRANSACTION)\s*[`"']|\.(?:beginTransaction|begin_transaction|BeginTx|Begin|startTransaction|StartTransaction)\s*\()/g
|
|
10891
|
+
);
|
|
10892
|
+
for (const m of manualBeginMatches) {
|
|
10893
|
+
if (shouldSkipMatch(context, m.line, m.column, m.lineContent)) continue;
|
|
10894
|
+
if (/^\s*(?:async\s+)?(?:with|using)\b/.test(m.lineContent)) continue;
|
|
10895
|
+
const rawForward = getForwardWindow(lines, m.line, 40);
|
|
10896
|
+
const commitIdx = rawForward.search(/\bCOMMIT\b|\.\s*(?:commit|Commit)\s*\(|->\s*commit\s*\(/i);
|
|
10897
|
+
const txSegment = commitIdx >= 0 ? rawForward.slice(0, commitIdx) : rawForward;
|
|
10898
|
+
if (EXTERNAL_IO_IN_TX_RE.test(txSegment)) {
|
|
10899
|
+
pushFinding({
|
|
10900
|
+
ruleId: "OPS-DB-001",
|
|
10901
|
+
line: m.line,
|
|
10902
|
+
column: m.column,
|
|
10903
|
+
severity: "high",
|
|
10904
|
+
subcategory: "io-in-transaction",
|
|
10905
|
+
title: "External Network or Blocking I/O Inside DB Transaction",
|
|
10906
|
+
message: "External HTTP request or sleep call runs between BEGIN and COMMIT, keeping database locks and connections pinned while waiting on remote I/O.",
|
|
10907
|
+
cwe: ["CWE-667", "CWE-400"],
|
|
10908
|
+
fixDescription: "Commit the database transaction before calling external APIs, or complete external fetches before issuing BEGIN."
|
|
10909
|
+
});
|
|
10910
|
+
}
|
|
10911
|
+
if (!ROLLBACK_RE.test(rawForward)) {
|
|
10912
|
+
pushFinding({
|
|
10913
|
+
ruleId: "OPS-DB-002",
|
|
10914
|
+
line: m.line,
|
|
10915
|
+
column: m.column,
|
|
10916
|
+
severity: "high",
|
|
10917
|
+
subcategory: "missing-rollback",
|
|
10918
|
+
title: "Manual DB Transaction Missing Rollback Handler",
|
|
10919
|
+
message: "Explicit database transaction starts without a corresponding ROLLBACK / rollback() error handler; an exception can leave the connection locked in an aborted or idle-in-transaction state.",
|
|
10920
|
+
cwe: ["CWE-404", "CWE-667"],
|
|
10921
|
+
fixDescription: "Wrap manual transactions in try/catch (or Go defer tx.Rollback()) and invoke ROLLBACK on error before releasing the connection, or use a callback/context-managed transaction helper."
|
|
10922
|
+
});
|
|
10923
|
+
}
|
|
10924
|
+
}
|
|
10925
|
+
const unmanagedOrmTxMatches = matchPattern(
|
|
10926
|
+
content,
|
|
10927
|
+
/\b(?:const|let|var)\s+[a-zA-Z_$][\w$]*\s*=\s*(?:await\s+)?[a-zA-Z_$][\w$.]*\.transaction\s*\(\s*\)/g
|
|
10928
|
+
);
|
|
10929
|
+
for (const m of unmanagedOrmTxMatches) {
|
|
10930
|
+
if (shouldSkipMatch(context, m.line, m.column, m.lineContent)) continue;
|
|
10931
|
+
const rawForward = getForwardWindow(lines, m.line, 40);
|
|
10932
|
+
if (!ROLLBACK_RE.test(rawForward)) {
|
|
10933
|
+
pushFinding({
|
|
10934
|
+
ruleId: "OPS-DB-002",
|
|
10935
|
+
line: m.line,
|
|
10936
|
+
column: m.column,
|
|
10937
|
+
severity: "high",
|
|
10938
|
+
subcategory: "missing-rollback",
|
|
10939
|
+
title: "Unmanaged ORM Transaction Missing Rollback Handler",
|
|
10940
|
+
message: "Unmanaged transaction handle created without a rollback() call in catch/error handling; failed requests can leak open transactions and hold locks.",
|
|
10941
|
+
cwe: ["CWE-404", "CWE-667"],
|
|
10942
|
+
fixDescription: "Call rollback() inside a catch block (and release resources in finally), or pass a callback to .transaction(async (t) => ...)."
|
|
10943
|
+
});
|
|
10944
|
+
}
|
|
10945
|
+
}
|
|
10946
|
+
const forUpdateMatches = matchPattern(
|
|
8989
10947
|
content,
|
|
8990
|
-
|
|
10948
|
+
/\bFOR\s+(?:UPDATE|NO\s+KEY\s+UPDATE|SHARE)\b/gi
|
|
8991
10949
|
);
|
|
8992
|
-
for (const m of
|
|
8993
|
-
if (
|
|
8994
|
-
|
|
10950
|
+
for (const m of forUpdateMatches) {
|
|
10951
|
+
if (shouldSkipMatch(context, m.line, m.column, m.lineContent)) continue;
|
|
10952
|
+
const preWin = getPrecedingWindow(lines, m.line, 6);
|
|
10953
|
+
if (!/\bSELECT\b/i.test(preWin)) continue;
|
|
10954
|
+
const lockWin = `${getPrecedingWindow(lines, m.line, 8)}
|
|
10955
|
+
${m.lineContent}
|
|
10956
|
+
${getForwardWindow(lines, m.line, 4)}`;
|
|
10957
|
+
if (LOCK_TIMEOUT_GUARD_RE.test(lockWin)) continue;
|
|
8995
10958
|
pushFinding({
|
|
8996
|
-
ruleId: "OPS-
|
|
10959
|
+
ruleId: "OPS-DB-003",
|
|
8997
10960
|
line: m.line,
|
|
8998
10961
|
column: m.column,
|
|
8999
|
-
severity: "
|
|
9000
|
-
|
|
9001
|
-
|
|
9002
|
-
|
|
9003
|
-
|
|
9004
|
-
|
|
10962
|
+
severity: "medium",
|
|
10963
|
+
confidence: "medium",
|
|
10964
|
+
subcategory: "blocking-db-lock",
|
|
10965
|
+
title: "Blocking Row Lock Without NOWAIT, SKIP LOCKED, or Lock Timeout",
|
|
10966
|
+
message: "SELECT ... FOR UPDATE acquires blocking row locks without NOWAIT, SKIP LOCKED, or a lock_timeout guard, risking cascading lock waits and connection pool exhaustion.",
|
|
10967
|
+
cwe: ["CWE-667", "CWE-770"],
|
|
10968
|
+
fixDescription: "Add NOWAIT or SKIP LOCKED to fail fast or skip contended rows, and set a bounded lock_timeout / statement_timeout on the session."
|
|
10969
|
+
});
|
|
10970
|
+
}
|
|
10971
|
+
const tableLockMatches = matchPattern(
|
|
10972
|
+
content,
|
|
10973
|
+
/\b(?:LOCK\s+TABLES\b|LOCK\s+TABLE\b[^\n;]*\bEXCLUSIVE\s+MODE\b)/gi
|
|
10974
|
+
);
|
|
10975
|
+
for (const m of tableLockMatches) {
|
|
10976
|
+
if (shouldSkipMatch(context, m.line, m.column, m.lineContent)) continue;
|
|
10977
|
+
pushFinding({
|
|
10978
|
+
ruleId: "OPS-DB-003",
|
|
10979
|
+
line: m.line,
|
|
10980
|
+
column: m.column,
|
|
10981
|
+
severity: "medium",
|
|
10982
|
+
subcategory: "blocking-db-lock",
|
|
10983
|
+
title: "Explicit Table-Level Lock Contention Risk",
|
|
10984
|
+
message: "Table-wide exclusive locking blocks concurrent reads/writes across the table and can stall all worker connections.",
|
|
10985
|
+
cwe: ["CWE-667", "CWE-770"],
|
|
10986
|
+
fixDescription: "Avoid table-level locks in application code; use optimistic locking (version columns), atomic UPDATE statements, or bounded row locks."
|
|
9005
10987
|
});
|
|
9006
10988
|
}
|
|
10989
|
+
const poolConfigMatches = matchPattern(
|
|
10990
|
+
content,
|
|
10991
|
+
/(?:\bnew\s+(?:pg\.)?Pool|\bmysql2?(?:\.promise)?\.createPool|\bcreate_engine|\basyncpg\.create_pool)\s*\(\s*(?!\s*\))/g
|
|
10992
|
+
);
|
|
10993
|
+
for (const m of poolConfigMatches) {
|
|
10994
|
+
if (shouldSkipMatch(context, m.line, m.column, m.lineContent)) continue;
|
|
10995
|
+
const callWin = getParenCallWindow(lines, m.line, 12);
|
|
10996
|
+
if (!/[:=]/.test(callWin)) continue;
|
|
10997
|
+
if (!POOL_BOUND_OR_TIMEOUT_RE.test(callWin)) {
|
|
10998
|
+
pushFinding({
|
|
10999
|
+
ruleId: "OPS-DB-003",
|
|
11000
|
+
line: m.line,
|
|
11001
|
+
column: m.column,
|
|
11002
|
+
severity: "medium",
|
|
11003
|
+
confidence: "medium",
|
|
11004
|
+
subcategory: "blocking-db-lock",
|
|
11005
|
+
title: "Database Pool Configured Without Size Limit or Timeout",
|
|
11006
|
+
message: "Database pool configuration specifies connection options without explicit max pool size or connection/acquire timeout, risking connection exhaustion or indefinite request hangs.",
|
|
11007
|
+
cwe: ["CWE-667", "CWE-770"],
|
|
11008
|
+
fixDescription: "Explicitly configure max pool size (e.g., max / pool_size) and connection/acquire/statement timeouts on the pool."
|
|
11009
|
+
});
|
|
11010
|
+
}
|
|
11011
|
+
}
|
|
11012
|
+
const usesPgModule = language === "javascript" || language === "typescript" ? /\bfrom\s+['"]pg['"]|\brequire\s*\(\s*['"]pg['"]\s*\)/.test(content) : false;
|
|
11013
|
+
if (usesPgModule) {
|
|
11014
|
+
const pgClientMatches = matchPattern(content, /\bnew\s+(?:pg\.)?Client\s*\(/g);
|
|
11015
|
+
for (const m of pgClientMatches) {
|
|
11016
|
+
if (shouldSkipMatch(context, m.line, m.column, m.lineContent)) continue;
|
|
11017
|
+
const forwardWin = getForwardWindow(lines, m.line, 40);
|
|
11018
|
+
const isTopLevel = m.lineContent.search(/\S/) === 0;
|
|
11019
|
+
const hasFinallyEnd = /\bfinally\b[\s\S]*?\.\s*end\s*\(/.test(forwardWin);
|
|
11020
|
+
if (isTopLevel || !/\.\s*end\s*\(/.test(forwardWin) || !hasFinallyEnd && /\.\s*connect\s*\(/.test(forwardWin)) {
|
|
11021
|
+
pushFinding({
|
|
11022
|
+
ruleId: "OPS-DB-004",
|
|
11023
|
+
line: m.line,
|
|
11024
|
+
column: m.column,
|
|
11025
|
+
severity: "high",
|
|
11026
|
+
subcategory: "pinned-db-connection",
|
|
11027
|
+
title: "Dedicated pg.Client Connection Held Without Pool or Guaranteed Close",
|
|
11028
|
+
message: "Using a dedicated pg.Client connection (especially persistent module-level or without finally { await client.end() }) pins a backend DB session/socket, causing lock retention and connection drops.",
|
|
11029
|
+
cwe: ["CWE-404", "CWE-770"],
|
|
11030
|
+
fixDescription: "Use pg.Pool (with explicit max and timeouts) for shared server workloads, or wrap short-lived Client usage in try { await client.connect(); ... } finally { await client.end(); }."
|
|
11031
|
+
});
|
|
11032
|
+
}
|
|
11033
|
+
}
|
|
11034
|
+
}
|
|
11035
|
+
if (language === "python") {
|
|
11036
|
+
const pyDirectConnMatches = matchPattern(
|
|
11037
|
+
content,
|
|
11038
|
+
/\b(?:psycopg2|psycopg|pymysql|MySQLdb|mysql\.connector|asyncpg)\.connect\s*\(/g
|
|
11039
|
+
);
|
|
11040
|
+
for (const m of pyDirectConnMatches) {
|
|
11041
|
+
if (shouldSkipMatch(context, m.line, m.column, m.lineContent)) continue;
|
|
11042
|
+
if (/^\s*(?:async\s+)?with\b/.test(m.lineContent)) continue;
|
|
11043
|
+
const forwardWin = getForwardWindow(lines, m.line, 40);
|
|
11044
|
+
const hasSafeClose = /\bfinally\s*:[\s\S]*?\.\s*close\s*\(/.test(forwardWin) || /\bwith\s+closing\s*\(/.test(m.lineContent);
|
|
11045
|
+
if (!hasSafeClose) {
|
|
11046
|
+
pushFinding({
|
|
11047
|
+
ruleId: "OPS-DB-004",
|
|
11048
|
+
line: m.line,
|
|
11049
|
+
column: m.column,
|
|
11050
|
+
severity: "high",
|
|
11051
|
+
subcategory: "pinned-db-connection",
|
|
11052
|
+
title: "Dedicated Python DB Connection Held Without Context Manager or Finally Close",
|
|
11053
|
+
message: "Direct database .connect() opened without a with-context manager or finally: .close() block; exceptions or keep-alive references pin DB sessions and locks indefinitely.",
|
|
11054
|
+
cwe: ["CWE-404", "CWE-770"],
|
|
11055
|
+
fixDescription: "Use a connection pool (e.g., psycopg_pool, asyncpg.create_pool, SQLAlchemy QueuePool) or wrap direct connections in `with driver.connect(...) as conn:` / `try ... finally: conn.close()`."
|
|
11056
|
+
});
|
|
11057
|
+
}
|
|
11058
|
+
}
|
|
11059
|
+
}
|
|
11060
|
+
if (language === "go") {
|
|
11061
|
+
const goConnMatches = matchPattern(content, /\.\s*Conn\s*\(/g);
|
|
11062
|
+
for (const m of goConnMatches) {
|
|
11063
|
+
if (shouldSkipMatch(context, m.line, m.column, m.lineContent)) continue;
|
|
11064
|
+
const stmtWin = getStatementWindow(lines, m.line, 4);
|
|
11065
|
+
if (!/(?:context\.|ctx\b)/.test(stmtWin)) continue;
|
|
11066
|
+
const forwardWin = getForwardWindow(lines, m.line, 20);
|
|
11067
|
+
if (!/\bdefer\s+[a-zA-Z_]\w*\.Close\s*\(/.test(forwardWin)) {
|
|
11068
|
+
pushFinding({
|
|
11069
|
+
ruleId: "OPS-DB-004",
|
|
11070
|
+
line: m.line,
|
|
11071
|
+
column: m.column,
|
|
11072
|
+
severity: "high",
|
|
11073
|
+
subcategory: "pinned-db-connection",
|
|
11074
|
+
title: "Pinned Go *sql.Conn Missing defer Close()",
|
|
11075
|
+
message: "Pinned database connection acquired via db.Conn(ctx) lacks `defer conn.Close()`, leaking an exclusive connection from the SQL pool on early returns or panics.",
|
|
11076
|
+
cwe: ["CWE-404", "CWE-770"],
|
|
11077
|
+
fixDescription: "Immediately call `defer conn.Close()` right after checking err from `db.Conn(ctx)`."
|
|
11078
|
+
});
|
|
11079
|
+
}
|
|
11080
|
+
}
|
|
11081
|
+
}
|
|
9007
11082
|
return findings;
|
|
9008
11083
|
}
|
|
9009
11084
|
|
|
@@ -9012,13 +11087,15 @@ var OPS_ANALYZERS = [
|
|
|
9012
11087
|
{ name: "oom-memory", analyze: analyzeOomMemory },
|
|
9013
11088
|
{ name: "timeout-resilience", analyze: analyzeTimeoutResilience },
|
|
9014
11089
|
{ name: "resource-leaks", analyze: analyzeResourceLeaks },
|
|
9015
|
-
{ name: "ops-performance", analyze: analyzeOpsPerformance }
|
|
11090
|
+
{ name: "ops-performance", analyze: analyzeOpsPerformance },
|
|
11091
|
+
{ name: "db-operations", analyze: analyzeDbOps }
|
|
9016
11092
|
];
|
|
9017
11093
|
var OPS_CATEGORIES = /* @__PURE__ */ new Set([
|
|
9018
11094
|
"oom-memory",
|
|
9019
11095
|
"timeout-resilience",
|
|
9020
11096
|
"resource-leaks",
|
|
9021
|
-
"ops-performance"
|
|
11097
|
+
"ops-performance",
|
|
11098
|
+
"db-operations"
|
|
9022
11099
|
]);
|
|
9023
11100
|
var OperationsScanner = class extends BaseScanner {
|
|
9024
11101
|
name = "OperationsScanner";
|
|
@@ -10336,11 +12413,11 @@ var QualityScanner = class {
|
|
|
10336
12413
|
};
|
|
10337
12414
|
|
|
10338
12415
|
// src/scanners/cve/index.ts
|
|
10339
|
-
import { resolve as
|
|
12416
|
+
import { resolve as resolve11 } from "path";
|
|
10340
12417
|
|
|
10341
12418
|
// src/scanners/cve/parsers/package-parser.ts
|
|
10342
|
-
import { basename as basename2, dirname as
|
|
10343
|
-
import { existsSync as
|
|
12419
|
+
import { basename as basename2, dirname as dirname9, extname as extname4, join as join3, resolve as resolve10 } from "path";
|
|
12420
|
+
import { existsSync as existsSync10, readFileSync as readFileSync9 } from "fs";
|
|
10344
12421
|
import yaml4 from "js-yaml";
|
|
10345
12422
|
function normalizePkgName(name, ecosystem) {
|
|
10346
12423
|
const lower = name.toLowerCase().trim();
|
|
@@ -10370,29 +12447,29 @@ function findCoveringLockfile(manifestPath) {
|
|
|
10370
12447
|
if (!candidates) return null;
|
|
10371
12448
|
const hasDirSep = /[\\/]/.test(manifestPath);
|
|
10372
12449
|
const maxLevels = hasDirSep ? 4 : 0;
|
|
10373
|
-
let currentDir =
|
|
12450
|
+
let currentDir = dirname9(resolve10(manifestPath));
|
|
10374
12451
|
for (let level = 0; level <= maxLevels; level++) {
|
|
10375
12452
|
for (const candidate of candidates) {
|
|
10376
12453
|
const lockPath = join3(currentDir, candidate);
|
|
10377
|
-
if (
|
|
12454
|
+
if (existsSync10(lockPath)) {
|
|
10378
12455
|
return { lockPath, lockType: candidate.toLowerCase(), isParent: level > 0 };
|
|
10379
12456
|
}
|
|
10380
12457
|
}
|
|
10381
|
-
if (
|
|
12458
|
+
if (existsSync10(join3(currentDir, ".git"))) {
|
|
10382
12459
|
break;
|
|
10383
12460
|
}
|
|
10384
|
-
const parent =
|
|
12461
|
+
const parent = dirname9(currentDir);
|
|
10385
12462
|
if (parent === currentDir) break;
|
|
10386
12463
|
currentDir = parent;
|
|
10387
12464
|
}
|
|
10388
12465
|
return null;
|
|
10389
12466
|
}
|
|
10390
12467
|
function isNpmWorkspaceRoot(dir) {
|
|
10391
|
-
if (
|
|
12468
|
+
if (existsSync10(join3(dir, "pnpm-workspace.yaml"))) {
|
|
10392
12469
|
return true;
|
|
10393
12470
|
}
|
|
10394
12471
|
const rootPkgPath = join3(dir, "package.json");
|
|
10395
|
-
if (!
|
|
12472
|
+
if (!existsSync10(rootPkgPath)) return false;
|
|
10396
12473
|
try {
|
|
10397
12474
|
const pkg = JSON.parse(readFileSync9(rootPkgPath, "utf-8"));
|
|
10398
12475
|
return Boolean(pkg && typeof pkg === "object" && pkg.workspaces);
|
|
@@ -10418,7 +12495,7 @@ function loadLockfileMap(lockPath, ecosystem) {
|
|
|
10418
12495
|
}
|
|
10419
12496
|
function parseDependencies(content, filePath) {
|
|
10420
12497
|
const fileName = basename2(filePath).toLowerCase();
|
|
10421
|
-
const ext =
|
|
12498
|
+
const ext = extname4(filePath).toLowerCase();
|
|
10422
12499
|
if (ext === ".csproj") {
|
|
10423
12500
|
return parseNuGetXml(content);
|
|
10424
12501
|
}
|
|
@@ -10503,7 +12580,7 @@ function parsePackageJson(content, filePath) {
|
|
|
10503
12580
|
const matchedCount = declaredNames.filter(
|
|
10504
12581
|
(name) => loaded.lockedVersions.has(normalizePkgName(name, "npm"))
|
|
10505
12582
|
).length;
|
|
10506
|
-
const applies = !coveringLock.isParent || declaredNames.length === 0 || matchedCount > 0 || isNpmWorkspaceRoot(
|
|
12583
|
+
const applies = !coveringLock.isParent || declaredNames.length === 0 || matchedCount > 0 || isNpmWorkspaceRoot(dirname9(coveringLock.lockPath));
|
|
10507
12584
|
if (applies) {
|
|
10508
12585
|
hasLockfile = true;
|
|
10509
12586
|
lockedVersions = loaded.lockedVersions;
|
|
@@ -11465,7 +13542,7 @@ function cleanVersion(version) {
|
|
|
11465
13542
|
}
|
|
11466
13543
|
|
|
11467
13544
|
// src/scanners/cve/vulnerability-db.ts
|
|
11468
|
-
import { existsSync as
|
|
13545
|
+
import { existsSync as existsSync11, readFileSync as readFileSync10, writeFileSync as writeFileSync5 } from "fs";
|
|
11469
13546
|
import { join as join4 } from "path";
|
|
11470
13547
|
import { tmpdir } from "os";
|
|
11471
13548
|
var OSV_CACHE_TTL_MS = 12 * 60 * 60 * 1e3;
|
|
@@ -11476,7 +13553,7 @@ function loadDiskCache() {
|
|
|
11476
13553
|
if (diskCacheLoaded) return;
|
|
11477
13554
|
diskCacheLoaded = true;
|
|
11478
13555
|
try {
|
|
11479
|
-
if (!
|
|
13556
|
+
if (!existsSync11(OSV_CACHE_PATH)) return;
|
|
11480
13557
|
const raw = JSON.parse(readFileSync10(OSV_CACHE_PATH, "utf-8"));
|
|
11481
13558
|
const now = Date.now();
|
|
11482
13559
|
for (const [k, entry] of Object.entries(raw)) {
|
|
@@ -11699,7 +13776,7 @@ var CVEScanner = class {
|
|
|
11699
13776
|
if (!content) return findings;
|
|
11700
13777
|
try {
|
|
11701
13778
|
const coveringLock = findCoveringLockfile(filePath);
|
|
11702
|
-
if (coveringLock && context.discoveredLockFiles?.has(
|
|
13779
|
+
if (coveringLock && context.discoveredLockFiles?.has(resolve11(coveringLock.lockPath).toLowerCase())) {
|
|
11703
13780
|
return findings;
|
|
11704
13781
|
}
|
|
11705
13782
|
const dependencies = parseDependencies(content, filePath);
|
|
@@ -11785,4 +13862,4 @@ export {
|
|
|
11785
13862
|
QualityScanner,
|
|
11786
13863
|
CVEScanner
|
|
11787
13864
|
};
|
|
11788
|
-
//# sourceMappingURL=chunk-
|
|
13865
|
+
//# sourceMappingURL=chunk-ZP6AOU5P.js.map
|