afterbuild/ops
Resource

AI app security checklist — 25 checks to secure AI-generated code.

AI builders move fast and leave security for later. Later is now. Here are the 25 checks that catch the most critical gaps in AI-built apps before real users find them.

By Hyder ShahFounder · Afterbuild LabsLast updated 2026-11-04

How do you secure AI-generated code before launch?Review it the way you would review a new contractor's pull request. Turn on Supabase RLS with owner-checking policies on every table, keep secret keys out of the browser bundle, check auth and ownership on every API route, verify Stripe webhook signatures, and audit dependencies. The 25 checks below cover each step.

Security in AI-built apps is not a theoretical problem. In 2025, Matt Palmer's CVE-2025-48757 statement reported inadequate RLS settings in 170 of the 1,645 Lovable projects he scanned. In February 2026, The Register reported a separate case: one Lovable-hosted app whose missing access controls and inverted AI-generated auth logic exposed 18,697 user records. Our 2026 vibe-coding research collects more of these. Across languages, Veracode's 2025 GenAI Code Security Report found that 45% of AI-generated code samples failed security tests and introduced OWASP Top 10 vulnerabilities, and that the tools failed to defend against cross-site scripting in 86% of relevant samples. For the full list of failure classes, see the nine security risks in AI generated code.

The good news: the failure modes are repetitive. The same gaps show up across apps built with Lovable, Bolt, Replit, Cursor and v0, because the builders make the same assumptions. Below is the complete list of 25 checks, grouped by category, with an explanation for each item and the specific fix. If you want the wider picture first, our guide to vibe coding security and whether AI-built code is safe for production covers when an app is ready to go live.

How to use this checklist

Work through the six sections in order, because later checks assume earlier ones (an API ownership check that relies on RLS is only as good as the RLS policy). Tick an item only after you have seen the evidence: the RLS badge in the dashboard, a 401 from a logged-out request, a rejected forged webhook. Each item maps to an OWASP ASVS 5.0 chapter in the table near the end, and the pre-launch sign-off sheet turns the list into a launch gate. You can also get the checklist sent to you from the form at the end of the page.

1. Supabase RLS (6 checks)

Row-Level Security is the single most important security feature you will configure in an AI-built app, and it is the one the AI reliably gets wrong.

Why RLS on every table

When RLS is disabled on a Supabase table, the anon key (which is shipped to every browser that loads your app) has full read and write access to that table. A curious user can open the browser devtools, grab the supabase client, and run supabase.from('any_table').select('*'). If RLS is off, they get everything. Check in the Supabase dashboard: Table Editor → select each table → ensure the “RLS enabled” badge is present. If not, click “Enable RLS.”

Why SELECT policies per table

Enabling RLS without writing policies locks the table completely — nobody can read anything, including the legitimate owner. So you need at least one SELECT policy per table. The canonical policy for user-owned data is USING (auth.uid() = user_id), which says “a row is visible if the current authenticated user's ID matches the row's user_id column.” If your schema has shared resources, the policy includes a join against the membership table.

Why INSERT policies must set user_id

An easy mistake: write an INSERT policy that says WITH CHECK (true) because “only authenticated users can hit this anyway.” The problem is the client sends the user_idvalue, and an attacker can send any value they like — including another user's ID. The correct policy is WITH CHECK (auth.uid() = user_id), which rejects any insert that claims a different user. A complete owner-only policy set for a table looks like this:

alter table public.projects enable row level security;

create policy "owners read" on public.projects
  for select to authenticated using ((select auth.uid()) = user_id);
create policy "owners insert" on public.projects
  for insert to authenticated with check ((select auth.uid()) = user_id);
create policy "owners update" on public.projects
  for update to authenticated
  using ((select auth.uid()) = user_id) with check ((select auth.uid()) = user_id);
create policy "owners delete" on public.projects
  for delete to authenticated using ((select auth.uid()) = user_id);

Service role keys do not belong in the client

The service role key bypasses RLS entirely. It is intended for server-side use only. Search your repo for SUPABASE_SERVICE_ROLE — if it is imported from anywhere inside app/ or components/ on the client, or prefixed with NEXT_PUBLIC_ or VITE_, it is exposed. Move it to server-only code (route handlers, server actions) and re-deploy.

Storage bucket policies

