npm package: @modular-intelligence/secrets-scanner
Description: MCP server wrapping TruffleHog and Gitleaks for secrets detection in code and repositories
Latest version: 1.0.2

# Secrets Scanner MCP Server

An MCP (Model Context Protocol) server that wraps **TruffleHog** and **Gitleaks** for comprehensive secrets detection in code repositories, filesystems, and cloud storage.

## Overview

This MCP server provides AI assistants with secure, sandboxed access to industry-standard secrets scanning tools. All secret values are **automatically redacted** in output to prevent accidental exposure.

## Features

- **Dual-Engine Scanning**: Combines TruffleHog and Gitleaks for comprehensive coverage
- **Multiple Scan Targets**: Git repositories, local filesystems, and S3 buckets
- **Verified Secrets Detection**: TruffleHog can validate if secrets are still active
- **Pre-Commit Protection**: Scan staged changes before committing
- **Baseline Comparison**: Track new and resolved secrets over time
- **Security Hardened**:
  - All secret values are redacted (shows first/last characters only)
  - Path traversal protection
  - System directory blocking
  - HTTPS-only repository URLs
  - Private IP blocking
  - Execution timeouts
  - Buffer overflow protection

## Prerequisites

Install the scanning tools:

```bash
# TruffleHog
brew install trufflesecurity/trufflehog/trufflehog
# or
go install github.com/trufflesecurity/trufflehog/v3@latest

# Gitleaks
brew install gitleaks
# or
go install github.com/gitleaks/gitleaks/v8@latest
```

For S3 scanning, set AWS credentials:
```bash
export AWS_ACCESS_KEY_ID="your-key"
export AWS_SECRET_ACCESS_KEY="your-secret"
export AWS_REGION="us-east-1"  # optional
```

## Installation

```bash
cd secrets-scanner
bun install
bun run build
```

## Configuration

Add to your MCP settings file (e.g., `claude_desktop_config.json`):

```json
{
  "mcpServers": {
    "secrets-scanner": {
      "command": "bun",
      "args": ["run", "/absolute/path/to/secrets-scanner/src/index.ts"]
    }
  }
}
```

## Available Tools

### 1. trufflehog_scan_repo

Scan a Git repository for exposed secrets in commit history.

**Parameters:**
- `repo_url` (required): HTTPS Git repository URL
- `since_commit` (optional): Only scan commits after this hash
- `branch` (optional): Specific branch to scan
- `only_verified` (optional, default: false): Only report verified (active) secrets
- `timeout` (optional, default: 120): Maximum scan duration in seconds (30-600)

**Example:**
```typescript
{
  "repo_url": "https://github.com/example/repo.git",
  "only_verified": true,
  "timeout": 180
}
```

**Output:**
```json
{
  "findings": [
    {
      "detector_type": "AWS",
      "decoder_type": "PLAIN",
      "verified": true,
      "redacted_raw": "AKIA****xyz9",
      "source_metadata": {
        "file": "config.py",
        "commit": "abc123...",
        "email": "dev@example.com",
        "timestamp": "2024-01-15T10:30:00Z",
        "line": 42
      }
    }
  ],
  "total": 5,
  "verified_count": 2
}
```

### 2. trufflehog_scan_fs

Scan a local filesystem directory for secrets.

**Parameters:**
- `path` (required): Absolute path to directory
- `only_verified` (optional, default: false): Only report verified secrets
- `timeout` (optional, default: 120): Maximum scan duration in seconds

**Example:**
```typescript
{
  "path": "/Users/dev/project",
  "only_verified": false
}
```

### 3. trufflehog_scan_s3

Scan an S3 bucket for exposed secrets.

**Parameters:**
- `bucket` (required): S3 bucket name
- `prefix` (optional): S3 key prefix to limit scan scope
- `only_verified` (optional, default: false): Only report verified secrets
- `timeout` (optional, default: 300): Maximum scan duration in seconds

**Requirements:**
- `AWS_ACCESS_KEY_ID` environment variable
- `AWS_SECRET_ACCESS_KEY` environment variable

**Example:**
```typescript
{
  "bucket": "my-app-backups",
  "prefix": "configs/",
  "only_verified": true
}
```

### 4. gitleaks_scan_repo

Scan a Git repository using Gitleaks' entropy detection and pattern matching.

**Parameters:**
- `repo_url` (required): HTTPS Git repository URL
- `since_commit` (optional): Only scan commits after this hash
- `timeout` (optional, default: 120): Maximum scan duration in seconds

**Example:**
```typescript
{
  "repo_url": "https://github.com/example/repo.git",
  "since_commit": "abc123def456"
}
```

**Output:**
```json
{
  "findings": [
    {
      "description": "AWS Access Key",
      "file": "deploy.sh",
      "start_line": 15,
      "end_line": 15,
      "commit": "xyz789...",
      "author": "John Doe",
      "email": "john@example.com",
      "date": "2024-01-10T14:22:00Z",
      "rule_id": "aws-access-token",
      "entropy": 4.5,
      "redacted_match": "AKIA****xyz9"
    }
  ],
  "total": 3
}
```

### 5. gitleaks_scan_dir

Scan a local directory without Git history (useful for non-Git projects).

**Parameters:**
- `path` (required): Absolute path to directory
- `timeout` (optional, default: 120): Maximum scan duration in seconds

**Example:**
```typescript
{
  "path": "/Users/dev/legacy-app",
  "timeout": 90
}
```

### 6. gitleaks_protect

Pre-commit hook mode - scan only staged Git changes.

