feat: add code-sentinel plugin for security scanning and refactoring

Adds security scanning via PreToolUse hooks + refactoring commands:
- PreToolUse hook catches security issues before code is written
- /security-scan command for comprehensive security audit
- /refactor command to apply refactoring patterns
- /refactor-dry command to preview refactoring opportunities
- security-reviewer agent for vulnerability analysis
- refactor-advisor agent for code structure improvements
- security-patterns skill for vulnerability detection rules

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-01-20 12:32:43 -05:00
parent 395daecda8
commit 870ed26510
10 changed files with 512 additions and 0 deletions

View File

@@ -0,0 +1,13 @@
{
"name": "code-sentinel",
"description": "Security scanning and code refactoring tools",
"version": "1.0.0",
"author": {
"name": "Leo Miranda",
"email": "leobmiranda@gmail.com"
},
"homepage": "https://gitea.hotserv.cloud/personal-projects/support-claude-mktplace/src/branch/main/plugins/code-sentinel/README.md",
"repository": "https://gitea.hotserv.cloud/personal-projects/support-claude-mktplace.git",
"license": "MIT",
"keywords": ["security", "refactoring", "code-quality", "static-analysis", "hooks"]
}

View File

@@ -0,0 +1,47 @@
# code-sentinel
Security scanning and code refactoring tools for Claude Code projects.
## Features
### Security Scanning
- **PreToolUse Hook**: Catches vulnerabilities BEFORE code is written
- **Full Audit**: `/security-scan` for comprehensive project review
- **Pattern Detection**: SQL injection, XSS, command injection, secrets, and more
### Refactoring
- **Pattern Library**: Extract method, simplify conditionals, modernize syntax
- **Safe Transforms**: Preview changes before applying
- **Reference Updates**: Automatically updates all call sites
## Commands
| Command | Description |
|---------|-------------|
| `/security-scan` | Full project security audit |
| `/refactor <target>` | Apply refactoring with pattern |
| `/refactor-dry <target>` | Preview opportunities without changes |
## Hooks
- **PreToolUse (Write\|Edit)**: Scans code for security patterns before writing
## Security Patterns Detected
| Category | Examples |
|----------|----------|
| Injection | SQL, Command, Code (eval), XSS |
| Secrets | Hardcoded API keys, passwords |
| Deserialization | Pickle, unsafe YAML |
| Path Traversal | Unsanitized file paths |
## Installation
```bash
/plugin marketplace add https://gitea.hotserv.cloud/personal-projects/support-claude-mktplace.git
/plugin install code-sentinel
```
## Integration
See claude-md-integration.md for CLAUDE.md additions.

View File

@@ -0,0 +1,48 @@
---
description: Code structure and refactoring specialist
---
# Refactor Advisor Agent
You are a software architect specializing in code quality, design patterns, and refactoring.
## Expertise
- Martin Fowler's refactoring catalog
- SOLID principles
- Design patterns (GoF, enterprise, functional)
- Code smells detection
- Cyclomatic complexity analysis
- Technical debt assessment
## Analysis Approach
When analyzing code:
1. **Identify Code Smells**
- Long methods (>20 lines)
- Large classes (>200 lines)
- Long parameter lists (>3 params)
- Duplicate code
- Feature envy
- Data clumps
2. **Assess Structure**
- Single responsibility adherence
- Coupling between modules
- Cohesion within modules
- Abstraction levels
3. **Recommend Refactorings**
- Match smells to appropriate refactorings
- Consider dependencies and side effects
- Prioritize by impact and risk
- Provide step-by-step approach
## Output Style
Be practical:
- Focus on high-impact improvements
- Explain the "why" behind recommendations
- Provide concrete before/after examples
- Consider testing implications

View File

@@ -0,0 +1,50 @@
---
description: Security-focused code review agent
---
# Security Reviewer Agent
You are a security engineer specializing in application security and secure coding practices.
## Expertise
- OWASP Top 10 vulnerabilities
- Language-specific security pitfalls (Python, JavaScript, Go, etc.)
- Authentication and authorization flaws
- Cryptographic misuse
- Input validation and output encoding
- Secure configuration
## Review Approach
When reviewing code:
1. **Identify Trust Boundaries**
- Where does user input enter?
- Where does data leave the system?
- What operations are privileged?
2. **Trace Data Flow**
- Follow user input through the code
- Check for sanitization at each boundary
- Verify output encoding
3. **Check Security Controls**
- Authentication present where needed?
- Authorization checked before actions?
- Secrets properly managed?
- Errors handled without leaking info?
4. **Language-Specific Checks**
Python: eval, pickle, yaml.load, subprocess
JavaScript: innerHTML, eval, prototype pollution
SQL: parameterized queries, ORM usage
Shell: quoting, input validation
## Output Style
Be specific and actionable:
- Quote the vulnerable line
- Explain the attack vector
- Provide the secure alternative
- Rate severity (Critical/High/Medium/Low)

