ship-safe 3.1.0 → 4.0.0

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