← 返回列表
全部 Skill›测试与安全 Testing & Security›security-review

security-review

作者 @affaan-m · 语言 zh
在添加身份验证、处理用户输入、处理机密信息、创建API端点或实现支付/敏感功能时使用此技能。提供全面的安全检查清单和模式。
测试与安全 Testing & Security安全需海外环境执行命令访问网络敏感路径
存储库
最近源活动
—
检测 SKILL.md 语言
zh
星标 ★
309,846
分支 Fork
0
安装选项
提示
指令
使用 AI 助手安装
将下面的提示复制到你正在使用的 AI 助手中。
下载完整 Skill 目录(含全部配套文件)。 下载压缩包 ↓
SKILL.md 原文预览

安全审查技能

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

何时激活

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

安全检查清单

1. 密钥管理

#### FAIL: 绝对不要这样做

const apiKey = "sk-proj-xxxxx"  // Hardcoded secret
const dbPassword = "password123" // In source code

#### PASS: 始终这样做

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

// Verify secrets exist
if (!apiKey) {
  throw new Error('OPENAI_API_KEY not configured')
}

#### 验证步骤

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

2. 输入验证

#### 始终验证用户输入

import { z } from 'zod'

// Define validation schema
const CreateUserSchema = z.object({
  email: z.string().email(),
  name: z.string().min(1).max(100),
  age: z.number().int().min(0).max(150)
})

// Validate before processing
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
  }
}

#### 文件上传验证

function validateFileUpload(file: File) {
  // Size check (5MB max)
  const maxSize = 5 * 1024 * 1024
  if (file.size > maxSize) {
    throw new Error('File too large (max 5MB)')
  }

  // Type check
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']
  if (!allowedTypes.includes(file.type)) {
    throw new Error('Invalid file type')
  }

  // Extension check
  const allowedExtensions = ['.jpg', '.jpeg', '.png', '.gif']
  const extension = file.name.toLowerCase().match(/\.[^.]+$/)?.[0]
  if (!extension || !allowedExtensions.includes(extension)) {
    throw new Error('Invalid file extension')
  }

  return true
}

#### 验证步骤

  • \[ ] 所有用户输入都使用模式进行了验证
  • \[ ] 文件上传受到限制(大小、类型、扩展名)
  • \[ ] 查询中没有直接使用用户输入
  • \[ ] 使用白名单验证(而非黑名单)
  • \[ ] 错误消息不会泄露敏感信息

3. SQL 注入防护

#### FAIL: 绝对不要拼接 SQL

// DANGEROUS - SQL Injection vulnerability
const query = `SELECT * FROM users WHERE email = '${userEmail}'`
await db.query(query)

#### PASS: 始终使用参数化查询

// Safe - parameterized query
const { data } = await supabase
  .from('users')
  .select('*')
  .eq('email', userEmail)

// Or with raw SQL
await db.query(
  'SELECT * FROM users WHERE email = $1',
  [userEmail]
)

#### 验证步骤

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

4. 身份验证与授权

#### JWT 令牌处理

// FAIL: WRONG: localStorage (vulnerable to XSS)
localStorage.setItem('token', token)

// PASS: CORRECT: httpOnly cookies
res.setHeader('Set-Cookie',
  `token=${token}; HttpOnly; Secure; SameSite=Strict; Max-Age=3600`)

#### 授权检查

export async function deleteUser(userId: string, requesterId: string) {
  // ALWAYS verify authorization first
  const requester = await db.users.findUnique({
    where: { id: requesterId }
  })

  if (requester.role !== 'admin') {
    return NextResponse.json(
      { error: 'Unauthorized' },
      { status: 403 }
    )
  }

  // Proceed with deletion
  await db.users.delete({ where: { id: userId } })
}

#### 行级安全(Supabase)

-- Enable RLS on all tables
ALTER TABLE users ENABLE ROW LEVEL SECURITY;

-- Users can only view their own data
CREATE POLICY "Users view own data"
  ON users FOR SELECT
  USING (auth.uid() = id);

-- Users can only update their own data
CREATE POLICY "Users update own data"
  ON users FOR UPDATE
  USING (auth.uid() = id);

#### 验证步骤

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

5. XSS 防护

#### 清理 HTML

import DOMPurify from 'isomorphic-dompurify'

// ALWAYS sanitize user-provided HTML
function renderUserContent(html: string) {
  const clean = DOMPurify.sanitize(html, {
    ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'p'],
    ALLOWED_ATTR: []
  })
  return <div dangerouslySetInnerHTML={{ __html: clean }} />
}

#### 内容安全策略

// 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()
  }
]

#### 验证步骤

  • \[ ] 用户提供的 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: 'Invalid CSRF token' },
      { status: 403 }
    )
  }

  // Process request
}

#### SameSite Cookie

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 minutes
  max: 100, // 100 requests per window
  message: 'Too many requests'
})

// Apply to routes
app.use('/api/', limiter)

#### 昂贵操作

// Aggressive rate limiting for searches
const searchLimiter = rateLimit({
  windowMs: 60 * 1000, // 1 minute
  max: 10, // 10 requests per minute
  message: 'Too many search requests'
})

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

#### 验证步骤

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

8. 敏感数据泄露

#### 日志记录

评论
Aaffaan-m
affaan-m
affaan-m/ECC
查看 GitHub 仓库 查看作者的其他 Skill
来源信息
作者@affaan-m
所属大类测试与安全 Testing & Security / 安全
国内可用性需海外环境
最近源活动—
风险提示执行命令、访问网络、敏感路径
提示:风险标签为程序静态扫描结果,仅作提示,不代表安全认证。安装前请阅读 SKILL.md 及其引用的脚本、权限,自行判断是否可信。