@agenticcli/shipguard 0.11.0 → 0.12.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
@@ -4,6 +4,7 @@ import {
4
4
  assertTrustedApiUrl,
5
5
  authCheck,
6
6
  clearCredentials,
7
+ compileDetectorRegex,
7
8
  databaseCheck,
8
9
  deploymentCheck,
9
10
  deriveBlocking,
@@ -15,6 +16,7 @@ import {
15
16
  isTokenExpired,
16
17
  loadChecksumManifest,
17
18
  loadCredentials,
19
+ looksFakeKey,
18
20
  payments,
19
21
  redactFindingsEvidence,
20
22
  runProRules,
@@ -23,7 +25,7 @@ import {
23
25
  secretsCheck,
24
26
  validateBundleCompile,
25
27
  writeSecureFileSync
26
- } from "./chunk-FQY6IANN.js";
28
+ } from "./chunk-WMGOTWCL.js";
27
29
  import {
28
30
  DEFAULT_HISTORY_PATH,
29
31
  DEFAULT_MAX_FILES,
@@ -40,6 +42,7 @@ import {
40
42
  SCAN_ID_REUSE_WINDOW_ENV_VAR,
41
43
  SEVERITY_WEIGHTS,
42
44
  applyVerdict,
45
+ assertCwdAlive,
43
46
  buildIgnoreRules,
44
47
  capReached,
45
48
  classifyIgnored,
@@ -51,7 +54,7 @@ import {
51
54
  isShipguardArtifactPath,
52
55
  readCandidate,
53
56
  readFiles
54
- } from "./chunk-7NXELBFO.js";
57
+ } from "./chunk-IPNOC7JF.js";
55
58
  import {
56
59
  logger
57
60
  } from "./chunk-NC5RELTG.js";
@@ -361,10 +364,10 @@ function getChangedFilesDetailed(dir) {
361
364
  var free_bundle_default = {
362
365
  schemaVersion: 1,
363
366
  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.",
364
- corpusVersion: 19,
365
- corpusHash: "sha256:4edcc0b1a6f89a2c34e796f022a693cf7b89dbc4e3bcf4afd5e7b54804150a97",
366
- ruleCount: 30,
367
- contentHash: "sha256:1e274f5f8176c4ad8566703a67b110d038b528942c26c25c2b7299367bc8ffa8",
367
+ corpusVersion: 28,
368
+ corpusHash: "sha256:260d041653902d294ec4dcb9ee654113604738bcf0e355d241fd81baaec69a98",
369
+ ruleCount: 36,
370
+ contentHash: "sha256:8ead9a382dcb1ea6c62929622dfc2d7815942bee5d548bf70464d97c9d9e4b8c",
368
371
  rules: [
369
372
  {
370
373
  id: "generic.auth.jwt-none-algorithm",
@@ -507,7 +510,7 @@ var free_bundle_default = {
507
510
  severity: "high",
508
511
  confidence: "MEDIUM",
509
512
  action: "warn",
510
- version: 5,
513
+ version: 6,
511
514
  status: "experimental",
512
515
  cwe: [
513
516
  "CWE-942",
@@ -523,7 +526,8 @@ var free_bundle_default = {
523
526
  `Access-Control-Allow-Origin[^\\n]{0,40}req\\.(headers|get)\\s*\\(\\s*['"]origin['"]`,
524
527
  `setHeader\\s*\\(\\s*['"]Access-Control-Allow-Origin['"]\\s*,[^\\n]{0,60}origin`,
525
528
  `res\\.header\\s*\\(\\s*['"]Access-Control-Allow-Origin['"]\\s*,[^\\n]{0,60}req\\.headers\\.origin`,
526
- `response\\.setHeader\\s*\\(\\s*['"]Access-Control-Allow-Origin['"]\\s*,[^\\n]{0,60}request\\.headers`
529
+ `response\\.setHeader\\s*\\(\\s*['"]Access-Control-Allow-Origin['"]\\s*,[^\\n]{0,60}request\\.headers`,
530
+ `\\.headers\\s*\\.\\s*(?:set|append)\\s*\\(\\s*['"]Access-Control-Allow-Origin['"]\\s*,\\s*(?:(?:origin|requestOrigin|reqOrigin)\\b|[\\w$.?!]{0,40}headers(?:\\.origin\\b|\\.get\\(\\s*['"]origin['"]\\s*\\)|\\[\\s*['"]origin['"]\\s*\\]))`
527
531
  ],
528
532
  antiPatterns: [
529
533
  "\\btest\\b|\\bspec\\b|__tests__|__fixtures__",
@@ -864,6 +868,49 @@ var free_bundle_default = {
864
868
  "https://cwe.mitre.org/data/definitions/78.html"
865
869
  ]
866
870
  },
871
+ {
872
+ id: "generic.injection.child-process-exec-variable",
873
+ framework: [
874
+ "generic"
875
+ ],
876
+ category: "injection",
877
+ tier: "free",
878
+ severity: "high",
879
+ confidence: "MEDIUM",
880
+ action: "warn",
881
+ version: 1,
882
+ status: "experimental",
883
+ cwe: [
884
+ "CWE-78"
885
+ ],
886
+ owasp: [
887
+ "A03:2021"
888
+ ],
889
+ matcher: {
890
+ type: "pattern",
891
+ fileGlob: "**/*.{ts,js,tsx,jsx}",
892
+ patterns: [
893
+ "(?:^|[^\\w$.]|child_process\\.|\\bcp\\.)(?:exec|execSync)\\s*\\(\\s*(?:cmd|command|cmdLine|cmdline|commandLine|shellCmd|shellCommand|fullCmd|script)\\s*[,)]",
894
+ "(?:^|[^\\w$.]|child_process\\.|\\bcp\\.)(?:exec|execSync)\\s*\\(\\s*req(?:uest)?\\.(?:body|query|params)\\b"
895
+ ],
896
+ antiPatterns: [
897
+ `(?:const|let|var)\\s+(?:cmd|command|cmdLine|cmdline|commandLine|shellCmd|shellCommand|fullCmd|script)(?::\\s?\\w{1,10})?\\s?=\\s?(?:"[^"$+\\n]{0,120}"|'[^'$+\\n]{0,120}');?[ \\t]*\\n`,
898
+ "\\.test\\.|\\bspec\\b|__tests__|__fixtures__",
899
+ "eslint-disable"
900
+ ],
901
+ flags: "",
902
+ antiPatternScope: "file"
903
+ },
904
+ explanation: 'Node.js child_process.exec() or execSync() is called with a command held in a variable (or taken straight from the request) instead of a fixed string. exec() runs the command through the system shell (/bin/sh), so any part of that variable that comes from user input can add its own commands (for example "; rm -rf" or "$(curl ...)"). AI-written route handlers often build the command in a variable first and pass it to exec() on the next line.',
905
+ recommendation: "Use execFile() or spawn() with the command and its arguments as separate values; they do not start a shell, so user input cannot add commands. If a shell is unavoidable, validate the input against a strict allowlist first.",
906
+ fix: 'Replace `const cmd = "tool " + input; exec(cmd)` with `execFile("tool", [input])`.',
907
+ findingType: "vulnerability",
908
+ aiCodeTarget: true,
909
+ references: [
910
+ "https://cwe.mitre.org/data/definitions/78.html",
911
+ "https://cheatsheetseries.owasp.org/cheatsheets/OS_Command_Injection_Defense_Cheat_Sheet.html"
912
+ ]
913
+ },
867
914
  {
868
915
  id: "generic.injection.eval-user-input",
869
916
  framework: [
@@ -997,6 +1044,48 @@ var free_bundle_default = {
997
1044
  "https://github.com/PyCQA/bandit"
998
1045
  ]
999
1046
  },
1047
+ {
1048
+ id: "generic.injection.sql-string-built",
1049
+ framework: [
1050
+ "generic"
1051
+ ],
1052
+ category: "injection",
1053
+ tier: "free",
1054
+ severity: "high",
1055
+ confidence: "MEDIUM",
1056
+ action: "warn",
1057
+ version: 1,
1058
+ status: "experimental",
1059
+ cwe: [
1060
+ "CWE-89"
1061
+ ],
1062
+ owasp: [
1063
+ "A03:2021"
1064
+ ],
1065
+ matcher: {
1066
+ type: "pattern",
1067
+ fileGlob: "**/*.{ts,js,tsx,jsx,mjs,cjs}",
1068
+ patterns: [
1069
+ '"(?:select\\s[\\w.*,() ]{1,100}\\sfrom|insert\\s+into|update\\s+[\\w.]+\\s+set|delete\\s+from)\\s[^"\\n]{0,200}"\\s*\\+',
1070
+ `'(?:select\\s[\\w.*,"() ]{1,100}\\sfrom|insert\\s+into|update\\s+[\\w.]+\\s+set|delete\\s+from)\\s[^'\\n]{0,200}'\\s*\\+`,
1071
+ '(?:^|[^\\w$`])`\\s*(?:select\\s[\\w.*,"() ]{1,100}\\sfrom|insert\\s+into|update\\s+[\\w.]+\\s+set|delete\\s+from)\\s[^`]{0,200}\\$\\{',
1072
+ `\\b(?:sql|query|queryText|stmt|statement)\\s*\\+=\\s*(?:"[^"\\n]{0,120}"|'[^'\\n]{0,120}')\\s*\\+`
1073
+ ],
1074
+ antiPatterns: [
1075
+ "//\\s*shipguard-ignore"
1076
+ ],
1077
+ flags: "im"
1078
+ },
1079
+ explanation: `A SQL statement is built by joining strings or by putting \${...} into a template string, and the result is sent to the database. If any part of it comes from a user (a search box, a URL parameter, a form field), the user can change the meaning of the query: read other people's rows, skip a login check, or delete data. This includes a search written as "... ILIKE '%" + q + "%'" and a statement kept in a variable that is later passed to pool.query(sql).`,
1080
+ recommendation: 'Send values as parameters, never inside the SQL text. With node-postgres write pool.query("SELECT ... WHERE title ILIKE $1", ["%" + q + "%"]); with postgres.js use its tagged template sql`SELECT ... WHERE title ILIKE ${"%" + q + "%"}`, which sends ${...} as a parameter. Table and column names cannot be parameters: pick them from a fixed list in your code.',
1081
+ fix: "Replace the joined string with a parameterized query: pool.query('SELECT ... WHERE col = $1', [value]).",
1082
+ findingType: "vulnerability",
1083
+ aiCodeTarget: true,
1084
+ references: [
1085
+ "https://cwe.mitre.org/data/definitions/89.html",
1086
+ "https://node-postgres.com/features/queries"
1087
+ ]
1088
+ },
1000
1089
  {
1001
1090
  id: "generic.injection.unsafe-deserialization-python",
1002
1091
  framework: [
@@ -1466,6 +1555,49 @@ var free_bundle_default = {
1466
1555
  "https://github.com/gitleaks/gitleaks"
1467
1556
  ]
1468
1557
  },
1558
+ {
1559
+ id: "generic.secrets.resend-api-key",
1560
+ framework: [
1561
+ "generic"
1562
+ ],
1563
+ category: "secrets",
1564
+ tier: "local",
1565
+ severity: "critical",
1566
+ confidence: "HIGH",
1567
+ action: "block",
1568
+ version: 2,
1569
+ status: "experimental",
1570
+ cwe: [
1571
+ "CWE-798"
1572
+ ],
1573
+ owasp: [
1574
+ "A07:2021"
1575
+ ],
1576
+ matcher: {
1577
+ type: "pattern",
1578
+ fileGlob: "**/*.{ts,js,tsx,jsx,py,rb,go,yaml,yml,json,conf,ini,env}",
1579
+ patterns: [
1580
+ "\\bre_[A-Za-z0-9]{6,12}_[A-Za-z0-9]{20,40}\\b"
1581
+ ],
1582
+ antiPatterns: [
1583
+ "re_x{6,}|re_123456789|YOUR_RESEND|REPLACE_ME|example|placeholder",
1584
+ "process\\.env\\.[A-Za-z0-9_]+!?\\s*(?:[,;)}\\]]|$)",
1585
+ `os\\.environ(?:\\.get\\([A-Za-z0-9_'". :/+=@-]{0,64}\\)|\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\])?(?:[,;)}\\]]|$)`,
1586
+ `ENV\\[[A-Za-z0-9_'". :/+=@-]{0,64}\\](?:[,;)}\\]]|$)`,
1587
+ "\\.test\\.|\\bspec\\b|__tests__"
1588
+ ],
1589
+ flags: ""
1590
+ },
1591
+ explanation: "A hardcoded Resend API key (re_ prefix) was detected in source. Anyone who can read the repository can send email as your domain through your Resend account (phishing, spam, password-reset abuse) until the key is revoked.",
1592
+ recommendation: "Remove the key from source and revoke it in the Resend dashboard under API Keys. Store the replacement in an environment variable (RESEND_API_KEY) loaded at runtime. Never commit live API keys to version control.",
1593
+ fix: "Replace the literal with `process.env.RESEND_API_KEY` and add RESEND_API_KEY to .env.local (gitignored). Revoke the exposed key.",
1594
+ findingType: "vulnerability",
1595
+ aiCodeTarget: true,
1596
+ references: [
1597
+ "https://cwe.mitre.org/data/definitions/798.html",
1598
+ "https://resend.com/docs/dashboard/api-keys/introduction"
1599
+ ]
1600
+ },
1469
1601
  {
1470
1602
  id: "generic.secrets.slack-token",
1471
1603
  framework: [
@@ -1521,7 +1653,7 @@ var free_bundle_default = {
1521
1653
  severity: "critical",
1522
1654
  confidence: "HIGH",
1523
1655
  action: "block",
1524
- version: 6,
1656
+ version: 7,
1525
1657
  status: "experimental",
1526
1658
  cwe: [
1527
1659
  "CWE-798"
@@ -1533,7 +1665,7 @@ var free_bundle_default = {
1533
1665
  type: "pattern",
1534
1666
  fileGlob: "**/*.{ts,js,tsx,jsx,py,rb,go,yaml,yml,json,conf,ini,env}",
1535
1667
  patterns: [
1536
- "sk_live_[a-zA-Z0-9]{20,64}"
1668
+ "(?:sk|rk)_live_[a-zA-Z0-9]{20,64}"
1537
1669
  ],
1538
1670
  antiPatterns: [
1539
1671
  "sk_live_xxxx|YOUR_STRIPE_KEY|REPLACE_ME",
@@ -1546,7 +1678,7 @@ var free_bundle_default = {
1546
1678
  ],
1547
1679
  flags: ""
1548
1680
  },
1549
- 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.",
1681
+ explanation: "A hardcoded Stripe live secret key (sk_live_ prefix) or live restricted key (rk_live_ prefix) was detected in source. A secret key grants full access to the Stripe account including charges, refunds, customer data, and payouts; a restricted key grants whatever permissions it was created with. Either one is a live payment-account credential.",
1550
1682
  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.",
1551
1683
  fix: "Replace with `process.env.STRIPE_SECRET_KEY` and add it to .env.local (gitignored). Rotate the exposed key immediately.",
1552
1684
  findingType: "vulnerability",
@@ -1645,6 +1777,45 @@ var free_bundle_default = {
1645
1777
  "https://docs.python-requests.org/en/latest/user/advanced/#ssl-cert-verification"
1646
1778
  ]
1647
1779
  },
1780
+ {
1781
+ id: "nextjs.secrets.env-public-prefix-secret",
1782
+ framework: [
1783
+ "nextjs"
1784
+ ],
1785
+ category: "secrets",
1786
+ tier: "free",
1787
+ severity: "high",
1788
+ confidence: "HIGH",
1789
+ action: "block",
1790
+ version: 3,
1791
+ status: "experimental",
1792
+ cwe: [
1793
+ "CWE-312"
1794
+ ],
1795
+ owasp: [
1796
+ "A02:2021"
1797
+ ],
1798
+ matcher: {
1799
+ type: "pattern",
1800
+ fileGlob: "**/*.{ts,tsx,js,jsx,env}",
1801
+ patterns: [
1802
+ "NEXT_PUBLIC_(SECRET_KEY|PRIVATE_KEY|AUTH_SECRET|AUTH_TOKEN|CLIENT_SECRET|DB_PASSWORD|DATABASE_PASSWORD|OPENAI_API_KEY|STRIPE_SECRET|SENDGRID_API_KEY|TWILIO_AUTH_TOKEN|JWT_SECRET|WEBHOOK_SECRET|SUPABASE_SERVICE_ROLE)"
1803
+ ],
1804
+ antiPatterns: [
1805
+ "NEXT_PUBLIC_SUPABASE_URL",
1806
+ "NEXT_PUBLIC_SUPABASE_ANON_KEY",
1807
+ "NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY",
1808
+ "NEXT_PUBLIC_GA_",
1809
+ "NEXT_PUBLIC_POSTHOG_KEY"
1810
+ ],
1811
+ flags: "i"
1812
+ },
1813
+ explanation: "An environment variable prefixed with NEXT_PUBLIC_ and a sensitive name (SECRET, KEY, TOKEN, PASSWORD, API_KEY, etc.) is exposed to the client-side JavaScript bundle at build time. Next.js statically inlines all NEXT_PUBLIC_ variables into the browser bundle, making secrets visible to any user who inspects the page source or network traffic.",
1814
+ recommendation: "Remove the NEXT_PUBLIC_ prefix so the variable stays server-side only. Access sensitive values only in Server Components, API routes, or Server Actions where they remain private. For values genuinely needed on the client (e.g. publishable keys), use vendor-specific public-safe key formats and verify they carry no elevated privileges.",
1815
+ fix: "Rename NEXT_PUBLIC_SECRET_KEY to SECRET_KEY and access it only in server-side code.",
1816
+ findingType: "vulnerability",
1817
+ aiCodeTarget: true
1818
+ },
1648
1819
  {
1649
1820
  id: "postgresql.auth.trust-auth-method",
1650
1821
  framework: [
@@ -1684,6 +1855,124 @@ PostgreSQL official docs: "Trust authentication is only suitable for TCP/IP conn
1684
1855
  fix: "Replace 'trust' with 'scram-sha-256' in pg_hba.conf and set POSTGRES_PASSWORD in your Docker configuration.",
1685
1856
  findingType: "vulnerability",
1686
1857
  aiCodeTarget: true
1858
+ },
1859
+ {
1860
+ id: "react.xss.dangerouslysetinnerhtml-unsanitized",
1861
+ framework: [
1862
+ "react"
1863
+ ],
1864
+ category: "injection",
1865
+ tier: "free",
1866
+ severity: "high",
1867
+ confidence: "MEDIUM",
1868
+ action: "warn",
1869
+ version: 4,
1870
+ status: "experimental",
1871
+ cwe: [
1872
+ "CWE-79"
1873
+ ],
1874
+ owasp: [
1875
+ "A03:2021"
1876
+ ],
1877
+ matcher: {
1878
+ type: "pattern",
1879
+ fileGlob: "**/*.{tsx,jsx,ts,js}",
1880
+ patterns: [
1881
+ "__html\\s*:\\s*`[^`]*\\$\\{",
1882
+ "__html\\s*:\\s*[A-Za-z_$][\\w$.]*\\s*(?:\\}|,|\\?\\?|\\|\\||\\?|!|\\bas\\s)",
1883
+ "__html\\s*:\\s*[A-Za-z_$][\\w$.]*\\s*\\+",
1884
+ `__html\\s*:\\s*[\\'"][^\\'"]*[\\'"]\\s*\\+`,
1885
+ "__html\\s*:\\s*[A-Za-z_$][\\w$.]*\\.(?:replace|replaceAll|trim|toString|slice|substring|concat|join|toLowerCase|toUpperCase)\\s*\\(",
1886
+ "dangerouslySetInnerHTML\\s*=\\s*\\{\\s*[A-Za-z_$][\\w$.]*\\s*\\}",
1887
+ "dangerouslySetInnerHTML\\s*=\\s*\\{\\s*\\{\\s*\\.\\.\\."
1888
+ ],
1889
+ antiPatterns: [
1890
+ "__html\\s*:\\s*(?:await\\s+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)\\s*\\(",
1891
+ `^[ \\t]*(?:const|let|var)[ \\t]+clean[ \\t]*=[ \\t]*(?:await[ \\t]+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)[ \\t]*\\([^\\n]{0,100}\\n(?:(?:[^=\\n]|[^=\\nn]=[{"\\']){0,100}\\n){0,3}(?:[^=\\n]|[^=\\nn]=[{"\\']){0,100}__html[ \\t]*:[ \\t]*clean[ \\t]*(?:\\}|,|(?:\\?\\?|\\|\\|)[ \\t]*(?:""|'')[ \\t]*[,}])`,
1892
+ `^[ \\t]*(?:const|let|var)[ \\t]+cleanHtml[ \\t]*=[ \\t]*(?:await[ \\t]+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)[ \\t]*\\([^\\n]{0,100}\\n(?:(?:[^=\\n]|[^=\\nl]=[{"\\']){0,100}\\n){0,3}(?:[^=\\n]|[^=\\nl]=[{"\\']){0,100}__html[ \\t]*:[ \\t]*cleanHtml[ \\t]*(?:\\}|,|(?:\\?\\?|\\|\\|)[ \\t]*(?:""|'')[ \\t]*[,}])`,
1893
+ `^[ \\t]*(?:const|let|var)[ \\t]+cleanContent[ \\t]*=[ \\t]*(?:await[ \\t]+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)[ \\t]*\\([^\\n]{0,100}\\n(?:(?:[^=\\n]|[^=\\nt]=[{"\\']){0,100}\\n){0,3}(?:[^=\\n]|[^=\\nt]=[{"\\']){0,100}__html[ \\t]*:[ \\t]*cleanContent[ \\t]*(?:\\}|,|(?:\\?\\?|\\|\\|)[ \\t]*(?:""|'')[ \\t]*[,}])`,
1894
+ `^[ \\t]*(?:const|let|var)[ \\t]+cleanMarkup[ \\t]*=[ \\t]*(?:await[ \\t]+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)[ \\t]*\\([^\\n]{0,100}\\n(?:(?:[^=\\n]|[^=\\np]=[{"\\']){0,100}\\n){0,3}(?:[^=\\n]|[^=\\np]=[{"\\']){0,100}__html[ \\t]*:[ \\t]*cleanMarkup[ \\t]*(?:\\}|,|(?:\\?\\?|\\|\\|)[ \\t]*(?:""|'')[ \\t]*[,}])`,
1895
+ `^[ \\t]*(?:const|let|var)[ \\t]+cleanBody[ \\t]*=[ \\t]*(?:await[ \\t]+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)[ \\t]*\\([^\\n]{0,100}\\n(?:(?:[^=\\n]|[^=\\ny]=[{"\\']){0,100}\\n){0,3}(?:[^=\\n]|[^=\\ny]=[{"\\']){0,100}__html[ \\t]*:[ \\t]*cleanBody[ \\t]*(?:\\}|,|(?:\\?\\?|\\|\\|)[ \\t]*(?:""|'')[ \\t]*[,}])`,
1896
+ `^[ \\t]*(?:const|let|var)[ \\t]+cleanText[ \\t]*=[ \\t]*(?:await[ \\t]+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)[ \\t]*\\([^\\n]{0,100}\\n(?:(?:[^=\\n]|[^=\\nt]=[{"\\']){0,100}\\n){0,3}(?:[^=\\n]|[^=\\nt]=[{"\\']){0,100}__html[ \\t]*:[ \\t]*cleanText[ \\t]*(?:\\}|,|(?:\\?\\?|\\|\\|)[ \\t]*(?:""|'')[ \\t]*[,}])`,
1897
+ `^[ \\t]*(?:const|let|var)[ \\t]+safe[ \\t]*=[ \\t]*(?:await[ \\t]+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)[ \\t]*\\([^\\n]{0,100}\\n(?:(?:[^=\\n]|[^=\\ne]=[{"\\']){0,100}\\n){0,3}(?:[^=\\n]|[^=\\ne]=[{"\\']){0,100}__html[ \\t]*:[ \\t]*safe[ \\t]*(?:\\}|,|(?:\\?\\?|\\|\\|)[ \\t]*(?:""|'')[ \\t]*[,}])`,
1898
+ `^[ \\t]*(?:const|let|var)[ \\t]+safeHtml[ \\t]*=[ \\t]*(?:await[ \\t]+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)[ \\t]*\\([^\\n]{0,100}\\n(?:(?:[^=\\n]|[^=\\nl]=[{"\\']){0,100}\\n){0,3}(?:[^=\\n]|[^=\\nl]=[{"\\']){0,100}__html[ \\t]*:[ \\t]*safeHtml[ \\t]*(?:\\}|,|(?:\\?\\?|\\|\\|)[ \\t]*(?:""|'')[ \\t]*[,}])`,
1899
+ `^[ \\t]*(?:const|let|var)[ \\t]+safeContent[ \\t]*=[ \\t]*(?:await[ \\t]+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)[ \\t]*\\([^\\n]{0,100}\\n(?:(?:[^=\\n]|[^=\\nt]=[{"\\']){0,100}\\n){0,3}(?:[^=\\n]|[^=\\nt]=[{"\\']){0,100}__html[ \\t]*:[ \\t]*safeContent[ \\t]*(?:\\}|,|(?:\\?\\?|\\|\\|)[ \\t]*(?:""|'')[ \\t]*[,}])`,
1900
+ `^[ \\t]*(?:const|let|var)[ \\t]+safeMarkup[ \\t]*=[ \\t]*(?:await[ \\t]+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)[ \\t]*\\([^\\n]{0,100}\\n(?:(?:[^=\\n]|[^=\\np]=[{"\\']){0,100}\\n){0,3}(?:[^=\\n]|[^=\\np]=[{"\\']){0,100}__html[ \\t]*:[ \\t]*safeMarkup[ \\t]*(?:\\}|,|(?:\\?\\?|\\|\\|)[ \\t]*(?:""|'')[ \\t]*[,}])`,
1901
+ `^[ \\t]*(?:const|let|var)[ \\t]+safeBody[ \\t]*=[ \\t]*(?:await[ \\t]+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)[ \\t]*\\([^\\n]{0,100}\\n(?:(?:[^=\\n]|[^=\\ny]=[{"\\']){0,100}\\n){0,3}(?:[^=\\n]|[^=\\ny]=[{"\\']){0,100}__html[ \\t]*:[ \\t]*safeBody[ \\t]*(?:\\}|,|(?:\\?\\?|\\|\\|)[ \\t]*(?:""|'')[ \\t]*[,}])`,
1902
+ `^[ \\t]*(?:const|let|var)[ \\t]+safeText[ \\t]*=[ \\t]*(?:await[ \\t]+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)[ \\t]*\\([^\\n]{0,100}\\n(?:(?:[^=\\n]|[^=\\nt]=[{"\\']){0,100}\\n){0,3}(?:[^=\\n]|[^=\\nt]=[{"\\']){0,100}__html[ \\t]*:[ \\t]*safeText[ \\t]*(?:\\}|,|(?:\\?\\?|\\|\\|)[ \\t]*(?:""|'')[ \\t]*[,}])`,
1903
+ `^[ \\t]*(?:const|let|var)[ \\t]+sanitized[ \\t]*=[ \\t]*(?:await[ \\t]+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)[ \\t]*\\([^\\n]{0,100}\\n(?:(?:[^=\\n]|[^=\\nd]=[{"\\']){0,100}\\n){0,3}(?:[^=\\n]|[^=\\nd]=[{"\\']){0,100}__html[ \\t]*:[ \\t]*sanitized[ \\t]*(?:\\}|,|(?:\\?\\?|\\|\\|)[ \\t]*(?:""|'')[ \\t]*[,}])`,
1904
+ `^[ \\t]*(?:const|let|var)[ \\t]+sanitizedHtml[ \\t]*=[ \\t]*(?:await[ \\t]+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)[ \\t]*\\([^\\n]{0,100}\\n(?:(?:[^=\\n]|[^=\\nl]=[{"\\']){0,100}\\n){0,3}(?:[^=\\n]|[^=\\nl]=[{"\\']){0,100}__html[ \\t]*:[ \\t]*sanitizedHtml[ \\t]*(?:\\}|,|(?:\\?\\?|\\|\\|)[ \\t]*(?:""|'')[ \\t]*[,}])`,
1905
+ `^[ \\t]*(?:const|let|var)[ \\t]+sanitizedContent[ \\t]*=[ \\t]*(?:await[ \\t]+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)[ \\t]*\\([^\\n]{0,100}\\n(?:(?:[^=\\n]|[^=\\nt]=[{"\\']){0,100}\\n){0,3}(?:[^=\\n]|[^=\\nt]=[{"\\']){0,100}__html[ \\t]*:[ \\t]*sanitizedContent[ \\t]*(?:\\}|,|(?:\\?\\?|\\|\\|)[ \\t]*(?:""|'')[ \\t]*[,}])`,
1906
+ `^[ \\t]*(?:const|let|var)[ \\t]+sanitizedMarkup[ \\t]*=[ \\t]*(?:await[ \\t]+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)[ \\t]*\\([^\\n]{0,100}\\n(?:(?:[^=\\n]|[^=\\np]=[{"\\']){0,100}\\n){0,3}(?:[^=\\n]|[^=\\np]=[{"\\']){0,100}__html[ \\t]*:[ \\t]*sanitizedMarkup[ \\t]*(?:\\}|,|(?:\\?\\?|\\|\\|)[ \\t]*(?:""|'')[ \\t]*[,}])`,
1907
+ `^[ \\t]*(?:const|let|var)[ \\t]+sanitizedBody[ \\t]*=[ \\t]*(?:await[ \\t]+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)[ \\t]*\\([^\\n]{0,100}\\n(?:(?:[^=\\n]|[^=\\ny]=[{"\\']){0,100}\\n){0,3}(?:[^=\\n]|[^=\\ny]=[{"\\']){0,100}__html[ \\t]*:[ \\t]*sanitizedBody[ \\t]*(?:\\}|,|(?:\\?\\?|\\|\\|)[ \\t]*(?:""|'')[ \\t]*[,}])`,
1908
+ `^[ \\t]*(?:const|let|var)[ \\t]+sanitizedText[ \\t]*=[ \\t]*(?:await[ \\t]+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)[ \\t]*\\([^\\n]{0,100}\\n(?:(?:[^=\\n]|[^=\\nt]=[{"\\']){0,100}\\n){0,3}(?:[^=\\n]|[^=\\nt]=[{"\\']){0,100}__html[ \\t]*:[ \\t]*sanitizedText[ \\t]*(?:\\}|,|(?:\\?\\?|\\|\\|)[ \\t]*(?:""|'')[ \\t]*[,}])`,
1909
+ `^[ \\t]*(?:const|let|var)[ \\t]+purified[ \\t]*=[ \\t]*(?:await[ \\t]+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)[ \\t]*\\([^\\n]{0,100}\\n(?:(?:[^=\\n]|[^=\\nd]=[{"\\']){0,100}\\n){0,3}(?:[^=\\n]|[^=\\nd]=[{"\\']){0,100}__html[ \\t]*:[ \\t]*purified[ \\t]*(?:\\}|,|(?:\\?\\?|\\|\\|)[ \\t]*(?:""|'')[ \\t]*[,}])`,
1910
+ `^[ \\t]*(?:const|let|var)[ \\t]+purifiedHtml[ \\t]*=[ \\t]*(?:await[ \\t]+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)[ \\t]*\\([^\\n]{0,100}\\n(?:(?:[^=\\n]|[^=\\nl]=[{"\\']){0,100}\\n){0,3}(?:[^=\\n]|[^=\\nl]=[{"\\']){0,100}__html[ \\t]*:[ \\t]*purifiedHtml[ \\t]*(?:\\}|,|(?:\\?\\?|\\|\\|)[ \\t]*(?:""|'')[ \\t]*[,}])`,
1911
+ `^[ \\t]*(?:const|let|var)[ \\t]+purifiedContent[ \\t]*=[ \\t]*(?:await[ \\t]+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)[ \\t]*\\([^\\n]{0,100}\\n(?:(?:[^=\\n]|[^=\\nt]=[{"\\']){0,100}\\n){0,3}(?:[^=\\n]|[^=\\nt]=[{"\\']){0,100}__html[ \\t]*:[ \\t]*purifiedContent[ \\t]*(?:\\}|,|(?:\\?\\?|\\|\\|)[ \\t]*(?:""|'')[ \\t]*[,}])`,
1912
+ `^[ \\t]*(?:const|let|var)[ \\t]+purifiedMarkup[ \\t]*=[ \\t]*(?:await[ \\t]+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)[ \\t]*\\([^\\n]{0,100}\\n(?:(?:[^=\\n]|[^=\\np]=[{"\\']){0,100}\\n){0,3}(?:[^=\\n]|[^=\\np]=[{"\\']){0,100}__html[ \\t]*:[ \\t]*purifiedMarkup[ \\t]*(?:\\}|,|(?:\\?\\?|\\|\\|)[ \\t]*(?:""|'')[ \\t]*[,}])`,
1913
+ `^[ \\t]*(?:const|let|var)[ \\t]+purifiedBody[ \\t]*=[ \\t]*(?:await[ \\t]+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)[ \\t]*\\([^\\n]{0,100}\\n(?:(?:[^=\\n]|[^=\\ny]=[{"\\']){0,100}\\n){0,3}(?:[^=\\n]|[^=\\ny]=[{"\\']){0,100}__html[ \\t]*:[ \\t]*purifiedBody[ \\t]*(?:\\}|,|(?:\\?\\?|\\|\\|)[ \\t]*(?:""|'')[ \\t]*[,}])`,
1914
+ `^[ \\t]*(?:const|let|var)[ \\t]+purifiedText[ \\t]*=[ \\t]*(?:await[ \\t]+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)[ \\t]*\\([^\\n]{0,100}\\n(?:(?:[^=\\n]|[^=\\nt]=[{"\\']){0,100}\\n){0,3}(?:[^=\\n]|[^=\\nt]=[{"\\']){0,100}__html[ \\t]*:[ \\t]*purifiedText[ \\t]*(?:\\}|,|(?:\\?\\?|\\|\\|)[ \\t]*(?:""|'')[ \\t]*[,}])`,
1915
+ `^[ \\t]*(?:const|let|var)[ \\t]+escaped[ \\t]*=[ \\t]*(?:await[ \\t]+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)[ \\t]*\\([^\\n]{0,100}\\n(?:(?:[^=\\n]|[^=\\nd]=[{"\\']){0,100}\\n){0,3}(?:[^=\\n]|[^=\\nd]=[{"\\']){0,100}__html[ \\t]*:[ \\t]*escaped[ \\t]*(?:\\}|,|(?:\\?\\?|\\|\\|)[ \\t]*(?:""|'')[ \\t]*[,}])`,
1916
+ `^[ \\t]*(?:const|let|var)[ \\t]+escapedHtml[ \\t]*=[ \\t]*(?:await[ \\t]+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)[ \\t]*\\([^\\n]{0,100}\\n(?:(?:[^=\\n]|[^=\\nl]=[{"\\']){0,100}\\n){0,3}(?:[^=\\n]|[^=\\nl]=[{"\\']){0,100}__html[ \\t]*:[ \\t]*escapedHtml[ \\t]*(?:\\}|,|(?:\\?\\?|\\|\\|)[ \\t]*(?:""|'')[ \\t]*[,}])`,
1917
+ `^[ \\t]*(?:const|let|var)[ \\t]+escapedContent[ \\t]*=[ \\t]*(?:await[ \\t]+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)[ \\t]*\\([^\\n]{0,100}\\n(?:(?:[^=\\n]|[^=\\nt]=[{"\\']){0,100}\\n){0,3}(?:[^=\\n]|[^=\\nt]=[{"\\']){0,100}__html[ \\t]*:[ \\t]*escapedContent[ \\t]*(?:\\}|,|(?:\\?\\?|\\|\\|)[ \\t]*(?:""|'')[ \\t]*[,}])`,
1918
+ `^[ \\t]*(?:const|let|var)[ \\t]+escapedMarkup[ \\t]*=[ \\t]*(?:await[ \\t]+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)[ \\t]*\\([^\\n]{0,100}\\n(?:(?:[^=\\n]|[^=\\np]=[{"\\']){0,100}\\n){0,3}(?:[^=\\n]|[^=\\np]=[{"\\']){0,100}__html[ \\t]*:[ \\t]*escapedMarkup[ \\t]*(?:\\}|,|(?:\\?\\?|\\|\\|)[ \\t]*(?:""|'')[ \\t]*[,}])`,
1919
+ `^[ \\t]*(?:const|let|var)[ \\t]+escapedBody[ \\t]*=[ \\t]*(?:await[ \\t]+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)[ \\t]*\\([^\\n]{0,100}\\n(?:(?:[^=\\n]|[^=\\ny]=[{"\\']){0,100}\\n){0,3}(?:[^=\\n]|[^=\\ny]=[{"\\']){0,100}__html[ \\t]*:[ \\t]*escapedBody[ \\t]*(?:\\}|,|(?:\\?\\?|\\|\\|)[ \\t]*(?:""|'')[ \\t]*[,}])`,
1920
+ `^[ \\t]*(?:const|let|var)[ \\t]+escapedText[ \\t]*=[ \\t]*(?:await[ \\t]+)?(?:DOMPurify\\.sanitize|purify\\.sanitize|sanitize[A-Za-z_]{0,12}|escapeHtml|xss)[ \\t]*\\([^\\n]{0,100}\\n(?:(?:[^=\\n]|[^=\\nt]=[{"\\']){0,100}\\n){0,3}(?:[^=\\n]|[^=\\nt]=[{"\\']){0,100}__html[ \\t]*:[ \\t]*escapedText[ \\t]*(?:\\}|,|(?:\\?\\?|\\|\\|)[ \\t]*(?:""|'')[ \\t]*[,}])`
1921
+ ],
1922
+ flags: "m",
1923
+ antiPatternScope: {
1924
+ lines: 3
1925
+ }
1926
+ },
1927
+ explanation: "dangerouslySetInnerHTML is given a value built at run time (a variable, a property, or a string with ${...} or + parts in it) and the file shows no sanitizer. React does not escape this value, so if any of it comes from a user (a comment, a profile bio, a URL parameter, a database row somebody else wrote), an attacker can run JavaScript in other visitors' browsers and steal their session.",
1928
+ recommendation: "Run the value through a sanitizer such as DOMPurify.sanitize() before it reaches __html, or render the content as text, or use a Markdown component that does not need dangerouslySetInnerHTML. A fixed string you wrote yourself, or JSON.stringify(...) for JSON-LD, is fine and is not reported.",
1929
+ fix: "Use `{ __html: DOMPurify.sanitize(value) }` after `npm i dompurify`.",
1930
+ findingType: "vulnerability",
1931
+ aiCodeTarget: true
1932
+ },
1933
+ {
1934
+ id: "supabase.rls.permissive-policy-using-true",
1935
+ framework: [
1936
+ "supabase"
1937
+ ],
1938
+ category: "database",
1939
+ tier: "free",
1940
+ severity: "high",
1941
+ confidence: "MEDIUM",
1942
+ action: "warn",
1943
+ version: 3,
1944
+ status: "experimental",
1945
+ cwe: [
1946
+ "CWE-284",
1947
+ "CWE-732"
1948
+ ],
1949
+ owasp: [
1950
+ "A01:2021"
1951
+ ],
1952
+ matcher: {
1953
+ type: "pattern",
1954
+ fileGlob: "**/*.sql",
1955
+ patterns: [
1956
+ "with\\s+check\\s*\\(\\s*true\\s*\\)",
1957
+ "for\\s+(?:insert|update|delete|all)\\s+(?:to\\s+[\\w,]+\\s+)?using\\s*\\(\\s*true\\s*\\)",
1958
+ '\\bon\\s+[\\w."]+\\s+(?:to\\s+\\w+\\s+)?using\\s*\\(\\s*true\\s*\\)'
1959
+ ],
1960
+ antiPatterns: [
1961
+ "-- public catalog",
1962
+ "-- intentionally open",
1963
+ "-- read-only public",
1964
+ "__tests__|test_migration"
1965
+ ],
1966
+ flags: "i",
1967
+ antiPatternScope: {
1968
+ lines: 5
1969
+ }
1970
+ },
1971
+ explanation: "A row-level security policy that can change data (INSERT, UPDATE, DELETE, or no FOR clause, which means ALL commands) uses USING (true) or WITH CHECK (true). That grants every row to every role the policy names, which is the same as having no row-level security on writes: any signed-in or anonymous user can modify or delete other people's rows.",
1972
+ recommendation: "Replace true with a condition that ties the row to the user, such as USING (auth.uid() = user_id) and WITH CHECK (auth.uid() = user_id). A SELECT policy of USING (true) on a public table is a legitimate choice and is not reported. If a write policy is open on purpose (a waitlist or contact form that only inserts), add the comment `-- intentionally open` above it.",
1973
+ fix: "Replace USING (true) / WITH CHECK (true) with USING (auth.uid() = user_id) / WITH CHECK (auth.uid() = user_id).",
1974
+ findingType: "vulnerability",
1975
+ aiCodeTarget: true
1687
1976
  }
1688
1977
  ]
1689
1978
  };
@@ -2004,6 +2293,52 @@ function collapseSameIssueFindings(findings) {
2004
2293
  return { findings: findings.filter((_, i) => !dropped.has(i)), notes };
2005
2294
  }
2006
2295
 
2296
+ // src/core/tidy-findings.ts
2297
+ var HANDLER_DECL_RE = compileDetectorRegex(
2298
+ "\\bexport\\s+(?:async\\s+)?function\\s+POST\\b|\\bexport\\s+const\\s+POST\\b|\\bexport\\s+default\\s+(?:async\\s+)?function\\b"
2299
+ );
2300
+ var HANDLER_CALL_RE = compileDetectorRegex("\\.post\\s*\\(");
2301
+ var HANDLER_ANCHORED = /* @__PURE__ */ new Set([
2302
+ "payment_webhook_without_signature_check",
2303
+ "missing_idempotency",
2304
+ "missing_error_handling"
2305
+ ]);
2306
+ function firstHandlerLine(content) {
2307
+ const lines = content.split("\n");
2308
+ for (const re of [HANDLER_DECL_RE, HANDLER_CALL_RE]) {
2309
+ for (let i = 0; i < lines.length; i++) {
2310
+ if (re.test(lines[i])) return i + 1;
2311
+ }
2312
+ }
2313
+ return void 0;
2314
+ }
2315
+ function fillMissingLines(findings, files) {
2316
+ const byPath = /* @__PURE__ */ new Map();
2317
+ for (const f of files) if (!byPath.has(f.relativePath)) byPath.set(f.relativePath, f);
2318
+ let filled = 0;
2319
+ for (const f of findings) {
2320
+ if (f.line !== void 0 && f.line !== null) continue;
2321
+ if (!f.file) continue;
2322
+ const file = byPath.get(f.file);
2323
+ const anchored = HANDLER_ANCHORED.has(f.id) && file ? firstHandlerLine(file.content) : void 0;
2324
+ f.line = anchored ?? 1;
2325
+ filled++;
2326
+ }
2327
+ return filled;
2328
+ }
2329
+ function lowerFakeKeyConfidence(findings) {
2330
+ let lowered = 0;
2331
+ for (const f of findings) {
2332
+ const isSecret = f.category === "secrets" || f.id.includes(".secrets.");
2333
+ if (!isSecret || f.column === void 0 || f.confidence === "LOW" || !f.evidence) continue;
2334
+ const value = f.evidence.trim().replace(/^['"`]+|['"`]+$/g, "");
2335
+ if (/\s/.test(value) || !looksFakeKey(value)) continue;
2336
+ f.confidence = "LOW";
2337
+ lowered++;
2338
+ }
2339
+ return lowered;
2340
+ }
2341
+
2007
2342
  // src/core/scanner.ts
2008
2343
  var CHECK_MODULES = [secretsCheck, authCheck, databaseCheck, payments, deploymentCheck];
2009
2344
  function computeTreeDigest(files) {
@@ -2178,6 +2513,7 @@ async function scan(options, proRules, onProgress) {
2178
2513
  ignoreRules
2179
2514
  });
2180
2515
  }
2516
+ assertCwdAlive();
2181
2517
  const files = state.files;
2182
2518
  const skippedTooLarge = state.skippedTooLarge;
2183
2519
  const skippedTooLargeFiles = state.skippedTooLargeFiles;
@@ -2239,6 +2575,8 @@ async function scan(options, proRules, onProgress) {
2239
2575
  );
2240
2576
  }
2241
2577
  allFindings = collapsed.findings;
2578
+ fillMissingLines(allFindings, files);
2579
+ lowerFakeKeyConfidence(allFindings);
2242
2580
  redactFindingsEvidence(allFindings, sourceRedacted);
2243
2581
  const riskScore = computeRiskScore(allFindings);
2244
2582
  const treeDigest = computeTreeDigest(files);
@@ -2297,7 +2635,7 @@ async function scan(options, proRules, onProgress) {
2297
2635
  detail: `${state.skippedUnknownBinary} file(s) contain NUL or control data that no text reading explains and show no sign of a known binary format, so they were not scanned: ${named}${extra}. If they are safe, add their paths to ignore.paths in shipguard.policy.yml.`
2298
2636
  });
2299
2637
  }
2300
- if (state.acceptedPaths === 0 && !nothingToCheck) {
2638
+ if (state.acceptedPaths === 0) {
2301
2639
  const parts = [];
2302
2640
  const add = (n, label) => {
2303
2641
  if (n > 0) parts.push(`${n} ${label}`);
@@ -2312,7 +2650,7 @@ async function scan(options, proRules, onProgress) {
2312
2650
  add(state.notReached, "not reached");
2313
2651
  degradedReasons.push({
2314
2652
  code: "NO_FILES_SCANNED",
2315
- detail: `0 files were scanned (${state.discovered} candidate file(s)${parts.length > 0 ? `: ${parts.join(", ")}` : ""}, 0 readable). A scan that read nothing cannot report that shipping is safe.`
2653
+ detail: nothingToCheck ? "--changed: git reports no changed files, so nothing was scanned. This is NOT a safe-to-ship result: run `shipguard scan` (without --changed) to check the whole tree." : `0 files were scanned (${state.discovered} candidate file(s)${parts.length > 0 ? `: ${parts.join(", ")}` : ""}, 0 readable). A scan that read nothing cannot report that shipping is safe.`
2316
2654
  });
2317
2655
  }
2318
2656
  const isDegraded = degradedReasons.length > 0 || void 0;
@@ -2472,7 +2810,7 @@ function quickstartHelp(isTTY) {
2472
2810
  lines.push(` ${chalk.cyan("hook")} ${chalk.dim("--target")} Install the gate at the merge boundary`);
2473
2811
  lines.push(` ${chalk.cyan("schema")} ${chalk.dim("--json")} Print the machine-readable scan contract`);
2474
2812
  lines.push(` ${chalk.cyan("feedback")} Where to send feedback (GitHub issues)`);
2475
- lines.push(` ${chalk.cyan("rate")} ${chalk.dim("<id> up|down")} Rate a rule finding`);
2813
+ lines.push(` ${chalk.cyan("rate")} ${chalk.dim("<n> helpful|not-helpful")} Rate a rule finding`);
2476
2814
  lines.push(` ${chalk.cyan("telemetry")} ${chalk.dim("status")} Show or change the pseudonymous usage ping`);
2477
2815
  lines.push(` ${chalk.cyan("help")} ${chalk.dim("/ ?")} Show this screen`);
2478
2816
  lines.push("");
@@ -2506,7 +2844,7 @@ function quickstartHelp(isTTY) {
2506
2844
  lines.push(" hook --target Install the gate at the merge boundary");
2507
2845
  lines.push(" schema --json Machine-readable scan contract");
2508
2846
  lines.push(" feedback Where to send feedback (GitHub issues)");
2509
- lines.push(" rate <id> up|down Rate a finding");
2847
+ lines.push(" rate <n> helpful|not-helpful Rate finding number n");
2510
2848
  lines.push(" telemetry status|enable|disable|reset Pseudonymous usage ping");
2511
2849
  lines.push(" help / ? Show this screen");
2512
2850
  lines.push("");
@@ -2552,7 +2890,10 @@ var SEVERITY_COLORS = {
2552
2890
  info: chalk.gray
2553
2891
  };
2554
2892
  function renderNothingToCheck() {
2555
- return chalk.green(" \u2713 Nothing to check: no files changed, so nothing was scanned.");
2893
+ return chalk.yellow(" \u26A0 Nothing was scanned: no files changed. This is NOT a safe-to-ship result.");
2894
+ }
2895
+ function renderNothingScanned() {
2896
+ return chalk.yellow(" \u26A0 Nothing to scan: no readable files were found. This is NOT a clean result.");
2556
2897
  }
2557
2898
  function renderFindingsSummary(findings) {
2558
2899
  if (findings.length === 0) {
@@ -2769,12 +3110,12 @@ function actionFooter(opts) {
2769
3110
  const lines = [""];
2770
3111
  lines.push(chalk.bold(" \u2500\u2500 What now? \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"));
2771
3112
  lines.push("");
2772
- lines.push(` ${chalk.cyan("shipguard report")} ${chalk.dim("# open the full report")}`);
3113
+ lines.push(` ${chalk.cyan("shipguard hook --target git")} ${chalk.dim("# run this gate before every push")}`);
2773
3114
  if (hasFindings && topRuleId) {
2774
- lines.push(` ${chalk.cyan(`shipguard rate ${topRuleId} up`)} ${chalk.dim("# was this finding helpful?")}`);
2775
- lines.push(` ${chalk.cyan(`shipguard rate ${topRuleId} down`)} ${chalk.dim("# false positive?")}`);
3115
+ lines.push(` ${chalk.cyan(`shipguard rate 1 helpful`)} ${chalk.dim("# was this finding helpful?")}`);
3116
+ lines.push(` ${chalk.cyan(`shipguard rate 1 not-helpful`)} ${chalk.dim("# false positive?")}`);
2776
3117
  } else if (hasFindings) {
2777
- lines.push(` ${chalk.cyan("shipguard rate <ruleId> up")} ${chalk.dim("# rate a finding")}`);
3118
+ lines.push(` ${chalk.cyan("shipguard rate <n> helpful")} ${chalk.dim("# rate a finding (or not-helpful)")}`);
2778
3119
  }
2779
3120
  lines.push(` ${chalk.cyan('shipguard feedback "<thoughts>"')} ${chalk.dim("# what do you think?")}`);
2780
3121
  if (!isLoggedIn) {
@@ -2837,7 +3178,7 @@ function quietVerdict(result, strict) {
2837
3178
  const degraded = result.degraded === true;
2838
3179
  const icon = recommendation === "SAFE_TO_SHIP" ? "\u2705" : recommendation === "DO_NOT_SHIP" ? "\u26D4" : "\u26A0\uFE0F";
2839
3180
  const colorFn = recommendation === "SAFE_TO_SHIP" ? chalk.green : recommendation === "DO_NOT_SHIP" ? chalk.red : chalk.yellow;
2840
- const degradedNote = degraded ? " incomplete=yes" : "";
3181
+ const degradedNote = (degraded ? " incomplete=yes" : "") + (result.coverage?.scanned === 0 ? " nothing-scanned=yes" : "");
2841
3182
  const suffix = blockingCount > 0 && !strict ? " (informational \u2014 exit 0; use --strict to enforce)" : "";
2842
3183
  return colorFn(`${icon} ${recommendation.replace(/_/g, " ")} score=${score}/100 findings=${totalFindings} blocking=${blockingCount}${degradedNote}${suffix}`);
2843
3184
  }
@@ -3111,6 +3452,7 @@ function resolveRepoIdentity(cwd) {
3111
3452
  }
3112
3453
  }
3113
3454
  const id = randomUUID();
3455
+ assertCwdAlive();
3114
3456
  mkdirSync(dirname(fallbackPath), { recursive: true });
3115
3457
  writeFileSync2(fallbackPath, `${id}
3116
3458
  `, "utf-8");
@@ -3209,6 +3551,7 @@ var HistoryStore = class _HistoryStore {
3209
3551
  }
3210
3552
  const preExisted = existsSync5(dbPath);
3211
3553
  try {
3554
+ assertCwdAlive();
3212
3555
  mkdirSync2(dirname2(dbPath), { recursive: true });
3213
3556
  } catch (err) {
3214
3557
  return {
@@ -3914,7 +4257,7 @@ var IS_PUBLISHED_BUILD = true;
3914
4257
  function getProvenance(published = IS_PUBLISHED_BUILD) {
3915
4258
  return published ? "published" : "dev";
3916
4259
  }
3917
- var PROD_TELEMETRY_ENDPOINT = "https://cheery-toucan-348.convex.site/cli-telemetry";
4260
+ var PROD_TELEMETRY_ENDPOINT = "https://agenticcli.dev/api/cli-telemetry";
3918
4261
  function isLoopbackUrl(raw2) {
3919
4262
  if (!raw2) return false;
3920
4263
  try {
@@ -3934,6 +4277,21 @@ function resolveTraffic(env, published) {
3934
4277
  if (v === "test" || v === "internal") return v;
3935
4278
  return published ? void 0 : "test";
3936
4279
  }
4280
+ var TELEMETRY_AGENTS = ["claude_code", "codex", "cursor", "gemini_cli", "copilot", "opencode", "other_agent", "none"];
4281
+ var TELEMETRY_OUTPUTS = ["json", "human", "sarif"];
4282
+ var AGENT_MARKERS = [
4283
+ ["claude_code", ["CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT"]],
4284
+ ["codex", ["CODEX_SANDBOX", "CODEX_SANDBOX_NETWORK_DISABLED"]],
4285
+ ["cursor", ["CURSOR_AGENT"]],
4286
+ ["gemini_cli", ["GEMINI_CLI"]],
4287
+ ["copilot", ["COPILOT_CLI", "COPILOT_AGENT_RUNNER_TYPE"]],
4288
+ ["opencode", ["OPENCODE"]]
4289
+ ];
4290
+ var OTHER_AGENT_MARKERS = ["AI_AGENT", "AGENT", "GOOSE_TERMINAL"];
4291
+ function detectAgent(env = process.env) {
4292
+ for (const [agent, vars] of AGENT_MARKERS) if (vars.some((k) => env[k] !== void 0 && env[k] !== "")) return agent;
4293
+ return OTHER_AGENT_MARKERS.some((k) => env[k] !== void 0 && env[k] !== "") ? "other_agent" : "none";
4294
+ }
3937
4295
  var ALLOWED_KEYS = [
3938
4296
  "schema",
3939
4297
  "eventId",
@@ -3942,7 +4300,10 @@ var ALLOWED_KEYS = [
3942
4300
  "provenance",
3943
4301
  "verdict",
3944
4302
  "durationBucket",
3945
- "ci"
4303
+ "ci",
4304
+ "agent",
4305
+ "interactive",
4306
+ "output"
3946
4307
  ];
3947
4308
  var VERSION_RE = /^(0|[1-9]\d{0,2})\.(0|[1-9]\d{0,2})\.(0|[1-9]\d{0,2})(-[0-9A-Za-z.-]{1,24})?$/;
3948
4309
  var DURATION_BUCKETS = ["lt1s", "1to5s", "5to30s", "gt30s"];
@@ -3988,8 +4349,8 @@ function envOptOut(env) {
3988
4349
  return null;
3989
4350
  }
3990
4351
  function buildPayload(input) {
3991
- const { schema, eventId, installId, cliVersion, provenance, verdict, durationBucket: durationBucket2, ci, traffic } = input;
3992
- const out = { schema, eventId, installId, cliVersion, provenance, verdict, durationBucket: durationBucket2, ci };
4352
+ const { schema, eventId, installId, cliVersion, provenance, verdict, durationBucket: durationBucket2, ci, agent, interactive, output, traffic } = input;
4353
+ const out = { schema, eventId, installId, cliVersion, provenance, verdict, durationBucket: durationBucket2, ci, agent, interactive, output };
3993
4354
  if (traffic === "test" || traffic === "internal") out.traffic = traffic;
3994
4355
  return out;
3995
4356
  }
@@ -4003,7 +4364,7 @@ function validatePayload(payload) {
4003
4364
  const keys = Object.keys(obj);
4004
4365
  if (!isTrafficOk(obj, keys.length, ALLOWED_KEYS.length)) return false;
4005
4366
  for (const k of ALLOWED_KEYS) if (!(k in obj)) return false;
4006
- if (obj.schema !== 2) return false;
4367
+ if (obj.schema !== 4) return false;
4007
4368
  if (typeof obj.eventId !== "string" || !UUID_V4.test(obj.eventId)) return false;
4008
4369
  if (typeof obj.ci !== "boolean") return false;
4009
4370
  if (obj.ci) {
@@ -4015,6 +4376,9 @@ function validatePayload(payload) {
4015
4376
  if (obj.provenance !== "published" && obj.provenance !== "dev") return false;
4016
4377
  if (!["safe", "review", "blocked", "error"].includes(obj.verdict)) return false;
4017
4378
  if (!DURATION_BUCKETS.includes(obj.durationBucket)) return false;
4379
+ if (!TELEMETRY_AGENTS.includes(obj.agent)) return false;
4380
+ if (typeof obj.interactive !== "boolean") return false;
4381
+ if (!TELEMETRY_OUTPUTS.includes(obj.output)) return false;
4018
4382
  return true;
4019
4383
  }
4020
4384
  function decideTelemetry(input = {}) {
@@ -4028,7 +4392,15 @@ function decideTelemetry(input = {}) {
4028
4392
  if (projectTelemetryEnabled({ policy: input.policy, projectDir: input.projectDir }) === false) return { enabled: false, source: "project-policy" };
4029
4393
  return { enabled: true, source: "default" };
4030
4394
  }
4031
- var NOTICE_TEXT = "shipguard: sends a pseudonymous usage ping after each scan, once on first run and after login (version, verdict, duration bucket, a random install id outside CI; never code, paths or your account). Turn it off: SHIPGUARD_TELEMETRY=0, DO_NOT_TRACK=1, or `shipguard telemetry disable`. " + goLink("telemetry");
4395
+ var NOTICE_TEXT = "shipguard: usage pings: on (turn off: SHIPGUARD_TELEMETRY=0, DO_NOT_TRACK=1, or `shipguard telemetry disable`). A pseudonymous ping after each scan, once on first run and after login. Every ping carries the version, build type, a CI flag and a random install id outside CI; a scan ping also carries the verdict, a duration bucket, which coding agent runs it (or none), whether stdout is a terminal and the output kind. Never code, paths or your account. " + goLink("telemetry");
4396
+ function telemetryState(opts = {}) {
4397
+ try {
4398
+ return decideTelemetry(opts).enabled ? "on" : "off";
4399
+ } catch (err) {
4400
+ logger.debug(`telemetry: state check failed, reporting off: ${err instanceof Error ? err.message : String(err)}`);
4401
+ return "off";
4402
+ }
4403
+ }
4032
4404
  var PING_WAIT_MS = 1500;
4033
4405
  var FETCH_TIMEOUT_MS = 1e3;
4034
4406
  function debugEnabled(env) {
@@ -4050,13 +4422,16 @@ function sendTelemetry(input, opts = {}) {
4050
4422
  const endpoint = resolveEndpoint(published, env);
4051
4423
  const ci = detectCi(env);
4052
4424
  const base = {
4053
- schema: 2,
4425
+ schema: 4,
4054
4426
  eventId: randomUUID5(),
4055
4427
  cliVersion: input.cliVersion,
4056
4428
  provenance: getProvenance(published),
4057
4429
  verdict: input.verdict,
4058
4430
  durationBucket: durationBucket(input.durationMs),
4059
4431
  ci,
4432
+ agent: detectAgent(env),
4433
+ interactive: opts.interactive ?? Boolean(process.stdout.isTTY),
4434
+ output: input.output,
4060
4435
  traffic: resolveTraffic(env, published)
4061
4436
  };
4062
4437
  if (debug) {
@@ -4117,7 +4492,7 @@ function postBounded(endpoint, body) {
4117
4492
  });
4118
4493
  });
4119
4494
  }
4120
- var CLI_VERSION = true ? "0.11.0" : process.env.npm_package_version ?? "0.0.0-dev";
4495
+ var CLI_VERSION = true ? "0.12.0" : process.env.npm_package_version ?? "0.0.0-dev";
4121
4496
  var LIFECYCLE_KEYS = ["schema", "event", "eventId", "installId", "cliVersion", "provenance", "ci"];
4122
4497
  function validateLifecyclePayload(payload) {
4123
4498
  if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return false;
@@ -4238,7 +4613,7 @@ function exitWhenDrained() {
4238
4613
 
4239
4614
  // src/commands/scan.ts
4240
4615
  var LEARN_MORE = `Docs ${goLink("docs")} \xB7 Site ${goLink("site")} \xB7 Pricing ${goLink("pricing")} \xB7 Issues https://github.com/agenticcli/shipguard/issues`;
4241
- var CLI_VERSION2 = true ? "0.11.0" : process.env.npm_package_version ?? "0.0.0-dev";
4616
+ var CLI_VERSION2 = true ? "0.12.0" : process.env.npm_package_version ?? "0.0.0-dev";
4242
4617
  function resolveExitCode(opts) {
4243
4618
  if (opts.strict && (opts.blockingCount > 0 || opts.degraded === true || opts.recommendation === "DO_NOT_SHIP")) {
4244
4619
  return EXIT_CODES.BLOCKED;
@@ -4272,6 +4647,15 @@ function platformUnavailableMessage(retryAfterSeconds) {
4272
4647
  const wait = retryAfterSeconds !== void 0 ? ` (suggested wait: ${formatSuggestedWait(retryAfterSeconds)})` : "";
4273
4648
  return `ShipGuard's service is temporarily unavailable. This is on our side, not a problem with your project. Please try again in a few minutes${wait}, or pass --allow-degraded to run local rules only.`;
4274
4649
  }
4650
+ var EXIT_NOTICE = "exit 0 = scan finished, not safe. Add --strict to fail on blocking findings.";
4651
+ function exitMeaning(opts) {
4652
+ if (opts.exitCode === EXIT_CODES.BLOCKED) {
4653
+ return opts.regressionBlocks ? "exit 1 = blocked: --check-regressions found a rule that passed before and now fails." : "exit 1 = blocked: --strict found a blocking finding, a scan that did not finish, or a DO_NOT_SHIP verdict.";
4654
+ }
4655
+ if (opts.strict) return "exit 0 = scan finished and --strict found nothing that blocks.";
4656
+ if (opts.notSafe) return EXIT_NOTICE;
4657
+ return "exit 0 = scan finished. Read recommendation for the verdict; add --strict to fail on blocking findings.";
4658
+ }
4275
4659
  function isProjectRoot(dir) {
4276
4660
  return existsSync7(join7(dir, "package.json")) || existsSync7(join7(dir, ".git"));
4277
4661
  }
@@ -4342,18 +4726,19 @@ ${LEARN_MORE}`).action(async (scanPath, opts) => {
4342
4726
  if (machineOutput) {
4343
4727
  console.log(JSON.stringify({ error: pathProblem.message, code: pathProblem.code }));
4344
4728
  }
4345
- return exitWithError(EXIT_CODES.CONFIG_ERROR, startTime, process.cwd());
4729
+ return exitWithError(EXIT_CODES.CONFIG_ERROR, startTime, process.cwd(), outputKind(opts));
4346
4730
  }
4347
4731
  }
4348
4732
  if (!scanPath && !opts.all && !isProjectRoot(cwd)) {
4349
- logger.error(
4350
- `Refusing to scan a non-project directory ${cwd}. Pass a path (\`shipguard scan ./my-app\`) or \`--all\` to override.`
4351
- );
4352
- if (!machineOutput) {
4733
+ const refusal = `Refusing to scan a non-project directory ${cwd}. Pass a path (\`shipguard scan ./my-app\`) or \`--all\` to override.`;
4734
+ logger.error(refusal);
4735
+ if (machineOutput) {
4736
+ console.log(JSON.stringify({ error: refusal, code: "NOT_A_PROJECT" }));
4737
+ } else {
4353
4738
  console.log(`
4354
4739
  ${LEARN_MORE}`);
4355
4740
  }
4356
- return exitWithError(EXIT_CODES.CONFIG_ERROR, startTime, process.cwd());
4741
+ return exitWithError(EXIT_CODES.CONFIG_ERROR, startTime, process.cwd(), outputKind(opts));
4357
4742
  }
4358
4743
  const originalCwd = process.cwd();
4359
4744
  if (scanPath) {
@@ -4368,10 +4753,13 @@ ${LEARN_MORE}`);
4368
4753
  }
4369
4754
  });
4370
4755
  }
4371
- async function exitWithError(exitCode, startTime, projectDir, policy) {
4756
+ function outputKind(opts) {
4757
+ return opts.sarif ? "sarif" : opts.json ? "json" : "human";
4758
+ }
4759
+ async function exitWithError(exitCode, startTime, projectDir, output, policy) {
4372
4760
  try {
4373
4761
  await sendTelemetry(
4374
- { cliVersion: CLI_VERSION2, verdict: "error", durationMs: Date.now() - startTime },
4762
+ { cliVersion: CLI_VERSION2, verdict: "error", durationMs: Date.now() - startTime, output },
4375
4763
  { policy, projectDir }
4376
4764
  );
4377
4765
  } catch (err) {
@@ -4398,8 +4786,12 @@ async function runScan(ctx) {
4398
4786
  try {
4399
4787
  policy = await loadPolicy(cwd);
4400
4788
  } catch (error) {
4401
- logger.error(`Config error: ${error instanceof Error ? error.message : error}`);
4402
- return exitWithError(EXIT_CODES.CONFIG_ERROR, startTime, cwd);
4789
+ const message = error instanceof Error ? error.message : String(error);
4790
+ logger.error(`Config error: ${message}`);
4791
+ if (machineOutput) {
4792
+ console.log(JSON.stringify({ error: message, code: "INVALID_POLICY" }));
4793
+ }
4794
+ return exitWithError(EXIT_CODES.CONFIG_ERROR, startTime, cwd, outputKind(opts));
4403
4795
  }
4404
4796
  const changedOnly = Boolean(opts.changed);
4405
4797
  const categories = opts.category ? opts.category.split(",").map((c) => c.trim()) : [];
@@ -4449,8 +4841,8 @@ async function runScan(ctx) {
4449
4841
  logger.info("Detecting stack...");
4450
4842
  }
4451
4843
  try {
4452
- const { fetchProRules } = await import("./pro-scanner-43JOEAJM.js");
4453
- const { hasConfig, generateConfig } = await import("./config-generator-L7VDUKDY.js");
4844
+ const { fetchProRules } = await import("./pro-scanner-NSDJLVII.js");
4845
+ const { hasConfig, generateConfig } = await import("./config-generator-BNFR3LZR.js");
4454
4846
  const frameworks = detectedFrameworks;
4455
4847
  if (!hasConfig(cwd)) {
4456
4848
  const configPath = generateConfig(cwd, frameworks);
@@ -4492,7 +4884,7 @@ async function runScan(ctx) {
4492
4884
  } else {
4493
4885
  console.log(JSON.stringify({ error: errMsg, code: "NO_RULES_APPLIED" }));
4494
4886
  }
4495
- return exitWithError(EXIT_CODES.RUNTIME_ERROR, startTime, cwd, policy);
4887
+ return exitWithError(EXIT_CODES.RUNTIME_ERROR, startTime, cwd, outputKind(opts), policy);
4496
4888
  }
4497
4889
  const rawErrCode = err?.code;
4498
4890
  const KNOWN_PRO_FETCH_ERROR_CODES = [
@@ -4531,7 +4923,7 @@ async function runScan(ctx) {
4531
4923
  ...retryAfterSeconds !== void 0 ? { retryAfterSeconds } : {}
4532
4924
  }));
4533
4925
  }
4534
- return exitWithError(EXIT_CODES.RUNTIME_ERROR, startTime, cwd, policy);
4926
+ return exitWithError(EXIT_CODES.RUNTIME_ERROR, startTime, cwd, outputKind(opts), policy);
4535
4927
  }
4536
4928
  }
4537
4929
  }
@@ -4563,7 +4955,7 @@ async function runScan(ctx) {
4563
4955
  } else {
4564
4956
  console.log(JSON.stringify({ error: String(error) }));
4565
4957
  }
4566
- return exitWithError(EXIT_CODES.RUNTIME_ERROR, startTime, cwd, policy);
4958
+ return exitWithError(EXIT_CODES.RUNTIME_ERROR, startTime, cwd, outputKind(opts), policy);
4567
4959
  }
4568
4960
  if (showProgress) {
4569
4961
  process.stderr.write("\r\x1B[K");
@@ -4622,6 +5014,7 @@ async function runScan(ctx) {
4622
5014
  result.coverageChanged = historyOutcome.coverageChanged;
4623
5015
  }
4624
5016
  const publicResult = { ...result };
5017
+ publicResult.telemetry = telemetryState({ policy, projectDir: cwd });
4625
5018
  const shouldReport = scanOptions.generateReport || policy.scan.generate_report;
4626
5019
  let reportPaths;
4627
5020
  if (shouldReport) {
@@ -4632,6 +5025,24 @@ async function runScan(ctx) {
4632
5025
  logger.error(`Report generation failed: ${error instanceof Error ? error.message : error}`);
4633
5026
  }
4634
5027
  }
5028
+ let exitCode = resolveExitCode({
5029
+ strict: scanOptions.strict,
5030
+ blockingCount: result.riskScore.blockingCount,
5031
+ // the hard stop must not inherit the false-safe on an
5032
+ // unfinished scan. Uses the FINAL degraded value (post pro-fetch OR-merge).
5033
+ degraded: result.degraded === true,
5034
+ // CLI-2/J-3 — the hard stop must not disagree with the printed verdict:
5035
+ // a scan can print DO_NOT_SHIP with blockingCount 0 (active non-blocking findings,
5036
+ // degradation). effectiveRecommendation
5037
+ // reads the SAME field the human panel / --json `recommendation` print.
5038
+ recommendation: effectiveRecommendation(result)
5039
+ });
5040
+ const strictBlocked = exitCode === EXIT_CODES.BLOCKED;
5041
+ const regressionBlocks = Boolean(opts.checkRegressions) && exitCode === EXIT_CODES.SAFE && (result.regressions?.length ?? 0) > 0;
5042
+ if (regressionBlocks) exitCode = EXIT_CODES.BLOCKED;
5043
+ const notSafe = result.riskScore.blockingCount > 0 || effectiveRecommendation(result) === "DO_NOT_SHIP";
5044
+ const showExitNotice = exitCode === EXIT_CODES.SAFE && !scanOptions.strict && notSafe;
5045
+ publicResult.exitMeaning = exitMeaning({ exitCode, strict: scanOptions.strict, notSafe, regressionBlocks });
4635
5046
  if (opts.sarif) {
4636
5047
  console.log(JSON.stringify(toSarif(publicResult), null, 2));
4637
5048
  } else if (scanOptions.json) {
@@ -4647,6 +5058,8 @@ async function runScan(ctx) {
4647
5058
  }
4648
5059
  if (result.coverage?.changed?.nothingToCheck) {
4649
5060
  console.log(renderNothingToCheck());
5061
+ } else if (coverage && coverage.scanned === 0) {
5062
+ console.log(renderNothingScanned());
4650
5063
  } else {
4651
5064
  console.log(renderFindingsSummary(result.findings));
4652
5065
  }
@@ -4685,7 +5098,7 @@ async function runScan(ctx) {
4685
5098
  );
4686
5099
  }
4687
5100
  if (coverage?.changed?.nothingToCheck) {
4688
- logger.info("Nothing to check: git reports no changed files. Run `shipguard scan` to check the whole tree.");
5101
+ logger.warn("Nothing to check: git reports no changed files, so nothing was scanned (verdict: not safe, scan incomplete). Run `shipguard scan` to check the whole tree.");
4689
5102
  } else if (coverage && coverage.scanned === 0) {
4690
5103
  logger.warn(
4691
5104
  `Nothing was scanned (0 of ${coverage.discovered} candidate file(s) could be read). A scan that read nothing is DO_NOT_SHIP, never safe.`
@@ -4729,6 +5142,7 @@ async function runScan(ctx) {
4729
5142
  scanOptions.strict,
4730
5143
  reportPaths
4731
5144
  ));
5145
+ if (showExitNotice) console.log(EXIT_NOTICE);
4732
5146
  }
4733
5147
  let telemetryDone = void 0;
4734
5148
  try {
@@ -4738,26 +5152,15 @@ async function runScan(ctx) {
4738
5152
  {
4739
5153
  cliVersion: CLI_VERSION2,
4740
5154
  verdict: verdictBucket,
4741
- durationMs: elapsedMs
5155
+ durationMs: elapsedMs,
5156
+ output: outputKind(opts)
4742
5157
  },
4743
5158
  { policy, projectDir: cwd }
4744
5159
  );
4745
5160
  } catch (err) {
4746
5161
  logger.debug(`telemetry: skipped (ignored): ${err instanceof Error ? err.message : String(err)}`);
4747
5162
  }
4748
- let exitCode = resolveExitCode({
4749
- strict: scanOptions.strict,
4750
- blockingCount: result.riskScore.blockingCount,
4751
- // the hard stop must not inherit the false-safe on an
4752
- // unfinished scan. Uses the FINAL degraded value (post pro-fetch OR-merge).
4753
- degraded: result.degraded === true,
4754
- // CLI-2/J-3 — the hard stop must not disagree with the printed verdict:
4755
- // a scan can print DO_NOT_SHIP with blockingCount 0 (active non-blocking findings,
4756
- // degradation). effectiveRecommendation
4757
- // reads the SAME field the human panel / --json `recommendation` print.
4758
- recommendation: effectiveRecommendation(result)
4759
- });
4760
- if (exitCode === EXIT_CODES.BLOCKED && !machineOutput && !quiet) {
5163
+ if (strictBlocked && !machineOutput && !quiet) {
4761
5164
  if (result.degraded === true) {
4762
5165
  logger.warn(
4763
5166
  `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.`
@@ -4770,11 +5173,8 @@ async function runScan(ctx) {
4770
5173
  );
4771
5174
  }
4772
5175
  }
4773
- if (opts.checkRegressions && exitCode === EXIT_CODES.SAFE && (result.regressions?.length ?? 0) > 0) {
4774
- exitCode = EXIT_CODES.BLOCKED;
4775
- if (!machineOutput && !quiet) {
4776
- logger.warn(`--check-regressions: ${result.regressions?.length} previously-passing rule(s) now fail \u2014 exiting with code 1`);
4777
- }
5176
+ if (regressionBlocks && !machineOutput && !quiet) {
5177
+ logger.warn(`--check-regressions: ${result.regressions?.length} previously-passing rule(s) now fail \u2014 exiting with code 1`);
4778
5178
  }
4779
5179
  await telemetryDone;
4780
5180
  if (exitCode !== EXIT_CODES.SAFE) {
@@ -4944,7 +5344,7 @@ function statusCommand() {
4944
5344
  // src/commands/history.ts
4945
5345
  import { Command as Command6 } from "commander";
4946
5346
  import { resolve as resolve5 } from "path";
4947
- var CLI_VERSION3 = true ? "0.11.0" : process.env.npm_package_version ?? "0.0.0-dev";
5347
+ var CLI_VERSION3 = true ? "0.12.0" : process.env.npm_package_version ?? "0.0.0-dev";
4948
5348
  function historyCommand() {
4949
5349
  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) => {
4950
5350
  const cwd = scanPath ? resolve5(scanPath) : process.cwd();
@@ -5018,18 +5418,18 @@ var HOOK_BLOCK_VERSION = 1;
5018
5418
  var HOOK_MARKER_START = "# >>> shipguard managed block >>>";
5019
5419
  var HOOK_MARKER_END = "# <<< shipguard managed block <<<";
5020
5420
  var GATE_COMMAND = "shipguard scan --json --strict";
5421
+ var NPX_SPEC = "@agenticcli/shipguard@0";
5422
+ var LOCAL_BIN = "./node_modules/.bin/shipguard";
5423
+ function resolverShell(exitCode) {
5424
+ return [
5425
+ `_sg_run() { if [ -x ${LOCAL_BIN} ]; then ${LOCAL_BIN} "$@"; elif command -v shipguard >/dev/null 2>&1; then shipguard "$@"; else npx --yes ${NPX_SPEC} "$@"; fi; }`,
5426
+ `if ! { [ -x ${LOCAL_BIN} ] || command -v shipguard >/dev/null 2>&1 || { command -v npx >/dev/null 2>&1 && npx --yes ${NPX_SPEC} --version >/dev/null 2>&1; }; }; then echo "ShipGuard could not start, so the release gate did NOT run and nothing was scanned." >&2; echo " Fix: npm i -D @agenticcli/shipguard (or: npm i -g @agenticcli/shipguard)." >&2; echo " Without a local install, npx needs network access to fetch ${NPX_SPEC}." >&2; exit ${exitCode}; fi`
5427
+ ];
5428
+ }
5021
5429
  function gateShellBody(indent = "") {
5022
5430
  const l = (s) => `${indent}${s}`;
5023
5431
  return [
5024
- l("if command -v shipguard >/dev/null 2>&1; then"),
5025
- l(' _sg_run() { shipguard "$@"; }'),
5026
- l("elif command -v npx >/dev/null 2>&1; then"),
5027
- l(' _sg_run() { npx --no-install shipguard "$@"; }'),
5028
- l("else"),
5029
- l(' echo "ShipGuard: not installed, so the release gate did not run \u2014 refusing to pass." >&2'),
5030
- l(' echo " Install it: npm i -g @agenticcli/shipguard" >&2'),
5031
- l(" exit 1"),
5032
- l("fi"),
5432
+ ...resolverShell(1).map(l),
5033
5433
  l("_sg_out=$(_sg_run scan --json --strict 2>&1) || {"),
5034
5434
  l(' echo "ShipGuard blocked this: the release gate did not pass." >&2'),
5035
5435
  l(' printf "%s\\n" "$_sg_out" >&2'),
@@ -5055,8 +5455,8 @@ function gitHookBlock(hookName) {
5055
5455
  ].join("\n");
5056
5456
  }
5057
5457
  var GIT_HOOK_NAMES = ["pre-push", "pre-merge-commit"];
5058
- 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'`;
5059
- var CLAUDE_HOOK_FINGERPRINT = "shipguard scan --json --strict";
5458
+ var CLAUDE_HOOK_COMMAND = `sh -c '_sg_in=$(cat); case "$_sg_in" in *"git merge"*|*"git push"*) ${resolverShell(2).join("; ")}; _sg_out=$(_sg_run scan --json --strict 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'`;
5459
+ var CLAUDE_HOOK_FINGERPRINT = " scan --json --strict";
5060
5460
  function ciWorkflowYaml() {
5061
5461
  return `# ${HOOK_MARKER_START.replace("# ", "")} v${HOOK_BLOCK_VERSION} (github-actions)
5062
5462
  # Installed by \`shipguard hook --target ci\`. Re-run that command to update this file.
@@ -5266,7 +5666,7 @@ Exit codes:
5266
5666
 
5267
5667
  // src/commands/schema.ts
5268
5668
  import { Command as Command8 } from "commander";
5269
- var CLI_VERSION4 = true ? "0.11.0" : process.env.npm_package_version ?? "0.0.0-dev";
5669
+ var CLI_VERSION4 = true ? "0.12.0" : process.env.npm_package_version ?? "0.0.0-dev";
5270
5670
  var CURRENT_SCHEMA_VERSION2 = "6";
5271
5671
  function buildSchemaContract(limits) {
5272
5672
  const src = (value, fallback) => value === fallback ? "default" : "policy";
@@ -5282,6 +5682,16 @@ function buildSchemaContract(limits) {
5282
5682
  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.",
5283
5683
  deprecatedMirrors: ["riskScore.recommendation"]
5284
5684
  },
5685
+ configError: {
5686
+ shape: '{ "error": string, "code": string }',
5687
+ when: "exit code 2 with --json or --sarif: stdout is exactly this one JSON object (also for --sarif, instead of a SARIF document); the same message is on stderr",
5688
+ codes: [
5689
+ { code: "INVALID_POLICY", meaning: "shipguard.policy.yml could not be parsed" },
5690
+ { code: "NOT_A_PROJECT", meaning: "the directory is not a project root; pass a path or --all" },
5691
+ { code: "PATH_NOT_FOUND", meaning: "the scan path does not exist or cannot be read" },
5692
+ { code: "PATH_NOT_A_DIRECTORY", meaning: "the scan path is a file, not a directory" }
5693
+ ]
5694
+ },
5285
5695
  exitCodes: [
5286
5696
  {
5287
5697
  code: EXIT_CODES.SAFE,
@@ -5314,7 +5724,7 @@ function buildSchemaContract(limits) {
5314
5724
  { code: "COMPILE_FAILURE", meaning: "A Pro rule bundle failed to compile; the whole bundle was refused rather than partly run." },
5315
5725
  { code: "SYMLINK_SKIPPED", meaning: "One or more symlinks were not followed (privacy) and were not scanned." },
5316
5726
  { code: "UNSCANNED_UNKNOWN_BINARY", meaning: "One or more files hold NUL or control data that no text reading explains and show no sign of a known binary format; they were not scanned. Add their paths to ignore.paths if they are safe." },
5317
- { code: "NO_FILES_SCANNED", meaning: "Zero files were scanned (empty tree, everything ignored or binary, or --changed where every changed file was ignored or unreadable). A scan that read nothing is never SAFE_TO_SHIP. Exception: --changed when git reports no changed files is not degraded; it sets coverage.changed.nothingToCheck: true." }
5727
+ { code: "NO_FILES_SCANNED", meaning: "Zero files were scanned (empty tree, everything ignored or binary, or --changed where every changed file was ignored or unreadable). A scan that read nothing is never SAFE_TO_SHIP. --changed when git reports no changed files is the same code and also sets coverage.changed.nothingToCheck: true (nothing was scanned: not safe, --strict exits 1)." }
5318
5728
  ],
5319
5729
  limits: {
5320
5730
  maxFiles: {
@@ -5447,6 +5857,9 @@ function renderSchemaHuman(c) {
5447
5857
  lines.push("Exit codes:");
5448
5858
  for (const e of c.exitCodes) lines.push(` ${e.code} ${e.name} \u2014 ${e.meaning}`);
5449
5859
  lines.push("");
5860
+ lines.push(`Config errors (exit 2) with --json/--sarif: stdout is ${c.configError.shape}`);
5861
+ for (const e of c.configError.codes) lines.push(` ${e.code} \u2014 ${e.meaning}`);
5862
+ lines.push("");
5450
5863
  lines.push("Limits:");
5451
5864
  for (const [name, entry] of Object.entries(c.limits)) {
5452
5865
  if (name === "unanalyzableTypes" || name === "verificationStatus") continue;
@@ -5647,8 +6060,14 @@ if (rawArgs[0] === "?") {
5647
6060
  process.argv = [process.argv[0], process.argv[1], "help"];
5648
6061
  }
5649
6062
  program.name("shipguard").description("CLI-first release gate for AI-built apps").version(
5650
- true ? "0.11.0" : process.env.npm_package_version ?? "0.0.0-dev"
6063
+ true ? "0.12.0" : process.env.npm_package_version ?? "0.0.0-dev"
5651
6064
  ).helpCommand(false).addHelpText("after", `
6065
+ Exit codes:
6066
+ 0 scan completed (not "safe": read the verdict; the JSON \`recommendation\` field has it)
6067
+ 1 blocked only with --strict (a blocking finding, an unfinished scan, or DO_NOT_SHIP)
6068
+ 2 config error (bad flags, bad policy file, not a project folder)
6069
+ 3 runtime error (the scan could not run, or --pro could not fetch its rules)
6070
+
5652
6071
  Learn more:
5653
6072
  Docs ${goLink("docs")}
5654
6073
  Site ${goLink("site")}