ship-safe 6.1.0 → 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 (48) hide show
  1. package/README.md +735 -594
  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 +40 -4
  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 -979
  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 -567
  34. package/cli/commands/score.js +449 -448
  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 +1 -0
  44. package/cli/utils/patterns.js +1121 -1121
  45. package/cli/utils/pdf-generator.js +94 -94
  46. package/package.json +69 -68
  47. package/cli/__tests__/agents.test.js +0 -1301
  48. package/configs/supabase/rls-templates.sql +0 -242
@@ -1,979 +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
-
395
- // PDF export
396
- if (options.pdf) {
397
- const pdfPath = typeof options.pdf === 'string' ? options.pdf : 'ship-safe-report.pdf';
398
- const result = generatePDF(path.resolve(htmlPath), path.resolve(pdfPath));
399
- if (result) {
400
- console.log(chalk.cyan(` PDF report: ${chalk.white.bold(pdfPath)}`));
401
- } else {
402
- // Fallback: print-optimized HTML
403
- const fallbackPath = pdfPath.replace(/\.pdf$/, '.print.html');
404
- generatePrintHTML(path.resolve(htmlPath), path.resolve(fallbackPath));
405
- console.log(chalk.yellow(` Chrome not found — saved print-optimized HTML: ${fallbackPath}`));
406
- console.log(chalk.gray(' Open in a browser and Print → Save as PDF'));
407
- }
408
- }
409
- }
410
-
411
- if (!machineOutput && !options.csv && !options.md) {
412
- // ── Policy Violations ──────────────────────────────────────────────────
413
- const violations = policy.evaluate(scoreResult, filteredFindings);
414
- if (violations.length > 0) {
415
- console.log();
416
- console.log(chalk.red.bold(' Policy Violations:'));
417
- for (const v of violations.slice(0, 5)) {
418
- console.log(chalk.red(` ✗ ${v.message}`));
419
- }
420
- }
421
-
422
- // ── Trend ───────────────────────────────────────────────────────────────
423
- const trend = scoringEngine.getTrend(absolutePath, scoreResult.score);
424
- if (trend) {
425
- const arrow = trend.diff > 0 ? chalk.green('↑') : trend.diff < 0 ? chalk.red('↓') : chalk.gray('→');
426
- const roundedDiff = Math.round(trend.diff * 10) / 10;
427
- const diffLabel = roundedDiff === 0 ? chalk.gray('no change') : chalk.white(`${roundedDiff > 0 ? '+' : ''}${roundedDiff}`);
428
- console.log(chalk.gray(` Trend: ${trend.previousScore} → ${trend.currentScore} ${arrow} (`) + diffLabel + chalk.gray(')'));
429
- }
430
-
431
- // ── Detailed Comparison ────────────────────────────────────────────────
432
- if (options.compare) {
433
- printComparison(scoringEngine, absolutePath, scoreResult);
434
- }
435
-
436
- console.log();
437
- console.log(chalk.cyan('═'.repeat(60)));
438
- console.log();
439
- }
440
-
441
- process.exit(scoreResult.score >= 75 ? 0 : 1);
442
- }
443
-
444
- // =============================================================================
445
- // REMEDIATION PLAN BUILDER
446
- // =============================================================================
447
-
448
- function buildRemediationPlan(findings, depVulns, rootPath) {
449
- const plan = [];
450
- let priority = 1;
451
-
452
- // Exclude low-confidence findings (test files, docs, comments) from remediation plan
453
- const actionable = findings.filter(f => f.confidence !== 'low');
454
-
455
- // Priority order: secrets first, then by severity
456
- const secretFindings = actionable.filter(f => f.category === 'secrets' || f.category === 'secret');
457
- const otherFindings = actionable.filter(f => f.category !== 'secrets' && f.category !== 'secret');
458
-
459
- // Group and sort
460
- for (const sev of SEV_ORDER) {
461
- // Secrets at this severity — group .env findings by file
462
- const sevSecrets = secretFindings.filter(s => s.severity === sev);
463
- const envGroups = new Map();
464
- const nonEnvSecrets = [];
465
-
466
- for (const f of sevSecrets) {
467
- const relFile = path.relative(rootPath, f.file).replace(/\\/g, '/');
468
- if (f.file.match(/\.env(\..*)?$/)) {
469
- if (!envGroups.has(relFile)) envGroups.set(relFile, []);
470
- envGroups.get(relFile).push(f);
471
- } else {
472
- nonEnvSecrets.push(f);
473
- }
474
- }
475
-
476
- // One plan item per .env file
477
- for (const [relFile, envFindings] of envGroups) {
478
- const names = envFindings.map(f => f.title || f.rule).join(', ');
479
- plan.push({
480
- priority: priority++,
481
- severity: sev,
482
- category: 'secrets',
483
- categoryLabel: 'SECRETS',
484
- title: `${envFindings.length} secret${envFindings.length > 1 ? 's' : ''} in ${relFile} (${names})`,
485
- file: relFile,
486
- action: envFindings[0].fix || 'Ensure .env is in .gitignore and use a secrets manager for production',
487
- effort: 'low',
488
- });
489
- }
490
-
491
- // Individual items for non-.env secrets
492
- for (const f of nonEnvSecrets) {
493
- plan.push({
494
- priority: priority++,
495
- severity: sev,
496
- category: 'secrets',
497
- categoryLabel: 'SECRETS',
498
- title: f.title || f.rule,
499
- file: `${path.relative(rootPath, f.file).replace(/\\/g, '/')}:${f.line}`,
500
- action: f.aiFix || f.fix || f.description,
501
- effort: 'low',
502
- });
503
- }
504
-
505
- // Other findings at this severity
506
- for (const f of otherFindings.filter(s => s.severity === sev)) {
507
- plan.push({
508
- priority: priority++,
509
- severity: sev,
510
- category: f.category,
511
- categoryLabel: (CATEGORY_LABELS[f.category] || f.category).toUpperCase(),
512
- title: f.title || f.rule,
513
- file: `${path.relative(rootPath, f.file).replace(/\\/g, '/')}:${f.line}`,
514
- action: f.aiFix || f.fix || f.description,
515
- effort: EFFORT_MAP[f.category] || 'medium',
516
- });
517
- }
518
-
519
- // Dep vulns at this severity
520
- for (const d of depVulns.filter(v => v.severity === sev || (sev === 'medium' && v.severity === 'moderate'))) {
521
- plan.push({
522
- priority: priority++,
523
- severity: sev,
524
- category: 'deps',
525
- categoryLabel: 'DEPENDENCIES',
526
- title: `Vulnerable: ${d.package || d.id}`,
527
- file: 'package.json',
528
- action: d.description ? `${d.description.slice(0, 80)}` : 'Update to patched version',
529
- effort: 'medium',
530
- });
531
- }
532
- }
533
-
534
- return plan;
535
- }
536
-
537
- // =============================================================================
538
- // CONSOLE OUTPUT
539
- // =============================================================================
540
-
541
- function printReport(scoreResult, findings, depVulns, recon, plan, rootPath, filesScanned) {
542
- const GRADE_COLOR = { A: chalk.green.bold, B: chalk.cyan.bold, C: chalk.yellow.bold, D: chalk.red, F: chalk.red.bold };
543
- const SEV_ICON = { critical: '🔴', high: '🟠', medium: '🟡', low: '🔵' };
544
- const SEV_LABEL = { critical: 'CRITICAL — fix immediately', high: 'HIGH — fix before deploy', medium: 'MEDIUM — fix soon', low: 'LOW — review when possible' };
545
-
546
- // ── Score ─────────────────────────────────────────────────────────────────
547
- const gradeColor = GRADE_COLOR[scoreResult.grade.letter] || chalk.white;
548
- const scoreColor = scoreResult.score >= 75 ? chalk.green.bold : scoreResult.score >= 60 ? chalk.yellow.bold : chalk.red.bold;
549
-
550
- console.log(chalk.cyan(' ' + ''.repeat(56)));
551
- console.log(
552
- chalk.white.bold(' Security Score: ') +
553
- scoreColor(`${scoreResult.score}/100 `) +
554
- gradeColor(scoreResult.grade.letter) +
555
- chalk.gray(` ${scoreResult.grade.label}`)
556
- );
557
- console.log(chalk.cyan(' ' + '═'.repeat(56)));
558
- console.log();
559
-
560
- // ── Category Breakdown ────────────────────────────────────────────────────
561
- console.log(chalk.white.bold(' Category Breakdown'));
562
- console.log(chalk.gray(' ' + '─'.repeat(56)));
563
-
564
- for (const [key, cat] of Object.entries(scoreResult.categories)) {
565
- const count = Object.values(cat.counts).reduce((a, b) => a + b, 0);
566
- const icon = count === 0 ? chalk.green('✔') : chalk.red('✘');
567
- const status = count === 0 ? chalk.green('clean') : chalk.red(`${count} issue(s)`);
568
- const deduction = cat.deduction > 0 ? chalk.red(`-${Math.round(cat.deduction * 10) / 10} pts`) : chalk.gray('+0');
569
- console.log(` ${icon} ${chalk.white(cat.label.padEnd(22))} ${status.padEnd(25)} ${deduction}`);
570
- }
571
-
572
- // Deps row only print if not already included in scoreResult.categories
573
- const hasDepsCategory = Object.values(scoreResult.categories).some(c => c.label?.toLowerCase().includes('depend'));
574
- if (!hasDepsCategory) {
575
- const depIcon = depVulns.length === 0 ? chalk.green('✔') : chalk.red('');
576
- const depStatus = depVulns.length === 0 ? chalk.green('clean') : chalk.red(`${depVulns.length} CVE(s)`);
577
- console.log(` ${depIcon} ${chalk.white('Dependencies'.padEnd(22))} ${depStatus}`);
578
- }
579
-
580
- console.log(chalk.gray(`\n Files scanned: ${filesScanned} | Findings: ${findings.length} | CVEs: ${depVulns.length}`));
581
-
582
- // ── Remediation Plan ──────────────────────────────────────────────────────
583
- if (plan.length > 0) {
584
- console.log();
585
- console.log(chalk.cyan(' ' + '═'.repeat(56)));
586
- console.log(chalk.cyan.bold(' Remediation Plan'));
587
- console.log(chalk.cyan(' ' + '═'.repeat(56)));
588
-
589
- let currentSev = null;
590
- let shown = 0;
591
- const maxItems = 30;
592
-
593
- for (const item of plan) {
594
- if (shown >= maxItems) {
595
- console.log(chalk.gray(`\n ... and ${plan.length - maxItems} more items in the full report`));
596
- break;
597
- }
598
-
599
- if (item.severity !== currentSev) {
600
- currentSev = item.severity;
601
- console.log();
602
- console.log(chalk.white.bold(` ${SEV_ICON[currentSev] || '⚪'} ${SEV_LABEL[currentSev] || currentSev.toUpperCase()}`));
603
- console.log(chalk.gray(' ' + '─'.repeat(56)));
604
- }
605
-
606
- console.log(
607
- chalk.white(` ${String(item.priority).padStart(2)}.`) +
608
- chalk.gray(` [${item.categoryLabel}] `) +
609
- chalk.white(item.title)
610
- );
611
- console.log(
612
- chalk.gray(` ${item.file}`) +
613
- chalk.gray(' → ') +
614
- chalk.green((item.action || '').slice(0, 70))
615
- );
616
- shown++;
617
- }
618
- } else {
619
- console.log();
620
- console.log(chalk.green.bold(' All clear — safe to ship!'));
621
- }
622
-
623
- // ── Attack Surface ────────────────────────────────────────────────────────
624
- if (recon) {
625
- console.log();
626
- console.log(chalk.gray(' Attack Surface:'));
627
- if (recon.frameworks?.length) console.log(chalk.gray(` Frameworks: ${recon.frameworks.join(', ')}`));
628
- if (recon.databases?.length) console.log(chalk.gray(` Databases: ${recon.databases.join(', ')}`));
629
- if (recon.authPatterns?.length) console.log(chalk.gray(` Auth: ${recon.authPatterns.join(', ')}`));
630
- if (recon.apiRoutes?.length) console.log(chalk.gray(` API Routes: ${recon.apiRoutes.length} discovered`));
631
- }
632
- }
633
-
634
- // =============================================================================
635
- // JSON OUTPUT
636
- // =============================================================================
637
-
638
- function outputJSON(scoreResult, findings, depVulns, recon, agentResults, remediationPlan, suppressions, history) {
639
- const output = {
640
- score: scoreResult.score,
641
- grade: scoreResult.grade.letter,
642
- gradeLabel: scoreResult.grade.label,
643
- totalFindings: findings.length,
644
- totalDepVulns: depVulns.length,
645
- categories: Object.fromEntries(
646
- Object.entries(scoreResult.categories).map(([k, v]) => [k, {
647
- label: v.label,
648
- findingCount: Object.values(v.counts).reduce((a, b) => a + b, 0),
649
- deduction: v.deduction,
650
- counts: v.counts,
651
- }])
652
- ),
653
- findings: findings.map(f => ({
654
- file: f.file, line: f.line, severity: f.severity, category: f.category,
655
- rule: f.rule, title: f.title, description: f.description, fix: f.fix,
656
- cwe: f.cwe, owasp: f.owasp,
657
- })),
658
- depVulns: depVulns.map(d => ({
659
- severity: d.severity, package: d.package || d.id, description: d.description,
660
- })),
661
- remediationPlan,
662
- recon,
663
- agents: agentResults,
664
- };
665
- if (scoreResult.compliance) output.compliance = scoreResult.compliance;
666
- if (suppressions) output.suppressions = suppressions;
667
- if (history && history.length >= 2) {
668
- const prev = history[history.length - 2];
669
- output.comparison = {
670
- previousScore: prev.score,
671
- previousGrade: prev.grade,
672
- previousDate: prev.timestamp,
673
- diff: scoreResult.score - prev.score,
674
- categoryComparison: Object.fromEntries(
675
- Object.entries(scoreResult.categories).map(([k, v]) => {
676
- const prevCat = prev.categoryScores?.[k];
677
- return [k, {
678
- label: v.label,
679
- current: -v.deduction,
680
- previous: prevCat ? -prevCat.deduction : 0,
681
- delta: prevCat ? prevCat.deduction - v.deduction : 0,
682
- }];
683
- })
684
- ),
685
- };
686
- }
687
- console.log(JSON.stringify(output, null, 2));
688
- }
689
-
690
- // =============================================================================
691
- // SARIF OUTPUT
692
- // =============================================================================
693
-
694
- function outputSARIF(findings, rootPath) {
695
- const rules = {};
696
- for (const f of findings) {
697
- if (!rules[f.rule]) {
698
- rules[f.rule] = {
699
- id: f.rule,
700
- name: f.title || f.rule,
701
- shortDescription: { text: f.title || f.rule },
702
- fullDescription: { text: f.description || '' },
703
- defaultConfiguration: {
704
- level: ['critical', 'high'].includes(f.severity) ? 'error' : 'warning',
705
- },
706
- };
707
- }
708
- }
709
-
710
- console.log(JSON.stringify({
711
- version: '2.1.0',
712
- $schema: 'https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json',
713
- runs: [{
714
- tool: {
715
- driver: {
716
- name: 'ship-safe',
717
- version: '4.0.0',
718
- informationUri: 'https://github.com/asamassekou10/ship-safe',
719
- rules: Object.values(rules),
720
- }
721
- },
722
- results: findings.map(f => ({
723
- ruleId: f.rule,
724
- level: ['critical', 'high'].includes(f.severity) ? 'error' : 'warning',
725
- message: { text: `${f.title}: ${f.description}` },
726
- locations: [{
727
- physicalLocation: {
728
- artifactLocation: { uri: path.relative(rootPath, f.file).replace(/\\/g, '/'), uriBaseId: '%SRCROOT%' },
729
- region: { startLine: f.line, startColumn: f.column || 1 },
730
- }
731
- }],
732
- })),
733
- }],
734
- }, null, 2));
735
- }
736
-
737
- // =============================================================================
738
- // FILE SCANNING (inline from scan.js to avoid circular deps)
739
- // =============================================================================
740
-
741
- async function findFiles(rootPath) {
742
- const globIgnore = Array.from(SKIP_DIRS).map(dir => `**/${dir}/**`);
743
-
744
- // Respect .gitignore patterns
745
- const gitignoreGlobs = loadGitignorePatterns(rootPath);
746
- globIgnore.push(...gitignoreGlobs);
747
-
748
- // Load .ship-safeignore
749
- const ignorePath = path.join(rootPath, '.ship-safeignore');
750
- if (fs.existsSync(ignorePath)) {
751
- try {
752
- const patterns = fs.readFileSync(ignorePath, 'utf-8')
753
- .split('\n').map(l => l.trim()).filter(l => l && !l.startsWith('#'));
754
- for (const p of patterns) {
755
- if (p.endsWith('/')) { globIgnore.push(`**/${p}**`); }
756
- else { globIgnore.push(`**/${p}`); globIgnore.push(p); }
757
- }
758
- } catch { /* skip */ }
759
- }
760
-
761
- const files = await fg('**/*', {
762
- cwd: rootPath, absolute: true, onlyFiles: true, ignore: globIgnore, dot: true
763
- });
764
-
765
- return files.filter(file => {
766
- const ext = path.extname(file).toLowerCase();
767
- if (SKIP_EXTENSIONS.has(ext)) return false;
768
- if (SKIP_FILENAMES.has(path.basename(file))) return false;
769
- if (path.basename(file).endsWith('.min.js') || path.basename(file).endsWith('.min.css')) return false;
770
- try { if (fs.statSync(file).size > MAX_FILE_SIZE) return false; } catch { return false; }
771
- return true;
772
- });
773
- }
774
-
775
- function scanFileForSecrets(filePath) {
776
- const findings = [];
777
- try {
778
- const content = fs.readFileSync(filePath, 'utf-8');
779
- const lines = content.split('\n');
780
- for (let lineNum = 0; lineNum < lines.length; lineNum++) {
781
- const line = lines[lineNum];
782
- if (/ship-safe-ignore/i.test(line)) continue;
783
- for (const pattern of SECRET_PATTERNS) {
784
- pattern.pattern.lastIndex = 0;
785
- let match;
786
- while ((match = pattern.pattern.exec(line)) !== null) {
787
- if (pattern.requiresEntropyCheck && !isHighEntropyMatch(match[0])) continue;
788
- findings.push({
789
- line: lineNum + 1, column: match.index + 1, matched: match[0],
790
- patternName: pattern.name, severity: pattern.severity,
791
- confidence: getConfidence(pattern, match[0]),
792
- description: pattern.description, category: pattern.category || 'secret'
793
- });
794
- }
795
- }
796
- }
797
- } catch { /* skip */ }
798
-
799
- const seen = new Set();
800
- return findings.filter(f => {
801
- const key = `${f.line}:${f.matched}`;
802
- if (seen.has(key)) return false;
803
- seen.add(key);
804
- return true;
805
- });
806
- }
807
-
808
- function deduplicateFindings(findings) {
809
- const seen = new Set();
810
- return findings.filter(f => {
811
- const key = `${f.file}:${f.line}:${f.rule}`;
812
- if (seen.has(key)) return false;
813
- seen.add(key);
814
- return true;
815
- });
816
- }
817
-
818
- // =============================================================================
819
- // SUPPRESSION COUNTING
820
- // =============================================================================
821
-
822
- function countSuppressions(files) {
823
- const suppressions = {};
824
- let total = 0;
825
- for (const file of files) {
826
- try {
827
- const content = fs.readFileSync(file, 'utf-8');
828
- const lines = content.split('\n');
829
- for (const line of lines) {
830
- if (/ship-safe-ignore/i.test(line)) {
831
- total++;
832
- // Try to extract rule name from comment: ship-safe-ignore RULE_NAME
833
- const match = line.match(/ship-safe-ignore\s+(\w+)/i);
834
- const rule = match ? match[1] : '_unspecified';
835
- suppressions[rule] = (suppressions[rule] || 0) + 1;
836
- }
837
- }
838
- } catch { /* skip */ }
839
- }
840
- return total > 0 ? { total, rules: suppressions } : null;
841
- }
842
-
843
- // =============================================================================
844
- // CSV OUTPUT
845
- // =============================================================================
846
-
847
- function outputCSV(findings, depVulns, scoreResult, rootPath) {
848
- const escape = (s) => {
849
- if (!s) return '';
850
- const str = String(s).replace(/"/g, '""');
851
- return str.includes(',') || str.includes('"') || str.includes('\n') ? `"${str}"` : str;
852
- };
853
-
854
- console.log('severity,category,rule,file,line,title,description,fix');
855
- for (const f of findings) {
856
- const relFile = path.relative(rootPath, f.file).replace(/\\/g, '/');
857
- console.log([
858
- escape(f.severity), escape(f.category), escape(f.rule),
859
- escape(relFile), f.line || '', escape(f.title),
860
- escape(f.description), escape(f.fix),
861
- ].join(','));
862
- }
863
- for (const d of depVulns) {
864
- console.log([
865
- escape(d.severity), 'deps', escape(d.id || d.package),
866
- 'package.json', '', escape(`Vulnerable: ${d.package || d.id}`),
867
- escape(d.description), escape('Update to patched version'),
868
- ].join(','));
869
- }
870
- }
871
-
872
- // =============================================================================
873
- // MARKDOWN OUTPUT
874
- // =============================================================================
875
-
876
- function outputMarkdown(scoreResult, findings, depVulns, remediationPlan, rootPath) {
877
- const lines = [];
878
- lines.push('# Ship Safe Security Report');
879
- lines.push('');
880
- lines.push(`**Score: ${scoreResult.score}/100 (${scoreResult.grade.letter})** — ${scoreResult.grade.label}`);
881
- lines.push('');
882
- lines.push(`> Generated: ${new Date().toISOString()}`);
883
- lines.push('');
884
-
885
- // Category breakdown
886
- lines.push('## Category Breakdown');
887
- lines.push('');
888
- lines.push('| Category | Issues | Deduction |');
889
- lines.push('|----------|--------|-----------|');
890
- for (const [, cat] of Object.entries(scoreResult.categories)) {
891
- const count = Object.values(cat.counts).reduce((a, b) => a + b, 0);
892
- lines.push(`| ${cat.label} | ${count} | -${cat.deduction} |`);
893
- }
894
- lines.push('');
895
-
896
- // Findings by severity
897
- for (const sev of SEV_ORDER) {
898
- const sevFindings = findings.filter(f => f.severity === sev);
899
- if (sevFindings.length === 0) continue;
900
-
901
- lines.push(`## ${sev.charAt(0).toUpperCase() + sev.slice(1)} (${sevFindings.length})`);
902
- lines.push('');
903
- lines.push('| File | Rule | Description | Fix |');
904
- lines.push('|------|------|-------------|-----|');
905
- for (const f of sevFindings) {
906
- const relFile = path.relative(rootPath, f.file).replace(/\\/g, '/');
907
- lines.push(`| ${relFile}:${f.line} | ${f.rule} | ${(f.description || '').slice(0, 80)} | ${(f.fix || '').slice(0, 60)} |`);
908
- }
909
- lines.push('');
910
- }
911
-
912
- // Dep vulns
913
- if (depVulns.length > 0) {
914
- lines.push('## Dependency Vulnerabilities');
915
- lines.push('');
916
- lines.push('| Severity | Package | Description |');
917
- lines.push('|----------|---------|-------------|');
918
- for (const d of depVulns) {
919
- lines.push(`| ${d.severity} | ${d.package || d.id} | ${(d.description || '').slice(0, 80)} |`);
920
- }
921
- lines.push('');
922
- }
923
-
924
- console.log(lines.join('\n'));
925
- }
926
-
927
- // =============================================================================
928
- // COMPARISON OUTPUT
929
- // =============================================================================
930
-
931
- function printComparison(scoringEngine, rootPath, scoreResult) {
932
- const history = scoringEngine.loadHistory(rootPath);
933
- if (history.length < 2) {
934
- console.log(chalk.gray('\n No previous scan to compare against.'));
935
- return;
936
- }
937
-
938
- const prev = history[history.length - 2];
939
- console.log();
940
- console.log(chalk.cyan.bold(' Detailed Comparison'));
941
- console.log(chalk.gray(' ' + '─'.repeat(56)));
942
- console.log(chalk.gray(` Previous scan: ${new Date(prev.timestamp).toLocaleString()}`));
943
- console.log();
944
- console.log(chalk.white(' Category'.padEnd(26)) + chalk.white('Previous'.padEnd(12)) + chalk.white('Current'.padEnd(12)) + chalk.white('Delta'));
945
- console.log(chalk.gray(' ' + '─'.repeat(56)));
946
-
947
- for (const [key, cat] of Object.entries(scoreResult.categories)) {
948
- const prevCat = prev.categoryScores?.[key];
949
- const prevDed = prevCat ? prevCat.deduction : 0;
950
- const curDed = cat.deduction;
951
- const delta = prevDed - curDed;
952
-
953
- let deltaStr;
954
- if (delta > 0) deltaStr = chalk.green(`+${delta} improved`);
955
- else if (delta < 0) deltaStr = chalk.red(`${delta} regressed`);
956
- else deltaStr = chalk.gray('→ unchanged');
957
-
958
- console.log(
959
- ` ${chalk.white(cat.label.padEnd(24))}` +
960
- `${chalk.gray(String(-prevDed).padEnd(12))}` +
961
- `${chalk.gray(String(-curDed).padEnd(12))}` +
962
- deltaStr
963
- );
964
- }
965
-
966
- const overallDiff = scoreResult.score - prev.score;
967
- let overallDelta;
968
- if (overallDiff > 0) overallDelta = chalk.green(`+${overallDiff} improved`);
969
- else if (overallDiff < 0) overallDelta = chalk.red(`${overallDiff} regressed`);
970
- else overallDelta = chalk.gray('→ unchanged');
971
-
972
- console.log(chalk.gray(' ' + '─'.repeat(56)));
973
- console.log(
974
- ` ${chalk.white.bold('Overall'.padEnd(24))}` +
975
- `${chalk.gray(`${prev.score}/100 ${prev.grade}`.padEnd(12))}` +
976
- `${chalk.gray(`${scoreResult.score}/100 ${scoreResult.grade.letter}`.padEnd(12))}` +
977
- overallDelta
978
- );
979
- }
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
+ }