praxis-sec 1.0.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 (183) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +170 -0
  3. package/ai-defense/cost-protection.md +292 -0
  4. package/ai-defense/llm-security-checklist.md +324 -0
  5. package/ai-defense/prompt-injection-patterns.js +283 -0
  6. package/ai-defense/system-prompt-armor.md +327 -0
  7. package/checklists/launch-day.md +168 -0
  8. package/cli/agents/abom-generator.js +225 -0
  9. package/cli/agents/agent-attestation-agent.js +318 -0
  10. package/cli/agents/agent-config-scanner.js +787 -0
  11. package/cli/agents/agent-telemetry-agent.js +415 -0
  12. package/cli/agents/agentic-security-agent.js +296 -0
  13. package/cli/agents/agentic-supply-chain-agent.js +463 -0
  14. package/cli/agents/ai-infra-inventory-agent.js +449 -0
  15. package/cli/agents/api-fuzzer.js +345 -0
  16. package/cli/agents/auth-bypass-agent.js +348 -0
  17. package/cli/agents/base-agent.js +280 -0
  18. package/cli/agents/cicd-scanner.js +300 -0
  19. package/cli/agents/config-auditor.js +757 -0
  20. package/cli/agents/deep-analyzer.js +776 -0
  21. package/cli/agents/endpoint-agent-abuse-agent.js +404 -0
  22. package/cli/agents/exception-handler-agent.js +187 -0
  23. package/cli/agents/git-history-scanner.js +169 -0
  24. package/cli/agents/governance-audits.js +138 -0
  25. package/cli/agents/hermes-security-agent.js +536 -0
  26. package/cli/agents/html-reporter.js +1125 -0
  27. package/cli/agents/index.js +147 -0
  28. package/cli/agents/injection-tester.js +502 -0
  29. package/cli/agents/legal-risk-agent.js +328 -0
  30. package/cli/agents/llm-redteam.js +199 -0
  31. package/cli/agents/managed-agent-scanner.js +333 -0
  32. package/cli/agents/mcp-security-agent.js +588 -0
  33. package/cli/agents/memory-poisoning-agent.js +305 -0
  34. package/cli/agents/mobile-scanner.js +231 -0
  35. package/cli/agents/model-file-scanner.js +259 -0
  36. package/cli/agents/orchestrator.js +355 -0
  37. package/cli/agents/pii-compliance-agent.js +301 -0
  38. package/cli/agents/policy-engine.js +229 -0
  39. package/cli/agents/prompt-injection-prober.js +224 -0
  40. package/cli/agents/rag-security-agent.js +204 -0
  41. package/cli/agents/recon-agent.js +207 -0
  42. package/cli/agents/sbom-generator.js +265 -0
  43. package/cli/agents/scoring-engine.js +273 -0
  44. package/cli/agents/ssrf-prober.js +130 -0
  45. package/cli/agents/stateful-watcher.js +238 -0
  46. package/cli/agents/supabase-rls-agent.js +154 -0
  47. package/cli/agents/supply-chain-agent.js +857 -0
  48. package/cli/agents/swarm-orchestrator.js +200 -0
  49. package/cli/agents/verifier-agent.js +303 -0
  50. package/cli/agents/vibe-coding-agent.js +250 -0
  51. package/cli/bin/praxis.js +866 -0
  52. package/cli/commands/abom.js +73 -0
  53. package/cli/commands/agent-fix.js +1245 -0
  54. package/cli/commands/audit.js +1180 -0
  55. package/cli/commands/autofix.js +383 -0
  56. package/cli/commands/baseline.js +193 -0
  57. package/cli/commands/benchmark.js +327 -0
  58. package/cli/commands/checklist.js +223 -0
  59. package/cli/commands/ci.js +403 -0
  60. package/cli/commands/deps.js +516 -0
  61. package/cli/commands/diff.js +200 -0
  62. package/cli/commands/doctor.js +195 -0
  63. package/cli/commands/env-audit.js +349 -0
  64. package/cli/commands/fix.js +218 -0
  65. package/cli/commands/guard.js +396 -0
  66. package/cli/commands/hooks.js +278 -0
  67. package/cli/commands/init.js +514 -0
  68. package/cli/commands/legal.js +158 -0
  69. package/cli/commands/live-advisories.js +241 -0
  70. package/cli/commands/mcp.js +660 -0
  71. package/cli/commands/openclaw.js +386 -0
  72. package/cli/commands/red-team.js +350 -0
  73. package/cli/commands/redteam.js +78 -0
  74. package/cli/commands/remediate.js +797 -0
  75. package/cli/commands/rotate.js +768 -0
  76. package/cli/commands/rules.js +196 -0
  77. package/cli/commands/scan-mcp.js +534 -0
  78. package/cli/commands/scan-skill.js +588 -0
  79. package/cli/commands/scan-standard.js +251 -0
  80. package/cli/commands/scan.js +524 -0
  81. package/cli/commands/score.js +449 -0
  82. package/cli/commands/shell.js +514 -0
  83. package/cli/commands/team-report.js +398 -0
  84. package/cli/commands/undo.js +161 -0
  85. package/cli/commands/update-intel.js +126 -0
  86. package/cli/commands/vibe-check.js +276 -0
  87. package/cli/commands/watch.js +757 -0
  88. package/cli/commands/web.js +63 -0
  89. package/cli/core/ast/guardrail-detector.js +141 -0
  90. package/cli/core/ast/index.js +22 -0
  91. package/cli/core/ast/parser.js +676 -0
  92. package/cli/core/ast/scope-tree.js +287 -0
  93. package/cli/core/ast/taint-tracker.js +158 -0
  94. package/cli/core/branding.js +37 -0
  95. package/cli/core/env.js +38 -0
  96. package/cli/core/errors.js +61 -0
  97. package/cli/core/fs.js +62 -0
  98. package/cli/core/output/compliance.js +90 -0
  99. package/cli/core/output/html-theme.js +158 -0
  100. package/cli/core/output/index.js +57 -0
  101. package/cli/core/output/json.js +48 -0
  102. package/cli/core/output/sarif.js +240 -0
  103. package/cli/core/version.js +67 -0
  104. package/cli/core/web/jobs.js +183 -0
  105. package/cli/core/web/projects.js +146 -0
  106. package/cli/core/web/server.js +439 -0
  107. package/cli/data/atlas-knowledge.json +5640 -0
  108. package/cli/data/eaa-catalog.json +39 -0
  109. package/cli/data/known-mcps.json +26 -0
  110. package/cli/data/probes/prompt-injection-corpus.json +271 -0
  111. package/cli/data/threat-intel.json +85 -0
  112. package/cli/data/threatpacks/latest.json +41 -0
  113. package/cli/hooks/patterns.js +313 -0
  114. package/cli/hooks/post-tool-use.js +140 -0
  115. package/cli/hooks/pre-tool-use.js +186 -0
  116. package/cli/index.js +90 -0
  117. package/cli/providers/llm-provider.js +766 -0
  118. package/cli/utils/autofix-rules.js +74 -0
  119. package/cli/utils/cache-manager.js +310 -0
  120. package/cli/utils/compliance-map.js +191 -0
  121. package/cli/utils/entropy.js +132 -0
  122. package/cli/utils/fix-ledger.js +127 -0
  123. package/cli/utils/hermes-tool-registry.js +252 -0
  124. package/cli/utils/intel/cache.js +61 -0
  125. package/cli/utils/intel/http.js +88 -0
  126. package/cli/utils/intel/index.js +235 -0
  127. package/cli/utils/intel/merge.js +229 -0
  128. package/cli/utils/intel/sources/epss.js +54 -0
  129. package/cli/utils/intel/sources/ghsa.js +81 -0
  130. package/cli/utils/intel/sources/gitguardian.js +40 -0
  131. package/cli/utils/intel/sources/gitleaks.js +101 -0
  132. package/cli/utils/intel/sources/kev.js +38 -0
  133. package/cli/utils/intel/sources/nvd.js +84 -0
  134. package/cli/utils/intel/sources/osv.js +132 -0
  135. package/cli/utils/intel/sources/phylum.js +44 -0
  136. package/cli/utils/intel/sources/snyk.js +46 -0
  137. package/cli/utils/intel/sources/socket.js +69 -0
  138. package/cli/utils/intel/sources/sonatype.js +84 -0
  139. package/cli/utils/intel/sources/threatpack.js +69 -0
  140. package/cli/utils/mcp-trust.js +60 -0
  141. package/cli/utils/output.js +251 -0
  142. package/cli/utils/patterns.js +1130 -0
  143. package/cli/utils/pdf-generator.js +94 -0
  144. package/cli/utils/plugin-loader.js +364 -0
  145. package/cli/utils/rule-import.js +228 -0
  146. package/cli/utils/rule-registry.js +426 -0
  147. package/cli/utils/scan-fingerprint.js +109 -0
  148. package/cli/utils/scan-playbook.js +312 -0
  149. package/cli/utils/score-history.js +119 -0
  150. package/cli/utils/secrets-verifier.js +247 -0
  151. package/cli/utils/security-memory.js +296 -0
  152. package/cli/utils/standards/atlas-knowledge.js +87 -0
  153. package/cli/utils/standards/index.js +127 -0
  154. package/cli/utils/standards/sources/avid.js +45 -0
  155. package/cli/utils/standards/sources/eu-ai-act.js +89 -0
  156. package/cli/utils/standards/sources/google-saif.js +39 -0
  157. package/cli/utils/standards/sources/iso-42001.js +94 -0
  158. package/cli/utils/standards/sources/mitre-atlas.js +54 -0
  159. package/cli/utils/standards/sources/nist-ai-600-1.js +45 -0
  160. package/cli/utils/standards/sources/owasp-llm.js +45 -0
  161. package/cli/utils/standards/sources/owasp-ml.js +45 -0
  162. package/cli/utils/threat-intel.js +265 -0
  163. package/configs/firebase/firestore-rules.txt +215 -0
  164. package/configs/firebase/security-checklist.md +236 -0
  165. package/configs/firebase/storage-rules.txt +206 -0
  166. package/configs/gitignore-template +258 -0
  167. package/configs/nextjs-security-headers.js +220 -0
  168. package/configs/praxisignore-template +50 -0
  169. package/configs/supabase/secure-client.ts +225 -0
  170. package/configs/supabase/security-checklist.md +278 -0
  171. package/docs/THIRD_PARTY_NOTICES.md +26 -0
  172. package/docs/THREAT_INTEL.md +292 -0
  173. package/docs/USAGE.md +1205 -0
  174. package/docs/design/WEB-UI.md +82 -0
  175. package/package.json +71 -0
  176. package/scripts/check-determinism.mjs +119 -0
  177. package/snippets/README.md +122 -0
  178. package/snippets/api-security/api-security-checklist.md +412 -0
  179. package/snippets/api-security/cors-config.ts +322 -0
  180. package/snippets/api-security/input-validation.ts +430 -0
  181. package/snippets/auth/jwt-checklist.md +322 -0
  182. package/snippets/rate-limiting/nextjs-middleware.ts +211 -0
  183. package/snippets/rate-limiting/upstash-ratelimit.ts +229 -0
