Communitygithub.com

安全审查技能

在添加身份验证、处理用户输入、使用密钥、创建API端点或实现支付/敏感功能时使用此技能。提供全面的安全清单和模式。

安全审查技能 是什么?

安全审查技能是一个全面的开发助手,专为AI编码工具(如Claude Code、Cursor、Codex)设计,旨在指导开发者和AI智能体生成安全、健壮的代码。该技能涵盖了从密钥管理、输入验证、SQL注入防护到XSS、CSRF、速率限制、依赖安全和区块链(Solana)安全等十个关键领域。每个领域都提供了清晰的“失败(禁止)”和“通过(推荐)”代码示例,以及可操作的验证步骤,帮助用户在执行常见但风险较高的操作(如处理用户输入、创建API端点、实现支付功能或集成第三方API)时遵循最佳实践。此技能还包含自动化安全测试示例和一个详尽的预部署检查清单,确保在生产发布前系统性地消除常见漏洞。它支持Next.js、Supabase、JWT和Solana等主流技术栈,强调安全是不可协商的,并通过OWASP等资源提供深入学习路径。

兼容平台~Claude Code✓Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/security-review

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

安全审查技能 是做什么的?

此技能确保所有代码遵循安全最佳实践,并识别潜在漏洞。

何时激活

  • 实现身份验证或授权
  • 处理用户输入或文件上传
  • 创建新的API端点
  • 使用密钥或凭据
  • 实现支付功能
  • 存储或传输敏感数据
  • 集成第三方API

安全清单

1. 密钥管理

禁止:切勿这样做

const apiKey = "sk-proj-xxxxx"  // 硬编码密钥
const dbPassword = "password123" // 在源代码中

通过:始终这样做

const apiKey = process.env.OPENAI_API_KEY
const dbUrl = process.env.DATABASE_URL

// 验证密钥是否存在
if (!apiKey) {
  throw new Error('OPENAI_API_KEY 未配置')
}

验证步骤

  • 没有硬编码的API密钥、令牌或密码
  • 所有密钥存储在环境变量中
  • .env.local 在 .gitignore 中
  • git历史中没有密钥
  • 生产密钥存储在托管平台(Vercel, Railway)中

2. 输入验证

始终验证用户输入

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) {
  try {
    const validated = CreateUserSchema.parse(input)
    return await db.users.create(validated)
  } catch (error) {
    if (error instanceof z.ZodError) {
      return { success: false, errors: error.issues }
    }
    throw error
  }
}

文件上传验证

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
}

验证步骤

  • 所有用户输入都经过模式验证
  • 文件上传受限(大小、类型、扩展名)
  • 查询中不直接使用用户输入
  • 白名单验证(非黑名单)
  • 错误消息不泄露敏感信息

3. SQL注入防护

禁止:切勿拼接SQL

// 危险 - SQL注入漏洞
const query = `SELECT * FROM users WHERE email = '${userEmail}'`
await db.query(query)

通过:始终使用参数化查询

// 安全 - 参数化查询
const { data } = await supabase
  .from('users')
  .select('*')
  .eq('email', userEmail)

// 或者使用原始SQL
await db.query(
  'SELECT * FROM users WHERE email = $1',
  [userEmail]
)

验证步骤

  • 所有数据库查询都使用参数化查询
  • SQL中没有字符串拼接
  • ORM/查询构建器正确使用
  • Supabase查询已正确清理

4. 身份验证与授权

JWT令牌处理

// 禁止:错误:localStorage(易受XSS攻击)
localStorage.setItem('token', 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: '未授权' },
      { status: 403 }
    )
  }

  // 继续删除操作
  await db.users.delete({ where: { id: userId } })
}

行级安全(Supabase)

-- 在所有表上启用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);

验证步骤

  • 令牌存储在httpOnly cookies中(非localStorage)
  • 在敏感操作前进行授权检查
  • Supabase中启用了行级安全
  • 实现了基于角色的访问控制
  • 会话管理安全

5. XSS防护

清理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 }} />
}

内容安全策略(CSP)

从严格策略开始,仅在具有文档化的删除计划时才放宽。不要默认使用 'unsafe-inline' 或 'unsafe-eval';它们会削弱CSP的大部分保护能力, 应被视为临时的兼容性债务。

// next.config.js
const securityHeaders = [
  {
    key: 'Content-Security-Policy',
    value: `
      default-src 'self';
      base-uri 'self';
      object-src 'none';
      frame-ancestors 'none';
      script-src 'self';
      style-src 'self';
      img-src 'self' data: https:;
      font-src 'self';
      connect-src 'self' https://api.example.com;
    `.replace(/\s{2,}/g, ' ').trim()
  }
]

