npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

api-key-guard

v1.1.3

Published

A comprehensive tool to detect, prevent, and manage API key leaks in your codebase with AI-powered README generation

Readme

🔐 API Key Guard

npm version npm downloads License: MIT

A comprehensive CLI tool for detecting, preventing, and managing API key leaks in your codebase with AI-powered documentation generation.

⚡ Quick Start

# Install globally
npm install -g api-key-guard

# Scan for API key leaks
api-key-guard scan

# Setup git hooks for automatic scanning
api-key-guard setup-hooks

# Generate AI-powered README (requires GEMINI_API_KEY)
export GEMINI_API_KEY=your_api_key_here
api-key-guard readme

🚨 The Problem

API key leaks in code repositories are a critical security vulnerability that can lead to:

  • Data breaches and unauthorized access
  • Financial losses from misused cloud resources
  • Service disruptions and security incidents
  • Reputational damage from exposed credentials

✨ Features

  • 🔍 Smart Detection: Advanced regex patterns detect AWS keys, GitHub tokens, Google API keys, and more
  • Auto-Fix Keys: Automatically replace hardcoded keys with environment variables
  • �🔒 Git Hooks Integration: Automatic pre-commit scanning to prevent leaks
  • 🤖 AI-Powered README: Generate professional documentation using Google's Gemini API
  • Fast Scanning: Efficient file parsing with configurable ignore patterns
  • 🌈 Clear Output: Color-coded results with detailed reporting
  • 📋 Multiple Formats: Support for JS, TS, Python, JSON, YAML, ENV files, and more

📋 CLI Commands

Scan for API Keys

# Scan current directory
api-key-guard scan

# Scan specific path
api-key-guard scan --path ./src

# Verbose output with pattern details
api-key-guard scan --verbose

Fix Hardcoded Keys

# Automatically fix hardcoded API keys
api-key-guard fix

# Preview fixes without applying
api-key-guard fix --dry-run

# Fix specific file only
api-key-guard fix --file src/config.js

# Fix without creating backups
api-key-guard fix --no-backup

Git Hooks Setup

# Install pre-commit hook
api-key-guard setup-hooks

AI README Generation

# Generate README.md
api-key-guard readme

# Force overwrite existing file
api-key-guard readme --force

# Custom output file
api-key-guard readme --output DOCUMENTATION.md

🛠️ Installation

Prerequisites: Node.js 14+ and npm

# Global installation (recommended)
npm install -g api-key-guard

# Local project installation
npm install --save-dev api-key-guard

Verify installation:

api-key-guard --version

🔑 API Key Types Detected

  • AWS Access Keys: AKIA...
  • GitHub Tokens: ghp_..., github_pat_...
  • Google API Keys: AIza...
  • Generic Patterns: api_key, secret_key, access_token
  • Bearer Tokens: Bearer ...
  • Custom Patterns: High-entropy strings

🤖 AI README Generation

The readme command uses Google's Gemini API to generate comprehensive documentation:

Setup

  1. Get API key from Google AI Studio
  2. Set environment variable:
    export GEMINI_API_KEY=your_api_key_here

Generated Content

  • Project overview and description
  • Installation instructions
  • Usage examples and CLI documentation
  • Security best practices
  • Contributing guidelines

⚙️ Configuration

Create .api-key-guard.json in your project root:

{
  "ignorePatterns": [
    "node_modules/**",
    "dist/**",
    "*.min.js",
    "test/**/*.fixture.js"
  ],
  "customPatterns": [
    {
      "name": "Custom API Key",
      "pattern": "custom_key_[0-9a-f]{32}"
    }
  ]
}

🔐 Git Hooks

The setup-hooks command creates a pre-commit hook that:

  1. Scans staged files for API keys
  2. Blocks commits if leaks are detected
  3. Provides clear feedback on detected patterns
  4. Allows bypass with --no-verify if needed

🛡️ Security Features

  • Zero Storage: API keys are never stored or logged
  • Environment Variables: Secure handling of authentication tokens
  • Pattern Matching: Regular expressions detect common key formats
  • Entropy Analysis: Identifies high-entropy strings that may be secrets
  • Configurable Scanning: Customize patterns and ignore rules

📊 Usage Examples

Basic Scanning:

api-key-guard scan
# ✅ No potential API key leaks detected!

With API Key Detection:

api-key-guard scan --verbose
# 🚨 Found 2 potential API key leak(s):
#   📄 src/config.js:15
#      Pattern: AKIA1234567890ABCDEF
#   📄 .env.example:3  
#      Pattern: sk-1234567890abcdef...

