name: security-implementation-guide description: 用于认证、授权、输入验证和常见漏洞预防的综合安全模式 license: MIT metadata: adapted-by: ai-skills category: security
安全实施指南
用于Web应用程序的生产就绪安全模式。
输入验证
清理
import DOMPurify from 'isomorphic-dompurify';
function sanitizeHTML(dirty: string): string {
return DOMPurify.sanitize(dirty, {
ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'p'],
ALLOWED_ATTR: []
});
}
// SQL注入预防 - 使用参数化查询
const result = await db.query(
'SELECT * FROM users WHERE email = $1',
[email] // 切勿直接插值!
);
XSS预防
// React自动转义
<div>{userInput}</div> // 安全
// 危险 - 避免使用dangerouslySetInnerHTML
<div dangerouslySetInnerHTML={{ __html: sanitizeHTML(userInput) }} />
// 设置安全头部
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'"],
styleSrc: ["'self'", "'unsafe-inline'"],
}
}
}));
认证
密码哈希
import bcrypt from 'bcrypt'; // allow-secret
async function hashPassword(password: string): Promise<string> { // allow-secret
const saltRounds = 12;
return bcrypt.hash(password, saltRounds); // allow-secret
}
async function verifyPassword(password: string, hash: string): Promise<boolean> { // allow-secret
return bcrypt.compare(password, hash); // allow-secret
}
速率限制
import rateLimit from 'express-rate-limit';
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 5, // 5次尝试
message: '登录尝试过多',
standardHeaders: true,
legacyHeaders: false,
});
app.post('/api/login', loginLimiter, loginHandler);
CSRF保护
import csrf from 'csurf';
const csrfProtection = csrf({ cookie: true });
app.get('/form', csrfProtection, (req, res) => {
res.render('form', { csrfToken: req.csrfToken() });
});
app.post('/process', csrfProtection, (req, res) => {
// 受保护的端点
});
集成点
补充:
- security-threat-modeler: 用于威胁分析
- backend-implementation-patterns: 用于安全API
- verification-loop: 用于安全检查