codehere 0.2.1 → 0.3.0-rc.1

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 (235) hide show
  1. package/README.md +88 -68
  2. package/dist/domain/entities/task.js +4 -4
  3. package/dist/error-handler.js +4 -9
  4. package/dist/index.js +253 -1219
  5. package/dist/infrastructure/config/product-context.js +7 -6
  6. package/dist/infrastructure/hooks/claude-sdk-hook.js +335 -63
  7. package/dist/infrastructure/observability/execution-tracer.js +11 -6
  8. package/dist/infrastructure/orchestration/agent-adapter.js +13 -0
  9. package/dist/infrastructure/orchestration/agent-installer.js +101 -0
  10. package/dist/infrastructure/orchestration/agents-config-seed.js +56 -0
  11. package/dist/infrastructure/orchestration/aider-adapter.js +319 -0
  12. package/dist/infrastructure/orchestration/artifacts-extractor.js +175 -0
  13. package/dist/infrastructure/orchestration/claude-code-adapter.js +352 -0
  14. package/dist/infrastructure/orchestration/codex-adapter.js +310 -0
  15. package/dist/infrastructure/orchestration/generic-cli-adapter.js +553 -0
  16. package/dist/infrastructure/orchestration/opencode-adapter.js +275 -0
  17. package/dist/infrastructure/orchestration/progress-aggregator.js +189 -0
  18. package/dist/infrastructure/orchestration/readiness.js +106 -0
  19. package/dist/infrastructure/orchestration/session-manager.js +272 -0
  20. package/dist/infrastructure/orchestration/session-persistence.js +109 -0
  21. package/dist/infrastructure/protocols/mcp-helpers.js +10 -30
  22. package/dist/infrastructure/protocols/mcp-server-impl.js +359 -21
  23. package/dist/infrastructure/protocols/ui-page.js +1827 -0
  24. package/dist/infrastructure/security/file-collection.js +115 -0
  25. package/dist/infrastructure/security/trust-scorer.js +301 -56
  26. package/dist/infrastructure/storage/task-repository.js +8 -7
  27. package/dist/monitoring.js +10 -49
  28. package/dist/presentation/cli/commands/help-command.js +96 -139
  29. package/dist/presentation/cli/commands/hook-command.js +17 -24
  30. package/dist/presentation/cli/commands/report-command.js +59 -72
  31. package/dist/presentation/cli/commands/setup-command.js +4 -4
  32. package/dist/presentation/cli/commands/status-command.js +334 -43
  33. package/dist/presentation/cli/commands/trust-command.js +115 -99
  34. package/dist/presentation/cli/error-display.js +17 -21
  35. package/dist/ui.js +17 -12
  36. package/package.json +35 -67
  37. package/dist/agents/base.js +0 -101
  38. package/dist/agents/orchestrator-model-driven.js +0 -141
  39. package/dist/agents/react-orchestrator-agent.js +0 -54
  40. package/dist/application/agents/execution-agent.js +0 -508
  41. package/dist/application/agents/multi-agent-orchestrator.js +0 -295
  42. package/dist/application/agents/planning-agent.js +0 -433
  43. package/dist/application/agents/validation-agent.js +0 -317
  44. package/dist/application/architectures/plan-and-act.js +0 -242
  45. package/dist/application/index.js +0 -12
  46. package/dist/application/services/agent-factory.js +0 -28
  47. package/dist/application/services/dependency-container.js +0 -596
  48. package/dist/application/services/git-context-service.js +0 -83
  49. package/dist/application/services/intelligent-router.js +0 -934
  50. package/dist/application/services/tool-executor-service.js +0 -94
  51. package/dist/application/use-cases/ask-question-use-case.js +0 -338
  52. package/dist/application/use-cases/edit-file-use-case.js +0 -830
  53. package/dist/application/use-cases/explain-file-use-case.js +0 -50
  54. package/dist/application/use-cases/index-codebase-use-case.js +0 -113
  55. package/dist/application/use-cases/planning-use-case.js +0 -276
  56. package/dist/application/use-cases/react-orchestration-use-case.js +0 -329
  57. package/dist/application/use-cases/reflexion-use-case.js +0 -30
  58. package/dist/application/workflows/deterministic-workflows.js +0 -189
  59. package/dist/ast-parser.js +0 -331
  60. package/dist/cache.js +0 -180
  61. package/dist/chat.js +0 -251
  62. package/dist/code-analysis.js +0 -327
  63. package/dist/context.js +0 -187
  64. package/dist/docs.js +0 -146
  65. package/dist/domain/entities/code-chunk.js +0 -6
  66. package/dist/domain/entities/decision.js +0 -9
  67. package/dist/domain/entities/edit.js +0 -6
  68. package/dist/domain/entities/knowledge-node.js +0 -9
  69. package/dist/domain/entities/knowledge-preservation.js +0 -10
  70. package/dist/domain/entities/memory.js +0 -6
  71. package/dist/domain/entities/pattern.js +0 -7
  72. package/dist/domain/entities/plan.js +0 -6
  73. package/dist/domain/entities/query.js +0 -6
  74. package/dist/domain/errors/embeddings-not-found-error.js +0 -13
  75. package/dist/domain/index.js +0 -19
  76. package/dist/domain/interfaces/ai-service.interface.js +0 -6
  77. package/dist/domain/interfaces/code-analyzer.interface.js +0 -6
  78. package/dist/domain/interfaces/decision-repository.interface.js +0 -9
  79. package/dist/domain/interfaces/embedding-repository.interface.js +0 -6
  80. package/dist/domain/interfaces/knowledge-graph-repository.interface.js +0 -9
  81. package/dist/domain/interfaces/knowledge-preservation-repository.interface.js +0 -8
  82. package/dist/domain/interfaces/memory-repository.interface.js +0 -6
  83. package/dist/domain/interfaces/pattern-repository.interface.js +0 -6
  84. package/dist/domain/interfaces/verification-service.interface.js +0 -6
  85. package/dist/domain/services/cross-team-pattern-sharing.js +0 -125
  86. package/dist/domain/services/decision-recorder.js +0 -223
  87. package/dist/domain/services/decision-retriever.js +0 -133
  88. package/dist/domain/services/environment-mode-manager.js +0 -22
  89. package/dist/domain/services/graded-memory-activation.js +0 -69
  90. package/dist/domain/services/knowledge-access.js +0 -132
  91. package/dist/domain/services/knowledge-extractor.js +0 -247
  92. package/dist/domain/services/knowledge-graph-builder.js +0 -268
  93. package/dist/domain/services/knowledge-graph-query.js +0 -187
  94. package/dist/domain/services/memory-retriever.js +0 -82
  95. package/dist/domain/services/memory-synthesizer.js +0 -91
  96. package/dist/domain/services/pattern-extractor.js +0 -442
  97. package/dist/domain/services/query-intent-classifier.js +0 -140
  98. package/dist/domain/services/react-loop.js +0 -186
  99. package/dist/domain/services/risk-tier-detector.js +0 -78
  100. package/dist/edit.js +0 -319
  101. package/dist/embed.js +0 -459
  102. package/dist/formatter.js +0 -168
  103. package/dist/git.js +0 -198
  104. package/dist/infrastructure/ai/cohere-ai-service.js +0 -607
  105. package/dist/infrastructure/ai/command-r-evaluation.js +0 -206
  106. package/dist/infrastructure/ai/model-config.js +0 -84
  107. package/dist/infrastructure/ai/provider-ai-service.js +0 -477
  108. package/dist/infrastructure/cache/embedding-cache.js +0 -175
  109. package/dist/infrastructure/cache/query-result-cache.js +0 -66
  110. package/dist/infrastructure/cache/response-cache.js +0 -48
  111. package/dist/infrastructure/cache/security-scan-cache.js +0 -47
  112. package/dist/infrastructure/chunking/ast-code-chunker.js +0 -19
  113. package/dist/infrastructure/chunking/code-aware-chunker.js +0 -397
  114. package/dist/infrastructure/context/context-compressor.js +0 -329
  115. package/dist/infrastructure/context/conversation-context.js +0 -128
  116. package/dist/infrastructure/context/session-manager.js +0 -94
  117. package/dist/infrastructure/cost/cost-tracker.js +0 -360
  118. package/dist/infrastructure/file-scanner/file-scanner.js +0 -106
  119. package/dist/infrastructure/governance/nist-ai-rmf.js +0 -292
  120. package/dist/infrastructure/governance/policy-as-code.js +0 -258
  121. package/dist/infrastructure/governance/prompt-to-code-lineage.js +0 -239
  122. package/dist/infrastructure/index.js +0 -7
  123. package/dist/infrastructure/observability/prompt-versioner.js +0 -145
  124. package/dist/infrastructure/protocols/a2a-metadata.js +0 -137
  125. package/dist/infrastructure/protocols/a2a-protocol.js +0 -314
  126. package/dist/infrastructure/protocols/mcp-oauth.js +0 -184
  127. package/dist/infrastructure/protocols/mcp-server.js +0 -333
  128. package/dist/infrastructure/protocols/streaming-handler.js +0 -103
  129. package/dist/infrastructure/providers/cohere-provider.js +0 -444
  130. package/dist/infrastructure/providers/fake-provider.js +0 -130
  131. package/dist/infrastructure/providers/local-llm-provider.js +0 -330
  132. package/dist/infrastructure/providers/model-config.types.js +0 -9
  133. package/dist/infrastructure/providers/model-provider.interface.js +0 -8
  134. package/dist/infrastructure/providers/openai-provider.js +0 -413
  135. package/dist/infrastructure/providers/openrouter-provider.js +0 -399
  136. package/dist/infrastructure/providers/operation-provider-resolver.js +0 -105
  137. package/dist/infrastructure/providers/provider-config-loader.js +0 -120
  138. package/dist/infrastructure/providers/provider-registry.js +0 -88
  139. package/dist/infrastructure/safety/pattern-detector.js +0 -133
  140. package/dist/infrastructure/security/ai-sast-scanner.js +0 -290
  141. package/dist/infrastructure/security/docker-sandbox.js +0 -178
  142. package/dist/infrastructure/security/enhanced-security-gate.js +0 -151
  143. package/dist/infrastructure/security/license-scanner.js +0 -167
  144. package/dist/infrastructure/security/provider-bias-detector.js +0 -164
  145. package/dist/infrastructure/security/sandbox-executor.js +0 -64
  146. package/dist/infrastructure/serialization/toon-serializer.js +0 -119
  147. package/dist/infrastructure/storage/memory-stream-service.js +0 -204
  148. package/dist/infrastructure/storage/plan-repository.js +0 -96
  149. package/dist/infrastructure/storage/sqlite-decision-repository.js +0 -232
  150. package/dist/infrastructure/storage/sqlite-embedding-repository.js +0 -311
  151. package/dist/infrastructure/storage/sqlite-knowledge-graph-repository.js +0 -417
  152. package/dist/infrastructure/storage/sqlite-knowledge-preservation-repository.js +0 -230
  153. package/dist/infrastructure/storage/sqlite-memory-repository.js +0 -229
  154. package/dist/infrastructure/storage/sqlite-pattern-repository.js +0 -249
  155. package/dist/infrastructure/storage/task-helpers.js +0 -197
  156. package/dist/infrastructure/telemetry/telemetry-service.js +0 -167
  157. package/dist/infrastructure/ux/appropriate-friction.js +0 -213
  158. package/dist/infrastructure/ux/bi-directional-learning.js +0 -337
  159. package/dist/infrastructure/ux/capability-boundaries.js +0 -42
  160. package/dist/infrastructure/ux/comprehensive-formatter.js +0 -117
  161. package/dist/infrastructure/ux/contextual-feature-discovery.js +0 -10
  162. package/dist/infrastructure/ux/expectation-management.js +0 -327
  163. package/dist/infrastructure/ux/feature-discovery.js +0 -14
  164. package/dist/infrastructure/ux/feedback-prompt.js +0 -45
  165. package/dist/infrastructure/ux/hitl-validation.js +0 -297
  166. package/dist/infrastructure/ux/progress-indicator.js +0 -116
  167. package/dist/infrastructure/ux/progressive-disclosure.js +0 -236
  168. package/dist/infrastructure/ux/review-checkpoint.js +0 -72
  169. package/dist/infrastructure/ux/staged-feature-intro.js +0 -24
  170. package/dist/infrastructure/ux/stream-markdown.js +0 -151
  171. package/dist/infrastructure/ux/syntax-highlighter.js +0 -91
  172. package/dist/infrastructure/ux/team-standards.js +0 -196
  173. package/dist/infrastructure/ux/transparency.js +0 -71
  174. package/dist/infrastructure/validation/agent-feedback.js +0 -55
  175. package/dist/infrastructure/validation/agent-validation-helper.js +0 -137
  176. package/dist/infrastructure/validation/review-handler.js +0 -40
  177. package/dist/infrastructure/validation/summary-aggregator.js +0 -70
  178. package/dist/infrastructure/validation/summary-extractor.js +0 -45
  179. package/dist/infrastructure/validation/trace-summary.js +0 -52
  180. package/dist/infrastructure/verification/verification-service.js +0 -47
  181. package/dist/infrastructure/xai/attention-visualizer.js +0 -172
  182. package/dist/infrastructure/xai/cot-visualizer.js +0 -283
  183. package/dist/infrastructure/xai/decision-tree-log.js +0 -212
  184. package/dist/infrastructure/xai/interactive-xai.js +0 -260
  185. package/dist/infrastructure/xai/uncertainty-quantifier.js +0 -198
  186. package/dist/intelligent-retrieval.js +0 -272
  187. package/dist/intent/classifier.js +0 -2
  188. package/dist/intent/context.js +0 -2
  189. package/dist/iterative-refinement.js +0 -189
  190. package/dist/learning.js +0 -232
  191. package/dist/log.js +0 -31
  192. package/dist/migrate.js +0 -133
  193. package/dist/parallel-processor.js +0 -530
  194. package/dist/planner.js +0 -198
  195. package/dist/policy.js +0 -26
  196. package/dist/presentation/cli/commands/ask-command.js +0 -314
  197. package/dist/presentation/cli/commands/cost-command.js +0 -191
  198. package/dist/presentation/cli/commands/decision-command.js +0 -207
  199. package/dist/presentation/cli/commands/docs-command.js +0 -25
  200. package/dist/presentation/cli/commands/fix-command.js +0 -53
  201. package/dist/presentation/cli/commands/knowledge-command.js +0 -129
  202. package/dist/presentation/cli/commands/learning-dashboard-command.js +0 -183
  203. package/dist/presentation/cli/commands/models-command.js +0 -194
  204. package/dist/presentation/cli/commands/orchestrate-command.js +0 -207
  205. package/dist/presentation/cli/commands/plan-command.js +0 -246
  206. package/dist/presentation/cli/commands/product-command.js +0 -199
  207. package/dist/presentation/cli/commands/react-command.js +0 -181
  208. package/dist/presentation/cli/commands/review-command.js +0 -154
  209. package/dist/presentation/cli/commands/run-command.js +0 -188
  210. package/dist/presentation/cli/commands/smart-command.js +0 -395
  211. package/dist/presentation/cli/commands/suggest-command.js +0 -138
  212. package/dist/presentation/cli/commands/trace-command.js +0 -129
  213. package/dist/presentation/cli/commands/undo-command.js +0 -150
  214. package/dist/query-optimizer.js +0 -205
  215. package/dist/refactor.js +0 -116
  216. package/dist/review.js +0 -206
  217. package/dist/search.js +0 -163
  218. package/dist/session.js +0 -652
  219. package/dist/task-verification.js +0 -336
  220. package/dist/testgen.js +0 -166
  221. package/dist/token-optimizer.js +0 -277
  222. package/dist/tools/bash.js +0 -213
  223. package/dist/tools/edit.js +0 -235
  224. package/dist/tools/executor.js +0 -153
  225. package/dist/tools/git-tool.js +0 -292
  226. package/dist/tools/parser.js +0 -158
  227. package/dist/tools/registry.js +0 -302
  228. package/dist/tools/search.js +0 -100
  229. package/dist/types.js +0 -2
  230. package/dist/utils/check-api-status.js +0 -100
  231. package/dist/utils/diff-parser.js +0 -162
  232. package/dist/verification/backup.js +0 -259
  233. package/dist/verification/compiler.js +0 -264
  234. package/dist/verification/index.js +0 -273
  235. package/dist/verification/test-runner.js +0 -379
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Canonical file-collection rules for the trust scanner.
3
+ *
4
+ * Historic bug: IGNORE_DIRS and the test-file filter lived in three places
5
+ * (trust-command, mcp-helpers, report-command) and drifted. The v0.3.0-alpha
6
+ * shipreadiness fix patched two of them; report-command kept the old rules
7
+ * and produced different finding counts than `trust` for the same directory.
8
+ *
9
+ * Single source of truth now — every scanner entry point imports from here.
10
+ */
11
+ import { readdirSync, statSync } from 'fs';
12
+ import { join, extname } from 'path';
13
+ export const CODE_EXTENSIONS = new Set([
14
+ '.ts',
15
+ '.tsx',
16
+ '.js',
17
+ '.jsx',
18
+ '.mjs',
19
+ '.cjs',
20
+ '.py',
21
+ '.rb',
22
+ '.go',
23
+ '.java',
24
+ '.cs',
25
+ '.php',
26
+ '.sh',
27
+ '.bash',
28
+ '.zsh',
29
+ '.sql',
30
+ '.html',
31
+ '.vue',
32
+ '.svelte',
33
+ ]);
34
+ export const IGNORE_DIRS = new Set([
35
+ // JS/TS
36
+ 'node_modules',
37
+ 'dist',
38
+ 'build',
39
+ '.next',
40
+ '.nuxt',
41
+ '.svelte-kit',
42
+ '.turbo',
43
+ '.parcel-cache',
44
+ // Python
45
+ 'venv',
46
+ '__pycache__',
47
+ '.pytest_cache',
48
+ '.ruff_cache',
49
+ '.mypy_cache',
50
+ '.tox',
51
+ '__pypackages__',
52
+ // Rust / Go / PHP / Java / .NET
53
+ 'target',
54
+ 'vendor',
55
+ '.gradle',
56
+ 'obj',
57
+ // VCS / tooling / coverage / codehere
58
+ '.git',
59
+ '.hg',
60
+ '.svn',
61
+ 'coverage',
62
+ '.cache',
63
+ '.codehere',
64
+ '.codehere-cache',
65
+ // Test fixtures / mocks (intentionally-vulnerable code used as scanner inputs)
66
+ 'fixtures',
67
+ 'test-fixtures',
68
+ '__fixtures__',
69
+ '__mocks__',
70
+ ]);
71
+ // Test files contain deliberate vulnerability patterns as scanner inputs —
72
+ // SQL injection strings, hardcoded "credentials" etc. — that inflate the
73
+ // finding count without being real production risks. Skip by default.
74
+ export const TEST_FILE_RE = /\.(test|spec)\.[cm]?[jt]sx?$/;
75
+ export function shouldIgnoreDir(name) {
76
+ if (IGNORE_DIRS.has(name))
77
+ return true;
78
+ // Python virtualenv variants — .venv, .venv311, .venv-py3, venv3.11, env-py3
79
+ if (name.startsWith('.venv') || name.startsWith('venv'))
80
+ return true;
81
+ return false;
82
+ }
83
+ export function shouldIgnoreFile(name) {
84
+ return TEST_FILE_RE.test(name);
85
+ }
86
+ export function isCodeFile(name) {
87
+ return CODE_EXTENSIONS.has(extname(name)) && !shouldIgnoreFile(name);
88
+ }
89
+ /**
90
+ * Walk a directory and return paths of code files worth scanning.
91
+ * If `target` is a single file, it is returned as-is (explicit targets
92
+ * are never excluded — user pointed at it on purpose).
93
+ */
94
+ export function collectCodeFiles(target) {
95
+ const stat = statSync(target);
96
+ if (stat.isFile())
97
+ return [target];
98
+ const files = [];
99
+ function walk(dir) {
100
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
101
+ if (shouldIgnoreDir(entry.name))
102
+ continue;
103
+ const full = join(dir, entry.name);
104
+ if (entry.isDirectory()) {
105
+ walk(full);
106
+ }
107
+ else if (isCodeFile(entry.name)) {
108
+ files.push(full);
109
+ }
110
+ }
111
+ }
112
+ walk(target);
113
+ return files;
114
+ }
115
+ //# sourceMappingURL=file-collection.js.map
@@ -9,60 +9,283 @@
9
9
  *
