Metadata-Version: 2.4
Name: vetgate
Version: 0.9.1
Summary: Fast local security and quality gate for LLM-written code: C#, Node.js/TypeScript, PHP, SQL migrations (PostgreSQL/T-SQL), config/env/Docker, dependencies, HTML/JSX. Explainable rules, post-edit and pre-commit hooks.
License: MIT License
        
        Copyright (c) 2026 vetgate contributors
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://github.com/stuckerbsas/vetgate
Project-URL: Issues, https://github.com/stuckerbsas/vetgate/issues
Keywords: security,sast,csharp,dotnet,nodejs,typescript,javascript,php,sql,postgresql,mssql,performance,accessibility,llm,code-review,claude-code
Classifier: Development Status :: 4 - Beta
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: C#
Classifier: Programming Language :: JavaScript
Classifier: Programming Language :: PHP
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Quality Assurance
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: tree-sitter>=0.23
Requires-Dist: tree-sitter-c-sharp>=0.23
Requires-Dist: tree-sitter-javascript>=0.23
Requires-Dist: tree-sitter-typescript>=0.23
Requires-Dist: tree-sitter-php>=0.23
Requires-Dist: tomli>=1.1; python_version < "3.11"
Dynamic: license-file

# vetgate

> **Beta.** Calibrated on a private ~2,800-file .NET codebase and on public repos (eShop, nopCommerce,
> Bitwarden server, Jellyfin, Ghost, cal.com, Payload, Vercel Commerce, Juice Shop). False-positive reports are very welcome.

A fast, local, low-noise security and quality gate for code written or changed by LLM coding agents.

| Stack | Files |
|---|---|
| C# / ASP.NET Core | `.cs`, Razor `.cshtml/.razor` |
| Node.js / TypeScript | `.js .mjs .cjs .jsx .ts .mts .cts .tsx` (Express, Fastify, Koa, Next.js, NestJS, React) |
| PHP | `.php .phtml`, Blade `{!! !!}` (plain PHP, Laravel, Symfony, WordPress) |
| SQL / DB migrations | `.sql` — T-SQL and PostgreSQL: missing RLS, excessive grants, plaintext sensitive columns, missing PKs/FK indexes ([docs/rules/db.md](docs/rules/db.md)) |
| Config / env / containers | secrets in `appsettings*.json`, `web.config`, `.env*`, `docker-compose*.yml`, `Dockerfile`, `application*.yml/.properties`, `local.settings.json`, `config/*.json`; Docker rules; env files not git-ignored ([docs/rules/config.md](docs/rules/config.md)) |
| Dependencies | NuGet, npm, Composer, PyPI manifests and lockfiles ([docs/rules/deps.md](docs/rules/deps.md)) |
| Markup | `.html .htm .vue .svelte` (plus markup in `.jsx/.tsx` and Razor) |

What it checks, in every language (same base set, see [docs/rules/baseline.md](docs/rules/baseline.md)):

- **Security:** injection (SQL, NoSQL, command, code, regex, XXE), path traversal, SSRF, open redirect, XSS,
  insecure deserialization, hardcoded secrets, weak crypto/random, disabled TLS/JWT validation, permissive CORS,
  insecure cookies, secrets in logs, stack traces returned to clients, endpoints without auth.
- **SQL / DB migrations** (`.sql`, T-SQL and PostgreSQL): tenant tables without row-level security, excessive
  grants, plaintext password / token columns, tables without a primary key, foreign keys without an index. The
  schema is built across all migrations. Details: [docs/rules/db.md](docs/rules/db.md)
- **Config, env and containers:** secrets in config / `.env` / compose / Dockerfiles, containers running as root,
  `curl | sh`, privileged containers, exposed DB ports, `.env` files git does not ignore.
  Details: [docs/rules/config.md](docs/rules/config.md)
