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