@agenticcli/shipguard 0.1.0 → 0.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 +34 -6
- package/dist/chunk-7HMLDAMC.js +115 -0
- package/dist/{chunk-42MA7DQY.js → chunk-YE2GPROS.js} +67 -4
- package/dist/cli.js +1032 -232
- package/dist/{config-generator-EQNRHODF.js → config-generator-YSWNA53I.js} +14 -0
- package/dist/{pro-scanner-YZDS67FB.js → pro-scanner-IJJLUSAC.js} +1 -1
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -11,10 +11,16 @@ import {
|
|
|
11
11
|
runProRulesWithDispatch,
|
|
12
12
|
saveCredentials,
|
|
13
13
|
secretsCheck
|
|
14
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-YE2GPROS.js";
|
|
15
|
+
import {
|
|
16
|
+
DEFAULT_MAX_FILES,
|
|
17
|
+
DEFAULT_MAX_FILE_SIZE_BYTES,
|
|
18
|
+
DEFAULT_MAX_TOTAL_BYTES,
|
|
19
|
+
readFiles
|
|
20
|
+
} from "./chunk-7HMLDAMC.js";
|
|
15
21
|
|
|
16
22
|
// src/cli.ts
|
|
17
|
-
import { Command as Command7 } from "commander";
|
|
23
|
+
import { Command as Command7, CommanderError } from "commander";
|
|
18
24
|
|
|
19
25
|
// src/commands/init.ts
|
|
20
26
|
import { Command } from "commander";
|
|
@@ -83,12 +89,19 @@ var DEFAULT_POLICY = {
|
|
|
83
89
|
"dist/**",
|
|
84
90
|
"build/**",
|
|
85
91
|
".next/**",
|
|
86
|
-
"coverage/**"
|
|
92
|
+
"coverage/**",
|
|
93
|
+
// ShipGuard's own report output — never scan the tool's own artifacts
|
|
94
|
+
".shipguard/**"
|
|
87
95
|
]
|
|
88
96
|
},
|
|
89
97
|
report: {
|
|
90
98
|
output: ".shipguard/reports/latest.md",
|
|
91
99
|
format: "markdown"
|
|
100
|
+
},
|
|
101
|
+
limits: {
|
|
102
|
+
maxFileSizeBytes: DEFAULT_MAX_FILE_SIZE_BYTES,
|
|
103
|
+
maxTotalBytes: DEFAULT_MAX_TOTAL_BYTES,
|
|
104
|
+
maxFiles: DEFAULT_MAX_FILES
|
|
92
105
|
}
|
|
93
106
|
};
|
|
94
107
|
async function loadPolicy(dir) {
|
|
@@ -99,7 +112,11 @@ async function loadPolicy(dir) {
|
|
|
99
112
|
try {
|
|
100
113
|
const content = await readFile(policyPath, "utf-8");
|
|
101
114
|
const parsed = YAML.parse(content);
|
|
102
|
-
return {
|
|
115
|
+
return {
|
|
116
|
+
...DEFAULT_POLICY,
|
|
117
|
+
...parsed,
|
|
118
|
+
limits: { ...DEFAULT_POLICY.limits, ...parsed.limits ?? {} }
|
|
119
|
+
};
|
|
103
120
|
} catch (error) {
|
|
104
121
|
throw new Error(`Invalid policy file: ${error instanceof Error ? error.message : error}`);
|
|
105
122
|
}
|
|
@@ -172,10 +189,12 @@ function initCommand() {
|
|
|
172
189
|
// src/commands/scan.ts
|
|
173
190
|
import { Command as Command2 } from "commander";
|
|
174
191
|
import { randomUUID } from "crypto";
|
|
192
|
+
import { existsSync as existsSync3 } from "fs";
|
|
193
|
+
import { join as join5, resolve as resolve3 } from "path";
|
|
175
194
|
|
|
176
195
|
// src/core/scanner.ts
|
|
177
|
-
import { readFile as
|
|
178
|
-
import { join as
|
|
196
|
+
import { readFile as readFile2, stat } from "fs/promises";
|
|
197
|
+
import { join as join2 } from "path";
|
|
179
198
|
|
|
180
199
|
// src/core/risk-score.ts
|
|
181
200
|
function computeRiskScore(findings) {
|
|
@@ -267,46 +286,6 @@ function getChangedFiles(dir) {
|
|
|
267
286
|
}
|
|
268
287
|
}
|
|
269
288
|
|
|
270
|
-
// src/utils/fs.ts
|
|
271
|
-
import fg from "fast-glob";
|
|
272
|
-
import { readFile as readFile2 } from "fs/promises";
|
|
273
|
-
import { join as join2 } from "path";
|
|
274
|
-
async function readFiles(rootDir, patterns = ["**/*"], ignorePatterns = []) {
|
|
275
|
-
const defaultIgnore = [
|
|
276
|
-
"node_modules/**",
|
|
277
|
-
"dist/**",
|
|
278
|
-
"build/**",
|
|
279
|
-
".next/**",
|
|
280
|
-
"coverage/**",
|
|
281
|
-
".git/**",
|
|
282
|
-
"*.lock",
|
|
283
|
-
"pnpm-lock.yaml",
|
|
284
|
-
"package-lock.json"
|
|
285
|
-
];
|
|
286
|
-
const allIgnore = [...defaultIgnore, ...ignorePatterns];
|
|
287
|
-
const filePaths = await fg(patterns, {
|
|
288
|
-
cwd: rootDir,
|
|
289
|
-
ignore: allIgnore,
|
|
290
|
-
dot: true,
|
|
291
|
-
absolute: false,
|
|
292
|
-
onlyFiles: true
|
|
293
|
-
});
|
|
294
|
-
const files = [];
|
|
295
|
-
for (const fp of filePaths) {
|
|
296
|
-
try {
|
|
297
|
-
const fullPath = join2(rootDir, fp);
|
|
298
|
-
const content = await readFile2(fullPath, "utf-8");
|
|
299
|
-
files.push({
|
|
300
|
-
path: fullPath,
|
|
301
|
-
content,
|
|
302
|
-
relativePath: fp
|
|
303
|
-
});
|
|
304
|
-
} catch {
|
|
305
|
-
}
|
|
306
|
-
}
|
|
307
|
-
return files;
|
|
308
|
-
}
|
|
309
|
-
|
|
310
289
|
// src/core/scanner.ts
|
|
311
290
|
var CHECK_MODULES = [secretsCheck, authCheck, databaseCheck, payments, deploymentCheck];
|
|
312
291
|
var DEFAULT_IGNORE = [
|
|
@@ -315,13 +294,23 @@ var DEFAULT_IGNORE = [
|
|
|
315
294
|
"build/**",
|
|
316
295
|
".next/**",
|
|
317
296
|
"coverage/**",
|
|
318
|
-
".git/**"
|
|
297
|
+
".git/**",
|
|
298
|
+
// ShipGuard's own report output — never scan the tool's own artifacts
|
|
299
|
+
".shipguard/**"
|
|
319
300
|
];
|
|
320
|
-
async function scan(options, proRules) {
|
|
301
|
+
async function scan(options, proRules, onProgress) {
|
|
321
302
|
const cwd = process.cwd();
|
|
322
303
|
const policy = await loadPolicy(cwd);
|
|
323
304
|
const ignorePatterns = [...DEFAULT_IGNORE, ...policy.ignore.paths];
|
|
305
|
+
const limits = {
|
|
306
|
+
maxFileSizeBytes: policy.limits?.maxFileSizeBytes ?? DEFAULT_MAX_FILE_SIZE_BYTES,
|
|
307
|
+
maxTotalBytes: policy.limits?.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES,
|
|
308
|
+
maxFiles: policy.limits?.maxFiles ?? DEFAULT_MAX_FILES
|
|
309
|
+
};
|
|
324
310
|
let files;
|
|
311
|
+
let skippedTooLarge = 0;
|
|
312
|
+
let skippedBinary = 0;
|
|
313
|
+
let truncated = false;
|
|
325
314
|
if (options.changedOnly && isGitRepo(cwd)) {
|
|
326
315
|
const changedRelPaths = getChangedFiles(cwd);
|
|
327
316
|
const filteredPaths = changedRelPaths.filter(
|
|
@@ -331,19 +320,57 @@ async function scan(options, proRules) {
|
|
|
331
320
|
})
|
|
332
321
|
);
|
|
333
322
|
files = [];
|
|
323
|
+
let totalBytes = 0;
|
|
324
|
+
const changedTotal = filteredPaths.length;
|
|
325
|
+
let changedProcessed = 0;
|
|
334
326
|
for (const relPath of filteredPaths) {
|
|
327
|
+
if (files.length >= limits.maxFiles || totalBytes >= limits.maxTotalBytes) {
|
|
328
|
+
truncated = true;
|
|
329
|
+
break;
|
|
330
|
+
}
|
|
331
|
+
const fullPath = join2(cwd, relPath);
|
|
335
332
|
try {
|
|
336
|
-
const
|
|
337
|
-
|
|
333
|
+
const fileStat = await stat(fullPath);
|
|
334
|
+
if (fileStat.size > limits.maxFileSizeBytes) {
|
|
335
|
+
skippedTooLarge++;
|
|
336
|
+
onProgress?.(++changedProcessed, changedTotal, relPath);
|
|
337
|
+
continue;
|
|
338
|
+
}
|
|
339
|
+
const buffer = await readFile2(fullPath);
|
|
340
|
+
const checkLen = Math.min(buffer.length, 8192);
|
|
341
|
+
let isBinary = false;
|
|
342
|
+
for (let i = 0; i < checkLen; i++) {
|
|
343
|
+
if (buffer[i] === 0) {
|
|
344
|
+
isBinary = true;
|
|
345
|
+
break;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
if (isBinary) {
|
|
349
|
+
skippedBinary++;
|
|
350
|
+
onProgress?.(++changedProcessed, changedTotal, relPath);
|
|
351
|
+
continue;
|
|
352
|
+
}
|
|
353
|
+
const content = buffer.toString("utf-8");
|
|
354
|
+
totalBytes += buffer.length;
|
|
338
355
|
files.push({ path: fullPath, content, relativePath: relPath });
|
|
339
356
|
} catch {
|
|
340
357
|
}
|
|
358
|
+
onProgress?.(++changedProcessed, changedTotal, relPath);
|
|
341
359
|
}
|
|
342
360
|
} else {
|
|
343
361
|
if (options.changedOnly && !isGitRepo(cwd)) {
|
|
344
362
|
logger.warn("--changed flag set but not a git repository \u2014 scanning all files");
|
|
345
363
|
}
|
|
346
|
-
|
|
364
|
+
const readResult = await readFiles(cwd, ["**/*"], ignorePatterns, {
|
|
365
|
+
maxFileSizeBytes: limits.maxFileSizeBytes,
|
|
366
|
+
maxTotalBytes: limits.maxTotalBytes,
|
|
367
|
+
maxFiles: limits.maxFiles,
|
|
368
|
+
onProgress
|
|
369
|
+
});
|
|
370
|
+
files = readResult.files;
|
|
371
|
+
skippedTooLarge = readResult.skippedTooLarge;
|
|
372
|
+
skippedBinary = readResult.skippedBinary;
|
|
373
|
+
truncated = readResult.truncated;
|
|
347
374
|
}
|
|
348
375
|
let allFindings = CHECK_MODULES.flatMap((mod) => mod.run(files, policy));
|
|
349
376
|
let coderefDegraded = false;
|
|
@@ -364,14 +391,18 @@ async function scan(options, proRules) {
|
|
|
364
391
|
policyUsed: policy.project.name,
|
|
365
392
|
// Propagate coderef version-skip degradation — scan.ts:145 will OR-merge with
|
|
366
393
|
// its own degraded flag so this is not clobbered.
|
|
367
|
-
degraded: coderefDegraded || void 0
|
|
394
|
+
degraded: coderefDegraded || truncated || void 0,
|
|
395
|
+
// Internal metadata for the human-output path — NOT included in --json output
|
|
396
|
+
_skippedTooLarge: skippedTooLarge,
|
|
397
|
+
_skippedBinary: skippedBinary,
|
|
398
|
+
_truncated: truncated
|
|
368
399
|
};
|
|
369
400
|
return result;
|
|
370
401
|
}
|
|
371
402
|
|
|
372
403
|
// src/core/report.ts
|
|
373
404
|
import { mkdir as mkdir2, writeFile as writeFile2 } from "fs/promises";
|
|
374
|
-
import { dirname } from "path";
|
|
405
|
+
import { dirname, basename, join as join3 } from "path";
|
|
375
406
|
function severitySection(title, findings) {
|
|
376
407
|
if (findings.length === 0) {
|
|
377
408
|
return `## ${title}
|
|
@@ -402,10 +433,41 @@ function buildFixOrder(findings) {
|
|
|
402
433
|
...nonBlocking.sort((a, b) => severityOrder.indexOf(a.severity) - severityOrder.indexOf(b.severity))
|
|
403
434
|
];
|
|
404
435
|
if (sorted.length === 0) return "No findings to address.\n";
|
|
405
|
-
return sorted.map((f, i) => `${i + 1}. **${f.title}** (${f.severity}) \u2014 ${f.file}${f.line != null ? `:${f.line}` : ""}${f.blocking ? " \
|
|
436
|
+
return sorted.map((f, i) => `${i + 1}. **${f.title}** (${f.severity}) \u2014 ${f.file}${f.line != null ? `:${f.line}` : ""}${f.blocking ? " \u{1F6D1} blocking" : ""}`).join("\n");
|
|
437
|
+
}
|
|
438
|
+
function attitudeLine(recommendation) {
|
|
439
|
+
if (recommendation === "SAFE_TO_SHIP") return "SHIP IT \u2014 nothing blocking. Go make something people want.";
|
|
440
|
+
if (recommendation === "DO_NOT_SHIP") return "BLOCKED \u2014 shipping this would hurt. Fix the criticals first.";
|
|
441
|
+
return `HOLD UP \u2014 findings need eyes before this ships.`;
|
|
442
|
+
}
|
|
443
|
+
function topThreeFindings(findings) {
|
|
444
|
+
const severityOrder = ["critical", "high", "medium", "low", "info"];
|
|
445
|
+
const sorted = [...findings].sort((a, b) => {
|
|
446
|
+
if (a.blocking !== b.blocking) return a.blocking ? -1 : 1;
|
|
447
|
+
return severityOrder.indexOf(a.severity) - severityOrder.indexOf(b.severity);
|
|
448
|
+
});
|
|
449
|
+
const top = sorted.slice(0, 3);
|
|
450
|
+
if (top.length === 0) return "None \u2014 clean scan.\n";
|
|
451
|
+
return top.map((f, i) => `${i + 1}. **${f.title}** (${f.severity}) \u2014 ${f.file}${f.line != null ? `:${f.line}` : ""}`).join("\n");
|
|
452
|
+
}
|
|
453
|
+
function severityBreakdownTable(riskScore) {
|
|
454
|
+
const rows = [
|
|
455
|
+
["Critical", riskScore.criticalCount],
|
|
456
|
+
["High", riskScore.highCount],
|
|
457
|
+
["Medium", riskScore.mediumCount],
|
|
458
|
+
["Low", riskScore.lowCount],
|
|
459
|
+
["Info", riskScore.infoCount]
|
|
460
|
+
];
|
|
461
|
+
const lines = ["| Severity | Count |", "|----------|-------|"];
|
|
462
|
+
for (const [label, count] of rows) {
|
|
463
|
+
lines.push(`| ${label} | ${count} |`);
|
|
464
|
+
}
|
|
465
|
+
return lines.join("\n");
|
|
406
466
|
}
|
|
407
|
-
|
|
408
|
-
const { riskScore, findings, filesScanned, timestamp } = result;
|
|
467
|
+
function buildUserMarkdown(result, elapsedMs) {
|
|
468
|
+
const { riskScore, findings, filesScanned, timestamp, recommendation } = result;
|
|
469
|
+
const rec = recommendation ?? riskScore.recommendation;
|
|
470
|
+
const elapsedStr = elapsedMs != null ? elapsedMs < 1e3 ? `${elapsedMs}ms` : `${(elapsedMs / 1e3).toFixed(1)}s` : "N/A";
|
|
409
471
|
const critical = findings.filter((f) => f.severity === "critical");
|
|
410
472
|
const high = findings.filter((f) => f.severity === "high");
|
|
411
473
|
const medium = findings.filter((f) => f.severity === "medium");
|
|
@@ -413,12 +475,23 @@ async function generateReport(result, outputPath) {
|
|
|
413
475
|
const sections = [
|
|
414
476
|
"# ShipGuard Release Report",
|
|
415
477
|
"",
|
|
416
|
-
"##
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
478
|
+
"## SUMMARY",
|
|
479
|
+
"",
|
|
480
|
+
`**Verdict:** ${rec} \u2014 ${attitudeLine(rec)}`,
|
|
481
|
+
"",
|
|
482
|
+
`**Files scanned:** ${filesScanned} | **Elapsed:** ${elapsedStr} | **Generated:** ${timestamp}`,
|
|
483
|
+
"",
|
|
484
|
+
"### Severity Breakdown",
|
|
485
|
+
"",
|
|
486
|
+
severityBreakdownTable(riskScore),
|
|
487
|
+
"",
|
|
488
|
+
`**Risk Score:** ${riskScore.score}/100 | **Total Findings:** ${riskScore.totalFindings}`,
|
|
489
|
+
"",
|
|
490
|
+
"### Top 3 Things to Fix",
|
|
491
|
+
"",
|
|
492
|
+
topThreeFindings(findings),
|
|
493
|
+
"",
|
|
494
|
+
"---",
|
|
422
495
|
"",
|
|
423
496
|
severitySection("Critical Findings", critical),
|
|
424
497
|
severitySection("High Findings", high),
|
|
@@ -430,12 +503,30 @@ async function generateReport(result, outputPath) {
|
|
|
430
503
|
"",
|
|
431
504
|
"## Final Recommendation",
|
|
432
505
|
"",
|
|
433
|
-
`**${
|
|
506
|
+
`**${rec}**`,
|
|
434
507
|
""
|
|
435
508
|
];
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
509
|
+
return sections.join("\n");
|
|
510
|
+
}
|
|
511
|
+
function buildAgentJson(result) {
|
|
512
|
+
const publicResult = { ...result };
|
|
513
|
+
delete publicResult._skippedTooLarge;
|
|
514
|
+
delete publicResult._skippedBinary;
|
|
515
|
+
delete publicResult._truncated;
|
|
516
|
+
return JSON.stringify(publicResult, null, 2);
|
|
517
|
+
}
|
|
518
|
+
async function generateReport(result, outputPath, elapsedMs) {
|
|
519
|
+
const dir = dirname(outputPath);
|
|
520
|
+
const base = basename(outputPath, ".md");
|
|
521
|
+
const jsonPath = join3(dir, `${base}.json`);
|
|
522
|
+
const mdContent = buildUserMarkdown(result, elapsedMs);
|
|
523
|
+
const jsonContent = buildAgentJson(result);
|
|
524
|
+
await mkdir2(dir, { recursive: true });
|
|
525
|
+
await Promise.all([
|
|
526
|
+
writeFile2(outputPath, mdContent, "utf-8"),
|
|
527
|
+
writeFile2(jsonPath, jsonContent, "utf-8")
|
|
528
|
+
]);
|
|
529
|
+
return { mdPath: outputPath, jsonPath };
|
|
439
530
|
}
|
|
440
531
|
|
|
441
532
|
// src/core/sarif.ts
|
|
@@ -521,7 +612,472 @@ function toSarif(result) {
|
|
|
521
612
|
};
|
|
522
613
|
}
|
|
523
614
|
|
|
615
|
+
// src/core/render.ts
|
|
616
|
+
import chalk2 from "chalk";
|
|
617
|
+
import { existsSync as existsSync2, mkdirSync, writeFileSync } from "fs";
|
|
618
|
+
import { join as join4, basename as basename2 } from "path";
|
|
619
|
+
import { homedir } from "os";
|
|
620
|
+
var DOCS_URL = "https://agenticcli.dev/docs";
|
|
621
|
+
var SITE_URL = "https://agenticcli.dev";
|
|
622
|
+
var PRICING_URL = "https://agenticcli.dev/pricing";
|
|
623
|
+
var ISSUES_URL = "https://github.com/ramxH3421/agentic-cli/issues";
|
|
624
|
+
var SEVERITY_ORDER = ["critical", "high", "medium", "low", "info"];
|
|
625
|
+
var BOX_WIDTH = 78;
|
|
626
|
+
var H = "\u2500";
|
|
627
|
+
var V = "\u2502";
|
|
628
|
+
var TL = "\u256D";
|
|
629
|
+
var TR = "\u256E";
|
|
630
|
+
var BL = "\u2570";
|
|
631
|
+
var BR = "\u256F";
|
|
632
|
+
var SECTION = "\u251C" + H.repeat(BOX_WIDTH - 2) + "\u2524";
|
|
633
|
+
var BAR_FULL = "\u2588";
|
|
634
|
+
var BAR_EMPTY = "\u2591";
|
|
635
|
+
var SEVERITY_ICONS = {
|
|
636
|
+
critical: "\u{1F6D1}",
|
|
637
|
+
high: "\u26D4",
|
|
638
|
+
medium: "\u26A0\uFE0F",
|
|
639
|
+
low: "\u{1F41B}",
|
|
640
|
+
info: "\u2139\uFE0F"
|
|
641
|
+
};
|
|
642
|
+
function quickstartHelp(isTTY) {
|
|
643
|
+
const lines = [];
|
|
644
|
+
if (isTTY) {
|
|
645
|
+
lines.push("");
|
|
646
|
+
lines.push(chalk2.bold.cyan(" \u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E"));
|
|
647
|
+
lines.push(chalk2.bold.cyan(" \u2502") + chalk2.bold(" \u{1F6E1} ShipGuard \u2014 CLI-first release gate for AI-built apps ") + chalk2.bold.cyan(" \u2502"));
|
|
648
|
+
lines.push(chalk2.bold.cyan(" \u2502") + " Catches secrets, auth gaps, and deployment issues before you ship " + chalk2.bold.cyan(" \u2502"));
|
|
649
|
+
lines.push(chalk2.bold.cyan(" \u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F"));
|
|
650
|
+
lines.push("");
|
|
651
|
+
lines.push(chalk2.bold(" Get started in 2 commands:"));
|
|
652
|
+
lines.push("");
|
|
653
|
+
lines.push(` ${chalk2.green("npx @agenticcli/shipguard scan")} ${chalk2.dim("# zero install \u2014 scan right now")}`);
|
|
654
|
+
lines.push(` ${chalk2.green("shipguard scan --strict")} ${chalk2.dim("# CI mode: exit 1 on blocking issues")}`);
|
|
655
|
+
lines.push("");
|
|
656
|
+
lines.push(chalk2.bold(" Commands:"));
|
|
657
|
+
lines.push("");
|
|
658
|
+
lines.push(` ${chalk2.cyan("scan")} ${chalk2.dim("[path]")} Scan a project for high-risk issues`);
|
|
659
|
+
lines.push(` ${chalk2.cyan("init")} Generate a .shipguard.yml policy file`);
|
|
660
|
+
lines.push(` ${chalk2.cyan("login")} Authenticate to unlock Pro rules`);
|
|
661
|
+
lines.push(` ${chalk2.cyan("logout")} Remove saved credentials`);
|
|
662
|
+
lines.push(` ${chalk2.cyan("status")} Show auth status and credits`);
|
|
663
|
+
lines.push(` ${chalk2.cyan("feedback")} ${chalk2.dim("<text>")} Send feedback on your last scan`);
|
|
664
|
+
lines.push(` ${chalk2.cyan("rate")} ${chalk2.dim("<id> up|down")} Rate a rule finding`);
|
|
665
|
+
lines.push(` ${chalk2.cyan("help")} ${chalk2.dim("/ ?")} Show this screen`);
|
|
666
|
+
lines.push("");
|
|
667
|
+
lines.push(chalk2.bold(" Exit codes:"));
|
|
668
|
+
lines.push(` ${chalk2.green("0")} Safe \u2014 no blocking findings`);
|
|
669
|
+
lines.push(` ${chalk2.yellow("1")} Blocked \u2014 strict mode + blocking findings`);
|
|
670
|
+
lines.push(` ${chalk2.red("2")} Config error / degraded scan`);
|
|
671
|
+
lines.push(` ${chalk2.red("3")} Runtime error`);
|
|
672
|
+
lines.push("");
|
|
673
|
+
lines.push(` ${chalk2.dim("Docs")} ${chalk2.underline(DOCS_URL)}`);
|
|
674
|
+
lines.push(` ${chalk2.dim("Site")} ${chalk2.underline(SITE_URL)}`);
|
|
675
|
+
lines.push(` ${chalk2.dim("Pricing")} ${chalk2.underline(PRICING_URL)}`);
|
|
676
|
+
lines.push(` ${chalk2.dim("Issues")} ${chalk2.underline(ISSUES_URL)}`);
|
|
677
|
+
lines.push("");
|
|
678
|
+
} else {
|
|
679
|
+
lines.push("");
|
|
680
|
+
lines.push(" ShipGuard \u2014 CLI-first release gate for AI-built apps");
|
|
681
|
+
lines.push(" Catches secrets, auth gaps, and deployment issues before you ship");
|
|
682
|
+
lines.push("");
|
|
683
|
+
lines.push(" Get started in 2 commands:");
|
|
684
|
+
lines.push("");
|
|
685
|
+
lines.push(" npx @agenticcli/shipguard scan # zero install");
|
|
686
|
+
lines.push(" shipguard scan --strict # CI mode");
|
|
687
|
+
lines.push("");
|
|
688
|
+
lines.push(" Commands:");
|
|
689
|
+
lines.push(" scan [path] Scan a project");
|
|
690
|
+
lines.push(" init Generate policy file");
|
|
691
|
+
lines.push(" login Authenticate");
|
|
692
|
+
lines.push(" logout Remove credentials");
|
|
693
|
+
lines.push(" status Auth status + credits");
|
|
694
|
+
lines.push(" feedback <text> Send feedback");
|
|
695
|
+
lines.push(" rate <id> up|down Rate a finding");
|
|
696
|
+
lines.push(" help / ? Show this screen");
|
|
697
|
+
lines.push("");
|
|
698
|
+
lines.push(" Exit codes: 0=safe 1=blocked 2=config-error 3=runtime-error");
|
|
699
|
+
lines.push("");
|
|
700
|
+
lines.push(` Docs: ${DOCS_URL}`);
|
|
701
|
+
lines.push(` Site: ${SITE_URL}`);
|
|
702
|
+
lines.push(` Pricing: ${PRICING_URL}`);
|
|
703
|
+
lines.push(` Issues: ${ISSUES_URL}`);
|
|
704
|
+
lines.push("");
|
|
705
|
+
}
|
|
706
|
+
return lines.join("\n");
|
|
707
|
+
}
|
|
708
|
+
function findingFpLabel(confidence) {
|
|
709
|
+
switch (confidence) {
|
|
710
|
+
case "HIGH":
|
|
711
|
+
return "low false-positive chance";
|
|
712
|
+
case "MEDIUM":
|
|
713
|
+
return "moderate \u2014 review";
|
|
714
|
+
case "LOW":
|
|
715
|
+
return "higher false-positive \u2014 verify manually";
|
|
716
|
+
default:
|
|
717
|
+
return "unrated";
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
function renderProgressBar(current, total, width = 20, currentFile) {
|
|
721
|
+
const fraction = total > 0 ? Math.min(current / total, 1) : 0;
|
|
722
|
+
const filled = Math.round(fraction * width);
|
|
723
|
+
const empty = width - filled;
|
|
724
|
+
const bar = chalk2.cyan(BAR_FULL.repeat(filled)) + chalk2.gray(BAR_EMPTY.repeat(empty));
|
|
725
|
+
const counter = `${current}/${total}`;
|
|
726
|
+
const fileHint = currentFile ? ` ${chalk2.dim(basename2(currentFile) || truncatePath(currentFile, 30))}` : "";
|
|
727
|
+
return `${chalk2.cyan("\u{1F50D}")} scanning [${bar}] ${chalk2.bold(counter)}${fileHint}`;
|
|
728
|
+
}
|
|
729
|
+
function shouldShowProgress(gates) {
|
|
730
|
+
return gates.isTTY && !gates.quiet && !gates.machineOutput;
|
|
731
|
+
}
|
|
732
|
+
var SEVERITY_COLORS = {
|
|
733
|
+
critical: chalk2.bgRed.white,
|
|
734
|
+
high: chalk2.red,
|
|
735
|
+
medium: chalk2.yellow,
|
|
736
|
+
low: chalk2.blue,
|
|
737
|
+
info: chalk2.gray
|
|
738
|
+
};
|
|
739
|
+
function renderFindingsSummary(findings) {
|
|
740
|
+
if (findings.length === 0) {
|
|
741
|
+
return chalk2.green(" \u2713 No findings detected \u2014 clean scan.");
|
|
742
|
+
}
|
|
743
|
+
const lines = [];
|
|
744
|
+
lines.push(
|
|
745
|
+
chalk2.dim(
|
|
746
|
+
" Confidence legend: HIGH \u2192 low false-positive chance MEDIUM \u2192 moderate \u2014 review LOW \u2192 higher false-positive"
|
|
747
|
+
)
|
|
748
|
+
);
|
|
749
|
+
lines.push("");
|
|
750
|
+
for (const sev of SEVERITY_ORDER) {
|
|
751
|
+
const group = findings.filter((f) => f.severity === sev);
|
|
752
|
+
if (group.length === 0) continue;
|
|
753
|
+
const colorFn = SEVERITY_COLORS[sev] || chalk2.white;
|
|
754
|
+
const icon = SEVERITY_ICONS[sev] ?? "";
|
|
755
|
+
lines.push(` ${colorFn(` ${sev.toUpperCase().padEnd(8)} `)} ${icon} ${group.length} finding${group.length !== 1 ? "s" : ""}`);
|
|
756
|
+
for (const f of group) {
|
|
757
|
+
const location = f.line != null ? `${f.file}:${f.line}` : f.file;
|
|
758
|
+
const fpLabel = chalk2.dim(`[${findingFpLabel(f.confidence)}]`);
|
|
759
|
+
lines.push(` ${chalk2.bold(f.title)} \u2014 ${chalk2.cyan(location)} ${fpLabel}`);
|
|
760
|
+
if (f.evidence) {
|
|
761
|
+
lines.push(` Evidence: ${chalk2.yellow(truncate(f.evidence, 100))}`);
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
lines.push("");
|
|
765
|
+
}
|
|
766
|
+
return lines.join("\n");
|
|
767
|
+
}
|
|
768
|
+
function findingsByCategoryTable(findings) {
|
|
769
|
+
if (findings.length === 0) {
|
|
770
|
+
return chalk2.dim(" No findings across any category.");
|
|
771
|
+
}
|
|
772
|
+
const catCounts = {};
|
|
773
|
+
for (const f of findings) {
|
|
774
|
+
catCounts[f.category] = (catCounts[f.category] ?? 0) + 1;
|
|
775
|
+
}
|
|
776
|
+
const lines = [];
|
|
777
|
+
lines.push(chalk2.bold(" Category breakdown:"));
|
|
778
|
+
for (const [cat, count] of Object.entries(catCounts).sort()) {
|
|
779
|
+
const bar = chalk2.cyan("\u25A0".repeat(Math.min(count, 10)));
|
|
780
|
+
lines.push(` ${cat.padEnd(14)} ${String(count).padStart(3)} ${bar}`);
|
|
781
|
+
}
|
|
782
|
+
return lines.join("\n");
|
|
783
|
+
}
|
|
784
|
+
function coverageLine() {
|
|
785
|
+
return chalk2.dim(
|
|
786
|
+
` Coverage: secrets, auth, payments, database, deployment (free tier).
|
|
787
|
+
Deeper agentic rules available via Pro \u2014 some issue classes may be missed on free.
|
|
788
|
+
Upgrade: ${chalk2.underline(PRICING_URL)}`
|
|
789
|
+
);
|
|
790
|
+
}
|
|
791
|
+
var VERDICT_CONFIG = {
|
|
792
|
+
SAFE_TO_SHIP: {
|
|
793
|
+
icon: "\u2705",
|
|
794
|
+
color: chalk2.greenBright,
|
|
795
|
+
label: "SAFE TO SHIP",
|
|
796
|
+
// Deterministic verdict message — no RNG so tests are stable
|
|
797
|
+
attitudeLine: () => chalk2.green(" SHIP IT \u2014 nothing blocking. Go make something people want."),
|
|
798
|
+
helpLine: (blockingCount) => blockingCount > 0 ? chalk2.green(` No blocking issues \u2014 ${blockingCount} informational finding(s) noted.`) : chalk2.green(" Clean \u2014 safe to ship. No issues found.")
|
|
799
|
+
},
|
|
800
|
+
REVIEW_BEFORE_SHIP: {
|
|
801
|
+
icon: "\u26A0\uFE0F",
|
|
802
|
+
color: chalk2.yellowBright,
|
|
803
|
+
label: "REVIEW BEFORE SHIP",
|
|
804
|
+
attitudeLine: (blockingCount) => chalk2.yellow(` HOLD UP \u2014 ${blockingCount} finding${blockingCount !== 1 ? "s" : ""} want eyes before this ships.`),
|
|
805
|
+
helpLine: (blockingCount) => chalk2.yellow(` ${blockingCount} finding(s) need attention before shipping.`)
|
|
806
|
+
},
|
|
807
|
+
DO_NOT_SHIP: {
|
|
808
|
+
icon: "\u{1F6D1}",
|
|
809
|
+
color: chalk2.redBright,
|
|
810
|
+
label: "DO NOT SHIP",
|
|
811
|
+
attitudeLine: () => chalk2.red(" BLOCKED \u2014 shipping this would hurt. Fix the criticals first."),
|
|
812
|
+
helpLine: (blockingCount) => chalk2.red(` Blocked: ${blockingCount} critical/blocking issue(s) must be fixed first.`)
|
|
813
|
+
}
|
|
814
|
+
};
|
|
815
|
+
function boxLine(content) {
|
|
816
|
+
const inner = ` ${content}`;
|
|
817
|
+
const visibleLen = displayWidth(inner);
|
|
818
|
+
const pad = Math.max(0, BOX_WIDTH - 2 - visibleLen);
|
|
819
|
+
return `${V}${inner}${" ".repeat(pad)}${V}`;
|
|
820
|
+
}
|
|
821
|
+
function boxEmpty() {
|
|
822
|
+
return `${V}${" ".repeat(BOX_WIDTH - 2)}${V}`;
|
|
823
|
+
}
|
|
824
|
+
function boxTop() {
|
|
825
|
+
return chalk2.dim(TL + H.repeat(BOX_WIDTH - 2) + TR);
|
|
826
|
+
}
|
|
827
|
+
function boxBottom() {
|
|
828
|
+
return chalk2.dim(BL + H.repeat(BOX_WIDTH - 2) + BR);
|
|
829
|
+
}
|
|
830
|
+
function boxSection() {
|
|
831
|
+
return chalk2.dim(SECTION);
|
|
832
|
+
}
|
|
833
|
+
function severityBar(riskScore, barWidth = 30) {
|
|
834
|
+
const total = riskScore.totalFindings;
|
|
835
|
+
if (total === 0) return chalk2.green(" " + BAR_FULL.repeat(barWidth) + " all clear");
|
|
836
|
+
const counts = [
|
|
837
|
+
{ sev: "critical", count: riskScore.criticalCount, color: chalk2.bgRed.white },
|
|
838
|
+
{ sev: "high", count: riskScore.highCount, color: chalk2.red },
|
|
839
|
+
{ sev: "medium", count: riskScore.mediumCount, color: chalk2.yellow },
|
|
840
|
+
{ sev: "low", count: riskScore.lowCount, color: chalk2.blue },
|
|
841
|
+
{ sev: "info", count: riskScore.infoCount, color: chalk2.gray }
|
|
842
|
+
].filter((c) => c.count > 0);
|
|
843
|
+
let assigned = 0;
|
|
844
|
+
const segments = [];
|
|
845
|
+
for (let i = 0; i < counts.length; i++) {
|
|
846
|
+
const c = counts[i];
|
|
847
|
+
const w = i === counts.length - 1 ? barWidth - assigned : Math.max(1, Math.round(c.count / total * barWidth));
|
|
848
|
+
segments.push({ color: c.color, width: Math.min(w, barWidth - assigned), sev: c.sev });
|
|
849
|
+
assigned += segments[segments.length - 1].width;
|
|
850
|
+
if (assigned >= barWidth) break;
|
|
851
|
+
}
|
|
852
|
+
const bar = segments.map((s) => s.color(BAR_FULL.repeat(s.width))).join("");
|
|
853
|
+
const legend = counts.map((c) => {
|
|
854
|
+
const icon = SEVERITY_ICONS[c.sev] ?? "";
|
|
855
|
+
return `${icon}${c.count}`;
|
|
856
|
+
}).join(" ");
|
|
857
|
+
return ` ${bar} ${legend}`;
|
|
858
|
+
}
|
|
859
|
+
function verdictPanel(result, elapsedMs, skippedCount, topFindings) {
|
|
860
|
+
const { riskScore, filesScanned } = result;
|
|
861
|
+
const recommendation = riskScore.recommendation;
|
|
862
|
+
const cfg = VERDICT_CONFIG[recommendation];
|
|
863
|
+
const elapsedStr = elapsedMs < 1e3 ? `${elapsedMs}ms` : `${(elapsedMs / 1e3).toFixed(1)}s`;
|
|
864
|
+
const lines = [""];
|
|
865
|
+
lines.push(boxTop());
|
|
866
|
+
lines.push(boxLine(chalk2.bold(" ShipGuard \u2014 Release Gate Report")));
|
|
867
|
+
lines.push(boxEmpty());
|
|
868
|
+
const verdictLabel = cfg.color(chalk2.bold(`${cfg.icon} ${cfg.label}`));
|
|
869
|
+
lines.push(boxLine(` ${verdictLabel}`));
|
|
870
|
+
lines.push(boxEmpty());
|
|
871
|
+
const attitudeLine2 = recommendation === "REVIEW_BEFORE_SHIP" ? cfg.attitudeLine(riskScore.blockingCount) : cfg.attitudeLine();
|
|
872
|
+
lines.push(boxLine(attitudeLine2));
|
|
873
|
+
lines.push(boxEmpty());
|
|
874
|
+
lines.push(boxSection());
|
|
875
|
+
lines.push(boxLine(chalk2.bold(" Severity breakdown")));
|
|
876
|
+
lines.push(boxLine(severityBar(riskScore)));
|
|
877
|
+
lines.push(boxSection());
|
|
878
|
+
lines.push(boxLine(chalk2.bold(" Run summary")));
|
|
879
|
+
const skippedSuffix = skippedCount && skippedCount > 0 ? chalk2.dim(` (${skippedCount} skipped)`) : "";
|
|
880
|
+
lines.push(boxLine(` Files scanned: ${chalk2.cyan(filesScanned)}${skippedSuffix}`));
|
|
881
|
+
lines.push(boxLine(` Elapsed time: ${chalk2.cyan(elapsedStr)}`));
|
|
882
|
+
lines.push(boxLine(` Total findings: ${chalk2.cyan(riskScore.totalFindings)}`));
|
|
883
|
+
const sevLines = [];
|
|
884
|
+
if (riskScore.criticalCount > 0) sevLines.push(chalk2.red(`\u{1F6D1} ${riskScore.criticalCount} critical`));
|
|
885
|
+
if (riskScore.highCount > 0) sevLines.push(chalk2.red(`\u26D4 ${riskScore.highCount} high`));
|
|
886
|
+
if (riskScore.mediumCount > 0) sevLines.push(chalk2.yellow(`\u26A0\uFE0F ${riskScore.mediumCount} medium`));
|
|
887
|
+
if (riskScore.lowCount > 0) sevLines.push(chalk2.blue(`\u{1F41B} ${riskScore.lowCount} low`));
|
|
888
|
+
if (riskScore.infoCount > 0) sevLines.push(chalk2.gray(`\u2139\uFE0F ${riskScore.infoCount} info`));
|
|
889
|
+
if (sevLines.length > 0) {
|
|
890
|
+
lines.push(boxLine(` ${sevLines.join(" ")}`));
|
|
891
|
+
}
|
|
892
|
+
lines.push(boxSection());
|
|
893
|
+
lines.push(boxLine(chalk2.bold(" How ShipGuard helped")));
|
|
894
|
+
lines.push(boxLine(cfg.helpLine(riskScore.blockingCount)));
|
|
895
|
+
lines.push(boxSection());
|
|
896
|
+
lines.push(boxLine(chalk2.bold(" Learn more")));
|
|
897
|
+
lines.push(boxLine(` Docs ${chalk2.underline(DOCS_URL)}`));
|
|
898
|
+
lines.push(boxLine(` Site ${chalk2.underline(SITE_URL)}`));
|
|
899
|
+
lines.push(boxLine(` Pricing ${chalk2.underline(PRICING_URL)}`));
|
|
900
|
+
lines.push(boxEmpty());
|
|
901
|
+
lines.push(boxBottom());
|
|
902
|
+
lines.push("");
|
|
903
|
+
return lines.join("\n");
|
|
904
|
+
}
|
|
905
|
+
function actionFooter(opts) {
|
|
906
|
+
const { hasFindings, topRuleId, isLoggedIn } = opts;
|
|
907
|
+
const lines = [""];
|
|
908
|
+
lines.push(chalk2.bold(" \u2500\u2500 What now? \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"));
|
|
909
|
+
lines.push("");
|
|
910
|
+
lines.push(` ${chalk2.cyan("shipguard report")} ${chalk2.dim("# open the full report")}`);
|
|
911
|
+
if (hasFindings && topRuleId) {
|
|
912
|
+
lines.push(` ${chalk2.cyan(`shipguard rate ${topRuleId} up`)} ${chalk2.dim("# was this finding helpful?")}`);
|
|
913
|
+
lines.push(` ${chalk2.cyan(`shipguard rate ${topRuleId} down`)} ${chalk2.dim("# false positive?")}`);
|
|
914
|
+
} else if (hasFindings) {
|
|
915
|
+
lines.push(` ${chalk2.cyan("shipguard rate <ruleId> up")} ${chalk2.dim("# rate a finding")}`);
|
|
916
|
+
}
|
|
917
|
+
lines.push(` ${chalk2.cyan('shipguard feedback "<thoughts>"')} ${chalk2.dim("# what do you think?")}`);
|
|
918
|
+
if (!isLoggedIn) {
|
|
919
|
+
lines.push("");
|
|
920
|
+
lines.push(` ${chalk2.yellow("shipguard login")} ${chalk2.dim("# unlock Pro rules")}`);
|
|
921
|
+
lines.push(` ${chalk2.yellow("shipguard scan --pro")} ${chalk2.dim("# deeper checks after login")}`);
|
|
922
|
+
}
|
|
923
|
+
lines.push("");
|
|
924
|
+
lines.push(` ${chalk2.dim("Full docs: " + DOCS_URL)}`);
|
|
925
|
+
lines.push("");
|
|
926
|
+
return lines.join("\n");
|
|
927
|
+
}
|
|
928
|
+
function getShipguardConfigDir() {
|
|
929
|
+
return join4(homedir(), ".config", "shipguard");
|
|
930
|
+
}
|
|
931
|
+
function welcomeBanner(configDir) {
|
|
932
|
+
const dir = configDir ?? getShipguardConfigDir();
|
|
933
|
+
const marker = join4(dir, ".welcomed");
|
|
934
|
+
if (existsSync2(marker)) {
|
|
935
|
+
return "";
|
|
936
|
+
}
|
|
937
|
+
try {
|
|
938
|
+
mkdirSync(dir, { recursive: true });
|
|
939
|
+
writeFileSync(marker, "1", "utf-8");
|
|
940
|
+
} catch {
|
|
941
|
+
}
|
|
942
|
+
const BANNER_INNER = BOX_WIDTH - 2;
|
|
943
|
+
function bannerLine(content) {
|
|
944
|
+
const inner = ` ${content}`;
|
|
945
|
+
const w = displayWidth(inner);
|
|
946
|
+
const pad = Math.max(0, BANNER_INNER - w);
|
|
947
|
+
return chalk2.cyan(" \u2502") + inner + " ".repeat(pad) + chalk2.cyan("\u2502");
|
|
948
|
+
}
|
|
949
|
+
const top = chalk2.bold(chalk2.cyan(" \u256D" + "\u2500".repeat(BANNER_INNER) + "\u256E"));
|
|
950
|
+
const bottom = chalk2.bold(chalk2.cyan(" \u2570" + "\u2500".repeat(BANNER_INNER) + "\u256F"));
|
|
951
|
+
const empty = chalk2.cyan(" \u2502") + " ".repeat(BANNER_INNER) + chalk2.cyan("\u2502");
|
|
952
|
+
return [
|
|
953
|
+
"",
|
|
954
|
+
top,
|
|
955
|
+
bannerLine("ShipGuard is a CLI-first release gate for AI-built apps."),
|
|
956
|
+
bannerLine("It catches secrets, auth flaws, and deployment issues before"),
|
|
957
|
+
bannerLine("they ship \u2014 deterministic, fast, privacy-preserving."),
|
|
958
|
+
empty,
|
|
959
|
+
bannerLine(chalk2.bold("Quick start:")),
|
|
960
|
+
bannerLine(` ${chalk2.green("shipguard scan <path>")} Run a scan on your project`),
|
|
961
|
+
bannerLine(` ${chalk2.green("shipguard login")} Unlock Pro rules`),
|
|
962
|
+
bannerLine(` ${chalk2.green("shipguard scan --json")} Machine-readable output for CI/agents`),
|
|
963
|
+
empty,
|
|
964
|
+
bannerLine(`Docs: ${chalk2.underline(DOCS_URL)}`),
|
|
965
|
+
empty,
|
|
966
|
+
bannerLine(chalk2.dim("Anonymous usage ping enabled \u2014 opt out: SHIPGUARD_TELEMETRY=0")),
|
|
967
|
+
bannerLine(chalk2.dim(`Details: ${chalk2.underline("agenticcli.dev/docs#telemetry")}`)),
|
|
968
|
+
bottom,
|
|
969
|
+
""
|
|
970
|
+
].join("\n");
|
|
971
|
+
}
|
|
972
|
+
function quietVerdict(result) {
|
|
973
|
+
const { recommendation, score, totalFindings, blockingCount } = result.riskScore;
|
|
974
|
+
const icon = recommendation === "SAFE_TO_SHIP" ? "\u2705" : recommendation === "DO_NOT_SHIP" ? "\u26D4" : "\u26A0\uFE0F";
|
|
975
|
+
const colorFn = recommendation === "SAFE_TO_SHIP" ? chalk2.green : recommendation === "DO_NOT_SHIP" ? chalk2.red : chalk2.yellow;
|
|
976
|
+
return colorFn(`${icon} ${recommendation.replace(/_/g, " ")} score=${score}/100 findings=${totalFindings} blocking=${blockingCount}`);
|
|
977
|
+
}
|
|
978
|
+
function truncate(str, maxLen) {
|
|
979
|
+
return str.length <= maxLen ? str : `${str.slice(0, maxLen - 3)}...`;
|
|
980
|
+
}
|
|
981
|
+
function truncatePath(filePath, maxLen) {
|
|
982
|
+
if (filePath.length <= maxLen) return filePath;
|
|
983
|
+
const parts = filePath.split("/");
|
|
984
|
+
const tail = parts.slice(-2).join("/");
|
|
985
|
+
return tail.length <= maxLen ? `\u2026/${tail}` : `\u2026${tail.slice(-maxLen)}`;
|
|
986
|
+
}
|
|
987
|
+
function displayWidth(str) {
|
|
988
|
+
const plain = str.replace(/\x1b\[[0-9;]*m/g, "");
|
|
989
|
+
let width = 0;
|
|
990
|
+
for (const char of plain) {
|
|
991
|
+
const cp = char.codePointAt(0) ?? 0;
|
|
992
|
+
if (cp >= 65024 && cp <= 65039 || // Variation selectors
|
|
993
|
+
cp === 8204 || cp === 8205 || // ZWNJ, ZWJ
|
|
994
|
+
cp === 65279 || // BOM / zero-width no-break space
|
|
995
|
+
cp >= 768 && cp <= 879 || // Combining Diacritical Marks
|
|
996
|
+
cp >= 6832 && cp <= 6911 || // Combining Diacritical Marks Extended
|
|
997
|
+
cp >= 7616 && cp <= 7679 || // Combining Diacritical Marks Supplement
|
|
998
|
+
cp >= 8400 && cp <= 8447 || // Combining Diacritical Marks for Symbols
|
|
999
|
+
cp >= 65056 && cp <= 65071) {
|
|
1000
|
+
continue;
|
|
1001
|
+
}
|
|
1002
|
+
if (cp >= 4352 && cp <= 4447 || // Hangul Jamo
|
|
1003
|
+
cp >= 11904 && cp <= 12031 || // CJK Radicals Supplement
|
|
1004
|
+
cp >= 12032 && cp <= 12287 || // Kangxi Radicals
|
|
1005
|
+
cp >= 12288 && cp <= 12351 || // CJK Symbols and Punctuation
|
|
1006
|
+
cp >= 12352 && cp <= 12447 || // Hiragana
|
|
1007
|
+
cp >= 12448 && cp <= 12543 || // Katakana
|
|
1008
|
+
cp >= 12544 && cp <= 12591 || // Bopomofo
|
|
1009
|
+
cp >= 12592 && cp <= 12687 || // Hangul Compatibility Jamo
|
|
1010
|
+
cp >= 12688 && cp <= 12703 || // Kanbun
|
|
1011
|
+
cp >= 12704 && cp <= 12735 || // Bopomofo Extended
|
|
1012
|
+
cp >= 12784 && cp <= 12799 || // Katakana Phonetic Extensions
|
|
1013
|
+
cp >= 12800 && cp <= 13055 || // Enclosed CJK Letters and Months
|
|
1014
|
+
cp >= 13056 && cp <= 13311 || // CJK Compatibility
|
|
1015
|
+
cp >= 13312 && cp <= 19903 || // CJK Unified Ideographs Extension A
|
|
1016
|
+
cp >= 19968 && cp <= 40959 || // CJK Unified Ideographs
|
|
1017
|
+
cp >= 40960 && cp <= 42127 || // Yi Syllables
|
|
1018
|
+
cp >= 42128 && cp <= 42191 || // Yi Radicals
|
|
1019
|
+
cp >= 43360 && cp <= 43391 || // Hangul Jamo Extended-A
|
|
1020
|
+
cp >= 44032 && cp <= 55215 || // Hangul Syllables
|
|
1021
|
+
cp >= 55216 && cp <= 55295 || // Hangul Jamo Extended-B
|
|
1022
|
+
cp >= 63744 && cp <= 64255 || // CJK Compatibility Ideographs
|
|
1023
|
+
cp >= 65040 && cp <= 65055 || // Vertical Forms
|
|
1024
|
+
cp >= 65072 && cp <= 65103 || // CJK Compatibility Forms
|
|
1025
|
+
cp >= 65104 && cp <= 65135 || // Small Form Variants
|
|
1026
|
+
cp >= 65280 && cp <= 65519 || // Halfwidth and Fullwidth Forms
|
|
1027
|
+
cp >= 110592 && cp <= 110847 || // Kana Supplement
|
|
1028
|
+
cp >= 126976 && cp <= 131071 || // Mahjong/Domino/Emoji block (includes ⛔ ✅ ⚠ 🔴 etc.)
|
|
1029
|
+
cp >= 131072 && cp <= 173791 || // CJK Unified Ideographs Extension B
|
|
1030
|
+
cp >= 173824 && cp <= 183983 || // CJK Extensions C/D/E
|
|
1031
|
+
cp >= 183984 && cp <= 191471 || // CJK Extension F
|
|
1032
|
+
cp >= 196608 && cp <= 201551 || // CJK Extension G
|
|
1033
|
+
// Common BMP symbols rendered as 2-wide in most terminals
|
|
1034
|
+
cp === 8505 || // ℹ️
|
|
1035
|
+
cp === 8986 || cp === 8987 || // ⌚ ⌛
|
|
1036
|
+
cp === 9193 || cp === 9203 || // ⏩ ⏳
|
|
1037
|
+
cp >= 9725 && cp <= 9726 || // ◽ ◾
|
|
1038
|
+
cp >= 9728 && cp <= 10175 || // Misc Symbols & Dingbats (includes ⚠ ⛔ ✅)
|
|
1039
|
+
cp >= 11088 && cp <= 11093 || // ⭐ ⭕
|
|
1040
|
+
cp === 12351) {
|
|
1041
|
+
width += 2;
|
|
1042
|
+
continue;
|
|
1043
|
+
}
|
|
1044
|
+
width += 1;
|
|
1045
|
+
}
|
|
1046
|
+
return width;
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
// src/core/telemetry.ts
|
|
1050
|
+
function shouldSendTelemetry() {
|
|
1051
|
+
if (process.env.SHIPGUARD_TELEMETRY === "0") return false;
|
|
1052
|
+
if (process.env.DO_NOT_TRACK === "1") return false;
|
|
1053
|
+
return true;
|
|
1054
|
+
}
|
|
1055
|
+
function buildPayload(input) {
|
|
1056
|
+
const { cliVersion, verdict, durationMs, ci, rulePackCount } = input;
|
|
1057
|
+
return { cliVersion, verdict, durationMs, ci, rulePackCount };
|
|
1058
|
+
}
|
|
1059
|
+
function sendTelemetry(payload) {
|
|
1060
|
+
if (!shouldSendTelemetry()) return;
|
|
1061
|
+
const endpoint = process.env.SHIPGUARD_TELEMETRY_URL ?? "https://cheery-toucan-348.convex.site/cli-telemetry";
|
|
1062
|
+
const body = JSON.stringify(buildPayload(payload));
|
|
1063
|
+
const controller = new AbortController();
|
|
1064
|
+
const timeout = setTimeout(() => controller.abort(), 1e3);
|
|
1065
|
+
fetch(endpoint, {
|
|
1066
|
+
method: "POST",
|
|
1067
|
+
headers: { "Content-Type": "application/json" },
|
|
1068
|
+
body,
|
|
1069
|
+
signal: controller.signal
|
|
1070
|
+
}).catch(() => {
|
|
1071
|
+
if (process.env.SHIPGUARD_DEBUG) {
|
|
1072
|
+
console.debug("[shipguard:telemetry] ping failed (silent)");
|
|
1073
|
+
}
|
|
1074
|
+
}).finally(() => {
|
|
1075
|
+
clearTimeout(timeout);
|
|
1076
|
+
});
|
|
1077
|
+
}
|
|
1078
|
+
|
|
524
1079
|
// src/commands/scan.ts
|
|
1080
|
+
var LEARN_MORE = "Docs https://agenticcli.dev/docs \xB7 Site https://agenticcli.dev \xB7 Pricing https://agenticcli.dev/pricing \xB7 Issues https://github.com/ramxH3421/agentic-cli/issues";
|
|
525
1081
|
function resolveExitCode(opts) {
|
|
526
1082
|
if (opts.strict && opts.blockingCount > 0) {
|
|
527
1083
|
return EXIT_CODES.BLOCKED;
|
|
@@ -531,192 +1087,310 @@ function resolveExitCode(opts) {
|
|
|
531
1087
|
}
|
|
532
1088
|
return EXIT_CODES.SAFE;
|
|
533
1089
|
}
|
|
534
|
-
|
|
1090
|
+
function isProjectRoot(dir) {
|
|
1091
|
+
return existsSync3(join5(dir, "package.json")) || existsSync3(join5(dir, ".git"));
|
|
1092
|
+
}
|
|
535
1093
|
function scanCommand() {
|
|
536
|
-
return new Command2("scan").description("Scan your project for high-risk issues").option("--changed", "Only scan changed files from git diff").option("--report", "Generate a detailed Markdown report").option("--strict", "Exit with code 1 if blocking issues found").option("--json", "Output results as JSON").option("--sarif", "Output results as SARIF 2.1.0 (for GitHub Code Scanning)").option("--pro", "Include pro quality gate rules (requires authentication)").option("--api-url <url>", "API server URL", "https://agenticcli.dev").option("--category <categories>", "Comma-separated category filter for pro rules").option("--beta", "Include beta-stage rules").
|
|
537
|
-
|
|
1094
|
+
return new Command2("scan").description("Scan your project for high-risk issues (verbose by default; use --quiet for one-line verdict)").argument("[path]", "Path to project root to scan (defaults to current directory)").option("--changed", "Only scan changed files from git diff").option("--report", "Generate a detailed Markdown report").option("--strict", "Exit with code 1 if blocking issues found").option("--json", "Output results as JSON (machine-readable; suppresses all decoration)").option("--sarif", "Output results as SARIF 2.1.0 (for GitHub Code Scanning)").option("-q, --quiet", "One-line verdict only (suppresses progress, panel, and tips)").option("--pro", "Include pro quality gate rules (requires authentication)").option("--api-url <url>", "API server URL", "https://agenticcli.dev").option("--category <categories>", "Comma-separated category filter for pro rules").option("--beta", "Include beta-stage rules").option("--all", "Scan any directory, even without package.json or .git").addHelpText("after", `
|
|
1095
|
+
Output modes:
|
|
1096
|
+
(default) Verbose: live progress (TTY), categorized findings, gamified verdict panel
|
|
1097
|
+
--quiet / -q One-line verdict + exit code only \u2014 ideal for scripts
|
|
1098
|
+
--json Machine-readable JSON to stdout; all decoration suppressed
|
|
1099
|
+
--sarif SARIF 2.1.0 to stdout (GitHub Code Scanning)
|
|
1100
|
+
|
|
1101
|
+
Auto-quiet: progress animations are suppressed in non-TTY (piped/CI) environments automatically.
|
|
1102
|
+
|
|
1103
|
+
Examples:
|
|
1104
|
+
shipguard scan Scan current project (rich output)
|
|
1105
|
+
shipguard scan --quiet One-line verdict only
|
|
1106
|
+
shipguard scan ./my-app Scan a specific directory
|
|
1107
|
+
shipguard scan --changed Scan only git-diff files (faster)
|
|
1108
|
+
shipguard scan --json Machine-readable output for CI/agents
|
|
1109
|
+
shipguard scan --pro Include pro quality gate rules (requires login)
|
|
1110
|
+
shipguard scan --all Scan any directory regardless of project markers
|
|
1111
|
+
|
|
1112
|
+
Exit codes:
|
|
1113
|
+
0 Safe \u2014 no blocking findings
|
|
1114
|
+
1 Blocked \u2014 strict mode + blocking findings
|
|
1115
|
+
2 Config error / degraded scan (incomplete results)
|
|
1116
|
+
3 Runtime error
|
|
1117
|
+
|
|
1118
|
+
${LEARN_MORE}`).action(async (scanPath, opts) => {
|
|
1119
|
+
const startTime = Date.now();
|
|
1120
|
+
const cwd = scanPath ? resolve3(scanPath) : process.cwd();
|
|
538
1121
|
const scanId = randomUUID();
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
1122
|
+
const machineOutput = Boolean(opts.json) || Boolean(opts.sarif);
|
|
1123
|
+
const quiet = Boolean(opts.quiet);
|
|
1124
|
+
if (!scanPath && !opts.all && !isProjectRoot(cwd)) {
|
|
1125
|
+
logger.error(
|
|
1126
|
+
`Refusing to scan a non-project directory ${cwd}. Pass a path (\`shipguard scan ./my-app\`) or \`--all\` to override.`
|
|
1127
|
+
);
|
|
1128
|
+
if (!machineOutput) {
|
|
1129
|
+
console.log(`
|
|
1130
|
+
${LEARN_MORE}`);
|
|
1131
|
+
}
|
|
544
1132
|
process.exit(EXIT_CODES.CONFIG_ERROR);
|
|
545
1133
|
}
|
|
546
|
-
const
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
generateReport: Boolean(opts.report),
|
|
550
|
-
strict: Boolean(opts.strict),
|
|
551
|
-
json: Boolean(opts.json),
|
|
552
|
-
reportPath: policy.report.output ?? DEFAULT_REPORT_FILE
|
|
553
|
-
};
|
|
554
|
-
const machineOutput = scanOptions.json || Boolean(opts.sarif);
|
|
555
|
-
if (!machineOutput) {
|
|
556
|
-
logger.divider();
|
|
557
|
-
logger.info(`ShipGuard \u2014 scanning ${policy.project.name}`);
|
|
558
|
-
if (scanOptions.changedOnly && inGitRepo) {
|
|
559
|
-
logger.info("Mode: changed files only");
|
|
560
|
-
} else {
|
|
561
|
-
logger.info("Mode: full project scan");
|
|
562
|
-
}
|
|
563
|
-
logger.divider();
|
|
1134
|
+
const originalCwd = process.cwd();
|
|
1135
|
+
if (scanPath) {
|
|
1136
|
+
process.chdir(cwd);
|
|
564
1137
|
}
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
if (!machineOutput) {
|
|
571
|
-
logger.info("Detecting stack...");
|
|
572
|
-
}
|
|
573
|
-
try {
|
|
574
|
-
const { detectFrameworks } = await import("./framework-PA6RVE7G.js");
|
|
575
|
-
const { fetchProRules } = await import("./pro-scanner-YZDS67FB.js");
|
|
576
|
-
const { hasConfig, generateConfig } = await import("./config-generator-EQNRHODF.js");
|
|
577
|
-
const detectedResult = detectFrameworks(cwd);
|
|
578
|
-
const { frameworks } = detectedResult;
|
|
579
|
-
if (!hasConfig(cwd)) {
|
|
580
|
-
const configPath = generateConfig(cwd, detectedResult.frameworks);
|
|
581
|
-
if (!machineOutput) {
|
|
582
|
-
logger.success(`Config saved to ${configPath}`);
|
|
583
|
-
}
|
|
584
|
-
}
|
|
585
|
-
if (!machineOutput) {
|
|
586
|
-
for (const fw of frameworks) {
|
|
587
|
-
logger.info(` + ${fw.name}${fw.version ? ` ${fw.version}` : ""}`);
|
|
588
|
-
}
|
|
589
|
-
logger.info("Fetching pro rules...");
|
|
590
|
-
}
|
|
591
|
-
const categories = opts.category ? opts.category.split(",").map((c) => c.trim()) : void 0;
|
|
592
|
-
const fetched = await fetchProRules(
|
|
593
|
-
frameworks.map((f) => f.name),
|
|
594
|
-
categories,
|
|
595
|
-
opts.apiUrl
|
|
596
|
-
);
|
|
597
|
-
proRules = fetched.rules;
|
|
598
|
-
creditsRemaining = fetched.creditsRemaining;
|
|
599
|
-
rulesVersion = fetched.rulesVersion;
|
|
600
|
-
if (!machineOutput && proRules.length > 0) {
|
|
601
|
-
const breakdown = {};
|
|
602
|
-
for (const r of proRules) {
|
|
603
|
-
breakdown[r.category] = (breakdown[r.category] ?? 0) + 1;
|
|
604
|
-
}
|
|
605
|
-
const breakdownStr = Object.entries(breakdown).map(([cat, count]) => `${cat}: ${count}`).join(", ");
|
|
606
|
-
logger.info(` + ${proRules.length} rules loaded (${breakdownStr})`);
|
|
607
|
-
logger.info(" + Encrypted | Signed | Memory-only");
|
|
608
|
-
}
|
|
609
|
-
} catch (err) {
|
|
610
|
-
logger.warn(`Pro rules unavailable: ${err instanceof Error ? err.message : String(err)}`);
|
|
611
|
-
logger.warn("Degrading to free scan \u2014 pro rules will not be applied");
|
|
612
|
-
degraded = true;
|
|
1138
|
+
try {
|
|
1139
|
+
await runScan({ cwd, scanId, opts, machineOutput, quiet, startTime });
|
|
1140
|
+
} finally {
|
|
1141
|
+
if (scanPath) {
|
|
1142
|
+
process.chdir(originalCwd);
|
|
613
1143
|
}
|
|
614
1144
|
}
|
|
615
|
-
|
|
616
|
-
|
|
1145
|
+
});
|
|
1146
|
+
}
|
|
1147
|
+
async function runScan(ctx) {
|
|
1148
|
+
const { cwd, scanId, opts, machineOutput, quiet, startTime } = ctx;
|
|
1149
|
+
let policy;
|
|
1150
|
+
try {
|
|
1151
|
+
policy = await loadPolicy(cwd);
|
|
1152
|
+
} catch (error) {
|
|
1153
|
+
logger.error(`Config error: ${error instanceof Error ? error.message : error}`);
|
|
1154
|
+
process.exit(EXIT_CODES.CONFIG_ERROR);
|
|
1155
|
+
return;
|
|
1156
|
+
}
|
|
1157
|
+
const inGitRepo = isGitRepo(cwd);
|
|
1158
|
+
const scanOptions = {
|
|
1159
|
+
changedOnly: Boolean(opts.changed),
|
|
1160
|
+
generateReport: Boolean(opts.report),
|
|
1161
|
+
strict: Boolean(opts.strict),
|
|
1162
|
+
json: Boolean(opts.json),
|
|
1163
|
+
reportPath: policy.report.output ?? DEFAULT_REPORT_FILE
|
|
1164
|
+
};
|
|
1165
|
+
if (!machineOutput && !quiet) {
|
|
1166
|
+
logger.divider();
|
|
1167
|
+
logger.info(`ShipGuard \u2014 scanning ${policy.project.name}`);
|
|
1168
|
+
logger.info(`Scan path: ${cwd}`);
|
|
1169
|
+
if (scanOptions.changedOnly && inGitRepo) {
|
|
1170
|
+
logger.info("Mode: changed files only");
|
|
1171
|
+
} else {
|
|
1172
|
+
logger.info("Mode: full project scan");
|
|
1173
|
+
}
|
|
1174
|
+
logger.divider();
|
|
1175
|
+
}
|
|
1176
|
+
let proRules;
|
|
1177
|
+
let creditsRemaining;
|
|
1178
|
+
let rulesVersion;
|
|
1179
|
+
let degraded = false;
|
|
1180
|
+
if (opts.pro) {
|
|
1181
|
+
if (!machineOutput && !quiet) {
|
|
1182
|
+
logger.info("Detecting stack...");
|
|
617
1183
|
}
|
|
618
|
-
let result;
|
|
619
1184
|
try {
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
}
|
|
625
|
-
|
|
1185
|
+
const { detectFrameworks } = await import("./framework-PA6RVE7G.js");
|
|
1186
|
+
const { fetchProRules } = await import("./pro-scanner-IJJLUSAC.js");
|
|
1187
|
+
const { hasConfig, generateConfig } = await import("./config-generator-YSWNA53I.js");
|
|
1188
|
+
const detectedResult = detectFrameworks(cwd);
|
|
1189
|
+
const { frameworks } = detectedResult;
|
|
1190
|
+
if (!hasConfig(cwd)) {
|
|
1191
|
+
const configPath = generateConfig(cwd, detectedResult.frameworks);
|
|
1192
|
+
if (!machineOutput && !quiet) {
|
|
1193
|
+
logger.success(`Config saved to ${configPath}`);
|
|
1194
|
+
}
|
|
626
1195
|
}
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
result.creditsWarning = creditsRemaining !== void 0 && creditsRemaining < 10;
|
|
633
|
-
result.rulesVersion = rulesVersion;
|
|
634
|
-
if (proRules?.length) {
|
|
635
|
-
const breakdown = {};
|
|
636
|
-
for (const r of proRules) {
|
|
637
|
-
breakdown[r.category] = (breakdown[r.category] ?? 0) + 1;
|
|
1196
|
+
if (!machineOutput && !quiet) {
|
|
1197
|
+
for (const fw of frameworks) {
|
|
1198
|
+
logger.info(` + ${fw.name}${fw.version ? ` ${fw.version}` : ""}`);
|
|
1199
|
+
}
|
|
1200
|
+
logger.info("Fetching pro rules...");
|
|
638
1201
|
}
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
for (const severity of SEVERITY_ORDER) {
|
|
653
|
-
const group = findings.filter((f) => f.severity === severity);
|
|
654
|
-
if (group.length === 0) continue;
|
|
655
|
-
for (const finding of group) {
|
|
656
|
-
const location = finding.line != null ? `${finding.file}:${finding.line}` : finding.file;
|
|
657
|
-
logger.finding(severity, `${finding.title} \u2014 ${location}`);
|
|
658
|
-
if (finding.evidence) {
|
|
659
|
-
logger.finding(severity, ` Evidence: ${finding.evidence}`);
|
|
660
|
-
}
|
|
661
|
-
}
|
|
1202
|
+
const categories = opts.category ? opts.category.split(",").map((c) => c.trim()) : void 0;
|
|
1203
|
+
const fetched = await fetchProRules(
|
|
1204
|
+
frameworks.map((f) => f.name),
|
|
1205
|
+
categories,
|
|
1206
|
+
opts.apiUrl
|
|
1207
|
+
);
|
|
1208
|
+
proRules = fetched.rules;
|
|
1209
|
+
creditsRemaining = fetched.creditsRemaining;
|
|
1210
|
+
rulesVersion = fetched.rulesVersion;
|
|
1211
|
+
if (!machineOutput && !quiet && proRules.length > 0) {
|
|
1212
|
+
const breakdown = {};
|
|
1213
|
+
for (const r of proRules) {
|
|
1214
|
+
breakdown[r.category] = (breakdown[r.category] ?? 0) + 1;
|
|
662
1215
|
}
|
|
1216
|
+
const breakdownStr = Object.entries(breakdown).map(([cat, count]) => `${cat}: ${count}`).join(", ");
|
|
1217
|
+
logger.info(` + ${proRules.length} rules loaded (${breakdownStr})`);
|
|
1218
|
+
logger.info(" + Encrypted | Signed | Memory-only");
|
|
663
1219
|
}
|
|
664
|
-
|
|
1220
|
+
} catch (err) {
|
|
1221
|
+
logger.warn(`Pro rules unavailable: ${err instanceof Error ? err.message : String(err)}`);
|
|
1222
|
+
logger.warn("Degrading to free scan \u2014 pro rules will not be applied");
|
|
1223
|
+
degraded = true;
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
const showProgress = shouldShowProgress({
|
|
1227
|
+
isTTY: Boolean(process.stdout.isTTY),
|
|
1228
|
+
quiet,
|
|
1229
|
+
machineOutput
|
|
1230
|
+
});
|
|
1231
|
+
let lastDrawMs = 0;
|
|
1232
|
+
const onProgress = showProgress ? (current, total, file) => {
|
|
1233
|
+
const now = Date.now();
|
|
1234
|
+
if (now - lastDrawMs >= 60 || current === total) {
|
|
1235
|
+
lastDrawMs = now;
|
|
1236
|
+
process.stderr.write(`\r\x1B[K${renderProgressBar(current, total, 20, file)}`);
|
|
1237
|
+
}
|
|
1238
|
+
} : void 0;
|
|
1239
|
+
if (!showProgress && !machineOutput && !quiet) {
|
|
1240
|
+
logger.info("Scanning files...");
|
|
1241
|
+
}
|
|
1242
|
+
let result;
|
|
1243
|
+
try {
|
|
1244
|
+
result = await scan(scanOptions, proRules, onProgress);
|
|
1245
|
+
} catch (error) {
|
|
1246
|
+
if (showProgress) {
|
|
1247
|
+
process.stderr.write("\r\x1B[K");
|
|
1248
|
+
}
|
|
1249
|
+
if (!machineOutput) {
|
|
1250
|
+
logger.error(`Scan failed: ${error instanceof Error ? error.message : error}`);
|
|
1251
|
+
} else {
|
|
1252
|
+
console.log(JSON.stringify({ error: String(error) }));
|
|
1253
|
+
}
|
|
1254
|
+
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
|
1255
|
+
}
|
|
1256
|
+
if (showProgress) {
|
|
1257
|
+
process.stderr.write("\r\x1B[K");
|
|
1258
|
+
}
|
|
1259
|
+
const skippedTooLarge = result._skippedTooLarge ?? 0;
|
|
1260
|
+
const skippedBinary = result._skippedBinary ?? 0;
|
|
1261
|
+
const truncatedByBounds = result._truncated ?? false;
|
|
1262
|
+
result.recommendation = result.riskScore.recommendation;
|
|
1263
|
+
result.schemaVersion = "2";
|
|
1264
|
+
result.degraded = degraded || Boolean(result.degraded);
|
|
1265
|
+
result.creditsWarning = creditsRemaining !== void 0 && creditsRemaining < 10;
|
|
1266
|
+
result.rulesVersion = rulesVersion;
|
|
1267
|
+
if (proRules?.length) {
|
|
1268
|
+
const breakdown = {};
|
|
1269
|
+
for (const r of proRules) {
|
|
1270
|
+
breakdown[r.category] = (breakdown[r.category] ?? 0) + 1;
|
|
1271
|
+
}
|
|
1272
|
+
result.rulesApplied = proRules.length;
|
|
1273
|
+
result.rulesBreakdown = breakdown;
|
|
1274
|
+
result.aiCodeIssues = result.findings.filter((f) => f.aiCodeTarget).length;
|
|
1275
|
+
}
|
|
1276
|
+
const publicResult = { ...result };
|
|
1277
|
+
delete publicResult._skippedTooLarge;
|
|
1278
|
+
delete publicResult._skippedBinary;
|
|
1279
|
+
delete publicResult._truncated;
|
|
1280
|
+
if (opts.sarif) {
|
|
1281
|
+
console.log(JSON.stringify(toSarif(publicResult), null, 2));
|
|
1282
|
+
} else if (scanOptions.json) {
|
|
1283
|
+
console.log(JSON.stringify(publicResult, null, 2));
|
|
1284
|
+
} else if (quiet) {
|
|
1285
|
+
console.log(quietVerdict(result));
|
|
1286
|
+
} else {
|
|
1287
|
+
const elapsedMs = Date.now() - startTime;
|
|
1288
|
+
const isTTY = Boolean(process.stdout.isTTY);
|
|
1289
|
+
if (isTTY) {
|
|
1290
|
+
const banner = welcomeBanner();
|
|
1291
|
+
if (banner) console.log(banner);
|
|
1292
|
+
}
|
|
1293
|
+
console.log(renderFindingsSummary(result.findings));
|
|
1294
|
+
if (result.findings.length > 0) {
|
|
1295
|
+
console.log(findingsByCategoryTable(result.findings));
|
|
665
1296
|
console.log("");
|
|
666
|
-
logger.info(`Files scanned: ${result.filesScanned} | Findings: ${riskScore.totalFindings} | Blocking: ${riskScore.blockingCount}`);
|
|
667
|
-
if (creditsRemaining !== void 0) {
|
|
668
|
-
logger.info(`Credits remaining: ${creditsRemaining}`);
|
|
669
|
-
}
|
|
670
|
-
if (degraded) {
|
|
671
|
-
logger.warn("Scan ran in degraded mode \u2014 pro rules were unavailable");
|
|
672
|
-
}
|
|
673
1297
|
}
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
await generateReport(result, reportPath);
|
|
679
|
-
if (!machineOutput) {
|
|
680
|
-
logger.success(`Report written to ${reportPath}`);
|
|
681
|
-
}
|
|
682
|
-
} catch (error) {
|
|
683
|
-
logger.error(`Report generation failed: ${error instanceof Error ? error.message : error}`);
|
|
684
|
-
}
|
|
1298
|
+
if (skippedTooLarge > 0 || skippedBinary > 0) {
|
|
1299
|
+
logger.info(
|
|
1300
|
+
`Files skipped: ${skippedTooLarge + skippedBinary}` + (skippedTooLarge > 0 ? ` (too large: ${skippedTooLarge})` : "") + (skippedBinary > 0 ? ` (binary: ${skippedBinary})` : "")
|
|
1301
|
+
);
|
|
685
1302
|
}
|
|
686
|
-
if (
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
1303
|
+
if (creditsRemaining !== void 0) {
|
|
1304
|
+
logger.info(`Credits remaining: ${creditsRemaining}`);
|
|
1305
|
+
}
|
|
1306
|
+
if (degraded) {
|
|
1307
|
+
logger.warn("Scan ran in degraded mode \u2014 pro rules were unavailable");
|
|
1308
|
+
}
|
|
1309
|
+
if (truncatedByBounds) {
|
|
1310
|
+
logger.warn(
|
|
1311
|
+
`Scan was truncated: file count or total size limit was reached. Results are INCOMPLETE \u2014 add a \`.shipguardignore\` or edit \`shipguard.policy.yml\` limits.`
|
|
1312
|
+
);
|
|
1313
|
+
logger.warn(`Docs: https://agenticcli.dev/docs`);
|
|
1314
|
+
}
|
|
1315
|
+
console.log(coverageLine());
|
|
1316
|
+
console.log("");
|
|
1317
|
+
console.log(verdictPanel(result, elapsedMs, skippedTooLarge + skippedBinary, result.findings));
|
|
1318
|
+
const topRuleId = result.findings.length > 0 ? result.findings[0].id : void 0;
|
|
1319
|
+
const isLoggedIn = Boolean(opts.pro && !degraded);
|
|
1320
|
+
console.log(actionFooter({
|
|
1321
|
+
hasFindings: result.findings.length > 0,
|
|
1322
|
+
topRuleId,
|
|
1323
|
+
isLoggedIn
|
|
1324
|
+
}));
|
|
1325
|
+
}
|
|
1326
|
+
const shouldReport = scanOptions.generateReport || policy.scan.generate_report;
|
|
1327
|
+
if (shouldReport) {
|
|
1328
|
+
const reportPath = scanOptions.reportPath;
|
|
1329
|
+
const reportElapsedMs = Date.now() - startTime;
|
|
1330
|
+
try {
|
|
1331
|
+
const paths = await generateReport(result, reportPath, reportElapsedMs);
|
|
1332
|
+
if (!machineOutput && !quiet) {
|
|
1333
|
+
logger.success(`Report: ${paths.mdPath} \xB7 agent view: ${paths.jsonPath}`);
|
|
1334
|
+
}
|
|
1335
|
+
} catch (error) {
|
|
1336
|
+
logger.error(`Report generation failed: ${error instanceof Error ? error.message : error}`);
|
|
707
1337
|
}
|
|
708
|
-
|
|
1338
|
+
}
|
|
1339
|
+
if (opts.pro && !degraded) {
|
|
1340
|
+
fetch(`${opts.apiUrl}/api/telemetry/ingest`, {
|
|
1341
|
+
method: "POST",
|
|
1342
|
+
headers: { "Content-Type": "application/json" },
|
|
1343
|
+
body: JSON.stringify({
|
|
1344
|
+
scanId,
|
|
1345
|
+
findingsCount: result.findings.length,
|
|
1346
|
+
blocked: result.riskScore.blockingCount > 0,
|
|
1347
|
+
riskScore: result.riskScore.score,
|
|
1348
|
+
recommendation: result.riskScore.recommendation,
|
|
1349
|
+
severityBreakdown: {
|
|
1350
|
+
critical: result.riskScore.criticalCount,
|
|
1351
|
+
high: result.riskScore.highCount,
|
|
1352
|
+
medium: result.riskScore.mediumCount,
|
|
1353
|
+
low: result.riskScore.lowCount,
|
|
1354
|
+
info: result.riskScore.infoCount
|
|
1355
|
+
},
|
|
1356
|
+
rulesApplied: proRules?.length ?? 0
|
|
1357
|
+
})
|
|
1358
|
+
}).catch(() => {
|
|
1359
|
+
});
|
|
1360
|
+
}
|
|
1361
|
+
try {
|
|
1362
|
+
const elapsedMs = Date.now() - startTime;
|
|
1363
|
+
const exitCode2 = resolveExitCode({
|
|
709
1364
|
strict: scanOptions.strict,
|
|
710
1365
|
blockingCount: result.riskScore.blockingCount,
|
|
711
1366
|
degraded: Boolean(result.degraded)
|
|
712
1367
|
});
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
}
|
|
1368
|
+
const verdictMap = {
|
|
1369
|
+
[EXIT_CODES.SAFE]: "safe",
|
|
1370
|
+
[EXIT_CODES.BLOCKED]: "blocked",
|
|
1371
|
+
[EXIT_CODES.CONFIG_ERROR]: "review",
|
|
1372
|
+
[EXIT_CODES.RUNTIME_ERROR]: "error"
|
|
1373
|
+
};
|
|
1374
|
+
sendTelemetry({
|
|
1375
|
+
cliVersion: "0.1.2",
|
|
1376
|
+
verdict: verdictMap[exitCode2] ?? "error",
|
|
1377
|
+
durationMs: elapsedMs,
|
|
1378
|
+
ci: Boolean(process.env.CI),
|
|
1379
|
+
rulePackCount: proRules ? 1 : 0
|
|
1380
|
+
});
|
|
1381
|
+
} catch {
|
|
1382
|
+
}
|
|
1383
|
+
const exitCode = resolveExitCode({
|
|
1384
|
+
strict: scanOptions.strict,
|
|
1385
|
+
blockingCount: result.riskScore.blockingCount,
|
|
1386
|
+
degraded: Boolean(result.degraded)
|
|
719
1387
|
});
|
|
1388
|
+
if (exitCode === EXIT_CODES.BLOCKED && !machineOutput && !quiet) {
|
|
1389
|
+
logger.warn(`Strict mode: ${result.riskScore.blockingCount} blocking finding(s) \u2014 exiting with code 1`);
|
|
1390
|
+
}
|
|
1391
|
+
if (exitCode !== EXIT_CODES.SAFE) {
|
|
1392
|
+
process.exit(exitCode);
|
|
1393
|
+
}
|
|
720
1394
|
}
|
|
721
1395
|
|
|
722
1396
|
// src/commands/login.ts
|
|
@@ -895,9 +1569,53 @@ function rateCommand() {
|
|
|
895
1569
|
});
|
|
896
1570
|
}
|
|
897
1571
|
|
|
1572
|
+
// src/handlers.ts
|
|
1573
|
+
var ISSUES_URL2 = "https://github.com/ramxH3421/agentic-cli/issues";
|
|
1574
|
+
var DOCS_URL2 = "https://agenticcli.dev/docs";
|
|
1575
|
+
var REPORT_LINE = `Report this: ${ISSUES_URL2} \xB7 Docs: ${DOCS_URL2}`;
|
|
1576
|
+
function handleUncaughtException(error) {
|
|
1577
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1578
|
+
console.error(`\x1B[31m\u2717\x1B[0m Unexpected error: ${message}`);
|
|
1579
|
+
if (process.env.SHIPGUARD_DEBUG && error instanceof Error) {
|
|
1580
|
+
console.error(error.stack);
|
|
1581
|
+
}
|
|
1582
|
+
console.error(REPORT_LINE);
|
|
1583
|
+
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
|
1584
|
+
}
|
|
1585
|
+
function handleUnhandledRejection(reason, _promise) {
|
|
1586
|
+
const message = reason instanceof Error ? reason.message : String(reason);
|
|
1587
|
+
console.error(`\x1B[31m\u2717\x1B[0m Unhandled rejection: ${message}`);
|
|
1588
|
+
if (process.env.SHIPGUARD_DEBUG && reason instanceof Error) {
|
|
1589
|
+
console.error(reason.stack);
|
|
1590
|
+
}
|
|
1591
|
+
console.error(REPORT_LINE);
|
|
1592
|
+
process.exit(EXIT_CODES.RUNTIME_ERROR);
|
|
1593
|
+
}
|
|
1594
|
+
function handleSignal() {
|
|
1595
|
+
console.error("\nInterrupted.");
|
|
1596
|
+
process.exit(130);
|
|
1597
|
+
}
|
|
1598
|
+
|
|
898
1599
|
// src/cli.ts
|
|
1600
|
+
process.on("uncaughtException", handleUncaughtException);
|
|
1601
|
+
process.on("unhandledRejection", handleUnhandledRejection);
|
|
1602
|
+
process.on("SIGINT", handleSignal);
|
|
1603
|
+
process.on("SIGTERM", handleSignal);
|
|
1604
|
+
var ISSUES_URL3 = "https://github.com/ramxH3421/agentic-cli/issues";
|
|
899
1605
|
var program = new Command7();
|
|
900
|
-
|
|
1606
|
+
var rawArgs = process.argv.slice(2);
|
|
1607
|
+
if (rawArgs[0] === "?") {
|
|
1608
|
+
process.argv = [process.argv[0], process.argv[1], "help"];
|
|
1609
|
+
}
|
|
1610
|
+
program.name("shipguard").description("CLI-first release gate for AI-built apps").version(
|
|
1611
|
+
true ? "0.2.0" : process.env.npm_package_version ?? "0.0.0-dev"
|
|
1612
|
+
).helpCommand(false).addHelpText("after", `
|
|
1613
|
+
Learn more:
|
|
1614
|
+
Docs https://agenticcli.dev/docs
|
|
1615
|
+
Site https://agenticcli.dev
|
|
1616
|
+
Pricing https://agenticcli.dev/pricing
|
|
1617
|
+
Issues ${ISSUES_URL3}`);
|
|
1618
|
+
program.exitOverride();
|
|
901
1619
|
program.addCommand(initCommand());
|
|
902
1620
|
program.addCommand(scanCommand());
|
|
903
1621
|
program.addCommand(loginCommand());
|
|
@@ -905,4 +1623,86 @@ program.addCommand(logoutCommand());
|
|
|
905
1623
|
program.addCommand(statusCommand());
|
|
906
1624
|
program.addCommand(feedbackCommand());
|
|
907
1625
|
program.addCommand(rateCommand());
|
|
908
|
-
program.
|
|
1626
|
+
program.addCommand(
|
|
1627
|
+
new Command7("help").description("Show the quickstart guide").action(() => {
|
|
1628
|
+
const isTTY = Boolean(process.stdout.isTTY);
|
|
1629
|
+
process.stdout.write(quickstartHelp(isTTY) + "\n");
|
|
1630
|
+
})
|
|
1631
|
+
);
|
|
1632
|
+
program.allowExcessArguments(true);
|
|
1633
|
+
program.action(() => {
|
|
1634
|
+
const isTTY = Boolean(process.stdout.isTTY);
|
|
1635
|
+
process.stdout.write(quickstartHelp(isTTY) + "\n");
|
|
1636
|
+
});
|
|
1637
|
+
function levenshtein(a, b) {
|
|
1638
|
+
const m = a.length;
|
|
1639
|
+
const n = b.length;
|
|
1640
|
+
const dp = Array.from(
|
|
1641
|
+
{ length: m + 1 },
|
|
1642
|
+
(_, i) => Array.from({ length: n + 1 }, (_2, j) => i === 0 ? j : j === 0 ? i : 0)
|
|
1643
|
+
);
|
|
1644
|
+
for (let i = 1; i <= m; i++) {
|
|
1645
|
+
for (let j = 1; j <= n; j++) {
|
|
1646
|
+
dp[i][j] = a[i - 1] === b[j - 1] ? dp[i - 1][j - 1] : 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
|
|
1647
|
+
}
|
|
1648
|
+
}
|
|
1649
|
+
return dp[m][n];
|
|
1650
|
+
}
|
|
1651
|
+
function closestCommand(input) {
|
|
1652
|
+
const names = ["scan", "init", "login", "logout", "status", "feedback", "rate", "help"];
|
|
1653
|
+
let best;
|
|
1654
|
+
let bestDist = Infinity;
|
|
1655
|
+
for (const name of names) {
|
|
1656
|
+
const d = levenshtein(input.toLowerCase(), name);
|
|
1657
|
+
if (d < bestDist) {
|
|
1658
|
+
bestDist = d;
|
|
1659
|
+
best = name;
|
|
1660
|
+
}
|
|
1661
|
+
}
|
|
1662
|
+
return bestDist <= 3 ? best : void 0;
|
|
1663
|
+
}
|
|
1664
|
+
(async () => {
|
|
1665
|
+
const KNOWN_COMMANDS = /* @__PURE__ */ new Set(["scan", "init", "login", "logout", "status", "feedback", "rate", "help"]);
|
|
1666
|
+
const firstNonFlag = process.argv.slice(2).find((a) => !a.startsWith("-"));
|
|
1667
|
+
if (firstNonFlag && firstNonFlag !== "?" && !KNOWN_COMMANDS.has(firstNonFlag)) {
|
|
1668
|
+
const suggestion = closestCommand(firstNonFlag);
|
|
1669
|
+
const hint = suggestion ? `
|
|
1670
|
+
Did you mean \`shipguard ${suggestion}\`?` : "";
|
|
1671
|
+
process.stderr.write(
|
|
1672
|
+
`shipguard: unknown command "${firstNonFlag}"${hint}
|
|
1673
|
+
Run \`shipguard help\` to see available commands.
|
|
1674
|
+
`
|
|
1675
|
+
);
|
|
1676
|
+
process.exit(2);
|
|
1677
|
+
}
|
|
1678
|
+
try {
|
|
1679
|
+
await program.parseAsync(process.argv);
|
|
1680
|
+
} catch (err) {
|
|
1681
|
+
if (err instanceof CommanderError) {
|
|
1682
|
+
if (err.code === "commander.unknownCommand") {
|
|
1683
|
+
const unknownToken = process.argv.slice(2).find((a) => !a.startsWith("-")) ?? "?";
|
|
1684
|
+
const suggestion = closestCommand(unknownToken);
|
|
1685
|
+
const hint = suggestion ? `
|
|
1686
|
+
Did you mean \`shipguard ${suggestion}\`?` : "";
|
|
1687
|
+
process.stderr.write(
|
|
1688
|
+
`shipguard: unknown command "${unknownToken}"${hint}
|
|
1689
|
+
Run \`shipguard help\` to see available commands.
|
|
1690
|
+
`
|
|
1691
|
+
);
|
|
1692
|
+
process.exit(2);
|
|
1693
|
+
}
|
|
1694
|
+
if (err.exitCode === 0) {
|
|
1695
|
+
process.exit(0);
|
|
1696
|
+
}
|
|
1697
|
+
process.stderr.write(`shipguard: ${err.message}
|
|
1698
|
+
`);
|
|
1699
|
+
process.exit(2);
|
|
1700
|
+
}
|
|
1701
|
+
throw err;
|
|
1702
|
+
}
|
|
1703
|
+
})();
|
|
1704
|
+
export {
|
|
1705
|
+
handleSignal,
|
|
1706
|
+
handleUncaughtException,
|
|
1707
|
+
handleUnhandledRejection
|
|
1708
|
+
};
|