Supabase Storage has its own policies, separate from table RLS. Per the Supabase Storage access control docs, Storage does not allow uploads to a bucket without RLS policies. The tempting fix for a failing upload is a broad policy that lets any authenticated user read and write every file. In a multi-tenant app, that means any logged-in user can read anyone's files. Scope policies per bucket instead: users read and write only inside their own folder, matching (storage.foldername(name))[1] = (select auth.jwt()->>'sub'). Public buckets serve files to anyone with the URL, so keep private data out of them.

2. Authentication (5 checks)

OAuth redirect URLs

AI builders create OAuth flows with the preview URL hardcoded. Once you deploy, the OAuth provider redirects users back to https://stackblitz-something.com instead of your real domain, and the auth flow dies. Fix in two places: the OAuth provider dashboard (Google Cloud Console, GitHub OAuth Apps) must have your production domain in the redirect URI list, and the Supabase Auth “Site URL” and “Redirect URLs” settings must include it.

Password reset email templates

The default Supabase password reset email includes a link to {{ .SiteURL }}/auth/callback?.... If your Site URL is still the preview domain, the email bounces users nowhere. Change the Site URL in Supabase Auth settings and send yourself a test reset email to verify the link works.

Session refresh

Supabase access tokens expire after one hour by default (see Supabase's sessions guide), and each refresh token can be used once. Without a refresh mechanism, users are randomly bounced to login mid-task. The fix in Next.js is a middleware that calls supabase.auth.getUser() on every request, which refreshes the cookie. In React Router / Vite apps, it is onAuthStateChange plus correct session handling in your root provider.

Protected routes actually check auth

Hiding the navigation button to /admin does not protect /admin. An attacker types the URL into the browser and hits the page. Every protected route must check auth server-side (in Next.js: getUser() at the top of the server component or route handler, and redirect if null). Audit by trying to hit every protected URL while logged out.

Magic link expiry

Supabase magic links and email OTPs expire after one hour by default, and a user can request a new one once every 60 seconds (per the passwordless email docs). Check the value in Supabase Auth settings and keep it at one hour or less; Supabase strongly discourages anything above one day.

3. Environment variables (4 checks)

The public prefix trap

Next.js exposes any env var prefixed NEXT_PUBLIC_ to the browser bundle. Vite does the same with VITE_. AI builders sometimes prefix things liberally to “make them work,” which can inadvertently ship your database connection string, Stripe secret key, or API credentials to every visitor. Search your code for every env var; anything with a sk_, database URL, or service role token must not be in a public-prefixed variable.

.env in .gitignore

Open .gitignore. Verify it includes .env, .env.local, .env.production, and any other env file variant you use. Run git log -- .env to check no env file was ever committed. If one was, you must rotate every secret in it and then cleanse the git history (or accept the leak).

Dev vs production vars

Using the same Stripe live key in development and production means test transactions hit your real account. Using the same Supabase project for both means seed data and real data mix. Create two environments: a dev Supabase project, a Stripe test mode, local-only keys for development; production equivalents only deployed to the production host. Never cross the streams.

4. API endpoints (4 checks)

Authentication at every endpoint

Every API route that does anything other than public content must start with an auth check. In Next.js: const user = await getUser(); if (!user) return new Response(null, { status: 401 }); at the top of the handler. AI-generated routes often skip this on the assumption that “the frontend only calls it when logged in” — which is irrelevant, because anyone can hit the URL directly.

Ownership checks on resource endpoints

An endpoint like GET /api/projects/[id] must check that the project belongs to the authenticated user. The AI sometimes writes select * from projects where id = $1 with no user check — any logged-in user can fetch any project by iterating IDs. Always join on user_id or rely on RLS to enforce it. If you rely on RLS, verify RLS is actually enabled (Section 1).

Rate limiting on auth

Login and password reset endpoints without rate limiting are vulnerable to credential stuffing. Supabase Auth has built-in rate limits on its hosted endpoints, but any custom auth logic you wrote (magic link senders, custom login handlers) needs its own. Upstash Rate Limit, Vercel KV, or a simple Redis counter — the implementation is small; the protection is large.

SQL injection

When using the Supabase client with typed queries (.from().select() etc.), SQL injection is mostly impossible because values are parameterized. The risk appears when AI code drops into raw SQL — rpc() calls or custom functions — and concatenates user input into a query string. Search for any $${-interpolated SQL and fix it to use parameters.

5. Stripe and payments (4 checks)

Signature verification

A public webhook URL without signature verification accepts any POST. An attacker can send a fake checkout.session.completed payload with their own user ID and grant themselves premium. Follow Stripe's webhook signing guide and use stripe.webhooks.constructEvent(rawBody, signature, webhookSecret). Read the raw request body, not parsed JSON — Stripe computes the signature over the raw bytes, and most web frameworks default to parsed JSON which fails verification. In a Next.js route handler:

// app/api/stripe/webhook/route.ts
import Stripe from "stripe";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);

export async function POST(req: Request) {
  const rawBody = await req.text(); // raw bytes, not req.json()
  const signature = req.headers.get("stripe-signature") ?? "";
  let event: Stripe.Event;
  try {
    event = stripe.webhooks.constructEvent(
      rawBody, signature, process.env.STRIPE_WEBHOOK_SECRET!,
    );
  } catch {
    return new Response("Invalid signature", { status: 400 });
  }
  // skip event.id if already recorded in processed_events, then handle it
  return new Response(null, { status: 200 });
}

Handle payment failure

When a recurring payment fails, Stripe fires invoice.payment_failed. If you ignore the event, the user keeps access while Stripe retries the payment. You want to either start dunning (notify the user, retry their card, require action) or revoke access after a grace period. Either is defensible; doing nothing is not.

Handle subscription cancellation

When a subscription ends (user cancels, payment failures exhausted, manual delete), Stripe fires customer.subscription.deleted. Your handler must update the subscriptions table to mark the user as non-paying. Otherwise former customers keep access forever. Test this by cancelling a test subscription in the Stripe dashboard and verifying access is revoked in your app.

Idempotency

Stripe delivers webhooks at-least-once. If your handler times out or returns a 500, Stripe retries: in live mode it keeps trying for up to three days with exponential back-off, according to Stripe's webhook docs, which also warn that an endpoint can receive the same event more than once. Your code must produce the same database state whether an event is processed once or three times. Standard pattern: a processed_events table with a unique constraint on stripe_event_id; before processing, insert the ID and catch the unique violation to skip duplicates.

6. Code and dependency security (2 checks)

Dependency audit

Run npm auditin your repo. Fix every “critical” and “high” finding before launch. Most are one npm audit fix away. For the ones that aren't, read the advisory and decide: update the direct dependency, replace it, or accept the risk with a documented rationale. Do not launch with known critical CVEs in your dependency tree.

Hardcoded values

AI builders occasionally burn values into the code during development and forget to clean them up: a test API key, a test user ID, a webhook secret, a debug bypass that says if (email === 'test@example.com') return true;. Grep for these patterns. Search for sk_test, sk_live, bypass, debug, TODO, and your own email address. Anything you find, move to env vars or delete.

AI-generated code review best practices

The checklist catches known gaps. Reviewing each AI change as it lands stops new ones from appearing between audits:

For a structured pass over a whole repo, our code audit checklist and process guide shows how a full security review is run, and our fixed-fee security audit for AI-built apps is the done-for-you version.

Securely deploy vibe-coded apps: headers and monitoring

Passing the 25 checks makes the code safer. The deploy decides whether you find out when something still goes wrong. Before you point a real domain at the app:

In Next.js, headers go in next.config.ts:

async headers() {
  return [{
    source: "/(.*)",
    headers: [
      { key: "Strict-Transport-Security", value: "max-age=63072000; includeSubDomains" },
      { key: "X-Content-Type-Options", value: "nosniff" },
      { key: "Content-Security-Policy", value: "frame-ancestors 'none'" },
    ],
  }];
}

OWASP ASVS 5.0 mapping

The OWASP Application Security Verification Standard (ASVS 5.0.0, published 30 May 2025) is the reference for what “verified” means in web app security. This is our chapter-level mapping of each section above; use it to find the detailed requirements in the standard, not as a compliance claim.

Checklist sectionASVS 5.0 chapters
1. Supabase RLSV8 Authorization; V5 File Handling (Storage); V13 Configuration (service role key)
2. AuthenticationV6 Authentication; V7 Session Management; V10 OAuth and OIDC
3. Environment variablesV13 Configuration; V14 Data Protection
4. API endpointsV4 API and Web Service; V8 Authorization; V1 Encoding and Sanitization; V2 Validation and Business Logic
5. Stripe and paymentsV4 API and Web Service; V2 Validation and Business Logic
6. Code and dependenciesV15 Secure Coding and Architecture; V13 Configuration
Deploy, headers and monitoringV3 Web Frontend Security; V12 Secure Communication; V16 Security Logging and Error Handling

Pre-launch sign-off sheet

Print the checklist. Go item by item. For each one, open the relevant tool (Supabase dashboard, Stripe dashboard, your code editor) and verify. Do not guess, and do not assume the AI did it. Then fill in one row per section and launch only when every row has evidence and a name:

SectionChecks passedEvidence (screenshot, test, log)Signed off by / date
1. Supabase RLS (6)__ / __  
2. Authentication (5)__ / __  
3. Environment variables (4)__ / __  
4. API endpoints (4)__ / __  
5. Stripe and payments (4)__ / __  
6. Code and dependencies (2)__ / __  
Deploy, headers and monitoring__ / __  

If an item feels ambiguous or you cannot verify it yourself, get a second reviewer. Our $49 async repo audit returns a written review with severity-ranked issues in 48 hours, and the $499 Security Audit covers RLS, secrets and OWASP checks in 48 hours to 3 days.

See how rescue works →

Sources

Sources and vendor defaults checked 4 November 2026.

Related reading

Is AI-built code safe for production? · Bolt.new security guide · Replit data leak risks · Supabase RLS SaaS blueprint

FAQ
How do I secure AI-generated code?
Treat it like code from a new contractor: review it before it ships. Enable Supabase RLS with owner-checking policies on every table, keep secret keys out of NEXT_PUBLIC_ and VITE_ variables, check auth and ownership server-side on every route, verify Stripe webhook signatures, run npm audit, and search the code for hardcoded keys and debug bypasses.
What are vibe coding security best practices?
Read every diff the AI produces before you accept it, ask for the security-relevant parts (policies, auth checks, webhook handlers) explicitly instead of assuming them, test as a second user and as a logged-out visitor, keep secrets server-side, and run this checklist again after every large AI-generated change, not only before the first launch.
How do I secure a Lovable app?
Most Lovable apps run on Supabase, so start with RLS: every table needs RLS enabled and policies that compare auth.uid() to the row owner. Then check that no service role key or other secret reaches the browser, that protected pages check auth server-side, and that Storage buckets have their own policies. Fix what Lovable's pre-publish security scan flags before you publish.
Do I need a security audit before launch?
If the app stores personal data or takes payments, yes. You can run this checklist yourself, but a second reviewer who did not prompt the code finds what you skimmed past. Our $49 async repo audit returns a written review in 48 hours, and the $499 Security Audit covers RLS, secrets and OWASP checks in 48 hours to 3 days.
Which of these 25 checks is most critical?
Supabase RLS, specifically whether every table has SELECT policies that check auth.uid() = user_id. Without them, the anon key shipped in every browser can read rows it should not. Matt Palmer's 2025 scan (CVE-2025-48757) found inadequate RLS settings in 170 of 1,645 Lovable projects it checked.
How long does it take to run these 25 checks?
A developer who knows Supabase and Stripe can work through the list in an afternoon. Testing each RLS policy with a real second-user token and replaying Stripe test events takes longest.
Do AI builders ever pass this checklist without human review?
Do not count on it. AI builders get some items right some of the time, but RLS policies, webhook verification, API auth and env var hygiene each depend on details the prompt rarely states. Verify every item yourself rather than assuming the builder handled it.
My app passed all 25 checks. Is it production-ready?
Probably yes for a basic launch. This checklist covers the failure modes that cause breaches and financial errors. It doesn't cover performance (N+1 queries), observability (error monitoring, logging), or maintainability (test coverage, code organization). Those matter less for day one and more for month six.
Can I run these checks myself?
Yes — that's why we published this list. For each item, there's a Supabase dashboard check, a code search pattern, or a Stripe CLI command. If you're comfortable in the Supabase dashboard and can read TypeScript, you can run most of these in an afternoon. What we do that's harder to do yourself: test each RLS policy with a real user token, verify the webhook handler with a Stripe CLI test, and read the code with fresh eyes for hardcoded values the AI buried in a file you haven't looked at.
Next step

Get a $49 audit before you launch

Send your repo URL and a 2-sentence description. We return a written audit with severity-ranked issues and fix-cost estimates in 48 hours, which also scopes the deeper $499 Security Audit if you need it.

Get the $49 audit