@codepulse-oss/core 2.0.1 → 3.1.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.
Files changed (128) hide show
  1. package/dist/__tests__/all-wasm-languages.test.d.ts +2 -0
  2. package/dist/__tests__/all-wasm-languages.test.d.ts.map +1 -0
  3. package/dist/__tests__/all-wasm-languages.test.js +158 -0
  4. package/dist/__tests__/all-wasm-languages.test.js.map +1 -0
  5. package/dist/__tests__/v3-architecture.test.d.ts +2 -0
  6. package/dist/__tests__/v3-architecture.test.d.ts.map +1 -0
  7. package/dist/__tests__/v3-architecture.test.js +168 -0
  8. package/dist/__tests__/v3-architecture.test.js.map +1 -0
  9. package/dist/__tests__/v3.1-intelligence.test.d.ts +2 -0
  10. package/dist/__tests__/v3.1-intelligence.test.d.ts.map +1 -0
  11. package/dist/__tests__/v3.1-intelligence.test.js +208 -0
  12. package/dist/__tests__/v3.1-intelligence.test.js.map +1 -0
  13. package/dist/ai/privacy-firewall.d.ts +32 -0
  14. package/dist/ai/privacy-firewall.d.ts.map +1 -0
  15. package/dist/ai/privacy-firewall.js +143 -0
  16. package/dist/ai/privacy-firewall.js.map +1 -0
  17. package/dist/ai/provider.d.ts +50 -0
  18. package/dist/ai/provider.d.ts.map +1 -1
  19. package/dist/ai/provider.js +247 -24
  20. package/dist/ai/provider.js.map +1 -1
  21. package/dist/audit/archeology.d.ts +34 -0
  22. package/dist/audit/archeology.d.ts.map +1 -0
  23. package/dist/audit/archeology.js +162 -0
  24. package/dist/audit/archeology.js.map +1 -0
  25. package/dist/audit/architecture-guard.d.ts +35 -0
  26. package/dist/audit/architecture-guard.d.ts.map +1 -0
  27. package/dist/audit/architecture-guard.js +213 -0
  28. package/dist/audit/architecture-guard.js.map +1 -0
  29. package/dist/audit/baseline.d.ts +43 -0
  30. package/dist/audit/baseline.d.ts.map +1 -0
  31. package/dist/audit/baseline.js +140 -0
  32. package/dist/audit/baseline.js.map +1 -0
  33. package/dist/audit/dead-code-analyzer.d.ts +22 -0
  34. package/dist/audit/dead-code-analyzer.d.ts.map +1 -0
  35. package/dist/audit/dead-code-analyzer.js +265 -0
  36. package/dist/audit/dead-code-analyzer.js.map +1 -0
  37. package/dist/audit/iac-scanner.d.ts +12 -0
  38. package/dist/audit/iac-scanner.d.ts.map +1 -0
  39. package/dist/audit/iac-scanner.js +282 -0
  40. package/dist/audit/iac-scanner.js.map +1 -0
  41. package/dist/audit/live-accessibility.d.ts +26 -0
  42. package/dist/audit/live-accessibility.d.ts.map +1 -0
  43. package/dist/audit/live-accessibility.js +360 -0
  44. package/dist/audit/live-accessibility.js.map +1 -0
  45. package/dist/audit/main-scanner.d.ts.map +1 -1
  46. package/dist/audit/main-scanner.js +50 -1
  47. package/dist/audit/main-scanner.js.map +1 -1
  48. package/dist/audit/reachability.d.ts +17 -1
  49. package/dist/audit/reachability.d.ts.map +1 -1
  50. package/dist/audit/reachability.js +89 -2
  51. package/dist/audit/reachability.js.map +1 -1
  52. package/dist/audit/slop-detector.d.ts +14 -0
  53. package/dist/audit/slop-detector.d.ts.map +1 -0
  54. package/dist/audit/slop-detector.js +256 -0
  55. package/dist/audit/slop-detector.js.map +1 -0
  56. package/dist/autofix/worktree-autofix.d.ts +37 -0
  57. package/dist/autofix/worktree-autofix.d.ts.map +1 -1
  58. package/dist/autofix/worktree-autofix.js +141 -10
  59. package/dist/autofix/worktree-autofix.js.map +1 -1
  60. package/dist/config/codepulse-config.d.ts +14 -2
  61. package/dist/config/codepulse-config.d.ts.map +1 -1
  62. package/dist/config/codepulse-config.js +57 -31
  63. package/dist/config/codepulse-config.js.map +1 -1
  64. package/dist/db/database.d.ts +24 -0
  65. package/dist/db/database.d.ts.map +1 -1
  66. package/dist/db/database.js +61 -0
  67. package/dist/db/database.js.map +1 -1
  68. package/dist/docs/docs-generator.d.ts +1 -0
  69. package/dist/docs/docs-generator.d.ts.map +1 -1
  70. package/dist/docs/docs-generator.js +60 -1
  71. package/dist/docs/docs-generator.js.map +1 -1
  72. package/dist/graph/pagerank-map.d.ts +67 -0
  73. package/dist/graph/pagerank-map.d.ts.map +1 -0
  74. package/dist/graph/pagerank-map.js +273 -0
  75. package/dist/graph/pagerank-map.js.map +1 -0
  76. package/dist/graph/tree-sitter-indexer.d.ts +14 -1
  77. package/dist/graph/tree-sitter-indexer.d.ts.map +1 -1
  78. package/dist/graph/tree-sitter-indexer.js +415 -67
  79. package/dist/graph/tree-sitter-indexer.js.map +1 -1
  80. package/dist/index.d.ts +15 -0
  81. package/dist/index.d.ts.map +1 -1
  82. package/dist/index.js +15 -0
  83. package/dist/index.js.map +1 -1
  84. package/dist/output/context-pack.d.ts +26 -2
  85. package/dist/output/context-pack.d.ts.map +1 -1
  86. package/dist/output/context-pack.js +98 -13
  87. package/dist/output/context-pack.js.map +1 -1
  88. package/dist/output/markdown-writer.d.ts.map +1 -1
  89. package/dist/output/markdown-writer.js +8 -1
  90. package/dist/output/markdown-writer.js.map +1 -1
  91. package/dist/output/sarif-writer.d.ts +12 -0
  92. package/dist/output/sarif-writer.d.ts.map +1 -0
  93. package/dist/output/sarif-writer.js +147 -0
  94. package/dist/output/sarif-writer.js.map +1 -0
  95. package/dist/review/bundler.d.ts.map +1 -1
  96. package/dist/review/bundler.js +8 -2
  97. package/dist/review/bundler.js.map +1 -1
  98. package/dist/review/engine.d.ts.map +1 -1
  99. package/dist/review/engine.js +20 -5
  100. package/dist/review/engine.js.map +1 -1
  101. package/dist/sast/ast-grep-runner.d.ts +28 -0
  102. package/dist/sast/ast-grep-runner.d.ts.map +1 -0
  103. package/dist/sast/ast-grep-runner.js +215 -0
  104. package/dist/sast/ast-grep-runner.js.map +1 -0
  105. package/dist/sast/ast-queries.d.ts +7 -0
  106. package/dist/sast/ast-queries.d.ts.map +1 -0
  107. package/dist/sast/ast-queries.js +701 -0
  108. package/dist/sast/ast-queries.js.map +1 -0
  109. package/dist/sast/oxlint-runner.d.ts +24 -0
  110. package/dist/sast/oxlint-runner.d.ts.map +1 -0
  111. package/dist/sast/oxlint-runner.js +150 -0
  112. package/dist/sast/oxlint-runner.js.map +1 -0
  113. package/dist/sast/runner.d.ts.map +1 -1
  114. package/dist/sast/runner.js +66 -2
  115. package/dist/sast/runner.js.map +1 -1
  116. package/dist/sast/sbom-generator.d.ts +27 -0
  117. package/dist/sast/sbom-generator.d.ts.map +1 -0
  118. package/dist/sast/sbom-generator.js +191 -0
  119. package/dist/sast/sbom-generator.js.map +1 -0
  120. package/dist/sast/secret-registry.d.ts +18 -0
  121. package/dist/sast/secret-registry.d.ts.map +1 -0
  122. package/dist/sast/secret-registry.js +236 -0
  123. package/dist/sast/secret-registry.js.map +1 -0
  124. package/dist/types/review.d.ts +39 -0
  125. package/dist/types/review.d.ts.map +1 -1
  126. package/dist/types/review.js +16 -0
  127. package/dist/types/review.js.map +1 -1
  128. package/package.json +5 -2
