Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions .codex/prompts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,33 @@ This directory contains 14 pre-configured commands that provide automated workfl
- Data protection compliance
- Security best practices enforcement

#### `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 対策の棚卸し
- ロール×リソース表とギャップ修正アクションをレポート化

#### `update-deps.md`

**Purpose**: Manages dependency updates with safety checks and compatibility validation
Expand Down
128 changes: 128 additions & 0 deletions .codex/prompts/next-security-check.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
# 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)を実行
72 changes: 72 additions & 0 deletions .codex/prompts/next-security:authz-review.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# `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)
```
71 changes: 71 additions & 0 deletions .codex/prompts/next-security:config-audit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# `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
```
58 changes: 58 additions & 0 deletions .codex/prompts/next-security:deps-scan.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# `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)

```
Loading