v1.31.0
hookPreToolUse[Bash]bloquea

bash-guard

Bloquear operaciones destructivas

PreToolUseevento
Bashmatcher
bloqueapolítica
10 stimeout
2026-09-22último cambio

Qué comprueba

Los flags cortos se tokenizan: -rf, -r -f, -fu y find -delete cuentan igual que la forma canonica (ADR-032) Salida: hallazgos y motivo del bloqueo por stderr, que es lo que Claude Code muestra con exit 1 y 2 (stdout solo es contexto en SessionStart y UserPromptSubmit; ADR-004 D1 enmendado por ADR-030)

Códigos de salida

ExitSignificado
0permitir
2BLOCK intrinseco (operacion git o SQL destructiva; no configurable)

Política

Bloquea siempre: es uno de los irrenunciables (daño irreversible), no configurable.

ClaveTipoDefaultQué hace
hooks.policystring"warn"WARN-first por defecto (avisan sin bloquear); 'block' eleva todos los hooks defensivos a bloqueo. Los hooks intrinsecamente BLOCK (bash-guard, protect-files certs/keys, hilo-json-guard) no se degradan nunca.
hooks.blockListarray[]Hooks concretos elevados a BLOCK aunque policy=warn (ej. ['secret-scanner']).

Código fuente

bash-guard.js · 159 líneas
// bash-guard.js - Bloquear operaciones destructivas
// Evento: PreToolUse[Bash]
// Exit 0 = permitir · Exit 2 = BLOCK intrinseco (operacion git o SQL destructiva; no configurable)
// Los flags cortos se tokenizan: -rf, -r -f, -fu y find -delete cuentan igual que la forma canonica (ADR-032)
// Salida: hallazgos y motivo del bloqueo por stderr, que es lo que Claude Code muestra con exit 1 y 2 (stdout solo es
//         contexto en SessionStart y UserPromptSubmit; ADR-004 D1 enmendado por ADR-030)
// Historial del original (condensado):
//   v2.1.0: safeTargets incluye .git/*.lock (FB-001: borrar un index.lock/HEAD.lock
//     huerfano que deja Visual Studio NO es destructivo).
//   v2.0.0: try/catch global, git restore ., branch -D, --no-verify, stash drop/clear, SQL DROP
//     ampliado, --force-with-lease NO bloqueado, word boundaries. v1.0.0: 7 patrones basicos.
//
// Politica: BLOCK INTRINSECO — resolvePolicy con intrinsicBlock:true devuelve
// 'block' incondicionalmente (operaciones destructivas irreversibles, no degradable a WARN).

'use strict';

const h = require('./lib/helpers');
const config = require('./lib/config');

