HookStackGitHub
Back to catalogue
SecurityPreToolUse· Write|EditPreToolUseBefore tool execution · can block⚡ blocking

Sensitive file write protection

Prevents the agent from modifying sensitive files (.env, secrets, private keys, CI lockfiles) by intercepting the Write and Edit tools and checking the target path.

Use cases

  • Configuration protection
  • Compliance
  • Local secrets integrity

Providers & tags

Claude Code
#security#files#protection#secrets

settings.json fragment

{
  "hooks": {
    "PreToolUse": [
      {
        "hooks": [
          {
            "command": "node $CLAUDE_PROJECT_DIR/.claude/hooks/protect-paths.mjs",
            "type": "command"
          }
        ],
        "matcher": "Write|Edit"
      }
    ]
  }
}

Script · .claude/hooks/protect-paths.mjs

#!/usr/bin/env node
// Protège les fichiers sensibles contre l'écriture (PreToolUse Write|Edit)
import { readFileSync } from 'fs';
import { fileURLToPath } from 'url';

const PROTECTED = [
  /\/\.env$/,
  /\/\.env\.local$/,
  /\/\.env\.production/,
  /\/secrets\//,
  /\/(id_rsa|id_ed25519|.*\.pem)$/,
];

export function run(input) {
  const filePath = input.tool_input?.file_path ?? '';
  const blocked = PROTECTED.find((p) => p.test(filePath));
  return blocked
    ? { decision: 'block', reason: `Fichier protégé : ${filePath}. Modifiez manuellement si intentionnel.` }
    : null;
}

/* v8 ignore next 5 */
if (process.argv[1] === fileURLToPath(import.meta.url)) {
  const input = JSON.parse(readFileSync(0, 'utf8'));
  const result = run(input);
  if (result) process.stdout.write(JSON.stringify(result));
}