@code-sentinel-cli/code-sentinel-cli 4.0.6 → 4.0.7

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.
Files changed (27) hide show
  1. package/dist/bin.js +16204 -9882
  2. package/dist/builtin-rules/static/general/dockerfile-dependency-confusion.rule.js +27 -2
  3. package/dist/builtin-rules/static/general/java-weak-randomness.rule.js +41 -0
  4. package/dist/builtin-rules/static/general/kubernetes-pod-security.rule.js +90 -0
  5. package/dist/builtin-rules/static/general/no-dynamic-code-eval.rule.js +84 -0
  6. package/dist/builtin-rules/static/general/no-hardcoded-secret.rule.js +179 -13
  7. package/dist/builtin-rules/static/general/no-reflective-access-override.rule.js +6 -23
  8. package/dist/builtin-rules/static/general/no-unsafe-html-sink.rule.js +50 -7
  9. package/dist/builtin-rules/static/general/openapi-https-credentials.rule.js +90 -0
  10. package/dist/builtin-rules/static/general/sensitive-exception-response.rule.js +44 -0
  11. package/dist/builtin-rules/static/general/sensitive-output-exposure.rule.js +1 -1
  12. package/dist/builtin-rules/static/spring-boot/explicit-csp-required.rule.js +37 -0
  13. package/dist/builtin-rules/static/spring-boot/no-command-injection.rule.js +7 -1
  14. package/dist/builtin-rules/static/spring-boot/no-devtools-in-production.rule.js +13 -16
  15. package/dist/builtin-rules/static/spring-boot/no-global-permit-all.rule.js +50 -0
  16. package/dist/builtin-rules/static/spring-boot/no-negative-sensitive-input.rule.js +91 -0
  17. package/dist/builtin-rules/static/spring-boot/no-path-traversal.rule.js +7 -1
  18. package/dist/builtin-rules/static/spring-boot/no-servlet-xss.rule.js +7 -1
  19. package/dist/builtin-rules/static/spring-boot/no-spel-injection.rule.js +7 -1
  20. package/dist/builtin-rules/static/spring-boot/no-sql-string-concat.rule.js +7 -1
  21. package/dist/builtin-rules/static/spring-boot/no-ssrf.rule.js +23 -3
  22. package/dist/builtin-rules/static/spring-boot/password-reset-without-proof.rule.js +84 -0
  23. package/dist/builtin-rules/static/spring-boot/stored-content-without-sanitization.rule.js +93 -0
  24. package/dist/index.d.ts +154 -18
  25. package/dist/index.js +16204 -9882
  26. package/node_modules/@code-sentinel/parsers/index.js +330 -198
  27. package/package.json +1 -1
@@ -3,7 +3,7 @@ import { DOCKERFILE_RE, auditDockerfileDependencyConfusion } from '@code-sentine
3
3
  // builtin-rules/static/general/dockerfile-dependency-confusion.rule.ts
