Dev.to AI 🤖 Ai 👁 0 📖 5 min read

We Audited 145 AI-Built Next.js + Supabase Apps. 16 Left Their Databases Wide Open.

We recently audited 145 public Next.js + Supabase projects built with AI coding assistants. Sixteen of them had completely wide-open database permissions. Anyone grabbing the public frontend key straight out of the brows

We recently audited 145 public Next.js + Supabase projects built with AI coding assistants. Sixteen of them had completely wide-open database permissions. Anyone grabbing the public frontend key straight out of the browser could read all the data.

How we checked them was boring on purpose. Every Next.js + Supabase app ships its project URL and public anon key to the browser by design. Using only that public key, without logging in or running exploits, we checked what the PostgREST API returned and looked at the public code and config patterns around auth, storage, API routes, and database policies. When one curl call against /rest/v1/<table>?select=* dumps live rows, there is nothing theoretical left to argue about.

A few failure patterns stood out right away.

In Supabase, a table ends up wide open to the public anon key in two familiar ways: either Row Level Security was never enabled on a public table, or RLS was switched on alongside a USING (true) policy pasted in so the prototype would stop returning empty arrays. Even TO authenticated USING (true) looks careful in a migration file, yet it still lets any signed-in user read and edit every other user's rows.

Even when table policies look decent, quiet RLS bypasses keep showing up next to them. Putting SUPABASE_SERVICE_ROLE_KEY behind a NEXT_PUBLIC_ prefix tells Next.js to inline full database access into client JavaScript. In Postgres, standard views execute with the view owner's privileges by default, skipping base-table RLS unless you set security_invoker = true (or keep the view out of exposed schemas).

The same shortcuts carry straight into Next.js server routes: endpoints calling paid AI APIs with no auth, rate limit, or usage cap (an open wallet waiting for a curl loop), Stripe webhooks calling req.json() without checking stripe-signature, and routes authorizing off supabase.auth.getSession() cookies or trusting userId and price fields from the browser.

None of this happens because models haven't heard of RLS or HMAC signatures. It happens because of the feedback loop we put them in. When you tell Cursor or Claude Code "build the dashboard and fix why the table returns []," the model optimizes for making the screen work on the next reload. RLS blocking a query looks like friction to clear, so the quickest patch is USING (true) or reaching for service_role. getSession() passes local happy-path testing. Public storage buckets make image previews show up on the first try. Add training data full of short quickstarts that skip rate limits and webhook verification for readability, and assistants happily ship demo defaults unless you spell out hard boundaries.

We turned our audit notes into 12 practical rules. Even if you never install a rule file, checking your app against these twelve points before launch catches most of the painful mistakes:

  1. Require owner-scoped RLS on every public table. Enable RLS in the same migration that creates the table, scoped to auth.uid() = user_id (or tenant membership). Never ship USING (true) or WITH CHECK (true) as a general policy, including for authenticated.
  2. Keep server secrets out of client code and NEXT_PUBLIC_ vars. Only the Supabase anon key and Stripe publishable key (pk_...) belong in the browser. Keep service_role, database passwords, Stripe secrets, and AI keys strictly server-side.
  3. Make storage buckets private by default. Set public = false, scope storage.objects policies by user folder ((storage.foldername(name))[1] = auth.uid()::text), and serve private files through short-lived signed URLs. Leave public buckets strictly for world-readable assets like product images.
  4. Add auth, rate limits, and spend caps to every paid-API route. Before calling OpenAI, Anthropic, Replicate, or ElevenLabs, verify the user, enforce per-user/IP rate limits, cap input size, and check a daily or monthly usage ceiling. Uncapped metered endpoints leave your provider balance exposed to any script.
  5. Verify webhook signatures against the raw body. For Stripe, read await req.text() and validate stripe-signature via stripe.webhooks.constructEvent() using STRIPE_WEBHOOK_SECRET, returning 400 on failure. Never trust req.json() directly, and handle retries idempotently.
  6. Authenticate and check ownership in every API route. Resolve the caller server-side at the top of every Route Handler and Server Action, then confirm they own the target record before reading or writing it. Ignore client-sent userId, role, isAdmin, and price fields; load roles from your database and prices from your server catalog.
  7. Keep real secrets out of git. Store credentials in .env.local or your host's env panel, ignore .env* with !.env.example, and commit only placeholders. If a real key ever hits a commit, rotate it immediately; deleting it later leaves it in git history.
  8. Keep internals out of responses and secrets out of logs. Return plain messages (Something went wrong, Not found, Unauthorized) instead of stack traces or SQL errors, and return 404 rather than revealing another user owns an ID. Strip tokens, Authorization headers, and sensitive auth or payment payloads before logging.
  9. Revalidate server-side auth with getUser(), not getSession(). In Route Handlers, Server Actions, and middleware.ts, call supabase.auth.getUser(), fail closed on error || !user, and never fall back to getSession(). Cookie-only getSession() is fine for non-authoritative browser UI, not server authorization, and you still need to scope queries by user.id.
  10. Lock down Postgres views and SECURITY DEFINER functions. Set with (security_invoker = true) on exposed views (Postgres 15+) or move server-only and private materialized views to a non-exposed private schema with client privileges revoked. Prefer SECURITY INVOKER for functions; when SECURITY DEFINER is genuinely needed, pin set search_path = '', schema-qualify all objects, enforce auth.uid(), and revoke default PUBLIC and anon EXECUTE.
  11. Validate uploaded file content, size, and encoding server-side. Private buckets only restrict downloads. Pair host-aware size caps with a three-way check across extension, declared MIME, and magic bytes (file-type), reject .html/.svg/scripts on image endpoints, re-encode images to strip EXIF/GPS metadata, store under random keys (<user_id>/<uuid>.<ext>), and serve with X-Content-Type-Options: nosniff (plus Content-Disposition: attachment for PDFs and other non-reencoded files).
  12. Commit lockfiles, run frozen installs, verify new packages, and gate on high-severity audits. Track your lockfile in git and run frozen CI installs (npm ci, pnpm install --frozen-lockfile, etc.) without fallback. Verify unfamiliar packages in official docs and npm view before installing (AI tools invent plausible names attackers can register, known as "slopsquatting"), and fail builds on high or critical advisories without swallowing errors via || true.

Repeating all twelve rules in every prompt gets old fast, so we packaged them as a free skill pack called Vibe Security Rules (v2). It includes ready-to-use files for Cursor (cursor-rules.mdc) and Claude Code (claude-code-rules.md), a 12-item pre-launch self-check for your own app, and 39 verification cases testing broken and safe code.

It is free, and our first real user has already run it on their project. If you try it on your repo and spot an edge case we missed, open an issue.

📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.