Your first check is free. No card needed.Run a free security check

How to stop strangers running up your AI bill through your app

Treat your AI endpoint like a paid API you resell: refuse every request without a verified sign-in, count each user's requests on the server and stop them at a daily limit. Fix the model, the instructions and the maximum output tokens in server code, so the browser only sends the user's message. Then set a hard spend limit with your AI provider as the last line, because spend alerts alone do not stop traffic.

Imagine opening your OpenAI usage page on a Monday and seeing a line that went vertical on Saturday night. Your key never left the server. Someone opened the Network tab, copied the request your chat box sends to your Edge Function, and replayed it from a script, with your instructions swapped for theirs and the output length raised as high as the model allows.

That is the problem after the leaked key, and it is easier to miss because the code looks right: the secret sits in a server variable, exactly as the guide to an exposed API key recommends. The endpoint in front of it is the open door.

Why is my endpoint open if the key is on the server?

Because the endpoint does whatever the request asks. Moving the key to the server stops people from copying it. It does nothing to stop them from using your server as a free relay to the same model, on your bill. OWASP lists this as LLM10:2025 Unbounded Consumption and names one form of it "Denial of Wallet": high volumes of requests that run up cost-per-use charges.

Five gaps show up again and again in AI features built quickly:

  • No sign-in check, or one the public key passes. On Supabase, Edge Functions check the Authorization header by default, but Supabase's own docs say publishable and secret keys "are not JWTs, but the check still accepts them", and that "the check alone doesn't authenticate a caller that sends only an API key" (Supabase: Authorization headers). Your publishable key is in every visitor's browser.
  • No per-user limit. One account can send ten thousand requests as easily as ten.
  • The browser chooses the model, the maximum output and the whole prompt, including the system message.
  • CORS is treated as protection. CORS is a rule that browsers apply to scripts running on web pages (MDN: CORS). A script run from a terminal never asks for permission. Our CORS guide covers what it is actually for.
  • A free tier anyone can join again and again, with a throwaway email each time.

What does the broken version look like?

This is the shape of many generated chat functions. It works, and the key stays secret:

// supabase/functions/chat/index.ts (the version to replace)
Deno.serve(async (req) => {
  const { messages, model, max_tokens } = await req.json()
  const r = await fetch("https://api.openai.com/v1/chat/completions", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${Deno.env.get("OPENAI_API_KEY")}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ model, max_tokens, messages }),
  })
  return new Response(await r.text(), {
    headers: { "Access-Control-Allow-Origin": "*" },
  })
})

Nothing asks who is calling. model, max_tokens and messages come straight from the request, so a caller can pick your most expensive model, ask for the longest possible answer and replace your system message with their own work. The CORS header is irrelevant outside a browser.

How do I fix it on the server?

The browser should send one thing: the user's message.

1. Count usage in a table the browser cannot touch

create table public.ai_usage (
  user_id uuid not null references auth.users on delete cascade,
  day date not null default current_date,
  requests int not null default 0,
  primary key (user_id, day)
);
alter table public.ai_usage enable row level security;
-- no policies: the browser can neither read nor write this table

create or replace function public.take_ai_credit()
returns boolean
language sql
security definer
set search_path = ''
as $$
  insert into public.ai_usage (user_id, day, requests)
  values (auth.uid(), current_date, 1)
  on conflict (user_id, day)
  do update set requests = public.ai_usage.requests + 1
  where public.ai_usage.requests < 50   -- the daily limit
  returning true;
$$;

The function adds one to today's count for the signed-in user and returns nothing once they reach 50. The limit lives in the database, so no request can change it.

2. Check the user, cap the input, then count

// supabase/functions/chat/index.ts (the fixed version)
import { createClient } from "npm:@supabase/supabase-js@2"
import OpenAI from "npm:openai"

const INSTRUCTIONS = "You answer questions about recipes saved in this app. Keep answers short."
const MODEL = Deno.env.get("OPENAI_MODEL")! // set by you, never by the request
const MAX_OUTPUT_TOKENS = 600
const MAX_INPUT_CHARS = 4000
const openai = new OpenAI({ apiKey: Deno.env.get("OPENAI_API_KEY") })

Deno.serve(async (req) => {
  const auth = req.headers.get("Authorization") ?? ""
  const supabase = createClient(
    Deno.env.get("SUPABASE_URL")!,
    Deno.env.get("SUPABASE_ANON_KEY")!, // or your publishable key
    { global: { headers: { Authorization: auth } } },
  )

  // A real signed-in user, not the public key
  const { data, error } = await supabase.auth.getClaims(auth.replace("Bearer ", ""))
  const claims = data?.claims
  if (error || !claims?.sub || claims.role !== "authenticated" || claims.is_anonymous) {
    return new Response("Sign in first", { status: 401 })
  }

  const { message } = await req.json()
  if (typeof message !== "string" || !message || message.length > MAX_INPUT_CHARS) {
    return new Response("Message missing or too long", { status: 413 })
  }

  const { data: allowed } = await supabase.rpc("take_ai_credit")
  if (allowed !== true) return new Response("Daily limit reached", { status: 429 })

  const r = await openai.responses.create({
    model: MODEL,
    instructions: INSTRUCTIONS,
    input: message,
    max_output_tokens: MAX_OUTPUT_TOKENS,
  })
  return Response.json({ reply: r.output_text })
})

