Dev.to Security 🔐 Cybersecurity 👁 2 📖 3 min read

Your OpenAI key is sitting in the JavaScript every visitor downloads

When you prototype an AI feature in Lovable, Bolt, Cursor or a quick React app, the fastest path to a working demo is a direct fetch("https://api.openai.com/v1/chat/completions") from the browser. It works in five minut

When you prototype an AI feature in Lovable, Bolt, Cursor or a quick React app, the fastest path to a working demo is a direct fetch("https://api.openai.com/v1/chat/completions") from the browser.

It works in five minutes. It also ships your secret API key inside the JavaScript bundle every single visitor downloads.

The leak takes ten seconds to verify

Here is the vulnerable client file from my open-source lab (labs/02-key-in-bundle/lab.py):

const OPENAI_KEY = "sk-proj-FAKE0LAB1KEY2DO3NOT4USE5abcdefgh";
go.onclick = async () => {
  const r = await fetch("https://api.openai.com/v1/chat/completions", {
    method: "POST",
    headers: {
      "Authorization": "Bearer " + OPENAI_KEY,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      model: "gpt-4o-mini",
      messages: [{ role: "user", content: q.value }]
    })
  });
  a.textContent = (await r.json()).choices[0].message.content;
};

You do not need a hacker to find this. Any visitor opens DevTools → Sources (or runs curl on assets/app.js) and copies the key. Even if you put the key in a .env file with a VITE_ or NEXT_PUBLIC_ prefix, your bundler still inlines that exact value into the client JavaScript at build time.

Once a secret ships to the browser, two things happen:

  1. Anyone can run their own workload on your OpenAI, Anthropic or Stripe bill until your spend limit hits.
  2. Bots continuously scrape public bundles and Git commits for sk-, sk_live_ and service_role tokens.

The fix: one small server proxy with a rate limit

Move the key into a server-side endpoint. The browser calls /api/chat on your own origin; the server reads the key from an environment variable, applies a per-IP or per-user rate limit, and forwards the request upstream.

Client side (zero secrets):

go.onclick = async () => {
  const r = await fetch("/api/chat", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ question: q.value })
  });
  a.textContent = (await r.json()).answer;
};

Server side (minimal Python handler from the lab, same pattern applies in Next.js Route Handlers, Cloudflare Workers or Supabase Edge Functions):

ip = self.client_address[0]
counts[ip] = counts.get(ip, 0) + 1
if counts[ip] > limit:
    return self.send_error(429, "rate limit")

q = json.loads(self.rfile.read(int(self.headers["Content-Length"])))["question"][:2000]
req = urllib.request.Request(
    upstream,
    data=json.dumps({"model": "gpt-4o-mini", "messages": [{"role": "user", "content": q}]}).encode(),
    headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"}
)

Notice two details that prototypes usually skip:

  • Input cap ([:2000]): prevents someone from sending 100k-token prompts through your proxy.
  • Rate limit (429): moving the key off the client without a rate limit still leaves an open proxy anyone can abuse.

Verify the built bundle — then rotate the old key

Do not assume a refactor cleaned your bundle. Scan the actual built dist/ folder and run a repeatable self-test:

python3 lab.py --selftest
# {"scan": {"vulnerable": ["secret.client_side"], "fixed": []},
#  "key_in_served_files": false, "proxy_answer": "hello from the stub",
#  "upstream_got_key": true, "rate_limited_3rd_call": true}
# SELFTEST OK

One step people forget: rotating the key that already shipped. Removing a key from app.js stops future downloads, not copies already sitting in CDN caches, browser caches or scrape logs. Revoke the old key, generate a new one server-side only, and set a hard monthly spend limit in your provider dashboard.

Four checks before you launch

  1. Grep your built dist/ or .next/static/ output for sk-, sk_live_, AIza, service_role and ghp_.
  2. Audit every VITE_* and NEXT_PUBLIC_* variable — treat every single one as public.
  3. Add rate limiting and input length caps to every AI proxy route.
  4. Rotate any key that ever touched a client bundle or a public Git commit.

The lab and scanner

This lab (labs/02-key-in-bundle), the offline bundle scanner, and the two other labs (Supabase row-level security and indirect prompt injection in an e-mail agent) are open source: https://github.com/mikebillnova-create/ai-app-security-check

If you are shipping an AI-built app and want a manual pre-launch check with PR-ready patches and a free re-test, there is a free public exposure check and a 48-hour Light Audit (€199, €0 if no confirmed issues are found) here: https://ai-app-security.pages.dev

The lab uses a fake key and a local stub server. Never scan or test systems you do not own or have written permission to test.

📰 Read the original article on Dev.to Security

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