This skill is intended to ensure all code follows security best practices and to identify potential vulnerabilities.
When to Enable
- When implementing authentication or authorization
- When handling user input or file uploads
- When creating new API endpoints
- When operating on secrets or credentials
- When implementing payment functionality
- When storing or transmitting sensitive data
- When integrating third-party APIs
Security Self-Check Checklist
1. Secrets Management
❌ Strictly Prohibited
const apiKey = "sk-proj-xxxxx" // 硬编码机密
const dbPassword = "password123" // 出现在源代码中
✅ Recommended Practices
const apiKey = process.env.OPENAI_API_KEY
const dbUrl = process.env.DATABASE_URL
// 验证机密是否存在
if (!apiKey) {
throw new Error('未配置 OPENAI_API_KEY')
}
Verification Steps
- No hardcoded API keys, tokens, or passwords
- All secrets are stored in environment variables
-
.env.localAlready included in .gitignore - Git history contains no secrets
- Production secrets are configured on hosting platforms (such as Vercel, Railway)
2. Input Validation
Always validate user input
import { z } from 'zod'
// 定义验证模式(Schema)
const CreateUserSchema = z.object({
email: z.string().email(),
name: z.string().min(1).max(100),
age: z.number().int().min(0).max(150)
})
// 在处理前进行验证
export async function createUser(input: unknown) {
try {
const validated = CreateUserSchema.parse(input)
return await db.users.create(validated)
} catch (error) {
if (error instanceof z.ZodError) {
return { success: false, errors: error.errors }
}
throw error
}
}
File upload validation
function validateFileUpload(file: File) {
// 大小检查(最大 5MB)
const maxSize = 5 * 1024 * 1024
if (file.size > maxSize) {
throw new Error('文件过大(最大 5MB)')
}
// 类型检查
const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']
if (!allowedTypes.includes(file.type)) {
throw new Error('无效的文件类型')
}
// 扩展名检查
const allowedExtensions = ['.jpg', '.jpeg', '.png', '.gif']
const extension = file.name.toLowerCase().match(/\.[^.]+$/)?.[0]
if (!extension || !allowedExtensions.includes(extension)) {
throw new Error('无效的文件扩展名')
}
return true
}
Verification Steps
- All user input is validated through schemas
- File uploads are restricted (size, type, extension)
- User input is not used directly in queries
- Use whitelist validation (not blacklist)
- Error messages do not leak sensitive information
3. SQL Injection Prevention
❌ Strictly prohibit SQL concatenation
// 危险 - 存在 SQL 注入漏洞
const query = `SELECT * FROM users WHERE email = '${userEmail}'`
await db.query(query)
✅ Always use parameterized queries
// 安全 - 参数化查询
const { data } = await supabase
.from('users')
.select('*')
.eq('email', userEmail)
// 或使用原始 SQL
await db.query(
'SELECT * FROM users WHERE email = $1',
[userEmail]
)
Verification Steps
- All database queries use parameterized queries
- No string concatenation in SQL
- ORM or query builder is used correctly
- Supabase queries are correctly filtered
4. Authentication & Authorization
JWT token handling
// ❌ 错误做法:存储在 localStorage 中(易受 XSS 攻击)
localStorage.setItem('token', token)
// ✅ 正确做法:使用 httpOnly cookies
res.setHeader('Set-Cookie',
`token=${token}; HttpOnly; Secure; SameSite=Strict; Max-Age=3600`)
Authorization checks
export async function deleteUser(userId: string, requesterId: string) {
// 务必先验证授权
const requester = await db.users.findUnique({
where: { id: requesterId }
})
if (requester.role !== 'admin') {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 403 }
)
}
// 执行删除操作
await db.users.delete({ where: { id: userId } })
}
Row Level Security (Supabase Row Level Security)
-- 在所有表上启用 RLS
ALTER TABLE users 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);
Verification Steps
- Tokens are stored in httpOnly cookies (not localStorage)
- Authorization checks are performed before sensitive operations
- Row Level Security (RLS) is enabled in Supabase
- Role-Based Access Control (RBAC) is implemented
- Session Management is secure
5. XSS Prevention
Sanitize HTML
import DOMPurify from 'isomorphic-dompurify'
// 始终清理用户提供的 HTML
function renderUserContent(html: string) {
const clean = DOMPurify.sanitize(html, {
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'p'],
ALLOWED_ATTR: []
})
return <div dangerouslySetInnerHTML={{ __html: clean }} />
}
Content Security Policy
// next.config.js
const securityHeaders = [
{
key: 'Content-Security-Policy',
value: `
default-src 'self';
script-src 'self' 'unsafe-eval' 'unsafe-inline';
style-src 'self' 'unsafe-inline';
img-src 'self' data: https:;
font-src 'self';
connect-src 'self' https://api.example.com;
`.replace(/\s{2,}/g, ' ').trim()
}
]
Verification Steps
- User-provided HTML is sanitized
- CSP response headers are configured
- No unvalidated dynamic content rendering
- React's built-in XSS protection mechanisms are used
6. CSRF Protection
CSRF Tokens
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 }
)
}
// 处理请求
}
SameSite Cookies
res.setHeader('Set-Cookie',
`session=${sessionId}; HttpOnly; Secure; SameSite=Strict`)
Verification Steps
- CSRF tokens are used in state-changing operations
- All cookies are set with SameSite=Strict
- Implemented the Double-submit cookie pattern
7. Rate Limiting
API Rate Limiting
import rateLimit from 'express-rate-limit'
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 分钟
max: 100, // 每个窗口期最大 100 次请求
message: '请求过于频繁'
})
// 应用于路由
app.use('/api/', limiter)
High-cost operations
// 为搜索操作设置更严格的速率限制
const searchLimiter = rateLimit({
windowMs: 60 * 1000, // 1 分钟
max: 10, // 每分钟最大 10 次请求
message: '搜索请求过于频繁'
})
app.use('/api/search', searchLimiter)
Verification steps
- Rate limits are set on all API endpoints
- Stricter limits are set for high-cost operations
- IP-based rate limiting
- User-based rate limiting (authenticated users)
8. Sensitive Data Exposure
Logging
// ❌ 错误做法:记录敏感数据
console.log('User login:', { email, password })
console.log('Payment:', { cardNumber, cvv })
// ✅ 正确做法:屏蔽敏感数据
console.log('User login:', { email, userId })
console.log('Payment:', { last4: card.last4, userId })
Error messages
// ❌ 错误做法:泄露内部细节
catch (error) {
return NextResponse.json(
{ error: error.message, stack: error.stack },
{ status: 500 }
)
}
// ✅ 正确做法:通用的错误消息
catch (error) {
console.error('Internal error:', error)
return NextResponse.json(
{ error: '发生错误,请稍后重试。' },
{ status: 500 }
)
}
Verification steps
- Logs do not contain passwords, tokens, or secrets
- Generic error messages are shown to users
- Detailed errors are logged only in server logs
- Stack traces are not exposed to users
9. Blockchain Security (Solana)
Wallet verification
import { verify } from '@solana/web3.js'
async function verifyWalletOwnership(
publicKey: string,
signature: string,
message: string
) {
try {
const isValid = verify(
Buffer.from(message),
Buffer.from(signature, 'base64'),
Buffer.from(publicKey, 'base64')
)
return isValid
} catch (error) {
return false
}
}
Transaction verification
async function verifyTransaction(transaction: Transaction) {
// 验证收款人
if (transaction.to !== expectedRecipient) {
throw new Error('无效的收款人')
}
// 验证金额
if (transaction.amount > maxAmount) {
throw new Error('金额超出限制')
}
// 验证用户余额充足
const balance = await getBalance(transaction.from)
if (balance < transaction.amount) {
throw new Error('余额不足')
}
return true
}
Verification steps
- Wallet signatures have been verified
- Transaction details have been validated
- Balance checks are performed before transactions
- No blind transaction signing behavior
10. Dependency Security
Regular updates
# 检查漏洞
npm audit
# 自动修复可修复的问题
npm audit fix
# 更新依赖
npm update
# 检查过期的包
npm outdated
Lock files
# 务必提交锁定文件
git add package-lock.json
# 在 CI/CD 中使用以确保可重现的构建
npm ci # 而不是 npm install
Verification steps
- Dependencies are kept up to date
- No known vulnerabilities (npm audit clean)
- Lock files have been committed
- Dependabot is enabled on GitHub
- Regular security updates are performed
Security Testing
Automated security testing
// 测试身份验证
test('需要身份验证', async () => {
const response = await fetch('/api/protected')
expect(response.status).toBe(401)
})
// 测试授权
test('需要管理员角色', async () => {
const response = await fetch('/api/admin', {
headers: { Authorization: `Bearer ${userToken}` }
})
expect(response.status).toBe(403)
})
// 测试输入验证
test('拒绝无效输入', async () => {
const response = await fetch('/api/users', {
method: 'POST',
body: JSON.stringify({ email: 'not-an-email' })
})
expect(response.status).toBe(400)
})
// 测试速率限制
test('执行速率限制', async () => {
const requests = Array(101).fill(null).map(() =>
fetch('/api/endpoint')
)
const responses = await Promise.all(requests)
const tooManyRequests = responses.filter(r => r.status === 429)
expect(tooManyRequests.length).toBeGreaterThan(0)
})
Pre-deployment security checklist
Before deploying to any production environment:
- Secrets: No hardcoded secrets, all in environment variables
- Input Validation: All user input has been validated
- SQL Injection: All queries are parameterized
- XSS: User content has been sanitized
- CSRF: Protection is enabled
- Authentication: Correct token handling
- Authorization: Role checks are in place
- Rate Limiting: Enabled on all endpoints
- HTTPS: Enforced in production
- Security Headers: CSP, X-Frame-Options configured
- Error Handling: Errors do not contain sensitive data
- Logging: Logs do not contain sensitive data
- Dependencies: Up to date, no known vulnerabilities
- Row Level Security: Enabled in Supabase
- CORS: Correctly configured
- File Uploads: Validated (size, type)
- Wallet Signatures: Verified (if it is a blockchain project)
Resources
Please remember: Security is not optional. A single vulnerability can compromise the entire platform. When in doubt, err on the side of caution.