@@ -0,0 +1,701 @@
1
+ import path from 'node:path';
2
+ import Parser from 'web-tree-sitter';
3
+ import { TreeSitterGraphIndexer } from '../graph/tree-sitter-indexer.js';
4
+ import { maskSecrets } from '../utils/platform.js';
5
+ function captureNode(match, name) {
6
+ return match.captures.find((c) => c.name === name)?.node;
7
+ }
8
+ function isInsideAsyncFunction(node) {
9
+ let cur = node.parent;
10
+ while (cur) {
11
+ if (cur.type === 'function_declaration' ||
12
+ cur.type === 'function_expression' ||
13
+ cur.type === 'arrow_function' ||
14
+ cur.type === 'method_definition') {
15
+ return /^\s*(?:export\s+)?async\b/.test(cur.text) || cur.children.some((c) => c.type === 'async');
16
+ }
17
+ cur = cur.parent;
18
+ }
19
+ return false;
20
+ }
21
+ function hasAwaitOrThenParent(node) {
22
+ let cur = node.parent;
23
+ while (cur && cur.type !== 'statement_block' && cur.type !== 'program') {
24
+ if (cur.type === 'await_expression' || cur.type === 'return_statement' || cur.type === 'variable_declarator') {
25
+ return true;
26
+ }
27
+ if (cur.type === 'member_expression' && /\.(?:then|catch|finally)$/.test(cur.text)) {
28
+ return true;
29
+ }
30
+ cur = cur.parent;
31
+ }
32
+ return false;
33
+ }
34
+ const JS_TS_RULES = [
35
+ {
36
+ id: 'CP-AST-SQLI-TEMPLATE',
37
+ severity: 'critical',
38
+ category: 'security',
39
+ cwe: 'CWE-89',
40
+ captureName: 'call',
41
+ query: `
42
+ (call_expression
43
+ function: [(identifier) @fn (member_expression property: (property_identifier) @fn)]
44
+ arguments: (arguments (template_string (template_substitution)) @arg)
45
+ (#match? @fn "^(query|queryRaw|execute|raw|unsafe|prepare|exec)$")
46
+ ) @call
47
+ `,
48
+ predicate: (_m, node) => {
49
+ const arg = node.childForFieldName('arguments')?.text ?? '';
50
+ return /SELECT|INSERT|UPDATE|DELETE|FROM|WHERE|\$\{/i.test(arg);
51
+ },
52
+ message: 'SQL query string built via template interpolation inside database call (SQL injection risk).',
53
+ suggestion: 'Use parameterized placeholders ($1, ?) or typed query builder bindings instead of ${...}.'
54
+ },
55
+ {
56
+ id: 'CP-AST-SQLI-CONCAT',
57
+ severity: 'critical',
58
+ category: 'security',
59
+ cwe: 'CWE-89',
60
+ captureName: 'call',
61
+ query: `
62
+ (call_expression
63
+ function: [(identifier) @fn (member_expression property: (property_identifier) @fn)]
64
+ arguments: (arguments (binary_expression) @arg)
65
+ (#match? @fn "^(query|queryRaw|execute|raw|prepare|exec)$")
66
+ ) @call
67
+ `,
68
+ predicate: (m) => {
69
+ const argText = captureNode(m, 'arg')?.text ?? '';
70
+ return /SELECT|INSERT|UPDATE|DELETE|WHERE/i.test(argText);
71
+ },
72
+ message: 'SQL query constructed using binary string concatenation (`+`).',
73
+ suggestion: 'Bind user values cleanly as query parameters rather than concatenating strings.'
74
+ },
75
+ {
76
+ id: 'CP-AST-XSS-INNERHTML',
77
+ severity: 'high',
78
+ category: 'security',
79
+ cwe: 'CWE-79',
80
+ captureName: 'assign',
81
+ query: `
82
+ (assignment_expression
83
+ left: (member_expression property: (property_identifier) @prop)
84
+ (#match? @prop "^(innerHTML|outerHTML)$")
85
+ ) @assign
86
+ `,
87
+ predicate: (_m, node) => {
88
+ const rhs = node.childForFieldName('right');
89
+ return Boolean(rhs && rhs.type !== 'string' && !/^['"`]\s*['"`]$/.test(rhs.text));
90
+ },
91
+ message: 'Dynamic HTML assigned to `.innerHTML`/`.outerHTML` sink (DOM XSS risk).',
92
+ suggestion: 'Use `.textContent`, DOMPurify sanitization, or structured DOM `createElement`/`appendChild` APIs.'
93
+ },
94
+ {
95
+ id: 'CP-AST-XSS-DOCWRITE',
96
+ severity: 'high',
97
+ category: 'security',
98
+ cwe: 'CWE-79',
99
+ captureName: 'call',
100
+ query: `
101
+ (call_expression
102
+ function: (member_expression
103
+ object: (identifier) @obj
104
+ property: (property_identifier) @prop)
105
+ (#eq? @obj "document")
106
+ (#match? @prop "^(write|writeln)$")
107
+ ) @call
108
+ `,
109
+ message: 'Unsafe `document.write`/`writeln` DOM injection call.',
110
+ suggestion: 'Render content safely via `.textContent` or declarative DOM APIs.'
111
+ },
112
+ {
113
+ id: 'CP-AST-EXEC-EVAL',
114
+ severity: 'critical',
115
+ category: 'security',
116
+ cwe: 'CWE-95',
117
+ captureName: 'call',
118
+ query: `
119
+ (call_expression
120
+ function: (identifier) @fn
121
+ arguments: (arguments (_) @arg)
122
+ (#eq? @fn "eval")
123
+ ) @call
124
+ `,
125
+ predicate: (m) => captureNode(m, 'arg')?.type !== 'string',
126
+ message: 'Dynamic `eval()` invocation enables arbitrary code execution.',
127
+ suggestion: 'Replace `eval()` with explicit parsing (`JSON.parse`) or structured dispatch.'
128
+ },
129
+ {
130
+ id: 'CP-AST-EXEC-FUNCTION',
131
+ severity: 'critical',
132
+ category: 'security',
133
+ cwe: 'CWE-95',
134
+ captureName: 'expr',
135
+ query: `
136
+ (new_expression
137
+ constructor: (identifier) @ctor
138
+ (#eq? @ctor "Function")
139
+ ) @expr
140
+ `,
141
+ message: 'Dynamic `new Function(...)` constructor compiles strings into executable code.',
142
+ suggestion: 'Avoid dynamic function generation; use static typed helpers.'
143
+ },
144
+ {
145
+ id: 'CP-AST-CMD-EXEC',
146
+ severity: 'critical',
147
+ category: 'security',
148
+ cwe: 'CWE-78',
149
+ captureName: 'call',
150
+ query: `
151
+ (call_expression
152
+ function: [(identifier) @fn (member_expression property: (property_identifier) @fn)]
153
+ arguments: (arguments (_) @cmd)
154
+ (#match? @fn "^(exec|execSync)$")
155
+ ) @call
156
+ `,
157
+ predicate: (m, node) => {
158
+ const arg = captureNode(m, 'cmd');
159
+ if (!arg)
160
+ return false;
161
+ const fnExpr = node.childForFieldName('function')?.text ?? '';
162
+ // Avoid flagging safe RegExp.prototype.exec
163
+ if (fnExpr === 'exec' || /regex|pattern|re\./i.test(fnExpr))
164
+ return false;
165
+ return (arg.type === 'template_string' && arg.text.includes('${')) || arg.type === 'binary_expression' || arg.type === 'identifier';
166
+ },
167
+ message: 'Shell command executed via `exec`/`execSync` with dynamic input (command injection risk).',
168
+ suggestion: 'Use `execFile`/`spawn` with explicit argument arrays (`shell: false`).'
169
+ },
170
+ {
171
+ id: 'CP-AST-REACT-USEEFFECT',
172
+ severity: 'medium',
173
+ category: 'performance',
174
+ captureName: 'call',
175
+ query: `
176
+ (call_expression
177
+ function: (identifier) @hook
178
+ arguments: (arguments (arrow_function body: (statement_block) @body))
179
+ (#eq? @hook "useEffect")
180
+ ) @call
181
+ `,
182
+ predicate: (m) => {
183
+ const body = captureNode(m, 'body')?.text ?? '';
184
+ return /(?:addEventListener|setInterval|\.subscribe\()/.test(body) && !/\breturn\s*(?:\(|function)/.test(body);
185
+ },
186
+ message: 'React `useEffect` registers listener/interval/subscription without returning a cleanup callback.',
187
+ suggestion: 'Return `() => { removeEventListener / clearInterval / unsubscribe }` from `useEffect` to prevent memory leaks.'
188
+ },
189
+ {
190
+ id: 'CP-AST-EMPTY-CATCH',
191
+ severity: 'high',
192
+ category: 'reliability',
193
+ cwe: 'CWE-390',
194
+ captureName: 'catch',
195
+ query: `
196
+ (catch_clause
197
+ body: (statement_block) @body
198
+ ) @catch
199
+ `,
200
+ predicate: (m, _n, file) => {
201
+ const body = captureNode(m, 'body');
202
+ if (!body || body.namedChildren.length > 0)
203
+ return false;
204
+ return !/\.test\.|\.spec\.|__tests__/i.test(file);
205
+ },
206
+ message: 'Empty `catch` block silently swallows runtime exceptions.',
207
+ suggestion: 'Log, handle explicitly, or rethrow errors cleanly — especially in auth/DB/finance paths.'
208
+ },
209
+ {
210
+ id: 'CP-AST-UNAWAITED-MUTATION',
211
+ severity: 'high',
212
+ category: 'concurrency',
213
+ captureName: 'call',
214
+ query: `
215
+ (expression_statement
216
+ (call_expression
217
+ function: (member_expression property: (property_identifier) @method)
218
+ ) @call
219
+ )
220
+ (#match? @method "^(save|update|delete|create|insert|transfer|charge|commit)$")
221
+ `,
222
+ predicate: (_m, node) => isInsideAsyncFunction(node) && !hasAwaitOrThenParent(node),
223
+ message: 'Async DB/state mutation called inside `async` function without `await` or `.catch()`.',
224
+ suggestion: 'Await the mutation promise so errors propagate cleanly and race conditions do not occur.'
225
+ },
226
+ {
227
+ id: 'CP-AST-TIMING-COMPARE',
228
+ severity: 'high',
229
+ category: 'auth',
230
+ cwe: 'CWE-208',
231
+ captureName: 'cmp',
232
+ query: `
233
+ (binary_expression
234
+ left: (_) @left
235
+ operator: ["===" "==" "!==" "!="]
236
+ right: (_) @right
237
+ ) @cmp
238
+ `,
239
+ predicate: (m, _n, file, content) => {
240
+ if (/timingSafeEqual/i.test(content) || /\.test\.|\.spec\.|__tests__/i.test(file))
241
+ return false;
242
+ const l = captureNode(m, 'left')?.text ?? '';
243
+ const r = captureNode(m, 'right')?.text ?? '';
244
+ const combined = `${l} ${r}`;
245
+ const isSecretName = /\b(?:secret|hmac|signature|webhookSecret|expectedToken|expectedSignature|apiKey|digest)\b/i.test(combined);
246
+ const comparedToNullOrBool = /\b(?:null|undefined|true|false)\b|['"]{2}|0/.test(l) || /\b(?:null|undefined|true|false)\b|['"]{2}|0/.test(r);
247
+ return isSecretName && !comparedToNullOrBool;
248
+ },
249
+ message: 'Secret/signature/HMAC value compared with non-constant-time `===`/`==` operator.',
250
+ suggestion: 'Compare secret tokens/HMAC signatures using `crypto.timingSafeEqual(Buffer.from(...), Buffer.from(...))`.'
251
+ },
252
+ {
253
+ id: 'CP-AST-PROTO-POLLUTE',
254
+ severity: 'high',
255
+ category: 'security',
256
+ cwe: 'CWE-1321',
257
+ captureName: 'call',
258
+ query: `
259
+ (call_expression
260
+ function: (member_expression
261
+ object: (identifier) @obj
262
+ property: (property_identifier) @prop)
263
+ arguments: (arguments (_) (_) @src)
264
+ (#eq? @obj "Object")
265
+ (#eq? @prop "assign")
266
+ ) @call
267
+ `,
268
+ predicate: (m) => /\breq\.(body|query|params)\b/.test(captureNode(m, 'src')?.text ?? ''),
269
+ message: '`Object.assign(..., req.body/query)` risks prototype pollution (`__proto__`, `constructor`).',
270
+ suggestion: 'Pick explicit schema-validated fields (`zod` / `structuredClone`) before merging.'
271
+ },
272
+ {
273
+ id: 'CP-AST-SSRF-FETCH',
274
+ severity: 'high',
275
+ category: 'security',
276
+ cwe: 'CWE-918',
277
+ captureName: 'call',
278
+ query: `
279
+ (call_expression
280
+ function: [(identifier) @fn (member_expression property: (property_identifier) @fn)]
281
+ arguments: (arguments (_) @urlArg)
282
+ (#match? @fn "^(fetch|get|post|request)$")
283
+ ) @call
284
+ `,
285
+ predicate: (m) => /\breq\.(body|query|params)\b/.test(captureNode(m, 'urlArg')?.text ?? ''),
286
+ message: 'Outbound HTTP fetch passes unvalidated request input into target URL (SSRF risk).',
287
+ suggestion: 'Validate hostnames against an allowlist and block loopback/RFC1918/metadata IPs (`169.254.169.254`).'
288
+ },
289
+ {
290
+ id: 'CP-AST-PATH-TRAVERSAL',
291
+ severity: 'critical',
292
+ category: 'security',
293
+ cwe: 'CWE-22',
294
+ captureName: 'call',
295
+ query: `
296
+ (call_expression
297
+ function: [(identifier) @fn (member_expression property: (property_identifier) @fn)]
298
+ arguments: (arguments (_) @pathArg)
299
+ (#match? @fn "^(readFile|readFileSync|writeFile|writeFileSync|sendFile|createReadStream)$")
300
+ ) @call
301
+ `,
302
+ predicate: (m, node) => /\breq\.(body|query|params)\b/.test(node.text),
303
+ message: 'Filesystem read/write uses raw HTTP request parameters (Path Traversal risk).',
304
+ suggestion: 'Resolve with `path.resolve(root, input)` and verify containment inside root (`safeResolveInside`).'
305
+ },
306
+ {
307
+ id: 'CP-AST-WEAK-HASH',
308
+ severity: 'medium',
309
+ category: 'security',
310
+ cwe: 'CWE-328',
311
+ captureName: 'call',
312
+ query: `
313
+ (call_expression
314
+ function: (member_expression property: (property_identifier) @fn)
315
+ arguments: (arguments (string) @alg)
316
+ (#eq? @fn "createHash")
317
+ ) @call
318
+ `,
319
+ predicate: (m, _n, file, content) => {
320
+ const alg = captureNode(m, 'alg')?.text.toLowerCase() ?? '';
321
+ const isSecurityContext = /password|token|secret|auth|sign|hmac|key/i.test(file + ' ' + content);
322
+ return isSecurityContext && (alg.includes('md5') || alg.includes('sha1'));
323
+ },
324
+ message: 'Weak hash algorithm (`md5`/`sha1`) used in security/auth context.',
325
+ suggestion: 'Use SHA-256/512 for digests or `scrypt`/`argon2id` for passwords.'
326
+ },
327
+ {
328
+ id: 'CP-AST-TLS-DISABLED',
329
+ severity: 'critical',
330
+ category: 'security',
331
+ cwe: 'CWE-295',
332
+ captureName: 'pair',
333
+ query: `
334
+ (pair
335
+ key: (property_identifier) @k
336
+ value: (false) @v
337
+ (#eq? @k "rejectUnauthorized")
338
+ ) @pair
339
+ `,
340
+ message: 'TLS certificate verification explicitly disabled (`rejectUnauthorized: false`).',
341
+ suggestion: 'Remove `rejectUnauthorized: false` or provide explicit custom CA certificates.'
342
+ },
343
+ {
344
+ id: 'CP-AST-OPEN-REDIRECT',
345
+ severity: 'high',
346
+ category: 'security',
347
+ cwe: 'CWE-601',
348
+ captureName: 'call',
349
+ query: `
350
+ (call_expression
351
+ function: (member_expression property: (property_identifier) @fn)
352
+ arguments: (arguments (_) @arg)
353
+ (#eq? @fn "redirect")
354
+ ) @call
355
+ `,
356
+ predicate: (m) => /\breq\.(query|body|params)\b/.test(captureNode(m, 'arg')?.text ?? ''),
357
+ message: 'HTTP redirect destination derived directly from request input (Open Redirect risk).',
358
+ suggestion: 'Validate redirect targets against same-origin relative paths or an allowlist of origins.'
359
+ },
360
+ {
361
+ id: 'CP-AST-CORS-WILDCARD',
362
+ severity: 'high',
363
+ category: 'security',
364
+ cwe: 'CWE-942',
365
+ captureName: 'obj',
366
+ query: `
367
+ (object) @obj
368
+ `,
369
+ predicate: (_m, node) => /origin\s*:\s*['"]\*['"]/.test(node.text) && /credentials\s*:\s*true/.test(node.text),
370
+ message: 'CORS configuration combines wildcard `origin: "*"` with `credentials: true`.',
371
+ suggestion: 'Restrict `origin` to explicit trusted origins when `credentials: true` is enabled.'
372
+ },
373
+ {
374
+ id: 'CP-AST-JWT-NONE',
375
+ severity: 'critical',
376
+ category: 'auth',
377
+ cwe: 'CWE-347',
378
+ captureName: 'call',
379
+ query: `
380
+ (call_expression
381
+ function: (member_expression property: (property_identifier) @fn)
382
+ (#match? @fn "^(verify|decode)$")
383
+ ) @call
384
+ `,
385
+ predicate: (_m, node) => /\bignoreExpiration\s*:\s*true\b/.test(node.text) || /algorithms\s*:\s*\[\s*['"]none['"]/i.test(node.text),
386
+ message: 'JWT verification bypasses expiration or permits `none` algorithm.',
387
+ suggestion: 'Enforce strong asymmetric/HMAC algorithms (e.g. `RS256`, `HS256`) and validate expiration.'
388
+ },
389
+ {
390
+ id: 'CP-AST-NOSQL-WHERE',
391
+ severity: 'critical',
392
+ category: 'security',
393
+ cwe: 'CWE-943',
394
+ captureName: 'call',
395
+ query: `
396
+ (call_expression
397
+ function: (member_expression property: (property_identifier) @fn)
398
+ arguments: (arguments (_) @q)
399
+ (#match? @fn "^(find|findOne|deleteMany|updateOne)$")
400
+ ) @call
401
+ `,
402
+ predicate: (m) => /\breq\.(body|query)\b/.test(captureNode(m, 'q')?.text ?? '') || /\$where/.test(captureNode(m, 'q')?.text ?? ''),
403
+ message: 'Raw request object or `$where` passed to database query (NoSQL operator injection risk).',
404
+ suggestion: 'Extract scalar fields with explicit Zod/type validation before querying.'
405
+ },
406
+ {
407
+ id: 'CP-AST-DESERIALIZE-VM',
408
+ severity: 'critical',
409
+ category: 'security',
410
+ cwe: 'CWE-94',
411
+ captureName: 'call',
412
+ query: `
413
+ (call_expression
414
+ function: (member_expression
415
+ object: (identifier) @obj
416
+ property: (property_identifier) @fn)
417
+ (#eq? @obj "vm")
418
+ (#match? @fn "^(runInNewContext|runInThisContext|runInContext|Script)$")
419
+ ) @call
420
+ `,
421
+ message: 'Node `vm` module executes code strings without process isolation (sandbox escape risk).',
422
+ suggestion: 'Avoid executing untrusted code via Node `vm`; use WebAssembly or isolated subprocesses.'
423
+ },
424
+ {
425
+ id: 'CP-AST-RANDOM-SECURITY',
426
+ severity: 'medium',
427
+ category: 'security',
428
+ cwe: 'CWE-338',
429
+ captureName: 'call',
430
+ query: `
431
+ (call_expression
432
+ function: (member_expression
433
+ object: (identifier) @obj
434
+ property: (property_identifier) @fn)
435
+ (#eq? @obj "Math")
436
+ (#eq? @fn "random")
437
+ ) @call
438
+ `,
439
+ predicate: (_m, node, file) => {
440
+ const parentText = node.parent?.parent?.text ?? '';
441
+ return /(?:token|secret|nonce|otp|salt|apiKey|session|csrf|password)/i.test(`${file} ${parentText}`);
442
+ },
443
+ message: '`Math.random()` is not cryptographically secure for tokens/secrets/nonces.',
444
+ suggestion: 'Use `crypto.randomBytes()` or `crypto.randomUUID()`.'
445
+ }
446
+ ];
447
+ const TSX_RULES = [
448
+ ...JS_TS_RULES,
449
+ {
450
+ id: 'CP-AST-XSS-DANGEROUSLY',
451
+ severity: 'high',
452
+ category: 'security',
453
+ cwe: 'CWE-79',
454
+ captureName: 'attr',
455
+ query: `
456
+ (jsx_attribute
457
+ (property_identifier) @name
458
+ (#eq? @name "dangerouslySetInnerHTML")
459
+ ) @attr
460
+ `,
461
+ predicate: (_m, node) => !/DOMPurify\.sanitize|sanitizeHtml/i.test(node.text),
462
+ message: 'React `dangerouslySetInnerHTML` used without inline HTML sanitizer.',
463
+ suggestion: 'Sanitize HTML through DOMPurify before passing to `dangerouslySetInnerHTML`, or render JSX nodes.'
464
+ }
465
+ ];
466
+ const PYTHON_RULES = [
467
+ {
468
+ id: 'CP-AST-SQLI-PY-FSTRING',
469
+ severity: 'critical',
470
+ category: 'security',
471
+ cwe: 'CWE-89',
472
+ captureName: 'call',
473
+ query: `
474
+ (call
475
+ function: (attribute attribute: (identifier) @fn)
476
+ arguments: (argument_list (string (interpolation)) @q)
477
+ (#match? @fn "^(execute|executemany|raw)$")
478
+ ) @call
479
+ `,
480
+ predicate: (m) => /SELECT|INSERT|UPDATE|DELETE|WHERE/i.test(captureNode(m, 'q')?.text ?? ''),
481
+ message: 'Python f-string SQL query interpolated into DB `.execute()` call (SQL injection risk).',
482
+ suggestion: 'Pass bound parameter tuples: `cursor.execute("SELECT ... WHERE id = %s", (user_id,))`.'
483
+ },
484
+ {
485
+ id: 'CP-AST-CMD-PY-SHELL',
486
+ severity: 'critical',
487
+ category: 'security',
488
+ cwe: 'CWE-78',
489
+ captureName: 'call',
490
+ query: `
491
+ (call
492
+ function: (attribute object: (identifier) @mod attribute: (identifier) @fn)
493
+ arguments: (argument_list) @args
494
+ (#match? @mod "^(subprocess|os)$")
495
+ (#match? @fn "^(run|Popen|call|check_output|system)$")
496
+ ) @call
497
+ `,
498
+ predicate: (m) => {
499
+ const fn = captureNode(m, 'fn')?.text ?? '';
500
+ const args = captureNode(m, 'args')?.text ?? '';
501
+ return fn === 'system' || /\bshell\s*=\s*True\b/.test(args);
502
+ },
503
+ message: 'Python shell execution (`shell=True` or `os.system`) enables command injection.',
504
+ suggestion: 'Use `subprocess.run([...], shell=False)` with explicit argument lists.'
505
+ },
506
+ {
507
+ id: 'CP-AST-PY-BARE-EXCEPT',
508
+ severity: 'medium',
509
+ category: 'reliability',
510
+ cwe: 'CWE-390',
511
+ captureName: 'ex',
512
+ query: `
513
+ (except_clause
514
+ (block (pass_statement))
515
+ ) @ex
516
+ `,
517
+ message: 'Python `except ...: pass` silently ignores exceptions.',
518
+ suggestion: 'Catch specific exception subclasses and log or handle failures cleanly.'
519
+ },
520
+ {
521
+ id: 'CP-AST-INSECURE-YAML',
522
+ severity: 'high',
523
+ category: 'security',
524
+ cwe: 'CWE-502',
525
+ captureName: 'call',
526
+ query: `
527
+ (call
528
+ function: (attribute object: (identifier) @mod attribute: (identifier) @fn)
529
+ arguments: (argument_list) @args
530
+ (#eq? @mod "yaml")
531
+ (#eq? @fn "load")
532
+ ) @call
533
+ `,
534
+ predicate: (m) => !/SafeLoader|CSafeLoader/.test(captureNode(m, 'args')?.text ?? ''),
535
+ message: '`yaml.load(...)` without `SafeLoader` allows arbitrary Python object deserialization.',
536
+ suggestion: 'Use `yaml.safe_load(...)`.'
537
+ },
538
+ {
539
+ id: 'CP-AST-PICKLE-LOADS',
540
+ severity: 'critical',
541
+ category: 'security',
542
+ cwe: 'CWE-502',
543
+ captureName: 'call',
544
+ query: `
545
+ (call
546
+ function: (attribute object: (identifier) @mod attribute: (identifier) @fn)
547
+ (#eq? @mod "pickle")
548
+ (#match? @fn "^(load|loads)$")
549
+ ) @call
550
+ `,
551
+ message: '`pickle.load`/`loads` executes arbitrary code when given untrusted bytes.',
552
+ suggestion: 'Deserialize structured JSON (`json.loads`) instead of `pickle`.'
553
+ },
554
+ {
555
+ id: 'CP-AST-TLS-DISABLED-PY',
556
+ severity: 'high',
557
+ category: 'security',
558
+ cwe: 'CWE-295',
559
+ captureName: 'call',
560
+ query: `
561
+ (call
562
+ function: (attribute object: (identifier) @mod)
563
+ arguments: (argument_list (keyword_argument name: (identifier) @kw value: (false)))
564
+ (#eq? @mod "requests")
565
+ (#eq? @kw "verify")
566
+ ) @call
567
+ `,
568
+ message: 'Python `requests` disables TLS certificate validation (`verify=False`).',
569
+ suggestion: 'Remove `verify=False` or pass a CA bundle path.'
570
+ }
571
+ ];
572
+ const GO_RULES = [
573
+ {
574
+ id: 'CP-AST-SQLI-GO-SPRINTF',
575
+ severity: 'critical',
576
+ category: 'security',
577
+ cwe: 'CWE-89',
578
+ captureName: 'call',
579
+ query: `
580
+ (call_expression
581
+ function: (selector_expression field: (field_identifier) @fn)
582
+ arguments: (argument_list) @args
583
+ (#match? @fn "^(Sprintf|Query|Exec|QueryRow)$")
584
+ ) @call
585
+ `,
586
+ predicate: (m) => {
587
+ const fn = captureNode(m, 'fn')?.text ?? '';
588
+ const args = captureNode(m, 'args')?.text ?? '';
589
+ if (fn === 'Sprintf')
590
+ return /SELECT|INSERT|UPDATE|DELETE/i.test(args) && /%[sv]/.test(args);
591
+ return /\+\s*[A-Za-z_]/.test(args) || /fmt\.Sprintf/.test(args);
592
+ },
593
+ message: 'Go SQL query constructed dynamically with `fmt.Sprintf` or string concatenation.',
594
+ suggestion: 'Use parameterized SQL queries (`db.Query("SELECT ... WHERE id = $1", id)`).'
595
+ },
596
+ {
597
+ id: 'CP-AST-CMD-GO-SH',
598
+ severity: 'critical',
599
+ category: 'security',
600
+ cwe: 'CWE-78',
601
+ captureName: 'call',
602
+ query: `
603
+ (call_expression
604
+ function: (selector_expression operand: (identifier) @pkg field: (field_identifier) @fn)
605
+ arguments: (argument_list) @args
606
+ (#eq? @pkg "exec")
607
+ (#match? @fn "^(Command|CommandContext)$")
608
+ ) @call
609
+ `,
610
+ predicate: (m) => /["'](?:sh|bash|cmd)["']\s*,\s*["']-c["']/.test(captureNode(m, 'args')?.text ?? ''),
611
+ message: 'Go `exec.Command` invokes an interactive shell (`sh -c`), risking command injection.',
612
+ suggestion: 'Execute target binaries directly without `sh -c` and pass arguments separately.'
613
+ }
614
+ ];
615
+ function rulesForLanguage(lang) {
616
+ switch (lang) {
617
+ case 'typescript':
618
+ case 'javascript':
619
+ return JS_TS_RULES;
620
+ case 'tsx':
621
+ return TSX_RULES;
622
+ case 'python':
623
+ return PYTHON_RULES;
624
+ case 'go':
625
+ return GO_RULES;
626
+ default:
627
+ return [];
628
+ }
629
+ }
630
+ /**
631
+ * Execute compiled Tree-sitter S-expression structural queries against source files,
632
+ * ignoring comments, docstrings, and inert literals.
633
+ */
634
+ export async function runAstQueryRules(file, content) {
635
+ const ext = path.extname(file).toLowerCase();
636
+ const loaded = await TreeSitterGraphIndexer.loadLanguageForExt(ext);
637
+ if (!loaded)
638
+ return [];
639
+ const rules = rulesForLanguage(loaded.lang);
640
+ if (rules.length === 0)
641
+ return [];
642
+ const parser = new Parser();
643
+ const diagnostics = [];
644
+ const seen = new Set();
645
+ try {
646
+ parser.setLanguage(loaded.language);
647
+ const tree = parser.parse(content);
648
+ if (!tree)
649
+ return [];
650
+ try {
651
+ for (const rule of rules) {
652
+ let query = null;
653
+ try {
654
+ query = loaded.language.query(rule.query);
655
+ const matches = query.matches(tree.rootNode);
656
+ for (const match of matches) {
657
+ const target = captureNode(match, rule.captureName) ?? match.captures[0]?.node;
658
+ if (!target)
659
+ continue;
660
+ if (rule.predicate && !rule.predicate(match, target, file, content))
661
+ continue;
662
+ const lineStart = target.startPosition.row + 1;
663
+ const lineEnd = target.endPosition.row + 1;
664
+ const key = `${rule.id}:${lineStart}`;
665
+ if (seen.has(key))
666
+ continue;
667
+ seen.add(key);
668
+ diagnostics.push({
669
+ ruleId: rule.id,
670
+ tool: 'codepulse-ast',
671
+ severity: rule.severity,
672
+ category: rule.category,
673
+ file,
674
+ lineStart,
675
+ lineEnd,
676
+ columnStart: target.startPosition.column + 1,
677
+ columnEnd: target.endPosition.column + 1,
678
+ message: rule.cwe ? `[${rule.cwe}] ${rule.message}` : rule.message,
679
+ suggestion: rule.suggestion,
680
+ snippet: maskSecrets(target.text.split(/\r?\n/).slice(0, 3).join('\n').slice(0, 240))
681
+ });
682
+ }
683
+ }
684
+ catch {
685
+ // Gracefully skip if a specific grammar version rejects a query pattern
686
+ }
687
+ finally {
688
+ query?.delete();
689
+ }
690
+ }
691
+ }
692
+ finally {
693
+ tree.delete();
694
+ }
695
+ }
696
+ finally {
697
+ parser.delete();
698
+ }
699
+ return diagnostics;
700
+ }
701
+ //# sourceMappingURL=ast-queries.js.map