Automatic Key Fixing:

api-key-guard fix --dry-run
# 📋 Found 3 fixable API key(s):
#   📄 src/config.js:15
#     const apiKey = "sk-1234567890abcdef"
#     → const apiKey = process.env.API_KEY
#   
#   📄 src/auth.js:8
#     const token = "ghp_abcdefghijklmnop"
#     → const token = process.env.GITHUB_TOKEN

# Apply fixes
api-key-guard fix
# 🔧 Applying fixes...
# ✅ Successfully fixed 3 API keys!
# 📝 Updated 2 file(s)
# 🔐 Added 3 environment variable(s)

🤝 Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Commit changes: git commit -m 'Add amazing feature'
  4. Push to branch: git push origin feature/amazing-feature
  5. Open a Pull Request

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙋‍♂️ Support


Made with ❤️ for developer security npm install --save-dev api-key-guard


## 🚀 CLI Usage Examples

`api-key-guard` provides several commands for different use cases.

### 🔍 `api-key-guard scan` - Detect API Keys

Scans your project for potential API key leaks.

**Basic Scan (current directory):**

```bash
api-key-guard scan .

Scan a specific directory:

api-key-guard scan src/

Scan a specific file:

api-key-guard scan config/secrets.js

Verbose output (shows more details about detection):

api-key-guard scan . --verbose

Fail on leak (exit with a non-zero code if leaks are found, useful for CI/CD):

api-key-guard scan . --fail-on-leak

Include specific file types (comma-separated):

api-key-guard scan . --include "*.js,*.ts,*.env"

Exclude specific file types (comma-separated):

api-key-guard scan . --exclude "*.min.js,*.lock"

Ignore files or directories using patterns (shell-like glob patterns):

api-key-guard scan . --ignore-pattern "node_modules/**" --ignore-pattern "dist/*"

Use a .gitignore file for ignore patterns:

api-key-guard scan . --ignore-file .gitignore

Combine options:

api-key-guard scan src/ --fail-on-leak --verbose --ignore-file .gitignore --include "*.js,*.ts"

🎣 api-key-guard setup-hooks - Integrate Git Hooks

Sets up Git pre-commit and/or pre-push hooks to automatically scan for keys before commits or pushes.

Set up pre-commit hook (default):

api-key-guard setup-hooks

This will configure your local .git/hooks/pre-commit script to run api-key-guard scan --fail-on-leak on staged files.

Set up pre-push hook:

api-key-guard setup-hooks --hook pre-push

This will configure your local .git/hooks/pre-push script to run api-key-guard scan --fail-on-leak on all changes being pushed.

Remove existing hooks (if you need to clean up):

api-key-guard setup-hooks --remove

📝 api-key-guard readme - Generate READMEs with AI

Leverages AI to help you generate a professional README.md for your project. (Requires an active internet connection and potentially an API key for the AI service, configured via environment variables).

Generate a README with a prompt:

api-key-guard readme "Generate a README for a Node.js CLI tool that detects API keys, focusing on its security benefits and ease of use."

Generate and save to a specific file:

api-key-guard readme --output docs/PROJECT_README.md "Generate a simple README for a web application using React and Node.js."

🎣 Git Hooks Usage

Once you've set up Git hooks using api-key-guard setup-hooks, the tool will automatically run during your git commit or git push operations.

Example of a pre-commit hook in action:

  1. You have api-key-guard pre-commit hook enabled.
  2. You accidentally add a file containing a hardcoded API key:
    // src/config.js
    const API_KEY = "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // BAD PRACTICE!
  3. You stage the file:
    git add src/config.js
  4. You try to commit:
    git commit -m "Add new config"
  5. api-key-guard will detect the leak, prevent the commit, and display a warning:
    🚨 api-key-guard: Potential API key leak detected in staged files! 🚨
    Path: src/config.js
    Line 2: const API_KEY = "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
        
    Commit aborted. Please remove or secure the sensitive information.
    If you need to bypass, use 'git commit --no-verify'.

To bypass the hook for a single commit (use with extreme caution!):

git commit -m "Temporary commit, will fix secrets later" --no-verify

⚙️ Configuration

api-key-guard can be configured using a api-key-guard.config.json file at the root of your project. This allows you to define custom rules, ignore patterns, and scanner settings.

Example api-key-guard.config.json:

{
  "scanPaths": [
    "src/",
    "config/",
    "server/"
  ],
  "ignorePatterns": [
    "node_modules/**",
    "dist/**",
    "*.min.js",
    "*.log",
    "testdata/**"
  ],
  "ignoreFiles": [
    ".gitignore",
    ".dockerignore"
  ],
  "includeFileTypes": [
    "*.js",
    "*.ts",
    "*.env",
    "*.json",
    "*.yaml",
    "*.yml"
  ],
  "excludeFileTypes": [
    "*.lock",
    "package-lock.json"
  ],
  "customRules": [
    {
      "name": "Custom-API-Key",
      "regex": "MY_CUSTOM_API_KEY_[a-zA-Z0-9]{32,64}",
      "description": "Detects specific internal API keys."
    }
  ],
  "failOnLeak": true,
  "verbose": false
}
  • scanPaths: An array of glob patterns for directories or files to explicitly scan. If empty, the current directory (.) is scanned.
  • ignorePatterns: An array of glob patterns for files or directories to ignore during scanning.
  • ignoreFiles: An array of filenames (e.g., .gitignore) whose contents will be used as additional ignore patterns.
  • includeFileTypes: An array of glob patterns for file types to explicitly include. If specified, only these types will be scanned.
  • excludeFileTypes: An array of glob patterns for file types to explicitly exclude.
  • customRules: An array of custom regex rules for detecting specific patterns. Each rule should have a name, regex, and description.
  • failOnLeak: Boolean. If true, the CLI will exit with a non-zero code if any leaks are found.
  • verbose: Boolean. If true, more detailed output will be provided.

🔒 Security Best Practices

While api-key-guard is a powerful tool, it's part of a broader security strategy. Always adhere to these best practices:

  • 🚫 Never Hardcode Secrets: The golden rule. Avoid placing API keys, passwords, or sensitive tokens directly in your code.
  • 🌳 Use Environment Variables: For development and deployment, load secrets from environment variables (e.g., using .env files locally and proper environment variable injection in production).
  • 🔐 Employ Secret Management Services: For production environments, utilize dedicated secret management services like AWS Secrets Manager, Azure Key Vault, Google Secret Manager, HashiCorp Vault, or similar.
  • 🔑 Implement Least Privilege: Grant API keys only the minimum necessary permissions required for their function.
  • 🔄 Rotate Keys Regularly: Periodically change your API keys, especially if they are long-lived.
  • 📚 Educate Your Team: Ensure all developers understand the risks of secret exposure and the proper procedures for handling sensitive information.
  • ⚙️ Integrate into CI/CD: Incorporate api-key-guard scans into your Continuous Integration/Continuous Deployment pipelines to catch leaks before deployment.

api-key-guard helps you catch mistakes, but proactive secure coding practices are paramount.

🛣️ Future Roadmap

We are continuously working to enhance api-key-guard. Here are some planned features:

  • Advanced Entropy Analysis: Improve detection of generic high-entropy strings that might indicate secrets without specific patterns.
  • Machine Learning-Based Detection: Explore ML models for more intelligent and adaptive secret detection.
  • Cloud Provider Integrations: Direct integrations with AWS, Azure, GCP for scanning cloud-specific credential formats.
  • Reporting & Alerting: Generate detailed reports and integrate with alerting systems (e.g., Slack, email) when leaks are detected in CI/CD.
  • Support for More Secret Types: Expand detection to include private keys, database connection strings, access tokens, etc.
  • IDE Extensions: Develop extensions for popular IDEs (VS Code, IntelliJ) for real-time feedback.
  • Web UI for Centralized Management: A future goal for larger teams to manage configurations and view scan results centrally.

🤝 Contributing

We welcome contributions to api-key-guard! Whether it's bug reports, feature requests, or code contributions, your help is valuable.

  1. Report Bugs: If you find a bug, please open an issue on GitHub, providing detailed steps to reproduce, expected behavior, and actual behavior.
  2. Suggest Features: Have an idea for a new feature or improvement? Open an issue to discuss it.
  3. Code Contributions:
    • Fork the repository.
    • Create a new branch (git checkout -b feature/your-feature-name or fix/bug-fix-description).
    • Make your changes.
    • Write tests for your changes.
    • Ensure your code adheres to the project's coding style.
    • Commit your changes (git commit -m "feat: Add new feature") using conventional commits.
    • Push to your fork (git push origin feature/your-feature-name).
    • Open a Pull Request to the main branch of the original repository.

Please adhere to our Code of Conduct.

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.