/**
 * audit-log.js — PostToolUse Hook
 * 稽核所有 Bash 指令，自動 redact momo 敏感 Token。
 */
const fs = require('fs');
const os = require('os');
const path = require('path');
let d = '';
process.stdin.on('data', c => d += c);
process.stdin.on('end', () => {
  try {
    const input = JSON.parse(d);
    let cmd = input.tool_input?.command || '';
    if (!cmd) { process.stdout.write(d); return; }
    // Redact
    cmd = cmd.replace(/\d{8,12}:[A-Za-z0-9_-]{35}/g, '<TELEGRAM_TOKEN>');
    cmd = cmd.replace(/sk-ant-api[0-9a-zA-Z_-]{20,}/g, '<ANTHROPIC_KEY>');
    cmd = cmd.replace(/AIza[a-zA-Z0-9_-]{35}/g, '<GOOGLE_KEY>');
    cmd = cmd.replace(/glpat-[a-zA-Z0-9_-]{20}/g, '<GITEA_PAT>');
    cmd = cmd.replace(/sk-[a-zA-Z0-9]{20,}/g, '<API_KEY>');
    cmd = cmd.replace(/(password\s*=\s*)[^\s'"]+/gi, '$1<REDACTED>');
    cmd = cmd.replace(/\n/g, ' ');
    const logPath = path.join(os.homedir(), '.claude', 'bash-commands.log');
    const logDir = path.dirname(logPath);
    if (!fs.existsSync(logDir)) fs.mkdirSync(logDir, { recursive: true });
    fs.appendFileSync(logPath, `[${new Date().toISOString()}] ${cmd}\n`);
  } catch (e) {}
  process.stdout.write(d);
});