View File

@@ -0,0 +1,26 @@
# Code Sentinel Integration
Add to your project's CLAUDE.md:
## Security & Code Quality
This project uses code-sentinel for security scanning and refactoring.
### Automatic Security Checks
PreToolUse hooks scan all code changes for:
- SQL/Command/Code injection
- XSS vulnerabilities
- Hardcoded secrets
- Unsafe deserialization
Critical issues are blocked. Warnings are noted but allowed.
### Commands
- `/security-scan` - Full project security audit
- `/refactor <target>` - Apply refactoring pattern
- `/refactor-dry <target>` - Preview refactoring opportunities
### Severity Levels
- 🔴 Critical: Must fix immediately
- 🟠 High: Fix before release
- 🟡 Medium: Improve when possible

View File

@@ -0,0 +1,57 @@
---
description: Preview refactoring changes without applying them
---
# Refactor Dry Run
Analyze and preview refactoring opportunities without making changes.
## Usage
```
/refactor-dry <target> [--all]
```
**Target:** File path, function name, or "." for current file
**--all:** Show all opportunities, not just recommended
## Process
1. **Scan Target**
Analyze code for refactoring opportunities.
2. **Score Opportunities**
Each opportunity rated by:
- Impact (how much it improves code)
- Risk (likelihood of breaking something)
- Effort (complexity of the refactoring)
3. **Output**
```
## Refactoring Opportunities: src/handlers.py
### Recommended (High Impact, Low Risk)
1. **extract-method** at lines 45-67
- Extract order validation logic
- Impact: High (reduces complexity from 12 to 4)
- Risk: Low (pure function, no side effects)
- Run: `/refactor src/handlers.py:45 --pattern=extract-method`
2. **use-dataclass** for OrderInput class
- Convert to dataclass with validation
- Impact: Medium (reduces boilerplate)
- Risk: Low
- Run: `/refactor src/models.py:OrderInput --pattern=use-dataclass`
### Optional (Consider Later)
3. **use-fstring** at 12 locations
- Modernize string formatting
- Impact: Low (readability only)
- Risk: None
### Summary
- 2 recommended refactorings
- 1 optional improvement
- Estimated complexity reduction: 35%
```

View File

@@ -0,0 +1,81 @@
---
description: Apply refactoring patterns to improve code structure and maintainability
---
# Refactor
Apply refactoring transformations to specified code.
## Usage
```
/refactor <target> [--pattern=<pattern>]
```
**Target:** File path, function name, or "." for current context
**Pattern:** Specific refactoring pattern (optional)
## Available Patterns
### Structure
| Pattern | Description |
|---------|-------------|
| `extract-method` | Extract code block into named function |
| `extract-class` | Move related methods to new class |
| `inline` | Inline trivial function/variable |
| `rename` | Rename with all references updated |
| `move` | Move function/class to different module |
### Simplification
| Pattern | Description |
|---------|-------------|
| `simplify-conditional` | Flatten nested if/else |
| `remove-dead-code` | Delete unreachable code |
| `consolidate-duplicate` | Merge duplicate code blocks |
| `decompose-conditional` | Break complex conditions into named parts |
### Modernization
| Pattern | Description |
|---------|-------------|
| `use-comprehension` | Convert loops to list/dict comprehensions |
| `use-pathlib` | Replace os.path with pathlib |
| `use-fstring` | Convert .format() to f-strings |
| `use-typing` | Add type hints |
| `use-dataclass` | Convert class to dataclass |
## Process
1. **Analyze Target**
- Parse code structure
- Identify refactoring opportunities
- Check for side effects and dependencies
2. **Propose Changes**
- Show before/after diff
- Explain the improvement
- List affected files/references
3. **Apply (with confirmation)**
- Make changes
- Update all references
- Run existing tests if available
4. **Output**
```
## Refactoring: extract-method
### Target
src/handlers.py:create_order (lines 45-89)
### Changes
- Extracted validation logic → validate_order_input()
- Extracted pricing logic → calculate_order_total()
- Original function now 15 lines (was 44)
### Files Modified
- src/handlers.py
- tests/test_handlers.py (updated calls)
### Metrics
- Cyclomatic complexity: 12 → 4
- Function length: 44 → 15 lines
```

View File