10
10
  * All passes run locally, zero API calls.
11
11
  */
12
- import { scanPayload } from '../hooks/claude-sdk-hook.js';
13
12
  export const CODE_PATTERNS = [
14
13
  // Secrets (scan with strings visible — must see inside string literals)
15
- { regex: /(?:password|passwd|pass|pwd|secret|api_?key|auth_?token)\s*[:=]\s*['"`][^'"`\s]{4,}['"`]/gi, severity: 'high', category: 'Secrets', description: 'Hardcoded credential', cwe: 'CWE-798', scanRaw: true },
16
- { regex: /(?:password|passwd|secret|api.?key|auth.?token)[^\n]*\|\|\s*['"`][^'"`\s]{3,}['"`]/gi, severity: 'high', category: 'Secrets', description: 'Hardcoded fallback credential (env var || literal)', cwe: 'CWE-798', scanRaw: true },
17
- { regex: /sk-[a-zA-Z0-9]{32,}|xoxb-[a-zA-Z0-9-]+|ghp_[a-zA-Z0-9]{36,}/i, severity: 'critical', category: 'Secrets', description: 'API key pattern (OpenAI/Slack/GitHub)', cwe: 'CWE-798', scanRaw: true },
14
+ {
15
+ regex: /(?:password|passwd|pass|pwd|secret|api_?key|auth_?token)\s*[:=]\s*['"`][^'"`\s]{4,}['"`]/gi,
16
+ severity: 'high',
17
+ category: 'Secrets',
18
+ description: 'Hardcoded credential',
19
+ cwe: 'CWE-798',
20
+ scanRaw: true,
21
+ },
22
+ {
23
+ regex: /(?:password|passwd|secret|api.?key|auth.?token)[^\n]*\|\|\s*['"`][^'"`\s]{3,}['"`]/gi,
24
+ severity: 'high',
25
+ category: 'Secrets',
26
+ description: 'Hardcoded fallback credential (env var || literal)',
27
+ cwe: 'CWE-798',
28
+ scanRaw: true,
29
+ },
30
+ {
31
+ regex: /sk-[a-zA-Z0-9]{32,}|xoxb-[a-zA-Z0-9-]+|ghp_[a-zA-Z0-9]{36,}/i,
32
+ severity: 'critical',
33
+ category: 'Secrets',
34
+ description: 'API key pattern (OpenAI/Slack/GitHub)',
35
+ cwe: 'CWE-798',
36
+ scanRaw: true,
37
+ },
18
38
  // SQL Injection (scan with strings visible — SQL lives inside string literals)
19
39
  // Per-quote-type to allow inner quotes: "SELECT...WHERE name='" + user
20
- { regex: /"[^"]*SELECT[^"]*FROM[^"]*WHERE[^"]*"\s*\+/gi, severity: 'critical', category: 'SQL Injection', description: 'SQL query built with string concatenation (double-quoted)', cwe: 'CWE-89', scanRaw: true },
21
- { regex: /'[^']*SELECT[^']*FROM[^']*WHERE[^']*'\s*\+/gi, severity: 'critical', category: 'SQL Injection', description: 'SQL query built with string concatenation (single-quoted)', cwe: 'CWE-89', scanRaw: true },
22
- { regex: /query\s*\(\s*['"`][^'"`]*\$\{|execute\s*\([`'"]\s*SELECT.*\$\{/gi, severity: 'critical', category: 'SQL Injection', description: 'String interpolation in SQL query', cwe: 'CWE-89', scanRaw: true },
23
- { regex: /pool\.query\s*\([^,)]*\+[^,)]*\)/g, severity: 'high', category: 'SQL Injection', description: 'String concatenation in SQL query call', cwe: 'CWE-89' },
40
+ {
41
+ regex: /"[^"]*SELECT[^"]*FROM[^"]*WHERE[^"]*"\s*\+/gi,
42
+ severity: 'critical',
43
+ category: 'SQL Injection',
44
+ description: 'SQL query built with string concatenation (double-quoted)',
45
+ cwe: 'CWE-89',
46
+ scanRaw: true,
47
+ },
48
+ {
49
+ regex: /'[^']*SELECT[^']*FROM[^']*WHERE[^']*'\s*\+/gi,
50
+ severity: 'critical',
51
+ category: 'SQL Injection',
52
+ description: 'SQL query built with string concatenation (single-quoted)',
53
+ cwe: 'CWE-89',
54
+ scanRaw: true,
55
+ },
56
+ // Require a SQL keyword inside the interpolated string — otherwise this
57
+ // matches any `query("prompt with ${x}")` (handleQuery, graphql.query, etc.)
58
+ {
59
+ regex: /query\s*\(\s*['"`][^'"`]*\b(?:SELECT|INSERT|UPDATE|DELETE|WHERE|FROM)\b[^'"`]*\$\{|execute\s*\([`'"]\s*SELECT.*\$\{/gi,
60
+ severity: 'critical',
61
+ category: 'SQL Injection',
62
+ description: 'String interpolation in SQL query',
63
+ cwe: 'CWE-89',
64
+ scanRaw: true,
65
+ },
66
+ {
67
+ regex: /pool\.query\s*\([^,)]*\+[^,)]*\)/g,
68
+ severity: 'high',
69
+ category: 'SQL Injection',
70
+ description: 'String concatenation in SQL query call',
71
+ cwe: 'CWE-89',
72
+ },
24
73
  // Command injection with user input (scan with strings visible)
25
74
  // Catches require('child_process').execSync(req.body.cmd) — child_process is in a string
26
75
  // but the method call and req. reference are in plain code
27
- { regex: /\.exec(?:Sync)?\s*\(\s*req\./gi, severity: 'critical', category: 'Command Injection', description: 'exec/execSync called directly with request input', cwe: 'CWE-78', scanRaw: true },
76
+ {
77
+ regex: /\.exec(?:Sync)?\s*\(\s*req\./gi,
78
+ severity: 'critical',
79
+ category: 'Command Injection',
80
+ description: 'exec/execSync called directly with request input',
81
+ cwe: 'CWE-78',
82
+ scanRaw: true,
83
+ },
28
84
  // Injection (scan fully stripped — structural, must not trigger on pattern defs or comments)
29
- { regex: /\beval\s*\(/g, severity: 'critical', category: 'Code Injection', description: 'eval() allows arbitrary code execution', cwe: 'CWE-95' },
30
- { regex: /new\s+Function\s*\(/g, severity: 'critical', category: 'Code Injection', description: 'Function() constructor execution', cwe: 'CWE-95' },
31
- { regex: /child_process\.exec(?:Sync)?\s*\(\s*[^,)'"]*(?:req\.|body\.|params\.|query\.)/g, severity: 'critical', category: 'Command Injection', description: 'execSync/exec with user-controlled input', cwe: 'CWE-78' },
32
- { regex: /child_process\.exec\s*\(\s*[^,)]*\+/g, severity: 'critical', category: 'Command Injection', description: 'Command injection via string concat', cwe: 'CWE-78' },
85
+ {
86
+ regex: /\beval\s*\(/g,
87
+ severity: 'critical',
88
+ category: 'Code Injection',
89
+ description: 'eval() allows arbitrary code execution',
90
+ cwe: 'CWE-95',
91
+ },
92
+ {
93
+ regex: /new\s+Function\s*\(/g,
94
+ severity: 'critical',
95
+ category: 'Code Injection',
96
+ description: 'Function() constructor execution',
97
+ cwe: 'CWE-95',
98
+ },
99
+ {
100
+ regex: /child_process\.exec(?:Sync)?\s*\(\s*[^,)'"]*(?:req\.|body\.|params\.|query\.)/g,
101
+ severity: 'critical',
102
+ category: 'Command Injection',
103
+ description: 'execSync/exec with user-controlled input',
104
+ cwe: 'CWE-78',
105
+ },
106
+ {
107
+ regex: /child_process\.exec\s*\(\s*[^,)]*\+/g,
108
+ severity: 'critical',
109
+ category: 'Command Injection',
110
+ description: 'Command injection via string concat',
111
+ cwe: 'CWE-78',
112
+ },
33
113
  // Destructured exec/execSync with string concat containing user input
34
- { regex: /\bexec(?:Sync)?\s*\([^)]*\+\s*req\./g, severity: 'critical', category: 'Command Injection', description: 'exec() with string concatenation of user input', cwe: 'CWE-78', scanRaw: true },
35
- { regex: /\.innerHTML\s*=\s*[^=]/g, severity: 'high', category: 'XSS', description: 'innerHTML assignment (potential XSS)', cwe: 'CWE-79' },
36
- { regex: /document\.write\s*\(/g, severity: 'high', category: 'XSS', description: 'document.write can lead to XSS', cwe: 'CWE-79' },
114
+ {
115
+ regex: /\bexec(?:Sync)?\s*\([^)]*\+\s*req\./g,
116
+ severity: 'critical',
117
+ category: 'Command Injection',
118
+ description: 'exec() with string concatenation of user input',
119
+ cwe: 'CWE-78',
120
+ scanRaw: true,
121
+ },
122
+ {
123
+ regex: /\.innerHTML\s*=\s*[^=]/g,
124
+ severity: 'high',
125
+ category: 'XSS',
126
+ description: 'innerHTML assignment (potential XSS)',
127
+ cwe: 'CWE-79',
128
+ },
129
+ {
130
+ regex: /document\.write\s*\(/g,
131
+ severity: 'high',
132
+ category: 'XSS',
133
+ description: 'document.write can lead to XSS',
134
+ cwe: 'CWE-79',
135
+ },
37
136
  // Insecure deserialization
38
- { regex: /JSON\.parse\s*\([^)]*req\.|JSON\.parse\s*\([^)]*input/gi, severity: 'medium', category: 'Insecure Input', description: 'JSON.parse on unvalidated user input', cwe: 'CWE-502' },
39
- { regex: /yaml\.load\s*\([^)]*\)/g, severity: 'high', category: 'Insecure Deserialization', description: 'yaml.load without safeLoad', cwe: 'CWE-502' },
40
- { regex: /pickle\.loads\s*\(/g, severity: 'critical', category: 'Insecure Deserialization', description: 'pickle.loads on arbitrary data', cwe: 'CWE-502' },
137
+ {
138
+ regex: /JSON\.parse\s*\([^)]*req\.|JSON\.parse\s*\([^)]*input/gi,
139
+ severity: 'medium',
140
+ category: 'Insecure Input',
141
+ description: 'JSON.parse on unvalidated user input',
142
+ cwe: 'CWE-502',
143
+ },
144
+ {
145
+ regex: /yaml\.load\s*\([^)]*\)/g,
146
+ severity: 'high',
147
+ category: 'Insecure Deserialization',
148
+ description: 'yaml.load without safeLoad',
149
+ cwe: 'CWE-502',
150
+ },
151
+ {
152
+ regex: /pickle\.loads\s*\(/g,
153
+ severity: 'critical',
154
+ category: 'Insecure Deserialization',
155
+ description: 'pickle.loads on arbitrary data',
156
+ cwe: 'CWE-502',
157
+ },
41
158
  // Auth issues
42
- { regex: /jwt\.verify\s*\([^,)]+,\s*[^,)]+,\s*\{\s*algorithms\s*:\s*\[\s*['"`]none['"`]/i, severity: 'critical', category: 'Auth Bypass', description: 'JWT algorithm:none vulnerability', cwe: 'CWE-347' },
43
- { regex: /password\s*===?\s*['"`]|password\s*==\s*req\./gi, severity: 'high', category: 'Auth Bypass', description: 'Plaintext password comparison', cwe: 'CWE-256' },
159
+ {
160
+ regex: /jwt\.verify\s*\([^,)]+,\s*[^,)]+,\s*\{\s*algorithms\s*:\s*\[\s*['"`]none['"`]/i,
161
+ severity: 'critical',
162
+ category: 'Auth Bypass',
163
+ description: 'JWT algorithm:none vulnerability',
164
+ cwe: 'CWE-347',
165
+ },
166
+ {
167
+ regex: /password\s*===?\s*['"`]|password\s*==\s*req\./gi,
168
+ severity: 'high',
169
+ category: 'Auth Bypass',
170
+ description: 'Plaintext password comparison',
171
+ cwe: 'CWE-256',
172
+ },
44
173
  // Weak crypto
45
- { regex: /Math\.random\s*\(\s*\).*(?:token|key|secret|password|nonce|salt)/gi, severity: 'high', category: 'Weak Crypto', description: 'Math.random() for security-sensitive value', cwe: 'CWE-338' },
46
- { regex: /createCipheriv\s*\([^,]*['"`](?:des|rc4|md5)[^'"]*['"`]/gi, severity: 'high', category: 'Weak Crypto', description: 'Weak/deprecated cipher algorithm', cwe: 'CWE-327' },
174
+ {
175
+ regex: /Math\.random\s*\(\s*\).*(?:token|key|secret|password|nonce|salt)/gi,
176
+ severity: 'high',
177
+ category: 'Weak Crypto',
178
+ description: 'Math.random() for security-sensitive value',
179
+ cwe: 'CWE-338',
180
+ },
181
+ {
182
+ regex: /createCipheriv\s*\([^,]*['"`](?:des|rc4|md5)[^'"]*['"`]/gi,
183
+ severity: 'high',
184
+ category: 'Weak Crypto',
185
+ description: 'Weak/deprecated cipher algorithm',
186
+ cwe: 'CWE-327',
187
+ },
47
188
  // Path traversal
48
- { regex: /readFile\s*\([^)]*req\.|readFileSync\s*\([^)]*user/gi, severity: 'high', category: 'Path Traversal', description: 'File read with user-controlled path', cwe: 'CWE-22' },
49
- { regex: /__dirname\s*\+\s*['"`/]*\s*\+?\s*req\.(params|query|body)/gi, severity: 'high', category: 'Path Traversal', description: 'Path built from user input without sanitization', cwe: 'CWE-22' },
50
- { regex: /sendFile\s*\([^)]*req\.(params|query|body)/gi, severity: 'high', category: 'Path Traversal', description: 'sendFile with user-controlled path', cwe: 'CWE-22' },
189
+ {
190
+ regex: /readFile\s*\([^)]*req\.|readFileSync\s*\([^)]*user/gi,
191
+ severity: 'high',
192
+ category: 'Path Traversal',
193
+ description: 'File read with user-controlled path',
194
+ cwe: 'CWE-22',
195
+ },
196
+ {
197
+ regex: /__dirname\s*\+\s*['"`/]*\s*\+?\s*req\.(params|query|body)/gi,
198
+ severity: 'high',
199
+ category: 'Path Traversal',
200
+ description: 'Path built from user input without sanitization',
201
+ cwe: 'CWE-22',
202
+ },
203
+ {
204
+ regex: /sendFile\s*\([^)]*req\.(params|query|body)/gi,
205
+ severity: 'high',
206
+ category: 'Path Traversal',
207
+ description: 'sendFile with user-controlled path',
208
+ cwe: 'CWE-22',
209
+ },
51
210
  // Open redirect
52
- { regex: /res\.redirect\s*\([^)]*req\.(query|body|params)/gi, severity: 'medium', category: 'Open Redirect', description: 'Redirect to user-controlled URL', cwe: 'CWE-601' },
211
+ {
212
+ regex: /res\.redirect\s*\([^)]*req\.(query|body|params)/gi,
213
+ severity: 'medium',
214
+ category: 'Open Redirect',
215
+ description: 'Redirect to user-controlled URL',
216
+ cwe: 'CWE-601',
217
+ },
53
218
  // Server-side XSS (template injection in response)
54
- { regex: /res\.send\s*\(\s*`[^`]*\$\{[^}]*req\.(query|body|params)/gi, severity: 'high', category: 'XSS', description: 'User input interpolated directly into response HTML', cwe: 'CWE-79', scanRaw: true },
55
- { regex: /res\.send\s*\([^)]*\+\s*req\.(query|body|params)/gi, severity: 'high', category: 'XSS', description: 'User input concatenated into response', cwe: 'CWE-79', scanRaw: true },
56
- // Command injection via variable indirection (exec with non-literal arg)
57
- { regex: /\.exec\s*\(\s*(?!['"`])(\w+)\s*[,)]/g, severity: 'high', category: 'Command Injection', description: 'exec() called with variable argument — verify input is not user-controlled', cwe: 'CWE-78' },
219
+ {
220
+ regex: /res\.send\s*\(\s*`[^`]*\$\{[^}]*req\.(query|body|params)/gi,
221
+ severity: 'high',
222
+ category: 'XSS',
223
+ description: 'User input interpolated directly into response HTML',
224
+ cwe: 'CWE-79',
225
+ scanRaw: true,
226
+ },
227
+ {
228
+ regex: /res\.send\s*\([^)]*\+\s*req\.(query|body|params)/gi,
229
+ severity: 'high',
230
+ category: 'XSS',
231
+ description: 'User input concatenated into response',
232
+ cwe: 'CWE-79',
233
+ scanRaw: true,
234
+ },
235
+ // Command injection via variable indirection (exec with non-literal arg).
236
+ // Gated: only fires if file references child_process — otherwise regex.exec(str)
237
+ // lights up every bundled highlight.js / parser in the ecosystem.
238
+ // requiresContext must match an actual import, not the literal string
239
+ // child_process (which this scanner file itself contains as pattern data).
240
+ {
241
+ regex: /\.exec\s*\(\s*(?!['"`])(\w+)\s*[,)]/g,
242
+ severity: 'high',
243
+ category: 'Command Injection',
244
+ description: 'exec() called with variable argument — verify input is not user-controlled',
245
+ cwe: 'CWE-78',
246
+ requiresContext: /(?:from|require\()\s*['"](?:node:)?child_process['"]/,
247
+ },
58
248
  // SSRF
59
- { regex: /fetch\s*\(\s*req\.(body|query|params)/gi, severity: 'high', category: 'SSRF', description: 'Server-side request to user-controlled URL', cwe: 'CWE-918' },
60
- { regex: /axios\s*\.\s*(?:get|post|put|delete)\s*\(\s*req\.(body|query|params)/gi, severity: 'high', category: 'SSRF', description: 'HTTP request to user-controlled URL', cwe: 'CWE-918' },
249
+ {
250
+ regex: /fetch\s*\(\s*req\.(body|query|params)/gi,
251
+ severity: 'high',
252
+ category: 'SSRF',
253
+ description: 'Server-side request to user-controlled URL',
254
+ cwe: 'CWE-918',
255
+ },
256
+ {
257
+ regex: /axios\s*\.\s*(?:get|post|put|delete)\s*\(\s*req\.(body|query|params)/gi,
258
+ severity: 'high',
259
+ category: 'SSRF',
260
+ description: 'HTTP request to user-controlled URL',
261
+ cwe: 'CWE-918',
262
+ },
61
263
  // Weak crypto (MD5, SHA1 for passwords)
62
- { regex: /createHash\s*\(\s*['"`]md5['"`]\s*\)/gi, severity: 'high', category: 'Weak Crypto', description: 'MD5 hash is cryptographically broken — use bcrypt/argon2 for passwords', cwe: 'CWE-328', scanRaw: true },
63
- { regex: /createHash\s*\(\s*['"`]sha1['"`]\s*\)/gi, severity: 'medium', category: 'Weak Crypto', description: 'SHA1 is deprecated for security use — use SHA-256+ or bcrypt', cwe: 'CWE-328', scanRaw: true },
264
+ {
265
+ regex: /createHash\s*\(\s*['"`]md5['"`]\s*\)/gi,
266
+ severity: 'high',
267
+ category: 'Weak Crypto',
268
+ description: 'MD5 hash is cryptographically broken — use bcrypt/argon2 for passwords',
269
+ cwe: 'CWE-328',
270
+ scanRaw: true,
271
+ },
272
+ {
273
+ regex: /createHash\s*\(\s*['"`]sha1['"`]\s*\)/gi,
274
+ severity: 'medium',
275
+ category: 'Weak Crypto',
276
+ description: 'SHA1 is deprecated for security use — use SHA-256+ or bcrypt',
277
+ cwe: 'CWE-328',
278
+ scanRaw: true,
279
+ },
64
280
  // JWT algorithm:none (both sign and verify — scan raw to catch string content)
65
- { regex: /jwt\.(?:sign|verify)\s*\([^)]*algorithm\s*:\s*['"`]none['"`]/gi, severity: 'critical', category: 'Auth Bypass', description: 'JWT with algorithm "none" disables signature verification', cwe: 'CWE-347', scanRaw: true },
281
+ {
282
+ regex: /jwt\.(?:sign|verify)\s*\([^)]*algorithm\s*:\s*['"`]none['"`]/gi,
283
+ severity: 'critical',
284
+ category: 'Auth Bypass',
285
+ description: 'JWT with algorithm "none" disables signature verification',
286
+ cwe: 'CWE-347',
287
+ scanRaw: true,
288
+ },
66
289
  ];
67
290
  export function measureComplexity(code) {
68
291
  const lines = code.split('\n').length;
@@ -100,8 +323,8 @@ function isRegexStart(code, pos) {
100
323
  if (j < 0)
101
324
  return true;
102
325
  const prev = code[j];
103
- return '=([{,;!&|?:~^%+->'.includes(prev) ||
104
- /\b(return|typeof|instanceof|in|new|delete|void|throw|case)\s*$/.test(code.slice(0, pos).trimEnd());
326
+ return ('=([{,;!&|?:~^%+->'.includes(prev) ||
327
+ /\b(return|typeof|instanceof|in|new|delete|void|throw|case)\s*$/.test(code.slice(0, pos).trimEnd()));
105
328
  }
106
329
  /**
107
330
  * Strip ONLY comments and regex literals — string literals remain visible.
@@ -254,14 +477,36 @@ function stripLiterals(code) {
254
477
  }
255
478
  return out.join('');
256
479
  }
480
+ /**
481
+ * Public-by-design credential patterns — not secrets, should not flag.
482
+ * Firebase web API keys: Google documents these as safe to expose (security is via Firebase Rules).
483
+ * Stripe publishable keys: meant to be used in client code (pk_test_, pk_live_).
484
+ * Supabase anon keys: public by design when used with row-level security.
485
+ */
486
+ const PUBLIC_KEY_SIGNATURES = [
487
+ /AIzaSy[A-Za-z0-9_-]{33}/, // Firebase / Google Cloud web API key
488
+ /pk_(?:test|live)_[A-Za-z0-9]{20,}/, // Stripe publishable key
489
+ ];
490
+ function isKnownPublicKey(matched) {
491
+ if (!matched)
492
+ return false;
493
+ return PUBLIC_KEY_SIGNATURES.some((re) => re.test(matched));
494
+ }
257
495
  export function scoreFile(filepath, code) {
258
496
  const allFindings = [];
259
497
  // Pass 1: Comments+regex stripped but strings visible — catches secrets/SQL inside literals
260
498
  const rawForSecrets = stripCommentsAndRegex(code);
261
- for (const pattern of CODE_PATTERNS.filter(p => p.scanRaw)) {
499
+ for (const pattern of CODE_PATTERNS.filter((p) => p.scanRaw)) {
262
500
  let match;
263
501
  const re = new RegExp(pattern.regex.source, pattern.regex.flags);
264
502
  while ((match = re.exec(rawForSecrets)) !== null) {
503
+ const matched = match[0].substring(0, 80);
504
+ // Skip known public-by-design keys (Firebase, Stripe publishable, etc.)
505
+ if (pattern.category === 'Secrets' && isKnownPublicKey(matched)) {
506
+ if (!re.global)
507
+ break;
508
+ continue;
509
+ }
265
510
  const line = code.substring(0, match.index).split('\n').length;
266
511
  allFindings.push({
267
512
  severity: pattern.severity,
@@ -269,7 +514,7 @@ export function scoreFile(filepath, code) {
269
514
  description: pattern.description,
270
515
  line,
271
516
  cwe: pattern.cwe,
272
- matched: match[0].substring(0, 80),
517
+ matched,
273
518
  });
274
519
  if (!re.global)
275
520
  break;
@@ -277,7 +522,16 @@ export function scoreFile(filepath, code) {
277
522
  }
278
523
  // Pass 2: Fully stripped code — structural patterns (no false positives from literals)
279
524
  const scannable = stripLiterals(code);
280
- for (const pattern of CODE_PATTERNS.filter(p => !p.scanRaw)) {
525
+ // Context gate test: use comment-stripped source so `// require('child_process')`
526
+ // in a comment doesn't count as real usage. Strings still visible so actual
527
+ // imports like `from 'child_process'` still match.
528
+ const contextTarget = rawForSecrets;
529
+ for (const pattern of CODE_PATTERNS.filter((p) => !p.scanRaw)) {
530
+ // Context gate: skip pattern if the file doesn't have the required context
531
+ // (e.g., .exec(var) only fires if the file uses child_process).
532
+ if (pattern.requiresContext && !pattern.requiresContext.test(contextTarget)) {
533
+ continue;
534
+ }
281
535
  let match;
282
536
  const re = new RegExp(pattern.regex.source, pattern.regex.flags);
283
537
  while ((match = re.exec(scannable)) !== null) {
@@ -293,19 +547,10 @@ export function scoreFile(filepath, code) {
293
547
  break;
294
548
  }
295
549
  }
296
- // Pass 3: Hook-layer instruction patterns on fully stripped code
297
- const instructionFindings = scanPayload(scannable);
298
- for (const f of instructionFindings) {
299
- const isDupe = allFindings.some(af => af.category === f.category && af.description === f.description);
300
- if (!isDupe) {
301
- allFindings.push({
302
- severity: f.severity,
303
- category: f.category,
304
- description: f.description,
305
- matched: f.matched,
306
- });
307
- }
308
- }
550
+ // Pass 3 (removed): hook-layer instruction patterns are designed for runtime
551
+ // tool_input JSON, not source code. Firing them on source lit up every docstring
552
+ // containing phrases like "act as a flag". The hook handler still uses scanPayload
553
+ // directly; source scanning stays with Pass 1 + Pass 2 only.
309
554
  const complexity = measureComplexity(code);
310
555
  let penalty = 0;
311
556
  for (const f of allFindings)
@@ -320,8 +565,8 @@ export function scoreFile(filepath, code) {
320
565
  penalty += 3;
321
566
  const score = Math.max(0, Math.min(100, 100 - penalty));
322
567
  const grade = score >= 90 ? 'A' : score >= 75 ? 'B' : score >= 60 ? 'C' : score >= 40 ? 'D' : 'F';
323
- const critical = allFindings.filter(f => f.severity === 'critical').length;
324
- const high = allFindings.filter(f => f.severity === 'high').length;
568
+ const critical = allFindings.filter((f) => f.severity === 'critical').length;
569
+ const high = allFindings.filter((f) => f.severity === 'high').length;
325
570
  const summary = critical > 0
326
571
  ? `${critical} critical issue${critical > 1 ? 's' : ''} require immediate attention`
327
572
  : high > 0
@@ -58,7 +58,10 @@ export class JsonlTaskRepository {
58
58
  }
59
59
  try {
60
60
  const content = readFileSync(this.tasksPath, 'utf-8');
61
- const lines = content.trim().split('\n').filter(line => line.trim());
61
+ const lines = content
62
+ .trim()
63
+ .split('\n')
64
+ .filter((line) => line.trim());
62
65
  // Load all tasks, then keep only the latest version of each ID
63
66
  const allTasks = [];
64
67
  for (const line of lines) {
@@ -120,7 +123,7 @@ export class JsonlTaskRepository {
120
123
  this.loadTasks();
121
124
  // Load all tasks and find the latest version of this ID
122
125
  const allTasks = Array.from(this.tasksCache.values());
123
- const tasksWithId = allTasks.filter(task => task.id === id);
126
+ const tasksWithId = allTasks.filter((task) => task.id === id);
124
127
  if (tasksWithId.length === 0) {
125
128
  return null;
126
129
  }
@@ -135,7 +138,7 @@ export class JsonlTaskRepository {
135
138
  async getByStatus(status) {
136
139
  this.loadTasks();
137
140
  const tasks = Array.from(this.tasksCache.values());
138
- return tasks.filter(task => task.status === status);
141
+ return tasks.filter((task) => task.status === status);
139
142
  }
140
143
  /**
141
144
  * Get tasks by mode
@@ -143,7 +146,7 @@ export class JsonlTaskRepository {
143
146
  async getByMode(mode) {
144
147
  this.loadTasks();
145
148
  const tasks = Array.from(this.tasksCache.values());
146
- return tasks.filter(task => task.mode === mode);
149
+ return tasks.filter((task) => task.mode === mode);
147
150
  }
148
151
  /**
149
152
  * Get recent tasks (latest updated first)
@@ -151,9 +154,7 @@ export class JsonlTaskRepository {
151
154
  async getRecent(limit = 10) {
152
155
  this.loadTasks();
153
156
  const tasks = Array.from(this.tasksCache.values());
154
- return tasks
155
- .sort((a, b) => b.updatedAt - a.updatedAt)
156
- .slice(0, limit);
157
+ return tasks.sort((a, b) => b.updatedAt - a.updatedAt).slice(0, limit);
157
158
  }
158
159
  /**
159
160
  * Get all tasks (latest version of each)