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


A comprehensive CLI tool for detecting, preventing, and managing API key leaks in your codebase with AI-powered documentation generation.
``bashInstall globally
npm install -g api-key-guard
🚨 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
$3
`bash
Scan current directory
api-key-guard scanScan specific path
api-key-guard scan --path ./srcVerbose output with pattern details
api-key-guard scan --verbose
`$3
`bash
Automatically fix hardcoded API keys
api-key-guard fixPreview fixes without applying
api-key-guard fix --dry-runFix specific file only
api-key-guard fix --file src/config.jsFix without creating backups
api-key-guard fix --no-backup
`$3
`bash
Install pre-commit hook
api-key-guard setup-hooks
`$3
`bash
Generate README.md
api-key-guard readmeForce overwrite existing file
api-key-guard readme --forceCustom output file
api-key-guard readme --output DOCUMENTATION.md
`🛠️ Installation
Prerequisites: Node.js 14+ and npm
`bash
Global installation (recommended)
npm install -g api-key-guardLocal project installation
npm install --save-dev api-key-guard
`Verify installation:
`bash
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:$3
1. Get API key from Google AI Studio
2. Set environment variable:
`bash
export GEMINI_API_KEY=your_api_key_here
`$3
- 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:`json
{
"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:
`bash
api-key-guard scan
✅ No potential API key leaks detected!
`With API Key Detection:
`bash
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:
`bash
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
- 📖 Documentation
- 🐛 Report Issues
- 💬 Discussions
---
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.$3
Scans your project for potential API key leaks.
Basic Scan (current directory):
`bash
api-key-guard scan .
`Scan a specific directory:
`bash
api-key-guard scan src/
`Scan a specific file:
`bash
api-key-guard scan config/secrets.js
`Verbose output (shows more details about detection):
`bash
api-key-guard scan . --verbose
`Fail on leak (exit with a non-zero code if leaks are found, useful for CI/CD):
`bash
api-key-guard scan . --fail-on-leak
`Include specific file types (comma-separated):
`bash
api-key-guard scan . --include ".js,.ts,*.env"
`Exclude specific file types (comma-separated):
`bash
api-key-guard scan . --exclude ".min.js,.lock"
`Ignore files or directories using patterns (shell-like glob patterns):
`bash
api-key-guard scan . --ignore-pattern "node_modules/*" --ignore-pattern "dist/"
`Use a
.gitignore file for ignore patterns:`bash
api-key-guard scan . --ignore-file .gitignore
`Combine options:
`bash
api-key-guard scan src/ --fail-on-leak --verbose --ignore-file .gitignore --include ".js,.ts"
`$3
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):
`bash
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:
`bash
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):
`bash
api-key-guard setup-hooks --remove
`$3
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:
`bash
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:
`bash
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:
`javascript
// src/config.js
const API_KEY = "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // BAD PRACTICE!
`
3. You stage the file:
`bash
git add src/config.js
`
4. You try to commit:
`bash
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!):
`bash
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:`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.
``