</>RescueMyRepoFree scan

// guide · AI costs · published Nov 23, 2026

Can a bot drain your OpenAI credits? Lock down the AI endpoint in your vibe-coded app

Short answer

Moving your OpenAI key to the server is step one, not the finish line. If the route or Edge Function that uses it doesn't check for a real signed-in user and limit how often each user can call it, a script can spend your credits all night. If your app uses Supabase anonymous sign-ins, a getUser() check isn't enough either: anonymous users pass it, and a bot can create a fresh one per request. Reject user.is_anonymous, add a per-user limit, cap max_tokens, and set a budget at your AI provider.

Why this happens in AI-built apps

When you ask Lovable, Bolt, Cursor or Claude Code for an AI feature, the result usually works on the first try: a server route or Supabase Edge Function with your key in server env. That fixes the leaked-key problem, but the endpoint itself is public. OWASP lists this as API4, unrestricted resource consumption (OWASP). As one builder put it on X this week: “someone scripting anon sign ups to drain your openai credits hurts way more than a leaked row.”

// supabase/functions/generate/index.ts: what AI tools often generate
Deno.serve(async (req) => {
  const { prompt } = await req.json();             // anyone can send anything
  const openai = new OpenAI({ apiKey: Deno.env.get("OPENAI_API_KEY") });
  const r = await openai.chat.completions.create({
    model: "gpt-4o", messages: [{ role: "user", content: prompt }],   // no max_tokens
  });
  return new Response(JSON.stringify(r));
});
// The key is safely server-side... and anyone can spend it.

Supabase's default verify_jwt on Edge Functions doesn't save you here: it checks that the caller has a valid JWT for your project, and the public anon key in your frontend is one (Supabase Edge Function auth).

The anonymous sign-in trap

Anonymous sign-ins let visitors try your app without an email. Supabase's docs are explicit: anonymous users use the authenticated Postgres role like permanent users, and their JWT carries an is_anonymous claim you have to check yourself (Supabase anonymous sign-ins). So an AI route that only does if (!user) return 401 lets every anonymous visitor in, and a per-user limit resets each time a bot calls signInAnonymously() again. Supabase limits anonymous sign-ins to 30 per hour per IP by default and recommends CAPTCHA or Turnstile (rate limits), but attackers rotate IPs, so the AI call itself needs the check.

Test it on your own app in 2 minutes

Only test endpoints you own. Use a short prompt so the test costs almost nothing:

# Your OWN app only. 1) No login at all:
curl -i -X POST "https://<project>.supabase.co/functions/v1/generate" \
  -H "Authorization: Bearer <your public anon key>" \
  -H "Content-Type: application/json" -d '{"prompt":"say hi"}'
# An AI answer here = anyone on the internet can spend your credits.

# 2) As an anonymous user (only if your app uses anonymous sign-ins),
#    in the browser console of your app:
#    const { data } = await supabase.auth.signInAnonymously();
#    await supabase.functions.invoke("generate", { body: { prompt: "say hi" } });
# An AI answer here = a script can mint a new user per request.

The fix

1. Require a real user and reject anonymous ones, 2. count requests per user, 3. cap input and output size. In a Supabase Edge Function:

// supabase/functions/generate/index.ts
import OpenAI from "npm:openai";
import { createClient } from "npm:@supabase/supabase-js@2";

Deno.serve(async (req) => {
  const auth = req.headers.get("Authorization") ?? "";
  const supabase = createClient(Deno.env.get("SUPABASE_URL")!, Deno.env.get("SUPABASE_ANON_KEY")!,
    { global: { headers: { Authorization: auth } } });
  const { data: { user } } = await supabase.auth.getUser(auth.replace("Bearer ", ""));
  if (!user) return new Response("Sign in first", { status: 401 });
  if (user.is_anonymous) return new Response("Create an account to use AI features", { status: 403 });

  const admin = createClient(Deno.env.get("SUPABASE_URL")!, Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!);
  const { data: allowed } = await admin.rpc("take_ai_credit", { p_user: user.id, p_per_hour: 20 });
  if (!allowed) return new Response("Too many requests, try again later", { status: 429 });

  const { prompt } = await req.json();
  if (typeof prompt !== "string" || prompt.length > 4000) return new Response("Prompt too long", { status: 400 });
  const openai = new OpenAI({ apiKey: Deno.env.get("OPENAI_API_KEY") });
  const r = await openai.chat.completions.create({
    model: "gpt-4o-mini", max_tokens: 800, messages: [{ role: "user", content: prompt }],
  });
  return Response.json({ text: r.choices[0].message.content });
});

The limiter it calls is one table and one function. Clients can't read, write or call it; only your function with the service role key can:

-- A tiny per-user limiter in Postgres (no extra service needed)
create table public.ai_usage (
  id bigint generated always as identity primary key,
  user_id uuid not null references auth.users(id) on delete cascade,
  created_at timestamptz not null default now()
);
create index on public.ai_usage (user_id, created_at);
alter table public.ai_usage enable row level security;   -- no policies: clients can't touch it