**Parameters:**
- `path` (required): Absolute path to Git repository
- `staged_only` (optional, default: true): Only scan staged changes
- `timeout` (optional, default: 120): Maximum scan duration in seconds

**Example:**
```typescript
{
  "path": "/Users/dev/my-repo",
  "staged_only": true
}
```

**Output:**
```json
{
  "findings": [...],
  "clean": false,
  "total": 1
}
```

### 7. secrets_compare

Compare current scan results against a baseline to detect new or resolved secrets.

**Parameters:**
- `path` (required): Absolute path to directory to scan
- `baseline_path` (required): Path to previous scan results JSON file
- `timeout` (optional, default: 120): Maximum scan duration in seconds

**Example:**
```typescript
{
  "path": "/Users/dev/project",
  "baseline_path": "/Users/dev/baseline-scan.json"
}
```

**Output:**
```json
{
  "new_findings": [
    {
      "description": "GitHub Token",
      "file": "auth.js",
      "start_line": 23,
      "end_line": 23,
      "rule_id": "github-pat",
      "redacted_match": "ghp_****abc1"
    }
  ],
  "resolved_findings": [
    {
      "description": "Old API Key",
      "file": "config.old",
      "start_line": 10,
      "end_line": 10,
      "rule_id": "generic-api-key",
      "redacted_match": "sk_t****xyz9"
    }
  ],
  "unchanged_count": 5
}
```

## Security Features

### Secret Redaction

All secret values are automatically redacted using the following algorithm:
- **Secrets ≥ 12 characters**: Show first 4 and last 4 chars, mask middle with asterisks
  - Example: `AKIAIOSFODNN7EXAMPLE` → `AKIA********MPLE`
- **Secrets < 12 characters**: Show first 2 and last 2 chars
  - Example: `abc12345` → `ab****45`
- **Secrets ≤ 4 characters**: Show only asterisks
  - Example: `key1` → `****`

### Path Validation

- Only absolute paths allowed
- Path traversal (`../`) blocked
- System directories blocked: `/etc`, `/proc`, `/sys`, `/dev`, `/root`, `/var/run`
- Other users' home directories blocked

### Repository URL Validation

- HTTPS only (no HTTP, file://, git://)
- Private IP addresses blocked (10.x.x.x, 172.16-31.x.x, 192.168.x.x)
- Localhost blocked
- Link-local addresses blocked

### S3 Bucket Validation

- Must be 3-63 characters
- Lowercase letters, numbers, dots, hyphens only
- Cannot be formatted as IP address
- No consecutive dots
- Credentials via environment variables only

### Execution Safety

- Maximum buffer size: 10MB
- Configurable timeouts (30-600 seconds)
- Processes killed with SIGKILL on timeout
- Non-zero exit codes handled gracefully

## Use Cases

### Pre-Commit Hook Integration

```typescript
// Scan staged changes before committing
{
  "path": "/Users/dev/my-project",
  "staged_only": true
}
```

### CI/CD Pipeline

```typescript
// Scan repository in CI
{
  "repo_url": "https://github.com/company/app.git",
  "branch": "main",
  "only_verified": true,
  "timeout": 300
}
```

### Security Audit

```typescript
// Full historical scan
{
  "repo_url": "https://github.com/company/legacy-app.git",
  "only_verified": false
}
```

### Baseline Tracking

```bash
# Initial scan (save results)
gitleaks detect --source /path/to/repo --report-format json --report-path baseline.json

# Later comparison
{
  "path": "/path/to/repo",
  "baseline_path": "/path/to/baseline.json"
}
```

## Limitations

- **Repository Size**: Large repositories may timeout or exceed buffer limits
- **S3 Scanning**: Requires valid AWS credentials in environment
- **Git History**: Full history scans can be slow on large repositories
- **Rate Limits**: TruffleHog verification may hit API rate limits

## Best Practices

1. **Start Small**: Test on small repositories first
2. **Use Timeouts**: Adjust timeout based on repository size
3. **Verified Only**: Use `only_verified: true` in production to reduce false positives
4. **Regular Scans**: Schedule periodic scans and use baseline comparison
5. **Pre-Commit**: Integrate `gitleaks_protect` into development workflow
6. **Incremental Scans**: Use `since_commit` to scan only recent changes
7. **Credential Rotation**: If verified secrets are found, rotate them immediately

## Troubleshooting

### Tool Not Found

```
Error: spawn trufflehog ENOENT
```

**Solution**: Install TruffleHog and ensure it's in your PATH:
```bash
which trufflehog
brew install trufflesecurity/trufflehog/trufflehog
```

### Timeout Errors

```
Error: TruffleHog execution timed out after 120 seconds
```

**Solution**: Increase timeout or limit scan scope:
```typescript
{
  "repo_url": "https://github.com/example/repo.git",
  "since_commit": "recent_commit_hash",
  "timeout": 300
}
```

### AWS Credentials Not Found

```
Error: AWS credentials not found. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
```

**Solution**: Export AWS credentials:
```bash
export AWS_ACCESS_KEY_ID="your-key"
export AWS_SECRET_ACCESS_KEY="your-secret"
```

### Buffer Size Exceeded

```
Error: Output exceeded maximum buffer size (10MB)
```

**Solution**: Limit scan scope using `since_commit`, `branch`, or `prefix` parameters.

## License

MIT

## Contributing

Contributions welcome! Please ensure:
- All secret values are redacted in output
- Security validations are maintained
- Tests cover new functionality
- Documentation is updated

## Security Disclosure

If you discover a security vulnerability, please email security@example.com instead of using the issue tracker.