# Vercel + Supabase Pre-Launch Security Check (free AI agent kit from Bot Pantry)

Canonical page: https://botpantry.com/kits/prelaunch-security
Free download (.zip, no sign-up): https://botpantry.com/api/download?kit=prelaunch-security
For: Vibe coders shipping on Vercel + Supabase
Setup time: 45-90 min (verified by Kit Inspector)
Works with: Cursor; Claude Code; v0; Lovable; Bolt; Replit; Supabase; Vercel; Node.js 18+; ChatGPT, Claude, or Grok
Published: 2026-11-16 · Updated: 2026-11-28

A one-hour security pass before you share your app's link: tested scripts find leaked keys, missing Supabase Row Level Security, unprotected API routes and server actions, plus the dashboard settings that stop a runaway bill.

## What's inside
- A secret scanner that checks your repo, git history, the next.config env block, your built JavaScript and your live site
- A read-only Supabase SQL audit for RLS, risky policies, definer views/functions and who can read storage files
- A route scanner that flags API routes and server actions with no real auth check, public routes that call a paid API with no verified rate limit, and CORS * in next.config / vercel.json
- Drop-in Cursor and Claude Code rules and commands that run the check read-only and ask before anything destructive
- Runaway-bill checks for Vercel, Supabase and AI providers, with exact dashboard paths

---

The kit's README (included in the .zip) follows.

# Vercel + Supabase Pre-Launch Security Check — Bot Pantry Kit

A first security pass (about 45–90 minutes for a beginner, including setup; fixing what it finds comes after) for apps built with Cursor, Claude Code, v0, Lovable, Bolt or Replit on **Next.js + Supabase + Vercel**, before you share the link. It finds the four mistakes that actually hurt vibe-coded apps:

1. **Leaked keys** — secrets with a `NEXT_PUBLIC_` prefix, the Supabase `service_role`/secret key in browser JavaScript, a committed `.env`, keys still sitting in git history.
2. **Missing Row Level Security** — tables anyone can read or edit with your public key, `using (true)` policies, storage buckets open to the world.
3. **Unprotected API routes and server actions** — no login check, no ownership check, no rate limit on routes that call paid AI APIs (even when the call hides in a helper), and `Access-Control-Allow-Origin: *` set in your config files.
4. **Runaway bills** — no Vercel spend limit, no Supabase spend cap, AI API keys with no budget.

You get three real scripts that do the checking (tested, see below), drop-in rules for Cursor and Claude Code so your AI runs the checks *and* stops creating these problems (and asks before anything destructive), prompts for every other tool, a checklist, and guardrails.

> **Facts checked against official docs on 2026-10-21.** Two recent changes matter: Supabase is replacing `anon`/`service_role` keys with `sb_publishable_…`/`sb_secret_…` keys (legacy keys deprecated by end of 2026), and from **2026-10-30** new Supabase tables are not exposed to the API until you `grant` access. Vercel replaced the "Sensitive" toggle with **Config / Secret** variable types (Aug 2026). Next.js shipped critical fixes on 2026-10-14 (**16.4.1 / 15.5.28**). Vercel now calls its emergency switch **Attack Mode**.

## Contents
| File | What it is |
|---|---|
| `scripts/scan-secrets.mjs` | Finds secrets in your repo, `.env` files in git, git history, the `next.config` `env` block, your build output (`.next/static`), and optionally your live site's JavaScript. Node 18+, no installs. |
| `scripts/scan-routes.mjs` | Lists route handlers and server actions with no real auth check, public routes that call a paid API with no rate limit it can verify (HIGH), `getSession()` used for auth on the server, outdated Next.js (installed version), risky `next.config` image settings, and CORS `*` in `next.config` / `vercel.json` / `proxy.ts` headers. |
| `scripts/rls-audit.sql` | Read-only SQL for the Supabase SQL Editor: tables without RLS in **every schema your API exposes**, `true` policies, "any logged-in user can edit" policies, `user_metadata` in policies, security-definer views/functions, public buckets, and who can **read and write** storage files. |
| `drop-in/cursor/` | Cursor rules (always-on guardrails + an on-demand "run the security check" rule) and the `/security-check` command. Goes in your project's `.cursor/` folder. |
| `drop-in/claude/commands/*.md` | Claude Code slash commands: `/security-check`, `/check-keys`, `/check-rls`, `/check-routes`, `/check-bills`. Go in `.claude/commands/`. |
| `drop-in/claude/settings.json` | Optional Claude Code permissions: blocks reading `.env` and common destructive commands (`git push`, `rm -rf`, `supabase db push`, deploys), asks before builds. |
| `drop-in/CLAUDE.md` | Block to paste into your project's `CLAUDE.md` (Claude Code). |
| `drop-in/cursorignore` | Keeps `.env*` out of Cursor's AI features. Goes in your project as `.cursorignore`. |
| `prompts/00-04*.md` | The same checks as copy-paste prompts for v0, Lovable, Bolt, Replit, ChatGPT, Claude, Grok. |
| `checklist.md` | The whole pass on one page. Tick it off before launch. |
| `guardrails.md` | Rules for you and your AI: read-only first, ask before anything destructive, no auto-changes to production, how to rotate a leaked key. |
| `setup/tools.md` | Where each file goes in each tool, and which mode to use in Lovable, Bolt and Replit. |
| `examples.md` | Real scanner output and before/after fixes. |
| `troubleshooting.md` | False positives, "permission denied", broken app after enabling RLS, Windows, exit codes, and more. |

The drop-in folders ship as `cursor/` and `claude/` (no dot) so they don't vanish when you unzip; the setup commands copy them to `.cursor/` and `.claude/`.

## What you need
> - **Node.js 18 or newer.** Check with `node -v` in a terminal. No other installs.
> - **git** (for the history checks; `git --version`). Without it the scanner still runs and skips history.
> - **A terminal opened in the unzipped kit folder** (Mac: Terminal; Windows: PowerShell, Git Bash or WSL; or the terminal inside Cursor/VS Code). Your app's folder next to it, called `my-app` below.
> - For the build-output check: your app must build locally. If `next build` fails for missing env vars, copy them into `.env.local` (never commit it), or skip the build and use `--url` on your deployed site.

## Setup (10–20 minutes the first time)
From the unzipped kit folder, with your app at `../my-app`.

