Audit a TypeScript API Route for Race Conditions, Auth, and N+1 Bugs

Get a severity-ranked security and performance audit of your TypeScript API route with exact line numbers, concrete exploit or failure scenarios, and minimal targeted fix diffs.

Agent prompt for Claude and Gemini

You get: Findings Summary Table with columns and detailed Findings

Prompt

Prompt
Act as a staff backend security and performance engineer reviewing a production TypeScript API route.

Audit the code I paste right after this prompt for three failure classes: race conditions (check-then-act bugs, missing transactions, lost updates), authorization bypasses (IDOR, missing tenant scoping, role escalation), and N+1 database queries.

Follow these rules:
- Cite the exact line number or symbol name for every finding and skip generic style or formatting feedback.
- Write one concrete exploit or concurrent failure scenario for each finding, showing the exact request sequence or query count.
- Keep every fix diff minimal and targeted to the root cause without refactoring unrelated code.
- Rank findings from Critical to Low and omit any category that has no real issue in the pasted code.
- Include one concrete verification check (a test case or query-count assertion) for every Critical or High finding.

Output format:
1. Findings Summary Table with columns: Severity, Category, Line or Symbol, and Issue.
2. Detailed Findings: numbered sections matching the table, each with Root Cause, Failure or Exploit Scenario, Minimal Fix Diff, and Verification Check.
3. Assumptions and Missing Context: list any unseen middleware, database constraints, or isolation levels that could change the severity.

Example output

Audit findings ranked by severityThree issues found in the credit redeem route
  1. Critical: Cross-tenant auth bypassLine 14orgId from URL used without checking org membership
  2. High: Double-spend race conditionLines 22-31Balance check and deduction run outside a transaction
  3. Medium: N+1 query on receiptsLines 36-41One findReceiptById query per redeemed credit

Example for: a Next.js App Router POST /api/orgs/42/credits/redeem handler for a B2B SaaS billing service.

1. Findings Summary Table
SeverityCategoryLine or SymbolIssue
CriticalAuth BypassLine 14 (POST)Route reads orgId from the URL without verifying the caller belongs to that org
HighRace ConditionLines 22-31 (redeemCredit)Balance check and deduction run outside a database transaction
MediumN+1 QueryLines 36-41 (loadReceipts)Loop executes one findReceiptById query per redeemed credit
2. Detailed Findings
1. Critical — Cross-Tenant IDOR on Credit Redemption
  • Root Cause: Line 14 trusts params.orgId after checking only that session.userId exists, never verifying org membership.
  • Failure or Exploit Scenario: Authenticated user 91 (member of org 10) sends POST /api/orgs/42/credits/redeem and drains org 42's credit balance.
  • Minimal Fix Diff:
  const session = await requireSession(req);
+ await assertOrgMember(session.userId, orgId);
  • Verification Check: Add an integration test where a user from org 10 posts to /api/orgs/42/credits/redeem and assert HTTP 403.
2. High — Double-Spend Race Condition on Credit Balance
  • Root Cause: Line 22 reads org.creditBalance, checks balance >= amount, and line 31 writes the new balance in a separate query.
  • Failure or Exploit Scenario: Two concurrent requests for 100 credits on a 100-credit balance both read 100, pass the check, and redeem 200 credits total.
  • Minimal Fix Diff:
- const org = await orgRepo.findById(orgId);
- if (org.creditBalance < amount) return forbidden();
- await orgRepo.setBalance(orgId, org.creditBalance - amount);
+ const updated = await orgRepo.decrementBalanceIfSufficient(orgId, amount);
+ if (!updated) return conflict();
  • Verification Check: Run two parallel Promise.all requests for the full balance and assert one returns 200 and one returns 409.
3. Medium — N+1 Query Loading Redemption Receipts
  • Root Cause: Lines 36-41 iterate over redemptionIds and await receiptRepo.findById(id) inside a for loop.
  • Failure or Exploit Scenario: Redeeming 50 credits triggers 51 database queries instead of 2, spiking p99 latency under load.
  • Minimal Fix Diff:
- const receipts = [];
- for (const id of redemptionIds) receipts.push(await receiptRepo.findById(id));
+ const receipts = await receiptRepo.findByIds(redemptionIds);
3. Assumptions and Missing Context
  • Assumed orgRepo.decrementBalanceIfSufficient uses an atomic UPDATE orgs SET credit_balance = credit_balance - $1 WHERE id = $2 AND credit_balance >= $1.
  • Assumed no upstream edge middleware already enforces org membership on /api/orgs/42/*.
Written by AI from this prompt. Your results will vary.

Tips and common edits

Why this works

  • Constrains the audit to three high-impact backend failure classes so the model skips low-value linting feedback.
  • Requires concrete exploit or concurrent request sequences, which forces the model to prove a bug is real before reporting it.
  • Pairs every Critical or High finding with a verification test so you can confirm the fix in CI.

Use in Cursor, Claude, or Gemini before merging billing, auth, or high-traffic API routes. Paste the route handler plus any auth middleware or repository helpers it calls so the audit can trace tenant checks and database queries.

Common edits

  • Add your ORM name (Prisma, Drizzle, or TypeORM) to the first line so fix diffs match your exact query API.
  • Include rate-limiting or input-validation checks in the second paragraph when auditing public unauthenticated endpoints.

Reuse it: Use in a workflowAdapt in the builder

Prompt details

By
Prompts-GPT editors
Published
How prompts are written and checked

Did this prompt work?

More in Cursor

Audit API Route Handlers for Auth and Permission Leaks

Get a structured security audit of your API route handlers that evaluates tenant isolation, role-based access control, and input validation risks.

Audit a Pull Request Diff for Breaking API Changes

Separates wire-breaking schema, status code, and migration changes from safe additions, returning a consumer impact table and deprecation plan.

Audit Cursor Rules Files for Conflicts and Context Bloat

Get a line-by-line audit of your .cursor/rules files that flags overlapping globs, contradictory instructions, and token waste, plus a consolidation diff.

AI Coding AgentsClaude Code

Audit AI Code Diffs for Performance Regressions

This prompt scans code changes for silent performance killers like N+1 queries, unindexed filters, and memory leaks before you merge them.

Reconcile OpenAPI Schema Drift with Backend Logic

Get a three-column alignment matrix that identifies discrepancies between your OpenAPI spec, TypeScript client types, and actual backend request validation logic.