@code-sentinel-cli/code-sentinel-cli 3.0.3 → 3.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/README.md +1 -1
  2. package/dist/bin.js +1184 -809
  3. package/dist/builtin-rules/ai/angular/api-service-contract-risk.prompt.md +71 -0
  4. package/dist/builtin-rules/ai/angular/api-service-contract-risk.rule.yaml +22 -0
  5. package/dist/builtin-rules/ai/angular/component-state-flow.prompt.md +79 -0
  6. package/dist/builtin-rules/ai/angular/component-state-flow.rule.yaml +26 -0
  7. package/dist/builtin-rules/ai/angular/cross-feature-api-drift.prompt.md +70 -0
  8. package/dist/builtin-rules/ai/angular/cross-feature-api-drift.rule.yaml +42 -0
  9. package/dist/builtin-rules/ai/angular/cross-feature-route-permission-drift.prompt.md +73 -0
  10. package/dist/builtin-rules/ai/angular/cross-feature-route-permission-drift.rule.yaml +50 -0
  11. package/dist/builtin-rules/ai/angular/reactive-form-flow.prompt.md +82 -0
  12. package/dist/builtin-rules/ai/angular/reactive-form-flow.rule.yaml +23 -0
  13. package/dist/builtin-rules/ai/angular/route-permission-flow.prompt.md +80 -0
  14. package/dist/builtin-rules/ai/angular/route-permission-flow.rule.yaml +23 -0
  15. package/dist/builtin-rules/ai/angular/rxjs-flow-risk.prompt.md +82 -0
  16. package/dist/builtin-rules/ai/angular/rxjs-flow-risk.rule.yaml +24 -0
  17. package/dist/builtin-rules/ai/angular/template-contract-risk.prompt.md +80 -0
  18. package/dist/builtin-rules/ai/angular/template-contract-risk.rule.yaml +25 -0
  19. package/dist/builtin-rules/ai/flutter/dynamic-content-risk.prompt.md +55 -0
  20. package/dist/builtin-rules/ai/flutter/dynamic-content-risk.rule.yaml +18 -0
  21. package/dist/builtin-rules/ai/flutter/feature-state-flow-risk.prompt.md +58 -0
  22. package/dist/builtin-rules/ai/flutter/feature-state-flow-risk.rule.yaml +18 -0
  23. package/dist/builtin-rules/ai/flutter/native-platform-consistency-risk.prompt.md +56 -0
  24. package/dist/builtin-rules/ai/flutter/native-platform-consistency-risk.rule.yaml +18 -0
  25. package/dist/builtin-rules/ai/flutter/network-auth-flow-risk.prompt.md +57 -0
  26. package/dist/builtin-rules/ai/flutter/network-auth-flow-risk.rule.yaml +19 -0
  27. package/dist/builtin-rules/ai/flutter/ui-responsive-accessibility-risk.prompt.md +60 -0
  28. package/dist/builtin-rules/ai/flutter/ui-responsive-accessibility-risk.rule.yaml +18 -0
  29. package/dist/builtin-rules/ai/general/code-clarity.prompt.md +57 -0
  30. package/dist/builtin-rules/ai/general/code-clarity.rule.yaml +20 -0
  31. package/dist/builtin-rules/ai/spring-boot/business-invariant-risk.prompt.md +86 -0
  32. package/dist/builtin-rules/ai/spring-boot/business-invariant-risk.rule.yaml +25 -0
  33. package/dist/builtin-rules/ai/spring-boot/cache-consistency-risk.prompt.md +80 -0
  34. package/dist/builtin-rules/ai/spring-boot/cache-consistency-risk.rule.yaml +25 -0
  35. package/dist/builtin-rules/ai/spring-boot/cross-feature-error-handling-drift.prompt.md +76 -0
  36. package/dist/builtin-rules/ai/spring-boot/cross-feature-error-handling-drift.rule.yaml +63 -0
  37. package/dist/builtin-rules/ai/spring-boot/cross-feature-transaction-boundary-drift.prompt.md +85 -0
  38. package/dist/builtin-rules/ai/spring-boot/cross-feature-transaction-boundary-drift.rule.yaml +68 -0
  39. package/dist/builtin-rules/ai/spring-boot/error-handling-completeness.prompt.md +121 -0
  40. package/dist/builtin-rules/ai/spring-boot/error-handling-completeness.rule.yaml +84 -0
  41. package/dist/builtin-rules/ai/spring-boot/event-publishing-risk.prompt.md +80 -0
  42. package/dist/builtin-rules/ai/spring-boot/event-publishing-risk.rule.yaml +25 -0
  43. package/dist/builtin-rules/ai/spring-boot/io-boundary-risk.prompt.md +78 -0
  44. package/dist/builtin-rules/ai/spring-boot/io-boundary-risk.rule.yaml +25 -0
  45. package/dist/builtin-rules/ai/spring-boot/ownership-scope-risk.prompt.md +83 -0
  46. package/dist/builtin-rules/ai/spring-boot/ownership-scope-risk.rule.yaml +25 -0
  47. package/dist/builtin-rules/ai/spring-boot/pagination-risk.prompt.md +81 -0
  48. package/dist/builtin-rules/ai/spring-boot/pagination-risk.rule.yaml +25 -0
  49. package/dist/builtin-rules/ai/spring-boot/security-authorization-risk.prompt.md +75 -0
  50. package/dist/builtin-rules/ai/spring-boot/security-authorization-risk.rule.yaml +26 -0
  51. package/dist/builtin-rules/ai/spring-boot/security-mass-assignment-risk.prompt.md +75 -0
  52. package/dist/builtin-rules/ai/spring-boot/security-mass-assignment-risk.rule.yaml +24 -0
  53. package/dist/builtin-rules/ai/spring-boot/security-redirect-risk.prompt.md +74 -0
  54. package/dist/builtin-rules/ai/spring-boot/security-redirect-risk.rule.yaml +24 -0
  55. package/dist/builtin-rules/ai/spring-boot/security-sensitive-data-risk.prompt.md +75 -0
  56. package/dist/builtin-rules/ai/spring-boot/security-sensitive-data-risk.rule.yaml +25 -0
  57. package/dist/builtin-rules/ai/spring-boot/transaction-loop-risk.prompt.md +78 -0
  58. package/dist/builtin-rules/ai/spring-boot/transaction-loop-risk.rule.yaml +25 -0
  59. package/dist/builtin-rules/static/angular/component-prefix.rule.js +78 -0
  60. package/dist/builtin-rules/static/angular/image-control-alt-required.rule.js +105 -0
  61. package/dist/builtin-rules/static/angular/img-alt-required.rule.js +96 -0
  62. package/dist/builtin-rules/static/angular/inject-pattern.rule.js +47 -0
  63. package/dist/builtin-rules/static/angular/lifecycle-method-required.rule.js +59 -0
  64. package/dist/builtin-rules/static/angular/no-any-type.rule.yaml +55 -0
  65. package/dist/builtin-rules/static/angular/no-direct-dom-access.rule.js +191 -0
  66. package/dist/builtin-rules/static/angular/no-dom-xss.rule.js +48 -0
  67. package/dist/builtin-rules/static/angular/no-leaky-subscription.rule.js +197 -0
  68. package/dist/builtin-rules/static/angular/no-ngmodule.rule.yaml +44 -0
  69. package/dist/builtin-rules/static/angular/no-non-null-asserted-optional-chain.rule.js +53 -0
  70. package/dist/builtin-rules/static/angular/no-uncalled-signal-in-condition.rule.js +112 -0
  71. package/dist/builtin-rules/static/angular/observable-naming.rule.js +85 -0
  72. package/dist/builtin-rules/static/angular/onpush-required.rule.js +70 -0
  73. package/dist/builtin-rules/static/angular/standalone-component-required.rule.js +65 -0
  74. package/dist/builtin-rules/static/angular/template-dom-xss.rule.js +112 -0
  75. package/dist/builtin-rules/static/angular/template-syntax-modern.rule.js +154 -0
  76. package/dist/builtin-rules/static/angular/trackby-required.rule.js +66 -0
  77. package/dist/builtin-rules/static/flutter/android-exported-component.rule.js +75 -0
  78. package/dist/builtin-rules/static/flutter/android-manifest-hardening.rule.js +117 -0
  79. package/dist/builtin-rules/static/flutter/android-sensitive-permissions.rule.js +87 -0
  80. package/dist/builtin-rules/static/flutter/debug-tooling-release-risk.rule.js +90 -0
  81. package/dist/builtin-rules/static/flutter/dynamic-archive-risk.rule.js +96 -0
  82. package/dist/builtin-rules/static/flutter/hive-sensitive-storage.rule.js +77 -0
  83. package/dist/builtin-rules/static/flutter/ios-privacy-hardening.rule.js +119 -0
  84. package/dist/builtin-rules/static/flutter/packaged-env-risk.rule.js +95 -0
  85. package/dist/builtin-rules/static/flutter/sensitive-log-leak.rule.js +94 -0
  86. package/dist/builtin-rules/static/flutter/webview-bridge-guard.rule.js +102 -0
  87. package/dist/builtin-rules/static/general/file-too-long.rule.js +41 -0
  88. package/dist/builtin-rules/static/general/function-too-long.rule.js +72 -0
  89. package/dist/builtin-rules/static/general/no-circular-import.rule.js +39 -0
  90. package/dist/builtin-rules/static/general/no-code-injection.rule.js +48 -0
  91. package/dist/builtin-rules/static/general/no-console-log.rule.js +110 -0
  92. package/dist/builtin-rules/static/general/no-empty-catch.rule.yaml +56 -0
  93. package/dist/builtin-rules/static/general/no-hardcoded-secret.rule.js +517 -0
  94. package/dist/builtin-rules/static/general/no-magic-number.rule.js +78 -0
  95. package/dist/builtin-rules/static/general/no-open-redirect.rule.js +46 -0
  96. package/dist/builtin-rules/static/general/no-todo-comment.rule.yaml +30 -0
  97. package/dist/builtin-rules/static/general/no-unresolved-import-symbol.rule.js +80 -0
  98. package/dist/builtin-rules/static/general/no-unused-export.rule.js +140 -0
  99. package/dist/builtin-rules/static/spring-boot/no-autowired-field.rule.js +162 -0
  100. package/dist/builtin-rules/static/spring-boot/no-business-logic-in-controller.rule.js +94 -0
  101. package/dist/builtin-rules/static/spring-boot/no-command-injection.rule.js +47 -0
  102. package/dist/builtin-rules/static/spring-boot/no-entity-in-controller.rule.yaml +52 -0
  103. package/dist/builtin-rules/static/spring-boot/no-nplus1-query-in-loop.rule.js +106 -0
  104. package/dist/builtin-rules/static/spring-boot/no-path-traversal.rule.js +47 -0
  105. package/dist/builtin-rules/static/spring-boot/no-spel-injection.rule.js +41 -0
  106. package/dist/builtin-rules/static/spring-boot/no-sql-string-concat.rule.js +194 -0
  107. package/dist/builtin-rules/static/spring-boot/no-ssrf.rule.js +49 -0
  108. package/dist/builtin-rules/static/spring-boot/no-transactional-self-invocation.rule.js +142 -0
  109. package/dist/builtin-rules/static/spring-boot/no-unclosed-resource.rule.js +108 -0
  110. package/dist/builtin-rules/static/spring-boot/no-unsafe-shared-formatter.rule.js +118 -0
  111. package/dist/builtin-rules/static/spring-boot/repository-naming.rule.yaml +42 -0
  112. package/dist/builtin-rules/static/spring-boot/restful-naming.rule.yaml +39 -0
  113. package/dist/builtin-rules/static/spring-boot/transaction-on-service.rule.yaml +58 -0
  114. package/dist/builtin-rules/static/spring-boot/validate-input.rule.js +123 -0
  115. package/dist/builtin-rules/vauthz/static/spring-boot/require-authz-check.rule.js +101 -0
  116. package/dist/index.d.ts +224 -47
  117. package/dist/index.js +1183 -808
  118. package/package.json +3 -2
  119. package/src/migrations/0000_initial.sql +62 -0
  120. package/src/migrations/0001_add_confidence.sql +7 -0
  121. package/src/migrations/0002_add_ai_stats.sql +21 -0
  122. package/src/migrations/0003_add_fix_recipe.sql +29 -0
  123. package/src/migrations/0004_add_ast_graph.sql +61 -0
  124. package/src/migrations/0005_add_project_id.sql +1 -0
  125. package/src/migrations/0006_add_ai_model.sql +5 -0
  126. package/src/migrations/0006_add_rule_results.sql +1 -0
  127. package/src/migrations/0007_add_finding_metadata.sql +4 -0
  128. package/src/migrations/0008_add_coverage.sql +2 -0
  129. package/src/migrations/0009_run_provenance.sql +5 -0