@@ -0,0 +1,1180 @@
1
+ /**
2
+ * Audit Command — Full Security Audit
3
+ * =====================================
4
+ *
5
+ * One command to run everything: secrets, agents, deps, score, and
6
+ * generate a comprehensive report with a prioritized remediation plan.
7
+ *
8
+ * USAGE:
9
+ * npx praxis-sec audit [path] Full audit with HTML report
10
+ * npx praxis-sec audit . --json JSON output
11
+ * npx praxis-sec audit . --html report.html Custom report path
12
+ * npx praxis-sec audit . --no-deps Skip dependency audit
13
+ */
14
+
15
+ import fs from 'fs';
16
+ import path from 'path';
17
+ import { renderFindingsSARIF } from '../core/output/sarif.js';
18
+ import chalk from 'chalk';
19
+ import ora from 'ora';
20
+ import fg from 'fast-glob';
21
+ import { buildOrchestrator, buildOrchestratorAsync } from '../agents/index.js';
22
+ import { LegalRiskAgent } from '../agents/legal-risk-agent.js';
23
+ import { ScoringEngine } from '../agents/scoring-engine.js';
24
+ import { PolicyEngine } from '../agents/policy-engine.js';
25
+ import { HTMLReporter } from '../agents/html-reporter.js';
26
+ import { SBOMGenerator } from '../agents/sbom-generator.js';
27
+ import { autoDetectProvider } from '../providers/llm-provider.js';
28
+ import { runDepsAudit } from './deps.js';
29
+ import {
30
+ SECRET_PATTERNS,
31
+ SECURITY_PATTERNS,
32
+ SKIP_DIRS,
33
+ SKIP_EXTENSIONS,
34
+ SKIP_FILENAMES,
35
+ MAX_FILE_SIZE,
36
+ loadGitignorePatterns
37
+ } from '../utils/patterns.js';
38
+ import { isHighEntropyMatch, getConfidence } from '../utils/entropy.js';
39
+ import { printBanner } from '../utils/output.js';
40
+ import { CacheManager } from '../utils/cache-manager.js';
41
+ import { filterBaseline } from './baseline.js';
42
+ import { SecurityMemory } from '../utils/security-memory.js';
43
+ import { ScanPlaybook } from '../utils/scan-playbook.js';
44
+ import { generatePDF, generatePrintHTML, isChromeAvailable } from '../utils/pdf-generator.js';
45
+ import { SecretsVerifier } from '../utils/secrets-verifier.js';
46
+ import { applyInlineAnnotations } from './autofix.js';
47
+ import { buildScanFingerprint } from '../utils/scan-fingerprint.js';
48
+
49
+ // =============================================================================
50
+ // CONSTANTS
51
+ // =============================================================================
52
+
53
+ const ALL_PATTERNS = [...SECRET_PATTERNS, ...SECURITY_PATTERNS];
54
+
55
+ const SEV_ORDER = ['critical', 'high', 'medium', 'low'];
56
+
57
+ const CATEGORY_LABELS = {
58
+ secrets: 'Secrets',
59
+ injection: 'Code Vulnerabilities',
60
+ deps: 'Dependencies',
61
+ auth: 'Auth & Access Control',
62
+ config: 'Configuration',
63
+ 'supply-chain': 'Supply Chain',
64
+ api: 'API Security',
65
+ llm: 'AI/LLM Security',
66
+ legal: 'Legal Risk',
67
+ };
68
+
69
+ const EFFORT_MAP = {
70
+ secrets: 'low',
71
+ config: 'low',
72
+ deps: 'medium',
73
+ injection: 'medium',
74
+ auth: 'medium',
75
+ 'supply-chain': 'medium',
76
+ api: 'medium',
77
+ llm: 'high',
78
+ legal: 'low',
79
+ };
80
+
81
+ // =============================================================================
82
+ // MAIN COMMAND
83
+ // =============================================================================
84
+
85
+ export async function auditCommand(targetPath = '.', options = {}) {
86
+ const absolutePath = path.resolve(targetPath);
87
+ const machineOutput = options.json || options.sarif || options.csv || options.md;
88
+
89
+ if (!fs.existsSync(absolutePath)) {
90
+ console.error(chalk.red(` Path does not exist: ${absolutePath}`));
91
+ process.exitCode = 1;
92
+ return;
93
+ }
94
+
95
+ if (!machineOutput) {
96
+ printBanner();
97
+ }
98
+
99
+ // ── Cache Layer ──────────────────────────────────────────────────────────
100
+ // --deep forces a fresh scan so taint analysis covers every finding,
101
+ // not just the ones from files changed since the last cached run.
102
+ const useCache = options.cache !== false && !options.deep;
103
+ const cache = new CacheManager(absolutePath);
104
+ let cacheData = useCache ? cache.load() : null;
105
+ let cacheDiff = null;
106
+ let allFiles = [];
107
+
108
+ // ── Phase 1: Secret Scan ──────────────────────────────────────────────────
109
+ const secretSpinner = machineOutput ? null : ora({ text: chalk.white('[Phase 1/4] Scanning for secrets...'), color: 'cyan' }).start();
110
+ let secretFindings = [];
111
+ let filesScanned = 0;
112
+
113
+ try {
114
+ allFiles = await findFiles(absolutePath);
115
+ filesScanned = allFiles.length;
116
+
117
+ // Determine which files need scanning (incremental if cache exists)
118
+ let filesToScan = allFiles;
119
+ let cachedSecretFindings = [];
120
+
121
+ if (cacheData) {
122
+ cacheDiff = cache.diff(allFiles);
123
+ filesToScan = cacheDiff.changedFiles;
124
+ // Reuse cached findings for unchanged files (secrets only)
125
+ cachedSecretFindings = cacheDiff.cachedFindings.filter(
126
+ f => f.category === 'secrets' || f.category === 'secret'
127
+ );
128
+ }
129
+
130
+ for (const file of filesToScan) {
131
+ const fileResults = scanFileForSecrets(file);
132
+ for (const f of fileResults) {
133
+ secretFindings.push({
134
+ file,
135
+ line: f.line,
136
+ column: f.column,
137
+ severity: f.severity,
138
+ category: f.category || 'secrets',
139
+ rule: f.patternName,
140
+ title: f.patternName.replace(/_/g, ' '),
141
+ description: f.description,
142
+ matched: f.matched,
143
+ confidence: f.confidence,
144
+ fix: file.match(/\.env(\..*)?$/)
145
+ ? `Ensure .env is in .gitignore and use a secrets manager for production`
146
+ : `Move to environment variable or secrets manager`,
147
+ });
148
+ }
149
+ }
150
+
151
+ // Downgrade .env findings if the file is gitignored (properly managed)
152
+ const gitignoreContent = (() => {
153
+ try { return fs.readFileSync(path.join(absolutePath, '.gitignore'), 'utf-8'); } catch { return ''; }
154
+ })();
155
+ const envIsGitignored = gitignoreContent.split('\n')
156
+ .map(l => l.trim())
157
+ .some(l => /^\.env(\s|$)/.test(l) || l === '*.env' || l === '.env*' || l === '.env.local' || l === '.env.production');
158
+
159
+ if (envIsGitignored) {
160
+ for (const f of secretFindings) {
161
+ if (f.file.match(/\.env(\..*)?$/) && !f.file.includes('node_modules')) {
162
+ f.severity = 'low';
163
+ f.confidence = 'low';
164
+ f.fix = 'Already gitignored — ensure secrets manager is used for production deploys';
165
+ }
166
+ }
167
+ }
168
+
169
+ // Downgrade secrets in test files (intentional test fixtures)
170
+ const TEST_PATH = /(?:__tests__|\.test\.|\.spec\.|\/test\/|\/tests\/|\/fixtures?\/)/i;
171
+ for (const f of secretFindings) {
172
+ if (TEST_PATH.test(f.file)) {
173
+ f.confidence = 'low';
174
+ }
175
+ }
176
+
177
+ // Merge with cached findings for unchanged files
178
+ secretFindings = [...secretFindings, ...cachedSecretFindings];
179
+
180
+ const cacheNote = cacheDiff && cacheDiff.changedFiles.length < allFiles.length
181
+ ? ` (${cacheDiff.changedFiles.length} changed, ${cacheDiff.unchangedCount} cached)`
182
+ : '';
183
+
184
+ if (secretSpinner) secretSpinner.succeed(
185
+ secretFindings.length === 0
186
+ ? chalk.green(`[Phase 1/4] Secrets: clean${cacheNote}`)
187
+ : chalk.red(`[Phase 1/4] Secrets: ${secretFindings.length} found${cacheNote}`)
188
+ );
189
+ } catch (err) {
190
+ if (secretSpinner) secretSpinner.fail(chalk.red(`[Phase 1/4] Secret scan failed: ${err.message}`));
191
+ }
192
+
193
+ // ── Phase 2: Agent Scan ───────────────────────────────────────────────────
194
+ const orchestrator = await buildOrchestratorAsync(absolutePath, { quiet: true });
195
+
196
+ // --hermes-only: filter to llm + supply-chain category agents only
197
+ if (options.hermesOnly && orchestrator.agents) {
198
+ const hermesCategories = new Set(['llm', 'supply-chain']);
199
+ orchestrator.agents = orchestrator.agents.filter(a =>
200
+ hermesCategories.has(a.category) || hermesCategories.has(a.constructor?.category)
201
+ );
202
+ }
203
+
204
+ const registeredAgentCount = orchestrator.agents?.length || 15;
205
+ const agentSpinner = machineOutput ? null : ora({ text: chalk.white(`[Phase 2/4] Running ${registeredAgentCount} security agents...`), color: 'cyan' }).start();
206
+ let agentFindings = [];
207
+ let recon = null;
208
+ let agentResults = [];
209
+
210
+ try {
211
+ // Suppress individual agent spinners by using quiet mode
212
+ // Pass changedFiles for incremental scanning if cache is valid
213
+ const orchestratorOpts = { quiet: true };
214
+ if (options.deep) orchestratorOpts.deep = true;
215
+ if (options.local) orchestratorOpts.local = true;
216
+ if (options.model) orchestratorOpts.model = options.model;
217
+ if (options.provider) orchestratorOpts.provider = options.provider;
218
+ if (options.baseUrl) orchestratorOpts.baseUrl = options.baseUrl;
219
+ if (options.budget) orchestratorOpts.budget = options.budget;
220
+ if (options.verbose) orchestratorOpts.verbose = true;
221
+ if (cacheDiff && cacheDiff.changedFiles.length < allFiles.length) {
222
+ orchestratorOpts.changedFiles = cacheDiff.changedFiles;
223
+ }
224
+ const results = await orchestrator.runAll(absolutePath, orchestratorOpts); // praxis-ignore — orchestrator result, not LLM output triggering actions
225
+ recon = results.recon;
226
+ agentFindings = results.findings;
227
+ agentResults = results.agentResults;
228
+
229
+ const totalAgentFindings = agentFindings.length;
230
+ const agentCount = agentResults.filter(a => a.success).length;
231
+ if (agentSpinner) agentSpinner.succeed(
232
+ totalAgentFindings === 0
233
+ ? chalk.green(`[Phase 2/4] ${agentCount} agents: clean`)
234
+ : chalk.yellow(`[Phase 2/4] ${agentCount} agents: ${totalAgentFindings} finding(s)`)
235
+ );
236
+ } catch (err) {
237
+ if (agentSpinner) agentSpinner.fail(chalk.red(`[Phase 2/4] Agent scan failed: ${err.message}`));
238
+ }
239
+
240
+ // ── Phase 3: Dependency Audit ─────────────────────────────────────────────
241
+ let depVulns = [];
242
+ if (options.deps !== false) {
243
+ const depSpinner = machineOutput ? null : ora({ text: chalk.white('[Phase 3/4] Auditing dependencies...'), color: 'cyan' }).start();
244
+ try {
245
+ const depResult = await runDepsAudit(absolutePath);
246
+ depVulns = depResult.vulns || [];
247
+ if (depSpinner) depSpinner.succeed(
248
+ depVulns.length === 0
249
+ ? chalk.green('[Phase 3/4] Dependencies: clean')
250
+ : chalk.red(`[Phase 3/4] Dependencies: ${depVulns.length} CVE(s)`)
251
+ );
252
+ } catch {
253
+ if (depSpinner) depSpinner.succeed(chalk.gray('[Phase 3/4] Dependencies: skipped (no manifest)'));
254
+ }
255
+ } else if (!machineOutput) {
256
+ console.log(chalk.gray(' [Phase 3/4] Dependencies: skipped (--no-deps)'));
257
+ }
258
+
259
+ // ── Phase 3b: Legal Risk Scan (opt-in) ───────────────────────────────────
260
+ let legalFindings = [];
261
+ if (options.includeLegal) {
262
+ const legalSpinner = machineOutput ? null : ora({ text: chalk.white('[Phase 3b] Legal risk scan…'), color: 'cyan' }).start();
263
+ try {
264
+ const legalAgent = new LegalRiskAgent();
265
+ legalFindings = await legalAgent.analyze({ rootPath: absolutePath, files: allFiles });
266
+ if (legalSpinner) legalSpinner.succeed(
267
+ legalFindings.length === 0
268
+ ? chalk.green('[Phase 3b] Legal: clean')
269
+ : chalk.yellow(`[Phase 3b] Legal: ${legalFindings.length} finding(s)`)
270
+ );
271
+ } catch {
272
+ if (legalSpinner) legalSpinner.succeed(chalk.gray('[Phase 3b] Legal: skipped'));
273
+ }
274
+ }
275
+
276
+ // ── Phase 4: Merge, Score, and Build Plan ─────────────────────────────────
277
+ const scoreSpinner = machineOutput ? null : ora({ text: chalk.white('[Phase 4/4] Computing security score...'), color: 'cyan' }).start();
278
+
279
+ // Merge secret findings + agent findings + legal findings, deduplicate
280
+ const allFindings = deduplicateFindings([...secretFindings, ...agentFindings, ...legalFindings]);
281
+
282
+ // Apply policy
283
+ const policy = PolicyEngine.load(absolutePath);
284
+ let filteredFindings = policy.applyPolicy(allFindings);
285
+
286
+ // Apply baseline filter (only show new findings)
287
+ if (options.baseline) {
288
+ const beforeCount = filteredFindings.length;
289
+ filteredFindings = filterBaseline(filteredFindings, absolutePath);
290
+ if (!machineOutput && beforeCount !== filteredFindings.length) {
291
+ console.log(chalk.gray(` Baseline: ${beforeCount - filteredFindings.length} known finding(s) filtered, ${filteredFindings.length} new`));
292
+ }
293
+ }
294
+
295
+ // ── Scan Playbook — update with latest recon + findings ─────────────────
296
+ try {
297
+ const playbook = new ScanPlaybook(absolutePath);
298
+ const suppressedRules = new SecurityMemory(absolutePath).list().map(e => e.rule).filter(Boolean);
299
+ playbook.update(recon, { score: scoreResult.score, grade: scoreResult.grade?.letter || scoreResult.grade, totalFindings: filteredFindings.length }, filteredFindings, suppressedRules);
300
+ } catch { /* non-fatal */ }
301
+
302
+ // ── Security Memory Filter ──────────────────────────────────────────────
303
+ // Auto-learn false positives from deep analysis results, then suppress
304
+ // any finding that memory recognises from a previous scan.
305
+ const secMemory = new SecurityMemory(absolutePath);
306
+ if (options.deep) {
307
+ // After deep analysis ran, learn any new false positives
308
+ const newFPs = secMemory.learnFromAnalysis(filteredFindings);
309
+ if (newFPs > 0 && !machineOutput) {
310
+ console.log(chalk.gray(` Memory: ${newFPs} new false positive(s) learned and will be suppressed in future scans`));
311
+ }
312
+ }
313
+ const { kept: memFiltered, suppressedCount: memSuppressed } = secMemory.filter(filteredFindings);
314
+ filteredFindings = memFiltered;
315
+ if (memSuppressed > 0 && !machineOutput) {
316
+ console.log(chalk.gray(` Memory: ${memSuppressed} previously-confirmed false positive(s) suppressed`));
317
+ }
318
+
319
+ // Count suppressions (praxis-ignore comments)
320
+ const suppressions = countSuppressions(allFiles);
321
+
322
+ // Score
323
+ const scoringEngine = new ScoringEngine();
324
+ const scoreResult = scoringEngine.compute(filteredFindings, depVulns);
325
+ // Round score to 1 decimal place to avoid floating-point noise (e.g., 63.300000000000004)
326
+ scoreResult.score = Math.round(scoreResult.score * 10) / 10;
327
+ scoringEngine.saveToHistory(absolutePath, scoreResult, suppressions);
328
+
329
+ const gradeColor = scoreResult.score >= 75 ? chalk.green.bold : scoreResult.score >= 60 ? chalk.yellow.bold : chalk.red.bold;
330
+ if (scoreSpinner) scoreSpinner.succeed(
331
+ chalk.white('[Phase 4/4] Score: ') + gradeColor(`${scoreResult.score}/100 ${scoreResult.grade.letter}`)
332
+ );
333
+
334
+ // ── AI Classification (optional, with LLM cache) ───────────────────────
335
+ if (options.ai !== false && !options.noAi) {
336
+ const provider = autoDetectProvider(absolutePath, {
337
+ provider: options.provider,
338
+ baseUrl: options.baseUrl,
339
+ model: options.model,
340
+ think: options.think || false,
341
+ });
342
+ if (provider && filteredFindings.length > 0 && filteredFindings.length <= 50) {
343
+ const aiSpinner = machineOutput ? null : ora({ text: `Classifying with ${provider.name}...`, color: 'cyan' }).start();
344
+ try {
345
+ // Check LLM cache for existing classifications
346
+ const llmCache = cache.loadLLMClassifications();
347
+ const uncachedFindings = [];
348
+ let cachedCount = 0;
349
+
350
+ for (const finding of filteredFindings) {
351
+ const key = cache.getLLMCacheKey(finding);
352
+ const cached = llmCache[key];
353
+ if (cached) {
354
+ finding.aiClassification = cached.classification;
355
+ finding.aiReason = cached.reason;
356
+ finding.aiFix = cached.fix;
357
+ cachedCount++;
358
+ } else {
359
+ uncachedFindings.push(finding);
360
+ }
361
+ }
362
+
363
+ // Only send uncached findings to LLM
364
+ if (uncachedFindings.length > 0) {
365
+ const classifications = await provider.classify(uncachedFindings);
366
+ const newCacheEntries = {};
367
+ for (const cl of classifications) {
368
+ const finding = filteredFindings.find(f => `${f.file}:${f.line}` === cl.id);
369
+ if (finding) {
370
+ finding.aiClassification = cl.classification;
371
+ finding.aiReason = cl.reason;
372
+ finding.aiFix = cl.fix;
373
+ const key = cache.getLLMCacheKey(finding);
374
+ newCacheEntries[key] = {
375
+ classification: cl.classification,
376
+ reason: cl.reason,
377
+ fix: cl.fix,
378
+ cachedAt: new Date().toISOString(),
379
+ };
380
+ }
381
+ }
382
+ cache.saveLLMClassifications(newCacheEntries);
383
+ }
384
+
385
+ const cacheNote = cachedCount > 0 ? `, ${cachedCount} cached` : '';
386
+ if (aiSpinner) aiSpinner.succeed(chalk.green(`AI classification complete (${provider.name}${cacheNote})`));
387
+ } catch (err) {
388
+ if (aiSpinner) aiSpinner.fail(chalk.yellow(`AI classification failed: ${err.message}`));
389
+ }
390
+ }
391
+ }
392
+
393
+ // ── Secrets Verification (optional, --verify flag) ─────────────────────
394
+ if (options.verify) {
395
+ const verifySpinner = machineOutput ? null : ora({ text: 'Verifying leaked secrets against provider APIs...', color: 'cyan' }).start();
396
+ try {
397
+ const verifier = new SecretsVerifier();
398
+ const verifyResults = await verifier.verify(filteredFindings);
399
+ const activeCount = verifyResults.filter(r => r.result.active === true).length;
400
+ const inactiveCount = verifyResults.filter(r => r.result.active === false).length;
401
+ if (verifySpinner) {
402
+ verifySpinner.succeed(chalk.green(
403
+ `Secrets verified: ${activeCount} active, ${inactiveCount} inactive, ${verifyResults.length - activeCount - inactiveCount} unknown`
404
+ ));
405
+ }
406
+ // Show active secrets warning
407
+ if (activeCount > 0 && !machineOutput) {
408
+ console.log(chalk.red.bold(' ⚠ ACTIVE SECRETS DETECTED — rotate immediately:'));
409
+ for (const r of verifyResults.filter(r => r.result.active === true)) {
410
+ const rel = path.relative(absolutePath, r.finding.file).replace(/\\/g, '/');
411
+ console.log(chalk.red(` ${r.result.provider}: ${rel}:${r.finding.line} — ${r.result.info}`));
412
+ }
413
+ }
414
+ } catch (err) {
415
+ if (verifySpinner) verifySpinner.fail(chalk.yellow(`Secrets verification failed: ${err.message}`));
416
+ }
417
+ }
418
+
419
+ // ── Save Cache ──────────────────────────────────────────────────────────
420
+ if (useCache) {
421
+ try {
422
+ // Merge agent findings back for cache (secret + agent findings from changed files)
423
+ // plus cached findings from unchanged files
424
+ const cachedAgentFindings = cacheData && cacheDiff
425
+ ? cacheDiff.cachedFindings.filter(f => f.category !== 'secrets' && f.category !== 'secret')
426
+ : [];
427
+ const allFindingsForCache = [...secretFindings, ...agentFindings, ...cachedAgentFindings];
428
+ cache.save(allFiles, deduplicateFindings(allFindingsForCache), recon, scoreResult);
429
+ } catch {
430
+ // Silent — caching should never break a scan
431
+ }
432
+ }
433
+
434
+ // ── Build Remediation Plan ────────────────────────────────────────────────
435
+ const remediationPlan = buildRemediationPlan(filteredFindings, depVulns, absolutePath);
436
+
437
+ // Skip all output and file generation for inner agentic re-scans
438
+ if (options._agenticInner) {
439
+ return { score: scoreResult.score, findings: filteredFindings };
440
+ }
441
+
442
+ // ── Output ────────────────────────────────────────────────────────────────
443
+ if (!machineOutput) console.log();
444
+
445
+ if (options.csv) {
446
+ outputCSV(filteredFindings, depVulns, scoreResult, absolutePath);
447
+ } else if (options.md) {
448
+ outputMarkdown(scoreResult, filteredFindings, depVulns, remediationPlan, absolutePath);
449
+ } else if (options.json) {
450
+ outputJSON(scoreResult, filteredFindings, depVulns, recon, agentResults, remediationPlan, suppressions, options.compare ? scoringEngine.loadHistory(absolutePath) : null, filesScanned);
451
+ } else if (options.sarif) {
452
+ outputSARIF(filteredFindings, absolutePath);
453
+ } else {
454
+ printReport(scoreResult, filteredFindings, depVulns, recon, remediationPlan, absolutePath, filesScanned);
455
+ }
456
+
457
+ // ── HTML Report — always on for human output, or when --html is explicit ──
458
+ const explicitHtml = typeof options.html === 'string' || options.html === true;
459
+ if (explicitHtml || (!options.json && !options.sarif && !options.csv && !options.md)) {
460
+ const htmlPath = typeof options.html === 'string' ? options.html : 'praxis-report.html';
461
+ const reporter = new HTMLReporter();
462
+ reporter.generateToFile(scoreResult, filteredFindings, recon, absolutePath, htmlPath, agentResults, filesScanned);
463
+
464
+ // If --html-dir or --suite specified, also generate granular multi-page report suite
465
+ if (options.htmlDir || options['html-dir'] || options.suite) {
466
+ const suiteDir = typeof (options.htmlDir || options['html-dir'] || options.suite) === 'string'
467
+ ? (options.htmlDir || options['html-dir'] || options.suite)
468
+ : 'report';
469
+ reporter.generateReportSuite(scoreResult, filteredFindings, depVulns, recon, remediationPlan, absolutePath, suiteDir, agentResults, filesScanned);
470
+ }
471
+
472
+ // Keep stdout pure JSON/SARIF when combined with machine output
473
+ const note = machineOutput ? console.error : console.log;
474
+ note();
475
+ note(chalk.cyan(` Full report: ${chalk.white.bold(htmlPath)}`));
476
+ note(chalk.gray(` Dashboard: `) + chalk.cyan(''));
477
+
478
+ // PDF export
479
+ if (options.pdf) {
480
+ const pdfPath = typeof options.pdf === 'string' ? options.pdf : 'praxis-report.pdf';
481
+ const result = generatePDF(path.resolve(htmlPath), path.resolve(pdfPath));
482
+ if (result) {
483
+ note(chalk.cyan(` PDF report: ${chalk.white.bold(pdfPath)}`));
484
+ } else {
485
+ // Fallback: print-optimized HTML
486
+ const fallbackPath = pdfPath.replace(/\.pdf$/, '.print.html');
487
+ generatePrintHTML(path.resolve(htmlPath), path.resolve(fallbackPath));
488
+ note(chalk.yellow(` Chrome not found — saved print-optimized HTML: ${fallbackPath}`));
489
+ note(chalk.gray(' Open in a browser and Print → Save as PDF'));
490
+ }
491
+ }
492
+ }
493
+
494
+ if (!machineOutput && !options.csv && !options.md) {
495
+ // ── Policy Violations ──────────────────────────────────────────────────
496
+ const violations = policy.evaluate(scoreResult, filteredFindings, {
497
+ agentResults,
498
+ depsRun: options.deps !== false,
499
+ secretsRun: true,
500
+ depVulns,
501
+ });
502
+ if (violations.length > 0) {
503
+ console.log();
504
+ console.log(chalk.red.bold(' Policy Violations:'));
505
+ for (const v of violations.slice(0, 5)) {
506
+ console.log(chalk.red(` ✗ ${v.message}`));
507
+ }
508
+ }
509
+
510
+ // ── Trend ───────────────────────────────────────────────────────────────
511
+ const trend = scoringEngine.getTrend(absolutePath, scoreResult.score);
512
+ if (trend) {
513
+ const arrow = trend.diff > 0 ? chalk.green('↑') : trend.diff < 0 ? chalk.red('↓') : chalk.gray('→');
514
+ const roundedDiff = Math.round(trend.diff * 10) / 10;
515
+ const diffLabel = roundedDiff === 0 ? chalk.gray('no change') : chalk.white(`${roundedDiff > 0 ? '+' : ''}${roundedDiff}`);
516
+ console.log(chalk.gray(` Trend: ${trend.previousScore} → ${trend.currentScore} ${arrow} (`) + diffLabel + chalk.gray(')'));
517
+ }
518
+
519
+ // ── Detailed Comparison ────────────────────────────────────────────────
520
+ if (options.compare) {
521
+ printComparison(scoringEngine, absolutePath, scoreResult);
522
+ }
523
+
524
+ console.log();
525
+ console.log(chalk.cyan('═'.repeat(60)));
526
+ console.log();
527
+ }
528
+
529
+ // ── Agentic Loop (--agentic) ────────────────────────────────────────────
530
+ // Scan → annotate fixes → re-scan cycle until score >= target or maxIter.
531
+ // NOTE: process.exit() is deferred until after the loop so all iterations
532
+ // can run. The inner re-scans use _agenticInner: true to skip process.exit.
533
+ if (options.agentic && !options._agenticInner) {
534
+ const maxIter = typeof options.agentic === 'number' ? options.agentic : 3;
535
+ const targetScore = options.agenticTarget ?? 75;
536
+ let iteration = 1;
537
+ let currentScore = scoreResult.score;
538
+ let currentFindings = filteredFindings;
539
+
540
+ if (!machineOutput) {
541
+ console.log();
542
+ console.log(chalk.cyan.bold(` Agentic mode: scan→fix→verify loop (max ${maxIter} iterations, target score: ${targetScore})`));
543
+ }
544
+
545
+ while (currentScore < targetScore && iteration <= maxIter) {
546
+ if (!machineOutput) {
547
+ console.log(chalk.cyan(`\n ─── Agentic iteration ${iteration}/${maxIter} (current score: ${currentScore}) ───`));
548
+ }
549
+
550
+ const actionable = currentFindings.filter(f => f.fix && f.severity !== 'low');
551
+ if (actionable.length === 0) {
552
+ if (!machineOutput) console.log(chalk.gray(' No auto-fixable findings — stopping agentic loop.'));
553
+ break;
554
+ }
555
+
556
+ // Delegate annotation to autofix module (handles comment style, idempotency, NEVER_EDIT list)
557
+ const fixCount = applyInlineAnnotations(actionable);
558
+ if (!machineOutput) {
559
+ console.log(chalk.yellow(` Annotated ${fixCount} finding(s). Re-scanning...`));
560
+ }
561
+ if (fixCount === 0) break;
562
+
563
+ // Re-scan without recursing into the agentic loop or calling process.exit
564
+ const innerResult = await runAuditInner(targetPath, {
565
+ ...options,
566
+ agentic: false,
567
+ _agenticInner: true,
568
+ json: false,
569
+ sarif: false,
570
+ csv: false,
571
+ md: false,
572
+ html: false,
573
+ pdf: false,
574
+ quiet: true,
575
+ });
576
+
577
+ const prevScore = currentScore;
578
+ currentScore = innerResult?.score ?? currentScore;
579
+ currentFindings = innerResult?.findings ?? currentFindings;
580
+
581
+ if (!machineOutput) {
582
+ const diff = currentScore - prevScore;
583
+ const arrow = diff > 0 ? chalk.green(`↑ +${diff.toFixed(1)}`) : diff < 0 ? chalk.red(`↓ ${diff.toFixed(1)}`) : chalk.gray('→ 0');
584
+ console.log(chalk.cyan(` Re-scan score: ${currentScore} ${arrow}`));
585
+ }
586
+
587
+ iteration++;
588
+ }
589
+
590
+ if (!machineOutput) {
591
+ if (currentScore >= targetScore) {
592
+ console.log(chalk.green.bold(`\n Agentic loop complete — target score ${targetScore} reached (${currentScore}).`));
593
+ } else {
594
+ console.log(chalk.yellow(`\n Agentic loop stopped after ${iteration - 1} iteration(s). Final score: ${currentScore}`));
595
+ }
596
+ }
597
+ }
598
+
599
+ // ── Exit code logic ─────────────────────────────────────────────────────
600
+ // Only gate the exit code when --fail-below is explicitly requested;
601
+ // a plain scan reports findings and exits 0 (CI gating belongs to `scan ci`).
602
+ // Use process.exitCode (natural event-loop drain) instead of process.exit()
603
+ // so in-flight libuv handles (plugin dynamic imports, etc.) close cleanly.
604
+ if (options.failBelow !== undefined) {
605
+ let threshold = 75;
606
+ if (options.failBelow === 'baseline') {
607
+ // Read baseline score from .praxis/hermes-baseline.json
608
+ const baselinePath = path.join(absolutePath, '.praxis', 'hermes-baseline.json');
609
+ try {
610
+ const baseline = JSON.parse(fs.readFileSync(baselinePath, 'utf-8'));
611
+ threshold = baseline.score || 0;
612
+ if (!machineOutput) {
613
+ console.log(chalk.gray(` Baseline threshold: ${threshold}/100 (from ${baselinePath})`));
614
+ }
615
+ } catch {
616
+ if (!machineOutput) {
617
+ console.log(chalk.yellow(` Warning: could not read baseline — using score 0 as threshold`));
618
+ }
619
+ threshold = 0;
620
+ }
621
+ } else {
622
+ const parsed = parseInt(options.failBelow, 10);
623
+ threshold = Number.isNaN(parsed) ? 75 : parsed;
624
+ }
625
+ process.exitCode = scoreResult.score >= threshold ? 0 : 1;
626
+ }
627
+ }
628
+
629
+ /**
630
+ * Run a lightweight inner audit that returns { score, findings } without
631
+ * calling process.exit(). Used exclusively by the --agentic loop.
632
+ */
633
+ async function runAuditInner(targetPath, options) {
634
+ try {
635
+ return await auditCommand(targetPath, options);
636
+ } catch {
637
+ return null;
638
+ }
639
+ }
640
+
641
+ // =============================================================================
642
+ // REMEDIATION PLAN BUILDER
643
+ // =============================================================================
644
+
645
+ function buildRemediationPlan(findings, depVulns, rootPath) {
646
+ const plan = [];
647
+ let priority = 1;
648
+
649
+ // Exclude low-confidence findings (test files, docs, comments) from remediation plan
650
+ const actionable = findings.filter(f => f.confidence !== 'low');
651
+
652
+ // Priority order: secrets first, then by severity
653
+ const secretFindings = actionable.filter(f => f.category === 'secrets' || f.category === 'secret');
654
+ const otherFindings = actionable.filter(f => f.category !== 'secrets' && f.category !== 'secret');
655
+
656
+ // Group and sort
657
+ for (const sev of SEV_ORDER) {
658
+ // Secrets at this severity — group .env findings by file
659
+ const sevSecrets = secretFindings.filter(s => s.severity === sev);
660
+ const envGroups = new Map();
661
+ const nonEnvSecrets = [];
662
+
663
+ for (const f of sevSecrets) {
664
+ const relFile = path.relative(rootPath, f.file).replace(/\\/g, '/');
665
+ if (f.file.match(/\.env(\..*)?$/)) {
666
+ if (!envGroups.has(relFile)) envGroups.set(relFile, []);
667
+ envGroups.get(relFile).push(f);
668
+ } else {
669
+ nonEnvSecrets.push(f);
670
+ }
671
+ }
672
+
673
+ // One plan item per .env file
674
+ for (const [relFile, envFindings] of envGroups) {
675
+ const names = envFindings.map(f => f.title || f.rule).join(', ');
676
+ plan.push({
677
+ priority: priority++,
678
+ severity: sev,
679
+ category: 'secrets',
680
+ categoryLabel: 'SECRETS',
681
+ title: `${envFindings.length} secret${envFindings.length > 1 ? 's' : ''} in ${relFile} (${names})`,
682
+ file: relFile,
683
+ action: envFindings[0].fix || 'Ensure .env is in .gitignore and use a secrets manager for production',
684
+ effort: 'low',
685
+ });
686
+ }
687
+
688
+ // Individual items for non-.env secrets
689
+ for (const f of nonEnvSecrets) {
690
+ plan.push({
691
+ priority: priority++,
692
+ severity: sev,
693
+ category: 'secrets',
694
+ categoryLabel: 'SECRETS',
695
+ title: f.title || f.rule,
696
+ file: `${path.relative(rootPath, f.file).replace(/\\/g, '/')}:${f.line}`,
697
+ action: f.aiFix || f.fix || f.description,
698
+ effort: 'low',
699
+ });
700
+ }
701
+
702
+ // Other findings at this severity
703
+ for (const f of otherFindings.filter(s => s.severity === sev)) {
704
+ plan.push({
705
+ priority: priority++,
706
+ severity: sev,
707
+ category: f.category,
708
+ categoryLabel: (CATEGORY_LABELS[f.category] || f.category).toUpperCase(),
709
+ title: f.title || f.rule,
710
+ file: `${path.relative(rootPath, f.file).replace(/\\/g, '/')}:${f.line}`,
711
+ action: f.aiFix || f.fix || f.description,
712
+ effort: EFFORT_MAP[f.category] || 'medium',
713
+ });
714
+ }
715
+
716
+ // Dep vulns at this severity
717
+ for (const d of depVulns.filter(v => v.severity === sev || (sev === 'medium' && v.severity === 'moderate'))) {
718
+ plan.push({
719
+ priority: priority++,
720
+ severity: sev,
721
+ category: 'deps',
722
+ categoryLabel: 'DEPENDENCIES',
723
+ title: `Vulnerable: ${d.package || d.id}`,
724
+ file: 'package.json',
725
+ action: d.description ? `${d.description.slice(0, 80)}` : 'Update to patched version',
726
+ effort: 'medium',
727
+ });
728
+ }
729
+ }
730
+
731
+ return plan;
732
+ }
733
+
734
+ // =============================================================================
735
+ // CONSOLE OUTPUT
736
+ // =============================================================================
737
+
738
+ function printReport(scoreResult, findings, depVulns, recon, plan, rootPath, filesScanned) {
739
+ const GRADE_COLOR = { A: chalk.green.bold, B: chalk.cyan.bold, C: chalk.yellow.bold, D: chalk.red, F: chalk.red.bold };
740
+ const SEV_ICON = { critical: '🔴', high: '🟠', medium: '🟡', low: '🔵' };
741
+ const SEV_LABEL = { critical: 'CRITICAL — fix immediately', high: 'HIGH — fix before deploy', medium: 'MEDIUM — fix soon', low: 'LOW — review when possible' };
742
+
743
+ // ── Score ─────────────────────────────────────────────────────────────────
744
+ const gradeColor = GRADE_COLOR[scoreResult.grade.letter] || chalk.white;
745
+ const scoreColor = scoreResult.score >= 75 ? chalk.green.bold : scoreResult.score >= 60 ? chalk.yellow.bold : chalk.red.bold;
746
+
747
+ console.log(chalk.cyan(' ' + '═'.repeat(56)));
748
+ console.log(
749
+ chalk.white.bold(' Security Score: ') +
750
+ scoreColor(`${scoreResult.score}/100 `) +
751
+ gradeColor(scoreResult.grade.letter) +
752
+ chalk.gray(` — ${scoreResult.grade.label}`)
753
+ );
754
+ console.log(chalk.cyan(' ' + '═'.repeat(56)));
755
+ console.log();
756
+
757
+ // ── Category Breakdown ────────────────────────────────────────────────────
758
+ console.log(chalk.white.bold(' Category Breakdown'));
759
+ console.log(chalk.gray(' ' + '─'.repeat(56)));
760
+
761
+ for (const [key, cat] of Object.entries(scoreResult.categories)) {
762
+ const count = Object.values(cat.counts).reduce((a, b) => a + b, 0);
763
+ const icon = count === 0 ? chalk.green('✔') : chalk.red('✘');
764
+ const status = count === 0 ? chalk.green('clean') : chalk.red(`${count} issue(s)`);
765
+ const deduction = cat.deduction > 0 ? chalk.red(`-${Math.round(cat.deduction * 10) / 10} pts`) : chalk.gray('+0');
766
+ console.log(` ${icon} ${chalk.white(cat.label.padEnd(22))} ${status.padEnd(25)} ${deduction}`);
767
+ }
768
+
769
+ // Deps row — only print if not already included in scoreResult.categories
770
+ const hasDepsCategory = Object.values(scoreResult.categories).some(c => c.label?.toLowerCase().includes('depend'));
771
+ if (!hasDepsCategory) {
772
+ const depIcon = depVulns.length === 0 ? chalk.green('✔') : chalk.red('✘');
773
+ const depStatus = depVulns.length === 0 ? chalk.green('clean') : chalk.red(`${depVulns.length} CVE(s)`);
774
+ console.log(` ${depIcon} ${chalk.white('Dependencies'.padEnd(22))} ${depStatus}`);
775
+ }
776
+
777
+ console.log(chalk.gray(`\n Files scanned: ${filesScanned} | Findings: ${findings.length} | CVEs: ${depVulns.length}`));
778
+
779
+ // ── Remediation Plan ──────────────────────────────────────────────────────
780
+ if (plan.length > 0) {
781
+ console.log();
782
+ console.log(chalk.cyan(' ' + '═'.repeat(56)));
783
+ console.log(chalk.cyan.bold(' Remediation Plan'));
784
+ console.log(chalk.cyan(' ' + '═'.repeat(56)));
785
+
786
+ let currentSev = null;
787
+ let shown = 0;
788
+ const maxItems = 30;
789
+
790
+ for (const item of plan) {
791
+ if (shown >= maxItems) {
792
+ console.log(chalk.gray(`\n ... and ${plan.length - maxItems} more items in the full report`));
793
+ break;
794
+ }
795
+
796
+ if (item.severity !== currentSev) {
797
+ currentSev = item.severity;
798
+ console.log();
799
+ console.log(chalk.white.bold(` ${SEV_ICON[currentSev] || '⚪'} ${SEV_LABEL[currentSev] || currentSev.toUpperCase()}`));
800
+ console.log(chalk.gray(' ' + '─'.repeat(56)));
801
+ }
802
+
803
+ console.log(
804
+ chalk.white(` ${String(item.priority).padStart(2)}.`) +
805
+ chalk.gray(` [${item.categoryLabel}] `) +
806
+ chalk.white(item.title)
807
+ );
808
+ console.log(
809
+ chalk.gray(` ${item.file}`) +
810
+ chalk.gray(' → ') +
811
+ chalk.green((item.action || '').slice(0, 70))
812
+ );
813
+ shown++;
814
+ }
815
+ } else {
816
+ console.log();
817
+ console.log(chalk.green.bold(' All clear — safe to ship!'));
818
+ }
819
+
820
+ // ── Attack Surface ────────────────────────────────────────────────────────
821
+ if (recon) {
822
+ console.log();
823
+ console.log(chalk.gray(' Attack Surface:'));
824
+ if (recon.frameworks?.length) console.log(chalk.gray(` Frameworks: ${recon.frameworks.join(', ')}`));
825
+ if (recon.databases?.length) console.log(chalk.gray(` Databases: ${recon.databases.join(', ')}`));
826
+ if (recon.authPatterns?.length) console.log(chalk.gray(` Auth: ${recon.authPatterns.join(', ')}`));
827
+ if (recon.apiRoutes?.length) console.log(chalk.gray(` API Routes: ${recon.apiRoutes.length} discovered`));
828
+ }
829
+ }
830
+
831
+ // =============================================================================
832
+ // JSON OUTPUT
833
+ // =============================================================================
834
+
835
+ function outputJSON(scoreResult, findings, depVulns, recon, agentResults, remediationPlan, suppressions, history, filesScanned = null) {
836
+ const output = {
837
+ score: scoreResult.score,
838
+ grade: scoreResult.grade.letter,
839
+ gradeLabel: scoreResult.grade.label,
840
+ totalFindings: findings.length,
841
+ totalDepVulns: depVulns.length,
842
+ categories: Object.fromEntries(
843
+ Object.entries(scoreResult.categories).map(([k, v]) => [k, {
844
+ label: v.label,
845
+ findingCount: Object.values(v.counts).reduce((a, b) => a + b, 0),
846
+ deduction: v.deduction,
847
+ counts: v.counts,
848
+ }])
849
+ ),
850
+ findings: findings.map(f => {
851
+ const normFile = String(f.file || '')
852
+ .replace(/\\/g, '/')
853
+ .replace(/^[a-zA-Z]:\/+/, '')
854
+ .replace(/^.*\/Praxis\/showcase-target\//, 'showcase-target/')
855
+ .replace(/^.*\/Praxis\//, '');
856
+ return {
857
+ file: normFile, line: f.line, severity: f.severity, category: f.category,
858
+ rule: f.rule, title: f.title, description: f.description, fix: f.fix,
859
+ cwe: f.cwe, owasp: f.owasp,
860
+ ...(f.eaa ? { eaa: f.eaa } : {}),
861
+ ...(f.confidence ? { confidence: f.confidence } : {}),
862
+ ...(f.standards ? { standards: f.standards } : {}),
863
+ ...(f.deepAnalysis ? { deepAnalysis: f.deepAnalysis } : {}),
864
+ ...(f.aiClassification ? {
865
+ aiClassification: f.aiClassification,
866
+ ...(f.aiReason ? { aiReason: f.aiReason } : {}),
867
+ ...(f.aiFix ? { aiFix: f.aiFix } : {}),
868
+ } : {}),
869
+ };
870
+ }),
871
+ depVulns: depVulns.map(d => ({
872
+ severity: d.severity, package: d.package || d.id, description: d.description,
873
+ })),
874
+ remediationPlan,
875
+ recon,
876
+ agents: agentResults,
877
+ // Provenance: which tool, runtime and vendored data produced these numbers (P-IMP-053).
878
+ fingerprint: buildScanFingerprint({ filesScanned }),
879
+ };
880
+ if (scoreResult.compliance) output.compliance = scoreResult.compliance;
881
+ if (scoreResult.standardsSummary) output.standardsSummary = scoreResult.standardsSummary;
882
+ if (scoreResult.agenticSummary) output.agenticSummary = scoreResult.agenticSummary;
883
+ if (suppressions) output.suppressions = suppressions;
884
+ if (history && history.length >= 2) {
885
+ const prev = history[history.length - 2];
886
+ output.comparison = {
887
+ previousScore: prev.score,
888
+ previousGrade: prev.grade,
889
+ previousDate: prev.timestamp,
890
+ diff: scoreResult.score - prev.score,
891
+ categoryComparison: Object.fromEntries(
892
+ Object.entries(scoreResult.categories).map(([k, v]) => {
893
+ const prevCat = prev.categoryScores?.[k];
894
+ return [k, {
895
+ label: v.label,
896
+ current: -v.deduction,
897
+ previous: prevCat ? -prevCat.deduction : 0,
898
+ delta: prevCat ? prevCat.deduction - v.deduction : 0,
899
+ }];
900
+ })
901
+ ),
902
+ };
903
+ }
904
+ console.log(JSON.stringify(output, null, 2));
905
+ }
906
+
907
+ // =============================================================================
908
+ // SARIF OUTPUT
909
+ // =============================================================================
910
+
911
+ /**
912
+ * SARIF for GitHub Code Scanning.
913
+ *
914
+ * Delegates to the shared serializer in `cli/core/output/sarif.js` (P-IMP-062). This was
915
+ * a private copy, hardcoding a driver version of `4.0.0` while the package was at a
916
+ * different number entirely, and it carried no `security-severity` — so the default
917
+ * `praxis scan` lost severity fidelity in Code Scanning.
918
+ */
919
+ function outputSARIF(findings, rootPath) {
920
+ console.log(renderFindingsSARIF(findings, { rootPath }));
921
+ }
922
+
923
+ // =============================================================================
924
+ // FILE SCANNING (inline from scan.js to avoid circular deps)
925
+ // =============================================================================
926
+
927
+ // Walk up from `start` looking for `name`. Returns the absolute path or null.
928
+ // Bounded to 8 ancestors to avoid runaway loops on weird filesystems.
929
+ function findUpwards(start, name) {
930
+ let dir = path.resolve(start);
931
+ for (let i = 0; i < 8; i++) {
932
+ const candidate = path.join(dir, name);
933
+ if (fs.existsSync(candidate)) return candidate;
934
+ const parent = path.dirname(dir);
935
+ if (parent === dir) return null;
936
+ dir = parent;
937
+ }
938
+ return null;
939
+ }
940
+
941
+ async function findFiles(rootPath) {
942
+ const globIgnore = Array.from(SKIP_DIRS).map(dir => `**/${dir}/**`);
943
+
944
+ // Respect .gitignore patterns
945
+ const gitignoreGlobs = loadGitignorePatterns(rootPath);
946
+ globIgnore.push(...gitignoreGlobs);
947
+
948
+ // Load .praxisignore — walk up to the project root so subdirectory scans
949
+ // still honor the repo-level ignore file.
950
+ const ignorePath = findUpwards(rootPath, '.praxisignore');
951
+ if (ignorePath) {
952
+ try {
953
+ const patterns = fs.readFileSync(ignorePath, 'utf-8')
954
+ .split('\n').map(l => l.trim()).filter(l => l && !l.startsWith('#'));
955
+ for (const p of patterns) {
956
+ if (p.endsWith('/')) { globIgnore.push(`**/${p}**`); }
957
+ else { globIgnore.push(`**/${p}`); globIgnore.push(p); }
958
+ }
959
+ } catch { /* skip */ }
960
+ }
961
+
962
+ const files = await fg('**/*', {
963
+ cwd: rootPath, absolute: true, onlyFiles: true, ignore: globIgnore, dot: true
964
+ });
965
+
966
+ return files.filter(file => {
967
+ const ext = path.extname(file).toLowerCase();
968
+ if (SKIP_EXTENSIONS.has(ext)) return false;
969
+ if (SKIP_FILENAMES.has(path.basename(file))) return false;
970
+ if (path.basename(file).endsWith('.min.js') || path.basename(file).endsWith('.min.css')) return false;
971
+ try { if (fs.statSync(file).size > MAX_FILE_SIZE) return false; } catch { return false; }
972
+ return true;
973
+ });
974
+ }
975
+
976
+ function scanFileForSecrets(filePath) {
977
+ const findings = [];
978
+ try {
979
+ const content = fs.readFileSync(filePath, 'utf-8');
980
+ const lines = content.split('\n');
981
+ for (let lineNum = 0; lineNum < lines.length; lineNum++) {
982
+ const line = lines[lineNum];
983
+ if (/praxis-ignore/i.test(line)) continue;
984
+ for (const pattern of SECRET_PATTERNS) {
985
+ pattern.pattern.lastIndex = 0;
986
+ let match;
987
+ while ((match = pattern.pattern.exec(line)) !== null) {
988
+ if (pattern.requiresEntropyCheck && !isHighEntropyMatch(match[0])) continue;
989
+ findings.push({
990
+ line: lineNum + 1, column: match.index + 1, matched: match[0],
991
+ patternName: pattern.name, severity: pattern.severity,
992
+ confidence: getConfidence(pattern, match[0]),
993
+ description: pattern.description, category: pattern.category || 'secret'
994
+ });
995
+ }
996
+ }
997
+ }
998
+ } catch { /* skip */ }
999
+
1000
+ const seen = new Set();
1001
+ return findings.filter(f => {
1002
+ const key = `${f.line}:${f.matched}`;
1003
+ if (seen.has(key)) return false;
1004
+ seen.add(key);
1005
+ return true;
1006
+ });
1007
+ }
1008
+
1009
+ function deduplicateFindings(findings) {
1010
+ const seen = new Set();
1011
+ return findings.filter(f => {
1012
+ const key = `${f.file}:${f.line}:${f.rule}`;
1013
+ if (seen.has(key)) return false;
1014
+ seen.add(key);
1015
+ return true;
1016
+ });
1017
+ }
1018
+
1019
+ // =============================================================================
1020
+ // SUPPRESSION COUNTING
1021
+ // =============================================================================
1022
+
1023
+ function countSuppressions(files) {
1024
+ const suppressions = {};
1025
+ let total = 0;
1026
+ for (const file of files) {
1027
+ try {
1028
+ const content = fs.readFileSync(file, 'utf-8');
1029
+ const lines = content.split('\n');
1030
+ for (const line of lines) {
1031
+ if (/praxis-ignore/i.test(line)) {
1032
+ total++;
1033
+ // Try to extract rule name from comment: praxis-ignore RULE_NAME
1034
+ const match = line.match(/praxis-ignore\s+(\w+)/i);
1035
+ const rule = match ? match[1] : '_unspecified';
1036
+ suppressions[rule] = (suppressions[rule] || 0) + 1;
1037
+ }
1038
+ }
1039
+ } catch { /* skip */ }
1040
+ }
1041
+ return total > 0 ? { total, rules: suppressions } : null;
1042
+ }
1043
+
1044
+ // =============================================================================
1045
+ // CSV OUTPUT
1046
+ // =============================================================================
1047
+
1048
+ function outputCSV(findings, depVulns, scoreResult, rootPath) {
1049
+ const escape = (s) => {
1050
+ if (!s) return '';
1051
+ const str = String(s).replace(/"/g, '""');
1052
+ return str.includes(',') || str.includes('"') || str.includes('\n') ? `"${str}"` : str;
1053
+ };
1054
+
1055
+ console.log('severity,category,rule,file,line,title,description,fix');
1056
+ for (const f of findings) {
1057
+ const relFile = path.relative(rootPath, f.file).replace(/\\/g, '/');
1058
+ console.log([
1059
+ escape(f.severity), escape(f.category), escape(f.rule),
1060
+ escape(relFile), f.line || '', escape(f.title),
1061
+ escape(f.description), escape(f.fix),
1062
+ ].join(','));
1063
+ }
1064
+ for (const d of depVulns) {
1065
+ console.log([
1066
+ escape(d.severity), 'deps', escape(d.id || d.package),
1067
+ 'package.json', '', escape(`Vulnerable: ${d.package || d.id}`),
1068
+ escape(d.description), escape('Update to patched version'),
1069
+ ].join(','));
1070
+ }
1071
+ }
1072
+
1073
+ // =============================================================================
1074
+ // MARKDOWN OUTPUT
1075
+ // =============================================================================
1076
+
1077
+ function outputMarkdown(scoreResult, findings, depVulns, remediationPlan, rootPath) {
1078
+ const lines = [];
1079
+ lines.push('# Praxis Security Report');
1080
+ lines.push('');
1081
+ lines.push(`**Score: ${scoreResult.score}/100 (${scoreResult.grade.letter})** — ${scoreResult.grade.label}`);
1082
+ lines.push('');
1083
+ lines.push(`> Generated: ${new Date().toISOString()}`);
1084
+ lines.push('');
1085
+
1086
+ // Category breakdown
1087
+ lines.push('## Category Breakdown');
1088
+ lines.push('');
1089
+ lines.push('| Category | Issues | Deduction |');
1090
+ lines.push('|----------|--------|-----------|');
1091
+ for (const [, cat] of Object.entries(scoreResult.categories)) {
1092
+ const count = Object.values(cat.counts).reduce((a, b) => a + b, 0);
1093
+ lines.push(`| ${cat.label} | ${count} | -${cat.deduction} |`);
1094
+ }
1095
+ lines.push('');
1096
+
1097
+ // Findings by severity
1098
+ for (const sev of SEV_ORDER) {
1099
+ const sevFindings = findings.filter(f => f.severity === sev);
1100
+ if (sevFindings.length === 0) continue;
1101
+
1102
+ lines.push(`## ${sev.charAt(0).toUpperCase() + sev.slice(1)} (${sevFindings.length})`);
1103
+ lines.push('');
1104
+ lines.push('| File | Rule | Description | Fix |');
1105
+ lines.push('|------|------|-------------|-----|');
1106
+ for (const f of sevFindings) {
1107
+ const relFile = path.relative(rootPath, f.file).replace(/\\/g, '/');
1108
+ lines.push(`| ${relFile}:${f.line} | ${f.rule} | ${(f.description || '').slice(0, 80)} | ${(f.fix || '').slice(0, 60)} |`);
1109
+ }
1110
+ lines.push('');
1111
+ }
1112
+
1113
+ // Dep vulns
1114
+ if (depVulns.length > 0) {
1115
+ lines.push('## Dependency Vulnerabilities');
1116
+ lines.push('');
1117
+ lines.push('| Severity | Package | Description |');
1118
+ lines.push('|----------|---------|-------------|');
1119
+ for (const d of depVulns) {
1120
+ lines.push(`| ${d.severity} | ${d.package || d.id} | ${(d.description || '').slice(0, 80)} |`);
1121
+ }
1122
+ lines.push('');
1123
+ }
1124
+
1125
+ console.log(lines.join('\n'));
1126
+ }
1127
+
1128
+ // =============================================================================
1129
+ // COMPARISON OUTPUT
1130
+ // =============================================================================
1131
+
1132
+ function printComparison(scoringEngine, rootPath, scoreResult) {
1133
+ const history = scoringEngine.loadHistory(rootPath);
1134
+ if (history.length < 2) {
1135
+ console.log(chalk.gray('\n No previous scan to compare against.'));
1136
+ return;
1137
+ }
1138
+
1139
+ const prev = history[history.length - 2];
1140
+ console.log();
1141
+ console.log(chalk.cyan.bold(' Detailed Comparison'));
1142
+ console.log(chalk.gray(' ' + '─'.repeat(56)));
1143
+ console.log(chalk.gray(` Previous scan: ${new Date(prev.timestamp).toLocaleString()}`));
1144
+ console.log();
1145
+ console.log(chalk.white(' Category'.padEnd(26)) + chalk.white('Previous'.padEnd(12)) + chalk.white('Current'.padEnd(12)) + chalk.white('Delta'));
1146
+ console.log(chalk.gray(' ' + '─'.repeat(56)));
1147
+
1148
+ for (const [key, cat] of Object.entries(scoreResult.categories)) {
1149
+ const prevCat = prev.categoryScores?.[key];
1150
+ const prevDed = prevCat ? prevCat.deduction : 0;
1151
+ const curDed = cat.deduction;
1152
+ const delta = prevDed - curDed;
1153
+
1154
+ let deltaStr;
1155
+ if (delta > 0) deltaStr = chalk.green(`+${delta} improved`);
1156
+ else if (delta < 0) deltaStr = chalk.red(`${delta} regressed`);
1157
+ else deltaStr = chalk.gray('→ unchanged');
1158
+
1159
+ console.log(
1160
+ ` ${chalk.white(cat.label.padEnd(24))}` +
1161
+ `${chalk.gray(String(-prevDed).padEnd(12))}` +
1162
+ `${chalk.gray(String(-curDed).padEnd(12))}` +
1163
+ deltaStr
1164
+ );
1165
+ }
1166
+
1167
+ const overallDiff = scoreResult.score - prev.score;
1168
+ let overallDelta;
1169
+ if (overallDiff > 0) overallDelta = chalk.green(`+${overallDiff} improved`);
1170
+ else if (overallDiff < 0) overallDelta = chalk.red(`${overallDiff} regressed`);
1171
+ else overallDelta = chalk.gray('→ unchanged');
1172
+
1173
+ console.log(chalk.gray(' ' + '─'.repeat(56)));
1174
+ console.log(
1175
+ ` ${chalk.white.bold('Overall'.padEnd(24))}` +
1176
+ `${chalk.gray(`${prev.score}/100 ${prev.grade}`.padEnd(12))}` +
1177
+ `${chalk.gray(`${scoreResult.score}/100 ${scoreResult.grade.letter}`.padEnd(12))}` +
1178
+ overallDelta
1179
+ );
1180
+ }