depsec Documentation
AI-powered security scanning for Python packages. Catch typosquatting, malicious code, and supply chain attacks before they reach your environment.
Installation
depsec requires Python 3.10+ and works on Linux, macOS, and Windows.
Basic Install
$ pip install depsec
This installs depsec with Tier 1 (heuristics) and Tier 2 (AST analysis) support. No additional configuration is needed.
With AI Support
# Install with the Anthropic SDK for Tier 3 AI analysis $ pip install depsec[ai] # Set your API key $ export ANTHROPIC_API_KEY=sk-...
Note: AI analysis is entirely optional. Tiers 1 and 2 provide substantial security coverage without it. When AI is enabled, it is only triggered for packages already flagged by earlier tiers, keeping API costs low.
Usage
depsec is a drop-in replacement for pip install. It sits between you and pip, analyzing every package before it touches your system.
Commands
depsec install [packages...] [options]
Resolve, analyze, and install packages. This is the primary command.
-r, --requirement FILE Install from a requirements file. Can be specified multiple times.--dry-run Analyze packages without installing them. Shows what would happen.--allow-blocked Install packages even if they are blocked by security analysis. Use with caution.$ depsec install flask requests Resolving 12 packages... Analyzing flask (3.0.0) ✓ Safe Analyzing requests (2.31.0) ✓ Safe Analyzing jinja2 (3.1.2) ✓ Safe Analyzing reqeusts (1.0.0) ✗ Blocked — Typosquat of 'requests' (distance: 2) → Setup.py contains: subprocess.Popen, base64.b64decode 11 packages safe · 0 warnings · 1 blocked
Exits with code 1 if any packages are blocked (unless --allow-blocked is used).
depsec audit [packages...] [options]
Analyze packages without installing them. This runs the same analysis pipeline as install but never installs anything. Designed for CI pipelines and security reviews.
-r, --requirement FILE Audit packages from a requirements file.$ depsec audit -r requirements.txt
Exits with code 1 if any packages would be blocked. This makes it ideal for use in CI/CD pipelines as a quality gate.
depsec verify
Run a self-integrity check on depsec's own installation. This command verifies that depsec itself has not been tampered with.
Reports:
- Installed version
- SHA-256 hashes of all installed
.pyfiles - Dependency versions
- Installation source (pip, pipx, etc.)
Exit Codes
| Code | Meaning |
|---|---|
0 | All packages are safe (or warned but not blocked) |
1 | One or more packages were blocked |
Analysis Pipeline
depsec uses a 3-tier analysis pipeline. Each tier adds depth, and packages only proceed to higher tiers if earlier tiers flag potential issues.
Tier 1 Static Heuristics
Less than 100ms per package. Runs on every package.
Typosquatting Detection
Compares package names against a curated list of 200+ popular PyPI packages using multiple detection strategies:
Levenshtein distance -- measures edit distance between the package name and popular packages (threshold varies by name length).
Homoglyph detection -- catches character substitutions that look similar: 0/o, 1/l/i, rn/m, vv/w.
Separator confusion -- detects swaps between hyphens, underscores, and dots (e.g., python-dateutil vs python_dateutil).
Known CVE Lookup
Queries the OSV database for known vulnerabilities affecting the specific package version. Maps CVSS scores to depsec severity levels and includes affected version ranges and references.
Metadata Analysis
Fetches metadata from the PyPI JSON API and checks for suspicious indicators: recently created packages (less than 7 days old), missing homepage or repository URL, empty or very short descriptions, and missing author/maintainer information.
Tier 2 AST Analysis
Less than 1 second per package. Parses Python source with the ast module -- no code is ever executed.
Suspicious Imports
Flags imports of modules commonly used in malicious packages: os, subprocess, socket, ctypes, and others.
Dangerous Function Calls
Detects calls to exec(), eval(), compile(), __import__(), os.system(), subprocess.Popen(), and other functions that enable arbitrary code execution.
Obfuscation Patterns
Identifies techniques used to hide malicious payloads: base64.b64decode(), codecs.decode(), zlib.decompress(), marshal.loads(), and bytes.fromhex().
Network Access
Identifies HTTP requests, raw socket creation, and other network operations that may indicate data exfiltration or command-and-control communication.
File System Writes
Flags writes to system paths (/etc, /usr, /tmp, etc.) that could indicate persistent backdoor installation.
setup.py receives stricter scrutiny. Because setup.py executes during pip install, it is scanned with elevated severity levels. The same pattern in setup.py is treated as more suspicious than in a regular module file.
Tier 3 AI Analysis
2-10 seconds per package. Only triggered when Tiers 1-2 find issues.
When a package is flagged by earlier tiers, depsec sends the relevant source files to Claude for deeper adversarial security analysis. The AI reviews code behavior, not claims -- the system prompt explicitly instructs the model to ignore comments or strings that attempt to influence the assessment.
Key principle: AI is advisory only. AI findings can only add to the risk score. They can never remove or override findings from Tiers 1 and 2. This is enforced by an assertion in the pipeline code, not merely by convention.
The AI analysis includes hardening against prompt injection:
- Source code is scanned for prompt injection patterns before being sent to the model
- Detected patterns are flagged with inline warnings so the model treats them as untrusted
- Response parser rejects "clearance" findings that match phrases like "code is safe"
- If the AI returns zero findings despite Tier 1-2 flags, a disagreement finding is generated at HIGH severity
Risk Scoring
Each finding has a severity level that maps to a numeric score. The package risk score is the maximum severity score across all findings.
| Severity | Score |
|---|---|
| CRITICAL | 0.9 |
| HIGH | 0.7 |
| MEDIUM | 0.5 |
| LOW | 0.2 |
| INFO | 0.05 |
The risk score determines the outcome:
| Score Range | Outcome | Behavior |
|---|---|---|
| ≥ 0.8 | BLOCKED | Installation prevented (red X) |
| 0.4 – 0.79 | WARNED | Warning shown, installation proceeds (yellow) |
| < 0.4 | SAFE | No issues found (green checkmark) |
Configuration
depsec reads configuration from ~/.depsec/config.toml. All settings have sensible defaults -- depsec works out of the box with no configuration file.
# General behavior mode [general] mode = "block" # "block", "warn", "audit-only" # Analysis settings [analysis] enable_ai = true # Enable Tier 3 AI analysis ai_provider = "anthropic" ai_model = "claude-sonnet-4-20250514" max_ai_analysis_time = 30 # Seconds before AI analysis times out # Risk score thresholds [thresholds] block_score = 0.8 # Risk score >= this blocks installation warn_score = 0.4 # Risk score >= this shows warnings # Package lists [allowlist] packages = ["requests", "flask", "django"] curated_list = "top-5000" # Popular package list for typosquat checks # Always block these packages [denylist] packages = ["colourama"]
Configuration Options
[general]
mode
Default: "block". Controls what happens when risky packages are found.
"block" -- prevents installation of packages with risk score above the block threshold. "warn" -- shows warnings but always installs. "audit-only" -- only reports findings, never installs.
[analysis]
enable_ai
Default: true. Enables Tier 3 AI-powered analysis. Requires the depsec[ai] extra and ANTHROPIC_API_KEY environment variable. When disabled, only Tiers 1 and 2 run.
ai_provider
Default: "anthropic". The AI provider to use for Tier 3 analysis.
ai_model
Default: "claude-sonnet-4-20250514". The specific model to use for AI analysis.
max_ai_analysis_time
Default: 30 (seconds). Maximum time to wait for AI analysis before timing out. If the timeout is reached, AI findings are discarded and Tier 1-2 findings are preserved.
[thresholds]
block_score / warn_score
Defaults: 0.8 / 0.4. Packages with a risk score at or above block_score are blocked. Packages between warn_score and block_score show warnings. Packages below warn_score are considered safe.
[allowlist]
packages
Default: []. A list of package names to skip analysis for. Use this for known-good packages that trigger false positives.
curated_list
Default: "top-5000". The curated list of popular packages used for typosquatting detection. Packages on this list are not flagged as typosquats.
[denylist]
packages
Default: []. A list of package names to always block, regardless of analysis results.
Architecture
depsec intercepts the package installation flow by using pip install --dry-run --report to resolve dependencies without installing anything, then downloads packages to a staging directory for analysis before allowing installation.
The Pip Bridge
depsec does not reimplement dependency resolution. It delegates to pip using pip install --dry-run --report <tmpfile>, which resolves the full dependency tree (including transitive dependencies) without installing anything. The JSON report is parsed into PackageInfo objects with name, version, SHA-256 hash, and download URL.
Packages are downloaded to a temporary staging directory. After analysis, approved packages are installed using pip install --no-index --find-links <staging_dir>, ensuring pip installs from local files only.
Module Overview
depsec/cli/
- main.py -- Entry point and command group
- install_cmd.py -- Install command with analysis gate
- audit_cmd.py -- Audit-only command for CI
- verify_cmd.py -- Self-integrity verification
depsec/pip_bridge/
- resolver.py -- Dependency resolution via pip --dry-run --report
- downloader.py -- Package download to staging directory
- installer.py -- Final installation from local files
depsec/analysis/
- pipeline.py -- Orchestrator, runs all tiers sequentially
- models.py -- Data models (PackageInfo, Finding, AnalysisResult)
- typosquat.py -- Tier 1: Typosquatting detection
- cve_checker.py -- Tier 1: CVE lookup via OSV API
- metadata.py -- Tier 1: PyPI metadata analysis
- ast_scanner.py -- Tier 2: AST-based source code scanning
- ai_analyzer.py -- Tier 3: LLM-powered analysis
depsec/config/
- settings.py -- Settings dataclass with TOML loading
- defaults.py -- Default configuration values
depsec/cache/
- store.py -- SQLite-backed cache keyed on package SHA-256
Security Model
A security tool is a high-value target. If an attacker compromises depsec, they can suppress findings for malicious packages, giving users a false sense of security. depsec applies defense-in-depth to its own supply chain.
Core principle: AI is advisory, deterministic checks are authoritative. Tier 1-2 findings are preserved regardless of AI output, enforced by assertion -- not convention.
Defense Layers
Distribution Security
Trusted Publishers on PyPI via GitHub Actions OIDC (no stored API tokens). Sigstore attestations and SLSA Level 3 build provenance on every release. CycloneDX SBOM published with each release.
Dependency Security
Minimal dependencies -- only click and httpx at runtime. All dependencies pinned with SHA-256 hashes. CI installs with --require-hashes to detect tampering.
Build Pipeline Security
All GitHub Actions pinned to commit SHAs, not mutable tags. Minimal workflow permissions. Reproducible builds with SOURCE_DATE_EPOCH=0.
AI Safety
AI findings can only increase risk scores, never decrease them. Prompt injection patterns are detected and flagged before being sent to the model. "Clearance" responses from the AI are rejected.
Runtime Integrity
Self-verification via depsec verify hashes all installed files and reports dependency versions. Analysis cache is keyed on immutable SHA-256 hashes.
Audit Logging
All analysis results, including AI interactions, are logged to ~/.depsec/depsec.log for forensic review.
Self-Verification
Run depsec verify at any time to check depsec's own integrity. This command hashes every installed .py file and reports the installed version, dependency versions, and installation source.
$ depsec verify
CI/CD Integration
Use depsec audit in your CI/CD pipeline to catch malicious or vulnerable dependencies before they reach production. The command exits with code 1 if any packages would be blocked, making it a natural fit for pipeline quality gates.
GitHub Actions
name: CI on: [push, pull_request] jobs: audit: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: python-version: "3.12" - name: Install depsec run: pip install depsec - name: Audit dependencies run: depsec audit -r requirements.txt
GitLab CI
audit: image: python:3.12 script: - pip install depsec - depsec audit -r requirements.txt
Tip: For AI-powered analysis in CI, install depsec[ai] and set the ANTHROPIC_API_KEY as a masked/secret environment variable in your CI platform.