ship-safe 6.1.1 → 6.2.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 (47) hide show
  1. package/README.md +735 -641
  2. package/cli/agents/api-fuzzer.js +345 -345
  3. package/cli/agents/auth-bypass-agent.js +348 -348
  4. package/cli/agents/base-agent.js +272 -272
  5. package/cli/agents/cicd-scanner.js +236 -201
  6. package/cli/agents/config-auditor.js +521 -521
  7. package/cli/agents/deep-analyzer.js +6 -2
  8. package/cli/agents/git-history-scanner.js +170 -170
  9. package/cli/agents/html-reporter.js +568 -568
  10. package/cli/agents/index.js +84 -84
  11. package/cli/agents/injection-tester.js +500 -500
  12. package/cli/agents/llm-redteam.js +251 -251
  13. package/cli/agents/mobile-scanner.js +231 -231
  14. package/cli/agents/orchestrator.js +322 -322
  15. package/cli/agents/pii-compliance-agent.js +301 -301
  16. package/cli/agents/scoring-engine.js +248 -248
  17. package/cli/agents/supabase-rls-agent.js +154 -154
  18. package/cli/agents/supply-chain-agent.js +650 -507
  19. package/cli/bin/ship-safe.js +452 -426
  20. package/cli/commands/agent.js +608 -608
  21. package/cli/commands/audit.js +986 -980
  22. package/cli/commands/baseline.js +193 -193
  23. package/cli/commands/ci.js +342 -342
  24. package/cli/commands/deps.js +516 -516
  25. package/cli/commands/doctor.js +159 -159
  26. package/cli/commands/fix.js +218 -218
  27. package/cli/commands/hooks.js +268 -0
  28. package/cli/commands/init.js +407 -407
  29. package/cli/commands/mcp.js +304 -304
  30. package/cli/commands/red-team.js +7 -1
  31. package/cli/commands/remediate.js +798 -798
  32. package/cli/commands/rotate.js +571 -571
  33. package/cli/commands/scan.js +569 -569
  34. package/cli/commands/score.js +449 -449
  35. package/cli/commands/watch.js +281 -281
  36. package/cli/hooks/patterns.js +313 -0
  37. package/cli/hooks/post-tool-use.js +140 -0
  38. package/cli/hooks/pre-tool-use.js +186 -0
  39. package/cli/index.js +73 -69
  40. package/cli/providers/llm-provider.js +397 -287
  41. package/cli/utils/autofix-rules.js +74 -74
  42. package/cli/utils/cache-manager.js +311 -311
  43. package/cli/utils/output.js +230 -230
  44. package/cli/utils/patterns.js +1121 -1121
  45. package/cli/utils/pdf-generator.js +94 -94
  46. package/package.json +69 -69
  47. package/configs/supabase/rls-templates.sql +0 -242
