...

/

Building Security Hooks

Building Security Hooks

Explore deterministic hooks that scan secrets and block risky prod actions, safeguarding AI-assisted development workflows.

Now that we are comfortable with hooks and how PreToolUse and PostToolUse work, let us use them for added security. We will build two small, deterministic guardrails: a pre-save secret scanner and a “hands-off prod” directory gate. These are simple, local scripts, but they reliably prevent whole classes of mistakes that prompts alone cannot.

Even a smart AI coding assistant can inadvertently do risky things, such as inserting an API key into code or running commands in a production folder. By implementing security hooks, we create an automatic safety net that catches these issues every time, rather than relying on the AI to remember ad hoc instructions. Hooks run at fixed trigger points in Claude’s workflow and can block actions, or provide immediate feedback when something is not safe. This deterministic control ensures critical safeguards always happen, such as preventing a secret from leaking.

Common security pitfalls in coding are mentioned below.

  • Hardcoded secrets: Accidentally embedding passwords, API keys, or tokens in source code.

  • Unsafe file access: Modifying or executing files in production or other sensitive locations without proper oversight.

With Claude Code’s hook system, we can address these by enforcing rules automatically. We will walk through two concrete hook examples that address these scenarios.

Scanning for secrets before saving code

One valuable safeguard is scanning new or edited code for any hardcoded secrets before the file is saved or committed to version control. This hook acts as a pre-save gatekeeper: if Claude attempts to save a file containing something that looks like a secret, the hook blocks the save and prompts Claude to fix the issue. This prevents sensitive data from ever reaching your disk or repository.

We will use a PreToolUse hook that triggers on file Write and Edit operations. Claude Code’s tools for writing to files are Write (for saving file content) and Edit or MultiEdit. We configure the hook to match these tool names, so it runs every time Claude is about to write or edit a file. The hook runs a custom script that scans the file content for patterns that resemble secrets. If any are found, the script exits with a special code to block the tool call and returns an error message, which Claude will see and respond to.

In your Claude settings, either global ~/.claude/settings.json ...