- **Billing:** paid APIs (Google Maps/Places/Gemini, OpenAI, Anthropic...) called in loops or render effects
  without a rate limit, cache or cap.
- **Quality and practices:** functions over 80 lines, nesting over 4 levels, cyclomatic complexity over 15, files
  over 500 lines, self-recursion, empty catch, async without error handling, debug leftovers, duplicated / unused /
  catch-all helpers, markup hygiene (`IMG_NO_ALT`, `CLICK_NO_KEYBOARD`, `SCRIPT_NO_SRI`).
- **Performance** (`--focus performance`, report-only): N+1 queries/HTTP calls in loops, linear lookups in loops,
  nested loops over the same collection, loop-invariant work (C#, Node, PHP).
  Details: [docs/rules/performance.md](docs/rules/performance.md)
- **Dependencies** (NuGet, npm, Composer, PyPI manifests and lockfiles): `DEPENDENCY_UNPINNED` (low, offline,
  part of `security`) and, opt-in, `DEPENDENCY_VULNERABLE` via OSV.dev (`vetgate deps` / `--focus deps`).
  Details: [docs/rules/deps.md](docs/rules/deps.md)

- **Deterministic and explainable.** Every finding says where the data comes from (`source`), which control is
  missing (`guard`), where it lands (`sink`) and why that is exploitable (`reason`).
- **Fast.** Milliseconds per file, no server, no model download. `--diff` scans only what changed.
- **Low noise by design.** Intra-procedural taint with guard recognition. The default vetgate is calibrated to
  0 medium+ findings on a large real-world .NET codebase (~2,800 files).
- **Built for agents.** A post-edit hook feeds findings back to the coding agent after every edit, and the
  `compact` format uses one line per finding.

It is a pre-filter, not a full SAST: data is followed within one file (including its private helpers) but not
across files, and there is no business-logic or IDOR analysis. Use it to catch the
obvious things cheaply, and keep human or LLM review for what needs reasoning.

## Install

```bash
pip install vetgate      # Python 3.10+
```

Dependencies (from `pyproject.toml`): `tree-sitter` plus the `tree-sitter-c-sharp`, `tree-sitter-javascript`,
`tree-sitter-typescript` and `tree-sitter-php` grammars, used by the C#, Node.js / TypeScript and PHP packs
(Razor reuses the C# helpers), and `tomli` on Python 3.10 only. The SQL (`db`), config / env / Docker, markup and
deps checks use their own regex / hand-written parsers and the standard library (`json`, `tomllib`,
`urllib` for the opt-in OSV lookup); no other runtime dependency.

### npm launcher (not published yet)

`npm/` holds a dependency-free Node.js launcher (`npx vetgate`, `npm i -g vetgate`) that runs the Python engine
above; it still needs `pip install vetgate`. Resolution order, env vars and exit codes: [npm/README.md](npm/README.md).
Local test: `cd npm && node --test`, `node bin/vetgate.js --version`, `npm link` (undo: `npm unlink -g vetgate`),
`npm pack` then `npx ./vetgate-<version>.tgz`.
Before the first release: publish the same version to PyPI first, confirm the npm package name and account, and
add an npm publish workflow (with provenance).

## Use

```bash
vetgate src/                                   # security focus, blocks on medium+
vetgate src/ --focus all --format text         # security + debug + quality + practices + performance
vetgate deps .                                 # vulnerable dependencies via OSV.dev (the only network check)
vetgate . --diff                               # only files changed vs HEAD (+ untracked)
vetgate . --diff origin/main --format sarif > gate.sarif
git diff --name-only | vetgate --files-from -
```

| Option | Meaning |
|---|---|
| `--focus security,debug,quality,practices,performance,all` | which checks to run (default `security`) |
| `--focus deps` / `vetgate deps` | vulnerable dependencies via OSV.dev; never part of `all` or the hooks |
| `--offline` | deps: answer from the local OSV cache only |
| `--min-severity low/medium/high` | default `medium` for security only, `low` otherwise |
| `--format json/text/compact/sarif` | SARIF works with GitHub code scanning |
| `--disable RULE,...` | skip rules |
| `--include-tests` | also scan test projects (skipped by default) |
| `--include-dapper` | C#: also check dynamic Dapper SQL |
| `--no-fail` | always exit 0 |

Exit code: `0` clean, `1` findings at or above the threshold, `2` error.

Suppress one finding: `// vetgate-ignore: RULE -- reason` on the line or the line above.

## Configuration

Put a `.vetgate.toml` in the repository root (git top-level, or the scan root outside git). The CLI, the
PostToolUse hook and the pre-commit hook read it. CLI flags always override the file; `--disable` lists are
combined. Use `--config FILE` to read another file and `--no-config` to ignore it. Unknown keys print a
warning on stderr and are ignored. See [docs/vetgate.example.toml](docs/vetgate.example.toml).

```toml
focus = ["security", "quality"]
min_severity = "medium"
disable = ["DEBUG_CONSOLE_OUTPUT"]
exclude = ["legacy/**", "scripts/*.js"]   # globs relative to the repo root
include_tests = false

[thresholds]                    # defaults (vetgate/thresholds.py)
overlong_method_lines = 80      # OVERLONG_METHOD: line count only
overlong_file_lines = 500       # OVERLONG_FILE
max_nesting_depth = 4           # DEEP_NESTING
max_cyclomatic_complexity = 15  # HIGH_COMPLEXITY
grab_bag_max = 15               # HELPER_GRAB_BAG

[severity]            # per-rule override
ENDPOINT_NO_AUTH = "medium"
```

## Rules (Node.js / TypeScript, HTML)

**security**: `CMD_INJ`, `CODE_INJECTION`, `SQL_INJ`, `NOSQL_INJ`, `PATH_TRAVERSAL`, `SSRF`, `OPEN_REDIRECT`,
`XSS_RAW_HTML`, `PROTOTYPE_POLLUTION`, `HARDCODED_SECRET`, `WEAK_CRYPTO`, `INSECURE_RANDOM`, `LOG_SENSITIVE_DATA`,
`CORS_PERMISSIVE`, `JWT_VALIDATION_DISABLED`, `EXCEPTION_DETAILS_IN_RESPONSE`, `CERT_VALIDATION_DISABLED`,
`INSECURE_COOKIE`, `PAID_API_UNBOUNDED` (billing), `CLIENT_TRUSTED_PRICE`, `PAYMENT_WEBHOOK_UNVERIFIED`,
`COUPON_REUSE_RACE` (payments: [docs/rules/payments.md](docs/rules/payments.md))

**debug / quality / practices** (low): `DEBUG_CONSOLE_OUTPUT`, `SECURITY_BYPASS_TODO`, `EMPTY_CATCH_BLOCK`,
`SELF_RECURSION`, `OVERLONG_METHOD`, `OVERLONG_FILE`, `DEEP_NESTING`, `HIGH_COMPLEXITY`, `SYNC_IO_IN_HANDLER`,
`PROMISE_WITHOUT_CATCH`, `PROCESS_EXIT_IN_HANDLER`, `DEPRECATED_BUFFER_CTOR`, `ASYNC_PROMISE_EXECUTOR`

**markup** (HTML/Vue/Svelte/JSX/TSX/Razor): `IMG_NO_ALT`, `CLICK_NO_KEYBOARD` (practices, low), `SCRIPT_NO_SRI`
(runs with security; low, medium over `http://`)

Details: [docs/rules/nodejs.md](docs/rules/nodejs.md)

## Rules (PHP)

**security**: `SQL_INJ`, `CMD_INJ`, `CODE_INJECTION`, `PATH_TRAVERSAL`, `SSRF`, `OPEN_REDIRECT`, `XSS_RAW_HTML`,
`INSECURE_DESERIALIZATION`, `XXE`, `HARDCODED_SECRET`, `WEAK_CRYPTO`, `INSECURE_RANDOM`, `CERT_VALIDATION_DISABLED`,
`LOG_SENSITIVE_DATA`, `EXCEPTION_DETAILS_IN_RESPONSE`, `PAID_API_UNBOUNDED`, `CLIENT_TRUSTED_PRICE`,
`PAYMENT_WEBHOOK_UNVERIFIED`, `COUPON_REUSE_RACE`

**debug / quality** (low): `DEBUG_CONSOLE_OUTPUT`, `EMPTY_CATCH_BLOCK`, `SELF_RECURSION`, `OVERLONG_METHOD`, `OVERLONG_FILE`,
`DEEP_NESTING`, `HIGH_COMPLEXITY`

Details: [docs/rules/php.md](docs/rules/php.md)

## Rules (SQL schema, `db`)

**security**: `DB_RLS_MISSING` (medium when the schema uses RLS elsewhere, else one low per schema),
`DB_EXCESSIVE_GRANT`, `DB_PLAINTEXT_SENSITIVE_COLUMN`, `DB_COUPON_NO_UNIQUE` (low)

**practices / quality**: `DB_NO_PRIMARY_KEY`, `DB_FK_NO_INDEX` (low), `DB_NULLABLE_KEY_COLUMN` (low),
`DB_REPEATED_COLUMNS` (low), `DB_LIST_IN_COLUMN` (low)

The schema is aggregated across files, so a PK, index or policy added by a later migration counts.
Details: [docs/rules/db.md](docs/rules/db.md)

## Rules (C#)

**security** (default gate): `SQL_INJ`, `CMD_INJ`, `PATH_TRAVERSAL`, `INSECURE_DESERIALIZATION`,
`HARDCODED_SECRET`, `ENDPOINT_NO_AUTH`, `WEAK_CRYPTO`, `SSRF`, `OPEN_REDIRECT`, `XSS_RAW_HTML`, `XXE`,
`CERT_VALIDATION_DISABLED`, `JWT_VALIDATION_DISABLED`, `INSECURE_RANDOM`, `CORS_PERMISSIVE`, `LDAP_INJ`,
`XPATH_INJ`, `REGEX_INJECTION`, `INSECURE_COOKIE`, `LOG_SENSITIVE_DATA`, `JWT_HTTPS_METADATA_DISABLED`,
`EXCEPTION_DETAILS_IN_RESPONSE`, `PAID_API_UNBOUNDED`, `CLIENT_TRUSTED_PRICE`, `PAYMENT_WEBHOOK_UNVERIFIED`,
`COUPON_REUSE_RACE` ([payments](docs/rules/payments.md)); quality adds `SELF_RECURSION`
(`ENDPOINT_NO_AUTH` is reported as low: many apps expose public endpoints without `[AllowAnonymous]`.)

**debug** (low): `DEBUG_CONSOLE_OUTPUT`, `SECURITY_BYPASS_TODO`, `TEST_STUB_LEAK`
**quality** (low): `ASYNC_NO_TRY_CATCH` (entry points only), `EMPTY_CATCH_BLOCK`, `OVERLONG_METHOD` (80 lines),
`OVERLONG_FILE` (500 lines), `DEEP_NESTING` (4 levels), `HIGH_COMPLEXITY` (15), `SELF_RECURSION`
**practices** (low): `ASYNC_VOID`, `SYNC_OVER_ASYNC`, `THREAD_SLEEP_IN_ASYNC`, `LOG_INTERPOLATION`,
`HTTPCLIENT_PER_CALL`, `THROW_EX_RESETS_STACK`, `STRING_CONCAT_IN_LOOP`, `DISPOSABLE_NOT_DISPOSED`,
`COUNT_INSTEAD_OF_ANY`, `GC_COLLECT`, `FIRE_AND_FORGET_TASK`, `DEV_EXCEPTION_PAGE_UNGUARDED`, `SYNC_IO_IN_HANDLER`

**Razor views** (`.cshtml`, `.razor`): `XSS_RAW_HTML` for `Html.Raw` / `MarkupString`, plus `IMG_NO_ALT`,
`CLICK_NO_KEYBOARD`, `SCRIPT_NO_SRI`.
**Config files** (`appsettings*.json`, `web.config`, `app.config`) are covered by the language-agnostic config pack below.

Full reference (what is flagged, what is not, how to fix): [docs/rules/csharp.md](docs/rules/csharp.md)

## Rules (config, env and container files)

One engine for every stack (`appsettings*.json`, `web.config`, `*.config`, `.env*`, `docker-compose*.yml`,
`Dockerfile`, `application*.yml/.properties`, `local.settings.json`, `secrets.json`, `config/*.json|yml`):

**security**: `CONFIG_HARDCODED_SECRET` (high for known token formats / private keys, medium for literal
passwords / secrets / tokens, low for localhost dev defaults, publishable keys and git-ignored files),
`DOCKER_RUNS_AS_ROOT`, `DOCKER_CURL_PIPE_SH`, `DOCKER_PRIVILEGED`, `DOCKER_DB_PORT_EXPOSED` (medium),
`DOCKER_IMAGE_LATEST`, `DOCKER_ADD_REMOTE_URL` (low).
**Env / secret files in git** (CLI full scans; `--diff` / pre-commit check only the changed files):
`ENV_FILE_NOT_GITIGNORED` (a `.env`, `.env.local`, `local.settings.json`, `*.pfx`, `id_rsa`... that git does not
ignore or that is committed; high with secrets inside) and `ENV_GITIGNORE_GAP` (low: `.gitignore` ignores `.env`
but not `.env.local`). Values are never printed.

Full reference: [docs/rules/config.md](docs/rules/config.md)

## Baseline (only new findings)

For a repo with legacy findings, record them once and let the gate report only new ones:

```
vetgate . --focus all --write-baseline      # writes .vetgate-baseline.json at the git top-level
vetgate . --focus all                       # auto-uses the baseline; exit code counts new findings only
vetgate . --baseline other.json             # explicit file; --no-baseline ignores it
```

Fingerprints use the relative path, rule, the finding line with whitespace removed and an occurrence index, so
they survive line shifts. The file stores only sha256 hashes, never code. The PostToolUse and pre-commit hooks
also respect the baseline.

## Repo-level helper checks

A full scan with `--focus quality` (any language) also looks across files: `DUPLICATE_HELPER` (copy-pasted
function bodies), `UNUSED_HELPER` (helpers nothing calls), `HELPER_GRAB_BAG` (utils/helpers files with more
than 15 functions) and `REINVENTED_STDLIB` (hand-written `deepClone`, `IsNullOrEmpty`...). They are low and
never run in the hooks or with `--diff`. Every language implements the same base set:
[docs/rules/baseline.md](docs/rules/baseline.md).

## Example

```
$ vetgate Controllers/ToolsController.cs --format text
Controllers/ToolsController.cs:19: [HIGH] CMD_INJ (deterministic, 1.0)
    source: request parameter 'tool' ([FromQuery])
    guard : no allowlist / argument escaping before process start
    sink  : process execution (executable: tool)
    reason: Request-controlled text becomes part of the executable or its command line; ...
```

## GitHub Action

```yaml
jobs:
  vetgate:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      security-events: write
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - uses: stuckerbsas/vetgate@v0
```

On pull requests only changed files are scanned. Findings go to code scanning as SARIF, and the job fails on
medium+ unless `fail: false`. Inputs and a full workflow: [docs/github-action.md](docs/github-action.md).

## Coding-agent integration

- **Post-edit hook (Claude Code):** the `vetgate-hook` command runs as a `PostToolUse` hook on `Edit|Write`.
  It reports medium+ findings anywhere in the edited file and low findings only on lines changed vs git `HEAD`,
  so legacy noise does not flood the context. It says nothing when the file is clean and never blocks the edit.
  ```json
  { "hooks": { "PostToolUse": [ { "matcher": "Edit|Write|MultiEdit", "hooks": [
      { "type": "command", "command": "vetgate-hook", "timeout": 30 } ] } ] } }
  ```
- **git pre-commit hook:** checks the staged files, blocks the commit on medium+ findings and lists low ones
  without blocking (skip once with `git commit --no-verify`). It is offline only: `VETGATE_NO_NETWORK=1` is forced
  and the `deps` focus never runs. With the [pre-commit](https://pre-commit.com) framework, in
  `.pre-commit-config.yaml` (use a release that ships `vetgate-pre-commit`):
  ```yaml
  repos:
    - repo: https://github.com/stuckerbsas/vetgate
      rev: v0.9.1
      hooks:
        - id: vetgate
  ```
  Or call the console script directly from `.git/hooks/pre-commit` (after `pip install vetgate`):
  ```sh
  vetgate-pre-commit || exit 1
  ```
  Existing setups that call `python /path/to/vetgate/hooks/pre_commit.py` keep working (thin wrapper).
- **Skill:** [SKILL.md](SKILL.md) tells an agent when to run the vetgate and how to act on the results.

## Feedback and data

- **Report a false positive or a missed issue:** `vetgate report Path/File.cs:42` (add `--kind missed-issue`,
  `--open` to open the browser). It prints the prefilled issue so you can review or trim the snippet; nothing is
  sent automatically.
- **Network:** everything runs locally and offline. The one exception is the opt-in `deps` focus, which sends
  only ecosystem, package name and version to OSV.dev (never paths or project names, never from the hooks;
  `VETGATE_NO_NETWORK=1` turns it off). See [docs/rules/deps.md](docs/rules/deps.md).
- **Local case log:** the post-edit hook appends each finding it reports to `~/.vetgate/findings.jsonl` (local
  only; `VETGATE_NO_LOG=1` disables it, `VETGATE_HOME` moves it). `vetgate feedback` labels cases as *fixed*
  (likely true positive) or *suppressed* (likely false positive), and `vetgate feedback --export cases.jsonl`
  writes them as a dataset for training a learned second layer.

## Development

```bash
python -m unittest discover -s tests       # fixtures + core tests
python run_fixtures.py                     # fixtures + false-positive check on real codebases
```

Each rule has a fixture in `fixtures/<lang>/` with a `FIXTURE-RULES: ...` header and an `EXPECT: RULE` marker on
every line that must be flagged. Vulnerable and safe cases sit side by side, and the reported set must match
exactly. Real-codebase false-positive targets come from `--fp-target`, `$VETGATE_FP_TARGETS` (`os.pathsep`-separated)
or a gitignored `vetgate.local.json` (`{"fp_targets": ["..."]}`). They must give 0 medium+ findings; with none
configured the step is skipped with a message.

New rule: fixture first, then the rule, then `run_fixtures.py` must be all green.

New language: add `vetgate/languages/<lang>/` exposing `NAME`, `EXTENSIONS`, `FOCUSES`, `is_test_file`,
`analyze(path, source, focuses, options)` and register it in `vetgate/languages/__init__.py`.

```
vetgate/cli.py, core.py      CLI, finding schema, suppressions, diff mode, json/text/compact/sarif
vetgate/thresholds.py        default thresholds (single source of truth)
vetgate/languages/csharp/    common (parser + taint), security, security_web, debug, quality, practices
vetgate/pre_commit.py        git pre-commit gate (`vetgate-pre-commit`)
fixtures/                    regression fixtures per language
hooks/post_edit_gate.py      Claude Code post-edit hook (repo checkout wrapper)
```
