Communitygithub.com

安全審查

在加入認證、處理使用者輸入、使用機密資訊、建立 API 端點,或實作支付/敏感功能時使用。提供全面的安全檢查清單與模式。

安全審查 是什麼?

此技能(安全審查)作為一份詳盡的開發安全檢查清單,涵蓋金鑰管理、輸入驗證、SQL 注入防範、認證與授權、XSS 防護、CSRF 保護、速率限制、敏感性資料暴露、區塊鏈安全(Solana)以及依賴安全性等十個重點領域。每個領域皆包含明確的「失敗」與「通過」程式碼範例,並提供可操作的驗證步驟,確保開發者能確實遵循最佳實務。該技能支援所有通用開發平台,並特別針對 Next.js、Supabase 及區塊鏈(Solana)提供具體實作建議。其設計使開發者能在編寫或審查程式碼時,直接依據內建範例進行修補與驗證,從而將安全性內建於軟體開發生命週期。此外,技能還包含自動化安全測試的參考範例與一份詳細的部署前檢查清單,協助團隊在進入生產環境前系統性地消除潛在漏洞。

相容平台~Claude Code✓Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/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 "使用者檢視自己的資料"
  ON users FOR SELECT
  USING (auth.uid() = id);

-- 使用者只能更新自己的資料
CREATE POLICY "使用者更新自己的資料"
  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/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

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.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

相關技能