Dev.to AI 🤖 Ai 👁 0 📖 6 min read

Why Pure Regex Secret Scanners Break Real Debug Logs — and How Entropy + Context Whitelisting Fixes Local AI Prompt Sanitization

Every week, more of our debugging workflow happens inside Claude Code, Cursor, or ChatGPT. You hit a 502 in a staging worker, copy 60 lines of stack trace, an .env snippet, or a browser DevTools request dump, and paste i

Every week, more of our debugging workflow happens inside Claude Code, Cursor, or ChatGPT. You hit a 502 in a staging worker, copy 60 lines of stack trace, an .env snippet, or a browser DevTools request dump, and paste it straight into an AI chat.

Three seconds later, you realize line 14 had DATABASE_URL=postgres://billing_rw:... and line 19 had your Authorization: Bearer ... token.

If you try to solve this by searching for a quick regex script to scrub secrets before prompting, you run straight into a classic engineering trap: pure regex secret scanners fail in both directions.

Why Naive Regex Breaks Real Debug Logs

When we started upgrading BlurDock from a screen-share privacy extension into an AI Secret Guard (v1.1.0), we tested standard regex-only secret lists against real Node.js stack traces, HTTP dumps, and .env files. Two failure modes showed up immediately:

1. False negatives on unprefixed secrets

Vendor-prefixed keys (sk-proj-..., sk-ant-..., AKIA..., ghp_..., sk_live_...) are the easy 50%. The other 50% of credentials in real debugging sessions have no universal vendor prefix:

  • Custom webhook signing secrets (WEBHOOK_SIGNING_SECRET=wh9k2M8pQ4rT7vX1zC5bN0mL3jH6fD)
  • Opaque Authorization: Bearer tokens
  • Session cookies (Cookie: session_id=sess_8a7b6c5d4e3f2g1h9i0j; theme=dark)
  • Database credentials embedded inside postgres://user:pass@host:5432/db

2. False positives that wreck debuggability

The standard workaround—matching any long alphanumeric token or any string with high randomness—destroys the very debug context the LLM needs:

  • Git commit SHAs (commit=a8c9f01e2b3d4c5a6b7c8d9e0f1a2b3c4d5e6f7a) get redacted.
  • Lockfile SRI hashes (sha512-9f8e7d6c5b4a...) get redacted.
  • Long camelCase TypeScript identifiers (createUserSessionTokenHandler) get redacted.
  • Documentation placeholders (OPENAI_API_KEY=your_api_key_here_replace_me) get redacted.
  • 16-digit order or tracking IDs (4532 0151 1283 0367) get mistaken for credit card numbers.

And if a naive scrubber replaces all secrets with the exact same literal [REDACTED], the AI can no longer tell whether the failing retry used the same API key as the initial request or a mismatched second key.

A 3-Layer Architecture That Runs 100% Locally in Browser RAM

We wanted a detector small enough to ship inside a zero-dependency Manifest V3 browser extension (strictly activeTab, scripting, and storage permissions—zero network calls) and fast enough to run on every keystroke inside a standalone web tool.

Here is the three-layer pipeline we converged on.

Layer 1: Vendor Signatures + Capture-Group Boundary Preservation

For known credential formats, high-precision signatures run first at priority 1 (PEM private key blocks, database DSNs, OpenAI/Anthropic/AWS/GitHub/Stripe/Slack/Google keys, JWTs).

For structured headers like Authorization: Bearer and Cookie:, capture-group indexing matters more than people expect. Instead of replacing the entire header line, we only slice out the secret group (match[2]):

{
  type: 'secret',
  subtype: 'COOKIE_SECRET',
  regex: /(\b(?:session_?id|sid|connect\.sid|auth_?token|__Secure-[A-Za-z0-9_.-]+)\s*=\s*)([A-Za-z0-9._~%+/=-]{12,})/gi,
  valueGroup: 2,
}

That turns:

Cookie: session_id=sess_8a7b6c5d4e3f2g1h9i0j; theme=dark
Authorization: Bearer tok_prod_9f8e7d6c5b4a3210XyZwVuTsRq

into:

Cookie: session_id=<COOKIE_SECRET_1>; theme=dark
Authorization: Bearer <BEARER_TOKEN_1>

The LLM still sees the exact header scheme (Bearer) and non-sensitive cookies (theme=dark), while zero credential bytes leave your machine.

