@beaverscan/cli
v1.1.1
Published
BeaverScan CLI - Security code scanner for JavaScript/TypeScript
Maintainers
Readme
🦫 BeaverScan CLI
BeaverScan CLI is a security code scanner for JavaScript and TypeScript projects. It detects vulnerabilities, exposed secrets, bad practices, and vulnerable dependencies directly in your source code.
Features
Security Scanners
- Secrets Scanner: Detects exposed API keys, tokens, credentials, and other sensitive information
- Injection Scanner: Identifies SQL injection, XSS, and command injection vulnerabilities
- Bad Practices Scanner: Finds insecure coding patterns like
eval(), unsafe DOM manipulation, and weak configurations - Dependency Scanner: Checks npm packages for known vulnerabilities using npm audit
Reporting Options
- Terminal Output: Colorful, interactive terminal display
- JSON Export: Machine-readable JSON reports
- HTML Reports: Beautiful, shareable HTML reports with charts and filtering
- SARIF Export: Industry-standard SARIF 2.1.0 format for GitHub Security tab integration
Installation
Via npm (Recommended)
npm install -g @beaverscan/cliFrom Source (Development)
cd cli
npm install
npm run build
npm linkUsage
Basic Scan
# Scan current directory
beaverscan scan .
# Scan specific directory
beaverscan scan ./src
# Scan with full mode (more thorough)
beaverscan scan ./app --fullOutput Formats
# Terminal output (default)
beaverscan scan ./src
# JSON output
beaverscan scan ./src --output json
# HTML report
beaverscan scan ./src --output html
# SARIF report (GitHub Security tab compatible)
beaverscan scan ./src --output sarif
# All formats
beaverscan scan ./src --output allFiltering by Severity
# Show only critical issues
beaverscan scan ./src --severity critical
# Show high and critical
beaverscan scan ./src --severity high
# Show all issues (default)
beaverscan scan ./src --severity allExclude Patterns
# Exclude test files
beaverscan scan ./src --exclude "**/*.test.ts" "**/*.spec.ts"
# Exclude multiple directories
beaverscan scan . --exclude "examples/**" "docs/**"Custom Report Path
# Save reports to specific directory
beaverscan scan ./src --output all --report-path ./reportsInteractive Mode
Launch BeaverScan in interactive mode for a guided, step-by-step security scanning experience.
# Start interactive mode
beaverscan scan . --interactiveFeatures
- 📋 Pre-scan Configuration: Interactive prompts to select scanners, severity level, and options
- 📊 Real-time Progress: Live progress indicators showing scan status for each scanner
- 🔍 Interactive Results Explorer: Navigate through issues by severity or file
- 💡 Detailed Issue View: See code snippets, fix recommendations, and CVE information
- 📤 Easy Export: Export results in JSON or SARIF format directly from the interface
Workflow
- Welcome & Configuration: Select which scanners to run and configure scan options
- Live Scanning: Watch the progress as each scanner analyzes your code
- Results Explorer: Browse issues grouped by severity or file
- Issue Details: View detailed information for each security issue
- Actions: Export results or navigate back to the main menu
Example Session
🦫 BeaverScan Interactive Mode
Configure your security scan step by step
? Which scanners do you want to run?
◉ Secrets Scanner (52+ patterns + entropy detection)
◉ Injection Scanner (SQL, XSS, Command)
◉ Bad Practices Scanner
◉ Dependency Scanner
? Minimum severity level to report? All (critical, high, medium, low)
? Enable incremental scanning? No
? Compare with baseline? No
🦫 Scanning /Users/project/src...
✓ Secrets Scanner (2.3s) → 3 issues
✓ Injection Scanner (1.8s) → 1 issue
✓ Bad Practices (1.2s) → No issues
✓ Dependency Scanner (0.8s) → 2 issues
────────────────────────────────────────
Scan completed in 6.1s → 6 issues found
────────────────────────────────────────
┌──────────────────────────────────────┐
│ Scan Complete! │
│ Score: 72/100 (Grade: C) │
│ Found 6 issues (3 critical, 1 high) │
└──────────────────────────────────────┘
? What would you like to do?
❯ 🔍 View issues by severity
📁 View issues by file
📤 Export results
🚪 ExitNavigation: Use arrow keys to navigate, Enter to select, and follow on-screen prompts to explore your security scan results interactively.
Configuration
BeaverScan supports configuration files to persist your scanning preferences across runs. You can use either JSON or YAML format.
Configuration File Discovery
BeaverScan automatically looks for configuration files in the following order:
- CLI argument:
--config path/to/config.json - Project directory:
.beaverscanrc.jsonor.beaverscanrc.yml(searches upward from current directory) - Home directory:
~/.beaverscanrc.jsonor~/.beaverscanrc.yml - Default values: If no configuration file is found
Basic Configuration
Create a .beaverscanrc.json file in your project root:
{
"severity": "high",
"output": "html",
"reportPath": "./beaverscan-report",
"exclude": [
"node_modules/**",
"dist/**",
"**/*.test.ts"
],
"scanners": {
"secrets": true,
"injection": true,
"badPractices": true,
"dependencies": true
},
"full": false
}Or use YAML format (.beaverscanrc.yml):
severity: high
output: html
reportPath: ./beaverscan-report
exclude:
- node_modules/**
- dist/**
- '**/*.test.ts'
scanners:
secrets: true
injection: true
badPractices: true
dependencies: true
full: falseIgnore File (.beaverscanignore)
BeaverScan supports .beaverscanignore files to exclude files from scanning, using the same syntax as .gitignore.
File Discovery
BeaverScan automatically looks for ignore files in the following order:
- CLI argument:
--ignore-file path/to/.myignore - Project directory:
.beaverscanignore(searches upward from scan directory) - Home directory:
~/.beaverscanignore(global ignore patterns)
Syntax
The .beaverscanignore file supports standard gitignore syntax:
- Glob patterns: Standard glob patterns to match files
- Comments: Lines starting with
#are ignored - Negation: Lines starting with
!re-include previously excluded files - Blank lines: Ignored
Example .beaverscanignore
# Dependencies
node_modules/
vendor/
# Build outputs
dist/
build/
out/
# Test files
**/*.test.ts
**/*.spec.js
__tests__/
# Minified files
*.min.js
*.bundle.js
# Generated files
**/*.generated.ts
# Exclude entire directory
legacy/
# But include specific important file (negation)
!legacy/authentication.tsPattern Priority
Exclusion patterns are merged in the following priority order (lowest to highest):
- Default hardcoded exclusions (node_modules, dist, etc.)
.beaverscanignorefile patterns- Config file
excludearray (.beaverscanrc.json) - CLI
--excludeflags (highest priority)
CLI Usage
# Use project .beaverscanignore (automatically discovered)
beaverscan scan ./src
# Use custom ignore file
beaverscan scan ./src --ignore-file .myignore
# Combine with other exclusions
beaverscan scan ./src --ignore-file .myignore --exclude "**/*.backup.js"Note: The .beaverscanignore file is complementary to the exclude configuration option - patterns from both sources are combined.
SARIF Export (GitHub Security Integration)
BeaverScan supports exporting scan results in SARIF 2.1.0 format (Static Analysis Results Interchange Format), the industry-standard format for security tools. SARIF reports can be uploaded to GitHub's Security tab for centralized vulnerability tracking.
What is SARIF?
SARIF is a JSON-based format designed to represent the output of static analysis tools. It provides a standardized way to:
- Report security vulnerabilities and code quality issues
- Track issues across multiple scans
- Integrate with CI/CD pipelines
- Display results in GitHub Security tab
Generating SARIF Reports
# Generate SARIF report
beaverscan scan ./src --output sarif
# Save to specific directory
beaverscan scan ./src --output sarif --report-path ./security-reportsUploading to GitHub Security Tab
Method 1: Manual Upload
Run BeaverScan with SARIF output:
beaverscan scan . --output sarifGo to your GitHub repository → Security → Code scanning alerts
Click Upload SARIF file and select the generated
.sariffile
Method 2: GitHub Actions (Automated)
Create .github/workflows/beaverscan.yml:
name: BeaverScan Security Scan
on:
push:
branches: [main, dev]
pull_request:
branches: [main, dev]
jobs:
security-scan:
runs-on: ubuntu-latest
permissions:
security-events: write
contents: read
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install BeaverScan
run: npm install -g @beaverscan/cli
- name: Run BeaverScan
run: beaverscan scan . --output sarif --report-path ./
- name: Upload SARIF to GitHub Security
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: beaverscan-report-*.sarif
category: beaverscanSARIF Report Structure
BeaverScan SARIF reports include:
- Tool Information: BeaverScan version and metadata
- Rules: Detailed descriptions of each vulnerability type
- Results: Individual security findings with:
- File location and line numbers
- Severity levels mapped to SARIF standards
- Fix recommendations
- Fingerprints for deduplication
- Artifacts: List of scanned files
Severity Mapping
BeaverScan severity levels are mapped to SARIF as follows:
| BeaverScan | SARIF Level | Security Severity Score |
|------------|-------------|------------------------|
| critical | error | 9.5 |
| high | error | 8.5 |
| medium | warning | 6.0 |
| low | note | 3.0 |
The security-severity property enables GitHub to prioritize issues in the Security tab.
Baseline & Comparison Mode
BeaverScan supports baseline comparison to track security improvements over time and detect new vulnerabilities. This is especially useful in CI/CD pipelines where you want to fail builds only on new security issues, not existing ones.
How it Works
- Create Baseline: Save current scan results as a reference point
- Compare Scans: Compare subsequent scans against the baseline
- Track Changes: Identify new, fixed, and existing issues
- Smart CI/CD: Fail only on new critical/high issues
Creating a Baseline
# Save current scan as baseline
beaverscan scan . --baseline
# Creates .beaverscan-baseline.json in project rootThe baseline file contains:
- All security issues with unique fingerprints
- Scan metadata (timestamp, version, path)
- Issue summaries by severity
Comparing with Baseline
# Compare current scan with baseline
beaverscan scan . --compare-baseline
# Use custom baseline file
beaverscan scan . --compare-baseline --baseline-file ./my-baseline.jsonComparison Output:
🔄 Baseline Comparison Results
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📈 New Issues: 5
🔴 Critical: 2
🟠 High: 3
📉 Fixed Issues: 8
✅ sql-injection in auth.ts:45
✅ xss in components/Form.tsx:123
📊 Summary:
New: 5 | Fixed: 8 | Existing: 12
Net Change: -3 issues 🎉CI/CD Integration
In comparison mode, BeaverScan exits with different codes:
- Exit 0: No new critical/high issues (build passes ✅)
- Exit 1: New critical/high issues detected (build fails ❌)
This means your CI/CD pipeline won't fail on existing issues, only on newly introduced ones.
GitHub Actions Example:
name: Security Scan with Baseline
on: [push, pull_request]
jobs:
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install BeaverScan
run: npm install -g @beaverscan/cli
# On main branch: update baseline
- name: Update Baseline (main branch)
if: github.ref == 'refs/heads/main'
run: |
beaverscan scan . --baseline
git add .beaverscan-baseline.json
git commit -m "chore: update security baseline"
git push
# On PRs: compare with baseline
- name: Compare with Baseline (PR)
if: github.event_name == 'pull_request'
run: beaverscan scan . --compare-baselineUse Cases
1. Track Security Improvements
# Week 1: Create baseline with 50 issues
beaverscan scan . --baseline
# Week 2: Compare - fixed 10 issues!
beaverscan scan . --compare-baseline
# Output: Net Change: -10 issues 🎉2. Prevent Regressions
# Before refactor
beaverscan scan . --baseline
# After refactor
beaverscan scan . --compare-baseline
# Fails if new issues introduced3. CI/CD Quality Gates
# Only fail on NEW critical/high issues
beaverscan scan . --compare-baselineConfiguration
Add baseline settings to .beaverscanrc.json:
{
"baselineFile": "./.beaverscan-baseline.json"
}Best Practices
- Commit baseline files: Include
.beaverscan-baseline.jsonin version control - Update regularly: Refresh baseline after fixing issues
- Use in CI/CD: Compare on PRs, update baseline on main
- Custom baselines: Use different baselines for different environments
Baseline File Structure
{
"metadata": {
"createdAt": "2025-01-15T10:30:00Z",
"version": "1.0.1",
"scanPath": "/Users/me/project",
"totalIssues": 12
},
"report": { /* Full scan report */ },
"fingerprintedIssues": [
{
"type": "sql-injection",
"severity": "critical",
"message": "...",
"file": "src/db.ts",
"line": 45,
"fingerprint": "a1b2c3d4e5f6g7h8"
}
]
}Incremental Scanning
NEW: Incremental scanning significantly speeds up scans by only analyzing files that have changed since the last scan, using git to detect changes.
How it Works
- Git Integration: Uses
git diffto identify changed files - Smart Filtering: Only scans modified JavaScript/TypeScript files
- Automatic Caching: Caches scan results to avoid re-scanning unchanged files
- Multiple Modes: Supports different git diff modes (staged, unstaged, all, committed)
Basic Usage
# Scan only changed files
beaverscan scan . --incremental
# Scan only staged files (pre-commit hook)
beaverscan scan . --incremental --git-diff-mode staged
# Scan only unstaged files
beaverscan scan . --incremental --git-diff-mode unstaged
# Clear cache and start fresh
beaverscan scan . --clear-cacheGit Diff Modes
| Mode | Description | Use Case |
|------|-------------|----------|
| all | All changed files (staged + unstaged + untracked) | Default - General development |
| staged | Only staged files | Pre-commit hooks |
| unstaged | Only unstaged files | Check before staging |
| committed | Files from last commit | Post-commit validation |
Branch Comparison
Compare changes against a specific branch:
# Scan files changed compared to main branch
beaverscan scan . --incremental --git-base-branch main
# Scan files changed compared to develop branch
beaverscan scan . --incremental --git-base-branch developCombining with Baseline Mode
Incremental scanning works seamlessly with baseline mode for maximum efficiency:
# Create baseline on main branch
git checkout main
beaverscan scan . --baseline
# On feature branch: scan only changed files + compare with baseline
git checkout feature/my-feature
beaverscan scan . --incremental --compare-baselineBenefits:
- ⚡ 10-100x faster scans for typical development workflows
- 🎯 Focused feedback on files you're actively working on
- 🔄 Perfect for CI/CD - scan only PR changes
- 💾 Smart caching reduces redundant work
Configuration File
Enable incremental scanning by default:
{
"incremental": true,
"cache": true,
"gitDiffMode": "all"
}CI/CD Integration
Perfect for GitHub Actions, GitLab CI, and other CI/CD platforms:
# .github/workflows/security-scan.yml
- name: Security Scan (Incremental)
run: |
# Scan only files changed in this PR
beaverscan scan . --incremental --git-base-branch ${{ github.base_ref }}Cache Management
Caching is automatically enabled with --incremental:
# View cache stats (use --verbose or check .beaverscan-cache/)
beaverscan scan . --incremental --verbose
# Clear cache when needed
beaverscan scan . --clear-cache
# Disable cache (not recommended)
beaverscan scan . --incremental --no-cacheRequirements
- Git repository required
- Falls back to full scan if not in a git repository
- Cache stored in
.beaverscan-cache/(add to .gitignore)
Performance Comparison
Typical developer workflow (20 changed files out of 5,000):
| Mode | Files Scanned | Time | |------|---------------|------| | Full Scan | 5,000 | ~45 seconds | | Incremental Scan | 20 | ~2 seconds |
Speed improvement: 22x faster ⚡
Custom Rules
BeaverScan allows you to define custom security rules tailored to your project's specific needs. Custom rules can be:
- Pattern-based: Use regular expressions to match code patterns
- AST-based: Use Abstract Syntax Tree analysis for structural code matching
Pattern-Based Custom Rules
Pattern-based rules use regex to find security issues in your code:
{
"customRules": {
"rules": [
{
"id": "no-console-log",
"name": "Console Log Detection",
"description": "Detects console.log statements that should be removed in production",
"message": "Remove console.log statement before deploying to production",
"severity": "low",
"type": "pattern",
"enabled": true,
"pattern": {
"regex": "console\\.log\\(",
"flags": "g"
},
"filePatterns": ["**/*.ts", "**/*.tsx", "**/*.js", "**/*.jsx"],
"excludePatterns": ["**/*.test.ts"],
"fix": "Remove console.log statements or replace with a proper logging framework"
}
]
}
}AST-Based Custom Rules
AST-based rules analyze code structure using Babel's AST parser:
{
"customRules": {
"rules": [
{
"id": "unsafe-eval",
"name": "Unsafe eval() Usage",
"description": "Detects direct eval() calls which can be a security risk",
"message": "Avoid using eval() as it can execute arbitrary code",
"severity": "critical",
"type": "ast",
"enabled": true,
"astCheck": {
"nodeType": "CallExpression",
"conditions": [
{
"property": "callee.name",
"equals": "eval"
}
]
},
"filePatterns": ["**/*.ts", "**/*.js"],
"fix": "Refactor code to avoid eval()"
}
]
}
}Custom Rule Properties
| Property | Type | Required | Description |
|----------|------|----------|-------------|
| id | string | ✅ | Unique identifier for the rule (kebab-case) |
| name | string | ✅ | Human-readable rule name |
| description | string | ✅ | Detailed description of what the rule detects |
| message | string | ✅ | Message shown when rule is violated |
| severity | string | ✅ | Severity level: critical, high, medium, or low |
| type | string | ✅ | Rule type: pattern or ast |
| enabled | boolean | ❌ | Enable/disable rule (default: true) |
| filePatterns | string[] | ❌ | Glob patterns for files to scan (default: all supported files) |
| excludePatterns | string[] | ❌ | Glob patterns for files to exclude |
| fix | string | ❌ | Suggested fix or remediation advice |
Pattern Rule Properties
For type: "pattern" rules:
| Property | Type | Required | Description |
|----------|------|----------|-------------|
| pattern.regex | string | ✅ | Regular expression pattern |
| pattern.flags | string | ❌ | Regex flags: g, i, m, gi, etc. |
AST Rule Properties
For type: "ast" rules:
| Property | Type | Required | Description |
|----------|------|----------|-------------|
| astCheck.nodeType | string | ✅ | Babel AST node type (e.g., CallExpression, Identifier) |
| astCheck.conditions | array | ✅ | Array of conditions to match |
Condition Properties:
property: Dot-notation path to node property (e.g.,callee.name)equals: Exact value matchmatches: Regex pattern match (as string)exists: Boolean - check if property exists
Example Templates
Check the templates/ directory for complete examples:
.beaverscanrc.custom-rules-pattern.json- Pattern-based rules.beaverscanrc.custom-rules-ast.json- AST-based rules.beaverscanrc.custom-rules-full.yml- Comprehensive example
Advanced Configuration
Entropy Detection
BeaverScan uses entropy analysis to detect high-entropy strings that are likely secrets (API keys, tokens, etc.). Customize the detection behavior:
{
"entropyDetection": {
"enabled": true,
"thresholds": {
"base64": 4.5,
"hex": 3.5,
"alphanumeric": 4.0
},
"minLength": 20,
"maxLength": 100,
"whitelist": ["uuid", "timestamp"]
}
}Configuration Options:
enabled(boolean): Enable/disable entropy-based detection (default:true)thresholds(object): Entropy thresholds for different character sets (0-8 bits)base64(number): Threshold for base64 strings (default: 4.5)hex(number): Threshold for hexadecimal strings (default: 3.5)alphanumeric(number): Threshold for alphanumeric strings (default: 4.0)
minLength(number): Minimum string length to analyze (default: 20)maxLength(number): Maximum string length to analyze (default: 100)whitelist(string[]): Pattern names to exclude from detection (default:[])
Example - More Sensitive Detection:
{
"entropyDetection": {
"thresholds": {
"base64": 4.0,
"hex": 3.0,
"alphanumeric": 3.5
},
"minLength": 15
}
}Incremental Scanning & Caching
For faster scans in git repositories, enable incremental mode to scan only changed files:
{
"incremental": true,
"cache": true,
"cachePath": ".beaverscan-cache",
"gitDiffMode": "all",
"gitBaseBranch": "main"
}Configuration Options:
incremental(boolean): Scan only changed files via git diff (default:false)cache(boolean): Cache scan results for faster subsequent scans (default:false, auto-enabled withincremental)cachePath(string): Directory for cache storage (default:.beaverscan-cache)gitDiffMode(string): Which files to scan (default:all)all: All changed files (staged + unstaged + untracked)staged: Only staged filesunstaged: Only unstaged filescommitted: Files from last commit
gitBaseBranch(string): Base branch for comparison (e.g.,main,develop)
Example - CI/CD Configuration:
{
"incremental": true,
"gitDiffMode": "committed",
"gitBaseBranch": "main",
"cache": true
}Configuration Options Reference
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| severity | string | all | Minimum severity to report: all, critical, high, medium, low |
| output | string | terminal | Output format: terminal, json, html, sarif, all |
| reportPath | string | ./beaverscan-report | Directory where reports are saved |
| exclude | string[] | [] | Glob patterns to exclude from scanning |
| ignoreFile | string | - | Path to custom ignore file (alternative to .beaverscanignore) |
| scanners | object | all enabled | Toggle built-in scanners on/off |
| full | boolean | false | Enable full scan mode (slower, more thorough) |
| customRules | object | - | Custom security rules configuration |
| baselineFile | string | .beaverscan-baseline.json | Path to baseline file for comparison mode |
| incremental | boolean | false | Only scan changed files (requires git) |
| cache | boolean | false | Enable result caching (auto-enabled with incremental) |
| cachePath | string | .beaverscan-cache | Custom cache directory path |
| gitDiffMode | string | all | Git diff mode: staged, unstaged, all, committed |
| gitBaseBranch | string | - | Base branch for git diff comparison |
| entropyDetection | object | enabled | Entropy-based secret detection configuration |
GitHub Actions Integration
BeaverScan provides ready-to-use GitHub Actions workflow templates for seamless CI/CD integration.
Quick Start
1. Choose a template:
# Basic scan
cp templates/github-actions/basic-scan.yml .github/workflows/beaverscan.yml
# Baseline comparison (recommended for production)
cp templates/github-actions/baseline-comparison.yml .github/workflows/beaverscan.yml
# SARIF upload to GitHub Security
cp templates/github-actions/sarif-upload.yml .github/workflows/beaverscan.yml2. Commit and push:
git add .github/workflows/beaverscan.yml
git commit -m "ci: add BeaverScan security workflow"
git pushAvailable Workflows
1. Basic Security Scan
Simple scan on every push and PR:
name: BeaverScan
on: [push, pull_request]
jobs:
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
- run: npm install -g @beaverscan/cli
- run: beaverscan scan .2. Baseline Comparison (Recommended)
Track security improvements and fail only on NEW issues:
name: BeaverScan Baseline
on:
push:
branches: [main]
pull_request:
branches: [main]
permissions:
contents: write
jobs:
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- run: npm install -g @beaverscan/cli
# Update baseline on main
- name: Update Baseline
if: github.event_name == 'push'
run: beaverscan scan . --baseline
# Compare on PRs
- name: Compare with Baseline
if: github.event_name == 'pull_request'
run: beaverscan scan . --compare-baseline3. SARIF Upload to GitHub Security
Integrate with GitHub Advanced Security:
name: BeaverScan SARIF
on: [push, pull_request]
permissions:
security-events: write
jobs:
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- run: npm install -g @beaverscan/cli
- run: beaverscan scan . --output sarif
- name: Upload SARIF
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: beaverscan-report-*.sarifPre-built Workflows
This repository includes production-ready workflows in .github/workflows/:
- beaverscan-security.yml - Main workflow with baseline + SARIF
- beaverscan-reports.yml - Multi-format reports with artifacts
- beaverscan-scheduled.yml - Weekly security audit
Template Directory
All templates are available in templates/github-actions/:
| Template | Description | Best For |
|----------|-------------|----------|
| basic-scan.yml | Simple security scan | Getting started |
| baseline-comparison.yml | Baseline tracking | Production repos |
| sarif-upload.yml | GitHub Security integration | Advanced Security users |
Full documentation: See templates/github-actions/README.md
Features
✅ Baseline Comparison: Track security improvements, fail only on new issues ✅ SARIF Integration: Upload to GitHub Security tab ✅ Auto-commit: Automatically update baseline on main branch ✅ PR Comments: Post scan results on pull requests ✅ Scheduled Scans: Weekly security audits ✅ Multi-format Reports: HTML, JSON, SARIF artifacts
Best Practices
- Use baseline comparison for production workflows
- Upload SARIF to GitHub Security tab
- Run on PRs to catch issues early
- Update baseline after fixing issues
- Enable scheduled scans for continuous monitoring
GitLab CI Integration
BeaverScan provides ready-to-use GitLab CI pipeline templates for seamless integration with GitLab CI/CD.
Quick Start
1. Choose a template:
# Basic scan
cp templates/gitlab-ci/.gitlab-ci-basic.yml .gitlab-ci.yml
# Baseline comparison (recommended for production)
cp templates/gitlab-ci/baseline-comparison.gitlab-ci.yml .gitlab-ci.yml
# Security Dashboard integration
cp templates/gitlab-ci/security-dashboard.gitlab-ci.yml .gitlab-ci.yml
# Incremental scan (fastest, for large repos)
cp templates/gitlab-ci/incremental-scan.gitlab-ci.yml .gitlab-ci.yml2. Configure CI/CD permissions (for baseline templates):
- Go to Settings → CI/CD → Token permissions
- Enable "Allow CI job tokens to push to repository"
3. Commit and push:
git add .gitlab-ci.yml
git commit -m "ci: add BeaverScan security pipeline"
git pushAvailable Pipelines
1. Basic Security Scan
Simple scan on every push and merge request:
image: node:20
stages:
- security
beaverscan-scan:
stage: security
script:
- npm install -g @beaverscan/cli
- beaverscan scan .
artifacts:
paths:
- beaverscan-report-*
expire_in: 7 days2. Baseline Comparison (Recommended)
Track security improvements and fail only on NEW issues:
image: node:20
stages:
- security
- update-baseline
beaverscan-scan:
stage: security
script:
- npm install -g @beaverscan/cli
- |
if [ "$CI_COMMIT_BRANCH" = "$CI_DEFAULT_BRANCH" ]; then
beaverscan scan . --baseline
else
beaverscan scan . --compare-baseline
fi3. Security Dashboard Integration
Upload to GitLab Security Dashboard:
beaverscan-sast:
stage: security
script:
- npm install -g @beaverscan/cli
- beaverscan scan . --output sarif
artifacts:
reports:
sast: beaverscan-report-*.sarif4. Incremental Scan (Fastest)
Only scan changed files (10-100x faster):
beaverscan-incremental:
stage: security
script:
- npm install -g @beaverscan/cli
- |
if [ "$CI_PIPELINE_SOURCE" = "merge_request_event" ]; then
beaverscan scan . \
--incremental \
--git-base-branch origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME \
--compare-baseline \
--cache
fiTemplate Directory
All templates are available in templates/gitlab-ci/:
| Template | Description | Best For |
|----------|-------------|----------|
| .gitlab-ci-basic.yml | Simple security scan | Getting started |
| baseline-comparison.gitlab-ci.yml | Baseline tracking | Production repos |
| security-dashboard.gitlab-ci.yml | Security Dashboard integration | GitLab Ultimate users |
| incremental-scan.gitlab-ci.yml | Fast incremental scanning | Large repositories |
Full documentation: See templates/gitlab-ci/README.md
Features
✅ Baseline Comparison: Track security improvements, fail only on new issues ✅ Security Dashboard: Upload to GitLab Security & Compliance ✅ Incremental Scanning: 10-100x faster scans on changed files only ✅ Auto-commit: Automatically update baseline on main branch ✅ Cache Support: Ultra-fast subsequent scans ✅ Scheduled Pipelines: Weekly security audits
Best Practices
- Use baseline comparison for production pipelines
- Enable incremental scanning for faster feedback
- Upload SARIF to Security Dashboard (GitLab Ultimate)
- Run on MRs to catch issues early
- Update baseline after fixing issues
- Configure scheduled pipelines for continuous monitoring
Git Hooks
Install pre-commit hooks to automatically scan staged files before allowing commits. Perfect for catching security issues during development.
Quick Start
Install basic pre-commit hook:
beaverscan install-hook pre-commitInstall baseline comparison hook (recommended for legacy codebases):
# Create baseline first
beaverscan scan . --baseline
# Install hook
beaverscan install-hook pre-commit-baselineAvailable Hooks
1. Pre-Commit Hook
Blocks commits with critical/high severity issues:
# Install
beaverscan install-hook pre-commit
# Test (will block if issues found)
git add .
git commit -m "your changes"Features:
- ✅ Scans staged files only (ultra-fast)
- ✅ Blocks commits with critical/high issues
- ✅ Uses incremental scanning + caching
- ✅ Zero dependencies (native git hooks)
2. Pre-Commit Baseline Hook
Only blocks NEW critical/high severity issues:
# Install
beaverscan install-hook pre-commit-baseline
# Test
git add .
git commit -m "your changes"Features:
- ✅ All features of basic pre-commit hook
- ✅ Baseline comparison (allows existing issues)
- ✅ Perfect for gradual security improvements
- ✅ Ideal for legacy codebases
Hook Behavior
What happens during pre-commit:
- Detection: Hook detects staged files
- Scanning: Runs incremental scan on staged files only
- Evaluation: Checks for critical/high severity issues
- Decision:
- ✅ No issues or low/medium only → Commit proceeds
- ❌ Critical/high issues found → Commit blocked
Performance:
- Full repository scan: ~45 seconds (5000 files)
- Incremental scan (staged files): ~2 seconds (20 files)
- Speed improvement: 22x faster!
Bypass Hook (Emergency Only)
# Skip hook if absolutely necessary
git commit --no-verify -m "emergency fix"Warning: Only use --no-verify when absolutely necessary.
Manual Installation
If you prefer manual installation:
# Copy hook file
cp templates/git-hooks/pre-commit .git/hooks/pre-commit
# Make executable
chmod +x .git/hooks/pre-commitTemplate Directory
All templates are available in templates/git-hooks/:
| Template | Description | Best For |
|----------|-------------|----------|
| pre-commit | Basic pre-commit hook | New projects, strict security |
| pre-commit-baseline | Baseline comparison hook | Legacy code, gradual improvement |
| install-hook.sh | Manual installation script | Advanced users |
Full documentation: See templates/git-hooks/README.md
Best Practices
Choose the right hook:
- Use
pre-commitfor new projects with zero tolerance - Use
pre-commit-baselinefor legacy codebases
- Use
Team setup:
- Create baseline on main branch
- All developers install same hook
- Update baseline as issues are fixed
Combine with CI/CD:
- Pre-commit hook: Fast feedback during development
- CI/CD pipeline: Complete scan on push/PR
Keep hooks updated:
beaverscan install-hook pre-commit # Reinstalls latest version
Command Reference
scan <path>
Scan code for security vulnerabilities.
Arguments:
<path>- Path to scan (directory or file)
Options:
-c, --config <path>- Path to configuration file-o, --output <format>- Output format:terminal,json,html,sarif, orall(default:terminal)-s, --severity <level>- Filter by severity:all,critical,high,medium,low(default:all)-e, --exclude <patterns...>- Glob patterns to exclude from scanning-i, --ignore-file <path>- Path to ignore file (alternative to.beaverscanignore)-r, --report-path <path>- Directory to save reports--full- Run full scan (slower but more thorough)
version
Display version information.
Security Checks
1. Secrets Scanner
Detects 52+ types of exposed secrets across all major platforms and services.
Cloud Providers (9)
- AWS (Access Keys, Secret Keys)
- Google Cloud & Firebase
- Azure (Connection Strings)
- Cloudflare, DigitalOcean, Linode, Vercel
Payment & E-commerce (6)
- Stripe (Secret & Publishable Keys)
- Shopify, Square, PayPal, Plaid
Communication (8)
- Slack, Twilio, SendGrid
- Discord, Telegram, Intercom, Mailchimp
Version Control (4)
- GitHub, GitLab, Bitbucket, Gitea
CI/CD & DevOps (6)
- CircleCI, Travis CI, Jenkins
- Docker Hub, NPM, PyPI
Authentication & Identity (6)
- Auth0, Okta, Clerk, Supabase
- OAuth tokens, JWT tokens
APM & Monitoring (4)
- Datadog, New Relic, Sentry
Search & Data (4)
- Algolia, Elasticsearch, MongoDB Atlas
Hosting Platforms (4)
- Heroku, Railway, Render, Fly.io
AI & ML Services (4)
- OpenAI, Anthropic, Mapbox, Replicate
Generic Patterns (3)
- Private Keys (RSA, EC, DSA)
- Generic API Keys
- Hardcoded Passwords
- Database URLs with credentials
Example Output:
🔴 Critical Issues (3)
└─ OpenAI API Key found
src/config/openai.ts:5
const API_KEY = "sk-****************"
💡 Fix: Revoke OpenAI API key and create new one. Use environment variables
└─ AWS Access Key ID found
src/config/aws.ts:12
const AWS_KEY = "AKIA****************"
💡 Fix: Rotate AWS credentials immediately and use environment variables
└─ Stripe Secret API Key found
src/config/stripe.ts:3
const stripeKey = "sk_live_****************"
💡 Fix: Revoke Stripe secret key from dashboard. Use environment variables📚 Complete Pattern List: See SECRET_PATTERNS.md for all 52+ patterns
Entropy-Based Detection 🧠
In addition to pattern matching, BeaverScan uses intelligent entropy analysis to detect high-entropy strings that are likely secrets, even without specific patterns.
How it works:
- Calculates Shannon entropy for suspicious strings
- Detects base64, hexadecimal, and alphanumeric secrets
- Context-aware analysis (checks variable names like
apiKey,secret,token) - Smart filtering to avoid false positives (UUIDs, timestamps, git SHAs)
Configuration Example (.beaverscanrc.json):
{
"entropyDetection": {
"enabled": true,
"thresholds": {
"base64": 4.5,
"hex": 3.5,
"alphanumeric": 4.0
},
"minLength": 20,
"maxLength": 100,
"whitelist": []
}
}Example Detection:
// ✅ Detected (high entropy + context)
const apiSecret = "Xk7pQ9mL2vN8jR4tY6wZ1sA3dF5gH";
// ✅ Detected (very high entropy)
const token = "a8f3e7b2c9d1f4e6a5b8c7d2e9f1a3b4c5d6e7f8";
// ❌ Skipped (UUID pattern)
const id = "550e8400-e29b-41d4-a716-446655440000";Benefits:
- Catches secrets without specific patterns
- Complements regex-based detection
- Configurable thresholds per charset type
- Low false positive rate
2. Injection Scanner
Detects injection vulnerabilities:
- SQL Injection: String concatenation in database queries
- XSS (Cross-Site Scripting): Unsafe use of
innerHTML,dangerouslySetInnerHTML - Command Injection: Unsafe command execution with user input
Example Output:
🔴 Critical Issues (1)
└─ Potential SQL injection: Query built with string concatenation
src/api/users.ts:45
const query = "SELECT * FROM users WHERE id = " + userId
💡 Fix: Use parameterized queries or prepared statements3. Bad Practices Scanner
Identifies insecure coding practices:
eval()andFunction()constructor usagedocument.write()anddocument.writeln()- Insecure cookie settings (missing Secure/HttpOnly flags)
- Wildcard CORS configurations (
*) - Security-disabling comments (
eslint-disable security,@ts-ignore)
Example Output:
🟠 High Issues (1)
└─ Dangerous function: eval() can execute arbitrary code
src/utils/parser.ts:23
eval(userInput)
💡 Fix: Avoid using eval(). Use safer alternatives like JSON.parse()4. Dependency Scanner
Checks for vulnerable npm packages:
- Runs
npm auditto detect known CVEs - Identifies vulnerable dependencies
- Provides fix recommendations
- Shows severity levels and CVE numbers
Example Output:
📦 Dependencies (3 vulnerable)
└─ [email protected] - Prototype Pollution (CVE-2020-8203)
package.json:1
💡 Fix: Update lodash to 4.17.21 or higherScoring System
BeaverScan assigns a security score from 0-100 based on detected issues:
- Critical issues: -30 points each
- High issues: -20 points each
- Medium issues: -10 points each
- Low issues: -5 points each
Grade Scale
- A: 90-100 (Excellent)
- B: 80-89 (Good)
- C: 70-79 (Fair)
- D: 60-69 (Poor)
- E: 50-59 (Very Poor)
- F: 0-49 (Critical)
License
MIT