@@ -0,0 +1,80 @@
1
+ // builtin-rules/static/general/no-unresolved-import-symbol.rule.ts
2
+ var checkedKinds = /* @__PURE__ */ new Set([
3
+ "import",
4
+ "re-export",
5
+ "type-re-export",
6
+ "uses-type"
7
+ ]);
8
+ var ignoredSymbols = /* @__PURE__ */ new Set(["*", "default"]);
9
+ var exportSurfaceKinds = ["re-export", "type-re-export"];
10
+ var edgeSymbols = (edge) => {
11
+ if (!edge.symbol) return [];
12
+ if (edge.symbol === "default" && (edge.kind === "re-export" || edge.kind === "type-re-export")) {
13
+ return ["default"];
14
+ }
15
+ if (ignoredSymbols.has(edge.symbol)) return [];
16
+ return [edge.symbol];
17
+ };
18
+ var exportedNamesFor = (graph, path) => {
19
+ const names = /* @__PURE__ */ new Set();
20
+ const node = graph.getNode(path);
21
+ for (const symbol of node?.symbols ?? []) {
22
+ if (symbol.exported) names.add(symbol.name);
23
+ }
24
+ let hasWildcardReExport = false;
25
+ for (const kind of exportSurfaceKinds) {
26
+ for (const edge of graph.outgoing(path, kind)) {
27
+ if (edge.symbol === "*") {
28
+ hasWildcardReExport = true;
29
+ continue;
30
+ }
31
+ if (edge.alias) names.add(edge.alias);
32
+ else if (edge.symbol) names.add(edge.symbol);
33
+ }
34
+ }
35
+ return { names, hasWildcardReExport };
36
+ };
37
+ var rule = {
38
+ id: "general/no-unresolved-import-symbol",
39
+ version: 8,
40
+ kind: "static-ts",
41
+ title: "Khong import/re-export symbol khong duoc export",
42
+ description: "Named import/re-export noi bo phai tro toi symbol ma target file that su export; rule nay bo qua default, namespace, side-effect import va wildcard re-export de tranh false positive.",
43
+ severity: "error",
44
+ category: "correctness",
45
+ languages: ["typescript", "javascript"],
46
+ scope: "general",
47
+ requires: "semantic-ts",
48
+ usesAstGraph: true,
49
+ baseConfidence: 90,
50
+ check(ctx) {
51
+ const graph = ctx.astGraph;
52
+ if (!graph) return [];
53
+ const findings = [];
54
+ const seen = /* @__PURE__ */ new Set();
55
+ for (const edge of graph.outgoing(ctx.file.path)) {
56
+ if (!checkedKinds.has(edge.kind)) continue;
57
+ const exported = exportedNamesFor(graph, edge.toPath);
58
+ if (exported.hasWildcardReExport) continue;
59
+ for (const symbol of edgeSymbols(edge)) {
60
+ if (exported.names.has(symbol)) continue;
61
+ const key = `${edge.toPath}\0${symbol}`;
62
+ if (seen.has(key)) continue;
63
+ seen.add(key);
64
+ const action = edge.kind === "re-export" || edge.kind === "type-re-export" ? "Re-exported" : "Imported";
65
+ findings.push({
66
+ message: `${action} symbol '${symbol}' is not exported by '${edge.toPath}'.`,
67
+ file: ctx.file.path,
68
+ range: { line: 1, column: 1 },
69
+ suggestion: "Fix the imported/re-exported name, export it from the target module, or reference the module that owns the symbol.",
70
+ confidence: edge.kind === "uses-type" ? 88 : 92
71
+ });
72
+ }
73
+ }
74
+ return findings;
75
+ }
76
+ };
77
+
78
+ export { rule };
79
+ //# sourceMappingURL=no-unresolved-import-symbol.rule.js.map
80
+ //# sourceMappingURL=no-unresolved-import-symbol.rule.js.map
@@ -0,0 +1,140 @@
1
+ // builtin-rules/static/general/no-unused-export.rule.ts
2
+ var DEFAULT_SKIP_PATHS = [
3
+ "**/index.ts",
4
+ "**/index.tsx",
5
+ "**/index.js",
6
+ "**/index.jsx",
7
+ "**/public-api.ts",
8
+ "**/public_api.ts",
9
+ "**/*.d.ts",
10
+ "**/main.ts",
11
+ "**/main.tsx",
12
+ "**/*.module.ts",
13
+ "**/*.routes.ts",
14
+ "**/*.config.ts",
15
+ "**/test-setup.ts",
16
+ "**/jest-setup.ts",
17
+ "**/vitest-setup.ts"
18
+ ];
19
+ var DEFAULTS = {
20
+ skipPaths: DEFAULT_SKIP_PATHS,
21
+ includeDefaultExports: false,
22
+ includeOrphanFiles: false
23
+ };
24
+ var REGEX_SPECIAL = new Set(".+^$()|[]\\".split(""));
25
+ var globToRegex = (pattern) => {
26
+ let out = "^";
27
+ let i = 0;
28
+ while (i < pattern.length) {
29
+ const c = pattern[i];
30
+ if (c === "*" && pattern[i + 1] === "*" && pattern[i + 2] === "/") {
31
+ out += "(?:.*/)?";
32
+ i += 3;
33
+ continue;
34
+ }
35
+ if (c === "/" && pattern[i + 1] === "*" && pattern[i + 2] === "*" && i + 3 === pattern.length) {
36
+ out += "(?:/.*)?";
37
+ i += 3;
38
+ continue;
39
+ }
40
+ if (c === "*" && pattern[i + 1] === "*") {
41
+ out += ".*";
42
+ i += 2;
43
+ continue;
44
+ }
45
+ if (c === "*") {
46
+ out += "[^/]*";
47
+ i += 1;
48
+ continue;
49
+ }
50
+ if (c === "?") {
51
+ out += "[^/]";
52
+ i += 1;
53
+ continue;
54
+ }
55
+ if (c !== void 0 && REGEX_SPECIAL.has(c)) {
56
+ out += `\\${c}`;
57
+ i += 1;
58
+ continue;
59
+ }
60
+ out += c ?? "";
61
+ i += 1;
62
+ }
63
+ return new RegExp(`${out}$`);
64
+ };
65
+ var compilePatterns = (patterns) => patterns.map(globToRegex);
66
+ var matchesAny = (filePath, regexes) => {
67
+ for (const re of regexes) if (re.test(filePath)) return true;
68
+ return false;
69
+ };
70
+ var CONSUMING_KINDS = /* @__PURE__ */ new Set([
71
+ "import",
72
+ "re-export",
73
+ "type-re-export",
74
+ "uses-type"
75
+ ]);
76
+ var incomingHasOpaque = (edges) => {
77
+ for (const edge of edges) {
78
+ if (!CONSUMING_KINDS.has(edge.kind)) continue;
79
+ if (edge.symbol === "*") return true;
80
+ }
81
+ return false;
82
+ };
83
+ var consumedNames = (graph, targetPath) => {
84
+ const names = /* @__PURE__ */ new Set();
85
+ for (const edge of graph.incoming(targetPath)) {
86
+ if (!CONSUMING_KINDS.has(edge.kind)) continue;
87
+ if (edge.symbol && edge.symbol !== "*") names.add(edge.symbol);
88
+ }
89
+ return names;
90
+ };
91
+ var rule = {
92
+ id: "general/no-unused-export",
93
+ version: 1,
94
+ kind: "static-ts",
95
+ title: "Kh\xF4ng export symbol n\u1EBFu kh\xF4ng ai d\xF9ng",
96
+ description: "Symbol \u0111\u01B0\u1EE3c export nh\u01B0ng kh\xF4ng c\xF3 file n\xE0o trong project import l\u1EA1i. Conservative: b\u1ECF qua wildcard re-export targets, default exports (m\u1EB7c \u0111\u1ECBnh), orphan files, v\xE0 c\xE1c public-API/entry-point conventions (index.ts, public-api.ts, *.module.ts, *.routes.ts, *.d.ts, ...).",
97
+ severity: "info",
98
+ category: "maintainability",
99
+ languages: ["typescript", "javascript"],
100
+ scope: "general",
101
+ requires: "semantic-ts",
102
+ usesAstGraph: true,
103
+ baseConfidence: 65,
104
+ defaultOptions: DEFAULTS,
105
+ check(ctx) {
106
+ const graph = ctx.astGraph;
107
+ if (!graph) return [];
108
+ const options = {
109
+ skipPaths: ctx.options.skipPaths ?? DEFAULTS.skipPaths,
110
+ includeDefaultExports: ctx.options.includeDefaultExports ?? DEFAULTS.includeDefaultExports,
111
+ includeOrphanFiles: ctx.options.includeOrphanFiles ?? DEFAULTS.includeOrphanFiles
112
+ };
113
+ const skipRegexes = compilePatterns(options.skipPaths);
114
+ if (matchesAny(ctx.file.path, skipRegexes)) return [];
115
+ const node = graph.getNode(ctx.file.path);
116
+ if (!node?.symbols || node.symbols.length === 0) return [];
117
+ const incoming = graph.incoming(ctx.file.path);
118
+ if (incomingHasOpaque(incoming)) return [];
119
+ const hasAnyIncomingEdge = incoming.some((e) => CONSUMING_KINDS.has(e.kind));
120
+ if (!hasAnyIncomingEdge && !options.includeOrphanFiles) return [];
121
+ const consumed = consumedNames(graph, ctx.file.path);
122
+ const findings = [];
123
+ for (const symbol of node.symbols) {
124
+ if (!symbol.exported) continue;
125
+ if (symbol.name === "default" && !options.includeDefaultExports) continue;
126
+ if (consumed.has(symbol.name)) continue;
127
+ findings.push({
128
+ message: `Exported ${symbol.kind} '${symbol.name}' is not imported by any file in the project.`,
129
+ file: ctx.file.path,
130
+ range: { line: 1, column: 1 },
131
+ suggestion: "Remove the export, mark the symbol non-exported (file-local), or move it behind the public API barrel that consumers actually import."
132
+ });
133
+ }
134
+ return findings;
135
+ }
136
+ };
137
+
138
+ export { rule };
139
+ //# sourceMappingURL=no-unused-export.rule.js.map
140
+ //# sourceMappingURL=no-unused-export.rule.js.map
@@ -0,0 +1,162 @@
1
+ import { asTreeSitterTree } from '@code-sentinel/parsers';
2
+
3
+ // builtin-rules/static/spring-boot/no-autowired-field.rule.ts
4
+ var INJECTION_ANNOTATIONS = /* @__PURE__ */ new Set(["Autowired", "Inject", "Resource"]);
5
+ function* walk(node, type) {
6
+ const stack = [node];
7
+ while (stack.length > 0) {
8
+ const cur = stack.pop();
9
+ if (!cur) continue;
10
+ if (cur.type === type) yield cur;
11
+ for (let i = cur.namedChildCount - 1; i >= 0; i--) {
12
+ const child = cur.namedChild(i);
13
+ if (child) stack.push(child);
14
+ }
15
+ }
16
+ }
17
+ function* namedChildren(node) {
18
+ for (let i = 0; i < node.namedChildCount; i++) {
19
+ const child = node.namedChild(i);
20
+ if (child) yield child;
21
+ }
22
+ }
23
+ var toEdit = (filePath, start, end, newText) => ({
24
+ file: filePath,
25
+ startLine: start.startPosition.row + 1,
26
+ startColumn: start.startPosition.column + 1,
27
+ endLine: end.endPosition.row + 1,
28
+ endColumn: end.endPosition.column + 1,
29
+ newText
30
+ });
31
+ var insertionEdit = (filePath, line, column, newText) => ({
32
+ file: filePath,
33
+ startLine: line,
34
+ startColumn: column,
35
+ endLine: line,
36
+ endColumn: column,
37
+ newText
38
+ });
39
+ var collectInjectedFields = (classNode) => {
40
+ const out = [];
41
+ for (const field of walk(classNode, "field_declaration")) {
42
+ const modifiers = [...namedChildren(field)].find((child) => child.type === "modifiers");
43
+ if (!modifiers) continue;
44
+ for (const mod of namedChildren(modifiers)) {
45
+ if (mod.type !== "marker_annotation" && mod.type !== "annotation") continue;
46
+ const nameNode = mod.childForFieldName("name");
47
+ const annotationName = nameNode?.text;
48
+ if (!annotationName || !INJECTION_ANNOTATIONS.has(annotationName)) continue;
49
+ out.push({ fieldNode: field, annotationNode: mod, annotationName });
50
+ break;
51
+ }
52
+ }
53
+ return out;
54
+ };
55
+ var classHasConstructor = (classNode) => {
56
+ for (const ctor of walk(classNode, "constructor_declaration")) {
57
+ if (ctor.startIndex > classNode.startIndex && ctor.endIndex < classNode.endIndex) return true;
58
+ }
59
+ return false;
60
+ };
61
+ var parseSimplePrivateField = (fieldNode) => {
62
+ const normalized = fieldNode.text.replace(/\r\n/g, "\n").trim();
63
+ const match = /^@(Autowired|Inject|Resource)\s*\n\s*private\s+([A-Za-z_$][\w$<>\[\].?,\s]*)\s+([A-Za-z_$][\w$]*)\s*;$/.exec(
64
+ normalized
65
+ );
66
+ const typeText = match?.[2]?.replace(/\s+/g, " ").trim();
67
+ const name = match?.[3];
68
+ if (!typeText || !name) return void 0;
69
+ return { typeText, name };
70
+ };
71
+ var memberIndentForClass = (classNode) => {
72
+ const body = classNode.childForFieldName("body");
73
+ if (!body) return " ";
74
+ const match = /\n([ \t]*)\S/.exec(body.text);
75
+ return match?.[1] ?? " ";
76
+ };
77
+ var className = (classNode) => classNode.childForFieldName("name")?.text;
78
+ var closingBracePosition = (body) => {
79
+ const closeIndex = body.text.lastIndexOf("}");
80
+ if (closeIndex === -1) return void 0;
81
+ const beforeClose = body.text.slice(0, closeIndex);
82
+ const lines = beforeClose.split(/\r?\n/);
83
+ const lineOffset = lines.length - 1;
84
+ const lastLine = lines[lines.length - 1] ?? "";
85
+ return {
86
+ line: body.startPosition.row + lineOffset + 1,
87
+ column: (lineOffset === 0 ? body.startPosition.column : 0) + lastLine.length + 1
88
+ };
89
+ };
90
+ var buildFix = (args) => {
91
+ if (args.injectedFields.length !== 1) return void 0;
92
+ if (args.injectedFields[0]?.fieldNode.startIndex !== args.currentField.fieldNode.startIndex)
93
+ return void 0;
94
+ if (classHasConstructor(args.classNode)) return void 0;
95
+ const simple = parseSimplePrivateField(args.currentField.fieldNode);
96
+ const clsName = className(args.classNode);
97
+ const body = args.classNode.childForFieldName("body");
98
+ if (!simple || !clsName || !body) return void 0;
99
+ const insertAt = closingBracePosition(body);
100
+ if (!insertAt) return void 0;
101
+ const indent = memberIndentForClass(args.classNode);
102
+ const constructorText = `
103
+
104
+ ${indent}public ${clsName}(${simple.typeText} ${simple.name}) {
105
+ ${indent} this.${simple.name} = ${simple.name};
106
+ ${indent}}`;
107
+ return {
108
+ safety: "unsafe",
109
+ description: "Convert simple field injection to constructor injection",
110
+ edits: [
111
+ toEdit(
112
+ args.filePath,
113
+ args.currentField.fieldNode,
114
+ args.currentField.fieldNode,
115
+ `private final ${simple.typeText} ${simple.name};`
116
+ ),
117
+ insertionEdit(args.filePath, insertAt.line, insertAt.column, constructorText)
118
+ ]
119
+ };
120
+ };
121
+ var rule = {
122
+ id: "spring-boot/no-autowired-field",
123
+ version: 2,
124
+ kind: "static-ts",
125
+ title: "Avoid field injection - use constructor injection",
126
+ description: "Field injection hides dependencies, blocks final fields, and makes tests harder. Constructor injection keeps dependencies explicit and immutable.",
127
+ severity: "warning",
128
+ category: "spring-boot-best-practice",
129
+ languages: ["java"],
130
+ scope: "spring-boot",
131
+ requires: "syntactic",
132
+ baseConfidence: 95,
133
+ check(ctx) {
134
+ const tree = asTreeSitterTree(ctx.parsed);
135
+ const findings = [];
136
+ for (const cls of walk(tree.rootNode, "class_declaration")) {
137
+ const injectedFields = collectInjectedFields(cls);
138
+ for (const injected of injectedFields) {
139
+ findings.push({
140
+ message: `Field injection via @${injected.annotationName} - prefer constructor injection.`,
141
+ file: ctx.file.path,
142
+ range: {
143
+ line: injected.annotationNode.startPosition.row + 1,
144
+ column: injected.annotationNode.startPosition.column + 1
145
+ },
146
+ suggestion: "Declare the dependency as `private final`, add a constructor parameter, and assign it in the constructor. Spring 4.3+ autowires a single constructor without @Autowired.",
147
+ fix: buildFix({
148
+ classNode: cls,
149
+ injectedFields,
150
+ currentField: injected,
151
+ filePath: ctx.file.path
152
+ })
153
+ });
154
+ }
155
+ }
156
+ return findings;
157
+ }
158
+ };
159
+
160
+ export { rule };
161
+ //# sourceMappingURL=no-autowired-field.rule.js.map
162
+ //# sourceMappingURL=no-autowired-field.rule.js.map
@@ -0,0 +1,94 @@
1
+ import { asTreeSitterTree } from '@code-sentinel/parsers';
2
+
3
+ // builtin-rules/static/spring-boot/no-business-logic-in-controller.rule.ts
4
+ var CONTROLLER_ANNOTATIONS = /* @__PURE__ */ new Set(["RestController", "Controller"]);
5
+ function* walk(node, type) {
6
+ const stack = [node];
7
+ while (stack.length > 0) {
8
+ const cur = stack.pop();
9
+ if (!cur) continue;
10
+ if (cur.type === type) yield cur;
11
+ for (let i = cur.namedChildCount - 1; i >= 0; i--) {
12
+ const child = cur.namedChild(i);
13
+ if (child) stack.push(child);
14
+ }
15
+ }
16
+ }
17
+ function* directMethods(classNode) {
18
+ const body = classNode.childForFieldName("body");
19
+ if (!body) return;
20
+ for (let i = 0; i < body.namedChildCount; i++) {
21
+ const child = body.namedChild(i);
22
+ if (child?.type === "method_declaration") yield child;
23
+ }
24
+ }
25
+ var collectAnnotationNames = (node) => {
26
+ const names = /* @__PURE__ */ new Set();
27
+ for (let i = 0; i < node.namedChildCount; i++) {
28
+ const child = node.namedChild(i);
29
+ if (!child) continue;
30
+ if (child.type !== "modifiers") continue;
31
+ for (let j = 0; j < child.namedChildCount; j++) {
32
+ const mod = child.namedChild(j);
33
+ if (!mod) continue;
34
+ if (mod.type !== "marker_annotation" && mod.type !== "annotation") continue;
35
+ const nameNode = mod.childForFieldName("name");
36
+ if (nameNode) names.add(nameNode.text);
37
+ }
38
+ }
39
+ return names;
40
+ };
41
+ var isControllerClass = (classNode) => {
42
+ for (const a of collectAnnotationNames(classNode)) {
43
+ if (CONTROLLER_ANNOTATIONS.has(a)) return true;
44
+ }
45
+ return false;
46
+ };
47
+ var getMethodName = (method) => {
48
+ const nameNode = method.childForFieldName("name");
49
+ return nameNode?.text ?? "<anonymous>";
50
+ };
51
+ var rule = {
52
+ id: "spring-boot/no-business-logic-in-controller",
53
+ version: 3,
54
+ kind: "static-ts",
55
+ title: "Controller method qu\xE1 d\xE0i \u2014 nghi ng\u1EDD business logic l\u1EABn v\xE0o",
56
+ description: "Controller method d\xE0i th\u01B0\u1EDDng g\xE1nh business logic v\u1ED1n thu\u1ED9c Service. T\xE1ch helper / Service method ra \u0111\u1EC3 controller ch\u1EC9 orchestrate: validate input \u2192 call Service \u2192 return response. Threshold m\u1EB7c \u0111\u1ECBnh 30 d\xF2ng \u2014 tune qua `options.maxLines`.",
57
+ severity: "warning",
58
+ category: "architecture",
59
+ languages: ["java"],
60
+ scope: "spring-boot",
61
+ requires: "syntactic",
62
+ baseConfidence: 70,
63
+ defaultOptions: { maxLines: 30 },
64
+ check(ctx) {
65
+ const threshold = ctx.options.maxLines;
66
+ const tree = asTreeSitterTree(ctx.parsed);
67
+ const findings = [];
68
+ for (const cls of walk(tree.rootNode, "class_declaration")) {
69
+ if (!isControllerClass(cls)) continue;
70
+ for (const method of directMethods(cls)) {
71
+ const body = method.childForFieldName("body");
72
+ if (!body) continue;
73
+ const startLine = body.startPosition.row + 1;
74
+ const endLine = body.endPosition.row + 1;
75
+ const lineCount = endLine - startLine + 1;
76
+ if (lineCount <= threshold) continue;
77
+ findings.push({
78
+ message: `Controller method "${getMethodName(method)}" d\xE0i ${lineCount} d\xF2ng (gi\u1EDBi h\u1EA1n ${threshold}) \u2014 nghi business logic l\u1EABn v\xE0o.`,
79
+ file: ctx.file.path,
80
+ range: {
81
+ line: method.startPosition.row + 1,
82
+ column: method.startPosition.column + 1
83
+ },
84
+ suggestion: "T\xE1ch logic sang Service method; controller ch\u1EC9 validate + delegate + return."
85
+ });
86
+ }
87
+ }
88
+ return findings;
89
+ }
90
+ };
91
+
92
+ export { rule };
93
+ //# sourceMappingURL=no-business-logic-in-controller.rule.js.map
94
+ //# sourceMappingURL=no-business-logic-in-controller.rule.js.map
@@ -0,0 +1,47 @@
1
+ // builtin-rules/static/spring-boot/no-command-injection.rule.ts
2
+ var COMMAND_INJECTION_SINK_IDS = /* @__PURE__ */ new Set([
3
+ "spring/runtime-exec",
4
+ "spring/process-builder-command",
5
+ "spring/process-builder-ctor"
6
+ ]);
7
+ var SINK_LABEL = {
8
+ "spring/runtime-exec": "Runtime.exec(...)",
9
+ "spring/process-builder-command": "ProcessBuilder.command(...)",
10
+ "spring/process-builder-ctor": "new ProcessBuilder(...)"
11
+ };
12
+ var rule = {
13
+ id: "spring-boot/no-command-injection",
14
+ version: 2,
15
+ kind: "static-ts",
16
+ title: "Kh\xF4ng ch\u1EA1y l\u1EC7nh h\u1EC7 th\u1ED1ng t\u1EEB d\u1EEF li\u1EC7u ch\u01B0a ki\u1EC3m so\xE1t (OS Command Injection)",
17
+ description: "D\u1EEF li\u1EC7u t\u1EEB request (@RequestParam, @PathVariable, @RequestBody, @RequestHeader, HttpServletRequest, \u2026) ch\u1EA3y th\u1EB3ng v\xE0o l\u1EC7nh h\u1EC7 \u0111i\u1EC1u h\xE0nh (`Runtime.getRuntime().exec(...)` ho\u1EB7c `ProcessBuilder.command(...)`) l\xE0 l\u1ED7 h\u1ED5ng OS Command Injection (CWE-78) \u2014 k\u1EBB t\u1EA5n c\xF4ng ch\xE8n \u0111\u01B0\u1EE3c l\u1EC7nh shell t\xF9y \xFD ch\u1EA1y tr\xEAn server (RCE). Rule d\xF9ng taint analysis (Tier-1 li\xEAn th\u1EE7 t\u1EE5c trong c\xF9ng method) \u0111\u1EC3 truy v\u1EBFt lu\u1ED3ng d\u1EEF li\u1EC7u. Kh\u1EAFc ph\u1EE5c: tr\xE1nh g\u1ECDi shell; n\u1EBFu b\u1EAFt bu\u1ED9c, d\xF9ng allowlist l\u1EC7nh/tham s\u1ED1 c\u1ED1 \u0111\u1ECBnh v\xE0 truy\u1EC1n d\u1EA1ng m\u1EA3ng tham s\u1ED1 (kh\xF4ng n\u1ED1i chu\u1ED7i v\xE0o `sh -c`), kh\xF4ng bao gi\u1EDD d\u1EF1ng l\u1EC7nh t\u1EEB gi\xE1 tr\u1ECB do ng\u01B0\u1EDDi d\xF9ng nh\u1EADp.",
18
+ severity: "error",
19
+ category: "security",
20
+ languages: ["java"],
21
+ scope: "spring-boot",
22
+ requires: "syntactic",
23
+ usesTaint: true,
24
+ baseConfidence: 80,
25
+ check(ctx) {
26
+ const findings = [];
27
+ for (const tf of ctx.taintFindings ?? []) {
28
+ if (!COMMAND_INJECTION_SINK_IDS.has(tf.sinkId)) continue;
29
+ const sources = [...new Set(tf.sourceIds)].join(", ");
30
+ const laundered = (tf.path?.length ?? 0) > 0;
31
+ const sinkLabel = SINK_LABEL[tf.sinkId] ?? tf.sinkId;
32
+ const trace = laundered ? " (truy v\u1EBFt li\xEAn th\u1EE7 t\u1EE5c)" : "";
33
+ findings.push({
34
+ message: `\u26A0 Command Injection: d\u1EEF li\u1EC7u ch\u01B0a ki\u1EC3m so\xE1t (${sources}) ch\u1EA3y v\xE0o ${sinkLabel} \u2014 k\u1EBB t\u1EA5n c\xF4ng c\xF3 th\u1EC3 ch\u1EA1y l\u1EC7nh h\u1EC7 th\u1ED1ng t\xF9y \xFD tr\xEAn server (RCE).${trace}`,
35
+ file: ctx.file.path,
36
+ range: { line: tf.line, column: tf.column ?? 1 },
37
+ confidence: laundered ? 75 : 85,
38
+ suggestion: 'Tr\xE1nh g\u1ECDi shell v\u1EDBi d\u1EEF li\u1EC7u ng\u01B0\u1EDDi d\xF9ng. N\u1EBFu b\u1EAFt bu\u1ED9c: validate b\u1EB1ng allowlist l\u1EC7nh/tham s\u1ED1 c\u1ED1 \u0111\u1ECBnh, truy\u1EC1n tham s\u1ED1 d\u1EA1ng m\u1EA3ng (`new ProcessBuilder(List.of("cmd", arg))`) thay v\xEC n\u1ED1i chu\u1ED7i v\xE0o `sh -c`. Tuy\u1EC7t \u0111\u1ED1i kh\xF4ng d\u1EF1ng l\u1EC7nh t\u1EEB gi\xE1 tr\u1ECB do ng\u01B0\u1EDDi d\xF9ng nh\u1EADp.'
39
+ });
40
+ }
41
+ return findings;
42
+ }
43
+ };
44
+
45
+ export { rule };
46
+ //# sourceMappingURL=no-command-injection.rule.js.map
47
+ //# sourceMappingURL=no-command-injection.rule.js.map
@@ -0,0 +1,52 @@
1
+ id: spring-boot/no-entity-in-controller
2
+ # version: 2 (Quality Roadmap A2 mở rộng) — exclude Spring HTTP wrapper types
3
+ # whose name merely ends in "Entity" (ResponseEntity / HttpEntity /
4
+ # RequestEntity). These are transport types, not JPA entities, so flagging a
5
+ # method returning a raw `ResponseEntity` was a false positive.
6
+ version: 2
7
+ kind: static-yaml
8
+ title: "Controller không nên trả về Entity — dùng DTO"
9
+ description: |
10
+ Trả Entity trực tiếp ra HTTP response gây 3 vấn đề:
11
+ - Lộ schema database (Hibernate lazy fields, FK chains) ra client.
12
+ - Coupling tight giữa API contract và data model — khó evolve schema.
13
+ - Khả năng infinite recursion khi serialize quan hệ 2 chiều.
14
+
15
+ Pattern đúng: định nghĩa DTO/ViewModel/Response class riêng, dùng
16
+ mapper (MapStruct / manual) chuyển Entity → DTO trong Service.
17
+
18
+ Phase 8 đơn giản: trong class có annotation `@RestController` hoặc
19
+ `@Controller`, flag method có return type là `type_identifier` mà tên
20
+ kết thúc bằng `Entity`. Không bắt được return wrapped trong generic
21
+ (vd `ResponseEntity<UserEntity>`) — limitation đã biết, sẽ improve sau.
22
+ severity: warning
23
+ category: api-design
24
+ languages: [java]
25
+ scope: spring-boot
26
+ baseConfidence: 75
27
+ detection:
28
+ type: tree-sitter
29
+ captureName: violation
30
+ query: |
31
+ (class_declaration
32
+ (modifiers (marker_annotation name: (identifier) @ann))
33
+ body: (class_body
34
+ (method_declaration
35
+ type: (type_identifier) @violation)))
36
+ (#match? @ann "^(RestController|Controller)$")
37
+ (#match? @violation "^(?!(Response|Http|Request)Entity$).*Entity$")
38
+ message: "Controller trả về Entity — đổi sang DTO để tách API contract khỏi data model."
39
+ suggestion: "Tạo UserDto / UserResponse class riêng; chuyển Entity → DTO trong Service trước khi trả về controller."
40
+ examples:
41
+ good: |
42
+ @RestController
43
+ public class UserController {
44
+ @GetMapping("/users/{id}")
45
+ public UserDto getUser(@PathVariable Long id) { return service.findDto(id); }
46
+ }
47
+ bad: |
48
+ @RestController
49
+ public class UserController {
50
+ @GetMapping("/users/{id}")
51
+ public UserEntity getUser(@PathVariable Long id) { return repo.findById(id); }
52
+ }
@@ -0,0 +1,106 @@
1
+ import { asTreeSitterTree } from '@code-sentinel/parsers';
2
+
3
+ // builtin-rules/static/spring-boot/no-nplus1-query-in-loop.rule.ts
4
+ var LOOP_TYPES = /* @__PURE__ */ new Set([
5
+ "for_statement",
6
+ "enhanced_for_statement",
7
+ "while_statement",
8
+ "do_statement"
9
+ ]);
10
+ var SCOPE_BOUNDARIES = /* @__PURE__ */ new Set([
11
+ "lambda_expression",
12
+ "method_declaration",
13
+ "constructor_declaration",
14
+ "class_declaration",
15
+ "interface_declaration",
16
+ "record_declaration"
17
+ ]);
18
+ var REPO_SUFFIX = /(repository|repositories|repo|dao)$/i;
19
+ var REPO_ACCESSORS = /* @__PURE__ */ new Set([
20
+ "entitymanager",
21
+ "em",
22
+ "jdbctemplate",
23
+ "namedparameterjdbctemplate",
24
+ "mongotemplate",
25
+ "jpaqueryfactory",
26
+ "queryfactory",
27
+ "dslcontext"
28
+ ]);
29
+ var WRITE_PREFIX = /^(save|delete|persist|merge|remove|update|insert|flush)/i;
30
+ var OBJECT_METHODS = /* @__PURE__ */ new Set([
31
+ "getclass",
32
+ "hashcode",
33
+ "equals",
34
+ "tostring",
35
+ "wait",
36
+ "notify",
37
+ "notifyall"
38
+ ]);
39
+ function* walk(node, type) {
40
+ const stack = [node];
41
+ while (stack.length > 0) {
42
+ const cur = stack.pop();
43
+ if (!cur) continue;
44
+ if (cur.type === type) yield cur;
45
+ for (let i = cur.namedChildCount - 1; i >= 0; i--) {
46
+ const child = cur.namedChild(i);
47
+ if (child) stack.push(child);
48
+ }
49
+ }
50
+ }
51
+ function isInLoopBody(call) {
52
+ let cur = call.parent;
53
+ while (cur) {
54
+ if (LOOP_TYPES.has(cur.type)) return true;
55
+ if (SCOPE_BOUNDARIES.has(cur.type)) return false;
56
+ cur = cur.parent;
57
+ }
58
+ return false;
59
+ }
60
+ function receiverName(call) {
61
+ const obj = call.childForFieldName("object");
62
+ if (!obj) return null;
63
+ if (obj.type === "identifier") return obj.text;
64
+ if (obj.type === "field_access") return obj.childForFieldName("field")?.text ?? null;
65
+ return null;
66
+ }
67
+ var isRepositoryReceiver = (name) => REPO_SUFFIX.test(name) || REPO_ACCESSORS.has(name.toLowerCase());
68
+ var isQueryMethod = (name) => !WRITE_PREFIX.test(name) && !OBJECT_METHODS.has(name.toLowerCase());
69
+ var rule = {
70
+ id: "spring-boot/no-nplus1-query-in-loop",
71
+ version: 1,
72
+ kind: "static-ts",
73
+ title: "Query repository trong v\xF2ng l\u1EB7p \u2014 nguy c\u01A1 N+1",
74
+ description: "G\u1ECDi query l\xEAn repository/EntityManager b\xEAn trong v\xF2ng l\u1EB7p khi\u1EBFn m\u1ED7i ph\u1EA7n t\u1EED ph\xE1t sinh m\u1ED9t c\xE2u truy v\u1EA5n ri\xEAng (N+1): 1 query l\u1EA5y list + N query trong loop. Thay b\u1EB1ng m\u1ED9t truy v\u1EA5n g\u1ED9p \u2014 `JOIN FETCH` / `@EntityGraph`, m\u1ED9t derived query nh\u1EADn `Collection<Id>` (`findAllByIdIn(...)`), ho\u1EB7c gom id r\u1ED3i truy v\u1EA5n m\u1ED9t l\u1EA7n ngo\xE0i loop.",
75
+ severity: "warning",
76
+ category: "performance",
77
+ languages: ["java"],
78
+ scope: "spring-boot",
79
+ requires: "syntactic",
80
+ baseConfidence: 70,
81
+ check(ctx) {
82
+ const tree = asTreeSitterTree(ctx.parsed);
83
+ const findings = [];
84
+ for (const call of walk(tree.rootNode, "method_invocation")) {
85
+ if (!isInLoopBody(call)) continue;
86
+ const receiver = receiverName(call);
87
+ if (!receiver || !isRepositoryReceiver(receiver)) continue;
88
+ const method = call.childForFieldName("name")?.text;
89
+ if (!method || !isQueryMethod(method)) continue;
90
+ findings.push({
91
+ message: `Query \`${receiver}.${method}(...)\` n\u1EB1m trong v\xF2ng l\u1EB7p \u2014 m\u1ED7i v\xF2ng ph\xE1t sinh m\u1ED9t truy v\u1EA5n (nguy c\u01A1 N+1).`,
92
+ file: ctx.file.path,
93
+ range: {
94
+ line: call.startPosition.row + 1,
95
+ column: call.startPosition.column + 1
96
+ },
97
+ suggestion: "G\u1ED9p th\xE0nh m\u1ED9t truy v\u1EA5n ngo\xE0i loop: `JOIN FETCH`/`@EntityGraph`, ho\u1EB7c gom id r\u1ED3i g\u1ECDi `findAllByIdIn(ids)` m\u1ED9t l\u1EA7n thay v\xEC query t\u1EEBng ph\u1EA7n t\u1EED."
98
+ });
99
+ }
100
+ return findings;
101
+ }
102
+ };
103
+
104
+ export { rule };
105
+ //# sourceMappingURL=no-nplus1-query-in-loop.rule.js.map
106
+ //# sourceMappingURL=no-nplus1-query-in-loop.rule.js.map