Solo developers don't leak keys carelessly — they leak them structurally
Almost nobody leaks an API key out of recklessness. It happens because a solo developer is the whole team: you write the code, run the deploy, keep the notes, and test the demo at 11pm. In that setup a key ends up in three places at once — a .env in one side project, a notebook in another, a curl line in shell history — and there is nobody reviewing the diff that would have caught it.
That leaves two failure modes worth designing against. The silent leak: the key keeps working, someone else's traffic runs on your balance, and you notice weeks later. The loud break: you revoke a key and something you forgot about dies on a Sunday. Good key management makes both cheap — every key is identifiable, rotatable, and killable in under a minute.
You don't need a vault or a security team to get there. You need four habits, each finishable in an afternoon.
Habit 1 — One key per purpose, named after the purpose
A single key shared by five scripts is effectively unrotatable: every rotation becomes an outage across every project, so you postpone it forever. The fix is boring — mint one key per app and per environment, and name it after what it does. On AiCredits you can create and revoke keys independently in the dashboard, so a per-app key costs a click, not a budget line.
Two details in the snippet below do most of the work. There is no hardcoded fallback — os.environ.get("KEY", "sk-live-...") is exactly how a key becomes permanent. And the failure is loud: a missing or malformed key stops the script instead of silently spending.
import os
from openai import OpenAI
BASE_URL = "https://api.aicreditsapi.com/v1"
def get_client(purpose: str = "dev") -> OpenAI:
"""purpose is a key name: 'dev', 'prod', 'scratch'."""
key = os.environ.get(f"AICREDITS_KEY_{purpose.upper()}")
if not key:
raise RuntimeError(f"Set AICREDITS_KEY_{purpose.upper()} before running this")
key = key.strip()
if len(key) < 20 or " " in key:
raise RuntimeError("Malformed key - check for a trailing newline or a pasted prefix")
return OpenAI(api_key=key, base_url=BASE_URL)
if __name__ == "__main__":
client = get_client("dev")
resp = client.chat.completions.create(
model="deepseek-v4-flash",
messages=[{"role": "user", "content": "List three risks of shipping an API key in a frontend bundle."}],
)
print(resp.choices[0].message.content)
Use deepseek-v4-flash for development — it's the fast default and the one you want behind a runaway loop. Reserve deepseek-v4-pro for tasks that genuinely need stronger reasoning, since pro costs more per call than flash. Current rates live on aicreditsapi.com/pricing rather than in anyone's blog post, including this one.
Habit 2 — Make committing a key impossible, not unlikely
Write .gitignore before the first commit, add a .env.example with empty values so future-you knows what's required, and then enforce it with a hook. Intention is not enforcement; a pre-commit check is.
#!/usr/bin/env python3
"""Pre-commit guard: block staged files that look like they contain live keys."""
import re
import subprocess
import sys
PATTERNS = [
re.compile(r"sk-[A-Za-z0-9_\-]{16,}"),
re.compile(r"(?i)(api[_-]?key|secret|token)\s*[:=]\s*['\"][^'\"]{16,}['\"]"),
]
SKIP = re.compile(r"(\.env\.example|\.md)$")
staged = subprocess.run(
["git", "diff", "--cached", "--name-only", "--diff-filter=ACM"],
capture_output=True, text=True, check=True,
).stdout.split()
hits = []
for path in staged:
if SKIP.search(path):
continue
try:
text = open(path, encoding="utf-8", errors="ignore").read()
except OSError:
continue
for lineno, line in enumerate(text.splitlines(), 1):
if any(p.search(line) for p in PATTERNS):
hits.append(f"{path}:{lineno}: {line.strip()[:70]}")
if hits:
print("Commit blocked - possible secrets:\n " + "\n ".join(hits))
print("Move them to .env, or use git commit --no-verify if this is a false positive.")
sys.exit(1)
Install it once with cp scripts/check_secrets.py .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit, then run the same scan in CI — hooks are per-clone, and --no-verify exists.
The scanner is deliberately dumb. It flags any 16+ character value assigned to key/secret/token, not just AiCredits keys. That's the point: heuristics catch what humans skim past.
A false positive costs five seconds — rename the variable or use a placeholder like
sk-test-not-a-real-keyin docs. A false negative costs a balance.Layer it. Add gitleaks or detect-secrets in CI for entropy checks; they complement the hook rather than replace it.
Keep real values in
.envonly, and inject production keys from your host's secret store so they never touch disk.
Habit 3 — Rotate without downtime by keeping a spare key warm
Rotation only feels scary because most people rotate by deleting the only key they have. Do it in the other order: create key B, deploy it, confirm traffic flows, then revoke key A. To make that mechanical rather than heroic, let your code accept a key list and fail over on auth errors.
import os
from openai import AuthenticationError, OpenAI, RateLimitError
BASE_URL = "https://api.aicreditsapi.com/v1"
def ask(prompt: str, model: str = "deepseek-v4-flash") -> str:
keys = [k.strip() for k in os.environ.get("AICREDITS_API_KEYS", "").split(",") if k.strip()]
if not keys:
raise RuntimeError("AICREDITS_API_KEYS is empty")
failures = []
for i, key in enumerate(keys):
try:
resp = OpenAI(api_key=key, base_url=BASE_URL).chat.completions.create(
model=model,
messages=[{"role": "user", "content": prompt}],
)
return resp.choices[0].message.content
except AuthenticationError:
failures.append(f"key#{i} rejected (401) - revoke it in the dashboard")
except RateLimitError:
failures.append(f"key#{i} throttled (429) - back off instead")
raise RuntimeError("; ".join(failures))
if __name__ == "__main__":
print(ask("Explain in one sentence why cache hits are cheaper than fresh tokens."))
The distinction that keeps failover safe: a 401 means the key is dead and moving on is correct, while a 429 means you are being throttled and backing off beats hammering another key. Neither path should ever retry a request that already succeeded.
Rotate on a calendar, and immediately after anything that could have exposed a key: a screen share, a pushed branch, a lost laptop. A stale key isn't only a security problem — it's someone else's compute on your account.
Habit 4 — Never ship a key to the client
Browser bundles are plain text. Mobile apps decompile. Extensions can be read. Any key that reaches a client is public, and so-called restricted keys only narrow the damage.
Put a thin backend in front of the API. It holds the key, validates input, and rate-limits per user.
Separate staging and production keys so a load test can't exhaust the balance real users depend on.
For live demos, use a throwaway key with a small balance and revoke it the same day.
When a key leaks, revoke first and investigate second
The instinct is to confirm whether it was really exposed. Skip that. Revoking takes seconds and costs one redeploy; leaving it live costs whatever the key can reach.
Revoke in the dashboard, then rotate everything downstream (CI, deploy targets, cron jobs).
Check usage for calls you didn't make, especially off-hours traffic.
Search history with
git log -p -S 'sk-'. If the repo is public, rewrite history after revoking — deleting the commit alone leaves copies in forks and caches.Write down what broke, then fix the process rather than just the key.
The checklist you can finish today
| Risk | Fix that takes minutes | Where it lives |
|---|---|---|
| Key pasted into a notebook or chat | Move it to an env var and delete the paste | shell / .env |
| Key committed to git | Pre-commit secret scanner plus a CI scan | .git/hooks, CI |
| Key inside a JS bundle or mobile app | Call the API from your backend instead | architecture |
| One key shared by five scripts | One key per app and environment | AiCredits dashboard |
| Key printed in logs or stack traces | Redact key-shaped strings before logging | logging layer |
| Laptop lost or key screen-shared | Revoke first, recreate after | AiCredits dashboard |
Work top to bottom; every row is under ten minutes and removes a whole class of incident. All of it works with any OpenAI-compatible endpoint, including AiCredits — point the SDK at https://api.aicreditsapi.com/v1, mint one key per app, and check aicreditsapi.com/pricing before you scale up.
FAQ
Yes, provided the file is gitignored and never leaves your machine, and provided a pre-commit scanner backs up that promise. For production, inject the key from your host's secret store so the value never sits on disk at all.
Two per app — one for local development, one for production — plus a standby key if you want zero-downtime rotation. Extra keys are free to create and make revocation surgical instead of catastrophic.
No. Treat it as compromised the moment it hits a remote: forks, caches, and CI logs may already hold a copy. Revoke it in the dashboard first, then clean history and add the pre-commit scanner so the next commit can't repeat it.
No. Start with deepseek-v4-flash, the fast default, and switch to deepseek-v4-pro only when a task genuinely needs stronger reasoning — pro costs more per call. Keeping development on flash means a runaway loop stays cheap.
Not safely. Bundles and app binaries can be inspected, so any key shipped to a client is public. Put a small backend in front, hold the key there, and rate-limit per user.