@agenticcli/shipguard 0.5.1 → 0.6.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-KYVEU6H4.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 Command10, CommanderError } from "commander";
35
41
 
36
42
  // src/commands/init.ts
37
43
  import { Command } from "commander";
@@ -179,7 +185,29 @@ import { join as join6, 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,1633 @@ 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: 17,
488
+ corpusHash: "sha256:9092293614f1346c3eb5081d345126090393979296d6ea35688c42d7da3dc55d",
489
+ ruleCount: 30,
490
+ contentHash: "sha256:058228a9d82ff3c4fcdc1039c453855cdc5dac28841ab9b2e44268e680498d95",
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: 4,
681
+ status: "experimental",
682
+ cwe: [
683
+ "CWE-942"
684
+ ],
685
+ owasp: [
686
+ "A05:2021"
687
+ ],
688
+ matcher: {
689
+ type: "pattern",
690
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,go,rb,java,yaml,yml,conf}",
691
+ patterns: [
692
+ `Access-Control-Allow-Origin['",:\\s]+[*]`,
693
+ `(setHeader|header|res\\.set)\\s*\\(\\s*['"]Access-Control-Allow-Origin['"]\\s*,\\s*['"][*]['"]`,
694
+ `cors\\s*\\(\\s*\\{\\s*origin\\s*:\\s*['"][*]['"]`,
695
+ `allow_origins\\s*=\\s*\\[\\s*['"][*]['"]`
696
+ ],
697
+ antiPatterns: [
698
+ "\\btest\\b|\\bspec\\b|__fixtures__|__tests__",
699
+ "static|assets|cdn|fonts|images|public-api|intentional-wildcard"
700
+ ],
701
+ flags: ""
702
+ },
703
+ 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.",
704
+ 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.",
705
+ fix: "Replace `'*'` with `process.env.ALLOWED_ORIGIN` and validate against an allowlist.",
706
+ findingType: "vulnerability",
707
+ aiCodeTarget: true,
708
+ references: [
709
+ "https://cwe.mitre.org/data/definitions/942.html"
710
+ ]
711
+ },
712
+ {
713
+ id: "generic.crypto.aes-ecb-mode",
714
+ framework: [
715
+ "generic"
716
+ ],
717
+ category: "crypto",
718
+ tier: "free",
719
+ severity: "high",
720
+ confidence: "HIGH",
721
+ action: "block",
722
+ version: 3,
723
+ status: "experimental",
724
+ cwe: [
725
+ "CWE-327"
726
+ ],
727
+ owasp: [
728
+ "A02:2021"
729
+ ],
730
+ matcher: {
731
+ type: "pattern",
732
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,java,go,rb,cs}",
733
+ patterns: [
734
+ "AES[-/]ECB",
735
+ `createCipheriv\\s*\\(\\s*['"]aes-[0-9]+-ecb['"]`,
736
+ `Cipher\\.getInstance\\s*\\(\\s*['"]AES/ECB`,
737
+ "AES\\.new\\s*\\([^,)]{0,60},\\s*AES\\.MODE_ECB"
738
+ ],
739
+ antiPatterns: [
740
+ "\\btest\\b|\\bspec\\b|__fixtures__|__tests__",
741
+ "nosec|eslint-disable"
742
+ ],
743
+ flags: "i",
744
+ antiPatternScope: "statement",
745
+ boundary: "token"
746
+ },
747
+ 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.",
748
+ 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.",
749
+ fix: "Replace AES-ECB with AES-GCM: `createCipheriv('aes-256-gcm', key, iv)` and store the IV alongside the ciphertext.",
750
+ findingType: "vulnerability",
751
+ aiCodeTarget: true,
752
+ references: [
753
+ "https://cwe.mitre.org/data/definitions/327.html"
754
+ ]
755
+ },
756
+ {
757
+ id: "generic.crypto.des-rc4-3des",
758
+ framework: [
759
+ "generic"
760
+ ],
761
+ category: "crypto",
762
+ tier: "free",
763
+ severity: "high",
764
+ confidence: "HIGH",
765
+ action: "block",
766
+ version: 3,
767
+ status: "experimental",
768
+ cwe: [
769
+ "CWE-327"
770
+ ],
771
+ owasp: [
772
+ "A02:2021"
773
+ ],
774
+ matcher: {
775
+ type: "pattern",
776
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,java}",
777
+ patterns: [
778
+ `createCipheriv\\s*\\(\\s*['"](?:des|3des|des3|rc4|arcfour)['"]`,
779
+ `createCipheriv\\s*\\(\\s*['"](?:des|3des|des3|rc4|arcfour)-`,
780
+ `Cipher\\.getInstance\\s*\\(\\s*['"](?:DES|DESede|RC4|ARCFOUR)`,
781
+ "from Crypto\\.Cipher import (?:DES|DES3|ARC4)",
782
+ "from Cryptodome\\.Cipher import (?:DES|DES3|ARC4)"
783
+ ],
784
+ antiPatterns: [
785
+ "\\btest\\b|\\bspec\\b|__tests__|__fixtures__",
786
+ "legacy.compat|compat.legacy"
787
+ ],
788
+ flags: ""
789
+ },
790
+ 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.",
791
+ 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.",
792
+ 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).",
793
+ findingType: "vulnerability",
794
+ aiCodeTarget: true,
795
+ references: [
796
+ "https://csrc.nist.gov/pubs/sp/800/131/a/r3/ipd",
797
+ "https://cwe.mitre.org/data/definitions/327.html"
798
+ ]
799
+ },
800
+ {
801
+ id: "generic.crypto.math-random-token",
802
+ framework: [
803
+ "generic"
804
+ ],
805
+ category: "crypto",
806
+ tier: "free",
807
+ severity: "high",
808
+ confidence: "HIGH",
809
+ action: "block",
810
+ version: 3,
811
+ status: "experimental",
812
+ cwe: [
813
+ "CWE-338"
814
+ ],
815
+ owasp: [
816
+ "A02:2021"
817
+ ],
818
+ matcher: {
819
+ type: "pattern",
820
+ fileGlob: "**/*.{ts,js,tsx,jsx}",
821
+ patterns: [
822
+ "(token|session|secret|password|nonce|csrf|otp|apiKey|authToken)\\s*=\\s*Math\\.random\\s*\\(",
823
+ "(token|session|secret|password|nonce|csrf|otp|apiKey|authToken)\\s*=\\s*[a-z_]+\\s*\\+\\s*Math\\.random\\s*\\(",
824
+ "Math\\.random\\s*\\(\\s*\\)\\.toString\\s*\\(\\)"
825
+ ],
826
+ antiPatterns: [
827
+ "\\btest\\b|\\bspec\\b|__fixtures__|jitter|delay|sample|color|position",
828
+ "eslint-disable"
829
+ ],
830
+ flags: "i"
831
+ },
832
+ 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.",
833
+ 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)`.",
834
+ fix: "Replace `Math.random()` with `crypto.randomBytes(32).toString('hex')` for token generation.",
835
+ findingType: "vulnerability",
836
+ aiCodeTarget: true,
837
+ references: [
838
+ "https://cwe.mitre.org/data/definitions/338.html"
839
+ ]
840
+ },
841
+ {
842
+ id: "generic.crypto.md5-sha1-password-hash",
843
+ framework: [
844
+ "generic"
845
+ ],
846
+ category: "crypto",
847
+ tier: "free",
848
+ severity: "high",
849
+ confidence: "HIGH",
850
+ action: "block",
851
+ version: 5,
852
+ status: "experimental",
853
+ cwe: [
854
+ "CWE-916",
855
+ "CWE-327"
856
+ ],
857
+ owasp: [
858
+ "A02:2021"
859
+ ],
860
+ matcher: {
861
+ type: "pattern",
862
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,rb,go,java,php}",
863
+ patterns: [
864
+ "hashlib\\.(md5|sha1)\\s{0,8}\\(\\s{0,8}(password|passwd|pwd|secret|credential|raw_password|auth_pass|user_input|new_password|old_password)",
865
+ "(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}\\(",
866
+ `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)`,
867
+ `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)`
868
+ ],
869
+ antiPatterns: [
870
+ "\\btest\\b|\\bspec\\b|__fixtures__|checksum|etag|fingerprint|cache",
871
+ "nosec|eslint-disable"
872
+ ],
873
+ flags: "i"
874
+ },
875
+ 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.",
876
+ 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.",
877
+ fix: "Use bcrypt: `const hash = await bcrypt.hash(password, 12)` or Argon2id via the argon2 package.",
878
+ findingType: "vulnerability",
879
+ aiCodeTarget: true,
880
+ references: [
881
+ "https://cwe.mitre.org/data/definitions/916.html",
882
+ "https://cwe.mitre.org/data/definitions/327.html"
883
+ ]
884
+ },
885
+ {
886
+ id: "generic.crypto.static-iv",
887
+ framework: [
888
+ "generic"
889
+ ],
890
+ category: "crypto",
891
+ tier: "free",
892
+ severity: "high",
893
+ confidence: "MEDIUM",
894
+ action: "warn",
895
+ version: 3,
896
+ status: "experimental",
897
+ cwe: [
898
+ "CWE-329",
899
+ "CWE-327"
900
+ ],
901
+ owasp: [
902
+ "A02:2021"
903
+ ],
904
+ matcher: {
905
+ type: "pattern",
906
+ fileGlob: "**/*.{ts,js,tsx,jsx}",
907
+ patterns: [
908
+ "Buffer\\.alloc\\s*\\(\\s*(?:12|16)\\s*,\\s*0\\s*\\)",
909
+ `Buffer\\.from\\s*\\(\\s*['"]0{16,32}['"]\\s*,\\s*['"]hex['"]\\s*\\)`,
910
+ `const\\s+iv\\s*=\\s*['"]0{16,32}['"]`
911
+ ],
912
+ antiPatterns: [
913
+ "\\btest\\b|\\bspec\\b|__tests__|__fixtures__",
914
+ "crypto\\.randomBytes|randomBytes|randomFill|randomUUID"
915
+ ],
916
+ flags: ""
917
+ },
918
+ 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.",
919
+ 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.",
920
+ fix: "Replace Buffer.alloc(16, 0) with crypto.randomBytes(16). For GCM use crypto.randomBytes(12). Store IV with ciphertext.",
921
+ findingType: "vulnerability",
922
+ aiCodeTarget: true,
923
+ references: [
924
+ "https://cwe.mitre.org/data/definitions/329.html",
925
+ "https://cwe.mitre.org/data/definitions/327.html"
926
+ ]
927
+ },
928
+ {
929
+ id: "generic.injection.child-process-exec",
930
+ framework: [
931
+ "generic"
932
+ ],
933
+ category: "injection",
934
+ tier: "free",
935
+ severity: "high",
936
+ confidence: "MEDIUM",
937
+ action: "warn",
938
+ version: 3,
939
+ status: "experimental",
940
+ cwe: [
941
+ "CWE-78"
942
+ ],
943
+ owasp: [
944
+ "A03:2021"
945
+ ],
946
+ matcher: {
947
+ type: "pattern",
948
+ fileGlob: "**/*.{ts,js,tsx,jsx}",
949
+ patterns: [
950
+ "\\bexec\\s*\\(\\s*[a-zA-Z_$][a-zA-Z0-9_.]*\\s*\\+",
951
+ "\\bexec\\s*\\(\\s*`[^`]{0,200}\\$\\{",
952
+ "\\bexecSync\\s*\\(\\s*[a-zA-Z_$][a-zA-Z0-9_.]*\\s*\\+",
953
+ "\\bexecSync\\s*\\(\\s*`[^`]{0,200}\\$\\{"
954
+ ],
955
+ antiPatterns: [
956
+ "\\btest\\b|\\bspec\\b|__tests__|__fixtures__",
957
+ "eslint-disable"
958
+ ],
959
+ flags: ""
960
+ },
961
+ 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.",
962
+ 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.",
963
+ fix: "Replace exec('ls ' + userPath) with execFile('ls', [userPath]) to avoid shell interpretation.",
964
+ findingType: "vulnerability",
965
+ aiCodeTarget: true,
966
+ references: [
967
+ "https://cwe.mitre.org/data/definitions/78.html"
968
+ ]
969
+ },
970
+ {
971
+ id: "generic.injection.eval-user-input",
972
+ framework: [
973
+ "generic"
974
+ ],
975
+ category: "injection",
976
+ tier: "free",
977
+ severity: "high",
978
+ confidence: "HIGH",
979
+ action: "block",
980
+ version: 4,
981
+ status: "experimental",
982
+ cwe: [
983
+ "CWE-95"
984
+ ],
985
+ owasp: [
986
+ "A03:2021"
987
+ ],
988
+ matcher: {
989
+ type: "pattern",
990
+ fileGlob: "**/*.{ts,js,tsx,jsx}",
991
+ patterns: [
992
+ "eval\\s*\\(\\s*[a-zA-Z_$][a-zA-Z0-9_.\\[\\]]*\\s*\\)",
993
+ "eval\\s*\\(\\s*[a-zA-Z_$][a-zA-Z0-9_.\\[\\]]*\\s*\\+\\s*[a-zA-Z_$]",
994
+ "eval\\s*\\(`[^`]*`\\)",
995
+ "new\\s+Function\\s*\\(\\s*[a-zA-Z_$][a-zA-Z0-9_.]*\\s*\\)"
996
+ ],
997
+ antiPatterns: [
998
+ `eval\\s*\\(\\s*['"][^'"]{0,200}['"]\\s*\\)`,
999
+ "\\btest\\b|\\bspec\\b|__fixtures__|__tests__",
1000
+ "eslint-disable"
1001
+ ],
1002
+ flags: "",
1003
+ antiPatternScope: "block"
1004
+ },
1005
+ 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.",
1006
+ 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.",
1007
+ fix: "Remove eval(). For JSON use JSON.parse(). For dynamic dispatch use a lookup table { [key]: handler }.",
1008
+ findingType: "vulnerability",
1009
+ aiCodeTarget: true,
1010
+ references: [
1011
+ "https://cwe.mitre.org/data/definitions/95.html"
1012
+ ]
1013
+ },
1014
+ {
1015
+ id: "generic.injection.eval-user-input-python",
1016
+ framework: [
1017
+ "generic"
1018
+ ],
1019
+ category: "injection",
1020
+ tier: "free",
1021
+ severity: "high",
1022
+ confidence: "HIGH",
1023
+ action: "block",
1024
+ version: 3,
1025
+ status: "experimental",
1026
+ cwe: [
1027
+ "CWE-95",
1028
+ "CWE-94"
1029
+ ],
1030
+ owasp: [
1031
+ "A03:2021"
1032
+ ],
1033
+ matcher: {
1034
+ type: "pattern",
1035
+ fileGlob: "**/*.py",
1036
+ patterns: [
1037
+ "eval\\s*\\(\\s*(?:request|req)\\b",
1038
+ "exec\\s*\\(\\s*(?:request|req)\\b",
1039
+ "eval\\s*\\(\\s*input\\s*\\(",
1040
+ "exec\\s*\\(\\s*input\\s*\\(",
1041
+ `eval\\s*\\(\\s*f['"]`,
1042
+ `exec\\s*\\(\\s*f['"]`
1043
+ ],
1044
+ antiPatterns: [
1045
+ "\\.test\\.|\\bspec\\b|__tests__|test_|_test\\.py|conftest\\.py",
1046
+ "#\\s*nosec"
1047
+ ],
1048
+ flags: ""
1049
+ },
1050
+ 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.",
1051
+ 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.",
1052
+ fix: "Replace eval() with ast.literal_eval() for safe Python literal parsing, or json.loads() for JSON data.",
1053
+ findingType: "vulnerability",
1054
+ aiCodeTarget: true,
1055
+ references: [
1056
+ "https://cwe.mitre.org/data/definitions/95.html",
1057
+ "https://cwe.mitre.org/data/definitions/94.html"
1058
+ ]
1059
+ },
1060
+ {
1061
+ id: "generic.injection.shell-true",
1062
+ framework: [
1063
+ "generic"
1064
+ ],
1065
+ category: "injection",
1066
+ tier: "free",
1067
+ severity: "high",
1068
+ confidence: "HIGH",
1069
+ action: "block",
1070
+ version: 3,
1071
+ status: "experimental",
1072
+ cwe: [
1073
+ "CWE-78"
1074
+ ],
1075
+ owasp: [
1076
+ "A03:2021"
1077
+ ],
1078
+ matcher: {
1079
+ type: "pattern",
1080
+ fileGlob: "**/*.{py,rb,sh}",
1081
+ patterns: [
1082
+ "subprocess\\.(run|Popen|call|check_output)\\s*\\(\\s*shell\\s*=\\s*True",
1083
+ "shell\\s*=\\s*True",
1084
+ `os\\.system\\s*\\(\\s*f['"]`,
1085
+ "os\\.system\\s*\\([a-zA-Z_][a-zA-Z0-9_]*\\s*\\+"
1086
+ ],
1087
+ antiPatterns: [
1088
+ "\\btest\\b|\\bspec\\b|__fixtures__",
1089
+ "#\\s*safe"
1090
+ ],
1091
+ flags: ""
1092
+ },
1093
+ 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.",
1094
+ 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.',
1095
+ fix: "Replace `subprocess.run(cmd_string, shell=True)` with `subprocess.run(['cmd', arg], shell=False)`.",
1096
+ findingType: "vulnerability",
1097
+ aiCodeTarget: true,
1098
+ references: [
1099
+ "https://cwe.mitre.org/data/definitions/78.html",
1100
+ "https://github.com/PyCQA/bandit"
1101
+ ]
1102
+ },
1103
+ {
1104
+ id: "generic.injection.unsafe-deserialization-python",
1105
+ framework: [
1106
+ "generic"
1107
+ ],
1108
+ category: "injection",
1109
+ tier: "free",
1110
+ severity: "high",
1111
+ confidence: "HIGH",
1112
+ action: "block",
1113
+ version: 3,
1114
+ status: "experimental",
1115
+ cwe: [
1116
+ "CWE-502"
1117
+ ],
1118
+ owasp: [
1119
+ "A08:2021"
1120
+ ],
1121
+ matcher: {
1122
+ type: "pattern",
1123
+ fileGlob: "**/*.py",
1124
+ patterns: [
1125
+ "yaml\\.load\\s*\\(",
1126
+ "yaml\\.unsafe_load\\s*\\(",
1127
+ "pickle\\.loads\\s*\\(",
1128
+ "pickle\\.load\\s*\\("
1129
+ ],
1130
+ antiPatterns: [
1131
+ "\\.test\\.|\\bspec\\b|__tests__|test_|_test\\.py|conftest\\.py",
1132
+ "SafeLoader|yaml\\.safe_load"
1133
+ ],
1134
+ flags: ""
1135
+ },
1136
+ 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.",
1137
+ 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.",
1138
+ fix: "Replace yaml.load(data) with yaml.safe_load(data). For pickle, switch to json.loads() for untrusted external data.",
1139
+ findingType: "vulnerability",
1140
+ aiCodeTarget: true,
1141
+ references: [
1142
+ "https://cwe.mitre.org/data/definitions/502.html",
1143
+ "https://pyyaml.org/wiki/PyYAMLDocumentation"
1144
+ ]
1145
+ },
1146
+ {
1147
+ id: "generic.injection.vm-runcontext",
1148
+ framework: [
1149
+ "generic"
1150
+ ],
1151
+ category: "injection",
1152
+ tier: "free",
1153
+ severity: "high",
1154
+ confidence: "MEDIUM",
1155
+ action: "warn",
1156
+ version: 3,
1157
+ status: "experimental",
1158
+ cwe: [
1159
+ "CWE-95"
1160
+ ],
1161
+ owasp: [
1162
+ "A03:2021"
1163
+ ],
1164
+ matcher: {
1165
+ type: "pattern",
1166
+ fileGlob: "**/*.{ts,js,tsx,jsx}",
1167
+ patterns: [
1168
+ "vm\\.runInThisContext\\s*\\(",
1169
+ "vm\\.runInNewContext\\s*\\(",
1170
+ "new vm\\.Script\\s*\\("
1171
+ ],
1172
+ antiPatterns: [
1173
+ "\\btest\\b|\\bspec\\b|__tests__|__fixtures__",
1174
+ "eslint-disable"
1175
+ ],
1176
+ flags: ""
1177
+ },
1178
+ 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.',
1179
+ 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.",
1180
+ fix: "Remove vm.runInThisContext/runInNewContext. Use isolated-vm or subprocess sandboxing for untrusted code execution.",
1181
+ findingType: "vulnerability",
1182
+ aiCodeTarget: true,
1183
+ references: [
1184
+ "https://cwe.mitre.org/data/definitions/95.html",
1185
+ "https://nodejs.org/api/vm.html"
1186
+ ]
1187
+ },
1188
+ {
1189
+ id: "generic.secrets.anthropic-api-key",
1190
+ framework: [
1191
+ "generic"
1192
+ ],
1193
+ category: "secrets",
1194
+ tier: "local",
1195
+ severity: "critical",
1196
+ confidence: "HIGH",
1197
+ action: "block",
1198
+ version: 4,
1199
+ status: "experimental",
1200
+ cwe: [
1201
+ "CWE-798"
1202
+ ],
1203
+ owasp: [
1204
+ "A07:2021"
1205
+ ],
1206
+ matcher: {
1207
+ type: "pattern",
1208
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,env,.env*}",
1209
+ patterns: [
1210
+ "sk-ant-api03-[a-zA-Z0-9]{80,100}"
1211
+ ],
1212
+ antiPatterns: [
1213
+ "YOUR_API_KEY|REPLACE_ME|example|placeholder|sk-ant-test",
1214
+ "process\\.env\\.[A-Za-z0-9_]+!?\\s*(?:[,;)}\\]]|$)",
1215
+ `os\\.environ(?:\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)|\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\])?(?:[,;)}\\]]|$)`
1216
+ ],
1217
+ flags: ""
1218
+ },
1219
+ 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.",
1220
+ 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.",
1221
+ fix: "Replace the literal key with `process.env.ANTHROPIC_API_KEY` and add ANTHROPIC_API_KEY to .env.local (gitignored).",
1222
+ findingType: "vulnerability",
1223
+ aiCodeTarget: true,
1224
+ references: [
1225
+ "https://cwe.mitre.org/data/definitions/798.html"
1226
+ ]
1227
+ },
1228
+ {
1229
+ id: "generic.secrets.aws-access-key",
1230
+ framework: [
1231
+ "generic"
1232
+ ],
1233
+ category: "secrets",
1234
+ tier: "local",
1235
+ severity: "high",
1236
+ confidence: "HIGH",
1237
+ action: "block",
1238
+ version: 4,
1239
+ status: "experimental",
1240
+ cwe: [
1241
+ "CWE-798"
1242
+ ],
1243
+ owasp: [
1244
+ "A07:2021"
1245
+ ],
1246
+ matcher: {
1247
+ type: "pattern",
1248
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,go,rb,java,yaml,yml,json,toml,cfg,conf,ini,sh,env}",
1249
+ patterns: [
1250
+ "(A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}"
1251
+ ],
1252
+ antiPatterns: [
1253
+ "YOUR_KEY|REPLACE_ME|EXAMPLE|PLACEHOLDER|FAKE|DUMMY|example|placeholder",
1254
+ "process\\.env\\.[A-Za-z0-9_]+!?\\s*(?:[,;)}\\]]|$)",
1255
+ `os\\.environ(?:\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)|\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\])?(?:[,;)}\\]]|$)`,
1256
+ `ENV\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\](?:[,;)}\\]]|$)`,
1257
+ `secrets\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)(?:[,;)}\\]]|$)`,
1258
+ `secrets\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\](?:[,;)}\\]]|$)`,
1259
+ "\\.test\\.|\\bspec\\b|__tests__"
1260
+ ],
1261
+ flags: ""
1262
+ },
1263
+ 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.",
1264
+ 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.",
1265
+ fix: "Replace the literal key with `process.env.AWS_ACCESS_KEY_ID` and use IAM roles or AWS credential providers in production.",
1266
+ findingType: "vulnerability",
1267
+ aiCodeTarget: true,
1268
+ references: [
1269
+ "https://cwe.mitre.org/data/definitions/798.html",
1270
+ "https://github.com/gitleaks/gitleaks"
1271
+ ]
1272
+ },
1273
+ {
1274
+ id: "generic.secrets.azure-storage-key",
1275
+ framework: [
1276
+ "generic"
1277
+ ],
1278
+ category: "secrets",
1279
+ tier: "local",
1280
+ severity: "high",
1281
+ confidence: "HIGH",
1282
+ action: "block",
1283
+ version: 4,
1284
+ status: "experimental",
1285
+ cwe: [
1286
+ "CWE-798"
1287
+ ],
1288
+ owasp: [
1289
+ "A07:2021"
1290
+ ],
1291
+ matcher: {
1292
+ type: "pattern",
1293
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,go,cs,env,yaml,yml,json,conf,ini,xml,config}",
1294
+ patterns: [
1295
+ "AccountKey\\s*=\\s*[a-zA-Z0-9+/]{40,100}={0,2}"
1296
+ ],
1297
+ antiPatterns: [
1298
+ "AccountKey=YOUR_KEY|AccountKey=REPLACE_ME|AccountKey=example|AccountKey=test",
1299
+ "process\\.env\\.[A-Za-z0-9_]+!?\\s*(?:[,;)}\\]]|$)",
1300
+ `os\\.environ(?:\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)|\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\])?(?:[,;)}\\]]|$)`,
1301
+ `ENV\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\](?:[,;)}\\]]|$)`,
1302
+ `secrets\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)(?:[,;)}\\]]|$)`,
1303
+ `secrets\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\](?:[,;)}\\]]|$)`,
1304
+ "\\.test\\.|\\bspec\\b|__tests__"
1305
+ ],
1306
+ flags: ""
1307
+ },
1308
+ 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.",
1309
+ 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.",
1310
+ fix: "Replace with `process.env.AZURE_STORAGE_CONNECTION_STRING` and rotate the account key in Azure Portal.",
1311
+ findingType: "vulnerability",
1312
+ aiCodeTarget: true,
1313
+ references: [
1314
+ "https://cwe.mitre.org/data/definitions/798.html",
1315
+ "https://github.com/gitleaks/gitleaks"
1316
+ ]
1317
+ },
1318
+ {
1319
+ id: "generic.secrets.db-connection-string",
1320
+ framework: [
1321
+ "generic"
1322
+ ],
1323
+ category: "secrets",
1324
+ tier: "local",
1325
+ severity: "high",
1326
+ confidence: "HIGH",
1327
+ action: "block",
1328
+ version: 4,
1329
+ status: "experimental",
1330
+ cwe: [
1331
+ "CWE-259",
1332
+ "CWE-798"
1333
+ ],
1334
+ owasp: [
1335
+ "A07:2021"
1336
+ ],
1337
+ matcher: {
1338
+ type: "pattern",
1339
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,go,rb,java,env,yaml,yml,json,conf,ini,toml}",
1340
+ patterns: [
1341
+ "(postgres|postgresql|mysql|mongodb|mongodb\\+srv|redis|mssql|sqlserver)://[a-zA-Z0-9._%-]+:[a-zA-Z0-9._@!#$%^&*()-]+@[a-zA-Z0-9._-]+"
1342
+ ],
1343
+ antiPatterns: [
1344
+ "YOUR_DB_PASSWORD|REPLACE_ME|password_here|<password>",
1345
+ "process\\.env\\.[A-Za-z0-9_]+!?\\s*(?:[,;)}\\]]|$)",
1346
+ `os\\.environ(?:\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)|\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\])?(?:[,;)}\\]]|$)`,
1347
+ `ENV\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\](?:[,;)}\\]]|$)`,
1348
+ `secrets\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)(?:[,;)}\\]]|$)`,
1349
+ `secrets\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\](?:[,;)}\\]]|$)`,
1350
+ "\\.test\\.|\\bspec\\b|__tests__"
1351
+ ],
1352
+ flags: "i"
1353
+ },
1354
+ 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.",
1355
+ 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.",
1356
+ fix: "Replace with `process.env.DATABASE_URL` and rotate the database password.",
1357
+ findingType: "vulnerability",
1358
+ aiCodeTarget: true,
1359
+ references: [
1360
+ "https://cwe.mitre.org/data/definitions/259.html",
1361
+ "https://cwe.mitre.org/data/definitions/798.html"
1362
+ ]
1363
+ },
1364
+ {
1365
+ id: "generic.secrets.gcp-service-account-key",
1366
+ framework: [
1367
+ "generic"
1368
+ ],
1369
+ category: "secrets",
1370
+ tier: "local",
1371
+ severity: "high",
1372
+ confidence: "HIGH",
1373
+ action: "block",
1374
+ version: 4,
1375
+ status: "experimental",
1376
+ cwe: [
1377
+ "CWE-798"
1378
+ ],
1379
+ owasp: [
1380
+ "A07:2021"
1381
+ ],
1382
+ matcher: {
1383
+ type: "pattern",
1384
+ fileGlob: "**/*.{json,js,ts,py,go,yaml,yml,conf,env}",
1385
+ patterns: [
1386
+ '"type"\\s*:\\s*"service_account"',
1387
+ '"private_key_id"\\s*:\\s*"[a-f0-9]{40}"'
1388
+ ],
1389
+ antiPatterns: [
1390
+ "YOUR_KEY_ID|REPLACE_ME|test_service_account",
1391
+ `os\\.environ(?:\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)|\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\])?(?:[,;)}\\]]|$)`,
1392
+ "process\\.env\\.[A-Za-z0-9_]+!?\\s*(?:[,;)}\\]]|$)",
1393
+ "\\.test\\.|\\bspec\\b|__tests__"
1394
+ ],
1395
+ flags: ""
1396
+ },
1397
+ 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.',
1398
+ 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.",
1399
+ fix: "Delete the key JSON from source. Use `GOOGLE_APPLICATION_CREDENTIALS=/path/to/key.json` loaded at runtime outside the repo.",
1400
+ findingType: "vulnerability",
1401
+ aiCodeTarget: true,
1402
+ references: [
1403
+ "https://cwe.mitre.org/data/definitions/798.html",
1404
+ "https://cloud.google.com/iam/docs/best-practices-for-managing-service-account-keys"
1405
+ ]
1406
+ },
1407
+ {
1408
+ id: "generic.secrets.github-token",
1409
+ framework: [
1410
+ "generic"
1411
+ ],
1412
+ category: "secrets",
1413
+ tier: "local",
1414
+ severity: "high",
1415
+ confidence: "HIGH",
1416
+ action: "block",
1417
+ version: 4,
1418
+ status: "experimental",
1419
+ cwe: [
1420
+ "CWE-798"
1421
+ ],
1422
+ owasp: [
1423
+ "A07:2021"
1424
+ ],
1425
+ matcher: {
1426
+ type: "pattern",
1427
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,go,rb,yaml,yml,env,json,sh,conf}",
1428
+ patterns: [
1429
+ "(ghp_|gho_|ghu_|ghs_|ghr_|github_pat_)[a-zA-Z0-9_]{20,80}"
1430
+ ],
1431
+ antiPatterns: [
1432
+ "YOUR_TOKEN|REPLACE_ME|ghp_example|ghp_xxxx|github_pat_example",
1433
+ "process\\.env\\.[A-Za-z0-9_]+!?\\s*(?:[,;)}\\]]|$)",
1434
+ `os\\.environ(?:\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)|\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\])?(?:[,;)}\\]]|$)`,
1435
+ `ENV\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\](?:[,;)}\\]]|$)`,
1436
+ `secrets\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)(?:[,;)}\\]]|$)`,
1437
+ `secrets\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\](?:[,;)}\\]]|$)`,
1438
+ "\\.test\\.|\\bspec\\b|__tests__"
1439
+ ],
1440
+ flags: ""
1441
+ },
1442
+ 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.",
1443
+ 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.",
1444
+ fix: "Replace with `process.env.GITHUB_TOKEN` and revoke the exposed token at github.com/settings/tokens.",
1445
+ findingType: "vulnerability",
1446
+ aiCodeTarget: true,
1447
+ references: [
1448
+ "https://cwe.mitre.org/data/definitions/798.html",
1449
+ "https://github.com/gitleaks/gitleaks"
1450
+ ]
1451
+ },
1452
+ {
1453
+ id: "generic.secrets.huggingface-token",
1454
+ framework: [
1455
+ "generic"
1456
+ ],
1457
+ category: "secrets",
1458
+ tier: "local",
1459
+ severity: "high",
1460
+ confidence: "HIGH",
1461
+ action: "block",
1462
+ version: 4,
1463
+ status: "experimental",
1464
+ cwe: [
1465
+ "CWE-798"
1466
+ ],
1467
+ owasp: [
1468
+ "A07:2021"
1469
+ ],
1470
+ matcher: {
1471
+ type: "pattern",
1472
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,env,.env*}",
1473
+ patterns: [
1474
+ "hf_[a-zA-Z0-9]{34}"
1475
+ ],
1476
+ antiPatterns: [
1477
+ "YOUR_TOKEN|REPLACE_ME|example|placeholder",
1478
+ "process\\.env\\.[A-Za-z0-9_]+!?\\s*(?:[,;)}\\]]|$)",
1479
+ `os\\.environ(?:\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)|\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\])?(?:[,;)}\\]]|$)`
1480
+ ],
1481
+ flags: ""
1482
+ },
1483
+ 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.",
1484
+ 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.",
1485
+ fix: "Replace the literal token with `process.env.HF_TOKEN` and add HF_TOKEN to .env.local (gitignored).",
1486
+ findingType: "vulnerability",
1487
+ aiCodeTarget: true,
1488
+ references: [
1489
+ "https://cwe.mitre.org/data/definitions/798.html",
1490
+ "https://huggingface.co/docs/hub/security-tokens"
1491
+ ]
1492
+ },
1493
+ {
1494
+ id: "generic.secrets.openai-api-key",
1495
+ framework: [
1496
+ "generic"
1497
+ ],
1498
+ category: "secrets",
1499
+ tier: "local",
1500
+ severity: "critical",
1501
+ confidence: "HIGH",
1502
+ action: "block",
1503
+ version: 4,
1504
+ status: "experimental",
1505
+ cwe: [
1506
+ "CWE-798"
1507
+ ],
1508
+ owasp: [
1509
+ "A07:2021"
1510
+ ],
1511
+ matcher: {
1512
+ type: "pattern",
1513
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,env,.env*}",
1514
+ patterns: [
1515
+ "sk-[a-zA-Z0-9]{48}",
1516
+ "sk-proj-[a-zA-Z0-9_-]{43}"
1517
+ ],
1518
+ antiPatterns: [
1519
+ "YOUR_API_KEY|REPLACE_ME|example|placeholder|sk-test",
1520
+ "process\\.env\\.[A-Za-z0-9_]+!?\\s*(?:[,;)}\\]]|$)",
1521
+ `os\\.environ(?:\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)|\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\])?(?:[,;)}\\]]|$)`
1522
+ ],
1523
+ flags: ""
1524
+ },
1525
+ 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.",
1526
+ 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.",
1527
+ fix: "Replace the literal key with `process.env.OPENAI_API_KEY` and add OPENAI_API_KEY to .env.local (gitignored).",
1528
+ findingType: "vulnerability",
1529
+ aiCodeTarget: true
1530
+ },
1531
+ {
1532
+ id: "generic.secrets.private-key-pem",
1533
+ framework: [
1534
+ "generic"
1535
+ ],
1536
+ category: "secrets",
1537
+ tier: "local",
1538
+ severity: "high",
1539
+ confidence: "HIGH",
1540
+ action: "block",
1541
+ version: 4,
1542
+ status: "experimental",
1543
+ cwe: [
1544
+ "CWE-321"
1545
+ ],
1546
+ owasp: [
1547
+ "A02:2021"
1548
+ ],
1549
+ matcher: {
1550
+ type: "pattern",
1551
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,go,rb,java,pem,key,env,yaml,yml,json,conf}",
1552
+ patterns: [
1553
+ "-----BEGIN (RSA |EC |DSA |OPENSSH |ENCRYPTED |PRIVATE KEY|)[^-]{0,30}PRIVATE KEY-----(?:\\n|\\\\n)[ \\t]{0,20}[A-Za-z0-9+/=]{40,1000}"
1554
+ ],
1555
+ antiPatterns: [
1556
+ "REPLACE_ME|YOUR_PRIVATE_KEY|example_key|test_key|dummy_key",
1557
+ "readFileSync|loadKey|fs\\.read|open\\(|path\\.join",
1558
+ "\\.test\\.|\\bspec\\b|__tests__|__fixtures__"
1559
+ ],
1560
+ flags: ""
1561
+ },
1562
+ 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.",
1563
+ 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.",
1564
+ fix: "Store the key in a file outside the repository and load with `fs.readFileSync(process.env.PRIVATE_KEY_PATH, 'utf8')`.",
1565
+ findingType: "vulnerability",
1566
+ aiCodeTarget: true,
1567
+ references: [
1568
+ "https://cwe.mitre.org/data/definitions/321.html",
1569
+ "https://github.com/gitleaks/gitleaks"
1570
+ ]
1571
+ },
1572
+ {
1573
+ id: "generic.secrets.slack-token",
1574
+ framework: [
1575
+ "generic"
1576
+ ],
1577
+ category: "secrets",
1578
+ tier: "local",
1579
+ severity: "high",
1580
+ confidence: "HIGH",
1581
+ action: "block",
1582
+ version: 4,
1583
+ status: "experimental",
1584
+ cwe: [
1585
+ "CWE-798"
1586
+ ],
1587
+ owasp: [
1588
+ "A07:2021"
1589
+ ],
1590
+ matcher: {
1591
+ type: "pattern",
1592
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,go,rb,env,yaml,yml,json,conf,ini}",
1593
+ patterns: [
1594
+ "xox[bpoas]-[0-9a-zA-Z-]{10,120}"
1595
+ ],
1596
+ antiPatterns: [
1597
+ "xoxb-REPLACE|xoxb-example|YOUR_SLACK_TOKEN|xox.-xxxx",
1598
+ "process\\.env\\.[A-Za-z0-9_]+!?\\s*(?:[,;)}\\]]|$)",
1599
+ `os\\.environ(?:\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)|\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\])?(?:[,;)}\\]]|$)`,
1600
+ `ENV\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\](?:[,;)}\\]]|$)`,
1601
+ `secrets\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)(?:[,;)}\\]]|$)`,
1602
+ `secrets\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\](?:[,;)}\\]]|$)`,
1603
+ "\\.test\\.|\\bspec\\b|__tests__"
1604
+ ],
1605
+ flags: ""
1606
+ },
1607
+ 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.",
1608
+ 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.",
1609
+ fix: "Replace with `process.env.SLACK_BOT_TOKEN` and revoke the exposed token at api.slack.com/apps.",
1610
+ findingType: "vulnerability",
1611
+ aiCodeTarget: true,
1612
+ references: [
1613
+ "https://cwe.mitre.org/data/definitions/798.html",
1614
+ "https://docs.slack.dev/authentication/tokens/"
1615
+ ]
1616
+ },
1617
+ {
1618
+ id: "generic.secrets.stripe-live-key",
1619
+ framework: [
1620
+ "generic"
1621
+ ],
1622
+ category: "secrets",
1623
+ tier: "local",
1624
+ severity: "critical",
1625
+ confidence: "HIGH",
1626
+ action: "block",
1627
+ version: 5,
1628
+ status: "experimental",
1629
+ cwe: [
1630
+ "CWE-798"
1631
+ ],
1632
+ owasp: [
1633
+ "A07:2021"
1634
+ ],
1635
+ matcher: {
1636
+ type: "pattern",
1637
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,rb,go,yaml,yml,json,conf,ini,env}",
1638
+ patterns: [
1639
+ "sk_live_[a-zA-Z0-9]{20,64}"
1640
+ ],
1641
+ antiPatterns: [
1642
+ "sk_live_xxxx|YOUR_STRIPE_KEY|REPLACE_ME",
1643
+ "process\\.env\\.[A-Za-z0-9_]+!?\\s*(?:[,;)}\\]]|$)",
1644
+ `os\\.environ(?:\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)|\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\])?(?:[,;)}\\]]|$)`,
1645
+ `ENV\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\](?:[,;)}\\]]|$)`,
1646
+ `secrets\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)(?:[,;)}\\]]|$)`,
1647
+ `secrets\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\](?:[,;)}\\]]|$)`,
1648
+ "\\.test\\.|\\bspec\\b|__tests__"
1649
+ ],
1650
+ flags: ""
1651
+ },
1652
+ 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.",
1653
+ 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.",
1654
+ fix: "Replace with `process.env.STRIPE_SECRET_KEY` and add it to .env.local (gitignored). Rotate the exposed key immediately.",
1655
+ findingType: "vulnerability",
1656
+ aiCodeTarget: true,
1657
+ references: [
1658
+ "https://cwe.mitre.org/data/definitions/798.html",
1659
+ "https://docs.stripe.com/keys-best-practices"
1660
+ ]
1661
+ },
1662
+ {
1663
+ id: "generic.tls.reject-unauthorized-disabled",
1664
+ framework: [
1665
+ "generic"
1666
+ ],
1667
+ category: "config",
1668
+ tier: "free",
1669
+ severity: "high",
1670
+ confidence: "HIGH",
1671
+ action: "block",
1672
+ version: 4,
1673
+ status: "experimental",
1674
+ cwe: [
1675
+ "CWE-295"
1676
+ ],
1677
+ owasp: [
1678
+ "A02:2021"
1679
+ ],
1680
+ matcher: {
1681
+ type: "pattern",
1682
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,go,rb,yaml,yml,conf,env}",
1683
+ patterns: [
1684
+ "rejectUnauthorized\\s*:\\s*false",
1685
+ `NODE_TLS_REJECT_UNAUTHORIZED\\s*[=:]\\s*['"]?0['"]?`,
1686
+ "verify\\s*=\\s*False",
1687
+ "ssl\\._create_unverified_context\\s*\\(",
1688
+ "verify_mode\\s*=\\s*ssl\\.CERT_NONE",
1689
+ "InsecureSkipVerify\\s*:\\s*true"
1690
+ ],
1691
+ antiPatterns: [
1692
+ "\\.test\\.|\\bspec\\b|__tests__|__fixtures__",
1693
+ "dev-only|local-only|localhost_only"
1694
+ ],
1695
+ flags: "",
1696
+ antiPatternScope: {
1697
+ lines: 3
1698
+ }
1699
+ },
1700
+ 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.",
1701
+ 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.",
1702
+ fix: "Remove `rejectUnauthorized: false`. For self-signed certs use `ca: [fs.readFileSync('ca.crt')]` instead.",
1703
+ findingType: "vulnerability",
1704
+ aiCodeTarget: true,
1705
+ references: [
1706
+ "https://cwe.mitre.org/data/definitions/295.html"
1707
+ ]
1708
+ },
1709
+ {
1710
+ id: "generic.tls.verify-disabled-python",
1711
+ framework: [
1712
+ "generic"
1713
+ ],
1714
+ category: "config",
1715
+ tier: "free",
1716
+ severity: "high",
1717
+ confidence: "HIGH",
1718
+ action: "block",
1719
+ version: 3,
1720
+ status: "experimental",
1721
+ cwe: [
1722
+ "CWE-295"
1723
+ ],
1724
+ owasp: [
1725
+ "A02:2021"
1726
+ ],
1727
+ matcher: {
1728
+ type: "pattern",
1729
+ fileGlob: "**/*.py",
1730
+ patterns: [
1731
+ "verify\\s*=\\s*False",
1732
+ "ssl\\._create_unverified_context\\s*\\(",
1733
+ "\\.verify_mode\\s*=\\s*ssl\\.CERT_NONE"
1734
+ ],
1735
+ antiPatterns: [
1736
+ "\\.test\\.|\\bspec\\b|__tests__|test_|_test\\.py|conftest\\.py",
1737
+ "dev-only|local-only|localhost_only"
1738
+ ],
1739
+ flags: ""
1740
+ },
1741
+ 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.",
1742
+ 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.",
1743
+ 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().",
1744
+ findingType: "vulnerability",
1745
+ aiCodeTarget: true,
1746
+ references: [
1747
+ "https://cwe.mitre.org/data/definitions/295.html",
1748
+ "https://docs.python-requests.org/en/latest/user/advanced/#ssl-cert-verification"
1749
+ ]
1750
+ },
1751
+ {
1752
+ id: "postgresql.auth.trust-auth-method",
1753
+ framework: [
1754
+ "postgresql"
1755
+ ],
1756
+ category: "auth",
1757
+ tier: "free",
1758
+ severity: "critical",
1759
+ confidence: "HIGH",
1760
+ action: "block",
1761
+ version: 3,
1762
+ status: "experimental",
1763
+ cwe: [
1764
+ "CWE-287",
1765
+ "CWE-306"
1766
+ ],
1767
+ owasp: [
1768
+ "A07:2021"
1769
+ ],
1770
+ matcher: {
1771
+ type: "pattern",
1772
+ fileGlob: "**/{pg_hba.conf,docker-compose*.yml,docker-compose*.yaml,.env*}",
1773
+ patterns: [
1774
+ "POSTGRES_HOST_AUTH_METHOD[ \\t]*[:=][ \\t]*trust",
1775
+ "^(host|local)[ \\t]+[^ \\t\\n]+[ \\t]+[^ \\t\\n]+[ \\t]+[^ \\t\\n]+[ \\t]+trust"
1776
+ ],
1777
+ antiPatterns: [
1778
+ "__tests__|test_migration",
1779
+ "# trust|#trust"
1780
+ ],
1781
+ flags: "im"
1782
+ },
1783
+ 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.
1784
+ 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.
1785
+ 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."`,
1786
+ 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.",
1787
+ fix: "Replace 'trust' with 'scram-sha-256' in pg_hba.conf and set POSTGRES_PASSWORD in your Docker configuration.",
1788
+ findingType: "vulnerability",
1789
+ aiCodeTarget: true
1790
+ }
1791
+ ]
1792
+ };
1793
+
1794
+ // src/core/bundled-rules.ts
1795
+ var SUPPORTED_FREE_BUNDLE_SCHEMA_VERSION = 1;
1796
+ var raw = free_bundle_default;
1797
+ var FreeBundleError = class extends Error {
1798
+ constructor(message) {
1799
+ super(message);
1800
+ this.name = "FreeBundleError";
1801
+ }
1802
+ };
1803
+ var validated = false;
1804
+ function validateOnce() {
1805
+ if (validated) return;
1806
+ if (raw.schemaVersion !== SUPPORTED_FREE_BUNDLE_SCHEMA_VERSION) {
1807
+ throw new FreeBundleError(
1808
+ `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.`
1809
+ );
1810
+ }
1811
+ if (!Array.isArray(raw.rules) || raw.rules.length === 0) {
1812
+ throw new FreeBundleError(
1813
+ "Bundled rule set is empty. An offline scan with zero corpus rules would report clean while applying nothing \u2014 failing loud instead."
1814
+ );
1815
+ }
1816
+ if (raw.rules.length !== raw.ruleCount) {
1817
+ throw new FreeBundleError(
1818
+ `Bundled rule set declares ruleCount ${raw.ruleCount} but carries ${raw.rules.length} rules \u2014 the bundle is inconsistent with its own header.`
1819
+ );
1820
+ }
1821
+ const compile = validateBundleCompile(raw.rules);
1822
+ if (!compile.ok) {
1823
+ throw new FreeBundleError(
1824
+ `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.`
1825
+ );
1826
+ }
1827
+ validated = true;
1828
+ }
1829
+ function loadBundledRules() {
1830
+ validateOnce();
1831
+ return raw.rules;
1832
+ }
1833
+ function bundledRulesMeta() {
1834
+ validateOnce();
1835
+ return {
1836
+ corpusVersion: raw.corpusVersion,
1837
+ contentHash: raw.contentHash,
1838
+ ruleCount: raw.ruleCount
1839
+ };
1840
+ }
1841
+
1842
+ // src/core/legacy-corpus-map.ts
1843
+ var LEGACY_TO_CORPUS = Object.freeze({
1844
+ // The legacy secrets check is one catch-all id covering ~15 provider patterns. The corpus
1845
+ // splits the same ground into one rule per provider, each with its own CWE + fix text. Same
1846
+ // line, same secret, better finding.
1847
+ hardcoded_secret: [
1848
+ "generic.secrets.anthropic-api-key",
1849
+ "generic.secrets.aws-access-key",
1850
+ "generic.secrets.azure-storage-key",
1851
+ "generic.secrets.db-connection-string",
1852
+ "generic.secrets.gcp-service-account-key",
1853
+ "generic.secrets.github-token",
1854
+ "generic.secrets.huggingface-token",
1855
+ "generic.secrets.openai-api-key",
1856
+ "generic.secrets.private-key-pem",
1857
+ "generic.secrets.slack-token",
1858
+ "generic.secrets.stripe-live-key"
1859
+ ],
1860
+ // Next.js headers() wildcard CORS — the corpus rule covers the same
1861
+ // `Access-Control-Allow-Origin: *` shape across every framework.
1862
+ deployment_cors_wildcard: ["generic.cors.wildcard-origin"],
1863
+ // `origin: '*'` in a cors() middleware config — same defect, same line.
1864
+ deployment_config_cors_wildcard_origin: ["generic.cors.wildcard-origin"],
1865
+ // `debug: true` in a config file.
1866
+ deployment_config_debug_mode: ["generic.config.debug-mode-enabled"]
1867
+ });
1868
+ var LEGACY_RETAINED_NO_CORPUS_EQUIVALENT = Object.freeze([
1869
+ // secrets
1870
+ "exposed_env",
1871
+ // a .env file tracked by git — a repo-state fact no content regex can see
1872
+ // auth (the corpus has no route-authorization rules at all)
1873
+ "public_admin_route",
1874
+ "auth_route_without_guard",
1875
+ // database
1876
+ "db-drop-table",
1877
+ "db-drop-column",
1878
+ "db-truncate",
1879
+ "db-delete-without-where",
1880
+ "db-alter-drop",
1881
+ "db-push-in-scripts",
1882
+ "db-schema-without-migration",
1883
+ "pkg-json-unparseable-database",
1884
+ // payments
1885
+ "payment_webhook_without_signature_check",
1886
+ "missing_idempotency",
1887
+ "missing_error_handling",
1888
+ // deployment / IaC config shapes
1889
+ "deployment_source_maps_exposed",
1890
+ "deployment_missing_x_frame_options",
1891
+ "deployment_missing_x_content_type",
1892
+ "deployment_docker_root_user",
1893
+ "deployment_docker_unpinned_image",
1894
+ "deployment_compose_unpinned_image",
1895
+ "deployment_vercel_broad_rewrite",
1896
+ "deployment_vercel_missing_headers",
1897
+ "deployment_netlify_missing_headers",
1898
+ "deployment_missing_env_example",
1899
+ "deployment_env_undocumented_keys",
1900
+ "pkg-json-unparseable-deployment"
1901
+ ]);
1902
+ var SEVERITY_RANK = Object.freeze({
1903
+ critical: 4,
1904
+ high: 3,
1905
+ medium: 2,
1906
+ low: 1,
1907
+ info: 0
1908
+ });
1909
+ function dedupeLegacyAgainstCorpus(legacyFindings, corpusFindings, isUserSuppressed = (cf) => cf.suppressed === true) {
1910
+ const corpusIndex = /* @__PURE__ */ new Map();
1911
+ for (const f of corpusFindings) {
1912
+ if (f.line === void 0) continue;
1913
+ const key = `${f.file} ${f.line}`;
1914
+ let byId = corpusIndex.get(key);
1915
+ if (!byId) {
1916
+ byId = /* @__PURE__ */ new Map();
1917
+ corpusIndex.set(key, byId);
1918
+ }
1919
+ byId.set(f.id, f);
1920
+ }
1921
+ const promoted = /* @__PURE__ */ new Map();
1922
+ const notes = [];
1923
+ const severityDisagreements = [];
1924
+ const kept = [];
1925
+ for (const f of legacyFindings) {
1926
+ const mapped = LEGACY_TO_CORPUS[f.id];
1927
+ if (!mapped || f.line === void 0) {
1928
+ kept.push(f);
1929
+ continue;
1930
+ }
1931
+ const atSameLine = corpusIndex.get(`${f.file} ${f.line}`);
1932
+ const twinIds = atSameLine ? mapped.filter((id) => atSameLine.has(id)) : [];
1933
+ const activeTwin = twinIds.find((id) => !atSameLine.get(id).suppressed);
1934
+ const suppressedTwin = twinIds.find((id) => {
1935
+ const cf = atSameLine.get(id);
1936
+ return cf.suppressed === true && isUserSuppressed(cf);
1937
+ });
1938
+ if (f.suppressed) {
1939
+ if (suppressedTwin !== void 0 && activeTwin === void 0) {
1940
+ notes.push({ legacyId: f.id, corpusId: suppressedTwin, file: f.file, line: f.line });
1941
+ } else {
1942
+ kept.push(f);
1943
+ }
1944
+ continue;
1945
+ }
1946
+ if (activeTwin === void 0) {
1947
+ if (suppressedTwin !== void 0) {
1948
+ notes.push({
1949
+ legacyId: f.id,
1950
+ corpusId: suppressedTwin,
1951
+ file: f.file,
1952
+ line: f.line,
1953
+ supersededBySuppressedTwin: true
1954
+ });
1955
+ } else {
1956
+ kept.push(f);
1957
+ }
1958
+ continue;
1959
+ }
1960
+ const winnerId = activeTwin;
1961
+ const corpusFinding = atSameLine.get(winnerId);
1962
+ const legacyRank = SEVERITY_RANK[f.severity] ?? 0;
1963
+ const corpusRank = SEVERITY_RANK[corpusFinding.severity] ?? 0;
1964
+ const severityRaised = legacyRank > corpusRank;
1965
+ if (severityRaised) {
1966
+ severityDisagreements.push({
1967
+ legacyId: f.id,
1968
+ corpusId: winnerId,
1969
+ file: f.file,
1970
+ line: f.line,
1971
+ legacySeverity: f.severity,
1972
+ corpusSeverity: corpusFinding.severity
1973
+ });
1974
+ }
1975
+ const blockingPromoted = f.blocking === true && corpusFinding.blocking !== true;
1976
+ if (severityRaised || blockingPromoted) {
1977
+ const prev = promoted.get(corpusFinding);
1978
+ const nextSeverity = severityRaised && (!prev?.severity || (SEVERITY_RANK[f.severity] ?? 0) > (SEVERITY_RANK[prev.severity] ?? 0)) ? f.severity : prev?.severity;
1979
+ promoted.set(corpusFinding, {
1980
+ legacyId: prev?.legacyId ?? f.id,
1981
+ blocking: blockingPromoted || prev?.blocking === true,
1982
+ severity: nextSeverity
1983
+ });
1984
+ }
1985
+ notes.push({
1986
+ legacyId: f.id,
1987
+ corpusId: winnerId,
1988
+ file: f.file,
1989
+ line: f.line,
1990
+ ...blockingPromoted ? { blockingPromoted: true } : {},
1991
+ ...severityRaised ? { severityRaised: true } : {}
1992
+ });
1993
+ }
1994
+ const outCorpus = corpusFindings.map((cf) => {
1995
+ const p = promoted.get(cf);
1996
+ if (p === void 0) return cf;
1997
+ const notesText = [];
1998
+ if (p.severity) {
1999
+ notesText.push(
2000
+ `Severity raised from ${cf.severity} to ${p.severity} because the equivalent built-in check (${p.legacyId}) rates this defect ${p.severity}.`
2001
+ );
2002
+ }
2003
+ if (p.blocking) {
2004
+ notesText.push(
2005
+ `Reported as BLOCKING because the equivalent built-in check (${p.legacyId}) blocks on this line; this rule's own action is warn.`
2006
+ );
2007
+ }
2008
+ return {
2009
+ ...cf,
2010
+ ...p.severity ? { severity: p.severity } : {},
2011
+ ...p.blocking ? { blocking: true } : {},
2012
+ explanation: `${cf.explanation}
2013
+ [shipguard] ${notesText.join(" ")}`
2014
+ };
2015
+ });
2016
+ return { findings: kept, corpusFindings: outCorpus, notes, severityDisagreements };
2017
+ }
2018
+
2019
+ // src/core/collapse-findings.ts
2020
+ var SEVERITY_RANK2 = Object.freeze({
2021
+ critical: 4,
2022
+ high: 3,
2023
+ medium: 2,
2024
+ low: 1,
2025
+ info: 0
2026
+ });
2027
+ function isSecretsFinding(f) {
2028
+ return f.category === "secrets" || f.id.includes(".secrets.");
2029
+ }
2030
+ function normaliseEvidence(evidence) {
2031
+ return (evidence ?? "").trim().replace(/^(\.\.\.|['"`])+|(\.\.\.|['"`])+$/g, "").trim();
2032
+ }
2033
+ function endLineOf(f) {
2034
+ const start = f.line;
2035
+ if (!f.evidence) return start;
2036
+ let end = f.evidence.length;
2037
+ while (end > 0 && (f.evidence.charCodeAt(end - 1) === 10 || f.evidence.charCodeAt(end - 1) === 13)) end--;
2038
+ let newlines = 0;
2039
+ for (let i = 0; i < end; i++) {
2040
+ if (f.evidence.charCodeAt(i) === 10) newlines++;
2041
+ }
2042
+ return start + newlines;
2043
+ }
2044
+ function outranks(a, b) {
2045
+ return (SEVERITY_RANK2[a.severity] ?? 0) > (SEVERITY_RANK2[b.severity] ?? 0);
2046
+ }
2047
+ function collapseSameIssueFindings(findings) {
2048
+ const groups = /* @__PURE__ */ new Map();
2049
+ for (let i = 0; i < findings.length; i++) {
2050
+ const f = findings[i];
2051
+ if (f.line === void 0) continue;
2052
+ let valueKey = "";
2053
+ if (isSecretsFinding(f)) {
2054
+ if (f.column === void 0) continue;
2055
+ valueKey = normaliseEvidence(f.evidence);
2056
+ }
2057
+ const key = `${f.id}\0${f.file}\0${f.suppressed ? "s" : "a"}\0${valueKey}`;
2058
+ const g = groups.get(key);
2059
+ if (g) g.push(i);
2060
+ else groups.set(key, [i]);
2061
+ }
2062
+ const dropped = /* @__PURE__ */ new Set();
2063
+ const notes = [];
2064
+ for (const indices of groups.values()) {
2065
+ if (indices.length < 2) continue;
2066
+ const ordered = [...indices].sort((x, y) => {
2067
+ const fx = findings[x];
2068
+ const fy = findings[y];
2069
+ return fx.line - fy.line || (fx.column ?? 0) - (fy.column ?? 0) || x - y;
2070
+ });
2071
+ let cluster = [];
2072
+ let clusterEnd = -1;
2073
+ const flush = () => {
2074
+ if (cluster.length < 2) return;
2075
+ let winner = cluster[0];
2076
+ for (const idx of cluster.slice(1)) {
2077
+ if (outranks(findings[idx], findings[winner])) winner = idx;
2078
+ }
2079
+ for (const idx of cluster) {
2080
+ if (idx === winner) continue;
2081
+ dropped.add(idx);
2082
+ const d = findings[idx];
2083
+ notes.push({
2084
+ id: d.id,
2085
+ file: d.file,
2086
+ line: d.line,
2087
+ keptColumn: findings[winner].column,
2088
+ droppedColumn: d.column
2089
+ });
2090
+ }
2091
+ };
2092
+ for (const idx of ordered) {
2093
+ const f = findings[idx];
2094
+ const start = f.line;
2095
+ if (cluster.length > 0 && start <= clusterEnd) {
2096
+ cluster.push(idx);
2097
+ clusterEnd = Math.max(clusterEnd, endLineOf(f));
2098
+ } else {
2099
+ flush();
2100
+ cluster = [idx];
2101
+ clusterEnd = endLineOf(f);
2102
+ }
2103
+ }
2104
+ flush();
2105
+ }
2106
+ if (dropped.size === 0) return { findings, notes };
2107
+ return { findings: findings.filter((_, i) => !dropped.has(i)), notes };
2108
+ }
2109
+
290
2110
  // src/core/scanner.ts
291
2111
  var CHECK_MODULES = [secretsCheck, authCheck, databaseCheck, payments, deploymentCheck];
292
2112
  var DEFAULT_IGNORE = [
@@ -299,10 +2119,45 @@ var DEFAULT_IGNORE = [
299
2119
  // ShipGuard's own report output — never scan the tool's own artifacts
300
2120
  ".shipguard/**"
301
2121
  ];
2122
+ function selfArtifactIgnorePatterns(policy) {
2123
+ const patterns = [];
2124
+ const add = (p) => {
2125
+ if (!p) return;
2126
+ if (p.startsWith("/")) return;
2127
+ const rel = p.replace(/^\.\//, "");
2128
+ if (!rel) return;
2129
+ patterns.push(rel);
2130
+ };
2131
+ const reportOutput = policy.report?.output;
2132
+ add(reportOutput);
2133
+ if (reportOutput) {
2134
+ add(reportOutput.replace(/\.md$/, ".json"));
2135
+ const reportDir = dirname2(reportOutput);
2136
+ add(join3(reportDir === "." ? "" : reportDir, RUNS_SUBDIR, "**"));
2137
+ }
2138
+ add(policy.history?.path);
2139
+ add(process.env[HISTORY_PATH_ENV_VAR]);
2140
+ return patterns;
2141
+ }
2142
+ function computeTreeDigest(files) {
2143
+ if (files.length === 0) return void 0;
2144
+ const encoder = new TextEncoder();
2145
+ const lines = files.map((f) => `${f.relativePath}\0${toHex(sha256(encoder.encode(f.content)))}
2146
+ `).sort(compareScanPaths);
2147
+ return toHex(sha256(encoder.encode(lines.join(""))));
2148
+ }
2149
+ function toHex(bytes) {
2150
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
2151
+ }
302
2152
  async function scan(options, proRules, onProgress) {
303
2153
  const cwd = process.cwd();
304
2154
  const policy = await loadPolicy(cwd);
305
- const ignorePatterns = [...DEFAULT_IGNORE, ...policy.ignore.paths];
2155
+ const ignorePatterns = [
2156
+ ...DEFAULT_IGNORE,
2157
+ // Rec #6 — ShipGuard's own artifacts, wherever the policy put them.
2158
+ ...selfArtifactIgnorePatterns(policy),
2159
+ ...policy.ignore.paths
2160
+ ];
306
2161
  const limits = {
307
2162
  maxFileSizeBytes: policy.limits?.maxFileSizeBytes ?? DEFAULT_MAX_FILE_SIZE_BYTES,
308
2163
  maxTotalBytes: policy.limits?.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES,
@@ -312,6 +2167,9 @@ async function scan(options, proRules, onProgress) {
312
2167
  let skippedTooLarge = 0;
313
2168
  const skippedTooLargeFiles = [];
314
2169
  let skippedBinary = 0;
2170
+ const skippedBinaryFiles = [];
2171
+ let skippedSymlinks = 0;
2172
+ const skippedSymlinkFiles = [];
315
2173
  let truncated = false;
316
2174
  const changedInvalidUtf8 = [];
317
2175
  const changedUnreadable = [];
@@ -320,12 +2178,13 @@ async function scan(options, proRules, onProgress) {
320
2178
  if (changedRelPaths.length === 0) {
321
2179
  logger.info("--changed: git ran successfully \u2014 0 changed files to scan.");
322
2180
  }
2181
+ const changedIgnore = [...DEFAULT_IGNORE, ...selfArtifactIgnorePatterns(policy)];
323
2182
  const filteredPaths = changedRelPaths.filter(
324
- (rp) => !DEFAULT_IGNORE.some((pat) => {
2183
+ (rp) => !changedIgnore.some((pat) => {
325
2184
  const prefix = pat.replace("/**", "");
326
2185
  return rp.startsWith(prefix + "/") || rp === prefix;
327
2186
  })
328
- );
2187
+ ).sort(compareScanPaths);
329
2188
  files = [];
330
2189
  let totalBytes = 0;
331
2190
  const changedTotal = filteredPaths.length;
@@ -335,7 +2194,7 @@ async function scan(options, proRules, onProgress) {
335
2194
  truncated = true;
336
2195
  break;
337
2196
  }
338
- const fullPath = join2(cwd, relPath);
2197
+ const fullPath = join3(cwd, relPath);
339
2198
  try {
340
2199
  let resolvedPath;
341
2200
  try {
@@ -402,14 +2261,39 @@ async function scan(options, proRules, onProgress) {
402
2261
  skippedTooLarge = readResult.skippedTooLarge;
403
2262
  skippedTooLargeFiles.push(...readResult.skippedTooLargeFiles);
404
2263
  skippedBinary = readResult.skippedBinary;
2264
+ skippedBinaryFiles.push(...readResult.skippedBinaryFiles);
2265
+ skippedSymlinks = readResult.skippedSymlinks;
2266
+ skippedSymlinkFiles.push(...readResult.skippedSymlinkFiles);
405
2267
  truncated = readResult.truncated;
406
2268
  changedInvalidUtf8.push(...readResult.invalidUtf8Files);
407
2269
  changedUnreadable.push(...readResult.unreadableFiles);
408
2270
  }
409
- let allFindings = applySuppressions(
410
- CHECK_MODULES.flatMap((mod) => mod.run(files, policy)),
2271
+ const sourceRedacted = /* @__PURE__ */ new Set();
2272
+ const legacyFindings = applySuppressions(
2273
+ CHECK_MODULES.flatMap((mod) => {
2274
+ const found = mod.run(files, policy);
2275
+ if (mod === secretsCheck) for (const f of found) sourceRedacted.add(f);
2276
+ return found;
2277
+ }),
411
2278
  files
412
2279
  );
2280
+ const bundledFindings = applySuppressions(runProRules(loadBundledRules(), files, policy), files);
2281
+ const { findings: dedupedLegacy, corpusFindings: dedupedCorpus, notes: dedupNotes, severityDisagreements } = dedupeLegacyAgainstCorpus(legacyFindings, bundledFindings, (cf) => {
2282
+ if (cf.line === void 0) return false;
2283
+ const file = files.find((x) => x.relativePath === cf.file);
2284
+ return file !== void 0 && isLineSuppressed(file.content.split("\n"), cf.line - 1, cf.id);
2285
+ });
2286
+ for (const n of dedupNotes) {
2287
+ logger.debug(
2288
+ `[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.` : "")
2289
+ );
2290
+ }
2291
+ for (const d of severityDisagreements) {
2292
+ logger.warn(
2293
+ `[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.`
2294
+ );
2295
+ }
2296
+ let allFindings = [...dedupedLegacy, ...dedupedCorpus];
413
2297
  let coderefDegraded = false;
414
2298
  if (proRules?.length) {
415
2299
  const checksumManifest = loadChecksumManifest();
@@ -429,7 +2313,16 @@ async function scan(options, proRules, onProgress) {
429
2313
  logger.warn(w);
430
2314
  }
431
2315
  }
2316
+ const collapsed = collapseSameIssueFindings(allFindings);
2317
+ for (const n of collapsed.notes) {
2318
+ logger.debug(
2319
+ `[shipguard] ${n.file}:${n.line} \u2014 "${n.id}" matched more than once (columns ${n.keptColumn ?? "?"} and ${n.droppedColumn ?? "?"}); reported as one finding.`
2320
+ );
2321
+ }
2322
+ allFindings = collapsed.findings;
2323
+ redactFindingsEvidence(allFindings, sourceRedacted);
432
2324
  const riskScore = computeRiskScore(allFindings);
2325
+ const treeDigest = computeTreeDigest(files);
433
2326
  const degradedReasons = [];
434
2327
  if (skippedTooLarge > 0) {
435
2328
  const named = skippedTooLargeFiles.slice(0, 10).join(", ");
@@ -445,181 +2338,66 @@ async function scan(options, proRules, onProgress) {
445
2338
  detail: "File count or total size ceiling was reached; collection stopped early \u2014 results are incomplete."
446
2339
  });
447
2340
  }
448
- if (coderefDegraded) {
449
- degradedReasons.push({
450
- code: "CODEREF_SKIPPED",
451
- detail: "One or more pro coderef rules were skipped because they require a newer CLI version."
452
- });
453
- }
454
- if (changedInvalidUtf8.length > 0) {
455
- const named = changedInvalidUtf8.slice(0, 10).map((f) => f.relativePath).join(", ");
456
- const extra = changedInvalidUtf8.length > 10 ? ` (and ${changedInvalidUtf8.length - 10} more)` : "";
457
- degradedReasons.push({
458
- code: "INVALID_UTF8",
459
- detail: `${changedInvalidUtf8.length} file(s) contained invalid UTF-8 and were not scanned: ${named}${extra}`
460
- });
461
- }
462
- if (changedUnreadable.length > 0) {
463
- const named = changedUnreadable.slice(0, 10).join(", ");
464
- const extra = changedUnreadable.length > 10 ? ` (and ${changedUnreadable.length - 10} more)` : "";
2341
+ if (skippedSymlinks > 0) {
2342
+ const named = skippedSymlinkFiles.slice(0, 10).join(", ");
2343
+ const extra = skippedSymlinks > skippedSymlinkFiles.length || skippedSymlinkFiles.length > 10 ? ` (and others)` : "";
465
2344
  degradedReasons.push({
466
- code: "UNREADABLE_FILE",
467
- detail: `${changedUnreadable.length} file(s) could not be read and were not scanned: ${named}${extra}`
2345
+ code: "SYMLINK_SKIPPED",
2346
+ detail: `${skippedSymlinks} symlink(s) were not followed (privacy moat) and were not scanned: ${named}${extra}`
468
2347
  });
469
2348
  }
470
- const isDegraded = degradedReasons.length > 0 || void 0;
471
- const result = {
472
- findings: allFindings,
473
- riskScore,
474
- filesScanned: files.length,
475
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
476
- 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.
483
- degraded: isDegraded,
484
- // Machine-readable WHY for each degrade source — safe to key on in agent logic.
485
- // scan.ts OR-merges its own PRO_RULES_UNAVAILABLE entry after pro-fetch failure.
486
- degradedReasons: degradedReasons.length > 0 ? degradedReasons : void 0,
487
- // Internal metadata for the human-output path — NOT included in --json output
488
- _skippedTooLarge: skippedTooLarge,
489
- _skippedTooLargeFiles: skippedTooLargeFiles,
490
- _skippedBinary: skippedBinary,
491
- _truncated: truncated
492
- };
493
- return result;
494
- }
495
-
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} |`);
2349
+ if (coderefDegraded) {
2350
+ degradedReasons.push({
2351
+ code: "CODEREF_SKIPPED",
2352
+ detail: "One or more pro coderef rules were skipped because they require a newer CLI version."
2353
+ });
557
2354
  }
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 };
2355
+ if (changedInvalidUtf8.length > 0) {
2356
+ const named = changedInvalidUtf8.slice(0, 10).map((f) => f.relativePath).join(", ");
2357
+ const extra = changedInvalidUtf8.length > 10 ? ` (and ${changedInvalidUtf8.length - 10} more)` : "";
2358
+ degradedReasons.push({
2359
+ code: "INVALID_UTF8",
2360
+ detail: `${changedInvalidUtf8.length} file(s) contained invalid UTF-8 and were not scanned: ${named}${extra}`
2361
+ });
2362
+ }
2363
+ if (changedUnreadable.length > 0) {
2364
+ const named = changedUnreadable.slice(0, 10).join(", ");
2365
+ const extra = changedUnreadable.length > 10 ? ` (and ${changedUnreadable.length - 10} more)` : "";
2366
+ degradedReasons.push({
2367
+ code: "UNREADABLE_FILE",
2368
+ detail: `${changedUnreadable.length} file(s) could not be read and were not scanned: ${named}${extra}`
2369
+ });
2370
+ }
2371
+ const isDegraded = degradedReasons.length > 0 || void 0;
2372
+ const result = {
2373
+ findings: allFindings,
2374
+ riskScore,
2375
+ filesScanned: files.length,
2376
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2377
+ policyUsed: policy.project.name,
2378
+ // Degraded when ANY of: coderef version-skip, collection truncation, a file
2379
+ // skipped for being too large, OR a symlink not followed (incident EDGE-1).
2380
+ // The oversized-skip case (incident f8fdaa6c/18e93b67) and the symlink-skip
2381
+ // case both mean content was NOT scanned — the scan is incomplete, so it must
2382
+ // NOT be reported SAFE. Binary skips (skippedBinary) are NORMAL and
2383
+ // intentionally EXCLUDED — a binary file legitimately has no source to scan.
2384
+ // scan.ts OR-merges this with its own pro-fetch-failure flag.
2385
+ treeDigest,
2386
+ degraded: isDegraded,
2387
+ // Machine-readable WHY for each degrade source — safe to key on in agent logic.
2388
+ // scan.ts OR-merges its own PRO_RULES_UNAVAILABLE entry after pro-fetch failure.
2389
+ degradedReasons: degradedReasons.length > 0 ? degradedReasons : void 0,
2390
+ // Internal metadata for the human-output path — NOT included in --json output
2391
+ _skippedTooLarge: skippedTooLarge,
2392
+ _skippedTooLargeFiles: skippedTooLargeFiles,
2393
+ _skippedBinary: skippedBinary,
2394
+ _skippedBinaryFiles: skippedBinaryFiles,
2395
+ _skippedSymlinks: skippedSymlinks,
2396
+ _skippedSymlinkFiles: skippedSymlinkFiles,
2397
+ _truncated: truncated
2398
+ };
2399
+ applyVerdict(result);
2400
+ return result;
623
2401
  }
624
2402
 
625
2403
  // src/core/sarif.ts
@@ -750,16 +2528,18 @@ function quickstartHelp(isTTY) {
750
2528
  lines.push("");
751
2529
  lines.push(` ${chalk.cyan("scan")} ${chalk.dim("[path]")} Scan a project for high-risk issues`);
752
2530
  lines.push(` ${chalk.cyan("init")} Generate a .shipguard.yml policy file`);
753
- lines.push(` ${chalk.cyan("login")} Authenticate to unlock Pro rules`);
2531
+ lines.push(` ${chalk.cyan("login")} Sign in to scan with the full rule corpus`);
754
2532
  lines.push(` ${chalk.cyan("logout")} Remove saved credentials`);
755
2533
  lines.push(` ${chalk.cyan("status")} Show auth status and credits`);
2534
+ lines.push(` ${chalk.cyan("hook")} ${chalk.dim("--target")} Install the gate at the merge boundary`);
2535
+ lines.push(` ${chalk.cyan("schema")} ${chalk.dim("--json")} Print the machine-readable scan contract`);
756
2536
  lines.push(` ${chalk.cyan("feedback")} ${chalk.dim("<text>")} Send feedback on your last scan`);
757
2537
  lines.push(` ${chalk.cyan("rate")} ${chalk.dim("<id> up|down")} Rate a rule finding`);
758
2538
  lines.push(` ${chalk.cyan("help")} ${chalk.dim("/ ?")} Show this screen`);
759
2539
  lines.push("");
760
2540
  lines.push(chalk.bold(" Exit codes (verdict-neutral \u2014 read the JSON for the verdict):"));
761
2541
  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`);
2542
+ lines.push(` ${chalk.yellow("1")} Blocked \u2014 ONLY with --strict, on blocking findings or an unfinished scan`);
763
2543
  lines.push(` ${chalk.red("2")} Config error`);
764
2544
  lines.push(` ${chalk.red("3")} Runtime error \u2014 scan could not meaningfully run`);
765
2545
  lines.push("");
@@ -784,11 +2564,13 @@ function quickstartHelp(isTTY) {
784
2564
  lines.push(" login Authenticate");
785
2565
  lines.push(" logout Remove credentials");
786
2566
  lines.push(" status Auth status + credits");
2567
+ lines.push(" hook --target Install the gate at the merge boundary");
2568
+ lines.push(" schema --json Machine-readable scan contract");
787
2569
  lines.push(" feedback <text> Send feedback");
788
2570
  lines.push(" rate <id> up|down Rate a finding");
789
2571
  lines.push(" help / ? Show this screen");
790
2572
  lines.push("");
791
- lines.push(" Exit codes: 0=completed (verdict in JSON) 1=blocked (--strict only) 2=config-error 3=runtime-error");
2573
+ 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
2574
  lines.push("");
793
2575
  lines.push(` Docs: ${DOCS_URL}`);
794
2576
  lines.push(` Site: ${SITE_URL}`);
@@ -875,10 +2657,12 @@ function findingsByCategoryTable(findings) {
875
2657
  return lines.join("\n");
876
2658
  }
877
2659
  function coverageLine() {
2660
+ const bundled = bundledRulesMeta();
878
2661
  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)}`
2662
+ ` Coverage: ${bundled.ruleCount} bundled rules from the maintained corpus, plus local checks
2663
+ for secrets, auth, payments, database and deployment. Runs offline, no account needed.
2664
+ \`shipguard login\` scans against the full current corpus, not just the offline subset.
2665
+ Plans: ${chalk.underline(PRICING_URL)}`
882
2666
  );
883
2667
  }
884
2668
  var VERDICT_CONFIG = {
@@ -949,24 +2733,15 @@ function severityBar(riskScore, barWidth = 30) {
949
2733
  }).join(" ");
950
2734
  return ` ${bar} ${legend}`;
951
2735
  }
952
- function verdictPanel(result, elapsedMs, skippedCount, topFindings, strict) {
2736
+ function verdictPanel(result, elapsedMs, skippedCount, topFindings, strict, reportPaths) {
953
2737
  const { riskScore, filesScanned } = result;
954
- const recommendation = riskScore.recommendation;
2738
+ const recommendation = effectiveRecommendation(result);
2739
+ const degraded = result.degraded === true;
955
2740
  const cfg = VERDICT_CONFIG[recommendation];
956
2741
  const elapsedStr = elapsedMs < 1e3 ? `${elapsedMs}ms` : `${(elapsedMs / 1e3).toFixed(1)}s`;
957
2742
  const lines = [""];
958
2743
  lines.push(boxTop());
959
2744
  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
2745
  lines.push(boxSection());
971
2746
  lines.push(boxLine(chalk.bold(" Severity breakdown")));
972
2747
  lines.push(boxLine(severityBar(riskScore)));
@@ -987,12 +2762,36 @@ function verdictPanel(result, elapsedMs, skippedCount, topFindings, strict) {
987
2762
  }
988
2763
  lines.push(boxSection());
989
2764
  lines.push(boxLine(chalk.bold(" How ShipGuard helped")));
990
- lines.push(boxLine(cfg.helpLine(riskScore.blockingCount)));
2765
+ if (degraded) {
2766
+ lines.push(boxLine(chalk.red(" Incomplete scan \u2014 verdict is fail-closed until this is fixed:")));
2767
+ for (const reason of result.degradedReasons ?? []) {
2768
+ lines.push(boxLine(chalk.red(` \xB7 ${reason.code}${reason.detail ? ` \u2014 ${truncate(reason.detail, 60)}` : ""}`)));
2769
+ }
2770
+ if ((result.degradedReasons ?? []).length === 0) {
2771
+ lines.push(boxLine(chalk.red(" \xB7 reason not recorded \u2014 see `degraded` in --json output")));
2772
+ }
2773
+ } else {
2774
+ lines.push(boxLine(cfg.helpLine(riskScore.blockingCount)));
2775
+ }
2776
+ if (reportPaths) {
2777
+ lines.push(boxSection());
2778
+ lines.push(boxLine(chalk.bold(" Report written")));
2779
+ lines.push(boxLine(` ${truncatePath(reportPaths.mdPath, 68)}`));
2780
+ lines.push(boxLine(chalk.dim(` agent view: ${truncatePath(reportPaths.runJsonPath, 56)}`)));
2781
+ }
991
2782
  lines.push(boxSection());
992
2783
  lines.push(boxLine(chalk.bold(" Learn more")));
993
2784
  lines.push(boxLine(` Docs ${chalk.underline(DOCS_URL)}`));
994
2785
  lines.push(boxLine(` Site ${chalk.underline(SITE_URL)}`));
995
2786
  lines.push(boxLine(` Pricing ${chalk.underline(PRICING_URL)}`));
2787
+ lines.push(boxSection());
2788
+ const verdictLabel = cfg.color(chalk.bold(`${cfg.icon} ${cfg.label}`));
2789
+ lines.push(boxLine(` ${verdictLabel}`));
2790
+ if ((riskScore.blockingCount > 0 || degraded) && !strict) {
2791
+ lines.push(boxLine(chalk.dim(" (informational \u2014 exit 0; use --strict to enforce as exit 1)")));
2792
+ }
2793
+ 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();
2794
+ lines.push(boxLine(attitudeLine2));
996
2795
  lines.push(boxEmpty());
997
2796
  lines.push(boxBottom());
998
2797
  lines.push("");
@@ -1013,8 +2812,8 @@ function actionFooter(opts) {
1013
2812
  lines.push(` ${chalk.cyan('shipguard feedback "<thoughts>"')} ${chalk.dim("# what do you think?")}`);
1014
2813
  if (!isLoggedIn) {
1015
2814
  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")}`);
2815
+ lines.push(` ${chalk.yellow("shipguard login")} ${chalk.dim("# sign in for the full rule corpus")}`);
2816
+ lines.push(` ${chalk.yellow("shipguard scan --pro")} ${chalk.dim("# scan with it (uses one scan credit)")}`);
1018
2817
  }
1019
2818
  lines.push("");
1020
2819
  lines.push(` ${chalk.dim("Full docs: " + DOCS_URL)}`);
@@ -1054,7 +2853,7 @@ function welcomeBanner(configDir) {
1054
2853
  empty,
1055
2854
  bannerLine(chalk.bold("Quick start:")),
1056
2855
  bannerLine(` ${chalk.green("shipguard scan <path>")} Run a scan on your project`),
1057
- bannerLine(` ${chalk.green("shipguard login")} Unlock Pro rules`),
2856
+ bannerLine(` ${chalk.green("shipguard login")} Scan with the full rule corpus`),
1058
2857
  bannerLine(` ${chalk.green("shipguard scan --json")} Machine-readable output for CI/agents`),
1059
2858
  empty,
1060
2859
  bannerLine(`Docs: ${chalk.underline(DOCS_URL)}`),
@@ -1066,11 +2865,14 @@ function welcomeBanner(configDir) {
1066
2865
  ].join("\n");
1067
2866
  }
1068
2867
  function quietVerdict(result, strict) {
1069
- const { recommendation, score, totalFindings, blockingCount } = result.riskScore;
2868
+ const { score, totalFindings, blockingCount } = result.riskScore;
2869
+ const recommendation = effectiveRecommendation(result);
2870
+ const degraded = result.degraded === true;
1070
2871
  const icon = recommendation === "SAFE_TO_SHIP" ? "\u2705" : recommendation === "DO_NOT_SHIP" ? "\u26D4" : "\u26A0\uFE0F";
1071
2872
  const colorFn = recommendation === "SAFE_TO_SHIP" ? chalk.green : recommendation === "DO_NOT_SHIP" ? chalk.red : chalk.yellow;
2873
+ const degradedNote = degraded ? " incomplete=yes" : "";
1072
2874
  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}`);
2875
+ return colorFn(`${icon} ${recommendation.replace(/_/g, " ")} score=${score}/100 findings=${totalFindings} blocking=${blockingCount}${degradedNote}${suffix}`);
1074
2876
  }
1075
2877
  function truncate(str, maxLen) {
1076
2878
  return str.length <= maxLen ? str : `${str.slice(0, maxLen - 3)}...`;
@@ -1143,9 +2945,6 @@ function displayWidth(str) {
1143
2945
  return width;
1144
2946
  }
1145
2947
 
1146
- // src/core/history/index.ts
1147
- import { createHash as createHash5 } from "crypto";
1148
-
1149
2948
  // src/core/history/schema.ts
1150
2949
  var CURRENT_SCHEMA_VERSION = 2;
1151
2950
  var MIGRATION_1_INIT = `
@@ -1241,9 +3040,9 @@ function resolveHistoryPath(cwd, policy) {
1241
3040
 
1242
3041
  // src/core/history/identity.ts
1243
3042
  import { execFileSync as execFileSync2 } from "child_process";
1244
- import { createHash as createHash2, randomUUID } from "crypto";
3043
+ import { createHash as createHash2, randomUUID as randomUUID2 } from "crypto";
1245
3044
  import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync, writeFileSync as writeFileSync2 } from "fs";
1246
- import { dirname as dirname2, join as join5 } from "path";
3045
+ import { dirname as dirname3, join as join5 } from "path";
1247
3046
  function tryGit(cwd, args) {
1248
3047
  try {
1249
3048
  return execFileSync2("git", args, { cwd, encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }).trim();
@@ -1281,23 +3080,23 @@ function resolveRepoIdentity(cwd) {
1281
3080
  return { repoId: existing, repoIdKind: "fallback-uuid", remoteLabel };
1282
3081
  }
1283
3082
  }
1284
- const id = randomUUID();
1285
- mkdirSync2(dirname2(fallbackPath), { recursive: true });
3083
+ const id = randomUUID2();
3084
+ mkdirSync2(dirname3(fallbackPath), { recursive: true });
1286
3085
  writeFileSync2(fallbackPath, `${id}
1287
3086
  `, "utf-8");
1288
3087
  ensureGitignored(cwd, ".shipguard/");
1289
3088
  return { repoId: id, repoIdKind: "fallback-uuid", remoteLabel };
1290
3089
  } catch (err) {
1291
3090
  logger.warn(`Could not persist fallback repo identity: ${err instanceof Error ? err.message : err}`);
1292
- return { repoId: randomUUID(), repoIdKind: "fallback-uuid", remoteLabel };
3091
+ return { repoId: randomUUID2(), repoIdKind: "fallback-uuid", remoteLabel };
1293
3092
  }
1294
3093
  }
1295
3094
  function resolveContentIdentity(cwd, excludePrefixes = []) {
1296
3095
  const headSha = tryGit(cwd, ["rev-parse", "HEAD"]);
1297
3096
  if (!headSha) return void 0;
1298
- const raw = tryGit(cwd, ["status", "--porcelain", "-z"]) ?? "";
3097
+ const raw2 = tryGit(cwd, ["status", "--porcelain", "-z"]) ?? "";
1299
3098
  const normalizedExcludes = excludePrefixes.map((p) => p.replace(/\\/g, "/").replace(/^\.\//, "")).filter(Boolean);
1300
- const records = raw.split("\0").filter(Boolean);
3099
+ const records = raw2.split("\0").filter(Boolean);
1301
3100
  const kept = records.filter((rec) => {
1302
3101
  const path = rec.length > 3 ? rec.slice(3) : rec;
1303
3102
  return !normalizedExcludes.some((ex) => path === ex || path === ex.replace(/\/$/, "") || path.startsWith(ex));
@@ -1321,9 +3120,9 @@ function computeScopeFingerprint(input) {
1321
3120
  }
1322
3121
 
1323
3122
  // src/core/history/store.ts
1324
- import { randomUUID as randomUUID2 } from "crypto";
3123
+ import { randomUUID as randomUUID3 } from "crypto";
1325
3124
  import { existsSync as existsSync4, mkdirSync as mkdirSync3 } from "fs";
1326
- import { dirname as dirname3 } from "path";
3125
+ import { dirname as dirname4 } from "path";
1327
3126
  var sqliteModulePromise;
1328
3127
  var warningFilterInstalled = false;
1329
3128
  function installSqliteWarningFilter() {
@@ -1375,7 +3174,7 @@ var HistoryStore = class _HistoryStore {
1375
3174
  }
1376
3175
  const preExisted = existsSync4(dbPath);
1377
3176
  try {
1378
- mkdirSync3(dirname3(dbPath), { recursive: true });
3177
+ mkdirSync3(dirname4(dbPath), { recursive: true });
1379
3178
  } catch (err) {
1380
3179
  return {
1381
3180
  ok: false,
@@ -1598,7 +3397,7 @@ var HistoryStore = class _HistoryStore {
1598
3397
  return { ok: true, scanId: row.scan_id, reused: true };
1599
3398
  }
1600
3399
  }
1601
- const scanId = randomUUID2();
3400
+ const scanId = randomUUID3();
1602
3401
  this.db.prepare(
1603
3402
  `INSERT INTO scan_id_reservations (repo_id, reuse_key, scan_id, created_at) VALUES (?, ?, ?, ?)
1604
3403
  ON CONFLICT(repo_id, reuse_key) DO UPDATE SET scan_id = excluded.scan_id, created_at = excluded.created_at`
@@ -1722,7 +3521,7 @@ function computeRegressionResult(current, baseline) {
1722
3521
  }
1723
3522
 
1724
3523
  // src/core/history/scan-id.ts
1725
- import { createHash as createHash4, randomUUID as randomUUID3 } from "crypto";
3524
+ import { createHash as createHash4, randomUUID as randomUUID4 } from "crypto";
1726
3525
  import { relative } from "path";
1727
3526
  function computeScanIdReuseKey(input) {
1728
3527
  const normalized = {
@@ -1757,7 +3556,7 @@ async function resolveScanId(input) {
1757
3556
  const excludePrefixes = [".shipguard/", historyRelPath];
1758
3557
  const contentIdentity = resolveContentIdentity(cwd, excludePrefixes);
1759
3558
  if (!contentIdentity) {
1760
- return { scanId: randomUUID3(), scanIdReused: false };
3559
+ return { scanId: randomUUID4(), scanIdReused: false };
1761
3560
  }
1762
3561
  const identity = resolveRepoIdentity(cwd);
1763
3562
  const reuseKey = computeScanIdReuseKey({
@@ -1772,14 +3571,14 @@ async function resolveScanId(input) {
1772
3571
  const openResult = await HistoryStore.open(historyPath, cliVersion);
1773
3572
  if (!openResult.ok) {
1774
3573
  logger.warn(`ShipGuard scanId persistence unavailable (${openResult.status}) \u2014 minting a fresh scanId: ${openResult.reason}`);
1775
- return { scanId: randomUUID3(), scanIdReused: false };
3574
+ return { scanId: randomUUID4(), scanIdReused: false };
1776
3575
  }
1777
3576
  const store = openResult.store;
1778
3577
  try {
1779
3578
  const result = store.reserveScanId(identity.repoId, reuseKey, reuseWindowMs);
1780
3579
  if (!result.ok) {
1781
3580
  logger.warn(`ShipGuard scanId persistence failed \u2014 minting a fresh scanId: ${result.reason}`);
1782
- return { scanId: randomUUID3(), scanIdReused: false };
3581
+ return { scanId: randomUUID4(), scanIdReused: false };
1783
3582
  }
1784
3583
  return { scanId: result.scanId, scanIdReused: result.reused };
1785
3584
  } finally {
@@ -1789,7 +3588,7 @@ async function resolveScanId(input) {
1789
3588
  logger.warn(
1790
3589
  `ShipGuard scanId persistence failed unexpectedly \u2014 minting a fresh scanId: ${err instanceof Error ? err.message : err}`
1791
3590
  );
1792
- return { scanId: randomUUID3(), scanIdReused: false };
3591
+ return { scanId: randomUUID4(), scanIdReused: false };
1793
3592
  }
1794
3593
  }
1795
3594
 
@@ -1798,10 +3597,6 @@ function isActive(finding) {
1798
3597
  if (finding.suppressionState) return finding.suppressionState === "active";
1799
3598
  return !finding.suppressed;
1800
3599
  }
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
3600
  function buildRuleOutcomes(policy, proRules, proApplied, cliVersion, corpusVersion, result) {
1806
3601
  const outcomes = [];
1807
3602
  const countActive = (ruleId) => result.findings.filter((f) => f.id === ruleId && isActive(f)).length;
@@ -1854,7 +3649,7 @@ async function recordScanHistory(input) {
1854
3649
  const ruleVersionById = new Map(ruleOutcomes.map((ro) => [ro.ruleId, ro.ruleVersion]));
1855
3650
  const findingRows = result.findings.map((f) => ({
1856
3651
  ruleId: f.id,
1857
- findingKey: computeFindingKey(f),
3652
+ findingKey: getFindingKey(f),
1858
3653
  filePath: f.file,
1859
3654
  severity: f.severity,
1860
3655
  blocking: Boolean(f.blocking),
@@ -1954,9 +3749,9 @@ function sendTelemetry(payload) {
1954
3749
 
1955
3750
  // src/commands/scan.ts
1956
3751
  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";
3752
+ var CLI_VERSION = true ? "0.6.0" : process.env.npm_package_version ?? "0.0.0-dev";
1958
3753
  function resolveExitCode(opts) {
1959
- if (opts.strict && opts.blockingCount > 0) {
3754
+ if (opts.strict && (opts.blockingCount > 0 || opts.degraded === true || opts.recommendation === "DO_NOT_SHIP")) {
1960
3755
  return EXIT_CODES.BLOCKED;
1961
3756
  }
1962
3757
  return EXIT_CODES.SAFE;
@@ -1973,6 +3768,8 @@ function proFetchActionHint(code, retryAfterSeconds) {
1973
3768
  return "This looks like a transient server/network issue \u2014 retry the scan, or pass --allow-degraded to run local rules only.";
1974
3769
  case "BUNDLE_INVALID":
1975
3770
  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.";
3771
+ case "NO_ACTIVE_RELEASE":
3772
+ 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
3773
  default:
1977
3774
  return "Retry the scan, or pass --allow-degraded to run local rules only.";
1978
3775
  }
@@ -1981,7 +3778,7 @@ function isProjectRoot(dir) {
1981
3778
  return existsSync5(join6(dir, "package.json")) || existsSync5(join6(dir, ".git"));
1982
3779
  }
1983
3780
  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", `
3781
+ 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
3782
  Output modes:
1986
3783
  (default) Verbose: live progress (TTY), categorized findings, gamified verdict panel
1987
3784
  --quiet / -q One-line verdict + exit code only \u2014 ideal for scripts
@@ -2007,16 +3804,22 @@ Exit codes (verdict-neutral by default \u2014 ShipGuard informs, you choose the
2007
3804
  0 Scan completed. Verdict is in the JSON \`recommendation\` field \u2014 this
2008
3805
  is returned EVEN IF findings are blocking, or the scan is degraded/
2009
3806
  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).
3807
+ 1 Blocked \u2014 with --strict AND at least one of: a blocking finding, a scan
3808
+ that did not finish (\`degraded:true\` \u2014 an unfinished scan cannot clear
3809
+ a hard gate), or an effective \`recommendation\` of DO_NOT_SHIP (suppressed
3810
+ findings still count toward the risk score, so a scan can cross the
3811
+ DO_NOT_SHIP threshold with zero blocking findings \u2014 the exit code always
3812
+ agrees with the printed verdict). OR with --check-regressions AND at
3813
+ least one regression (see \`regressions\` in --json output \u2014
3814
+ informational-only unless this flag is set).
2013
3815
  2 Config error (bad policy file, bad flags, non-project directory).
2014
3816
  3 Runtime error \u2014 the scan could not meaningfully run at all. This
2015
3817
  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).
3818
+ credits, rate limit, server, an invalid bundle, or no active rule
3819
+ release on the server) \u2014 the requested gate did not run, so
3820
+ ShipGuard fails loud instead of silently falling back to a free
3821
+ scan. Pass --allow-degraded to opt back into the free-scan
3822
+ fallback (degraded:true, exit code unaffected).
2020
3823
 
2021
3824
  Local history (E5): every scan is recorded to a local SQLite store
2022
3825
  (\`.shipguard/history.db\` by default; override via \`history.path\` in
@@ -2112,8 +3915,8 @@ async function runScan(ctx) {
2112
3915
  logger.info("Detecting stack...");
2113
3916
  }
2114
3917
  try {
2115
- const { fetchProRules } = await import("./pro-scanner-MAKMWHIY.js");
2116
- const { hasConfig, generateConfig } = await import("./config-generator-TUQCF2SD.js");
3918
+ const { fetchProRules } = await import("./pro-scanner-3DY7KU5C.js");
3919
+ const { hasConfig, generateConfig } = await import("./config-generator-2AC37XZ2.js");
2117
3920
  const frameworks = detectedFrameworks;
2118
3921
  if (!hasConfig(cwd)) {
2119
3922
  const configPath = generateConfig(cwd, frameworks);
@@ -2163,7 +3966,8 @@ async function runScan(ctx) {
2163
3966
  "INSUFFICIENT_CREDITS",
2164
3967
  "RATE_LIMITED",
2165
3968
  "SERVER_ERROR",
2166
- "BUNDLE_INVALID"
3969
+ "BUNDLE_INVALID",
3970
+ "NO_ACTIVE_RELEASE"
2167
3971
  ];
2168
3972
  const proErrorCode = typeof rawErrCode === "string" && KNOWN_PRO_FETCH_ERROR_CODES.includes(rawErrCode) ? rawErrCode : "SERVER_ERROR";
2169
3973
  const retryAfterSeconds = err?.retryAfterSeconds;
@@ -2228,9 +4032,11 @@ async function runScan(ctx) {
2228
4032
  const skippedTooLarge = result._skippedTooLarge ?? 0;
2229
4033
  const skippedTooLargeFiles = result._skippedTooLargeFiles ?? [];
2230
4034
  const skippedBinary = result._skippedBinary ?? 0;
4035
+ const skippedBinaryFiles = result._skippedBinaryFiles ?? [];
4036
+ const skippedSymlinks = result._skippedSymlinks ?? 0;
4037
+ const skippedSymlinkFiles = result._skippedSymlinkFiles ?? [];
2231
4038
  const truncatedByBounds = result._truncated ?? false;
2232
- result.recommendation = result.riskScore.recommendation;
2233
- result.schemaVersion = "4";
4039
+ result.schemaVersion = "5";
2234
4040
  result.scanIdReused = scanIdReused;
2235
4041
  result.degraded = degraded || Boolean(result.degraded);
2236
4042
  if (result.degraded) {
@@ -2240,6 +4046,9 @@ async function runScan(ctx) {
2240
4046
  }
2241
4047
  result.creditsWarning = creditsRemaining !== void 0 && creditsRemaining < 10;
2242
4048
  result.rulesVersion = rulesVersion;
4049
+ result.runId = scanId;
4050
+ result.cliVersion = CLI_VERSION;
4051
+ applyVerdict(result);
2243
4052
  if (proRules?.length) {
2244
4053
  const breakdown = {};
2245
4054
  for (const r of proRules) {
@@ -2274,7 +4083,20 @@ async function runScan(ctx) {
2274
4083
  delete publicResult._skippedTooLarge;
2275
4084
  delete publicResult._skippedTooLargeFiles;
2276
4085
  delete publicResult._skippedBinary;
4086
+ delete publicResult._skippedBinaryFiles;
4087
+ delete publicResult._skippedSymlinks;
4088
+ delete publicResult._skippedSymlinkFiles;
2277
4089
  delete publicResult._truncated;
4090
+ const shouldReport = scanOptions.generateReport || policy.scan.generate_report;
4091
+ let reportPaths;
4092
+ if (shouldReport) {
4093
+ const reportElapsedMs = Date.now() - startTime;
4094
+ try {
4095
+ reportPaths = await generateReport(result, scanOptions.reportPath, reportElapsedMs);
4096
+ } catch (error) {
4097
+ logger.error(`Report generation failed: ${error instanceof Error ? error.message : error}`);
4098
+ }
4099
+ }
2278
4100
  if (opts.sarif) {
2279
4101
  console.log(JSON.stringify(toSarif(publicResult), null, 2));
2280
4102
  } else if (scanOptions.json) {
@@ -2303,8 +4125,20 @@ async function runScan(ctx) {
2303
4125
  `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
4126
  );
2305
4127
  }
4128
+ if (skippedSymlinks > 0) {
4129
+ const named = skippedSymlinkFiles.slice(0, 10).join(", ");
4130
+ const more = skippedSymlinks > skippedSymlinkFiles.length || skippedSymlinkFiles.length > 10 ? ` (and others)` : "";
4131
+ logger.warn(
4132
+ `Scan INCOMPLETE: ${skippedSymlinks} symlink(s) not followed \u2014 NOT scanned: ${named}${more}`
4133
+ );
4134
+ logger.warn(
4135
+ `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).`
4136
+ );
4137
+ }
2306
4138
  if (skippedBinary > 0) {
2307
- logger.info(`Files skipped (binary, normal): ${skippedBinary}`);
4139
+ const named = skippedBinaryFiles.slice(0, 10).join(", ");
4140
+ const more = skippedBinary > skippedBinaryFiles.length || skippedBinaryFiles.length > 10 ? ` (and others)` : "";
4141
+ logger.info(`Files skipped (binary, normal): ${skippedBinary} \u2014 ${named}${more}`);
2308
4142
  }
2309
4143
  if (creditsRemaining !== void 0) {
2310
4144
  logger.info(`Credits remaining: ${creditsRemaining}`);
@@ -2323,7 +4157,6 @@ async function runScan(ctx) {
2323
4157
  }
2324
4158
  console.log(coverageLine());
2325
4159
  console.log("");
2326
- console.log(verdictPanel(result, elapsedMs, skippedTooLarge + skippedBinary, result.findings, scanOptions.strict));
2327
4160
  const topRuleId = result.findings.length > 0 ? result.findings[0].id : void 0;
2328
4161
  const isLoggedIn = Boolean(opts.pro && !degraded);
2329
4162
  console.log(actionFooter({
@@ -2331,19 +4164,14 @@ async function runScan(ctx) {
2331
4164
  topRuleId,
2332
4165
  isLoggedIn
2333
4166
  }));
2334
- }
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
- }
4167
+ console.log(verdictPanel(
4168
+ result,
4169
+ elapsedMs,
4170
+ skippedTooLarge + skippedBinary + skippedSymlinks,
4171
+ result.findings,
4172
+ scanOptions.strict,
4173
+ reportPaths
4174
+ ));
2347
4175
  }
2348
4176
  if (opts.pro && !degraded) {
2349
4177
  fetch(`${opts.apiUrl}/api/telemetry/ingest`, {
@@ -2381,10 +4209,28 @@ async function runScan(ctx) {
2381
4209
  }
2382
4210
  let exitCode = resolveExitCode({
2383
4211
  strict: scanOptions.strict,
2384
- blockingCount: result.riskScore.blockingCount
4212
+ blockingCount: result.riskScore.blockingCount,
4213
+ // Recommendation #3 — the hard stop must not inherit the false-safe on an
4214
+ // unfinished scan. Uses the FINAL degraded value (post pro-fetch OR-merge).
4215
+ degraded: result.degraded === true,
4216
+ // CLI-2/J-3 — the hard stop must not disagree with the printed verdict:
4217
+ // a scan can print DO_NOT_SHIP with blockingCount 0 (active non-blocking findings,
4218
+ // degradation). effectiveRecommendation
4219
+ // reads the SAME field the human panel / --json `recommendation` print.
4220
+ recommendation: effectiveRecommendation(result)
2385
4221
  });
2386
4222
  if (exitCode === EXIT_CODES.BLOCKED && !machineOutput && !quiet) {
2387
- logger.warn(`Strict mode: ${result.riskScore.blockingCount} blocking finding(s) \u2014 exiting with code 1`);
4223
+ if (result.degraded === true) {
4224
+ logger.warn(
4225
+ `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.`
4226
+ );
4227
+ } else if (result.riskScore.blockingCount > 0) {
4228
+ logger.warn(`Strict mode: ${result.riskScore.blockingCount} blocking finding(s) \u2014 exiting with code 1`);
4229
+ } else {
4230
+ logger.warn(
4231
+ `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.`
4232
+ );
4233
+ }
2388
4234
  }
2389
4235
  if (opts.checkRegressions && exitCode === EXIT_CODES.SAFE && (result.regressions?.length ?? 0) > 0) {
2390
4236
  exitCode = EXIT_CODES.BLOCKED;
@@ -2500,7 +4346,7 @@ function statusCommand() {
2500
4346
  // src/commands/history.ts
2501
4347
  import { Command as Command6 } from "commander";
2502
4348
  import { resolve as resolve5 } from "path";
2503
- var CLI_VERSION2 = true ? "0.5.1" : process.env.npm_package_version ?? "0.0.0-dev";
4349
+ var CLI_VERSION2 = true ? "0.6.0" : process.env.npm_package_version ?? "0.0.0-dev";
2504
4350
  function historyCommand() {
2505
4351
  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
4352
  const cwd = scanPath ? resolve5(scanPath) : process.cwd();
@@ -2561,10 +4407,439 @@ function historyCommand() {
2561
4407
  });
2562
4408
  }
2563
4409
 
2564
- // src/commands/feedback.ts
4410
+ // src/commands/hook.ts
2565
4411
  import { Command as Command7 } from "commander";
4412
+ import { execFileSync as execFileSync3 } from "child_process";
4413
+ import { chmodSync, existsSync as existsSync6, mkdirSync as mkdirSync4, readFileSync as readFileSync2, writeFileSync as writeFileSync3 } from "fs";
4414
+ import { dirname as dirname5, isAbsolute, join as join7, relative as relative2, resolve as resolve6 } from "path";
4415
+
4416
+ // src/core/hook-templates.ts
4417
+ var HOOK_BLOCK_VERSION = 1;
4418
+ var HOOK_MARKER_START = "# >>> shipguard managed block >>>";
4419
+ var HOOK_MARKER_END = "# <<< shipguard managed block <<<";
4420
+ var GATE_COMMAND = "shipguard scan --json --strict";
4421
+ function gateShellBody(indent = "") {
4422
+ const l = (s) => `${indent}${s}`;
4423
+ return [
4424
+ l("if command -v shipguard >/dev/null 2>&1; then"),
4425
+ l(' _sg_run() { shipguard "$@"; }'),
4426
+ l("elif command -v npx >/dev/null 2>&1; then"),
4427
+ l(' _sg_run() { npx --no-install shipguard "$@"; }'),
4428
+ l("else"),
4429
+ l(' echo "ShipGuard: not installed, so the release gate did not run \u2014 refusing to pass." >&2'),
4430
+ l(' echo " Install it: npm i -g @agenticcli/shipguard" >&2'),
4431
+ l(" exit 1"),
4432
+ l("fi"),
4433
+ l("_sg_out=$(_sg_run scan --json --strict 2>&1) || {"),
4434
+ l(' echo "ShipGuard blocked this: the release gate did not pass." >&2'),
4435
+ l(' printf "%s\\n" "$_sg_out" >&2'),
4436
+ l(" exit 1"),
4437
+ l("}")
4438
+ ].join("\n");
4439
+ }
4440
+ function gitHookScript(hookName) {
4441
+ return ["#!/bin/sh", gitHookBlock(hookName), ""].join("\n");
4442
+ }
4443
+ function gitHookBlock(hookName) {
4444
+ return [
4445
+ HOOK_MARKER_START + ` v${HOOK_BLOCK_VERSION} (${hookName})`,
4446
+ "# Installed by `shipguard hook`. Re-run that command to update this block.",
4447
+ `# Runs the release gate as a HARD STOP: ${GATE_COMMAND}`,
4448
+ "#",
4449
+ "# HONEST LIMIT: a git hook binds humans and well-behaved agents only.",
4450
+ "# `--no-verify` skips it. For a stop an agent cannot route around, also run:",
4451
+ "# shipguard hook --target claude (runs outside the model)",
4452
+ "# shipguard hook --target ci (server-side; pair with branch protection)",
4453
+ gateShellBody(),
4454
+ HOOK_MARKER_END
4455
+ ].join("\n");
4456
+ }
4457
+ var GIT_HOOK_NAMES = ["pre-push", "pre-merge-commit"];
4458
+ 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'`;
4459
+ var CLAUDE_HOOK_FINGERPRINT = "shipguard scan --json --strict";
4460
+ function ciWorkflowYaml() {
4461
+ return `# ${HOOK_MARKER_START.replace("# ", "")} v${HOOK_BLOCK_VERSION} (github-actions)
4462
+ # Installed by \`shipguard hook --target ci\`. Re-run that command to update this file.
4463
+ #
4464
+ # This is the only layer that binds EVERYONE \u2014 it runs server-side, so nothing
4465
+ # local can skip it. Turn on branch protection for this check to make it binding.
4466
+ name: ShipGuard release gate
4467
+
4468
+ on:
4469
+ pull_request:
4470
+ push:
4471
+ branches: [main]
4472
+
4473
+ jobs:
4474
+ shipguard:
4475
+ name: ShipGuard verdict
4476
+ runs-on: ubuntu-latest
4477
+ steps:
4478
+ - uses: actions/checkout@v4
4479
+ - uses: actions/setup-node@v4
4480
+ with:
4481
+ node-version: '20'
4482
+ - name: Run the release gate
4483
+ run: npx --yes @agenticcli/shipguard scan --json --strict
4484
+ # ${HOOK_MARKER_END.replace("# ", "")}
4485
+ `;
4486
+ }
4487
+ var BINDING_NOTES = {
4488
+ 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.",
4489
+ claude: "Binds the agent. It runs outside the model, so the agent cannot argue, prompt, or inject its way past it inside a session.",
4490
+ 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."
4491
+ };
4492
+ function replaceManagedBlock(content, replacement) {
4493
+ const start = content.indexOf(HOOK_MARKER_START);
4494
+ if (start === -1) return void 0;
4495
+ const endMarker = content.indexOf(HOOK_MARKER_END, start);
4496
+ if (endMarker === -1) return void 0;
4497
+ const end = endMarker + HOOK_MARKER_END.length;
4498
+ return content.slice(0, start) + replacement.trim() + content.slice(end);
4499
+ }
4500
+ function isManaged(content) {
4501
+ return content.includes(HOOK_MARKER_START);
4502
+ }
4503
+
4504
+ // src/commands/hook.ts
4505
+ function writeManaged(path, whole, block, executable) {
4506
+ if (!existsSync6(path)) {
4507
+ mkdirSync4(dirname5(path), { recursive: true });
4508
+ writeFileSync3(path, whole, "utf-8");
4509
+ if (executable) chmodSync(path, 493);
4510
+ return { path, status: "created" };
4511
+ }
4512
+ const current = readFileSync2(path, "utf-8");
4513
+ if (!isManaged(current)) {
4514
+ return {
4515
+ path,
4516
+ status: "refused",
4517
+ manualLine: GATE_COMMAND
4518
+ };
4519
+ }
4520
+ const merged = replaceManagedBlock(current, block) ?? whole;
4521
+ if (merged === current) return { path, status: "unchanged" };
4522
+ writeFileSync3(path, merged, "utf-8");
4523
+ if (executable) chmodSync(path, 493);
4524
+ return { path, status: "updated" };
4525
+ }
4526
+ function resolveGitHooksDir(cwd) {
4527
+ const out = execFileSync3("git", ["rev-parse", "--git-path", "hooks"], {
4528
+ cwd,
4529
+ encoding: "utf-8",
4530
+ stdio: ["pipe", "pipe", "pipe"]
4531
+ }).trim();
4532
+ return isAbsolute(out) ? out : resolve6(cwd, out);
4533
+ }
4534
+ function installGit(cwd) {
4535
+ const hooksDir = resolveGitHooksDir(cwd);
4536
+ return GIT_HOOK_NAMES.map(
4537
+ (name) => writeManaged(join7(hooksDir, name), gitHookScript(name), gitHookBlock(name), true)
4538
+ );
4539
+ }
4540
+ function installClaude(cwd) {
4541
+ const path = join7(cwd, ".claude", "settings.json");
4542
+ const entry = { matcher: "Bash", hooks: [{ type: "command", command: CLAUDE_HOOK_COMMAND }] };
4543
+ if (!existsSync6(path)) {
4544
+ mkdirSync4(dirname5(path), { recursive: true });
4545
+ writeFileSync3(path, JSON.stringify({ hooks: { PreToolUse: [entry] } }, null, 2) + "\n", "utf-8");
4546
+ return [{ path, status: "created" }];
4547
+ }
4548
+ const raw2 = readFileSync2(path, "utf-8");
4549
+ let settings;
4550
+ try {
4551
+ settings = JSON.parse(raw2);
4552
+ } catch (err) {
4553
+ logger.error(
4554
+ `Could not parse ${path}: ${err instanceof Error ? err.message : err}. Refusing to touch it.`
4555
+ );
4556
+ return [{ path, status: "refused", manualLine: CLAUDE_HOOK_COMMAND }];
4557
+ }
4558
+ const preToolUse = settings.hooks?.PreToolUse ?? [];
4559
+ const ourIndex = preToolUse.findIndex(
4560
+ (e) => (e.hooks ?? []).some((h) => typeof h.command === "string" && h.command.includes(CLAUDE_HOOK_FINGERPRINT))
4561
+ );
4562
+ const next = [...preToolUse];
4563
+ let status;
4564
+ if (ourIndex === -1) {
4565
+ next.push(entry);
4566
+ status = "created";
4567
+ } else if (JSON.stringify(next[ourIndex]) === JSON.stringify(entry)) {
4568
+ status = "unchanged";
4569
+ } else {
4570
+ next[ourIndex] = entry;
4571
+ status = "updated";
4572
+ }
4573
+ if (status !== "unchanged") {
4574
+ const merged = {
4575
+ ...settings,
4576
+ hooks: { ...settings.hooks ?? {}, PreToolUse: next }
4577
+ };
4578
+ writeFileSync3(path, JSON.stringify(merged, null, 2) + "\n", "utf-8");
4579
+ }
4580
+ return [{ path, status }];
4581
+ }
4582
+ function installCi(cwd) {
4583
+ const path = join7(cwd, ".github", "workflows", "shipguard.yml");
4584
+ const yaml = ciWorkflowYaml();
4585
+ return [writeManaged(path, yaml, yaml, false)];
4586
+ }
4587
+ var TARGETS = ["git", "claude", "ci"];
4588
+ function hookCommand() {
4589
+ return new Command7("hook").description("Install the ShipGuard release gate at the merge boundary (git hook, Claude Code hook, or CI job)").option(
4590
+ "--target <target>",
4591
+ `Where to install the gate: ${TARGETS.join(" | ")}`,
4592
+ "git"
4593
+ ).addHelpText("after", `
4594
+ What each target installs (all of them run \`${GATE_COMMAND}\`):
4595
+
4596
+ --target git .git/hooks/pre-push and pre-merge-commit
4597
+ ${BINDING_NOTES.git}
4598
+
4599
+ --target claude .claude/settings.json \u2014 a PreToolUse hook on Bash \`git merge\`/\`git push\`
4600
+ ${BINDING_NOTES.claude}
4601
+
4602
+ --target ci .github/workflows/shipguard.yml
4603
+ ${BINDING_NOTES.ci}
4604
+
4605
+ Install all three where you can. ShipGuard never blocks on its own \u2014 installing a
4606
+ hook is the deliberate act that turns the hard stop on.
4607
+
4608
+ Re-running is safe: an existing ShipGuard block is updated in place, never duplicated.
4609
+ A hook file somebody else wrote is never overwritten \u2014 you get the line to add by hand.
4610
+
4611
+ Exit codes:
4612
+ 0 Installed (or already up to date).
4613
+ 2 Config error \u2014 unknown --target, or --target git outside a git repository.
4614
+ 3 Runtime error \u2014 the files could not be written.`).action((opts) => {
4615
+ const cwd = process.cwd();
4616
+ const target = String(opts.target ?? "git");
4617
+ if (!TARGETS.includes(target)) {
4618
+ logger.error(`Unknown --target "${opts.target}". Choose one of: ${TARGETS.join(", ")}.`);
4619
+ process.exit(EXIT_CODES.CONFIG_ERROR);
4620
+ return;
4621
+ }
4622
+ if (target === "git" && !isGitRepo(cwd)) {
4623
+ logger.error(
4624
+ `Not a git repository: ${cwd}. Run this inside your project, or use --target ci / --target claude.`
4625
+ );
4626
+ process.exit(EXIT_CODES.CONFIG_ERROR);
4627
+ return;
4628
+ }
4629
+ let outcomes;
4630
+ try {
4631
+ outcomes = target === "git" ? installGit(cwd) : target === "claude" ? installClaude(cwd) : installCi(cwd);
4632
+ } catch (err) {
4633
+ logger.error(`Could not install the hook: ${err instanceof Error ? err.message : err}`);
4634
+ process.exit(EXIT_CODES.RUNTIME_ERROR);
4635
+ return;
4636
+ }
4637
+ const refused = outcomes.filter((o) => o.status === "refused");
4638
+ for (const outcome of outcomes) {
4639
+ const shown = isAbsolute(outcome.path) ? relative2(cwd, outcome.path) || outcome.path : outcome.path;
4640
+ switch (outcome.status) {
4641
+ case "created":
4642
+ logger.success(`Installed the release gate: ${shown}`);
4643
+ break;
4644
+ case "updated":
4645
+ logger.success(`Updated the release gate: ${shown}`);
4646
+ break;
4647
+ case "unchanged":
4648
+ logger.info(`Already up to date: ${shown}`);
4649
+ break;
4650
+ case "refused":
4651
+ logger.warn(`${shown} was written by something else \u2014 not touching it.`);
4652
+ logger.warn(` Add this line to it yourself: ${outcome.manualLine}`);
4653
+ break;
4654
+ }
4655
+ }
4656
+ logger.info(`What this binds: ${BINDING_NOTES[target]}`);
4657
+ if (target === "git") {
4658
+ logger.info("For a stop an agent cannot route around, also run: shipguard hook --target claude");
4659
+ logger.info("And for one nothing local can skip: shipguard hook --target ci");
4660
+ }
4661
+ if (refused.length > 0) {
4662
+ logger.info("Nothing was overwritten.");
4663
+ }
4664
+ });
4665
+ }
4666
+
4667
+ // src/commands/schema.ts
4668
+ import { Command as Command8 } from "commander";
4669
+ var CLI_VERSION3 = true ? "0.6.0" : process.env.npm_package_version ?? "0.0.0-dev";
4670
+ var CURRENT_SCHEMA_VERSION2 = "5";
4671
+ function buildSchemaContract(limits) {
4672
+ const src = (value, fallback) => value === fallback ? "default" : "policy";
4673
+ return {
4674
+ schemaVersion: CURRENT_SCHEMA_VERSION2,
4675
+ cliVersion: CLI_VERSION3,
4676
+ contract: "shipguard-scan-result",
4677
+ recommendation: {
4678
+ field: "recommendation",
4679
+ // Closed set. Deliberately NOT extended for degraded scans — a new value would be a
4680
+ // fail-open trap for the very common `recommendation !== 'DO_NOT_SHIP'` parser.
4681
+ values: ["SAFE_TO_SHIP", "REVIEW_BEFORE_SHIP", "DO_NOT_SHIP"],
4682
+ 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.",
4683
+ deprecatedMirrors: ["riskScore.recommendation"]
4684
+ },
4685
+ exitCodes: [
4686
+ {
4687
+ code: EXIT_CODES.SAFE,
4688
+ name: "COMPLETED",
4689
+ 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."
4690
+ },
4691
+ {
4692
+ code: EXIT_CODES.BLOCKED,
4693
+ name: "BLOCKED",
4694
+ 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."
4695
+ },
4696
+ {
4697
+ code: EXIT_CODES.CONFIG_ERROR,
4698
+ name: "CONFIG_ERROR",
4699
+ meaning: "Bad policy file, unknown flag, or a non-project directory without --all. Never used for a degraded-but-completed scan."
4700
+ },
4701
+ {
4702
+ code: EXIT_CODES.RUNTIME_ERROR,
4703
+ name: "RUNTIME_ERROR",
4704
+ 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)."
4705
+ }
4706
+ ],
4707
+ degradeCodes: [
4708
+ { code: "FILE_TOO_LARGE", meaning: "One or more files exceeded the per-file size cap and were not scanned." },
4709
+ { code: "OUTPUT_TRUNCATED", meaning: "The file-count or total-bytes ceiling was reached; collection stopped early." },
4710
+ { code: "CODEREF_SKIPPED", meaning: "One or more Pro coderef rules need a newer CLI and were skipped." },
4711
+ { code: "PRO_RULES_UNAVAILABLE", meaning: "Pro rules could not be fetched (auth, credits, rate limit, network)." },
4712
+ { code: "INVALID_UTF8", meaning: "One or more files were not valid UTF-8 and were skipped rather than mangled." },
4713
+ { code: "UNREADABLE_FILE", meaning: "One or more files could not be read from disk." },
4714
+ { code: "COMPILE_FAILURE", meaning: "A Pro rule bundle failed to compile; the whole bundle was refused rather than partly run." }
4715
+ ],
4716
+ limits: {
4717
+ maxFiles: {
4718
+ value: limits.maxFiles,
4719
+ unit: "files",
4720
+ source: src(limits.maxFiles, DEFAULT_MAX_FILES),
4721
+ behaviorAtLimit: "Collection stops; the remaining files are NOT scanned.",
4722
+ machineSignal: 'degraded:true + degradedReasons[].code === "OUTPUT_TRUNCATED"',
4723
+ verifiedBy: null
4724
+ },
4725
+ maxFileSizeBytes: {
4726
+ value: limits.maxFileSizeBytes,
4727
+ unit: "bytes",
4728
+ source: src(limits.maxFileSizeBytes, DEFAULT_MAX_FILE_SIZE_BYTES),
4729
+ behaviorAtLimit: "The individual file is skipped unread; the rest of the scan continues.",
4730
+ machineSignal: 'degraded:true + degradedReasons[].code === "FILE_TOO_LARGE" (detail names the files)',
4731
+ verifiedBy: null
4732
+ },
4733
+ maxTotalBytes: {
4734
+ value: limits.maxTotalBytes,
4735
+ unit: "bytes",
4736
+ source: src(limits.maxTotalBytes, DEFAULT_MAX_TOTAL_BYTES),
4737
+ behaviorAtLimit: "Collection stops; the remaining files are NOT scanned.",
4738
+ machineSignal: 'degraded:true + degradedReasons[].code === "OUTPUT_TRUNCATED"',
4739
+ verifiedBy: null
4740
+ },
4741
+ unanalyzableTypes: [
4742
+ {
4743
+ type: "binary",
4744
+ behavior: "Skipped. A binary file has no source to scan.",
4745
+ // Deliberately no degrade signal: a binary skip is normal, not incomplete coverage.
4746
+ machineSignal: null,
4747
+ verifiedBy: null
4748
+ },
4749
+ {
4750
+ type: "invalid-utf8",
4751
+ behavior: "Skipped unread \u2014 decoding with replacement characters can destroy a secret that straddles the bad bytes.",
4752
+ machineSignal: 'degradedReasons[].code === "INVALID_UTF8"',
4753
+ verifiedBy: null
4754
+ },
4755
+ {
4756
+ type: "symlink",
4757
+ behavior: "Never followed. A symlink pointing out of the project root is refused.",
4758
+ machineSignal: 'degradedReasons[].code === "UNREADABLE_FILE" when the path was reported as changed',
4759
+ verifiedBy: null
4760
+ },
4761
+ {
4762
+ type: "unreadable",
4763
+ behavior: "Skipped \u2014 permission error, deleted mid-scan, dangling symlink.",
4764
+ machineSignal: 'degradedReasons[].code === "UNREADABLE_FILE"',
4765
+ verifiedBy: null
4766
+ },
4767
+ {
4768
+ type: "ignored-by-default",
4769
+ behavior: "Not collected: node_modules, dist, build, .next, coverage, .git, lockfiles, images/archives/media, and ShipGuard\u2019s own artifacts.",
4770
+ machineSignal: null,
4771
+ verifiedBy: null
4772
+ }
4773
+ ],
4774
+ 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."
4775
+ }
4776
+ };
4777
+ }
4778
+ function schemaCommand() {
4779
+ 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", `
4780
+ Run this inside a project to see the limits THAT project actually uses (its
4781
+ shipguard.policy.yml is merged in); run it anywhere else for the defaults.
4782
+
4783
+ Examples:
4784
+ shipguard schema --json The contract, for an agent or a script
4785
+ shipguard schema The same thing, readable
4786
+
4787
+ Exit codes:
4788
+ 0 Printed.
4789
+ 2 Config error \u2014 the project's policy file could not be read.`).action(async (opts) => {
4790
+ const cwd = process.cwd();
4791
+ let contract;
4792
+ try {
4793
+ const policy = await loadPolicy(cwd);
4794
+ contract = buildSchemaContract({
4795
+ maxFiles: policy.limits?.maxFiles ?? DEFAULT_MAX_FILES,
4796
+ maxFileSizeBytes: policy.limits?.maxFileSizeBytes ?? DEFAULT_MAX_FILE_SIZE_BYTES,
4797
+ maxTotalBytes: policy.limits?.maxTotalBytes ?? DEFAULT_MAX_TOTAL_BYTES
4798
+ });
4799
+ } catch (error) {
4800
+ logger.error(`Config error: ${error instanceof Error ? error.message : error}`);
4801
+ process.exit(EXIT_CODES.CONFIG_ERROR);
4802
+ return;
4803
+ }
4804
+ if (opts.json) {
4805
+ console.log(JSON.stringify(contract, null, 2));
4806
+ return;
4807
+ }
4808
+ console.log(renderSchemaHuman(contract));
4809
+ });
4810
+ }
4811
+ function renderSchemaHuman(c) {
4812
+ const lines = [];
4813
+ lines.push(`ShipGuard scan contract \u2014 schemaVersion ${c.schemaVersion} (CLI ${c.cliVersion})`);
4814
+ lines.push("");
4815
+ lines.push(`Verdict field: ${c.recommendation.field}`);
4816
+ lines.push(` Values: ${c.recommendation.values.join(", ")}`);
4817
+ lines.push(` Fail-closed: ${c.recommendation.failClosed}`);
4818
+ lines.push(` Deprecated copies: ${c.recommendation.deprecatedMirrors.join(", ")}`);
4819
+ lines.push("");
4820
+ lines.push("Exit codes:");
4821
+ for (const e of c.exitCodes) lines.push(` ${e.code} ${e.name} \u2014 ${e.meaning}`);
4822
+ lines.push("");
4823
+ lines.push("Limits:");
4824
+ for (const [name, entry] of Object.entries(c.limits)) {
4825
+ if (name === "unanalyzableTypes" || name === "verificationStatus") continue;
4826
+ const l = entry;
4827
+ lines.push(` ${name}: ${l.value} ${l.unit ?? ""} (${l.source})`);
4828
+ lines.push(` at the limit: ${l.behaviorAtLimit}`);
4829
+ lines.push(` machine signal: ${l.machineSignal ?? "none"}`);
4830
+ }
4831
+ lines.push("");
4832
+ lines.push("File types that are not analyzed:");
4833
+ for (const t of c.limits.unanalyzableTypes) lines.push(` ${t.type} \u2014 ${t.behavior}`);
4834
+ lines.push("");
4835
+ lines.push(c.limits.verificationStatus);
4836
+ return lines.join("\n");
4837
+ }
4838
+
4839
+ // src/commands/feedback.ts
4840
+ import { Command as Command9 } from "commander";
2566
4841
  function feedbackCommand() {
2567
- return new Command7("feedback").description("Send feedback about your last scan").argument("<text>", "Your feedback text").action(async (text) => {
4842
+ return new Command9("feedback").description("Send feedback about your last scan").argument("<text>", "Your feedback text").action(async (text) => {
2568
4843
  let token;
2569
4844
  try {
2570
4845
  const t = await getAuthToken();
@@ -2603,7 +4878,7 @@ function feedbackCommand() {
2603
4878
  });
2604
4879
  }
2605
4880
  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) => {
4881
+ 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
4882
  const num = parseInt(findingNumber, 10);
2608
4883
  if (isNaN(num) || num < 1) {
2609
4884
  logger.error("Finding number must be a positive integer.");
@@ -2688,13 +4963,13 @@ process.on("unhandledRejection", handleUnhandledRejection);
2688
4963
  process.on("SIGINT", handleSignal);
2689
4964
  process.on("SIGTERM", handleSignal);
2690
4965
  var ISSUES_URL3 = "https://github.com/agenticcli/shipguard/issues";
2691
- var program = new Command8();
4966
+ var program = new Command10();
2692
4967
  var rawArgs = process.argv.slice(2);
2693
4968
  if (rawArgs[0] === "?") {
2694
4969
  process.argv = [process.argv[0], process.argv[1], "help"];
2695
4970
  }
2696
4971
  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"
4972
+ true ? "0.6.0" : process.env.npm_package_version ?? "0.0.0-dev"
2698
4973
  ).helpCommand(false).addHelpText("after", `
2699
4974
  Learn more:
2700
4975
  Docs https://agenticcli.dev/docs
@@ -2712,10 +4987,12 @@ addSubcommand(loginCommand());
2712
4987
  addSubcommand(logoutCommand());
2713
4988
  addSubcommand(statusCommand());
2714
4989
  addSubcommand(historyCommand());
4990
+ addSubcommand(hookCommand());
4991
+ addSubcommand(schemaCommand());
2715
4992
  addSubcommand(feedbackCommand());
2716
4993
  addSubcommand(rateCommand());
2717
4994
  program.addCommand(
2718
- new Command8("help").description("Show the quickstart guide").action(() => {
4995
+ new Command10("help").description("Show the quickstart guide").action(() => {
2719
4996
  const isTTY = Boolean(process.stdout.isTTY);
2720
4997
  process.stdout.write(quickstartHelp(isTTY) + "\n");
2721
4998
  })
@@ -2740,7 +5017,7 @@ function levenshtein(a, b) {
2740
5017
  return dp[m][n];
2741
5018
  }
2742
5019
  function closestCommand(input) {
2743
- const names = ["scan", "init", "login", "logout", "status", "history", "feedback", "rate", "help"];
5020
+ const names = ["scan", "init", "login", "logout", "status", "history", "hook", "schema", "feedback", "rate", "help"];
2744
5021
  let best;
2745
5022
  let bestDist = Infinity;
2746
5023
  for (const name of names) {
@@ -2753,7 +5030,7 @@ function closestCommand(input) {
2753
5030
  return bestDist <= 3 ? best : void 0;
2754
5031
  }
2755
5032
  (async () => {
2756
- const KNOWN_COMMANDS = /* @__PURE__ */ new Set(["scan", "init", "login", "logout", "status", "history", "feedback", "rate", "help"]);
5033
+ const KNOWN_COMMANDS = /* @__PURE__ */ new Set(["scan", "init", "login", "logout", "status", "history", "hook", "schema", "feedback", "rate", "help"]);
2757
5034
  const firstNonFlag = process.argv.slice(2).find((a) => !a.startsWith("-"));
2758
5035
  if (firstNonFlag && firstNonFlag !== "?" && !KNOWN_COMMANDS.has(firstNonFlag)) {
2759
5036
  const suggestion = closestCommand(firstNonFlag);