**Mac / Linux / Git Bash / WSL:**
```bash
mkdir -p ../my-app/scripts/security ../my-app/.cursor ../my-app/.claude/commands
cp scripts/* checklist.md guardrails.md ../my-app/scripts/security/        # scripts + the checklist/guardrails the AI refers to
cp -R drop-in/cursor/. ../my-app/.cursor/                                  # Cursor rules + /security-check
cp drop-in/claude/commands/*.md ../my-app/.claude/commands/                # Claude Code commands
[ -e ../my-app/.claude/settings.json ] || cp drop-in/claude/settings.json ../my-app/.claude/   # only if you don't have one
grep -qs 'Bot Pantry pre-launch kit' ../my-app/.cursorignore || cat drop-in/cursorignore >> ../my-app/.cursorignore   # adds once; creates it if missing
grep -qs 'Bot Pantry pre-launch kit' ../my-app/CLAUDE.md || cat drop-in/CLAUDE.md >> ../my-app/CLAUDE.md                # adds once; creates it if missing
```
**Windows PowerShell:**
```powershell
New-Item -ItemType Directory -Force ..\my-app\scripts\security, ..\my-app\.cursor, ..\my-app\.claude\commands | Out-Null
Copy-Item scripts\*, checklist.md, guardrails.md ..\my-app\scripts\security\
Copy-Item -Recurse -Force drop-in\cursor\* ..\my-app\.cursor\
Copy-Item drop-in\claude\commands\*.md ..\my-app\.claude\commands\
if (-not (Test-Path ..\my-app\.claude\settings.json)) { Copy-Item drop-in\claude\settings.json ..\my-app\.claude\ }
if (-not ((Test-Path ..\my-app\.cursorignore) -and (Select-String -Quiet -SimpleMatch 'Bot Pantry pre-launch kit' ..\my-app\.cursorignore))) { Get-Content -Encoding utf8 drop-in\cursorignore | Add-Content -Encoding utf8 ..\my-app\.cursorignore }
if (-not ((Test-Path ..\my-app\CLAUDE.md) -and (Select-String -Quiet -SimpleMatch 'Bot Pantry pre-launch kit' ..\my-app\CLAUDE.md))) { Get-Content -Encoding utf8 drop-in\CLAUDE.md | Add-Content -Encoding utf8 ..\my-app\CLAUDE.md }
```
Safe to re-run: the last two lines add the kit's text to `CLAUDE.md` and `.cursorignore` only once (they look for the line "Bot Pantry pre-launch kit" first), and `-Encoding utf8` keeps characters like … intact in Windows PowerShell 5.1. If you edited that text and want it re-added, delete the old block first.

Already have a `.claude/settings.json`? Merge the `deny` and `ask` lists from `drop-in/claude/settings.json` into it by hand. Commit these files on a branch (after checking `.env*` is in `.gitignore`). They contain no secrets.

**Using v0, Lovable, Bolt or Replit?** You may not have a terminal. Switch to a mode that can't change your app (Lovable: Chat mode; Bolt and Replit: Plan mode), paste `prompts/00-full-audit.md` into the chat, paste `scripts/rls-audit.sql` into the Supabase SQL Editor, and work through `checklist.md` by hand. See `setup/tools.md`.

## Run it
**1. Build (carefully).** Open your app's `package.json` and look at the `build`, `prebuild` and `postbuild` scripts. If they only run `next build`, run `npm run build`. If they also run migrations or seeds (`prisma migrate deploy`, `drizzle-kit push`, `supabase db push`…), run `npx next build` instead so nothing touches your database. Build fails for missing env vars? See "What you need", or skip to `--url`.