create or replace function public.take_ai_credit(p_user uuid, p_per_hour int)
returns boolean language plpgsql security definer set search_path = '' as $$
begin
  perform pg_advisory_xact_lock(hashtext(p_user::text));
  if (select count(*) from public.ai_usage
      where user_id = p_user and created_at > now() - interval '1 hour') >= p_per_hour then
    return false;
  end if;
  insert into public.ai_usage (user_id) values (p_user);
  return true;
end $$;
revoke execute on function public.take_ai_credit(uuid, int) from public, anon, authenticated;

In Next.js, the same thing with Upstash Ratelimit (docs), a common choice on Vercel:

// app/api/chat/route.ts (Next.js) with Upstash Ratelimit
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
import { createClient } from "@/lib/supabase/server";

const ratelimit = new Ratelimit({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(20, "1 h") });

export async function POST(req: Request) {
  const supabase = await createClient();
  const { data: { user } } = await supabase.auth.getUser();
  if (!user || user.is_anonymous) return new Response("Sign in first", { status: 401 });
  const { success } = await ratelimit.limit(user.id);
  if (!success) return new Response("Too many requests", { status: 429 });
  // ...validate input length, call the model with max_tokens set
}

If anonymous visitors must get a free taste, give them their own small quota keyed by IP (for example 3 requests per day), a cheaper model and a lower max_tokens, and turn on CAPTCHA/Turnstile for anonymous sign-ins in your Supabase Auth settings.

4. Set a seatbelt at the provider. In your AI provider's dashboard, set a monthly budget and usage alerts, and use a separate API key per project so you can see and revoke one app's usage without breaking the others.

Tell your AI coding tool

Paste this into Lovable, Bolt, Cursor or Claude Code:

Audit this app for AI cost abuse ("denial of wallet").
1. List every server route, server action and supabase/functions/* file that calls OpenAI, Anthropic, Gemini, Groq, xAI, OpenRouter, the Lovable AI gateway or the Vercel AI SDK.
2. For each one: require a signed-in user verified on the server (supabase.auth.getUser() with the caller's token) and return 401 if missing. If the app uses Supabase anonymous sign-ins, also return 403 when user.is_anonymous is true.
3. Add a per-user rate limit (20 requests/hour and a daily cap) using a Postgres usage table with a security definer function only the service role can execute, or Upstash Ratelimit; return 429 when exceeded.
4. Set max_tokens on every model call and reject inputs over 4,000 characters.
5. Keep every AI key in server env only (no VITE_ / NEXT_PUBLIC_ prefix, no dangerouslyAllowBrowser).
6. Show me the diff and how to test: a logged-out curl and an anonymous session must both get 401/403, and the 21st request in an hour must get 429.

Check your repo automatically

RescueMyRepo's free scan finds server routes and Supabase Edge Functions that call paid AI APIs and flags ones with no user check (high), no rate-limit logic (medium), and, new today, routes that check the Supabase user but let anonymous users through while your app turns on anonymous sign-ins (medium). Each finding comes with a fix prompt. It also flags AI SDKs called from the browser, leaked keys, open Supabase tables and unverified Stripe webhooks.

Scan my repo freePublic GitHub repos · no signup · about a minute

FAQ

My AI route checks supabase.auth.getUser(). Isn't that enough?

Only if every user had to sign up. If your app uses Supabase anonymous sign-ins (signInAnonymously(), or enable_anonymous_sign_ins = true in supabase/config.toml), anonymous users get a real session and the authenticated role, so getUser() returns a user for them. A script can create a new anonymous user before each request. Reject user.is_anonymous on paid AI routes, or give anonymous visitors a small separate quota.

Doesn't Supabase rate-limit anonymous sign-ins?

Yes. Supabase documents an IP-based limit of 30 anonymous sign-ins per hour by default and strongly recommends invisible CAPTCHA or Cloudflare Turnstile. That slows a single machine down, but it doesn't help if each anonymous user can make unlimited AI calls, and attackers rotate IPs. Limit the AI calls themselves.

My Edge Function has verify_jwt on. Is it protected?

Not by itself. The default JWT check only proves the caller has a valid token for your project, and your public anon key works for that. Call supabase.auth.getUser() with the caller's Authorization header inside the function and return 401 when there is no signed-in (non-anonymous) user.

What should the rate limit be?

Start with what a real user needs: for a chat or generate button, something like 20 requests per user per hour plus a daily cap, a max_tokens limit on every call, and a maximum input length. Return HTTP 429 when the limit is hit. Raise the numbers for paid plans, read from a table users can't edit.

Is a spend limit at OpenAI or Anthropic enough?

It's the seatbelt, not the brakes. Set a monthly budget and usage alerts in your AI provider's dashboard and use a separate key per project, so a leak or abuse is noticed and capped. But hitting the cap also breaks the app for every real user, so the per-user limits in your code are what actually stop one abuser.

Does RescueMyRepo detect this?

Yes. The free scan finds server routes and Supabase Edge Functions that call OpenAI, Anthropic, Gemini, Groq, xAI, OpenRouter, the Lovable AI gateway or the Vercel AI SDK and flags ones with no user check (high), no rate-limit logic (medium), and, new on Nov 23, 2026, routes that check the Supabase user but let anonymous users through while the app turns on anonymous sign-ins (medium). It also flags AI SDKs called from the browser with your key.

Sources