Fixing Leaked OpenAI / Anthropic Keys in Client Code
Exposing an OpenAI (sk-proj-*) or Anthropic API key in frontend JavaScript is the fastest way to wake up to a $1,000+ overnight bill. Bots scrape newly deployed SPAs specifically hunting for LLM keys.
Many tutorials and AI builders use `dangerouslyAllowBrowser: true` in the OpenAI SDK to avoid setting up a backend route — effectively handing your credit card to every visitor.
- Automated key harvesters max out your OpenAI monthly spend limit within minutes
- Provider safety systems may revoke your key mid-launch, breaking your live app
- Exposes your system prompts and lets attackers abuse your account for policy-violating content
Vulnerable Pattern vs. Production Fix
// src/components/AiWriter.tsx — CRITICAL LEAK
import OpenAI from "openai";
const client = new OpenAI({
apiKey: import.meta.env.VITE_OPENAI_API_KEY, // Visible in DevTools!
dangerouslyAllowBrowser: true,
});// app/api/generate/route.ts — SERVER ONLY
import { requireSession } from "@/lib/auth";
import { enforceRateLimit } from "@/lib/ratelimit";
export async function POST(req: Request) {
const session = await requireSession();
const limit = await enforceRateLimit(`ai:${session.user.id}`, 15, 60);
if (!limit.ok) return Response.json({ error: "Too many requests" }, { status: 429 });
const { prompt } = (await req.json()) as { prompt?: string };
if (!prompt || prompt.length > 2000) {
return Response.json({ error: "Prompt must be 1–2000 chars" }, { status: 400 });
}
const res = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`, // Server-only!
},
body: JSON.stringify({
model: "gpt-4o-mini",
max_tokens: 600,
messages: [{ role: "user", content: prompt }],
}),
});
return Response.json(await res.json());
}Copy-Paste AI Fix Prompt (Cursor · Lovable · Bolt · Claude Code)
Eliminate all client-side LLM API key leaks in this repo: 1. Remove dangerouslyAllowBrowser: true and delete any VITE_OPENAI_API_KEY, NEXT_PUBLIC_OPENAI_API_KEY, or client Anthropic/Gemini keys. 2. Create an authenticated server-side API route (or Supabase Edge Function) using server-only OPENAI_API_KEY. 3. Add prompt length validation, max_tokens caps, and per-user rate limiting on the proxy endpoint. 4. Update the React frontend to call our internal proxy route instead of api.openai.com directly.
How to Verify Your Fix Worked
- 1Revoke the exposed key in platform.openai.com/api-keys and set a strict monthly hard spend cap.
- 2Build your app and verify zero `sk-proj-` or `sk-` strings exist in the generated JS bundle.
- 3Re-scan with VibeSecCheck to confirm the Client-Side Secret Leak check passes.
Frequently Asked Questions
Why does the OpenAI SDK have a dangerouslyAllowBrowser option?
It exists solely for bring-your-own-key (BYOK) local tools where end users paste their own personal key. It should NEVER be used with your SaaS's API key.
Should I set monthly usage limits in OpenAI/Anthropic even after moving keys to the server?
Yes! Always configure hard monthly spend caps and email alerts in your AI provider billing settings as a safety net against bugs or runaway loops.
Does VibeSecCheck echo full leaked keys if it finds one?
Never. VibeSecCheck masks detected patterns (e.g., sk-proj-***[REDACTED]) so sensitive secrets are never logged or displayed in full.