@agenticcli/shipguard 0.5.1 → 0.7.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 CHANGED
@@ -8,30 +8,36 @@ import {
8
8
  deploymentCheck,
9
9
  deriveBlocking,
10
10
  getAuthToken,
11
+ getFindingKey,
12
+ isLineSuppressed,
11
13
  isTokenExpired,
12
14
  loadChecksumManifest,
13
15
  loadCredentials,
14
16
  logger,
15
17
  payments,
18
+ redactFindingsEvidence,
19
+ runProRules,
16
20
  runProRulesWithDispatch,
17
21
  saveCredentials,
18
- secretsCheck
19
- } from "./chunk-R2U4UQXN.js";
22
+ secretsCheck,
23
+ validateBundleCompile
24
+ } from "./chunk-BVWCA2VJ.js";
20
25
  import {
21
26
  DEFAULT_MAX_FILES,
22
27
  DEFAULT_MAX_FILE_SIZE_BYTES,
23
28
  DEFAULT_MAX_TOTAL_BYTES,
29
+ compareScanPaths,
24
30
  readFiles
25
- } from "./chunk-QUBEIHTH.js";
31
+ } from "./chunk-3NSULPWH.js";
26
32
  import {
27
33
  decodeUtf8Strict,
28
34
  detectBinary,
29
35
  normalizeNewlines,
30
36
  stripBom
31
- } from "./chunk-5T42QTNT.js";
37
+ } from "./chunk-MPQ42F54.js";
32
38
 
33
39
  // src/cli.ts
34
- import { Command as Command8, CommanderError } from "commander";
40
+ import { Command as Command11, CommanderError } from "commander";
35
41
 
36
42
  // src/commands/init.ts
37
43
  import { Command } from "commander";
