Blocking Secrets & PDPA/PCI Leaks Before They Hit External LLMs or GitHub

Why .gitignore Isn’t Enough with AI Coding Agents#

When an AI coding agent reads files and executes git commands on your workstation, sensitive data has two outbound exit paths: (1) Outbound LLM Prompts (e.g., an agent reading .env via read_file or a developer pasting customer records into chat) and (2) Outbound Git Commits & Pushes to remote repositories.

Relying on .gitignore and developer memory doesn’t scale across dozens of daily agent sessions. To close both exits systematically, I built a two-boundary defense:

  1. Outbound LLM Boundary (ai-privacy-gateway): A zero-dependency Node.js middleware wired directly into the local LLM router (port 20128) running 16 Secret Rules (OWASP LLM02) and 5 PDPA/PCI-DSS Rules in ~0.3 ms, backed by a toggleable semantic classifier (Jev System One).
  2. Outbound Git Boundary (~/.githooks): Global pre-commit and pre-push hooks combining gitleaks (deterministic secret scan) with jev-git-guard (a fast Rust binary ported from Python) to evaluate diffs semantically before commits leave the machine.

Why Plain Regex Rules Aren’t Enough#

  1. Naive regex triggers false positives: A 13-digit Unix timestamp looks identical to a Thai National ID without a checksum, and test fixtures like user@example.com inside source files shouldn’t be treated as customer PII.
  2. Scrubbing tool outputs breaks coding agents: Redacting mock phone numbers or placeholder emails inside read_file responses corrupts the code context and causes patch edits to fail.
  3. Unstructured business secrets have no prefix: Financial summaries, internal margins, or prompt injections don’t start with sk- or ghp_.
  4. pre-commit alone misses --no-verify: A pre-commit hook only inspects staged diffs; if a secret slipped into an earlier commit, only a pre-push hook checking @{u}..HEAD catches it before reaching GitHub.

Two-Boundary Defense Architecture#

Boundary 1: Outbound LLM Traffic (Port 20128)
[ Hermes / CLI / IDE ]
│ (/v1/chat/completions, /v1/messages, /v1/responses)
▼
[ ai-privacy-gateway (wrapHttpHandler inside 9router) ]
├── Stage 1 (~0.3 ms): Deterministic Regex + Checksums
│ ├── Role = ALL (user, system, tool) ──► 16 Secret Rules (OWASP LLM02)
│ └── Role = USER only ──► 5 PDPA/PCI Rules (Modulo-11 + Luhn)
├── Stage 2 (~250–320 ms, toggleable): Jev System-One Semantic Classifier
└── Zero-Leak Audit Log (privacy-audit.jsonl: 5MB x 3, 64KB tail read)
│
▼
[ Upstream LLM Providers ]
Boundary 2: Outbound Git Traffic (~/.githooks)
[ git commit ] ──► gitleaks protect --staged ──► jev-git-guard.exe (pre-commit)
[ git push ] ──► jev-git-guard.exe --mode=pre-push (diff @{u}..HEAD) ──► GitHub

