Cost and Security: Three Lines of Defense—Keys, Bills, and Sandboxes
The answer up front: Vibe coding security isn't mysticism—it's three lines of defense you can set with your own hands: watch your keys, lock your bill, fence in your sandbox. Only after setting all three can you honestly say "this time I accept everything." This lesson condenses API key security, cost control, and command boundaries into a checklist you can walk through in 10 minutes.
Why does this lesson come after the review checklist? The red lines in Review Checklist check for "hidden mines in AI-written code"; this lesson goes a step further and looks at your own assets—API keys, bills, and the files on your computer. The real case from 7/2025 is worth repeating: Replit's AI agent deleted the production database even after the user explicitly said "do not make any changes" (see Vibe Coding Reliable or Not: Risks, Controversies, and Real Cases for details). Verbal prohibitions can't stop an AI; only system boundaries can.
This lesson is the fifth discipline set in Workflow Guide: "Set up cost and security defenses"—watch your keys, set billing caps, and use a sandbox whenever you can.
Works with all four tools (Claude Code, Codex, OpenCode, WorkBuddy), walkable in 10 minutes with zero background.
What You'll Be Able to Do
- Run a key security checkup on the API keys you have on hand: not hardcoded in code, not committed to a repository, knowing where they're stored and where they get sent
- Distinguish the risk differences among the three charging models—subscription, pay-as-you-go, and credits—set spending caps on pay-as-you-go channels, and know where to check how much you've spent this month
- Open the sandbox with
/sandboxin Claude Code and verify it truly holds with two probe commands; be able to say where Codex's sandbox is enabled by default - Walk through the two questions of data privacy and netizenship: does this project touch my private data? Could that data leave my machine?
Your Current Predicament
- You've heard plenty of scary stories: API keys leaked and used to run up bills, thousands of dollars in one night; an AI agent "taking initiative" and deleting the production database—but when it's your turn, you don't know what to defend against or how
- The tool gives you "full autonomy," yet you don't know which files on your computer its commands can touch: SSH keys, cloud service credentials, browser profiles—can it read them all?
- You want to set a spending cap for the AI but can't find the switch anywhere in the settings; the subscription feels capped, yet you've heard people still received sky-high bills
When to Use This Technique
When you need to:
- Secure your three assets—keys, bills, and file boundaries—before handing the project over to the AI with full autonomy
- Connect a pay-as-you-go API key for the first time (that's exactly how OpenCode connects to domestic Chinese models)
- Judge whether a new project deserves the original "accept everything" approach
And you don't want to:
- Discover only after a key leak that "the key was sitting in plaintext in the code all along"
- Find out from the month-end bill how many tokens the AI burned through in one night
- Have AI commands roam freely across your entire computer
🎒 Preparation Before You Start
- Finish reading Review Checklist: How to Check AI-Written Code Before Going Live—that lesson checks for mines in the code, this one looks at your assets; only together do they form a complete defense
- Have installed and used at least one tool: Claude Code, Codex, OpenCode or WorkBuddy
- Have your own API key or subscription account—if not, first read Price Comparison: How Much Do the Four Tools Cost; defenses only count when they land on a real account
- 10 minutes and a glass of water ☕
Core Idea
The essence of the three lines of defense: don't gamble on the AI not causing trouble; just make sure that even if it does, it can't hurt you. Engineer Simon Willison listed a security checklist for beginners in his "When is it OK to vibe code?" section; this lesson takes the three items you can actually "set up" and turns them into three lines of defense:
| Defense line | What it covers | Corresponding Willison checklist item | Consequence of not setting it |
|---|---|---|---|
| One: Keys | Storage and exposure surface of API keys, passwords, and tokens | Item 2 "watch your keys" | Keys hardcoded into code and exposed with the repository, used by others to run up your bill |
| Two: Bills | Spending caps and usage visibility for pay-as-you-go | Item 5 "money is live" | Vibe coding against an API with no billing cap, burning thousands of dollars in one night |
| Three: Sandbox | The file and network scope AI commands can touch | "Safety for beginners starts with a sandbox" | AI commands read the credentials in ~/.ssh and delete directories they shouldn't |
Two other items on the checklist don't rise to "defense line" level but take 30 seconds to get through: data privacy (item 3) and netizenship (item 4), covered in step 4 on this page; item 1 "low-risk projects" and item 6 "get someone to review" were already covered in Review Checklist—set the intensity based on "who it's for."
Why does a sandbox count as a defense line on its own? Willison's original words: "Safe vibe coding for complete beginners starts with a sandbox" — safe vibe coding for complete beginners starts with a sandbox. His positive example is Claude Artifacts: code is locked in an isolated environment, can only load approved libraries, and cannot make outbound network requests; at the same time he cautions that some other popular tools have "far fewer safety rails." The Claude Code and Codex you run on your own machine also have their own sandboxes — this lesson teaches you to turn them on and verify them.
A way to remember the division of labor among the three defense lines: Defense line one and defense line two guard against "losses," while defense line three guards against "overstepping boundaries." In the Replit case, what the AI crossed was the boundary — so don't pin your hopes on a "don't touch anything" instruction in the prompt; draw the boundary at the operating-system level.
Follow along with me
(Use the AI project you currently have on hand as the material, and walk through four steps: first check the keys, then lock the bill, then turn on the sandbox, and finally run two quick checks along the way.)
Step 1: Guard your API key security — don't hardcode it, don't commit it to the repo, know where it's stored
Why: Item 2 of Willison's checklist puts the key problem perfectly: things like API keys "look similar in shape to a password" (anything that looks similar in shape to a password). Once code involves a key, you must understand how that code works, otherwise it's easy to expose it unintentionally. Acceptance check has a red line checking "whether a key has been written into the code"; this step goes one step further, examining where the key is stored, its exposure surface, and where it goes.
Three rules — go through them one by one:
Rule one: don't hardcode. Keys are not hardcoded in the code; put them in environment variables or a config file. OpenCode's official way to connect a custom model provider is the model to follow — the config only contains the name of the environment variable, and the value stays in the environment:
"env": ["ACME_API_KEY"]Rule two: don't commit it to the repo. Files storing keys are not committed to the Git repository; before making a project public, do a global search for key, secret, token, password (Acceptance check step 3 red line one's search method — use it directly).
Rule three: know where it's stored and where it gets sent. The four tools store credentials differently:
| Tool | Where the key is stored | What you need to confirm |
|---|---|---|
| Claude Code | Official documentation: API keys and tokens are stored in the keychain on macOS, in a file with 0600 permissions on Linux, and inherit the user directory's access controls on Windows | The tool has already taken care of it for you — don't copy it into your project "for convenience" |
| Codex | Sign in with your ChatGPT account (Sign in with ChatGPT), no manual key management | There is no key to manage — the account itself is the credential |
| OpenCode | Paste the key in /connect, or connect an environment variable using the env approach above | The key you paste is usually billed by usage — this door leads straight to defense line two |
| WorkBuddy | Log in by scanning a QR code with WeChat, credit-based system within the platform | No personal key involved; the key point is not to lend your account to others |
For code involving keys, have the AI explain where they go (the first magic template on this page):
In this project, what are all the key-like things (API keys, tokens, passwords),
and which files are they stored in? Which addresses will they be sent to? Will they become public along with the repository?
Explain each one, assuming I know nothing about code.You should see: a key inventory — for each key, the storage location, where it's sent, and whether it will become public, with answers to all three. For any that can't be answered, either keep asking until you understand, or replace the key before using it.
- Quick check: for every key in the project, I know the three things: "where it's stored, where it's sent, and whether it will become public"
Step 2: Put a lock on the bill — for usage-based billing, set a cap before you start
Why: Item 5 of Willison's checklist is a real disaster he has seen: "vibe coding against an API with no billing cap, racked up thousands of dollars in charges" — a bill of thousands of dollars. His conclusion: be very careful vibe coding against anything billed by usage. When AI can't fix something it retries, loops, and can run for hours at a stretch — every attempt costs money.
First figure out which billing method your money uses, then decide how big a lock to set:
| Billing method | Who falls into this category | What happens when you hit the cap | What you need to do |
|---|---|---|---|
| Subscription tier | Claude Pro/Max/Ultra, ChatGPT tiers, OpenCode Go, WorkBuddy all editions | Usage pauses when the plan limit is reached; it doesn't snowball by usage | Remember where to check usage |
| Subscription + extra usage | Claude subscription with usage credits enabled (keep using beyond the plan) | The extra portion is billed by usage and needs a separate monthly cap | Set a cap (move 1) |
| Pure usage-based | Claude Console/API accounts, OpenCode connecting a model provider with your own key | No cap means running naked | Must set a cap (move 2) |
| Credit system | WorkBuddy | Credits are issued monthly and are valid only for the current month with no rollover — a natural monthly ceiling | Know the balance entry point |
Move 1: Subscription users — find the usage entry point, and set a monthly cap before enabling extra usage.
Run /usage in Claude Code: subscription users see the plan usage bar, activity stats, and usage breakdown (the Session cost column is for API users — subscription users can ignore it). To enable usage credits, go to claude.ai's Settings > Usage: the usage credits toggle, balance, this month's spending, and the monthly spending cap are all on this page (running /usage-credits in the CLI opens it directly). Before enabling it, set the monthly cap to the amount you're willing to bear this month.
Know the official behavior in advance: when Pro/Max/Ultra reaches the spending cap, Claude Code will prompt you to "raise or remove the cap" — when you see this prompt, think it through before pressing; don't casually click remove.
Move 2: API / own-key users — set a hard cap in the backend that issued the key.
Claude Console (API) users: in the Console you can set total spend limits for a workspace, and the cost and usage reports are in the same place; the first time you log in to Claude Code with a Console account, a workspace named "Claude Code" is also automatically created to collect this spending. OpenCode Users with their own key: the key is issued by the model provider, so go to the provider's account backend to find a spend-limit-type feature and set it — whether each provider's backend has this feature depends on the vendor.
Move 3: Unattended runs — cap that single run from the command line.
When letting Claude Code run a long task on its own (non-interactive print mode), add --max-budget-usd so it stops as soon as the estimated API cost for this run reaches the number:
claude -p --max-budget-usd 5.00 "帮我重构这个项目并跑通测试"Three official reminders: this is a client-side estimate and may differ from the bill; subagents' costs are also counted; actual spending may slightly exceed the line, so leave some headroom when setting it.
You should see: subscription users—/usage opens and you know where to find your plan's usage bar; API users—the workspace spending cap is set; unattended scripts—the command includes --max-budget-usd.
- Quick check: for every paid channel I use, I know "where the cap is set and where usage is visible"; pay-as-you-go channels have at least one hard cap
Step 3: Turn on the sandbox—draw an activity boundary for AI commands
Why: shell commands run by AI can, by default, touch everything your user account can—Claude Code's official docs state plainly that the sandbox's default read permissions cover most of the system, including credential files like ~/.ssh and ~/.aws/credentials. That's why this counts as its own line of defense: writing "don't touch anything" a hundred times in a prompt is worth less than drawing a line at the operating-system level that it cannot cross. Current sandbox status of the four tools:
| Tool | Sandbox status | How to enable / verify |
|---|---|---|
| Claude Code | Off by default | Run /sandbox in a session to open the panel; or set sandbox.enabled: true in ~/.claude/settings.json |
| Codex | The default permission mode includes a sandbox automatically | Works out of the box on macOS; on Linux/WSL2 install bubblewrap; Windows PowerShell uses a native sandbox, and WSL2 uses the Linux sandbox |
| OpenCode | The official docs have no equivalent sandbox switch | Your main defenses are lines one and two—especially when bringing your own pay-as-you-go key |
| WorkBuddy | The default permission mode comes with sandbox constraints | Keep "default permissions" at the bottom of the input box: commands run in the sandbox first, and file access is bounded by the workspace; don't casually turn on "allow full access" |
With Claude Code: enable it in three steps, verify with two probes.
The sandbox is a boundary enforced by the operating system: where files can be written, where the network can go—anything outside the circle is denied. To enable it: run /sandbox in a session and pick a mode in the panel (auto-allow = commands inside the circle no longer ask you one by one; regular = confirm each one as before). Platform differences to know in advance:
- macOS: uses the built-in Seatbelt, works with zero dependencies
- Linux/WSL2: requires installing
bubblewrapandsocat(Ubuntu/Debian:sudo apt-get install bubblewrap socat; Fedora:sudo dnf install bubblewrap socat) - Native Windows: sandbox not supported, commands run bare by default—if you want a sandbox, run Claude Code inside WSL2
After enabling it, you must verify (use the official probes and have Claude run them; commands you type yourself are usually outside the sandbox and won't show it):
| Probe command | What you should see when the sandbox is active |
|---|---|
touch ~/sandbox-probe | An error Operation not permitted (macOS) or Read-only file system (Linux/WSL2) |
curl --noproxy '*' https://example.com | An error Could not resolve host (the network has no direct egress; everything goes through a local proxy that only allows listed domains, and the domain list starts empty) |
⚠️ When the sandbox fails to start, the default is to run bare
Official warning: when the sandbox fails to start due to missing dependencies or an unsupported platform, Claude Code by default continues running commands without a sandbox. To make it exit rather than run bare, set sandbox.failIfUnavailable: true. If a verification probe "succeeds," go back and check dependencies and the switch.
With Codex: confirm your platform is covered by the default sandbox.
Codex's default permission mode applies the sandbox automatically, no manual enabling needed—but on Linux/WSL2 you must install bubblewrap first (sudo apt install bubblewrap or sudo dnf install bubblewrap), or it will warn. The official docs are clear about how these two controls relate: the sandbox defines the technical boundary, while the approval policy decides whether the AI stops to ask you before crossing it—they work together, it's not either-or.
You should see: Claude Code—the /sandbox panel shows the sandbox is enabled, and both probes hit the wall with errors; Codex—bubblewrap is installed on Linux and startup shows no warning.
- Quick check: if using Claude Code, both probes verified; if using Codex, confirmed my platform is covered by the default sandbox
Step 4: Two quick extra checks—data privacy and network citizenship
Why: Willison's checklist has two more items that don't rank as "lines of defense," but each takes 30 seconds, so just do them in passing.
The privacy question: will this project touch private data I wouldn't want exposed during screen sharing? If so, Willison's bar is strict—you must be absolutely certain whether the data could leave your machine; if you can't be certain, don't feed the data in. The sandbox network isolation from Step 3 is precisely one of the technical guarantees that "data can't get out": once the boundary is drawn, privacy is protected along with it.
The network citizenship question: will this tool send requests to external platforms? If so, think about the load and cost on other people's services—this is one reason Willison likes sandboxes: a sandbox keeps your project from accidentally harming elsewhere.
Answer both questions for your current project (the second magic template on this page):
Data privacy check: what private data will this project touch? Will the data leave this machine—
which addresses will it be sent to? Network citizenship check: which external services will it send requests to?
At roughly what frequency?You should see: both questions have concrete answers that can go into the project README. For any project where the answer is "don't know," either find out—or don't feed it private data yet.
- Quick check: I can give concrete answers to both the private-data and external-request questions
Checkpoint ✅
- Every key in the project passes the three rules: not hardcoded, not in the repo, and I know where it's stored
- I can tell subscription / pay-as-you-go / credits apart for paid channels: pay-as-you-go ones have hard caps, and I know where each channel's usage entry point is
- Claude Code sandbox is on and both probes verified; if using Codex, confirmed my platform is covered by the default sandbox
- Both the data-privacy and network-citizenship questions are answered, and the answers went into the project docs
- With the three lines of defense done, I've re-rated this project's risk level—I know whether it still deserves "accept all"
Pitfall reminders
❌ API key pasted into code to "get it running first"
Symptom: the key sits in code as plaintext, the project gets pushed to a repo casually, or a screenshot sent to a group for help includes the key. Cause: AI-generated code often fills the example's placeholder with a real key, and you hit Accept All without reading the diff—and CodeRabbit's quantitative research says AI-assisted code has 2.74 times more security vulnerabilities than human-written code. Correct approach: the three rules from Step 1 plus Willison's line "if the code involves keys, you must understand how it works"; for any key already exposed, go to the provider's dashboard immediately to revoke and replace it.
❌ "I'm on a subscription, no need to worry about billing"
It's true that a subscription stops when the plan's usage tops out. But two loopholes need plugging: first, once usage credits are enabled on a Claude subscription, usage beyond the plan is billed pay-as-you-go—without a monthly spending cap, you're back in the "no billing cap" disaster scenario Willison described; second, the most common way to use OpenCode is bringing your own model-provider key on pay-as-you-go billing, which has nothing to do with subscriptions. Correct approach: use the table from Step 2 to sort out the billing method first, set hard caps for pay-as-you-go, and set a monthly cap before enabling usage credits.
❌ Assuming the sandbox is "on by default," or that "turning it on makes you bulletproof"
Both directions are wrong. Direction one: Claude Code's sandbox is off by default, and the official docs state plainly—when the sandbox fails to start (missing dependencies, unsupported platform), it will keep running commands without a sandbox by default; not enabling it and not verifying it means this line of defense doesn't exist. Direction two: the sandbox only covers shell commands the AI runs—Claude's file tools, MCP servers, and hooks all run outside the sandbox, and the commands you type yourself usually do too. The right approach: /sandbox turned on + probe verification + setting failIfUnavailable: true as needed; for exposure outside the sandbox, fall back on permission prompts and the checklist from review checks.
Advanced tips (optional)
Also keep credential files outside the sandbox (Claude Code). The sandbox's default read permissions cover credential files like ~/.ssh and ~/.aws/credentials, and the official docs say plainly "there is no built-in credential deny list—only what you list gets blocked." Add sandbox.credentials in ~/.claude/settings.json to keep credential files and token environment variables out of sandboxed commands (official example, verbatim):
{
"sandbox": {
"enabled": true,
"credentials": {
"files": [
{ "path": "~/.aws/credentials", "mode": "deny" },
{ "path": "~/.ssh", "mode": "deny" }
],
"envVars": [
{ "name": "GITHUB_TOKEN", "mode": "deny" },
{ "name": "NPM_TOKEN", "mode": "deny" }
]
}
}
}Effect of deny mode: commands inside the sandbox can't read these files, and the listed environment variables are cleared before the command runs.
See where your money goes (Claude Code). /usage doesn't just show totals: subscription users can also see usage attribution breakdowns by skill, subagent, plugin, and MCP server, plus official suggestion lines (e.g., "a certain file takes 49k tokens per request, trim it"). When a bill looks off, run it before guessing.
Team users: export usage into your own monitoring system. Claude Code supports exporting each member's token and cost metrics to your own observability system via OpenTelemetry: just set CLAUDE_CODE_ENABLE_TELEMETRY=1 plus the OTEL_* family of environment variables. Only when spending is visible can it be controlled.
WorkBuddy's natural guardrails. Credits are issued monthly, valid only for the current month with no rollover—that itself is a monthly spending ceiling; it also has loop-execution confirmation—when it detects a task might be looping, it pauses and asks you before executing the tool call, and choosing "terminate request" can even lead to a refund evaluation. For beginners afraid of pay-as-you-go billing running wild, this is a friendly default design.
Lesson summary
✅ You've set up all three lines of defense: keys (not hardcoded, not in the repo, knowing where they're stored, reading up when involved) → billing (distinguishing subscription / pay-as-you-go / credits, always setting a cap for pay-as-you-go, knowing your usage entry points) → sandbox (Claude Code /sandbox turned on + probe verification, Codex default mode includes it, WorkBuddy default permissions include sandbox constraints, OpenCode relies on the first two lines).
✅ You understand why API key security ranks first: one key leak means losses with no ceiling—AI-assisted code has 2.74 times more security vulnerabilities than human-written code, and plaintext keys are an exposure you can entirely plug yourself.
✅ You remember the two framing statements: Willison's "completely novice secure vibe coding starts with a sandbox"; and the disaster he's seen—vibe coding against an API with no billing cap, a bill of thousands of dollars.
Key concepts recap:
| Concept | In one sentence | Where to go deeper |
|---|---|---|
| Three lines of defense | Keys, billing, sandbox—don't gamble on the AI not causing trouble, just ensure that trouble can't hurt you | Core idea of this page |
| Three rules for keys | Not hardcoded, not in the repo, knowing where they're stored | Step 1 on this page |
| Billing caps | Subscriptions stop at the limit; pay-as-you-go without a cap is running naked | Step 2 on this page |
| Sandbox | The file / network boundary the operating system draws around AI commands | Step 3 on this page |
| The privacy question | For data you don't want exposed during screen sharing, confirm it can't leave your machine | Step 4 on this page |
Next lesson preview
The five disciplines are now established—planning, prompts, error messages, acceptance, and defenses: you now have a complete vibe coding workflow. Next stop, real practice: Scenario practice: choose your route—a website, a mini program, or a browser extension.
You will learn:
- How to pick among the three routes: the respective barriers and outputs of websites, WeChat mini programs, and browser extensions
- What the best first project is for each route
- How the five disciplines land in real projects: from planning to acceptance to defenses, used throughout
- Getting an early read on the rules and costs of going live: hosting platform free tiers, authentication fees, listing reviews