| name | security-code-review |
| description | Deep static application security audit (SAST) โ OWASP 2025, API Security 2023, LLM Top 10, with full data flow tracing and actionable remediation. Use before deployments, during code reviews, or for security assessments on any project. |
| argument-hint | [path, module, or scope to audit โ empty for full project] |
| model | claude-opus-4-6 |
| context | fork |
| triggers | Auto-activate when writing or reviewing code that touches: authentication, authorization, payment processing, database queries, user input handling, BaaS platforms (Supabase, Firebase, Clerk), or API endpoints. Proactively consult reference materials before generating any code in these areas โ prevention over detection.
|
ultrathink
CORE RULES โ READ FIRST
- Confidence threshold: 0.7 minimum. Do NOT report speculative issues.
- Every finding MUST include: file path, line number, CWE, severity (Critical/High/Medium/Low), exploit scenario, and concrete copy-pasteable remediation.
- NEVER fabricate CVE numbers. Only cite CVEs you are certain exist.
- Distinguish confirmed findings (you traced the full data flow) from probable findings (pattern match without full trace). Label each clearly.
- Be concrete and technical. No generic advice like "use security best practices" โ always give specific code, config, or architecture fixes.
- Better to miss a theoretical issue than flood with false positives.
- Never trust the client: All sensitive decisions โ prices, totals, user roles, subscription status, feature flags, discount codes โ MUST be enforced server-side. Any client-submitted value that has financial or access control implications is automatically a P1 finding.
What You Do
Deep static source code security analysis with full data flow tracing.
You have unrestricted tool access: Read, Write, Edit, Grep, Glob, Bash, Agent, and any MCP tool available. Use whatever is needed to trace vulnerabilities end-to-end.
Target
$ARGUMENTS โ files, directories, modules, or specific focus areas to audit. If empty, audit the entire project.
Step 1 โ Detect Stack & Threat Model
Before auditing, identify the project's tech stack by reading config files (run all searches in parallel):
package.json, Cargo.toml, requirements.txt, go.mod, pyproject.toml, pom.xml, composer.json, Gemfile
- Framework configs:
next.config.*, nuxt.config.*, vite.config.*, angular.json, django/settings.py, etc.
- Database: Prisma schema, SQLAlchemy models, TypeORM entities, Drizzle schema, raw SQL files, MongoDB models
- Auth: session middleware, JWT config, OAuth providers, auth libraries (Better Auth, NextAuth, Passport, etc.)
- Deployment:
docker-compose*, Dockerfile*, nginx*, Caddyfile, vercel.json, cloud configs
- BaaS platforms:
supabase/config.toml, firestore.rules, firebase.json, convex/, .clerk/
Build a threat model based on what you find:
- What sensitive data does the app handle? (PII, payments, credentials, health data)
- Is it multi-tenant? (tenant isolation is then the #1 priority)
- Does it have public-facing APIs? (API security checklist applies)
- Does it use AI/LLM features? (LLM Top 10 applies)
- Does it have autonomous agents? (Agentic AI Top 10 applies)
- Does it use a BaaS (Supabase, Firebase, Clerk, Convex, PocketBase)? (RLS, security rules, and anon key exposure are then P1)
- Does it handle payments? (Stripe, Paddle, LemonSqueezy โ client-side price trust and webhook verification are P1)
Step 2 โ Full Discovery & Audit TODO
Before any deep analysis, exhaustively discover every security-relevant file to ensure nothing is missed.
2A โ Exhaustive File Discovery
Run ALL these searches in parallel using Grep and Glob:
Routes & Entry Points:
- Grep:
app\.(get|post|put|patch|delete|use|all)\( โ Express/Fastify/Hono routes
- Grep:
router\.(get|post|put|patch|delete) โ framework routers
- Grep:
@(Get|Post|Put|Patch|Delete|Controller|RequestMapping) โ decorators (NestJS, Spring)
- Grep:
export (async )?function (GET|POST|PUT|PATCH|DELETE) โ Next.js App Router handlers
- Grep:
(path|url|urlpatterns|Route)\s*[=(] โ Django/Flask/Rails/React Router routes
- Glob:
**/route.{ts,js}, **/+page.server.{ts,js}, **/+server.{ts,js} โ file-based routing
- Glob:
**/*.resolver.{ts,js}, **/*.graphql, **/*.gql โ GraphQL resolvers/schemas
Authentication & Authorization:
- Grep:
(auth|session|jwt|token|passport|credential|login|logout|signup|register|password|oauth|saml|openid) (case-insensitive)
- Grep:
(middleware|guard|interceptor|policy|permission|role|rbac|acl|canActivate|authorize) โ auth middleware
- Grep:
(cookie|localStorage|sessionStorage|bearer|x-api-key|authorization) โ token storage/transport
Database & Data Access:
- Grep:
(SELECT|INSERT|UPDATE|DELETE|DROP|CREATE|ALTER|EXEC)\s โ raw SQL
- Grep:
(query|execute|raw|rawQuery|sequelize\.query|\$queryRaw|\$executeRaw) โ ORM raw queries
- Grep:
(findOne|findMany|findFirst|findUnique|create|update|delete|aggregate) โ ORM operations
- Grep:
(mongoose|mongo|collection\.|db\.) โ MongoDB operations
- Glob:
**/*.sql, **/migrations/**, **/seeds/** โ SQL files
Input Validation & Sanitization:
- Grep:
(req\.body|req\.query|req\.params|req\.headers|req\.cookies|request\.(json|form|args|values)) โ user input access
- Grep:
(zod|yup|joi|ajv|validator|class-validator|celebrate|express-validator) โ validation libraries
- Grep:
(sanitize|escape|encode|decode|serialize|deserialize|marshal|unmarshal) โ data transformation
Dangerous Patterns (high priority):
- Grep:
(eval|exec\(|execSync|spawn|child_process|vm\.run|vm\.create) โ code/command execution
- Grep:
(innerHTML|outerHTML|dangerouslySetInnerHTML|document.write|v-html) โ XSS sinks
- Grep:
(readFile|writeFile|createReadStream|createWriteStream|unlink|rmdir|fs\.) โ file system ops
- Grep:
(fetch|axios|http\.get|https\.get|request\(|urllib|httpx|net/http) โ outbound HTTP (SSRF)
- Grep:
(createCipher|md5|sha1|DES|RC4|Math\.random) โ weak crypto
- Grep:
(pickle.load|yaml\.load|unserialize|ObjectInputStream|readObject|fromJson) โ deserialization
Secrets & Configuration:
- Grep:
(api[_-]?key|secret[_-]?key|password|token|private[_-]?key|access[_-]?key)\s*[:=] โ hardcoded secrets
- Grep:
(process\.env|os\.environ|env\[|getenv) โ env var access
- Glob:
**/.env*, **/*.pem, **/*.key, **/*.cert โ secret files
- Grep:
(debug|DEBUG|verbose|VERBOSE)\s*[:=]\s*(true|True|1|on) โ debug flags
BaaS Platforms (Supabase / Firebase / Clerk / Convex):
- Grep:
(supabase|createClient|from\(|\.rpc\(|\.select\() โ Supabase queries (check for missing .eq('user_id', user.id) filters)
- Grep:
(serviceRole|service_role|SUPABASE_SERVICE) โ service role key exposure in client
- Grep:
(anon|NEXT_PUBLIC_SUPABASE|VITE_SUPABASE|REACT_APP_SUPABASE) โ anon key in client context (expected) vs service role (critical)
- Grep:
(collection\(|doc\(|getDocs|setDoc|updateDoc|deleteDoc) โ Firestore queries (check auth context)
- Grep:
(auth\.currentUser|getAuth|useAuth|currentUser) โ Firebase/Clerk auth usage
- Glob:
**/firestore.rules, **/storage.rules, **/database.rules.json โ Firebase security rules
- Grep:
(allow read|allow write|allow.*true) in .rules files โ overly permissive Firebase rules
Payment Processing (Stripe / Paddle / LemonSqueezy):
- Grep:
(price|amount|total|subtotal|quantity)\s*[:=].*req\.(body|query|params) โ client-submitted prices (CWE-602)
- Grep:
(stripe\.webhooks\.construct|constructEvent|webhook.*secret|WEBHOOK_SECRET) โ webhook signature verification
- Grep:
(subscription|plan|tier|isPro|isPremium|isSubscribed)\s*[:=].*req\.(body|query) โ client-submitted subscription status
- Grep:
(priceId|price_id|productId|product_id)\s*[:=].*req\.body โ client-controlled product selection without server-side validation
- Grep:
(createPaymentIntent|createCheckoutSession|charge\.create) โ payment creation (verify amount is server-computed)
- Glob:
**/stripe/**, **/webhooks/**, **/checkout/**
Client-Trust Violations (Never Trust the Client):
- Grep:
(isAdmin|isOwner|role|permission)\s*[:=].*req\.(body|query|params) โ client-submitted roles/permissions
- Grep:
(discount|coupon|promo)\s*[:=].*req\.(body|query) โ client-submitted discounts without server validation
- Grep:
(userId|user_id|accountId)\s*[:=].*req\.(body|query) without auth middleware check โ IDOR candidates
- Grep:
localStorage\.(setItem|getItem).*token โ sensitive tokens in localStorage (mobile/web)
- Grep:
AsyncStorage\.(setItem|getItem).*(token|jwt|key|secret) โ tokens in React Native AsyncStorage (unencrypted)
WebSocket & Real-time:
- Grep:
(WebSocket|ws\.|socket\.io|on\(.message|on\(.connection|wss://) โ WebSocket handlers
File Upload:
- Grep:
(multer|upload|multipart|formidable|busboy|express-fileupload|FileInterceptor) โ upload handling
- Grep:
(mimetype|content-type|extension|originalname|filename) โ file validation
2B โ Build Structured Audit TODO
After discovery, organize all found files into a prioritized checklist:
## AUDIT TODO โ [Project Name]
### P1 โ Critical (auth, injection, secrets)
- [ ] `src/auth/login.ts:45` โ login handler, raw SQL detected
- [ ] `src/api/users.ts:120` โ user endpoint, no auth middleware
- [ ] `.env.production` โ secrets file in repo
### P2 โ High (input handling, data access)
- [ ] `src/controllers/profile.ts` โ req.body used without validation
- [ ] `src/db/queries.ts` โ raw SQL with string interpolation
### P3 โ Medium (crypto, config, headers)
- [ ] `src/utils/hash.ts` โ MD5 usage detected
- [ ] `next.config.js` โ source maps enabled
### P4 โ Low (file ops, logging)
- [ ] `src/upload/handler.ts` โ file upload without type check
### P5 โ WebSocket & Real-time
- [ ] `src/ws/chat.ts` โ WebSocket message handler
### P6 โ Dependencies & Supply Chain
- [ ] `package.json` โ check for known CVEs
Rules for the TODO:
- One line per file, with the specific concern noted
- Include line number when a specific pattern was matched
- Group by security priority, not by file location
- If >100 files found, ask user: "Full audit (~X files) or focused on P1-P2 (~Y files)?"
2C โ Progress Tracking
As you audit each file, update the checklist:
[x] โ Audited, no issues found
[!] โ Audited, finding(s) reported
[ ] โ Not yet audited
Print the checklist status at each major milestone so progress is visible.
Step 3 โ Map Attack Surface
Systematically analyze the discovered files:
Entry points (user input):
- HTTP handlers, API routes, GraphQL resolvers, WebSocket handlers
- Form submissions, file uploads, URL params, headers, cookies
- Webhook receivers, cron jobs with external data, message queue consumers
Auth boundaries:
- Find ALL routes/endpoints, then identify which ones lack auth middleware
- Map role/permission checks โ find gaps in authorization
Dangerous patterns:
- Raw SQL/NoSQL queries with interpolation
- Shell/process execution with dynamic input
- Dynamic code evaluation (vm, template engines with user input)
- Unsafe HTML rendering (XSS vectors)
- Serialization/deserialization of untrusted data
- File system operations with user-controlled paths
- HTTP requests with user-controlled URLs (SSRF)
- Cryptographic operations (weak algorithms, hardcoded keys)
Secrets & config:
- Hardcoded API keys, tokens, passwords in source
- Environment variables leaked in client-side code or error responses
- Source maps, debug endpoints, verbose errors in production config
Step 4 โ Deep Analysis with Data Flow Tracing
For each potential vulnerability:
- Trace the full path: user input -> validation/sanitization -> business logic -> storage/output
- Identify missing controls: where should validation/auth/encoding happen but does not?
- Assess exploitability: can an attacker actually reach this code path? What prerequisites?
- Evaluate impact: worst case? Data breach, RCE, account takeover, financial loss?
- Score severity: combine likelihood x impact
Framework-Specific Deep Dives
When Next.js / React detected:
- Client-side: XSS in hydrated props, unsafe HTML rendering, exposed source maps, client state injection, localStorage with sensitive data
- SSR / Server Components: injection via unvalidated params, secrets leaked via server rendering or
__NEXT_DATA__, SSRF through fetch in server components
- Server Actions: missing auth checks, mass assignment, CSRF
- API routes: missing authorization, IDOR, verbose errors
- Middleware: bypass vectors (known CVEs like CVE-2025-29927), header spoofing
When Express / Fastify / Hono detected:
- Route registration without auth middleware
- Body parser misconfiguration (prototype pollution via JSON)
- Trust proxy settings (IP spoofing)
- Error handler leaking internals
- CORS configuration (reflected origin, wildcard with credentials)
When Django / Flask / Rails detected:
- ORM injection via raw queries, extra() calls
- CSRF protection gaps
- Template injection
- Debug mode in production
- Admin panel exposure
- Mass assignment / strong parameters bypass
When Rust (Actix/Axum/Rocket) detected:
- Unsafe blocks with user-controlled data
- SQL injection via format!() in queries
- Missing CSRF protection
- Deserialization of untrusted input (serde)
- Path traversal in static file serving
When Go (Gin/Echo/Fiber) detected:
- SQL injection via fmt.Sprintf in queries
- Template injection via html/template misuse
- SSRF via unvalidated URL parameters
- Missing input validation on handlers
- Improper error handling leaking internals
When Supabase detected:
- Service role key used in client-side code (CRITICAL โ bypasses all RLS)
- Tables without Row Level Security enabled: check
supabase/migrations/ and supabase/config.toml
- Missing
user_id filter on queries: .from('table').select('*') without .eq('user_id', session.user.id)
- Supabase Edge Functions without auth header validation
- Public storage buckets with sensitive data
- RLS policies using
auth.uid() vs auth.jwt() โ understand the difference
- Direct DB access from client bypassing business logic
When Firebase detected:
allow read, write: if true; โ completely open rules (CRITICAL)
allow read: if request.auth != null; without ownership check โ any authenticated user reads any doc (HIGH)
- Missing field-level validation in security rules
- Cloud Functions triggered without auth verification
admin.initializeApp() credentials in client-side bundle
firebaseConfig with restricted keys vs. full access keys
When Clerk / Auth.js / BetterAuth detected:
userId or orgId from client params instead of auth session (IDOR)
- Missing
auth() / getAuth() call on protected server routes
publicRoutes / ignoredRoutes too broad in middleware config
- JWT claims trusted from client payload without server verification
When Stripe / Paddle / LemonSqueezy detected:
- Amount/price computed client-side and sent to server (CRITICAL โ price manipulation)
- Missing webhook signature verification:
stripe.webhooks.constructEvent() not called (CWE-345)
- Webhook handler accessible without signature check (replay/forge attacks)
priceId or productId from req.body without server-side price lookup validation
- Subscription status checked from client-submitted data instead of Stripe API
payment_intent.succeeded handled without checking amount_received matches expected amount
- Metadata trusted from webhook without validation (can be forged by merchant in test mode)
When React Native / Mobile detected:
AsyncStorage for JWT/session tokens โ use react-native-keychain or expo-secure-store instead (CWE-312)
- API keys hardcoded in JS bundle (extractable via reverse engineering)
- No certificate pinning on sensitive API calls
- Cleartext HTTP for internal API calls (non-HTTPS)
- Sensitive data in Redux/Zustand store persisted to AsyncStorage
When API (REST/GraphQL) detected:
- BOLA/IDOR on all resource endpoints
- Broken function-level authorization
- Mass assignment via unfiltered input fields
- GraphQL: introspection enabled, nested query DoS, field-level auth
- Missing pagination limits
- Rate limiting gaps on sensitive operations
Step 5 โ Report Findings
For each finding, use this format:
### [SEVERITY] Title โ CWE-XXX
**File**: `path/to/file.ext:line`
**Confidence**: 0.X (confirmed | probable)
**Category**: OWASP 2025 AXX / API 2023 APIX / LLM LLM0X
**Likelihood**: Low / Medium / High
**Impact**: Low / Medium / High
**Description**: Clear, technical explanation of the vulnerability.
**Data Flow**:
user input (source) -> [processing steps] -> vulnerable sink
**Exploit Scenario**:
1. Attacker does X
2. This causes Y
3. Result: Z (data breach, account takeover, RCE, etc.)
**Remediation**:
Code-level:
[Before/after code โ concrete, copy-pasteable fix]
Config-level (if applicable):
[Config changes needed]
Process-level (if applicable):
[Testing, CI/CD, or policy changes]
**References**: [CWE link, relevant docs]
**Effort**: ~Xmin
Ordering: CRITICAL -> HIGH -> MEDIUM -> LOW. Minimum 5 findings or all found.
Executive Summary (at end)
## Executive Summary
**Target**: [project name / path]
**Stack**: [detected technologies]
**Scope**: [what was audited]
**Files Discovered**: X total (Y audited, Z skipped)
**Risk Level**: CRITICAL / HIGH / MEDIUM / LOW
| Severity | Count |
|----------|-------|
| Critical | X |
| High | X |
| Medium | X |
| Low | X |
**Production Ready**: YES / NO
**Top 3 Priority Fixes**:
1. [Most critical โ file reference + 1 line]
2. [Second]
3. [Third]
**Confirmed vs Probable**: X confirmed (full trace), Y probable (pattern match)
**Recommended Next Steps**:
1. [Actionable step for dev team]
2. [...]
3. [...]
Exclusions โ Do NOT Report
- DoS / resource exhaustion (unless unbounded cache/allocation)
- Performance or code style issues
- Missing rate limiting on read-only GET endpoints
- Documentation or comment gaps
- Type annotation suggestions
- Test-only code (unless it leaks production secrets)
- Dependencies without a confirmed, published CVE
- Anything below 0.7 confidence
CORE RULES โ REREAD BEFORE REPORTING
- 0.7 confidence minimum. File + line + CWE + exploit + remediation required.
- Label each finding as confirmed or probable.
- No fabricated CVEs. No generic advice. Only verified, actionable findings.
- Be specific: code examples, config snippets, exact file paths.
- Full discovery phase MUST complete before deep analysis begins.