安全实现指南 security-implementation-guide

这个技能提供生产就绪的安全实现模式,涵盖身份验证、授权、输入验证、常见漏洞预防等,适用于Web应用程序开发。关键词:安全、身份验证、密码哈希、CSRF保护、XSS预防、速率限制。

身份认证 0 次安装 0 次浏览 更新于 3/7/2026

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: 用于安全检查