验证步骤

  • 用户提供的HTML已清理
  • 配置了CSP头
  • 没有未经验证的动态内容渲染
  • 使用了React内置的XSS防护

6. CSRF防护

CSRF令牌

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: '无效的CSRF令牌' },
      { status: 403 }
    )
  }

  // 处理请求
}

SameSite Cookies

res.setHeader('Set-Cookie',
  `session=${sessionId}; HttpOnly; Secure; SameSite=Strict`)

验证步骤

  • 对状态更改操作使用CSRF令牌
  • 所有cookie设置SameSite=Strict
  • 实现了双重提交cookie模式

7. 速率限制

API速率限制

import rateLimit from 'express-rate-limit'

const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15分钟
  max: 100, // 每个窗口100个请求
  message: '请求过多'
})

// 应用于路由
app.use('/api/', limiter)

昂贵操作

// 对搜索应用更严格的速率限制
const searchLimiter = rateLimit({
  windowMs: 60 * 1000, // 1分钟
  max: 10, // 每分钟10个请求
  message: '搜索请求过多'
})

app.use('/api/search', searchLimiter)

验证步骤

  • 所有API端点都启用了速率限制
  • 对昂贵操作应用更严格的限制
  • 基于IP的速率限制
  • 基于用户的速率限制(已认证)

8. 敏感数据泄露

日志记录

// 禁止:错误:记录敏感数据
console.log('用户登录:', { email, password })
console.log('支付:', { cardNumber, cvv })

// 通过:正确:脱敏敏感数据
console.log('用户登录:', { email, userId })
console.log('支付:', { last4: card.last4, userId })

错误消息

// 禁止:错误:暴露内部细节
catch (error) {
  return NextResponse.json(
    { error: error.message, stack: error.stack },
    { status: 500 }
  )
}

// 通过:正确:通用错误消息
catch (error) {
  console.error('内部错误:', error)
  return NextResponse.json(
    { error: '发生错误。请重试。' },
    { status: 500 }
  )
}

验证步骤

  • 日志中没有密码、令牌或密钥
  • 对用户显示通用错误消息
  • 详细错误仅出现在服务器日志中
  • 不向用户暴露堆栈跟踪

9. 区块链安全(Solana)

钱包验证

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
  }
}

交易验证

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
}

验证步骤

  • 钱包签名已验证
  • 交易详情已验证
  • 交易前进行余额检查
  • 没有盲目签署交易

10. 依赖安全

定期更新

# 检查漏洞
npm audit

# 自动修复可修复的问题
npm audit fix

# 更新依赖
npm update

# 检查过时的包
npm outdated

锁定文件

# 始终提交锁定文件
git add package-lock.json

# 在CI/CD中使用以实现可重现构建
npm ci  # 代替 npm install

验证步骤

  • 依赖项已更新
  • 没有已知漏洞(npm audit clean)
  • 锁定文件已提交
  • 在GitHub上启用了Dependabot
  • 定期进行安全更新

安全测试

自动化安全测试

// 测试身份验证
test('requires authentication', async () => {
  const response = await fetch('/api/protected')
  expect(response.status).toBe(401)
})

// 测试授权
test('requires admin role', async () => {
  const response = await fetch('/api/admin', {
    headers: { Authorization: `Bearer ${userToken}` }
  })
  expect(response.status).toBe(403)
})

// 测试输入验证
test('rejects invalid input', async () => {
  const response = await fetch('/api/users', {
    method: 'POST',
    body: JSON.stringify({ email: 'not-an-email' })
  })
  expect(response.status).toBe(400)
})

// 测试速率限制
test('enforces rate limits', 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)
})

预部署安全清单

在任何生产部署之前:

  • 密钥:没有硬编码密钥,所有密钥在环境变量中
  • 输入验证:所有用户输入已验证
  • SQL注入:所有查询已参数化
  • XSS:用户内容已清理
  • CSRF:已启用防护
  • 身份验证:正确处理令牌
  • 授权:角色检查已到位
  • 速率限制:所有端点已启用
  • HTTPS:在生产环境中强制启用
  • 安全头:已配置CSP、X-Frame-Options
  • 错误处理:错误中不包含敏感数据
  • 日志记录:未记录敏感数据
  • 依赖:已更新,无漏洞
  • 行级安全:在Supabase中已启用
  • CORS:已正确配置
  • 文件上传:已验证(大小、类型)
  • 钱包签名:已验证(如果是区块链项目)

资源


请记住:安全不可协商。一个漏洞可能危及整个平台。如有疑问,请谨慎行事。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

相关技能