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
Maintainers
Readme
🔐 API Key Guard
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 --verboseFix 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-backupGit Hooks Setup
# Install pre-commit hook
api-key-guard setup-hooksAI 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-guardVerify 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
- Get API key from Google AI Studio
- 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:
- Scans staged files for API keys
- Blocks commits if leaks are detected
- Provides clear feedback on detected patterns
- Allows bypass with
--no-verifyif 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
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature - Commit changes:
git commit -m 'Add amazing feature' - Push to branch:
git push origin feature/amazing-feature - 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.jsVerbose output (shows more details about detection):
api-key-guard scan . --verboseFail on leak (exit with a non-zero code if leaks are found, useful for CI/CD):
api-key-guard scan . --fail-on-leakInclude 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 .gitignoreCombine 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-hooksThis 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-pushThis 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:
- You have
api-key-guardpre-commit hook enabled. - You accidentally add a file containing a hardcoded API key:
// src/config.js const API_KEY = "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // BAD PRACTICE! - You stage the file:
git add src/config.js - You try to commit:
git commit -m "Add new config" api-key-guardwill 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 aname,regex, anddescription.failOnLeak: Boolean. Iftrue, the CLI will exit with a non-zero code if any leaks are found.verbose: Boolean. Iftrue, 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
.envfiles 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-guardscans 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.
- Report Bugs: If you find a bug, please open an issue on GitHub, providing detailed steps to reproduce, expected behavior, and actual behavior.
- Suggest Features: Have an idea for a new feature or improvement? Open an issue to discuss it.
- Code Contributions:
- Fork the repository.
- Create a new branch (
git checkout -b feature/your-feature-nameorfix/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
mainbranch 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.
