@agenticcli/shipguard 0.10.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-6XMYOF3N.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,13 +54,13 @@ import {
51
54
  isShipguardArtifactPath,
52
55
  readCandidate,
53
56
  readFiles
54
- } from "./chunk-E4Z2MZ5J.js";
57
+ } from "./chunk-IPNOC7JF.js";
55
58
  import {
56
59
  logger
57
60
  } from "./chunk-NC5RELTG.js";
58
61
  import {
59
62
  decodeUtf8Strict
60
- } from "./chunk-KGIK7XNK.js";
63
+ } from "./chunk-RVDTQ2FR.js";
61
64
 
62
65
  // src/cli.ts
63
66
  import { Command as Command11, CommanderError } from "commander";
@@ -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) {
@@ -2080,6 +2415,7 @@ async function scan(options, proRules, onProgress) {
2080
2415
  };
2081
2416
  let state;
2082
2417
  let mode = "full";
2418
+ let nothingToCheck = false;
2083
2419
  let changedInfo;
2084
2420
  if (options.changedOnly && isGitRepo(cwd)) {
2085
2421
  mode = "changed";
@@ -2089,7 +2425,9 @@ async function scan(options, proRules, onProgress) {
2089
2425
  changedInfo = { listed, outsideScope: changed.outsideScope };
2090
2426
  const defaultCounts = /* @__PURE__ */ new Map();
2091
2427
  const candidates = [];
2428
+ let ownFilesOnly = true;
2092
2429
  for (const rp of changed.paths) {
2430
+ if (!isShipguardArtifactPath(rp)) ownFilesOnly = false;
2093
2431
  const rule = classifyIgnored(rp, ignoreRules);
2094
2432
  if (!rule && isShipguardArtifactPath(rp)) {
2095
2433
  state.selfArtifacts++;
@@ -2110,12 +2448,12 @@ async function scan(options, proRules, onProgress) {
2110
2448
  state.unreadableFiles.push(display);
2111
2449
  }
2112
2450
  state.discovered = candidates.length + changed.unaddressable.length + (changed.unreadable ?? []).length;
2113
- if (listed === 0) {
2114
- logger.info("--changed: git ran successfully - 0 changed files to scan.");
2115
- }
2116
- if (candidates.length === 0 && !options.json) {
2451
+ if (ownFilesOnly && changed.outsideScope === 0 && changed.unaddressable.length === 0 && (changed.unreadable ?? []).length === 0) {
2452
+ nothingToCheck = true;
2453
+ changedInfo.nothingToCheck = true;
2454
+ } else if (candidates.length === 0 && !options.json) {
2117
2455
  logger.warn(
2118
- "`--changed` scans only files that differ from git; on a clean checkout it scans nothing. Run `shipguard scan` for the whole tree."
2456
+ "`--changed` scans only files that differ from git; every changed file was ignored or could not be read. Run `shipguard scan` for the whole tree."
2119
2457
  );
2120
2458
  }
2121
2459
  const canonicalCwd = await realpath(cwd).catch(() => cwd);
@@ -2175,6 +2513,7 @@ async function scan(options, proRules, onProgress) {
2175
2513
  ignoreRules
2176
2514
  });
2177
2515
  }
2516
+ assertCwdAlive();
2178
2517
  const files = state.files;
2179
2518
  const skippedTooLarge = state.skippedTooLarge;
2180
2519
  const skippedTooLargeFiles = state.skippedTooLargeFiles;
@@ -2236,6 +2575,8 @@ async function scan(options, proRules, onProgress) {
2236
2575
  );
2237
2576
  }
2238
2577
  allFindings = collapsed.findings;
2578
+ fillMissingLines(allFindings, files);
2579
+ lowerFakeKeyConfidence(allFindings);
2239
2580
  redactFindingsEvidence(allFindings, sourceRedacted);
2240
2581
  const riskScore = computeRiskScore(allFindings);
2241
2582
  const treeDigest = computeTreeDigest(files);
@@ -2309,7 +2650,7 @@ async function scan(options, proRules, onProgress) {
2309
2650
  add(state.notReached, "not reached");
2310
2651
  degradedReasons.push({
2311
2652
  code: "NO_FILES_SCANNED",
2312
- 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.`
2313
2654
  });
2314
2655
  }
2315
2656
  const isDegraded = degradedReasons.length > 0 || void 0;
@@ -2469,7 +2810,7 @@ function quickstartHelp(isTTY) {
2469
2810
  lines.push(` ${chalk.cyan("hook")} ${chalk.dim("--target")} Install the gate at the merge boundary`);
2470
2811
  lines.push(` ${chalk.cyan("schema")} ${chalk.dim("--json")} Print the machine-readable scan contract`);
2471
2812
  lines.push(` ${chalk.cyan("feedback")} Where to send feedback (GitHub issues)`);
2472
- 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`);
2473
2814
  lines.push(` ${chalk.cyan("telemetry")} ${chalk.dim("status")} Show or change the pseudonymous usage ping`);
2474
2815
  lines.push(` ${chalk.cyan("help")} ${chalk.dim("/ ?")} Show this screen`);
2475
2816
  lines.push("");
@@ -2503,7 +2844,7 @@ function quickstartHelp(isTTY) {
2503
2844
  lines.push(" hook --target Install the gate at the merge boundary");
2504
2845
  lines.push(" schema --json Machine-readable scan contract");
2505
2846
  lines.push(" feedback Where to send feedback (GitHub issues)");
2506
- lines.push(" rate <id> up|down Rate a finding");
2847
+ lines.push(" rate <n> helpful|not-helpful Rate finding number n");
2507
2848
  lines.push(" telemetry status|enable|disable|reset Pseudonymous usage ping");
2508
2849
  lines.push(" help / ? Show this screen");
2509
2850
  lines.push("");
@@ -2548,6 +2889,12 @@ var SEVERITY_COLORS = {
2548
2889
  low: chalk.blue,
2549
2890
  info: chalk.gray
2550
2891
  };
2892
+ function renderNothingToCheck() {
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.");
2897
+ }
2551
2898
  function renderFindingsSummary(findings) {
2552
2899
  if (findings.length === 0) {
2553
2900
  return chalk.green(" \u2713 No findings detected \u2014 clean scan.");
@@ -2763,12 +3110,12 @@ function actionFooter(opts) {
2763
3110
  const lines = [""];
2764
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"));
2765
3112
  lines.push("");
2766
- 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")}`);
2767
3114
  if (hasFindings && topRuleId) {
2768
- lines.push(` ${chalk.cyan(`shipguard rate ${topRuleId} up`)} ${chalk.dim("# was this finding helpful?")}`);
2769
- 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?")}`);
2770
3117
  } else if (hasFindings) {
2771
- 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)")}`);
2772
3119
  }
2773
3120
  lines.push(` ${chalk.cyan('shipguard feedback "<thoughts>"')} ${chalk.dim("# what do you think?")}`);
2774
3121
  if (!isLoggedIn) {
@@ -2831,7 +3178,7 @@ function quietVerdict(result, strict) {
2831
3178
  const degraded = result.degraded === true;
2832
3179
  const icon = recommendation === "SAFE_TO_SHIP" ? "\u2705" : recommendation === "DO_NOT_SHIP" ? "\u26D4" : "\u26A0\uFE0F";
2833
3180
  const colorFn = recommendation === "SAFE_TO_SHIP" ? chalk.green : recommendation === "DO_NOT_SHIP" ? chalk.red : chalk.yellow;
2834
- const degradedNote = degraded ? " incomplete=yes" : "";
3181
+ const degradedNote = (degraded ? " incomplete=yes" : "") + (result.coverage?.scanned === 0 ? " nothing-scanned=yes" : "");
2835
3182
  const suffix = blockingCount > 0 && !strict ? " (informational \u2014 exit 0; use --strict to enforce)" : "";
2836
3183
  return colorFn(`${icon} ${recommendation.replace(/_/g, " ")} score=${score}/100 findings=${totalFindings} blocking=${blockingCount}${degradedNote}${suffix}`);
2837
3184
  }
@@ -3105,6 +3452,7 @@ function resolveRepoIdentity(cwd) {
3105
3452
  }
3106
3453
  }
3107
3454
  const id = randomUUID();
3455
+ assertCwdAlive();
3108
3456
  mkdirSync(dirname(fallbackPath), { recursive: true });
3109
3457
  writeFileSync2(fallbackPath, `${id}
3110
3458
  `, "utf-8");
@@ -3203,6 +3551,7 @@ var HistoryStore = class _HistoryStore {
3203
3551
  }
3204
3552
  const preExisted = existsSync5(dbPath);
3205
3553
  try {
3554
+ assertCwdAlive();
3206
3555
  mkdirSync2(dirname2(dbPath), { recursive: true });
3207
3556
  } catch (err) {
3208
3557
  return {
@@ -3908,7 +4257,7 @@ var IS_PUBLISHED_BUILD = true;
3908
4257
  function getProvenance(published = IS_PUBLISHED_BUILD) {
3909
4258
  return published ? "published" : "dev";
3910
4259
  }
3911
- var PROD_TELEMETRY_ENDPOINT = "https://cheery-toucan-348.convex.site/cli-telemetry";
4260
+ var PROD_TELEMETRY_ENDPOINT = "https://agenticcli.dev/api/cli-telemetry";
3912
4261
  function isLoopbackUrl(raw2) {
3913
4262
  if (!raw2) return false;
3914
4263
  try {
@@ -3928,6 +4277,21 @@ function resolveTraffic(env, published) {
3928
4277
  if (v === "test" || v === "internal") return v;
3929
4278
  return published ? void 0 : "test";
3930
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
+ }
3931
4295
  var ALLOWED_KEYS = [
3932
4296
  "schema",
3933
4297
  "eventId",
@@ -3936,7 +4300,10 @@ var ALLOWED_KEYS = [
3936
4300
  "provenance",
3937
4301
  "verdict",
3938
4302
  "durationBucket",
3939
- "ci"
4303
+ "ci",
4304
+ "agent",
4305
+ "interactive",
4306
+ "output"
3940
4307
  ];
3941
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})?$/;
3942
4309
  var DURATION_BUCKETS = ["lt1s", "1to5s", "5to30s", "gt30s"];
@@ -3982,8 +4349,8 @@ function envOptOut(env) {
3982
4349
  return null;
3983
4350
  }
3984
4351
  function buildPayload(input) {
3985
- const { schema, eventId, installId, cliVersion, provenance, verdict, durationBucket: durationBucket2, ci, traffic } = input;
3986
- 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 };
3987
4354
  if (traffic === "test" || traffic === "internal") out.traffic = traffic;
3988
4355
  return out;
3989
4356
  }
@@ -3997,7 +4364,7 @@ function validatePayload(payload) {
3997
4364
  const keys = Object.keys(obj);
3998
4365
  if (!isTrafficOk(obj, keys.length, ALLOWED_KEYS.length)) return false;
3999
4366
  for (const k of ALLOWED_KEYS) if (!(k in obj)) return false;
4000
- if (obj.schema !== 2) return false;
4367
+ if (obj.schema !== 4) return false;
4001
4368
  if (typeof obj.eventId !== "string" || !UUID_V4.test(obj.eventId)) return false;
4002
4369
  if (typeof obj.ci !== "boolean") return false;
4003
4370
  if (obj.ci) {
@@ -4009,6 +4376,9 @@ function validatePayload(payload) {
4009
4376
  if (obj.provenance !== "published" && obj.provenance !== "dev") return false;
4010
4377
  if (!["safe", "review", "blocked", "error"].includes(obj.verdict)) return false;
4011
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;
4012
4382
  return true;
4013
4383
  }
4014
4384
  function decideTelemetry(input = {}) {
@@ -4022,7 +4392,15 @@ function decideTelemetry(input = {}) {
4022
4392
  if (projectTelemetryEnabled({ policy: input.policy, projectDir: input.projectDir }) === false) return { enabled: false, source: "project-policy" };
4023
4393
  return { enabled: true, source: "default" };
4024
4394
  }
4025
- 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
+ }
4026
4404
  var PING_WAIT_MS = 1500;
4027
4405
  var FETCH_TIMEOUT_MS = 1e3;
4028
4406
  function debugEnabled(env) {
@@ -4044,13 +4422,16 @@ function sendTelemetry(input, opts = {}) {
4044
4422
  const endpoint = resolveEndpoint(published, env);
4045
4423
  const ci = detectCi(env);
4046
4424
  const base = {
4047
- schema: 2,
4425
+ schema: 4,
4048
4426
  eventId: randomUUID5(),
4049
4427
  cliVersion: input.cliVersion,
4050
4428
  provenance: getProvenance(published),
4051
4429
  verdict: input.verdict,
4052
4430
  durationBucket: durationBucket(input.durationMs),
4053
4431
  ci,
4432
+ agent: detectAgent(env),
4433
+ interactive: opts.interactive ?? Boolean(process.stdout.isTTY),
4434
+ output: input.output,
4054
4435
  traffic: resolveTraffic(env, published)
4055
4436
  };
4056
4437
  if (debug) {
@@ -4111,7 +4492,7 @@ function postBounded(endpoint, body) {
4111
4492
  });
4112
4493
  });
4113
4494
  }
4114
- var CLI_VERSION = true ? "0.10.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";
4115
4496
  var LIFECYCLE_KEYS = ["schema", "event", "eventId", "installId", "cliVersion", "provenance", "ci"];
4116
4497
  function validateLifecyclePayload(payload) {
4117
4498
  if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return false;
@@ -4232,7 +4613,7 @@ function exitWhenDrained() {
4232
4613
 
4233
4614
  // src/commands/scan.ts
4234
4615
  var LEARN_MORE = `Docs ${goLink("docs")} \xB7 Site ${goLink("site")} \xB7 Pricing ${goLink("pricing")} \xB7 Issues https://github.com/agenticcli/shipguard/issues`;
4235
- var CLI_VERSION2 = true ? "0.10.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";
4236
4617
  function resolveExitCode(opts) {
4237
4618
  if (opts.strict && (opts.blockingCount > 0 || opts.degraded === true || opts.recommendation === "DO_NOT_SHIP")) {
4238
4619
  return EXIT_CODES.BLOCKED;
@@ -4266,6 +4647,15 @@ function platformUnavailableMessage(retryAfterSeconds) {
4266
4647
  const wait = retryAfterSeconds !== void 0 ? ` (suggested wait: ${formatSuggestedWait(retryAfterSeconds)})` : "";
4267
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.`;
4268
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
+ }
4269
4659
  function isProjectRoot(dir) {
4270
4660
  return existsSync7(join7(dir, "package.json")) || existsSync7(join7(dir, ".git"));
4271
4661
  }
@@ -4336,18 +4726,19 @@ ${LEARN_MORE}`).action(async (scanPath, opts) => {
4336
4726
  if (machineOutput) {
4337
4727
  console.log(JSON.stringify({ error: pathProblem.message, code: pathProblem.code }));
4338
4728
  }
4339
- return exitWithError(EXIT_CODES.CONFIG_ERROR, startTime, process.cwd());
4729
+ return exitWithError(EXIT_CODES.CONFIG_ERROR, startTime, process.cwd(), outputKind(opts));
4340
4730
  }
4341
4731
  }
4342
4732
  if (!scanPath && !opts.all && !isProjectRoot(cwd)) {
4343
- logger.error(
4344
- `Refusing to scan a non-project directory ${cwd}. Pass a path (\`shipguard scan ./my-app\`) or \`--all\` to override.`
4345
- );
4346
- 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 {
4347
4738
  console.log(`
4348
4739
  ${LEARN_MORE}`);
4349
4740
  }
4350
- return exitWithError(EXIT_CODES.CONFIG_ERROR, startTime, process.cwd());
4741
+ return exitWithError(EXIT_CODES.CONFIG_ERROR, startTime, process.cwd(), outputKind(opts));
4351
4742
  }
4352
4743
  const originalCwd = process.cwd();
4353
4744
  if (scanPath) {
@@ -4362,10 +4753,13 @@ ${LEARN_MORE}`);
4362
4753
  }
4363
4754
  });
4364
4755
  }
4365
- 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) {
4366
4760
  try {
4367
4761
  await sendTelemetry(
4368
- { cliVersion: CLI_VERSION2, verdict: "error", durationMs: Date.now() - startTime },
4762
+ { cliVersion: CLI_VERSION2, verdict: "error", durationMs: Date.now() - startTime, output },
4369
4763
  { policy, projectDir }
4370
4764
  );
4371
4765
  } catch (err) {
@@ -4392,8 +4786,12 @@ async function runScan(ctx) {
4392
4786
  try {
4393
4787
  policy = await loadPolicy(cwd);
4394
4788
  } catch (error) {
4395
- logger.error(`Config error: ${error instanceof Error ? error.message : error}`);
4396
- 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));
4397
4795
  }
4398
4796
  const changedOnly = Boolean(opts.changed);
4399
4797
  const categories = opts.category ? opts.category.split(",").map((c) => c.trim()) : [];
@@ -4443,8 +4841,8 @@ async function runScan(ctx) {
4443
4841
  logger.info("Detecting stack...");
4444
4842
  }
4445
4843
  try {
4446
- const { fetchProRules } = await import("./pro-scanner-TPNDJ6L6.js");
4447
- const { hasConfig, generateConfig } = await import("./config-generator-S5KFHKGQ.js");
4844
+ const { fetchProRules } = await import("./pro-scanner-NSDJLVII.js");
4845
+ const { hasConfig, generateConfig } = await import("./config-generator-BNFR3LZR.js");
4448
4846
  const frameworks = detectedFrameworks;
4449
4847
  if (!hasConfig(cwd)) {
4450
4848
  const configPath = generateConfig(cwd, frameworks);
@@ -4486,7 +4884,7 @@ async function runScan(ctx) {
4486
4884
  } else {
4487
4885
  console.log(JSON.stringify({ error: errMsg, code: "NO_RULES_APPLIED" }));
4488
4886
  }
4489
- return exitWithError(EXIT_CODES.RUNTIME_ERROR, startTime, cwd, policy);
4887
+ return exitWithError(EXIT_CODES.RUNTIME_ERROR, startTime, cwd, outputKind(opts), policy);
4490
4888
  }
4491
4889
  const rawErrCode = err?.code;
4492
4890
  const KNOWN_PRO_FETCH_ERROR_CODES = [
@@ -4525,7 +4923,7 @@ async function runScan(ctx) {
4525
4923
  ...retryAfterSeconds !== void 0 ? { retryAfterSeconds } : {}
4526
4924
  }));
4527
4925
  }
4528
- return exitWithError(EXIT_CODES.RUNTIME_ERROR, startTime, cwd, policy);
4926
+ return exitWithError(EXIT_CODES.RUNTIME_ERROR, startTime, cwd, outputKind(opts), policy);
4529
4927
  }
4530
4928
  }
4531
4929
  }
@@ -4557,7 +4955,7 @@ async function runScan(ctx) {
4557
4955
  } else {
4558
4956
  console.log(JSON.stringify({ error: String(error) }));
4559
4957
  }
4560
- return exitWithError(EXIT_CODES.RUNTIME_ERROR, startTime, cwd, policy);
4958
+ return exitWithError(EXIT_CODES.RUNTIME_ERROR, startTime, cwd, outputKind(opts), policy);
4561
4959
  }
4562
4960
  if (showProgress) {
4563
4961
  process.stderr.write("\r\x1B[K");
@@ -4616,6 +5014,7 @@ async function runScan(ctx) {
4616
5014
  result.coverageChanged = historyOutcome.coverageChanged;
4617
5015
  }
4618
5016
  const publicResult = { ...result };
5017
+ publicResult.telemetry = telemetryState({ policy, projectDir: cwd });
4619
5018
  const shouldReport = scanOptions.generateReport || policy.scan.generate_report;
4620
5019
  let reportPaths;
4621
5020
  if (shouldReport) {
@@ -4626,6 +5025,24 @@ async function runScan(ctx) {
4626
5025
  logger.error(`Report generation failed: ${error instanceof Error ? error.message : error}`);
4627
5026
  }
4628
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 });
4629
5046
  if (opts.sarif) {
4630
5047
  console.log(JSON.stringify(toSarif(publicResult), null, 2));
4631
5048
  } else if (scanOptions.json) {
@@ -4639,7 +5056,13 @@ async function runScan(ctx) {
4639
5056
  const banner = welcomeBanner();
4640
5057
  if (banner) console.log(banner);
4641
5058
  }
4642
- console.log(renderFindingsSummary(result.findings));
5059
+ if (result.coverage?.changed?.nothingToCheck) {
5060
+ console.log(renderNothingToCheck());
5061
+ } else if (coverage && coverage.scanned === 0) {
5062
+ console.log(renderNothingScanned());
5063
+ } else {
5064
+ console.log(renderFindingsSummary(result.findings));
5065
+ }
4643
5066
  if (result.findings.length > 0) {
4644
5067
  console.log(findingsByCategoryTable(result.findings));
4645
5068
  console.log("");
@@ -4674,7 +5097,9 @@ async function runScan(ctx) {
4674
5097
  `If these files are safe, add their paths to \`ignore.paths\` in shipguard.policy.yml. Verdict is degraded \u2014 see \`degradedReasons\` in --json output.`
4675
5098
  );
4676
5099
  }
4677
- if (coverage && coverage.scanned === 0) {
5100
+ if (coverage?.changed?.nothingToCheck) {
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.");
5102
+ } else if (coverage && coverage.scanned === 0) {
4678
5103
  logger.warn(
4679
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.`
4680
5105
  );
@@ -4717,6 +5142,7 @@ async function runScan(ctx) {
4717
5142
  scanOptions.strict,
4718
5143
  reportPaths
4719
5144
  ));
5145
+ if (showExitNotice) console.log(EXIT_NOTICE);
4720
5146
  }
4721
5147
  let telemetryDone = void 0;
4722
5148
  try {
@@ -4726,26 +5152,15 @@ async function runScan(ctx) {
4726
5152
  {
4727
5153
  cliVersion: CLI_VERSION2,
4728
5154
  verdict: verdictBucket,
4729
- durationMs: elapsedMs
5155
+ durationMs: elapsedMs,
5156
+ output: outputKind(opts)
4730
5157
  },
4731
5158
  { policy, projectDir: cwd }
4732
5159
  );
4733
5160
  } catch (err) {
4734
5161
  logger.debug(`telemetry: skipped (ignored): ${err instanceof Error ? err.message : String(err)}`);
4735
5162
  }
4736
- let exitCode = resolveExitCode({
4737
- strict: scanOptions.strict,
4738
- blockingCount: result.riskScore.blockingCount,
4739
- // the hard stop must not inherit the false-safe on an
4740
- // unfinished scan. Uses the FINAL degraded value (post pro-fetch OR-merge).
4741
- degraded: result.degraded === true,
4742
- // CLI-2/J-3 — the hard stop must not disagree with the printed verdict:
4743
- // a scan can print DO_NOT_SHIP with blockingCount 0 (active non-blocking findings,
4744
- // degradation). effectiveRecommendation
4745
- // reads the SAME field the human panel / --json `recommendation` print.
4746
- recommendation: effectiveRecommendation(result)
4747
- });
4748
- if (exitCode === EXIT_CODES.BLOCKED && !machineOutput && !quiet) {
5163
+ if (strictBlocked && !machineOutput && !quiet) {
4749
5164
  if (result.degraded === true) {
4750
5165
  logger.warn(
4751
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.`
@@ -4758,11 +5173,8 @@ async function runScan(ctx) {
4758
5173
  );
4759
5174
  }
4760
5175
  }
4761
- if (opts.checkRegressions && exitCode === EXIT_CODES.SAFE && (result.regressions?.length ?? 0) > 0) {
4762
- exitCode = EXIT_CODES.BLOCKED;
4763
- if (!machineOutput && !quiet) {
4764
- logger.warn(`--check-regressions: ${result.regressions?.length} previously-passing rule(s) now fail \u2014 exiting with code 1`);
4765
- }
5176
+ if (regressionBlocks && !machineOutput && !quiet) {
5177
+ logger.warn(`--check-regressions: ${result.regressions?.length} previously-passing rule(s) now fail \u2014 exiting with code 1`);
4766
5178
  }
4767
5179
  await telemetryDone;
4768
5180
  if (exitCode !== EXIT_CODES.SAFE) {
@@ -4821,6 +5233,7 @@ function openUrl(raw2, apiUrl, onError = () => {
4821
5233
 
4822
5234
  // src/commands/login.ts
4823
5235
  var DEFAULT_API_URL = "https://agenticcli.dev";
5236
+ var SIGN_IN_TIMED_OUT = "Sign-in timed out. Run `shipguard login` again.";
4824
5237
  function loginCommand() {
4825
5238
  return new Command3("login").description("Authenticate with ShipGuard for pro features").option("--api-url <url>", "API server URL", DEFAULT_API_URL).action(async (opts) => {
4826
5239
  const apiUrl = opts.apiUrl;
@@ -4872,10 +5285,14 @@ Visit: ${safeUrl.href}`);
4872
5285
  await new Promise((r) => setTimeout(r, 5e3));
4873
5286
  continue;
4874
5287
  }
5288
+ if (error === "expired_token") {
5289
+ logger.error(SIGN_IN_TIMED_OUT);
5290
+ process.exit(2);
5291
+ }
4875
5292
  logger.error(`Auth failed: ${error}`);
4876
5293
  process.exit(2);
4877
5294
  }
4878
- logger.error("Auth timed out");
5295
+ logger.error(SIGN_IN_TIMED_OUT);
4879
5296
  process.exit(2);
4880
5297
  });
4881
5298
  }
@@ -4927,7 +5344,7 @@ function statusCommand() {
4927
5344
  // src/commands/history.ts
4928
5345
  import { Command as Command6 } from "commander";
4929
5346
  import { resolve as resolve5 } from "path";
4930
- var CLI_VERSION3 = true ? "0.10.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";
4931
5348
  function historyCommand() {
4932
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) => {
4933
5350
  const cwd = scanPath ? resolve5(scanPath) : process.cwd();
@@ -5001,18 +5418,18 @@ var HOOK_BLOCK_VERSION = 1;
5001
5418
  var HOOK_MARKER_START = "# >>> shipguard managed block >>>";
5002
5419
  var HOOK_MARKER_END = "# <<< shipguard managed block <<<";
5003
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
+ }
5004
5429
  function gateShellBody(indent = "") {
5005
5430
  const l = (s) => `${indent}${s}`;
5006
5431
  return [
5007
- l("if command -v shipguard >/dev/null 2>&1; then"),
5008
- l(' _sg_run() { shipguard "$@"; }'),
5009
- l("elif command -v npx >/dev/null 2>&1; then"),
5010
- l(' _sg_run() { npx --no-install shipguard "$@"; }'),
5011
- l("else"),
5012
- l(' echo "ShipGuard: not installed, so the release gate did not run \u2014 refusing to pass." >&2'),
5013
- l(' echo " Install it: npm i -g @agenticcli/shipguard" >&2'),
5014
- l(" exit 1"),
5015
- l("fi"),
5432
+ ...resolverShell(1).map(l),
5016
5433
  l("_sg_out=$(_sg_run scan --json --strict 2>&1) || {"),
5017
5434
  l(' echo "ShipGuard blocked this: the release gate did not pass." >&2'),
5018
5435
  l(' printf "%s\\n" "$_sg_out" >&2'),
@@ -5038,8 +5455,8 @@ function gitHookBlock(hookName) {
5038
5455
  ].join("\n");
5039
5456
  }
5040
5457
  var GIT_HOOK_NAMES = ["pre-push", "pre-merge-commit"];
5041
- 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'`;
5042
- 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";
5043
5460
  function ciWorkflowYaml() {
5044
5461
  return `# ${HOOK_MARKER_START.replace("# ", "")} v${HOOK_BLOCK_VERSION} (github-actions)
5045
5462
  # Installed by \`shipguard hook --target ci\`. Re-run that command to update this file.
@@ -5249,7 +5666,7 @@ Exit codes:
5249
5666
 
5250
5667
  // src/commands/schema.ts
5251
5668
  import { Command as Command8 } from "commander";
5252
- var CLI_VERSION4 = true ? "0.10.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";
5253
5670
  var CURRENT_SCHEMA_VERSION2 = "6";
5254
5671
  function buildSchemaContract(limits) {
5255
5672
  const src = (value, fallback) => value === fallback ? "default" : "policy";
@@ -5265,6 +5682,16 @@ function buildSchemaContract(limits) {
5265
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.",
5266
5683
  deprecatedMirrors: ["riskScore.recommendation"]
5267
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
+ },
5268
5695
  exitCodes: [
5269
5696
  {
5270
5697
  code: EXIT_CODES.SAFE,
@@ -5297,7 +5724,7 @@ function buildSchemaContract(limits) {
5297
5724
  { code: "COMPILE_FAILURE", meaning: "A Pro rule bundle failed to compile; the whole bundle was refused rather than partly run." },
5298
5725
  { code: "SYMLINK_SKIPPED", meaning: "One or more symlinks were not followed (privacy) and were not scanned." },
5299
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." },
5300
- { code: "NO_FILES_SCANNED", meaning: "Zero files were scanned (empty tree, everything ignored or binary, or --changed on a clean checkout). A scan that read nothing is never SAFE_TO_SHIP." }
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)." }
5301
5728
  ],
5302
5729
  limits: {
5303
5730
  maxFiles: {
@@ -5430,6 +5857,9 @@ function renderSchemaHuman(c) {
5430
5857
  lines.push("Exit codes:");
5431
5858
  for (const e of c.exitCodes) lines.push(` ${e.code} ${e.name} \u2014 ${e.meaning}`);
5432
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("");
5433
5863
  lines.push("Limits:");
5434
5864
  for (const [name, entry] of Object.entries(c.limits)) {
5435
5865
  if (name === "unanalyzableTypes" || name === "verificationStatus") continue;
@@ -5630,8 +6060,14 @@ if (rawArgs[0] === "?") {
5630
6060
  process.argv = [process.argv[0], process.argv[1], "help"];
5631
6061
  }
5632
6062
  program.name("shipguard").description("CLI-first release gate for AI-built apps").version(
5633
- true ? "0.10.0" : process.env.npm_package_version ?? "0.0.0-dev"
6063
+ true ? "0.12.0" : process.env.npm_package_version ?? "0.0.0-dev"
5634
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
+
5635
6071
  Learn more:
5636
6072
  Docs ${goLink("docs")}
5637
6073
  Site ${goLink("site")}