{"id":34549483,"url":"https://github.com/686f6c61/hardcoded-api-key-detector","last_synced_at":"2026-04-29T21:35:18.637Z","repository":{"id":328815805,"uuid":"1116858367","full_name":"686f6c61/hardcoded-api-key-detector","owner":"686f6c61","description":"Comprehensive security tool to detect hardcoded API keys, secrets, and credentials in your codebase","archived":false,"fork":false,"pushed_at":"2026-04-06T01:23:42.000Z","size":337,"stargazers_count":0,"open_issues_count":2,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-04-06T01:27:50.233Z","etag":null,"topics":["api-key","npm-package","npmjs","security-tools","typescript"],"latest_commit_sha":null,"homepage":"https://hardcoded-api-key-detector.686f6c61.dev","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/686f6c61.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-12-15T13:34:54.000Z","updated_at":"2026-04-05T23:40:03.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/686f6c61/hardcoded-api-key-detector","commit_stats":null,"previous_names":["686f6c61/hardcoded-api-key-detector"],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/686f6c61/hardcoded-api-key-detector","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/686f6c61%2Fhardcoded-api-key-detector","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/686f6c61%2Fhardcoded-api-key-detector/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/686f6c61%2Fhardcoded-api-key-detector/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/686f6c61%2Fhardcoded-api-key-detector/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/686f6c61","download_url":"https://codeload.github.com/686f6c61/hardcoded-api-key-detector/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/686f6c61%2Fhardcoded-api-key-detector/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32445541,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-29T20:22:27.477Z","status":"ssl_error","status_checked_at":"2026-04-29T20:22:26.507Z","response_time":110,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api-key","npm-package","npmjs","security-tools","typescript"],"created_at":"2025-12-24T07:45:56.850Z","updated_at":"2026-04-29T21:35:18.631Z","avatar_url":"https://github.com/686f6c61.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Hardcoded API Key Detector\n\n[![npm version](https://img.shields.io/npm/v/hardcoded-api-key-detector.svg)](https://www.npmjs.com/package/hardcoded-api-key-detector)\n[![npm downloads](https://img.shields.io/npm/dm/hardcoded-api-key-detector.svg)](https://www.npmjs.com/package/hardcoded-api-key-detector)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![Node Version](https://img.shields.io/node/v/hardcoded-api-key-detector.svg)](https://nodejs.org)\n[![GitHub issues](https://img.shields.io/github/issues/686f6c61/hardcoded-api-key-detector.svg)](https://github.com/686f6c61/hardcoded-api-key-detector/issues)\n\n**[View Documentation \u0026 Examples →](https://hardcoded-api-key-detector.686f6c61.dev)**\n\nA comprehensive and high-performance Node.js security tool designed to detect hardcoded API keys, tokens, and sensitive credentials in your codebase before they reach production. With 245 detection patterns covering major cloud providers, AI platforms, databases, payment services, and development tools, plus advanced features like entropy analysis, baseline filtering, and inline ignore comments, this tool helps prevent accidental credential exposure that could lead to security breaches and financial loss.\n\n## Why Use This Tool\n\nHardcoded credentials are one of the most common security vulnerabilities in modern software development. According to security research, thousands of API keys and secrets are accidentally committed to public repositories every day, leading to unauthorized access, data breaches, and compromised systems. This tool provides an automated, fast, and accurate way to detect these vulnerabilities before they become a problem.\n\n**Key Benefits:**\n- **Prevent Security Breaches**: Detect hardcoded credentials before they reach your repository\n- **Save Time and Money**: Automated scanning is faster and more reliable than manual code review\n- **Comprehensive Coverage**: 245 patterns covering AI platforms, cloud providers, databases, and more\n- **High Accuracy**: Context-aware detection reduces false positives to less than 10%\n- **CI/CD Integration**: Works seamlessly with GitHub Actions, GitLab CI, Jenkins, and other platforms\n- **Developer Friendly**: Simple installation and configuration with minimal setup required\n\n## Features\n\n**Extensive Detection Coverage**\n\nThe tool includes 245 carefully crafted detection patterns that identify credentials from major service providers. Patterns are continuously updated and maintained by the community to ensure coverage of the latest services and credential formats.\n\n**Context-Aware Pattern Matching**\n\nUnlike simple regex-based tools, this detector uses context-aware patterns that look for variable names and assignment patterns in addition to credential formats. This approach dramatically reduces false positives while maintaining high detection accuracy. For example, it distinguishes between actual API keys and random strings that happen to match credential formats.\n\n**Multiple Output Formats**\n\nGenerate reports in various formats to suit your workflow: console output for quick feedback, JSON for programmatic processing, HTML for comprehensive reporting, CSV for data analysis, TXT for simple text-based sharing, and JUnit XML for CI/CD integration. Each format provides detailed information about detected credentials including file location, line number, severity level, and service identification.\n\n**Performance Optimized**\n\nThe tool supports parallel processing with worker threads for scanning large codebases efficiently. Stream-based analysis handles large files without excessive memory usage. A typical scan of a medium-sized project (1000 files) completes in under 10 seconds.\n\n**Git Integration**\n\nAutomatic pre-commit hooks prevent credentials from being committed to your repository. The hooks scan staged files and block commits if high-severity issues are detected, providing immediate feedback to developers before code is pushed.\n\n**Customizable Configuration**\n\nTailor the tool to your specific needs with flexible configuration options. Exclude test files or specific directories, set minimum severity thresholds, disable patterns that cause false positives in your codebase, and add custom patterns for proprietary services.\n\n**Zero Dependencies for Runtime**\n\nThe core scanning engine has minimal runtime dependencies, making it lightweight and fast. All detection patterns are stored in JSON format, making them easy to read, modify, and contribute to.\n\n**Advanced False Positive Reduction**\n\nThree powerful mechanisms work together to dramatically reduce false positives:\n\nBaseline/Ignore File: Generate a baseline of known findings and filter them from future scans. Review and mark findings as accepted risk, preventing alert fatigue from recurring issues. SHA-256 hashing ensures findings are tracked accurately even across file modifications.\n\nInline Ignore Comments: Use ESLint-style comments to suppress specific findings directly in your source code. Supports single-line ignores, next-line ignores, and block-level disabling for complete control over what gets flagged.\n\nEntropy Detection: Shannon entropy analysis identifies high-randomness strings that are more likely to be secrets. Generic patterns can be configured to only report matches with high entropy, filtering out common variable names and test data.\n\n**Baseline Management**\n\nGenerate and maintain baselines of known findings to focus on new issues. Each finding is hashed to track it uniquely across code changes. Mark findings as reviewed with reason and reviewer information for audit trails. Baseline files can be committed to version control to share accepted risks across teams.\n\n## Installation\n\n### Global Installation\n\nInstall the tool globally to use it across all your projects:\n\n```bash\nnpm install -g hardcoded-api-key-detector\n```\n\nAfter global installation, the `hardcoded-detector` command will be available system-wide.\n\n### Local Installation (Recommended for Projects)\n\nInstall as a development dependency in your project:\n\n```bash\nnpm install --save-dev hardcoded-api-key-detector\n```\n\nThis approach ensures consistent versions across your team and allows you to configure the tool specifically for your project.\n\n### Using npx (No Installation Required)\n\nRun the tool without installing it:\n\n```bash\nnpx hardcoded-api-key-detector scan\n```\n\nThis is useful for one-time scans or trying the tool before committing to an installation.\n\n## Quick Start\n\n### Basic Usage\n\nScan your current directory for hardcoded credentials:\n\n```bash\nhardcoded-detector scan\n```\n\nThis command scans all files in the current directory and subdirectories, excluding common paths like `node_modules` and `.git`. Results are displayed in the console with color-coded severity levels.\n\n### Scan Specific Directory\n\nTarget a specific directory for scanning:\n\n```bash\nhardcoded-detector scan ./src\n```\n\nThis is useful when you want to focus on application code and exclude test files or documentation.\n\n### Filter by Severity Level\n\nFocus on high-priority issues by setting a minimum severity threshold:\n\n```bash\nhardcoded-detector scan --severity high\n```\n\nThis command only reports credentials with \"high\" or \"critical\" severity, reducing noise from low-priority detections.\n\n### Generate Reports in Different Formats\n\nOutput results to various file formats for different use cases:\n\n```bash\n# JSON format for programmatic processing\nhardcoded-detector scan --output json --file security-report.json\n\n# HTML format for comprehensive visual reports\nhardcoded-detector scan --output html --file security-report.html\n\n# TXT format for simple text-based sharing\nhardcoded-detector scan --output txt --file security-report.txt\n\n# CSV format for spreadsheet analysis\nhardcoded-detector scan --output csv --file security-report.csv\n```\n\nThe JSON output includes detailed metadata, severity breakdowns, and complete finding information suitable for integration with other security tools. HTML reports provide a comprehensive visual overview with syntax highlighting. TXT reports offer a simple, parseable format ideal for sharing via email or processing with text tools.\n\nReal examples of generated reports are included in this repository:\n- **[examples/example-report.txt](examples/example-report.txt)** - Text format report (729 KB) showing 2,921 findings with file paths, line numbers, and detected tokens\n- **[examples/example-report.html](examples/example-report.html)** - HTML format report (5.4 MB) with interactive filtering and syntax highlighting\n\nThese reports were generated by scanning the test files in the `examples/` directory using:\n```bash\nhardcoded-detector scan examples/ --severity high --output txt --file examples/example-report.txt\nhardcoded-detector scan examples/ --severity high --output html --file examples/example-report.html\n```\n\n### Scan Only Staged Files\n\nCheck staged files before committing:\n\n```bash\nhardcoded-detector scan --staged\n```\n\nThis is particularly useful in pre-commit hooks or when you want to verify changes before creating a commit.\n\n## Advanced Features\n\n### Baseline/Ignore File\n\nThe baseline feature allows you to establish a snapshot of known findings and filter them from future scans. This is essential for managing existing codebases that may have legacy credentials or accepted risks.\n\n#### Generate a Baseline\n\nCreate a baseline from your current scan results:\n\n```bash\nhardcoded-detector scan --generate-baseline\n```\n\nThis creates a `.hardcoded-detector-baseline.json` file containing all current findings with SHA-256 hashes for tracking.\n\n#### Use Baseline Filtering\n\nRun scans with baseline filtering to see only new findings:\n\n```bash\nhardcoded-detector scan --baseline\n```\n\nOnly findings not in the baseline will be reported, allowing you to focus on new issues.\n\n#### Custom Baseline Path\n\nSpecify a custom baseline file location:\n\n```bash\nhardcoded-detector scan --baseline --baseline-path ./security/my-baseline.json\n```\n\n#### Baseline File Structure\n\nThe baseline file contains detailed information about each accepted finding:\n\n```json\n{\n  \"version\": \"1.0.0\",\n  \"generatedAt\": \"2024-12-14T10:30:00.000Z\",\n  \"totalFindings\": 15,\n  \"files\": {\n    \"src/config.js:42\": {\n      \"type\": \"aws_access_key\",\n      \"name\": \"AWS Access Key\",\n      \"severity\": \"critical\",\n      \"hash\": \"a1b2c3d4...\",\n      \"reviewed\": true,\n      \"reviewedBy\": \"security-team@company.com\",\n      \"reviewDate\": \"2024-12-14T11:00:00.000Z\",\n      \"reason\": \"Test credential for development environment only\",\n      \"line\": 42,\n      \"match\": \"AKIAIOSFODNN7EXAMPLE\"\n    }\n  }\n}\n```\n\n#### Workflow Integration\n\nTypical workflow for managing baselines:\n\n1. Initial scan: `hardcoded-detector scan --generate-baseline`\n2. Review findings and mark as accepted risk\n3. Commit baseline to version control\n4. CI/CD scans: `hardcoded-detector scan --baseline`\n5. Only new findings will fail the build\n\n### Inline Ignore Comments\n\nSuppress specific findings directly in your source code using ESLint-style comments. This provides fine-grained control without maintaining external configuration.\n\n#### Disable Single Line\n\nIgnore a finding on the same line:\n\n```javascript\nconst apiKey = \"your_api_key_here\"; // hardcoded-detector:disable-line\n```\n\n#### Disable Next Line\n\nIgnore a finding on the following line:\n\n```javascript\n// hardcoded-detector:disable-next-line\nconst apiKey = \"your_api_key_here\";\n```\n\n#### Disable Block\n\nDisable detection for a block of code:\n\n```javascript\n/* hardcoded-detector:disable */\nconst config = {\n  apiKey: \"your_api_key_here\",\n  secret: \"your_secret_here\",\n  token: \"your_token_here\"\n};\n/* hardcoded-detector:enable */\n```\n\n#### Supported Comment Styles\n\nThe tool recognizes various comment styles:\n\n```javascript\n// Single-line JavaScript/TypeScript comments\n# Python/Shell comments\n/* Multi-line C-style comments */\n\u003c!-- HTML comments --\u003e\n```\n\n#### Best Practices\n\nUse inline ignores sparingly for legitimate cases:\n- Test fixtures and example code\n- Documentation and comments\n- Environment-specific configurations that are not secrets\n- False positives from generic patterns\n\nDo not use inline ignores to hide real secrets. Always rotate and externalize credentials.\n\n### Entropy Detection\n\nShannon entropy analysis helps distinguish between random secrets and structured non-secret strings. High-entropy strings (high randomness) are more likely to be secrets.\n\n#### Enable Entropy Filtering\n\nActivate entropy-based filtering to reduce false positives:\n\n```bash\nhardcoded-detector scan --entropy-filter\n```\n\nWhen enabled, generic patterns will only report matches with high entropy (typically 4.5+ on a scale of 0-8).\n\n#### How Entropy Works\n\nShannon entropy measures the randomness of a string:\n\n- Low entropy (0-3.5): Common words, patterns, repeated characters\n  - Example: \"password123\" - entropy ~3.2\n  - Example: \"aaabbbccc\" - entropy ~1.5\n\n- Medium entropy (3.5-4.5): Mixed alphanumeric with some structure\n  - Example: \"MyApiKey2024\" - entropy ~3.8\n  - Example: \"user_token_abc\" - entropy ~4.0\n\n- High entropy (4.5+): Random strings, true secrets\n  - Example: \"xK9mP2qR7nL5wT3yH8\" - entropy ~4.8\n  - Example: random 32-character API keys typically have entropy ~5.0+\n\n#### Entropy in Findings\n\nAll scan results include entropy information:\n\n```json\n{\n  \"match\": \"xK9mP2qR7nL5wT3yH8\",\n  \"line\": 15,\n  \"severity\": \"high\",\n  \"entropy\": {\n    \"value\": 4.82,\n    \"level\": \"high\"\n  }\n}\n```\n\n#### Pattern Configuration\n\nIndividual patterns can be configured to require high entropy using the `useEntropyFilter` flag in custom patterns:\n\n```json\n{\n  \"custom_api_key\": {\n    \"name\": \"Custom API Key\",\n    \"pattern\": \"[A-Za-z0-9]{32}\",\n    \"useEntropyFilter\": true,\n    \"severity\": \"high\"\n  }\n}\n```\n\n#### Benefits\n\nEntropy filtering dramatically reduces false positives for generic patterns:\n- Filters out variable names like \"apiKeyExample\" or \"testSecretKey\"\n- Filters out placeholder values like \"your-api-key-here\"\n- Retains detection of actual random credentials\n- Works particularly well with hex strings and Base64 patterns\n\n### Combining Features\n\nThe most powerful approach combines all three features:\n\n```bash\n# Generate initial baseline\nhardcoded-detector scan --generate-baseline\n\n# Scan with baseline and entropy filtering\nhardcoded-detector scan --baseline --entropy-filter\n\n# Review new findings and add inline ignores for false positives\n# Commit baseline and code changes together\n```\n\nThis provides:\n- Historical context (baseline)\n- Inline documentation (ignore comments)\n- Smart filtering (entropy detection)\n\n## Real-World Use Cases\n\n### Use Case 1: Pre-Commit Security Check\n\n**Scenario**: You want to prevent developers from accidentally committing API keys to your repository.\n\n**Solution**: Install pre-commit hooks that automatically scan staged files before each commit.\n\n```bash\n# Install the tool\nnpm install --save-dev hardcoded-api-key-detector\n\n# Install git hooks\nnpx hardcoded-detector install-hooks\n\n# Configure to block high-severity issues\nnpx hardcoded-detector init\n```\n\nEdit `.hardcoded-detector.json`:\n```json\n{\n  \"severity\": \"high\",\n  \"hooks\": {\n    \"preCommit\": true\n  }\n}\n```\n\n**Result**: When developers try to commit files containing high-severity credentials, the commit is blocked with a detailed error message showing the detected issues.\n\n### Use Case 2: CI/CD Pipeline Integration\n\n**Scenario**: You want to scan all code in pull requests before merging to your main branch.\n\n**Solution**: Add the detector to your GitHub Actions workflow.\n\nCreate `.github/workflows/security-scan.yml`:\n\n```yaml\nname: Security Scan\n\non:\n  pull_request:\n    branches: [ main, develop ]\n  push:\n    branches: [ main ]\n\njobs:\n  security-scan:\n    runs-on: ubuntu-latest\n\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v3\n        with:\n          fetch-depth: 0\n\n      - name: Setup Node.js\n        uses: actions/setup-node@v3\n        with:\n          node-version: '18'\n\n      - name: Install detector\n        run: npm install -g hardcoded-api-key-detector\n\n      - name: Run security scan\n        run: hardcoded-detector scan --severity high --output json --file security-report.json\n\n      - name: Check for high-severity issues\n        run: |\n          HIGH_COUNT=$(jq '.summary.severityBreakdown.high // 0' security-report.json)\n          CRITICAL_COUNT=$(jq '.summary.severityBreakdown.critical // 0' security-report.json)\n          TOTAL=$((HIGH_COUNT + CRITICAL_COUNT))\n\n          if [ $TOTAL -gt 0 ]; then\n            echo \"Found $TOTAL high or critical severity issues\"\n            jq '.findings[] | select(.findings[].severity == \"high\" or .findings[].severity == \"critical\")' security-report.json\n            exit 1\n          fi\n\n      - name: Upload security report\n        if: always()\n        uses: actions/upload-artifact@v3\n        with:\n          name: security-report\n          path: security-report.json\n\n      - name: Comment on PR with results\n        if: github.event_name == 'pull_request' \u0026\u0026 failure()\n        uses: actions/github-script@v6\n        with:\n          script: |\n            const fs = require('fs');\n            const report = JSON.parse(fs.readFileSync('security-report.json', 'utf8'));\n\n            let comment = '## Security Scan Results\\\\n\\\\n';\n            comment += `Found ${report.summary.totalFindings} potential credential(s) in ${report.summary.filesWithIssues} file(s)\\\\n\\\\n`;\n            comment += '### Severity Breakdown\\\\n';\n            comment += `- Critical: ${report.summary.severityBreakdown.critical || 0}\\\\n`;\n            comment += `- High: ${report.summary.severityBreakdown.high || 0}\\\\n`;\n            comment += `- Medium: ${report.summary.severityBreakdown.medium || 0}\\\\n`;\n            comment += `- Low: ${report.summary.severityBreakdown.low || 0}\\\\n\\\\n`;\n            comment += 'Please review and remove any hardcoded credentials before merging.';\n\n            github.rest.issues.createComment({\n              issue_number: context.issue.number,\n              owner: context.repo.owner,\n              repo: context.repo.repo,\n              body: comment\n            });\n```\n\n**Result**: Every pull request is automatically scanned. If credentials are detected, the workflow fails and a comment is added to the PR with detailed findings.\n\n### Use Case 3: Scheduled Repository Audits\n\n**Scenario**: You want to periodically scan your entire repository to catch any credentials that may have been committed before the tool was implemented.\n\n**Solution**: Set up a scheduled GitHub Actions workflow.\n\nCreate `.github/workflows/weekly-audit.yml`:\n\n```yaml\nname: Weekly Security Audit\n\non:\n  schedule:\n    # Run every Monday at 9 AM UTC\n    - cron: '0 9 * * 1'\n  workflow_dispatch: # Allow manual triggering\n\njobs:\n  security-audit:\n    runs-on: ubuntu-latest\n\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v3\n\n      - name: Setup Node.js\n        uses: actions/setup-node@v3\n        with:\n          node-version: '18'\n\n      - name: Run comprehensive scan\n        run: |\n          npx hardcoded-api-key-detector scan \\\n            --severity medium \\\n            --output html \\\n            --file audit-report.html\n\n      - name: Upload audit report\n        uses: actions/upload-artifact@v3\n        with:\n          name: weekly-audit-report\n          path: audit-report.html\n          retention-days: 90\n\n      - name: Send notification if issues found\n        if: failure()\n        run: |\n          # Send email, Slack notification, etc.\n          echo \"Security issues detected in weekly audit\"\n```\n\n**Result**: Your repository is automatically scanned every week, and comprehensive HTML reports are archived for compliance and tracking purposes.\n\n### Use Case 4: Development Environment Setup\n\n**Scenario**: New developers joining your team should have the tool configured automatically.\n\n**Solution**: Add setup instructions to your project's documentation and package.json.\n\nIn `package.json`:\n```json\n{\n  \"scripts\": {\n    \"prepare\": \"hardcoded-detector install-hooks\",\n    \"security:scan\": \"hardcoded-detector scan --severity high\",\n    \"security:full\": \"hardcoded-detector scan --output html --file security-report.html\"\n  },\n  \"devDependencies\": {\n    \"hardcoded-api-key-detector\": \"^1.0.0\"\n  }\n}\n```\n\nIn your project's README:\n```markdown\n## Setup\n\n1. Install dependencies: `npm install`\n2. Git hooks will be automatically installed\n3. Run security scan: `npm run security:scan`\n```\n\n**Result**: When new developers run `npm install`, git hooks are automatically installed, ensuring consistent security practices across your team.\n\n### Use Case 5: Integration with Existing Security Tools\n\n**Scenario**: You want to integrate credential detection with your existing security scanning pipeline.\n\n**Solution**: Use the JSON output format to pipe results to other tools or databases.\n\n```bash\n# Scan and process results with jq\nhardcoded-detector scan --output json | jq '.findings[] | select(.findings[].severity == \"critical\")'\n\n# Export to CSV for spreadsheet analysis\nhardcoded-detector scan --output csv --file credentials-report.csv\n\n# Generate JUnit XML for Jenkins or other CI tools\nhardcoded-detector scan --output junit --file test-results.xml\n```\n\n**Integration with SonarQube example**:\n```bash\n# Generate JSON report\nhardcoded-detector scan --output json --file sonar-security.json\n\n# Convert to SonarQube format and import\nnode convert-to-sonar-format.js sonar-security.json \u003e sonar-import.json\n```\n\n**Result**: Credential detection results are integrated into your broader security and quality assurance processes.\n\n## GitHub Actions Integration\n\n### Basic Configuration\n\nThe simplest GitHub Actions integration scans your code on every push and pull request:\n\n```yaml\nname: Credential Scan\n\non: [push, pull_request]\n\njobs:\n  scan:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v3\n      - uses: actions/setup-node@v3\n        with:\n          node-version: '18'\n      - run: npx hardcoded-api-key-detector scan --severity high\n```\n\n### Advanced Configuration with Failure Threshold\n\nThis configuration only fails the build if critical or high-severity credentials are found:\n\n```yaml\nname: Security Check\n\non:\n  pull_request:\n    branches: [ main ]\n\njobs:\n  credential-scan:\n    runs-on: ubuntu-latest\n\n    steps:\n      - name: Checkout repository\n        uses: actions/checkout@v3\n\n      - name: Setup Node.js\n        uses: actions/setup-node@v3\n        with:\n          node-version: '18'\n          cache: 'npm'\n\n      - name: Scan for credentials\n        id: scan\n        run: |\n          npx hardcoded-api-key-detector scan \\\n            --output json \\\n            --file scan-results.json || true\n\n      - name: Analyze results\n        run: |\n          CRITICAL=$(jq '.summary.severityBreakdown.critical // 0' scan-results.json)\n          HIGH=$(jq '.summary.severityBreakdown.high // 0' scan-results.json)\n\n          echo \"Critical issues: $CRITICAL\"\n          echo \"High issues: $HIGH\"\n\n          if [ $CRITICAL -gt 0 ] || [ $HIGH -gt 0 ]; then\n            echo \"::error::Found $CRITICAL critical and $HIGH high severity credential(s)\"\n            exit 1\n          fi\n\n      - name: Upload scan results\n        if: always()\n        uses: actions/upload-artifact@v3\n        with:\n          name: credential-scan-results\n          path: scan-results.json\n```\n\n### Scan Only Changed Files\n\nFor faster PR checks, scan only the files modified in the pull request:\n\n```yaml\nname: Scan Changed Files\n\non:\n  pull_request:\n    branches: [ main ]\n\njobs:\n  scan-changes:\n    runs-on: ubuntu-latest\n\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v3\n        with:\n          fetch-depth: 0\n\n      - name: Get changed files\n        id: changed-files\n        run: |\n          git diff --name-only origin/${{ github.base_ref }}...HEAD \u003e changed-files.txt\n          echo \"Changed files:\"\n          cat changed-files.txt\n\n      - name: Scan changed files\n        run: |\n          while IFS= read -r file; do\n            if [ -f \"$file\" ]; then\n              npx hardcoded-api-key-detector scan \"$file\" --severity high\n            fi\n          done \u003c changed-files.txt\n```\n\n### Matrix Strategy for Multiple Node Versions\n\nEnsure compatibility across different Node.js versions:\n\n```yaml\nname: Multi-Version Scan\n\non: [push, pull_request]\n\njobs:\n  scan:\n    runs-on: ${{ matrix.os }}\n    strategy:\n      matrix:\n        os: [ubuntu-latest, windows-latest, macos-latest]\n        node-version: [14, 16, 18, 20]\n\n    steps:\n      - uses: actions/checkout@v3\n      - name: Use Node.js ${{ matrix.node-version }}\n        uses: actions/setup-node@v3\n        with:\n          node-version: ${{ matrix.node-version }}\n      - run: npx hardcoded-api-key-detector scan --severity high\n```\n\n### Slack Notification on Detection\n\nSend notifications to Slack when credentials are detected:\n\n```yaml\nname: Scan with Notifications\n\non: [push]\n\njobs:\n  scan:\n    runs-on: ubuntu-latest\n\n    steps:\n      - uses: actions/checkout@v3\n      - uses: actions/setup-node@v3\n        with:\n          node-version: '18'\n\n      - name: Run scan\n        id: scan\n        run: |\n          npx hardcoded-api-key-detector scan \\\n            --output json \\\n            --file results.json || true\n\n          ISSUES=$(jq '.summary.totalFindings' results.json)\n          echo \"issues=$ISSUES\" \u003e\u003e $GITHUB_OUTPUT\n\n      - name: Send Slack notification\n        if: steps.scan.outputs.issues \u003e 0\n        uses: slackapi/slack-github-action@v1\n        with:\n          payload: |\n            {\n              \"text\": \"Hardcoded credentials detected!\",\n              \"blocks\": [\n                {\n                  \"type\": \"section\",\n                  \"text\": {\n                    \"type\": \"mrkdwn\",\n                    \"text\": \"*Credential Scan Alert*\\nFound ${{ steps.scan.outputs.issues }} potential credential(s) in commit ${{ github.sha }}\"\n                  }\n                }\n              ]\n            }\n        env:\n          SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}\n```\n\n## Configuration\n\n### Configuration File\n\nCreate a `.hardcoded-detector.json` file in your project root to customize behavior:\n\n```json\n{\n  \"version\": \"1.0.0\",\n  \"exclude\": [\n    \"node_modules/**\",\n    \"dist/**\",\n    \"build/**\",\n    \"coverage/**\",\n    \"test/**\",\n    \"tests/**\",\n    \"*.test.js\",\n    \"*.spec.js\",\n    \"*.min.js\",\n    \".git/**\"\n  ],\n  \"severity\": \"medium\",\n  \"output\": {\n    \"format\": \"console\",\n    \"colors\": true,\n    \"verbose\": false\n  },\n  \"hooks\": {\n    \"preCommit\": true,\n    \"prePush\": false\n  },\n  \"patterns\": {\n    \"customPatterns\": \"./custom-patterns.json\",\n    \"disabledPatterns\": [\n      \"generic_api_key\",\n      \"generic_secret_key\"\n    ],\n    \"excludeCategories\": [\n      \"cryptocurrency\"\n    ]\n  },\n  \"reporting\": {\n    \"groupBy\": \"file\",\n    \"showContext\": true,\n    \"contextLines\": 3\n  }\n}\n```\n\n### Configuration Options Explained\n\n**exclude**: Array of glob patterns specifying files and directories to skip during scanning. By default, the tool excludes common paths like `node_modules`, `.git`, and build directories. Add your project-specific exclusions here.\n\n**severity**: Minimum severity level for reporting. Options are `low`, `medium`, `high`, or `critical`. Setting this to `high` will only report high and critical severity findings, reducing noise from lower-priority detections.\n\n**output**: Controls how results are displayed. The `format` option supports `console`, `json`, `html`, `csv`, and `junit`. Enable `colors` for terminal output and `verbose` for detailed information about each finding.\n\n**hooks**: Configuration for git hooks. Enable `preCommit` to scan staged files before each commit, or `prePush` to scan before pushing to remote repositories.\n\n**patterns.customPatterns**: Path to a JSON file containing custom detection patterns specific to your organization or proprietary services.\n\n**patterns.disabledPatterns**: Array of pattern IDs to disable. Use this when specific patterns cause too many false positives in your codebase.\n\n**patterns.excludeCategories**: Array of categories to exclude from scanning. For example, exclude `cryptocurrency` if you don't work with blockchain applications.\n\n**reporting.groupBy**: How to organize findings in reports. Options are `file` (group by file path) or `severity` (group by severity level).\n\n**reporting.showContext**: Whether to show surrounding code lines for each finding. This helps understand the context of detected credentials.\n\n**reporting.contextLines**: Number of lines to show before and after each finding when `showContext` is enabled.\n\n## Custom Detection Patterns\n\n### Creating Custom Patterns\n\nOrganizations often have internal services with proprietary credential formats. You can add custom detection patterns to identify these credentials:\n\nCreate a `custom-patterns.json` file:\n\n```json\n{\n  \"metadata\": {\n    \"version\": \"1.0.0\",\n    \"description\": \"Custom patterns for Acme Corporation internal services\",\n    \"author\": \"security-team@acme.com\"\n  },\n  \"patterns\": {\n    \"acme_internal_api\": {\n      \"name\": \"Acme Internal API Key\",\n      \"pattern\": \"(?i)(?:acme|internal)_?(?:api|access)_?(?:key|token)\\\\s*[=:]\\\\s*['\\\"]?(ACME_[A-Z0-9]{32})['\\\"]?\",\n      \"severity\": \"critical\",\n      \"category\": \"custom\",\n      \"service\": \"Acme Internal Services\",\n      \"description\": \"Internal API key for Acme services with context\",\n      \"confidence\": \"high\",\n      \"references\": [\n        \"https://docs.acme.internal/security/api-keys\"\n      ]\n    },\n    \"acme_database_password\": {\n      \"name\": \"Acme Database Password\",\n      \"pattern\": \"(?i)(?:database|db)_?(?:password|pwd|pass)\\\\s*[=:]\\\\s*['\\\"]?([A-Za-z0-9!@#$%^\u0026*]{16,})['\\\"]?\",\n      \"severity\": \"critical\",\n      \"category\": \"database\",\n      \"service\": \"Acme Database\",\n      \"description\": \"Database password with context (minimum 16 characters)\",\n      \"confidence\": \"medium\"\n    },\n    \"acme_service_token\": {\n      \"name\": \"Acme Service Token\",\n      \"pattern\": \"(?i)(?:acme|service)_?(?:token|bearer)\\\\s*[=:]\\\\s*['\\\"]?(ast_[a-z0-9]{48})['\\\"]?\",\n      \"severity\": \"high\",\n      \"category\": \"authentication\",\n      \"service\": \"Acme Service Authentication\",\n      \"description\": \"Service authentication token with context\",\n      \"confidence\": \"high\"\n    }\n  }\n}\n```\n\n### Pattern Design Guidelines\n\n**Use Context-Aware Patterns**: Include variable names or assignment patterns to reduce false positives. The pattern should look for both the credential format and its context (variable name).\n\n**Choose Appropriate Severity**: Assign severity based on the potential impact of credential exposure. Critical severity should be reserved for credentials that could cause immediate and severe damage.\n\n**Set Realistic Confidence Levels**: High confidence should only be assigned to patterns with distinctive formats or strong contextual clues. Medium confidence is appropriate for patterns that might have some false positives.\n\n**Include References**: Link to internal documentation about the credential type, security policies, and rotation procedures.\n\n### Reference Custom Patterns in Configuration\n\nIn your `.hardcoded-detector.json`:\n\n```json\n{\n  \"patterns\": {\n    \"customPatterns\": \"./custom-patterns.json\"\n  }\n}\n```\n\nThe tool will merge your custom patterns with the built-in patterns during scanning.\n\n## Supported Services and Patterns\n\nThe tool includes 245 detection patterns across 15 categories:\n\n### AI and Machine Learning Platforms (17 patterns)\n\nOpenAI GPT/DALL-E/Whisper API keys, Anthropic Claude API keys, Google AI Gemini API keys, Hugging Face model tokens, Cohere language model keys, Replicate ML deployment tokens, Stability AI image generation keys, ElevenLabs voice synthesis keys, AssemblyAI speech-to-text keys, Deepgram speech recognition keys, Pinecone vector database keys, Weaviate vector search keys, LangSmith monitoring tokens, Mistral AI API keys, Together AI keys, and more specialized AI service credentials.\n\n### Cloud Service Providers (25 patterns)\n\nAmazon Web Services access keys and secret keys, Google Cloud Platform API keys and service account credentials, Microsoft Azure subscription keys and storage account keys, DigitalOcean personal access tokens and Spaces keys, Vercel deployment tokens, Render API tokens, Heroku API keys, Netlify build tokens, Railway cloud platform tokens, Fly.io edge computing credentials, Cloudflare API tokens, Fastly CDN tokens, Linode cloud hosting keys, Vultr server provider keys, Oracle Cloud infrastructure tokens, and other cloud platform credentials.\n\n### Database Services (29 patterns)\n\nMongoDB connection URIs with embedded credentials, PostgreSQL connection strings, MySQL connection URIs, Redis connection strings with passwords, Elasticsearch cluster credentials, Supabase PostgreSQL credentials, PlanetScale MySQL database keys, Firebase Realtime Database URIs, Airtable API tokens, Notion database integration tokens, FaunaDB serverless database keys, InfluxDB time-series database tokens, ClickHouse analytical database credentials, and other database service authentication.\n\n### Payment Processing (13 patterns)\n\nStripe live and test API secret keys, PayPal access tokens and client secrets, Square OAuth tokens and access tokens, Braintree payment gateway credentials, and other payment service provider authentication tokens.\n\n### Communication Services (13 patterns)\n\nTwilio API keys and auth tokens, SendGrid email API keys, Postmark server tokens, Mailchimp marketing API keys, Mailjet email service keys, Slack bot tokens and user tokens, Discord bot tokens and webhooks, Telegram bot API tokens, and other messaging platform credentials.\n\n### Development Tools (15 patterns)\n\nGitHub personal access tokens, GitLab personal access tokens and deploy tokens, Bitbucket app passwords, NPM package registry tokens, Docker Hub registry credentials, CircleCI API tokens, Travis CI tokens, Jenkins authentication tokens, and other CI/CD platform credentials.\n\n### Monitoring and Analytics (25 patterns)\n\nDatadog API keys and application keys, New Relic license keys, Sentry error tracking tokens, LogRocket session replay tokens, Amplitude analytics keys, Mixpanel tracking tokens, Segment write keys, Bugsnag error monitoring keys, Rollbar access tokens, and other observability platform credentials.\n\n### Authentication Services (12 patterns)\n\nAuth0 client secrets, Okta API tokens, Firebase authentication keys, Clerk secret keys, JWT tokens with context, OAuth bearer tokens, and other identity management platform credentials.\n\n### Storage and CDN (9 patterns)\n\nAWS S3 access keys, Azure Blob Storage credentials, Cloudinary media management keys, Imgix image processing tokens, BunnyCDN API keys, KeyCDN acceleration keys, and other content delivery network credentials.\n\n### Security and Certificates (13 patterns)\n\nPrivate keys in PEM format (RSA, DSA, ECDSA, Ed25519), SSH private keys, PGP private key blocks, SSL/TLS certificates, and other cryptographic credentials.\n\n### E-commerce Platforms (8 patterns)\n\nShopify API keys and access tokens, WooCommerce consumer keys, BigCommerce API tokens, Magento access tokens, Etsy API keys, and other online store platform credentials.\n\n### Content Management Systems (8 patterns)\n\nWordPress.com API keys, Drupal API tokens, Ghost admin API keys, Contentful content management tokens, Sanity studio tokens, Strapi CMS keys, and other content platform credentials.\n\n### CRM and Marketing (12 patterns)\n\nSalesforce access tokens, HubSpot API keys, Zendesk authentication tokens, Intercom API tokens, Mailchimp marketing keys, ConvertKit API secrets, ActiveCampaign keys, and other customer relationship management credentials.\n\n### Infrastructure as Code (8 patterns)\n\nTerraform Cloud tokens, HashiCorp Vault tokens, Consul cluster tokens, Nomad orchestration tokens, Pulumi access tokens, and other infrastructure management credentials.\n\n### Generic Patterns (8 patterns)\n\nGeneric API key patterns with context, generic secret key patterns, JWT tokens, bearer tokens, password patterns in URLs, connection strings, and other common credential formats.\n\nTo see all available patterns with details:\n\n```bash\nhardcoded-detector patterns\n\n# Filter by category\nhardcoded-detector patterns --category ai\n\n# Filter by service\nhardcoded-detector patterns --service github\n```\n\n## Command Line Interface\n\n### scan command\n\nScan directories for hardcoded credentials:\n\n```bash\nhardcoded-detector scan [directory] [options]\n```\n\n**Arguments:**\n- `directory`: Path to scan (default: current directory)\n\n**Options:**\n- `-c, --config \u003cpath\u003e`: Path to configuration file (default: `.hardcoded-detector.json`)\n- `-o, --output \u003cformat\u003e`: Output format - `console`, `json`, `html`, `csv`, or `junit` (default: `console`)\n- `-f, --file \u003cpath\u003e`: Output file path (writes to stdout if not specified)\n- `-s, --severity \u003clevel\u003e`: Minimum severity level - `low`, `medium`, `high`, or `critical` (default: `medium`)\n- `--staged`: Scan only staged files in git (useful for pre-commit hooks)\n- `--exclude \u003cpatterns...\u003e`: Additional glob patterns to exclude (adds to config exclusions)\n- `--baseline`: Use baseline file to filter known findings\n- `--baseline-path \u003cpath\u003e`: Path to baseline file (default: `.hardcoded-detector-baseline.json`)\n- `--generate-baseline`: Generate baseline file from current scan results\n- `--entropy-filter`: Enable entropy-based filtering to reduce false positives\n- `--no-colors`: Disable colored output (useful for CI/CD logs)\n- `--verbose`: Enable verbose logging with detailed scan progress\n\n**Examples:**\n\n```bash\n# Scan current directory with default settings\nhardcoded-detector scan\n\n# Scan specific directory with high severity threshold\nhardcoded-detector scan ./src --severity high\n\n# Generate HTML report\nhardcoded-detector scan --output html --file security-audit.html\n\n# Scan only staged files (pre-commit scenario)\nhardcoded-detector scan --staged --severity high\n\n# Exclude additional patterns\nhardcoded-detector scan --exclude \"**/*.test.js\" \"fixtures/**\"\n\n# Verbose JSON output to file\nhardcoded-detector scan --output json --file report.json --verbose\n\n# Generate baseline from current scan\nhardcoded-detector scan --generate-baseline\n\n# Scan with baseline filtering\nhardcoded-detector scan --baseline\n\n# Scan with entropy filtering enabled\nhardcoded-detector scan --entropy-filter\n\n# Combine baseline and entropy filtering\nhardcoded-detector scan --baseline --entropy-filter --severity high\n```\n\n### init command\n\nInitialize configuration file with sensible defaults:\n\n```bash\nhardcoded-detector init [options]\n```\n\n**Options:**\n- `-f, --force`: Overwrite existing configuration file\n\nThis command creates a `.hardcoded-detector.json` file in your current directory with recommended settings. Review and customize the file for your project's specific needs.\n\n**Example:**\n\n```bash\n# Create configuration file\nhardcoded-detector init\n\n# Force overwrite existing configuration\nhardcoded-detector init --force\n```\n\n### install-hooks command\n\nInstall git pre-commit hooks for automatic scanning:\n\n```bash\nhardcoded-detector install-hooks\n```\n\nThis command creates or updates `.git/hooks/pre-commit` to automatically scan staged files before each commit. If high or critical severity credentials are detected, the commit is blocked and findings are displayed.\n\nThe hook script:\n- Scans only staged files for performance\n- Uses the severity level from your configuration\n- Provides clear feedback about detected issues\n- Can be bypassed with `git commit --no-verify` in emergencies (not recommended)\n\n**Example:**\n\n```bash\n# Install hooks\nhardcoded-detector install-hooks\n\n# Verify installation\ncat .git/hooks/pre-commit\n```\n\n### patterns command\n\nList available detection patterns:\n\n```bash\nhardcoded-detector patterns [options]\n```\n\n**Options:**\n- `-c, --category \u003ccategory\u003e`: Filter by category (e.g., `ai`, `cloud`, `database`)\n- `-s, --service \u003cservice\u003e`: Filter by service name (e.g., `github`, `aws`, `stripe`)\n- `--json`: Output in JSON format\n\n**Examples:**\n\n```bash\n# List all patterns\nhardcoded-detector patterns\n\n# Show only AI platform patterns\nhardcoded-detector patterns --category ai\n\n# Show GitHub-specific patterns\nhardcoded-detector patterns --service github\n\n# Export patterns to JSON\nhardcoded-detector patterns --json \u003e patterns-list.json\n```\n\n## Programmatic API Usage\n\n### Basic Usage\n\n```javascript\nconst HardcodedApiDetector = require('hardcoded-api-key-detector');\n\n// Create detector instance with options\nconst detector = new HardcodedApiDetector({\n  severity: 'high',\n  exclude: ['test/**', '*.test.js'],\n  customPatternsPath: './custom-patterns.json'\n});\n\n// Scan a directory\nasync function scanProject() {\n  try {\n    const results = await detector.scan('./src');\n\n    console.log(`Scanned ${results.totalFiles} files`);\n    console.log(`Found issues in ${results.filesWithIssues} files`);\n\n    // Process findings\n    results.findings.forEach(fileResult =\u003e {\n      console.log(`\\nFile: ${fileResult.file}`);\n      fileResult.findings.forEach(finding =\u003e {\n        console.log(`  - ${finding.name} (${finding.severity})`);\n        console.log(`    Line ${finding.line}: ${finding.lineContent}`);\n      });\n    });\n\n    // Exit with error if critical issues found\n    const criticalCount = results.findings\n      .reduce((sum, f) =\u003e sum + f.findings.filter(x =\u003e x.severity === 'critical').length, 0);\n\n    if (criticalCount \u003e 0) {\n      console.error(`Found ${criticalCount} critical issues!`);\n      process.exit(1);\n    }\n  } catch (error) {\n    console.error('Scan failed:', error.message);\n    process.exit(1);\n  }\n}\n\nscanProject();\n```\n\n### Advanced Usage with Content Analyzer\n\n```javascript\nconst ContentAnalyzer = require('hardcoded-api-key-detector/src/scanner/analyzer');\nconst fs = require('fs').promises;\n\nasync function analyzeSpecificFiles() {\n  // Create analyzer with custom patterns\n  const analyzer = new ContentAnalyzer('./custom-patterns.json');\n\n  // Analyze individual files\n  const filesToScan = ['src/config.js', 'src/auth.js', 'src/api.js'];\n\n  for (const file of filesToScan) {\n    const findings = await analyzer.analyzeContent(file, {\n      minSeverity: 'high',\n      disabledPatterns: ['generic_api_key'],\n      excludeCategories: ['cryptocurrency']\n    });\n\n    if (findings.length \u003e 0) {\n      console.log(`\\nIssues in ${file}:`);\n      findings.forEach(finding =\u003e {\n        console.log(`  ${finding.name} at line ${finding.line}`);\n        console.log(`  Severity: ${finding.severity}, Confidence: ${finding.confidence}`);\n        console.log(`  Service: ${finding.service}, Category: ${finding.type}`);\n      });\n    }\n  }\n}\n\nanalyzeSpecificFiles().catch(console.error);\n```\n\n### Custom Reporter\n\n```javascript\nconst HardcodedApiDetector = require('hardcoded-api-key-detector');\n\nclass CustomReporter {\n  constructor() {\n    this.detector = new HardcodedApiDetector({\n      severity: 'medium'\n    });\n  }\n\n  async generateReport(directory) {\n    const results = await this.detector.scan(directory);\n\n    // Create custom report format\n    const report = {\n      timestamp: new Date().toISOString(),\n      directory: directory,\n      summary: {\n        totalFiles: results.totalFiles,\n        filesWithIssues: results.filesWithIssues,\n        totalFindings: results.findings.reduce((sum, f) =\u003e sum + f.findings.length, 0)\n      },\n      severityBreakdown: this.calculateSeverityBreakdown(results),\n      highRiskFiles: this.identifyHighRiskFiles(results),\n      recommendations: this.generateRecommendations(results)\n    };\n\n    return report;\n  }\n\n  calculateSeverityBreakdown(results) {\n    const breakdown = { critical: 0, high: 0, medium: 0, low: 0 };\n\n    results.findings.forEach(fileResult =\u003e {\n      fileResult.findings.forEach(finding =\u003e {\n        breakdown[finding.severity]++;\n      });\n    });\n\n    return breakdown;\n  }\n\n  identifyHighRiskFiles(results) {\n    return results.findings\n      .filter(f =\u003e f.findings.some(finding =\u003e finding.severity === 'critical' || finding.severity === 'high'))\n      .map(f =\u003e ({\n        file: f.file,\n        criticalCount: f.findings.filter(x =\u003e x.severity === 'critical').length,\n        highCount: f.findings.filter(x =\u003e x.severity === 'high').length\n      }));\n  }\n\n  generateRecommendations(results) {\n    const recommendations = [];\n\n    if (this.calculateSeverityBreakdown(results).critical \u003e 0) {\n      recommendations.push('Immediately rotate all critical credentials found');\n    }\n\n    if (results.filesWithIssues \u003e 0) {\n      recommendations.push('Move credentials to environment variables or secure vault');\n      recommendations.push('Add .env files to .gitignore');\n      recommendations.push('Install pre-commit hooks to prevent future occurrences');\n    }\n\n    return recommendations;\n  }\n}\n\n// Usage\nconst reporter = new CustomReporter();\nreporter.generateReport('./src')\n  .then(report =\u003e console.log(JSON.stringify(report, null, 2)))\n  .catch(console.error);\n```\n\n## Output Formats\n\n### Console Output\n\nHuman-readable format with color-coded severity levels:\n\n```\nScanning for hardcoded API keys...\nUsing single-threaded scanning for 42 files\n\n[RESULTS] Scan Results:\nFiles scanned: 42\nFiles with issues: 3\n\n[CRITICAL] Critical: 1\n[HIGH] High: 2\n[MEDIUM] Medium: 1\n\n[FILE] src/config/database.js\n  [FOUND] MongoDB Connection URI (critical)\n    Line 15: const mongoUri = \"mongodb://admin:password123@localhost:27017/myapp\";\n    Service: MongoDB | Category: database\n    MongoDB connection string with embedded credentials\n\n[FILE] src/auth/github.js\n  [FOUND] GitHub Personal Access Token (high)\n    Line 8: const githubToken = \"YOUR_GITHUB_TOKEN_HERE\";\n    Service: GitHub | Category: development\n    GitHub Personal Access Token\n\n[FILE] src/services/stripe.js\n  [FOUND] Stripe API Key (high)\n    Line 22: const stripeKey = \"YOUR_STRIPE_KEY_HERE\";\n    Service: Stripe | Category: payment\n    Stripe API Secret Key\n```\n\n### JSON Output\n\nStructured format suitable for programmatic processing:\n\n```json\n{\n  \"metadata\": {\n    \"scanTime\": \"2024-12-14T15:30:00.000Z\",\n    \"tool\": \"hardcoded-api-detector\",\n    \"version\": \"1.0.0\",\n    \"scanDuration\": 1.234\n  },\n  \"summary\": {\n    \"totalFiles\": 42,\n    \"filesWithIssues\": 3,\n    \"totalFindings\": 4,\n    \"severityBreakdown\": {\n      \"critical\": 1,\n      \"high\": 2,\n      \"medium\": 1,\n      \"low\": 0\n    }\n  },\n  \"findings\": [\n    {\n      \"file\": \"src/config/database.js\",\n      \"findings\": [\n        {\n          \"id\": \"mongodb_uri\",\n          \"name\": \"MongoDB Connection URI\",\n          \"severity\": \"critical\",\n          \"type\": \"database\",\n          \"service\": \"MongoDB\",\n          \"description\": \"MongoDB connection string with embedded credentials\",\n          \"confidence\": \"high\",\n          \"match\": \"mongodb://admin:password123@localhost:27017/myapp\",\n          \"line\": 15,\n          \"column\": 20,\n          \"lineContent\": \"const mongoUri = \\\"mongodb://admin:password123@localhost:27017/myapp\\\";\"\n        }\n      ]\n    }\n  ]\n}\n```\n\n### HTML Output\n\nComprehensive report with syntax highlighting and interactive filtering:\n\nThe HTML report includes:\n- Executive summary with charts and statistics\n- Filterable findings by severity, service, and category\n- Syntax-highlighted code snippets\n- Exportable data tables\n- Recommendations and remediation guidance\n\nGenerate HTML report:\n```bash\n# Generate HTML report from your codebase\nhardcoded-detector scan --output html --file security-report.html\n\n# Example: scan the examples directory\nhardcoded-detector scan examples/ --severity high --output html --file examples/example-report.html\n```\n\nA real example report is available at **[examples/example-report.html](examples/example-report.html)** (5.4 MB) generated from scanning the test files in this repository. Open it in your browser to see the full interactive report with:\n- Executive summary with 2,921 findings (144 critical, 2,777 high)\n- Color-coded severity indicators\n- Organized by file with code context\n- Clean relative paths (e.g., `./examples/database-config.js`)\n\n### CSV Output\n\nSpreadsheet-compatible format for analysis:\n\n```csv\nFile,Line,Severity,Service,Category,Name,Description,Match\nsrc/config/database.js,15,critical,MongoDB,database,MongoDB Connection URI,MongoDB connection string with embedded credentials,\"mongodb://admin:password123@localhost:27017/myapp\"\nsrc/auth/github.js,8,high,GitHub,development,GitHub Personal Access Token,GitHub Personal Access Token,YOUR_GITHUB_TOKEN_HERE\n```\n\nGenerate CSV report:\n```bash\nhardcoded-detector scan --output csv --file findings.csv\n```\n\n### Text (TXT) Output\n\nSimple text format showing file path, line number, and detected token:\n\n```\n================================================================================\n  HARDCODED API DETECTOR - TEXT REPORT\n================================================================================\n\nScan Time: 14/12/2024, 15:30:00\nTool: hardcoded-api-detector\nRepository: https://github.com/686f6c61/hardcoded-api-detector\n\n--------------------------------------------------------------------------------\nSUMMARY\n--------------------------------------------------------------------------------\nFiles Scanned:      42\nFiles with Issues:  3\nTotal Findings:     4\n\nSeverity Breakdown:\n  Critical:         1\n  High:             2\n  Medium:           1\n  Low:              0\n\n--------------------------------------------------------------------------------\nFINDINGS\n--------------------------------------------------------------------------------\n\nFormat: FILE:LINE - TOKEN (CREDENTIAL_NAME) [SEVERITY]\n\nsrc/config/database.js:15                                    - mongodb://admin:password123@localhost:27017/myapp\n                                                               (MongoDB Connection URI) [CRITICAL]\n                                                               Service: MongoDB\n\nsrc/auth/github.js:8                                         - YOUR_GITHUB_TOKEN_HERE\n                                                               (GitHub Personal Access Token) [HIGH]\n                                                               Service: GitHub\n\nsrc/services/stripe.js:22                                    - YOUR_STRIPE_KEY_HERE\n                                                               (Stripe API Key) [HIGH]\n                                                               Service: Stripe\n\n--------------------------------------------------------------------------------\nEnd of Report - 4 findings detected\n--------------------------------------------------------------------------------\n```\n\nGenerate TXT report:\n```bash\n# Generate text report from your codebase\nhardcoded-detector scan --output txt --file findings.txt\n\n# Example: scan the examples directory\nhardcoded-detector scan examples/ --severity high --output txt --file examples/example-report.txt\n```\n\nThis format is ideal for:\n- Quick review and sharing via email or chat\n- Parsing with simple text processing tools (grep, awk, sed)\n- Archiving scan results in a human-readable format\n- Integration with legacy systems that require plain text\n- Processing with shell scripts for automation\n\nA real example report is available at **[examples/example-report.txt](examples/example-report.txt)** (729 KB) generated from scanning the test files in this repository. The report shows 2,921 findings with clean relative paths:\n\n```\n./examples/database-config.js:5                              - mongodb://admin:SuperSecret123@\n                                                               (MongoDB Connection URI) [HIGH]\n                                                               Service: MongoDB\n\n./examples/aws-config.js:9                                   - aws_secret_access_key: \"wJal...\"\n                                                               (AWS Secret Access Key) [CRITICAL]\n                                                               Service: Amazon Web Services\n```\n\n### JUnit XML Output\n\nCompatible with CI/CD platforms like Jenkins:\n\n```xml\n\u003c?xml version=\"1.0\" encoding=\"UTF-8\"?\u003e\n\u003ctestsuites\u003e\n  \u003ctestsuite name=\"Hardcoded API Detector\" tests=\"42\" failures=\"3\" errors=\"0\" time=\"1.234\"\u003e\n    \u003ctestcase name=\"src/config/database.js\" classname=\"credential-scan\"\u003e\n      \u003cfailure message=\"MongoDB Connection URI (critical)\" type=\"credential\"\u003e\n        Line 15: const mongoUri = \"mongodb://admin:password123@localhost:27017/myapp\";\n        Service: MongoDB | Category: database\n      \u003c/failure\u003e\n    \u003c/testcase\u003e\n  \u003c/testsuite\u003e\n\u003c/testsuites\u003e\n```\n\n## Contributing\n\nWe welcome contributions from the community. Whether you want to add detection patterns for new services, fix bugs, improve documentation, or suggest enhancements, your input is valuable.\n\n### Ways to Contribute\n\n**Add New Detection Patterns**: If you use a service that is not currently supported, add a detection pattern to `src/detectors/services.json`. Follow the pattern format and include tests.\n\n**Report False Positives**: If a pattern incorrectly identifies something as a credential, create an issue with the pattern ID and example code. We will refine the pattern to improve accuracy.\n\n**Improve Documentation**: Help make the documentation clearer, more comprehensive, or better organized. Fix typos, add examples, or clarify confusing sections.\n\n**Fix Bugs**: Review open issues and submit pull requests with fixes. Include tests that verify the fix.\n\n**Suggest Features**: Have an idea for a new feature or improvement? Create an issue to discuss it with the community.\n\n### Development Setup\n\n```bash\n# Fork and clone the repository\ngit clone https://github.com/your-username/hardcoded-api-key-detector.git\ncd hardcoded-api-key-detector\n\n# Install dependencies\nnpm install\n\n# Run tests\nnpm test\n\n# Run linter\nnpm run lint\n\n# Run tests with coverage\nnpm run test:coverage\n```\n\n### Adding a New Pattern\n\n1. Edit `src/detectors/services.json`\n2. Add your pattern following this structure:\n\n```json\n{\n  \"your_service_key\": {\n    \"name\": \"Your Service API Key\",\n    \"pattern\": \"(?i)(?:yourservice|alias)_?(?:api)_?(?:key)\\\\s*[=:]\\\\s*['\\\"]?([A-Z0-9]{32})['\\\"]?\",\n    \"severity\": \"high\",\n    \"category\": \"cloud\",\n    \"service\": \"Your Service\",\n    \"description\": \"Your Service API Key with context\",\n    \"confidence\": \"high\",\n    \"references\": [\n      \"https://docs.yourservice.com/authentication\"\n    ]\n  }\n}\n```\n\n3. Add tests in `tests/analyzer.test.js`\n4. Run tests to verify\n5. Submit a pull request\n\nFor detailed contribution guidelines, see [CONTRIBUTING.md](CONTRIBUTING.md).\n\n## Changelog\n\n### Version 1.0.0 (2024-12-14)\n\nInitial release of Hardcoded API Key Detector with comprehensive security scanning capabilities.\n\n**Core Features:**\n- 245 detection patterns covering AI platforms, cloud providers, databases, payment services, development tools, and more\n- Context-aware pattern matching to reduce false positives\n- Multiple output formats: console, JSON, HTML, CSV, TXT, JUnit XML\n- Parallel processing with worker threads for large codebases\n- Stream-based analysis for memory-efficient scanning\n- Git integration with pre-commit hooks\n- Customizable configuration and custom pattern support\n\n**Advanced Features:**\n- Baseline/Ignore File: Generate and maintain baselines of known findings with SHA-256 hashing for accurate tracking across code changes\n- Inline Ignore Comments: ESLint-style comments for suppressing specific findings (disable-line, disable-next-line, disable/enable blocks)\n- Entropy Detection: Shannon entropy analysis to identify high-randomness strings and filter out low-entropy false positives\n- Entropy filtering flag to enable smart detection on generic patterns\n\n**CLI Commands:**\n- `scan` - Scan directories for hardcoded credentials with filtering options\n- `init` - Initialize configuration file with recommended settings\n- `install-hooks` - Install git pre-commit hooks for automatic scanning\n- `patterns` - List available detection patterns with filtering\n\n**New Scan Options:**\n- `--baseline` - Use baseline file to filter known findings\n- `--baseline-path` - Specify custom baseline file location\n- `--generate-baseline` - Create baseline from scan results\n- `--entropy-filter` - Enable entropy-based false positive reduction\n\n**Supported Services:**\n- AI/ML: OpenAI, Anthropic Claude, Google AI, Hugging Face, Cohere, and 12 more\n- Cloud: AWS, GCP, Azure, DigitalOcean, Vercel, Heroku, and 19 more\n- Databases: MongoDB, PostgreSQL, Redis, Elasticsearch, and 25 more\n- Payment: Stripe, PayPal, Square, Braintree, and 9 more\n- Communication: Twilio, SendGrid, Mailchimp, Slack, Discord, and 8 more\n- Development: GitHub, GitLab, NPM, Docker, CircleCI, and 10 more\n- And 190+ additional patterns across monitoring, authentication, storage, CMS, CRM, and infrastructure services\n\n**Performance:**\n- Scan medium-sized projects (1000 files) in under 10 seconds\n- Memory-efficient stream processing for large files\n- Parallel worker threads for multi-core utilization\n- ReDoS protection with safe regex execution and timeouts\n\n**Integration:**\n- GitHub Actions workflows included\n- GitLab CI/CD compatible\n- Jenkins integration via JUnit XML output\n- Slack notification examples\n- Programmatic API for custom integrations\n\n**Documentation:**\n- Comprehensive README with real-world use cases\n- API documentation for programmatic usage\n- Contributing guidelines for pattern additions\n- Example reports (HTML, TXT, JSON) included\n\n## License\n\nThis project is licensed under the MIT License. See the [LICENSE](LICENSE) file for complete details.\n\n## Support and Community\n\n**GitHub Issues**: Report bugs, request features, or ask questions at https://github.com/686f6c61/hardcoded-api-key-detector/issues\n\n**Pull Requests**: Contributions are welcome. Please read the contributing guidelines before submitting.\n\n**Security Issues**: If you discover a security vulnerability, please email the maintainer directly rather than creating a public issue.\n\n## Author\n\nCreated and maintained by 686f6c61.\n\n## Acknowledgments\n\nThis project is built with contributions from the open-source community. Special thanks to all contributors who have added patterns, reported issues, and improved the tool.\n\nThe detection patterns are based on publicly available documentation from service providers and security research on credential formats.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2F686f6c61%2Fhardcoded-api-key-detector","html_url":"https://awesome.ecosyste.ms/projects/github.com%2F686f6c61%2Fhardcoded-api-key-detector","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2F686f6c61%2Fhardcoded-api-key-detector/lists"}