v1.31.0
hookPreToolUse[Write|Edit]configurable

cert-expiry-reminder

Aviso sobre certificados x.509 caducados o proximos a caducar

PreToolUseevento
Write|Editmatcher
configurablepolítica
5 stimeout
2026-09-22último cambio

Qué comprueba

WARN-first: al detectar un cert CADUCADO, resolvePolicy(cfg, 'cert-expiry-reminder') decide exit 1 (warn, default) o exit 2 (block) segun ecosystem.config -> hooks.policy / hooks.blockList. certBlockOnExpired (ESTADO_PROYECTO.json) sigue siendo el opt-in strict del proyecto (mismo mensaje que el .ps1). Detecta edicion de archivos: .pfx, .cer, .crt, .p12 Para cada uno, lee la fecha de caducidad del cert: - crypto.X509Certificate de Node (equivalente al X509Certificate2 de .NET que usa el .ps1) para PEM/DER (.cer/.crt). - Para .pfx/.p12 (PKCS#12), fallback a openssl pkcs12 sin password via spawnSync; si openssl no esta disponible o el cert tiene password, degrada con gracia al mismo aviso "no se pudo leer" del .ps1 (exit 0). Comportamiento: - Cert caducado (NotAfter < hoy): AVISO por defecto (exit segun politica). - Caduca en <30 dias: warning critico (no bloquea, exit 0) - Caduca en <90 dias: warning (no bloquea, exit 0) - Caduca en >=90 dias: silencioso (exit 0 sin output)

Códigos de salida

ExitSignificado
0permitir (con aviso si caduca <90d)
1AVISO (politica warn) ·
2BLOCK (politica block)

Política

WARN-first: avisa (exit 1) por defecto y bloquea (exit 2) solo si la organización lo pone en hooks.blockList o sube hooks.policy a block.

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

cert-expiry-reminder.js · 205 líneas
#!/usr/bin/env node
// cert-expiry-reminder.js - Aviso sobre certificados x.509 caducados o proximos a caducar
// Evento: PreToolUse[Write|Edit]
// Exit 0 = permitir (con aviso si caduca <90d) · Exit 1 = AVISO (politica warn) ·
// Exit 2 = BLOCK (politica block)
//   WARN-first: al detectar un cert CADUCADO, resolvePolicy(cfg, 'cert-expiry-reminder')
//   decide exit 1 (warn, default) o exit 2 (block) segun ecosystem.config ->
//   hooks.policy / hooks.blockList. certBlockOnExpired (ESTADO_PROYECTO.json) sigue
//   siendo el opt-in strict del proyecto (mismo mensaje que el .ps1).
//
// Detecta edicion de archivos: *.pfx, *.cer, *.crt, *.p12
// Para cada uno, lee la fecha de caducidad del cert:
//   - crypto.X509Certificate de Node (equivalente al X509Certificate2 de .NET que usa
//     el .ps1) para PEM/DER (.cer/.crt).
//   - Para .pfx/.p12 (PKCS#12), fallback a `openssl pkcs12` sin password via spawnSync;
//     si openssl no esta disponible o el cert tiene password, degrada con gracia al
//     mismo aviso "no se pudo leer" del .ps1 (exit 0).
// Comportamiento:
//   - Cert caducado (NotAfter < hoy): AVISO por defecto (exit segun politica).
//   - Caduca en <30 dias: warning critico (no bloquea, exit 0)
//   - Caduca en <90 dias: warning (no bloquea, exit 0)
//   - Caduca en >=90 dias: silencioso (exit 0 sin output)

'use strict';

const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const { spawnSync } = require('child_process');
const h = require('./lib/helpers');
const cfgLib = require('./lib/config');

// Emitir aviso por stderr
function aviso(msg) {
  console.error(msg);
}

function fmtDate(d) {
  const y = d.getFullYear();
  const mo = String(d.getMonth() + 1).padStart(2, '0');
  const da = String(d.getDate()).padStart(2, '0');
  return `${y}-${mo}-${da}`;
}

// Node separa los RDN del subject/issuer con '\n'; .NET los une con ', '
function flattenDn(dn) {
  return String(dn).split('\n').join(', ');
}

function loadCertificate(filePath, ext) {
  const buf = fs.readFileSync(filePath);
  try {
    return new crypto.X509Certificate(buf); // PEM o DER (.cer/.crt)
  } catch (ePrimary) {
    // PKCS#12: X509Certificate no lo parsea; intentar openssl sin password
    if (ext === '.pfx' || ext === '.p12') {
      try {
        const r = spawnSync('openssl',
          ['pkcs12', '-in', filePath, '-nokeys', '-clcerts', '-passin', 'pass:'],
          { encoding: 'utf8' });
        if (r.status === 0 && r.stdout && r.stdout.includes('-----BEGIN CERTIFICATE-----')) {
          return new crypto.X509Certificate(r.stdout.slice(r.stdout.indexOf('-----BEGIN CERTIFICATE-----')));
        }
      } catch { /* openssl no disponible - degradar con gracia */ }
    }
    throw ePrimary;
  }
}

function main() {
  const hookData = h.readHookInput();
  const filePath = h.getFilePath(hookData);
  if (!filePath) return 0;

  // Solo procesar extensiones de cert
  const ext = path.extname(filePath).toLowerCase();
  const certExtensions = ['.pfx', '.cer', '.crt', '.p12'];
  if (!certExtensions.includes(ext)) return 0;

  // Si el archivo NO existe aun en disco (Write nuevo), no podemos leer cert -> avisar generico
  if (!fs.existsSync(filePath)) {
    aviso(h.txt(`AVISO cert-expiry-reminder: vas a crear un cert nuevo (${filePath}). Verifica:`,
            `WARNING cert-expiry-reminder: you are creating a new certificate (${filePath}). Check:`));
    aviso(h.txt('  1. Su fecha de caducidad (NotAfter) cubre el periodo de uso planeado',
            '  1. Its expiry date (NotAfter) covers the planned period of use'));
    aviso(h.txt('  2. Esta protegido por .gitignore (no commitear .pfx con clave privada)',
            '  2. It is covered by .gitignore (never commit a .pfx holding a private key)'));
    aviso(h.txt('  3. Su clave privada esta en Azure Key Vault si es para produccion',
            '  3. Its private key lives in a secrets vault if it is for production'));
    return 0;
  }

  // Leer config (umbrales custom + bloqueo configurable)
  const repoRoot = process.env.CLAUDE_PROJECT_DIR || process.cwd();
  const estadoFile = path.join(repoRoot, '_hilo', 'ESTADO_PROYECTO.json');
  let umbralWarning = 90;
  let umbralCritico = 30;
  let bloqueaCaducado = false; // default: SOLO AVISO (WARN-first). Opt-in para strict.

  const estado = h.readJsonSafe(estadoFile); // JSON corrupto/ausente -> defaults
  if (estado && estado.configuracion) {
    if (estado.configuracion.certWarningDias !== null && estado.configuracion.certWarningDias !== undefined) {
      umbralWarning = parseInt(estado.configuracion.certWarningDias, 10);
    }
    if (estado.configuracion.certCriticalDias !== null && estado.configuracion.certCriticalDias !== undefined) {
      umbralCritico = parseInt(estado.configuracion.certCriticalDias, 10);
    }
    if (estado.configuracion.certBlockOnExpired !== null && estado.configuracion.certBlockOnExpired !== undefined) {
      bloqueaCaducado = Boolean(estado.configuracion.certBlockOnExpired);
    }
  }

  // Leer el cert
  let notAfter, subject, issuer;
  try {
    const cert = loadCertificate(filePath, ext);
    notAfter = new Date(cert.validTo);
    subject = flattenDn(cert.subject);
    issuer = flattenDn(cert.issuer);
  } catch (e) {
    // Si el cert tiene password (.pfx) o esta corrupto, no podemos leer NotAfter
    // No bloquear - solo avisar
    aviso(h.txt(`AVISO cert-expiry-reminder: no se pudo leer fecha de caducidad de ${filePath}`,
            `WARNING cert-expiry-reminder: could not read the expiry date of ${filePath}`));
    aviso(h.txt(`  Razon: ${e.message}`,
            `  Reason: ${e.message}`));
    aviso(h.txt('  (puede ser .pfx con password o cert corrupto). Verifica manualmente.',
            '  (it may be a password-protected .pfx or a corrupt certificate). Check it by hand.'));
    return 0;
  }

  const ahora = new Date();
  const diasRestantes = Math.round((notAfter.getTime() - ahora.getTime()) / 86400000);

  // Truncar nombres largos para legibilidad
  const subjectShort = subject.length > 80 ? subject.substring(0, 77) + '...' : subject;
  const fileName = path.basename(filePath);

  // Cert caducado
  if (diasRestantes < 0) {
    const policy = cfgLib.resolvePolicy(cfgLib.load(), 'cert-expiry-reminder');
    const exitCode = policy === 'block' ? 2 : 1;
    const diasCaducado = Math.abs(diasRestantes);
    aviso('');
    aviso(h.txt(`AVISO cert-expiry-reminder: ${fileName} esta CADUCADO hace ${diasCaducado} dias.`,
            `WARNING cert-expiry-reminder: ${fileName} EXPIRED ${diasCaducado} days ago.`));
    aviso(`  Subject: ${subjectShort}`);
    aviso(`  Issuer: ${issuer}`);
    aviso(`  NotAfter: ${fmtDate(notAfter)}`);
    aviso('');
    aviso(h.txt('  Editar un cert caducado en lugar de renovar suele ser error.',
            '  Editing an expired certificate instead of renewing it is usually a mistake.'));
    aviso(h.txt('  Fix recomendado: renovar el cert con CA, NO modificar el archivo caducado.',
            '  Recommended fix: renew the certificate with the CA, do NOT edit the expired file.'));
    if (bloqueaCaducado) {
      aviso(h.txt('  Modo strict (certBlockOnExpired=true): bloqueando edit.',
            '  Strict mode (certBlockOnExpired=true): blocking the edit.'));
      return exitCode;
    }
    if (policy === 'block') {
      aviso(h.txt('  Politica: block (ecosystem.config hooks.policy): bloqueando edit.',
            '  Policy: block (ecosystem.config hooks.policy): blocking the edit.'));
    } else {
      aviso(h.txt(`  Modo default (politica: ${policy}, ecosystem.config hooks.policy): edit permitido, decide tu si renovar o continuar.`,
            `  Default mode (policy: ${policy}, ecosystem.config hooks.policy): the edit is allowed, renewing or continuing is your call.`));
      aviso(h.txt('  Para bloquear: setear configuracion.certBlockOnExpired=true en _hilo/ESTADO_PROYECTO.json',
            '  To block instead: set configuracion.certBlockOnExpired=true in _hilo/ESTADO_PROYECTO.json'));
    }
    return exitCode;
  }

  // Cert critico (<30 dias)
  if (diasRestantes < umbralCritico) {
    aviso(h.txt(`AVISO cert-expiry-reminder: ${fileName} caduca en ${diasRestantes} dias (umbral critico: ${umbralCritico}).`,
            `WARNING cert-expiry-reminder: ${fileName} expires in ${diasRestantes} days (critical threshold: ${umbralCritico}).`));
    aviso(`  Subject: ${subjectShort}`);
    aviso(`  NotAfter: ${fmtDate(notAfter)}`);
    aviso(h.txt('  ACCION INMEDIATA: solicitar renovacion del cert AHORA.',
            '  IMMEDIATE ACTION: request the certificate renewal NOW.'));
    return 0;
  }

  // Cert proximo (<90 dias)
  if (diasRestantes < umbralWarning) {
    aviso(h.txt(`AVISO cert-expiry-reminder: ${fileName} caduca en ${diasRestantes} dias (umbral warning: ${umbralWarning}).`,
            `WARNING cert-expiry-reminder: ${fileName} expires in ${diasRestantes} days (warning threshold: ${umbralWarning}).`));
    aviso(`  Subject: ${subjectShort}`);
    aviso(`  NotAfter: ${fmtDate(notAfter)}`);
    aviso(h.txt('  Planifica renovacion en las proximas semanas.',
            '  Plan the renewal over the coming weeks.'));
    return 0;
  }

  // Cert OK (>=90 dias) - silencioso
  return 0;
}

try {
  process.exit(main());
} catch (e) {
  console.error(h.txt(`cert-expiry-reminder: error inesperado (${e.message}) - no se bloquea el flujo`,
                    `cert-expiry-reminder: unexpected error (${e.message}) - not blocking`));
  process.exit(0);
}

Historial

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

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/cert-expiry-reminder.jsCopyright 2026 Hugo Valer Rojas · Apache-2.0