security-review

security-review

熱門

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

23萬星標
0分支
更新於 2026/6/10
SKILL.md
readonlyread-only
name
security-review
description

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

安全審查技能

此技能確保所有程式碼遵循安全最佳實務,並識別潛在漏洞。

何時啟用

  • 實作驗證或授權
  • 處理使用者輸入或檔案上傳
  • 建立新的 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:正確設定
  • [ ] 檔案上傳:已驗證(大小、類型)
  • [ ] 錢包簽章:已驗證(若使用區塊鏈)

資源


切記:安全不是選項。一個漏洞就可能危及整個平台。如有疑慮,寧可謹慎。