**2. Scan.**
```bash
cd my-app
node scripts/security/scan-secrets.mjs .        # keys + .env + git history + next.config env + build output
node scripts/security/scan-secrets.mjs . --url https://your-app.vercel.app   # + your live site's JS
node scripts/security/scan-routes.mjs .         # routes + server actions
```
(Same commands in PowerShell, with `\` instead of `/` if you like.)

**3. Database.** Open Supabase Dashboard → **SQL Editor**, paste `scripts/security/rls-audit.sql`, click **Run**. Zero rows = none of these checks matched (not proof that every policy is right). Then open **Advisors → Security Advisor** and fix every ERROR. With the Supabase CLI instead: `supabase login`, `supabase link --project-ref <your-project-ref>`, then `supabase db advisors --linked --type security` (add `--level info` to see INFO items, `--fail-on error` for CI). Plain `supabase db advisors` without `--linked` checks your *local* database, not the real one.

**What the output means.** Each finding has a severity, a `where:` line (a file, `git history: …`, or a URL; the same leaked value in several files is listed once with "+N more") and a one-line fix. Secrets are masked (first 10 characters only). Both scripts finish with **exit code 1 when there is at least one HIGH finding** and 0 otherwise. That number is how CI knows to stop; MEDIUM, LOW and INFO never change it. Exit code 0 (or an empty list) only means no pattern matched: it is **not** a sign-off that the app is protected.

For routes and server actions the rule is: **clean = every route that writes or spends money reaches a gate the scanner fully verified; anything else is flagged for you to confirm.** A clearly missing or broken check is **HIGH**. Gate-like code the scanner can't fully check (a helper it can't fully verify, a try/catch, a wrapper, a combined condition, a cron secret that isn't checked for being set) is **MEDIUM `confirm-auth-gate`**. A confirm is not a pass: open the file and check it yourself. Each confirm says why, and how to test it in a way that fails when the hole is real (a `curl` with no cookies for most routes; `Authorization: Bearer undefined` against a preview without `CRON_SECRET` for cron routes; a bad signature that must get a 400 for webhooks; the request field that can change the user for reassignments; a signed-out try for server actions).

Or let your AI drive: in Claude Code type `/security-check`; in Cursor type `/security-check` or "run the prelaunch security check". The AI checks the build script, runs the scanners, explains each finding in plain English, and proposes fixes **without** touching production or running anything destructive without asking (see `guardrails.md`).

> **Limits (read this).** A clean result means "none of these patterns matched", **never** "this app is protected". Tested on fixtures, **not yet on a real hosted Supabase project or on Windows PowerShell 5.1** (the PowerShell setup was run in PowerShell 7 on Linux). The scripts are pattern matchers, not a compiler, and there are always more ways to write a broken check than they know:
> - **Keys** hidden by string-joining (`'sk-' + rest`) or unusual encodings are missed.
> - **Route auth**: clean = every write route reaches a gate the scanner fully verified; anything else is flagged for you to confirm. "Fully verified" is narrow on purpose: in the handler's own body, before the first write or paid call, a direct `supabase.auth.getClaims()` / `getUser()`, NextAuth `auth()` / `getServerSession()` or Clerk `auth()` / `currentUser()` (imported from the library or your NextAuth config file; for Supabase, called on a client made by `createClient()` / `createServerClient()` from `@supabase/*`, directly or through your own `utils/supabase/server.ts`), then a plain `if (!user) return …` (or throw / `redirect()` / `notFound()`) on its result, with the checked value not reassigned before the write; an awaited helper whose own code does exactly that and throws or redirects; or a shared-secret comparison that also fails when the variable is missing. Everything else, **including correct code** such as the Next.js docs' `verifySession()` helper, a check inside `try`, or a Hono `handle(app)` it can't see into, is a MEDIUM "confirm". Helpers are read up to two local imports deep to tell a do-nothing helper (HIGH) from a real one; a package helper is trusted by name only, as a confirm. A helper only counts as verified when its login check and its stop always run: if anything can skip them (an `if`, an early `return`, `&&`, `||`, `?:`), it is never clean. It is HIGH when the skip can come from the request (body, query, headers, cookies, route params, a server-action argument, the helper's own parameter filled from one of those, a variable set from one later, or a helper that reads `headers()` / `cookies()`), and a confirm that names the condition otherwise. When the export is `fn(handler)` or a nest of those (`withAuth(withRateLimit(handler))`) and `fn` is a local or imported function that returns a function, the scanner reads the returned closure: a login check that exits before `handler()` is called counts as a gate on the route. A readable wrapper that checks nothing (`withLogging`) is peeled off and the handler is judged as usual (HIGH if the route is open). A wrapper-like name (`withX`, `wrap…`) it cannot read or fully verify is a MEDIUM confirm, never a HIGH "result is never checked". NextAuth `auth(…)` and Hono `handle(app)` stay as they were.
> - **What the route scanner trusts**: it trusts your NextAuth config. A Credentials `authorize()` (inline, or a function in the same file passed as `authorize: login`) is clean only when every return that hands out a user sits on the passing side of a recognised password check: after `if (!ok) return null` / `throw` (a braced block may log first; inside a `try` that has only a `finally`, with no `return` in it, a `return user` after the try counts too), inside `if (ok)`, in `ok ? user : null` / `!ok ? null : user` / `ok && user` with no `||` / `??` fallback, or in `switch (true) { case ok: return user }` when no other case falls into it. Recognised checks: an awaited `bcrypt.compare` / `argon2.verify`, `compareSync`, `timingSafeEqual` (scrypt) that compares the typed password with a stored value (not with itself or its own hash), also as an item of an awaited `Promise.all([…])`, where its result is the name destructured at the same position (`const [user, ok] = await Promise.all([lookup, bcrypt.compare(…)])`, also `[user, ok] = await Promise.all(…)`, or `const pair = await Promise.all(…)` followed by `const [user, ok] = pair` (also `pair as …`, `pair!`, `[...pair]`, or through an alias `const p2 = pair`) up to the point where that name is assigned again, or by `pair[1]` / `p2[1]` when it never is; writing `pair[1] = true` or `p2[1] = true` counts as overwriting the check); a comparison with an environment value that is first checked to be set (`if (!process.env.ADMIN_PASSWORD) return null`); a call with `password`, `hash` or `verify` in its name that is given the password (`signInWithPassword`, `verifyPassword`); a same-file function judged by its code, not its name; or a backend login (`fetch` / `axios` sending the credentials or password) tested on `res.ok`, `res.status` or a field of the parsed answer (a bare `res` is always truthy and doesn't count). It is HIGH (`nextauth-credentials-open`) when a user can be returned and the password is never verified (only checked for being there, its length or `undefined` / `''`, hashed, logged or not used), when a check exists but a return still hands out a user whether or not it passed (an `else` or `catch` that returns a user, `?? user`, `|| { id: "guest" }`, an inverted or always-true test, a result that isn't used, a result overwritten before it's tested such as `ok = true` or `ok ||= true`, a compare whose `.catch()` returns `true` or another truthy value), or when an env value is compared without checking it's set (wherever it's missing, `undefined === undefined` signs in anyone who leaves the password out). Everything else is a MEDIUM `nextauth-credentials-check` naming the reason: a `compare()` that isn't awaited (a Promise is always truthy, so any password works), also when it sits inside an `async` function whose result isn't awaited (`const ok = (async () => await bcrypt.compare(…))()`), a callback-style `bcrypt.compare(pw, hash, cb)` (its answer arrives too late to be tested), a check result assigned again from another value before the test (`ok = user.legacy ? user.legacyOk : ok`), a `.catch()` on the compare that the scanner can't read, a password written in the source code (treat it as leaked), a plain `===` / `!==` against another value (`user.password`), or the password handed to a function in another file or a library; that finding names the file it resolved (the NextAuth v5 docs' `getUserFromDb(email, pwHash)` layout gets this and is fine if that function checks the hash). It recognises these by name and shape, not by running them: a check against the wrong user's hash, a function in another file that accepts anyone, or a backend that accepts any password still pass. An `authorize()` defined in another file isn't read. Writes are followed two files deep (plus barrels, `export * as` namespaces, `import * as repo`, `await import()` and `import().then(…)`, object methods such as `posts.remove()`, `export default { … }` objects and `new Repo()` class instances in the same file); a call it can't follow (three files deep, a class defined in another file, an `import()` with a computed path) is a MEDIUM that names the call, not a HIGH, so read it. It reads `tsconfig.json` / `jsconfig.json` `paths`: a package name mapped to a local file (`"@clerk/nextjs/server": ["./lib/fake.ts"]`) is not trusted, but a bundler alias set somewhere else (webpack / Turbopack config) is not seen. A check in `middleware.ts` / `proxy.ts` never counts: Next.js says not to rely on it alone, so a route protected only there is HIGH even when the middleware looks right. The scanner can still be fooled by code it misreads, and "before the first paid call" only knows the listed SDKs (OpenAI, Anthropic, AI SDK, Google GenAI, Mistral, fal, ElevenLabs, Replicate, Resend…) and `fetch()` to their URLs.
> - **Paid calls and rate limits**: a public route is HIGH when it calls a paid API and no rate limit the scanner recognises runs first. It finds paid calls by a call to a known provider URL (`fetch`, `axios`, …), by a client made from a listed SDK in this file or a file you import (`const client = new OpenAI()`, `const mailer = new Resend()`, `generateText()` from the AI SDK), by a function that returns one of those clients (`getOpenAI().chat.completions.create()`, `const client = getOpenAI(); client.chat…`, a lazy singleton, `client ||= new OpenAI()` / `client ??= new` / `client = client || new`, `export default function getOpenAI()`, a barrel `export { getOpenAI } from` / `export * from`, `const { chat } = getOpenAI()`, `(await getOpenAI()).chat…`, `import * as ai`, `getResend().emails.send()`), and through helpers up to two files deep. A provider name in a string or a type (`{ provider: 'openai' }`, `'Powered by OpenAI'`, `Boolean(process.env.OPENAI_API_KEY)`, `OpenAI.Chat.ChatCompletion`) is not a paid call. A `fetch` / `axios` / `ky` call whose arguments or headers contain `process.env.*_API_KEY` is still a paid call even when the URL itself is an environment variable or a const template, and a const that holds a known paid host used in a template or concatenation counts too. It can't see a provider chosen from a map or table, an `axios.create` instance, a client made with `require()`, a class or object-property client (`Ai.get()`, `{ chat: c.chat }`), a `globalThis` cache, a wrapper that only re-exports a method, a wrapper inside a package, or an SDK that isn't on its list. It recognises `@upstash/ratelimit` (and `@unkey/ratelimit`), `checkRateLimit()` from `@vercel/firewall`, BotID, Arcjet, `rate-limiter-flexible`, and a readable custom helper that keeps a store, counts and compares; the limit must run before the paid call, be awaited, and its result tested the right way round (`if (!success) return …`). A result that is only logged or echoed (`console.log(success)`, `remaining` in the JSON), never tested in a condition, never assigned to another name, and never passed to anything but a logger or an echoed object is HIGH, the same as an ignored result. A result stored on the request or another object (`(req as any).rl = await limit(); if (!req.rl.success)`, `ctx.rl.success`) is followed the same way as a local name. An `if` that tests the result but whose body only logs, builds a response, or sets a flag that is never later tested, and never exits (`if (!success) { console.log() }`), is HIGH. A `.catch(() => {})` on the limiter that the scanner can't prove stops the request stays a MEDIUM confirm, not a HIGH. `export const POST = withRateLimit(handler)` (also `export default`, and nested wrappers) is followed when `withRateLimit` is a local or imported function that returns a function: a recognised limiter that exits before `handler()` is called counts as verified on the route. A readable no-op wrapper is peeled off. A wrapper the scanner can't verify is a MEDIUM confirm, never "result is never checked". A result that is tested (`if (success) { … } else { return 429 }`, `success ? … : …`, `success && …`, `switch (success)`), assigned to another name (`const limited = !success; if (limited)`), or passed to a helper is a MEDIUM confirm, never a HIGH, when the scanner can't fully verify that over-limit requests are stopped. It does **not** judge the numbers (10,000 a minute passes). A limit that exists only as a Vercel Firewall rule in the dashboard is invisible to it (the route stays HIGH until the handler also calls `checkRateLimit()` or another recognised limiter), and one that sits in `proxy.ts` / `middleware.ts`, in a branch, or in code it can't read is a MEDIUM confirm, never clean. A rate limit doesn't replace a login check on a route that writes data: that stays HIGH. Stripe calls that move money are an explicit allowlist (not every `.create()`): `refunds`, `payouts`, `transfers`, `charges`, `paymentIntents` `create` / `confirm` / `capture` / `cancel` / `incrementAuthorization`, `subscriptions` / `subscriptionItems` / `subscriptionSchedules` `create` / `update` / `cancel` / `resume` / `delete`, `invoices` `pay` / `void` / `finalize` only, `creditNotes`, `customers` `del` / `delete` only, `topups`, `applicationFees`, and `billingPortal` `create` / `update`. `checkout.sessions.create`, `setupIntents.create`, `prices.list`, `products`, `paymentLinks`, `paymentMethods`, `customers.create`, and other read or session-setup calls are not HIGH "moves money" (a public one is the usual MEDIUM `no-auth-route`). Prisma write verbs (`create`, `update`, `delete`, …) are unchanged. Both are also found on a getter or an aliased client (`getStripe().refunds.create`, `stripeClient.refunds.create`, `db.post.create` from a file that exports a `PrismaClient`), not only on variables named `stripe` or `prisma`. A client whose factory file isn't in the project isn't followed. A namespace import (`import * as OpenAISdk from 'openai'; new OpenAISdk.OpenAI()`) is a paid client, and a `const headers = { Authorization: \`Bearer ${process.env.OPENAI_API_KEY}\` }` used later in `fetch(process.env.LLM_URL, { headers })` is a paid call. INFO `public-paid-route` means "limit verified", not "safe": per-IP limits can be rotated, so also set the provider's hard spend limit.
> - **CORS in config files**: `Access-Control-Allow-Origin: *` is reported from `next.config.(js|mjs|ts|cjs|mts)` `headers()` (also through a `const` array), `vercel.json` `headers` / `routes`, and a `proxy.ts` / `middleware.ts` that sets it, when the path is `/api/…` or every path; static-asset paths (fonts, `/_next/static`, images) are ignored. A value that falls back to `*` (`process.env.ALLOWED_ORIGIN || '*'`, also `res.headers.set('Access-Control-Allow-Origin', process.env.X || '*')` in `middleware.ts` / `proxy.ts`, a `const origin = process.env.X || '*'` used as the value, or an object property `'Access-Control-Allow-Origin': process.env.X ?? '*'`) is reported as MEDIUM (the `*` is used when the variable is missing, typical on a preview). It doesn't see an origin that is only `process.env.X` with no fallback `*`, a computed origin with no literal `|| '*'` / `?? '*'`, or code that echoes the request's `Origin`. A route that sets the header itself gets the older route-level check (MEDIUM, only when it writes or spends money).
> - **Routers aren't followed**: tRPC procedures, Hono sub-routers and similar. A tRPC `publicProcedure…mutation()` that writes is flagged; otherwise check yourself that every mutation and private query uses your protected procedure.
> - **SQL** reads policy text: it can't see inside your own functions (`is_admin()`, Supabase's RBAC `authorize()`; those get a WARN naming the function), and a membership lookup with a `WHERE` (`auth.uid() IN (select … where …)`) is trusted.
>
> So read the code each finding points to, and test with two accounts and a signed-out browser. The Next.js version floor (16.4.1 / 15.5.28) is current as of the 2026-10-14 security release. Cursor now calls `.cursor/commands` legacy and recommends Skills (`/migrate-to-skills`); the commands still work.

## What it checks

### (a) Exposed keys and env vars
- **`NEXT_PUBLIC_` (also `VITE_`, `EXPO_PUBLIC_`, `REACT_APP_`) on a secret.** Next.js copies every `NEXT_PUBLIC_` value into the browser JavaScript at build time. `NEXT_PUBLIC_OPENAI_API_KEY` = your key is public. Only the Supabase URL and the **publishable** (`sb_publishable_…`) or legacy **anon** key belong there. Names that clearly hold a secret (`SECRET`, `SERVICE_ROLE`, `PASSWORD`, `DATABASE_URL`, a provider name + `KEY`/`TOKEN`) are HIGH; other `KEY`/`TOKEN` names are MEDIUM ("check it"); harmless-looking names such as `NEXT_PUBLIC_ADMIN_EMAIL` or `NEXT_PUBLIC_OPENAI_MODEL` are LOW and never fail CI.
- **The `next.config` `env` block.** Next.js inlines every key listed there into browser JavaScript, *with or without* a prefix. A secret-looking name there (or `...process.env`) is HIGH.
- **Supabase secret key in the browser.** `sb_secret_…` and the legacy `service_role` key bypass Row Level Security completely. The scanner decodes legacy JWT keys and flags the ones with `role: service_role`, in source and in `.next/static`. (New `sb_secret_` keys also refuse browser requests with a 401, but a leaked one still works from any script.)
- **Secret key reachable from client code.** `"use client"` files that import your admin client, and server files using the secret key without `import 'server-only'` (that import makes the build fail if a client component ever pulls it in).
- **Hardcoded keys** for OpenAI, Anthropic, xAI, Groq, Stripe, Resend, AWS, GitHub, Slack, Google, private keys, and database URLs with passwords, including simple `atob('…')` / `Buffer.from('…', 'base64')` hiding. Keys glued together from pieces are not detected.
- **`.env` in git**: tracked now, ever committed in history, or not covered by `.gitignore`. Deleting a file does not remove it from history. If it was ever pushed, rotate.
- **Vercel env vars**: store keys as type **Secret** (write-only after saving); use **Config** only for public values. Keep production values different from preview/development (team policy *Separate Production Secret Values*).

### (b) Supabase Row Level Security
- Tables in **exposed schemas** with **RLS off** while `anon`/`authenticated` have grants. On hosted Supabase the exposed list lives in the Dashboard (Settings → Data API), not in the database, so the SQL treats every schema `anon` or `authenticated` can use as exposed (minus Supabase's own system schemas). Custom schemas like `api` are covered; a row from one tells you to check whether it's really in your exposed list. Anyone with your project URL and public key can read and change every row. (Supabase Security Advisor calls this `rls_disabled_in_public`, level ERROR.)
- Policies written but **RLS never enabled** (the policies do nothing).
- **`using (true)` / `with check (true)`** (and tautologies like `1 = 1` or `user_id = user_id`) on insert/update/delete, and `select … using (true)` on tables that aren't meant to be public. Each `OR` branch of a policy is judged on its own, because one weak branch lets everyone through: `auth.uid() = user_id OR true` is reported like `true`. That includes an `OR` inside an `AND` (`bucket_id = 'docs' AND (owner_id = auth.uid() OR auth.role() = 'authenticated')` has a branch with no owner check) and every way through a `CASE` (`CASE WHEN auth.role() = 'authenticated' THEN true ELSE … END`, also the simple form `CASE auth.role() WHEN 'anon' THEN true … END`; a `CASE` with no `ELSE` counts as `ELSE false`), and a role check that includes `anon` (`auth.role() = 'anon'`, `auth.role() IN ('anon', 'authenticated')`, `current_user = 'anon'`) counts as "everyone".
- Signed-out callers: a branch like `auth.uid() is null`, `coalesce(auth.uid() = user_id, true)` or `(auth.uid() = user_id) IS NOT FALSE` lets anyone who isn't logged in through, and is reported like `true`. `NOT (NOT …)`, `NOT (user_id <> auth.uid())` and `NOT (auth.uid() IS NULL)` are read as what they mean, and `coalesce(user_id, auth.uid()) = auth.uid()` as "owner, or a row with no owner".
- Policies that only check **"is logged in"** (`auth.uid() is not null`, `NOT (auth.uid() IS NULL)`, `auth.uid()::text is not null`, `auth.email() is not null`, `auth.role() = 'authenticated'` or `<> 'anon'`, the JWT `role` claim, JWT claims every signed-in user has (`aud = 'authenticated'`, `is_anonymous = false`, `sub is not null`), an e-mail domain pattern (`email LIKE '%@company.com'`: anyone can sign up with it unless sign-ups are restricted), `current_user`, or `auth.uid() IN (select id from profiles)` with no `WHERE`), on their own or as one `OR` branch next to an owner check: every user can edit every other user's rows. `auth.uid() <> user_id` ("anyone *except* the owner") is reported the same way. A policy that checks login *and* (`AND`) compares `auth.uid()` to a column is not flagged; neither is `auth.role() = 'service_role'`. Read policies that only check "is logged in" are a WARN: every signed-in user reads every row, and Supabase sign-ups are open by default.
- **Write policies with no owner check at all** (WARN): an insert/update/delete whose check never compares `auth.uid()` (or a JWT claim) with the row, e.g. `with check (body <> '')`. A user can then create or hand over rows that belong to someone else. The WITH CHECK is what stops that. If the policy calls your own function instead (`authorize('posts.delete')`), the WARN names it so you can check that the function looks at the signed-in user.
- Policies created `as restrictive` only narrow access, so `using (true)` there is not flagged.
- Policies that trust **`user_metadata`** (users can edit their own).
- **Views without `security_invoker = on`** and **SECURITY DEFINER functions** callable over `/rest/v1/rpc`: both skip RLS. Trigger functions such as Supabase's `handle_new_user()` can't be called over `/rpc` and aren't flagged.
- **Storage**: public buckets (any file URL readable); **who can read files**: a `select` policy for `anon` on a private bucket, `using (true)` (also as an `OR` branch), or a read policy for every signed-in user with no owner check (HIGH when it covers a private bucket). "Owner check" means `owner`/`owner_id`, the folder name (`(storage.foldername(name))[1] = (select auth.uid()::text)` or the `auth.jwt()->>'sub'` form; a folder compared with the JWT `role` or `aud` claim doesn't count, every user has those), or a `name LIKE auth.uid() || '/%'` prefix compared with `auth.uid()`; `owner_id = owner_id`, `<> auth.uid()` and `auth.uid()::text = ANY (storage.foldername(name))` (matches the uid at *any* folder level) don't count; and write policies that aren't limited to one bucket and the file's owner.
- **The 2026-10-30 grants change**: after that date new tables need an explicit `grant` before the API can see them. The safe order for every new table is **grant → enable RLS → policies**, in one migration. Grant each role that needs the table, **including `service_role`** if server code uses the secret key (it bypasses RLS but still needs grants). The rules files teach your AI this.

### (c) Unprotected API routes and server actions
- Every `app/**/route.ts` method (including Hono-style `export const GET = handle(app)` and NextAuth's `export const POST = auth(async (req) => …)`), `pages/api/*`, plain `api/*` Vercel function, and every `"use server"` action (including `export default` and arrow-function actions) gets one of three results when it writes or calls a paid API:
  - **clean**: the handler itself, before the first write or paid call, at its top level, calls `supabase.auth.getClaims()` / `getUser()` (on a client from `createClient()` / `createServerClient()`, also through your own `utils/supabase/server.ts` or a `lib/supabase/index.ts` barrel), NextAuth `auth()` / `getServerSession()` or Clerk `auth()` / `currentUser()` and stops with `if (!user) return …` (or `throw`, `redirect()`, `notFound()`; `if (error || !data?.claims)` and `if (!user || role !== 'editor')` are fine), or Clerk's `await auth.protect()`; or it awaits a helper whose own code does exactly that and throws or redirects (`const { supabase, user } = await requireUser()`); or it compares a request value with a secret **and** fails when the secret isn't set: ``const secret = process.env.CRON_SECRET; if (!secret || auth !== `Bearer ${secret}`) return …``;
  - **MEDIUM `confirm-auth-gate`**: gate-like code it can't fully verify: a helper it can't fully verify (the Next.js docs' `verifySession()`, a helper in a package), a check inside `try`, a wrapper or router handler, a webhook signature check (Stripe's documented `constructEvent` form is named as such, with what to check), a condition built from other values, a login helper that only runs under a condition built only from environment values and constants (`if (process.env.NODE_ENV === 'production') await requireUser()`, braced or not, in the route or inside the helper; the finding names the condition), or under a condition the scanner can't trace (`if (await featureOff()) return` inside a helper; the finding says it can't tell and names the function), a checked user that's reassigned before the write (`user = body.actAs ?? user`), a Supabase client the scanner can't trace to `createClient()`, or a cron check that doesn't make sure `CRON_SECRET` is set (`Bearer undefined` gets in wherever it's missing), or a NextAuth Credentials password check it can't confirm (`nextauth-credentials-check`, see Limits). The finding says why and how to test it. Open it and check it;
  - **HIGH**: clearly unprotected. No check at all; only `getSession()`; a 401 response without `return` (`if (!user) NextResponse.json(…)`); a check after the write, in a branch, in a callback, or in a `try` whose `catch` swallows the error; `if (!user && debug)`, `!(user || header)`, `user || header`, `data.user ?? { id: 'guest' }`; `claims.sub !== body.userId` as the only check; a helper that returns `null` when signed out and the route never checks the result; a helper whose code doesn't verify anyone (also through re-exports); a secret check that's skipped when the variable is unset (`if (process.env.CRON_SECRET && …)`) or uses loose `!=`; `auth.protect()` or an async gate helper that isn't awaited (also inside `Promise.all` with the write); `getUser()` on a hand-written object (`const supabase = { auth: { getUser: … } }`); a login helper that only runs under a condition the caller controls (`body.system ? null : await requireUser()`, `body.requireLogin && await requireUser()`, `if (!asGuest) await requireUser()` where `asGuest` is a server-action argument, or a header, cookie or query value; also an `else` branch, a flag set later with `skip = true` or `skip ||= …`, a helper such as `ensureAuth(opts)` that skips itself on its own argument when the route passes `{ guest: body.guest }`, a helper that skips on `headers()` / `cookies()`, and a helper called with a literal, or a `const` holding one, that always skips it, `ensureAuth(true)`; also a login check inside a loop over a request value, `for (const id of body.ids) await requireUser()`, which an empty list skips; also a labeled block that a request value breaks out of before the check, `skip: { if (body.skip) break skip; await requireUser() }`); a write inside `finally` after a login check in its `try` (the `finally` runs even when the check throws); a NextAuth Credentials `authorize()` that can return a user without verifying the password (`nextauth-credentials-open`, reported on the config file; see Limits). Checks that test the wrong thing get their own HIGH, `auth-wrong-field`: `if (error)` after `getClaims()` (no error when signed out), `if (!data)` after `getUser()` (`data` is always there), and `if (!session)` after Clerk's `auth()` (always an object).
- Helpers are read up to two local imports deep (`./`, `../`, `@/`). In a helper, only `throw`, `redirect()` and `notFound()` stop the request: `return null` doesn't. `getSession()` inside a helper is reported too. **Writes are followed into the functions a route calls** the same way: a route with no login check that calls `createPost()` from `lib/posts.ts`, which inserts with the secret key, is HIGH "writes data with no login check", not "fine if public". Object methods (`posts.remove(id)` from `const posts = { remove: async … }` or `export default { … }`), class instances (`const repo = new Repo()` with `class Repo` in the same file), barrels (`export * from './c1'`, `export * as sb from './server'`), namespace imports (`import * as repo from '@/lib/posts'`) and dynamic imports (`await import('@/lib/c1')`, `import('@/lib/c1').then((m) => m.createPost(…))`) are followed too. When a public route calls a method on a local import that the scanner couldn't follow (three files deep, a class defined in another file, or anything from an `import()` with a computed path), the finding names it ("calls createPost() → insertRow() in lib/c3.ts, which the scanner didn't follow") instead of "fine if public". `requireEnv()`, `ensureJson()`, reading the `Authorization` header, a database lookup like `getUser(id)`, and `if (!process.env.OPENAI_API_KEY) return` don't count as auth.
- **Supabase's own sign-in / sign-up / sign-out / e-mail confirm code** (`signInWithPassword`, `signUp`, `signOut`, `verifyOtp`, `exchangeCodeForSession`…) is INFO `auth-flow`: public by design, keep Supabase's auth rate limits on. If the same action also writes a row with no login check, that is still HIGH.
- **tRPC**: a `publicProcedure…mutation()` that writes is MEDIUM; the tRPC route itself gets a reminder to check your procedures.
- **Writes** include database inserts/updates/deletes and RPCs, Supabase Storage `upload`/`remove`/`move`, Stripe calls that move money (an explicit allowlist: `refunds.create`, `paymentIntents.create` / `confirm` / `capture`, `subscriptions.update` / `cancel`, `invoices.pay` / `void` / `finalize`, `billingPortal.sessions.create`, … — not `checkout.sessions.create`, `setupIntents.create`, or reads), `@vercel/blob` `put`/`del`, and KV/Redis writes. A secret-key client created anywhere in the file (also at the top, outside the handler) is called out as bypassing RLS. This is a careful pattern match, not a proof; see Limits above.
- **Server actions are public POST endpoints.** A check on the page does not protect the action; Next.js docs say to re-check auth (and ownership) inside each action.
- **`supabase.auth.getSession()` on the server** is flagged: it reads the cookie without verifying it. Use `getClaims()` (or `getUser()`).
- **`proxy.ts` / `middleware.ts` is not an auth boundary** (Next.js 16 renamed middleware to proxy). Use it for redirects, check auth again in the route.
- **Paid API calls** (OpenAI, Anthropic, the AI SDK, Gemini, Replicate, Groq, Mistral, Resend, Twilio…, called directly, through a helper, through an SDK client created in a file you import, or through a function that returns one of those clients):
  - **HIGH `unprotected-route` + HIGH `paid-api-no-rate-limit`** (paid-API cost and abuse risk): no verified login check and no rate limit the scanner recognises. The finding says if a limiter is there but its result is never checked, is only logged or echoed, is tested the wrong way round, or runs after the paid call.
  - **INFO `public-paid-route`**: no login check, but a recognised limiter runs first and stops the request. Fine for an endpoint that is public on purpose; still set the provider's hard spend limit.
  - **MEDIUM `paid-api-rate-limit-unverified`**: a limiter that is only named like one, sits in a branch, in `proxy.ts`, or in code the scanner can't fully verify (including a result tested in a condition, assigned to another name, or passed to a helper when it can't confirm over-limit requests are stopped). Send more requests than the limit allows and check that the extra ones get 429 and never reach the provider.
  - **MEDIUM `paid-api-no-rate-limit`**: signed-in route, no limiter. Fix with `checkRateLimit` from `@vercel/firewall` (needs a matching rule in Vercel → Firewall; Hobby gets 1 rule per project), Upstash Ratelimit, or another limiter, keyed on the user id (or the IP for a public route), returning 429 *before* the paid call.
- **Next.js older than the 2026-10-14 security release** (16.4.1 / 15.5.28). It reads the installed version (`node_modules/next`), then your lockfile, then the `package.json` range, and says which. On 15.x also check that `npm ls sharp` shows 0.35.5 or later.
- **CORS `*` in config**: `Access-Control-Allow-Origin: *` in `next.config` `headers()`, `vercel.json` or `proxy.ts` / `middleware.ts` on `/api/…` or every path is MEDIUM `cors-wildcard-config`; with `Access-Control-Allow-Credentials: true` next to it, HIGH `cors-wildcard-credentials` (browsers refuse that pair, and the usual fix, echoing the `Origin`, lets any website make signed-in requests). Use one exact origin. A value that falls back to `*` (`process.env.X || '*'`) is also MEDIUM. Static assets (`/fonts`, `/_next/static`, images) are fine open and are ignored.
- `vercel.json` functions with a long `maxDuration`, and `next.config` image settings that let anyone use your optimizer.

### (d) Runaway-bill limits (dashboard checks; scripts can't see billing)
- **Vercel Hobby:** projects pause at the free limits; no surprise bill. **Vercel Pro:** Settings → Billing → **Spend Management** (now on by default for Pro): check the on-demand budget and that **Pause production deployments** is on. Spend is checked every few minutes, so set it below your true maximum. It does **not** stop AI Gateway or v0 usage or storage charges, and it doesn't cover **Marketplace integrations**: Supabase billed through the Vercel Marketplace isn't capped by it (use Supabase's Spend Cap).
- **Function limits:** with Fluid compute the default max duration is 300 s. Set `export const maxDuration = 30` (or what you need) on AI routes.
- **Vercel Firewall:** a rate-limit rule on `/api/*`. Emergency switch, **Attack Mode**: available free on all plans (Hobby, Pro, Enterprise), and blocked requests don't count toward usage. Project → **Firewall** → **Bot Management** → under **Attack Mode**, **Enable**. Turn it on only during an attack: standalone APIs, mobile apps and unrecognized automated callers may fail the challenge.
- **Supabase:** Pro orgs have the **Spend Cap** on by default (Billing → Cost Control). Keep it on until you have real traffic. It does not cap compute, extra projects, custom domains, IPv4, PITR or phone MFA. Turn on Auth **CAPTCHA** and check **Auth rate limits** so bots can't spam sign-ups or SMS.
- **AI APIs:** one key per app, a **project budget with "Enforce a hard limit"** on OpenAI, a **workspace spend limit** on Anthropic, prepaid credits with auto-recharge off where offered.

## Tested
Run on 2026-11-16 on Linux (Node 24.22, PostgreSQL 17.11, Next.js 16.4.2) against throwaway test apps and databases with randomly generated fake keys. Nothing was deployed and no real service was called. An independent review added its own test cases over twelve rounds, mostly code written to fool the scanners; all of them are in the suites below. The paid-route and CORS tests were added on 2026-11-27 after a new-user field test missed an open paid route and a CORS `*` in `next.config`; follow-ups the same day added getter-returned paid clients, limiter results that are only logged or echoed, CORS `process.env.X || '*'`, checks that a provider name in a string or a type is not treated as a paid call, and limiter forms that test the result in a condition, assign it, or pass it to a helper (MEDIUM confirm, not a false HIGH). A 2026-11-28 follow-up restricted Stripe "moves money" to an explicit allowlist (a public `checkout.sessions.create` or `setupIntents.create` is not HIGH), followed `export const POST = withRateLimit(handler)` / `withAuth(handler)` wrappers (a readable no-op wrapper is peeled off; an unreadable one is a MEDIUM confirm, never "result is never checked"), treated a limiter result stored on the request or an object, flagged an `if (!success)` whose body never exits, resolved a `const origin = env || '*'` alias and an object-property `?? '*'` in middleware, and caught `import * as OpenAISdk; new OpenAISdk.OpenAI()` plus a provider env key in a headers object used by a later fetch. They ran the same way.
- **Secret scanner:** keys in client code, built `.next/static` chunks, prerendered HTML, git history (also after `git rm`), committed `.env.local`, CI files, JSON, base64 and the `next.config` `env` block are all caught; the anon JWT, publishable keys and placeholders are not flagged; `--url` only fetched same-origin scripts. **Missed (disclosed):** a key glued together from strings.
- **Route scanner:** 271 deliberately unprotected routes and actions, plus 124 deliberately broken NextAuth config files (counted separately, they aren't routes), across thirty-five test sets: missing auth, auth only in a comment, a 401 without `return`, checks after the write, in a branch, in a callback, in a swallowing `try/catch` (also `redirect()` swallowed), inverted, switched off with `&&`, `||` or `??`, `claims.sub !== body.userId`, secret checks that are skipped when the env var is unset or use `!=`, do-nothing and `return null` helpers (same file, imported, two files away, re-exported), `getSession()` in a helper, refunds, blob and storage deletes, paid calls before the check, look-alike `auth()`/`currentUser()` functions, wrong-field checks (`if (error)` after `getClaims()`, `if (!data)` after `getUser()`, `if (!session)` after Clerk `auth()`), a gate secret read from a `NEXT_PUBLIC_` / `VITE_` variable, a route protected only by `middleware.ts`, writes inside functions the route calls, un-awaited `auth.protect()` and gate helpers, `Promise.all([gate, write])`, a mock `supabase = { auth: … }` object, a user reassigned after the check, a login helper skipped by a request value or server-action argument (ternary, `&&`, `||`, `if`, `else`, `switch`, braced or not, through a variable set later or a helper that reads headers), a helper that skips its own check on an argument the route fills from the request (also destructured, nested in a second helper, or through a default parameter), a helper called with a literal or a `const` that always skips it, a check inside `try` whose `catch` decides, inside `finally`, a `.map()` / `.forEach()` callback, a `while` loop, a loop over a request list or an IIFE, a labeled block that a request value `break`s out of (also from an `else`), a write inside `finally` after the check in its `try`, writes three files deep, in object methods, `export default` objects, class instances, namespace imports and behind `await import()` / `import().then()`, and (added after a field test on 2026-11-27) public routes, server actions and `pages/api` handlers that call a paid API through a helper's `fetch` to a provider URL (also two files deep), an SDK client imported from another file, a function that returns a paid SDK client (`getOpenAI().chat…`, `const client = getOpenAI(); client.chat…`, a lazy singleton, `client ||= new OpenAI()`, a barrel re-export, `export default function getOpenAI()`, `const { chat } = getOpenAI()`, `import * as ai`, `getResend().emails.send()`), a `fetch` whose headers carry `process.env.*_API_KEY` or whose URL is a paid-host const template, a Stripe/Prisma write on a getter or aliased client, an aliased `new Resend()` / `twilio()` / `new Anthropic()` / `new Mistral()` / `new Replicate()`, an `axios` call, or the AI SDK, with no rate limit, a limiter whose result is ignored, only logged or echoed, tested the wrong way round or un-awaited, a limit that runs after the paid call or inside a branch, and a limiter next to a database write. **237 are HIGH, 13 are MEDIUM "confirm", 7 are MEDIUM "calls X, which the scanner didn't follow" (writes three files deep, in a class instance exported from another file, or behind an `import()` with a computed path) and 14 are MEDIUM "rate limit the scanner can't verify" (a limiter that is only named like one, in a branch, in a package it can't read, a helper that returns a value nobody tests, or a result tested in a condition / assigned / passed to a helper that the scanner can't fully verify); none comes out clean.** Of the 124 broken NextAuth configs, 114 are HIGH `nextauth-credentials-open` (an `authorize()` that returns a fixed user (twice, incl. the old docs' "J Smith" example), returns the typed-in name, reads the e-mail and always returns a user, has only a TODO, looks the user up or upserts it without checking the password, only checks that a password was typed (`if (credentials?.password)`, `!== ''`, `=== undefined`, a length check, a `throw` when it's missing), hashes it but never compares, logs it, compares it with itself or with its own hash, ignores the `compare()` result (also one run inside `Promise.all`, destructured or not) or the backend's answer, overwrites the result before testing it (`ok = true`, `ok = 1`, `ok ||= true`), turns a failing compare into a pass with `.catch(() => true)` (or `1`, or a block that returns `true`), tests only the user from a `Promise.all` result (destructured later, by index, or reassigned first), overwrites the compare's slot of that result (`pair[1] = true`, also through an alias `p2[1] = true`), returns before testing it, or lets a `finally` or a swallowing `catch` override the check, tests a bare `fetch` response, returns a guest user when the check fails (separate `return`, ternary, `!ok ? guest : user`, `||`, `??`, `else`, `catch`, `finally`, a labeled `break`, a `switch (true)` default or a case that falls into the passing one, also after a log line), inverts or `|| true`s the test, uses a same-file `verifyPassword()` that verifies nothing, signs in a demo e-mail before the check, compares with an env value that may be unset, or is passed by reference) and 10 are a MEDIUM `nextauth-credentials-check` naming the problem (a `bcrypt.compare` that isn't awaited, also inside an un-awaited `async` function, a callback-style compare, a hard-coded password, a plain-text `user.password ===` / `!==` compare, a check in another file that accepts anyone, a result reassigned from another value (also `ok = user.legacy || ok`), a password that only goes through `Promise.resolve()`); none comes out clean. Of 105 correct configs, 97 are clean (bcrypt with `if`/ternary/`&&`/`throw` (also `CredentialsSignin`, a log before `return null`, `!ok ? null : user`, `ok === false ? null : user`, `switch (true) { case ok: … }`, a bare `return;`, `ok !== true`, a `try` whose `catch` returns null, `.catch(() => false)`, a result reset to `false` in a `catch`), a lookup and compare run together in `Promise.all` and both tested (in any order, renamed, with three items, destructured on a later line, also with `as` / `satisfies` / `!`, through an alias or a spread, or with `pair` reassigned after the test, assigned to `let` names declared first, or read as `pair[0]` / `pair[1]`), a typed destructure or a typed `pair`, a braced `if (!ok) { throw }` inside nested `try` / `finally`, a check that throws inside `try { … } finally { … }` before the `return`, argon2 `verify`, `compareSync`, `if (ok === false) return null`, `.catch()` that logs and returns `false`, validation, a rate limit or a second factor before or after the compare, an awaited `async` wrapper, `compareSync`, argon2, `timingSafeEqual` with a length check, `verifyPassword`, zod-validated input, a same-file helper that uses bcrypt, Supabase `signInWithPassword`, the NextAuth v4 docs' `fetch` example and other backend logins via `fetch` / `axios` that test `res.ok` or `res.status`, a delegated `verifyLogin()`, a password compared with an env value that is checked to be set, an `authorize` that always returns `null`, a function passed by reference) and 8 are a confirm: the password goes to a function in another file (the NextAuth v5 docs' `getUserFromDb()` forms, a `checkCredentials()` in `lib/`, a `loginUser()` in a library, one called inside `Promise.all`), or the check result is assigned again from another value before the test (`ok = !!ok`, `ok = ok && user.active`), which the finding names; none is HIGH. The confirms are the reassigned / shadowed user cases, code using a `tsconfig` `paths` alias or a local stub posing as Clerk or NextAuth (also through a barrel), a cron check that doesn't test that `CRON_SECRET` is set (the finding names the "Bearer undefined" hole), and a secret compared with a value taken from the request body. In a copy of that set without the `paths` aliases, the route behind a NextAuth Credentials provider whose `authorize()` accepts anyone is clean itself, but its config file is HIGH `nextauth-credentials-open`. Correct setups: the plain Supabase, NextAuth (incl. the `auth()` wrapper), Clerk (incl. `isAuthenticated`, `auth.protect()`, an aliased import and a one-line re-export), `pages/api`, fail-closed cron-secret forms and fully verified helpers (`requireUser()` with `getUser()` + `redirect()`, also two files away) come out clean; correct code the scanner can't fully verify (the Next.js docs' `verifySession()`, checks inside `try`, a verified Stripe webhook that writes, cron checks without an "is it set" test, a Supabase client file that isn't in the project, a login helper behind an environment condition (braced or not, in the route or inside the helper) or behind a function the scanner can't trace, a ternary that picks between two login helpers, `if (c) await requireUser(); else throw …` or its mirror, a check in a labeled block or a `try` with a `finally`) gets a MEDIUM "confirm", never a HIGH. Supabase's official `with-supabase` Next.js template and the SSR guide's `utils/supabase` layout, each with 9 typical handlers added (getUser / getClaims routes, actions that redirect, throw or upload, a strict `requireUser()` helper, an admin-client delete behind `getUser()`, a rate-limited OpenAI route), and 7 client-file layouts (arrow-function `createClient`, `src/`, relative import, renamed export, JavaScript + `jsconfig.json`, no `tsconfig.json`, a `lib/supabase/index.ts` barrel) all scan **0 HIGH, 0 MEDIUM**. A realistic 13-handler Supabase + Stripe + OpenAI app gives 0 false HIGH: 3 MEDIUM (the Vercel cron one-liner's real "Bearer undefined" gap, the Stripe webhook, a public `GET`) and its sign-in / sign-up / sign-out code as INFO.
- **Paid routes and CORS in config (added 2026-11-27):** of 27 correct paid-API setups, 24 report INFO `public-paid-route` and 3 are clean (a recognised limiter before the call: Upstash with the limiter in the same file, in another file or created inside the handler, `checkRateLimit()`, BotID, Arcjet, `rate-limiter-flexible` in `try` / `catch`, a custom counter, a helper that throws, a helper that returns the result or a blocked flag, an inline `if (!(await rl.limit(ip)).success)`, a renamed or aliased `success` (`success: ok`, `const allowed = success`, `(await limit()).success`, `res?.success`), a result stored on the request (`(req as any).rl.success`), a `withRateLimit(handler)` wrapper, a server action, a `pages/api` handler; plus a signed-in route with a limiter, a `withAuth` wrapper on a write, and `withAuth(withRateLimit(handler))`, which are clean). Fourteen limiter forms the scanner can't fully verify (`if (success) { … } else { return 429 }`, `success ? … : …`, `success && …`, `const limited = !success`, a result passed to a helper, `switch (success)`, a limiter that is only named like one, in a branch, or in a package it can't read) are MEDIUM, not HIGH; a result that is only logged or echoed stays HIGH, as does an `if (!success) { console.log() }` with no exit. Five signed-in routes with no verified limiter are MEDIUM (including `withAuth(handler)` with no limiter), and 7 look-alikes that aren't paid calls (a helper file that also holds a client, a formatter from a file that also calls the provider, a public route that calls nothing paid, a `getSupabase()` getter on a read-only route, a Stripe `prices.list` GET, a public `checkout.sessions.create`, a public `setupIntents.create`) produce no paid finding; a Supabase `.limit(10)` query is not mistaken for a limiter. A limiter in `proxy.ts` makes the route it covers a MEDIUM confirm, and a route it doesn't cover stays HIGH. CORS: 12 wrong configs (10 MEDIUM and 2 HIGH with credentials: `next.config` `.js` / `.mjs` / `.mts` / `.ts`, a `const` header array, a value written before the key, a lower-case key, a `process.env.X || '*'` fallback, a `const origin = process.env.X || '*'` alias, `vercel.json`, a `proxy.ts`, a `middleware.ts` `.set(..., process.env.X || '*')`) are flagged, and 6 correct ones (your own origin, an origin from an env var with no fallback `*`, static assets only, other headers only, a comment) are not.
- **RLS audit SQL**, each suite in its own fresh Postgres cluster modeled on hosted Supabase (no `pgrst.db_schemas` setting): 123 expected findings across ten databases, including `OR true`, role and `current_user` tricks, `auth.uid() is null`, `<> user_id`, `coalesce(…, true)`, `IS NOT FALSE`, `NOT (NOT …)`, `coalesce(user_id, auth.uid())`, an `OR` hidden inside an `AND` or a `CASE` (also the simple `CASE auth.role() WHEN 'anon'` form), JWT `aud` / `is_anonymous` / `sub` / e-mail-domain checks, login-only reads, writes with no owner check, storage folders compared with the JWT `role`, and storage reads of private buckets; 63 correct setups not flagged (login *and* owner, `NOT (user_id <> auth.uid())`, `CASE … THEN owner END` with no `ELSE`, team membership, folder / `split_part` / `LIKE` / `(select auth.uid()::text)` / JWT `sub` owner checks, `app_metadata` admin and custom claims, restrictive policies, `NOT (… OR …)`, public avatars, `handle_new_user()`, Supabase's own storage examples). It ran inside `begin read only`, and after the suggested fixes `set role anon` went from seeing rows to seeing none.
- **Setup:** the bash block and the PowerShell block (PowerShell 7.4 on Linux) each run twice into a clean app: files in place, the `CLAUDE.md` / `.cursorignore` text added exactly once, `…` characters intact, and the installed kit causes 0 findings.
- **Read-only:** before/after hashes of every test file (including `.git`) and git state were identical after every scan.

The test fixtures aren't included in the download, so it contains no fake keys.

**Not tested:** a real hosted Supabase project, a real Upstash, Vercel Firewall (`checkRateLimit()` needs its rule created in the dashboard), BotID or Arcjet account (their calls were only read by the scanner, never run), a real AI provider, a live AI model running the prompts and commands (they were desk-checked), and Windows itself (PowerShell 5.1; the scripts are plain Node and should work).

## Sources (checked 2026-10-21)
Supabase: API keys and migrating to publishable/secret keys; Row Level Security; Securing your API; Advisors / database linter; "Tables not exposed to Data and GraphQL API automatically" changelog; Storage access control; Spend cap; Creating an SSR client (getClaims). Supabase CLI `db advisors` (CLI PR #4957, March 2026); Supabase MCP server (read-only and project-scoped URLs). Vercel: Config and Secret environment variables (changelog 2026-08-24); Spend Management (incl. what it excludes); Attack Mode; Configuring max duration; WAF Rate Limiting and Rate Limiting SDK. Next.js: Data security guide; proxy.js; `next.config` env; Security update 2026-10-14. Claude Code permissions; Cursor rules and Skills. OpenAI spend limits; Anthropic workspaces.

---
This kit is free from Bot Pantry: https://botpantry.com/kits/prelaunch-security
Share that link with anyone it would help. New kits added regularly, plus a weekly roundup of the most-downloaded ones: https://botpantry.com/newsletter
