From c7c07ac4e2a4db5fb4fd3c96b6ae618b6ea0096f Mon Sep 17 00:00:00 2001 From: keito4 Date: Fri, 2 Jan 2026 15:55:32 +0900 Subject: [PATCH 1/2] feat: add automatic PR creation from Issues MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue #277で提案されたPR自動作成機能をclaude.ymlに追加しました。 ## Changes ### 1. settings パラメータ追加 `permissions.allowedTools`で必要なBashツールを許可: - Bash(gh:*) - GitHub CLIコマンド - Bash(npm:*) - npmコマンド - Bash(pnpm:*) - pnpmコマンド - Bash(npx:*) - npxコマンド ### 2. claude_args にシステムプロンプト追加 Issueから作業する際、コード変更完了後にPRを自動作成するよう指示 ## Benefits ### Before - Issueからの作業完了後、手動でPR作成URLをクリック - PRのタイトルや本文を手動で入力 - ワークフローの中断 ### After - Issueからの作業完了後、自動的にPRが作成される - gh pr createコマンドが自動実行される - シームレスなワークフロー ## Behavior Issueから@claude: コード変更完了後、自動的にPR作成 PRコメントで@claude: PR作成不要(既にPR内) ## Type of Change - New feature (non-breaking change which adds functionality) - CI/CD changes ## Source This feature was discovered from keito4-org/n8n_custom_node repository using the config-contribution-discover command. Closes #277 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 --- .github/workflows/claude.yml | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/.github/workflows/claude.yml b/.github/workflows/claude.yml index 3f0358c1..90e15cb9 100644 --- a/.github/workflows/claude.yml +++ b/.github/workflows/claude.yml @@ -47,10 +47,19 @@ jobs: actions: read checks: read - # Optional: Give a custom prompt to Claude. If this is not specified, Claude will perform the instructions specified in the comment that tagged it. - # prompt: 'Update the pull request description to include a summary of changes.' + # Settings for allowed tools and permissions + settings: | + { + "permissions": { + "allowedTools": [ + "Bash(gh:*)", + "Bash(npm:*)", + "Bash(pnpm:*)", + "Bash(npx:*)" + ] + } + } - # Optional: Add claude_args to customize behavior and configuration - # See https://github.com/anthropics/claude-code-action/blob/main/docs/usage.md - # or https://docs.claude.com/en/docs/claude-code/cli-reference for available options - # claude_args: '--allowed-tools Bash(gh pr:*)' + # System prompt to automatically create PRs when working on Issues + claude_args: | + --system-prompt "When working on GitHub Issues (not PRs), after completing all code changes and pushing to a branch, you MUST create a Pull Request by running 'gh pr create' command. Do not just provide a link - actually execute the gh pr create command to create the PR automatically." From b7ef2af0fe70c5b4f4409692b1dba510a4ae0218 Mon Sep 17 00:00:00 2001 From: keito4 Date: Fri, 2 Jan 2026 17:48:10 +0900 Subject: [PATCH 2/2] docs: remove duplicate and unused files from .codex/prompts/ MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 完全重複ファイル削除: git-sync.md, setup-husky.md, README.md (.claude/commands/に存在) - 未使用のNext.js特化ファイル削除: next-security-*.md (このリポジトリはNext.jsプロジェクトではない) - 未使用のリファクタリングプロンプト削除: refactor:*.md (実際に使用されていない) - その他の未使用ファイル削除: setup-recommended-ci.md - 空ディレクトリ削除: .codex/prompts/ - ドキュメント更新: README.mdと.claude/commands/README.mdから.codex/prompts/への参照を削除 削減効果: - 13ファイル削除 - 約31.9K削減 - 重複コード534行削除 (2.78%の重複率を解消) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- .claude/commands/README.md | 2 +- .codex/prompts/README.md | 339 -------- .codex/prompts/git-sync.md | 243 ------ .codex/prompts/next-security-check.md | 128 --- .codex/prompts/next-security:authz-review.md | 72 -- .codex/prompts/next-security:config-audit.md | 71 -- .codex/prompts/next-security:deps-scan.md | 58 -- .codex/prompts/refactor:decouple.md | 45 -- .codex/prompts/refactor:dedupe.md | 45 -- .codex/prompts/refactor:reorganize.md | 45 -- .codex/prompts/refactor:simplify.md | 45 -- .codex/prompts/refactor:split.md | 47 -- .codex/prompts/setup-husky.md | 128 --- .codex/prompts/setup-recommended-ci.md | 788 ------------------- README.md | 2 +- 15 files changed, 2 insertions(+), 2056 deletions(-) delete mode 100644 .codex/prompts/README.md delete mode 100644 .codex/prompts/git-sync.md delete mode 100644 .codex/prompts/next-security-check.md delete mode 100644 .codex/prompts/next-security:authz-review.md delete mode 100644 .codex/prompts/next-security:config-audit.md delete mode 100644 .codex/prompts/next-security:deps-scan.md delete mode 100644 .codex/prompts/refactor:decouple.md delete mode 100644 .codex/prompts/refactor:dedupe.md delete mode 100644 .codex/prompts/refactor:reorganize.md delete mode 100644 .codex/prompts/refactor:simplify.md delete mode 100644 .codex/prompts/refactor:split.md delete mode 100644 .codex/prompts/setup-husky.md delete mode 100644 .codex/prompts/setup-recommended-ci.md diff --git a/.claude/commands/README.md b/.claude/commands/README.md index 7dd23977..fad4d9e6 100644 --- a/.claude/commands/README.md +++ b/.claude/commands/README.md @@ -1,6 +1,6 @@ # Claude Automated Commands -This directory contains pre-configured commands that provide automated workflows for common development tasks. These commands can be invoked directly by Claude or triggered automatically based on repository events and context. Additional automated commands are available in the `.codex/prompts/` directory. +This directory contains pre-configured commands that provide automated workflows for common development tasks. These commands can be invoked directly by Claude or triggered automatically based on repository events and context. ## Available Commands diff --git a/.codex/prompts/README.md b/.codex/prompts/README.md deleted file mode 100644 index eb3fdfa2..00000000 --- a/.codex/prompts/README.md +++ /dev/null @@ -1,339 +0,0 @@ -# Codex Automated Prompts - -This directory contains 12 pre-configured prompts that provide automated workflows for common development tasks. These prompts can be invoked directly by Codex CLI or triggered automatically based on repository events and context. - -## Command Categories - -### Quality & Testing - -### Security Analysis - -#### `next-security-check.md` - -**Purpose**: Comprehensive security review for Next.js applications -**Features**: - -- Full security audit workflow -- Dependency vulnerability scanning -- Configuration security assessment -- Authorization flow validation - -#### `next-security:deps-scan.md` - -**Purpose**: Focused dependency vulnerability scanning for Next.js applications -**Features**: - -- `npm audit --omit dev` execution for critical/high vulnerabilities -- Major package delay detection via `npm outdated` -- Security-related ESLint plugin version health checks -- Severity-based summary and response plan templates - -#### `next-security:config-audit.md` - -**Purpose**: Static audit of Next.js configuration files and build output -**Checks**: - -- HSTS, CSP, Permissions-Policy, images.domains, environment variable exposure settings -- `next-safe-middleware` / `helmet` application status and matcher coverage -- `npm run lint / type-check / build` execution to collect warnings and configuration issues - -#### `next-security:authz-review.md` - -**Purpose**: Reviews authentication and authorization flows (RBAC/ABAC) in Next.js applications -**Highlights**: - -- Verification that middleware/API routes/Server Actions enforce roles and permissions -- NextAuth/Lucia session configuration, Cookie, and CSRF countermeasures inventory -- Role × resource matrix and gap correction action reporting - -### Code Refactoring - -#### `refactor:decouple.md` - -**Purpose**: Guides decoupling of tightly coupled code components -**Focus**: - -- Component dependency reduction -- Interface-based design patterns -- Separation of concerns improvement - -#### `refactor:dedupe.md` - -**Purpose**: Eliminates code duplication and consolidates redundant implementations -**Focus**: - -- Duplicate code identification -- Common utility extraction -- Single source of truth establishment - -#### `refactor:reorganize.md` - -**Purpose**: Improves code organization and project structure -**Focus**: - -- File and directory restructuring -- Logical grouping of related functionality -- Import path optimization - -#### `refactor:simplify.md` - -**Purpose**: Simplifies complex code structures and reduces cognitive load -**Focus**: - -- Complex logic breakdown -- Unnecessary abstraction removal -- Code readability improvement - -#### `refactor:split.md` - -**Purpose**: Splits large files or functions into smaller, manageable pieces -**Focus**: - -- Large file decomposition -- Function size reduction -- Modular design promotion - -### Development Environment - -#### `git-sync.md` - -**Purpose**: Provides comprehensive Git synchronization and branch management workflows -**Features**: - -- Branch synchronization with upstream -- Conflict resolution guidance -- Git workflow automation -- Repository state validation - -#### `setup-husky.md` - -**Purpose**: Configures Husky Git hooks for automated code quality enforcement -**Features**: - -- Pre-commit hook setup -- Commit message validation -- Code quality gate enforcement -- Development workflow integration - -#### `setup-recommended-ci.md` - -**Purpose**: Comprehensive guide for setting up recommended CI/CD pipeline based on Elu-co-jp organization standards -**Features**: - -- Step-by-step CI/CD setup instructions -- Quality checks (lint, format, type-check, complexity) -- Unit & E2E testing with 70%+ coverage requirement -- Security scanning (dependency audit, SAST, license compliance) -- Claude Code Review integration -- GitHub Secrets configuration guide -- Husky Git hooks setup -- Troubleshooting guide - -#### `next-security:deps-scan.md` - -**Purpose**: Runs a least-privilege dependency vulnerability sweep for Next.js apps -**Features**: - -- `npm audit --omit dev`, `npm outdated` などでクリティカル/ハイの脆弱性と主要パッケージの遅延を検出 -- セキュリティ関連 ESLint / lint プラグインのバージョン健全性を確認 -- 重大度別のサマリーと対応計画テンプレを出力 - -#### `next-security:config-audit.md` - -**Purpose**: Static audit of `next.config.*`, middleware, and build output -**Checks**: - -- HSTS, CSP, Permissions-Policy, images.domains、環境変数公開設定 -- `next-safe-middleware` / `helmet` 適用状況と matcher の網羅性 -- `npm run lint / type-check / build` を実行し、警告や設定不備を収集 - -#### `next-security:authz-review.md` - -**Purpose**: Reviews authentication & authorization flows (RBAC/ABAC) in Next.js -**Highlights**: - -- Middleware / API Routes / Server Actions がロールや権限を強制しているか検証 -- NextAuth/Lucia のセッション設定、Cookie、CSRF 対策の棚卸し -- ロール×リソース表とギャップ修正アクションをレポート化 - -## Command Usage - -### Direct Invocation - -Commands can be invoked directly in Claude interactions: - -``` -codex run next-security-check -codex execute refactor:decouple -codex run next-security:deps-scan -codex execute git-sync -``` - -### Automatic Triggers - -Commands are automatically triggered by: - -- **Repository Events**: Push, PR creation, issue updates -- **Quality Thresholds**: Coverage drops, lint failures, security issues -- **Time-based Triggers**: Scheduled maintenance, dependency updates -- **Context Patterns**: Specific file changes, error patterns, user actions - -### Workflow Integration - -Commands integrate with development workflows through: - -- **GitHub Actions**: Automated execution in CI/CD pipelines -- **Git Hooks**: Pre-commit, pre-push, and post-merge execution -- **IDE Integration**: Direct invocation from development environments -- **Slack/Teams**: Notification-driven execution - -## Command Configuration - -### Global Settings - -Command behavior is configured in: - -- `.claude/settings.json`: Global command preferences and thresholds -- `.claude/CLAUDE.md`: Quality standards and workflow requirements -- Repository-specific overrides in individual command files - -### Environment Variables - -Commands support customization through environment variables: - -- `CLAUDE_COVERAGE_THRESHOLD`: Test coverage requirements -- `CLAUDE_SECURITY_LEVEL`: Security analysis strictness -- `CLAUDE_CI_TIMEOUT`: CI operation timeout limits -- `CLAUDE_REVIEWER_COUNT`: Required reviewer count for PRs - -### Quality Gates - -Commands enforce quality standards through: - -- **Coverage Requirements**: 70%+ line coverage for all repositories -- **Security Standards**: Critical vulnerability blocking -- **Performance Thresholds**: Response time and resource usage limits -- **Documentation Standards**: Completeness and consistency requirements - -## Best Practices - -### For Development Teams - -#### Command Usage - -- **Use specific commands** for targeted analysis and fixes -- **Combine commands** for comprehensive workflows -- **Monitor command results** and act on recommendations -- **Customize thresholds** based on project requirements - -#### Integration Strategies - -- **Incorporate in CI/CD** for automated quality assurance -- **Use in code reviews** for consistent feedback -- **Schedule regular maintenance** commands for proactive management -- **Train team members** on command capabilities and usage - -### For Project Maintainers - -#### Configuration Management - -- **Set appropriate thresholds** for quality gates -- **Customize command behavior** for technology stack -- **Monitor command performance** and effectiveness -- **Update configurations** based on team feedback - -#### Workflow Optimization - -- **Identify bottlenecks** in development processes -- **Automate repetitive tasks** with command workflows -- **Measure improvement** in code quality and velocity -- **Refine triggers** based on usage patterns - -## Advanced Usage - -### Command Chaining - -Commands can be chained for complex workflows: - -``` -@claude run quality-check followed by test-all, then create a PR if all pass -@claude execute issue-auto-resolve, update dependencies, and run security-review -``` - -### Conditional Execution - -Commands support conditional execution based on context: - -``` -@claude run fix-ci only if tests are failing -@claude execute security-review if changes affect authentication code -@claude run check-coverage if new code was added -``` - -### Custom Workflows - -Create custom workflows by combining commands: - -```yaml -# Example: Release Preparation Workflow -- quality-check -- test-all -- check-coverage -- security-review -- update-deps -- pr (with release template) -``` - -## Monitoring and Analytics - -### Command Performance - -Monitor command effectiveness through: - -- **Execution time** and resource usage -- **Success rates** and failure patterns -- **Code quality improvements** over time -- **Developer productivity** metrics - -### Quality Trends - -Track quality improvements through: - -- **Coverage trend** analysis -- **Security vulnerability** reduction -- **CI/CD reliability** improvements -- **Issue resolution time** reduction - -## Troubleshooting - -### Command Failures - -If commands fail or produce unexpected results: - -1. **Check prerequisites** (dependencies, permissions, environment) -2. **Review configuration** (settings, thresholds, environment variables) -3. **Examine logs** for error messages and stack traces -4. **Test manually** with reduced scope or simplified inputs -5. **Update command definitions** if necessary - -### Performance Issues - -If commands are slow or timing out: - -1. **Review scope** and reduce if necessary -2. **Check resource availability** (memory, CPU, network) -3. **Optimize thresholds** and filters -4. **Consider parallel execution** for independent operations -5. **Monitor API rate limits** and usage - -### Integration Problems - -If commands don't integrate properly with workflows: - -1. **Verify trigger configurations** and event handling -2. **Check permissions** and access controls -3. **Review environment variables** and context passing -4. **Test isolated execution** before workflow integration -5. **Update integration configurations** as needed - -For detailed configuration and customization options, see the main [CLAUDE.md](../CLAUDE.md) documentation. diff --git a/.codex/prompts/git-sync.md b/.codex/prompts/git-sync.md deleted file mode 100644 index 7147c14c..00000000 --- a/.codex/prompts/git-sync.md +++ /dev/null @@ -1,243 +0,0 @@ -# Git Sync Commands - -## sync-main - -mainブランチに戻って最新版をpullする - -```bash -#!/bin/bash -set -e - -echo "🔄 Syncing with main branch..." - -# 現在のブランチを保存 -CURRENT_BRANCH=$(git branch --show-current) - -# 変更がある場合は確認 -if ! git diff --quiet || ! git diff --cached --quiet; then - echo "⚠️ Uncommitted changes detected!" - echo "Please commit or stash your changes before syncing." - exit 1 -fi - -# mainブランチに切り替え -echo "📦 Switching to main branch..." -git checkout main - -# 最新の変更を取得 -echo "⬇️ Pulling latest changes..." -git pull origin main - -echo "✅ Successfully synced with main branch!" -echo "📊 Latest commits:" -git log --oneline -5 -``` - -## sync-current - -現在のブランチを最新のmainと同期する - -```bash -#!/bin/bash -set -e - -echo "🔄 Syncing current branch with latest main..." - -# 現在のブランチを保存 -CURRENT_BRANCH=$(git branch --show-current) - -if [ "$CURRENT_BRANCH" = "main" ]; then - echo "📦 Already on main branch, pulling latest..." - git pull origin main -else - # 変更がある場合は確認 - if ! git diff --quiet || ! git diff --cached --quiet; then - echo "⚠️ Uncommitted changes detected!" - echo "Please commit or stash your changes before syncing." - exit 1 - fi - - echo "📦 Current branch: $CURRENT_BRANCH" - - # mainの最新を取得 - echo "⬇️ Fetching latest main..." - git fetch origin main - - # 現在のブランチにmainをマージ - echo "🔀 Merging latest main into $CURRENT_BRANCH..." - git merge origin/main - - echo "✅ Successfully synced $CURRENT_BRANCH with main!" -fi - -echo "📊 Latest commits:" -git log --oneline -5 -``` - -## create-pr - -現在のブランチからPRを作成する - -```bash -#!/bin/bash -set -e - -echo "🚀 Creating Pull Request..." - -# 現在のブランチを確認 -CURRENT_BRANCH=$(git branch --show-current) - -if [ "$CURRENT_BRANCH" = "main" ]; then - echo "❌ Cannot create PR from main branch!" - echo "Please create a feature branch first." - exit 1 -fi - -# 変更がある場合はコミット -if ! git diff --quiet || ! git diff --cached --quiet; then - echo "📝 Uncommitted changes detected." - read -p "Do you want to commit them? (y/n): " -n 1 -r - echo - if [[ $REPLY =~ ^[Yy]$ ]]; then - git add -A - read -p "Enter commit message: " COMMIT_MSG - git commit -m "$COMMIT_MSG" - else - echo "⚠️ Please commit your changes before creating a PR." - exit 1 - fi -fi - -# ブランチをプッシュ -echo "⬆️ Pushing branch to remote..." -git push -u origin "$CURRENT_BRANCH" - -# PRを作成 -echo "📝 Creating PR..." -gh pr create --fill - -echo "✅ Pull Request created successfully!" -``` - -## stash-and-sync - -変更を一時保存してmainと同期 - -```bash -#!/bin/bash -set -e - -echo "📦 Stashing changes and syncing with main..." - -# 変更がある場合はstash -if ! git diff --quiet || ! git diff --cached --quiet; then - echo "💾 Stashing current changes..." - git stash push -m "Auto-stash before sync $(date +%Y%m%d-%H%M%S)" - STASHED=true -else - STASHED=false -fi - -# 現在のブランチを保存 -CURRENT_BRANCH=$(git branch --show-current) - -# mainに切り替えて最新を取得 -echo "📦 Switching to main..." -git checkout main -git pull origin main - -# 元のブランチに戻る(mainでない場合) -if [ "$CURRENT_BRANCH" != "main" ]; then - echo "🔄 Returning to $CURRENT_BRANCH..." - git checkout "$CURRENT_BRANCH" - - # mainの変更をマージ - echo "🔀 Merging latest main..." - git merge main -fi - -# stashした変更を戻す -if [ "$STASHED" = true ]; then - echo "📤 Restoring stashed changes..." - git stash pop -fi - -echo "✅ Sync complete!" -echo "📊 Status:" -git status --short -``` - -## branch-status - -現在のブランチの状態を確認 - -```bash -#!/bin/bash - -echo "📊 Branch Status Report" -echo "=======================" - -# 現在のブランチ -CURRENT_BRANCH=$(git branch --show-current) -echo "📍 Current branch: $CURRENT_BRANCH" - -# リモートとの差分 -echo "" -echo "🔄 Remote status:" -git fetch origin --quiet -LOCAL=$(git rev-parse HEAD) -REMOTE=$(git rev-parse @{u} 2>/dev/null || echo "no-remote") - -if [ "$REMOTE" = "no-remote" ]; then - echo " ⚠️ No remote tracking branch" -else - if [ "$LOCAL" = "$REMOTE" ]; then - echo " ✅ Up to date with remote" - else - BEHIND=$(git rev-list --count HEAD..@{u}) - AHEAD=$(git rev-list --count @{u}..HEAD) - if [ "$BEHIND" -gt 0 ]; then - echo " ⬇️ Behind by $BEHIND commits" - fi - if [ "$AHEAD" -gt 0 ]; then - echo " ⬆️ Ahead by $AHEAD commits" - fi - fi -fi - -# mainとの差分 -if [ "$CURRENT_BRANCH" != "main" ]; then - echo "" - echo "📈 Comparison with main:" - git fetch origin main --quiet - BEHIND_MAIN=$(git rev-list --count HEAD..origin/main) - AHEAD_MAIN=$(git rev-list --count origin/main..HEAD) - - if [ "$BEHIND_MAIN" -gt 0 ]; then - echo " ⬇️ Behind main by $BEHIND_MAIN commits" - fi - if [ "$AHEAD_MAIN" -gt 0 ]; then - echo " ⬆️ Ahead of main by $AHEAD_MAIN commits" - fi - if [ "$BEHIND_MAIN" -eq 0 ] && [ "$AHEAD_MAIN" -eq 0 ]; then - echo " ✅ Even with main" - fi -fi - -# ローカルの変更 -echo "" -echo "📝 Local changes:" -CHANGES=$(git status --porcelain | wc -l) -if [ "$CHANGES" -eq 0 ]; then - echo " ✅ Working directory clean" -else - echo " 📄 Modified files: $(git diff --name-only | wc -l)" - echo " ➕ Staged files: $(git diff --cached --name-only | wc -l)" - echo " ❓ Untracked files: $(git ls-files --others --exclude-standard | wc -l)" -fi - -# 最近のコミット -echo "" -echo "📜 Recent commits:" -git log --oneline -5 -``` diff --git a/.codex/prompts/next-security-check.md b/.codex/prompts/next-security-check.md deleted file mode 100644 index 21e5ede9..00000000 --- a/.codex/prompts/next-security-check.md +++ /dev/null @@ -1,128 +0,0 @@ -# Next.js セキュリティチェック - -Next.js プロジェクトに対して、依存関係・設定・実装レベルのセキュリティリスクを洗い出すための定型フロー。 - -## ゴール - -- 既知の脆弱性(npm audit / Snyk など)をゼロにするか、リスクと回避策を明記する -- `next.config.{js,ts}` とミドルウェア層で主要ヘッダー・CSP・イメージ許可リストが適切に設定されている -- API Routes / Route Handlers / Server Actions で認可・入力検証・CSRF 対策が実装されている -- 秘匿情報が `env` 経由でクライアントに漏れていない -- ロール/権限ごとのアクセス制御が middleware・API・UI で一貫している - -## コマンドプリセット - -1. **`next-security:deps-scan`**(権限: read-only + npm install 実行権限) - - 依存関係の既知脆弱性とバージョン遅延を洗い出す - - 生成物はログのみ。リポジトリへ書き込みはしない -2. **`next-security:config-audit`**(権限: read-only) - - `next.config.*`, `middleware.*`, `app/(api|routes)` を静的に確認 - - ヘッダー/CSP/画像ホワイトリスト/環境変数公開範囲を検証 -3. **`next-security:authz-review`**(権限: read-only + .env.local 閲覧権限) - - 認証・認可(RBAC/ABAC)ロジックを確認 - - Role ごとのフロー、Session/Token の有効期限、権限付きリソースの保護状況を検証 - -> それぞれのコマンドを個別に回せるようにし、必要最低限の権限だけをエージェントに付与する。 -> 詳細手順は `.codex/prompts/next-security:*.md` を参照。 - -## 実行フロー(最低限) - -1. **依存関係スキャン** - - `npm --prefix next audit --omit dev` - - `npx --yes @nodesecurity/eslint-plugin-security --version` 等のプラグインが最新か確認 - - `npm outdated --prefix next next react react-dom next-auth` で主要パッケージの遅延を把握 -2. **ビルド時チェック** - - `npm --prefix next run lint` - - `npm --prefix next run type-check` - - `npm --prefix next run build`(`--no-lint` を付けない)で警告を確認 -3. **ミドルウェア/設定確認** - - `next.config.*` と `middleware.{js,ts}` を開いて、以下が揃っているか確認 - - `headers()` に HSTS / X-Content-Type-Options / X-Frame-Options / Referrer-Policy - - `Content-Security-Policy`(CSP)を `next-safe-middleware` などで集中管理し、`script-src` で `nonce` or `sha` を利用 - - `images.domains` / `remotePatterns` で外部イメージを最小限定 - - `env` でクライアントへ公開しているキーが非機密か -4. **実装確認ポイント** - - App Router: Route Handler / Server Action で `cache: 'no-store'` または `revalidate` の意図確認 - - API Routes: 認証ミドルウェア(NextAuth, Lucia など)で `getServerSession` を必須化、レートリミット(Upstash, KV)を適用 - - フォーム: `next/headers`+`csrfToken`、`SameSite=strict` Cookie 設定 - - SSR/ISR: 外部入力を `zod`, `valibot`, `Yup` などでサニタイズ後にテンプレートへ渡す - - クライアント: `dangerouslySetInnerHTML` 禁止 or sanitize-html, `next/script` は `strategy="afterInteractive"` 以上+`nonce` - -## 詳細チェックリスト - -- **依存関係** - - `next`, `react`, `react-dom`, `next-auth`, `next-safe-middleware` などの minor 以上の遅れを Issue 化 - - `dependencies` に dev-only ツールが紛れていないか -- **設定ファイル** - - `productionBrowserSourceMaps` を false にしてソース漏えい防止 - - `compress` 有効化で gzip/brotli、`poweredByHeader: false` - - `eslint.ignoreDuringBuilds` は極力使わない -- **ヘッダー/CSP** - - 必須: `Strict-Transport-Security`, `X-Content-Type-Options`, `X-Frame-Options`, `Referrer-Policy`, `Permissions-Policy` - - `Content-Security-Policy` で `frame-ancestors 'none'`、`connect-src` に外部 API を列挙 - - `next-safe-middleware` や `helmet` を middleware で適用し、`nonce` を `request` コンテキストから Layout へ伝搬 -- **API & データ** - - `POST` 以外で状態変更しない、`mutate` 系は `anti-CSRF token` を確認 - - Prisma/ORM クエリに raw SQL を渡さない、`where` 条件はユーザ入力を直接渡さない - - Upload ルートはファイルサイズ・拡張子・MIME を検証し S3 署名 URL を短期限に設定 -- **認証/セッション** - - NextAuth: `NEXTAUTH_SECRET` 設定済み、`jwt.maxAge` と `session.strategy` の要件一致 - - Middleware で `auth()` を呼び、`config.matcher` で保護パスを網羅 - - Cookie: `secure`, `httpOnly`, `sameSite=strict`、Edge Runtime でも暗号化 -- **権限/アクセス制御** - - ロール × リソースのマトリクスを用意し、Route Handler/API/ページごとに必要権限を明記 - - `next-auth` / `auth.js` の `callbacks.session` / `callbacks.jwt` でロール情報を必ず付与 - - middleware で `role` / `permission` を判定し、Route Group 単位で `config.matcher` に含める - - サーバーコンポーネント/Server Actions でも `assertPermission` などのガードを実行 - - クライアント側の UI 非表示だけに頼らず、API レベルで拒否(403)する -- **ビルド/デプロイ** - - `next build` 結果で警告がないことをスクショ or log として残す - - Vercel/Node サーバで `NODE_ENV=production` を強制 - - `.env*` を gitignore 済みか再確認、`NEXT_PUBLIC_*` の値を棚卸し - -## レポートテンプレ - -``` -## Summary -- npm audit: 0 critical / 1 high (axios CVE-2023-??? → 対応中) -- next.config.js: CSP + HSTS 適用済み、Permissions-Policy 追加予定 -- API Routes: /api/internal/* に未認証アクセス可能 → middleware で保護予定 - -## Action Items -1. Upgrade axios 1.6.0 → 1.7.4 (high) -2. Add CSRF token + SameSite=strict for POST /api/forms -3. Extend middleware matcher to /dashboard/* -``` - -## 参考コマンド - -### `next-security:deps-scan` - -``` -npm --prefix next audit --omit dev -npm --prefix next outdated -``` - -### `next-security:config-audit` - -``` -npm --prefix next run lint -npm --prefix next run type-check -npm --prefix next run build -``` - -### `next-security:authz-review` - -``` -rg -n "auth" next/ -rg -n "role" next/ -rg -n "permission" next/ -cat next/app/middleware.ts -cat next/app/api/**/route.ts -``` - -## Follow-up - -- 重大/高リスクが残る場合は Issue に `severity/security` ラベルで登録し ETA を記載 -- CSP や middleware 変更は必ず `next build && next start` で E2E 動作検証 -- 依存更新を行った場合は `npm --prefix next run test`(もしくは Playwright/E2E)を実行 diff --git a/.codex/prompts/next-security:authz-review.md b/.codex/prompts/next-security:authz-review.md deleted file mode 100644 index 6e5c3f6a..00000000 --- a/.codex/prompts/next-security:authz-review.md +++ /dev/null @@ -1,72 +0,0 @@ -# `next-security:authz-review` - -Next.js (App Router/Pages) の認証・認可実装を棚卸しし、ロール/権限ごとのアクセス制御とセッション設定が適切かを検証するコマンド。 - -## 目的 - -- RBAC/ABAC の要件と実装の乖離を検出 -- API Routes / Route Handlers / Server Actions が適切に保護されているか確認 -- セッション/Cookie/Token の安全設定(期限、SameSite、暗号化)を担保 -- UI だけでなくサーバー側で権限を enforce しているかを評価 - -## 必要権限と前提 - -- リポジトリ read 権限 -- `.env` や `NEXTAUTH_SECRET` など機密値を閲覧する場合は、最小限の view 権限のみ付与(書き込み不可) -- 認証プロバイダ(NextAuth, Lucia 等)の設定ファイルへアクセス可能であること -- 実ユーザー/ロール定義がどこに記録されているか(DB, config, code)を把握 - -## 実行手順 - -1. **認証基盤の特定** - - `rg -n "NextAuth" -g "*.ts" next/` - - `rg -n "auth(" next/` - - `rg -n "getServerSession" next/app` -2. **ロール/権限のデータフロー調査** - - `rg -n "role" next/` - - `rg -n "permission" next/` - - `auth.ts` / `lib/auth` / `middleware.ts` を確認し、`session.user.role` などの形を特定 -3. **Middleware でのガード** - - `middleware.{js,ts}` の `config.matcher` に保護対象パスが含まれているか - - 例: `/dashboard/:path*`, `/api/internal/:path*` -4. **API / Route Handler 点検** - - `cat next/app/api/**/route.ts | rg -n "auth|session|role"` - - 各 Route が `getServerSession`, `assertPermission`, `rateLimit` を実行しているか - - 状態変更系は `POST` のみに限定されているか -5. **Server Actions / RSC** - - `rg -n "\"use server\"" next/` - - 重要アクションで `assertPermission(user, "resource:action")` のようなガードがあるか確認 -6. **Cookie / セッション設定** - - NextAuth: `NEXTAUTH_SECRET`, `session.strategy`, `session.maxAge` - - Cookie オプション: `secure`, `httpOnly`, `sameSite=strict`, `partitioned` - - CSRF: `getCsrfToken` / `anti-CSRF token` の存在 -7. **UI と API の整合性** - - クライアント側でボタン非表示にするだけでなく、API 側でも 403 が返るか - - `role` 切替用の Feature flag がある場合、その制御フローを図解 - -## 期待アウトプット - -- ロール × リソース表(例: Admin, Editor, Viewer) -- 主要エンドポイントごとの認可方法(middleware/Server Action/API Route) -- セッション/Cookie 設定の要約 -- ギャップと是正策(例: `/api/internal/export` に認証ガードなし → middleware 追加) - -## レポートテンプレ - -``` -### next-security:authz-review - -| Resource | Admin | Editor | Viewer | Guard | -|-----------------------|-------|--------|--------|------------------------------------------| -| /dashboard | ✅ | ✅ | 🚫 | middleware + getServerSession | -| /api/internal/export | ✅ | 🚫 | 🚫 | ❌ (no auth) → add matcher + assertPerm | -| Server Action: publishPost | ✅ | ✅ | 🚫 | uses assertPermission("post:publish") | - -- Session: strategy="jwt", maxAge=30d, secure/httpOnly/sameSite=strict ✔ -- CSRF: form actions use csrfToken from next-auth/react ✅ -- Gap: /api/internal/export lacks auth; fix by extending middleware matcher - -**Action** -1. Protect /api/internal/export via middleware + getServerSession -2. Add rate limiting to POST /api/forms (abuse risk) -``` diff --git a/.codex/prompts/next-security:config-audit.md b/.codex/prompts/next-security:config-audit.md deleted file mode 100644 index 31536116..00000000 --- a/.codex/prompts/next-security:config-audit.md +++ /dev/null @@ -1,71 +0,0 @@ -# `next-security:config-audit` - -Next.js の設定・ミドルウェア・ビルド出力を静的に点検し、ヘッダーや CSP、公開範囲が適切かを確認するコマンド。 - -## 目的 - -- `next.config.{js,ts}` / `middleware.{js,ts}` / `app/(api|routes)` の設定に漏れがないか確認 -- HSTS, CSP, Permissions-Policy 等のセキュリティヘッダーが導入済みであることを保証 -- 画像ホワイトリスト・環境変数公開設定・ビルド警告を棚卸し - -## 必要権限と前提 - -- リポジトリ read 権限のみ(設定ファイルを閲覧) -- `.env` の中身は不要。公開環境に影響する変更は行わない -- `npm --prefix next run lint|type-check|build` を実行できる CI 相当の権限 -- Middleware 変更有無を確認するため `git status -sb` を参照(read-only) - -## 実行手順 - -1. **設定ファイル静的確認** - - `rg -n "headers" next/next.config.*` - - `rg -n "poweredByHeader" next/next.config.*` - - `rg -n "images:" next/next.config.*` - - `rg -n "env" next/next.config.*` - - `rg -n "middleware" next/app -g "middleware.{js,ts}"` -2. **セキュリティヘッダー** - - `next.config.*` の `headers()` 戻り値に以下が含まれるか確認 - - `Strict-Transport-Security` - - `X-Content-Type-Options` - - `X-Frame-Options` - - `Referrer-Policy` - - `Permissions-Policy` - - `Content-Security-Policy`(`nonce` / `sha` を Layout へ受け渡し) -3. **CSP / Middleware** - - `next-safe-middleware` / `helmet` の使用状況を確認 - - `config.matcher` が保護対象 Route を網羅しているかチェック -4. **画像・外部リソース** - - `images.domains` / `remotePatterns` / `experimental.images.allowFutureImage` - - `font-src`, `connect-src` など外部ドメイン列挙の最小化 -5. **ビルド検証** - - `npm --prefix next run lint` - - `npm --prefix next run type-check` - - `npm --prefix next run build` - - 警告/エラー、`next build` の `Size Limits` などを記録 -6. **環境変数公開確認** - - `rg -n "process\.env" next/ -g "*.ts"` で `NEXT_PUBLIC_` が適切か確認 - - `next.config.*` の `env` に秘匿情報が含まれていないか確認 - -## 期待アウトプット - -- セキュリティヘッダーの有無一覧 -- CSP の `default-src` / `script-src` / `connect-src` サマリ -- 画像/外部リソース許可リスト -- lint/type-check/build の結果(Pass/Fail + 警告) -- 改善アクション(例: Permissions-Policy 追加、CSP tighten) - -## レポートテンプレ - -``` -### next-security:config-audit - -- headers(): HSTS / X-CTO / XFO / Referrer OK, Permissions-Policy missing -- CSP: default-src 'self'; script-src 'self' 'nonce-...'; connect-src に *.vercel.app を追記予定 -- middleware: next-safe-middleware + custom matcher [/dashboard/:path*] ✅ -- build: lint ✔ / type-check ✔ / build ✔ (warnings 0) -- env: NEXT_PUBLIC_API_BASE ← 公開 API のみ。秘密情報なし - -**Action** -1. Add Permissions-Policy (camera=(), geolocation=()) -2. Restrict images.remotePatterns to CDN only -``` diff --git a/.codex/prompts/next-security:deps-scan.md b/.codex/prompts/next-security:deps-scan.md deleted file mode 100644 index 9ef93585..00000000 --- a/.codex/prompts/next-security:deps-scan.md +++ /dev/null @@ -1,58 +0,0 @@ -# `next-security:deps-scan` - -Next.js プロジェクトの依存関係に既知の脆弱性やサポート外バージョンが含まれていないかを、最小権限で洗い出すコマンド。 - -## 目的 - -- `next`, `react`, `next-auth` など基幹パッケージの脆弱性・EOL 状態を把握 -- セキュリティ関連の ESLint/型チェッカープラグインが最新であることを確認 -- 危険度の高い項目を Issue/PR に落とし込み、回避策と ETA を明記 - -## 必要権限と前提 - -- リポジトリ read 権限 -- `next/` ディレクトリで `npm audit` / `npm outdated` を実行できるローカル実行権限 -- `node_modules` を書き換えずに済むよう `npm install` は行わない(必要なら sandbox 環境を使う) -- 実行前に `node -v` / `npm -v` を記録し、結果に添付 - -## 実行手順 - -1. **環境確認** - - `node -v && npm -v` -2. **既知脆弱性の確認** - - `npm --prefix next audit --omit dev` - - 重大度別トータルと影響パッケージ一覧をメモ -3. **主要パッケージの遅延調査** - - `npm outdated --prefix next next react react-dom next-auth next-safe-middleware` - - `Target`, `Current`, `Latest` を表で整理 -4. **セキュリティ lint 依存の健全性** - - `npm --prefix next list --depth=0 | rg -E "eslint|security|helmet|safe"` - - `npx --yes npm-check-updates --target minor --cwd next --filter "eslint*|@next/eslint-plugin-next"` -5. **結果整理** - - クリティカル/ハイ優先度 → 必須対応 - - Med/Low → Issue backlog、回避策の有無を記述 - -## 期待アウトプット - -- 重大度ごとの件数表 -- 影響パッケージ・CVE・回避策・対応 ETA のリスト -- npm audit / outdated ログ(要約で可) -- 対応不要と判断した場合の理由(例: devDependency のみ、Feature flag 下など) - -## レポートテンプレ - -``` -### next-security:deps-scan -Node 20.11 / npm 10.5 - -| Severity | Count | Packages (example) | -|----------|-------|--------------------| -| Critical | 0 | - | -| High | 1 | axios@1.6.0 (CVE-2023-XXXX) | -| Moderate | 2 | postcss@8.4.5, braces@3.0.2 | - -**Upgrade plan** -- [ ] axios 1.6.0 → 1.7.4 (PR #123 ETA 2024-05-01) -- [ ] next 14.1.0 → 14.2.3 (blocked: storybook plugin) - -``` diff --git a/.codex/prompts/refactor:decouple.md b/.codex/prompts/refactor:decouple.md deleted file mode 100644 index 9ff82dbd..00000000 --- a/.codex/prompts/refactor:decouple.md +++ /dev/null @@ -1,45 +0,0 @@ -# 疎結合にして依存関係を減らす - -## 目的 - -具体実装への直接依存を避け、差し替え・テスト・進化に強い構造にする。 - -## 適用場面 - -- 実装詳細(ORM/HTTPクライアント)に直依存 -- テストで重いモック/スタブ連鎖が必要 -- 継承で結合が強く、拡張が困難 - -## 基本ルール - -- 抽象(インターフェース/ポート)に依存 -- 外部詳細はアダプタで隔離 -- 継承より合成(委譲)を優先 - -## 手順(最小リスク) - -0. リポジトリ全体で該当依存を洗い出し、5件ずつまとめてGitHub Issueを起票する(MCP経由を推奨) -1. 依存の向きを可視化(呼び出し/被呼び出し) -2. 抽象I/Fを導入し呼び出し側を差し替え -3. 具体実装をアダプタとして後置 - -## 測定指標(改善確認) - -- 実装→抽象のエッジ比率↑ -- テストでの差し替え箇所↓、モック軽量化 -- 置換(別DB/別HTTP)に要する修正箇所↓ - -## アンチパターン - -- 形骸化したI/F(1実装専用の名寄せだけ) -- 抽象を増やすだけで依存向きが変わらない - -## 関連タグ(refactor) - -`refactor:decouple`(依存逆転・I/F分割・継承→合成) - -## コミット例 - -``` -refactor:decouple storage behind Repository interface -``` diff --git a/.codex/prompts/refactor:dedupe.md b/.codex/prompts/refactor:dedupe.md deleted file mode 100644 index a747c763..00000000 --- a/.codex/prompts/refactor:dedupe.md +++ /dev/null @@ -1,45 +0,0 @@ -# 非冗長にして重複を排除する - -## 目的 - -同じ知識/意図の複数実装を一本化し、矛盾と修正漏れを防ぐ。 - -## 適用場面 - -- 同一ロジックが3箇所以上で再実装 -- マジックナンバー/リテラルが散在 -- 類似ユーティリティ/ヘルパーの乱立 - -## 基本ルール - -- 真実の所在は一箇所 -- 定数・共通ロジックを共有点へ集約 -- 使われないコードは削除 - -## 手順(最小リスク) - -0. リポジトリ全体で重複を調査し、5件単位でGitHub Issue化してから着手する(MCP経由を推奨) -1. 重複箇所を洗い出し、唯一実装を決定 -2. 参照側を順次置換(小さなPRで段階移行) -3. 旧実装を撤去し、テスト参照を一本化 - -## 測定指標(改善確認) - -- 重複率↓、同義ヘルパー数↓ -- 修正時の変更箇所数↓ -- マジック値の出現回数↓ - -## アンチパターン - -- 早すぎる共通化で可読性が下がる -- 巨大全能ヘルパーの作成 - -## 関連タグ(refactor) - -`refactor:dedupe`, `refactor:simplify`(定数化・命名整理) - -## コミット例 - -``` -refactor:dedupe date range handling across billing/reporting -``` diff --git a/.codex/prompts/refactor:reorganize.md b/.codex/prompts/refactor:reorganize.md deleted file mode 100644 index e0d75844..00000000 --- a/.codex/prompts/refactor:reorganize.md +++ /dev/null @@ -1,45 +0,0 @@ -# 高凝集にして内部変更を容易にする - -## 目的 - -密接に関連するデータと振る舞いを近接配置し、内部の作り替えを低コストにする。 - -## 適用場面 - -- 関連機能が別散し、修正が横断的になる -- 値/型/定数が多所に点在 -- 長関数が複数の小責務を抱えている - -## 基本ルール - -- 近くで使うものは近くに置く -- 役割が近い小片は統合して読み順を素直に -- ディレクトリは役割(関心)名で切る - -## 手順(最小リスク) - -0. 関連箇所を全リポジトリから洗い出し、5件ずつGitHub Issueに整理してから実装を開始(MCP経由を推奨) -1. 使用箇所へ定義を移動(近接配置) -2. 値オブジェクト/パラメータオブジェクト化で意図を集約 -3. 同系のヘルパー・定数を1か所へ統合 - -## 測定指標(改善確認) - -- 変更時に触るファイル数↓ -- 同名/類似ユーティリティ数↓ -- 関数の引数個数↓、局所変数の寿命↓ - -## アンチパターン - -- 形だけのクラス分割で実質凝集が下がる -- 便利フォルダ(misc/utils)への無差別集約 - -## 関連タグ(refactor) - -`refactor:reorganize`, `refactor:simplify`, `refactor:dedupe` - -## コミット例 - -``` -refactor:reorganize group user validators under domain/user/validators -``` diff --git a/.codex/prompts/refactor:simplify.md b/.codex/prompts/refactor:simplify.md deleted file mode 100644 index e58e90fc..00000000 --- a/.codex/prompts/refactor:simplify.md +++ /dev/null @@ -1,45 +0,0 @@ -# 単純化して理解性を向上させる - -## 目的 - -複雑な実装を簡潔で明快な形に整理し、可読性と保守性を向上させる。 - -## 適用場面 - -- ネストが深すぎて追跡困難 -- 条件分岐が複雑で理解しにくい -- 不必要な抽象化で過度に複雑 - -## 基本ルール - -- 早期リターンで条件ネストを削減 -- 複雑な条件式を説明的な変数/関数に抽出 -- 不要な中間層・ラッパーを除去 - -## 手順(最小リスク) - -0. 複雑度の高い箇所をリポジトリ全体から抽出し、5件ずつGitHub Issueにまとめてから対応を進める(MCP経由を推奨) -1. 複雑な条件を説明的な変数に抽出 -2. 早期リターン/ガード句の導入 -3. 不要な抽象層の削除 - -## 測定指標(改善確認) - -- 循環的複雑度(CC)↓ -- ネスト深度↓ -- 行数/メソッド数の削減 - -## アンチパターン - -- 過度な簡略化で意図が不明瞭になる -- パフォーマンスを犠牲にした単純化 - -## 関連タグ(refactor) - -`refactor:simplify`, `refactor:dedupe`, `refactor:reorganize` - -## コミット例 - -``` -refactor:simplify complex validation logic with early returns -``` diff --git a/.codex/prompts/refactor:split.md b/.codex/prompts/refactor:split.md deleted file mode 100644 index 495b2ca4..00000000 --- a/.codex/prompts/refactor:split.md +++ /dev/null @@ -1,47 +0,0 @@ -# 関心を分離して影響範囲を限定する - -## 目的 - -単一の変更理由に専念するユニットへ分割し、修正の波及・レビュー範囲を局所化する。 - -## 適用場面 - -- 1ファイル/関数に複数の変更理由が混在 -- I/O・計算・表示が同居 -- 外部依存(DB/HTTP/FS)が多系統 - -## 基本ルール - -- 公開面(export/公開API)は最小限 -- ファイルは「役割」単位で切る -- 同一関心が3件以上なら専用ディレクトリ化 - -## 手順(最小リスク) - -0. 関心が混在している箇所を全体から洗い出し、5件の単位でGitHub Issueを作成してからリファクタリングに着手(MCP経由を推奨) -1. `refactor:reorganize`で入れ物(ディレクトリ/命名)を先に整える -2. 純粋処理を`refactor:split`(extract-function/module)で分ける -3. I/O/境界を`refactor:split-io-boundary`相当で退避 -4. 旧コードを撤去し、公開面を再確認 - -## 測定指標(改善確認) - -- 循環的複雑度(CC)↓、ネスト深度↓ -- ファイル行数↓、依存グラフの循環減 -- 1ユニット=1変更理由の説明可能性↑ - -## アンチパターン - -- 目的の異なる修正を1PRに混在 -- 公開面の肥大化(境界が漏れる) -- 細片化しすぎて探索性が低下 - -## 関連タグ(refactor) - -`refactor:split`[`-by-reason`|`-by-layer`|`-by-feature`|`-io-boundary`|`-cqrs`], `refactor:reorganize` - -## コミット例 - -``` -refactor:split-by-reason checkout (parse/validate/execute) -``` diff --git a/.codex/prompts/setup-husky.md b/.codex/prompts/setup-husky.md deleted file mode 100644 index 98374421..00000000 --- a/.codex/prompts/setup-husky.md +++ /dev/null @@ -1,128 +0,0 @@ -Husky + lint-staged + commitlint 最小構成 - -コミット前に軽量な自動整形と静的チェックを行い、プッシュ前とCIで重い検証を実行します。 - -方針 -• pre-commit: ステージ済みファイルに対して ESLint 自動修正と Prettier 整形を高速実行 -• pre-push: 型チェックとテストを実行 -• commit-msg: Conventional Commits を commitlint で検証 -• npm --prefix next で一貫して next/ の依存を使用 - -⸻ - -セットアップ - -npm i -D husky lint-staged @commitlint/cli @commitlint/config-conventional -npm pkg set scripts.prepare="husky" -npm run prepare -npx husky add .husky/pre-commit "npx lint-staged" -npx husky add .husky/commit-msg "npx commitlint --edit \$1" -npx husky add .husky/pre-push "npm --prefix next run type-check && npm --prefix next run test:ci" - -⸻ - -必要な npm scripts(next/package.json) - -{ -"scripts": { -"type-check": "tsc --noEmit", -"lint": "eslint .", -"format": "prettier --write .", -"format:check": "prettier --check .", -"test:ci": "jest --ci --runInBand" -} -} - -⸻ - -設定ファイル - -.lintstagedrc.json(リポジトリルート) - -{ -"next/**/\*.{ts,tsx}": [ -"npm --prefix next exec eslint --cache --cache-location .cache/eslint --max-warnings=0 --fix", -"npm --prefix next exec prettier --write" -], -"next/**/\*.{js,jsx,json,md,css,scss}": [ -"npm --prefix next exec prettier --write" -] -} - -.commitlintrc.json(リポジトリルート) - -{ -"extends": ["@commitlint/config-conventional"] -} - -.eslintignore(任意、next/に配置) - -node_modules -.next -dist -coverage -public - -.prettierignore(任意、next/に配置) - -node_modules -.next -dist -coverage -build - -package.json(任意、ルート。Nodeバージョン固定) - -{ -"engines": { -"node": ">=20 <23" -} -} - -.nvmrc(任意、ルート) - -20 - -⸻ - -CI 例(GitHub Actions) - -.github/workflows/ci.yml - -name: CI -on: -push: -branches: [main] -pull_request: -jobs: -node: -runs-on: ubuntu-latest -steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 -with: -node-version: 20 -cache: npm - run: npm ci - run: npm ci -working-directory: next - run: npm run type-check -working-directory: next - run: npm run lint -working-directory: next - run: npm run format:check -working-directory: next - run: npm run test:ci -working-directory: next - -⸻ - -トラブルシューティング - -フックの確認 - -git config core.hooksPath - -Husky の再初期化 - -rm -rf .husky -npm run prepare -npx husky add .husky/pre-commit "npx lint-staged" -npx husky add .husky/commit-msg "npx commitlint --edit \$1" -npx husky add .husky/pre-push "npm --prefix next run type-check && npm --prefix next run test:ci" - -一時的にフックをスキップ - -git commit --no-verify -m "urgent: emergency fix" diff --git a/.codex/prompts/setup-recommended-ci.md b/.codex/prompts/setup-recommended-ci.md deleted file mode 100644 index bd79c55b..00000000 --- a/.codex/prompts/setup-recommended-ci.md +++ /dev/null @@ -1,788 +0,0 @@ -# 推奨CI/CDセットアップガイド - -このコマンドは、Elu-co-jp 組織で使用されている推奨CI/CD構成をリポジトリに適用するための包括的なガイドです。 - -## 概要 - -このガイドでは、以下の要素を含む完全なCI/CDパイプラインの構築を支援します: - -1. **基本品質チェック**: Lint、フォーマット、型チェック、複雑度分析 -2. **テスト & カバレッジ**: ユニットテスト、E2Eテスト (70%+ カバレッジ要件) -3. **セキュリティスキャン**: 依存関係の脆弱性、SAST、ライセンス準拠 -4. **Claude統合**: AIアシストコードレビュー -5. **リリース自動化**: セマンティックバージョニング、リリースノート生成 - ---- - -## 前提条件 - -このガイドを実行する前に、以下を確認してください: - -- Node.js 20.x がインストールされている -- リポジトリが GitHub 上にホストされている -- package.json が存在する -- 必要な npm scripts が定義されている (または作成する準備がある) - ---- - -## ステップ1: リポジトリ構造の確認 - -まず、現在のリポジトリ構造を確認します: - -```bash -# プロジェクトルートでの確認 -ls -la -cat package.json | jq '.scripts' -``` - -### 必要なディレクトリ構造 - -``` -project-root/ -├── .github/ -│ └── workflows/ -│ ├── ci.yml -│ ├── claude-code-review.yml -│ ├── security.yml -│ └── release.yml (オプション) -├── next/ (Next.jsプロジェクトの場合) -│ ├── package.json -│ └── ... -├── package.json -└── ... -``` - ---- - -## ステップ2: 必要な npm scripts の確認と作成 - -以下の npm scripts が必要です。存在しない場合は追加してください: - -### ルート package.json - -```json -{ - "scripts": { - "prepare": "husky", - "build": "cd next && npm run build", - "lint": "cd next && npm run lint", - "type-check": "cd next && npm run type-check", - "test": "cd next && npm run test", - "ci:test": "cd next && npm run ci:test", - "format:check": "cd next && npm run format:check" - } -} -``` - -### Next.js package.json (next/package.json) - -```json -{ - "scripts": { - "dev": "next dev", - "build": "next build", - "start": "next start", - "lint": "eslint .", - "lint:strict": "eslint . --max-warnings 0", - "format": "prettier --write .", - "format:check": "prettier --check .", - "type-check": "tsc --noEmit", - "test": "vitest", - "test:e2e": "playwright test", - "ci:test": "vitest run --coverage", - "complexity:check": "npx complexity-report --format json --output complexity.json src/" - } -} -``` - -### 確認コマンド - -```bash -# ルートディレクトリで確認 -npm run build --dry-run -npm run lint --dry-run -npm run type-check --dry-run -npm run test --dry-run -``` - ---- - -## ステップ3: 基本CI ワークフロー (.github/workflows/ci.yml) - -### 最小構成版 (シンプルなプロジェクト向け) - -```yaml -name: CI Pipeline - -on: - pull_request: - branches: [main] - push: - branches: [main] - -concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -env: - NODE_VERSION: '20' - COVERAGE_THRESHOLD: 70 - -jobs: - quality: - name: Quality Checks - runs-on: ubuntu-latest - timeout-minutes: 10 - - steps: - - name: Checkout code - uses: actions/checkout@v4 - - - name: Setup Node.js - uses: actions/setup-node@v4 - with: - node-version: ${{ env.NODE_VERSION }} - cache: 'npm' - - - name: Install dependencies - run: npm ci - - - name: Run ESLint - run: npm run lint - - - name: Check Prettier formatting - run: npm run format:check - - - name: TypeScript type check - run: npm run type-check - - test: - name: Unit Tests & Coverage - runs-on: ubuntu-latest - timeout-minutes: 15 - needs: quality - - steps: - - name: Checkout code - uses: actions/checkout@v4 - - - name: Setup Node.js - uses: actions/setup-node@v4 - with: - node-version: ${{ env.NODE_VERSION }} - cache: 'npm' - - - name: Install dependencies - run: npm ci - - - name: Run unit tests with coverage - run: npm run ci:test - - - name: Check coverage threshold - run: | - if [ -f "./coverage/coverage-summary.json" ]; then - COVERAGE=$(node -e " - const fs = require('fs'); - const coverage = JSON.parse(fs.readFileSync('./coverage/coverage-summary.json', 'utf8')); - const total = coverage.total; - console.log(Math.floor(total.lines.pct)); - ") - echo "Current coverage: ${COVERAGE}%" - if [ "$COVERAGE" -lt "${{ env.COVERAGE_THRESHOLD }}" ]; then - echo "::warning::Test coverage (${COVERAGE}%) is below target (${{ env.COVERAGE_THRESHOLD }}%)" - fi - fi - - build: - name: Build Test - runs-on: ubuntu-latest - timeout-minutes: 10 - needs: [quality, test] - - steps: - - name: Checkout code - uses: actions/checkout@v4 - - - name: Setup Node.js - uses: actions/setup-node@v4 - with: - node-version: ${{ env.NODE_VERSION }} - cache: 'npm' - - - name: Install dependencies - run: npm ci - - - name: Build application - run: npm run build -``` - -### CI最適化: Path Filters による実行最適化 - -**目的**: 変更されたファイルに応じて必要なジョブのみを実行することで、CIの実行時間を短縮し、コストを削減します。 - -#### 実装方法 - -GitHub Actionsの`on.push.paths`と`on.pull_request.paths`フィルター、および`dorny/paths-filter`アクションを組み合わせて使用します。 - -##### 1. ワークフローレベルでのフィルタリング - -ワークフロー全体をスキップするには、`on`セクションで`paths`を指定します: - -```yaml -on: - pull_request: - paths: - - '**.js' - - '**.ts' - - '**.mjs' - - '**.cjs' - - '**.json' - - '**.sh' - - '**.bats' - - '.github/workflows/**' - - 'package.json' - - 'package-lock.json' - - '.eslintrc.*' - - '.prettierrc.*' - - 'tsconfig.json' - push: - branches: [main, master] - paths: - - '**.js' - - '**.ts' - # ... 同様のパターン -``` - -##### 2. ジョブレベルでの細かい制御 - -各ジョブを変更内容に応じて実行するには、`dorny/paths-filter`を使用します: - -```yaml -jobs: - changes: - name: Detect Changes - runs-on: ubuntu-latest - outputs: - code: ${{ steps.filter.outputs.code }} - scripts: ${{ steps.filter.outputs.scripts }} - workflows: ${{ steps.filter.outputs.workflows }} - dependencies: ${{ steps.filter.outputs.dependencies }} - steps: - - uses: actions/checkout@v4 - - uses: dorny/paths-filter@v3 - id: filter - with: - filters: | - code: - - '**.js' - - '**.ts' - - 'src/**' - - 'test/**/*.test.{js,ts}' - scripts: - - '**.sh' - - 'script/**' - workflows: - - '.github/workflows/**' - dependencies: - - 'package.json' - - 'package-lock.json' - - lint: - needs: changes - if: needs.changes.outputs.code == 'true' || needs.changes.outputs.dependencies == 'true' - # ... lintジョブの内容 - - test: - needs: changes - if: needs.changes.outputs.code == 'true' || needs.changes.outputs.dependencies == 'true' - # ... testジョブの内容 - - actionlint: - needs: changes - if: needs.changes.outputs.workflows == 'true' - # ... actionlintジョブの内容 -``` - -##### 3. Quality Gate での skipped 状態の処理 - -ジョブがスキップされた場合も成功として扱うように、Quality Gateを更新します: - -```yaml -quality-gate: - needs: [changes, lint, test, integration-test, actionlint] - if: always() - steps: - - name: Verify all checks passed - run: | - function check_result() { - local result=$1 - [[ "$result" == "success" || "$result" == "skipped" ]] - } - - if ! check_result "${{ needs.lint.result }}"; then - echo "::error::Lint & Format failed" - exit 1 - fi - # ... 他のジョブも同様にチェック -``` - -#### Path Filters のベストプラクティス - -| 対象ワークフロー | 推奨フィルター | 理由 | -| ---------------------- | ----------------------------------------------------- | ---------------------------------------- | -| **CI Pipeline** | コード、設定ファイル、ワークフロー自体 | ドキュメントのみの変更でテストをスキップ | -| **Docker Image Build** | `.devcontainer/**`, `npm/global.json`, `package.json` | DevContainer関連の変更時のみビルド | -| **Security Scans** | コード、依存関係ファイル | セキュリティに影響する変更のみスキャン | -| **Documentation** | `**.md`, `docs/**` | ドキュメント変更時のみデプロイ | - -#### 効果測定 - -Path Filtersを導入すると、以下のような効果が期待できます: - -- ドキュメントのみの変更: CI実行時間 **90%削減** (10分 → 1分) -- DevContainer変更なし: Docker Image Build **スキップ** (45分 → 0分) -- ワークフローのみの変更: Lint/Test **スキップ**、Actionlintのみ実行 - -**注意**: mainブランチへのpushでは、すべてのチェックを実行することを推奨します(path filtersを適用しない、または緩めに設定)。 - -### フル構成版 (Next.js + Supabase プロジェクト向け) - -Elu-co-jp リポジトリから参照: - -- `/Users/keito4/develop/github.com/Elu-co-jp/cyber_ace_1on1/.github/workflows/ci.yml` - -この構成には以下が含まれます: - -- GitHub Packages 認証 -- Supabase CLI 統合 -- DB型生成 -- E2E テスト (Critical Path / Full Suite) -- Scenario Flow テスト -- Edge Functions テスト -- PR コメントによるカバレッジレポート - ---- - -## ステップ4: セキュリティスキャン (.github/workflows/security.yml) - -### 推奨構成 - -```yaml -name: Security Scan - -on: - schedule: - - cron: '0 2 * * *' # 毎日午前2時 (JST 午前11時) - push: - branches: [main] - pull_request: - branches: [main] - workflow_dispatch: - -concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -env: - NODE_VERSION: '20' - -jobs: - dependency-scan: - name: Dependency Vulnerability Scan - runs-on: ubuntu-latest - timeout-minutes: 10 - - steps: - - name: Checkout code - uses: actions/checkout@v4 - - - name: Setup Node.js - uses: actions/setup-node@v4 - with: - node-version: ${{ env.NODE_VERSION }} - cache: 'npm' - - - name: Install dependencies - run: npm ci - - - name: Run npm audit - run: | - npm audit --audit-level=moderate --json > audit-results.json || true - - CRITICAL=$(cat audit-results.json | jq '.metadata.vulnerabilities.critical // 0') - HIGH=$(cat audit-results.json | jq '.metadata.vulnerabilities.high // 0') - - echo "Critical: $CRITICAL" >> $GITHUB_STEP_SUMMARY - echo "High: $HIGH" >> $GITHUB_STEP_SUMMARY - - if [ "$CRITICAL" -gt 0 ]; then - echo "❌ Critical vulnerabilities found" - npm audit --audit-level=critical - exit 1 - fi - - sast-scan: - name: SAST Scan - runs-on: ubuntu-latest - timeout-minutes: 15 - permissions: - actions: read - contents: read - security-events: write - - steps: - - name: Checkout code - uses: actions/checkout@v4 - - - name: Initialize CodeQL - uses: github/codeql-action/init@v3 - with: - languages: javascript-typescript - queries: security-extended,security-and-quality - - - name: Autobuild - uses: github/codeql-action/autobuild@v3 - - - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v3 - - license-check: - name: License Compliance Check - runs-on: ubuntu-latest - timeout-minutes: 10 - - steps: - - name: Checkout code - uses: actions/checkout@v4 - - - name: Setup Node.js - uses: actions/setup-node@v4 - with: - node-version: ${{ env.NODE_VERSION }} - cache: 'npm' - - - name: Install dependencies - run: npm ci - - - name: Install license-checker - run: npm install -g license-checker - - - name: Check licenses - run: | - license-checker --json --out licenses.json - - FORBIDDEN_FOUND=$(cat licenses.json | jq -r 'to_entries[] | select(.value.licenses | type == "string" and (test("GPL|AGPL"))) | .key' || echo "") - - if [ -n "$FORBIDDEN_FOUND" ]; then - echo "❌ Forbidden licenses found" - echo "$FORBIDDEN_FOUND" - exit 1 - fi -``` - -完全版は以下を参照: - -- `/Users/keito4/develop/github.com/Elu-co-jp/cyber_ace_1on1/.github/workflows/security.yml` - ---- - -## ステップ5: Claude統合 (.github/workflows/claude-code-review.yml) - -### 推奨構成 - -```yaml -name: Claude Code Review - -on: - pull_request: - types: [opened, synchronize] - -jobs: - claude-review: - runs-on: ubuntu-latest - permissions: - contents: read - pull-requests: read - issues: read - id-token: write - - steps: - - name: Checkout repository - uses: actions/checkout@v4 - with: - fetch-depth: 1 - - - name: Run Claude Code Review - uses: anthropics/claude-code-action@v1 - with: - claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} - prompt: | - REPO: ${{ github.repository }} - PR NUMBER: ${{ github.event.pull_request.number }} - - Please review this pull request and provide feedback on: - - Code quality and best practices - - Potential bugs or issues - - Performance considerations - - Security concerns - - Test coverage - - Use the repository's CLAUDE.md for guidance on style and conventions. - Use `gh pr comment` to leave your review as a comment on the PR. - - claude_args: '--allowed-tools "Bash(gh issue view:*),Bash(gh pr comment:*),Bash(gh pr diff:*),Bash(gh pr view:*)"' -``` - ---- - -## ステップ6: GitHub Secrets の設定 - -以下のシークレットを GitHub リポジトリに設定してください: - -### 必須シークレット - -| シークレット名 | 用途 | 取得方法 | -| ------------------------- | --------------------- | ------------------------- | -| `CLAUDE_CODE_OAUTH_TOKEN` | Claude Code Review 用 | Claude Code で OAuth 認証 | - -### オプショナルシークレット (プロジェクトに応じて) - -| シークレット名 | 用途 | 取得方法 | -| ----------------------- | -------------------------- | -------------------------- | -| `CODECOV_TOKEN` | Codecov カバレッジレポート | Codecov アカウントから取得 | -| `SUPABASE_ACCESS_TOKEN` | Supabase CLI 認証 | Supabase ダッシュボード | -| `SUPABASE_PROJECT_REF` | Supabase プロジェクト参照 | Supabase プロジェクト設定 | -| `SLACK_WEBHOOK_URL` | Slack 通知 | Slack アプリ設定 | - -### シークレット設定手順 - -```bash -# GitHub CLI を使用する場合 -gh secret set CLAUDE_CODE_OAUTH_TOKEN - -# または GitHub Web UI から: -# Settings → Secrets and variables → Actions → New repository secret -``` - ---- - -## ステップ7: Husky Git フックの設定 (オプション) - -CI の前段階でローカルチェックを行うため、Husky を設定します: - -```bash -# Husky と関連パッケージのインストール -npm install -D husky lint-staged @commitlint/cli @commitlint/config-conventional - -# package.json に prepare script を追加 -npm pkg set scripts.prepare="husky" - -# Husky 初期化 -npm run prepare - -# Pre-commit フックの追加 -npx husky add .husky/pre-commit "npx lint-staged" - -# Commit-msg フックの追加 -npx husky add .husky/commit-msg "npx commitlint --edit \$1" - -# Pre-push フックの追加 -npx husky add .husky/pre-push "npm run type-check && npm run test" -``` - -### .lintstagedrc.json の作成 - -```json -{ - "**/*.{ts,tsx,js,jsx}": ["eslint --cache --fix", "prettier --write"], - "**/*.{json,md,css,scss}": ["prettier --write"] -} -``` - -### .commitlintrc.json の作成 - -```json -{ - "extends": ["@commitlint/config-conventional"] -} -``` - -詳細は setup-husky コマンドを参照してください。 - ---- - -## ステップ8: 動作確認 - -すべてのワークフローが正しく設定されたことを確認します: - -### ローカルでの確認 - -```bash -# 依存関係のインストール -npm ci - -# 品質チェック -npm run lint -npm run format:check -npm run type-check - -# テスト -npm run test - -# ビルド -npm run build -``` - -### CI での確認 - -1. 新しいブランチを作成 - -```bash -git checkout -b test/ci-setup -``` - -2. ダミーの変更をコミット - -```bash -echo "# CI Test" >> README.md -git add README.md -git commit -m "test: CI setup verification" -``` - -3. プルリクエストを作成 - -```bash -git push -u origin test/ci-setup -gh pr create --fill -``` - -4. GitHub Actions タブでワークフローの実行を確認 - -### 確認項目チェックリスト - -- [ ] CI ワークフローが正常に実行される -- [ ] Quality checks (lint, format, type-check) が成功する -- [ ] テストが実行され、カバレッジが 70% 以上である -- [ ] ビルドが成功する -- [ ] Claude Code Review がPRにコメントを投稿する -- [ ] セキュリティスキャンが実行される (スケジュール実行も確認) - ---- - -## トラブルシューティング - -### npm ci が失敗する - -**原因**: package-lock.json が最新でない、または依存関係の問題 - -**解決策**: - -```bash -rm -rf node_modules package-lock.json -npm install -git add package-lock.json -git commit -m "chore: update package-lock.json" -``` - -### GitHub Packages 認証エラー - -**原因**: GitHub Packages への認証が失敗している - -**解決策**: -ワークフローに以下を追加: - -```yaml -- name: Setup Node.js - uses: actions/setup-node@v4 - with: - node-version: ${{ env.NODE_VERSION }} - cache: 'npm' - registry-url: 'https://npm.pkg.github.com' - env: - NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - -- name: Install dependencies - run: npm ci - env: - NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }} -``` - -### カバレッジ閾値エラー - -**原因**: テストカバレッジが 70% 未満 - -**解決策**: - -1. テストを追加してカバレッジを向上させる -2. 一時的に閾値を下げる (非推奨): - -```yaml -env: - COVERAGE_THRESHOLD: 60 -``` - -### Claude Code Review が動作しない - -**原因**: `CLAUDE_CODE_OAUTH_TOKEN` シークレットが設定されていない - -**解決策**: - -1. Claude Code で OAuth トークンを取得 -2. GitHub リポジトリの Settings → Secrets → Actions で設定 -3. ワークフローを再実行 - -### Supabase 型生成エラー - -**原因**: Supabase プロジェクトへの接続エラー - -**解決策**: - -```yaml -- name: Generate DB types - run: npm run types:gen || npm run types:sync || true - continue-on-error: true -``` - ---- - -## 参考リソース - -### Elu-co-jp リポジトリの実例 - -1. **cyber_ace_1on1** (フル構成): - - `.github/workflows/ci.yml` - 包括的なCI/CDパイプライン - - `.github/workflows/security.yml` - セキュリティスキャン - - `.github/workflows/claude-code-review.yml` - Claude統合 - -2. **management_tools** (シンプル構成): - - `.github/workflows/ci.yml` - 基本的なCI構成 - -3. **job_description** (最小構成): - - `.github/workflows/ci.yml` - 最小限の品質チェック - -### 関連コマンド - -- `setup-husky` - Git フック設定 -- `git-sync` - Git 同期コマンド -- `next-security-check` - Next.js セキュリティチェック - -### 外部リンク - -- [GitHub Actions ドキュメント](https://docs.github.com/actions) -- [Conventional Commits](https://www.conventionalcommits.org/) -- [Semantic Release](https://semantic-release.gitbook.io/) -- [CodeQL ドキュメント](https://codeql.github.com/docs/) - ---- - -## まとめ - -このガイドに従うことで、Elu-co-jp 組織の推奨CI/CD構成を適用できます: - -✅ **品質保証**: 自動化されたコード品質チェック -✅ **テストカバレッジ**: 70%+ の高いカバレッジ要件 -✅ **セキュリティ**: 包括的な脆弱性スキャン -✅ **AI支援**: Claude によるコードレビュー自動化 -✅ **継続的改善**: 定期的なセキュリティスキャンと依存関係更新 - -質問や問題がある場合は、Elu-co-jp の既存リポジトリを参照するか、チームに問い合わせてください。 diff --git a/README.md b/README.md index 12adb395..434cdbc1 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ It includes settings for various tools, such as the shell (Zsh), Git, npm, and V ## Directory Structure - `.claude/`: Claude Code configuration directory containing settings, commands, agents, and hooks. User-specific settings like `settings.local.json` are git-ignored while shared configurations are version-controlled. -- `.codex/`: Codex CLI configuration directory containing automated prompts and configuration for security analysis, refactoring, and development workflow automation. Includes DevContainer recommendations and feature documentation. +- `.codex/`: Contains MCP (Model Context Protocol) server configuration (`config.toml`) for Claude Code integration with external services like AWS, GitHub, Playwright, o3, Supabase, and Vercel. - `.devcontainer/`: Development container configuration providing containerized development environment with consistent tooling across different machines. - `.github/`: GitHub configuration including workflows for CI/CD, security scanning, and release automation. The `templates/` subdirectory contains reusable workflow templates for unified CI with coverage reporting and monorepo releases with change detection. - `brew/`: Contains Brewfiles for different operating systems (Linux, macOS) and dependency configurations, including lock files for reproducible package installations. Supports categorized package management and dependency analysis.