Boundary 1: ai-privacy-gateway (Pure Node.js, Zero External Dependencies)#

  • Role-Aware Scrubbing:
    • SECRETS_PRESET (16 rules) runs on ALL roles (user, system, assistant, tool): Covers Anthropic (sk-ant-), OpenAI (sk-), MaxPlus (ccsk/ccmk), GitHub (ghp_/github_pat_), AWS (AKIA/ASIA), Google API Keys (AIza), Slack, Telegram Bot Tokens, JWTs, Private Key blocks, DB connection strings (postgres://, mysql://, mongodb://, redis://), Bearer tokens, and .env assignments. Even if an agent reads a .env file via read_file, raw secrets are replaced with [REDACTED:...] before leaving the host.
    • PDPA_PCI_PRESET (5 rules) runs on role: "user" only: Protects Thai 13-digit National IDs, credit/debit card PANs, Thai phone numbers (06x/08x/09x & +66), emails, and context-aware bank accounts when pasted into chat, while leaving role: "tool" test fixtures intact.
  • Checksum Validators Against False Positives:
    • Thai National IDs must pass the Modulo-11 Checksum (ignoring 13-digit Unix timestamps).
    • Payment card PANs (13–19 digits) must pass the Luhn Algorithm (PCI-DSS).
    • Email checks allowlist placeholder domains (@example.com, @example.org, @example.net, @localhost, @users.noreply.github.com).
  • Stage 2 Semantic Classifier (src/classifier.js): Calls TypeSafe System One (jev-latest / jev-1.14.0) to classify unstructured business confidentiality (public, internal, confidential, restricted), contains_real_pii, and is_prompt_injection. Supports live runtime toggling (off | selective | always and tag | block) via POST /v1/privacy/config with zero restarts.
  • Zero-Leak Audit Log (logs/privacy-audit.jsonl): Records rule names and post-redaction snippets only—never raw PII or secrets—with SHA-256 deduplication (maxSeenHashes = 2000), automatic 5 MB x 3 rotation, and bounded 64 KB tail reads (GET /v1/privacy/audit).

Boundary 2: Global Git Hooks (gitleaks + jev-git-guard)#

  • Global core.hooksPath = ~/.githooks applies across every repository on the workstation (and chains .git/hooks/pre-commit.local if a repo has custom hooks).
  • pre-commit (2 layers):
    1. gitleaks protect --staged --verbose catches deterministic secret patterns in staged changes.
    2. jev-git-guard.exe (Rust port of jev-git-guard.py with 100% behavior parity) evaluates the diff semantically.
  • pre-push (--mode=pre-push): Inspects unpushed commits (@{u}..HEAD) so secrets committed earlier or via --no-verify are still blocked before leaving the machine.
  • Decision Gate Thresholds:
    • has_secrets.noul >= 0.60 -> BLOCK (exit 1)
    • is_destructive.noul >= 0.75 (deleting critical configs, schemas, lockfiles) -> BLOCK (exit 1)
    • verdict == "block" with confidence >= 0.70 -> BLOCK (exit 1)
    • Missing API keys or network timeouts fail-open (exit 0) so offline work never locks up, with JEV_GUARD_SKIP=1 and JEV_GUARD_ONLY escape hatches.

Replicating This Setup (Step-by-Step + Master Prompt)#

Step 1: Enable Global Git Hooks in Two Minutes#

  1. Install gitleaks and create ~/.githooks.
  2. Point Git globally to it: git config --global core.hooksPath ~/.githooks.
  3. Add a pre-commit hook running gitleaks protect --staged --verbose (plus your semantic diff guard) and a pre-push hook checking @{u}..HEAD.

Step 2: Master Prompt to Scaffold an Outbound Privacy Middleware#

Build a zero-dependency Node.js Outbound AI Privacy Middleware for a local LLM proxy with role-aware scrubbing:
1. Stage 1 Deterministic Scrubber (<1ms):
- Implement SECRETS_PRESET (OpenAI, Anthropic, GitHub PAT, AWS, Google API Key, JWT, Private Key, DB URIs, Bearer, .env assignments) running on ALL message roles (user, system, assistant, tool).
- Implement PDPA_PCI_PRESET (13-digit Thai National ID with Modulo-11 checksum, credit card PAN with Luhn checksum, Thai phone numbers, emails skipping @example.com/@localhost) running on role: "user" only so coding agents reading mock test files aren't broken.
2. Stage 2 Semantic Classifier (Toggleable):
- Expose POST /v1/privacy/config to switch modes (off | selective | always) and actions (tag | block) at runtime.
3. Zero-Leak Audit Logger:
- Log only rule names and redacted snippets to privacy-audit.jsonl with file rotation and bounded tail reads (e.g. 64 KB).
4. Unit Tests:
- Verify 13-digit timestamps don't trigger National ID redaction, placeholder emails remain untouched in tool outputs, and .env secrets are scrubbed across all roles.

Real-World Pitfalls Solved#

ChallengeOperational ImpactWorking Solution
Git Hooks Don’t Inherit Agent Env VarsHooks running from terminal shells couldn’t see TYPESAFE_API_KEYAdded safe .env parsing from %LOCALAPPDATA%/hermes/.env as a fallback while letting real process env vars take precedence.
Router Upgrades Wiped Injected MiddlewareRunning npm i -g 9router@latest overwrote custom-server.jsBuilt npm run patch-9router (scripts/patch-9router.js) to back up and re-wire wrapHttpHandler idempotently after upgrades.
Python Interpreter Startup Overhead on Every CommitSpawning Python on every git commit added noticeable lagPorted the guard to Rust (jev-git-guard-rs) and verified 100% parity against jev-git-guard.py using a 7-scenario harness (mock_jev.py + run_parity.sh).

Measured Results & Verification#

  • Stage 1 Latency: ~0.3 ms per request (all 7/7 unit & E2E tests passing in ai-privacy-gateway).
  • Stage 2 Semantic Classifier (jev-1.14.0):
    • Normal coding prompt (Merge Sort) -> level: "public", sensitivityScore: 0, flagged: false
    • Prompt containing factory profit figures + customer data -> Stage 1 scrubbed Thai National ID & phone immediately; Stage 2 scored level: "confidential", sensitivityScore: 0.7933, containsRealPii: 0.78, flagged: true in 322.7 ms
  • Git Hooks (gitleaks + jev-git-guard): Active on real commits and pushes (~180 ms for gitleaks and ~300–450 ms for jev-git-guard Rust binary); jev-git-guard-rs passes 8/8 unit tests and 7/7 parity scenarios.
Blocking Secrets & PDPA/PCI Leaks Before They Hit External LLMs or GitHub
https://www.chinnakrit.dev/posts/ai-privacy-gateway-and-git-guard/
Author
chinnakrit
Published
2026-11-13
License
CC BY-NC-SA 4.0
© 2026 chinnakrit
RSS / Sitemap
Powered by Astro & Fuwari
© 2026 chinnakrit
RSS / Sitemap
Powered by Astro & Fuwari