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:
- Outbound LLM Boundary (
ai-privacy-gateway): A zero-dependency Node.js middleware wired directly into the local LLM router (port20128) 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). - Outbound Git Boundary (
~/.githooks): Globalpre-commitandpre-pushhooks combininggitleaks(deterministic secret scan) withjev-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
- 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.cominside source files shouldn’t be treated as customer PII. - Scrubbing
tooloutputs breaks coding agents: Redacting mock phone numbers or placeholder emails insideread_fileresponses corrupts the code context and causespatchedits to fail. - Unstructured business secrets have no prefix: Financial summaries, internal margins, or prompt injections don’t start with
sk-orghp_. pre-commitalone misses--no-verify: Apre-commithook only inspects staged diffs; if a secret slipped into an earlier commit, only apre-pushhook checking@{u}..HEADcatches 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) ──► GitHubBoundary 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.envassignments. Even if an agent reads a.envfile viaread_file, raw secrets are replaced with[REDACTED:...]before leaving the host.PDPA_PCI_PRESET(5 rules) runs onrole: "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 leavingrole: "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, andis_prompt_injection. Supports live runtime toggling (off | selective | alwaysandtag | block) viaPOST /v1/privacy/configwith 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), automatic5 MB x 3rotation, and bounded64 KBtail reads (GET /v1/privacy/audit).
Boundary 2: Global Git Hooks (gitleaks + jev-git-guard)
- Global
core.hooksPath = ~/.githooksapplies across every repository on the workstation (and chains.git/hooks/pre-commit.localif a repo has custom hooks). pre-commit(2 layers):gitleaks protect --staged --verbosecatches deterministic secret patterns in staged changes.jev-git-guard.exe(Rust port ofjev-git-guard.pywith 100% behavior parity) evaluates the diff semantically.
pre-push(--mode=pre-push): Inspects unpushed commits (@{u}..HEAD) so secrets committed earlier or via--no-verifyare 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"withconfidence >= 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=1andJEV_GUARD_ONLYescape hatches.
Replicating This Setup (Step-by-Step + Master Prompt)
Step 1: Enable Global Git Hooks in Two Minutes
- Install
gitleaksand create~/.githooks. - Point Git globally to it:
git config --global core.hooksPath ~/.githooks. - Add a
pre-commithook runninggitleaks protect --staged --verbose(plus your semantic diff guard) and apre-pushhook 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
| Challenge | Operational Impact | Working Solution |
|---|---|---|
| Git Hooks Don’t Inherit Agent Env Vars | Hooks running from terminal shells couldn’t see TYPESAFE_API_KEY | Added safe .env parsing from %LOCALAPPDATA%/hermes/.env as a fallback while letting real process env vars take precedence. |
| Router Upgrades Wiped Injected Middleware | Running npm i -g 9router@latest overwrote custom-server.js | Built npm run patch-9router (scripts/patch-9router.js) to back up and re-wire wrapHttpHandler idempotently after upgrades. |
| Python Interpreter Startup Overhead on Every Commit | Spawning Python on every git commit added noticeable lag | Ported 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 msper request (all 7/7 unit & E2E tests passing inai-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: truein 322.7 ms
- Normal coding prompt (
- Git Hooks (
gitleaks+jev-git-guard): Active on real commits and pushes (~180 ms forgitleaksand ~300–450 ms forjev-git-guardRust binary);jev-git-guard-rspasses 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/ Writing Overview
8 posts
Posts
7,530
Total Words
39min
Reading Time
941
Avg Words
Posts by Year
2026 14
2024 1
Longest Posts
1 Software QA, Automated Testing Sandbox & Code Audit for AI Desktop Plugins 1,991 2 Blocking Secrets & PDPA/PCI Leaks Before They Hit External LLMs or GitHub 1,111 3 Goodbye Physical NAS? Turning Google Drive into a 5TB Virtual Drive (20TB-Ready) with rclone + WinFsp 1,044 4 Isolating AI from Your Real Browser: Building Edgebot MCP with Code-Enforced Guardrails 957 5 Case Study: Engineering & Auditing Production Desktop Plugins for Hermes Agent 758