Leak Shield 🛡️
Leak Shield is a local, privacy-first VS Code extension that scans source code and configuration files to detect credentials, API keys, private keys, tokens, and database secrets before they are committed or leaked.
Why Leak Shield?
Accidental credential exposure is one of the most common and costly security mistakes in software development. Many existing scanning tools rely on remote cloud APIs (which paradoxically transmit your source code to external servers), require complex CI/CD configurations, or produce overwhelming false positives.
Leak Shield is built on three core principles:
- 100% Local & Private: Operates entirely offline with zero telemetry, zero network calls, and no secret storage.
- Low False Positives: Focuses on high-confidence patterns and uses Shannon entropy heuristics alongside strict suppression for common placeholders (
your-api-key, changeme, test, dummy).
- Seamless In-Editor Experience: Runs automatically as you code, presenting findings via native VS Code diagnostics, hovers, and quick-fixes.
How It Works: The Automatic Workflow
💡 You do NOT need to repeatedly open the Command Palette.
Leak Shield is designed to operate passively in the background without interrupting your workflow.
The primary workflow is fully automatic:
1. Open / Edit / Save a File
│
▼
2. Automatic Background Scan (Debounced)
│
▼
3. Native Diagnostics Appear (Squiggly Underlines & Problems Panel)
│
▼
4. Hover to Inspect (Safe Redacted Preview & Remediation Advice)
│
▼
5. Apply Quick Fix (Explain Finding or Add Inline Ignore Comment)
- Automatic Scanning: Whenever you open, edit, or save a supported file, Leak Shield automatically scans the content.
- Clear Diagnostics: Detected secrets are underlined directly in the editor and listed in the VS Code Problems tab with masked previews (e.g.
AKIA...****...PLE).
- Informative Hovers: Hovering over any flagged range displays a markdown tooltip with finding details, confidence level, entropy rating, and remediation advice.
- Quick-Fix Code Actions: Click the lightbulb (or press
Cmd+. / Ctrl+.) to:
- Move Secret to Environment Variable: Automatically replaces hardcoded credentials with
process.env.VAR or os.environ["VAR"], generates .env entries, and shows an interactive review dialog.
- Explain Finding: Open a safe dialog summarizing the finding, confidence rating, and remediation steps.
- Ignore Line: Insert a language-appropriate ignore comment (
// leak-shield-ignore or # leak-shield-ignore).
Command Palette commands (Scan Workspace, Scan Current File, Clear Diagnostics) are available whenever you need manual or workspace-wide controls.
Supported Detections
Leak Shield includes deterministic detectors for high-risk credentials:
| Category |
Detector |
Recognized Formats / Patterns |
| Cloud Providers |
AWS Credentials |
Access Key IDs (AKIA..., ASIA..., ABIA..., ACCA...) and paired Secret Access Keys |
|
Google Cloud |
Google Cloud API Keys (AIza...) |
| Version Control |
GitHub Tokens |
Classic PATs (ghp_...), Fine-Grained PATs (github_pat_...), OAuth tokens (gho_...), User/Server tokens (ghu_..., ghs_...), and Refresh tokens (ghr_...) |
| Cryptography |
Private Keys |
PEM and OpenSSH private key blocks (RSA, DSA, EC, OPENSSH, PGP, ENCRYPTED), including JSON-escaped strings |
| SaaS & Services |
Stripe |
Live Secret Keys (sk_live_...), Restricted Keys (rk_live_...), and Webhook Secrets (whsec_...) |
|
Slack |
Bot Tokens (xoxb-...) and User Tokens (xoxp-...) |
|
Email & SMS |
SendGrid API Keys (SG....) and Twilio API Keys (SK...) |
|
AI Platforms |
OpenAI API Keys (sk-...) and Anthropic API Keys (sk-ant-...) |
|
Package Registries |
NPM Access Tokens (npm_...) and PyPI API Tokens (pypi-...) |
| Authentication |
JSON Web Tokens (JWT) |
Valid 3-segment base64url tokens with verified JSON algorithm headers (eyJ...) |
| Databases |
Database URLs |
URIs with embedded passwords (postgres://, mysql://, mongodb://, redis://, amqp://) |
| Generic Heuristics |
Generic Secret Assignments |
Variable assignments (API_KEY = "...", SECRET = "...", token: "...") validated with Shannon entropy ($\ge 3.2$ bits/char) and placeholder filtering |
| Custom Rules |
Custom Patterns |
User-defined regular expressions configured in settings |
Supported File Types
Leak Shield is syntax-independent and scans all standard text and source files:
- Languages: JavaScript, TypeScript, Python, Go, Rust, Java, Kotlin, C, C++, C#, Ruby, PHP, Shell (Bash/Zsh/Sh)
- Configuration & Data: JSON, YAML, TOML, XML, Markdown, Plaintext,
.env templates
Binary files (images, archives, compiled executables, fonts, bytecode) and files exceeding the size limit are automatically skipped.
Privacy & Security Guarantees
Leak Shield was designed from the ground up to guarantee strict privacy:
- Zero Network Access: No HTTP, WebSocket, DNS, or external API calls. Works completely offline in air-gapped environments.
- No Telemetry: No analytics, telemetry events, tracking pixels, or diagnostic phone-homes.
- No Secret Storage: Raw secrets are never saved to disk, temp directories, workspace storage, or the clipboard.
- Redaction Everywhere: Diagnostics, hovers, status bars, and inspection dialogs mask secret values (e.g.
AKIA...****...PLE or postgres://user:****@host:5432/db).
- Workspace Boundary Enforcement: Directory scans strictly respect the workspace boundary and will not follow symlinks outside the project root.
- No Shell Execution: Does not execute shell commands or arbitrary external scripts during standard scanning.
Leak Shield provides a conservative, minimal-diff Quick Fix action to move detected secrets into environment variables without risking code corruption.
Product Philosophy
Detect locally
↓
Explain the finding
↓
Offer a safe fix when possible
↓
Show reviewable preview
↓
Apply the smallest possible edit
↓
Optionally protect future commits
- JavaScript / TypeScript direct assignment:
const API_KEY = "actual-secret"; → const API_KEY = process.env.API_KEY;
- JavaScript / TypeScript camelCase declaration:
const apiKey = "actual-secret"; → const apiKey = process.env.API_KEY;
- JavaScript / TypeScript object property:
apiKey: "actual-secret" → apiKey: process.env.API_KEY
- Python direct assignment:
API_KEY = "actual-secret" → API_KEY = os.environ["API_KEY"]
(Strict constraint: ONLY offered if import os already exists in the file. Imports are never automatically injected.)
Patterns Intentionally NOT Auto-Fixed
Leak Shield never guesses when automated edits could break code. Automatic remediation is intentionally declined for:
- Secrets embedded inside arbitrary strings (
"https://user:SECRET@db.example.com")
- Concatenated strings (
"prefix-" + "SECRET")
- Template literals (
`https://${SECRET}`)
- Function arguments (
connect("SECRET"))
- Array elements (
["SECRET"])
- Ambiguous identifiers (
const x = "secret") without explicit user naming
- Existing
.env files
Conservative Minimal-Diff Editing
- Smallest Possible Edit: Replaces only the exact string literal and its enclosing quotes. Surrounding formatting, indentation, commas, semicolons, comments, and line endings are preserved.
- Full Pre-Validation: The entire multi-file remediation plan is validated prior to making any edit. If validation fails or you cancel, no files are modified.
- Environment Files: Safely appends or updates
.env without deleting or corrupting existing variables or comments. If a key already exists, explicit confirmation is required.
- Example Files: Appends
${KEY}= to .env.example without ever exposing the real secret.
- Git Ignore: Verifies whether
.env is ignored by Git and offers to add a minimal .env entry if unignored.
In addition to individual Quick Fixes, Leak Shield supports bulk remediation:
- Remediate All Secrets in This File (
leak-shield.remediateCurrentFile): Available via Command Palette or Quick Fix when multiple remediable secrets are found in the active file.
- Remediate All Secrets in Workspace (
leak-shield.remediateWorkspace): Scans project files and aggregates all remediable secrets into a single coordinated remediation plan.
- Unified Reviewable Preview: Displays a native VS Code QuickPick detailing all proposed replacements,
.env entries, .env.example templates, .gitignore status, and clearly flags any skipped unsafe/ambiguous findings with detailed explanations before applying changes.
- Variable Deduplication & Collision Protection: Reuses environment variable names when the secret value matches; flags collisions if identical variable names have conflicting secret values.
Optional Git Pre-Commit Secret Protection
Leak Shield includes an opt-in Git pre-commit hook that scans the staged content in your Git index before commits are finalized.
Activation UX
- Contextual First-Time Prompt: When opening a Git repository, Leak Shield non-intrusively notifies you:
Enable for This Workspace: Provisions the hook for the active repository and enables protection in workspace settings.
Enable for All Workspaces: Provisions the hook and sets leakShield.gitProtection.globalAutoEnable = true, automatically provisioning repo-level protection on any Git repository opened in the future without nagging.
Not Now: Suppresses the prompt for this workspace.
- Command Palette Controls: Configure at any time via
Leak Shield: Enable/Disable Git Protection or Leak Shield: Enable/Disable Git Protection for All Workspaces.
Key Behaviors
- Scans Staged Content Only: Evaluates the Git index (
git show :<file>) rather than your working tree:
- If a secret is staged in the index $\rightarrow$ the commit is blocked.
- If a secret is in your working tree but unstaged $\rightarrow$ the commit is allowed.
- Safe Coexistence: Uses delimited marker blocks (
# BEGIN LEAK SHIELD PRE-COMMIT HOOK ... # END LEAK SHIELD PRE-COMMIT HOOK). When no secrets are found, the hook falls through so existing linters, formatters, and test suites run normally.
- Active Hooks Path Resolution: Dynamically resolves repository Git hooks path via
git rev-parse --git-path hooks and respects core.hooksPath.
- Self-Contained Offline Runner: Runs independently via Node.js without requiring VS Code to be active.
- Privacy & Safety: Finding locations and detector names are displayed with masked values. Raw secrets are never printed in terminal hook output.
Commands
Access manual controls via the Command Palette (Ctrl+Shift+P / Cmd+Shift+P):
- Leak Shield: Open Menu (
leak-shield.showMenu) — Opens the interactive status bar menu with contextual remediation, scanning, and Git protection actions.
- Leak Shield: Scan Current File (
leak-shield.scanCurrentFile) — Forces an immediate scan of the active document.
- Leak Shield: Scan Workspace (
leak-shield.scanWorkspace) — Performs a full workspace scan with progress reporting and cancellation support.
- Leak Shield: Clear Diagnostics (
leak-shield.clearDiagnostics) — Clears all active Leak Shield diagnostics.
- Leak Shield: Explain Finding (
leak-shield.explainFinding) — Opens safe finding details for the secret at cursor position or active file.
- Leak Shield: Remediate All Secrets in This File (
leak-shield.remediateCurrentFile) — Bulk remediates all safe secrets in the active file into environment variables.
- Leak Shield: Remediate All Secrets in Workspace (
leak-shield.remediateWorkspace) — Bulk remediates all safe secrets across the workspace into environment variables.
- Leak Shield: Enable Git Protection (
leak-shield.enableGitProtection) — Configures pre-commit secret scanning for the active repository.
- Leak Shield: Disable Git Protection (
leak-shield.disableGitProtection) — Safely removes Leak Shield pre-commit hook configuration for the active repository.
- Leak Shield: Enable Git Protection for All Workspaces (
leak-shield.enableGitProtectionAll) — Enables automatic Git pre-commit secret scanning for all workspaces.
- Leak Shield: Disable Git Protection for All Workspaces (
leak-shield.disableGitProtectionAll) — Disables automatic Git pre-commit protection across all workspaces.
Configuration
Customize behavior in VS Code Settings (leakShield.*):
| Setting |
Default |
Description |
leakShield.enabled |
true |
Enable or disable all Leak Shield scanning. |
leakShield.gitProtection.enabled |
false |
Enable optional Git pre-commit secret scanning protection in workspace. |
leakShield.gitProtection.globalAutoEnable |
false |
Automatically provision Git pre-commit protection for all Git repositories opened in VS Code. |
leakShield.gitProtection.promptDismissed |
false |
Suppress the first-time Git repository protection prompt in this workspace. |
leakShield.scanOnSave |
true |
Automatically scan documents upon saving. |
leakShield.scanOnChange |
true |
Debounced scanning as you edit in the active editor. |
leakShield.scanOnOpen |
true |
Automatically scan documents when opened. |
leakShield.debounceDelayMs |
350 |
Keystroke debounce delay (ms) before triggering live scan. |
leakShield.severity |
"warning" |
Diagnostic severity: "warning", "error", or "information". |
leakShield.maxFileSizeKB |
2048 |
Maximum file size in KB to scan (default 2 MB). |
leakShield.minEntropy |
3.2 |
Shannon entropy threshold for generic secret heuristics. |
leakShield.ignoredPatterns |
[...] |
Glob patterns for paths to exclude (e.g. node_modules, dist, .git). |
leakShield.customPatterns |
[] |
Array of custom regex patterns for proprietary tokens. |
Example: Custom Pattern Configuration
{
"leakShield.customPatterns": [
{
"id": "corp-api-key",
"name": "Acme Internal Token",
"regex": "acme_token_[0-9a-zA-Z]{32}",
"confidence": "high",
"description": "Internal Acme microservice authentication key."
}
]
}
Ignoring Findings
Line-Level Ignore
Append // leak-shield-ignore or # leak-shield-ignore to any line:
const testKey = "AKIA...DEMO_KEY"; // leak-shield-ignore
File-Level Ignore
Add // leak-shield-ignore-file or # leak-shield-ignore-file at the top of a file to bypass scanning for that entire file:
// leak-shield-ignore-file
Examples (Using Synthetic Credentials)
Note: All examples below use illustrative synthetic placeholders.
AWS Access Key ID
// Flagged: Possible AWS Access Key ID detected [HIGH confidence]
const awsKey = "AKIA" + "...[16-char ID]";
Database URL with Password
// Flagged: Database connection string containing embedded credentials [HIGH confidence]
const dbUrl = "postgres://appuser:[REDACTED]@db.internal:5432/production";
Suppressed Placeholders (Low False-Positive Philosophy)
// NOT flagged: Known non-secret placeholders are automatically suppressed
const key1 = "your-api-key";
const key2 = "changeme";
const key3 = "placeholder";
const key4 = "YOUR_API_KEY";
Installation
From VS Code Marketplace
Search for Leak Shield in the Extensions view (Ctrl+Shift+X / Cmd+Shift+X) and click Install.
From VSIX
- Download
leak-shield-1.1.0.vsix from the Releases page.
- In VS Code, run
Extensions: Install from VSIX... from the Command Palette and select the downloaded file.
Development & Testing
# Clone the repository
git clone https://github.com/AJ-Kaarthick/leak-shield.git
cd leak-shield
# Install dependencies
npm install
# Run unit and integration tests
npm test
# Type-check TypeScript
npm run typecheck
# Build production bundle with esbuild
npm run build
# Package extension into VSIX
npm run package
Limitations & Disclaimer
- Heuristic Nature: Leak Shield uses deterministic regex patterns, Shannon entropy heuristics, and syntactic checks. It does not guarantee that all secrets will be caught, nor does it verify if a detected secret is active on external services.
- Defense in Depth: Leak Shield serves as an in-editor developer safety net. It should be used alongside pre-commit hooks, secret rotation policies, and CI/CD secret scanning.
Issues & Feedback
Found a bug or have a suggestion? Please open an issue on GitHub:
👉 https://github.com/AJ-Kaarthick/leak-shield/issues
License
MIT © ajkaarthick
| |