CodeGuard
Real-time code quality and security analysis - Grammarly for code
CodeGuard is a VSCode extension that provides instant feedback on code quality, security vulnerabilities, performance issues, and code smells as you type. It acts as your personal code reviewer, catching issues before they reach production.
✨ Why CodeGuard?
- ⚡ Lightning Fast: Analysis completes in <100ms for most files
- 🔒 Privacy First: All analysis runs locally by default - your code never leaves your machine
- 🎯 Accurate: Advanced data flow analysis and entropy filtering minimize false positives
- 🤖 AI-Powered: Optional intelligent fix suggestions (supports OpenAI, Claude, and local Ollama)
- 🔧 Customizable: Fine-tune rules, severities, and behavior to match your team's standards
- 🌍 Multi-Language: Supports JavaScript, TypeScript, Python, and Java
Features
🔒 Security Analysis
Detect security vulnerabilities before they reach production:
- SQL Injection: Identifies unsafe string concatenation in SQL queries with data flow analysis
- XSS (Cross-Site Scripting): Detects unescaped user input in HTML contexts
- Command Injection: Finds user input in shell command execution
- Path Traversal: Catches unsafe file path operations
- Unsafe Deserialization: Identifies dangerous deserialization patterns
Example Detection:
// ❌ CodeGuard will flag this
const query = "SELECT * FROM users WHERE id = " + userId;
// ✅ This is safe
const query = db.prepare("SELECT * FROM users WHERE id = ?").bind(userId);
🔍 Secret Scanning
Prevent credential leaks with intelligent secret detection:
- AWS Access Keys: Detects AKIA... patterns
- API Keys: Generic API key patterns with entropy analysis
- Hardcoded Passwords: Finds password assignments in plain text
- JWT Tokens: Identifies JWT token patterns
- Private Keys: Detects PEM-formatted private keys
Smart Entropy Filtering: Uses Shannon entropy to distinguish real secrets from test data, reducing false positives.
Example Detection:
// ❌ High entropy - flagged as potential secret
const apiKey = "sk-live-[REDACTED]";
// ✅ Low entropy - ignored as test data
const apiKey = "test_key_12345";
Catch performance issues early:
- Nested Loops: Detects O(n³) or worse complexity
- Blocking Operations: Finds synchronous I/O in async contexts
- Memory Leaks: Identifies unclosed resources and event listeners
- Inefficient String Operations: Catches string concatenation in loops
- Unnecessary Re-computations: Detects redundant calculations
Example Detection:
// ❌ CodeGuard will warn about O(n³) complexity
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
for (let k = 0; k < n; k++) {
// nested operations
}
}
}
// ❌ Blocking operation in async context
async function loadData() {
const data = fs.readFileSync('file.txt'); // Should use readFile
}
🧹 Code Quality
Maintain clean, maintainable code:
- Long Functions: Flags functions exceeding 50 lines
- Cyclomatic Complexity: Warns when complexity exceeds 10
- Duplicate Code: Detects duplicate blocks exceeding 6 lines
- Too Many Parameters: Flags functions with more than 5 parameters
- Deep Nesting: Warns about nesting exceeding 4 levels
Example Detection:
// ❌ Too many parameters
function createUser(name, email, age, address, phone, role, department) {
// ...
}
// ✅ Better approach
function createUser(userData) {
const { name, email, age, address, phone, role, department } = userData;
// ...
}
🤖 AI-Powered Fixes (Optional)
Get intelligent, context-aware fix suggestions:
- Multiple AI Providers: OpenAI GPT-4, Anthropic Claude, or local Ollama
- Context-Aware: Understands your code context for better suggestions
- Detailed Explanations: Each fix includes why it's better
- Privacy Conscious: Only sends minimal code context (never entire files)
- Fallback Support: Rule-based fixes when AI is unavailable
Example AI Fix:
// Your code with issue
const query = "SELECT * FROM users WHERE id = " + userId;
// AI suggests (with explanation)
const query = db.prepare("SELECT * FROM users WHERE id = ?").bind(userId);
// Explanation: Using parameterized queries prevents SQL injection by
// separating SQL logic from user data. The database driver handles
// proper escaping automatically.
📦 Installation
From VSCode Marketplace (Recommended)
- Open VSCode
- Go to Extensions (Ctrl+Shift+X / Cmd+Shift+X)
- Search for "CodeGuard"
- Click Install
From VSIX File
code --install-extension codeguard-0.1.0.vsix
From Source
git clone https://github.com/lekhanpro/CodeGuard.git
cd codeguard
npm install
npm run compile
code --install-extension .
🚀 Quick Start
- Install the extension (see above)
- Open a supported file (JavaScript, TypeScript, Python, or Java)
- Start typing - CodeGuard automatically analyzes your code
- View issues in the editor, Problems panel, or status bar
- Apply fixes using quick actions (lightbulb icon or Ctrl+.)
First-Time Setup
For AI-powered features (optional):
- Open Settings (Ctrl+, / Cmd+,)
- Search for "CodeGuard"
- Enable AI: Set
codeguard.ai.enabled to true
- Choose provider: Set
codeguard.ai.provider to ollama, openai, or claude
- Configure credentials (if needed)
Alternative: Copy .env.example to .env and configure your API keys there (see .env.example for all available options).
💡 Usage
Automatic Analysis
CodeGuard automatically activates when you open supported files and analyzes your code as you type:
- Debounced: Analysis triggers 500ms after you stop typing (configurable)
- Fast: Completes in <100ms for most files
- Non-blocking: Runs in background worker threads
- Incremental: Only analyzes changed regions in large files (>5000 lines)
Viewing Issues
Issues appear in multiple places:
Editor: Inline squiggly underlines
- Red: Errors (security issues, secrets)
- Yellow: Warnings (performance issues, high complexity)
- Blue: Info (code smells, suggestions)
Problems Panel: View → Problems (Ctrl+Shift+M / Cmd+Shift+M)
- Grouped by file and severity
- Click to jump to issue location
Status Bar: Bottom-right corner
- Shows total issue count by severity
- Click to open Problems panel
Quick Actions
Hover over any issue or press Ctrl+. (Cmd+. on Mac) to see available actions:
1. Fix with AI 🤖
Get intelligent, context-aware fix suggestions:
- Analyzes the issue and surrounding code
- Provides multiple fix options when applicable
- Includes detailed explanations
- Shows preview before applying
Requirements: AI must be enabled and configured
2. Ignore Issue 🚫
Suppress specific issues:
- Adds rule to
.codeguardignore file
- Can ignore by rule ID, file pattern, or line number
- Persists across sessions
- Team-shareable via version control
Example .codeguardignore:
{
"version": "1.0",
"rules": [
{
"ruleId": "sql-injection",
"filePattern": "src/legacy/**",
"reason": "Legacy code - scheduled for refactor"
},
{
"ruleId": "long-function",
"lineNumber": 42,
"reason": "Complex business logic - cannot be simplified"
}
]
}
3. Explain Issue 📖
View detailed documentation:
- What the issue is
- Why it's problematic
- How to fix it
- Code examples (good and bad)
- Related resources
Manual Analysis
Trigger analysis manually when needed:
Command Palette (Ctrl+Shift+P / Cmd+Shift+P):
CodeGuard: Analyze Current File - Analyze active file
CodeGuard: Clear All Diagnostics - Clear all issues
CodeGuard: Toggle Analysis On/Off - Enable/disable CodeGuard
Keyboard Shortcuts:
Ctrl+Shift+G / Cmd+Shift+G - Analyze current file
Ctrl+Shift+Alt+G / Cmd+Shift+Alt+G - Toggle on/off
Context Menu:
- Right-click in editor → "CodeGuard: Analyze Current File"
⚙️ Configuration
CodeGuard can be configured through VSCode settings or a .codeguardrc.json file in your workspace root.
Configuration Priority
Settings are merged in this order (highest priority first):
.codeguardrc.json in workspace root
- VSCode workspace settings
- VSCode user settings
- Default configuration
Basic Settings
Via VSCode Settings (Settings → Extensions → CodeGuard):
{
"codeguard.enabled": true,
"codeguard.debounceMs": 500,
"codeguard.maxAnalysisTimeMs": 5000
}
Via .codeguardrc.json:
{
"enabled": true,
"debounceMs": 500,
"maxAnalysisTimeMs": 5000,
"analyzers": {
"security": { "enabled": true },
"performance": { "enabled": true },
"secrets": { "enabled": true },
"codeSmells": { "enabled": true }
}
}
Analyzer Configuration
Enable or disable specific analyzers:
{
"codeguard.analyzers.security.enabled": true,
"codeguard.analyzers.performance.enabled": true,
"codeguard.analyzers.secrets.enabled": true,
"codeguard.analyzers.codeSmells.enabled": true
}
Customize severity levels (in .codeguardrc.json):
{
"analyzers": {
"security": {
"enabled": true,
"severity": {
"sql-injection": "error",
"xss": "error",
"command-injection": "warning"
}
},
"codeSmells": {
"enabled": true,
"severity": {
"long-function": "info",
"high-complexity": "warning",
"too-many-params": "info"
}
}
}
}
AI Configuration
Option 1: Local AI with Ollama (Recommended for Privacy)
Free, private, and runs on your machine
- Install Ollama: https://ollama.ai
- Pull a code model:
ollama pull codellama
# or
ollama pull deepseek-coder
- Configure CodeGuard:
{
"codeguard.ai.enabled": true,
"codeguard.ai.provider": "ollama",
"codeguard.ai.model": "codellama"
}
Supported Ollama Models:
codellama - Meta's Code Llama (7B, 13B, 34B)
deepseek-coder - DeepSeek Coder (1.3B, 6.7B, 33B)
phind-codellama - Phind's fine-tuned Code Llama
wizardcoder - WizardCoder models
Option 2: OpenAI GPT
Requires API key (paid)
- Get API key: https://platform.openai.com/api-keys
- Configure CodeGuard:
{
"codeguard.ai.enabled": true,
"codeguard.ai.provider": "openai",
"codeguard.ai.apiKey": "sk-...",
"codeguard.ai.model": "gpt-4"
}
Supported Models:
gpt-4 - Most capable (recommended)
gpt-4-turbo - Faster, cheaper
gpt-3.5-turbo - Fastest, cheapest
Option 3: Anthropic Claude
Requires API key (paid)
- Get API key: https://console.anthropic.com/
- Configure CodeGuard:
{
"codeguard.ai.enabled": true,
"codeguard.ai.provider": "claude",
"codeguard.ai.apiKey": "sk-ant-...",
"codeguard.ai.model": "claude-3-sonnet-20240229"
}
Supported Models:
claude-3-opus-20240229 - Most capable
claude-3-sonnet-20240229 - Balanced (recommended)
claude-3-haiku-20240307 - Fastest, cheapest
Advanced AI Settings
{
"codeguard.ai.enabled": true,
"codeguard.ai.provider": "openai",
"codeguard.ai.apiKey": "sk-...",
"codeguard.ai.model": "gpt-4",
"codeguard.ai.maxTokens": 1000,
"codeguard.ai.temperature": 0.2,
"codeguard.ai.timeout": 3000
}
Cache Configuration
Control caching behavior for performance:
{
"codeguard.cache.enabled": true,
"codeguard.cache.maxMemoryMB": 50,
"codeguard.cache.maxDiskMB": 500,
"codeguard.cache.ttlSeconds": 3600
}
Cache Behavior:
- Memory Cache: Fast LRU cache (50MB default)
- Disk Cache: Persistent SQLite cache (500MB default)
- Content-Based: Uses SHA-256 hash of file content as key
- Automatic Eviction: LRU eviction when limits exceeded
- Persistence: Survives VSCode restarts
Privacy Settings
Control network features and data sharing:
{
"codeguard.privacy.disableNetworkFeatures": false,
"codeguard.privacy.disableTelemetry": true
}
Privacy Guarantees:
- ✅ All static analysis runs locally (no network calls)
- ✅ AI features are optional and disabled by default
- ✅ When AI is enabled, only minimal context is sent (never entire files)
- ✅ No telemetry or tracking by default
- ✅ No code logging or transmission to external services
Disable All Network Features:
{
"codeguard.privacy.disableNetworkFeatures": true
}
This disables:
- AI fix suggestions
- Telemetry and error reporting
- Update checks
Optimize for your workflow:
{
"codeguard.debounceMs": 500, // Delay before analysis (ms)
"codeguard.maxAnalysisTimeMs": 5000, // Timeout per analyzer (ms)
"codeguard.cache.enabled": true, // Enable caching
"codeguard.incrementalThreshold": 5000 // Lines before incremental analysis
}
Performance Tips:
- Increase debounce (e.g., 1000ms) if you type very fast
- Decrease debounce (e.g., 300ms) for more immediate feedback
- Disable analyzers you don't need for faster analysis
- Enable caching for instant results on unchanged files
- Incremental analysis automatically activates for large files
Team Configuration
Share configuration across your team using .codeguardrc.json:
{
"version": "1.0",
"enabled": true,
"debounceMs": 500,
"analyzers": {
"security": {
"enabled": true,
"severity": {
"sql-injection": "error",
"xss": "error",
"command-injection": "error"
}
},
"codeSmells": {
"enabled": true,
"severity": {
"long-function": "warning",
"high-complexity": "warning"
},
"customRules": {
"maxFunctionLines": 100,
"maxComplexity": 15,
"maxParameters": 4
}
}
},
"ai": {
"enabled": false,
"provider": "none"
},
"privacy": {
"disableNetworkFeatures": false,
"disableTelemetry": true
}
}
Commit this file to version control to ensure consistent analysis across your team.
🔐 Privacy & Security
CodeGuard is designed with privacy as a core principle:
Local-First Architecture
- ✅ All static analysis runs locally on your machine
- ✅ No network requests for security, performance, secrets, or code smell detection
- ✅ No code transmission to external services by default
- ✅ No telemetry or tracking unless explicitly enabled
AI Privacy
When AI features are enabled:
- ✅ Minimal context only: Sends problematic code snippet + 10 lines of context (never entire files)
- ✅ Optional feature: AI is disabled by default
- ✅ Local AI option: Use Ollama for completely local AI processing
- ✅ Transparent: You control what data is sent and when
Data Storage
- ✅ Local cache only: Analysis results cached locally in SQLite
- ✅ No cloud sync: Cache never leaves your machine
- ✅ Configurable: Can disable caching entirely if desired
Network Features
Control network access:
{
"codeguard.privacy.disableNetworkFeatures": true
}
This disables:
- AI fix suggestions
- Telemetry and error reporting
- Update checks
Result: CodeGuard functions entirely offline with zero network activity.
CodeGuard is optimized for speed and efficiency:
- ⚡ <100ms analysis for files under 1000 lines
- ⚡ Incremental analysis for large files (>5000 lines)
- ⚡ Parallel execution of all analyzers
- ⚡ Smart caching with content-based hashing
- ⚡ Worker threads for non-blocking analysis
Memory Efficiency
- 💾 <5MB idle when no supported files are open
- 💾 50MB memory cache with LRU eviction
- 💾 500MB disk cache for persistent results
- 💾 Automatic cleanup when limits exceeded
- 🚀 <500ms activation time
- 🚀 Lazy loading of analyzers
- 🚀 Cached results available immediately on restart
Optimization Features
- Debouncing: Waits 500ms after typing stops before analyzing
- Incremental Analysis: Only analyzes changed regions in large files
- Content Hashing: Skips analysis for unchanged files
- Parallel Execution: All analyzers run concurrently
- Worker Threads: CPU-intensive work runs off main thread
🌍 Supported Languages
| Language |
Security |
Secrets |
Performance |
Code Smells |
| JavaScript |
✅ |
✅ |
✅ |
✅ |
| TypeScript |
✅ |
✅ |
✅ |
✅ |
| Python |
✅ |
✅ |
✅ |
✅ |
| Java |
✅ |
✅ |
✅ |
✅ |
Language-Specific Features
JavaScript/TypeScript:
- Type-aware analysis for TypeScript
- React-specific patterns (XSS in JSX)
- Node.js security patterns
- Async/await performance checks
Python:
- Django/Flask security patterns
- Async/await performance checks
- Python-specific code smells
Java:
- JDBC security patterns
- Spring framework patterns
- Java-specific performance issues
🛠️ Troubleshooting
Common Issues
Issue: CodeGuard not activating
Solution:
- Check file language is supported (JavaScript, TypeScript, Python, Java)
- Verify extension is enabled:
codeguard.enabled: true
- Check Output panel (View → Output → CodeGuard) for errors
- Reload VSCode:
Developer: Reload Window
Issue: Analysis is slow
Solution:
- Enable caching:
codeguard.cache.enabled: true
- Increase debounce:
codeguard.debounceMs: 1000
- Disable unused analyzers
- Check file size - incremental analysis activates at 5000 lines
Issue: Too many false positives
Solution:
- Use "Ignore Issue" action to suppress specific warnings
- Adjust severity levels in
.codeguardrc.json
- Disable specific rules you don't need
- Report false positives as issues on GitHub
Issue: AI fixes not working
Solution:
- Verify AI is enabled:
codeguard.ai.enabled: true
- Check provider is configured:
codeguard.ai.provider
- Verify API key (if using OpenAI/Claude)
- Check network connectivity (unless using Ollama)
- View Output panel for AI service errors
Issue: High memory usage
Solution:
- Reduce memory cache:
codeguard.cache.maxMemoryMB: 25
- Reduce disk cache:
codeguard.cache.maxDiskMB: 250
- Disable caching:
codeguard.cache.enabled: false
- Close unused files
Debug Mode
Enable verbose logging:
- Open Output panel (View → Output)
- Select "CodeGuard" from dropdown
- Set log level in settings:
{
"codeguard.logLevel": "debug"
}
Getting Help
📚 Examples
Example 1: Detecting SQL Injection
Before:
function getUser(userId) {
const query = "SELECT * FROM users WHERE id = " + userId;
return db.execute(query);
}
CodeGuard Detection:
- ❌ Error: SQL injection vulnerability detected
- 💡 Suggestion: Use parameterized queries
After (with AI fix):
function getUser(userId) {
const query = "SELECT * FROM users WHERE id = ?";
return db.execute(query, [userId]);
}
Example 2: Detecting Secrets
Before:
const config = {
apiKey: "sk-live-[REDACTED]",
dbPassword: "MySecretPassword123"
};
CodeGuard Detection:
- ❌ Error: API key detected (high entropy)
- ❌ Error: Hardcoded password detected
After:
const config = {
apiKey: process.env.API_KEY,
dbPassword: process.env.DB_PASSWORD
};
Before:
async function processData(items) {
let result = "";
for (let item of items) {
result += item.toString(); // Inefficient string concatenation
}
const data = fs.readFileSync('config.json'); // Blocking in async
return result;
}
CodeGuard Detection:
- ⚠️ Warning: Inefficient string concatenation in loop
- ⚠️ Warning: Blocking operation in async function
After:
async function processData(items) {
const result = items.map(item => item.toString()).join('');
const data = await fs.promises.readFile('config.json');
return result;
}
Example 4: Detecting Code Smells
Before:
function processOrder(orderId, userId, productId, quantity, price, discount, shippingAddress, billingAddress, paymentMethod) {
// 80 lines of complex logic...
if (condition1) {
if (condition2) {
if (condition3) {
if (condition4) {
if (condition5) {
// deeply nested code
}
}
}
}
}
}
CodeGuard Detection:
- ℹ️ Info: Function exceeds 50 lines (80 lines)
- ℹ️ Info: Too many parameters (9 parameters)
- ⚠️ Warning: Deep nesting detected (5 levels)
- ⚠️ Warning: High cyclomatic complexity (15)
After:
function processOrder(orderData) {
validateOrder(orderData);
const payment = processPayment(orderData);
const shipping = scheduleShipping(orderData);
return createOrderRecord(orderData, payment, shipping);
}
// Split into smaller, focused functions
function validateOrder(orderData) { /* ... */ }
function processPayment(orderData) { /* ... */ }
function scheduleShipping(orderData) { /* ... */ }
function createOrderRecord(orderData, payment, shipping) { /* ... */ }
📚 Documentation
User Documentation
Developer Documentation
Additional Resources
🤝 Contributing
Contributions are welcome! Please see CONTRIBUTING.md for details on:
- Development setup
- Code style guidelines
- Testing requirements
- Pull request process
- Adding new analyzers
- Adding new AI providers
📄 License
MIT License - see LICENSE for details.
🗺️ Roadmap
v0.2.0 (Next Release)
- [ ] Go language support
- [ ] Rust language support
- [ ] Custom rule configuration UI
- [ ] Team-shared rule sets via Git
v0.3.0
- [ ] C++ language support
- [ ] Ruby language support
- [ ] CI/CD integration (GitHub Actions, GitLab CI)
- [ ] Git pre-commit hooks
v0.4.0
- [ ] Hugging Face Inference API support
- [ ] More local AI models
- [ ] Rule marketplace
- [ ] VSCode web support
Future
- [ ] Real-time collaboration features
- [ ] Code quality trends and analytics
- [ ] Integration with issue trackers
- [ ] Custom analyzer SDK
🙏 Acknowledgments
CodeGuard is built with:
Special thanks to:
- The VSCode team for excellent extension APIs
- The open-source security community for vulnerability patterns
- All contributors and users providing feedback
📞 Support
Documentation
Made with ❤️ for developers who care about code quality
CodeGuard - Catch issues before they reach production