| name | security-review |
| description | Comprehensive security audit for code changes. Use this skill when implementing authentication, authorization, user input handling, API endpoints, secrets/credentials, payment features, or file uploads. Provides security checklists, vulnerability patterns, and remediation guidance. Integrates with implement-phase as a security quality gate. |
| allowed-tools | Read, Glob, Grep, Bash |
Security Review Skill
This skill ensures all code follows security best practices and identifies potential vulnerabilities before they reach production.
Design Philosophy
Security is not optional. This skill acts as a security quality gate that validates code against common vulnerability patterns (OWASP Top 10) and project-specific security requirements. One vulnerability can compromise the entire platform.
When to Activate
Trigger this skill when code involves:
- Authentication or authorization - Login flows, session management, role checks
- User input handling - Forms, query parameters, file uploads
- API endpoints - New routes, especially public-facing
- Secrets or credentials - API keys, database connections, tokens
- Payment features - Financial transactions, billing, subscriptions
- Sensitive data - PII, health data, financial records
- Third-party API integration - External service connections
- Database queries - Especially raw SQL or dynamic queries
Security Checklist
1. Secrets Management
BAD - Never Do This
const apiKey = "sk-proj-xxxxx"
const dbPassword = "password123"
const config = {
stripe_key: "sk_live_xxxxx"
}
GOOD - Always Do This
const apiKey = process.env.OPENAI_API_KEY
const dbUrl = process.env.DATABASE_URL
if (!apiKey) {
throw new Error('OPENAI_API_KEY not configured')
}
Verification Checklist
2. Input Validation
BAD - Never Trust User Input
async function createUser(req: Request) {
const { email, name, role } = req.body
return db.users.create({ email, name, role })
}
if (formData.email.includes('@')) { }
GOOD - Validate Everything Server-Side
import { z } from 'zod'
const CreateUserSchema = z.object({
email: z.string().email().max(255),
name: z.string().min(1).max(100).regex(/^[a-zA-Z\s]+$/),
age: z.number().int().min(0).max(150).optional()
})
export async function createUser(input: unknown) {
const validated = CreateUserSchema.parse(input)
return await db.users.create({
...validated,
role: 'user'
})
}
File Upload Validation
function validateFileUpload(file: File) {
const maxSize = 5 * 1024 * 1024
if (file.size > maxSize) {
throw new Error('File too large (max 5MB)')
}
const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']
if (!allowedTypes.includes(file.type)) {
throw new Error('Invalid file type')
}
const allowedExtensions = ['.jpg', '.jpeg', '.png', '.gif']
const extension = file.name.toLowerCase().match(/\.[^.]+$/)?.[0]
if (!extension || !allowedExtensions.includes(extension)) {
throw new Error('Invalid file extension')
}
const sanitizedName = file.name.replace(/[^a-zA-Z0-9.-]/g, '_')
return { ...file, name: sanitizedName }
}
Verification Checklist
3. SQL Injection Prevention
BAD - Never Concatenate SQL
const query = `SELECT * FROM users WHERE email = '${userEmail}'`
await db.query(query)
const search = `SELECT * FROM products WHERE name LIKE '%${term}%'`
GOOD - Always Use Parameterized Queries
const { data } = await supabase
.from('users')
.select('*')
.eq('email', userEmail)
await db.query(
'SELECT * FROM users WHERE email = $1',
[userEmail]
)
const user = await prisma.user.findUnique({
where: { email: userEmail }
})
await db.query(
'SELECT * FROM products WHERE name LIKE $1',
[`%${term}%`]
)
Verification Checklist
4. Authentication & Authorization
BAD - Insecure Token Storage
localStorage.setItem('token', token)
localStorage.setItem('user', JSON.stringify(user))
async function deleteUser(userId: string) {
await db.users.delete({ where: { id: userId } })
}
GOOD - Secure Token Handling
res.setHeader('Set-Cookie', [
`token=${token}; HttpOnly; Secure; SameSite=Strict; Max-Age=3600; Path=/`
])
export async function deleteUser(userId: string, requesterId: string) {
const requester = await db.users.findUnique({
where: { id: requesterId },
select: { id: true, role: true }
})
if (requester.id !== userId && requester.role !== 'admin') {
throw new ForbiddenError('Not authorized to delete this user')
}
await db.users.delete({ where: { id: userId } })
}
Row Level Security (Supabase/PostgreSQL)
ALTER TABLE users ENABLE ROW LEVEL SECURITY;
ALTER TABLE posts ENABLE ROW LEVEL SECURITY;
CREATE POLICY "Users view own data"
ON users FOR SELECT
USING (auth.uid() = id);
CREATE POLICY "Users update own data"
ON users FOR UPDATE
USING (auth.uid() = id);
CREATE POLICY "Admins can view all"
ON users FOR SELECT
USING (
EXISTS (
SELECT 1 FROM users WHERE id = auth.uid() AND role = 'admin'
)
);
Verification Checklist
5. XSS Prevention
BAD - Rendering Unsanitized Content
function Comment({ html }) {
return <div dangerouslySetInnerHTML={{ __html: html }} />
}
const userCode = getUserInput()
eval(userCode)
new Function(userCode)()
GOOD - Sanitize All User HTML
import DOMPurify from 'isomorphic-dompurify'
function SafeComment({ html }: { html: string }) {
const clean = DOMPurify.sanitize(html, {
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'p', 'br'],
ALLOWED_ATTR: []
})
return <div dangerouslySetInnerHTML={{ __html: clean }} />
}
import { marked } from 'marked'
import DOMPurify from 'isomorphic-dompurify'
function MarkdownContent({ markdown }: { markdown: string }) {
const html = marked(markdown)
const clean = DOMPurify.sanitize(html)
return <div dangerouslySetInnerHTML={{ __html: clean }} />
}
Content Security Policy
const securityHeaders = [
{
key: 'Content-Security-Policy',
value: [
"default-src 'self'",
"script-src 'self'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: https:",
"font-src 'self'",
"connect-src 'self' https://api.example.com",
"frame-ancestors 'none'",
"base-uri 'self'",
"form-action 'self'"
].join('; ')
},
{
key: 'X-Content-Type-Options',
value: 'nosniff'
},
{
key: 'X-Frame-Options',
value: 'DENY'
}
]
Verification Checklist
6. CSRF Protection
BAD - No CSRF Protection
app.get('/api/delete-account', async (req, res) => {
await deleteAccount(req.user.id)
})
app.post('/api/transfer', async (req, res) => {
await transferMoney(req.body.amount, req.body.to)
})
GOOD - Implement CSRF Protection
import { csrf } from '@/lib/csrf'
export async function POST(request: Request) {
const token = request.headers.get('X-CSRF-Token')
if (!csrf.verify(token)) {
return NextResponse.json(
{ error: 'Invalid CSRF token' },
{ status: 403 }
)
}
}
fetch('/api/action', {
method: 'POST',
headers: {
'X-CSRF-Token': csrfToken,
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
SameSite Cookies (Primary Defense)
res.setHeader('Set-Cookie', [
`session=${sessionId}; HttpOnly; Secure; SameSite=Strict; Path=/`
])
Verification Checklist
7. Rate Limiting
BAD - No Rate Limiting
app.post('/api/search', async (req, res) => {
const results = await expensiveSearch(req.body.query)
return res.json(results)
})
app.post('/api/login', async (req, res) => {
})
GOOD - Implement Rate Limiting
import rateLimit from 'express-rate-limit'
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
message: { error: 'Too many requests, please try again later' },
standardHeaders: true,
legacyHeaders: false
})
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 5,
message: { error: 'Too many login attempts' },
skipSuccessfulRequests: true
})
const searchLimiter = rateLimit({
windowMs: 60 * 1000,
max: 10,
message: { error: 'Too many search requests' }
})
app.use('/api/', apiLimiter)
app.use('/api/auth/', authLimiter)
app.use('/api/search', searchLimiter)
Verification Checklist
8. Sensitive Data Exposure
BAD - Leaking Sensitive Data
console.log('User login:', { email, password })
console.log('Payment processed:', { cardNumber, cvv, amount })
console.log('Request body:', req.body)
catch (error) {
return res.json({
error: error.message,
stack: error.stack,
query: sqlQuery
})
}
return res.json({ user })
GOOD - Protect Sensitive Data
console.log('User login:', { email, userId: user.id })
console.log('Payment processed:', {
last4: card.number.slice(-4),
amount,
userId
})
catch (error) {
logger.error('Payment failed', {
error: error.message,
userId,
})
return res.status(500).json({
error: 'Payment processing failed. Please try again.'
})
}
const user = await db.users.findUnique({
where: { id: userId },
select: {
id: true,
email: true,
name: true,
}
})
return res.json({ user })
Verification Checklist
9. Blockchain Security (Conditional)
Only applicable when project involves blockchain/crypto functionality.
BAD - Insecure Blockchain Handling
async function claimReward(walletAddress: string) {
await sendReward(walletAddress)
}
async function processTransaction(tx: any) {
await wallet.signAndSend(tx)
}
GOOD - Verify Everything
import { verify } from '@solana/web3.js'
import nacl from 'tweetnacl'
async function verifyWalletOwnership(
publicKey: string,
signature: string,
message: string
): Promise<boolean> {
try {
const messageBytes = new TextEncoder().encode(message)
const signatureBytes = Buffer.from(signature, 'base64')
const publicKeyBytes = Buffer.from(publicKey, 'base64')
return nacl.sign.detached.verify(
messageBytes,
signatureBytes,
publicKeyBytes
)
} catch {
return false
}
}
async function processTransaction(transaction: Transaction) {
if (transaction.to !== KNOWN_RECIPIENT) {
throw new Error('Invalid recipient address')
}
if (transaction.amount > MAX_TRANSACTION_AMOUNT) {
throw new Error('Amount exceeds limit')
}
const balance = await getBalance(transaction.from)
if (balance < transaction.amount + GAS_BUFFER) {
throw new Error('Insufficient balance')
}
await auditLog.record({
type: 'transaction',
from: transaction.from,
to: transaction.to,
amount: transaction.amount,
timestamp: new Date()
})
return await signAndSend(transaction)
}
Verification Checklist
10. Dependency Security
Regular Security Audits
npm audit
npm audit fix
npm outdated
npm update
npx npm-check-updates -i
Lock File Management
git add package-lock.json
npm ci
npm ci --ignore-scripts
Verification Checklist
Integration with implement-phase
When invoked as part of the implement-phase pipeline (Step 3), this skill provides structured output for orchestration.
Input Context
Security Review for Phase [N]
Context:
- Plan: [path to plan file]
- Phase: [phase number and name]
- Changed files: [list of modified/added files]
- Security-relevant changes: [auth, input, api, secrets, payment, uploads]
Output Format
STATUS: PASS | PASS_WITH_ISSUES | FAIL
CATEGORIES_CHECKED: [count of applicable categories reviewed]
ISSUES_FOUND:
- [CRITICAL] [Category]: [Description]
- [HIGH] [Category]: [Description]
- [MEDIUM] [Category]: [Description]
- [LOW] [Category]: [Description]
SEVERITY: CRITICAL | HIGH | MEDIUM | LOW | NONE
RECOMMENDATIONS:
- [Non-blocking improvement suggestions]
REPORT: [Path to detailed report if written]
Severity Levels
| Level | Meaning | Action Required |
|---|
| CRITICAL | Active vulnerability, exploitable now | Block deployment, fix immediately |
| HIGH | Serious vulnerability, likely exploitable | Block deployment, fix before merge |
| MEDIUM | Potential vulnerability, context-dependent | Should fix, may proceed with documented exception |
| LOW | Best practice violation, minimal risk | Note for improvement |
Integration Point in Pipeline
implement-phase Pipeline:
Step 1: Implementation
Step 2: Functional verification (tests pass)
Step 3: Code review
Step 4: SECURITY REVIEW (this skill) <--
Step 5: Plan synchronization
Step 6: Completion report
On FAIL:
- Block phase completion
- Report blocking issues
- Require fixes before retry
Pre-Deployment Security Checklist
Before ANY production deployment, verify:
Secrets & Configuration
Input & Data
Authentication & Authorization
Web Security
Infrastructure
Compliance
References
For detailed checklists and examples:
Security is everyone's responsibility. When in doubt, ask for a security review.