A high-performance TypeScript wrapper for TruffleHog secret scanner, designed for modern development workflows and CI/CD pipelines.
TruffleHog is a powerful secrets scanning engine that searches for credentials, API keys, and other sensitive data across your codebase, Git history, and file systems. It uses pattern recognition and entropy analysis to detect secrets that might accidentally be committed to your repository.
- Secret Detection - Comprehensive scanning for 800+ secret types including API keys, passwords, tokens, and certificates
- High Performance - Asynchronous scanning with configurable timeouts and caching
- Git Integration - Native support for scanning staged files, perfect for pre-commit hooks
- TypeScript API - Full TypeScript support with comprehensive type definitions
- Binary Management - Automatic TruffleHog binary download, verification, and caching
- Cross-Platform - Support for Linux, macOS, and Windows (x64 and ARM64)
- Security First - Cryptographic verification of downloaded binaries with checksums and signatures
- Configurable - Extensive configuration options for detectors, paths, and verification
- Rich Logging - Detailed logging with multiple verbosity levels and colored output
- CI/CD Ready - Optimized for continuous integration and pre-commit workflows
bun add trufflehog-js
npm install trufflehog-js
yarn add trufflehog-js
Variable | Description | Default |
---|---|---|
TRUFFLEHOG_BINARY_PATH |
Custom path to TruffleHog binary | Auto-download |
TRUFFLEHOG_LOG_LEVEL |
Logging level (debug, info, warn, error) | warn |
TRUFFLEHOG_VERBOSE |
Enable verbose output | false |
TRUFFLEHOG_CONFIG_PATH |
Path to TruffleHog configuration file | - |
Add to your .lefthook.yml
:
pre-commit:
commands:
secrets:
run: bunx trufflehog-js --staged --quiet
fail_text: "Secrets detected! Please remove before committing."
{
"husky": {
"hooks": {
"pre-commit": "bunx trufflehog-js --staged --quiet"
}
}
}
TruffleHog-JS provides a seamless integration layer between your JavaScript/TypeScript application and the TruffleHog secret scanner:
- Binary Management: Automatically downloads and verifies the appropriate TruffleHog binary for your platform
- Git Integration: Scans staged files in Git repositories, perfect for pre-commit workflows
- Result Processing: Parses TruffleHog's JSON output into structured TypeScript objects
- Error Handling: Provides comprehensive error types with appropriate exit codes for CI/CD
- Caching: Efficiently caches downloaded binaries and scan results for improved performance
- Repository Check: Verifies you're in a Git repository with staged files
- Binary Verification: Ensures TruffleHog binary is available and verified
- File Analysis: Scans staged files using TruffleHog's pattern recognition
- Result Parsing: Converts findings into structured data with file paths, secret types, and verification status
- Action Decision: Returns appropriate exit codes based on findings (0 = clean, 1 = secrets found, 2 = error)
# Scan staged files (typical pre-commit usage)
bunx trufflehog-js --staged
# Scan with verbose output for debugging
bunx trufflehog-js --staged --verbose
# Scan with custom timeout and excluded patterns
bunx trufflehog-js --staged --timeout 60000 --exclude "*.test.ts" --exclude "dist/*"
# Scan with specific detectors only
bunx trufflehog-js --staged --include-detectors "aws,github,slack"
# Scan excluding certain detectors
bunx trufflehog-js --staged --exclude-detectors "generic,test"
# Scan with verification enabled
bunx trufflehog-js --staged --verify
# Quiet mode for CI/CD (minimal output)
bunx trufflehog-js --staged --quiet
import { TruffleHogScanner, scanStagedFiles } from 'trufflehog-js';
// Simple staged file scanning
try {
const results = await scanStagedFiles();
if (results.length > 0) {
console.log(`Found ${results.length} secrets!`);
results.forEach(result => {
console.log(`${result.detector} in ${result.file}`);
});
} else {
console.log('No secrets detected');
}
} catch (error) {
console.error('Scan failed:', error.message);
}
import { TruffleHogScanner, createLogger } from 'trufflehog-js';
const logger = createLogger({ level: 'debug', timestamp: true });
const scanner = new TruffleHogScanner({
timeout: 120000,
logger,
binaryPath: '/custom/path/to/trufflehog' // Optional: use custom binary
});
// Scan with detailed options
const results = await scanner.scanStagedFiles({
verify: true,
includeDetectors: ['aws', 'github', 'slack'],
excludePaths: ['node_modules/**', '*.test.ts'],
timeout: 60000
});
// Process results
results.forEach(result => {
console.log(`Detector: ${result.detector}`);
console.log(`File: ${result.file}`);
console.log(`Verified: ${result.verified ? 'Yes' : 'No'}`);
console.log(`Secret: ${result.secret}`); // Redacted for security
});
import { TruffleHogScanner } from 'trufflehog-js';
const scanner = new TruffleHogScanner();
// Scan specific files
const fileResults = await scanner.scanFiles([
'src/config.ts',
'src/database.ts'
], {
verify: false,
excludeDetectors: ['test']
});
// Scan text content directly
const textResults = await scanner.scanText(`
const apiKey = "sk-1234567890abcdef";
const dbPassword = "super_secret_password";
`, 'config.ts');
console.log(`Found ${textResults.length} secrets in text`);
import {
TruffleHogScanner,
SecretsFoundError,
BinaryNotFoundError,
throwIfSecretsFound
} from 'trufflehog-js';
try {
const results = await scanStagedFiles({ verify: true });
// Throw error if secrets are found (useful for CI/CD)
throwIfSecretsFound(results);
console.log('No secrets detected');
} catch (error) {
if (error instanceof SecretsFoundError) {
console.error(`Found ${error.secretCount} secrets`);
process.exit(1);
} else if (error instanceof BinaryNotFoundError) {
console.error('TruffleHog binary not found. Run: bun install trufflehog-js');
process.exit(2);
} else {
console.error('Unexpected error:', error.message);
process.exit(2);
}
}
TruffleHog-JS is built with a modular architecture focused on reliability and performance:
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ CLI Interface │ │ TypeScript API │ │ Git Integration│
└─────────┬───────┘ └─────────┬───────┘ └─────────┬───────┘
│ │ │
└──────────────────────┼──────────────────────┘
│
┌─────────────▼───────────┐
│ Scanner Engine │
│ ┌─────────────────────┐│
│ │ Binary Manager ││
│ │ ┌─────────────────┐ ││
│ │ │ Cache System │ ││
│ │ └─────────────────┘ ││
│ └─────────────────────┘│
└─────────────────────────┘
│
┌─────────────▼───────────┐
│ TruffleHog │
│ Native Binary │
└─────────────────────────┘
- Scanner Engine: Main orchestration layer that coordinates scanning operations
- Binary Manager: Handles TruffleHog binary download, verification, and execution
- Cache System: Efficient caching of downloaded binaries and metadata
- Git Integration: Native Git operations for repository and staged file management
- Error System: Comprehensive error handling with typed exceptions
- Logger System: Configurable logging with multiple output levels
# Run all tests
bun test
# Run specific test suites
bun run test:unit
bun run test:integration
bun run test:performance
# Run tests with coverage
bun test --coverage
# Run performance benchmarks
bun run benchmark
- Unit Tests: Test individual components in isolation
- Integration Tests: Test component interactions and real scanning scenarios
- Performance Tests: Benchmark scanning performance and memory usage
- Bun v1.2.0 or higher
- Git
- Node.js v18+ (for compatibility testing)
# Clone the repository
git clone https://github.com/maloma7/trufflehog-js.git
cd trufflehog-js
# Install dependencies
bun install
# Run type checking
bun run typecheck
# Run linting
bun run lint
# Run all checks
bun run check
# Start development mode (watch mode)
bun run dev
# Format code
bun run format
# Fix linting issues
bun run lint:fix
# Clean build artifacts
bun run clean
Main scanner class providing comprehensive secret detection functionality.
class TruffleHogScanner {
constructor(options?: {
binaryPath?: string;
timeout?: number;
logger?: Logger;
});
scanStagedFiles(options?: ScanOptions): Promise<ScanResult[]>;
scanFiles(files: string[], options?: ScanOptions): Promise<ScanResult[]>;
scanText(content: string, filename?: string): Promise<ScanResult[]>;
}
Represents a detected secret with full context.
interface ScanResult {
detector: string; // Type of secret detected (e.g., 'aws', 'github')
file: string; // File path where secret was found
line: number; // Line number (when available)
verified: boolean; // Whether the secret was verified as active
secret: string; // Redacted secret value
raw: string; // Full TruffleHog output for debugging
}
Configuration options for scanning operations.
interface ScanOptions {
staged?: boolean; // Scan staged files only
quiet?: boolean; // Minimal output
verbose?: boolean; // Detailed output
config?: string; // Custom config file path
timeout?: number; // Scan timeout in milliseconds
verify?: boolean; // Enable secret verification
includeDetectors?: string[]; // Specific detectors to include
excludeDetectors?: string[]; // Detectors to exclude
includePaths?: string[]; // Path patterns to include
excludePaths?: string[]; // Path patterns to exclude
}
// Convenience functions
function scanStagedFiles(options?: ScanOptions): Promise<ScanResult[]>;
function scanFiles(files: string[], options?: ScanOptions): Promise<ScanResult[]>;
function scanText(content: string, filename?: string): Promise<ScanResult[]>;
function throwIfSecretsFound(results: ScanResult[]): void;
// Platform utilities
function getCurrentPlatform(): Platform;
function getPlatformInfo(): PlatformInfo;
function isSupportedPlatform(platform: string, arch: string): boolean;
// Git utilities
function getStagedFiles(workingDir?: string): Promise<string[]>;
function ensureGitRepository(workingDir?: string): Promise<void>;
function getGitRoot(workingDir?: string): Promise<string>;
// Logger utilities
function createLogger(options?: LoggerOptions): Logger;
# Set custom binary path
export TRUFFLEHOG_BINARY_PATH="/usr/local/bin/trufflehog"
# Or download manually
curl -sSfL https://raw.githubusercontent.com/trufflesecurity/trufflehog/main/scripts/install.sh | sh -s -- -b /usr/local/bin
# Fix binary permissions
chmod +x ~/.cache/trufflehog-js/*/trufflehog
# Clear cache and re-download
rm -rf ~/.cache/trufflehog-js
# Check platform support
bunx trufflehog-js --version
# Use custom binary for unsupported platforms
export TRUFFLEHOG_BINARY_PATH="/custom/path/to/trufflehog"
Enable detailed logging for troubleshooting:
# Environment variable
export TRUFFLEHOG_LOG_LEVEL=debug
# CLI flag
bunx trufflehog-js --staged --verbose
# Programmatic
const logger = createLogger({ level: 'debug' });
Code | Meaning | Action |
---|---|---|
0 | No secrets found | Continue (success) |
1 | Secrets detected | Block commit/deployment |
2 | Tool error | Block commit/deployment |
MIT License - see the LICENSE file for details.
- TruffleHog by Truffle Security for the excellent secret scanning engine
- TruffleHog - The original secret scanner
Last Updated: September 21, 2025
Version: 1.0.1
This documentation is a living document and will be updated as the project evolves and new features are added.