4
4
  var rule = {
5
5
  id: "general/dockerfile-dependency-confusion",
6
- version: 2,
6
+ version: 3,
7
7
  kind: "static-ts",
8
8
  title: "Ng\u0103n ch\u1EB7n Dependency Confusion & Insecure Package Registry trong Dockerfile (CWE-427/CWE-829)",
9
9
  description: "Ph\xE1t hi\u1EC7n c\u1EA5u h\xECnh package manager kh\xF4ng an to\xE0n trong Dockerfile (nh\u01B0 `pip install --extra-index-url`, `--trusted-host`, ho\u1EB7c c\u1EA5u h\xECnh registry qua HTTP cleartext) d\u1EABn \u0111\u1EBFn nguy c\u01A1 Dependency Confusion, Package Squatting ho\u1EB7c Man-in-the-Middle.",
@@ -14,11 +14,12 @@ var rule = {
14
14
  requires: "text",
15
15
  usesParser: false,
16
16
  baseConfidence: 90,
17
+ defaultOptions: { requirePinnedPackages: false },
17
18
  check(ctx) {
18
19
  const file = ctx.file;
19
20
  if (!DOCKERFILE_RE.test(file.path)) return [];
20
21
  const hits = auditDockerfileDependencyConfusion(file.content, file.path);
21
- return hits.map((h) => ({
22
+ const findings = hits.map((h) => ({
22
23
  message: h.reason,
23
24
  file: file.path,
24
25
  range: { line: h.line, column: 1 },
@@ -26,6 +27,30 @@ var rule = {
26
27
  confidence: 90,
27
28
  suggestion: h.reason.includes("--extra-index-url") ? "Ch\u1EC9 s\u1EED d\u1EE5ng `--index-url` tr\u1ECF t\u1EDBi kho n\u1ED9i b\u1ED9 (artifact proxy) \u0111\xE3 \u0111\u01B0\u1EE3c b\u1EA3o v\u1EC7, ho\u1EB7c s\u1EED d\u1EE5ng c\u01A1 ch\u1EBF hash-pinning (`--require-hashes`)." : h.reason.includes("--trusted-host") ? "Cung c\u1EA5p ch\u1EE9ng ch\u1EC9 CA n\u1ED9i b\u1ED9 h\u1EE3p l\u1EC7 cho h\u1EC7 \u0111i\u1EC1u h\xE0nh/container thay v\xEC b\u1ECF qua ki\u1EC3m tra an to\xE0n v\u1EDBi `--trusted-host`." : "S\u1EED d\u1EE5ng HTTPS k\xE8m ch\u1EE9ng ch\u1EC9 SSL h\u1EE3p l\u1EC7 cho kho l\u01B0u tr\u1EEF g\xF3i (registry)."
28
29
  }));
30
+ if (ctx.options.requirePinnedPackages) {
31
+ const lines = file.content.split("\n");
32
+ for (let i = 0; i < lines.length; i++) {
33
+ if (!/^\s*RUN\b/i.test(lines[i] ?? "")) continue;
34
+ const start = i;
35
+ let instruction = lines[i] ?? "";
36
+ while (/\\\s*$/.test(instruction) && i + 1 < lines.length)
37
+ instruction = instruction.replace(/\\\s*$/, " ") + (lines[++i] ?? "");
38
+ const install = instruction.match(
39
+ /(?:^\s*RUN\s+|&&\s*|;\s*|\|\|\s*)(?:sudo\s+)?apt(?:-get)?\s+(?:-[\w-]+\s+)*install\s+([^;&|]+)/i
40
+ );
41
+ const packages = install?.[1]?.replace(/\s+#.*$/, "")?.split(/\s+/).filter((token) => token && !token.startsWith("-") && !token.startsWith("#")) ?? [];
42
+ if (packages.some((token) => !/^[\w.+:-]+=\S+$/.test(token)))
43
+ findings.push({
44
+ file: file.path,
45
+ range: { line: start + 1, column: 1 },
46
+ severity: "warning",
47
+ confidence: 70,
48
+ message: "APT package installation has unpinned or dynamic versions; review repository trust and reproducibility. No compromised dependency is proven. [control=unpinned-os-package]",
49
+ suggestion: "Pin package versions (package=version), use a trusted repository/snapshot and verify the resulting image dependency inventory."
50
+ });
51
+ }
52
+ }
53
+ return findings;
29
54
  }
30
55
  };
31
56
 
@@ -0,0 +1,41 @@
1
+ import { maskJavaFiles } from '@code-sentinel/parsers';
2
+
3
+ // builtin-rules/static/general/java-weak-randomness.rule.ts
4
+ var rule = {
5
+ id: "general/java-weak-randomness",
6
+ version: 1,
7
+ kind: "static-ts",
8
+ title: "Java PRNG kh\xF4ng d\xF9ng cho gi\xE1 tr\u1ECB c\u1EA7n kh\xF3 \u0111o\xE1n",
9
+ severity: "warning",
10
+ category: "security",
11
+ languages: ["java"],
12
+ scope: "general",
13
+ usesParser: false,
14
+ baseConfidence: 60,
15
+ check: (ctx) => {
16
+ const masked = maskJavaFiles([ctx.file])[0]?.content ?? ctx.file.content;
17
+ const source = masked.replace(
18
+ /"(?:[^"\\]|\\.)*"/g,
19
+ (literal) => literal.replace(/[^\r\n]/g, " ")
20
+ );
21
+ const weakVariables = new Set(
22
+ [...source.matchAll(/\b(?:java\.util\.)?Random\s+([A-Za-z_$][\w$]*)\b/g)].map((m) => m[1])
23
+ );
24
+ const calls = [
25
+ ...source.matchAll(
26
+ /\bMath\s*\.\s*random\s*\(|\bThreadLocalRandom\s*\.\s*current\s*\(\s*\)\s*\.\s*next\w*\s*\(|\b([A-Za-z_$][\w$]*)\s*\.\s*next(?:Int|Long|Float|Double|Bytes|Boolean|Gaussian)\s*\(/g
27
+ )
28
+ ];
29
+ return calls.filter((match) => !match[1] || weakVariables.has(match[1])).map((match) => ({
30
+ file: ctx.file.path,
31
+ range: { line: source.slice(0, match.index).split("\n").length, column: 1 },
32
+ confidence: 60,
33
+ message: "Non-cryptographic Java PRNG used; review whether the generated value requires unpredictability or collision resistance. No security-sensitive use is proven. [control=weak-prng-review]",
34
+ suggestion: "Use SecureRandom for security values; use a uniqueness strategy for business identifiers. Suppress documented test/non-security uses after review."
35
+ }));
36
+ }
37
+ };
38
+
39
+ export { rule };
40
+ //# sourceMappingURL=java-weak-randomness.rule.js.map
41
+ //# sourceMappingURL=java-weak-randomness.rule.js.map
@@ -0,0 +1,90 @@
1
+ import { parseAllDocuments } from 'yaml';
2
+
3
+ // builtin-rules/static/general/infrastructure-config-audit.ts
4
+ var record = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
5
+ var list = (value) => Array.isArray(value) ? value : [];
6
+ var auditInfrastructureConfig = (content) => {
7
+ const signals = [];
8
+ for (const doc of parseAllDocuments(content)) {
9
+ if (doc.errors.length) continue;
10
+ let root;
11
+ try {
12
+ root = record(doc.toJS());
13
+ } catch {
14
+ continue;
15
+ }
16
+ if (!root) continue;
17
+ const line = content.slice(0, doc.range?.[0] ?? 0).split("\n").length;
18
+ const spec = record(root.spec);
19
+ const workload = ["Deployment", "StatefulSet", "DaemonSet", "Job", "ReplicaSet"].includes(
20
+ String(root.kind)
21
+ );
22
+ const pod = root.kind === "Pod" ? spec : workload ? record(record(spec?.template)?.spec) : root.kind === "CronJob" ? record(record(record(record(spec?.jobTemplate)?.spec)?.template)?.spec) : null;
23
+ if (pod && list(pod.containers).length) {
24
+ const podProfile = record(record(pod.securityContext)?.seccompProfile);
25
+ const unconstrained = [...list(pod.containers), ...list(pod.initContainers)].some(
26
+ (container) => {
27
+ const profile = record(record(record(container)?.securityContext)?.seccompProfile) ?? podProfile;
28
+ return !(profile?.type === "RuntimeDefault" || profile?.type === "Localhost" && typeof profile.localhostProfile === "string" && profile.localhostProfile.length > 0);
29
+ }
30
+ );
31
+ if (unconstrained) signals.push({ line, control: "k8s-seccomp" });
32
+ if (pod.automountServiceAccountToken !== false)
33
+ signals.push({ line, control: "k8s-token-automount" });
34
+ }
35
+ if (typeof root.openapi === "string") {
36
+ const paths = record(root.paths);
37
+ let exposed = false;
38
+ for (const path of Object.values(paths ?? {})) {
39
+ const pathItem = record(path);
40
+ for (const method of [
41
+ "get",
42
+ "post",
43
+ "put",
44
+ "patch",
45
+ "delete",
46
+ "head",
47
+ "options",
48
+ "trace"
49
+ ]) {
50
+ const operation = record(pathItem?.[method]);
51
+ if (!operation) continue;
52
+ const security = operation.security ?? root.security;
53
+ const authenticated = list(security).some(
54
+ (entry) => Object.keys(record(entry) ?? {}).length > 0
55
+ );
56
+ const servers = operation.servers ?? pathItem?.servers ?? root.servers;
57
+ if (authenticated && list(servers).some((server) => /^http:\/\//i.test(String(record(server)?.url ?? ""))))
58
+ exposed = true;
59
+ }
60
+ }
61
+ if (exposed) signals.push({ line, control: "openapi-http-credentials" });
62
+ }
63
+ }
64
+ return signals;
65
+ };
66
+
67
+ // builtin-rules/static/general/kubernetes-pod-security.rule.ts
68
+ var rule = {
69
+ id: "general/kubernetes-pod-security",
70
+ version: 1,
71
+ kind: "static-ts",
72
+ title: "Kubernetes khai b\xE1o seccomp v\xE0 gi\u1EDBi h\u1EA1n token ServiceAccount",
73
+ severity: "warning",
74
+ category: "security",
75
+ languages: ["yaml"],
76
+ scope: "general",
77
+ usesParser: false,
78
+ baseConfidence: 75,
79
+ check: (ctx) => auditInfrastructureConfig(ctx.file.content).filter((signal) => signal.control !== "openapi-http-credentials").map((signal) => ({
80
+ file: ctx.file.path,
81
+ range: { line: signal.line, column: 1 },
82
+ confidence: 75,
83
+ message: signal.control === "k8s-seccomp" ? "Pod/container lacks an explicit confined seccomp profile. Cluster defaults/admission policy require runtime review. [control=k8s-seccomp]" : "Pod does not explicitly disable ServiceAccount token automount. Effective ServiceAccount/admission policy requires runtime review. [control=k8s-token-automount]",
84
+ suggestion: signal.control === "k8s-seccomp" ? "Declare securityContext.seccompProfile.type: RuntimeDefault or a validated Localhost profile at pod/container level." : "Set automountServiceAccountToken: false for workloads that do not require Kubernetes API access; review RBAC for workloads that do."
85
+ }))
86
+ };
87
+
88
+ export { rule };
89
+ //# sourceMappingURL=kubernetes-pod-security.rule.js.map
90
+ //# sourceMappingURL=kubernetes-pod-security.rule.js.map
@@ -0,0 +1,84 @@
1
+ import { isThirdPartyAsset, maskJsComments } from '@code-sentinel/parsers';
2
+
3
+ // builtin-rules/static/general/no-dynamic-code-eval.rule.ts
4
+ var EVAL_CALL_RE = /(?<![\w$.])(?:(?:window|globalThis|self)\s*\.\s*)?eval\s*\(/g;
5
+ var NEW_FUNCTION_RE = /(?<![\w$.])new\s+Function\s*\(/g;
6
+ var STRING_CONSTANT_RE = /^\s*(?:'(?:[^'\\\n]|\\.)*'|"(?:[^"\\\n]|\\.)*"|`(?:[^`\\$]|\\.|\$(?!\{))*`)\s*$/;
7
+ var WRAP_PAREN_RE = /^\s*(['"`])\s*\(\s*\1\s*\+/;
8
+ var callArguments = (src, open) => {
9
+ const args = [];
10
+ let depth = 0;
11
+ let start = open + 1;
12
+ for (let i = open; i < src.length; i++) {
13
+ const ch = src[i];
14
+ if (ch === "'" || ch === '"' || ch === "`") {
15
+ for (i++; i < src.length && src[i] !== ch; i++) if (src[i] === "\\") i++;
16
+ continue;
17
+ }
18
+ if (ch === "(" || ch === "[" || ch === "{") depth++;
19
+ else if (ch === ")" || ch === "]" || ch === "}") {
20
+ depth--;
21
+ if (depth === 0) {
22
+ args.push(src.slice(start, i));
23
+ return args.map((a) => a.trim()).filter((a, _idx, all) => a !== "" || all.length > 1);
24
+ }
25
+ } else if (ch === "," && depth === 1) {
26
+ args.push(src.slice(start, i));
27
+ start = i + 1;
28
+ }
29
+ }
30
+ return null;
31
+ };
32
+ var lineOf = (content, index) => content.slice(0, index).split("\n").length;
33
+ var shorten = (s) => {
34
+ const one = s.replace(/\s+/g, " ").trim();
35
+ return one.length > 80 ? `${one.slice(0, 77)}...` : one;
36
+ };
37
+ var rule = {
38
+ id: "general/no-dynamic-code-eval",
39
+ version: 1,
40
+ kind: "static-ts",
41
+ title: "Kh\xF4ng \u0111\xE1nh gi\xE1 chu\u1ED7i \u0111\u1ED9ng th\xE0nh m\xE3 (eval / new Function)",
42
+ description: "Ph\xE1t hi\u1EC7n eval(x) v\xE0 new Function(..., x) khi x kh\xF4ng ph\u1EA3i chu\u1ED7i h\u1EB1ng (CWE-95). N\u1EBFu chu\u1ED7i l\u1EA5y t\u1EEB server, c\u1EA5u h\xECnh ho\u1EB7c ng\u01B0\u1EDDi d\xF9ng, ai ki\u1EC3m so\xE1t \u0111\u01B0\u1EE3c chu\u1ED7i \u0111\xF3 s\u1EBD ch\u1EA1y \u0111\u01B0\u1EE3c JavaScript tr\xEAn tr\xECnh duy\u1EC7t c\u1EE7a m\u1ECDi ng\u01B0\u1EDDi d\xF9ng.",
43
+ severity: "warning",
44
+ category: "security",
45
+ languages: ["typescript", "javascript"],
46
+ scope: "general",
47
+ requires: "syntactic",
48
+ usesParser: false,
49
+ baseConfidence: 70,
50
+ check(ctx) {
51
+ if (isThirdPartyAsset(ctx.file.path, ctx.file.content)) return [];
52
+ const content = maskJsComments(ctx.file.content);
53
+ const findings = [];
54
+ const report = (index, api, arg) => {
55
+ const wrap = WRAP_PAREN_RE.test(arg);
56
+ findings.push({
57
+ file: ctx.file.path,
58
+ range: { line: lineOf(content, index), column: 1 },
59
+ confidence: 70,
60
+ message: wrap ? `${api} d\u1EF1ng object/h\xE0m t\u1EEB chu\u1ED7i \u0111\u1ED9ng \`${shorten(arg)}\` (idiom \`'(' + x + ')'\`). N\u1EBFu chu\u1ED7i l\u1EA5y t\u1EEB server ho\u1EB7c c\u1EA5u h\xECnh, ai ghi \u0111\u01B0\u1EE3c n\xF3 s\u1EBD ch\u1EA1y \u0111\u01B0\u1EE3c JavaScript tr\xEAn tr\xECnh duy\u1EC7t ng\u01B0\u1EDDi d\xF9ng (CWE-95).` : `${api} \u0111\xE1nh gi\xE1 chu\u1ED7i \u0111\u1ED9ng \`${shorten(arg)}\` th\xE0nh m\xE3 (CWE-95). N\u1EBFu chu\u1ED7i c\xF3 ngu\u1ED3n ngo\xE0i m\xE3 ngu\u1ED3n, \u0111\xE2y l\xE0 \u0111i\u1EC3m ch\xE8n m\xE3.`,
61
+ suggestion: wrap ? "D\u1EEF li\u1EC7u th\xEC d\xF9ng JSON.parse; h\xE0nh vi (h\xE0m created/methods, c\xF4ng th\u1EE9c) th\xEC ch\u1ECDn t\u1EEB m\u1ED9t b\u1EA3ng h\xE0m \u0111\u1ECBnh s\u1EB5n theo t\xEAn, kh\xF4ng \u0111\xE1nh gi\xE1 m\xE3 l\u1EA5y t\u1EEB server." : "B\u1ECF eval/new Function: d\xF9ng JSON.parse cho d\u1EEF li\u1EC7u, m\u1ED9t b\u1EA3ng h\xE0m \u0111\u1ECBnh s\u1EB5n cho h\xE0nh vi, ho\u1EB7c new RegExp(escape(x)) cho bi\u1EC3u th\u1EE9c ch\xEDnh quy."
62
+ });
63
+ };
64
+ EVAL_CALL_RE.lastIndex = 0;
65
+ for (const m of content.matchAll(EVAL_CALL_RE)) {
66
+ const args = callArguments(content, m.index + m[0].length - 1);
67
+ const first = args?.[0];
68
+ if (first === void 0 || STRING_CONSTANT_RE.test(first)) continue;
69
+ report(m.index, "eval()", first);
70
+ }
71
+ NEW_FUNCTION_RE.lastIndex = 0;
72
+ for (const m of content.matchAll(NEW_FUNCTION_RE)) {
73
+ const args = callArguments(content, m.index + m[0].length - 1);
74
+ const body = args?.[args.length - 1];
75
+ if (body === void 0 || STRING_CONSTANT_RE.test(body)) continue;
76
+ report(m.index, "new Function()", body);
77
+ }
78
+ return findings.sort((a, b) => a.range.line - b.range.line);
79
+ }
80
+ };
81
+
82
+ export { rule };
83
+ //# sourceMappingURL=no-dynamic-code-eval.rule.js.map
84
+ //# sourceMappingURL=no-dynamic-code-eval.rule.js.map
@@ -1,3 +1,5 @@
1
+ import { maskJavaComments, maskJsComments } from '@code-sentinel/parsers';
2
+
1
3
  // builtin-rules/static/general/no-hardcoded-secret.rule.ts
2
4
  var PROVIDER_PATTERNS = [
3
5
  // ---- AWS ----
@@ -345,18 +347,34 @@ var GENERIC_PATTERNS = [
345
347
  var CONFIG_SECRET_PATTERNS = [
346
348
  {
347
349
  name: "config-secret-assignment",
348
- regex: /^\s*(?:[-\w.]+\.)?(?:password|passwd|pwd|secret|client[_-]?secret|api[_-]?key|apikey|access[_-]?token|auth[_-]?token)\s*[:=]\s*([^\s#'"][^\r\n#]*)/gim,
350
+ regex: /^[\t ]*(?:export[\t ]+)?[\w.-]*?(?:password|passwd|pwd|secret|api[_-]?key|access[_-]?token|auth[_-]?token)[\t ]*[:=][\t ]*["']?([^"'\r\n#]+)["']?/gim,
349
351
  confidence: 75,
350
352
  message: "Config file secret value detected.",
351
353
  payloadGroup: 1
352
354
  },
353
355
  {
354
356
  name: "config-empty-password",
355
- regex: /^\s*(?:[-\w.]+\.)?(?:password|passwd|pwd)\s*[:=]\s*(?:["']\s*["']\s*$|\s*$)/gim,
357
+ regex: /^[\t ]*[\w.-]*?(?:password|passwd|pwd)[\t ]*[:=][\t ]*(?:["'][\t ]*["']|null|~)?[\t ]*$/gim,
356
358
  confidence: 85,
357
359
  message: "Empty password in configuration file (CWE-258 / CWE-798)."
358
360
  }
359
361
  ];
362
+ var HTTP_URL_SECRET_PATTERN = {
363
+ name: "http-url-credentials",
364
+ regex: /\bhttps?:\/\/[^\s:/@'"<>]+:([^\s/@'"<>]+)@[^\s'"<>]+/gi,
365
+ confidence: 75,
366
+ message: "Inline credential in an HTTP/HTTPS URL detected.",
367
+ payloadGroup: 1
368
+ };
369
+ var XML_SECRET_PATTERNS = [
370
+ {
371
+ name: "xml-secret-element",
372
+ regex: /<([\w.-]*?(?:password|passwd|pwd|secret|api[_-]?key|access[_-]?token))\b[^>]*>([^<\r\n]+)<\/\1[\t ]*>/gi,
373
+ confidence: 75,
374
+ message: "Plaintext credential in XML configuration detected.",
375
+ payloadGroup: 2
376
+ }
377
+ ];
360
378
  var BUILTIN_PATTERNS = [
361
379
  ...PROVIDER_PATTERNS,
362
380
  ...PEM_PATTERNS,
@@ -419,9 +437,35 @@ var isFieldNameEcho = (payload) => FIELD_NAME_ECHOES.includes(payload.toLowerCas
419
437
  var looksExternalized = (payload) => {
420
438
  const trimmed = payload.trim();
421
439
  const lower = trimmed.toLowerCase();
422
- return trimmed.startsWith("${") || lower.startsWith("enc(") || lower.startsWith("{cipher}") || lower.startsWith("vault://") || lower.startsWith("optional:vault://");
440
+ return trimmed.startsWith("${") || /^\$[A-Z_][A-Z0-9_]*$/i.test(trimmed) || lower.startsWith("enc(") || lower.startsWith("{cipher}") || lower.startsWith("vault://") || lower.startsWith("optional:vault://");
423
441
  };
424
442
  var isConfigLanguage = (language) => language === "yaml" || language === "text" || language === "shell";
443
+ var maskConfigComments = (content) => content.split("\n").map((line) => {
444
+ let quote = "";
445
+ for (let i = 0; i < line.length; i++) {
446
+ const char = line[i];
447
+ if (quote) {
448
+ if (char === "\\" && quote === '"') {
449
+ i++;
450
+ continue;
451
+ }
452
+ if (char === quote) quote = "";
453
+ } else if (char === '"' || char === "'") {
454
+ quote = char;
455
+ } else if (char === "#" && (i === 0 || /[\t ]/.test(line[i - 1] ?? ""))) {
456
+ return line.slice(0, i) + " ".repeat(line.length - i);
457
+ }
458
+ }
459
+ return line;
460
+ }).join("\n");
461
+ var maskSecretComments = (content, language) => {
462
+ if (language === "java") return maskJavaComments(content);
463
+ if (language === "typescript" || language === "javascript") return maskJsComments(content);
464
+ if (language === "xml") {
465
+ return content.replace(/<!--[\s\S]*?(?:-->|$)/g, (comment) => comment.replace(/[^\r\n]/g, " "));
466
+ }
467
+ return isConfigLanguage(language) ? maskConfigComments(content) : content;
468
+ };
425
469
  var lineColAt = (content, offset) => {
426
470
  let line = 1;
427
471
  let lastNl = -1;
@@ -458,12 +502,111 @@ var compileExtra = (extras, logger) => {
458
502
  }
459
503
  return out;
460
504
  };
505
+ var PASSWORD_SINK_CALL_RE = /\b(?:setPassword|updatePassword|changePassword|resetPassword|withPassword|setNewPassword|addUser|addUserWithWorkflow)\s*\(/g;
506
+ var POSITIONAL_PASSWORD_SINKS = /* @__PURE__ */ new Map([
507
+ ["addUser", [3, 4]],
508
+ ["addUserWithWorkflow", [3, 4]]
509
+ ]);
510
+ var LIFERAY_ADD_USER_MIN_ARGS = 10;
511
+ var MIN_SINK_PASSWORD_LENGTH = 4;
512
+ var callArguments = (content, open) => {
513
+ const args = [];
514
+ let depth = 0;
515
+ let start = open + 1;
516
+ let quote = null;
517
+ for (let i = open; i < content.length; i++) {
518
+ const ch = content[i];
519
+ if (quote) {
520
+ if (ch === "\\") i++;
521
+ else if (ch === quote) quote = null;
522
+ continue;
523
+ }
524
+ if (ch === '"' || ch === "'") quote = ch;
525
+ else if (ch === "(") depth++;
526
+ else if (ch === ")") {
527
+ depth--;
528
+ if (depth === 0) {
529
+ args.push(content.slice(start, i));
530
+ return args;
531
+ }
532
+ } else if (ch === "," && depth === 1) {
533
+ args.push(content.slice(start, i));
534
+ start = i + 1;
535
+ } else if (ch === ";" && depth === 1) return null;
536
+ }
537
+ return null;
538
+ };
539
+ var acceptableSinkPassword = (value) => value.trim().length >= MIN_SINK_PASSWORD_LENGTH && // A mask like "******" is a display value, not a password (measured: tcct-be-base portal).
540
+ !/^(.)\1+$/.test(value) && !looksLikePlaceholder(value) && !isFieldNameEcho(value) && !looksExternalized(value);
541
+ var findPasswordSinkLiterals = (content) => {
542
+ const out = [];
543
+ PASSWORD_SINK_CALL_RE.lastIndex = 0;
544
+ let call;
545
+ while ((call = PASSWORD_SINK_CALL_RE.exec(content)) !== null) {
546
+ const open = call.index + call[0].length - 1;
547
+ const allArgs = callArguments(content, open);
548
+ if (!allArgs) continue;
549
+ const name = /^\w+/.exec(call[0])?.[0] ?? "";
550
+ const positions = POSITIONAL_PASSWORD_SINKS.get(name);
551
+ let args = allArgs;
552
+ if (positions) {
553
+ if (allArgs.length < LIFERAY_ADD_USER_MIN_ARGS) continue;
554
+ args = positions.map((i) => allArgs[i] ?? "");
555
+ }
556
+ const seen = /* @__PURE__ */ new Set();
557
+ for (const raw of args) {
558
+ const arg = raw.trim();
559
+ const literal = /^["']([^"'\\]*)["']$/.exec(arg)?.[1];
560
+ if (literal !== void 0) {
561
+ if (acceptableSinkPassword(literal) && !seen.has(literal)) {
562
+ seen.add(literal);
563
+ out.push({ offset: call.index, value: literal, via: null });
564
+ }
565
+ continue;
566
+ }
567
+ if (!/^[A-Za-z_$][\w$]*$/.test(arg)) continue;
568
+ const escaped = arg.replace(/\$/g, "\\$");
569
+ const assignRe = new RegExp(`\\b${escaped}\\s*=\\s*["']([^"'\\\\\\n]*)["']\\s*;`, "g");
570
+ let assign;
571
+ let nearest = null;
572
+ while ((assign = assignRe.exec(content)) !== null && assign.index < call.index) {
573
+ nearest = assign;
574
+ }
575
+ const value = nearest?.[1];
576
+ if (nearest && value !== void 0 && acceptableSinkPassword(value) && !seen.has(value)) {
577
+ seen.add(value);
578
+ out.push({ offset: nearest.index, value, via: arg });
579
+ }
580
+ }
581
+ }
582
+ return out;
583
+ };
461
584
  var isOwnTestFile = (filePath) => {
462
585
  const basename = filePath.split(/[/\\]/).pop() ?? filePath;
463
586
  return basename === "no-hardcoded-secret.test.ts" || basename === "no-hardcoded-secret.rule.ts";
464
587
  };
588
+ var EMPTY_PASSWORD_PATTERNS = /* @__PURE__ */ new Set([
589
+ "empty-password-assignment",
590
+ "empty-password-method-call"
591
+ ]);
465
592
  var rule = {
466
593
  id: "general/no-hardcoded-secret",
594
+ // v11: skip the EMPTY-password patterns in a Vue SFC ([ADR-0093]). A `.vue` component only ever
595
+ // runs in the browser, so `passWord: ''` in its `data()` is a form field being reset, never a
596
+ // credential a server authenticates with. Measured on mcdt_bqp: 54 of 54 hits were exactly that
597
+ // idiom, all at severity error (CI-blocking), while the same frontend's .js files had 0.
598
+ // Non-empty literals still fire — a real password committed in client code is still a leak.
599
+ // v10: MERGE of two independent lines of work. The password-literal-to-setter patterns (a
600
+ // literal reaching setPassword/updatePassword/... directly or via one local assignment,
601
+ // regardless of name or length — mcdt_bqp SR BUG-52784) were authored as "v6" on a branch while
602
+ // v6-v9 below shipped on main, so the number is taken fresh rather than reused.
603
+ // v9: ignore comments across source/config languages, preserving finding positions.
604
+ // v8: HTTP URL credentials, including comments and literal default passwords.
605
+ // v7: scan committed credentials in comments; optional encrypted-value review.
606
+ // v6: prefixed/short config credentials, XML elements, comment-aware empty passwords.
607
+ // v9: ignore comments across source/config languages, preserving finding positions.
608
+ // v8: HTTP URL credentials, including comments and literal default passwords.
609
+ // v7: scan committed credentials in comments; optional encrypted-value review.
467
610
  // v5: added empty-password-assignment and config-empty-password patterns (CWE-258/798).
468
611
  // v4: source-only execution + YAML/text support for Spring Boot application
469
612
  // config files. `.properties` is classified as `text`.
@@ -472,31 +615,37 @@ var rule = {
472
615
  // v2 (1.2.1): added FIELD_NAME_ECHOES filter for enum-value / label-dict
473
616
  // FPs (e.g. `PASSWORD = 'password'`). Bumped so the rule cache invalidates
474
617
  // stale v1 findings — Phase 9 cache key is (id, version, file.hash).
475
- version: 5,
618
+ version: 11,
476
619
  kind: "static-ts",
477
620
  title: "Kh\xF4ng hardcode secrets / API keys / private keys v\xE0o source",
478
621
  description: "Qu\xE9t credentials, API keys, tokens, private keys committed v\xE0o code. H\u1ED7 tr\u1EE3 AWS / GitHub / GitLab / Slack / Stripe / Google / Azure / Twilio / SendGrid / Mailgun / NPM / PyPI / Discord / Telegram / DataDog / New Relic / Cloudflare / DigitalOcean / Docker Hub + PEM private keys + connection strings c\xF3 inline credentials + JWT + generic password/secret/apiKey assignments. Severity = error (CI gate). Confidence t\u1EEB 65 (generic, c\xF3 false positive) t\u1EDBi 95 (provider-prefixed, near-zero false positive). Tune qua options.disabledPatterns + options.extraPatterns.",
479
622
  severity: "error",
480
623
  category: "security",
481
624
  // Pure content scan: can run on YAML and text-classified config files.
482
- languages: ["typescript", "javascript", "java", "yaml", "text", "shell"],
625
+ languages: ["typescript", "javascript", "java", "xml", "yaml", "text", "shell"],
483
626
  scope: "general",
484
627
  usesParser: false,
485
628
  baseConfidence: 80,
486
629
  defaultOptions: {
487
630
  disabledPatterns: [],
488
- extraPatterns: []
631
+ extraPatterns: [],
632
+ inspectEncryptedValues: false
489
633
  },
490
634
  check(ctx) {
491
635
  if (isOwnTestFile(ctx.file.path)) return [];
492
636
  const disabled = new Set(ctx.options.disabledPatterns);
493
637
  const extras = compileExtra(ctx.options.extraPatterns, ctx.logger);
638
+ const clientOnly = ctx.file.path.toLowerCase().endsWith(".vue");
494
639
  const patterns = [
495
- ...BUILTIN_PATTERNS.filter((p) => !disabled.has(p.name)),
640
+ ...BUILTIN_PATTERNS.filter(
641
+ (p) => !disabled.has(p.name) && !(clientOnly && EMPTY_PASSWORD_PATTERNS.has(p.name))
642
+ ),
643
+ ...!disabled.has(HTTP_URL_SECRET_PATTERN.name) ? [HTTP_URL_SECRET_PATTERN] : [],
496
644
  ...isConfigLanguage(ctx.file.language) ? CONFIG_SECRET_PATTERNS.filter((p) => !disabled.has(p.name)) : [],
645
+ ...ctx.file.language === "xml" ? XML_SECRET_PATTERNS.filter((p) => !disabled.has(p.name)) : [],
497
646
  ...extras
498
647
  ];
499
- const content = ctx.file.content;
648
+ const content = maskSecretComments(ctx.file.content, ctx.file.language);
500
649
  const findings = [];
501
650
  const reportedRanges = [];
502
651
  const overlapsReported = (start, end) => {
@@ -507,26 +656,43 @@ var rule = {
507
656
  };
508
657
  for (const pattern of patterns) {
509
658
  pattern.regex.lastIndex = 0;
510
- let match;
511
- while ((match = pattern.regex.exec(content)) !== null) {
659
+ for (const match of content.matchAll(pattern.regex)) {
512
660
  const matchStart = match.index;
513
661
  const matchEnd = matchStart + match[0].length;
514
662
  if (overlapsReported(matchStart, matchEnd)) continue;
515
663
  const payload = pattern.payloadGroup !== void 0 ? match[pattern.payloadGroup] : match[0];
516
- if (payload && (looksLikePlaceholder(payload) || isFieldNameEcho(payload) || looksExternalized(payload) || pattern.name === "config-secret-assignment" && payload.trim().length < 8)) {
664
+ const encrypted = payload !== void 0 && /^(?:ENC\(|\{cipher\})/i.test(payload.trim());
665
+ if (payload && (looksLikePlaceholder(payload) || isFieldNameEcho(payload) && pattern.name.startsWith("generic-") || looksExternalized(payload) && !(encrypted && ctx.options.inspectEncryptedValues) || pattern.name === "config-secret-assignment" && /^(?:true|false|null|~)?$/i.test(payload.trim()))) {
517
666
  continue;
518
667
  }
519
668
  const { line, column } = lineColAt(content, matchStart);
520
669
  findings.push({
521
- message: `${pattern.message} [pattern=${pattern.name}]`,
670
+ message: encrypted ? "Encrypted credential committed; review master-key separation and decryptability, not plaintext exposure. [control=encrypted-credential]" : `${pattern.message} [pattern=${pattern.name}]`,
522
671
  file: ctx.file.path,
523
672
  range: { line, column },
524
- confidence: pattern.confidence,
673
+ confidence: encrypted ? 60 : pattern.confidence,
674
+ ...encrypted ? { severity: "warning" } : {},
525
675
  suggestion: "Move the secret to an environment variable (vd `process.env.X`) v\xE0 rotate gi\xE1 tr\u1ECB \u0111\xE3 commit ngay. Th\xEAm `.env` v\xE0o `.gitignore`. N\u1EBFu l\xE0 test fixture, \u0111\u1EB7t file v\xE0o path \u0111\xE3 exclude ho\u1EB7c d\xF9ng `// code-sentinel-disable-next-line general/no-hardcoded-secret`."
526
676
  });
527
677
  reportedRanges.push({ start: matchStart, end: matchEnd });
528
678
  }
529
679
  }
680
+ if (!disabled.has("password-literal-to-setter") && !isConfigLanguage(ctx.file.language)) {
681
+ const masked = ctx.file.language === "java" ? maskJavaComments(content) : maskJsComments(content);
682
+ for (const hit of findPasswordSinkLiterals(masked)) {
683
+ const end = hit.offset + 1;
684
+ if (overlapsReported(hit.offset, end)) continue;
685
+ const { line, column } = lineColAt(content, hit.offset);
686
+ findings.push({
687
+ message: `${hit.via === null ? "Hard-coded password literal passed to a password-setting API" : `Hard-coded password literal assigned to \`${hit.via}\` and passed to a password-setting API`} (CWE-798 / CWE-259). [pattern=password-literal-to-setter]`,
688
+ file: ctx.file.path,
689
+ range: { line, column },
690
+ confidence: 85,
691
+ suggestion: "Kh\xF4ng \u0111\u1EB7t m\u1EADt kh\u1EA9u m\u1EB7c \u0111\u1ECBnh c\u1ED1 \u0111\u1ECBnh trong m\xE3: sinh m\u1EADt kh\u1EA9u ng\u1EABu nhi\xEAn (SecureRandom) v\xE0 bu\u1ED9c \u0111\u1ED5i \u1EDF l\u1EA7n \u0111\u0103ng nh\u1EADp \u0111\u1EA7u, ho\u1EB7c \u0111\u1ECDc t\u1EEB c\u1EA5u h\xECnh b\xED m\u1EADt. Rotate m\u1ECDi t\xE0i kho\u1EA3n \u0111\xE3 \u0111\u01B0\u1EE3c \u0111\u1EB7t gi\xE1 tr\u1ECB n\xE0y."
692
+ });
693
+ reportedRanges.push({ start: hit.offset, end });
694
+ }
695
+ }
530
696
  return findings;
531
697
  }
532
698
  };
@@ -1,11 +1,6 @@
1
- import { maskJavaFiles } from '@code-sentinel/parsers';
1
+ import { findReflectiveAccess } from '@code-sentinel/parsers';
2
2
 
3
3
  // builtin-rules/static/general/no-reflective-access-override.rule.ts
4
- var INSTANCE_SET_ACCESSIBLE_RE = /\b[A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*)*\s*\.\s*setAccessible\s*\(\s*true\s*\)/g;
5
- var TRY_SET_ACCESSIBLE_RE = /\b[A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*)*\s*\.\s*trySetAccessible\s*\(\s*\)/g;
6
- var STATIC_SET_ACCESSIBLE_RE = /\bAccessibleObject\s*\.\s*setAccessible\s*\(\s*[^,;\n]+\s*,\s*true\s*\)/g;
7
- var maskStringLiterals = (content) => content.replace(/"(?:[^"\\]|\\.)*"/g, (literal) => literal.replace(/[^\n]/g, " "));
8
- var lineOf = (content, index) => content.slice(0, index).split("\n").length;
9
4
  var finding = (file, line, api) => ({
10
5
  file,
11
6
  range: { line, column: 1 },
@@ -15,7 +10,7 @@ var finding = (file, line, api) => ({
15
10
  });
16
11
  var rule = {
17
12
  id: "general/no-reflective-access-override",
18
- version: 1,
13
+ version: 2,
19
14
  kind: "static-ts",
20
15
  title: "Kh\xF4ng v\u01B0\u1EE3t access modifier b\u1EB1ng Java reflection",
21
16
  description: "Ph\xE1t hi\u1EC7n Field/Method/AccessibleObject g\u1ECDi setAccessible(true) ho\u1EB7c trySetAccessible(), c\xF3 th\u1EC3 v\u01B0\u1EE3t private/protected access control.",
@@ -23,25 +18,13 @@ var rule = {
23
18
  category: "security",
24
19
  languages: ["java"],
25
20
  scope: "general",
26
- requires: "syntactic",
21
+ requires: "text",
27
22
  usesParser: false,
28
23
  baseConfidence: 80,
29
24
  check(ctx) {
30
- const source = maskJavaFiles([ctx.file])[0] ?? ctx.file;
31
- const content = maskStringLiterals(source.content);
32
- const findings = [];
33
- const patterns = [
34
- { re: INSTANCE_SET_ACCESSIBLE_RE, api: "setAccessible(true)" },
35
- { re: TRY_SET_ACCESSIBLE_RE, api: "trySetAccessible()" },
36
- { re: STATIC_SET_ACCESSIBLE_RE, api: "AccessibleObject.setAccessible(..., true)" }
37
- ];
38
- for (const { re, api } of patterns) {
39
- re.lastIndex = 0;
40
- for (const match of content.matchAll(re)) {
41
- findings.push(finding(source.path, lineOf(content, match.index ?? 0), api));
42
- }
43
- }
44
- return findings.sort((a, b) => a.range.line - b.range.line);
25
+ return findReflectiveAccess(ctx.file.content, ctx.file.path).map(
26
+ (hit) => finding(hit.file, hit.line, hit.api)
27
+ );
45
28
  }
46
29
  };
47
30