Communitygithub.com

セキュリティレビュー

認証の追加、ユーザー入力の処理、シークレットの操作、APIエンドポイントの作成、または決済/機密機能の実装時に使用します。包括的なセキュリティチェックリストとパターンを提供します。

セキュリティレビュー とは?

このスキルは、コードがセキュリティのベストプラクティスに従っていることを確認し、潜在的な脆弱性を特定するための包括的なガイドを提供します。認証、認可、ユーザー入力処理、APIエンドポイント作成、シークレット管理、決済機能など、さまざまなセキュリティ関連タスクを扱うAIエージェント(Claude Code、Cursor、Codexなど)向けに設計されています。スキルは、シークレット管理、入力検証、SQLインジェクション防止、認証・認可、XSS防止、CSRF保護、レート制限、機密データ露出防止、ブロックチェーン(Solana)セキュリティ、依存関係セキュリティの10のカテゴリにわたる詳細なチェックリストとコード例(パス/フェイルパターンを含む)を提供します。各セクションには検証手順が含まれており、開発者はコードをチェックして脆弱性がないことを確認できます。また、自動セキュリティテストの例と、本番環境デプロイ前の最終チェックリストも含まれています。

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

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

セキュリティレビュースキル

このスキルは、すべてのコードがセキュリティのベストプラクティスに従っていることを確認し、潜在的な脆弱性を特定します。

アクティブ化のタイミング

  • 認証または認可の実装時
  • ユーザー入力またはファイルアップロードの処理時
  • 新しい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 not configured')
}

検証手順

  • 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('File too large (max 5MB)')
  }

  // タイプチェック
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']
  if (!allowedTypes.includes(file.type)) {
    throw new Error('Invalid file type')
  }

  // 拡張子チェック
  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インジェクション防止

失敗:絶対に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で
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: 'Unauthorized' },
      { 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: 'Invalid CSRF token' },
      { 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: 'Too many requests'
})

// ルートに適用
app.use('/api/', limiter)

負荷の高い操作

// 検索に対する厳格なレート制限
const searchLimiter = rateLimit({
  windowMs: 60 * 1000, // 1分
  max: 10, // 1分間に10リクエスト
  message: 'Too many search requests'
})

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

検証手順

  • すべてのAPIエンドポイントでレート制限が有効
  • 負荷の高い操作にはより厳しい制限
  • IPベースのレート制限
  • ユーザーベースのレート制限(認証済み)

8. 機密データの露出

ロギング

// 失敗:間違い:機密データのロギング
console.log('User login:', { email, password })
console.log('Payment:', { cardNumber, cvv })

// 合格:正しい:機密データを編集
console.log('User login:', { email, userId })
console.log('Payment:', { last4: card.last4, userId })

エラーメッセージ

// 失敗:間違い:内部詳細の露出
catch (error) {
  return NextResponse.json(
    { error: error.message, stack: error.stack },
    { status: 500 }
  )
}

// 合格:正しい:汎用的なエラーメッセージ
catch (error) {
  console.error('Internal error:', error)
  return NextResponse.json(
    { error: 'An error occurred. Please try again.' },
    { 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('Invalid recipient')
  }

  // 金額を検証
  if (transaction.amount > maxAmount) {
    throw new Error('Amount exceeds limit')
  }

  // ユーザーが十分な残高を持っていることを検証
  const balance = await getBalance(transaction.from)
  if (balance < transaction.amount) {
    throw new Error('Insufficient balance')
  }

  return true
}

検証手順

  • ウォレット署名が検証されている
  • トランザクション詳細が検証されている
  • トランザクション前に残高チェックが行われている
  • 盲目的なトランザクション署名がない

10. 依存関係のセキュリティ

定期的な更新

# 脆弱性をチェック
npm audit

# 自動修正可能な問題を修正
npm audit fix

# 依存関係を更新
npm update

# 古いパッケージをチェック
npm outdated

ロックファイル

# 常にロックファイルをコミット

検証手順

  • 依存関係が最新である
  • 既知の脆弱性がない(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:適切に設定されている
  • ファイルアップロード:検証されている(サイズ、タイプ)
  • ウォレット署名:確認されている(ブロックチェーンの場合)

リソース


注意:セキュリティはオプションではありません。1つの脆弱性がプラットフォーム全体を危険にさらす可能性があります。疑わしい場合は、慎重を期してください。

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.

関連スキル