{"slug": "scanning-env-files-logs-for-leaked-secrets-in-pure-js-using-shannon-entropy", "title": "Scanning .env Files & Logs for Leaked Secrets in Pure JS Using Shannon Entropy", "summary": "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.", "body_md": "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.\n\nPasting sensitive logs into an online \"secret checker\" that uploads your text to a backend server defeats the entire purpose.\n\nHere 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**.\n\nDeterministic prefixes catch structured vendor tokens cleanly (`AKIA...` for AWS, `sk-proj-...` for OpenAI, `sk-ant-...` for Anthropic, `ghp_...` for GitHub, or `eyJ...` for JWTs).\n\nHowever, 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:\n\n``` js\nfunction shannonEntropy(str) {\n  if (!str) return 0;\n  const freq = {};\n  for (let i = 0; i < str.length; i++) {\n    freq[str[i]] = (freq[str[i]] || 0) + 1;\n  }\n  let h = 0;\n  const len = str.length;\n  for (const ch in freq) {\n    const p = freq[ch] / len;\n    h -= p * Math.log2(p);\n  }\n  return h;\n}\n```\n\nNormal 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**.\n\nBy 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:\n\n``` js\nconst SECRET_PATTERNS = [\n  { name: 'AWS Access Key ID', re: /\\bAKIA[0-9A-Z]{16}\\b/g, mask: '[REDACTED_AWS_ACCESS_KEY]' },\n  { name: 'OpenAI API Key', re: /\\bsk-(?:proj-)?[A-Za-z0-9_\\-]{20,}\\b/g, mask: '[REDACTED_OPENAI_KEY]' },\n  { name: 'Anthropic API Key', re: /\\bsk-ant-[A-Za-z0-9_\\-]{20,}\\b/g, mask: '[REDACTED_ANTHROPIC_KEY]' },\n  { name: 'GitHub PAT', re: /\\b(?:ghp|gho|ghs|github_pat)_[A-Za-z0-9_]{24,}\\b/g, mask: '[REDACTED_GITHUB_TOKEN]' },\n  { 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]' },\n  {\n    name: 'Database URI Password',\n    re: /((?:postgres(?:ql)?|mongodb(?:\\+srv)?|mysql|redis):\\/\\/[^:\\s]+:)([^@\\s]+)(@)/gi,\n    maskGroup: true\n  }\n];\n\nfunction sanitizeConfigOrLog(rawText) {\n  let redacted = rawText || '';\n  const findings = [];\n\n  for (const pat of SECRET_PATTERNS) {\n    pat.re.lastIndex = 0;\n    let m;\n    while ((m = pat.re.exec(rawText)) !== null) {\n      findings.push({\n        type: pat.name,\n        preview: m[0].slice(0, 8) + '...' + m[0].slice(-3),\n        entropy: shannonEntropy(m[0]).toFixed(2)\n      });\n    }\n    redacted = pat.maskGroup\n      ? redacted.replace(pat.re, '$1[REDACTED_DB_PASSWORD]$3')\n      : redacted.replace(pat.re, pat.mask);\n  }\n\n  // Catch prefix-less high-entropy secrets (e.g. WEBHOOK_SIGNING_SECRET=...)\n  rawText.split(/\\r?\\n/).forEach((line, idx) => {\n    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);\n    if (kv && redacted.includes(kv[2])) {\n      const ent = shannonEntropy(kv[2]);\n      if (ent >= 3.8) {\n        findings.push({\n          type: `High-Entropy Secret (${kv[1]}, Line ${idx + 1})`,\n          preview: kv[2].slice(0, 6) + '...',\n          entropy: ent.toFixed(2)\n        });\n        redacted = redacted.split(kv[2]).join('[REDACTED_HIGH_ENTROPY_SECRET]');\n      }\n    }\n  });\n\n  return { findings, redacted };\n}\n```\n\nWe 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:\n\n`.env` Sanitizer:`npm`, `PyPI`, `go.mod`, `Cargo.toml`):` v1.1.0` — Git History Scanner & Pre-Commit Hook):`pip install it-solutions-suite` (", "url": "https://wpnews.pro/news/scanning-env-files-logs-for-leaked-secrets-in-pure-js-using-shannon-entropy", "canonical_source": "https://dev.to/itsolutionsglobal/scanning-env-files-logs-for-leaked-secrets-in-pure-js-using-shannon-entropy-3nhj", "published_at": "2026-11-28 21:34:26+00:00", "updated_at": "2026-11-28 21:44:22.683995+00:00", "lang": "en", "topics": ["ai-tools", "developer-tools", "ai-safety"], "entities": ["AWS", "OpenAI", "Anthropic", "GitHub", "npm", "PyPI"], "also_reported_by": [], "takeaway": "Combine deterministic vendor-prefix regexes with a Shannon entropy sweep at a 3.8 bits/char threshold to catch prefix-less secrets like signing keys, and run it fully client-side so sensitive logs never leave the machine.", "recommendation": {"advice": "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.", "playbook": "agent-security", "playbook_url": "https://wpnews.pro/playbooks/agent-security"}, "alternates": {"html": "https://wpnews.pro/news/scanning-env-files-logs-for-leaked-secrets-in-pure-js-using-shannon-entropy", "markdown": "https://wpnews.pro/news/scanning-env-files-logs-for-leaked-secrets-in-pure-js-using-shannon-entropy.md", "text": "https://wpnews.pro/news/scanning-env-files-logs-for-leaked-secrets-in-pure-js-using-shannon-entropy.txt", "jsonld": "https://wpnews.pro/news/scanning-env-files-logs-for-leaked-secrets-in-pure-js-using-shannon-entropy.jsonld"}}