🛡️ r/BuildWithClaude — Local Agent Security & API Key Field Guide
Welcome to the r/BuildWithClaude Security Field Guide. Running agentic AI tools locally gives models permission to execute commands, modify files, and access system APIs. This guide covers core threat vectors, non-obvious sandbox configuration gaps, web app vulnerability audits, API key hygiene, emergency incident protocols, and community defense tools.
Last reviewed: November 2026. Claude Code changes often, so check the official security docs, permissions docs and sandboxing docs for the latest behavior.
⚠️ Agentic Threat Vectors & Vulnerabilities
When running local AI agents (like Claude Code), security risks stem from permission sprawl, supply chain hooks, indirect prompt injection, and cross-tool data leaks.
Know your mode first. New Claude Code sessions in the terminal and VS Code start in Auto mode: a background safety classifier approves or blocks actions instead of asking you each time. If you want to approve each action yourself, switch to Manual mode (press Shift+Tab to cycle modes). Much of the advice below depends on which mode you're in.
1. Permission Wildcards & Precedence Paradoxes
The Risk: Broad allow rules like
Bash(*),Bash(bash *)orBash(python *), or running with--dangerously-skip-permissions, let an agent run arbitrary scripts and sub-shells without prompting you.The Native Precedence Trap: Permission rules are evaluated
deny>ask>allow. Anallowrule can't carve an exception out of a broaderdenyrule (e.g., "deny allawscommands, but allowaws ec2 describe-instances"), because the broaddenywins.Upstream Bug Warning (#6527, reported Aug 2025): Including a bare
Bashtoken in yourallowlist has been reported to make Claude Code ignore yourasklist, so commands likerm -rfrun without confirmation. Check the issue for its current status, and test your ownaskrules before relying on them.Mitigation: Keep permissions scoped to specific tasks, files, or explicit command patterns. The supported way to "allow broadly but block a few commands" is a
PreToolUsehook that rejects those commands. For file paths, a!pattern in the same deny list carves out an exception:Read(*.env)followed byRead(!sample.env)blocks every.envfile exceptsample.env.
2. Supply Chain Attacks & Lifecycle Hooks
The Risk: Running a command like
npm install <package>triggerspostinstalllifecycle scripts in the background, which can run arbitrary code before you ever test the package. Additionally, agents often install the first search result from npm or PyPI, grabbing unmaintained or dead dependencies (e.g.,crypto-js).Mitigation: Inspect new dependencies before installing, check package maintenance status with
should-i-use, or run package installations withnpm install --ignore-scripts.
3. Indirect Prompt Injection
The Risk: External text read by Claude during a session (cloned repos, web fetches, GitHub issue comments, PDFs) can contain hidden prompts instructing the agent to exfiltrate files or execute unwanted tools.
Mitigation: Avoid letting agents analyze untrusted public repositories or web pages with auto-execution enabled. When you do need to work with untrusted content, Anthropic recommends doing it inside a virtual machine or dev container.
4. Context Window Secret Leakage & Cross-Tool MCP Leaks
The Risk: If
.envfiles, SSH keys, or recovery codes sit inside or near the workspace, Claude can read them into context. Once inside context, a value read via a filesystem MCP server can quietly be included in outbound tool calls (e.g., email or web fetch MCPs) without triggering warnings.Mitigation: Claude Code does not read a
.claudeignorefile, so it won't protect your secrets. Block them with deny rules in.claude/settings.json, for example"permissions": {"deny": ["Read(./.env)", "Read(./.env.*)"]}, and keep them out of git with.gitignore. Turn on the sandbox (/sandbox) so those rules are enforced by the operating system against every process, not just the commands Claude Code recognizes. Deny rules don't govern what an MCP server reads, so deny the MCP tool itself (mcp__<server>__*) or don't install one that can see your secrets. A local proxy likewardlinecan add a second layer for MCP tool traffic.
5. Silent / Deferred Execution
The Risk: Agents edit code files rather than running commands directly. Modifying
package.json,Makefile,.git/hooks, or.vscode/tasks.jsoncauses untrusted code to run later when you test or build.Mitigation: Always inspect
git diffbefore running test suites, commits, or builds after an agent session.
🔍 6 Non-Obvious Security Configuration Gaps
These are common gaps we see in community setups:
Broken Settings Files: Settings files are strict JSON: a trailing comma or a
//comment makes Claude Code reject the whole file. In an interactive session you get a Settings Error dialog at startup. If you choose to continue, or you runclaude -p, the session runs without that file's rules, including your deny rules. After editing, run/statusto confirm the file loaded,/permissionsto see your rules, andclaude doctorto list anything that was rejected.The Sandbox Only Covers Bash: The sandbox applies to terminal commands and the processes they start. Claude's
ReadandEdittools go through the permission system instead, and MCP servers and hooks run outside the sandbox entirely. Each layer must be configured separately.Deny Rules and Bash: A
Read(./.env)deny rule blocks Claude's file tools and the file commands Claude Code recognizes in terminal commands (cat,head,tail,sed, and redirects like< .env). It does not stop reads that never name the file:grep -rover the folder, or a Python or Node script that opens.envitself. Turn on the sandbox (/sandbox) to enforce yourReaddeny rules at the operating-system level for every process;sandbox.filesystem.denyReadlets you block more paths.Unsandboxed Command Fallbacks: If the sandbox blocks a command, Claude can retry it outside the sandbox. The retry goes through normal permissions: in Manual mode you're asked first, in Auto mode the safety classifier decides, and an
allowrule that matches the command approves it. Separately, if the sandbox can't start at all, Claude Code warns you and runs commands without it. To close both gaps, add this to your settings (the/sandboxOverrides tab calls the first setting Strict sandbox mode):{"sandbox": {"enabled": true, "allowUnsandboxedCommands": false, "failIfUnavailable": true}}Local Settings Are Invisible to CI & Teams: Claude Code keeps
settings.local.jsonout of git automatically only when it creates the file itself. If you create it by hand, add it to.gitignoreyourself. Either way, CI can't see it, so it cannot verify whether a teammate is bypassing rules or running with permission-skipping aliases.MCP Servers Approved by Name: MCP server approvals are tied to the server's name in
.mcp.jsonrather than pinned to a specific binary or package hash.
🛠️ Community Security & Defense Ecosystem
Members of r/BuildWithClaude have built open-source tools to address these specific security gaps. These tools are community-built and have not been audited by the mods. Read the code before installing, especially anything that changes your permissions or settings.
| Tool | Focus | Problem Solved | Link |
|---|---|---|---|
safetoclone.com | Repo Grading | Grades GitHub repos to help you avoid blindly downloading unknown or unsafe code. | safetoclone.com |
permcheck | Permission Containment | Helps express "broad restriction, narrow exceptions" policies that native deny > allow rules can't. Review what it writes to your settings. | GitHub |
wardline | MCP Anomaly Proxy | Policy gateway for MCP servers that detects behavioral spikes and blocks compromised agents. | GitHub |
guardrail-core | Credential Brokering | Mints short-lived, limited-use tokens for agents instead of exposing static API keys. | GitHub |
Handsfree | Config Health Doctor | Diagnoses broken JSON and risky overrides in .claude/settings.json. | GitHub |
should-i-use | Dependency Auditor | MCP server that flags ~1,000 dead or risky npm/PyPI packages before agents install them. | npm |
🌐 Top 3 Common Security Flaws in Vibe-Coded Web Apps
Reviews of community-submitted web apps keep turning up the same three problems in AI-generated deployments:
Database Tables Without Row-Level Security (RLS): Vibe-coded Supabase/Postgres setups frequently expose public "anon" API keys in the browser without enabling RLS. Anyone can query or dump database tables directly via REST without logging in.
Missing Security Headers: Many AI-built frontend deployments lack essential headers including
Content-Security-Policy(CSP),X-Frame-Options(clickjacking defense),HSTS(HTTPS enforcement),X-Content-Type-Options,Referrer-Policy, andPermissions-Policy.Email Spoofing (Missing/Weak SPF & DMARC): Domain configurations frequently omit SPF/DMARC records or leave DMARC set to
p=none, making the domain vulnerable to email spoofing.
💡 Real-World Case Studies & Audit Checklists
Case Study 1: "Is Factory Reset Overkill for Agent Anxiety?"
Community Scenario: A developer running Claude Code outside a container completed a session and questioned whether they should factory-reset their machine to ensure no hidden backdoors were installed.
The High-Caution 10-Point Audit Checklist
Before panicking or wiping a machine, perform the post-session audit steps used in this community incident. Your session transcript in ~/.claude/projects/ lists every command that ran.
Mapped Folder Boundaries: Verified every directory the session interacted with.
Command Log Review: Verified every terminal command executed during the session.
Outbound Domain Verification: Audited all external URLs and network requests.
Persistence Point Inspection: Checked OS startup items,
crontab, LaunchAgents, scheduled tasks, shell profiles (.zshrc,.bashrc),~/.ssh/authorized_keys, and global git hooks.System-Wide Installs: Audited global binaries (
Homebrew,pip,npm -g).Dependency Diffs: Cross-checked
package.jsonand lockfile change histories.Package Verification: Confirmed newly added dependencies were legitimate packages.
Credential Exposure Check: Verified
.envfiles, SSH keys, and tokens were untouched.Temp & Download Scans: Checked
/tmp,/var/tmp, and~/Downloadsfor binary drops.Active Connections: Audited live processes and listening network ports.
The Verdict: Claude Code runs commands with your normal user permissions, so it can change anything your account can, but not protected system files without sudo. If the session never used sudo, ran no unvetted binaries, and passed the checks above, the machine is very unlikely to be compromised and a wipe is usually unnecessary. For future sessions involving untrusted code, work inside a VM or dev container.
Case Study 2: Designer & Non-Coder System File Security
Community Scenario: Non-technical builders and designers expressed concern about Claude reading passwords or recovery codes stored elsewhere on their computer outside the active project folder.
System Permissions: Claude Code can read files outside your project folder. In Manual mode its file tools ask first; in Auto mode you may not be asked at all. Terminal commands like
catcan read anywhere your account can, and the sandbox allows reading the whole computer by default, including~/.sshand~/.aws/credentials.Lock it down: Add
"permissions": {"blockReadsOutsideWorkingDirectories": true}to~/.claude/settings.json(Claude Code v2.1.257 or later). Claude's file tools then refuse anything outside the project in every mode, and terminal commands that name an outside path ask you first. Turn on the sandbox as well, and sandboxed commands lose read access to your home folder entirely.Explicit Path Denial: Block specific sensitive files by adding
Readdeny rules and sandboxdenyReadrules in your global~/.claude/settings.json.Best of all: Keep passwords and recovery codes in a password manager rather than in files on disk.
🗝️ API Key Hygiene & Emergency Protocol
Key Hygiene Rules
Never Hardcode Keys: Keep keys out of your code. Prefer a per-project
.envfile protected byReaddeny rules (Section 4) over exporting keys in the shell you start Claude Code from. Terminal commands inherit that shell's environment, and a read-only command likeecho $API_KEYruns without a prompt. Keep.envfiles out of git by adding the lines.envand.env.*to your.gitignore. Note that.gitignoredoesn't stop Claude from reading them; deny rules do that.Use Ephemeral Tokens: Where possible, leverage credential brokers (guardrail-core) to mint short-lived tokens rather than persisting master API keys in local shells.
Scope API Key Permissions: Restrict API keys to read-only or single-service scopes. On testing accounts, turn off auto-recharge and set a spend limit in your provider's console so a runaway loop can't burn through credits.
Emergency Incident Response Protocol
If you suspect an API key leak or malicious command execution during a session:
Stop the agent immediately. If the terminal responds, press
Ctrl+Cor type/exit. Otherwise runpkill -f claude(Mac/Linux only; it may also close other Claude apps). On Windows, close the terminal window or end the process in Task Manager.Revoke Exposed API Keys: Go to your Anthropic / OpenAI console and immediately revoke and delete the affected key.
Audit Local Changes: Run
git status && git diffto see exactly what was modified.Review Transcript Logs: Check your session log in
~/.claude/projects/to review the exact commands executed.