agentleFS
ahtishamshahzadahtishamshahzad/backend-security-audit-skill/SKILL.md

backend-security-audit

Skill0 starsChanged 5 months agoMITView on GitHub

Audit, fix, and verify the security of a backend/API before launch. Use when a web or mobile app's backend needs a security review — leaked secrets, PII in logs, broken authentication, IDOR/authorization gaps, injection, payment-logic flaws, weak production hardening, or an attacker's-perspective pass. Built for AI-built ("vibe-coded") apps on Node/Express, NestJS, Fastify, Next.js API routes/server actions, tRPC, and Supabase/Firebase backends.

  • Reads credentials

1 other project uses a version of this.

Adopted by

Most recently taken up by

  • Other versions1 project uses a version of this.

    Word for word · 0

    None found.

    Edited · 0

    None found.

    Wrote their own version · 1

    1. lassejlv/skills★ 61same name

    How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.

  • In this repository2 other files it gives its agents.

The file

Show its rules and text

We split this skill into the rules it gives an agent

27 rules. About 0 are common, 24 are distinctive, and 3 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈24

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 3

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Use this skill when an app has, or is about to ship, any of:

    line 23
  2. Distinctive:

    Before starting, gather any available details (don't block on them):

    line 50
  3. Distinctive:

    If enough information is available, proceed with best-practice assumptions.

    line 61
  4. Very specific:

    Create/repair .gitignore and a placeholder .env.example

    line 94
  5. Distinctive:

    Every point where user data is collected (emails, phones, names, addresses, DOB, payment info, IP, device info) and where it goes afterward

    line 102
  6. Distinctive:

    Add a data-deletion/anonymization path if none exists

    line 111
  7. Distinctive:

    Every protected route/endpoint actually enforces auth (no endpoint silently works without a token)

    line 131
  8. Distinctive:

    No default/hardcoded admin accounts with known credentials

    line 135
  9. Distinctive:

    Add/repair auth middleware.

    line 140
  10. Distinctive:

    Add rate limiting to auth endpoints

    line 141
  11. Distinctive:

    Every endpoint that takes a user ID, order ID, document ID, etc.

    line 147
  12. Distinctive:

    Add ownership/tenant checks on data access

    line 154
  13. Distinctive:

    Add input validation and output escaping/sanitization

    line 170
  14. Distinctive:

    Check (when the app takes money):

    line 175
  15. Distinctive:

    Verify webhook signatures.

    line 186
  16. Distinctive:

    No default DB credentials.

    line 209
  17. Distinctive:

    Remove debug/test endpoints and logs.

    line 214
  18. Distinctive:

    Run last, after the above are addressed.

    line 218
  19. Distinctive:

    Use whatever the project already has, and offer to add tools only when useful.

    line 232
  20. Distinctive:

    Do not remove or weaken existing security controls to "make it work."

    line 262
  21. Distinctive:

    Do not change auth, payment, or data behavior in ways that alter product behavior without calling it out.

    line 263
  22. Distinctive:

    Do not exfiltrate data, hit third-party/production systems, or run destructive commands during the audit.

    line 264
  23. Distinctive:

    Do not add heavy security libraries without a clear reason and a note on the trade-off.

    line 266
  24. Very specific:

    Read config, env handling, routes/controllers/middleware, auth, DB/query layer, webhooks, logging, and (Supabase/Firebase) rules.

    line 277
  25. Distinctive:

    After the audit, respond with:

    line 305
  26. Distinctive:

    Before the final response, confirm:

    line 345
  27. Very specific:

    Every protected route's auth enforcement reviewed.

    line 352

≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Backend Security Audit Skill

Scope: This skill audits the backend / server / API of a web or mobile app — the code that handles secrets, databases, authentication, authorization, payments, and user data. It targets the mistakes that cause most real-world breaches in AI-built apps. It is an audit-fix-verify skill, not a rewrite tool, and not a replacement for professional penetration testing.

Skill Name

Backend Security Audit Skill

Skill Purpose

This skill helps an AI coding agent audit, fix, and verify the security of an application's backend before (and after) launch.

Use this skill when an app has, or is about to ship, any of:

  • Hardcoded secrets, API keys, or database credentials in source
  • Personal/PII data flowing into logs, third-party services, or the client
  • Weak or missing authentication (JWT, sessions, password reset)
  • Broken authorization / IDOR (users reaching other users' data)
  • Injection risk (SQL, NoSQL, command, XSS)
  • Payment or business-logic flaws (client-trusted prices, unverified webhooks, abuse)
  • Missing production hardening (debug endpoints, verbose errors, no rate limits, bad CORS, missing security headers)
  • A backend built quickly by an AI builder (Lovable, Bolt, Replit, Cursor, v0, Claude Code) and never security-reviewed

The goal is not to bolt on every security control blindly. The goal is to find the real, exploitable weaknesses, fix them safely without breaking the app, and verify each fix — reporting confirmed issues separately from potential ones.

Honest note (state this to the user in the final report): These checks catch the mistakes behind most real-world breaches in vibe-coded apps, but no AI audit replaces professional security testing. If the app handles real money or sensitive personal data at scale, run these checks and get a human security review before launch.

Supported Backends

  • Node.js: Express, NestJS, Fastify, Koa, Hapi
  • Next.js API routes, Route Handlers, and Server Actions
  • tRPC / GraphQL (Apollo, Yoga) resolvers
  • Serverless functions (Vercel, Netlify, AWS Lambda, Cloudflare Workers)
  • Backend-as-a-service: Supabase, Firebase, Appwrite (config + rules + server code)
  • ORMs / query layers: Prisma, Drizzle, Mongoose, Knex, raw SQL
  • TypeScript or JavaScript. (Python/FastAPI/Django share most of the same checks — apply the concepts, adjust the syntax.)

Input Requirements

Before starting, gather any available details (don't block on them):

  • What the app does, and whether it handles money or sensitive PII
  • Framework(s) and language
  • Database and query layer (Postgres/MySQL/Mongo; Prisma/Drizzle/raw)
  • Auth approach (custom JWT, sessions, Supabase Auth, Firebase Auth, Clerk, Auth0, NextAuth)
  • Payment provider, if any (Stripe, Razorpay, Paddle, LemonSqueezy)
  • Hosting/deploy target and how env vars are set
  • Whether this is pre-launch, live, or post-incident
  • Which area to prioritize, if the user has a specific concern

If enough information is available, proceed with best-practice assumptions. Ask only blocking questions.

Files & Locations To Inspect

The agent should inspect these when present:

  • package.json, lockfile, tsconfig.json
  • .env, .env.*, .env.example, .gitignore
  • next.config.js / next.config.ts, vercel.json, netlify.toml
  • src/**, app/**, pages/api/**, server/**, api/**, functions/**, routes/**, controllers/**, middleware/**, services/**, lib/**
  • Auth code: auth/**, middleware.ts, guards, session/JWT helpers
  • Database: schema/migrations, prisma/schema.prisma, model files, raw query call sites
  • Supabase: supabase/**, RLS policies, migrations; Firebase: firestore.rules, storage.rules, functions/**
  • Webhook handlers (payments, auth providers)
  • Logging/error-handling setup
  • CI config and any Dockerfile / deploy scripts (for exposed secrets / debug flags)

Security Areas To Audit

1. Secrets & Credentials

Check:

  • API keys, passwords, tokens, database URLs, or private keys as string literals anywhere in source — including config files, comments, tests, and seed data
  • Secrets committed to git (and still present in git history even if later removed)
  • Client-exposed secrets: any NEXT_PUBLIC_ / REACT_APP_ / EXPO_PUBLIC_ / VITE_ prefixed variable holds only public-safe values
  • Supabase: anon key used client-side only with Row Level Security enabled on every table; service-role key never client-side
  • Stripe: only the publishable key client-side; the secret key server-side only
  • Missing .env in .gitignore; missing .env.example with placeholder (not real) values

Recommend / fix:

  • Move every secret to environment variables (server-side only)
  • Create/repair .gitignore and a placeholder .env.example
  • Flag any secret found in git history for immediate rotation (a README note + explicit warning)
  • Never print the secret's value in the report — report its location and what it was, redacted

2. Personal Data (PII) Flow

Check:

  • Every point where user data is collected (emails, phones, names, addresses, DOB, payment info, IP, device info) and where it goes afterward
  • Logs, console.log, loggers, print statements, and error handlers that output PII, tokens, or connection strings
  • Third-party integrations/SDKs (analytics, error tracking, email, payment, AI APIs) — exactly what user fields are sent, and whether extra fields can be stripped
  • Whether users can delete or anonymize their data

Recommend / fix:

  • Scrub PII/secrets from logs (redact or remove)
  • Send third parties only the minimum fields they need
  • Add a data-deletion/anonymization path if none exists

3. Passwords & Sessions

Check:

  • Passwords hashed with bcrypt, argon2, or scrypt — never MD5/SHA-1/SHA-256-alone, never plaintext
  • Password values never logged, returned in responses, or stored outside the hash
  • Session tokens in httpOnly, Secure, SameSite cookies — not in localStorage (XSS-readable)
  • Sensitive data not sitting in localStorage

Recommend / fix:

  • Migrate weak hashing to argon2/bcrypt (with a re-hash-on-login path)
  • Move tokens to secure cookies; set proper cookie flags

4. Authentication

Check:

  • Every protected route/endpoint actually enforces auth (no endpoint silently works without a token)
  • JWT: strong signing secret from env, verified signature, sane expiry, algorithm pinned (no alg: none), token invalidation/blacklist on logout where needed
  • Expired/malformed tokens rejected
  • Password reset: tokens random, single-use, short-lived (≤15 min), tied to one user
  • No default/hardcoded admin accounts with known credentials
  • Rate limiting on login, signup, password reset, OTP (e.g. ≥ 5/min/IP login, ≤ 3/hr reset)

Recommend / fix:

  • Add/repair auth middleware; pin JWT algorithm; enforce expiry and reset-token rules
  • Add rate limiting to auth endpoints

5. Authorization & IDOR

Check:

  • Every endpoint that takes a user ID, order ID, document ID, etc. verifies ownership server-side before returning or mutating data (no Insecure Direct Object Reference)
  • Role checks (user/admin/moderator) happen server-side, not by hiding UI
  • A regular user can't reach admin endpoints by guessing URLs or editing their role in the JWT/session
  • Multi-tenant data is scoped by tenant on every query

Recommend / fix:

  • Add ownership/tenant checks on data access
  • Enforce roles in middleware/guards, server-side

6. Input Handling & Injection

Check:

  • SQL/NoSQL built with parameterized queries / ORM bindings, never string concatenation of user input
  • XSS: user input rendered into HTML/emails is escaped or sanitized; no dangerouslySetInnerHTML with unsanitized input
  • Command injection: no user input passed to shell/exec
  • File uploads: type validated server-side, size limited, stored without executable permissions, not served from a domain that can execute them
  • Request bodies validated (zod/joi/class-validator) — types, ranges, allowlists

Recommend / fix:

  • Convert raw SQL to parameterized/ORM queries
  • Add input validation and output escaping/sanitization
  • Harden file-upload handling

7. Payments & Business Logic

Check (when the app takes money):

  • Server independently computes totals, taxes, discounts — never trusts client-sent price/quantity/discount
  • Payment webhooks verify the provider's signature (Stripe, Razorpay, etc.)
  • Access to paid features gated on server-verified payment status
  • Logic abuse: negative amounts, stacking discounts infinitely, restarting free trials, self-referral loops, coupon reuse
  • Idempotency on payment/order creation to prevent double-charge/double-grant

Recommend / fix:

  • Move all price/total math server-side
  • Verify webhook signatures; verify payment status server-side
  • Close the specific logic-abuse holes found

8. API, Transport & Errors

Check:

  • CORS not set to allow all origins (*) unless the API is genuinely public; restrict to your frontend origin(s)
  • Security headers on responses: X-Content-Type-Options: nosniff, X-Frame-Options: DENY, Strict-Transport-Security, a sensible Content-Security-Policy (use helmet on Express)
  • Error responses to clients never include stack traces, DB errors, file paths, or internal info — generic message + correlation ID; details to server logs only
  • TLS/HTTPS enforced; DB connections use TLS in production

Recommend / fix:

  • Restrict CORS; add helmet/security headers; sanitize error responses; enforce TLS

9. Production Hardening

Check:

  • Debug/test artifacts removed: console.log debugging, commented-out security code, TODO/FIXME on incomplete security, test-only endpoints (/test, /debug, /admin-backdoor, /seed-data), hardcoded test credentials
  • Debug mode defaults off
  • Env-var validation: app fails fast (won't start) if a critical variable (DB URL, API key, auth secret) is missing
  • No default DB credentials; no DB port open to the internet without auth
  • Dependency vulnerabilities reviewed (npm audit / advisories)

Recommend / fix:

  • Remove debug/test endpoints and logs; add startup env validation; address critical dependency advisories

10. Attacker's Perspective Pass

Run last, after the above are addressed. Think like an attacker and probe:

  • ID manipulation: change an ID in the URL/body — can you read/modify another user's data?
  • Login bypass: any endpoint that works without a token? Expired/malformed tokens accepted? Default admin?
  • Privilege escalation: can a normal user hit admin endpoints or elevate their role via JWT/session tampering?
  • Feature abuse: unlimited signups, spam messaging, storage-filling uploads, API flooding, infinite promo/referral use
  • Content injection: JavaScript/SQL in every text field, search box, filter, username, bio, comment, filename
  • Internal exposure: reachable DB admin panel, .env via direct URL, .git/ directory, Swagger/OpenAPI docs meant to be internal, health checks leaking system info, env leaked through error messages
  • Business-logic manipulation: negative payments, infinite discount stacking, trial restart, self-referral

For each finding, describe what an attacker would do, the potential damage, and the exact fix. Prioritize data theft and unauthorized access first; abuse and logic flaws second.

Commands / Tools To Run When Possible

Use whatever the project already has, and offer to add tools only when useful. These open-source tools inspire and back up the checks:

# Secret scanning — including git history (github.com/gitleaks/gitleaks)
gitleaks detect --source . --redact -v
gitleaks detect --source . --log-opts="--all" --redact   # scan full history

# Dependency vulnerabilities
npm audit --production        # or: pnpm audit / yarn audit

# Static analysis (if available)
npx semgrep --config auto .    # semgrep.dev

# Data-flow / PII & security patterns (github.com/bearer/bearer)
bearer scan .

# Project's own checks
npm run lint
npm run typecheck
npm test

Prior art / credit: the areas above align with widely used open-source security tooling — Gitleaks (secret scanning), Bearer (PII/data-flow), Trail of Bits security review practices, and OWASP guidance. Cite the relevant tool when a check maps to it; recommend running the tool to confirm.

Rules and Constraints

  • Find the real, exploitable issue first — don't blindly bolt on controls that break the app.
  • Never print a discovered secret's value in output; report location + type, redacted. Recommend rotation for anything exposed or in git history.
  • Separate Confirmed vulnerabilities from Potential/Needs-verification ones. Don't overstate.
  • Never claim the app is "secure." Report what was checked, what was fixed, and what still needs human review.
  • Do not remove or weaken existing security controls to "make it work."
  • Do not change auth, payment, or data behavior in ways that alter product behavior without calling it out.
  • Do not exfiltrate data, hit third-party/production systems, or run destructive commands during the audit.
  • Make surgical, behavior-preserving fixes that match the project's conventions.
  • Do not add heavy security libraries without a clear reason and a note on the trade-off.
  • For apps handling real money or sensitive PII at scale, explicitly recommend a professional human security review.

Execution Workflow

Step 1: Understand the App & Risk

Identify what the app does, whether it handles money or sensitive PII, the framework, database, auth approach, and payment provider. Set the priority order accordingly.

Step 2: Inspect the Backend

Read config, env handling, routes/controllers/middleware, auth, DB/query layer, webhooks, logging, and (Supabase/Firebase) rules.

Step 3: Run the Checks In Order

Secrets → PII flow → passwords/sessions → authentication → authorization/IDOR → input/injection → payments/logic → API/transport/errors → production hardening → attacker's-perspective pass. Use available tools (gitleaks, npm audit, semgrep, bearer) to back up findings.

Step 4: Create a Fix Plan (before editing)

  • Confirmed issues (with severity) and potential ones
  • Files likely affected
  • Fix strategy per issue
  • Verification strategy
  • Risk / behavior impact

Step 5: Apply Safe Fixes

Focused, behavior-preserving changes only (move secrets to env, add ownership checks, parameterize queries, verify webhook signatures, scrub logs, add rate limits/headers/CORS, remove debug endpoints, add env validation).

Step 6: Verify

Re-scan with the tools; re-read the fixed code paths; run typecheck/lint/tests. Mark anything unrun as "unverified until run" with the exact command.

Step 7: Final Report

Deliver a client-ready report (format below).

Output Format

After the audit, respond with:

Summary

What was reviewed and the overall risk posture (one honest paragraph).

Issues Found

Each issue with severity and status:

  • Severity: Critical / High / Medium / Low
  • Status: Confirmed or Potential (needs verification)
  • One line: what it is, where (file:line), and the impact.

Fixes Applied

What was changed and why each change closes the issue (behavior preserved).

Files Changed

List changed files and the reason for each.

Verification

Tools/commands run (gitleaks, npm audit, semgrep, bearer, typecheck, lint, tests) and results. Mark anything unrun as "unverified until run."

Secrets To Rotate

Any secret that was exposed or is in git history — rotate immediately. (Values redacted.)

Remaining Risks

What still needs attention, real-environment testing, or a human security review.

Next Steps

Prioritized recommendations, and — for money/PII-at-scale apps — an explicit call for professional review.

Validation Checklist

Before the final response, confirm:

  • App purpose and risk level (money / sensitive PII?) established
  • Secrets scanned in code and git history; none printed in the report
  • Client-exposed env prefixes checked (NEXT_PUBLIC_ etc.); Supabase RLS / service-role usage checked
  • PII flow mapped; logs and third-party payloads reviewed
  • Password hashing and token storage reviewed
  • Every protected route's auth enforcement reviewed; JWT/reset/rate-limit rules checked
  • Ownership/IDOR and server-side role checks reviewed
  • Injection (SQL/NoSQL/XSS/command/upload) reviewed; input validation checked
  • Payment price integrity, webhook signatures, and logic abuse reviewed (if applicable)
  • CORS, security headers, error responses, TLS reviewed
  • Debug/test endpoints, env-var fail-fast, dependency advisories reviewed
  • Attacker's-perspective pass completed
  • Confirmed vs potential issues separated; severities assigned
  • Tools run where possible; unrun checks flagged
  • Report is client-ready and includes the human-review recommendation where warranted

Example Prompts

Example 1 — Secrets

Use the Backend Security Audit Skill to do a secret-leak pass across the whole codebase. Find every hardcoded key/password/token/DB URL, move them to env vars, fix .gitignore/.env.example, check NEXT_PUBLIC_ exposure and Supabase key usage, and flag anything in git history for rotation. Report locations (redacted) and what you changed.

Example 2 — Auth & IDOR

Use the Backend Security Audit Skill to audit authentication and authorization. Check every protected route, JWT handling, password reset, login rate limiting, and — critically — IDOR: can a user read another user's data by changing an ID? Fix what's safe and report each issue with severity.

Example 3 — Pre-deploy

Use the Backend Security Audit Skill for a pre-deploy production audit: env-var validation, debug/test endpoint removal, error handling, security headers, CORS, rate limiting, and DB security. List every check, pass/fail, and what you fixed.

Example 4 — Payments & attacker pass

Use the Backend Security Audit Skill. This app has Stripe payments and custom auth. Do a deep audit of the payment logic (server-side totals, webhook signatures, logic abuse) and then an attacker's-perspective pass. For each finding, explain the exploit, the damage, and the exact fix.

Supporting Files In This Skill

  • AGENTS.md — behavior contract for AI agents when this skill is active.
  • checklists/security-checklist.md — master audit checklist (all 10 areas).
  • checklists/secrets-checklist.md — secrets & credentials deep pass.
  • checklists/auth-idor-checklist.md — authentication & authorization/IDOR.
  • checklists/payments-checklist.md — payment & business-logic integrity.
  • checklists/pre-deploy-checklist.md — production hardening & attacker pass.
  • examples/ — audit request, worked secret-leak and IDOR/auth audits, and a client-ready report.
  • prompts/ — ready-to-paste starters for Claude Code, Cursor, Windsurf, and Antigravity.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.