Communitygithub.com

安全審查技能

在添加身份驗證、處理用戶輸入、使用秘密、創建API端點或實現支付/敏感功能時使用此技能。提供全面的安全檢查清單和模式。

安全審查技能 是什麼?

安全審查技能是一個旨在確保代碼遵循安全最佳實踐並識別潛在漏洞的AI代理技能。它專為開發者在實現身份驗證、授權、處理用戶輸入、創建API端點、使用秘密或密碼、實現支付功能以及集成第三方API等場景中使用。該技能提供了一個詳細的安全檢查清單,涵蓋十個關鍵領域:秘密管理、輸入驗證、SQL注入防護、身份驗證與授權、XSS防護、CSRF防護、速率限制、敏感數據暴露、區塊鏈安全(Solana)以及依賴安全性。每個部分都包含清晰的「FAIL(切勿執行)」和「PASS(始終執行)」代碼示例,以及可操作的驗證步驟。此外,它還包括自動化安全測試指南和一個全面的部署前安全檢查清單。該技能支持TypeScript和Node.js技術棧,重點關注流行的框架和庫,如Supabase和Next.js。其關鍵優勢在於它提供了具體、可立即實施的代碼模式和配置,而不是一般的安全建議,使其成為開發者確保代碼安全的實際工具。

相容平台~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 cookie
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 cookie 中(非 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 }} />
}

內容安全政策

從嚴開始,僅在有明確的移除計劃時放鬆。不要預設使用 '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 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 分鐘
  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 乾淨)
  • 已提交鎖定檔案
  • 在 GitHub 上啟用 Dependabot
  • 定期安全更新

安全測試

自動化安全測試

// 測試身分驗證
test('要求身分驗證', async () => {
  const response = await fetch('/api/protected')
  expect(response.status).toBe(401)
})

// 測試授權
test('要求管理員角色', async () => {
  const response = await fetch('/api/admin', {
    headers: { Authorization: `Bearer ${userToken}` }
  })
  expect(response.status).toBe(403)
})

// 測試輸入驗證
test('拒絕無效輸入', async () => {
  const response = await fetch('/api/users', {
    method: 'POST',
    body: JSON.stringify({ email: 'not-an-email' })
  })
  expect(response.status).toBe(400)
})

// 測試速率限制
test('強制執行速率限制', 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.

相關技能