3. Know why each line is there

  • getClaims verifies the token's signature (Supabase: getClaims). A signed-in user's token has role set to authenticated and their user id in sub; a token made from the anon key has role set to anon and no sub (Supabase: JWT fields). The is_anonymous check matters if you turned on anonymous sign-ins.
  • instructions is OpenAI's field for a system message, and max_output_tokens is an upper bound on generated tokens, reasoning tokens included (OpenAI API reference: create a response). Both now live in code the browser never sees.
  • The count happens before any money is spent.

Using Next.js instead? The same three checks go at the top of the route handler or server action, before the call to the provider. Our fix prompt for routes that require sign-in by default gives your AI coding tool the instruction in one paste.

What limits can I set with OpenAI and Anthropic?

Set these today. They do not replace the checks above: they cap the damage if something slips past them.

OpenAI. Organizations and projects can have a monthly spend limit. With Enforce a hard limit turned on, requests fail with a 429 and the code project_spend_limit_exceeded once tracked spend reaches it. Without it, the limit only notifies you. OpenAI also says enforcement is not instantaneous, so spend can slightly exceed the amount (OpenAI: Spend limits). Its key safety page puts it plainly: "Spend alerts alone don't stop API traffic" (OpenAI Help Center). Each project can also restrict which models it may use and set a rate limit per model, and a key created in a project is scoped to that project (OpenAI Help Center: projects).

Anthropic. You can set an organization spend limit below your usage tier's monthly cap. When usage reaches it, requests return HTTP 400 with invalid_request_error until the limit resets or you raise it. Workspaces can have their own lower spend and rate limits, though Anthropic notes that a spend limit on the default workspace might not count some usage, such as the Console playground (Claude docs: Rate limits).

Our rule of thumb: one project or workspace per app and per environment, each with its own key and its own hard limit. A staging bug or a key on a laptop then cannot spend production's budget. After you set a limit, check on a throwaway project that hitting it really returns the error you expect.

How do I stop endless free sign-ups?

A per-user quota only works if a user is hard to mint. Supabase Auth supports hCaptcha and Cloudflare Turnstile on sign-up, sign-in and password reset forms, under Bot and Abuse Protection in the dashboard (Supabase: CAPTCHA). Turn on Confirm email so users confirm their address before they can sign in (Supabase: General configuration).

Then size the free quota so that a hundred fake accounts cost you an amount you can shrug at. Work it out from your own numbers: daily limit, times the maximum output you allow, times your model's price. Limits on sign-up and password reset requests per IP address help too; the login rate limiting guide shows how to test them.

How will I notice before the invoice does?

Your ai_usage table is already a log. Once a day, look at the heaviest users:

select user_id, requests
from public.ai_usage
where day = current_date
order by requests desc
limit 10;

A user at the limit every day is either your best customer or a script. Compare the total with the provider's Usage page. If the provider shows far more requests than your table, something calls the provider without going through your counter, and that something is the next thing to find.

What we would skip: hiding the endpoint's address, renaming the function, or locking CORS down and calling it done. None of those changes what a request from a terminal can do.

Try it on your own app

Call your own AI endpoint from a terminal, signed out:

curl -i -X POST https://YOUR-PROJECT.supabase.co/functions/v1/chat \
  -H "Content-Type: application/json" \
  -d '{"message":"hello"}'

curl -i -X POST https://YOUR-PROJECT.supabase.co/functions/v1/chat \
  -H "Authorization: Bearer YOUR_PUBLISHABLE_KEY" \
  -H "Content-Type: application/json" \
  -d '{"message":"hello"}'

Both should answer 401. If either one returns a reply from the model, the endpoint is open. Then, signed in as a test user, add "model" and "max_tokens" fields to the body and confirm nothing changes, and send requests until you see the 429. Run that last part on a staging copy if you can, since each request costs a little.

Where does Saqr fit?

If you would rather not do this by hand on every release, a Saqr Full task tests your live app in a real browser and looks for AI or paid endpoints anyone can call without sign-in or limits, with a small rate-limit check on one API endpoint at the end. Every finding comes with the request and response that prove it, and a fix prompt for your AI coding tool. Your first Quick check is free, no card needed.

Saqr (usesaqr.com) is AI security for web apps. Its AI agents attack your live app from the outside, the way a real attacker would, and show you exactly what to fix. From $19 a month, cancel any time. Tests only apps you have shown are yours.

Questions

Is a hard spend limit enough on its own?

No. It caps the loss, but when one person burns through it your AI feature stops working for every other user until the limit resets. Per-user quotas keep one account from using everyone's budget.

Can I keep the rate limit counter in memory inside the function?

Not reliably. Serverless functions can run as several instances at once and each one starts with empty memory, so a counter in a variable is neither shared nor kept. Store the count in your database or a key-value store.

What daily limit should I pick?

Start from cost, not from a round number. Multiply the daily limit by the maximum output tokens you allow and your model's price, and pick the number you would happily pay for every free account, including fake ones.

Does this apply to Anthropic, Gemini or other providers?

Yes. The risk sits in your endpoint, not in the provider. Any server route that calls a paid model needs the same sign-in check, server-side quota and fixed model settings.

Should paying users have no limit?

Give them a higher limit, not none. A stolen session or a buggy loop in your own front end can still send thousands of requests, and a generous ceiling costs real customers nothing.