When to Use
In the following situationsproactivelyuse this Skill:
- Implementing authentication or authorization features
- Handling user input or file uploads
- Creating new API endpoints
- Handling confidential data or credentials
- Implementing payment features
- Integrating third-party APIs
- Handling finance/transaction-related code
Security Checklist (10 Major Categories)
1. Confidential Data Management (CRITICAL)
// 禁止: 硬編碼機密資料
const apiKey = "sk-proj-xxxxx" // 絕對禁止
const password = "admin123" // 絕對禁止
// 正確: 使用環境變數
const apiKey = process.env.OPENAI_API_KEY
if (!apiKey) {
throw new Error('OPENAI_API_KEY 未設定')
}
Check items:
- No hardcoded API keys, tokens, passwords
- All confidential data uses environment variables
-
.env.localAdded to .gitignore - No confidential data in Git history
- Production secrets stored in Vercel/Render
2. Input Validation
import { z } from 'zod'
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) {
const validated = CreateUserSchema.parse(input)
return await db.users.create(validated)
}
Check items:
- All user input validated using Zod
- File upload restrictions (size, type, extension)
- Error messages do not leak sensitive information
3. SQL Injection Protection (CRITICAL)
// 禁止: 字串串接 SQL
const query = `SELECT * FROM users WHERE email = '${userEmail}'`
// 正確: 參數化查詢
const { data } = await supabase
.from('users')
.select('*')
.eq('email', userEmail)
Check items:
- All database queries use parameterized queries
- No string concatenation in SQL
- ORM/Query Builder used correctly
4. Authentication and Authorization
// 正確: JWT Token 使用 httpOnly cookies
res.setHeader('Set-Cookie',
`token=${token}; HttpOnly; Secure; SameSite=Strict; Max-Age=3600`)
// 正確: 授權檢查
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 } })
}
Check items:
- Tokens stored in httpOnly cookies (not localStorage)
- Verify authorization before sensitive operations
- Supabase Row Level Security enabled
- RBAC implemented
5. XSS Protection
import DOMPurify from 'isomorphic-dompurify'
function renderUserContent(html: string) {
const clean = DOMPurify.sanitize(html, {
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'p'],
ALLOWED_ATTR: []
})
return <div dangerouslySetInnerHTML={{ __html: clean }} />
}
Check items:
- User-provided HTML sanitized
- CSP headers configured
- Use React's built-in XSS protection
6. CSRF Protection
// SameSite Cookies
res.setHeader('Set-Cookie',
`session=${sessionId}; HttpOnly; Secure; SameSite=Strict`)
Check items:
- State-changing operations use CSRF tokens
- All cookies set with SameSite=Strict
7. Rate Limiting
import rateLimit from 'express-rate-limit'
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 分鐘
max: 100, // 每視窗 100 請求
message: '請求過多,請稍後再試'
})
app.use('/api/', limiter)
Check items:
- Rate limiting enabled on all API endpoints
- Stricter limits for expensive operations
8. Sensitive Data Leakage
// 禁止: 記錄敏感資料
console.log('User login:', { email, password })
// 正確: 清理日誌
console.log('User login:', {
email: email.replace(/(?<=.).(?=.*@)/g, '*'),
passwordProvided: !!password
})
Check items:
- No passwords, tokens, confidential data in logs
- Error messages are generic for users
- Detailed errors only in server logs
9. Blockchain Security (Solana)
// 驗證錢包簽名
import { verify } from '@solana/web3.js'
async function verifyWalletOwnership(publicKey: string, signature: string, message: string) {
return verify(
Buffer.from(message),
Buffer.from(signature, 'base64'),
Buffer.from(publicKey, 'base64')
)
}
Check items:
- Wallet signatures verified
- Transaction details verified
- Balance check before transaction
- No blind signing of transactions
10. Dependency Security
# 檢查漏洞
npm audit
# 自動修復
npm audit fix
# 更新依賴
npm update
Check items:
- Dependencies kept up to date
- npm audit shows no known vulnerabilities
- Lock file committed
- GitHub Dependabot enabled
Security Review Report Format
# 安全審查報告
**檔案:** [path/to/file.ts]
**審查日期:** YYYY-MM-DD
**審查者:** security-reviewer
## 摘要
- **嚴重問題:** X
- **高風險問題:** Y
- **中風險問題:** Z
- **風險等級:** 高 / 中 / 低
## 嚴重問題 (立即修復)
### 1. [問題標題]
**嚴重程度:** CRITICAL
**類別:** SQL 注入 / XSS / 認證 / 等
**位置:** `file.ts:123`
**問題描述:**
[漏洞描述]
**影響:**
[被利用時的後果]
**修復方案:**
[安全實作範例]
Pre-deployment Security Checklist
- Confidential Data: No hardcoding, all use environment variables
- Input Validation: All user input validated
- SQL Injection: All queries parameterized
- XSS: User content sanitized
- CSRF: Protection enabled
- Authentication: Correct token handling
- Authorization: Role checks in place
- Rate limiting: Enabled on all endpoints
- HTTPS: Enforced in production
- Security headers: CSP, X-Frame-Options configured
- Dependencies: Up to date and vulnerability-free
Incident response
When a CRITICAL vulnerability is found:
- Log - Create a detailed report
- Notify - Immediately alert the project lead
- Recommend a fix - Provide secure code examples
- Test the fix - Verify the fix is effective
- Rotate secrets - Replace if leaked