cd /news/ai-tools/scanning-env-files-logs-for-leaked-s… · home › topics › ai-tools › article
[ARTICLE · art-177892] src=dev.to ↗ pub= topic=ai-tools verified=true sentiment=↑ positive

Scanning .env Files & Logs for Leaked Secrets in Pure JS Using Shannon Entropy

A developer shipped a roughly 60-line, zero-dependency JavaScript secret scanner that combines deterministic vendor token signatures (AWS, OpenAI, Anthropic, GitHub, JWT) with Shannon entropy analysis to catch prefix-less secrets like signing keys and webhook HMACs in .env files and logs. The tool runs entirely client-side, producing an audit report of findings and a redacted, copy-pasteable config, and is distributed via npm, PyPI, go.mod and Cargo.toml. The author notes that ordinary config values typically score 2.5–3.4 bits/char while cryptographic hex and base64 secrets score 3.8–5.2+, which is used as the detection threshold.

recommendation

Sanitize .env files and debug logs locally with prefix regexes plus a Shannon entropy check at 3.8 bits/char before pasting them into tickets or AI chats.

more in playbook: Securing agents and AI tools
by read2 min views56 publishedNov 28, 2026

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 (

── more in #ai-tools 4 stories · sorted by recency
── more on @aws 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/scanning-env-files-l…] indexed:0 read:2min 2026-11-28 · —