@@ -0,0 +1,64 @@
---
description: Full security audit of codebase - scans all files for vulnerability patterns
---
# Security Scan
Comprehensive security audit of the project.
## Process
1. **File Discovery**
Scan all code files: .py, .js, .ts, .jsx, .tsx, .go, .rs, .java, .rb, .php, .sh
2. **Pattern Detection**
### Critical Vulnerabilities
| Pattern | Risk | Detection |
|---------|------|-----------|
| SQL Injection | High | String concat in SQL queries |
| Command Injection | High | shell=True, os.system with vars |
| XSS | High | innerHTML with user input |
| Code Injection | Critical | eval/exec with external input |
| Deserialization | Critical | pickle.loads, yaml.load unsafe |
| Path Traversal | High | File ops without sanitization |
| Hardcoded Secrets | High | API keys, passwords in code |
| SSRF | Medium | URL from user input in requests |
### Code Quality Issues
| Pattern | Risk | Detection |
|---------|------|-----------|
| Broad Exceptions | Low | `except:` or `except Exception:` |
| Debug Statements | Low | print/console.log with data |
| TODO/FIXME Security | Medium | Comments mentioning security |
| Deprecated Functions | Medium | Known insecure functions |
3. **Output Format**
```
## Security Scan Report
### Critical (Immediate Action Required)
🔴 src/db.py:45 - SQL Injection
Code: `f"SELECT * FROM users WHERE id = {user_id}"`
Fix: Use parameterized query: `cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))`
### High
🟠 config.py:12 - Hardcoded Secret
Code: `API_KEY = "sk-1234..."`
Fix: Use environment variable: `API_KEY = os.environ.get("API_KEY")`
### Medium
🟡 utils.py:78 - Broad Exception
Code: `except:`
Fix: Catch specific exceptions
### Summary
- Critical: X (must fix before deploy)
- High: X (fix soon)
- Medium: X (improve when possible)
```
4. **Exit Code Guidance**
- Critical findings: Recommend blocking merge/deploy
- High findings: Recommend fixing before release
- Medium/Low: Informational

View File

@@ -0,0 +1,15 @@
{
"hooks": {
"PreToolUse": [
{
"matcher": "Write|Edit|MultiEdit",
"hooks": [
{
"type": "prompt",
"prompt": "SECURITY CHECK - Before writing this code, scan for these patterns:\n\n**Critical (BLOCK if found):**\n- eval(), exec() with user input\n- SQL string concatenation (SQL injection)\n- shell=True with user input (command injection)\n- Hardcoded secrets (API keys, passwords, tokens)\n- Pickle/marshal deserialization of untrusted data\n- innerHTML/dangerouslySetInnerHTML with user content (XSS)\n\n**Warning (WARN but allow):**\n- subprocess without input validation\n- File operations without path sanitization\n- HTTP requests without timeout\n- Broad exception catches (except:)\n- Debug/print statements with sensitive data\n\n**Response:**\n- If CRITICAL found: STOP, explain the issue, suggest safe alternative\n- If WARNING found: Note it briefly, proceed with suggestion\n- If clean: Proceed silently (say nothing)\n\nDo NOT announce clean scans. Only speak if issues found."
}
]
}
]
}
}

View File

@@ -0,0 +1,111 @@
---
description: Security vulnerability patterns and detection rules
---
# Security Patterns Skill
## Critical Patterns (Always Block)
### SQL Injection
```python
# VULNERABLE
query = f"SELECT * FROM users WHERE id = {user_id}"
query = "SELECT * FROM users WHERE id = " + user_id
# SAFE
cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))
User.objects.filter(id=user_id)
```
### Command Injection
```python
# VULNERABLE
os.system(f"convert {filename} output.png")
subprocess.run(cmd, shell=True)
# SAFE
subprocess.run(["convert", filename, "output.png"], shell=False)
shlex.quote(filename)
```
### Code Injection
```python
# VULNERABLE
eval(user_input)
exec(user_code)
# SAFE
ast.literal_eval(user_input) # Only for literals
# Use sandboxed execution environment
```
### XSS
```javascript
// VULNERABLE
element.innerHTML = userContent;
dangerouslySetInnerHTML={{__html: userData}}
// SAFE
element.textContent = userContent;
DOMPurify.sanitize(userContent)
```
### Hardcoded Secrets
```python
# VULNERABLE
API_KEY = "sk-1234567890abcdef"
password = "admin123"
# SAFE
API_KEY = os.environ.get("API_KEY")
password = get_secret("db_password")
```
### Unsafe Deserialization
```python
# VULNERABLE
data = pickle.loads(user_data)
config = yaml.load(file) # yaml.load without Loader
# SAFE
data = json.loads(user_data)
config = yaml.safe_load(file)
```
## Warning Patterns (Flag but Allow)
### Broad Exception Handling
```python
# WARNING
try:
risky_operation()
except:
pass
# BETTER
try:
risky_operation()
except SpecificError as e:
logger.error(f"Operation failed: {e}")
raise
```
### Missing Timeout
```python
# WARNING
response = requests.get(url)
# BETTER
response = requests.get(url, timeout=30)
```
### Path Traversal Risk
```python
# WARNING
file_path = os.path.join(base_dir, user_filename)
# BETTER
file_path = os.path.join(base_dir, os.path.basename(user_filename))
if not file_path.startswith(os.path.abspath(base_dir)):
raise ValueError("Invalid path")
```