DEV Community

Vildanden
Vildanden

Posted on

Stop Claude Code from publishing a package with a PreToolUse hook

A write guard can keep Claude Code off .env files. It will not stop a confident npm publish or cargo publish mid-session. Package registries do not ask you to confirm the same way git remotes sometimes do, and a model that just "finished the fix" may treat a publish as the obvious last step. A small PreToolUse hook can block those commands so a release stays a human decision.

The hook should name the command class and exit 2.

The hook

Save this as .claude/hooks/block_package_publish.py and make it executable:

#!/usr/bin/env python3
import json
import re
import sys

try:
    event = json.load(sys.stdin)
except json.JSONDecodeError:
    sys.exit(0)

if event.get("hook_event_name") not in (None, "PreToolUse"):
    sys.exit(0)

tool = (event.get("tool_name") or "")
if tool and tool not in ("Bash", "bash"):
    sys.exit(0)

input_data = event.get("tool_input") or event.get("input") or {}
command = str(input_data.get("command") or input_data.get("cmd") or "")
if not command:
    sys.exit(0)

# npm, pnpm, yarn, bun, cargo, twine, poetry, flit, vsce, ovsx
if re.search(
    r"(?i)(?:^|[;&|\n]|(?:&&)|(?:\|\|))\s*(?:(?:npx|pnpm|yarn|bunx|bun)\s+)?(?:npm|pnpm|yarn(?:\s+bpm)?|bun|cargo|twine|poetry|flit|uv|vsce|ovsx)\s+publish\b|(?:^|[;&|\n]|(?:&&)|(?:\|\|))\s*twine\s+upload\b",
    command,
):
    print("PreToolUse: package publish is blocked. Do the release yourself after you have reviewed the version and changelog.")
    sys.exit(2)
Enter fullscreen mode Exit fullscreen mode

Wire it in .claude/settings.json under PreToolUse for the Bash tool, with command set to python3 .claude/hooks/block_package_publish.py. Check the hooks page for your installed Claude Code version; payload fields can change between releases. The script reads command from the tool input and ignores non-shell tools.

Why this beats a pasted prompt

"Never publish" in CLAUDE.md only works when the model remembers it. A PreToolUse hook runs before the shell command, sonpm publish,pnpm publish,cargo publish, andtwine upload` cannot slip through as a helpful last step. If the package really must go out, run the publish command in your own terminal after you have checked the version, the files, and the registry.

Tips

  • Keep the hook local, fast, and free of network calls.
  • Pair it with a git-push ask rule so neither the registry nor the remote is a surprise.
  • Do not print the full command line. The message above names the class of action, not your package name.
  • If a docs script or a dry-run flag trips the hook, require an explicit allow-list for --dry-run rather than deleting the guard.

Want the rest of the setup?

I keep copy-ready Claude Code configs (CLAUDE.md templates, slash commands, hooks, permission rules) in Vildanden Agent Config. There's a free sample: https://justly-mia-429.rehost.page/

Top comments (0)