Every week, production API keys and database passwords end up pasted into GitHub issues, Slack threads, support tickets, or cloud LLM prompts because a developer copied a stack trace or .env snippet while debugging an incident.

Pasting sensitive logs into an online "secret checker" that uploads your text to a backend server defeats the entire purpose.

Here is how you can build a 100% client-side secret & log sanitizer in ~60 lines of zero-dependency JavaScript by combining deterministic token signatures with Shannon information entropy.

Deterministic prefixes catch structured vendor tokens cleanly (AKIA... for AWS, sk-proj-... for OpenAI, sk-ant-... for Anthropic, ghp_... for GitHub, or eyJ... for JWTs).

However, internal secrets like JWT_SIGNING_SECRET, COOKIE_KEY, or WEBHOOK_HMAC_SECRET are usually raw hex or base64 strings with no vendor prefix. That is where Shannon Entropy ($H$, measured in bits per character) shines:

function shannonEntropy(str) {
  if (!str) return 0;
  const freq = {};
  for (let i = 0; i < str.length; i++) {
    freq[str[i]] = (freq[str[i]] || 0) + 1;
  }
  let h = 0;
  const len = str.length;
  for (const ch in freq) {
    const p = freq[ch] / len;
    h -= p * Math.log2(p);
  }
  return h;
}

Normal English words or configuration values (production, us-east-1, postgres-primary) typically score $2.5 ext{–}3.4$ bits/char, whereas cryptographic hex and base64 secrets score $3.8 ext{–}5.2+$ bits/char.

By running deterministic patterns first (preserving URI hostnames while masking only the embedded password) and then sweeping KEY=VALUE assignments for high entropy, you get both an audit report and a safe copy-pasteable config:

const SECRET_PATTERNS = [
  { name: 'AWS Access Key ID', re: /\bAKIA[0-9A-Z]{16}\b/g, mask: '[REDACTED_AWS_ACCESS_KEY]' },
  { name: 'OpenAI API Key', re: /\bsk-(?:proj-)?[A-Za-z0-9_\-]{20,}\b/g, mask: '[REDACTED_OPENAI_KEY]' },
  { name: 'Anthropic API Key', re: /\bsk-ant-[A-Za-z0-9_\-]{20,}\b/g, mask: '[REDACTED_ANTHROPIC_KEY]' },
  { name: 'GitHub PAT', re: /\b(?:ghp|gho|ghs|github_pat)_[A-Za-z0-9_]{24,}\b/g, mask: '[REDACTED_GITHUB_TOKEN]' },
  { name: 'JWT Bearer Token', re: /\beyJ[A-Za-z0-9_\-]{10,}\.eyJ[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,}\b/g, mask: '[REDACTED_JWT_TOKEN]' },
  {
    name: 'Database URI Password',
    re: /((?:postgres(?:ql)?|mongodb(?:\+srv)?|mysql|redis):\/\/[^:\s]+:)([^@\s]+)(@)/gi,
    maskGroup: true
  }
];

function sanitizeConfigOrLog(rawText) {
  let redacted = rawText || '';
  const findings = [];

  for (const pat of SECRET_PATTERNS) {
    pat.re.lastIndex = 0;
    let m;
    while ((m = pat.re.exec(rawText)) !== null) {
      findings.push({
        type: pat.name,
        preview: m[0].slice(0, 8) + '...' + m[0].slice(-3),
        entropy: shannonEntropy(m[0]).toFixed(2)
      });
    }
    redacted = pat.maskGroup
      ? redacted.replace(pat.re, '$1[REDACTED_DB_PASSWORD]$3')
      : redacted.replace(pat.re, pat.mask);
  }

  // Catch prefix-less high-entropy secrets (e.g. WEBHOOK_SIGNING_SECRET=...)
  rawText.split(/\r?\n/).forEach((line, idx) => {
    const kv = line.match(/^\s*([A-Z0-9_]*(?:SECRET|TOKEN|PASSWORD|PRIVATE|SIGNING)[A-Z0-9_]*)\s*=\s*["']?([A-Za-z0-9+/=_\-]{24,})["']?\s*$/i);
    if (kv && redacted.includes(kv[2])) {
      const ent = shannonEntropy(kv[2]);
      if (ent >= 3.8) {
        findings.push({
          type: `High-Entropy Secret (${kv[1]}, Line ${idx + 1})`,
          preview: kv[2].slice(0, 6) + '...',
          entropy: ent.toFixed(2)
        });
        redacted = redacted.split(kv[2]).join('[REDACTED_HIGH_ENTROPY_SECRET]');
      }
    }
  });

  return { findings, redacted };
}

We shipped this scanner—alongside our zero-upload DevSecOps & compliance utilities—so you can sanitize .env files and debug logs locally before pasting them into tickets or AI chats:

.env Sanitizer:npm, PyPI, go.mod, Cargo.toml): v1.1.0 — Git History Scanner & Pre-Commit Hook):pip install it-solutions-suite (

原文来源:dev.to