// --- Wrapper de seguridad -----------------------------------------
// Cualquier excepcion no controlada -> exit 0 (permitir) + log a stderr.
// Mejor un falso negativo silencioso que un hook que rompe el flujo.
try {
  const hookData = h.readHookInput();
  // El comando en claro, no el JSON escapado del tool_input: casar patrones sobre el JSON era un falso negativo
  // por construccion (ADR-026 para los guards de Write; aqui el separador anterior a rm era una comilla, no un espacio).
  const ti = hookData && hookData.tool_input;
  const command = ti && typeof ti === 'object' && typeof ti.command === 'string' ? ti.command : h.getToolInput(hookData);
  if (!command) process.exit(0);

  const mode = config.resolvePolicy(config.load(), 'bash-guard', { intrinsicBlock: true }); // siempre 'block'
  const EXIT_BLOCK = mode === 'block' ? 2 : 1; // intrinseco: siempre 2

  // Flags cortos de una invocacion: cada grupo "-abc" aporta sus letras, en cualquier orden y repartidos en
  // grupos distintos ("-rf", "-r -f", "-fu"). Antes se casaba una forma concreta y "rm -r -f", "git push -fu"
  // o "find -delete" pasaban (ADR-030 fase 2, H-02). El segmento termina en | ; && o un salto de linea.
  const segmentOf = (re) => { const m = command.match(re); return m ? m[1] : null; };
  const shortFlags = (seg) => (seg.match(/(?:^|\s)-([a-zA-Z]+)(?=\s|$)/g) || []).map(g => g.trim().slice(1)).join('');

  // -- Operaciones git destructivas ----------------------------------

  // --force-with-lease es SEGURO (chequea remoto antes de sobrescribir). Bloquear --force y cualquier
  // grupo de flags cortos que lleve la f (-f, -fu, -uf...).
  const pushSeg = segmentOf(/\bgit\s+push\b([^|;&\n]*)/i);
  if (pushSeg !== null &&
      (/(^|\s)--force(=|\s|$)/i.test(pushSeg) || shortFlags(pushSeg).includes('f')) &&
      !/--force-with-lease/i.test(pushSeg)) {
    console.error(h.txt('BLOQUEADO: git push --force/-f. Usa --force-with-lease (mas seguro) o un push normal.', 'BLOCKED: git push --force/-f. Use --force-with-lease (safer) or a plain push.'));
    process.exit(EXIT_BLOCK);
  }

  if (/\bgit\s+reset\s+--hard\b/i.test(command)) {
    console.error(h.txt('BLOQUEADO: git reset --hard descartara todos los cambios no committeados.', 'BLOCKED: git reset --hard will discard every uncommitted change.'));
    process.exit(EXIT_BLOCK);
  }

  if (/\bgit\s+clean\s+-[a-zA-Z]*f/i.test(command)) {
    console.error(h.txt('BLOQUEADO: git clean -f eliminara archivos no rastreados permanentemente.', 'BLOCKED: git clean -f will delete untracked files permanently.'));
    process.exit(EXIT_BLOCK);
  }

  // v2.0.0: cubre legacy 'git checkout .' y moderno 'git restore .'
  if (/\bgit\s+(checkout|restore)\s+\.\B/i.test(command)) {
    console.error(h.txt('BLOQUEADO: descartara todos los cambios sin stage (git checkout/restore .).', 'BLOCKED: this discards every unstaged change (git checkout/restore .).'));
    process.exit(EXIT_BLOCK);
  }

  // v2.0.0: git branch -D / --delete --force borra rama sin garantia de merge.
  // Case-sensitive (sin /i, como -cmatch) para distinguir -D (force) de -d (safe).
  if (/\bgit\s+branch\s+-D\b/.test(command) ||
      /\bgit\s+branch\s+--delete\s+--force\b/i.test(command)) {
    console.error(h.txt('BLOQUEADO: git branch -D borra una rama sin garantia de merge. Usa -d en su lugar.', 'BLOCKED: git branch -D deletes a branch with no merge guarantee. Use -d instead.'));
    process.exit(EXIT_BLOCK);
  }

  // v2.0.0: --no-verify saltea pre-commit/pre-push hooks (red flag)
  if (/\bgit\s+(commit|push|merge|rebase)\b.*--no-verify\b/i.test(command)) {
    console.error(h.txt('BLOQUEADO: --no-verify saltea hooks defensivos. Si fallan, arregla la causa raiz.', 'BLOCKED: --no-verify skips defensive hooks. If they fail, fix the root cause.'));
    process.exit(EXIT_BLOCK);
  }

  // v2.0.0: git stash drop/clear elimina stashes sin recuperacion
  if (/\bgit\s+stash\s+(drop|clear)\b/i.test(command)) {
    console.error(h.txt('BLOQUEADO: git stash drop/clear elimina stashes sin posibilidad de recuperar.', 'BLOCKED: git stash drop/clear removes stashes with no way to recover them.'));
    process.exit(EXIT_BLOCK);
  }

  // -- Eliminacion recursiva peligrosa -------------------------------
  // Cubre: rm -rf, rm -fr, rm -r -f, rm -Rf, rm --recursive --force, Remove-Item -Recurse -Force, find ... -delete
  // Permitir en targets seguros (carpetas de build/cache/IDE + locks git huerfanos).
  // FB-001: .git/*.lock (index.lock, HEAD.lock) que deja Visual Studio NO es destructivo borrarlo.
  const safeTargets = /(node_modules|bin[\\/]|obj[\\/]|TestResults|\.vs|packages[\\/]|\.next|dist[\\/]|coverage[\\/]|out[\\/]|\.git[\\/][^ "']*\.lock)/i;
  const rmSeg = segmentOf(/(?:^|[\s;&|])rm\s([^|;&\n]*)/i);
  const rmFlags = rmSeg === null ? '' : shortFlags(rmSeg).toLowerCase();
  const rmDestructive = rmSeg !== null && (
    (rmFlags.includes('r') && rmFlags.includes('f')) ||
    (/(^|\s)--recursive(\s|$)/i.test(rmSeg) && /(^|\s)--force(\s|$)/i.test(rmSeg)) ||
    ((rmFlags.includes('r') || /(^|\s)--recursive(\s|$)/i.test(rmSeg)) && /(^|\s)--force(\s|$)/i.test(rmSeg)) ||
    ((rmFlags.includes('f') || /(^|\s)--force(\s|$)/i.test(rmSeg)) && /(^|\s)--recursive(\s|$)/i.test(rmSeg)));
  if ((rmDestructive || /Remove-Item.*-Recurse.*-Force|Remove-Item.*-Force.*-Recurse/i.test(command)) && !safeTargets.test(command)) {
    console.error(h.txt('BLOQUEADO: Eliminacion recursiva forzada detectada. Verifica el path.', 'BLOCKED: forced recursive delete detected. Check the path.'));
    process.exit(EXIT_BLOCK);
  }
  const findSeg = segmentOf(/\bfind\s([^|;&\n]*)/i);
  if (findSeg !== null && /(^|\s)-delete(\s|$)/i.test(findSeg) && !safeTargets.test(findSeg)) {
    console.error(h.txt('BLOQUEADO: find ... -delete borra todo lo que casa, sin papelera ni confirmacion. Lista primero sin -delete y verifica el path.', 'BLOCKED: find ... -delete removes everything that matches, with no recycle bin and no confirmation. List it first without -delete and check the path.'));
    process.exit(EXIT_BLOCK);
  }

  // -- Operaciones SQL destructivas ----------------------------------

  // v2.0.0: DROP ampliado a 8 tipos de objetos
  if (/\bDROP\s+(TABLE|DATABASE|SCHEMA|COLUMN|CONSTRAINT|INDEX|VIEW|PROCEDURE|FUNCTION|TRIGGER)\b/i.test(command)) {
    console.error(h.txt('BLOQUEADO: Operacion SQL DROP destructiva detectada. Verifica scope y backup.', 'BLOCKED: destructive SQL DROP detected. Check the scope and the backup.'));
    process.exit(EXIT_BLOCK);
  }

  if (/\bTRUNCATE\s+TABLE\b/i.test(command)) {
    console.error(h.txt('BLOQUEADO: TRUNCATE TABLE no es transaccional y borra todos los datos.', 'BLOCKED: TRUNCATE TABLE is not transactional and wipes every row.'));
    process.exit(EXIT_BLOCK);
  }

  // DELETE FROM sin WHERE. Negative lookahead: bloquear si NO va seguido de WHERE.
  // Cubre tanto 'DELETE FROM T' final como 'DELETE FROM T;' o dentro de quotes.
  if (/\bDELETE\s+FROM\s+\w+\b(?!\s+WHERE\b)/i.test(command)) {
    console.error(h.txt('BLOQUEADO: DELETE FROM sin WHERE detectado. Anade clausula WHERE.', 'BLOCKED: DELETE FROM with no WHERE detected. Add a WHERE clause.'));
    process.exit(EXIT_BLOCK);
  }

  // v2.0.0: ALTER TABLE ... DROP COLUMN/CONSTRAINT
  if (/\bALTER\s+TABLE\s+\w+.*\bDROP\s+(COLUMN|CONSTRAINT)\b/i.test(command)) {
    console.error(h.txt('BLOQUEADO: ALTER TABLE...DROP destructivo detectado. Verifica scope.', 'BLOCKED: destructive ALTER TABLE...DROP detected. Check the scope.'));
    process.exit(EXIT_BLOCK);
  }

  // -- Proteccion de archivos sensibles ---------------------
  if (/\.(pfx|key|pem|p12)\b/i.test(command)) {
    if (/\b(rm|del|Remove-Item|move|mv)\b/i.test(command)) {
      console.error(h.txt('BLOQUEADO: Operacion destructiva sobre certificado/clave privada detectada.', 'BLOCKED: destructive operation on a certificate or private key detected.'));
      process.exit(EXIT_BLOCK);
    }
  }

  // -- Advertencia dotnet run (no bloquea) ---------------------------
  if (/\bdotnet\s+run\b/i.test(command)) {
    console.log(h.txt('AVISO: dotnet run detectado. Verifica que launchSettings.json existe y el perfil es correcto.',
                      'WARNING: dotnet run detected. Check that launchSettings.json exists and the profile is right.'));
  }

  process.exit(0);
} catch (e) {
  // Error inesperado: permitir operacion en lugar de romper el flujo.
  // Log a stderr para diagnostico (no interfiere con exit 0).
  console.error(h.txt(`bash-guard.js: error inesperado, permitiendo operacion. Detalle: ${e && e.message ? e.message : e}`,
                      `bash-guard.js: unexpected error, allowing the operation. Detail: ${e && e.message ? e.message : e}`));
  process.exit(0);
}

Historial

7 cambios · 2026-09-07 → 2026-09-22. Último cambio: fix(higiene): lo que nadie mira no esta bien (ADR-076).

Notas de versiones anteriores

  • v2.1.0: safeTargets incluye .git/*.lock (FB-001: borrar un index.lock/HEAD.lock
  • huerfano que deja Visual Studio NO es destructivo).
  • v2.0.0: try/catch global, git restore ., branch -D, --no-verify, stash drop/clear, SQL DROP
  • ampliado, --force-with-lease NO bloqueado, word boundaries. v1.0.0: 7 patrones basicos.
  • Politica: BLOCK INTRINSECO — resolvePolicy con intrinsicBlock:true devuelve
  • 'block' incondicionalmente (operaciones destructivas irreversibles, no degradable a WARN).
Ovillo v1.31.0tag v1.31.0 (2026-10-06) · sin decisiones posteriores69 skills · 19 agents · 22 hooks · 3 reglas · 15 tools · 103 decisionesfuente: ovillo/.claude/hooks/bash-guard.jsCopyright 2026 Hugo Valer Rojas · Apache-2.0