← cd ../skills

$ cat ~/skills/code-review

Analyze a codebase for performance, security, and stability issues. Findings are sorted by priority and presented in a table with proposed fixes.

markdown
---
name: code-review
description: Analyze a codebase for performance, security, and stability issues. Findings are sorted by priority and presented in a table with proposed fixes.
---

# Code Review — Performance, Security & Stability

Scan the project for performance bottlenecks, security vulnerabilities, and stability risks. Produce a single prioritized table of findings with concrete fixes.

## Instructions

1. **Determine scope.** If the user specified files or directories, limit the review to those. Otherwise review the entire `src/` (or project root) directory.

2. **Read the codebase.** Use Glob, Grep, and Read tools to inspect source files. Focus on application code — skip `node_modules`, build output, and lockfiles.

3. **Analyze each category** described below. For every issue found, assign a severity:
   - **Critical** — exploitable vulnerability, data loss, or crash in production
   - **High** — significant performance degradation, auth bypass risk, or unhandled failure mode
   - **Medium** — inefficiency, weak security practice, or fragile pattern that could break under load
   - **Low** — minor improvement, hardening opportunity, or code smell

---

## 1. Performance

### 1.1 Rendering & Hydration
- Components re-rendering unnecessarily (missing memoization, inline objects/functions as props)
- Large component trees without code splitting (`React.lazy`, `next/dynamic`)
- Client Components that could be Server Components
- Blocking data fetches in the render path (waterfalls)

### 1.2 Bundle Size
- Large dependencies imported where only a small part is used (e.g., full `lodash` instead of `lodash/pick`)
- Missing tree-shaking due to barrel re-exports or side-effect imports
- Static assets (images, fonts) not optimized or not using framework primitives (`next/image`, `next/font`)

### 1.3 Data & Network
- Unbounded queries or missing pagination
- N+1 query patterns in loops
- Missing caching headers, revalidation strategy, or stale-while-revalidate
- Fetches that run on every render without deduplication

### 1.4 Memory & CPU
- Event listeners or subscriptions not cleaned up (leaks)
- Expensive computations in hot paths without caching (`useMemo`, memoize, LRU)
- Growing in-memory data structures (unbounded caches, large arrays kept alive)

---

## 2. Security

### 2.1 Injection
- SQL or NoSQL injection (raw string interpolation in queries)
- Command injection (unsanitized input passed to `exec`, `spawn`, shell commands)
- XSS — user input rendered without escaping (`dangerouslySetInnerHTML`, raw HTML templates)
- Path traversal (user-supplied paths passed to filesystem operations without validation)

### 2.2 Authentication & Authorization
- Missing auth checks on API routes, Server Actions, or protected pages
- Secrets or tokens hardcoded in source (not in environment variables)
- Sensitive env vars exposed to the client (`NEXT_PUBLIC_` prefix on secrets)
- JWT/session tokens stored insecurely (localStorage for auth tokens)

### 2.3 Data Exposure
- Sensitive data logged or returned in error responses
- Over-fetched data sent to the client (full DB rows instead of selected fields)
- Missing input validation on API boundaries (no schema validation with zod, etc.)
- CORS misconfiguration (wildcard origins on authenticated endpoints)

### 2.4 Dependencies
- Known vulnerable packages (check for `npm audit` / advisory patterns)
- Outdated dependencies with known CVEs
- Typosquatting risk (unusual package names)

---

## 3. Stability

### 3.1 Error Handling
- Unhandled promise rejections or missing `.catch()` on async operations
- Empty `catch` blocks that silently swallow errors
- Missing error boundaries in React component trees
- API routes that don't return proper error responses (status codes, messages)

### 3.2 Edge Cases & Validation
- Missing null/undefined checks on data from external sources (API responses, DB queries, params)
- Array operations on potentially empty or undefined arrays
- Type assertions (`as`) that bypass runtime safety
- Race conditions in concurrent state updates or parallel async operations

### 3.3 Infrastructure
- Missing health check endpoints
- No graceful shutdown handling (connections, cleanup)
- Hard-coded timeouts or retry counts (should be configurable)
- Missing rate limiting on public endpoints

### 3.4 Resilience
- External service calls without timeouts
- Missing retry logic for transient failures
- No fallback behavior when a dependency is unavailable
- Circular dependencies between modules

---

## Output Format

### Findings Table

Present ALL findings in a single markdown table, sorted by severity (Critical first, then High, Medium, Low):

| # | Severity | Category | Issue | File(s) | Proposed Fix |
|---|----------|----------|-------|---------|--------------|
| 1 | Critical | Security | SQL injection in user query — raw string interpolation in `db.query()` | `src/db/users.ts:42` | Use parameterized queries: `db.query("SELECT * FROM users WHERE id = $1", [id])` |
| 2 | High | Stability | Unhandled promise rejection in payment flow — `.catch()` missing on Stripe call | `src/api/payments.ts:87` | Add try/catch block and return 500 response with error context |
| 3 | High | Performance | Full lodash imported (72kB gzipped) — only `debounce` used | `src/hooks/useSearch.ts:1` | Replace with `import debounce from "lodash/debounce"` or use a 1kB alternative |
| 4 | Medium | Security | API key in source code — Stripe secret key hardcoded | `src/lib/stripe.ts:3` | Move to `process.env.STRIPE_SECRET_KEY` and add to `.env.local` |
| 5 | Low | Performance | Inline object as prop causes child re-render on every pass | `src/components/Dashboard.tsx:55` | Extract to a constant or wrap with `useMemo` |

### Summary

After the table, provide:

```
Category     | Critical | High | Medium | Low | Total
-------------|----------|------|--------|-----|------
Performance  |    0     |  1   |   2    |  3  |   6
Security     |    1     |  0   |   1    |  0  |   2
Stability    |    0     |  1   |   0    |  1  |   2
-------------|----------|------|--------|-----|------
Total        |    1     |  2   |   3    |  4  |  10
```

### Top 3 Priorities

After the summary, highlight the **top 3 issues** to fix immediately, with a brief justification of why they matter most.

### Prompt for Action

Finally, ask the user: "Which of these fixes would you like me to implement? You can select by number, severity level, or category."