@@ -174,12 +180,34 @@ function initCommand() {
174
180
 
175
181
  // src/commands/scan.ts
176
182
  import { Command as Command2 } from "commander";
177
- import { existsSync as existsSync5 } from "fs";
178
- import { join as join6, resolve as resolve4 } from "path";
183
+ import { existsSync as existsSync6 } from "fs";
184
+ import { join as join7, resolve as resolve4 } from "path";
179
185
 
180
186
  // src/core/scanner.ts
181
187
  import { readFile as readFile2, stat, realpath } from "fs/promises";
182
- import { join as join2 } from "path";
188
+ import { sha256 } from "@noble/hashes/sha2.js";
189
+ import { dirname as dirname2, join as join3 } from "path";
190
+
191
+ // src/core/verdict.ts
192
+ function computeVerdict(input) {
193
+ if (input.degraded === true) return "DO_NOT_SHIP";
194
+ const score = input.riskScore.score;
195
+ if (score <= 20) return "SAFE_TO_SHIP";
196
+ if (score < 50) return "REVIEW_BEFORE_SHIP";
197
+ return "DO_NOT_SHIP";
198
+ }
199
+ function applyVerdict(result) {
200
+ const verdict = computeVerdict({
201
+ riskScore: result.riskScore,
202
+ degraded: result.degraded
203
+ });
204
+ result.recommendation = verdict;
205
+ result.riskScore.recommendation = verdict;
206
+ return result;
207
+ }
208
+ function effectiveRecommendation(result) {
209
+ return result.recommendation ?? result.riskScore.recommendation;
210
+ }
183
211
 
184
212
  // src/core/risk-score.ts
185
213
  function computeRiskScore(findings) {
@@ -191,6 +219,7 @@ function computeRiskScore(findings) {
191
219
  let infoCount = 0;
192
220
  let blockingCount = 0;
193
221
  for (const finding of findings) {
222
+ if (finding.suppressed === true) continue;
194
223
  rawScore += SEVERITY_WEIGHTS[finding.severity] ?? 0;
195
224
  switch (finding.severity) {
196
225
  case "critical":
@@ -212,14 +241,10 @@ function computeRiskScore(findings) {
212
241
  if (finding.blocking) blockingCount++;
213
242
  }
214
243
  const score = Math.min(100, rawScore);
215
- let recommendation;
216
- if (score <= 20) {
217
- recommendation = "SAFE_TO_SHIP";
218
- } else if (score < 50) {
219
- recommendation = "REVIEW_BEFORE_SHIP";
220
- } else {
221
- recommendation = "DO_NOT_SHIP";
222
- }
244
+ const recommendation = computeVerdict({
245
+ riskScore: { score },
246
+ degraded: false
247
+ });
223
248
  return {
224
249
  score,
225
250
  recommendation,
@@ -233,6 +258,174 @@ function computeRiskScore(findings) {
233
258
  };
234
259
  }
235
260
 
261
+ // src/core/report.ts
262
+ import { mkdir as mkdir2, rename, writeFile as writeFile2 } from "fs/promises";
263
+ import { dirname, basename, join as join2 } from "path";
264
+ import { randomUUID } from "crypto";
265
+ function severitySection(title, findings) {
266
+ if (findings.length === 0) {
267
+ return `## ${title}
268
+
269
+ None
270
+ `;
271
+ }
272
+ const entries = findings.map((f) => {
273
+ const lines = [`### ${f.title}`];
274
+ lines.push(`- **File:** ${f.file}${f.line != null ? `:${f.line}` : ""}`);
275
+ lines.push(`- **Severity:** ${f.severity}`);
276
+ if (f.evidence != null) lines.push(`- **Evidence:** \`${f.evidence}\``);
277
+ lines.push(`- **Explanation:** ${f.explanation}`);
278
+ lines.push(`- **Recommendation:** ${f.recommendation}`);
279
+ return lines.join("\n");
280
+ });
281
+ return `## ${title}
282
+
283
+ ${entries.join("\n\n")}
284
+ `;
285
+ }
286
+ function buildFixOrder(findings) {
287
+ const blocking = findings.filter((f) => f.blocking);
288
+ const nonBlocking = findings.filter((f) => !f.blocking);
289
+ const severityOrder = ["critical", "high", "medium", "low", "info"];
290
+ const sorted = [
291
+ ...blocking.sort((a, b) => severityOrder.indexOf(a.severity) - severityOrder.indexOf(b.severity)),
292
+ ...nonBlocking.sort((a, b) => severityOrder.indexOf(a.severity) - severityOrder.indexOf(b.severity))
293
+ ];
294
+ if (sorted.length === 0) return "No findings to address.\n";
295
+ 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");
296
+ }
297
+ function attitudeLine(recommendation, degraded) {
298
+ if (degraded) return "INCOMPLETE \u2014 parts of this scan did not run, so it cannot say this is safe.";
299
+ if (recommendation === "SAFE_TO_SHIP") return "SHIP IT \u2014 nothing blocking. Go make something people want.";
300
+ if (recommendation === "DO_NOT_SHIP") return "BLOCKED \u2014 shipping this would hurt. Fix the criticals first.";
301
+ return `HOLD UP \u2014 findings need eyes before this ships.`;
302
+ }
303
+ function topThreeFindings(findings) {
304
+ const severityOrder = ["critical", "high", "medium", "low", "info"];
305
+ const sorted = [...findings].sort((a, b) => {
306
+ if (a.blocking !== b.blocking) return a.blocking ? -1 : 1;
307
+ return severityOrder.indexOf(a.severity) - severityOrder.indexOf(b.severity);
308
+ });
309
+ const top = sorted.slice(0, 3);
310
+ if (top.length === 0) return "None \u2014 clean scan.\n";
311
+ return top.map((f, i) => `${i + 1}. **${f.title}** (${f.severity}) \u2014 ${f.file}${f.line != null ? `:${f.line}` : ""}`).join("\n");
312
+ }
313
+ function severityBreakdownTable(riskScore) {
314
+ const rows = [
315
+ ["Critical", riskScore.criticalCount],
316
+ ["High", riskScore.highCount],
317
+ ["Medium", riskScore.mediumCount],
318
+ ["Low", riskScore.lowCount],
319
+ ["Info", riskScore.infoCount]
320
+ ];
321
+ const lines = ["| Severity | Count |", "|----------|-------|"];
322
+ for (const [label, count] of rows) {
323
+ lines.push(`| ${label} | ${count} |`);
324
+ }
325
+ return lines.join("\n");
326
+ }
327
+ function buildUserMarkdown(result, elapsedMs) {
328
+ const { riskScore, findings, filesScanned, timestamp } = result;
329
+ const rec = effectiveRecommendation(result);
330
+ const degraded = result.degraded === true;
331
+ const elapsedStr = elapsedMs != null ? elapsedMs < 1e3 ? `${elapsedMs}ms` : `${(elapsedMs / 1e3).toFixed(1)}s` : "N/A";
332
+ const critical = findings.filter((f) => f.severity === "critical");
333
+ const high = findings.filter((f) => f.severity === "high");
334
+ const medium = findings.filter((f) => f.severity === "medium");
335
+ const low = findings.filter((f) => f.severity === "low");
336
+ const sections = [
337
+ "# ShipGuard Release Report",
338
+ "",
339
+ "## SUMMARY",
340
+ "",
341
+ `**Verdict:** ${rec} \u2014 ${attitudeLine(rec, degraded)}`,
342
+ "",
343
+ `**Files scanned:** ${filesScanned} | **Elapsed:** ${elapsedStr} | **Generated:** ${timestamp}`,
344
+ "",
345
+ ...degraded ? [
346
+ "### Why this scan is incomplete",
347
+ "",
348
+ ...(result.degradedReasons ?? []).length > 0 ? (result.degradedReasons ?? []).map((r) => `- \`${r.code}\`${r.detail ? ` \u2014 ${r.detail}` : ""}`) : ["- Reason not recorded \u2014 see `degraded` in the JSON report."],
349
+ ""
350
+ ] : [],
351
+ "### Severity Breakdown",
352
+ "",
353
+ severityBreakdownTable(riskScore),
354
+ "",
355
+ `**Risk Score:** ${riskScore.score}/100 | **Total Findings:** ${riskScore.totalFindings}`,
356
+ "",
357
+ "### Top 3 Things to Fix",
358
+ "",
359
+ topThreeFindings(findings),
360
+ "",
361
+ "---",
362
+ "",
363
+ severitySection("Critical Findings", critical),
364
+ severitySection("High Findings", high),
365
+ severitySection("Medium Findings", medium),
366
+ severitySection("Low Findings", low),
367
+ "## Suggested Fix Order",
368
+ "",
369
+ buildFixOrder(findings),
370
+ "",
371
+ "## Final Recommendation",
372
+ "",
373
+ `**${rec}**`,
374
+ ""
375
+ ];
376
+ return sections.join("\n");
377
+ }
378
+ function buildAgentJson(result) {
379
+ const publicResult = { ...result };
380
+ delete publicResult._skippedTooLarge;
381
+ delete publicResult._skippedBinary;
382
+ delete publicResult._truncated;
383
+ return JSON.stringify(publicResult, null, 2);
384
+ }
385
+ var RUNS_SUBDIR = "runs";
386
+ async function writeAtomic(path, content) {
387
+ const tmp = `${path}.${process.pid}.${randomUUID().slice(0, 8)}.tmp`;
388
+ await writeFile2(tmp, content, "utf-8");
389
+ await rename(tmp, path);
390
+ }
391
+ async function generateReport(result, outputPath, elapsedMs) {
392
+ const dir = dirname(outputPath);
393
+ const base = basename(outputPath, ".md");
394
+ const jsonPath = join2(dir, `${base}.json`);
395
+ const runId = sanitizeRunId(result.runId) ?? `run-${Date.now()}`;
396
+ const runMdName = join2(RUNS_SUBDIR, `${runId}.md`);
397
+ const runJsonName = join2(RUNS_SUBDIR, `${runId}.json`);
398
+ const runMdPath = join2(dir, runMdName);
399
+ const runJsonPath = join2(dir, runJsonName);
400
+ const mdContent = buildUserMarkdown(result, elapsedMs);
401
+ const jsonContent = buildAgentJson(result);
402
+ const pointer = {
403
+ pointer: true,
404
+ pointerVersion: 1,
405
+ runId,
406
+ timestamp: result.timestamp,
407
+ recommendation: effectiveRecommendation(result),
408
+ runJson: runJsonName,
409
+ runMarkdown: runMdName
410
+ };
411
+ await mkdir2(dir, { recursive: true });
412
+ await mkdir2(join2(dir, RUNS_SUBDIR), { recursive: true });
413
+ await Promise.all([
414
+ writeAtomic(runMdPath, mdContent),
415
+ writeAtomic(runJsonPath, jsonContent)
416
+ ]);
417
+ await Promise.all([
418
+ writeAtomic(outputPath, mdContent),
419
+ writeAtomic(jsonPath, JSON.stringify(pointer, null, 2) + "\n")
420
+ ]);
421
+ return { mdPath: outputPath, jsonPath, runMdPath, runJsonPath };
422
+ }
423
+ function sanitizeRunId(runId) {
424
+ if (!runId) return void 0;
425
+ const safe = runId.replace(/[^A-Za-z0-9._-]/g, "");
426
+ return safe.length > 0 && safe !== "." && safe !== ".." ? safe.slice(0, 96) : void 0;
427
+ }
428
+
236
429
  // src/core/git.ts
237
430
  import { execFileSync } from "child_process";
238
431
  function isGitRepo(dir) {
@@ -287,6 +480,1653 @@ function getChangedFiles(dir) {
287
480
  return [...allFiles];
288
481
  }
289
482
 
483
+ // rules/free-bundle.json
484
+ var free_bundle_default = {
485
+ schemaVersion: 1,
486
+ description: "Offline free rule bundle compiled from rule-corpus/*/rule.yaml where bundleEligible=true and enabled=true. Governed by rules.md \xA74/\xA75/\xA79. Generated by scripts/build-free-bundle.ts \u2014 never hand-edited.",
487
+ corpusVersion: 18,
488
+ corpusHash: "sha256:6762d562afaa997b54e3cfdc7169a749e40b48e7680d1dd7f796358dda735cfe",
489
+ ruleCount: 30,
490
+ contentHash: "sha256:fce96295cc50f6345ad4ddee6745710ba1671156b8e04702ef21793427d399cb",
491
+ rules: [
492
+ {
493
+ id: "generic.auth.jwt-none-algorithm",
494
+ framework: [
495
+ "generic"
496
+ ],
497
+ category: "auth",
498
+ tier: "free",
499
+ severity: "critical",
500
+ confidence: "HIGH",
501
+ action: "block",
502
+ version: 3,
503
+ status: "experimental",
504
+ cwe: [
505
+ "CWE-347"
506
+ ],
507
+ owasp: [
508
+ "A02:2021"
509
+ ],
510
+ matcher: {
511
+ type: "pattern",
512
+ fileGlob: "**/*.{ts,js,tsx,jsx}",
513
+ patterns: [
514
+ `algorithm[s]?\\s*[=:]\\s*['"]none['"]`,
515
+ `algorithms\\s*[=:]\\s*\\[['"]\\s*none\\s*['"]`,
516
+ `algorithms\\s*[=:]\\s*\\[\\s*['"]\\w{2,10}['"]\\s*,\\s*['"]none['"]`,
517
+ `verify\\s*\\([^)]{0,40},\\s*['"]['"]\\s*[,)]`
518
+ ],
519
+ antiPatterns: [
520
+ "test|spec|\\.mock\\.",
521
+ "//\\s*disable"
522
+ ],
523
+ flags: "i",
524
+ antiPatternScope: {
525
+ lines: 3
526
+ }
527
+ },
528
+ explanation: 'JWT verification accepts the "none" algorithm, allowing attackers to forge tokens by stripping the signature. This is a critical authentication bypass.',
529
+ recommendation: 'Explicitly allowlist accepted algorithms (e.g., ["HS256", "RS256"]) when calling jwt.verify(). Never accept an empty string or array as a valid secret.',
530
+ fix: 'Pass `algorithms: ["HS256"]` to `jwt.verify()` and never accept an empty secret.',
531
+ findingType: "vulnerability",
532
+ aiCodeTarget: true
533
+ },
534
+ {
535
+ id: "generic.config.debug-endpoint-env-dump",
536
+ framework: [
537
+ "generic"
538
+ ],
539
+ category: "config",
540
+ tier: "free",
541
+ severity: "critical",
542
+ confidence: "HIGH",
543
+ action: "block",
544
+ version: 1,
545
+ status: "experimental",
546
+ cwe: [
547
+ "CWE-215",
548
+ "CWE-200"
549
+ ],
550
+ owasp: [
551
+ "A05:2021"
552
+ ],
553
+ matcher: {
554
+ type: "pattern",
555
+ fileGlob: "**/*.{ts,js,tsx,jsx,mjs,cjs,py}",
556
+ patterns: [
557
+ "res\\.(?:json|send|write|end)\\([^\\n;)]{0,30}process\\.env[^.\\w]",
558
+ "Response\\.json\\([^\\n;)]{0,30}process\\.env[^.\\w]",
559
+ "jsonify\\([^\\n;)]{0,16}os\\.environ[^.\\w]",
560
+ "return[ \\t]dict\\(os\\.environ\\)"
561
+ ],
562
+ antiPatterns: [
563
+ "\\.test\\.|\\bspec\\b|__tests__|__fixtures__|__mocks__",
564
+ "eslint-disable|shipguard-ignore"
565
+ ],
566
+ flags: ""
567
+ },
568
+ explanation: 'An HTTP handler returns the whole environment object (process.env / os.environ) in its response body. Every secret the process holds \u2014 API keys, database URLs, signing keys, cloud credentials \u2014 is handed to anyone who can reach the route. This is the classic "one quick debug endpoint to inspect config" that an AI coding agent adds mid-session and nobody removes; it needs no authentication bypass and no exploit, only the URL. Unlike a debug FLAG left on, this is a live exfiltration sink in the response body itself.',
569
+ recommendation: "Delete the endpoint. If you genuinely need runtime introspection, return a hand-picked allowlist of non-secret keys (for example only NODE_ENV and a build id), never the environment object, and put the route behind an authentication and authorization check.",
570
+ fix: "Remove the endpoint, or replace `process.env` with an explicit allowlist such as `{ nodeEnv: process.env.NODE_ENV }`.",
571
+ findingType: "vulnerability",
572
+ aiCodeTarget: true,
573
+ references: [
574
+ "https://cwe.mitre.org/data/definitions/215.html",
575
+ "https://cwe.mitre.org/data/definitions/200.html"
576
+ ]
577
+ },
578
+ {
579
+ id: "generic.config.debug-mode-enabled",
580
+ framework: [
581
+ "generic"
582
+ ],
583
+ category: "config",
584
+ tier: "free",
585
+ severity: "medium",
586
+ confidence: "MEDIUM",
587
+ action: "warn",
588
+ version: 3,
589
+ status: "experimental",
590
+ cwe: [
591
+ "CWE-489",
592
+ "CWE-215"
593
+ ],
594
+ owasp: [
595
+ "A05:2021"
596
+ ],
597
+ matcher: {
598
+ type: "pattern",
599
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,rb,php,go,env,yaml,yml,conf,ini,toml,json}",
600
+ patterns: [
601
+ `DEBUG\\s*=\\s*(True|true|1|"true"|'true')`,
602
+ "debug\\s*:\\s*true",
603
+ "FLASK_DEBUG\\s*=\\s*1",
604
+ "display_errors\\s*=\\s*On"
605
+ ],
606
+ antiPatterns: [
607
+ "\\.env\\.development|\\.env\\.local|\\.env\\.test|test_settings|dev\\.config",
608
+ "\\.test\\.|\\bspec\\b|__tests__|__fixtures__",
609
+ "dev only|development only"
610
+ ],
611
+ flags: "i"
612
+ },
613
+ explanation: "Debug mode is enabled in application configuration. Debug mode typically enables verbose error pages with stack traces, environment details, and internal paths visible to end users. This information aids attackers in understanding the application internals and finding exploitable weaknesses.",
614
+ recommendation: "Set DEBUG=False (or equivalent) for production deployments. Use environment variables to control debug settings so they differ between development and production. Ensure production config files never contain debug=true.",
615
+ fix: "Set `DEBUG=False` in production config. Use `NODE_ENV=production` to disable debug output automatically.",
616
+ findingType: "vulnerability",
617
+ aiCodeTarget: true,
618
+ references: [
619
+ "https://cwe.mitre.org/data/definitions/489.html",
620
+ "https://cwe.mitre.org/data/definitions/215.html"
621
+ ]
622
+ },
623
+ {
624
+ id: "generic.cors.reflected-origin",
625
+ framework: [
626
+ "generic"
627
+ ],
628
+ category: "deployment",
629
+ tier: "free",
630
+ severity: "high",
631
+ confidence: "MEDIUM",
632
+ action: "warn",
633
+ version: 4,
634
+ status: "experimental",
635
+ cwe: [
636
+ "CWE-942",
637
+ "CWE-346"
638
+ ],
639
+ owasp: [
640
+ "A05:2021"
641
+ ],
642
+ matcher: {
643
+ type: "pattern",
644
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,go}",
645
+ patterns: [
646
+ `Access-Control-Allow-Origin[^\\n]{0,40}req\\.(headers|get)\\s*\\(\\s*['"]origin['"]`,
647
+ `setHeader\\s*\\(\\s*['"]Access-Control-Allow-Origin['"]\\s*,[^\\n]{0,60}origin`,
648
+ `res\\.header\\s*\\(\\s*['"]Access-Control-Allow-Origin['"]\\s*,[^\\n]{0,60}req\\.headers\\.origin`,
649
+ `response\\.setHeader\\s*\\(\\s*['"]Access-Control-Allow-Origin['"]\\s*,[^\\n]{0,60}request\\.headers`
650
+ ],
651
+ antiPatterns: [
652
+ "\\btest\\b|\\bspec\\b|__tests__|__fixtures__",
653
+ "allowedOrigins|allowList|whitelist|validOrigins",
654
+ "includes\\s*\\(|indexOf\\s*\\(|has\\s*\\(|===|\\.test\\s*\\(|switch\\s*\\("
655
+ ],
656
+ flags: "",
657
+ antiPatternScope: "block"
658
+ },
659
+ explanation: 'The server reflects the incoming Origin request header back into Access-Control-Allow-Origin without validating it against an allowlist. This is more dangerous than a static wildcard: any attacker-controlled origin can read authenticated API responses. CVE-2024-25124 (CVSS 9.8) in the Fiber Go framework exploited exactly this pattern, granting any origin full credentialed access to protected endpoints (CWE-942, CWE-346).\nv4 (task #27 triage, rule-corpus/triage/2026-07-15-absence-block-candidates.md #5): downgraded HIGH/block -> MEDIUM/warn. FOUNDER-FYI: this rule ships in the offline FREE/bundled tier (tier: free, bundleEligible: true), so this downgrade reaches every CLI user, logged in or not \u2014 a wider blast radius than the Pro-only rules in this same wave. The sink itself is precise (reflecting req.headers.origin into Access-Control-Allow-Origin IS the specific dangerous act, not an over-broad capture) \u2014 the false positives come from the antiPattern vocabulary being too narrow: origin validation written as `const allowed = origin === \'https://example.com\'; if (allowed) ...` (variable named "allowed", comparison via ===, not includes()/allowList) or `/^https:\\/\\/(www\\.)?example\\.com$/.test(req.headers.origin)` (.test(), not in the antiPattern vocabulary either) are both common, correct validation idioms this rule\'s fixed vocabulary did not recognize. Expanded the antiPattern vocabulary to also cover ===, .test(, and switch( as a complementary fix, and downgraded to warn because the underlying gap (an unbounded set of ways to write "compare against an allowlist") cannot be fully enumerated by any fixed vocabulary \u2014 per rule-corpus/rule-logic.md Section 4, a rule with a residual absence-style blind spot is capped at warn, never block, regardless of confidence.',
660
+ recommendation: "Validate the incoming Origin header against a server-side allowlist before reflecting it. Store allowed origins in an environment variable (ALLOWED_ORIGINS) and check membership before setting Access-Control-Allow-Origin. Never reflect req.headers.origin directly.",
661
+ fix: "const allowed = (process.env.ALLOWED_ORIGINS || '').split(','); if (allowed.includes(req.headers.origin)) res.setHeader('Access-Control-Allow-Origin', req.headers.origin);",
662
+ findingType: "vulnerability",
663
+ aiCodeTarget: true,
664
+ references: [
665
+ "https://nvd.nist.gov/vuln/detail/CVE-2024-25124",
666
+ "https://cwe.mitre.org/data/definitions/942.html",
667
+ "https://cwe.mitre.org/data/definitions/346.html"
668
+ ]
669
+ },
670
+ {
671
+ id: "generic.cors.wildcard-origin",
672
+ framework: [
673
+ "generic"
674
+ ],
675
+ category: "deployment",
676
+ tier: "free",
677
+ severity: "high",
678
+ confidence: "MEDIUM",
679
+ action: "warn",
680
+ version: 5,
681
+ status: "experimental",
682
+ cwe: [
683
+ "CWE-942",
684
+ "CWE-346"
685
+ ],
686
+ owasp: [
687
+ "A05:2021"
688
+ ],
689
+ matcher: {
690
+ type: "pattern",
691
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,go,rb,java,yaml,yml,conf,json,jsonc,json5}",
692
+ patterns: [
693
+ `Access-Control-Allow-Origin['",:\\s]+[*]`,
694
+ `(setHeader|header|res\\.set)\\s*\\(\\s*['"]Access-Control-Allow-Origin['"]\\s*,\\s*['"][*]['"]`,
695
+ `cors\\s*\\(\\s*\\{\\s*origin\\s*:\\s*['"][*]['"]`,
696
+ `allow_origins\\s*=\\s*\\[\\s*['"][*]['"]`,
697
+ `Access-Control-Allow-Origin['"]\\s{0,40},\\s{0,40}['"]?value['"]?\\s{0,40}:\\s{0,40}['"]\\*['"]`,
698
+ `['"]?value['"]?\\s{0,40}:\\s{0,40}['"]\\*['"]\\s{0,40},\\s{0,40}['"]?key['"]?\\s{0,40}:\\s{0,40}['"]Access-Control-Allow-Origin['"]`,
699
+ `\\b(?:cors|enableCors)\\s{0,10}\\(\\s{0,10}\\{[^{}(]{0,200}\\borigin['"]?\\s{0,10}:\\s{0,10}(?:true\\b|\\[[^\\[\\]]{0,100}['"]\\*['"])`,
700
+ `\\b[cC]ors(?:Options?|Config|Opts?)?['"]?\\s{0,10}[:=]\\s{0,10}\\{[^{}(]{0,120}\\borigin['"]?\\s{0,10}:\\s{0,10}(?:true\\b|\\[[^\\[\\]]{0,100}['"]\\*['"])`,
701
+ `\\bregister\\s{0,10}\\(\\s{0,10}(?:cors|fastifyCors|require\\s{0,10}\\(\\s{0,10}['"]@fastify/cors['"]\\s{0,10}\\))\\s{0,10},\\s{0,10}\\{[^{}(]{0,200}\\borigin['"]?\\s{0,10}:\\s{0,10}(?:true\\b|\\[[^\\[\\]]{0,100}['"]\\*['"])`,
702
+ `\\b(?:[Aa]llow[Oo]rigin|Cors)['"]?\\s{0,10}:\\s{0,10}['"]{1,2}\\*['"]{1,2}`,
703
+ `\\b[Aa]llow[Oo]rigins['"]?\\s{0,20}:\\s{0,20}(?:\\[[^\\[\\]]{0,200}['"]\\*['"]|-\\s{0,10}['"]\\*['"])`
704
+ ],
705
+ antiPatterns: [
706
+ "\\btest\\b|\\bspec\\b|__fixtures__|__tests__",
707
+ "static|assets|cdn|fonts|images|public-api|intentional-wildcard",
708
+ "\\.(?:woff2?|ttf|otf|eot)\\b|font\\.css",
709
+ '[:,\\[]\\s{0,10}"[^"\\n]{0,300}[\\s(](?:Access-Control-Allow-Origin|[cC]ors[({:=]|[Aa]llow[Oo]rigins?:|origin:)',
710
+ ':\\s{0,10}"(?:Access-Control-Allow-Origin\\s{0,3}:|[cC]ors\\w{0,20}\\s{0,3}[({])'
711
+ ],
712
+ flags: ""
713
+ },
714
+ explanation: "A wildcard CORS origin (Access-Control-Allow-Origin: *) was detected. For API endpoints returning user data, this allows any origin on the internet to read responses. Combined with credentials: 'include', wildcard origins are rejected by browsers \u2014 but without credentials, sensitive data is still exposed to cross-origin requests from attacker-controlled pages.\nv4 (founder ruling 2026-08-08, batch item 11): upgraded MEDIUM -> HIGH. This closes a severity disagreement the CLI's own dedup logic had been surfacing since it shipped (packages/cli/src/core/legacy-corpus-map.ts, `dedupeLegacyAgainstCorpus` doc comment): the legacy hand-written deployment check already rates the same wildcard-CORS defect `high` (packages/cli/src/checks/deployment.ts, `deployment_cors_wildcard` / `deployment_config_cors_wildcard_origin`) and dedup kept both findings because it can never silently soften a report. Canonical ruling: CORS misconfiguration is HIGH severity \u2014 nothing about the detection pattern, confidence, or action (warn) changed, only the severity label.\nv5 (2026-09-30): detection widened to setups v4 missed. The rule now also covers JSON/JSONC/JSON5 files and these shapes: a cors middleware or option object whose origin is true (reflects every requesting origin, so credentialed requests from any site succeed) or is a list containing the wildcard; key/value header entries such as the Vercel vercel.json and Firebase Hosting firebase.json headers arrays; and AWS API Gateway (SAM AllowOrigin, HTTP API AllowOrigins, method response header parameters). Severity, confidence, action (warn) and tier are unchanged. False-positive guards: origin true is matched only inside cors()/enableCors()/register(cors) calls or cors option objects, never on a bare origin key; JSON string values that merely describe the header are ignored; font-file rules and the existing test/static markers still suppress.",
715
+ recommendation: "Replace the wildcard with an explicit allowlist of trusted origins. Use environment variables for origin configuration (ALLOWED_ORIGINS) so production and development settings can differ. Audit whether this endpoint requires CORS at all.",
716
+ fix: "Replace `'*'` with `process.env.ALLOWED_ORIGIN` and validate against an allowlist.",
717
+ findingType: "vulnerability",
718
+ aiCodeTarget: true,
719
+ references: [
720
+ "https://cwe.mitre.org/data/definitions/942.html",
721
+ "https://cwe.mitre.org/data/definitions/346.html",
722
+ "https://github.com/expressjs/cors#configuration-options",
723
+ "https://github.com/fastify/fastify-cors#options",
724
+ "https://vercel.com/docs/project-configuration",
725
+ "https://firebase.google.com/docs/hosting/full-config#headers",
726
+ "https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-property-api-corsconfiguration.html",
727
+ "https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-cors.html",
728
+ "https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html",
729
+ "https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Allow-Origin"
730
+ ]
731
+ },
732
+ {
733
+ id: "generic.crypto.aes-ecb-mode",
734
+ framework: [
735
+ "generic"
736
+ ],
737
+ category: "crypto",
738
+ tier: "free",
739
+ severity: "high",
740
+ confidence: "HIGH",
741
+ action: "block",
742
+ version: 3,
743
+ status: "experimental",
744
+ cwe: [
745
+ "CWE-327"
746
+ ],
747
+ owasp: [
748
+ "A02:2021"
749
+ ],
750
+ matcher: {
751
+ type: "pattern",
752
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,java,go,rb,cs}",
753
+ patterns: [
754
+ "AES[-/]ECB",
755
+ `createCipheriv\\s*\\(\\s*['"]aes-[0-9]+-ecb['"]`,
756
+ `Cipher\\.getInstance\\s*\\(\\s*['"]AES/ECB`,
757
+ "AES\\.new\\s*\\([^,)]{0,60},\\s*AES\\.MODE_ECB"
758
+ ],
759
+ antiPatterns: [
760
+ "\\btest\\b|\\bspec\\b|__fixtures__|__tests__",
761
+ "nosec|eslint-disable"
762
+ ],
763
+ flags: "i",
764
+ antiPatternScope: "statement",
765
+ boundary: "token"
766
+ },
767
+ explanation: "AES encryption in ECB (Electronic Code Book) mode was detected. ECB mode encrypts each block independently \u2014 identical plaintext blocks produce identical ciphertext. This leaks data patterns (the 'penguin effect') and does not provide semantic security. ECB is universally considered cryptographically broken for data encryption.",
768
+ recommendation: "Replace ECB mode with an authenticated encryption mode: AES-GCM (preferred) or AES-CBC with a random IV and HMAC authentication. Always include authentication to prevent ciphertext tampering.",
769
+ fix: "Replace AES-ECB with AES-GCM: `createCipheriv('aes-256-gcm', key, iv)` and store the IV alongside the ciphertext.",
770
+ findingType: "vulnerability",
771
+ aiCodeTarget: true,
772
+ references: [
773
+ "https://cwe.mitre.org/data/definitions/327.html"
774
+ ]
775
+ },
776
+ {
777
+ id: "generic.crypto.des-rc4-3des",
778
+ framework: [
779
+ "generic"
780
+ ],
781
+ category: "crypto",
782
+ tier: "free",
783
+ severity: "high",
784
+ confidence: "HIGH",
785
+ action: "block",
786
+ version: 3,
787
+ status: "experimental",
788
+ cwe: [
789
+ "CWE-327"
790
+ ],
791
+ owasp: [
792
+ "A02:2021"
793
+ ],
794
+ matcher: {
795
+ type: "pattern",
796
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,java}",
797
+ patterns: [
798
+ `createCipheriv\\s*\\(\\s*['"](?:des|3des|des3|rc4|arcfour)['"]`,
799
+ `createCipheriv\\s*\\(\\s*['"](?:des|3des|des3|rc4|arcfour)-`,
800
+ `Cipher\\.getInstance\\s*\\(\\s*['"](?:DES|DESede|RC4|ARCFOUR)`,
801
+ "from Crypto\\.Cipher import (?:DES|DES3|ARC4)",
802
+ "from Cryptodome\\.Cipher import (?:DES|DES3|ARC4)"
803
+ ],
804
+ antiPatterns: [
805
+ "\\btest\\b|\\bspec\\b|__tests__|__fixtures__",
806
+ "legacy.compat|compat.legacy"
807
+ ],
808
+ flags: ""
809
+ },
810
+ explanation: "A deprecated symmetric cipher (DES, Triple-DES/3DES, or RC4) was detected. NIST SP 800-131A Rev.3 (2024 Draft) formally disallows 2-key 3DES (2TDEA) and marks 3TDEA as deprecated. DES has a 56-bit key space brute-forceable in hours with modern hardware. RC4 has known statistical biases exploited in WEP cracking and BEAST/CRIME attacks. These algorithms remain in AI training data from legacy Stack Overflow answers, causing AI tools to reproduce them in new code.",
811
+ recommendation: "Replace with AES-256-GCM (authenticated encryption). For Node.js: createCipheriv('aes-256-gcm', key, iv). For Python pycryptodome: AES.new(key, AES.MODE_GCM). For Java: Cipher.getInstance('AES/GCM/NoPadding'). AES-GCM provides both confidentiality and integrity.",
812
+ fix: "Replace DES/3DES/RC4 with AES-256-GCM. Generate a 256-bit key with crypto.randomBytes(32) and a 12-byte IV with crypto.randomBytes(12).",
813
+ findingType: "vulnerability",
814
+ aiCodeTarget: true,
815
+ references: [
816
+ "https://csrc.nist.gov/pubs/sp/800/131/a/r3/ipd",
817
+ "https://cwe.mitre.org/data/definitions/327.html"
818
+ ]
819
+ },
820
+ {
821
+ id: "generic.crypto.math-random-token",
822
+ framework: [
823
+ "generic"
824
+ ],
825
+ category: "crypto",
826
+ tier: "free",
827
+ severity: "high",
828
+ confidence: "HIGH",
829
+ action: "block",
830
+ version: 3,
831
+ status: "experimental",
832
+ cwe: [
833
+ "CWE-338"
834
+ ],
835
+ owasp: [
836
+ "A02:2021"
837
+ ],
838
+ matcher: {
839
+ type: "pattern",
840
+ fileGlob: "**/*.{ts,js,tsx,jsx}",
841
+ patterns: [
842
+ "(token|session|secret|password|nonce|csrf|otp|apiKey|authToken)\\s*=\\s*Math\\.random\\s*\\(",
843
+ "(token|session|secret|password|nonce|csrf|otp|apiKey|authToken)\\s*=\\s*[a-z_]+\\s*\\+\\s*Math\\.random\\s*\\(",
844
+ "Math\\.random\\s*\\(\\s*\\)\\.toString\\s*\\(\\)"
845
+ ],
846
+ antiPatterns: [
847
+ "\\btest\\b|\\bspec\\b|__fixtures__|jitter|delay|sample|color|position",
848
+ "eslint-disable"
849
+ ],
850
+ flags: "i"
851
+ },
852
+ explanation: "Math.random() was detected in a security token or session generation context. Math.random() is a pseudo-random number generator seeded with a predictable internal state \u2014 an attacker who can observe a few outputs can predict future values, allowing session hijacking or CSRF token forgery.",
853
+ recommendation: "Replace with the Web Crypto API: `crypto.randomUUID()` for UUIDs, or `crypto.getRandomValues(new Uint8Array(32))` for raw bytes. In Node.js use `crypto.randomBytes(32)`.",
854
+ fix: "Replace `Math.random()` with `crypto.randomBytes(32).toString('hex')` for token generation.",
855
+ findingType: "vulnerability",
856
+ aiCodeTarget: true,
857
+ references: [
858
+ "https://cwe.mitre.org/data/definitions/338.html"
859
+ ]
860
+ },
861
+ {
862
+ id: "generic.crypto.md5-sha1-password-hash",
863
+ framework: [
864
+ "generic"
865
+ ],
866
+ category: "crypto",
867
+ tier: "free",
868
+ severity: "high",
869
+ confidence: "HIGH",
870
+ action: "block",
871
+ version: 5,
872
+ status: "experimental",
873
+ cwe: [
874
+ "CWE-916",
875
+ "CWE-327"
876
+ ],
877
+ owasp: [
878
+ "A02:2021"
879
+ ],
880
+ matcher: {
881
+ type: "pattern",
882
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,rb,go,java,php}",
883
+ patterns: [
884
+ "hashlib\\.(md5|sha1)\\s{0,8}\\(\\s{0,8}(password|passwd|pwd|secret|credential|raw_password|auth_pass|user_input|new_password|old_password)",
885
+ "(password|passwd|pwd|secret|credential|raw_password|auth_pass|user_input|new_password|old_password)\\s{0,8}=\\s{0,8}hashlib\\.(md5|sha1)\\s{0,8}\\(",
886
+ `createHash\\s{0,8}\\(\\s{0,8}['"]sha1['"]\\)\\s{0,8}\\.update\\s{0,8}\\(\\s{0,8}(password|passwd|pwd|secret|credential|raw_password|auth_pass|user_input)`,
887
+ `createHash\\s{0,8}\\(\\s{0,8}['"]md5['"]\\)\\s{0,8}\\.update\\s{0,8}\\(\\s{0,8}(password|passwd|pwd|secret|credential|raw_password|auth_pass|user_input)`
888
+ ],
889
+ antiPatterns: [
890
+ "\\btest\\b|\\bspec\\b|__fixtures__|checksum|etag|fingerprint|cache",
891
+ "nosec|eslint-disable"
892
+ ],
893
+ flags: "i"
894
+ },
895
+ explanation: "MD5 or SHA-1 was detected in a password hashing context. These algorithms are fast, unkeyed hash functions without work factors \u2014 susceptible to GPU-accelerated brute-force attacks and precomputed rainbow tables. Password databases hashed with MD5/SHA1 are regularly cracked within hours.",
896
+ recommendation: "Replace with a purpose-built password hashing algorithm with a cost factor: bcrypt (cost 12+), scrypt, or Argon2id. Never use general-purpose hash functions for password storage.",
897
+ fix: "Use bcrypt: `const hash = await bcrypt.hash(password, 12)` or Argon2id via the argon2 package.",
898
+ findingType: "vulnerability",
899
+ aiCodeTarget: true,
900
+ references: [
901
+ "https://cwe.mitre.org/data/definitions/916.html",
902
+ "https://cwe.mitre.org/data/definitions/327.html"
903
+ ]
904
+ },
905
+ {
906
+ id: "generic.crypto.static-iv",
907
+ framework: [
908
+ "generic"
909
+ ],
910
+ category: "crypto",
911
+ tier: "free",
912
+ severity: "high",
913
+ confidence: "MEDIUM",
914
+ action: "warn",
915
+ version: 3,
916
+ status: "experimental",
917
+ cwe: [
918
+ "CWE-329",
919
+ "CWE-327"
920
+ ],
921
+ owasp: [
922
+ "A02:2021"
923
+ ],
924
+ matcher: {
925
+ type: "pattern",
926
+ fileGlob: "**/*.{ts,js,tsx,jsx}",
927
+ patterns: [
928
+ "Buffer\\.alloc\\s*\\(\\s*(?:12|16)\\s*,\\s*0\\s*\\)",
929
+ `Buffer\\.from\\s*\\(\\s*['"]0{16,32}['"]\\s*,\\s*['"]hex['"]\\s*\\)`,
930
+ `const\\s+iv\\s*=\\s*['"]0{16,32}['"]`
931
+ ],
932
+ antiPatterns: [
933
+ "\\btest\\b|\\bspec\\b|__tests__|__fixtures__",
934
+ "crypto\\.randomBytes|randomBytes|randomFill|randomUUID"
935
+ ],
936
+ flags: ""
937
+ },
938
+ explanation: "A static or zero-initialized IV (Initialization Vector) was detected. Using a hardcoded or all-zero IV in AES-CBC, AES-GCM, or other IV-dependent modes destroys semantic security: identical plaintext always produces identical ciphertext, enabling pattern recognition. For AES-GCM, reusing a nonce with the same key is catastrophic \u2014 it allows recovery of the authentication key. IVs and nonces MUST be generated fresh using a CSPRNG for each encryption operation.",
939
+ recommendation: "Replace Buffer.alloc(16, 0) with crypto.randomBytes(16) for CBC mode or crypto.randomBytes(12) for GCM mode. Generate a new IV for every encryption call. Store the IV alongside the ciphertext so it is available for decryption without needing to be secret.",
940
+ fix: "Replace Buffer.alloc(16, 0) with crypto.randomBytes(16). For GCM use crypto.randomBytes(12). Store IV with ciphertext.",
941
+ findingType: "vulnerability",
942
+ aiCodeTarget: true,
943
+ references: [
944
+ "https://cwe.mitre.org/data/definitions/329.html",
945
+ "https://cwe.mitre.org/data/definitions/327.html"
946
+ ]
947
+ },
948
+ {
949
+ id: "generic.injection.child-process-exec",
950
+ framework: [
951
+ "generic"
952
+ ],
953
+ category: "injection",
954
+ tier: "free",
955
+ severity: "high",
956
+ confidence: "MEDIUM",
957
+ action: "warn",
958
+ version: 3,
959
+ status: "experimental",
960
+ cwe: [
961
+ "CWE-78"
962
+ ],
963
+ owasp: [
964
+ "A03:2021"
965
+ ],
966
+ matcher: {
967
+ type: "pattern",
968
+ fileGlob: "**/*.{ts,js,tsx,jsx}",
969
+ patterns: [
970
+ "\\bexec\\s*\\(\\s*[a-zA-Z_$][a-zA-Z0-9_.]*\\s*\\+",
971
+ "\\bexec\\s*\\(\\s*`[^`]{0,200}\\$\\{",
972
+ "\\bexecSync\\s*\\(\\s*[a-zA-Z_$][a-zA-Z0-9_.]*\\s*\\+",
973
+ "\\bexecSync\\s*\\(\\s*`[^`]{0,200}\\$\\{"
974
+ ],
975
+ antiPatterns: [
976
+ "\\btest\\b|\\bspec\\b|__tests__|__fixtures__",
977
+ "eslint-disable"
978
+ ],
979
+ flags: ""
980
+ },
981
+ explanation: "Node.js child_process.exec() or execSync() is called with a dynamically constructed command string (variable concatenation or template literal with interpolation). exec() invokes the system shell (/bin/sh) and is therefore vulnerable to shell injection when any portion of the command string is derived from user input. This is the Node.js equivalent of Python subprocess with shell=True.",
982
+ recommendation: "Replace exec() with execFile() or spawn() which do NOT use a shell and pass arguments as an array. This prevents shell injection even with user-controlled arguments. Alternatively, validate and sanitize all input before constructing shell commands.",
983
+ fix: "Replace exec('ls ' + userPath) with execFile('ls', [userPath]) to avoid shell interpretation.",
984
+ findingType: "vulnerability",
985
+ aiCodeTarget: true,
986
+ references: [
987
+ "https://cwe.mitre.org/data/definitions/78.html"
988
+ ]
989
+ },
990
+ {
991
+ id: "generic.injection.eval-user-input",
992
+ framework: [
993
+ "generic"
994
+ ],
995
+ category: "injection",
996
+ tier: "free",
997
+ severity: "high",
998
+ confidence: "HIGH",
999
+ action: "block",
1000
+ version: 4,
1001
+ status: "experimental",
1002
+ cwe: [
1003
+ "CWE-95"
1004
+ ],
1005
+ owasp: [
1006
+ "A03:2021"
1007
+ ],
1008
+ matcher: {
1009
+ type: "pattern",
1010
+ fileGlob: "**/*.{ts,js,tsx,jsx}",
1011
+ patterns: [
1012
+ "eval\\s*\\(\\s*[a-zA-Z_$][a-zA-Z0-9_.\\[\\]]*\\s*\\)",
1013
+ "eval\\s*\\(\\s*[a-zA-Z_$][a-zA-Z0-9_.\\[\\]]*\\s*\\+\\s*[a-zA-Z_$]",
1014
+ "eval\\s*\\(`[^`]*`\\)",
1015
+ "new\\s+Function\\s*\\(\\s*[a-zA-Z_$][a-zA-Z0-9_.]*\\s*\\)"
1016
+ ],
1017
+ antiPatterns: [
1018
+ `eval\\s*\\(\\s*['"][^'"]{0,200}['"]\\s*\\)`,
1019
+ "\\btest\\b|\\bspec\\b|__fixtures__|__tests__",
1020
+ "eslint-disable"
1021
+ ],
1022
+ flags: "",
1023
+ antiPatternScope: "block"
1024
+ },
1025
+ explanation: "eval() or new Function() is called with a non-literal argument. If any part of the evaluated expression is derived from user input, this is a direct code injection vulnerability (CWE-95, CVE-2024-4181) allowing arbitrary JavaScript execution in the server or browser context. CSA 2026 research found 24.2% of AI-generated JS snippets contained this weakness. HIGH confidence \u2014 antiPatterns filter string-literal eval calls that are provably safe.",
1026
+ recommendation: "Avoid eval() and new Function() entirely. Replace dynamic code evaluation with safe alternatives: JSON.parse for data parsing, Function.prototype.call for dynamic dispatch, or a sandboxed interpreter for user-provided expressions.",
1027
+ fix: "Remove eval(). For JSON use JSON.parse(). For dynamic dispatch use a lookup table { [key]: handler }.",
1028
+ findingType: "vulnerability",
1029
+ aiCodeTarget: true,
1030
+ references: [
1031
+ "https://cwe.mitre.org/data/definitions/95.html"
1032
+ ]
1033
+ },
1034
+ {
1035
+ id: "generic.injection.eval-user-input-python",
1036
+ framework: [
1037
+ "generic"
1038
+ ],
1039
+ category: "injection",
1040
+ tier: "free",
1041
+ severity: "high",
1042
+ confidence: "HIGH",
1043
+ action: "block",
1044
+ version: 3,
1045
+ status: "experimental",
1046
+ cwe: [
1047
+ "CWE-95",
1048
+ "CWE-94"
1049
+ ],
1050
+ owasp: [
1051
+ "A03:2021"
1052
+ ],
1053
+ matcher: {
1054
+ type: "pattern",
1055
+ fileGlob: "**/*.py",
1056
+ patterns: [
1057
+ "eval\\s*\\(\\s*(?:request|req)\\b",
1058
+ "exec\\s*\\(\\s*(?:request|req)\\b",
1059
+ "eval\\s*\\(\\s*input\\s*\\(",
1060
+ "exec\\s*\\(\\s*input\\s*\\(",
1061
+ `eval\\s*\\(\\s*f['"]`,
1062
+ `exec\\s*\\(\\s*f['"]`
1063
+ ],
1064
+ antiPatterns: [
1065
+ "\\.test\\.|\\bspec\\b|__tests__|test_|_test\\.py|conftest\\.py",
1066
+ "#\\s*nosec"
1067
+ ],
1068
+ flags: ""
1069
+ },
1070
+ explanation: "Python eval() or exec() is called with a user-controlled or externally-sourced argument. This enables Remote Code Execution \u2014 any attacker who controls the evaluated string can execute arbitrary Python code with the application's privilege level. CSA 2026 research found 29.5% of AI-generated Python snippets contained code-injection weaknesses (CWE-94/95). AI tools frequently generate eval() for dynamic config evaluation without considering that the input source may be attacker-controlled.",
1071
+ recommendation: "Avoid eval() and exec() entirely. Replace with safe alternatives: use json.loads() for JSON parsing, ast.literal_eval() for safe Python literal evaluation (no function calls), or a sandboxed expression evaluator like simpleeval. Never evaluate user-provided strings.",
1072
+ fix: "Replace eval() with ast.literal_eval() for safe Python literal parsing, or json.loads() for JSON data.",
1073
+ findingType: "vulnerability",
1074
+ aiCodeTarget: true,
1075
+ references: [
1076
+ "https://cwe.mitre.org/data/definitions/95.html",
1077
+ "https://cwe.mitre.org/data/definitions/94.html"
1078
+ ]
1079
+ },
1080
+ {
1081
+ id: "generic.injection.shell-true",
1082
+ framework: [
1083
+ "generic"
1084
+ ],
1085
+ category: "injection",
1086
+ tier: "free",
1087
+ severity: "high",
1088
+ confidence: "HIGH",
1089
+ action: "block",
1090
+ version: 3,
1091
+ status: "experimental",
1092
+ cwe: [
1093
+ "CWE-78"
1094
+ ],
1095
+ owasp: [
1096
+ "A03:2021"
1097
+ ],
1098
+ matcher: {
1099
+ type: "pattern",
1100
+ fileGlob: "**/*.{py,rb,sh}",
1101
+ patterns: [
1102
+ "subprocess\\.(run|Popen|call|check_output)\\s*\\(\\s*shell\\s*=\\s*True",
1103
+ "shell\\s*=\\s*True",
1104
+ `os\\.system\\s*\\(\\s*f['"]`,
1105
+ "os\\.system\\s*\\([a-zA-Z_][a-zA-Z0-9_]*\\s*\\+"
1106
+ ],
1107
+ antiPatterns: [
1108
+ "\\btest\\b|\\bspec\\b|__fixtures__",
1109
+ "#\\s*safe"
1110
+ ],
1111
+ flags: ""
1112
+ },
1113
+ explanation: "subprocess is called with shell=True, or os.system is called with a non-literal argument (f-string or concatenation). When shell=True, the command is passed to the shell interpreter \u2014 if any part of the command string includes user-controlled input, an attacker can inject arbitrary OS commands using shell metacharacters.",
1114
+ recommendation: 'Replace shell=True with the list form: subprocess.run(["cmd", arg1, arg2]) where each argument is a separate list element. The shell never interprets the arguments when using list form. Validate and sanitize any external input used in command construction.',
1115
+ fix: "Replace `subprocess.run(cmd_string, shell=True)` with `subprocess.run(['cmd', arg], shell=False)`.",
1116
+ findingType: "vulnerability",
1117
+ aiCodeTarget: true,
1118
+ references: [
1119
+ "https://cwe.mitre.org/data/definitions/78.html",
1120
+ "https://github.com/PyCQA/bandit"
1121
+ ]
1122
+ },
1123
+ {
1124
+ id: "generic.injection.unsafe-deserialization-python",
1125
+ framework: [
1126
+ "generic"
1127
+ ],
1128
+ category: "injection",
1129
+ tier: "free",
1130
+ severity: "high",
1131
+ confidence: "HIGH",
1132
+ action: "block",
1133
+ version: 3,
1134
+ status: "experimental",
1135
+ cwe: [
1136
+ "CWE-502"
1137
+ ],
1138
+ owasp: [
1139
+ "A08:2021"
1140
+ ],
1141
+ matcher: {
1142
+ type: "pattern",
1143
+ fileGlob: "**/*.py",
1144
+ patterns: [
1145
+ "yaml\\.load\\s*\\(",
1146
+ "yaml\\.unsafe_load\\s*\\(",
1147
+ "pickle\\.loads\\s*\\(",
1148
+ "pickle\\.load\\s*\\("
1149
+ ],
1150
+ antiPatterns: [
1151
+ "\\.test\\.|\\bspec\\b|__tests__|test_|_test\\.py|conftest\\.py",
1152
+ "SafeLoader|yaml\\.safe_load"
1153
+ ],
1154
+ flags: ""
1155
+ },
1156
+ explanation: "Unsafe deserialization was detected. yaml.load() without SafeLoader allows instantiation of arbitrary Python objects, enabling Remote Code Execution through specially crafted YAML. pickle.load/loads() on untrusted data enables RCE through the __reduce__ method \u2014 unpickling untrusted data is equivalent to remote code execution. AI tools reproduce the vulnerable yaml.load() call from documentation examples that predated the SafeLoader warning.",
1157
+ recommendation: "For YAML: replace yaml.load(data) with yaml.safe_load(data). Never use yaml.load() unless you control 100% of the input source. For pickle: avoid deserializing untrusted data entirely. Use JSON, msgpack, or protobuf for data interchange. If pickle is required for trusted internal data, add input validation and integrity verification before unpickling.",
1158
+ fix: "Replace yaml.load(data) with yaml.safe_load(data). For pickle, switch to json.loads() for untrusted external data.",
1159
+ findingType: "vulnerability",
1160
+ aiCodeTarget: true,
1161
+ references: [
1162
+ "https://cwe.mitre.org/data/definitions/502.html",
1163
+ "https://pyyaml.org/wiki/PyYAMLDocumentation"
1164
+ ]
1165
+ },
1166
+ {
1167
+ id: "generic.injection.vm-runcontext",
1168
+ framework: [
1169
+ "generic"
1170
+ ],
1171
+ category: "injection",
1172
+ tier: "free",
1173
+ severity: "high",
1174
+ confidence: "MEDIUM",
1175
+ action: "warn",
1176
+ version: 3,
1177
+ status: "experimental",
1178
+ cwe: [
1179
+ "CWE-95"
1180
+ ],
1181
+ owasp: [
1182
+ "A03:2021"
1183
+ ],
1184
+ matcher: {
1185
+ type: "pattern",
1186
+ fileGlob: "**/*.{ts,js,tsx,jsx}",
1187
+ patterns: [
1188
+ "vm\\.runInThisContext\\s*\\(",
1189
+ "vm\\.runInNewContext\\s*\\(",
1190
+ "new vm\\.Script\\s*\\("
1191
+ ],
1192
+ antiPatterns: [
1193
+ "\\btest\\b|\\bspec\\b|__tests__|__fixtures__",
1194
+ "eslint-disable"
1195
+ ],
1196
+ flags: ""
1197
+ },
1198
+ explanation: 'Node.js vm.runInThisContext(), vm.runInNewContext(), or new vm.Script() is used for dynamic code execution. The Node.js vm module is NOT a security boundary \u2014 sandbox escape techniques are well-documented and have been exploited in production. AI tools generate vm module usage to "safely sandbox" user code, but this provides no actual isolation from the Node.js process. This is functionally equivalent to eval() for security purposes.',
1199
+ recommendation: "Avoid the vm module for untrusted code execution. Consider vm2 (archived but more restrictive), isolated-vm, or a subprocess-based sandbox. For expression evaluation, use safer alternatives like mathjs or safe-eval with a restricted environment.",
1200
+ fix: "Remove vm.runInThisContext/runInNewContext. Use isolated-vm or subprocess sandboxing for untrusted code execution.",
1201
+ findingType: "vulnerability",
1202
+ aiCodeTarget: true,
1203
+ references: [
1204
+ "https://cwe.mitre.org/data/definitions/95.html",
1205
+ "https://nodejs.org/api/vm.html"
1206
+ ]
1207
+ },
1208
+ {
1209
+ id: "generic.secrets.anthropic-api-key",
1210
+ framework: [
1211
+ "generic"
1212
+ ],
1213
+ category: "secrets",
1214
+ tier: "local",
1215
+ severity: "critical",
1216
+ confidence: "HIGH",
1217
+ action: "block",
1218
+ version: 4,
1219
+ status: "experimental",
1220
+ cwe: [
1221
+ "CWE-798"
1222
+ ],
1223
+ owasp: [
1224
+ "A07:2021"
1225
+ ],
1226
+ matcher: {
1227
+ type: "pattern",
1228
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,env,.env*}",
1229
+ patterns: [
1230
+ "sk-ant-api03-[a-zA-Z0-9]{80,100}"
1231
+ ],
1232
+ antiPatterns: [
1233
+ "YOUR_API_KEY|REPLACE_ME|example|placeholder|sk-ant-test",
1234
+ "process\\.env\\.[A-Za-z0-9_]+!?\\s*(?:[,;)}\\]]|$)",
1235
+ `os\\.environ(?:\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)|\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\])?(?:[,;)}\\]]|$)`
1236
+ ],
1237
+ flags: ""
1238
+ },
1239
+ explanation: "A hardcoded Anthropic API key (sk-ant-api03- prefix) was detected in source code. Committing Anthropic API keys to version control exposes them to anyone with repository access. Anthropic API spend can reach thousands of dollars per day with an exposed key. This is particularly relevant for ShipGuard's target market of AI-heavy Next.js and Vercel applications where Anthropic SDK usage is common.",
1240
+ recommendation: "Remove the key from source immediately. Store it in environment variables (ANTHROPIC_API_KEY) and load via process.env.ANTHROPIC_API_KEY. Rotate the exposed key at console.anthropic.com. Never commit API keys to version control.",
1241
+ fix: "Replace the literal key with `process.env.ANTHROPIC_API_KEY` and add ANTHROPIC_API_KEY to .env.local (gitignored).",
1242
+ findingType: "vulnerability",
1243
+ aiCodeTarget: true,
1244
+ references: [
1245
+ "https://cwe.mitre.org/data/definitions/798.html"
1246
+ ]
1247
+ },
1248
+ {
1249
+ id: "generic.secrets.aws-access-key",
1250
+ framework: [
1251
+ "generic"
1252
+ ],
1253
+ category: "secrets",
1254
+ tier: "local",
1255
+ severity: "high",
1256
+ confidence: "HIGH",
1257
+ action: "block",
1258
+ version: 4,
1259
+ status: "experimental",
1260
+ cwe: [
1261
+ "CWE-798"
1262
+ ],
1263
+ owasp: [
1264
+ "A07:2021"
1265
+ ],
1266
+ matcher: {
1267
+ type: "pattern",
1268
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,go,rb,java,yaml,yml,json,toml,cfg,conf,ini,sh,env}",
1269
+ patterns: [
1270
+ "(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}"
1271
+ ],
1272
+ antiPatterns: [
1273
+ "YOUR_KEY|REPLACE_ME|EXAMPLE|PLACEHOLDER|FAKE|DUMMY|example|placeholder",
1274
+ "process\\.env\\.[A-Za-z0-9_]+!?\\s*(?:[,;)}\\]]|$)",
1275
+ `os\\.environ(?:\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)|\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\])?(?:[,;)}\\]]|$)`,
1276
+ `ENV\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\](?:[,;)}\\]]|$)`,
1277
+ `secrets\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)(?:[,;)}\\]]|$)`,
1278
+ `secrets\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\](?:[,;)}\\]]|$)`,
1279
+ "\\.test\\.|\\bspec\\b|__tests__"
1280
+ ],
1281
+ flags: ""
1282
+ },
1283
+ explanation: "A hardcoded AWS access key ID (AKIA/ASIA/AGPA prefix) was detected in source. Committing AWS credentials to version control enables full cloud account takeover, unauthorized resource provisioning, and billing fraud.",
1284
+ recommendation: "Remove the key immediately and rotate it in the AWS IAM console. Store credentials via environment variables, AWS credential files (~/.aws/credentials), or IAM roles for compute resources. Never commit access key IDs or secret access keys.",
1285
+ fix: "Replace the literal key with `process.env.AWS_ACCESS_KEY_ID` and use IAM roles or AWS credential providers in production.",
1286
+ findingType: "vulnerability",
1287
+ aiCodeTarget: true,
1288
+ references: [
1289
+ "https://cwe.mitre.org/data/definitions/798.html",
1290
+ "https://github.com/gitleaks/gitleaks"
1291
+ ]
1292
+ },
1293
+ {
1294
+ id: "generic.secrets.azure-storage-key",
1295
+ framework: [
1296
+ "generic"
1297
+ ],
1298
+ category: "secrets",
1299
+ tier: "local",
1300
+ severity: "high",
1301
+ confidence: "HIGH",
1302
+ action: "block",
1303
+ version: 4,
1304
+ status: "experimental",
1305
+ cwe: [
1306
+ "CWE-798"
1307
+ ],
1308
+ owasp: [
1309
+ "A07:2021"
1310
+ ],
1311
+ matcher: {
1312
+ type: "pattern",
1313
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,go,cs,env,yaml,yml,json,conf,ini,xml,config}",
1314
+ patterns: [
1315
+ "AccountKey\\s*=\\s*[a-zA-Z0-9+/]{40,100}={0,2}"
1316
+ ],
1317
+ antiPatterns: [
1318
+ "AccountKey=YOUR_KEY|AccountKey=REPLACE_ME|AccountKey=example|AccountKey=test",
1319
+ "process\\.env\\.[A-Za-z0-9_]+!?\\s*(?:[,;)}\\]]|$)",
1320
+ `os\\.environ(?:\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)|\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\])?(?:[,;)}\\]]|$)`,
1321
+ `ENV\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\](?:[,;)}\\]]|$)`,
1322
+ `secrets\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)(?:[,;)}\\]]|$)`,
1323
+ `secrets\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\](?:[,;)}\\]]|$)`,
1324
+ "\\.test\\.|\\bspec\\b|__tests__"
1325
+ ],
1326
+ flags: ""
1327
+ },
1328
+ explanation: "A hardcoded Azure Storage Account key (AccountKey= with base64 value) was detected in source. This key grants full read/write/delete access to all blobs, tables, queues, and file shares in the storage account.",
1329
+ recommendation: "Rotate the storage account key immediately in the Azure Portal. Use Azure Managed Identity, Azure Key Vault references, or connection strings loaded from environment variables (AZURE_STORAGE_CONNECTION_STRING) at runtime.",
1330
+ fix: "Replace with `process.env.AZURE_STORAGE_CONNECTION_STRING` and rotate the account key in Azure Portal.",
1331
+ findingType: "vulnerability",
1332
+ aiCodeTarget: true,
1333
+ references: [
1334
+ "https://cwe.mitre.org/data/definitions/798.html",
1335
+ "https://github.com/gitleaks/gitleaks"
1336
+ ]
1337
+ },
1338
+ {
1339
+ id: "generic.secrets.db-connection-string",
1340
+ framework: [
1341
+ "generic"
1342
+ ],
1343
+ category: "secrets",
1344
+ tier: "local",
1345
+ severity: "high",
1346
+ confidence: "HIGH",
1347
+ action: "block",
1348
+ version: 4,
1349
+ status: "experimental",
1350
+ cwe: [
1351
+ "CWE-259",
1352
+ "CWE-798"
1353
+ ],
1354
+ owasp: [
1355
+ "A07:2021"
1356
+ ],
1357
+ matcher: {
1358
+ type: "pattern",
1359
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,go,rb,java,env,yaml,yml,json,conf,ini,toml}",
1360
+ patterns: [
1361
+ "(postgres|postgresql|mysql|mongodb|mongodb\\+srv|redis|mssql|sqlserver)://[a-zA-Z0-9._%-]+:[a-zA-Z0-9._@!#$%^&*()-]+@[a-zA-Z0-9._-]+"
1362
+ ],
1363
+ antiPatterns: [
1364
+ "YOUR_DB_PASSWORD|REPLACE_ME|password_here|<password>",
1365
+ "process\\.env\\.[A-Za-z0-9_]+!?\\s*(?:[,;)}\\]]|$)",
1366
+ `os\\.environ(?:\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)|\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\])?(?:[,;)}\\]]|$)`,
1367
+ `ENV\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\](?:[,;)}\\]]|$)`,
1368
+ `secrets\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)(?:[,;)}\\]]|$)`,
1369
+ `secrets\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\](?:[,;)}\\]]|$)`,
1370
+ "\\.test\\.|\\bspec\\b|__tests__"
1371
+ ],
1372
+ flags: "i"
1373
+ },
1374
+ explanation: "A database connection string with embedded credentials was detected in source. The URI contains a non-empty password segment in the form scheme://user:pass@host. Committing connection strings exposes database credentials to all repository readers.",
1375
+ recommendation: "Replace the hardcoded connection string with an environment variable reference (DATABASE_URL). Use connection poolers or secrets managers for production deployments. Rotate the exposed database password immediately.",
1376
+ fix: "Replace with `process.env.DATABASE_URL` and rotate the database password.",
1377
+ findingType: "vulnerability",
1378
+ aiCodeTarget: true,
1379
+ references: [
1380
+ "https://cwe.mitre.org/data/definitions/259.html",
1381
+ "https://cwe.mitre.org/data/definitions/798.html"
1382
+ ]
1383
+ },
1384
+ {
1385
+ id: "generic.secrets.gcp-service-account-key",
1386
+ framework: [
1387
+ "generic"
1388
+ ],
1389
+ category: "secrets",
1390
+ tier: "local",
1391
+ severity: "high",
1392
+ confidence: "HIGH",
1393
+ action: "block",
1394
+ version: 4,
1395
+ status: "experimental",
1396
+ cwe: [
1397
+ "CWE-798"
1398
+ ],
1399
+ owasp: [
1400
+ "A07:2021"
1401
+ ],
1402
+ matcher: {
1403
+ type: "pattern",
1404
+ fileGlob: "**/*.{json,js,ts,py,go,yaml,yml,conf,env}",
1405
+ patterns: [
1406
+ '"type"\\s*:\\s*"service_account"',
1407
+ '"private_key_id"\\s*:\\s*"[a-f0-9]{40}"'
1408
+ ],
1409
+ antiPatterns: [
1410
+ "YOUR_KEY_ID|REPLACE_ME|test_service_account",
1411
+ `os\\.environ(?:\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)|\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\])?(?:[,;)}\\]]|$)`,
1412
+ "process\\.env\\.[A-Za-z0-9_]+!?\\s*(?:[,;)}\\]]|$)",
1413
+ "\\.test\\.|\\bspec\\b|__tests__"
1414
+ ],
1415
+ flags: ""
1416
+ },
1417
+ explanation: 'A GCP service account private key JSON literal was detected in source. The "type": "service_account" field is a unique identifier for GCP service account credential files. Committing these credentials grants impersonation of the service account and all its IAM permissions to anyone with repository access.',
1418
+ recommendation: "Remove the key from source and rotate it in the GCP IAM console. Use Application Default Credentials (ADC) with Workload Identity for compute environments, or load the credentials file path from an environment variable at runtime.",
1419
+ fix: "Delete the key JSON from source. Use `GOOGLE_APPLICATION_CREDENTIALS=/path/to/key.json` loaded at runtime outside the repo.",
1420
+ findingType: "vulnerability",
1421
+ aiCodeTarget: true,
1422
+ references: [
1423
+ "https://cwe.mitre.org/data/definitions/798.html",
1424
+ "https://cloud.google.com/iam/docs/best-practices-for-managing-service-account-keys"
1425
+ ]
1426
+ },
1427
+ {
1428
+ id: "generic.secrets.github-token",
1429
+ framework: [
1430
+ "generic"
1431
+ ],
1432
+ category: "secrets",
1433
+ tier: "local",
1434
+ severity: "high",
1435
+ confidence: "HIGH",
1436
+ action: "block",
1437
+ version: 4,
1438
+ status: "experimental",
1439
+ cwe: [
1440
+ "CWE-798"
1441
+ ],
1442
+ owasp: [
1443
+ "A07:2021"
1444
+ ],
1445
+ matcher: {
1446
+ type: "pattern",
1447
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,go,rb,yaml,yml,env,json,sh,conf}",
1448
+ patterns: [
1449
+ "(ghp_|gho_|ghu_|ghs_|ghr_|github_pat_)[a-zA-Z0-9_]{20,80}"
1450
+ ],
1451
+ antiPatterns: [
1452
+ "YOUR_TOKEN|REPLACE_ME|ghp_example|ghp_xxxx|github_pat_example",
1453
+ "process\\.env\\.[A-Za-z0-9_]+!?\\s*(?:[,;)}\\]]|$)",
1454
+ `os\\.environ(?:\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)|\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\])?(?:[,;)}\\]]|$)`,
1455
+ `ENV\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\](?:[,;)}\\]]|$)`,
1456
+ `secrets\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)(?:[,;)}\\]]|$)`,
1457
+ `secrets\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\](?:[,;)}\\]]|$)`,
1458
+ "\\.test\\.|\\bspec\\b|__tests__"
1459
+ ],
1460
+ flags: ""
1461
+ },
1462
+ explanation: "A hardcoded GitHub Personal Access Token (ghp_, gho_, ghu_, ghs_, github_pat_ prefix) was detected in source. This token grants repository read/write access, workflow triggering, and API access to GitHub resources associated with the account or org.",
1463
+ recommendation: "Revoke the token immediately at github.com/settings/tokens. Store tokens in environment variables or a secrets manager. For CI/CD, use GITHUB_TOKEN with minimum-privilege scopes rather than a personal access token.",
1464
+ fix: "Replace with `process.env.GITHUB_TOKEN` and revoke the exposed token at github.com/settings/tokens.",
1465
+ findingType: "vulnerability",
1466
+ aiCodeTarget: true,
1467
+ references: [
1468
+ "https://cwe.mitre.org/data/definitions/798.html",
1469
+ "https://github.com/gitleaks/gitleaks"
1470
+ ]
1471
+ },
1472
+ {
1473
+ id: "generic.secrets.huggingface-token",
1474
+ framework: [
1475
+ "generic"
1476
+ ],
1477
+ category: "secrets",
1478
+ tier: "local",
1479
+ severity: "high",
1480
+ confidence: "HIGH",
1481
+ action: "block",
1482
+ version: 4,
1483
+ status: "experimental",
1484
+ cwe: [
1485
+ "CWE-798"
1486
+ ],
1487
+ owasp: [
1488
+ "A07:2021"
1489
+ ],
1490
+ matcher: {
1491
+ type: "pattern",
1492
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,env,.env*}",
1493
+ patterns: [
1494
+ "hf_[a-zA-Z0-9]{34}"
1495
+ ],
1496
+ antiPatterns: [
1497
+ "YOUR_TOKEN|REPLACE_ME|example|placeholder",
1498
+ "process\\.env\\.[A-Za-z0-9_]+!?\\s*(?:[,;)}\\]]|$)",
1499
+ `os\\.environ(?:\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)|\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\])?(?:[,;)}\\]]|$)`
1500
+ ],
1501
+ flags: ""
1502
+ },
1503
+ explanation: "A hardcoded Hugging Face API token (hf_ prefix) was detected. Hugging Face tokens grant access to private model repositories, inference endpoints, and training datasets. With the growth of AI-generated code in machine-learning applications, these tokens appear frequently in AI-generated data-pipeline scripts and model-serving code.",
1504
+ recommendation: "Remove the token from source code. Store it in environment variables (HUGGINGFACE_TOKEN or HF_TOKEN) and load via process.env. Rotate the exposed token at huggingface.co/settings/tokens.",
1505
+ fix: "Replace the literal token with `process.env.HF_TOKEN` and add HF_TOKEN to .env.local (gitignored).",
1506
+ findingType: "vulnerability",
1507
+ aiCodeTarget: true,
1508
+ references: [
1509
+ "https://cwe.mitre.org/data/definitions/798.html",
1510
+ "https://huggingface.co/docs/hub/security-tokens"
1511
+ ]
1512
+ },
1513
+ {
1514
+ id: "generic.secrets.openai-api-key",
1515
+ framework: [
1516
+ "generic"
1517
+ ],
1518
+ category: "secrets",
1519
+ tier: "local",
1520
+ severity: "critical",
1521
+ confidence: "HIGH",
1522
+ action: "block",
1523
+ version: 4,
1524
+ status: "experimental",
1525
+ cwe: [
1526
+ "CWE-798"
1527
+ ],
1528
+ owasp: [
1529
+ "A07:2021"
1530
+ ],
1531
+ matcher: {
1532
+ type: "pattern",
1533
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,env,.env*}",
1534
+ patterns: [
1535
+ "sk-[a-zA-Z0-9]{48}",
1536
+ "sk-proj-[a-zA-Z0-9_-]{43}"
1537
+ ],
1538
+ antiPatterns: [
1539
+ "YOUR_API_KEY|REPLACE_ME|example|placeholder|sk-test",
1540
+ "process\\.env\\.[A-Za-z0-9_]+!?\\s*(?:[,;)}\\]]|$)",
1541
+ `os\\.environ(?:\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)|\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\])?(?:[,;)}\\]]|$)`
1542
+ ],
1543
+ flags: ""
1544
+ },
1545
+ explanation: "A hardcoded OpenAI API key was detected. Committing API keys to source control exposes them to anyone with repository access and can lead to unauthorized usage and billing charges.",
1546
+ recommendation: "Remove the key from source. Store it in environment variables (OPENAI_API_KEY) and load via process.env. Rotate the exposed key immediately at platform.openai.com.",
1547
+ fix: "Replace the literal key with `process.env.OPENAI_API_KEY` and add OPENAI_API_KEY to .env.local (gitignored).",
1548
+ findingType: "vulnerability",
1549
+ aiCodeTarget: true
1550
+ },
1551
+ {
1552
+ id: "generic.secrets.private-key-pem",
1553
+ framework: [
1554
+ "generic"
1555
+ ],
1556
+ category: "secrets",
1557
+ tier: "local",
1558
+ severity: "high",
1559
+ confidence: "HIGH",
1560
+ action: "block",
1561
+ version: 4,
1562
+ status: "experimental",
1563
+ cwe: [
1564
+ "CWE-321"
1565
+ ],
1566
+ owasp: [
1567
+ "A02:2021"
1568
+ ],
1569
+ matcher: {
1570
+ type: "pattern",
1571
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,go,rb,java,pem,key,env,yaml,yml,json,conf}",
1572
+ patterns: [
1573
+ "-----BEGIN (RSA |EC |DSA |OPENSSH |ENCRYPTED |PRIVATE KEY|)[^-]{0,30}PRIVATE KEY-----(?:\\n|\\\\n)[ \\t]{0,20}[A-Za-z0-9+/=]{40,1000}"
1574
+ ],
1575
+ antiPatterns: [
1576
+ "REPLACE_ME|YOUR_PRIVATE_KEY|example_key|test_key|dummy_key",
1577
+ "readFileSync|loadKey|fs\\.read|open\\(|path\\.join",
1578
+ "\\.test\\.|\\bspec\\b|__tests__|__fixtures__"
1579
+ ],
1580
+ flags: ""
1581
+ },
1582
+ explanation: "A PEM-encoded private key header was detected in source (RSA, EC, DSA, OPENSSH, or PKCS8 format). Committing private keys enables impersonation, decryption of data, and signing forgery by anyone with repository access.",
1583
+ recommendation: "Remove the key from source immediately. Load private keys from the filesystem at runtime using an environment variable for the path, or use a secrets manager (AWS Secrets Manager, HashiCorp Vault, GCP Secret Manager). Rotate all potentially compromised keys.",
1584
+ fix: "Store the key in a file outside the repository and load with `fs.readFileSync(process.env.PRIVATE_KEY_PATH, 'utf8')`.",
1585
+ findingType: "vulnerability",
1586
+ aiCodeTarget: true,
1587
+ references: [
1588
+ "https://cwe.mitre.org/data/definitions/321.html",
1589
+ "https://github.com/gitleaks/gitleaks"
1590
+ ]
1591
+ },
1592
+ {
1593
+ id: "generic.secrets.slack-token",
1594
+ framework: [
1595
+ "generic"
1596
+ ],
1597
+ category: "secrets",
1598
+ tier: "local",
1599
+ severity: "high",
1600
+ confidence: "HIGH",
1601
+ action: "block",
1602
+ version: 4,
1603
+ status: "experimental",
1604
+ cwe: [
1605
+ "CWE-798"
1606
+ ],
1607
+ owasp: [
1608
+ "A07:2021"
1609
+ ],
1610
+ matcher: {
1611
+ type: "pattern",
1612
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,go,rb,env,yaml,yml,json,conf,ini}",
1613
+ patterns: [
1614
+ "xox[bpoas]-[0-9a-zA-Z-]{10,120}"
1615
+ ],
1616
+ antiPatterns: [
1617
+ "xoxb-REPLACE|xoxb-example|YOUR_SLACK_TOKEN|xox.-xxxx",
1618
+ "process\\.env\\.[A-Za-z0-9_]+!?\\s*(?:[,;)}\\]]|$)",
1619
+ `os\\.environ(?:\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)|\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\])?(?:[,;)}\\]]|$)`,
1620
+ `ENV\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\](?:[,;)}\\]]|$)`,
1621
+ `secrets\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)(?:[,;)}\\]]|$)`,
1622
+ `secrets\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\](?:[,;)}\\]]|$)`,
1623
+ "\\.test\\.|\\bspec\\b|__tests__"
1624
+ ],
1625
+ flags: ""
1626
+ },
1627
+ explanation: "A hardcoded Slack token (xoxb- bot, xoxp- user, xoxa- app, xoxs- workspace, or xoxo- org prefix) was detected in source. This token grants access to Slack workspace messages, channels, and user data.",
1628
+ recommendation: "Revoke the token immediately at api.slack.com/apps. Store tokens in environment variables (SLACK_BOT_TOKEN). Use the Slack SDK's built-in env var loading instead of hardcoding credentials in source files.",
1629
+ fix: "Replace with `process.env.SLACK_BOT_TOKEN` and revoke the exposed token at api.slack.com/apps.",
1630
+ findingType: "vulnerability",
1631
+ aiCodeTarget: true,
1632
+ references: [
1633
+ "https://cwe.mitre.org/data/definitions/798.html",
1634
+ "https://docs.slack.dev/authentication/tokens/"
1635
+ ]
1636
+ },
1637
+ {
1638
+ id: "generic.secrets.stripe-live-key",
1639
+ framework: [
1640
+ "generic"
1641
+ ],
1642
+ category: "secrets",
1643
+ tier: "local",
1644
+ severity: "critical",
1645
+ confidence: "HIGH",
1646
+ action: "block",
1647
+ version: 5,
1648
+ status: "experimental",
1649
+ cwe: [
1650
+ "CWE-798"
1651
+ ],
1652
+ owasp: [
1653
+ "A07:2021"
1654
+ ],
1655
+ matcher: {
1656
+ type: "pattern",
1657
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,rb,go,yaml,yml,json,conf,ini,env}",
1658
+ patterns: [
1659
+ "sk_live_[a-zA-Z0-9]{20,64}"
1660
+ ],
1661
+ antiPatterns: [
1662
+ "sk_live_xxxx|YOUR_STRIPE_KEY|REPLACE_ME",
1663
+ "process\\.env\\.[A-Za-z0-9_]+!?\\s*(?:[,;)}\\]]|$)",
1664
+ `os\\.environ(?:\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)|\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\])?(?:[,;)}\\]]|$)`,
1665
+ `ENV\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\](?:[,;)}\\]]|$)`,
1666
+ `secrets\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)(?:[,;)}\\]]|$)`,
1667
+ `secrets\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\](?:[,;)}\\]]|$)`,
1668
+ "\\.test\\.|\\bspec\\b|__tests__"
1669
+ ],
1670
+ flags: ""
1671
+ },
1672
+ explanation: "A hardcoded Stripe live secret key (sk_live_ prefix) was detected in source. This key grants full access to the Stripe account including charges, refunds, customer data, and payouts \u2014 immediate payment account compromise if exposed.\nv5 (founder ruling 2026-08-08, batch item 11): upgraded HIGH -> CRITICAL. This closes a severity disagreement the CLI's own dedup logic had been surfacing since it shipped (packages/cli/src/core/legacy-corpus-map.ts, `dedupeLegacyAgainstCorpus` doc comment): the legacy hand-written secrets check already rates this same defect `critical` (packages/cli/src/checks/secrets.ts, 'Stripe Live Secret Key' pattern) and dedup kept both findings because it can never silently soften a report. A live Stripe secret key is a complete, immediate payment-account takeover \u2014 charges, refunds, payouts, customer PII \u2014 which is a canonical CRITICAL-severity secret exposure, not merely HIGH. Canon set by the founder ruling; nothing about the detection pattern itself changed.",
1673
+ recommendation: "Remove the key immediately and roll it in the Stripe dashboard under Developers > API Keys. Store the key in an environment variable (STRIPE_SECRET_KEY) loaded at runtime. Never commit live API keys to version control.",
1674
+ fix: "Replace with `process.env.STRIPE_SECRET_KEY` and add it to .env.local (gitignored). Rotate the exposed key immediately.",
1675
+ findingType: "vulnerability",
1676
+ aiCodeTarget: true,
1677
+ references: [
1678
+ "https://cwe.mitre.org/data/definitions/798.html",
1679
+ "https://docs.stripe.com/keys-best-practices"
1680
+ ]
1681
+ },
1682
+ {
1683
+ id: "generic.tls.reject-unauthorized-disabled",
1684
+ framework: [
1685
+ "generic"
1686
+ ],
1687
+ category: "config",
1688
+ tier: "free",
1689
+ severity: "high",
1690
+ confidence: "HIGH",
1691
+ action: "block",
1692
+ version: 4,
1693
+ status: "experimental",
1694
+ cwe: [
1695
+ "CWE-295"
1696
+ ],
1697
+ owasp: [
1698
+ "A02:2021"
1699
+ ],
1700
+ matcher: {
1701
+ type: "pattern",
1702
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,go,rb,yaml,yml,conf,env}",
1703
+ patterns: [
1704
+ "rejectUnauthorized\\s*:\\s*false",
1705
+ `NODE_TLS_REJECT_UNAUTHORIZED\\s*[=:]\\s*['"]?0['"]?`,
1706
+ "verify\\s*=\\s*False",
1707
+ "ssl\\._create_unverified_context\\s*\\(",
1708
+ "verify_mode\\s*=\\s*ssl\\.CERT_NONE",
1709
+ "InsecureSkipVerify\\s*:\\s*true"
1710
+ ],
1711
+ antiPatterns: [
1712
+ "\\.test\\.|\\bspec\\b|__tests__|__fixtures__",
1713
+ "dev-only|local-only|localhost_only"
1714
+ ],
1715
+ flags: "",
1716
+ antiPatternScope: {
1717
+ lines: 3
1718
+ }
1719
+ },
1720
+ explanation: "TLS certificate validation is disabled via rejectUnauthorized: false or NODE_TLS_REJECT_UNAUTHORIZED=0. This allows man-in-the-middle attacks where an attacker intercepts TLS connections without detection, potentially exposing credentials, session tokens, and sensitive data in transit.",
1721
+ recommendation: "Remove rejectUnauthorized: false. If connecting to a server with a self-signed certificate, add the CA certificate to the trusted store instead of disabling validation. Never disable TLS certificate verification in production code.",
1722
+ fix: "Remove `rejectUnauthorized: false`. For self-signed certs use `ca: [fs.readFileSync('ca.crt')]` instead.",
1723
+ findingType: "vulnerability",
1724
+ aiCodeTarget: true,
1725
+ references: [
1726
+ "https://cwe.mitre.org/data/definitions/295.html"
1727
+ ]
1728
+ },
1729
+ {
1730
+ id: "generic.tls.verify-disabled-python",
1731
+ framework: [
1732
+ "generic"
1733
+ ],
1734
+ category: "config",
1735
+ tier: "free",
1736
+ severity: "high",
1737
+ confidence: "HIGH",
1738
+ action: "block",
1739
+ version: 3,
1740
+ status: "experimental",
1741
+ cwe: [
1742
+ "CWE-295"
1743
+ ],
1744
+ owasp: [
1745
+ "A02:2021"
1746
+ ],
1747
+ matcher: {
1748
+ type: "pattern",
1749
+ fileGlob: "**/*.py",
1750
+ patterns: [
1751
+ "verify\\s*=\\s*False",
1752
+ "ssl\\._create_unverified_context\\s*\\(",
1753
+ "\\.verify_mode\\s*=\\s*ssl\\.CERT_NONE"
1754
+ ],
1755
+ antiPatterns: [
1756
+ "\\.test\\.|\\bspec\\b|__tests__|test_|_test\\.py|conftest\\.py",
1757
+ "dev-only|local-only|localhost_only"
1758
+ ],
1759
+ flags: ""
1760
+ },
1761
+ explanation: "Python TLS certificate validation is disabled via verify=False (requests library) or ssl._create_unverified_context() / ssl.CERT_NONE (ssl module). This downgrades HTTPS to an unencrypted channel vulnerable to man-in-the-middle attacks, exposing credentials, session tokens, and sensitive data in transit. This is the most common AI-generated TLS vulnerability pattern in Python \u2014 AI tools suggest verify=False to resolve SSL errors without explaining the security impact.",
1762
+ recommendation: "Remove verify=False. For self-signed or custom CA certificates, provide the CA bundle path: requests.get(url, verify='/path/to/ca-bundle.crt'). Never disable certificate validation in production code. In Python ssl module, use ssl.create_default_context() which enables validation by default.",
1763
+ fix: "Replace verify=False with verify=True (default) or verify='/path/to/ca.crt'. For ssl module use ssl.create_default_context() instead of ssl._create_unverified_context().",
1764
+ findingType: "vulnerability",
1765
+ aiCodeTarget: true,
1766
+ references: [
1767
+ "https://cwe.mitre.org/data/definitions/295.html",
1768
+ "https://docs.python-requests.org/en/latest/user/advanced/#ssl-cert-verification"
1769
+ ]
1770
+ },
1771
+ {
1772
+ id: "postgresql.auth.trust-auth-method",
1773
+ framework: [
1774
+ "postgresql"
1775
+ ],
1776
+ category: "auth",
1777
+ tier: "free",
1778
+ severity: "critical",
1779
+ confidence: "HIGH",
1780
+ action: "block",
1781
+ version: 3,
1782
+ status: "experimental",
1783
+ cwe: [
1784
+ "CWE-287",
1785
+ "CWE-306"
1786
+ ],
1787
+ owasp: [
1788
+ "A07:2021"
1789
+ ],
1790
+ matcher: {
1791
+ type: "pattern",
1792
+ fileGlob: "**/{pg_hba.conf,docker-compose*.yml,docker-compose*.yaml,.env*}",
1793
+ patterns: [
1794
+ "POSTGRES_HOST_AUTH_METHOD[ \\t]*[:=][ \\t]*trust",
1795
+ "^(host|local)[ \\t]+[^ \\t\\n]+[ \\t]+[^ \\t\\n]+[ \\t]+[^ \\t\\n]+[ \\t]+trust"
1796
+ ],
1797
+ antiPatterns: [
1798
+ "__tests__|test_migration",
1799
+ "# trust|#trust"
1800
+ ],
1801
+ flags: "im"
1802
+ },
1803
+ explanation: `PostgreSQL trust authentication is configured, meaning any connection from the allowed host is accepted without password verification. Anyone on the network (or local machine) can connect as any database user \u2014 including the postgres superuser \u2014 without credentials.
1804
+ AI-generated Docker configurations frequently omit the POSTGRES_PASSWORD environment variable, causing the official PostgreSQL Docker image to silently write 'host all all all trust' into pg_hba.conf. This makes the database fully accessible to anyone with network access to the PostgreSQL port.
1805
+ PostgreSQL official docs: "Trust authentication is only suitable for TCP/IP connections if you trust every user on every machine that is allowed to connect to the server."`,
1806
+ recommendation: "Set a strong POSTGRES_PASSWORD in docker-compose.yml and .env files. In pg_hba.conf, replace 'trust' with 'scram-sha-256' (PostgreSQL 10+) or 'md5' as the authentication method. Never use trust authentication for TCP/IP connections in any environment.",
1807
+ fix: "Replace 'trust' with 'scram-sha-256' in pg_hba.conf and set POSTGRES_PASSWORD in your Docker configuration.",
1808
+ findingType: "vulnerability",
1809
+ aiCodeTarget: true
1810
+ }
1811
+ ]
1812
+ };
1813
+
1814
+ // src/core/bundled-rules.ts
1815
+ var SUPPORTED_FREE_BUNDLE_SCHEMA_VERSION = 1;
1816
+ var raw = free_bundle_default;
1817
+ var FreeBundleError = class extends Error {
1818
+ constructor(message) {
1819
+ super(message);
1820
+ this.name = "FreeBundleError";
1821
+ }
1822
+ };
1823
+ var validated = false;
1824
+ function validateOnce() {
1825
+ if (validated) return;
1826
+ if (raw.schemaVersion !== SUPPORTED_FREE_BUNDLE_SCHEMA_VERSION) {
1827
+ throw new FreeBundleError(
1828
+ `Bundled rule set declares schemaVersion ${raw.schemaVersion}, but this CLI reads ${SUPPORTED_FREE_BUNDLE_SCHEMA_VERSION}. Refusing to run a bundle whose layout this build does not understand \u2014 a partially-parsed rule set would silently under-scan.`
1829
+ );
1830
+ }
1831
+ if (!Array.isArray(raw.rules) || raw.rules.length === 0) {
1832
+ throw new FreeBundleError(
1833
+ "Bundled rule set is empty. An offline scan with zero corpus rules would report clean while applying nothing \u2014 failing loud instead."
1834
+ );
1835
+ }
1836
+ if (raw.rules.length !== raw.ruleCount) {
1837
+ throw new FreeBundleError(
1838
+ `Bundled rule set declares ruleCount ${raw.ruleCount} but carries ${raw.rules.length} rules \u2014 the bundle is inconsistent with its own header.`
1839
+ );
1840
+ }
1841
+ const compile = validateBundleCompile(raw.rules);
1842
+ if (!compile.ok) {
1843
+ throw new FreeBundleError(
1844
+ `Bundled rule set failed to compile: ${compile.reason}. Refusing to run \u2014 a scan that silently applied zero corpus rules would report clean while checking nothing.`
1845
+ );
1846
+ }
1847
+ validated = true;
1848
+ }
1849
+ function loadBundledRules() {
1850
+ validateOnce();
1851
+ return raw.rules;
1852
+ }
1853
+ function bundledRulesMeta() {
1854
+ validateOnce();
1855
+ return {
1856
+ corpusVersion: raw.corpusVersion,
1857
+ contentHash: raw.contentHash,
1858
+ ruleCount: raw.ruleCount
1859
+ };
1860
+ }
1861
+
1862
+ // src/core/legacy-corpus-map.ts
1863
+ var LEGACY_TO_CORPUS = Object.freeze({
1864
+ // The legacy secrets check is one catch-all id covering ~15 provider patterns. The corpus
1865
+ // splits the same ground into one rule per provider, each with its own CWE + fix text. Same
1866
+ // line, same secret, better finding.
1867
+ hardcoded_secret: [
1868
+ "generic.secrets.anthropic-api-key",
1869
+ "generic.secrets.aws-access-key",
1870
+ "generic.secrets.azure-storage-key",
1871
+ "generic.secrets.db-connection-string",
1872
+ "generic.secrets.gcp-service-account-key",
1873
+ "generic.secrets.github-token",
1874
+ "generic.secrets.huggingface-token",
1875
+ "generic.secrets.openai-api-key",
1876
+ "generic.secrets.private-key-pem",
1877
+ "generic.secrets.slack-token",
1878
+ "generic.secrets.stripe-live-key"
1879
+ ],
1880
+ // Next.js headers() wildcard CORS — the corpus rule covers the same
1881
+ // `Access-Control-Allow-Origin: *` shape across every framework.
1882
+ deployment_cors_wildcard: ["generic.cors.wildcard-origin"],
1883
+ // `origin: '*'` in a cors() middleware config — same defect, same line.
1884
+ deployment_config_cors_wildcard_origin: ["generic.cors.wildcard-origin"],
1885
+ // `debug: true` in a config file.
1886
+ deployment_config_debug_mode: ["generic.config.debug-mode-enabled"]
1887
+ });
1888
+ var LEGACY_RETAINED_NO_CORPUS_EQUIVALENT = Object.freeze([
1889
+ // secrets
1890
+ "exposed_env",
1891
+ // a .env file tracked by git — a repo-state fact no content regex can see
1892
+ // auth (the corpus has no route-authorization rules at all)
1893
+ "public_admin_route",
1894
+ "auth_route_without_guard",
1895
+ // database
1896
+ "db-drop-table",
1897
+ "db-drop-column",
1898
+ "db-truncate",
1899
+ "db-delete-without-where",
1900
+ "db-alter-drop",
1901
+ "db-push-in-scripts",
1902
+ "db-schema-without-migration",
1903
+ "pkg-json-unparseable-database",
1904
+ // payments
1905
+ "payment_webhook_without_signature_check",
1906
+ "missing_idempotency",
1907
+ "missing_error_handling",
1908
+ // deployment / IaC config shapes
1909
+ "deployment_source_maps_exposed",
1910
+ "deployment_missing_x_frame_options",
1911
+ "deployment_missing_x_content_type",
1912
+ "deployment_docker_root_user",
1913
+ "deployment_docker_unpinned_image",
1914
+ "deployment_compose_unpinned_image",
1915
+ "deployment_vercel_broad_rewrite",
1916
+ "deployment_vercel_missing_headers",
1917
+ "deployment_netlify_missing_headers",
1918
+ "deployment_missing_env_example",
1919
+ "deployment_env_undocumented_keys",
1920
+ "pkg-json-unparseable-deployment"
1921
+ ]);
1922
+ var SEVERITY_RANK = Object.freeze({
1923
+ critical: 4,
1924
+ high: 3,
1925
+ medium: 2,
1926
+ low: 1,
1927
+ info: 0
1928
+ });
1929
+ function dedupeLegacyAgainstCorpus(legacyFindings, corpusFindings, isUserSuppressed = (cf) => cf.suppressed === true) {
1930
+ const corpusIndex = /* @__PURE__ */ new Map();
1931
+ for (const f of corpusFindings) {
1932
+ if (f.line === void 0) continue;
1933
+ const key = `${f.file} ${f.line}`;
1934
+ let byId = corpusIndex.get(key);
1935
+ if (!byId) {
1936
+ byId = /* @__PURE__ */ new Map();
1937
+ corpusIndex.set(key, byId);
1938
+ }
1939
+ byId.set(f.id, f);
1940
+ }
1941
+ const promoted = /* @__PURE__ */ new Map();
1942
+ const notes = [];
1943
+ const severityDisagreements = [];
1944
+ const kept = [];
1945
+ for (const f of legacyFindings) {
1946
+ const mapped = LEGACY_TO_CORPUS[f.id];
1947
+ if (!mapped || f.line === void 0) {
1948
+ kept.push(f);
1949
+ continue;
1950
+ }
1951
+ const atSameLine = corpusIndex.get(`${f.file} ${f.line}`);
1952
+ const twinIds = atSameLine ? mapped.filter((id) => atSameLine.has(id)) : [];
1953
+ const activeTwin = twinIds.find((id) => !atSameLine.get(id).suppressed);
1954
+ const suppressedTwin = twinIds.find((id) => {
1955
+ const cf = atSameLine.get(id);
1956
+ return cf.suppressed === true && isUserSuppressed(cf);
1957
+ });
1958
+ if (f.suppressed) {
1959
+ if (suppressedTwin !== void 0 && activeTwin === void 0) {
1960
+ notes.push({ legacyId: f.id, corpusId: suppressedTwin, file: f.file, line: f.line });
1961
+ } else {
1962
+ kept.push(f);
1963
+ }
1964
+ continue;
1965
+ }
1966
+ if (activeTwin === void 0) {
1967
+ if (suppressedTwin !== void 0) {
1968
+ notes.push({
1969
+ legacyId: f.id,
1970
+ corpusId: suppressedTwin,
1971
+ file: f.file,
1972
+ line: f.line,
1973
+ supersededBySuppressedTwin: true
1974
+ });
1975
+ } else {
1976
+ kept.push(f);
1977
+ }
1978
+ continue;
1979
+ }
1980
+ const winnerId = activeTwin;
1981
+ const corpusFinding = atSameLine.get(winnerId);
1982
+ const legacyRank = SEVERITY_RANK[f.severity] ?? 0;
1983
+ const corpusRank = SEVERITY_RANK[corpusFinding.severity] ?? 0;
1984
+ const severityRaised = legacyRank > corpusRank;
1985
+ if (severityRaised) {
1986
+ severityDisagreements.push({
1987
+ legacyId: f.id,
1988
+ corpusId: winnerId,
1989
+ file: f.file,
1990
+ line: f.line,
1991
+ legacySeverity: f.severity,
1992
+ corpusSeverity: corpusFinding.severity
1993
+ });
1994
+ }
1995
+ const blockingPromoted = f.blocking === true && corpusFinding.blocking !== true;
1996
+ if (severityRaised || blockingPromoted) {
1997
+ const prev = promoted.get(corpusFinding);
1998
+ const nextSeverity = severityRaised && (!prev?.severity || (SEVERITY_RANK[f.severity] ?? 0) > (SEVERITY_RANK[prev.severity] ?? 0)) ? f.severity : prev?.severity;
1999
+ promoted.set(corpusFinding, {
2000
+ legacyId: prev?.legacyId ?? f.id,
2001
+ blocking: blockingPromoted || prev?.blocking === true,
2002
+ severity: nextSeverity
2003
+ });
2004
+ }
2005
+ notes.push({
2006
+ legacyId: f.id,
2007
+ corpusId: winnerId,
2008
+ file: f.file,
2009
+ line: f.line,
2010
+ ...blockingPromoted ? { blockingPromoted: true } : {},
2011
+ ...severityRaised ? { severityRaised: true } : {}
2012
+ });
2013
+ }
2014
+ const outCorpus = corpusFindings.map((cf) => {
2015
+ const p = promoted.get(cf);
2016
+ if (p === void 0) return cf;
2017
+ const notesText = [];
2018
+ if (p.severity) {
2019
+ notesText.push(
2020
+ `Severity raised from ${cf.severity} to ${p.severity} because the equivalent built-in check (${p.legacyId}) rates this defect ${p.severity}.`
2021
+ );
2022
+ }
2023
+ if (p.blocking) {
2024
+ notesText.push(
2025
+ `Reported as BLOCKING because the equivalent built-in check (${p.legacyId}) blocks on this line; this rule's own action is warn.`
2026
+ );
2027
+ }
2028
+ return {
2029
+ ...cf,
2030
+ ...p.severity ? { severity: p.severity } : {},
2031
+ ...p.blocking ? { blocking: true } : {},
2032
+ explanation: `${cf.explanation}
2033
+ [shipguard] ${notesText.join(" ")}`
2034
+ };
2035
+ });
2036
+ return { findings: kept, corpusFindings: outCorpus, notes, severityDisagreements };
2037
+ }
2038
+
2039
+ // src/core/collapse-findings.ts
2040
+ var SEVERITY_RANK2 = Object.freeze({
2041
+ critical: 4,
2042
+ high: 3,
2043
+ medium: 2,
2044
+ low: 1,
2045
+ info: 0
2046
+ });
2047
+ function isSecretsFinding(f) {
2048
+ return f.category === "secrets" || f.id.includes(".secrets.");
2049
+ }
2050
+ function normaliseEvidence(evidence) {
2051
+ return (evidence ?? "").trim().replace(/^(\.\.\.|['"`])+|(\.\.\.|['"`])+$/g, "").trim();
2052
+ }
2053
+ function endLineOf(f) {
2054
+ const start = f.line;
2055
+ if (!f.evidence) return start;
2056
+ let end = f.evidence.length;
2057
+ while (end > 0 && (f.evidence.charCodeAt(end - 1) === 10 || f.evidence.charCodeAt(end - 1) === 13)) end--;
2058
+ let newlines = 0;
2059
+ for (let i = 0; i < end; i++) {
2060
+ if (f.evidence.charCodeAt(i) === 10) newlines++;
2061
+ }
2062
+ return start + newlines;
2063
+ }
2064
+ function outranks(a, b) {
2065
+ return (SEVERITY_RANK2[a.severity] ?? 0) > (SEVERITY_RANK2[b.severity] ?? 0);
2066
+ }
2067
+ function collapseSameIssueFindings(findings) {
2068
+ const groups = /* @__PURE__ */ new Map();
2069
+ for (let i = 0; i < findings.length; i++) {
2070
+ const f = findings[i];
2071
+ if (f.line === void 0) continue;
2072
+ let valueKey = "";
2073
+ if (isSecretsFinding(f)) {
2074
+ if (f.column === void 0) continue;
2075
+ valueKey = normaliseEvidence(f.evidence);
2076
+ }
2077
+ const key = `${f.id}\0${f.file}\0${f.suppressed ? "s" : "a"}\0${valueKey}`;
2078
+ const g = groups.get(key);
2079
+ if (g) g.push(i);
2080
+ else groups.set(key, [i]);
2081
+ }
2082
+ const dropped = /* @__PURE__ */ new Set();
2083
+ const notes = [];
2084
+ for (const indices of groups.values()) {
2085
+ if (indices.length < 2) continue;
2086
+ const ordered = [...indices].sort((x, y) => {
2087
+ const fx = findings[x];
2088
+ const fy = findings[y];
2089
+ return fx.line - fy.line || (fx.column ?? 0) - (fy.column ?? 0) || x - y;
2090
+ });
2091
+ let cluster = [];
2092
+ let clusterEnd = -1;
2093
+ const flush = () => {
2094
+ if (cluster.length < 2) return;
2095
+ let winner = cluster[0];
2096
+ for (const idx of cluster.slice(1)) {
2097
+ if (outranks(findings[idx], findings[winner])) winner = idx;
2098
+ }
2099
+ for (const idx of cluster) {
2100
+ if (idx === winner) continue;
2101
+ dropped.add(idx);
2102
+ const d = findings[idx];
2103
+ notes.push({
2104
+ id: d.id,
2105
+ file: d.file,
2106
+ line: d.line,
2107
+ keptColumn: findings[winner].column,
2108
+ droppedColumn: d.column
2109
+ });
2110
+ }
2111
+ };
2112
+ for (const idx of ordered) {
2113
+ const f = findings[idx];
2114
+ const start = f.line;
2115
+ if (cluster.length > 0 && start <= clusterEnd) {
2116
+ cluster.push(idx);
2117
+ clusterEnd = Math.max(clusterEnd, endLineOf(f));
2118
+ } else {
2119
+ flush();
2120
+ cluster = [idx];
2121
+ clusterEnd = endLineOf(f);
2122
+ }
2123
+ }
2124
+ flush();
2125
+ }
2126
+ if (dropped.size === 0) return { findings, notes };
2127
+ return { findings: findings.filter((_, i) => !dropped.has(i)), notes };
2128
+ }
2129
+
290
2130
  // src/core/scanner.ts
291
2131
  var CHECK_MODULES = [secretsCheck, authCheck, databaseCheck, payments, deploymentCheck];
292
2132
  var DEFAULT_IGNORE = [
@@ -299,10 +2139,45 @@ var DEFAULT_IGNORE = [
299
2139
  // ShipGuard's own report output — never scan the tool's own artifacts
300
2140
  ".shipguard/**"
301
2141
  ];
2142
+ function selfArtifactIgnorePatterns(policy) {
2143
+ const patterns = [];
2144
+ const add = (p) => {
2145
+ if (!p) return;
2146
+ if (p.startsWith("/")) return;
2147
+ const rel = p.replace(/^\.\//, "");
2148
+ if (!rel) return;
2149
+ patterns.push(rel);
2150
+ };
2151
+ const reportOutput = policy.report?.output;
2152
+ add(reportOutput);
2153
+ if (reportOutput) {
2154
+ add(reportOutput.replace(/\.md$/, ".json"));
2155
+ const reportDir = dirname2(reportOutput);
2156
+ add(join3(reportDir === "." ? "" : reportDir, RUNS_SUBDIR, "**"));
2157
+ }
2158
+ add(policy.history?.path);
2159
+ add(process.env[HISTORY_PATH_ENV_VAR]);
2160
+ return patterns;
2161
+ }
2162
+ function computeTreeDigest(files) {
2163
+ if (files.length === 0) return void 0;
2164
+ const encoder = new TextEncoder();
2165
+ const lines = files.map((f) => `${f.relativePath}\0${toHex(sha256(encoder.encode(f.content)))}
2166
+ `).sort(compareScanPaths);
2167
+ return toHex(sha256(encoder.encode(lines.join(""))));
2168
+ }
2169
+ function toHex(bytes) {
2170
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
2171
+ }
302
2172
  async function scan(options, proRules, onProgress) {
303
2173
  const cwd = process.cwd();
304
2174
  const policy = await loadPolicy(cwd);
305
- const ignorePatterns = [...DEFAULT_IGNORE, ...policy.ignore.paths];
2175
+ const ignorePatterns = [
2176
+ ...DEFAULT_IGNORE,
2177
+ // Rec #6 — ShipGuard's own artifacts, wherever the policy put them.
2178
+ ...selfArtifactIgnorePatterns(policy),
2179
+ ...policy.ignore.paths
2180
+ ];
306
2181
  const limits = {
307
2182
  maxFileSizeBytes: policy.limits?.maxFileSizeBytes ?? DEFAULT_MAX_FILE_SIZE_BYTES,
308
2183
  maxTotalBytes: policy.limits?.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES,
@@ -312,6 +2187,9 @@ async function scan(options, proRules, onProgress) {
312
2187
  let skippedTooLarge = 0;
313
2188
  const skippedTooLargeFiles = [];
314
2189
  let skippedBinary = 0;
2190
+ const skippedBinaryFiles = [];
2191
+ let skippedSymlinks = 0;
2192
+ const skippedSymlinkFiles = [];
315
2193
  let truncated = false;
316
2194
  const changedInvalidUtf8 = [];
317
2195
  const changedUnreadable = [];
@@ -320,12 +2198,13 @@ async function scan(options, proRules, onProgress) {
320
2198
  if (changedRelPaths.length === 0) {
321
2199
  logger.info("--changed: git ran successfully \u2014 0 changed files to scan.");
322
2200
  }
2201
+ const changedIgnore = [...DEFAULT_IGNORE, ...selfArtifactIgnorePatterns(policy)];
323
2202
  const filteredPaths = changedRelPaths.filter(
324
- (rp) => !DEFAULT_IGNORE.some((pat) => {
2203
+ (rp) => !changedIgnore.some((pat) => {
325
2204
  const prefix = pat.replace("/**", "");
326
2205
  return rp.startsWith(prefix + "/") || rp === prefix;
327
2206
  })
328
- );
2207
+ ).sort(compareScanPaths);
329
2208
  files = [];
330
2209
  let totalBytes = 0;
331
2210
  const changedTotal = filteredPaths.length;
@@ -335,7 +2214,7 @@ async function scan(options, proRules, onProgress) {
335
2214
  truncated = true;
336
2215
  break;
337
2216
  }
338
- const fullPath = join2(cwd, relPath);
2217
+ const fullPath = join3(cwd, relPath);
339
2218
  try {
340
2219
  let resolvedPath;
341
2220
  try {
@@ -402,14 +2281,39 @@ async function scan(options, proRules, onProgress) {
402
2281
  skippedTooLarge = readResult.skippedTooLarge;
403
2282
  skippedTooLargeFiles.push(...readResult.skippedTooLargeFiles);
404
2283
  skippedBinary = readResult.skippedBinary;
2284
+ skippedBinaryFiles.push(...readResult.skippedBinaryFiles);
2285
+ skippedSymlinks = readResult.skippedSymlinks;
2286
+ skippedSymlinkFiles.push(...readResult.skippedSymlinkFiles);
405
2287
  truncated = readResult.truncated;
406
2288
  changedInvalidUtf8.push(...readResult.invalidUtf8Files);
407
2289
  changedUnreadable.push(...readResult.unreadableFiles);
408
2290
  }
409
- let allFindings = applySuppressions(
410
- CHECK_MODULES.flatMap((mod) => mod.run(files, policy)),
2291
+ const sourceRedacted = /* @__PURE__ */ new Set();
2292
+ const legacyFindings = applySuppressions(
2293
+ CHECK_MODULES.flatMap((mod) => {
2294
+ const found = mod.run(files, policy);
2295
+ if (mod === secretsCheck) for (const f of found) sourceRedacted.add(f);
2296
+ return found;
2297
+ }),
411
2298
  files
412
2299
  );
2300
+ const bundledFindings = applySuppressions(runProRules(loadBundledRules(), files, policy), files);
2301
+ const { findings: dedupedLegacy, corpusFindings: dedupedCorpus, notes: dedupNotes, severityDisagreements } = dedupeLegacyAgainstCorpus(legacyFindings, bundledFindings, (cf) => {
2302
+ if (cf.line === void 0) return false;
2303
+ const file = files.find((x) => x.relativePath === cf.file);
2304
+ return file !== void 0 && isLineSuppressed(file.content.split("\n"), cf.line - 1, cf.id);
2305
+ });
2306
+ for (const n of dedupNotes) {
2307
+ logger.debug(
2308
+ `[shipguard] ${n.file}:${n.line} \u2014 legacy finding "${n.legacyId}" superseded by governed corpus rule "${n.corpusId}" (same line, same defect).` + (n.blockingPromoted ? ` The legacy finding was blocking, so the corpus finding is reported as blocking to keep the gate behaviour.` : "")
2309
+ );
2310
+ }
2311
+ for (const d of severityDisagreements) {
2312
+ logger.warn(
2313
+ `[shipguard] ${d.file}:${d.line} \u2014 "${d.legacyId}" (${d.legacySeverity}) and "${d.corpusId}" (${d.corpusSeverity}) describe the same defect with different severities. They are folded into one finding at the higher severity.`
2314
+ );
2315
+ }
2316
+ let allFindings = [...dedupedLegacy, ...dedupedCorpus];
413
2317
  let coderefDegraded = false;
414
2318
  if (proRules?.length) {
415
2319
  const checksumManifest = loadChecksumManifest();
@@ -429,7 +2333,16 @@ async function scan(options, proRules, onProgress) {
429
2333
  logger.warn(w);
430
2334
  }
431
2335
  }
2336
+ const collapsed = collapseSameIssueFindings(allFindings);
2337
+ for (const n of collapsed.notes) {
2338
+ logger.debug(
2339
+ `[shipguard] ${n.file}:${n.line} \u2014 "${n.id}" matched more than once (columns ${n.keptColumn ?? "?"} and ${n.droppedColumn ?? "?"}); reported as one finding.`
2340
+ );
2341
+ }
2342
+ allFindings = collapsed.findings;
2343
+ redactFindingsEvidence(allFindings, sourceRedacted);
432
2344
  const riskScore = computeRiskScore(allFindings);
2345
+ const treeDigest = computeTreeDigest(files);
433
2346
  const degradedReasons = [];
434
2347
  if (skippedTooLarge > 0) {
435
2348
  const named = skippedTooLargeFiles.slice(0, 10).join(", ");
@@ -445,6 +2358,14 @@ async function scan(options, proRules, onProgress) {
445
2358
  detail: "File count or total size ceiling was reached; collection stopped early \u2014 results are incomplete."
446
2359
  });
447
2360
  }
2361
+ if (skippedSymlinks > 0) {
2362
+ const named = skippedSymlinkFiles.slice(0, 10).join(", ");
2363
+ const extra = skippedSymlinks > skippedSymlinkFiles.length || skippedSymlinkFiles.length > 10 ? ` (and others)` : "";
2364
+ degradedReasons.push({
2365
+ code: "SYMLINK_SKIPPED",
2366
+ detail: `${skippedSymlinks} symlink(s) were not followed (privacy moat) and were not scanned: ${named}${extra}`
2367
+ });
2368
+ }
448
2369
  if (coderefDegraded) {
449
2370
  degradedReasons.push({
450
2371
  code: "CODEREF_SKIPPED",
@@ -474,12 +2395,14 @@ async function scan(options, proRules, onProgress) {
474
2395
  filesScanned: files.length,
475
2396
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
476
2397
  policyUsed: policy.project.name,
477
- // Degraded when ANY of: coderef version-skip, collection truncation, OR a
478
- // file was skipped for being too large. The oversized-skip case (incident
479
- // f8fdaa6c/18e93b67) means a file was NOT scanned — the scan is incomplete,
480
- // so it must NOT be reported SAFE. Binary skips (skippedBinary) are NORMAL
481
- // and intentionally EXCLUDED — a binary file legitimately has no source to
482
- // scan. scan.ts OR-merges this with its own pro-fetch-failure flag.
2398
+ // Degraded when ANY of: coderef version-skip, collection truncation, a file
2399
+ // skipped for being too large, OR a symlink not followed (incident EDGE-1).
2400
+ // The oversized-skip case (incident f8fdaa6c/18e93b67) and the symlink-skip
2401
+ // case both mean content was NOT scanned — the scan is incomplete, so it must
2402
+ // NOT be reported SAFE. Binary skips (skippedBinary) are NORMAL and
2403
+ // intentionally EXCLUDED — a binary file legitimately has no source to scan.
2404
+ // scan.ts OR-merges this with its own pro-fetch-failure flag.
2405
+ treeDigest,
483
2406
  degraded: isDegraded,
484
2407
  // Machine-readable WHY for each degrade source — safe to key on in agent logic.
485
2408
  // scan.ts OR-merges its own PRO_RULES_UNAVAILABLE entry after pro-fetch failure.
@@ -488,140 +2411,15 @@ async function scan(options, proRules, onProgress) {
488
2411
  _skippedTooLarge: skippedTooLarge,
489
2412
  _skippedTooLargeFiles: skippedTooLargeFiles,
490
2413
  _skippedBinary: skippedBinary,
2414
+ _skippedBinaryFiles: skippedBinaryFiles,
2415
+ _skippedSymlinks: skippedSymlinks,
2416
+ _skippedSymlinkFiles: skippedSymlinkFiles,
491
2417
  _truncated: truncated
492
2418
  };
2419
+ applyVerdict(result);
493
2420
  return result;
494
2421
  }
495
2422
 
496
- // src/core/report.ts
497
- import { mkdir as mkdir2, writeFile as writeFile2 } from "fs/promises";
498
- import { dirname, basename, join as join3 } from "path";
499
- function severitySection(title, findings) {
500
- if (findings.length === 0) {
501
- return `## ${title}
502
-
503
- None
504
- `;
505
- }
506
- const entries = findings.map((f) => {
507
- const lines = [`### ${f.title}`];
508
- lines.push(`- **File:** ${f.file}${f.line != null ? `:${f.line}` : ""}`);
509
- lines.push(`- **Severity:** ${f.severity}`);
510
- if (f.evidence != null) lines.push(`- **Evidence:** \`${f.evidence}\``);
511
- lines.push(`- **Explanation:** ${f.explanation}`);
512
- lines.push(`- **Recommendation:** ${f.recommendation}`);
513
- return lines.join("\n");
514
- });
515
- return `## ${title}
516
-
517
- ${entries.join("\n\n")}
518
- `;
519
- }
520
- function buildFixOrder(findings) {
521
- const blocking = findings.filter((f) => f.blocking);
522
- const nonBlocking = findings.filter((f) => !f.blocking);
523
- const severityOrder = ["critical", "high", "medium", "low", "info"];
524
- const sorted = [
525
- ...blocking.sort((a, b) => severityOrder.indexOf(a.severity) - severityOrder.indexOf(b.severity)),
526
- ...nonBlocking.sort((a, b) => severityOrder.indexOf(a.severity) - severityOrder.indexOf(b.severity))
527
- ];
528
- if (sorted.length === 0) return "No findings to address.\n";
529
- 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");
530
- }
531
- function attitudeLine(recommendation) {
532
- if (recommendation === "SAFE_TO_SHIP") return "SHIP IT \u2014 nothing blocking. Go make something people want.";
533
- if (recommendation === "DO_NOT_SHIP") return "BLOCKED \u2014 shipping this would hurt. Fix the criticals first.";
534
- return `HOLD UP \u2014 findings need eyes before this ships.`;
535
- }
536
- function topThreeFindings(findings) {
537
- const severityOrder = ["critical", "high", "medium", "low", "info"];
538
- const sorted = [...findings].sort((a, b) => {
539
- if (a.blocking !== b.blocking) return a.blocking ? -1 : 1;
540
- return severityOrder.indexOf(a.severity) - severityOrder.indexOf(b.severity);
541
- });
542
- const top = sorted.slice(0, 3);
543
- if (top.length === 0) return "None \u2014 clean scan.\n";
544
- return top.map((f, i) => `${i + 1}. **${f.title}** (${f.severity}) \u2014 ${f.file}${f.line != null ? `:${f.line}` : ""}`).join("\n");
545
- }
546
- function severityBreakdownTable(riskScore) {
547
- const rows = [
548
- ["Critical", riskScore.criticalCount],
549
- ["High", riskScore.highCount],
550
- ["Medium", riskScore.mediumCount],
551
- ["Low", riskScore.lowCount],
552
- ["Info", riskScore.infoCount]
553
- ];
554
- const lines = ["| Severity | Count |", "|----------|-------|"];
555
- for (const [label, count] of rows) {
556
- lines.push(`| ${label} | ${count} |`);
557
- }
558
- return lines.join("\n");
559
- }
560
- function buildUserMarkdown(result, elapsedMs) {
561
- const { riskScore, findings, filesScanned, timestamp, recommendation } = result;
562
- const rec = recommendation ?? riskScore.recommendation;
563
- const elapsedStr = elapsedMs != null ? elapsedMs < 1e3 ? `${elapsedMs}ms` : `${(elapsedMs / 1e3).toFixed(1)}s` : "N/A";
564
- const critical = findings.filter((f) => f.severity === "critical");
565
- const high = findings.filter((f) => f.severity === "high");
566
- const medium = findings.filter((f) => f.severity === "medium");
567
- const low = findings.filter((f) => f.severity === "low");
568
- const sections = [
569
- "# ShipGuard Release Report",
570
- "",
571
- "## SUMMARY",
572
- "",
573
- `**Verdict:** ${rec} \u2014 ${attitudeLine(rec)}`,
574
- "",
575
- `**Files scanned:** ${filesScanned} | **Elapsed:** ${elapsedStr} | **Generated:** ${timestamp}`,
576
- "",
577
- "### Severity Breakdown",
578
- "",
579
- severityBreakdownTable(riskScore),
580
- "",
581
- `**Risk Score:** ${riskScore.score}/100 | **Total Findings:** ${riskScore.totalFindings}`,
582
- "",
583
- "### Top 3 Things to Fix",
584
- "",
585
- topThreeFindings(findings),
586
- "",
587
- "---",
588
- "",
589
- severitySection("Critical Findings", critical),
590
- severitySection("High Findings", high),
591
- severitySection("Medium Findings", medium),
592
- severitySection("Low Findings", low),
593
- "## Suggested Fix Order",
594
- "",
595
- buildFixOrder(findings),
596
- "",
597
- "## Final Recommendation",
598
- "",
599
- `**${rec}**`,
600
- ""
601
- ];
602
- return sections.join("\n");
603
- }
604
- function buildAgentJson(result) {
605
- const publicResult = { ...result };
606
- delete publicResult._skippedTooLarge;
607
- delete publicResult._skippedBinary;
608
- delete publicResult._truncated;
609
- return JSON.stringify(publicResult, null, 2);
610
- }
611
- async function generateReport(result, outputPath, elapsedMs) {
612
- const dir = dirname(outputPath);
613
- const base = basename(outputPath, ".md");
614
- const jsonPath = join3(dir, `${base}.json`);
615
- const mdContent = buildUserMarkdown(result, elapsedMs);
616
- const jsonContent = buildAgentJson(result);
617
- await mkdir2(dir, { recursive: true });
618
- await Promise.all([
619
- writeFile2(outputPath, mdContent, "utf-8"),
620
- writeFile2(jsonPath, jsonContent, "utf-8")
621
- ]);
622
- return { mdPath: outputPath, jsonPath };
623
- }
624
-
625
2423
  // src/core/sarif.ts
626
2424
  import { createHash } from "crypto";
627
2425
  var SARIF_SCHEMA = "https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0.json";
@@ -750,16 +2548,19 @@ function quickstartHelp(isTTY) {
750
2548
  lines.push("");
751
2549
  lines.push(` ${chalk.cyan("scan")} ${chalk.dim("[path]")} Scan a project for high-risk issues`);
752
2550
  lines.push(` ${chalk.cyan("init")} Generate a .shipguard.yml policy file`);
753
- lines.push(` ${chalk.cyan("login")} Authenticate to unlock Pro rules`);
2551
+ lines.push(` ${chalk.cyan("login")} Sign in to scan with the full rule corpus`);
754
2552
  lines.push(` ${chalk.cyan("logout")} Remove saved credentials`);
755
2553
  lines.push(` ${chalk.cyan("status")} Show auth status and credits`);
756
- lines.push(` ${chalk.cyan("feedback")} ${chalk.dim("<text>")} Send feedback on your last scan`);
2554
+ lines.push(` ${chalk.cyan("hook")} ${chalk.dim("--target")} Install the gate at the merge boundary`);
2555
+ lines.push(` ${chalk.cyan("schema")} ${chalk.dim("--json")} Print the machine-readable scan contract`);
2556
+ lines.push(` ${chalk.cyan("feedback")} Where to send feedback (GitHub issues)`);
757
2557
  lines.push(` ${chalk.cyan("rate")} ${chalk.dim("<id> up|down")} Rate a rule finding`);
2558
+ lines.push(` ${chalk.cyan("telemetry")} ${chalk.dim("status")} Show or change the pseudonymous usage ping`);
758
2559
  lines.push(` ${chalk.cyan("help")} ${chalk.dim("/ ?")} Show this screen`);
759
2560
  lines.push("");
760
2561
  lines.push(chalk.bold(" Exit codes (verdict-neutral \u2014 read the JSON for the verdict):"));
761
2562
  lines.push(` ${chalk.green("0")} Scan completed \u2014 verdict is in the JSON \`recommendation\` field`);
762
- lines.push(` ${chalk.yellow("1")} Blocked \u2014 ONLY with --strict + blocking findings`);
2563
+ lines.push(` ${chalk.yellow("1")} Blocked \u2014 ONLY with --strict, on blocking findings or an unfinished scan`);
763
2564
  lines.push(` ${chalk.red("2")} Config error`);
764
2565
  lines.push(` ${chalk.red("3")} Runtime error \u2014 scan could not meaningfully run`);
765
2566
  lines.push("");
@@ -784,11 +2585,14 @@ function quickstartHelp(isTTY) {
784
2585
  lines.push(" login Authenticate");
785
2586
  lines.push(" logout Remove credentials");
786
2587
  lines.push(" status Auth status + credits");
787
- lines.push(" feedback <text> Send feedback");
2588
+ lines.push(" hook --target Install the gate at the merge boundary");
2589
+ lines.push(" schema --json Machine-readable scan contract");
2590
+ lines.push(" feedback Where to send feedback (GitHub issues)");
788
2591
  lines.push(" rate <id> up|down Rate a finding");
2592
+ lines.push(" telemetry status|enable|disable|reset Pseudonymous usage ping");
789
2593
  lines.push(" help / ? Show this screen");
790
2594
  lines.push("");
791
- lines.push(" Exit codes: 0=completed (verdict in JSON) 1=blocked (--strict only) 2=config-error 3=runtime-error");
2595
+ lines.push(" Exit codes: 0=completed (verdict in JSON) 1=blocked (--strict only: blocking findings or unfinished scan) 2=config-error 3=runtime-error");
792
2596
  lines.push("");
793
2597
  lines.push(` Docs: ${DOCS_URL}`);
794
2598
  lines.push(` Site: ${SITE_URL}`);
@@ -875,10 +2679,12 @@ function findingsByCategoryTable(findings) {
875
2679
  return lines.join("\n");
876
2680
  }
877
2681
  function coverageLine() {
2682
+ const bundled = bundledRulesMeta();
878
2683
  return chalk.dim(
879
- ` Coverage: secrets, auth, payments, database, deployment (free tier).
880
- Deeper agentic rules available via Pro \u2014 some issue classes may be missed on free.
881
- Upgrade: ${chalk.underline(PRICING_URL)}`
2684
+ ` Coverage: ${bundled.ruleCount} bundled rules from the maintained corpus, plus local checks
2685
+ for secrets, auth, payments, database and deployment. Runs offline, no account needed.
2686
+ \`shipguard login\` scans against the full current corpus, not just the offline subset.
2687
+ Plans: ${chalk.underline(PRICING_URL)}`
882
2688
  );
883
2689
  }
884
2690
  var VERDICT_CONFIG = {
@@ -949,24 +2755,15 @@ function severityBar(riskScore, barWidth = 30) {
949
2755
  }).join(" ");
950
2756
  return ` ${bar} ${legend}`;
951
2757
  }
952
- function verdictPanel(result, elapsedMs, skippedCount, topFindings, strict) {
2758
+ function verdictPanel(result, elapsedMs, skippedCount, topFindings, strict, reportPaths) {
953
2759
  const { riskScore, filesScanned } = result;
954
- const recommendation = riskScore.recommendation;
2760
+ const recommendation = effectiveRecommendation(result);
2761
+ const degraded = result.degraded === true;
955
2762
  const cfg = VERDICT_CONFIG[recommendation];
956
2763
  const elapsedStr = elapsedMs < 1e3 ? `${elapsedMs}ms` : `${(elapsedMs / 1e3).toFixed(1)}s`;
957
2764
  const lines = [""];
958
2765
  lines.push(boxTop());
959
2766
  lines.push(boxLine(chalk.bold(" ShipGuard \u2014 Release Gate Report")));
960
- lines.push(boxEmpty());
961
- const verdictLabel = cfg.color(chalk.bold(`${cfg.icon} ${cfg.label}`));
962
- lines.push(boxLine(` ${verdictLabel}`));
963
- if (riskScore.blockingCount > 0 && !strict) {
964
- lines.push(boxLine(chalk.dim(" (informational \u2014 exit 0; use --strict to enforce as exit 1)")));
965
- }
966
- lines.push(boxEmpty());
967
- const attitudeLine2 = recommendation === "REVIEW_BEFORE_SHIP" ? cfg.attitudeLine(riskScore.blockingCount) : cfg.attitudeLine();
968
- lines.push(boxLine(attitudeLine2));
969
- lines.push(boxEmpty());
970
2767
  lines.push(boxSection());
971
2768
  lines.push(boxLine(chalk.bold(" Severity breakdown")));
972
2769
  lines.push(boxLine(severityBar(riskScore)));
@@ -987,12 +2784,36 @@ function verdictPanel(result, elapsedMs, skippedCount, topFindings, strict) {
987
2784
  }
988
2785
  lines.push(boxSection());
989
2786
  lines.push(boxLine(chalk.bold(" How ShipGuard helped")));
990
- lines.push(boxLine(cfg.helpLine(riskScore.blockingCount)));
2787
+ if (degraded) {
2788
+ lines.push(boxLine(chalk.red(" Incomplete scan \u2014 verdict is fail-closed until this is fixed:")));
2789
+ for (const reason of result.degradedReasons ?? []) {
2790
+ lines.push(boxLine(chalk.red(` \xB7 ${reason.code}${reason.detail ? ` \u2014 ${truncate(reason.detail, 60)}` : ""}`)));
2791
+ }
2792
+ if ((result.degradedReasons ?? []).length === 0) {
2793
+ lines.push(boxLine(chalk.red(" \xB7 reason not recorded \u2014 see `degraded` in --json output")));
2794
+ }
2795
+ } else {
2796
+ lines.push(boxLine(cfg.helpLine(riskScore.blockingCount)));
2797
+ }
2798
+ if (reportPaths) {
2799
+ lines.push(boxSection());
2800
+ lines.push(boxLine(chalk.bold(" Report written")));
2801
+ lines.push(boxLine(` ${truncatePath(reportPaths.mdPath, 68)}`));
2802
+ lines.push(boxLine(chalk.dim(` agent view: ${truncatePath(reportPaths.runJsonPath, 56)}`)));
2803
+ }
991
2804
  lines.push(boxSection());
992
2805
  lines.push(boxLine(chalk.bold(" Learn more")));
993
2806
  lines.push(boxLine(` Docs ${chalk.underline(DOCS_URL)}`));
994
2807
  lines.push(boxLine(` Site ${chalk.underline(SITE_URL)}`));
995
2808
  lines.push(boxLine(` Pricing ${chalk.underline(PRICING_URL)}`));
2809
+ lines.push(boxSection());
2810
+ const verdictLabel = cfg.color(chalk.bold(`${cfg.icon} ${cfg.label}`));
2811
+ lines.push(boxLine(` ${verdictLabel}`));
2812
+ if ((riskScore.blockingCount > 0 || degraded) && !strict) {
2813
+ lines.push(boxLine(chalk.dim(" (informational \u2014 exit 0; use --strict to enforce as exit 1)")));
2814
+ }
2815
+ const attitudeLine2 = degraded ? chalk.red(" INCOMPLETE \u2014 parts of this scan did not run, so it cannot say this is safe.") : recommendation === "REVIEW_BEFORE_SHIP" ? cfg.attitudeLine(riskScore.blockingCount) : cfg.attitudeLine();
2816
+ lines.push(boxLine(attitudeLine2));
996
2817
  lines.push(boxEmpty());
997
2818
  lines.push(boxBottom());
998
2819
  lines.push("");
@@ -1013,8 +2834,8 @@ function actionFooter(opts) {
1013
2834
  lines.push(` ${chalk.cyan('shipguard feedback "<thoughts>"')} ${chalk.dim("# what do you think?")}`);
1014
2835
  if (!isLoggedIn) {
1015
2836
  lines.push("");
1016
- lines.push(` ${chalk.yellow("shipguard login")} ${chalk.dim("# unlock Pro rules")}`);
1017
- lines.push(` ${chalk.yellow("shipguard scan --pro")} ${chalk.dim("# deeper checks after login")}`);
2837
+ lines.push(` ${chalk.yellow("shipguard login")} ${chalk.dim("# sign in for the full rule corpus")}`);
2838
+ lines.push(` ${chalk.yellow("shipguard scan --pro")} ${chalk.dim("# scan with it (uses one scan credit)")}`);
1018
2839
  }
1019
2840
  lines.push("");
1020
2841
  lines.push(` ${chalk.dim("Full docs: " + DOCS_URL)}`);
@@ -1054,23 +2875,26 @@ function welcomeBanner(configDir) {
1054
2875
  empty,
1055
2876
  bannerLine(chalk.bold("Quick start:")),
1056
2877
  bannerLine(` ${chalk.green("shipguard scan <path>")} Run a scan on your project`),
1057
- bannerLine(` ${chalk.green("shipguard login")} Unlock Pro rules`),
2878
+ bannerLine(` ${chalk.green("shipguard login")} Scan with the full rule corpus`),
1058
2879
  bannerLine(` ${chalk.green("shipguard scan --json")} Machine-readable output for CI/agents`),
1059
2880
  empty,
1060
2881
  bannerLine(`Docs: ${chalk.underline(DOCS_URL)}`),
1061
2882
  empty,
1062
- bannerLine(chalk.dim("Anonymous usage ping enabled \u2014 opt out: SHIPGUARD_TELEMETRY=0")),
1063
- bannerLine(chalk.dim(`Details: ${chalk.underline("agenticcli.dev/docs#telemetry")}`)),
2883
+ bannerLine(chalk.dim("Pseudonymous usage ping \u2014 opt out: shipguard telemetry disable")),
2884
+ bannerLine(chalk.dim(`or SHIPGUARD_TELEMETRY=0 \xB7 Details: ${chalk.underline("agenticcli.dev/docs#telemetry")}`)),
1064
2885
  bottom,
1065
2886
  ""
1066
2887
  ].join("\n");
1067
2888
  }
1068
2889
  function quietVerdict(result, strict) {
1069
- const { recommendation, score, totalFindings, blockingCount } = result.riskScore;
2890
+ const { score, totalFindings, blockingCount } = result.riskScore;
2891
+ const recommendation = effectiveRecommendation(result);
2892
+ const degraded = result.degraded === true;
1070
2893
  const icon = recommendation === "SAFE_TO_SHIP" ? "\u2705" : recommendation === "DO_NOT_SHIP" ? "\u26D4" : "\u26A0\uFE0F";
1071
2894
  const colorFn = recommendation === "SAFE_TO_SHIP" ? chalk.green : recommendation === "DO_NOT_SHIP" ? chalk.red : chalk.yellow;
2895
+ const degradedNote = degraded ? " incomplete=yes" : "";
1072
2896
  const suffix = blockingCount > 0 && !strict ? " (informational \u2014 exit 0; use --strict to enforce)" : "";
1073
- return colorFn(`${icon} ${recommendation.replace(/_/g, " ")} score=${score}/100 findings=${totalFindings} blocking=${blockingCount}${suffix}`);
2897
+ return colorFn(`${icon} ${recommendation.replace(/_/g, " ")} score=${score}/100 findings=${totalFindings} blocking=${blockingCount}${degradedNote}${suffix}`);
1074
2898
  }
1075
2899
  function truncate(str, maxLen) {
1076
2900
  return str.length <= maxLen ? str : `${str.slice(0, maxLen - 3)}...`;
@@ -1143,9 +2967,6 @@ function displayWidth(str) {
1143
2967
  return width;
1144
2968
  }
1145
2969
 
1146
- // src/core/history/index.ts
1147
- import { createHash as createHash5 } from "crypto";
1148
-
1149
2970
  // src/core/history/schema.ts
1150
2971
  var CURRENT_SCHEMA_VERSION = 2;
1151
2972
  var MIGRATION_1_INIT = `
@@ -1241,9 +3062,9 @@ function resolveHistoryPath(cwd, policy) {
1241
3062
 
1242
3063
  // src/core/history/identity.ts
1243
3064
  import { execFileSync as execFileSync2 } from "child_process";
1244
- import { createHash as createHash2, randomUUID } from "crypto";
3065
+ import { createHash as createHash2, randomUUID as randomUUID2 } from "crypto";
1245
3066
  import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync, writeFileSync as writeFileSync2 } from "fs";
1246
- import { dirname as dirname2, join as join5 } from "path";
3067
+ import { dirname as dirname3, join as join5 } from "path";
1247
3068
  function tryGit(cwd, args) {
1248
3069
  try {
1249
3070
  return execFileSync2("git", args, { cwd, encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }).trim();
@@ -1281,23 +3102,23 @@ function resolveRepoIdentity(cwd) {
1281
3102
  return { repoId: existing, repoIdKind: "fallback-uuid", remoteLabel };
1282
3103
  }
1283
3104
  }
1284
- const id = randomUUID();
1285
- mkdirSync2(dirname2(fallbackPath), { recursive: true });
3105
+ const id = randomUUID2();
3106
+ mkdirSync2(dirname3(fallbackPath), { recursive: true });
1286
3107
  writeFileSync2(fallbackPath, `${id}
1287
3108
  `, "utf-8");
1288
3109
  ensureGitignored(cwd, ".shipguard/");
1289
3110
  return { repoId: id, repoIdKind: "fallback-uuid", remoteLabel };
1290
3111
  } catch (err) {
1291
3112
  logger.warn(`Could not persist fallback repo identity: ${err instanceof Error ? err.message : err}`);
1292
- return { repoId: randomUUID(), repoIdKind: "fallback-uuid", remoteLabel };
3113
+ return { repoId: randomUUID2(), repoIdKind: "fallback-uuid", remoteLabel };
1293
3114
  }
1294
3115
  }
1295
3116
  function resolveContentIdentity(cwd, excludePrefixes = []) {
1296
3117
  const headSha = tryGit(cwd, ["rev-parse", "HEAD"]);
1297
3118
  if (!headSha) return void 0;
1298
- const raw = tryGit(cwd, ["status", "--porcelain", "-z"]) ?? "";
3119
+ const raw2 = tryGit(cwd, ["status", "--porcelain", "-z"]) ?? "";
1299
3120
  const normalizedExcludes = excludePrefixes.map((p) => p.replace(/\\/g, "/").replace(/^\.\//, "")).filter(Boolean);
1300
- const records = raw.split("\0").filter(Boolean);
3121
+ const records = raw2.split("\0").filter(Boolean);
1301
3122
  const kept = records.filter((rec) => {
1302
3123
  const path = rec.length > 3 ? rec.slice(3) : rec;
1303
3124
  return !normalizedExcludes.some((ex) => path === ex || path === ex.replace(/\/$/, "") || path.startsWith(ex));
@@ -1321,9 +3142,9 @@ function computeScopeFingerprint(input) {
1321
3142
  }
1322
3143
 
1323
3144
  // src/core/history/store.ts
1324
- import { randomUUID as randomUUID2 } from "crypto";
3145
+ import { randomUUID as randomUUID3 } from "crypto";
1325
3146
  import { existsSync as existsSync4, mkdirSync as mkdirSync3 } from "fs";
1326
- import { dirname as dirname3 } from "path";
3147
+ import { dirname as dirname4 } from "path";
1327
3148
  var sqliteModulePromise;
1328
3149
  var warningFilterInstalled = false;
1329
3150
  function installSqliteWarningFilter() {
@@ -1375,7 +3196,7 @@ var HistoryStore = class _HistoryStore {
1375
3196
  }
1376
3197
  const preExisted = existsSync4(dbPath);
1377
3198
  try {
1378
- mkdirSync3(dirname3(dbPath), { recursive: true });
3199
+ mkdirSync3(dirname4(dbPath), { recursive: true });
1379
3200
  } catch (err) {
1380
3201
  return {
1381
3202
  ok: false,
@@ -1598,7 +3419,7 @@ var HistoryStore = class _HistoryStore {
1598
3419
  return { ok: true, scanId: row.scan_id, reused: true };
1599
3420
  }
1600
3421
  }
1601
- const scanId = randomUUID2();
3422
+ const scanId = randomUUID3();
1602
3423
  this.db.prepare(
1603
3424
  `INSERT INTO scan_id_reservations (repo_id, reuse_key, scan_id, created_at) VALUES (?, ?, ?, ?)
1604
3425
  ON CONFLICT(repo_id, reuse_key) DO UPDATE SET scan_id = excluded.scan_id, created_at = excluded.created_at`
@@ -1722,7 +3543,7 @@ function computeRegressionResult(current, baseline) {
1722
3543
  }
1723
3544
 
1724
3545
  // src/core/history/scan-id.ts
1725
- import { createHash as createHash4, randomUUID as randomUUID3 } from "crypto";
3546
+ import { createHash as createHash4, randomUUID as randomUUID4 } from "crypto";
1726
3547
  import { relative } from "path";
1727
3548
  function computeScanIdReuseKey(input) {
1728
3549
  const normalized = {
@@ -1757,7 +3578,7 @@ async function resolveScanId(input) {
1757
3578
  const excludePrefixes = [".shipguard/", historyRelPath];
1758
3579
  const contentIdentity = resolveContentIdentity(cwd, excludePrefixes);
1759
3580
  if (!contentIdentity) {
1760
- return { scanId: randomUUID3(), scanIdReused: false };
3581
+ return { scanId: randomUUID4(), scanIdReused: false };
1761
3582
  }
1762
3583
  const identity = resolveRepoIdentity(cwd);
1763
3584
  const reuseKey = computeScanIdReuseKey({
@@ -1772,14 +3593,14 @@ async function resolveScanId(input) {
1772
3593
  const openResult = await HistoryStore.open(historyPath, cliVersion);
1773
3594
  if (!openResult.ok) {
1774
3595
  logger.warn(`ShipGuard scanId persistence unavailable (${openResult.status}) \u2014 minting a fresh scanId: ${openResult.reason}`);
1775
- return { scanId: randomUUID3(), scanIdReused: false };
3596
+ return { scanId: randomUUID4(), scanIdReused: false };
1776
3597
  }
1777
3598
  const store = openResult.store;
1778
3599
  try {
1779
3600
  const result = store.reserveScanId(identity.repoId, reuseKey, reuseWindowMs);
1780
3601
  if (!result.ok) {
1781
3602
  logger.warn(`ShipGuard scanId persistence failed \u2014 minting a fresh scanId: ${result.reason}`);
1782
- return { scanId: randomUUID3(), scanIdReused: false };
3603
+ return { scanId: randomUUID4(), scanIdReused: false };
1783
3604
  }
1784
3605
  return { scanId: result.scanId, scanIdReused: result.reused };
1785
3606
  } finally {
@@ -1789,7 +3610,7 @@ async function resolveScanId(input) {
1789
3610
  logger.warn(
1790
3611
  `ShipGuard scanId persistence failed unexpectedly \u2014 minting a fresh scanId: ${err instanceof Error ? err.message : err}`
1791
3612
  );
1792
- return { scanId: randomUUID3(), scanIdReused: false };
3613
+ return { scanId: randomUUID4(), scanIdReused: false };
1793
3614
  }
1794
3615
  }
1795
3616
 
@@ -1798,10 +3619,6 @@ function isActive(finding) {
1798
3619
  if (finding.suppressionState) return finding.suppressionState === "active";
1799
3620
  return !finding.suppressed;
1800
3621
  }
1801
- function computeFindingKey(finding) {
1802
- const basis = finding.evidence && finding.evidence.length > 0 ? finding.evidence : finding.title;
1803
- return createHash5("sha256").update(basis).digest("hex").slice(0, 16);
1804
- }
1805
3622
  function buildRuleOutcomes(policy, proRules, proApplied, cliVersion, corpusVersion, result) {
1806
3623
  const outcomes = [];
1807
3624
  const countActive = (ruleId) => result.findings.filter((f) => f.id === ruleId && isActive(f)).length;
@@ -1854,7 +3671,7 @@ async function recordScanHistory(input) {
1854
3671
  const ruleVersionById = new Map(ruleOutcomes.map((ro) => [ro.ruleId, ro.ruleVersion]));
1855
3672
  const findingRows = result.findings.map((f) => ({
1856
3673
  ruleId: f.id,
1857
- findingKey: computeFindingKey(f),
3674
+ findingKey: getFindingKey(f),
1858
3675
  filePath: f.file,
1859
3676
  severity: f.severity,
1860
3677
  blocking: Boolean(f.blocking),
@@ -1907,56 +3724,338 @@ async function recordScanHistory(input) {
1907
3724
  const regressionResult = computeRegressionResult(currentSnapshot, baseline);
1908
3725
  return { stateStatus, ...regressionResult };
1909
3726
  } catch (err) {
1910
- logger.warn(
1911
- `ShipGuard history recording failed unexpectedly \u2014 this scan's findings/verdict are unaffected: ${err instanceof Error ? err.message : err}`
1912
- );
1913
- return {
1914
- stateStatus: "unavailable",
1915
- regressionCheckSkipped: true,
1916
- regressionCheckSkippedReason: "state-unavailable",
1917
- regressions: [],
1918
- coverageChanged: []
1919
- };
1920
- } finally {
1921
- store.close();
3727
+ logger.warn(
3728
+ `ShipGuard history recording failed unexpectedly \u2014 this scan's findings/verdict are unaffected: ${err instanceof Error ? err.message : err}`
3729
+ );
3730
+ return {
3731
+ stateStatus: "unavailable",
3732
+ regressionCheckSkipped: true,
3733
+ regressionCheckSkippedReason: "state-unavailable",
3734
+ regressions: [],
3735
+ coverageChanged: []
3736
+ };
3737
+ } finally {
3738
+ store.close();
3739
+ }
3740
+ }
3741
+
3742
+ // src/core/telemetry.ts
3743
+ import { randomUUID as randomUUID6 } from "crypto";
3744
+
3745
+ // src/core/telemetry-config.ts
3746
+ import { randomUUID as randomUUID5 } from "crypto";
3747
+ import { chmodSync, existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync2, writeFileSync as writeFileSync3 } from "fs";
3748
+ import { homedir as homedir2 } from "os";
3749
+ import { join as join6 } from "path";
3750
+ import YAML2 from "yaml";
3751
+ var CONFIG_FILE = "telemetry.json";
3752
+ var NOTICE_MARKER = "telemetry-notice-shown";
3753
+ function getConfigDir() {
3754
+ return join6(homedir2(), ".config", "shipguard");
3755
+ }
3756
+ function configFilePath(dir = getConfigDir()) {
3757
+ return join6(dir, CONFIG_FILE);
3758
+ }
3759
+ function readUserConfig(dir = getConfigDir()) {
3760
+ const file = configFilePath(dir);
3761
+ try {
3762
+ if (!existsSync5(file)) return {};
3763
+ const parsed = JSON.parse(readFileSync2(file, "utf-8"));
3764
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
3765
+ } catch (err) {
3766
+ logger.debug(`telemetry: ignoring unreadable ${file}: ${err instanceof Error ? err.message : String(err)}`);
3767
+ return {};
3768
+ }
3769
+ }
3770
+ function userConfigUnreadable(dir = getConfigDir()) {
3771
+ const file = configFilePath(dir);
3772
+ try {
3773
+ if (!existsSync5(file)) return false;
3774
+ const parsed = JSON.parse(readFileSync2(file, "utf-8"));
3775
+ return !(parsed && typeof parsed === "object" && !Array.isArray(parsed));
3776
+ } catch {
3777
+ return true;
3778
+ }
3779
+ }
3780
+ var UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
3781
+ function writeConfig(dir, next) {
3782
+ const file = configFilePath(dir);
3783
+ mkdirSync4(dir, { recursive: true, mode: 448 });
3784
+ writeFileSync3(file, JSON.stringify(next, null, 2) + "\n", { encoding: "utf-8", mode: 384 });
3785
+ chmodSync(file, 384);
3786
+ return file;
3787
+ }
3788
+ function readInstallId(dir = getConfigDir()) {
3789
+ const id = readUserConfig(dir).installId;
3790
+ return typeof id === "string" && UUID_V4.test(id) ? id : void 0;
3791
+ }
3792
+ function getOrCreateInstallId(dir = getConfigDir()) {
3793
+ const existing = readInstallId(dir);
3794
+ if (existing) return existing;
3795
+ try {
3796
+ const installId = randomUUID5();
3797
+ writeConfig(dir, { ...readUserConfig(dir), installId });
3798
+ return installId;
3799
+ } catch (err) {
3800
+ logger.debug(`telemetry: could not persist the install id: ${err instanceof Error ? err.message : String(err)}`);
3801
+ return void 0;
3802
+ }
3803
+ }
3804
+ function resetInstallId(dir = getConfigDir()) {
3805
+ const cfg = readUserConfig(dir);
3806
+ const hadId = "installId" in cfg;
3807
+ const oldId = readInstallId(dir);
3808
+ if (hadId) {
3809
+ delete cfg.installId;
3810
+ writeConfig(dir, cfg);
3811
+ }
3812
+ return { hadId, oldId };
3813
+ }
3814
+ function writeUserEnabled(dir, enabled) {
3815
+ return writeConfig(dir, { ...readUserConfig(dir), enabled });
3816
+ }
3817
+ function noticeShown(dir = getConfigDir()) {
3818
+ return existsSync5(join6(dir, NOTICE_MARKER));
3819
+ }
3820
+ function markNoticeShown(dir = getConfigDir()) {
3821
+ try {
3822
+ mkdirSync4(dir, { recursive: true, mode: 448 });
3823
+ writeFileSync3(join6(dir, NOTICE_MARKER), "1\n", { encoding: "utf-8", mode: 384 });
3824
+ } catch (err) {
3825
+ logger.debug(`telemetry: could not persist the notice marker: ${err instanceof Error ? err.message : String(err)}`);
3826
+ }
3827
+ }
3828
+ var FALSE_LIKE = /* @__PURE__ */ new Set(["false", "off", "no", "0"]);
3829
+ var GENERATED_CONFIG_FILE = ".shipguard.yml";
3830
+ function policyTelemetryEnabled(policy) {
3831
+ if (!policy || typeof policy !== "object") return void 0;
3832
+ const t = policy.telemetry;
3833
+ if (!t || typeof t !== "object") return void 0;
3834
+ const v = t.enabled;
3835
+ if (v === false || v === 0) return false;
3836
+ if (typeof v === "string" && FALSE_LIKE.has(v.trim().toLowerCase())) return false;
3837
+ if (v === true) return true;
3838
+ return void 0;
3839
+ }
3840
+ function readYamlToggle(file) {
3841
+ try {
3842
+ if (!existsSync5(file)) return void 0;
3843
+ return policyTelemetryEnabled(YAML2.parse(readFileSync2(file, "utf-8")));
3844
+ } catch (err) {
3845
+ logger.debug(`telemetry: ignoring unreadable ${file}: ${err instanceof Error ? err.message : String(err)}`);
3846
+ return void 0;
3847
+ }
3848
+ }
3849
+ function projectTelemetryEnabled(input) {
3850
+ const values = [policyTelemetryEnabled(input.policy)];
3851
+ if (input.projectDir) {
3852
+ if (input.policy === void 0) values.push(readYamlToggle(join6(input.projectDir, DEFAULT_POLICY_PATH)));
3853
+ values.push(readYamlToggle(join6(input.projectDir, GENERATED_CONFIG_FILE)));
1922
3854
  }
3855
+ if (values.includes(false)) return false;
3856
+ if (values.includes(true)) return true;
3857
+ return void 0;
1923
3858
  }
1924
3859
 
1925
3860
  // src/core/telemetry.ts
1926
- function shouldSendTelemetry() {
1927
- if (process.env.SHIPGUARD_TELEMETRY === "0") return false;
1928
- if (process.env.DO_NOT_TRACK === "1") return false;
1929
- return true;
3861
+ var IS_PUBLISHED_BUILD = true;
3862
+ function getProvenance(published = IS_PUBLISHED_BUILD) {
3863
+ return published ? "published" : "dev";
3864
+ }
3865
+ var PROD_TELEMETRY_ENDPOINT = "https://cheery-toucan-348.convex.site/cli-telemetry";
3866
+ function isLoopbackUrl(raw2) {
3867
+ if (!raw2) return false;
3868
+ try {
3869
+ const host = new URL(raw2).hostname;
3870
+ return host === "127.0.0.1" || host === "localhost" || host === "[::1]" || host === "::1";
3871
+ } catch {
3872
+ return false;
3873
+ }
3874
+ }
3875
+ function resolveEndpoint(published = IS_PUBLISHED_BUILD, env = process.env) {
3876
+ const override = env.SHIPGUARD_TELEMETRY_URL;
3877
+ if (published) return override || PROD_TELEMETRY_ENDPOINT;
3878
+ return isLoopbackUrl(override) ? override : null;
3879
+ }
3880
+ var ALLOWED_KEYS = [
3881
+ "schema",
3882
+ "eventId",
3883
+ "installId",
3884
+ "cliVersion",
3885
+ "provenance",
3886
+ "verdict",
3887
+ "durationBucket",
3888
+ "ci"
3889
+ ];
3890
+ var VERSION_RE = /^(0|[1-9]\d{0,2})\.(0|[1-9]\d{0,2})\.(0|[1-9]\d{0,2})(-[0-9A-Za-z.-]{1,24})?$/;
3891
+ var DURATION_BUCKETS = ["lt1s", "1to5s", "5to30s", "gt30s"];
3892
+ function durationBucket(ms) {
3893
+ if (!(ms >= 1e3)) return "lt1s";
3894
+ if (ms < 5e3) return "1to5s";
3895
+ if (ms < 3e4) return "5to30s";
3896
+ return "gt30s";
3897
+ }
3898
+ var CI_PROVIDER_VARS = [
3899
+ "GITHUB_ACTIONS",
3900
+ "GITLAB_CI",
3901
+ "CIRCLECI",
3902
+ "TRAVIS",
3903
+ "BUILDKITE",
3904
+ "JENKINS_URL",
3905
+ "TF_BUILD",
3906
+ "TEAMCITY_VERSION",
3907
+ "BITBUCKET_BUILD_NUMBER",
3908
+ "APPVEYOR",
3909
+ "DRONE",
3910
+ "CODEBUILD_BUILD_ID",
3911
+ "SEMAPHORE",
3912
+ "BUILD_BUILDID",
3913
+ "CF_BUILD_ID",
3914
+ "NETLIFY",
3915
+ "VERCEL",
3916
+ "WOODPECKER",
3917
+ "BUDDY",
3918
+ "HUDSON_URL"
3919
+ ];
3920
+ function detectCi(env = process.env) {
3921
+ const ci = env.CI;
3922
+ if (ci !== void 0 && !["", "0", "false"].includes(ci.trim().toLowerCase())) return true;
3923
+ return CI_PROVIDER_VARS.some((k) => env[k] !== void 0);
3924
+ }
3925
+ function isTruthyOff(v, offValues) {
3926
+ return v !== void 0 && offValues.includes(v.trim().toLowerCase());
3927
+ }
3928
+ function envOptOut(env) {
3929
+ if (isTruthyOff(env.SHIPGUARD_TELEMETRY, ["0", "false"])) return "env:SHIPGUARD_TELEMETRY";
3930
+ if (isTruthyOff(env.DO_NOT_TRACK, ["1", "true"])) return "env:DO_NOT_TRACK";
3931
+ return null;
1930
3932
  }
1931
3933
  function buildPayload(input) {
1932
- const { cliVersion, verdict, durationMs, ci, rulePackCount } = input;
1933
- return { cliVersion, verdict, durationMs, ci, rulePackCount };
1934
- }
1935
- function sendTelemetry(payload) {
1936
- if (!shouldSendTelemetry()) return;
1937
- const endpoint = process.env.SHIPGUARD_TELEMETRY_URL ?? "https://cheery-toucan-348.convex.site/cli-telemetry";
1938
- const body = JSON.stringify(buildPayload(payload));
1939
- const controller = new AbortController();
1940
- const timeout = setTimeout(() => controller.abort(), 1e3);
1941
- fetch(endpoint, {
1942
- method: "POST",
1943
- headers: { "Content-Type": "application/json" },
1944
- body,
1945
- signal: controller.signal
1946
- }).catch(() => {
1947
- if (process.env.SHIPGUARD_DEBUG) {
1948
- console.debug("[shipguard:telemetry] ping failed (silent)");
1949
- }
1950
- }).finally(() => {
1951
- clearTimeout(timeout);
1952
- });
3934
+ const { schema, eventId, installId, cliVersion, provenance, verdict, durationBucket: durationBucket2, ci } = input;
3935
+ return { schema, eventId, installId, cliVersion, provenance, verdict, durationBucket: durationBucket2, ci };
3936
+ }
3937
+ function validatePayload(payload) {
3938
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return false;
3939
+ const obj = payload;
3940
+ const keys = Object.keys(obj);
3941
+ if (keys.length !== ALLOWED_KEYS.length) return false;
3942
+ for (const k of ALLOWED_KEYS) if (!(k in obj)) return false;
3943
+ if (obj.schema !== 2) return false;
3944
+ if (typeof obj.eventId !== "string" || !UUID_V4.test(obj.eventId)) return false;
3945
+ if (typeof obj.ci !== "boolean") return false;
3946
+ if (obj.ci) {
3947
+ if (obj.installId !== null) return false;
3948
+ } else if (typeof obj.installId !== "string" || !UUID_V4.test(obj.installId)) {
3949
+ return false;
3950
+ }
3951
+ if (typeof obj.cliVersion !== "string" || obj.cliVersion.length > 40 || !VERSION_RE.test(obj.cliVersion)) return false;
3952
+ if (obj.provenance !== "published" && obj.provenance !== "dev") return false;
3953
+ if (!["safe", "review", "blocked", "error"].includes(obj.verdict)) return false;
3954
+ if (!DURATION_BUCKETS.includes(obj.durationBucket)) return false;
3955
+ return true;
3956
+ }
3957
+ function decideTelemetry(input = {}) {
3958
+ const env = input.env ?? process.env;
3959
+ const envOff = envOptOut(env);
3960
+ if (envOff) return { enabled: false, source: envOff };
3961
+ const dir = input.configDir ?? getConfigDir();
3962
+ if (userConfigUnreadable(dir) || readUserConfig(dir).enabled === false) {
3963
+ return { enabled: false, source: "user-config" };
3964
+ }
3965
+ if (projectTelemetryEnabled({ policy: input.policy, projectDir: input.projectDir }) === false) return { enabled: false, source: "project-policy" };
3966
+ return { enabled: true, source: "default" };
3967
+ }
3968
+ var NOTICE_TEXT = "shipguard: sends a pseudonymous usage ping after each scan (version, verdict, duration bucket, a random install id outside CI; never code, paths or your account). Turn it off: SHIPGUARD_TELEMETRY=0, DO_NOT_TRACK=1, or `shipguard telemetry disable`. https://agenticcli.dev/docs#telemetry";
3969
+ var PING_WAIT_MS = 1500;
3970
+ var FETCH_TIMEOUT_MS = 1e3;
3971
+ function debugEnabled(env) {
3972
+ const v = env.SHIPGUARD_TELEMETRY_DEBUG;
3973
+ return Boolean(v) && v !== "0";
3974
+ }
3975
+ function sendTelemetry(input, opts = {}) {
3976
+ try {
3977
+ const env = opts.env ?? process.env;
3978
+ const configDir = opts.configDir ?? getConfigDir();
3979
+ const published = opts.published ?? IS_PUBLISHED_BUILD;
3980
+ const debug = debugEnabled(env);
3981
+ const decision = decideTelemetry({ env, configDir, policy: opts.policy, projectDir: opts.projectDir });
3982
+ if (!decision.enabled) {
3983
+ if (debug) process.stderr.write(`[shipguard:telemetry] disabled (${decision.source}); nothing would be sent
3984
+ `);
3985
+ return Promise.resolve();
3986
+ }
3987
+ const endpoint = resolveEndpoint(published, env);
3988
+ const ci = detectCi(env);
3989
+ const base = {
3990
+ schema: 2,
3991
+ eventId: randomUUID6(),
3992
+ cliVersion: input.cliVersion,
3993
+ provenance: getProvenance(published),
3994
+ verdict: input.verdict,
3995
+ durationBucket: durationBucket(input.durationMs),
3996
+ ci
3997
+ };
3998
+ if (debug) {
3999
+ const stored = ci ? null : readInstallId(configDir);
4000
+ const installId2 = ci ? null : stored ?? randomUUID6();
4001
+ const note = !ci && !stored ? " (installId is a preview: none saved yet, one is created on the first real ping)" : "";
4002
+ process.stderr.write(
4003
+ `[shipguard:telemetry] SHIPGUARD_TELEMETRY_DEBUG=1: not sending. provenance=${base.provenance} endpoint=${endpoint ?? "(none: dev build without a loopback SHIPGUARD_TELEMETRY_URL)"} payload=${JSON.stringify(buildPayload({ ...base, installId: installId2 }))}${note}
4004
+ `
4005
+ );
4006
+ return Promise.resolve();
4007
+ }
4008
+ if (endpoint === null) {
4009
+ logger.debug("telemetry: dev build, not sending (set a loopback SHIPGUARD_TELEMETRY_URL to capture)");
4010
+ return Promise.resolve();
4011
+ }
4012
+ if (!noticeShown(configDir)) {
4013
+ process.stderr.write(NOTICE_TEXT + "\n");
4014
+ markNoticeShown(configDir);
4015
+ }
4016
+ const installId = ci ? null : getOrCreateInstallId(configDir) ?? void 0;
4017
+ if (installId === void 0) {
4018
+ logger.debug("telemetry: no install id could be saved; not sending");
4019
+ return Promise.resolve();
4020
+ }
4021
+ const payload = buildPayload({ ...base, installId });
4022
+ if (!validatePayload(payload)) {
4023
+ logger.debug("telemetry: payload failed validation; not sending");
4024
+ return Promise.resolve();
4025
+ }
4026
+ const body = JSON.stringify(payload);
4027
+ const controller = new AbortController();
4028
+ const abortTimer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
4029
+ const request = fetch(endpoint, {
4030
+ method: "POST",
4031
+ headers: { "Content-Type": "application/json" },
4032
+ body,
4033
+ signal: controller.signal
4034
+ }).then(
4035
+ () => void 0,
4036
+ (err) => {
4037
+ logger.debug(`telemetry: ping failed (ignored): ${err instanceof Error ? err.message : String(err)}`);
4038
+ }
4039
+ ).finally(() => clearTimeout(abortTimer));
4040
+ return new Promise((resolve7) => {
4041
+ const cap = setTimeout(resolve7, PING_WAIT_MS);
4042
+ cap.unref();
4043
+ void request.then(() => {
4044
+ clearTimeout(cap);
4045
+ resolve7();
4046
+ });
4047
+ });
4048
+ } catch (err) {
4049
+ logger.debug(`telemetry: skipped after error (ignored): ${err instanceof Error ? err.message : String(err)}`);
4050
+ return Promise.resolve();
4051
+ }
1953
4052
  }
1954
4053
 
1955
4054
  // src/commands/scan.ts
1956
4055
  var LEARN_MORE = "Docs https://agenticcli.dev/docs \xB7 Site https://agenticcli.dev \xB7 Pricing https://agenticcli.dev/pricing \xB7 Issues https://github.com/agenticcli/shipguard/issues";
1957
- var CLI_VERSION = true ? "0.5.1" : process.env.npm_package_version ?? "0.0.0-dev";
4056
+ var CLI_VERSION = true ? "0.7.0" : process.env.npm_package_version ?? "0.0.0-dev";
1958
4057
  function resolveExitCode(opts) {
1959
- if (opts.strict && opts.blockingCount > 0) {
4058
+ if (opts.strict && (opts.blockingCount > 0 || opts.degraded === true || opts.recommendation === "DO_NOT_SHIP")) {
1960
4059
  return EXIT_CODES.BLOCKED;
1961
4060
  }
1962
4061
  return EXIT_CODES.SAFE;
@@ -1973,15 +4072,17 @@ function proFetchActionHint(code, retryAfterSeconds) {
1973
4072
  return "This looks like a transient server/network issue \u2014 retry the scan, or pass --allow-degraded to run local rules only.";
1974
4073
  case "BUNDLE_INVALID":
1975
4074
  return "The pro rule bundle failed validation (server-side issue) \u2014 retry, or pass --allow-degraded to run local rules only. If this persists, contact support.";
4075
+ case "NO_ACTIVE_RELEASE":
4076
+ return "The Pro rule server has no active rule release yet \u2014 this is a server-side configuration gap, not something a retry or re-login will fix. Check https://agenticcli.dev/docs or contact support, or pass --allow-degraded to run local rules only in the meantime.";
1976
4077
  default:
1977
4078
  return "Retry the scan, or pass --allow-degraded to run local rules only.";
1978
4079
  }
1979
4080
  }
1980
4081
  function isProjectRoot(dir) {
1981
- return existsSync5(join6(dir, "package.json")) || existsSync5(join6(dir, ".git"));
4082
+ return existsSync6(join7(dir, "package.json")) || existsSync6(join7(dir, ".git"));
1982
4083
  }
1983
4084
  function scanCommand() {
1984
- 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", "Opt-in hard gate: exit 1 if blocking findings exist (default exit is 0 \u2014 verdict is informational, read the JSON `recommendation`)").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").option("--allow-degraded", "With --pro: fall back to local-only rules if the pro rule fetch fails, instead of failing loud (opt-in; restores the pre-2026-07-14 fallback behavior \u2014 see exit code 3 below)").option("--check-regressions", "Opt-in hard gate: exit 1 if a previously-passing blocking rule now fails under the same scan scope + corpus release (informational-only in --json unless this flag is set)").addHelpText("after", `
4085
+ 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", "Opt-in hard gate: exit 1 if blocking findings exist, the scan did not finish, OR the verdict is DO_NOT_SHIP (default exit is 0 \u2014 verdict is informational, read the JSON `recommendation`)").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").option("--allow-degraded", "With --pro: fall back to local-only rules if the pro rule fetch fails, instead of failing loud (opt-in; restores the pre-2026-07-14 fallback behavior \u2014 see exit code 3 below)").option("--check-regressions", "Opt-in hard gate: exit 1 if a previously-passing blocking rule now fails under the same scan scope + corpus release (informational-only in --json unless this flag is set)").addHelpText("after", `
1985
4086
  Output modes:
1986
4087
  (default) Verbose: live progress (TTY), categorized findings, gamified verdict panel
1987
4088
  --quiet / -q One-line verdict + exit code only \u2014 ideal for scripts
@@ -2007,16 +4108,22 @@ Exit codes (verdict-neutral by default \u2014 ShipGuard informs, you choose the
2007
4108
  0 Scan completed. Verdict is in the JSON \`recommendation\` field \u2014 this
2008
4109
  is returned EVEN IF findings are blocking, or the scan is degraded/
2009
4110
  partial (see \`degraded\`/\`degradedReasons\` in --json output).
2010
- 1 Blocked \u2014 with --strict AND at least one blocking finding, OR with
2011
- --check-regressions AND at least one regression (see \`regressions\`
2012
- in --json output \u2014 informational-only unless this flag is set).
4111
+ 1 Blocked \u2014 with --strict AND at least one of: a blocking finding, a scan
4112
+ that did not finish (\`degraded:true\` \u2014 an unfinished scan cannot clear
4113
+ a hard gate), or an effective \`recommendation\` of DO_NOT_SHIP (suppressed
4114
+ findings still count toward the risk score, so a scan can cross the
4115
+ DO_NOT_SHIP threshold with zero blocking findings \u2014 the exit code always
4116
+ agrees with the printed verdict). OR with --check-regressions AND at
4117
+ least one regression (see \`regressions\` in --json output \u2014
4118
+ informational-only unless this flag is set).
2013
4119
  2 Config error (bad policy file, bad flags, non-project directory).
2014
4120
  3 Runtime error \u2014 the scan could not meaningfully run at all. This
2015
4121
  INCLUDES an explicit --pro request whose rule fetch failed (auth,
2016
- credits, rate limit, server, or an invalid bundle) \u2014 the requested
2017
- gate did not run, so ShipGuard fails loud instead of silently
2018
- falling back to a free scan. Pass --allow-degraded to opt back into
2019
- the free-scan fallback (degraded:true, exit code unaffected).
4122
+ credits, rate limit, server, an invalid bundle, or no active rule
4123
+ release on the server) \u2014 the requested gate did not run, so
4124
+ ShipGuard fails loud instead of silently falling back to a free
4125
+ scan. Pass --allow-degraded to opt back into the free-scan
4126
+ fallback (degraded:true, exit code unaffected).
2020
4127
 
2021
4128
  Local history (E5): every scan is recorded to a local SQLite store
2022
4129
  (\`.shipguard/history.db\` by default; override via \`history.path\` in
@@ -2112,8 +4219,8 @@ async function runScan(ctx) {
2112
4219
  logger.info("Detecting stack...");
2113
4220
  }
2114
4221
  try {
2115
- const { fetchProRules } = await import("./pro-scanner-MAKMWHIY.js");
2116
- const { hasConfig, generateConfig } = await import("./config-generator-TUQCF2SD.js");
4222
+ const { fetchProRules } = await import("./pro-scanner-SFOR7SGK.js");
4223
+ const { hasConfig, generateConfig } = await import("./config-generator-2BVUZGEU.js");
2117
4224
  const frameworks = detectedFrameworks;
2118
4225
  if (!hasConfig(cwd)) {
2119
4226
  const configPath = generateConfig(cwd, frameworks);
@@ -2163,7 +4270,8 @@ async function runScan(ctx) {
2163
4270
  "INSUFFICIENT_CREDITS",
2164
4271
  "RATE_LIMITED",
2165
4272
  "SERVER_ERROR",
2166
- "BUNDLE_INVALID"
4273
+ "BUNDLE_INVALID",
4274
+ "NO_ACTIVE_RELEASE"
2167
4275
  ];
2168
4276
  const proErrorCode = typeof rawErrCode === "string" && KNOWN_PRO_FETCH_ERROR_CODES.includes(rawErrCode) ? rawErrCode : "SERVER_ERROR";
2169
4277
  const retryAfterSeconds = err?.retryAfterSeconds;
@@ -2228,9 +4336,11 @@ async function runScan(ctx) {
2228
4336
  const skippedTooLarge = result._skippedTooLarge ?? 0;
2229
4337
  const skippedTooLargeFiles = result._skippedTooLargeFiles ?? [];
2230
4338
  const skippedBinary = result._skippedBinary ?? 0;
4339
+ const skippedBinaryFiles = result._skippedBinaryFiles ?? [];
4340
+ const skippedSymlinks = result._skippedSymlinks ?? 0;
4341
+ const skippedSymlinkFiles = result._skippedSymlinkFiles ?? [];
2231
4342
  const truncatedByBounds = result._truncated ?? false;
2232
- result.recommendation = result.riskScore.recommendation;
2233
- result.schemaVersion = "4";
4343
+ result.schemaVersion = "5";
2234
4344
  result.scanIdReused = scanIdReused;
2235
4345
  result.degraded = degraded || Boolean(result.degraded);
2236
4346
  if (result.degraded) {
@@ -2240,6 +4350,9 @@ async function runScan(ctx) {
2240
4350
  }
2241
4351
  result.creditsWarning = creditsRemaining !== void 0 && creditsRemaining < 10;
2242
4352
  result.rulesVersion = rulesVersion;
4353
+ result.runId = scanId;
4354
+ result.cliVersion = CLI_VERSION;
4355
+ applyVerdict(result);
2243
4356
  if (proRules?.length) {
2244
4357
  const breakdown = {};
2245
4358
  for (const r of proRules) {
@@ -2274,7 +4387,20 @@ async function runScan(ctx) {
2274
4387
  delete publicResult._skippedTooLarge;
2275
4388
  delete publicResult._skippedTooLargeFiles;
2276
4389
  delete publicResult._skippedBinary;
4390
+ delete publicResult._skippedBinaryFiles;
4391
+ delete publicResult._skippedSymlinks;
4392
+ delete publicResult._skippedSymlinkFiles;
2277
4393
  delete publicResult._truncated;
4394
+ const shouldReport = scanOptions.generateReport || policy.scan.generate_report;
4395
+ let reportPaths;
4396
+ if (shouldReport) {
4397
+ const reportElapsedMs = Date.now() - startTime;
4398
+ try {
4399
+ reportPaths = await generateReport(result, scanOptions.reportPath, reportElapsedMs);
4400
+ } catch (error) {
4401
+ logger.error(`Report generation failed: ${error instanceof Error ? error.message : error}`);
4402
+ }
4403
+ }
2278
4404
  if (opts.sarif) {
2279
4405
  console.log(JSON.stringify(toSarif(publicResult), null, 2));
2280
4406
  } else if (scanOptions.json) {
@@ -2303,8 +4429,20 @@ async function runScan(ctx) {
2303
4429
  `These files were not checked. Split/minify-exclude them, or raise \`limits.maxFileSizeBytes\` in shipguard.policy.yml. Verdict is degraded \u2014 see \`degraded\`/\`degradedReasons\` in --json output (does not change the exit code).`
2304
4430
  );
2305
4431
  }
4432
+ if (skippedSymlinks > 0) {
4433
+ const named = skippedSymlinkFiles.slice(0, 10).join(", ");
4434
+ const more = skippedSymlinks > skippedSymlinkFiles.length || skippedSymlinkFiles.length > 10 ? ` (and others)` : "";
4435
+ logger.warn(
4436
+ `Scan INCOMPLETE: ${skippedSymlinks} symlink(s) not followed \u2014 NOT scanned: ${named}${more}`
4437
+ );
4438
+ logger.warn(
4439
+ `ShipGuard never follows symlinks (privacy moat \u2014 a symlink could point outside your project). If this path holds real source, replace the symlink with the real directory/file to have it scanned. Verdict is degraded \u2014 see \`degraded\`/\`degradedReasons\` in --json output (does not change the exit code).`
4440
+ );
4441
+ }
2306
4442
  if (skippedBinary > 0) {
2307
- logger.info(`Files skipped (binary, normal): ${skippedBinary}`);
4443
+ const named = skippedBinaryFiles.slice(0, 10).join(", ");
4444
+ const more = skippedBinary > skippedBinaryFiles.length || skippedBinaryFiles.length > 10 ? ` (and others)` : "";
4445
+ logger.info(`Files skipped (binary, normal): ${skippedBinary} \u2014 ${named}${more}`);
2308
4446
  }
2309
4447
  if (creditsRemaining !== void 0) {
2310
4448
  logger.info(`Credits remaining: ${creditsRemaining}`);
@@ -2323,7 +4461,6 @@ async function runScan(ctx) {
2323
4461
  }
2324
4462
  console.log(coverageLine());
2325
4463
  console.log("");
2326
- console.log(verdictPanel(result, elapsedMs, skippedTooLarge + skippedBinary, result.findings, scanOptions.strict));
2327
4464
  const topRuleId = result.findings.length > 0 ? result.findings[0].id : void 0;
2328
4465
  const isLoggedIn = Boolean(opts.pro && !degraded);
2329
4466
  console.log(actionFooter({
@@ -2331,60 +4468,54 @@ async function runScan(ctx) {
2331
4468
  topRuleId,
2332
4469
  isLoggedIn
2333
4470
  }));
4471
+ console.log(verdictPanel(
4472
+ result,
4473
+ elapsedMs,
4474
+ skippedTooLarge + skippedBinary + skippedSymlinks,
4475
+ result.findings,
4476
+ scanOptions.strict,
4477
+ reportPaths
4478
+ ));
2334
4479
  }
2335
- const shouldReport = scanOptions.generateReport || policy.scan.generate_report;
2336
- if (shouldReport) {
2337
- const reportPath = scanOptions.reportPath;
2338
- const reportElapsedMs = Date.now() - startTime;
2339
- try {
2340
- const paths = await generateReport(result, reportPath, reportElapsedMs);
2341
- if (!machineOutput && !quiet) {
2342
- logger.success(`Report: ${paths.mdPath} \xB7 agent view: ${paths.jsonPath}`);
2343
- }
2344
- } catch (error) {
2345
- logger.error(`Report generation failed: ${error instanceof Error ? error.message : error}`);
2346
- }
2347
- }
2348
- if (opts.pro && !degraded) {
2349
- fetch(`${opts.apiUrl}/api/telemetry/ingest`, {
2350
- method: "POST",
2351
- headers: { "Content-Type": "application/json" },
2352
- body: JSON.stringify({
2353
- scanId,
2354
- findingsCount: result.findings.length,
2355
- blocked: result.riskScore.blockingCount > 0,
2356
- riskScore: result.riskScore.score,
2357
- recommendation: result.riskScore.recommendation,
2358
- severityBreakdown: {
2359
- critical: result.riskScore.criticalCount,
2360
- high: result.riskScore.highCount,
2361
- medium: result.riskScore.mediumCount,
2362
- low: result.riskScore.lowCount,
2363
- info: result.riskScore.infoCount
2364
- },
2365
- rulesApplied: proRules?.length ?? 0
2366
- })
2367
- }).catch(() => {
2368
- });
2369
- }
4480
+ let telemetryDone = void 0;
2370
4481
  try {
2371
4482
  const elapsedMs = Date.now() - startTime;
2372
4483
  const verdictBucket = result.degraded ? "review" : result.riskScore.blockingCount > 0 ? "blocked" : result.riskScore.recommendation === "REVIEW_BEFORE_SHIP" ? "review" : "safe";
2373
- sendTelemetry({
2374
- cliVersion: CLI_VERSION,
2375
- verdict: verdictBucket,
2376
- durationMs: elapsedMs,
2377
- ci: Boolean(process.env.CI),
2378
- rulePackCount: proRules ? 1 : 0
2379
- });
2380
- } catch {
4484
+ telemetryDone = sendTelemetry(
4485
+ {
4486
+ cliVersion: CLI_VERSION,
4487
+ verdict: verdictBucket,
4488
+ durationMs: elapsedMs
4489
+ },
4490
+ { policy, projectDir: cwd }
4491
+ );
4492
+ } catch (err) {
4493
+ logger.debug(`telemetry: skipped (ignored): ${err instanceof Error ? err.message : String(err)}`);
2381
4494
  }
2382
4495
  let exitCode = resolveExitCode({
2383
4496
  strict: scanOptions.strict,
2384
- blockingCount: result.riskScore.blockingCount
4497
+ blockingCount: result.riskScore.blockingCount,
4498
+ // Recommendation #3 — the hard stop must not inherit the false-safe on an
4499
+ // unfinished scan. Uses the FINAL degraded value (post pro-fetch OR-merge).
4500
+ degraded: result.degraded === true,
4501
+ // CLI-2/J-3 — the hard stop must not disagree with the printed verdict:
4502
+ // a scan can print DO_NOT_SHIP with blockingCount 0 (active non-blocking findings,
4503
+ // degradation). effectiveRecommendation
4504
+ // reads the SAME field the human panel / --json `recommendation` print.
4505
+ recommendation: effectiveRecommendation(result)
2385
4506
  });
2386
4507
  if (exitCode === EXIT_CODES.BLOCKED && !machineOutput && !quiet) {
2387
- logger.warn(`Strict mode: ${result.riskScore.blockingCount} blocking finding(s) \u2014 exiting with code 1`);
4508
+ if (result.degraded === true) {
4509
+ logger.warn(
4510
+ `Strict mode: this scan did not finish \u2014 ${(result.degradedReasons ?? []).map((r) => r.code).join(", ") || "reason not recorded"} \u2014 exiting with code 1. Fix the cause or drop --strict to get a report without a hard stop.`
4511
+ );
4512
+ } else if (result.riskScore.blockingCount > 0) {
4513
+ logger.warn(`Strict mode: ${result.riskScore.blockingCount} blocking finding(s) \u2014 exiting with code 1`);
4514
+ } else {
4515
+ logger.warn(
4516
+ `Strict mode: verdict is DO_NOT_SHIP (risk score ${result.riskScore.score}/100) \u2014 exiting with code 1. No individual finding is policy-blocking, but the combined risk score of the active findings crossed the DO_NOT_SHIP threshold. Fix or drop --strict to get a report without a hard stop.`
4517
+ );
4518
+ }
2388
4519
  }
2389
4520
  if (opts.checkRegressions && exitCode === EXIT_CODES.SAFE && (result.regressions?.length ?? 0) > 0) {
2390
4521
  exitCode = EXIT_CODES.BLOCKED;
@@ -2392,6 +4523,7 @@ async function runScan(ctx) {
2392
4523
  logger.warn(`--check-regressions: ${result.regressions?.length} previously-passing rule(s) now fail \u2014 exiting with code 1`);
2393
4524
  }
2394
4525
  }
4526
+ await telemetryDone;
2395
4527
  if (exitCode !== EXIT_CODES.SAFE) {
2396
4528
  process.exit(exitCode);
2397
4529
  }
@@ -2500,7 +4632,7 @@ function statusCommand() {
2500
4632
  // src/commands/history.ts
2501
4633
  import { Command as Command6 } from "commander";
2502
4634
  import { resolve as resolve5 } from "path";
2503
- var CLI_VERSION2 = true ? "0.5.1" : process.env.npm_package_version ?? "0.0.0-dev";
4635
+ var CLI_VERSION2 = true ? "0.7.0" : process.env.npm_package_version ?? "0.0.0-dev";
2504
4636
  function historyCommand() {
2505
4637
  return new Command6("history").description("Show recent local scan history for this repo (read-only; --json for machine output)").argument("[path]", "Path to project root (defaults to current directory)").option("--json", "Output as JSON").option("--limit <n>", "Number of recent scans to show", (v) => Number.parseInt(v, 10) || 10, 10).action(async (scanPath, opts) => {
2506
4638
  const cwd = scanPath ? resolve5(scanPath) : process.cwd();
@@ -2561,49 +4693,446 @@ function historyCommand() {
2561
4693
  });
2562
4694
  }
2563
4695
 
2564
- // src/commands/feedback.ts
4696
+ // src/commands/hook.ts
2565
4697
  import { Command as Command7 } from "commander";
2566
- function feedbackCommand() {
2567
- return new Command7("feedback").description("Send feedback about your last scan").argument("<text>", "Your feedback text").action(async (text) => {
2568
- let token;
2569
- try {
2570
- const t = await getAuthToken();
2571
- if (!t) {
2572
- logger.error("Not authenticated. Run `shipguard login` first.");
2573
- return;
2574
- }
2575
- token = t;
2576
- } catch (err) {
2577
- logger.error(`Authentication failed: ${err instanceof Error ? err.message : String(err)}`);
4698
+ import { execFileSync as execFileSync3 } from "child_process";
4699
+ import { chmodSync as chmodSync2, existsSync as existsSync7, mkdirSync as mkdirSync5, readFileSync as readFileSync3, writeFileSync as writeFileSync4 } from "fs";
4700
+ import { dirname as dirname5, isAbsolute, join as join8, relative as relative2, resolve as resolve6 } from "path";
4701
+
4702
+ // src/core/hook-templates.ts
4703
+ var HOOK_BLOCK_VERSION = 1;
4704
+ var HOOK_MARKER_START = "# >>> shipguard managed block >>>";
4705
+ var HOOK_MARKER_END = "# <<< shipguard managed block <<<";
4706
+ var GATE_COMMAND = "shipguard scan --json --strict";
4707
+ function gateShellBody(indent = "") {
4708
+ const l = (s) => `${indent}${s}`;
4709
+ return [
4710
+ l("if command -v shipguard >/dev/null 2>&1; then"),
4711
+ l(' _sg_run() { shipguard "$@"; }'),
4712
+ l("elif command -v npx >/dev/null 2>&1; then"),
4713
+ l(' _sg_run() { npx --no-install shipguard "$@"; }'),
4714
+ l("else"),
4715
+ l(' echo "ShipGuard: not installed, so the release gate did not run \u2014 refusing to pass." >&2'),
4716
+ l(' echo " Install it: npm i -g @agenticcli/shipguard" >&2'),
4717
+ l(" exit 1"),
4718
+ l("fi"),
4719
+ l("_sg_out=$(_sg_run scan --json --strict 2>&1) || {"),
4720
+ l(' echo "ShipGuard blocked this: the release gate did not pass." >&2'),
4721
+ l(' printf "%s\\n" "$_sg_out" >&2'),
4722
+ l(" exit 1"),
4723
+ l("}")
4724
+ ].join("\n");
4725
+ }
4726
+ function gitHookScript(hookName) {
4727
+ return ["#!/bin/sh", gitHookBlock(hookName), ""].join("\n");
4728
+ }
4729
+ function gitHookBlock(hookName) {
4730
+ return [
4731
+ HOOK_MARKER_START + ` v${HOOK_BLOCK_VERSION} (${hookName})`,
4732
+ "# Installed by `shipguard hook`. Re-run that command to update this block.",
4733
+ `# Runs the release gate as a HARD STOP: ${GATE_COMMAND}`,
4734
+ "#",
4735
+ "# HONEST LIMIT: a git hook binds humans and well-behaved agents only.",
4736
+ "# `--no-verify` skips it. For a stop an agent cannot route around, also run:",
4737
+ "# shipguard hook --target claude (runs outside the model)",
4738
+ "# shipguard hook --target ci (server-side; pair with branch protection)",
4739
+ gateShellBody(),
4740
+ HOOK_MARKER_END
4741
+ ].join("\n");
4742
+ }
4743
+ var GIT_HOOK_NAMES = ["pre-push", "pre-merge-commit"];
4744
+ var CLAUDE_HOOK_COMMAND = `sh -c '_sg_in=$(cat); case "$_sg_in" in *"git merge"*|*"git push"*) _sg_out=$(${GATE_COMMAND} 2>&1) || { echo "ShipGuard blocked this merge/push: the release gate did not pass." >&2; printf "%s\\n" "$_sg_out" >&2; exit 2; };; esac; exit 0'`;
4745
+ var CLAUDE_HOOK_FINGERPRINT = "shipguard scan --json --strict";
4746
+ function ciWorkflowYaml() {
4747
+ return `# ${HOOK_MARKER_START.replace("# ", "")} v${HOOK_BLOCK_VERSION} (github-actions)
4748
+ # Installed by \`shipguard hook --target ci\`. Re-run that command to update this file.
4749
+ #
4750
+ # This is the only layer that binds EVERYONE \u2014 it runs server-side, so nothing
4751
+ # local can skip it. Turn on branch protection for this check to make it binding.
4752
+ name: ShipGuard release gate
4753
+
4754
+ on:
4755
+ pull_request:
4756
+ push:
4757
+ branches: [main]
4758
+
4759
+ jobs:
4760
+ shipguard:
4761
+ name: ShipGuard verdict
4762
+ runs-on: ubuntu-latest
4763
+ steps:
4764
+ - uses: actions/checkout@v4
4765
+ - uses: actions/setup-node@v4
4766
+ with:
4767
+ node-version: '20'
4768
+ - name: Run the release gate
4769
+ run: npx --yes @agenticcli/shipguard scan --json --strict
4770
+ # ${HOOK_MARKER_END.replace("# ", "")}
4771
+ `;
4772
+ }
4773
+ var BINDING_NOTES = {
4774
+ git: "Binds humans and well-behaved agents only. `git push --no-verify` skips it, and coding agents have been seen doing exactly that. Treat this as convenience, not a guarantee.",
4775
+ claude: "Binds the agent. It runs outside the model, so the agent cannot argue, prompt, or inject its way past it inside a session.",
4776
+ ci: "Binds everyone. It runs on GitHub, so nothing local can skip it. Turn on branch protection for this check to make it binding rather than advisory."
4777
+ };
4778
+ function replaceManagedBlock(content, replacement) {
4779
+ const start = content.indexOf(HOOK_MARKER_START);
4780
+ if (start === -1) return void 0;
4781
+ const endMarker = content.indexOf(HOOK_MARKER_END, start);
4782
+ if (endMarker === -1) return void 0;
4783
+ const end = endMarker + HOOK_MARKER_END.length;
4784
+ return content.slice(0, start) + replacement.trim() + content.slice(end);
4785
+ }
4786
+ function isManaged(content) {
4787
+ return content.includes(HOOK_MARKER_START);
4788
+ }
4789
+
4790
+ // src/commands/hook.ts
4791
+ function writeManaged(path, whole, block, executable) {
4792
+ if (!existsSync7(path)) {
4793
+ mkdirSync5(dirname5(path), { recursive: true });
4794
+ writeFileSync4(path, whole, "utf-8");
4795
+ if (executable) chmodSync2(path, 493);
4796
+ return { path, status: "created" };
4797
+ }
4798
+ const current = readFileSync3(path, "utf-8");
4799
+ if (!isManaged(current)) {
4800
+ return {
4801
+ path,
4802
+ status: "refused",
4803
+ manualLine: GATE_COMMAND
4804
+ };
4805
+ }
4806
+ const merged = replaceManagedBlock(current, block) ?? whole;
4807
+ if (merged === current) return { path, status: "unchanged" };
4808
+ writeFileSync4(path, merged, "utf-8");
4809
+ if (executable) chmodSync2(path, 493);
4810
+ return { path, status: "updated" };
4811
+ }
4812
+ function resolveGitHooksDir(cwd) {
4813
+ const out = execFileSync3("git", ["rev-parse", "--git-path", "hooks"], {
4814
+ cwd,
4815
+ encoding: "utf-8",
4816
+ stdio: ["pipe", "pipe", "pipe"]
4817
+ }).trim();
4818
+ return isAbsolute(out) ? out : resolve6(cwd, out);
4819
+ }
4820
+ function installGit(cwd) {
4821
+ const hooksDir = resolveGitHooksDir(cwd);
4822
+ return GIT_HOOK_NAMES.map(
4823
+ (name) => writeManaged(join8(hooksDir, name), gitHookScript(name), gitHookBlock(name), true)
4824
+ );
4825
+ }
4826
+ function installClaude(cwd) {
4827
+ const path = join8(cwd, ".claude", "settings.json");
4828
+ const entry = { matcher: "Bash", hooks: [{ type: "command", command: CLAUDE_HOOK_COMMAND }] };
4829
+ if (!existsSync7(path)) {
4830
+ mkdirSync5(dirname5(path), { recursive: true });
4831
+ writeFileSync4(path, JSON.stringify({ hooks: { PreToolUse: [entry] } }, null, 2) + "\n", "utf-8");
4832
+ return [{ path, status: "created" }];
4833
+ }
4834
+ const raw2 = readFileSync3(path, "utf-8");
4835
+ let settings;
4836
+ try {
4837
+ settings = JSON.parse(raw2);
4838
+ } catch (err) {
4839
+ logger.error(
4840
+ `Could not parse ${path}: ${err instanceof Error ? err.message : err}. Refusing to touch it.`
4841
+ );
4842
+ return [{ path, status: "refused", manualLine: CLAUDE_HOOK_COMMAND }];
4843
+ }
4844
+ const preToolUse = settings.hooks?.PreToolUse ?? [];
4845
+ const ourIndex = preToolUse.findIndex(
4846
+ (e) => (e.hooks ?? []).some((h) => typeof h.command === "string" && h.command.includes(CLAUDE_HOOK_FINGERPRINT))
4847
+ );
4848
+ const next = [...preToolUse];
4849
+ let status;
4850
+ if (ourIndex === -1) {
4851
+ next.push(entry);
4852
+ status = "created";
4853
+ } else if (JSON.stringify(next[ourIndex]) === JSON.stringify(entry)) {
4854
+ status = "unchanged";
4855
+ } else {
4856
+ next[ourIndex] = entry;
4857
+ status = "updated";
4858
+ }
4859
+ if (status !== "unchanged") {
4860
+ const merged = {
4861
+ ...settings,
4862
+ hooks: { ...settings.hooks ?? {}, PreToolUse: next }
4863
+ };
4864
+ writeFileSync4(path, JSON.stringify(merged, null, 2) + "\n", "utf-8");
4865
+ }
4866
+ return [{ path, status }];
4867
+ }
4868
+ function installCi(cwd) {
4869
+ const path = join8(cwd, ".github", "workflows", "shipguard.yml");
4870
+ const yaml = ciWorkflowYaml();
4871
+ return [writeManaged(path, yaml, yaml, false)];
4872
+ }
4873
+ var TARGETS = ["git", "claude", "ci"];
4874
+ function hookCommand() {
4875
+ return new Command7("hook").description("Install the ShipGuard release gate at the merge boundary (git hook, Claude Code hook, or CI job)").option(
4876
+ "--target <target>",
4877
+ `Where to install the gate: ${TARGETS.join(" | ")}`,
4878
+ "git"
4879
+ ).addHelpText("after", `
4880
+ What each target installs (all of them run \`${GATE_COMMAND}\`):
4881
+
4882
+ --target git .git/hooks/pre-push and pre-merge-commit
4883
+ ${BINDING_NOTES.git}
4884
+
4885
+ --target claude .claude/settings.json \u2014 a PreToolUse hook on Bash \`git merge\`/\`git push\`
4886
+ ${BINDING_NOTES.claude}
4887
+
4888
+ --target ci .github/workflows/shipguard.yml
4889
+ ${BINDING_NOTES.ci}
4890
+
4891
+ Install all three where you can. ShipGuard never blocks on its own \u2014 installing a
4892
+ hook is the deliberate act that turns the hard stop on.
4893
+
4894
+ Re-running is safe: an existing ShipGuard block is updated in place, never duplicated.
4895
+ A hook file somebody else wrote is never overwritten \u2014 you get the line to add by hand.
4896
+
4897
+ Exit codes:
4898
+ 0 Installed (or already up to date).
4899
+ 2 Config error \u2014 unknown --target, or --target git outside a git repository.
4900
+ 3 Runtime error \u2014 the files could not be written.`).action((opts) => {
4901
+ const cwd = process.cwd();
4902
+ const target = String(opts.target ?? "git");
4903
+ if (!TARGETS.includes(target)) {
4904
+ logger.error(`Unknown --target "${opts.target}". Choose one of: ${TARGETS.join(", ")}.`);
4905
+ process.exit(EXIT_CODES.CONFIG_ERROR);
2578
4906
  return;
2579
4907
  }
2580
- const creds = loadCredentials();
2581
- if (!creds) {
2582
- logger.error("No credentials found. Run `shipguard login` first.");
4908
+ if (target === "git" && !isGitRepo(cwd)) {
4909
+ logger.error(
4910
+ `Not a git repository: ${cwd}. Run this inside your project, or use --target ci / --target claude.`
4911
+ );
4912
+ process.exit(EXIT_CODES.CONFIG_ERROR);
2583
4913
  return;
2584
4914
  }
4915
+ let outcomes;
2585
4916
  try {
2586
- assertTrustedApiUrl(creds.apiUrl);
2587
- const res = await fetch(`${creds.apiUrl}/api/feedback`, {
2588
- method: "POST",
2589
- headers: {
2590
- "Authorization": `Bearer ${token}`,
2591
- "Content-Type": "application/json"
4917
+ outcomes = target === "git" ? installGit(cwd) : target === "claude" ? installClaude(cwd) : installCi(cwd);
4918
+ } catch (err) {
4919
+ logger.error(`Could not install the hook: ${err instanceof Error ? err.message : err}`);
4920
+ process.exit(EXIT_CODES.RUNTIME_ERROR);
4921
+ return;
4922
+ }
4923
+ const refused = outcomes.filter((o) => o.status === "refused");
4924
+ for (const outcome of outcomes) {
4925
+ const shown = isAbsolute(outcome.path) ? relative2(cwd, outcome.path) || outcome.path : outcome.path;
4926
+ switch (outcome.status) {
4927
+ case "created":
4928
+ logger.success(`Installed the release gate: ${shown}`);
4929
+ break;
4930
+ case "updated":
4931
+ logger.success(`Updated the release gate: ${shown}`);
4932
+ break;
4933
+ case "unchanged":
4934
+ logger.info(`Already up to date: ${shown}`);
4935
+ break;
4936
+ case "refused":
4937
+ logger.warn(`${shown} was written by something else \u2014 not touching it.`);
4938
+ logger.warn(` Add this line to it yourself: ${outcome.manualLine}`);
4939
+ break;
4940
+ }
4941
+ }
4942
+ logger.info(`What this binds: ${BINDING_NOTES[target]}`);
4943
+ if (target === "git") {
4944
+ logger.info("For a stop an agent cannot route around, also run: shipguard hook --target claude");
4945
+ logger.info("And for one nothing local can skip: shipguard hook --target ci");
4946
+ }
4947
+ if (refused.length > 0) {
4948
+ logger.info("Nothing was overwritten.");
4949
+ }
4950
+ });
4951
+ }
4952
+
4953
+ // src/commands/schema.ts
4954
+ import { Command as Command8 } from "commander";
4955
+ var CLI_VERSION3 = true ? "0.7.0" : process.env.npm_package_version ?? "0.0.0-dev";
4956
+ var CURRENT_SCHEMA_VERSION2 = "5";
4957
+ function buildSchemaContract(limits) {
4958
+ const src = (value, fallback) => value === fallback ? "default" : "policy";
4959
+ return {
4960
+ schemaVersion: CURRENT_SCHEMA_VERSION2,
4961
+ cliVersion: CLI_VERSION3,
4962
+ contract: "shipguard-scan-result",
4963
+ recommendation: {
4964
+ field: "recommendation",
4965
+ // Closed set. Deliberately NOT extended for degraded scans — a new value would be a
4966
+ // fail-open trap for the very common `recommendation !== 'DO_NOT_SHIP'` parser.
4967
+ values: ["SAFE_TO_SHIP", "REVIEW_BEFORE_SHIP", "DO_NOT_SHIP"],
4968
+ failClosed: "When `degraded` is true the recommendation is ALWAYS DO_NOT_SHIP \u2014 a scan that did not read everything it was asked to read cannot report that shipping is safe. The exit code is unaffected: ShipGuard is passive by default and still exits 0 while saying this. Only --strict turns it into a hard stop.",
4969
+ deprecatedMirrors: ["riskScore.recommendation"]
4970
+ },
4971
+ exitCodes: [
4972
+ {
4973
+ code: EXIT_CODES.SAFE,
4974
+ name: "COMPLETED",
4975
+ meaning: "The scan ran. The verdict is in the `recommendation` field \u2014 NOT in this exit code. Returned even when findings are blocking and even when `degraded` is true."
4976
+ },
4977
+ {
4978
+ code: EXIT_CODES.BLOCKED,
4979
+ name: "BLOCKED",
4980
+ meaning: "Opt-in hard stop. Returned only with --strict, when there is at least one blocking finding OR the scan did not finish (`degraded: true`); or with --check-regressions when a previously-passing rule now fails."
4981
+ },
4982
+ {
4983
+ code: EXIT_CODES.CONFIG_ERROR,
4984
+ name: "CONFIG_ERROR",
4985
+ meaning: "Bad policy file, unknown flag, or a non-project directory without --all. Never used for a degraded-but-completed scan."
4986
+ },
4987
+ {
4988
+ code: EXIT_CODES.RUNTIME_ERROR,
4989
+ name: "RUNTIME_ERROR",
4990
+ meaning: "The scan could not meaningfully run at all \u2014 zero rules applied, or an explicit --pro request whose rule fetch failed (pass --allow-degraded to opt into a free scan fallback instead)."
4991
+ }
4992
+ ],
4993
+ degradeCodes: [
4994
+ { code: "FILE_TOO_LARGE", meaning: "One or more files exceeded the per-file size cap and were not scanned." },
4995
+ { code: "OUTPUT_TRUNCATED", meaning: "The file-count or total-bytes ceiling was reached; collection stopped early." },
4996
+ { code: "CODEREF_SKIPPED", meaning: "One or more Pro coderef rules need a newer CLI and were skipped." },
4997
+ { code: "PRO_RULES_UNAVAILABLE", meaning: "Pro rules could not be fetched (auth, credits, rate limit, network)." },
4998
+ { code: "INVALID_UTF8", meaning: "One or more files were not valid UTF-8 and were skipped rather than mangled." },
4999
+ { code: "UNREADABLE_FILE", meaning: "One or more files could not be read from disk." },
5000
+ { code: "COMPILE_FAILURE", meaning: "A Pro rule bundle failed to compile; the whole bundle was refused rather than partly run." }
5001
+ ],
5002
+ limits: {
5003
+ maxFiles: {
5004
+ value: limits.maxFiles,
5005
+ unit: "files",
5006
+ source: src(limits.maxFiles, DEFAULT_MAX_FILES),
5007
+ behaviorAtLimit: "Collection stops; the remaining files are NOT scanned.",
5008
+ machineSignal: 'degraded:true + degradedReasons[].code === "OUTPUT_TRUNCATED"',
5009
+ verifiedBy: null
5010
+ },
5011
+ maxFileSizeBytes: {
5012
+ value: limits.maxFileSizeBytes,
5013
+ unit: "bytes",
5014
+ source: src(limits.maxFileSizeBytes, DEFAULT_MAX_FILE_SIZE_BYTES),
5015
+ behaviorAtLimit: "The individual file is skipped unread; the rest of the scan continues.",
5016
+ machineSignal: 'degraded:true + degradedReasons[].code === "FILE_TOO_LARGE" (detail names the files)',
5017
+ verifiedBy: null
5018
+ },
5019
+ maxTotalBytes: {
5020
+ value: limits.maxTotalBytes,
5021
+ unit: "bytes",
5022
+ source: src(limits.maxTotalBytes, DEFAULT_MAX_TOTAL_BYTES),
5023
+ behaviorAtLimit: "Collection stops; the remaining files are NOT scanned.",
5024
+ machineSignal: 'degraded:true + degradedReasons[].code === "OUTPUT_TRUNCATED"',
5025
+ verifiedBy: null
5026
+ },
5027
+ unanalyzableTypes: [
5028
+ {
5029
+ type: "binary",
5030
+ behavior: "Skipped. A binary file has no source to scan.",
5031
+ // Deliberately no degrade signal: a binary skip is normal, not incomplete coverage.
5032
+ machineSignal: null,
5033
+ verifiedBy: null
5034
+ },
5035
+ {
5036
+ type: "invalid-utf8",
5037
+ behavior: "Skipped unread \u2014 decoding with replacement characters can destroy a secret that straddles the bad bytes.",
5038
+ machineSignal: 'degradedReasons[].code === "INVALID_UTF8"',
5039
+ verifiedBy: null
2592
5040
  },
2593
- body: JSON.stringify({ freeText: text })
5041
+ {
5042
+ type: "symlink",
5043
+ behavior: "Never followed. A symlink pointing out of the project root is refused.",
5044
+ machineSignal: 'degradedReasons[].code === "UNREADABLE_FILE" when the path was reported as changed',
5045
+ verifiedBy: null
5046
+ },
5047
+ {
5048
+ type: "unreadable",
5049
+ behavior: "Skipped \u2014 permission error, deleted mid-scan, dangling symlink.",
5050
+ machineSignal: 'degradedReasons[].code === "UNREADABLE_FILE"',
5051
+ verifiedBy: null
5052
+ },
5053
+ {
5054
+ type: "ignored-by-default",
5055
+ behavior: "Not collected: node_modules, dist, build, .next, coverage, .git, lockfiles, images/archives/media, and ShipGuard\u2019s own artifacts.",
5056
+ machineSignal: null,
5057
+ verifiedBy: null
5058
+ }
5059
+ ],
5060
+ verificationStatus: "UNVERIFIED \u2014 these values are read from configuration, not measured. The boundary/scale round fills every verifiedBy with the run id that proved it. Until then, treat them as declared limits, not observed ones."
5061
+ }
5062
+ };
5063
+ }
5064
+ function schemaCommand() {
5065
+ return new Command8("schema").description("Print the machine-readable scan contract: verdict values, exit codes, and scan limits").option("--json", "Output the contract as JSON (the machine-readable form)").addHelpText("after", `
5066
+ Run this inside a project to see the limits THAT project actually uses (its
5067
+ shipguard.policy.yml is merged in); run it anywhere else for the defaults.
5068
+
5069
+ Examples:
5070
+ shipguard schema --json The contract, for an agent or a script
5071
+ shipguard schema The same thing, readable
5072
+
5073
+ Exit codes:
5074
+ 0 Printed.
5075
+ 2 Config error \u2014 the project's policy file could not be read.`).action(async (opts) => {
5076
+ const cwd = process.cwd();
5077
+ let contract;
5078
+ try {
5079
+ const policy = await loadPolicy(cwd);
5080
+ contract = buildSchemaContract({
5081
+ maxFiles: policy.limits?.maxFiles ?? DEFAULT_MAX_FILES,
5082
+ maxFileSizeBytes: policy.limits?.maxFileSizeBytes ?? DEFAULT_MAX_FILE_SIZE_BYTES,
5083
+ maxTotalBytes: policy.limits?.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES
2594
5084
  });
2595
- if (!res.ok) {
2596
- logger.error(`Feedback submission failed: ${res.statusText}`);
2597
- return;
2598
- }
2599
- logger.success("Feedback submitted \u2014 thank you!");
2600
- } catch (err) {
2601
- logger.error(`Failed to send feedback: ${err instanceof Error ? err.message : String(err)}`);
5085
+ } catch (error) {
5086
+ logger.error(`Config error: ${error instanceof Error ? error.message : error}`);
5087
+ process.exit(EXIT_CODES.CONFIG_ERROR);
5088
+ return;
5089
+ }
5090
+ if (opts.json) {
5091
+ console.log(JSON.stringify(contract, null, 2));
5092
+ return;
2602
5093
  }
5094
+ console.log(renderSchemaHuman(contract));
5095
+ });
5096
+ }
5097
+ function renderSchemaHuman(c) {
5098
+ const lines = [];
5099
+ lines.push(`ShipGuard scan contract \u2014 schemaVersion ${c.schemaVersion} (CLI ${c.cliVersion})`);
5100
+ lines.push("");
5101
+ lines.push(`Verdict field: ${c.recommendation.field}`);
5102
+ lines.push(` Values: ${c.recommendation.values.join(", ")}`);
5103
+ lines.push(` Fail-closed: ${c.recommendation.failClosed}`);
5104
+ lines.push(` Deprecated copies: ${c.recommendation.deprecatedMirrors.join(", ")}`);
5105
+ lines.push("");
5106
+ lines.push("Exit codes:");
5107
+ for (const e of c.exitCodes) lines.push(` ${e.code} ${e.name} \u2014 ${e.meaning}`);
5108
+ lines.push("");
5109
+ lines.push("Limits:");
5110
+ for (const [name, entry] of Object.entries(c.limits)) {
5111
+ if (name === "unanalyzableTypes" || name === "verificationStatus") continue;
5112
+ const l = entry;
5113
+ lines.push(` ${name}: ${l.value} ${l.unit ?? ""} (${l.source})`);
5114
+ lines.push(` at the limit: ${l.behaviorAtLimit}`);
5115
+ lines.push(` machine signal: ${l.machineSignal ?? "none"}`);
5116
+ }
5117
+ lines.push("");
5118
+ lines.push("File types that are not analyzed:");
5119
+ for (const t of c.limits.unanalyzableTypes) lines.push(` ${t.type} \u2014 ${t.behavior}`);
5120
+ lines.push("");
5121
+ lines.push(c.limits.verificationStatus);
5122
+ return lines.join("\n");
5123
+ }
5124
+
5125
+ // src/commands/feedback.ts
5126
+ import { Command as Command9 } from "commander";
5127
+ var ISSUES_URL2 = "https://github.com/agenticcli/shipguard/issues";
5128
+ function feedbackCommand() {
5129
+ return new Command9("feedback").description("Tell us what you think: prints where to send feedback (no network call)").argument("[text]", "Ignored. Feedback is not sent from the CLI; open an issue instead").action(() => {
5130
+ logger.info(`Feedback and bug reports go to GitHub issues: ${ISSUES_URL2}`);
5131
+ logger.info("The CLI does not send your feedback anywhere itself.");
2603
5132
  });
2604
5133
  }
2605
5134
  function rateCommand() {
2606
- return new Command7("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) => {
5135
+ return new Command9("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) => {
2607
5136
  const num = parseInt(findingNumber, 10);
2608
5137
  if (isNaN(num) || num < 1) {
2609
5138
  logger.error("Finding number must be a positive integer.");
@@ -2655,10 +5184,92 @@ function rateCommand() {
2655
5184
  });
2656
5185
  }
2657
5186
 
5187
+ // src/commands/telemetry.ts
5188
+ import { Command as Command10 } from "commander";
5189
+ var DOCS = "https://agenticcli.dev/docs#telemetry";
5190
+ var SOURCE_TEXT = {
5191
+ "env:SHIPGUARD_TELEMETRY": "SHIPGUARD_TELEMETRY=0 is set in the environment",
5192
+ "env:DO_NOT_TRACK": "DO_NOT_TRACK=1 is set in the environment",
5193
+ "user-config": "turned off with `shipguard telemetry disable`",
5194
+ "project-policy": "`telemetry.enabled: false` in shipguard.policy.yml or .shipguard.yml",
5195
+ default: "default (on)"
5196
+ };
5197
+ function telemetryCommand() {
5198
+ const cmd = new Command10("telemetry").description(
5199
+ "Show or change the pseudonymous usage ping (status, enable, disable, reset)"
5200
+ );
5201
+ cmd.command("status").description("Show whether usage pings are on, why, and where they would go").option("--json", "Machine-readable output").action(async (o) => {
5202
+ const decision = decideTelemetry({ projectDir: process.cwd() });
5203
+ const provenance = getProvenance();
5204
+ const endpoint = resolveEndpoint();
5205
+ const installId = readInstallId() ?? null;
5206
+ const info = {
5207
+ version: 2,
5208
+ enabled: decision.enabled,
5209
+ source: decision.source,
5210
+ provenance,
5211
+ endpoint,
5212
+ noticeShown: noticeShown(),
5213
+ installIdPresent: installId !== null,
5214
+ installId,
5215
+ ci: detectCi(),
5216
+ configFile: configFilePath(),
5217
+ optOut: ["SHIPGUARD_TELEMETRY=0", "DO_NOT_TRACK=1", "shipguard telemetry disable"]
5218
+ };
5219
+ if (o.json) {
5220
+ console.log(JSON.stringify(info, null, 2));
5221
+ return;
5222
+ }
5223
+ console.log(`Usage pings: ${decision.enabled ? "ON" : "OFF"} (${SOURCE_TEXT[decision.source]})`);
5224
+ console.log(
5225
+ `Build: ${provenance}` + (provenance === "dev" ? " (a dev build never pings production; only a loopback SHIPGUARD_TELEMETRY_URL)" : "")
5226
+ );
5227
+ console.log(`Endpoint: ${endpoint ?? "none"}`);
5228
+ console.log(
5229
+ `Install id: ${installId ?? "none yet"}` + (installId ? "" : " (a random id is made on the first ping outside CI)") + (detectCi() ? " (CI detected: no install id is created or sent)" : "")
5230
+ );
5231
+ console.log(`Sends: CLI version, verdict, duration bucket, CI flag, build type, install id (null in CI). Never code, paths, repo names or your account.`);
5232
+ console.log(`Turn off: SHIPGUARD_TELEMETRY=0 | DO_NOT_TRACK=1 | shipguard telemetry disable`);
5233
+ console.log(`Inspect: SHIPGUARD_TELEMETRY_DEBUG=1 shipguard scan (prints the exact payload, sends nothing)`);
5234
+ console.log(`Details: ${DOCS}`);
5235
+ });
5236
+ for (const [name, enabled] of [["enable", true], ["disable", false]]) {
5237
+ cmd.command(name).description(enabled ? "Turn usage pings on for this user" : "Turn usage pings off for this user").action(() => {
5238
+ try {
5239
+ const file = writeUserEnabled(getConfigDir(), enabled);
5240
+ console.log(`Usage pings ${enabled ? "enabled" : "disabled"} for this user (${file}).`);
5241
+ } catch (err) {
5242
+ logger.error(`Could not save the setting: ${err instanceof Error ? err.message : String(err)}`);
5243
+ process.exitCode = EXIT_CODES.RUNTIME_ERROR;
5244
+ return;
5245
+ }
5246
+ const decision = decideTelemetry({ projectDir: process.cwd() });
5247
+ if (enabled && !decision.enabled) {
5248
+ logger.warn(`Pings stay OFF: ${SOURCE_TEXT[decision.source]}.`);
5249
+ }
5250
+ });
5251
+ }
5252
+ cmd.command("reset").description("Forget the local install id (a new random one is made on the next ping)").action(() => {
5253
+ try {
5254
+ const { hadId, oldId } = resetInstallId(getConfigDir());
5255
+ console.log(hadId ? "Install id deleted. A new random one is made on the next ping." : "No install id was stored. Nothing to reset.");
5256
+ if (oldId) console.log(`Old install id: ${oldId}`);
5257
+ console.log(
5258
+ "Pings already sent stay on the server under the old id. Past events can be deleted on request" + (oldId ? ": quote the old install id above." : ".") + ` Retention and deletion: ${DOCS}`
5259
+ );
5260
+ } catch (err) {
5261
+ logger.error(`Could not reset the install id: ${err instanceof Error ? err.message : String(err)}`);
5262
+ process.exitCode = EXIT_CODES.RUNTIME_ERROR;
5263
+ }
5264
+ });
5265
+ for (const sub of cmd.commands) sub.exitOverride();
5266
+ return cmd;
5267
+ }
5268
+
2658
5269
  // src/handlers.ts
2659
- var ISSUES_URL2 = "https://github.com/agenticcli/shipguard/issues";
5270
+ var ISSUES_URL3 = "https://github.com/agenticcli/shipguard/issues";
2660
5271
  var DOCS_URL2 = "https://agenticcli.dev/docs";
2661
- var REPORT_LINE = `Report this: ${ISSUES_URL2} \xB7 Docs: ${DOCS_URL2}`;
5272
+ var REPORT_LINE = `Report this: ${ISSUES_URL3} \xB7 Docs: ${DOCS_URL2}`;
2662
5273
  function handleUncaughtException(error) {
2663
5274
  const message = error instanceof Error ? error.message : String(error);
2664
5275
  console.error(`\x1B[31m\u2717\x1B[0m Unexpected error: ${message}`);
@@ -2687,20 +5298,20 @@ process.on("uncaughtException", handleUncaughtException);
2687
5298
  process.on("unhandledRejection", handleUnhandledRejection);
2688
5299
  process.on("SIGINT", handleSignal);
2689
5300
  process.on("SIGTERM", handleSignal);
2690
- var ISSUES_URL3 = "https://github.com/agenticcli/shipguard/issues";
2691
- var program = new Command8();
5301
+ var ISSUES_URL4 = "https://github.com/agenticcli/shipguard/issues";
5302
+ var program = new Command11();
2692
5303
  var rawArgs = process.argv.slice(2);
2693
5304
  if (rawArgs[0] === "?") {
2694
5305
  process.argv = [process.argv[0], process.argv[1], "help"];
2695
5306
  }
2696
5307
  program.name("shipguard").description("CLI-first release gate for AI-built apps").version(
2697
- true ? "0.5.1" : process.env.npm_package_version ?? "0.0.0-dev"
5308
+ true ? "0.7.0" : process.env.npm_package_version ?? "0.0.0-dev"
2698
5309
  ).helpCommand(false).addHelpText("after", `
2699
5310
  Learn more:
2700
5311
  Docs https://agenticcli.dev/docs
2701
5312
  Site https://agenticcli.dev
2702
5313
  Pricing https://agenticcli.dev/pricing
2703
- Issues ${ISSUES_URL3}`);
5314
+ Issues ${ISSUES_URL4}`);
2704
5315
  program.exitOverride();
2705
5316
  function addSubcommand(cmd) {
2706
5317
  cmd.exitOverride();
@@ -2712,10 +5323,13 @@ addSubcommand(loginCommand());
2712
5323
  addSubcommand(logoutCommand());
2713
5324
  addSubcommand(statusCommand());
2714
5325
  addSubcommand(historyCommand());
5326
+ addSubcommand(hookCommand());
5327
+ addSubcommand(schemaCommand());
2715
5328
  addSubcommand(feedbackCommand());
2716
5329
  addSubcommand(rateCommand());
5330
+ addSubcommand(telemetryCommand());
2717
5331
  program.addCommand(
2718
- new Command8("help").description("Show the quickstart guide").action(() => {
5332
+ new Command11("help").description("Show the quickstart guide").action(() => {
2719
5333
  const isTTY = Boolean(process.stdout.isTTY);
2720
5334
  process.stdout.write(quickstartHelp(isTTY) + "\n");
2721
5335
  })
@@ -2740,7 +5354,7 @@ function levenshtein(a, b) {
2740
5354
  return dp[m][n];
2741
5355
  }
2742
5356
  function closestCommand(input) {
2743
- const names = ["scan", "init", "login", "logout", "status", "history", "feedback", "rate", "help"];
5357
+ const names = ["scan", "init", "login", "logout", "status", "history", "hook", "schema", "feedback", "rate", "telemetry", "help"];
2744
5358
  let best;
2745
5359
  let bestDist = Infinity;
2746
5360
  for (const name of names) {
@@ -2753,7 +5367,7 @@ function closestCommand(input) {
2753
5367
  return bestDist <= 3 ? best : void 0;
2754
5368
  }
2755
5369
  (async () => {
2756
- const KNOWN_COMMANDS = /* @__PURE__ */ new Set(["scan", "init", "login", "logout", "status", "history", "feedback", "rate", "help"]);
5370
+ const KNOWN_COMMANDS = /* @__PURE__ */ new Set(["scan", "init", "login", "logout", "status", "history", "hook", "schema", "feedback", "rate", "telemetry", "help"]);
2757
5371
  const firstNonFlag = process.argv.slice(2).find((a) => !a.startsWith("-"));
2758
5372
  if (firstNonFlag && firstNonFlag !== "?" && !KNOWN_COMMANDS.has(firstNonFlag)) {
2759
5373
  const suggestion = closestCommand(firstNonFlag);