For numeric PII, we apply strict validators instead of loose digit patterns: Luhn checksum verification for 13–19 digit payment cards (rejecting invalid order IDs like 4532 0151 1283 0367) and strict octet validation for IPv4 (distinguishing RFC1918/loopback <INTERNAL_IP_1> from public <IP_ADDR_1> while ignoring version strings like 10.01.2.3).

Layer 2: Context-Gated Shannon Entropy + Structural Whitelist

To catch unprefixed secrets (WEBHOOK_SIGNING_SECRET, CLIENT_SECRET, DB_PASS) without shredding code, we combine a key-context matcher with Shannon entropy:

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

In real logs, the entropy separation is sharp:

Token Sample Shannon Entropy (bits/char) Verdict
aaaaaaaaaaaa 0.00 Rejected (low entropy)
your_api_key_here_replace_me 3.45 Rejected by placeholder whitelist
createUserSessionTokenHandler 3.69 Rejected by camelCase identifier whitelist
sha512-9f8e7d6c5b4a... 5.27 Rejected by SRI hash whitelist
wh9k2M8pQ4rT7vX1zC5bN0mL3jH6fD 4.91 Caught (entropy+context → <API_SECRET_1>)
sk-proj-9x8y7zAbCdEf... 5.15 Caught (signature → <OPENAI_KEY_1>)

Notice rows 2–4: entropy alone is not enough. A long camelCase TypeScript symbol clears 3.69 bits/char, and an npm sha512- integrity digest hits 5.27 bits/char—even higher than an actual OpenAI key. Putting a lightweight structural whitelist before the entropy gate eliminates almost every developer false positive:

  1. Reject obvious template values (your_*, replace_me, changeme, placeholder).
  2. Reject pure camelCase / PascalCase or snake_case words with zero digits.
  3. Reject SRI digests (sha256-..., sha512-...), plain file paths (/usr/local/...), and non-credential URLs.
  4. Reject tokens preceded by non-secret context keys (commit=, git_sha=, integrity=, checksum=, trace_id=, etag=).
  5. Require mixed character classes (or 32+ char hex) and entropy ≥ 3.3 bits/char (configurable).

Layer 3: Deterministic Reversible Placeholders (RAM-Only Rehydration)

Instead of destructive [REDACTED] blocks, we assign each unique sensitive value a consistent, typed placeholder:

  • First OpenAI key → <OPENAI_KEY_1> (reused everywhere that exact key appears)
  • First Postgres DSN → <DATABASE_URL_1>
  • First internal IP → <INTERNAL_IP_1>

Because the mapping { "<OPENAI_KEY_1>": "sk-proj-..." } stays strictly inside local browser memory (never written to localStorage or sent over the network), you get a clean round-trip workflow:

  1. Scrub your log, .env, or curl dump locally.
  2. Paste the sanitized context into Claude Code, Cursor, or ChatGPT with a one-line note to preserve <PLACEHOLDER_N> tokens.
  3. Restore the AI's suggested patch or config locally in one click—swapping <OPENAI_KEY_1> and <DATABASE_URL_1> back into real values without ever exposing them to a remote server.

Try It Locally (Zero Uploads, Verifiable in DevTools)

We shipped this exact engine in two ways—both 100% local and free to test:

  1. Standalone Browser Tool (no install required): BlurDock Free AI Prompt & Log Secret Sanitizer

    • Paste any stack trace, .env, or HTTP header dump (or click the built-in False-Positive Stress Test preset).
    • Inspect each match's Shannon entropy score and detector method in the live audit table, whitelist any item in one click, and test Tab 2's local RAM rehydration.
    • Open your DevTools Network tab while pasting: 0 bytes leave your browser.
  2. Browser Extension for Live Web Dashboards & Screenshots (BlurDock v1.1.0):

    • When the secrets live inside a web console (Stripe, AWS, Vercel, Datadog, or an internal admin panel), BlurDock v1.1 lets you Copy Safe for AI directly from any page selection or DOM table (stripping URL query parameters automatically) and Guard Keys to highlight and blur all detected secrets before capturing a screenshot.
    • Strictly activeTab, scripting, and storage permissions only—zero background page reading.
    • Install directly from Microsoft Edge Add-ons or Firefox Add-ons (AMO).

(If you're building a full local-first AI developer workflow, this pairs nicely with our other zero-upload tools from Kinto Labs: DESIGN.md Generator for extracting design tokens from live pages and Pixel Diff Prompt Generator for generating structured VISUAL_DIFF.md QA briefs.)

What edge-case secret formats or noisy false positives have bitten you when scrubbing logs for AI assistants? Drop a sanitized example in the comments—we're constantly tightening the local whitelist rules.

📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.