ship-safe 3.2.0 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,620 @@
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
+ MAX_FILE_SIZE,
33
+ loadGitignorePatterns
34
+ } from '../utils/patterns.js';
35
+ import { isHighEntropyMatch, getConfidence } from '../utils/entropy.js';
36
+ import { CacheManager } from '../utils/cache-manager.js';
37
+
38
+ // =============================================================================
39
+ // CONSTANTS
40
+ // =============================================================================
41
+
42
+ const ALL_PATTERNS = [...SECRET_PATTERNS, ...SECURITY_PATTERNS];
43
+
44
+ const SEV_ORDER = ['critical', 'high', 'medium', 'low'];
45
+
46
+ const CATEGORY_LABELS = {
47
+ secrets: 'Secrets',
48
+ injection: 'Code Vulnerabilities',
49
+ deps: 'Dependencies',
50
+ auth: 'Auth & Access Control',
51
+ config: 'Configuration',
52
+ 'supply-chain': 'Supply Chain',
53
+ api: 'API Security',
54
+ llm: 'AI/LLM Security',
55
+ };
56
+
57
+ const EFFORT_MAP = {
58
+ secrets: 'low',
59
+ config: 'low',
60
+ deps: 'medium',
61
+ injection: 'medium',
62
+ auth: 'medium',
63
+ 'supply-chain': 'medium',
64
+ api: 'medium',
65
+ llm: 'high',
66
+ };
67
+
68
+ // =============================================================================
69
+ // MAIN COMMAND
70
+ // =============================================================================
71
+
72
+ export async function auditCommand(targetPath = '.', options = {}) {
73
+ const absolutePath = path.resolve(targetPath);
74
+ const machineOutput = options.json || options.sarif;
75
+
76
+ if (!fs.existsSync(absolutePath)) {
77
+ console.error(chalk.red(` Path does not exist: ${absolutePath}`));
78
+ process.exit(1);
79
+ }
80
+
81
+ if (!machineOutput) {
82
+ console.log();
83
+ console.log(chalk.cyan('═'.repeat(60)));
84
+ console.log(chalk.cyan.bold(' Ship Safe v4.0 — Full Security Audit'));
85
+ console.log(chalk.cyan('═'.repeat(60)));
86
+ console.log();
87
+ }
88
+
89
+ // ── Cache Layer ──────────────────────────────────────────────────────────
90
+ const useCache = options.cache !== false;
91
+ const cache = new CacheManager(absolutePath);
92
+ let cacheData = useCache ? cache.load() : null;
93
+ let cacheDiff = null;
94
+ let allFiles = [];
95
+
96
+ // ── Phase 1: Secret Scan ──────────────────────────────────────────────────
97
+ const secretSpinner = machineOutput ? null : ora({ text: chalk.white('[Phase 1/4] Scanning for secrets...'), color: 'cyan' }).start();
98
+ let secretFindings = [];
99
+ let filesScanned = 0;
100
+
101
+ try {
102
+ allFiles = await findFiles(absolutePath);
103
+ filesScanned = allFiles.length;
104
+
105
+ // Determine which files need scanning (incremental if cache exists)
106
+ let filesToScan = allFiles;
107
+ let cachedSecretFindings = [];
108
+
109
+ if (cacheData) {
110
+ cacheDiff = cache.diff(allFiles);
111
+ filesToScan = cacheDiff.changedFiles;
112
+ // Reuse cached findings for unchanged files (secrets only)
113
+ cachedSecretFindings = cacheDiff.cachedFindings.filter(
114
+ f => f.category === 'secrets' || f.category === 'secret'
115
+ );
116
+ }
117
+
118
+ for (const file of filesToScan) {
119
+ const fileResults = scanFileForSecrets(file);
120
+ for (const f of fileResults) {
121
+ secretFindings.push({
122
+ file,
123
+ line: f.line,
124
+ column: f.column,
125
+ severity: f.severity,
126
+ category: f.category || 'secrets',
127
+ rule: f.patternName,
128
+ title: f.patternName.replace(/_/g, ' '),
129
+ description: f.description,
130
+ matched: f.matched,
131
+ confidence: f.confidence,
132
+ fix: `Move to environment variable or secrets manager`,
133
+ });
134
+ }
135
+ }
136
+
137
+ // Merge with cached findings for unchanged files
138
+ secretFindings = [...secretFindings, ...cachedSecretFindings];
139
+
140
+ const cacheNote = cacheDiff && cacheDiff.changedFiles.length < allFiles.length
141
+ ? ` (${cacheDiff.changedFiles.length} changed, ${cacheDiff.unchangedCount} cached)`
142
+ : '';
143
+
144
+ if (secretSpinner) secretSpinner.succeed(
145
+ secretFindings.length === 0
146
+ ? chalk.green(`[Phase 1/4] Secrets: clean${cacheNote}`)
147
+ : chalk.red(`[Phase 1/4] Secrets: ${secretFindings.length} found${cacheNote}`)
148
+ );
149
+ } catch (err) {
150
+ if (secretSpinner) secretSpinner.fail(chalk.red(`[Phase 1/4] Secret scan failed: ${err.message}`));
151
+ }
152
+
153
+ // ── Phase 2: Agent Scan ───────────────────────────────────────────────────
154
+ const agentSpinner = machineOutput ? null : ora({ text: chalk.white('[Phase 2/4] Running 12 security agents...'), color: 'cyan' }).start();
155
+ let agentFindings = [];
156
+ let recon = null;
157
+ let agentResults = [];
158
+
159
+ try {
160
+ const orchestrator = buildOrchestrator();
161
+ // Suppress individual agent spinners by using quiet mode
162
+ // Pass changedFiles for incremental scanning if cache is valid
163
+ const orchestratorOpts = { quiet: true };
164
+ if (cacheDiff && cacheDiff.changedFiles.length < allFiles.length) {
165
+ orchestratorOpts.changedFiles = cacheDiff.changedFiles;
166
+ }
167
+ const results = await orchestrator.runAll(absolutePath, orchestratorOpts);
168
+ recon = results.recon;
169
+ agentFindings = results.findings;
170
+ agentResults = results.agentResults;
171
+
172
+ const totalAgentFindings = agentFindings.length;
173
+ const agentCount = agentResults.filter(a => a.success).length;
174
+ if (agentSpinner) agentSpinner.succeed(
175
+ totalAgentFindings === 0
176
+ ? chalk.green(`[Phase 2/4] ${agentCount} agents: clean`)
177
+ : chalk.yellow(`[Phase 2/4] ${agentCount} agents: ${totalAgentFindings} finding(s)`)
178
+ );
179
+ } catch (err) {
180
+ if (agentSpinner) agentSpinner.fail(chalk.red(`[Phase 2/4] Agent scan failed: ${err.message}`));
181
+ }
182
+
183
+ // ── Phase 3: Dependency Audit ─────────────────────────────────────────────
184
+ let depVulns = [];
185
+ if (options.deps !== false) {
186
+ const depSpinner = machineOutput ? null : ora({ text: chalk.white('[Phase 3/4] Auditing dependencies...'), color: 'cyan' }).start();
187
+ try {
188
+ const depResult = await runDepsAudit(absolutePath);
189
+ depVulns = depResult.vulns || [];
190
+ if (depSpinner) depSpinner.succeed(
191
+ depVulns.length === 0
192
+ ? chalk.green('[Phase 3/4] Dependencies: clean')
193
+ : chalk.red(`[Phase 3/4] Dependencies: ${depVulns.length} CVE(s)`)
194
+ );
195
+ } catch {
196
+ if (depSpinner) depSpinner.succeed(chalk.gray('[Phase 3/4] Dependencies: skipped (no manifest)'));
197
+ }
198
+ } else if (!machineOutput) {
199
+ console.log(chalk.gray(' [Phase 3/4] Dependencies: skipped (--no-deps)'));
200
+ }
201
+
202
+ // ── Phase 4: Merge, Score, and Build Plan ─────────────────────────────────
203
+ const scoreSpinner = machineOutput ? null : ora({ text: chalk.white('[Phase 4/4] Computing security score...'), color: 'cyan' }).start();
204
+
205
+ // Merge secret findings + agent findings, deduplicate
206
+ const allFindings = deduplicateFindings([...secretFindings, ...agentFindings]);
207
+
208
+ // Apply policy
209
+ const policy = PolicyEngine.load(absolutePath);
210
+ const filteredFindings = policy.applyPolicy(allFindings);
211
+
212
+ // Score
213
+ const scoringEngine = new ScoringEngine();
214
+ const scoreResult = scoringEngine.compute(filteredFindings, depVulns);
215
+ scoringEngine.saveToHistory(absolutePath, scoreResult);
216
+
217
+ const gradeColor = scoreResult.score >= 75 ? chalk.green.bold : scoreResult.score >= 60 ? chalk.yellow.bold : chalk.red.bold;
218
+ if (scoreSpinner) scoreSpinner.succeed(
219
+ chalk.white('[Phase 4/4] Score: ') + gradeColor(`${scoreResult.score}/100 ${scoreResult.grade.letter}`)
220
+ );
221
+
222
+ // ── AI Classification (optional) ─────────────────────────────────────────
223
+ if (options.ai !== false) {
224
+ const provider = autoDetectProvider(absolutePath);
225
+ if (provider && filteredFindings.length > 0 && filteredFindings.length <= 50) {
226
+ const aiSpinner = machineOutput ? null : ora({ text: `Classifying with ${provider.name}...`, color: 'cyan' }).start();
227
+ try {
228
+ const classifications = await provider.classify(filteredFindings);
229
+ for (const cl of classifications) {
230
+ const finding = filteredFindings.find(f => `${f.file}:${f.line}` === cl.id);
231
+ if (finding) {
232
+ finding.aiClassification = cl.classification;
233
+ finding.aiReason = cl.reason;
234
+ finding.aiFix = cl.fix;
235
+ }
236
+ }
237
+ if (aiSpinner) aiSpinner.succeed(chalk.green(`AI classification complete (${provider.name})`));
238
+ } catch (err) {
239
+ if (aiSpinner) aiSpinner.fail(chalk.yellow(`AI classification failed: ${err.message}`));
240
+ }
241
+ }
242
+ }
243
+
244
+ // ── Save Cache ──────────────────────────────────────────────────────────
245
+ if (useCache) {
246
+ try {
247
+ // Merge agent findings back for cache (secret + agent findings from changed files)
248
+ // plus cached findings from unchanged files
249
+ const cachedAgentFindings = cacheData && cacheDiff
250
+ ? cacheDiff.cachedFindings.filter(f => f.category !== 'secrets' && f.category !== 'secret')
251
+ : [];
252
+ const allFindingsForCache = [...secretFindings, ...agentFindings, ...cachedAgentFindings];
253
+ cache.save(allFiles, deduplicateFindings(allFindingsForCache), recon, scoreResult);
254
+ } catch {
255
+ // Silent — caching should never break a scan
256
+ }
257
+ }
258
+
259
+ // ── Build Remediation Plan ────────────────────────────────────────────────
260
+ const remediationPlan = buildRemediationPlan(filteredFindings, depVulns, absolutePath);
261
+
262
+ // ── Output ────────────────────────────────────────────────────────────────
263
+ console.log();
264
+
265
+ if (options.json) {
266
+ outputJSON(scoreResult, filteredFindings, depVulns, recon, agentResults, remediationPlan);
267
+ } else if (options.sarif) {
268
+ outputSARIF(filteredFindings, absolutePath);
269
+ } else {
270
+ printReport(scoreResult, filteredFindings, depVulns, recon, remediationPlan, absolutePath, filesScanned);
271
+ }
272
+
273
+ // ── HTML Report (always generate unless --json/--sarif) ───────────────────
274
+ if (!options.json && !options.sarif) {
275
+ const htmlPath = typeof options.html === 'string' ? options.html : 'ship-safe-report.html';
276
+ const reporter = new HTMLReporter();
277
+ reporter.generateFullReport(scoreResult, filteredFindings, depVulns, recon, remediationPlan, absolutePath, htmlPath);
278
+ console.log();
279
+ console.log(chalk.cyan(` Full report: ${chalk.white.bold(htmlPath)}`));
280
+ }
281
+
282
+ if (!machineOutput) {
283
+ // ── Policy Violations ──────────────────────────────────────────────────
284
+ const violations = policy.evaluate(scoreResult, filteredFindings);
285
+ if (violations.length > 0) {
286
+ console.log();
287
+ console.log(chalk.red.bold(' Policy Violations:'));
288
+ for (const v of violations.slice(0, 5)) {
289
+ console.log(chalk.red(` ✗ ${v.message}`));
290
+ }
291
+ }
292
+
293
+ // ── Trend ───────────────────────────────────────────────────────────────
294
+ const trend = scoringEngine.getTrend(absolutePath, scoreResult.score);
295
+ if (trend) {
296
+ const arrow = trend.diff > 0 ? chalk.green('↑') : trend.diff < 0 ? chalk.red('↓') : chalk.gray('→');
297
+ console.log(chalk.gray(` Trend: ${trend.previousScore} → ${trend.currentScore} ${arrow} (${trend.diff > 0 ? '+' : ''}${trend.diff})`));
298
+ }
299
+
300
+ console.log();
301
+ console.log(chalk.cyan('═'.repeat(60)));
302
+ console.log();
303
+ }
304
+
305
+ process.exit(scoreResult.score >= 75 ? 0 : 1);
306
+ }
307
+
308
+ // =============================================================================
309
+ // REMEDIATION PLAN BUILDER
310
+ // =============================================================================
311
+
312
+ function buildRemediationPlan(findings, depVulns, rootPath) {
313
+ const plan = [];
314
+ let priority = 1;
315
+
316
+ // Priority order: secrets first, then by severity
317
+ const secretFindings = findings.filter(f => f.category === 'secrets' || f.category === 'secret');
318
+ const otherFindings = findings.filter(f => f.category !== 'secrets' && f.category !== 'secret');
319
+
320
+ // Group and sort
321
+ for (const sev of SEV_ORDER) {
322
+ // Secrets at this severity
323
+ for (const f of secretFindings.filter(s => s.severity === sev)) {
324
+ plan.push({
325
+ priority: priority++,
326
+ severity: sev,
327
+ category: 'secrets',
328
+ categoryLabel: 'SECRETS',
329
+ title: f.title || f.rule,
330
+ file: `${path.relative(rootPath, f.file).replace(/\\/g, '/')}:${f.line}`,
331
+ action: f.aiFix || f.fix || f.description,
332
+ effort: 'low',
333
+ });
334
+ }
335
+
336
+ // Other findings at this severity
337
+ for (const f of otherFindings.filter(s => s.severity === sev)) {
338
+ plan.push({
339
+ priority: priority++,
340
+ severity: sev,
341
+ category: f.category,
342
+ categoryLabel: (CATEGORY_LABELS[f.category] || f.category).toUpperCase(),
343
+ title: f.title || f.rule,
344
+ file: `${path.relative(rootPath, f.file).replace(/\\/g, '/')}:${f.line}`,
345
+ action: f.aiFix || f.fix || f.description,
346
+ effort: EFFORT_MAP[f.category] || 'medium',
347
+ });
348
+ }
349
+
350
+ // Dep vulns at this severity
351
+ for (const d of depVulns.filter(v => v.severity === sev || (sev === 'medium' && v.severity === 'moderate'))) {
352
+ plan.push({
353
+ priority: priority++,
354
+ severity: sev,
355
+ category: 'deps',
356
+ categoryLabel: 'DEPENDENCIES',
357
+ title: `Vulnerable: ${d.package || d.id}`,
358
+ file: 'package.json',
359
+ action: d.description ? `${d.description.slice(0, 80)}` : 'Update to patched version',
360
+ effort: 'medium',
361
+ });
362
+ }
363
+ }
364
+
365
+ return plan;
366
+ }
367
+
368
+ // =============================================================================
369
+ // CONSOLE OUTPUT
370
+ // =============================================================================
371
+
372
+ function printReport(scoreResult, findings, depVulns, recon, plan, rootPath, filesScanned) {
373
+ const GRADE_COLOR = { A: chalk.green.bold, B: chalk.cyan.bold, C: chalk.yellow.bold, D: chalk.red, F: chalk.red.bold };
374
+ const SEV_ICON = { critical: '🔴', high: '🟠', medium: '🟡', low: '🔵' };
375
+ const SEV_LABEL = { critical: 'CRITICAL — fix immediately', high: 'HIGH — fix before deploy', medium: 'MEDIUM — fix soon', low: 'LOW — review when possible' };
376
+
377
+ // ── Score ─────────────────────────────────────────────────────────────────
378
+ const gradeColor = GRADE_COLOR[scoreResult.grade.letter] || chalk.white;
379
+ const scoreColor = scoreResult.score >= 75 ? chalk.green.bold : scoreResult.score >= 60 ? chalk.yellow.bold : chalk.red.bold;
380
+
381
+ console.log(chalk.cyan(' ' + '═'.repeat(56)));
382
+ console.log(
383
+ chalk.white.bold(' Security Score: ') +
384
+ scoreColor(`${scoreResult.score}/100 `) +
385
+ gradeColor(scoreResult.grade.letter) +
386
+ chalk.gray(` — ${scoreResult.grade.label}`)
387
+ );
388
+ console.log(chalk.cyan(' ' + '═'.repeat(56)));
389
+ console.log();
390
+
391
+ // ── Category Breakdown ────────────────────────────────────────────────────
392
+ console.log(chalk.white.bold(' Category Breakdown'));
393
+ console.log(chalk.gray(' ' + '─'.repeat(56)));
394
+
395
+ for (const [key, cat] of Object.entries(scoreResult.categories)) {
396
+ const count = Object.values(cat.counts).reduce((a, b) => a + b, 0);
397
+ const icon = count === 0 ? chalk.green('✔') : chalk.red('✘');
398
+ const status = count === 0 ? chalk.green('clean') : chalk.red(`${count} issue(s)`);
399
+ const deduction = cat.deduction > 0 ? chalk.red(`-${cat.deduction} pts`) : chalk.gray('+0');
400
+ console.log(` ${icon} ${chalk.white(cat.label.padEnd(22))} ${status.padEnd(25)} ${deduction}`);
401
+ }
402
+
403
+ // Deps row
404
+ const depIcon = depVulns.length === 0 ? chalk.green('✔') : chalk.red('✘');
405
+ const depStatus = depVulns.length === 0 ? chalk.green('clean') : chalk.red(`${depVulns.length} CVE(s)`);
406
+ console.log(` ${depIcon} ${chalk.white('Dependencies'.padEnd(22))} ${depStatus}`);
407
+
408
+ console.log(chalk.gray(`\n Files scanned: ${filesScanned} | Findings: ${findings.length} | CVEs: ${depVulns.length}`));
409
+
410
+ // ── Remediation Plan ──────────────────────────────────────────────────────
411
+ if (plan.length > 0) {
412
+ console.log();
413
+ console.log(chalk.cyan(' ' + '═'.repeat(56)));
414
+ console.log(chalk.cyan.bold(' Remediation Plan'));
415
+ console.log(chalk.cyan(' ' + '═'.repeat(56)));
416
+
417
+ let currentSev = null;
418
+ let shown = 0;
419
+ const maxItems = 30;
420
+
421
+ for (const item of plan) {
422
+ if (shown >= maxItems) {
423
+ console.log(chalk.gray(`\n ... and ${plan.length - maxItems} more items in the full report`));
424
+ break;
425
+ }
426
+
427
+ if (item.severity !== currentSev) {
428
+ currentSev = item.severity;
429
+ console.log();
430
+ console.log(chalk.white.bold(` ${SEV_ICON[currentSev] || '⚪'} ${SEV_LABEL[currentSev] || currentSev.toUpperCase()}`));
431
+ console.log(chalk.gray(' ' + '─'.repeat(56)));
432
+ }
433
+
434
+ console.log(
435
+ chalk.white(` ${String(item.priority).padStart(2)}.`) +
436
+ chalk.gray(` [${item.categoryLabel}] `) +
437
+ chalk.white(item.title)
438
+ );
439
+ console.log(
440
+ chalk.gray(` ${item.file}`) +
441
+ chalk.gray(' → ') +
442
+ chalk.green((item.action || '').slice(0, 70))
443
+ );
444
+ shown++;
445
+ }
446
+ } else {
447
+ console.log();
448
+ console.log(chalk.green.bold(' All clear — safe to ship!'));
449
+ }
450
+
451
+ // ── Attack Surface ────────────────────────────────────────────────────────
452
+ if (recon) {
453
+ console.log();
454
+ console.log(chalk.gray(' Attack Surface:'));
455
+ if (recon.frameworks?.length) console.log(chalk.gray(` Frameworks: ${recon.frameworks.join(', ')}`));
456
+ if (recon.databases?.length) console.log(chalk.gray(` Databases: ${recon.databases.join(', ')}`));
457
+ if (recon.authPatterns?.length) console.log(chalk.gray(` Auth: ${recon.authPatterns.join(', ')}`));
458
+ if (recon.apiRoutes?.length) console.log(chalk.gray(` API Routes: ${recon.apiRoutes.length} discovered`));
459
+ }
460
+ }
461
+
462
+ // =============================================================================
463
+ // JSON OUTPUT
464
+ // =============================================================================
465
+
466
+ function outputJSON(scoreResult, findings, depVulns, recon, agentResults, remediationPlan) {
467
+ console.log(JSON.stringify({
468
+ score: scoreResult.score,
469
+ grade: scoreResult.grade.letter,
470
+ gradeLabel: scoreResult.grade.label,
471
+ totalFindings: findings.length,
472
+ totalDepVulns: depVulns.length,
473
+ categories: Object.fromEntries(
474
+ Object.entries(scoreResult.categories).map(([k, v]) => [k, {
475
+ label: v.label,
476
+ findingCount: Object.values(v.counts).reduce((a, b) => a + b, 0),
477
+ deduction: v.deduction,
478
+ counts: v.counts,
479
+ }])
480
+ ),
481
+ findings: findings.map(f => ({
482
+ file: f.file, line: f.line, severity: f.severity, category: f.category,
483
+ rule: f.rule, title: f.title, description: f.description, fix: f.fix,
484
+ cwe: f.cwe, owasp: f.owasp,
485
+ })),
486
+ depVulns: depVulns.map(d => ({
487
+ severity: d.severity, package: d.package || d.id, description: d.description,
488
+ })),
489
+ remediationPlan,
490
+ recon,
491
+ agents: agentResults,
492
+ }, null, 2));
493
+ }
494
+
495
+ // =============================================================================
496
+ // SARIF OUTPUT
497
+ // =============================================================================
498
+
499
+ function outputSARIF(findings, rootPath) {
500
+ const rules = {};
501
+ for (const f of findings) {
502
+ if (!rules[f.rule]) {
503
+ rules[f.rule] = {
504
+ id: f.rule,
505
+ name: f.title || f.rule,
506
+ shortDescription: { text: f.title || f.rule },
507
+ fullDescription: { text: f.description || '' },
508
+ defaultConfiguration: {
509
+ level: ['critical', 'high'].includes(f.severity) ? 'error' : 'warning',
510
+ },
511
+ };
512
+ }
513
+ }
514
+
515
+ console.log(JSON.stringify({
516
+ version: '2.1.0',
517
+ $schema: 'https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json',
518
+ runs: [{
519
+ tool: {
520
+ driver: {
521
+ name: 'ship-safe',
522
+ version: '4.0.0',
523
+ informationUri: 'https://github.com/asamassekou10/ship-safe',
524
+ rules: Object.values(rules),
525
+ }
526
+ },
527
+ results: findings.map(f => ({
528
+ ruleId: f.rule,
529
+ level: ['critical', 'high'].includes(f.severity) ? 'error' : 'warning',
530
+ message: { text: `${f.title}: ${f.description}` },
531
+ locations: [{
532
+ physicalLocation: {
533
+ artifactLocation: { uri: path.relative(rootPath, f.file).replace(/\\/g, '/'), uriBaseId: '%SRCROOT%' },
534
+ region: { startLine: f.line, startColumn: f.column || 1 },
535
+ }
536
+ }],
537
+ })),
538
+ }],
539
+ }, null, 2));
540
+ }
541
+
542
+ // =============================================================================
543
+ // FILE SCANNING (inline from scan.js to avoid circular deps)
544
+ // =============================================================================
545
+
546
+ async function findFiles(rootPath) {
547
+ const globIgnore = Array.from(SKIP_DIRS).map(dir => `**/${dir}/**`);
548
+
549
+ // Respect .gitignore patterns
550
+ const gitignoreGlobs = loadGitignorePatterns(rootPath);
551
+ globIgnore.push(...gitignoreGlobs);
552
+
553
+ // Load .ship-safeignore
554
+ const ignorePath = path.join(rootPath, '.ship-safeignore');
555
+ if (fs.existsSync(ignorePath)) {
556
+ try {
557
+ const patterns = fs.readFileSync(ignorePath, 'utf-8')
558
+ .split('\n').map(l => l.trim()).filter(l => l && !l.startsWith('#'));
559
+ for (const p of patterns) {
560
+ if (p.endsWith('/')) { globIgnore.push(`**/${p}**`); }
561
+ else { globIgnore.push(`**/${p}`); globIgnore.push(p); }
562
+ }
563
+ } catch { /* skip */ }
564
+ }
565
+
566
+ const files = await fg('**/*', {
567
+ cwd: rootPath, absolute: true, onlyFiles: true, ignore: globIgnore, dot: true
568
+ });
569
+
570
+ return files.filter(file => {
571
+ const ext = path.extname(file).toLowerCase();
572
+ if (SKIP_EXTENSIONS.has(ext)) return false;
573
+ if (path.basename(file).endsWith('.min.js') || path.basename(file).endsWith('.min.css')) return false;
574
+ try { if (fs.statSync(file).size > MAX_FILE_SIZE) return false; } catch { return false; }
575
+ return true;
576
+ });
577
+ }
578
+
579
+ function scanFileForSecrets(filePath) {
580
+ const findings = [];
581
+ try {
582
+ const content = fs.readFileSync(filePath, 'utf-8');
583
+ const lines = content.split('\n');
584
+ for (let lineNum = 0; lineNum < lines.length; lineNum++) {
585
+ const line = lines[lineNum];
586
+ if (/ship-safe-ignore/i.test(line)) continue;
587
+ for (const pattern of SECRET_PATTERNS) {
588
+ pattern.pattern.lastIndex = 0;
589
+ let match;
590
+ while ((match = pattern.pattern.exec(line)) !== null) {
591
+ if (pattern.requiresEntropyCheck && !isHighEntropyMatch(match[0])) continue;
592
+ findings.push({
593
+ line: lineNum + 1, column: match.index + 1, matched: match[0],
594
+ patternName: pattern.name, severity: pattern.severity,
595
+ confidence: getConfidence(pattern, match[0]),
596
+ description: pattern.description, category: pattern.category || 'secret'
597
+ });
598
+ }
599
+ }
600
+ }
601
+ } catch { /* skip */ }
602
+
603
+ const seen = new Set();
604
+ return findings.filter(f => {
605
+ const key = `${f.line}:${f.matched}`;
606
+ if (seen.has(key)) return false;
607
+ seen.add(key);
608
+ return true;
609
+ });
610
+ }
611
+
612
+ function deduplicateFindings(findings) {
613
+ const seen = new Set();
614
+ return findings.filter(f => {
615
+ const key = `${f.file}:${f.line}:${f.rule}`;
616
+ if (seen.has(key)) return false;
617
+ seen.add(key);
618
+ return true;
619
+ });
620
+ }