@agenticcli/shipguard 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,908 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ authCheck,
4
+ clearCredentials,
5
+ databaseCheck,
6
+ deploymentCheck,
7
+ getAuthToken,
8
+ isTokenExpired,
9
+ loadCredentials,
10
+ payments,
11
+ runProRulesWithDispatch,
12
+ saveCredentials,
13
+ secretsCheck
14
+ } from "./chunk-42MA7DQY.js";
15
+
16
+ // src/cli.ts
17
+ import { Command as Command7 } from "commander";
18
+
19
+ // src/commands/init.ts
20
+ import { Command } from "commander";
21
+
22
+ // src/core/policy.ts
23
+ import { readFile, writeFile, mkdir } from "fs/promises";
24
+ import { join, resolve as resolve2 } from "path";
25
+ import YAML from "yaml";
26
+
27
+ // ../shared/dist/constants.js
28
+ var SEVERITY_WEIGHTS = {
29
+ info: 1,
30
+ low: 5,
31
+ medium: 15,
32
+ high: 30,
33
+ critical: 50
34
+ };
35
+ var EXIT_CODES = {
36
+ SAFE: 0,
37
+ BLOCKED: 1,
38
+ CONFIG_ERROR: 2,
39
+ RUNTIME_ERROR: 3
40
+ };
41
+ var DEFAULT_POLICY_PATH = "shipguard.policy.yml";
42
+ var DEFAULT_REPORT_DIR = ".shipguard/reports";
43
+ var DEFAULT_REPORT_FILE = ".shipguard/reports/latest.md";
44
+
45
+ // src/utils/paths.ts
46
+ import { resolve } from "path";
47
+ import { existsSync } from "fs";
48
+ function fileExists(filePath) {
49
+ return existsSync(filePath);
50
+ }
51
+
52
+ // src/core/policy.ts
53
+ var DEFAULT_POLICY = {
54
+ version: 1,
55
+ project: {
56
+ name: "my-app",
57
+ framework: "auto",
58
+ risk_profile: "standard"
59
+ },
60
+ scan: {
61
+ changed_files_only: true,
62
+ generate_report: true
63
+ },
64
+ block: [
65
+ "exposed_env",
66
+ "hardcoded_secret",
67
+ "public_admin_route",
68
+ "auth_route_without_guard",
69
+ "payment_webhook_without_signature_check",
70
+ "destructive_migration",
71
+ "unsafe_deployment_config"
72
+ ],
73
+ warn: [
74
+ "missing_tests_for_changed_code",
75
+ "missing_error_handling",
76
+ "risky_dependency_change",
77
+ "missing_rate_limit",
78
+ "missing_input_validation"
79
+ ],
80
+ ignore: {
81
+ paths: [
82
+ "node_modules/**",
83
+ "dist/**",
84
+ "build/**",
85
+ ".next/**",
86
+ "coverage/**"
87
+ ]
88
+ },
89
+ report: {
90
+ output: ".shipguard/reports/latest.md",
91
+ format: "markdown"
92
+ }
93
+ };
94
+ async function loadPolicy(dir) {
95
+ const policyPath = join(dir, DEFAULT_POLICY_PATH);
96
+ if (!fileExists(policyPath)) {
97
+ return DEFAULT_POLICY;
98
+ }
99
+ try {
100
+ const content = await readFile(policyPath, "utf-8");
101
+ const parsed = YAML.parse(content);
102
+ return { ...DEFAULT_POLICY, ...parsed };
103
+ } catch (error) {
104
+ throw new Error(`Invalid policy file: ${error instanceof Error ? error.message : error}`);
105
+ }
106
+ }
107
+ async function createPolicyFile(dir) {
108
+ const policyPath = join(dir, DEFAULT_POLICY_PATH);
109
+ if (fileExists(policyPath)) {
110
+ return false;
111
+ }
112
+ const yamlContent = YAML.stringify(DEFAULT_POLICY, { indent: 2 });
113
+ await writeFile(policyPath, yamlContent, "utf-8");
114
+ return true;
115
+ }
116
+ async function createShipguardDir(dir) {
117
+ const reportDir = resolve2(dir, DEFAULT_REPORT_DIR);
118
+ await mkdir(reportDir, { recursive: true });
119
+ }
120
+
121
+ // src/utils/logger.ts
122
+ import chalk from "chalk";
123
+ var logger = {
124
+ info: (msg) => console.log(chalk.blue("\u2139"), msg),
125
+ success: (msg) => console.log(chalk.green("\u2713"), msg),
126
+ warn: (msg) => console.log(chalk.yellow("\u26A0"), msg),
127
+ error: (msg) => console.error(chalk.red("\u2717"), msg),
128
+ finding: (severity, msg) => {
129
+ const colors = {
130
+ critical: chalk.bgRed.white,
131
+ high: chalk.red,
132
+ medium: chalk.yellow,
133
+ low: chalk.blue,
134
+ info: chalk.gray
135
+ };
136
+ const colorFn = colors[severity] || chalk.white;
137
+ const label = severity.toUpperCase().padEnd(8);
138
+ console.log(` ${colorFn(label)} ${msg}`);
139
+ },
140
+ score: (score, recommendation) => {
141
+ const color = score <= 20 ? chalk.green : score <= 50 ? chalk.yellow : chalk.red;
142
+ const icon = score <= 20 ? "\u2713" : score <= 50 ? "\u26A0" : "\u2717";
143
+ console.log("");
144
+ console.log(chalk.bold("ShipGuard Scan Result"));
145
+ console.log(`Risk Score: ${color(`${score}/100`)}`);
146
+ console.log(`Status: ${color(`${icon} ${recommendation.replace(/_/g, " ")}`)}`);
147
+ },
148
+ divider: () => console.log(chalk.gray("\u2500".repeat(50)))
149
+ };
150
+
151
+ // src/commands/init.ts
152
+ function initCommand() {
153
+ return new Command("init").description("Initialize ShipGuard in your project").action(async () => {
154
+ try {
155
+ const policyCreated = await createPolicyFile(process.cwd());
156
+ await createShipguardDir(process.cwd());
157
+ if (policyCreated) {
158
+ logger.success("ShipGuard initialized");
159
+ logger.info("Created shipguard.policy.yml");
160
+ logger.info("Run: shipguard scan");
161
+ } else {
162
+ logger.warn("shipguard.policy.yml already exists, skipping");
163
+ logger.info("Run: shipguard scan");
164
+ }
165
+ } catch (error) {
166
+ logger.error(`Init failed: ${error instanceof Error ? error.message : error}`);
167
+ process.exit(3);
168
+ }
169
+ });
170
+ }
171
+
172
+ // src/commands/scan.ts
173
+ import { Command as Command2 } from "commander";
174
+ import { randomUUID } from "crypto";
175
+
176
+ // src/core/scanner.ts
177
+ import { readFile as readFile3 } from "fs/promises";
178
+ import { join as join3 } from "path";
179
+
180
+ // src/core/risk-score.ts
181
+ function computeRiskScore(findings) {
182
+ let rawScore = 0;
183
+ let criticalCount = 0;
184
+ let highCount = 0;
185
+ let mediumCount = 0;
186
+ let lowCount = 0;
187
+ let infoCount = 0;
188
+ let blockingCount = 0;
189
+ for (const finding of findings) {
190
+ rawScore += SEVERITY_WEIGHTS[finding.severity] ?? 0;
191
+ switch (finding.severity) {
192
+ case "critical":
193
+ criticalCount++;
194
+ break;
195
+ case "high":
196
+ highCount++;
197
+ break;
198
+ case "medium":
199
+ mediumCount++;
200
+ break;
201
+ case "low":
202
+ lowCount++;
203
+ break;
204
+ case "info":
205
+ infoCount++;
206
+ break;
207
+ }
208
+ if (finding.blocking) blockingCount++;
209
+ }
210
+ const score = Math.min(100, rawScore);
211
+ let recommendation;
212
+ if (score <= 20) {
213
+ recommendation = "SAFE_TO_SHIP";
214
+ } else if (score < 50) {
215
+ recommendation = "REVIEW_BEFORE_SHIP";
216
+ } else {
217
+ recommendation = "DO_NOT_SHIP";
218
+ }
219
+ return {
220
+ score,
221
+ recommendation,
222
+ totalFindings: findings.length,
223
+ criticalCount,
224
+ highCount,
225
+ mediumCount,
226
+ lowCount,
227
+ infoCount,
228
+ blockingCount
229
+ };
230
+ }
231
+
232
+ // src/core/git.ts
233
+ import { execSync } from "child_process";
234
+ function isGitRepo(dir) {
235
+ try {
236
+ execSync("git rev-parse --is-inside-work-tree", { cwd: dir, stdio: "pipe" });
237
+ return true;
238
+ } catch {
239
+ return false;
240
+ }
241
+ }
242
+ function getChangedFiles(dir) {
243
+ try {
244
+ const diffOutput = execSync("git diff --name-only HEAD 2>/dev/null || git diff --name-only", {
245
+ cwd: dir,
246
+ encoding: "utf-8",
247
+ stdio: ["pipe", "pipe", "pipe"]
248
+ });
249
+ const stagedOutput = execSync("git diff --cached --name-only", {
250
+ cwd: dir,
251
+ encoding: "utf-8",
252
+ stdio: ["pipe", "pipe", "pipe"]
253
+ });
254
+ const untrackedOutput = execSync("git ls-files --others --exclude-standard", {
255
+ cwd: dir,
256
+ encoding: "utf-8",
257
+ stdio: ["pipe", "pipe", "pipe"]
258
+ });
259
+ const allFiles = /* @__PURE__ */ new Set();
260
+ const outputs = [diffOutput, stagedOutput, untrackedOutput];
261
+ for (const output of outputs) {
262
+ output.split("\n").map((f) => f.trim()).filter(Boolean).forEach((f) => allFiles.add(f));
263
+ }
264
+ return [...allFiles];
265
+ } catch {
266
+ return [];
267
+ }
268
+ }
269
+
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
+ // src/core/scanner.ts
311
+ var CHECK_MODULES = [secretsCheck, authCheck, databaseCheck, payments, deploymentCheck];
312
+ var DEFAULT_IGNORE = [
313
+ "node_modules/**",
314
+ "dist/**",
315
+ "build/**",
316
+ ".next/**",
317
+ "coverage/**",
318
+ ".git/**"
319
+ ];
320
+ async function scan(options, proRules) {
321
+ const cwd = process.cwd();
322
+ const policy = await loadPolicy(cwd);
323
+ const ignorePatterns = [...DEFAULT_IGNORE, ...policy.ignore.paths];
324
+ let files;
325
+ if (options.changedOnly && isGitRepo(cwd)) {
326
+ const changedRelPaths = getChangedFiles(cwd);
327
+ const filteredPaths = changedRelPaths.filter(
328
+ (rp) => !DEFAULT_IGNORE.some((pat) => {
329
+ const prefix = pat.replace("/**", "");
330
+ return rp.startsWith(prefix + "/") || rp === prefix;
331
+ })
332
+ );
333
+ files = [];
334
+ for (const relPath of filteredPaths) {
335
+ try {
336
+ const fullPath = join3(cwd, relPath);
337
+ const content = await readFile3(fullPath, "utf-8");
338
+ files.push({ path: fullPath, content, relativePath: relPath });
339
+ } catch {
340
+ }
341
+ }
342
+ } else {
343
+ if (options.changedOnly && !isGitRepo(cwd)) {
344
+ logger.warn("--changed flag set but not a git repository \u2014 scanning all files");
345
+ }
346
+ files = await readFiles(cwd, ["**/*"], ignorePatterns);
347
+ }
348
+ let allFindings = CHECK_MODULES.flatMap((mod) => mod.run(files, policy));
349
+ let coderefDegraded = false;
350
+ if (proRules?.length) {
351
+ const { findings: proFindings, degraded, warnings } = runProRulesWithDispatch(proRules, files, policy);
352
+ allFindings = [...allFindings, ...proFindings];
353
+ coderefDegraded = degraded;
354
+ for (const w of warnings) {
355
+ logger.warn(w);
356
+ }
357
+ }
358
+ const riskScore = computeRiskScore(allFindings);
359
+ const result = {
360
+ findings: allFindings,
361
+ riskScore,
362
+ filesScanned: files.length,
363
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
364
+ policyUsed: policy.project.name,
365
+ // Propagate coderef version-skip degradation — scan.ts:145 will OR-merge with
366
+ // its own degraded flag so this is not clobbered.
367
+ degraded: coderefDegraded || void 0
368
+ };
369
+ return result;
370
+ }
371
+
372
+ // src/core/report.ts
373
+ import { mkdir as mkdir2, writeFile as writeFile2 } from "fs/promises";
374
+ import { dirname } from "path";
375
+ function severitySection(title, findings) {
376
+ if (findings.length === 0) {
377
+ return `## ${title}
378
+
379
+ None
380
+ `;
381
+ }
382
+ const entries = findings.map((f) => {
383
+ const lines = [`### ${f.title}`];
384
+ lines.push(`- **File:** ${f.file}${f.line != null ? `:${f.line}` : ""}`);
385
+ lines.push(`- **Severity:** ${f.severity}`);
386
+ if (f.evidence != null) lines.push(`- **Evidence:** \`${f.evidence}\``);
387
+ lines.push(`- **Explanation:** ${f.explanation}`);
388
+ lines.push(`- **Recommendation:** ${f.recommendation}`);
389
+ return lines.join("\n");
390
+ });
391
+ return `## ${title}
392
+
393
+ ${entries.join("\n\n")}
394
+ `;
395
+ }
396
+ function buildFixOrder(findings) {
397
+ const blocking = findings.filter((f) => f.blocking);
398
+ const nonBlocking = findings.filter((f) => !f.blocking);
399
+ const severityOrder = ["critical", "high", "medium", "low", "info"];
400
+ const sorted = [
401
+ ...blocking.sort((a, b) => severityOrder.indexOf(a.severity) - severityOrder.indexOf(b.severity)),
402
+ ...nonBlocking.sort((a, b) => severityOrder.indexOf(a.severity) - severityOrder.indexOf(b.severity))
403
+ ];
404
+ 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 ? " \u26D4 blocking" : ""}`).join("\n");
406
+ }
407
+ async function generateReport(result, outputPath) {
408
+ const { riskScore, findings, filesScanned, timestamp } = result;
409
+ const critical = findings.filter((f) => f.severity === "critical");
410
+ const high = findings.filter((f) => f.severity === "high");
411
+ const medium = findings.filter((f) => f.severity === "medium");
412
+ const low = findings.filter((f) => f.severity === "low");
413
+ const sections = [
414
+ "# ShipGuard Release Report",
415
+ "",
416
+ "## Summary",
417
+ `- **Status:** ${riskScore.recommendation}`,
418
+ `- **Risk Score:** ${riskScore.score}/100`,
419
+ `- **Files Scanned:** ${filesScanned}`,
420
+ `- **Total Findings:** ${riskScore.totalFindings}`,
421
+ `- **Generated:** ${timestamp}`,
422
+ "",
423
+ severitySection("Critical Findings", critical),
424
+ severitySection("High Findings", high),
425
+ severitySection("Medium Findings", medium),
426
+ severitySection("Low Findings", low),
427
+ "## Suggested Fix Order",
428
+ "",
429
+ buildFixOrder(findings),
430
+ "",
431
+ "## Final Recommendation",
432
+ "",
433
+ `**${riskScore.recommendation}**`,
434
+ ""
435
+ ];
436
+ const content = sections.join("\n");
437
+ await mkdir2(dirname(outputPath), { recursive: true });
438
+ await writeFile2(outputPath, content, "utf-8");
439
+ }
440
+
441
+ // src/core/sarif.ts
442
+ import { createHash } from "crypto";
443
+ var SARIF_SCHEMA = "https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0.json";
444
+ var SARIF_VERSION = "2.1.0";
445
+ var SEVERITY_TO_LEVEL = {
446
+ critical: "error",
447
+ high: "error",
448
+ medium: "warning",
449
+ low: "note",
450
+ info: "note"
451
+ };
452
+ var SEVERITY_TO_SCORE = {
453
+ critical: 9,
454
+ high: 7,
455
+ medium: 5,
456
+ low: 3,
457
+ info: 1
458
+ };
459
+ function fingerprint(finding) {
460
+ const line = finding.line ?? 1;
461
+ return createHash("sha256").update(`${finding.id}:${finding.file}:${line}`).digest("hex");
462
+ }
463
+ function buildRules(findings) {
464
+ const seen = /* @__PURE__ */ new Map();
465
+ for (const f of findings) {
466
+ if (!seen.has(f.id)) {
467
+ seen.set(f.id, f);
468
+ }
469
+ }
470
+ return Array.from(seen.values()).map((f) => {
471
+ const tags = [...f.cwe ?? []];
472
+ return {
473
+ id: f.id,
474
+ shortDescription: { text: f.title },
475
+ fullDescription: { text: f.explanation },
476
+ ...f.fix ? { help: { text: f.fix } } : {},
477
+ properties: {
478
+ tags,
479
+ "security-severity": SEVERITY_TO_SCORE[f.severity]
480
+ }
481
+ };
482
+ });
483
+ }
484
+ function buildResults(findings) {
485
+ return findings.map((f) => {
486
+ const startLine = f.line ?? 1;
487
+ return {
488
+ ruleId: f.id,
489
+ level: SEVERITY_TO_LEVEL[f.severity],
490
+ message: { text: f.explanation },
491
+ locations: [
492
+ {
493
+ physicalLocation: {
494
+ artifactLocation: { uri: f.file },
495
+ region: { startLine }
496
+ }
497
+ }
498
+ ],
499
+ partialFingerprints: {
500
+ primary: fingerprint(f)
501
+ }
502
+ };
503
+ });
504
+ }
505
+ function toSarif(result) {
506
+ const { findings } = result;
507
+ return {
508
+ $schema: SARIF_SCHEMA,
509
+ version: SARIF_VERSION,
510
+ runs: [
511
+ {
512
+ tool: {
513
+ driver: {
514
+ name: "shipguard",
515
+ rules: buildRules(findings)
516
+ }
517
+ },
518
+ results: buildResults(findings)
519
+ }
520
+ ]
521
+ };
522
+ }
523
+
524
+ // src/commands/scan.ts
525
+ function resolveExitCode(opts) {
526
+ if (opts.strict && opts.blockingCount > 0) {
527
+ return EXIT_CODES.BLOCKED;
528
+ }
529
+ if (opts.degraded) {
530
+ return EXIT_CODES.CONFIG_ERROR;
531
+ }
532
+ return EXIT_CODES.SAFE;
533
+ }
534
+ var SEVERITY_ORDER = ["critical", "high", "medium", "low", "info"];
535
+ 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").action(async (opts) => {
537
+ const cwd = process.cwd();
538
+ const scanId = randomUUID();
539
+ let policy;
540
+ try {
541
+ policy = await loadPolicy(cwd);
542
+ } catch (error) {
543
+ logger.error(`Config error: ${error instanceof Error ? error.message : error}`);
544
+ process.exit(EXIT_CODES.CONFIG_ERROR);
545
+ }
546
+ const inGitRepo = isGitRepo(cwd);
547
+ const scanOptions = {
548
+ changedOnly: Boolean(opts.changed),
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();
564
+ }
565
+ let proRules;
566
+ let creditsRemaining;
567
+ let rulesVersion;
568
+ let degraded = false;
569
+ if (opts.pro) {
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;
613
+ }
614
+ }
615
+ if (!machineOutput) {
616
+ logger.info("Scanning files...");
617
+ }
618
+ let result;
619
+ try {
620
+ result = await scan(scanOptions, proRules);
621
+ } catch (error) {
622
+ if (!machineOutput) {
623
+ logger.error(`Scan failed: ${error instanceof Error ? error.message : error}`);
624
+ } else {
625
+ console.log(JSON.stringify({ error: String(error) }));
626
+ }
627
+ process.exit(EXIT_CODES.RUNTIME_ERROR);
628
+ }
629
+ result.recommendation = result.riskScore.recommendation;
630
+ result.schemaVersion = "2";
631
+ result.degraded = degraded || Boolean(result.degraded);
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;
638
+ }
639
+ result.rulesApplied = proRules.length;
640
+ result.rulesBreakdown = breakdown;
641
+ result.aiCodeIssues = result.findings.filter((f) => f.aiCodeTarget).length;
642
+ }
643
+ if (opts.sarif) {
644
+ console.log(JSON.stringify(toSarif(result), null, 2));
645
+ } else if (scanOptions.json) {
646
+ console.log(JSON.stringify(result, null, 2));
647
+ } else {
648
+ const { findings, riskScore } = result;
649
+ if (findings.length === 0) {
650
+ logger.success("No findings detected");
651
+ } else {
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
+ }
662
+ }
663
+ }
664
+ logger.score(riskScore.score, riskScore.recommendation);
665
+ 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
+ }
674
+ const shouldReport = scanOptions.generateReport || policy.scan.generate_report;
675
+ if (shouldReport) {
676
+ const reportPath = scanOptions.reportPath;
677
+ try {
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
+ }
685
+ }
686
+ if (opts.pro && !degraded) {
687
+ fetch(`${opts.apiUrl}/api/telemetry/ingest`, {
688
+ method: "POST",
689
+ headers: { "Content-Type": "application/json" },
690
+ body: JSON.stringify({
691
+ scanId,
692
+ findingsCount: result.findings.length,
693
+ blocked: result.riskScore.blockingCount > 0,
694
+ riskScore: result.riskScore.score,
695
+ recommendation: result.riskScore.recommendation,
696
+ severityBreakdown: {
697
+ critical: result.riskScore.criticalCount,
698
+ high: result.riskScore.highCount,
699
+ medium: result.riskScore.mediumCount,
700
+ low: result.riskScore.lowCount,
701
+ info: result.riskScore.infoCount
702
+ },
703
+ rulesApplied: proRules?.length ?? 0
704
+ })
705
+ }).catch(() => {
706
+ });
707
+ }
708
+ const exitCode = resolveExitCode({
709
+ strict: scanOptions.strict,
710
+ blockingCount: result.riskScore.blockingCount,
711
+ degraded: Boolean(result.degraded)
712
+ });
713
+ if (exitCode === EXIT_CODES.BLOCKED && !machineOutput) {
714
+ logger.warn(`Strict mode: ${result.riskScore.blockingCount} blocking finding(s) \u2014 exiting with code 1`);
715
+ }
716
+ if (exitCode !== EXIT_CODES.SAFE) {
717
+ process.exit(exitCode);
718
+ }
719
+ });
720
+ }
721
+
722
+ // src/commands/login.ts
723
+ import { Command as Command3 } from "commander";
724
+ import { exec } from "child_process";
725
+ var DEFAULT_API_URL = "https://agenticcli.dev";
726
+ function loginCommand() {
727
+ return new Command3("login").description("Authenticate with ShipGuard for pro features").option("--api-url <url>", "API server URL", DEFAULT_API_URL).action(async (opts) => {
728
+ const apiUrl = opts.apiUrl;
729
+ const res = await fetch(`${apiUrl}/api/auth/device`, { method: "POST" });
730
+ if (!res.ok) {
731
+ logger.error("Failed to start auth");
732
+ process.exit(2);
733
+ }
734
+ const { device_code, user_code, verification_uri, expires_in, interval } = await res.json();
735
+ logger.info(`
736
+ Visit: ${verification_uri}`);
737
+ logger.info(`Enter code: ${user_code}
738
+ `);
739
+ const openCmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
740
+ exec(`${openCmd} "${verification_uri}"`, () => {
741
+ });
742
+ const deadline = Date.now() + expires_in * 1e3;
743
+ const pollMs = (interval ?? 5) * 1e3;
744
+ while (Date.now() < deadline) {
745
+ await new Promise((r) => setTimeout(r, pollMs));
746
+ const tokenRes = await fetch(`${apiUrl}/api/auth/device/token`, {
747
+ method: "POST",
748
+ headers: { "Content-Type": "application/json" },
749
+ body: JSON.stringify({ device_code, grant_type: "urn:ietf:params:oauth:grant-type:device_code" })
750
+ });
751
+ const tokenBody = await tokenRes.json();
752
+ if (tokenRes.ok) {
753
+ const { access_token, refresh_token, expires_in: ttl } = tokenBody;
754
+ await saveCredentials({
755
+ accessToken: access_token,
756
+ refreshToken: refresh_token,
757
+ expiresAt: Date.now() + ttl * 1e3,
758
+ apiUrl
759
+ });
760
+ logger.success("Authenticated successfully!");
761
+ return;
762
+ }
763
+ const { error } = tokenBody;
764
+ if (error === "authorization_pending") continue;
765
+ if (error === "slow_down") {
766
+ await new Promise((r) => setTimeout(r, 5e3));
767
+ continue;
768
+ }
769
+ logger.error(`Auth failed: ${error}`);
770
+ process.exit(2);
771
+ }
772
+ logger.error("Auth timed out");
773
+ process.exit(2);
774
+ });
775
+ }
776
+
777
+ // src/commands/logout.ts
778
+ import { Command as Command4 } from "commander";
779
+ function logoutCommand() {
780
+ return new Command4("logout").description("Remove stored credentials").action(async () => {
781
+ clearCredentials();
782
+ logger.info("Logged out.");
783
+ });
784
+ }
785
+
786
+ // src/commands/status.ts
787
+ import { Command as Command5 } from "commander";
788
+ function statusCommand() {
789
+ return new Command5("status").description("Show authentication and account status").action(async () => {
790
+ const creds = loadCredentials();
791
+ if (!creds) {
792
+ logger.info("Not authenticated. Run `shipguard login` to get started.");
793
+ return;
794
+ }
795
+ const expired = isTokenExpired(creds);
796
+ logger.info(`API: ${creds.apiUrl}`);
797
+ logger.info(`Token: ${expired ? "expired" : "valid"} (expires ${new Date(creds.expiresAt).toISOString()})`);
798
+ if (!expired) {
799
+ try {
800
+ const res = await fetch(`${creds.apiUrl}/api/user/me`, {
801
+ headers: { "Authorization": `Bearer ${creds.accessToken}` }
802
+ });
803
+ if (res.ok) {
804
+ const { email, plan, credits } = await res.json();
805
+ logger.info(`Email: ${email}`);
806
+ logger.info(`Plan: ${plan}`);
807
+ logger.info(`Credits: ${credits}`);
808
+ } else {
809
+ logger.warn("Could not fetch account details (server returned non-OK)");
810
+ }
811
+ } catch {
812
+ logger.warn("Could not fetch account details");
813
+ }
814
+ } else {
815
+ logger.warn("Token is expired. Run `shipguard login` to re-authenticate.");
816
+ }
817
+ });
818
+ }
819
+
820
+ // src/commands/feedback.ts
821
+ import { Command as Command6 } from "commander";
822
+ function feedbackCommand() {
823
+ return new Command6("feedback").description("Send feedback about your last scan").argument("<text>", "Your feedback text").action(async (text) => {
824
+ const token = await getAuthToken();
825
+ if (!token) {
826
+ logger.error("Not authenticated. Run `shipguard login` first.");
827
+ return;
828
+ }
829
+ const creds = loadCredentials();
830
+ if (!creds) {
831
+ logger.error("No credentials found. Run `shipguard login` first.");
832
+ return;
833
+ }
834
+ try {
835
+ const res = await fetch(`${creds.apiUrl}/api/feedback`, {
836
+ method: "POST",
837
+ headers: {
838
+ "Authorization": `Bearer ${token}`,
839
+ "Content-Type": "application/json"
840
+ },
841
+ body: JSON.stringify({ freeText: text })
842
+ });
843
+ if (!res.ok) {
844
+ logger.error(`Feedback submission failed: ${res.statusText}`);
845
+ return;
846
+ }
847
+ logger.success("Feedback submitted \u2014 thank you!");
848
+ } catch (err) {
849
+ logger.error(`Failed to send feedback: ${err instanceof Error ? err.message : String(err)}`);
850
+ }
851
+ });
852
+ }
853
+ function rateCommand() {
854
+ return new Command6("rate").description("Rate a finding from your last scan").argument("<findingNumber>", "Finding number from scan output").argument("<rating>", 'Rating: "helpful" or "not-helpful"').action(async (findingNumber, rating) => {
855
+ const num = parseInt(findingNumber, 10);
856
+ if (isNaN(num) || num < 1) {
857
+ logger.error("Finding number must be a positive integer.");
858
+ return;
859
+ }
860
+ const ratingValue = rating === "helpful" ? 1 : rating === "not-helpful" ? -1 : null;
861
+ if (ratingValue === null) {
862
+ logger.error('Rating must be "helpful" or "not-helpful".');
863
+ return;
864
+ }
865
+ const token = await getAuthToken();
866
+ if (!token) {
867
+ logger.error("Not authenticated. Run `shipguard login` first.");
868
+ return;
869
+ }
870
+ const creds = loadCredentials();
871
+ if (!creds) {
872
+ logger.error("No credentials found. Run `shipguard login` first.");
873
+ return;
874
+ }
875
+ try {
876
+ const res = await fetch(`${creds.apiUrl}/api/feedback`, {
877
+ method: "POST",
878
+ headers: {
879
+ "Authorization": `Bearer ${token}`,
880
+ "Content-Type": "application/json"
881
+ },
882
+ body: JSON.stringify({
883
+ findingIndex: num - 1,
884
+ rating: ratingValue
885
+ })
886
+ });
887
+ if (!res.ok) {
888
+ logger.error(`Rating submission failed: ${res.statusText}`);
889
+ return;
890
+ }
891
+ logger.success(`Finding #${num} rated as ${rating}`);
892
+ } catch (err) {
893
+ logger.error(`Failed to send rating: ${err instanceof Error ? err.message : String(err)}`);
894
+ }
895
+ });
896
+ }
897
+
898
+ // src/cli.ts
899
+ var program = new Command7();
900
+ program.name("shipguard").description("CLI-first release gate for AI-built apps").version("0.1.0");
901
+ program.addCommand(initCommand());
902
+ program.addCommand(scanCommand());
903
+ program.addCommand(loginCommand());
904
+ program.addCommand(logoutCommand());
905
+ program.addCommand(statusCommand());
906
+ program.addCommand(feedbackCommand());
907
+ program.addCommand(rateCommand());
908
+ program.parseAsync(process.argv);