@@ -1,980 +1,986 @@
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 ship-safe audit [path] Full audit with HTML report
10
- * npx ship-safe audit . --json JSON output
11
- * npx ship-safe audit . --html report.html Custom report path
12
- * npx ship-safe audit . --no-deps Skip dependency audit
13
- */
14
-
15
- import fs from 'fs';
16
- import path from 'path';
17
- import chalk from 'chalk';
18
- import ora from 'ora';
19
- import fg from 'fast-glob';
20
- import { buildOrchestrator } from '../agents/index.js';
21
- import { ScoringEngine } from '../agents/scoring-engine.js';
22
- import { PolicyEngine } from '../agents/policy-engine.js';
23
- import { HTMLReporter } from '../agents/html-reporter.js';
24
- import { SBOMGenerator } from '../agents/sbom-generator.js';
25
- import { autoDetectProvider } from '../providers/llm-provider.js';
26
- import { runDepsAudit } from './deps.js';
27
- import {
28
- SECRET_PATTERNS,
29
- SECURITY_PATTERNS,
30
- SKIP_DIRS,
31
- SKIP_EXTENSIONS,
32
- SKIP_FILENAMES,
33
- MAX_FILE_SIZE,
34
- loadGitignorePatterns
35
- } from '../utils/patterns.js';
36
- import { isHighEntropyMatch, getConfidence } from '../utils/entropy.js';
37
- import { CacheManager } from '../utils/cache-manager.js';
38
- import { filterBaseline } from './baseline.js';
39
- import { generatePDF, generatePrintHTML, isChromeAvailable } from '../utils/pdf-generator.js';
40
- import { SecretsVerifier } from '../utils/secrets-verifier.js';
41
-
42
- // =============================================================================
43
- // CONSTANTS
44
- // =============================================================================
45
-
46
- const ALL_PATTERNS = [...SECRET_PATTERNS, ...SECURITY_PATTERNS];
47
-
48
- const SEV_ORDER = ['critical', 'high', 'medium', 'low'];
49
-
50
- const CATEGORY_LABELS = {
51
- secrets: 'Secrets',
52
- injection: 'Code Vulnerabilities',
53
- deps: 'Dependencies',
54
- auth: 'Auth & Access Control',
55
- config: 'Configuration',
56
- 'supply-chain': 'Supply Chain',
57
- api: 'API Security',
58
- llm: 'AI/LLM Security',
59
- };
60
-
61
- const EFFORT_MAP = {
62
- secrets: 'low',
63
- config: 'low',
64
- deps: 'medium',
65
- injection: 'medium',
66
- auth: 'medium',
67
- 'supply-chain': 'medium',
68
- api: 'medium',
69
- llm: 'high',
70
- };
71
-
72
- // =============================================================================
73
- // MAIN COMMAND
74
- // =============================================================================
75
-
76
- export async function auditCommand(targetPath = '.', options = {}) {
77
- const absolutePath = path.resolve(targetPath);
78
- const machineOutput = options.json || options.sarif || options.csv || options.md;
79
-
80
- if (!fs.existsSync(absolutePath)) {
81
- console.error(chalk.red(` Path does not exist: ${absolutePath}`));
82
- process.exit(1);
83
- }
84
-
85
- if (!machineOutput) {
86
- console.log();
87
- console.log(chalk.cyan('═'.repeat(60)));
88
- console.log(chalk.cyan.bold(' Ship Safe — Full Security Audit'));
89
- console.log(chalk.cyan('═'.repeat(60)));
90
- console.log();
91
- }
92
-
93
- // ── Cache Layer ──────────────────────────────────────────────────────────
94
- const useCache = options.cache !== false;
95
- const cache = new CacheManager(absolutePath);
96
- let cacheData = useCache ? cache.load() : null;
97
- let cacheDiff = null;
98
- let allFiles = [];
99
-
100
- // ── Phase 1: Secret Scan ──────────────────────────────────────────────────
101
- const secretSpinner = machineOutput ? null : ora({ text: chalk.white('[Phase 1/4] Scanning for secrets...'), color: 'cyan' }).start();
102
- let secretFindings = [];
103
- let filesScanned = 0;
104
-
105
- try {
106
- allFiles = await findFiles(absolutePath);
107
- filesScanned = allFiles.length;
108
-
109
- // Determine which files need scanning (incremental if cache exists)
110
- let filesToScan = allFiles;
111
- let cachedSecretFindings = [];
112
-
113
- if (cacheData) {
114
- cacheDiff = cache.diff(allFiles);
115
- filesToScan = cacheDiff.changedFiles;
116
- // Reuse cached findings for unchanged files (secrets only)
117
- cachedSecretFindings = cacheDiff.cachedFindings.filter(
118
- f => f.category === 'secrets' || f.category === 'secret'
119
- );
120
- }
121
-
122
- for (const file of filesToScan) {
123
- const fileResults = scanFileForSecrets(file);
124
- for (const f of fileResults) {
125
- secretFindings.push({
126
- file,
127
- line: f.line,
128
- column: f.column,
129
- severity: f.severity,
130
- category: f.category || 'secrets',
131
- rule: f.patternName,
132
- title: f.patternName.replace(/_/g, ' '),
133
- description: f.description,
134
- matched: f.matched,
135
- confidence: f.confidence,
136
- fix: file.match(/\.env(\..*)?$/)
137
- ? `Ensure .env is in .gitignore and use a secrets manager for production`
138
- : `Move to environment variable or secrets manager`,
139
- });
140
- }
141
- }
142
-
143
- // Downgrade .env findings if the file is gitignored (properly managed)
144
- const gitignoreContent = (() => {
145
- try { return fs.readFileSync(path.join(absolutePath, '.gitignore'), 'utf-8'); } catch { return ''; }
146
- })();
147
- const envIsGitignored = gitignoreContent.split('\n')
148
- .map(l => l.trim())
149
- .some(l => /^\.env(\s|$)/.test(l) || l === '*.env' || l === '.env*' || l === '.env.local' || l === '.env.production');
150
-
151
- if (envIsGitignored) {
152
- for (const f of secretFindings) {
153
- if (f.file.match(/\.env(\..*)?$/) && !f.file.includes('node_modules')) {
154
- f.severity = 'low';
155
- f.confidence = 'low';
156
- f.fix = 'Already gitignored — ensure secrets manager is used for production deploys';
157
- }
158
- }
159
- }
160
-
161
- // Downgrade secrets in test files (intentional test fixtures)
162
- const TEST_PATH = /(?:__tests__|\.test\.|\.spec\.|\/test\/|\/tests\/|\/fixtures?\/)/i;
163
- for (const f of secretFindings) {
164
- if (TEST_PATH.test(f.file)) {
165
- f.confidence = 'low';
166
- }
167
- }
168
-
169
- // Merge with cached findings for unchanged files
170
- secretFindings = [...secretFindings, ...cachedSecretFindings];
171
-
172
- const cacheNote = cacheDiff && cacheDiff.changedFiles.length < allFiles.length
173
- ? ` (${cacheDiff.changedFiles.length} changed, ${cacheDiff.unchangedCount} cached)`
174
- : '';
175
-
176
- if (secretSpinner) secretSpinner.succeed(
177
- secretFindings.length === 0
178
- ? chalk.green(`[Phase 1/4] Secrets: clean${cacheNote}`)
179
- : chalk.red(`[Phase 1/4] Secrets: ${secretFindings.length} found${cacheNote}`)
180
- );
181
- } catch (err) {
182
- if (secretSpinner) secretSpinner.fail(chalk.red(`[Phase 1/4] Secret scan failed: ${err.message}`));
183
- }
184
-
185
- // ── Phase 2: Agent Scan ───────────────────────────────────────────────────
186
- const orchestrator = buildOrchestrator();
187
- const registeredAgentCount = orchestrator.agents?.length || 15;
188
- const agentSpinner = machineOutput ? null : ora({ text: chalk.white(`[Phase 2/4] Running ${registeredAgentCount} security agents...`), color: 'cyan' }).start();
189
- let agentFindings = [];
190
- let recon = null;
191
- let agentResults = [];
192
-
193
- try {
194
- // Suppress individual agent spinners by using quiet mode
195
- // Pass changedFiles for incremental scanning if cache is valid
196
- const orchestratorOpts = { quiet: true };
197
- if (options.deep) orchestratorOpts.deep = true;
198
- if (options.local) orchestratorOpts.local = true;
199
- if (options.model) orchestratorOpts.model = options.model;
200
- if (options.budget) orchestratorOpts.budget = options.budget;
201
- if (options.verbose) orchestratorOpts.verbose = true;
202
- if (cacheDiff && cacheDiff.changedFiles.length < allFiles.length) {
203
- orchestratorOpts.changedFiles = cacheDiff.changedFiles;
204
- }
205
- const results = await orchestrator.runAll(absolutePath, orchestratorOpts); // ship-safe-ignore — orchestrator result, not LLM output triggering actions
206
- recon = results.recon;
207
- agentFindings = results.findings;
208
- agentResults = results.agentResults;
209
-
210
- const totalAgentFindings = agentFindings.length;
211
- const agentCount = agentResults.filter(a => a.success).length;
212
- if (agentSpinner) agentSpinner.succeed(
213
- totalAgentFindings === 0
214
- ? chalk.green(`[Phase 2/4] ${agentCount} agents: clean`)
215
- : chalk.yellow(`[Phase 2/4] ${agentCount} agents: ${totalAgentFindings} finding(s)`)
216
- );
217
- } catch (err) {
218
- if (agentSpinner) agentSpinner.fail(chalk.red(`[Phase 2/4] Agent scan failed: ${err.message}`));
219
- }
220
-
221
- // ── Phase 3: Dependency Audit ─────────────────────────────────────────────
222
- let depVulns = [];
223
- if (options.deps !== false) {
224
- const depSpinner = machineOutput ? null : ora({ text: chalk.white('[Phase 3/4] Auditing dependencies...'), color: 'cyan' }).start();
225
- try {
226
- const depResult = await runDepsAudit(absolutePath);
227
- depVulns = depResult.vulns || [];
228
- if (depSpinner) depSpinner.succeed(
229
- depVulns.length === 0
230
- ? chalk.green('[Phase 3/4] Dependencies: clean')
231
- : chalk.red(`[Phase 3/4] Dependencies: ${depVulns.length} CVE(s)`)
232
- );
233
- } catch {
234
- if (depSpinner) depSpinner.succeed(chalk.gray('[Phase 3/4] Dependencies: skipped (no manifest)'));
235
- }
236
- } else if (!machineOutput) {
237
- console.log(chalk.gray(' [Phase 3/4] Dependencies: skipped (--no-deps)'));
238
- }
239
-
240
- // ── Phase 4: Merge, Score, and Build Plan ─────────────────────────────────
241
- const scoreSpinner = machineOutput ? null : ora({ text: chalk.white('[Phase 4/4] Computing security score...'), color: 'cyan' }).start();
242
-
243
- // Merge secret findings + agent findings, deduplicate
244
- const allFindings = deduplicateFindings([...secretFindings, ...agentFindings]);
245
-
246
- // Apply policy
247
- const policy = PolicyEngine.load(absolutePath);
248
- let filteredFindings = policy.applyPolicy(allFindings);
249
-
250
- // Apply baseline filter (only show new findings)
251
- if (options.baseline) {
252
- const beforeCount = filteredFindings.length;
253
- filteredFindings = filterBaseline(filteredFindings, absolutePath);
254
- if (!machineOutput && beforeCount !== filteredFindings.length) {
255
- console.log(chalk.gray(` Baseline: ${beforeCount - filteredFindings.length} known finding(s) filtered, ${filteredFindings.length} new`));
256
- }
257
- }
258
-
259
- // Count suppressions (ship-safe-ignore comments)
260
- const suppressions = countSuppressions(allFiles);
261
-
262
- // Score
263
- const scoringEngine = new ScoringEngine();
264
- const scoreResult = scoringEngine.compute(filteredFindings, depVulns);
265
- // Round score to 1 decimal place to avoid floating-point noise (e.g., 63.300000000000004)
266
- scoreResult.score = Math.round(scoreResult.score * 10) / 10;
267
- scoringEngine.saveToHistory(absolutePath, scoreResult, suppressions);
268
-
269
- const gradeColor = scoreResult.score >= 75 ? chalk.green.bold : scoreResult.score >= 60 ? chalk.yellow.bold : chalk.red.bold;
270
- if (scoreSpinner) scoreSpinner.succeed(
271
- chalk.white('[Phase 4/4] Score: ') + gradeColor(`${scoreResult.score}/100 ${scoreResult.grade.letter}`)
272
- );
273
-
274
- // ── AI Classification (optional, with LLM cache) ───────────────────────
275
- if (options.ai !== false) {
276
- const provider = autoDetectProvider(absolutePath);
277
- if (provider && filteredFindings.length > 0 && filteredFindings.length <= 50) {
278
- const aiSpinner = machineOutput ? null : ora({ text: `Classifying with ${provider.name}...`, color: 'cyan' }).start();
279
- try {
280
- // Check LLM cache for existing classifications
281
- const llmCache = cache.loadLLMClassifications();
282
- const uncachedFindings = [];
283
- let cachedCount = 0;
284
-
285
- for (const finding of filteredFindings) {
286
- const key = cache.getLLMCacheKey(finding);
287
- const cached = llmCache[key];
288
- if (cached) {
289
- finding.aiClassification = cached.classification;
290
- finding.aiReason = cached.reason;
291
- finding.aiFix = cached.fix;
292
- cachedCount++;
293
- } else {
294
- uncachedFindings.push(finding);
295
- }
296
- }
297
-
298
- // Only send uncached findings to LLM
299
- if (uncachedFindings.length > 0) {
300
- const classifications = await provider.classify(uncachedFindings);
301
- const newCacheEntries = {};
302
- for (const cl of classifications) {
303
- const finding = filteredFindings.find(f => `${f.file}:${f.line}` === cl.id);
304
- if (finding) {
305
- finding.aiClassification = cl.classification;
306
- finding.aiReason = cl.reason;
307
- finding.aiFix = cl.fix;
308
- const key = cache.getLLMCacheKey(finding);
309
- newCacheEntries[key] = {
310
- classification: cl.classification,
311
- reason: cl.reason,
312
- fix: cl.fix,
313
- cachedAt: new Date().toISOString(),
314
- };
315
- }
316
- }
317
- cache.saveLLMClassifications(newCacheEntries);
318
- }
319
-
320
- const cacheNote = cachedCount > 0 ? `, ${cachedCount} cached` : '';
321
- if (aiSpinner) aiSpinner.succeed(chalk.green(`AI classification complete (${provider.name}${cacheNote})`));
322
- } catch (err) {
323
- if (aiSpinner) aiSpinner.fail(chalk.yellow(`AI classification failed: ${err.message}`));
324
- }
325
- }
326
- }
327
-
328
- // ── Secrets Verification (optional, --verify flag) ─────────────────────
329
- if (options.verify) {
330
- const verifySpinner = machineOutput ? null : ora({ text: 'Verifying leaked secrets against provider APIs...', color: 'cyan' }).start();
331
- try {
332
- const verifier = new SecretsVerifier();
333
- const verifyResults = await verifier.verify(filteredFindings);
334
- const activeCount = verifyResults.filter(r => r.result.active === true).length;
335
- const inactiveCount = verifyResults.filter(r => r.result.active === false).length;
336
- if (verifySpinner) {
337
- verifySpinner.succeed(chalk.green(
338
- `Secrets verified: ${activeCount} active, ${inactiveCount} inactive, ${verifyResults.length - activeCount - inactiveCount} unknown`
339
- ));
340
- }
341
- // Show active secrets warning
342
- if (activeCount > 0 && !machineOutput) {
343
- console.log(chalk.red.bold(' ⚠ ACTIVE SECRETS DETECTED — rotate immediately:'));
344
- for (const r of verifyResults.filter(r => r.result.active === true)) {
345
- const rel = path.relative(absolutePath, r.finding.file).replace(/\\/g, '/');
346
- console.log(chalk.red(` ${r.result.provider}: ${rel}:${r.finding.line} — ${r.result.info}`));
347
- }
348
- }
349
- } catch (err) {
350
- if (verifySpinner) verifySpinner.fail(chalk.yellow(`Secrets verification failed: ${err.message}`));
351
- }
352
- }
353
-
354
- // ── Save Cache ──────────────────────────────────────────────────────────
355
- if (useCache) {
356
- try {
357
- // Merge agent findings back for cache (secret + agent findings from changed files)
358
- // plus cached findings from unchanged files
359
- const cachedAgentFindings = cacheData && cacheDiff
360
- ? cacheDiff.cachedFindings.filter(f => f.category !== 'secrets' && f.category !== 'secret')
361
- : [];
362
- const allFindingsForCache = [...secretFindings, ...agentFindings, ...cachedAgentFindings];
363
- cache.save(allFiles, deduplicateFindings(allFindingsForCache), recon, scoreResult);
364
- } catch {
365
- // Silent caching should never break a scan
366
- }
367
- }
368
-
369
- // ── Build Remediation Plan ────────────────────────────────────────────────
370
- const remediationPlan = buildRemediationPlan(filteredFindings, depVulns, absolutePath);
371
-
372
- // ── Output ────────────────────────────────────────────────────────────────
373
- console.log();
374
-
375
- if (options.csv) {
376
- outputCSV(filteredFindings, depVulns, scoreResult, absolutePath);
377
- } else if (options.md) {
378
- outputMarkdown(scoreResult, filteredFindings, depVulns, remediationPlan, absolutePath);
379
- } else if (options.json) {
380
- outputJSON(scoreResult, filteredFindings, depVulns, recon, agentResults, remediationPlan, suppressions, options.compare ? scoringEngine.loadHistory(absolutePath) : null);
381
- } else if (options.sarif) {
382
- outputSARIF(filteredFindings, absolutePath);
383
- } else {
384
- printReport(scoreResult, filteredFindings, depVulns, recon, remediationPlan, absolutePath, filesScanned);
385
- }
386
-
387
- // ── HTML Report (always generate unless machine output) ───────────────────
388
- if (!options.json && !options.sarif && !options.csv && !options.md) {
389
- const htmlPath = typeof options.html === 'string' ? options.html : 'ship-safe-report.html';
390
- const reporter = new HTMLReporter();
391
- reporter.generateFullReport(scoreResult, filteredFindings, depVulns, recon, remediationPlan, absolutePath, htmlPath);
392
- console.log();
393
- console.log(chalk.cyan(` Full report: ${chalk.white.bold(htmlPath)}`));
394
- console.log(chalk.gray(` Dashboard: `) + chalk.cyan('https://shipsafecli.com/app'));
395
-
396
- // PDF export
397
- if (options.pdf) {
398
- const pdfPath = typeof options.pdf === 'string' ? options.pdf : 'ship-safe-report.pdf';
399
- const result = generatePDF(path.resolve(htmlPath), path.resolve(pdfPath));
400
- if (result) {
401
- console.log(chalk.cyan(` PDF report: ${chalk.white.bold(pdfPath)}`));
402
- } else {
403
- // Fallback: print-optimized HTML
404
- const fallbackPath = pdfPath.replace(/\.pdf$/, '.print.html');
405
- generatePrintHTML(path.resolve(htmlPath), path.resolve(fallbackPath));
406
- console.log(chalk.yellow(` Chrome not found — saved print-optimized HTML: ${fallbackPath}`));
407
- console.log(chalk.gray(' Open in a browser and Print → Save as PDF'));
408
- }
409
- }
410
- }
411
-
412
- if (!machineOutput && !options.csv && !options.md) {
413
- // ── Policy Violations ──────────────────────────────────────────────────
414
- const violations = policy.evaluate(scoreResult, filteredFindings);
415
- if (violations.length > 0) {
416
- console.log();
417
- console.log(chalk.red.bold(' Policy Violations:'));
418
- for (const v of violations.slice(0, 5)) {
419
- console.log(chalk.red(` ${v.message}`));
420
- }
421
- }
422
-
423
- // ── Trend ───────────────────────────────────────────────────────────────
424
- const trend = scoringEngine.getTrend(absolutePath, scoreResult.score);
425
- if (trend) {
426
- const arrow = trend.diff > 0 ? chalk.green('↑') : trend.diff < 0 ? chalk.red('↓') : chalk.gray('→');
427
- const roundedDiff = Math.round(trend.diff * 10) / 10;
428
- const diffLabel = roundedDiff === 0 ? chalk.gray('no change') : chalk.white(`${roundedDiff > 0 ? '+' : ''}${roundedDiff}`);
429
- console.log(chalk.gray(` Trend: ${trend.previousScore} ${trend.currentScore} ${arrow} (`) + diffLabel + chalk.gray(')'));
430
- }
431
-
432
- // ── Detailed Comparison ────────────────────────────────────────────────
433
- if (options.compare) {
434
- printComparison(scoringEngine, absolutePath, scoreResult);
435
- }
436
-
437
- console.log();
438
- console.log(chalk.cyan('═'.repeat(60)));
439
- console.log();
440
- }
441
-
442
- process.exit(scoreResult.score >= 75 ? 0 : 1);
443
- }
444
-
445
- // =============================================================================
446
- // REMEDIATION PLAN BUILDER
447
- // =============================================================================
448
-
449
- function buildRemediationPlan(findings, depVulns, rootPath) {
450
- const plan = [];
451
- let priority = 1;
452
-
453
- // Exclude low-confidence findings (test files, docs, comments) from remediation plan
454
- const actionable = findings.filter(f => f.confidence !== 'low');
455
-
456
- // Priority order: secrets first, then by severity
457
- const secretFindings = actionable.filter(f => f.category === 'secrets' || f.category === 'secret');
458
- const otherFindings = actionable.filter(f => f.category !== 'secrets' && f.category !== 'secret');
459
-
460
- // Group and sort
461
- for (const sev of SEV_ORDER) {
462
- // Secrets at this severity group .env findings by file
463
- const sevSecrets = secretFindings.filter(s => s.severity === sev);
464
- const envGroups = new Map();
465
- const nonEnvSecrets = [];
466
-
467
- for (const f of sevSecrets) {
468
- const relFile = path.relative(rootPath, f.file).replace(/\\/g, '/');
469
- if (f.file.match(/\.env(\..*)?$/)) {
470
- if (!envGroups.has(relFile)) envGroups.set(relFile, []);
471
- envGroups.get(relFile).push(f);
472
- } else {
473
- nonEnvSecrets.push(f);
474
- }
475
- }
476
-
477
- // One plan item per .env file
478
- for (const [relFile, envFindings] of envGroups) {
479
- const names = envFindings.map(f => f.title || f.rule).join(', ');
480
- plan.push({
481
- priority: priority++,
482
- severity: sev,
483
- category: 'secrets',
484
- categoryLabel: 'SECRETS',
485
- title: `${envFindings.length} secret${envFindings.length > 1 ? 's' : ''} in ${relFile} (${names})`,
486
- file: relFile,
487
- action: envFindings[0].fix || 'Ensure .env is in .gitignore and use a secrets manager for production',
488
- effort: 'low',
489
- });
490
- }
491
-
492
- // Individual items for non-.env secrets
493
- for (const f of nonEnvSecrets) {
494
- plan.push({
495
- priority: priority++,
496
- severity: sev,
497
- category: 'secrets',
498
- categoryLabel: 'SECRETS',
499
- title: f.title || f.rule,
500
- file: `${path.relative(rootPath, f.file).replace(/\\/g, '/')}:${f.line}`,
501
- action: f.aiFix || f.fix || f.description,
502
- effort: 'low',
503
- });
504
- }
505
-
506
- // Other findings at this severity
507
- for (const f of otherFindings.filter(s => s.severity === sev)) {
508
- plan.push({
509
- priority: priority++,
510
- severity: sev,
511
- category: f.category,
512
- categoryLabel: (CATEGORY_LABELS[f.category] || f.category).toUpperCase(),
513
- title: f.title || f.rule,
514
- file: `${path.relative(rootPath, f.file).replace(/\\/g, '/')}:${f.line}`,
515
- action: f.aiFix || f.fix || f.description,
516
- effort: EFFORT_MAP[f.category] || 'medium',
517
- });
518
- }
519
-
520
- // Dep vulns at this severity
521
- for (const d of depVulns.filter(v => v.severity === sev || (sev === 'medium' && v.severity === 'moderate'))) {
522
- plan.push({
523
- priority: priority++,
524
- severity: sev,
525
- category: 'deps',
526
- categoryLabel: 'DEPENDENCIES',
527
- title: `Vulnerable: ${d.package || d.id}`,
528
- file: 'package.json',
529
- action: d.description ? `${d.description.slice(0, 80)}` : 'Update to patched version',
530
- effort: 'medium',
531
- });
532
- }
533
- }
534
-
535
- return plan;
536
- }
537
-
538
- // =============================================================================
539
- // CONSOLE OUTPUT
540
- // =============================================================================
541
-
542
- function printReport(scoreResult, findings, depVulns, recon, plan, rootPath, filesScanned) {
543
- const GRADE_COLOR = { A: chalk.green.bold, B: chalk.cyan.bold, C: chalk.yellow.bold, D: chalk.red, F: chalk.red.bold };
544
- const SEV_ICON = { critical: '🔴', high: '🟠', medium: '🟡', low: '🔵' };
545
- const SEV_LABEL = { critical: 'CRITICAL — fix immediately', high: 'HIGH — fix before deploy', medium: 'MEDIUM — fix soon', low: 'LOW — review when possible' };
546
-
547
- // ── Score ─────────────────────────────────────────────────────────────────
548
- const gradeColor = GRADE_COLOR[scoreResult.grade.letter] || chalk.white;
549
- const scoreColor = scoreResult.score >= 75 ? chalk.green.bold : scoreResult.score >= 60 ? chalk.yellow.bold : chalk.red.bold;
550
-
551
- console.log(chalk.cyan(' ' + ''.repeat(56)));
552
- console.log(
553
- chalk.white.bold(' Security Score: ') +
554
- scoreColor(`${scoreResult.score}/100 `) +
555
- gradeColor(scoreResult.grade.letter) +
556
- chalk.gray(` — ${scoreResult.grade.label}`)
557
- );
558
- console.log(chalk.cyan(' ' + '═'.repeat(56)));
559
- console.log();
560
-
561
- // ── Category Breakdown ────────────────────────────────────────────────────
562
- console.log(chalk.white.bold(' Category Breakdown'));
563
- console.log(chalk.gray(' ' + '─'.repeat(56)));
564
-
565
- for (const [key, cat] of Object.entries(scoreResult.categories)) {
566
- const count = Object.values(cat.counts).reduce((a, b) => a + b, 0);
567
- const icon = count === 0 ? chalk.green('✔') : chalk.red('✘');
568
- const status = count === 0 ? chalk.green('clean') : chalk.red(`${count} issue(s)`);
569
- const deduction = cat.deduction > 0 ? chalk.red(`-${Math.round(cat.deduction * 10) / 10} pts`) : chalk.gray('+0');
570
- console.log(` ${icon} ${chalk.white(cat.label.padEnd(22))} ${status.padEnd(25)} ${deduction}`);
571
- }
572
-
573
- // Deps row only print if not already included in scoreResult.categories
574
- const hasDepsCategory = Object.values(scoreResult.categories).some(c => c.label?.toLowerCase().includes('depend'));
575
- if (!hasDepsCategory) {
576
- const depIcon = depVulns.length === 0 ? chalk.green('✔') : chalk.red('✘');
577
- const depStatus = depVulns.length === 0 ? chalk.green('clean') : chalk.red(`${depVulns.length} CVE(s)`);
578
- console.log(` ${depIcon} ${chalk.white('Dependencies'.padEnd(22))} ${depStatus}`);
579
- }
580
-
581
- console.log(chalk.gray(`\n Files scanned: ${filesScanned} | Findings: ${findings.length} | CVEs: ${depVulns.length}`));
582
-
583
- // ── Remediation Plan ──────────────────────────────────────────────────────
584
- if (plan.length > 0) {
585
- console.log();
586
- console.log(chalk.cyan(' ' + '═'.repeat(56)));
587
- console.log(chalk.cyan.bold(' Remediation Plan'));
588
- console.log(chalk.cyan(' ' + '═'.repeat(56)));
589
-
590
- let currentSev = null;
591
- let shown = 0;
592
- const maxItems = 30;
593
-
594
- for (const item of plan) {
595
- if (shown >= maxItems) {
596
- console.log(chalk.gray(`\n ... and ${plan.length - maxItems} more items in the full report`));
597
- break;
598
- }
599
-
600
- if (item.severity !== currentSev) {
601
- currentSev = item.severity;
602
- console.log();
603
- console.log(chalk.white.bold(` ${SEV_ICON[currentSev] || '⚪'} ${SEV_LABEL[currentSev] || currentSev.toUpperCase()}`));
604
- console.log(chalk.gray(' ' + '─'.repeat(56)));
605
- }
606
-
607
- console.log(
608
- chalk.white(` ${String(item.priority).padStart(2)}.`) +
609
- chalk.gray(` [${item.categoryLabel}] `) +
610
- chalk.white(item.title)
611
- );
612
- console.log(
613
- chalk.gray(` ${item.file}`) +
614
- chalk.gray(' → ') +
615
- chalk.green((item.action || '').slice(0, 70))
616
- );
617
- shown++;
618
- }
619
- } else {
620
- console.log();
621
- console.log(chalk.green.bold(' All clear — safe to ship!'));
622
- }
623
-
624
- // ── Attack Surface ────────────────────────────────────────────────────────
625
- if (recon) {
626
- console.log();
627
- console.log(chalk.gray(' Attack Surface:'));
628
- if (recon.frameworks?.length) console.log(chalk.gray(` Frameworks: ${recon.frameworks.join(', ')}`));
629
- if (recon.databases?.length) console.log(chalk.gray(` Databases: ${recon.databases.join(', ')}`));
630
- if (recon.authPatterns?.length) console.log(chalk.gray(` Auth: ${recon.authPatterns.join(', ')}`));
631
- if (recon.apiRoutes?.length) console.log(chalk.gray(` API Routes: ${recon.apiRoutes.length} discovered`));
632
- }
633
- }
634
-
635
- // =============================================================================
636
- // JSON OUTPUT
637
- // =============================================================================
638
-
639
- function outputJSON(scoreResult, findings, depVulns, recon, agentResults, remediationPlan, suppressions, history) {
640
- const output = {
641
- score: scoreResult.score,
642
- grade: scoreResult.grade.letter,
643
- gradeLabel: scoreResult.grade.label,
644
- totalFindings: findings.length,
645
- totalDepVulns: depVulns.length,
646
- categories: Object.fromEntries(
647
- Object.entries(scoreResult.categories).map(([k, v]) => [k, {
648
- label: v.label,
649
- findingCount: Object.values(v.counts).reduce((a, b) => a + b, 0),
650
- deduction: v.deduction,
651
- counts: v.counts,
652
- }])
653
- ),
654
- findings: findings.map(f => ({
655
- file: f.file, line: f.line, severity: f.severity, category: f.category,
656
- rule: f.rule, title: f.title, description: f.description, fix: f.fix,
657
- cwe: f.cwe, owasp: f.owasp,
658
- })),
659
- depVulns: depVulns.map(d => ({
660
- severity: d.severity, package: d.package || d.id, description: d.description,
661
- })),
662
- remediationPlan,
663
- recon,
664
- agents: agentResults,
665
- };
666
- if (scoreResult.compliance) output.compliance = scoreResult.compliance;
667
- if (suppressions) output.suppressions = suppressions;
668
- if (history && history.length >= 2) {
669
- const prev = history[history.length - 2];
670
- output.comparison = {
671
- previousScore: prev.score,
672
- previousGrade: prev.grade,
673
- previousDate: prev.timestamp,
674
- diff: scoreResult.score - prev.score,
675
- categoryComparison: Object.fromEntries(
676
- Object.entries(scoreResult.categories).map(([k, v]) => {
677
- const prevCat = prev.categoryScores?.[k];
678
- return [k, {
679
- label: v.label,
680
- current: -v.deduction,
681
- previous: prevCat ? -prevCat.deduction : 0,
682
- delta: prevCat ? prevCat.deduction - v.deduction : 0,
683
- }];
684
- })
685
- ),
686
- };
687
- }
688
- console.log(JSON.stringify(output, null, 2));
689
- }
690
-
691
- // =============================================================================
692
- // SARIF OUTPUT
693
- // =============================================================================
694
-
695
- function outputSARIF(findings, rootPath) {
696
- const rules = {};
697
- for (const f of findings) {
698
- if (!rules[f.rule]) {
699
- rules[f.rule] = {
700
- id: f.rule,
701
- name: f.title || f.rule,
702
- shortDescription: { text: f.title || f.rule },
703
- fullDescription: { text: f.description || '' },
704
- defaultConfiguration: {
705
- level: ['critical', 'high'].includes(f.severity) ? 'error' : 'warning',
706
- },
707
- };
708
- }
709
- }
710
-
711
- console.log(JSON.stringify({
712
- version: '2.1.0',
713
- $schema: 'https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json',
714
- runs: [{
715
- tool: {
716
- driver: {
717
- name: 'ship-safe',
718
- version: '4.0.0',
719
- informationUri: 'https://github.com/asamassekou10/ship-safe',
720
- rules: Object.values(rules),
721
- }
722
- },
723
- results: findings.map(f => ({
724
- ruleId: f.rule,
725
- level: ['critical', 'high'].includes(f.severity) ? 'error' : 'warning',
726
- message: { text: `${f.title}: ${f.description}` },
727
- locations: [{
728
- physicalLocation: {
729
- artifactLocation: { uri: path.relative(rootPath, f.file).replace(/\\/g, '/'), uriBaseId: '%SRCROOT%' },
730
- region: { startLine: f.line, startColumn: f.column || 1 },
731
- }
732
- }],
733
- })),
734
- }],
735
- }, null, 2));
736
- }
737
-
738
- // =============================================================================
739
- // FILE SCANNING (inline from scan.js to avoid circular deps)
740
- // =============================================================================
741
-
742
- async function findFiles(rootPath) {
743
- const globIgnore = Array.from(SKIP_DIRS).map(dir => `**/${dir}/**`);
744
-
745
- // Respect .gitignore patterns
746
- const gitignoreGlobs = loadGitignorePatterns(rootPath);
747
- globIgnore.push(...gitignoreGlobs);
748
-
749
- // Load .ship-safeignore
750
- const ignorePath = path.join(rootPath, '.ship-safeignore');
751
- if (fs.existsSync(ignorePath)) {
752
- try {
753
- const patterns = fs.readFileSync(ignorePath, 'utf-8')
754
- .split('\n').map(l => l.trim()).filter(l => l && !l.startsWith('#'));
755
- for (const p of patterns) {
756
- if (p.endsWith('/')) { globIgnore.push(`**/${p}**`); }
757
- else { globIgnore.push(`**/${p}`); globIgnore.push(p); }
758
- }
759
- } catch { /* skip */ }
760
- }
761
-
762
- const files = await fg('**/*', {
763
- cwd: rootPath, absolute: true, onlyFiles: true, ignore: globIgnore, dot: true
764
- });
765
-
766
- return files.filter(file => {
767
- const ext = path.extname(file).toLowerCase();
768
- if (SKIP_EXTENSIONS.has(ext)) return false;
769
- if (SKIP_FILENAMES.has(path.basename(file))) return false;
770
- if (path.basename(file).endsWith('.min.js') || path.basename(file).endsWith('.min.css')) return false;
771
- try { if (fs.statSync(file).size > MAX_FILE_SIZE) return false; } catch { return false; }
772
- return true;
773
- });
774
- }
775
-
776
- function scanFileForSecrets(filePath) {
777
- const findings = [];
778
- try {
779
- const content = fs.readFileSync(filePath, 'utf-8');
780
- const lines = content.split('\n');
781
- for (let lineNum = 0; lineNum < lines.length; lineNum++) {
782
- const line = lines[lineNum];
783
- if (/ship-safe-ignore/i.test(line)) continue;
784
- for (const pattern of SECRET_PATTERNS) {
785
- pattern.pattern.lastIndex = 0;
786
- let match;
787
- while ((match = pattern.pattern.exec(line)) !== null) {
788
- if (pattern.requiresEntropyCheck && !isHighEntropyMatch(match[0])) continue;
789
- findings.push({
790
- line: lineNum + 1, column: match.index + 1, matched: match[0],
791
- patternName: pattern.name, severity: pattern.severity,
792
- confidence: getConfidence(pattern, match[0]),
793
- description: pattern.description, category: pattern.category || 'secret'
794
- });
795
- }
796
- }
797
- }
798
- } catch { /* skip */ }
799
-
800
- const seen = new Set();
801
- return findings.filter(f => {
802
- const key = `${f.line}:${f.matched}`;
803
- if (seen.has(key)) return false;
804
- seen.add(key);
805
- return true;
806
- });
807
- }
808
-
809
- function deduplicateFindings(findings) {
810
- const seen = new Set();
811
- return findings.filter(f => {
812
- const key = `${f.file}:${f.line}:${f.rule}`;
813
- if (seen.has(key)) return false;
814
- seen.add(key);
815
- return true;
816
- });
817
- }
818
-
819
- // =============================================================================
820
- // SUPPRESSION COUNTING
821
- // =============================================================================
822
-
823
- function countSuppressions(files) {
824
- const suppressions = {};
825
- let total = 0;
826
- for (const file of files) {
827
- try {
828
- const content = fs.readFileSync(file, 'utf-8');
829
- const lines = content.split('\n');
830
- for (const line of lines) {
831
- if (/ship-safe-ignore/i.test(line)) {
832
- total++;
833
- // Try to extract rule name from comment: ship-safe-ignore RULE_NAME
834
- const match = line.match(/ship-safe-ignore\s+(\w+)/i);
835
- const rule = match ? match[1] : '_unspecified';
836
- suppressions[rule] = (suppressions[rule] || 0) + 1;
837
- }
838
- }
839
- } catch { /* skip */ }
840
- }
841
- return total > 0 ? { total, rules: suppressions } : null;
842
- }
843
-
844
- // =============================================================================
845
- // CSV OUTPUT
846
- // =============================================================================
847
-
848
- function outputCSV(findings, depVulns, scoreResult, rootPath) {
849
- const escape = (s) => {
850
- if (!s) return '';
851
- const str = String(s).replace(/"/g, '""');
852
- return str.includes(',') || str.includes('"') || str.includes('\n') ? `"${str}"` : str;
853
- };
854
-
855
- console.log('severity,category,rule,file,line,title,description,fix');
856
- for (const f of findings) {
857
- const relFile = path.relative(rootPath, f.file).replace(/\\/g, '/');
858
- console.log([
859
- escape(f.severity), escape(f.category), escape(f.rule),
860
- escape(relFile), f.line || '', escape(f.title),
861
- escape(f.description), escape(f.fix),
862
- ].join(','));
863
- }
864
- for (const d of depVulns) {
865
- console.log([
866
- escape(d.severity), 'deps', escape(d.id || d.package),
867
- 'package.json', '', escape(`Vulnerable: ${d.package || d.id}`),
868
- escape(d.description), escape('Update to patched version'),
869
- ].join(','));
870
- }
871
- }
872
-
873
- // =============================================================================
874
- // MARKDOWN OUTPUT
875
- // =============================================================================
876
-
877
- function outputMarkdown(scoreResult, findings, depVulns, remediationPlan, rootPath) {
878
- const lines = [];
879
- lines.push('# Ship Safe Security Report');
880
- lines.push('');
881
- lines.push(`**Score: ${scoreResult.score}/100 (${scoreResult.grade.letter})** — ${scoreResult.grade.label}`);
882
- lines.push('');
883
- lines.push(`> Generated: ${new Date().toISOString()}`);
884
- lines.push('');
885
-
886
- // Category breakdown
887
- lines.push('## Category Breakdown');
888
- lines.push('');
889
- lines.push('| Category | Issues | Deduction |');
890
- lines.push('|----------|--------|-----------|');
891
- for (const [, cat] of Object.entries(scoreResult.categories)) {
892
- const count = Object.values(cat.counts).reduce((a, b) => a + b, 0);
893
- lines.push(`| ${cat.label} | ${count} | -${cat.deduction} |`);
894
- }
895
- lines.push('');
896
-
897
- // Findings by severity
898
- for (const sev of SEV_ORDER) {
899
- const sevFindings = findings.filter(f => f.severity === sev);
900
- if (sevFindings.length === 0) continue;
901
-
902
- lines.push(`## ${sev.charAt(0).toUpperCase() + sev.slice(1)} (${sevFindings.length})`);
903
- lines.push('');
904
- lines.push('| File | Rule | Description | Fix |');
905
- lines.push('|------|------|-------------|-----|');
906
- for (const f of sevFindings) {
907
- const relFile = path.relative(rootPath, f.file).replace(/\\/g, '/');
908
- lines.push(`| ${relFile}:${f.line} | ${f.rule} | ${(f.description || '').slice(0, 80)} | ${(f.fix || '').slice(0, 60)} |`);
909
- }
910
- lines.push('');
911
- }
912
-
913
- // Dep vulns
914
- if (depVulns.length > 0) {
915
- lines.push('## Dependency Vulnerabilities');
916
- lines.push('');
917
- lines.push('| Severity | Package | Description |');
918
- lines.push('|----------|---------|-------------|');
919
- for (const d of depVulns) {
920
- lines.push(`| ${d.severity} | ${d.package || d.id} | ${(d.description || '').slice(0, 80)} |`);
921
- }
922
- lines.push('');
923
- }
924
-
925
- console.log(lines.join('\n'));
926
- }
927
-
928
- // =============================================================================
929
- // COMPARISON OUTPUT
930
- // =============================================================================
931
-
932
- function printComparison(scoringEngine, rootPath, scoreResult) {
933
- const history = scoringEngine.loadHistory(rootPath);
934
- if (history.length < 2) {
935
- console.log(chalk.gray('\n No previous scan to compare against.'));
936
- return;
937
- }
938
-
939
- const prev = history[history.length - 2];
940
- console.log();
941
- console.log(chalk.cyan.bold(' Detailed Comparison'));
942
- console.log(chalk.gray(' ' + '─'.repeat(56)));
943
- console.log(chalk.gray(` Previous scan: ${new Date(prev.timestamp).toLocaleString()}`));
944
- console.log();
945
- console.log(chalk.white(' Category'.padEnd(26)) + chalk.white('Previous'.padEnd(12)) + chalk.white('Current'.padEnd(12)) + chalk.white('Delta'));
946
- console.log(chalk.gray(' ' + '─'.repeat(56)));
947
-
948
- for (const [key, cat] of Object.entries(scoreResult.categories)) {
949
- const prevCat = prev.categoryScores?.[key];
950
- const prevDed = prevCat ? prevCat.deduction : 0;
951
- const curDed = cat.deduction;
952
- const delta = prevDed - curDed;
953
-
954
- let deltaStr;
955
- if (delta > 0) deltaStr = chalk.green(`+${delta} improved`);
956
- else if (delta < 0) deltaStr = chalk.red(`${delta} regressed`);
957
- else deltaStr = chalk.gray('→ unchanged');
958
-
959
- console.log(
960
- ` ${chalk.white(cat.label.padEnd(24))}` +
961
- `${chalk.gray(String(-prevDed).padEnd(12))}` +
962
- `${chalk.gray(String(-curDed).padEnd(12))}` +
963
- deltaStr
964
- );
965
- }
966
-
967
- const overallDiff = scoreResult.score - prev.score;
968
- let overallDelta;
969
- if (overallDiff > 0) overallDelta = chalk.green(`+${overallDiff} improved`);
970
- else if (overallDiff < 0) overallDelta = chalk.red(`${overallDiff} regressed`);
971
- else overallDelta = chalk.gray('→ unchanged');
972
-
973
- console.log(chalk.gray(' ' + '─'.repeat(56)));
974
- console.log(
975
- ` ${chalk.white.bold('Overall'.padEnd(24))}` +
976
- `${chalk.gray(`${prev.score}/100 ${prev.grade}`.padEnd(12))}` +
977
- `${chalk.gray(`${scoreResult.score}/100 ${scoreResult.grade.letter}`.padEnd(12))}` +
978
- overallDelta
979
- );
980
- }
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 ship-safe audit [path] Full audit with HTML report
10
+ * npx ship-safe audit . --json JSON output
11
+ * npx ship-safe audit . --html report.html Custom report path
12
+ * npx ship-safe audit . --no-deps Skip dependency audit
13
+ */
14
+
15
+ import fs from 'fs';
16
+ import path from 'path';
17
+ import chalk from 'chalk';
18
+ import ora from 'ora';
19
+ import fg from 'fast-glob';
20
+ import { buildOrchestrator } from '../agents/index.js';
21
+ import { ScoringEngine } from '../agents/scoring-engine.js';
22
+ import { PolicyEngine } from '../agents/policy-engine.js';
23
+ import { HTMLReporter } from '../agents/html-reporter.js';
24
+ import { SBOMGenerator } from '../agents/sbom-generator.js';
25
+ import { autoDetectProvider } from '../providers/llm-provider.js';
26
+ import { runDepsAudit } from './deps.js';
27
+ import {
28
+ SECRET_PATTERNS,
29
+ SECURITY_PATTERNS,
30
+ SKIP_DIRS,
31
+ SKIP_EXTENSIONS,
32
+ SKIP_FILENAMES,
33
+ MAX_FILE_SIZE,
34
+ loadGitignorePatterns
35
+ } from '../utils/patterns.js';
36
+ import { isHighEntropyMatch, getConfidence } from '../utils/entropy.js';
37
+ import { CacheManager } from '../utils/cache-manager.js';
38
+ import { filterBaseline } from './baseline.js';
39
+ import { generatePDF, generatePrintHTML, isChromeAvailable } from '../utils/pdf-generator.js';
40
+ import { SecretsVerifier } from '../utils/secrets-verifier.js';
41
+
42
+ // =============================================================================
43
+ // CONSTANTS
44
+ // =============================================================================
45
+
46
+ const ALL_PATTERNS = [...SECRET_PATTERNS, ...SECURITY_PATTERNS];
47
+
48
+ const SEV_ORDER = ['critical', 'high', 'medium', 'low'];
49
+
50
+ const CATEGORY_LABELS = {
51
+ secrets: 'Secrets',
52
+ injection: 'Code Vulnerabilities',
53
+ deps: 'Dependencies',
54
+ auth: 'Auth & Access Control',
55
+ config: 'Configuration',
56
+ 'supply-chain': 'Supply Chain',
57
+ api: 'API Security',
58
+ llm: 'AI/LLM Security',
59
+ };
60
+
61
+ const EFFORT_MAP = {
62
+ secrets: 'low',
63
+ config: 'low',
64
+ deps: 'medium',
65
+ injection: 'medium',
66
+ auth: 'medium',
67
+ 'supply-chain': 'medium',
68
+ api: 'medium',
69
+ llm: 'high',
70
+ };
71
+
72
+ // =============================================================================
73
+ // MAIN COMMAND
74
+ // =============================================================================
75
+
76
+ export async function auditCommand(targetPath = '.', options = {}) {
77
+ const absolutePath = path.resolve(targetPath);
78
+ const machineOutput = options.json || options.sarif || options.csv || options.md;
79
+
80
+ if (!fs.existsSync(absolutePath)) {
81
+ console.error(chalk.red(` Path does not exist: ${absolutePath}`));
82
+ process.exit(1);
83
+ }
84
+
85
+ if (!machineOutput) {
86
+ console.log();
87
+ console.log(chalk.cyan('═'.repeat(60)));
88
+ console.log(chalk.cyan.bold(' Ship Safe — Full Security Audit'));
89
+ console.log(chalk.cyan('═'.repeat(60)));
90
+ console.log();
91
+ }
92
+
93
+ // ── Cache Layer ──────────────────────────────────────────────────────────
94
+ const useCache = options.cache !== false;
95
+ const cache = new CacheManager(absolutePath);
96
+ let cacheData = useCache ? cache.load() : null;
97
+ let cacheDiff = null;
98
+ let allFiles = [];
99
+
100
+ // ── Phase 1: Secret Scan ──────────────────────────────────────────────────
101
+ const secretSpinner = machineOutput ? null : ora({ text: chalk.white('[Phase 1/4] Scanning for secrets...'), color: 'cyan' }).start();
102
+ let secretFindings = [];
103
+ let filesScanned = 0;
104
+
105
+ try {
106
+ allFiles = await findFiles(absolutePath);
107
+ filesScanned = allFiles.length;
108
+
109
+ // Determine which files need scanning (incremental if cache exists)
110
+ let filesToScan = allFiles;
111
+ let cachedSecretFindings = [];
112
+
113
+ if (cacheData) {
114
+ cacheDiff = cache.diff(allFiles);
115
+ filesToScan = cacheDiff.changedFiles;
116
+ // Reuse cached findings for unchanged files (secrets only)
117
+ cachedSecretFindings = cacheDiff.cachedFindings.filter(
118
+ f => f.category === 'secrets' || f.category === 'secret'
119
+ );
120
+ }
121
+
122
+ for (const file of filesToScan) {
123
+ const fileResults = scanFileForSecrets(file);
124
+ for (const f of fileResults) {
125
+ secretFindings.push({
126
+ file,
127
+ line: f.line,
128
+ column: f.column,
129
+ severity: f.severity,
130
+ category: f.category || 'secrets',
131
+ rule: f.patternName,
132
+ title: f.patternName.replace(/_/g, ' '),
133
+ description: f.description,
134
+ matched: f.matched,
135
+ confidence: f.confidence,
136
+ fix: file.match(/\.env(\..*)?$/)
137
+ ? `Ensure .env is in .gitignore and use a secrets manager for production`
138
+ : `Move to environment variable or secrets manager`,
139
+ });
140
+ }
141
+ }
142
+
143
+ // Downgrade .env findings if the file is gitignored (properly managed)
144
+ const gitignoreContent = (() => {
145
+ try { return fs.readFileSync(path.join(absolutePath, '.gitignore'), 'utf-8'); } catch { return ''; }
146
+ })();
147
+ const envIsGitignored = gitignoreContent.split('\n')
148
+ .map(l => l.trim())
149
+ .some(l => /^\.env(\s|$)/.test(l) || l === '*.env' || l === '.env*' || l === '.env.local' || l === '.env.production');
150
+
151
+ if (envIsGitignored) {
152
+ for (const f of secretFindings) {
153
+ if (f.file.match(/\.env(\..*)?$/) && !f.file.includes('node_modules')) {
154
+ f.severity = 'low';
155
+ f.confidence = 'low';
156
+ f.fix = 'Already gitignored — ensure secrets manager is used for production deploys';
157
+ }
158
+ }
159
+ }
160
+
161
+ // Downgrade secrets in test files (intentional test fixtures)
162
+ const TEST_PATH = /(?:__tests__|\.test\.|\.spec\.|\/test\/|\/tests\/|\/fixtures?\/)/i;
163
+ for (const f of secretFindings) {
164
+ if (TEST_PATH.test(f.file)) {
165
+ f.confidence = 'low';
166
+ }
167
+ }
168
+
169
+ // Merge with cached findings for unchanged files
170
+ secretFindings = [...secretFindings, ...cachedSecretFindings];
171
+
172
+ const cacheNote = cacheDiff && cacheDiff.changedFiles.length < allFiles.length
173
+ ? ` (${cacheDiff.changedFiles.length} changed, ${cacheDiff.unchangedCount} cached)`
174
+ : '';
175
+
176
+ if (secretSpinner) secretSpinner.succeed(
177
+ secretFindings.length === 0
178
+ ? chalk.green(`[Phase 1/4] Secrets: clean${cacheNote}`)
179
+ : chalk.red(`[Phase 1/4] Secrets: ${secretFindings.length} found${cacheNote}`)
180
+ );
181
+ } catch (err) {
182
+ if (secretSpinner) secretSpinner.fail(chalk.red(`[Phase 1/4] Secret scan failed: ${err.message}`));
183
+ }
184
+
185
+ // ── Phase 2: Agent Scan ───────────────────────────────────────────────────
186
+ const orchestrator = buildOrchestrator();
187
+ const registeredAgentCount = orchestrator.agents?.length || 15;
188
+ const agentSpinner = machineOutput ? null : ora({ text: chalk.white(`[Phase 2/4] Running ${registeredAgentCount} security agents...`), color: 'cyan' }).start();
189
+ let agentFindings = [];
190
+ let recon = null;
191
+ let agentResults = [];
192
+
193
+ try {
194
+ // Suppress individual agent spinners by using quiet mode
195
+ // Pass changedFiles for incremental scanning if cache is valid
196
+ const orchestratorOpts = { quiet: true };
197
+ if (options.deep) orchestratorOpts.deep = true;
198
+ if (options.local) orchestratorOpts.local = true;
199
+ if (options.model) orchestratorOpts.model = options.model;
200
+ if (options.provider) orchestratorOpts.provider = options.provider;
201
+ if (options.baseUrl) orchestratorOpts.baseUrl = options.baseUrl;
202
+ if (options.budget) orchestratorOpts.budget = options.budget;
203
+ if (options.verbose) orchestratorOpts.verbose = true;
204
+ if (cacheDiff && cacheDiff.changedFiles.length < allFiles.length) {
205
+ orchestratorOpts.changedFiles = cacheDiff.changedFiles;
206
+ }
207
+ const results = await orchestrator.runAll(absolutePath, orchestratorOpts); // ship-safe-ignore — orchestrator result, not LLM output triggering actions
208
+ recon = results.recon;
209
+ agentFindings = results.findings;
210
+ agentResults = results.agentResults;
211
+
212
+ const totalAgentFindings = agentFindings.length;
213
+ const agentCount = agentResults.filter(a => a.success).length;
214
+ if (agentSpinner) agentSpinner.succeed(
215
+ totalAgentFindings === 0
216
+ ? chalk.green(`[Phase 2/4] ${agentCount} agents: clean`)
217
+ : chalk.yellow(`[Phase 2/4] ${agentCount} agents: ${totalAgentFindings} finding(s)`)
218
+ );
219
+ } catch (err) {
220
+ if (agentSpinner) agentSpinner.fail(chalk.red(`[Phase 2/4] Agent scan failed: ${err.message}`));
221
+ }
222
+
223
+ // ── Phase 3: Dependency Audit ─────────────────────────────────────────────
224
+ let depVulns = [];
225
+ if (options.deps !== false) {
226
+ const depSpinner = machineOutput ? null : ora({ text: chalk.white('[Phase 3/4] Auditing dependencies...'), color: 'cyan' }).start();
227
+ try {
228
+ const depResult = await runDepsAudit(absolutePath);
229
+ depVulns = depResult.vulns || [];
230
+ if (depSpinner) depSpinner.succeed(
231
+ depVulns.length === 0
232
+ ? chalk.green('[Phase 3/4] Dependencies: clean')
233
+ : chalk.red(`[Phase 3/4] Dependencies: ${depVulns.length} CVE(s)`)
234
+ );
235
+ } catch {
236
+ if (depSpinner) depSpinner.succeed(chalk.gray('[Phase 3/4] Dependencies: skipped (no manifest)'));
237
+ }
238
+ } else if (!machineOutput) {
239
+ console.log(chalk.gray(' [Phase 3/4] Dependencies: skipped (--no-deps)'));
240
+ }
241
+
242
+ // ── Phase 4: Merge, Score, and Build Plan ─────────────────────────────────
243
+ const scoreSpinner = machineOutput ? null : ora({ text: chalk.white('[Phase 4/4] Computing security score...'), color: 'cyan' }).start();
244
+
245
+ // Merge secret findings + agent findings, deduplicate
246
+ const allFindings = deduplicateFindings([...secretFindings, ...agentFindings]);
247
+
248
+ // Apply policy
249
+ const policy = PolicyEngine.load(absolutePath);
250
+ let filteredFindings = policy.applyPolicy(allFindings);
251
+
252
+ // Apply baseline filter (only show new findings)
253
+ if (options.baseline) {
254
+ const beforeCount = filteredFindings.length;
255
+ filteredFindings = filterBaseline(filteredFindings, absolutePath);
256
+ if (!machineOutput && beforeCount !== filteredFindings.length) {
257
+ console.log(chalk.gray(` Baseline: ${beforeCount - filteredFindings.length} known finding(s) filtered, ${filteredFindings.length} new`));
258
+ }
259
+ }
260
+
261
+ // Count suppressions (ship-safe-ignore comments)
262
+ const suppressions = countSuppressions(allFiles);
263
+
264
+ // Score
265
+ const scoringEngine = new ScoringEngine();
266
+ const scoreResult = scoringEngine.compute(filteredFindings, depVulns);
267
+ // Round score to 1 decimal place to avoid floating-point noise (e.g., 63.300000000000004)
268
+ scoreResult.score = Math.round(scoreResult.score * 10) / 10;
269
+ scoringEngine.saveToHistory(absolutePath, scoreResult, suppressions);
270
+
271
+ const gradeColor = scoreResult.score >= 75 ? chalk.green.bold : scoreResult.score >= 60 ? chalk.yellow.bold : chalk.red.bold;
272
+ if (scoreSpinner) scoreSpinner.succeed(
273
+ chalk.white('[Phase 4/4] Score: ') + gradeColor(`${scoreResult.score}/100 ${scoreResult.grade.letter}`)
274
+ );
275
+
276
+ // ── AI Classification (optional, with LLM cache) ───────────────────────
277
+ if (options.ai !== false) {
278
+ const provider = autoDetectProvider(absolutePath, {
279
+ provider: options.provider,
280
+ baseUrl: options.baseUrl,
281
+ model: options.model,
282
+ });
283
+ if (provider && filteredFindings.length > 0 && filteredFindings.length <= 50) {
284
+ const aiSpinner = machineOutput ? null : ora({ text: `Classifying with ${provider.name}...`, color: 'cyan' }).start();
285
+ try {
286
+ // Check LLM cache for existing classifications
287
+ const llmCache = cache.loadLLMClassifications();
288
+ const uncachedFindings = [];
289
+ let cachedCount = 0;
290
+
291
+ for (const finding of filteredFindings) {
292
+ const key = cache.getLLMCacheKey(finding);
293
+ const cached = llmCache[key];
294
+ if (cached) {
295
+ finding.aiClassification = cached.classification;
296
+ finding.aiReason = cached.reason;
297
+ finding.aiFix = cached.fix;
298
+ cachedCount++;
299
+ } else {
300
+ uncachedFindings.push(finding);
301
+ }
302
+ }
303
+
304
+ // Only send uncached findings to LLM
305
+ if (uncachedFindings.length > 0) {
306
+ const classifications = await provider.classify(uncachedFindings);
307
+ const newCacheEntries = {};
308
+ for (const cl of classifications) {
309
+ const finding = filteredFindings.find(f => `${f.file}:${f.line}` === cl.id);
310
+ if (finding) {
311
+ finding.aiClassification = cl.classification;
312
+ finding.aiReason = cl.reason;
313
+ finding.aiFix = cl.fix;
314
+ const key = cache.getLLMCacheKey(finding);
315
+ newCacheEntries[key] = {
316
+ classification: cl.classification,
317
+ reason: cl.reason,
318
+ fix: cl.fix,
319
+ cachedAt: new Date().toISOString(),
320
+ };
321
+ }
322
+ }
323
+ cache.saveLLMClassifications(newCacheEntries);
324
+ }
325
+
326
+ const cacheNote = cachedCount > 0 ? `, ${cachedCount} cached` : '';
327
+ if (aiSpinner) aiSpinner.succeed(chalk.green(`AI classification complete (${provider.name}${cacheNote})`));
328
+ } catch (err) {
329
+ if (aiSpinner) aiSpinner.fail(chalk.yellow(`AI classification failed: ${err.message}`));
330
+ }
331
+ }
332
+ }
333
+
334
+ // ── Secrets Verification (optional, --verify flag) ─────────────────────
335
+ if (options.verify) {
336
+ const verifySpinner = machineOutput ? null : ora({ text: 'Verifying leaked secrets against provider APIs...', color: 'cyan' }).start();
337
+ try {
338
+ const verifier = new SecretsVerifier();
339
+ const verifyResults = await verifier.verify(filteredFindings);
340
+ const activeCount = verifyResults.filter(r => r.result.active === true).length;
341
+ const inactiveCount = verifyResults.filter(r => r.result.active === false).length;
342
+ if (verifySpinner) {
343
+ verifySpinner.succeed(chalk.green(
344
+ `Secrets verified: ${activeCount} active, ${inactiveCount} inactive, ${verifyResults.length - activeCount - inactiveCount} unknown`
345
+ ));
346
+ }
347
+ // Show active secrets warning
348
+ if (activeCount > 0 && !machineOutput) {
349
+ console.log(chalk.red.bold(' ⚠ ACTIVE SECRETS DETECTED — rotate immediately:'));
350
+ for (const r of verifyResults.filter(r => r.result.active === true)) {
351
+ const rel = path.relative(absolutePath, r.finding.file).replace(/\\/g, '/');
352
+ console.log(chalk.red(` ${r.result.provider}: ${rel}:${r.finding.line} — ${r.result.info}`));
353
+ }
354
+ }
355
+ } catch (err) {
356
+ if (verifySpinner) verifySpinner.fail(chalk.yellow(`Secrets verification failed: ${err.message}`));
357
+ }
358
+ }
359
+
360
+ // ── Save Cache ──────────────────────────────────────────────────────────
361
+ if (useCache) {
362
+ try {
363
+ // Merge agent findings back for cache (secret + agent findings from changed files)
364
+ // plus cached findings from unchanged files
365
+ const cachedAgentFindings = cacheData && cacheDiff
366
+ ? cacheDiff.cachedFindings.filter(f => f.category !== 'secrets' && f.category !== 'secret')
367
+ : [];
368
+ const allFindingsForCache = [...secretFindings, ...agentFindings, ...cachedAgentFindings];
369
+ cache.save(allFiles, deduplicateFindings(allFindingsForCache), recon, scoreResult);
370
+ } catch {
371
+ // Silent — caching should never break a scan
372
+ }
373
+ }
374
+
375
+ // ── Build Remediation Plan ────────────────────────────────────────────────
376
+ const remediationPlan = buildRemediationPlan(filteredFindings, depVulns, absolutePath);
377
+
378
+ // ── Output ────────────────────────────────────────────────────────────────
379
+ console.log();
380
+
381
+ if (options.csv) {
382
+ outputCSV(filteredFindings, depVulns, scoreResult, absolutePath);
383
+ } else if (options.md) {
384
+ outputMarkdown(scoreResult, filteredFindings, depVulns, remediationPlan, absolutePath);
385
+ } else if (options.json) {
386
+ outputJSON(scoreResult, filteredFindings, depVulns, recon, agentResults, remediationPlan, suppressions, options.compare ? scoringEngine.loadHistory(absolutePath) : null);
387
+ } else if (options.sarif) {
388
+ outputSARIF(filteredFindings, absolutePath);
389
+ } else {
390
+ printReport(scoreResult, filteredFindings, depVulns, recon, remediationPlan, absolutePath, filesScanned);
391
+ }
392
+
393
+ // ── HTML Report (always generate unless machine output) ───────────────────
394
+ if (!options.json && !options.sarif && !options.csv && !options.md) {
395
+ const htmlPath = typeof options.html === 'string' ? options.html : 'ship-safe-report.html';
396
+ const reporter = new HTMLReporter();
397
+ reporter.generateFullReport(scoreResult, filteredFindings, depVulns, recon, remediationPlan, absolutePath, htmlPath);
398
+ console.log();
399
+ console.log(chalk.cyan(` Full report: ${chalk.white.bold(htmlPath)}`));
400
+ console.log(chalk.gray(` Dashboard: `) + chalk.cyan('https://shipsafecli.com/app'));
401
+
402
+ // PDF export
403
+ if (options.pdf) {
404
+ const pdfPath = typeof options.pdf === 'string' ? options.pdf : 'ship-safe-report.pdf';
405
+ const result = generatePDF(path.resolve(htmlPath), path.resolve(pdfPath));
406
+ if (result) {
407
+ console.log(chalk.cyan(` PDF report: ${chalk.white.bold(pdfPath)}`));
408
+ } else {
409
+ // Fallback: print-optimized HTML
410
+ const fallbackPath = pdfPath.replace(/\.pdf$/, '.print.html');
411
+ generatePrintHTML(path.resolve(htmlPath), path.resolve(fallbackPath));
412
+ console.log(chalk.yellow(` Chrome not found saved print-optimized HTML: ${fallbackPath}`));
413
+ console.log(chalk.gray(' Open in a browser and Print → Save as PDF'));
414
+ }
415
+ }
416
+ }
417
+
418
+ if (!machineOutput && !options.csv && !options.md) {
419
+ // ── Policy Violations ──────────────────────────────────────────────────
420
+ const violations = policy.evaluate(scoreResult, filteredFindings);
421
+ if (violations.length > 0) {
422
+ console.log();
423
+ console.log(chalk.red.bold(' Policy Violations:'));
424
+ for (const v of violations.slice(0, 5)) {
425
+ console.log(chalk.red(` ${v.message}`));
426
+ }
427
+ }
428
+
429
+ // ── Trend ───────────────────────────────────────────────────────────────
430
+ const trend = scoringEngine.getTrend(absolutePath, scoreResult.score);
431
+ if (trend) {
432
+ const arrow = trend.diff > 0 ? chalk.green('↑') : trend.diff < 0 ? chalk.red('↓') : chalk.gray('→');
433
+ const roundedDiff = Math.round(trend.diff * 10) / 10;
434
+ const diffLabel = roundedDiff === 0 ? chalk.gray('no change') : chalk.white(`${roundedDiff > 0 ? '+' : ''}${roundedDiff}`);
435
+ console.log(chalk.gray(` Trend: ${trend.previousScore} → ${trend.currentScore} ${arrow} (`) + diffLabel + chalk.gray(')'));
436
+ }
437
+
438
+ // ── Detailed Comparison ────────────────────────────────────────────────
439
+ if (options.compare) {
440
+ printComparison(scoringEngine, absolutePath, scoreResult);
441
+ }
442
+
443
+ console.log();
444
+ console.log(chalk.cyan('═'.repeat(60)));
445
+ console.log();
446
+ }
447
+
448
+ process.exit(scoreResult.score >= 75 ? 0 : 1);
449
+ }
450
+
451
+ // =============================================================================
452
+ // REMEDIATION PLAN BUILDER
453
+ // =============================================================================
454
+
455
+ function buildRemediationPlan(findings, depVulns, rootPath) {
456
+ const plan = [];
457
+ let priority = 1;
458
+
459
+ // Exclude low-confidence findings (test files, docs, comments) from remediation plan
460
+ const actionable = findings.filter(f => f.confidence !== 'low');
461
+
462
+ // Priority order: secrets first, then by severity
463
+ const secretFindings = actionable.filter(f => f.category === 'secrets' || f.category === 'secret');
464
+ const otherFindings = actionable.filter(f => f.category !== 'secrets' && f.category !== 'secret');
465
+
466
+ // Group and sort
467
+ for (const sev of SEV_ORDER) {
468
+ // Secrets at this severity — group .env findings by file
469
+ const sevSecrets = secretFindings.filter(s => s.severity === sev);
470
+ const envGroups = new Map();
471
+ const nonEnvSecrets = [];
472
+
473
+ for (const f of sevSecrets) {
474
+ const relFile = path.relative(rootPath, f.file).replace(/\\/g, '/');
475
+ if (f.file.match(/\.env(\..*)?$/)) {
476
+ if (!envGroups.has(relFile)) envGroups.set(relFile, []);
477
+ envGroups.get(relFile).push(f);
478
+ } else {
479
+ nonEnvSecrets.push(f);
480
+ }
481
+ }
482
+
483
+ // One plan item per .env file
484
+ for (const [relFile, envFindings] of envGroups) {
485
+ const names = envFindings.map(f => f.title || f.rule).join(', ');
486
+ plan.push({
487
+ priority: priority++,
488
+ severity: sev,
489
+ category: 'secrets',
490
+ categoryLabel: 'SECRETS',
491
+ title: `${envFindings.length} secret${envFindings.length > 1 ? 's' : ''} in ${relFile} (${names})`,
492
+ file: relFile,
493
+ action: envFindings[0].fix || 'Ensure .env is in .gitignore and use a secrets manager for production',
494
+ effort: 'low',
495
+ });
496
+ }
497
+
498
+ // Individual items for non-.env secrets
499
+ for (const f of nonEnvSecrets) {
500
+ plan.push({
501
+ priority: priority++,
502
+ severity: sev,
503
+ category: 'secrets',
504
+ categoryLabel: 'SECRETS',
505
+ title: f.title || f.rule,
506
+ file: `${path.relative(rootPath, f.file).replace(/\\/g, '/')}:${f.line}`,
507
+ action: f.aiFix || f.fix || f.description,
508
+ effort: 'low',
509
+ });
510
+ }
511
+
512
+ // Other findings at this severity
513
+ for (const f of otherFindings.filter(s => s.severity === sev)) {
514
+ plan.push({
515
+ priority: priority++,
516
+ severity: sev,
517
+ category: f.category,
518
+ categoryLabel: (CATEGORY_LABELS[f.category] || f.category).toUpperCase(),
519
+ title: f.title || f.rule,
520
+ file: `${path.relative(rootPath, f.file).replace(/\\/g, '/')}:${f.line}`,
521
+ action: f.aiFix || f.fix || f.description,
522
+ effort: EFFORT_MAP[f.category] || 'medium',
523
+ });
524
+ }
525
+
526
+ // Dep vulns at this severity
527
+ for (const d of depVulns.filter(v => v.severity === sev || (sev === 'medium' && v.severity === 'moderate'))) {
528
+ plan.push({
529
+ priority: priority++,
530
+ severity: sev,
531
+ category: 'deps',
532
+ categoryLabel: 'DEPENDENCIES',
533
+ title: `Vulnerable: ${d.package || d.id}`,
534
+ file: 'package.json',
535
+ action: d.description ? `${d.description.slice(0, 80)}` : 'Update to patched version',
536
+ effort: 'medium',
537
+ });
538
+ }
539
+ }
540
+
541
+ return plan;
542
+ }
543
+
544
+ // =============================================================================
545
+ // CONSOLE OUTPUT
546
+ // =============================================================================
547
+
548
+ function printReport(scoreResult, findings, depVulns, recon, plan, rootPath, filesScanned) {
549
+ const GRADE_COLOR = { A: chalk.green.bold, B: chalk.cyan.bold, C: chalk.yellow.bold, D: chalk.red, F: chalk.red.bold };
550
+ const SEV_ICON = { critical: '🔴', high: '🟠', medium: '🟡', low: '🔵' };
551
+ const SEV_LABEL = { critical: 'CRITICAL — fix immediately', high: 'HIGH — fix before deploy', medium: 'MEDIUM — fix soon', low: 'LOW — review when possible' };
552
+
553
+ // ── Score ─────────────────────────────────────────────────────────────────
554
+ const gradeColor = GRADE_COLOR[scoreResult.grade.letter] || chalk.white;
555
+ const scoreColor = scoreResult.score >= 75 ? chalk.green.bold : scoreResult.score >= 60 ? chalk.yellow.bold : chalk.red.bold;
556
+
557
+ console.log(chalk.cyan(' ' + '═'.repeat(56)));
558
+ console.log(
559
+ chalk.white.bold(' Security Score: ') +
560
+ scoreColor(`${scoreResult.score}/100 `) +
561
+ gradeColor(scoreResult.grade.letter) +
562
+ chalk.gray(` — ${scoreResult.grade.label}`)
563
+ );
564
+ console.log(chalk.cyan(' ' + '═'.repeat(56)));
565
+ console.log();
566
+
567
+ // ── Category Breakdown ────────────────────────────────────────────────────
568
+ console.log(chalk.white.bold(' Category Breakdown'));
569
+ console.log(chalk.gray(' ' + '─'.repeat(56)));
570
+
571
+ for (const [key, cat] of Object.entries(scoreResult.categories)) {
572
+ const count = Object.values(cat.counts).reduce((a, b) => a + b, 0);
573
+ const icon = count === 0 ? chalk.green('✔') : chalk.red('✘');
574
+ const status = count === 0 ? chalk.green('clean') : chalk.red(`${count} issue(s)`);
575
+ const deduction = cat.deduction > 0 ? chalk.red(`-${Math.round(cat.deduction * 10) / 10} pts`) : chalk.gray('+0');
576
+ console.log(` ${icon} ${chalk.white(cat.label.padEnd(22))} ${status.padEnd(25)} ${deduction}`);
577
+ }
578
+
579
+ // Deps row — only print if not already included in scoreResult.categories
580
+ const hasDepsCategory = Object.values(scoreResult.categories).some(c => c.label?.toLowerCase().includes('depend'));
581
+ if (!hasDepsCategory) {
582
+ const depIcon = depVulns.length === 0 ? chalk.green('✔') : chalk.red('✘');
583
+ const depStatus = depVulns.length === 0 ? chalk.green('clean') : chalk.red(`${depVulns.length} CVE(s)`);
584
+ console.log(` ${depIcon} ${chalk.white('Dependencies'.padEnd(22))} ${depStatus}`);
585
+ }
586
+
587
+ console.log(chalk.gray(`\n Files scanned: ${filesScanned} | Findings: ${findings.length} | CVEs: ${depVulns.length}`));
588
+
589
+ // ── Remediation Plan ──────────────────────────────────────────────────────
590
+ if (plan.length > 0) {
591
+ console.log();
592
+ console.log(chalk.cyan(' ' + '═'.repeat(56)));
593
+ console.log(chalk.cyan.bold(' Remediation Plan'));
594
+ console.log(chalk.cyan(' ' + '═'.repeat(56)));
595
+
596
+ let currentSev = null;
597
+ let shown = 0;
598
+ const maxItems = 30;
599
+
600
+ for (const item of plan) {
601
+ if (shown >= maxItems) {
602
+ console.log(chalk.gray(`\n ... and ${plan.length - maxItems} more items in the full report`));
603
+ break;
604
+ }
605
+
606
+ if (item.severity !== currentSev) {
607
+ currentSev = item.severity;
608
+ console.log();
609
+ console.log(chalk.white.bold(` ${SEV_ICON[currentSev] || '⚪'} ${SEV_LABEL[currentSev] || currentSev.toUpperCase()}`));
610
+ console.log(chalk.gray(' ' + '─'.repeat(56)));
611
+ }
612
+
613
+ console.log(
614
+ chalk.white(` ${String(item.priority).padStart(2)}.`) +
615
+ chalk.gray(` [${item.categoryLabel}] `) +
616
+ chalk.white(item.title)
617
+ );
618
+ console.log(
619
+ chalk.gray(` ${item.file}`) +
620
+ chalk.gray(' → ') +
621
+ chalk.green((item.action || '').slice(0, 70))
622
+ );
623
+ shown++;
624
+ }
625
+ } else {
626
+ console.log();
627
+ console.log(chalk.green.bold(' All clear — safe to ship!'));
628
+ }
629
+
630
+ // ── Attack Surface ────────────────────────────────────────────────────────
631
+ if (recon) {
632
+ console.log();
633
+ console.log(chalk.gray(' Attack Surface:'));
634
+ if (recon.frameworks?.length) console.log(chalk.gray(` Frameworks: ${recon.frameworks.join(', ')}`));
635
+ if (recon.databases?.length) console.log(chalk.gray(` Databases: ${recon.databases.join(', ')}`));
636
+ if (recon.authPatterns?.length) console.log(chalk.gray(` Auth: ${recon.authPatterns.join(', ')}`));
637
+ if (recon.apiRoutes?.length) console.log(chalk.gray(` API Routes: ${recon.apiRoutes.length} discovered`));
638
+ }
639
+ }
640
+
641
+ // =============================================================================
642
+ // JSON OUTPUT
643
+ // =============================================================================
644
+
645
+ function outputJSON(scoreResult, findings, depVulns, recon, agentResults, remediationPlan, suppressions, history) {
646
+ const output = {
647
+ score: scoreResult.score,
648
+ grade: scoreResult.grade.letter,
649
+ gradeLabel: scoreResult.grade.label,
650
+ totalFindings: findings.length,
651
+ totalDepVulns: depVulns.length,
652
+ categories: Object.fromEntries(
653
+ Object.entries(scoreResult.categories).map(([k, v]) => [k, {
654
+ label: v.label,
655
+ findingCount: Object.values(v.counts).reduce((a, b) => a + b, 0),
656
+ deduction: v.deduction,
657
+ counts: v.counts,
658
+ }])
659
+ ),
660
+ findings: findings.map(f => ({
661
+ file: f.file, line: f.line, severity: f.severity, category: f.category,
662
+ rule: f.rule, title: f.title, description: f.description, fix: f.fix,
663
+ cwe: f.cwe, owasp: f.owasp,
664
+ })),
665
+ depVulns: depVulns.map(d => ({
666
+ severity: d.severity, package: d.package || d.id, description: d.description,
667
+ })),
668
+ remediationPlan,
669
+ recon,
670
+ agents: agentResults,
671
+ };
672
+ if (scoreResult.compliance) output.compliance = scoreResult.compliance;
673
+ if (suppressions) output.suppressions = suppressions;
674
+ if (history && history.length >= 2) {
675
+ const prev = history[history.length - 2];
676
+ output.comparison = {
677
+ previousScore: prev.score,
678
+ previousGrade: prev.grade,
679
+ previousDate: prev.timestamp,
680
+ diff: scoreResult.score - prev.score,
681
+ categoryComparison: Object.fromEntries(
682
+ Object.entries(scoreResult.categories).map(([k, v]) => {
683
+ const prevCat = prev.categoryScores?.[k];
684
+ return [k, {
685
+ label: v.label,
686
+ current: -v.deduction,
687
+ previous: prevCat ? -prevCat.deduction : 0,
688
+ delta: prevCat ? prevCat.deduction - v.deduction : 0,
689
+ }];
690
+ })
691
+ ),
692
+ };
693
+ }
694
+ console.log(JSON.stringify(output, null, 2));
695
+ }
696
+
697
+ // =============================================================================
698
+ // SARIF OUTPUT
699
+ // =============================================================================
700
+
701
+ function outputSARIF(findings, rootPath) {
702
+ const rules = {};
703
+ for (const f of findings) {
704
+ if (!rules[f.rule]) {
705
+ rules[f.rule] = {
706
+ id: f.rule,
707
+ name: f.title || f.rule,
708
+ shortDescription: { text: f.title || f.rule },
709
+ fullDescription: { text: f.description || '' },
710
+ defaultConfiguration: {
711
+ level: ['critical', 'high'].includes(f.severity) ? 'error' : 'warning',
712
+ },
713
+ };
714
+ }
715
+ }
716
+
717
+ console.log(JSON.stringify({
718
+ version: '2.1.0',
719
+ $schema: 'https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json',
720
+ runs: [{
721
+ tool: {
722
+ driver: {
723
+ name: 'ship-safe',
724
+ version: '4.0.0',
725
+ informationUri: 'https://github.com/asamassekou10/ship-safe',
726
+ rules: Object.values(rules),
727
+ }
728
+ },
729
+ results: findings.map(f => ({
730
+ ruleId: f.rule,
731
+ level: ['critical', 'high'].includes(f.severity) ? 'error' : 'warning',
732
+ message: { text: `${f.title}: ${f.description}` },
733
+ locations: [{
734
+ physicalLocation: {
735
+ artifactLocation: { uri: path.relative(rootPath, f.file).replace(/\\/g, '/'), uriBaseId: '%SRCROOT%' },
736
+ region: { startLine: f.line, startColumn: f.column || 1 },
737
+ }
738
+ }],
739
+ })),
740
+ }],
741
+ }, null, 2));
742
+ }
743
+
744
+ // =============================================================================
745
+ // FILE SCANNING (inline from scan.js to avoid circular deps)
746
+ // =============================================================================
747
+
748
+ async function findFiles(rootPath) {
749
+ const globIgnore = Array.from(SKIP_DIRS).map(dir => `**/${dir}/**`);
750
+
751
+ // Respect .gitignore patterns
752
+ const gitignoreGlobs = loadGitignorePatterns(rootPath);
753
+ globIgnore.push(...gitignoreGlobs);
754
+
755
+ // Load .ship-safeignore
756
+ const ignorePath = path.join(rootPath, '.ship-safeignore');
757
+ if (fs.existsSync(ignorePath)) {
758
+ try {
759
+ const patterns = fs.readFileSync(ignorePath, 'utf-8')
760
+ .split('\n').map(l => l.trim()).filter(l => l && !l.startsWith('#'));
761
+ for (const p of patterns) {
762
+ if (p.endsWith('/')) { globIgnore.push(`**/${p}**`); }
763
+ else { globIgnore.push(`**/${p}`); globIgnore.push(p); }
764
+ }
765
+ } catch { /* skip */ }
766
+ }
767
+
768
+ const files = await fg('**/*', {
769
+ cwd: rootPath, absolute: true, onlyFiles: true, ignore: globIgnore, dot: true
770
+ });
771
+
772
+ return files.filter(file => {
773
+ const ext = path.extname(file).toLowerCase();
774
+ if (SKIP_EXTENSIONS.has(ext)) return false;
775
+ if (SKIP_FILENAMES.has(path.basename(file))) return false;
776
+ if (path.basename(file).endsWith('.min.js') || path.basename(file).endsWith('.min.css')) return false;
777
+ try { if (fs.statSync(file).size > MAX_FILE_SIZE) return false; } catch { return false; }
778
+ return true;
779
+ });
780
+ }
781
+
782
+ function scanFileForSecrets(filePath) {
783
+ const findings = [];
784
+ try {
785
+ const content = fs.readFileSync(filePath, 'utf-8');
786
+ const lines = content.split('\n');
787
+ for (let lineNum = 0; lineNum < lines.length; lineNum++) {
788
+ const line = lines[lineNum];
789
+ if (/ship-safe-ignore/i.test(line)) continue;
790
+ for (const pattern of SECRET_PATTERNS) {
791
+ pattern.pattern.lastIndex = 0;
792
+ let match;
793
+ while ((match = pattern.pattern.exec(line)) !== null) {
794
+ if (pattern.requiresEntropyCheck && !isHighEntropyMatch(match[0])) continue;
795
+ findings.push({
796
+ line: lineNum + 1, column: match.index + 1, matched: match[0],
797
+ patternName: pattern.name, severity: pattern.severity,
798
+ confidence: getConfidence(pattern, match[0]),
799
+ description: pattern.description, category: pattern.category || 'secret'
800
+ });
801
+ }
802
+ }
803
+ }
804
+ } catch { /* skip */ }
805
+
806
+ const seen = new Set();
807
+ return findings.filter(f => {
808
+ const key = `${f.line}:${f.matched}`;
809
+ if (seen.has(key)) return false;
810
+ seen.add(key);
811
+ return true;
812
+ });
813
+ }
814
+
815
+ function deduplicateFindings(findings) {
816
+ const seen = new Set();
817
+ return findings.filter(f => {
818
+ const key = `${f.file}:${f.line}:${f.rule}`;
819
+ if (seen.has(key)) return false;
820
+ seen.add(key);
821
+ return true;
822
+ });
823
+ }
824
+
825
+ // =============================================================================
826
+ // SUPPRESSION COUNTING
827
+ // =============================================================================
828
+
829
+ function countSuppressions(files) {
830
+ const suppressions = {};
831
+ let total = 0;
832
+ for (const file of files) {
833
+ try {
834
+ const content = fs.readFileSync(file, 'utf-8');
835
+ const lines = content.split('\n');
836
+ for (const line of lines) {
837
+ if (/ship-safe-ignore/i.test(line)) {
838
+ total++;
839
+ // Try to extract rule name from comment: ship-safe-ignore RULE_NAME
840
+ const match = line.match(/ship-safe-ignore\s+(\w+)/i);
841
+ const rule = match ? match[1] : '_unspecified';
842
+ suppressions[rule] = (suppressions[rule] || 0) + 1;
843
+ }
844
+ }
845
+ } catch { /* skip */ }
846
+ }
847
+ return total > 0 ? { total, rules: suppressions } : null;
848
+ }
849
+
850
+ // =============================================================================
851
+ // CSV OUTPUT
852
+ // =============================================================================
853
+
854
+ function outputCSV(findings, depVulns, scoreResult, rootPath) {
855
+ const escape = (s) => {
856
+ if (!s) return '';
857
+ const str = String(s).replace(/"/g, '""');
858
+ return str.includes(',') || str.includes('"') || str.includes('\n') ? `"${str}"` : str;
859
+ };
860
+
861
+ console.log('severity,category,rule,file,line,title,description,fix');
862
+ for (const f of findings) {
863
+ const relFile = path.relative(rootPath, f.file).replace(/\\/g, '/');
864
+ console.log([
865
+ escape(f.severity), escape(f.category), escape(f.rule),
866
+ escape(relFile), f.line || '', escape(f.title),
867
+ escape(f.description), escape(f.fix),
868
+ ].join(','));
869
+ }
870
+ for (const d of depVulns) {
871
+ console.log([
872
+ escape(d.severity), 'deps', escape(d.id || d.package),
873
+ 'package.json', '', escape(`Vulnerable: ${d.package || d.id}`),
874
+ escape(d.description), escape('Update to patched version'),
875
+ ].join(','));
876
+ }
877
+ }
878
+
879
+ // =============================================================================
880
+ // MARKDOWN OUTPUT
881
+ // =============================================================================
882
+
883
+ function outputMarkdown(scoreResult, findings, depVulns, remediationPlan, rootPath) {
884
+ const lines = [];
885
+ lines.push('# Ship Safe Security Report');
886
+ lines.push('');
887
+ lines.push(`**Score: ${scoreResult.score}/100 (${scoreResult.grade.letter})** — ${scoreResult.grade.label}`);
888
+ lines.push('');
889
+ lines.push(`> Generated: ${new Date().toISOString()}`);
890
+ lines.push('');
891
+
892
+ // Category breakdown
893
+ lines.push('## Category Breakdown');
894
+ lines.push('');
895
+ lines.push('| Category | Issues | Deduction |');
896
+ lines.push('|----------|--------|-----------|');
897
+ for (const [, cat] of Object.entries(scoreResult.categories)) {
898
+ const count = Object.values(cat.counts).reduce((a, b) => a + b, 0);
899
+ lines.push(`| ${cat.label} | ${count} | -${cat.deduction} |`);
900
+ }
901
+ lines.push('');
902
+
903
+ // Findings by severity
904
+ for (const sev of SEV_ORDER) {
905
+ const sevFindings = findings.filter(f => f.severity === sev);
906
+ if (sevFindings.length === 0) continue;
907
+
908
+ lines.push(`## ${sev.charAt(0).toUpperCase() + sev.slice(1)} (${sevFindings.length})`);
909
+ lines.push('');
910
+ lines.push('| File | Rule | Description | Fix |');
911
+ lines.push('|------|------|-------------|-----|');
912
+ for (const f of sevFindings) {
913
+ const relFile = path.relative(rootPath, f.file).replace(/\\/g, '/');
914
+ lines.push(`| ${relFile}:${f.line} | ${f.rule} | ${(f.description || '').slice(0, 80)} | ${(f.fix || '').slice(0, 60)} |`);
915
+ }
916
+ lines.push('');
917
+ }
918
+
919
+ // Dep vulns
920
+ if (depVulns.length > 0) {
921
+ lines.push('## Dependency Vulnerabilities');
922
+ lines.push('');
923
+ lines.push('| Severity | Package | Description |');
924
+ lines.push('|----------|---------|-------------|');
925
+ for (const d of depVulns) {
926
+ lines.push(`| ${d.severity} | ${d.package || d.id} | ${(d.description || '').slice(0, 80)} |`);
927
+ }
928
+ lines.push('');
929
+ }
930
+
931
+ console.log(lines.join('\n'));
932
+ }
933
+
934
+ // =============================================================================
935
+ // COMPARISON OUTPUT
936
+ // =============================================================================
937
+
938
+ function printComparison(scoringEngine, rootPath, scoreResult) {
939
+ const history = scoringEngine.loadHistory(rootPath);
940
+ if (history.length < 2) {
941
+ console.log(chalk.gray('\n No previous scan to compare against.'));
942
+ return;
943
+ }
944
+
945
+ const prev = history[history.length - 2];
946
+ console.log();
947
+ console.log(chalk.cyan.bold(' Detailed Comparison'));
948
+ console.log(chalk.gray(' ' + '─'.repeat(56)));
949
+ console.log(chalk.gray(` Previous scan: ${new Date(prev.timestamp).toLocaleString()}`));
950
+ console.log();
951
+ console.log(chalk.white(' Category'.padEnd(26)) + chalk.white('Previous'.padEnd(12)) + chalk.white('Current'.padEnd(12)) + chalk.white('Delta'));
952
+ console.log(chalk.gray(' ' + '─'.repeat(56)));
953
+
954
+ for (const [key, cat] of Object.entries(scoreResult.categories)) {
955
+ const prevCat = prev.categoryScores?.[key];
956
+ const prevDed = prevCat ? prevCat.deduction : 0;
957
+ const curDed = cat.deduction;
958
+ const delta = prevDed - curDed;
959
+
960
+ let deltaStr;
961
+ if (delta > 0) deltaStr = chalk.green(`+${delta} improved`);
962
+ else if (delta < 0) deltaStr = chalk.red(`${delta} regressed`);
963
+ else deltaStr = chalk.gray('→ unchanged');
964
+
965
+ console.log(
966
+ ` ${chalk.white(cat.label.padEnd(24))}` +
967
+ `${chalk.gray(String(-prevDed).padEnd(12))}` +
968
+ `${chalk.gray(String(-curDed).padEnd(12))}` +
969
+ deltaStr
970
+ );
971
+ }
972
+
973
+ const overallDiff = scoreResult.score - prev.score;
974
+ let overallDelta;
975
+ if (overallDiff > 0) overallDelta = chalk.green(`+${overallDiff} improved`);
976
+ else if (overallDiff < 0) overallDelta = chalk.red(`${overallDiff} regressed`);
977
+ else overallDelta = chalk.gray('→ unchanged');
978
+
979
+ console.log(chalk.gray(' ' + '─'.repeat(56)));
980
+ console.log(
981
+ ` ${chalk.white.bold('Overall'.padEnd(24))}` +
982
+ `${chalk.gray(`${prev.score}/100 ${prev.grade}`.padEnd(12))}` +
983
+ `${chalk.gray(`${scoreResult.score}/100 ${scoreResult.grade.letter}`.padEnd(12))}` +
984
+ overallDelta
985
+ );
986
+ }