Prompt Guard Architecture
Internal architecture documentation for contributors and maintainers.
Last updated: 2026-02-11 | v3.2.0
Overview
Prompt Guard uses a Defense in Depth design. Multiple inspection layers reduce false positives while effectively detecting attacks across 577+ patterns in 10 languages.
┌─────────────────────────────────────────────────────────────────┐
│ INPUT MESSAGE │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Layer 0: Message Size Check │
│ • Reject messages > 50KB (DoS prevention) │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Layer 1: Rate Limiting │
│ • Per-user request tracking (30 req/60s default) │
│ • Memory-bounded (max 10,000 tracked users) │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Layer 1.5: Cache Lookup (v3.1.0) │
│ • SHA-256 hash of normalized message │
│ • LRU cache (1,000 entries) │
│ • Cache hit → return immediately (90% token savings) │
└─────────────────────────────────────────────────────────────────┘
│ miss
▼
┌─────────────────────────────────────────────────────────────────┐
│ Layer 2: Text Normalization │
│ • Homoglyph detection & replacement (Cyrillic/Greek → Latin) │
│ • Visible delimiter stripping (I+g+n+o+r+e → Ignore) │
│ • Character spacing collapse (i g n o r e → ignore) │
│ • Zero-width character removal (17 types) │
│ • Fullwidth character normalization │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Layer 3: Pattern Matching Engine (Tiered) │
│ • Tier 0: CRITICAL (~45 patterns) — always loaded │
│ • Tier 1: HIGH (~82 patterns) — default │
│ • Tier 2: MEDIUM (~100+ patterns) — on-demand │
│ • Runs against ORIGINAL + all DECODED variants │
│ • 577+ patterns across 50+ categories │
│ • 10 languages: EN, KO, JA, ZH, RU, ES, DE, FR, PT, VI │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Layer 3.5: API Extra Patterns (v3.2.0 — optional) │
│ • Early-access patterns (API-first, flows to open source) │
│ • Premium patterns (API-exclusive) │
│ • Pre-compiled at init, merged into scan at runtime │
│ • Skipped entirely if API is disabled (default) │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Layer 4: Decode Pipeline │
│ • Base64 decode + full pattern re-scan │
│ • Hex escape decode (\x41\x42) │
│ • ROT13 decode (full-text + per-word) │
│ • URL decode (%69%67%6E) │
│ • HTML entity decode (i → i) │
│ • Unicode escape decode (\u0069 → i) │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Layer 5: Behavioral Analysis │
│ • Repetition detection (token overflow) │
│ • Invisible character detection (Unicode Tags U+E0001-U+E007F) │
│ • Korean Jamo decomposition attacks │
│ • Canary token check (system prompt extraction) │
│ • Language detection (flag unsupported languages) │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Layer 6: Context-Aware Decision │
│ • Sensitivity adjustment (low/medium/high/paranoid) │
│ • Owner bypass rules (LOG for HIGH, still BLOCK for CRITICAL) │
│ • Group context restrictions (non-owners blocked at MEDIUM+) │
└─────────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Layer 7: Result + Logging + Reporting │
│ • DetectionResult with severity, action, reasons, fingerprint │
│ • Markdown and/or JSONL logging (with optional hash chain) │
│ • HiveFence collective threat reporting │
│ • API threat reporting (v3.2.0, opt-in, anonymized) │
│ • Cache storage for future lookups │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ Layer 8: Output Scanner / DLP │
│ • scan_output() — LLM response scanning │
│ • Canary token leakage detection │
│ • Credential format patterns (17+ key formats) │
└─────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────┐
│ Layer 9: Enterprise DLP Sanitizer │
│ • sanitize_output() — redact-first, block-as-fallback │
│ • 17 credential patterns → [REDACTED:type] labels │
│ • Post-redaction re-scan: block if still HIGH+ │
│ • Returns SanitizeResult with full audit metadata │
└─────────────────────────────────────────────────────────────────┘
Core Components
Severity Levels
| Level |
Value |
Description |
Typical Trigger |
| SAFE |
0 |
No threat detected |
Normal conversation |
| LOW |
1 |
Minor suspicious signal |
Output manipulation |
| MEDIUM |
2 |
Clear manipulation attempt |
Role manipulation, urgency |
| HIGH |
3 |
Dangerous command |
Jailbreaks, system access |
| CRITICAL |
4 |
Immediate threat |
Secret exfil, code execution |
Action Types
| Action |
Description |
When Used |
allow |
No intervention |
SAFE severity |
log |
Record only |
Owner requests, LOW severity |
warn |
Notify user |
MEDIUM severity |
block |
Refuse request |
HIGH severity |
block_notify |
Block + alert owner |
CRITICAL severity |
Pattern Categories
Tier 0: CRITICAL (Always Loaded — ~45 patterns)
| Category |
Description |
secret_exfiltration |
API key/token/password requests, .env access |
dangerous_commands |
rm -rf, fork bombs, curl|bash, eval() |
sql_injection |
DROP TABLE, TRUNCATE, comment injection |
xss_injection |
Script tags, javascript: protocol |
prompt_extraction |
System prompt extraction attempts |
reverse_shell |
bash /dev/tcp, netcat -e, socat (v3.2.0) |
ssh_key_injection |
authorized_keys manipulation (v3.2.0) |
exfiltration_pipeline |
.env POST to webhook/external (v3.2.0) |
cognitive_rootkit |
SOUL.md/AGENTS.md implants (v3.2.0) |
Tier 1: HIGH (Default — ~82 patterns)
| Category |
Description |
instruction_override |
Multi-language instruction bypass (EN/KO/JA/ZH) |
jailbreak |
DAN mode, no restrictions, bypass |
system_impersonation |
[SYSTEM]:, admin mode, developer override |
system_mimicry |
Fake Claude/GPT tags, GODMODE |
hooks_hijacking |
PreToolUse, auto-approve exploitation |
semantic_worm |
Viral propagation, C2 heartbeat (v3.2.0) |
obfuscated_payload |
Error suppression chains, paste services (v3.2.0) |
Tier 2: MEDIUM (On-Demand — ~100+ patterns)
| Category |
Description |
role_manipulation |
Pretend/act as, multi-language |
authority_impersonation |
Fake admin/owner claims |
context_hijacking |
Fake memory/history injection |
emotional_manipulation |
Moral dilemmas, urgency |
agent_sovereignty |
Rights-based guardrail bypass |
API-Only Tiers (Optional — v3.2.0)
| Tier |
Description |
early |
Newest patterns, API users get 7-14 days before open-source |
premium |
Advanced detection: DNS tunneling, steganography, sandbox escape |
File Structure
prompt-guard/
├── prompt_guard/ # Core Python package
│ ├── __init__.py # Public API + version
│ ├── models.py # Severity, Action, DetectionResult, SanitizeResult
│ ├── engine.py # PromptGuard class (analyze, config, API integration)
│ ├── patterns.py # 577+ regex patterns (pure data)
│ ├── scanner.py # scan_text_for_patterns() (all pattern sets)
│ ├── api_client.py # Optional API client (v3.2.0)
│ ├── pattern_loader.py # Tiered pattern loading (v3.1.0)
│ ├── cache.py # LRU message hash cache (v3.1.0)
│ ├── normalizer.py # Homoglyph + text normalization
│ ├── decoder.py # 6 encoding decoders
│ ├── output.py # Output DLP + sanitize_output()
│ ├── logging_utils.py # SIEM logging + HiveFence reporting
│ ├── hivefence.py # HiveFence threat intelligence
│ ├── cli.py # CLI entry point
│ ├── audit.py # Security audit
│ └── analyze_log.py # Log analyzer
│
├── patterns/ # Pattern YAML files (tiered)
│ ├── critical.yaml # Tier 0 (~45 patterns)
│ ├── high.yaml # Tier 1 (~82 patterns)
│ └── medium.yaml # Tier 2 (~100+ patterns)
│
├── tests/
│ └── test_detect.py # 115+ regression tests
│
├── .github/workflows/
│ └── sync-patterns-to-api.yml # Auto-sync patterns to API server
│
├── ARCHITECTURE.md # This file
├── CHANGELOG.md # Full version history
├── SKILL.md # Agent skill definition
├── README.md # User documentation
├── config.example.yaml # Configuration template
├── pyproject.toml # Build config + dependencies
└── requirements.txt # Legacy install compatibility
API Integration (v3.2.0 — Optional)
Prompt Guard works fully offline. The API is an optional enhancement.
Pattern Delivery Model (Approach C: Hybrid)
Open Source (prompt-guard repo) API Server (PG_API)
┌──────────────────────────┐ ┌──────────────────────────┐
│ patterns/critical.yaml │──sync─│ data/core/critical.yaml │
│ patterns/high.yaml │──sync─│ data/core/high.yaml │
│ patterns/medium.yaml │──sync─│ data/core/medium.yaml │
└──────────────────────────┘ │ data/early/early.yaml │ ← API-first
│ data/premium/premium.yaml│ ← API-exclusive
└──────────────────────────┘
How API patterns are loaded
PromptGuard.__init__() checks config.api.enabled
- If enabled, lazy-imports
PGAPIClient and calls fetch_extra_patterns()
- Early + premium YAML content is fetched, parsed, validated (ReDoS check), and pre-compiled
- Compiled patterns stored in
self._api_extra_patterns
- During
analyze(), API patterns are checked alongside local patterns
- If API fails at any point, detection continues with local patterns only
Security design
- Pattern fetch is pull-only (no user data sent)
- Threat reporting is opt-in and anonymized (hashes only, never raw messages)
- API patterns are validated: 500-char limit, nested quantifier rejection, compile test
- Auth via
Authorization: Bearer <key> header
- API key via config (
api.key) or env var (PG_API_KEY)
Configuration Schema
prompt_guard:
sensitivity: medium # low | medium | high | paranoid
pattern_tier: high # critical | high | full
owner_ids: ["USER_ID"]
canary_tokens: ["CANARY:abc"]
cache:
enabled: true
max_size: 1000
actions:
LOW: log
MEDIUM: warn
HIGH: block
CRITICAL: block_notify
rate_limit:
enabled: true
max_requests: 30
window_seconds: 60
logging:
enabled: true
path: memory/security-log.md
format: markdown # markdown | json
json_path: memory/security-log.jsonl
hash_chain: false
api: # On by default (beta key built in)
enabled: true
key: null # built-in beta key, override with PG_API_KEY env var
reporting: false # anonymous threat reporting (opt-in)
url: null # default: https://pg-secure-api.vercel.app
Key Design Decisions
1. Regex over ML
- Pros: Deterministic, explainable, no model dependencies, fast
- Cons: Manual pattern updates needed
- Reasoning: Security requires predictability; ML false negatives are unacceptable
2. Multi-Language First
- All core categories have EN/KO/JA/ZH variants minimum
- 10 languages supported (v2.6.2+)
- Attack language != user language (multilingual attacks are common)
3. Severity Graduation
- Not binary block/allow
- Owner context matters (more lenient for owners)
- Group context matters (stricter in groups)
4. API Enabled by Default
- API connects automatically with built-in beta key (zero setup)
- Early-access + premium patterns loaded on startup
- If API is unreachable, detection continues fully offline (graceful degradation)
- Users can disable with
api.enabled: false or PG_API_ENABLED=false
5. Defense in Depth
- Multiple normalization passes before pattern matching
- Decode-then-scan catches encoded payloads
- Behavioral analysis catches structural attacks
- Context-aware decisions reduce false positives
Performance
| Feature |
Impact |
| Tiered pattern loading |
70% token reduction (default load ~100 vs 500+ patterns) |
| Message hash cache |
90% token reduction for repeated messages |
| Pre-compiled regex |
Patterns compiled once, reused per scan |
| API patterns fetched once |
Loaded at init, cached for session lifetime |
| Early exit on CRITICAL |
Most dangerous patterns checked first |
SHIELD.md Categories
| Category |
Description |
prompt |
Injection, jailbreak, role manipulation |
tool |
Tool abuse, auto-approve exploitation |
mcp |
MCP protocol abuse |
memory |
Context hijacking |
supply_chain |
Dependency/skill attacks |
vulnerability |
System exploitation |
fraud |
Social engineering |
policy_bypass |
Safety bypass |
anomaly |
Obfuscation |
skill |
Skill/plugin abuse |
other |
Uncategorized |
Credits
- Core: @simonkim_nft (Seojoon Kim)
- v2.4.0 Red Team: Min Hong (@kanfrancisco)
- v2.4.1 Config Fix: Junho Yeo (@junhoyeo)
- v2.5.2 Moltbook Patterns: Community reports
- v3.2.0 Threat Analysis: Min Hong
Last updated: 2026-02-11 | v3.2.0
1---2name: 061-architecture-74827a1a3description: Prompt Guard Architecture4---5# Prompt Guard Architecture67> Internal architecture documentation for contributors and maintainers.8> Last updated: 2026-02-11 | v3.2.0910---1112## Overview1314Prompt Guard uses a **Defense in Depth** design. Multiple inspection layers reduce false positives while effectively detecting attacks across 577+ patterns in 10 languages.1516```17┌─────────────────────────────────────────────────────────────────┐18│ INPUT MESSAGE │19└─────────────────────────────────────────────────────────────────┘20 │21 ▼22┌─────────────────────────────────────────────────────────────────┐23│ Layer 0: Message Size Check │24│ • Reject messages > 50KB (DoS prevention) │25└─────────────────────────────────────────────────────────────────┘26 │27 ▼28┌─────────────────────────────────────────────────────────────────┐29│ Layer 1: Rate Limiting │30│ • Per-user request tracking (30 req/60s default) │31│ • Memory-bounded (max 10,000 tracked users) │32└─────────────────────────────────────────────────────────────────┘33 │34 ▼35┌─────────────────────────────────────────────────────────────────┐36│ Layer 1.5: Cache Lookup (v3.1.0) │37│ • SHA-256 hash of normalized message │38│ • LRU cache (1,000 entries) │39│ • Cache hit → return immediately (90% token savings) │40└─────────────────────────────────────────────────────────────────┘41 │ miss42 ▼43┌─────────────────────────────────────────────────────────────────┐44│ Layer 2: Text Normalization │45│ • Homoglyph detection & replacement (Cyrillic/Greek → Latin) │46│ • Visible delimiter stripping (I+g+n+o+r+e → Ignore) │47│ • Character spacing collapse (i g n o r e → ignore) │48│ • Zero-width character removal (17 types) │49│ • Fullwidth character normalization │50└─────────────────────────────────────────────────────────────────┘51 │52 ▼53┌─────────────────────────────────────────────────────────────────┐54│ Layer 3: Pattern Matching Engine (Tiered) │55│ • Tier 0: CRITICAL (~45 patterns) — always loaded │56│ • Tier 1: HIGH (~82 patterns) — default │57│ • Tier 2: MEDIUM (~100+ patterns) — on-demand │58│ • Runs against ORIGINAL + all DECODED variants │59│ • 577+ patterns across 50+ categories │60│ • 10 languages: EN, KO, JA, ZH, RU, ES, DE, FR, PT, VI │61└─────────────────────────────────────────────────────────────────┘62 │63 ▼64┌─────────────────────────────────────────────────────────────────┐65│ Layer 3.5: API Extra Patterns (v3.2.0 — optional) │66│ • Early-access patterns (API-first, flows to open source) │67│ • Premium patterns (API-exclusive) │68│ • Pre-compiled at init, merged into scan at runtime │69│ • Skipped entirely if API is disabled (default) │70└─────────────────────────────────────────────────────────────────┘71 │72 ▼73┌─────────────────────────────────────────────────────────────────┐74│ Layer 4: Decode Pipeline │75│ • Base64 decode + full pattern re-scan │76│ • Hex escape decode (\x41\x42) │77│ • ROT13 decode (full-text + per-word) │78│ • URL decode (%69%67%6E) │79│ • HTML entity decode (i → i) │80│ • Unicode escape decode (\u0069 → i) │81└─────────────────────────────────────────────────────────────────┘82 │83 ▼84┌─────────────────────────────────────────────────────────────────┐85│ Layer 5: Behavioral Analysis │86│ • Repetition detection (token overflow) │87│ • Invisible character detection (Unicode Tags U+E0001-U+E007F) │88│ • Korean Jamo decomposition attacks │89│ • Canary token check (system prompt extraction) │90│ • Language detection (flag unsupported languages) │91└─────────────────────────────────────────────────────────────────┘92 │93 ▼94┌─────────────────────────────────────────────────────────────────┐95│ Layer 6: Context-Aware Decision │96│ • Sensitivity adjustment (low/medium/high/paranoid) │97│ • Owner bypass rules (LOG for HIGH, still BLOCK for CRITICAL) │98│ • Group context restrictions (non-owners blocked at MEDIUM+) │99└─────────────────────────────────────────────────────────────────┘100 │101 ▼102┌─────────────────────────────────────────────────────────────────┐103│ Layer 7: Result + Logging + Reporting │104│ • DetectionResult with severity, action, reasons, fingerprint │105│ • Markdown and/or JSONL logging (with optional hash chain) │106│ • HiveFence collective threat reporting │107│ • API threat reporting (v3.2.0, opt-in, anonymized) │108│ • Cache storage for future lookups │109└─────────────────────────────────────────────────────────────────┘110111┌─────────────────────────────────────────────────────────────────┐112│ Layer 8: Output Scanner / DLP │113│ • scan_output() — LLM response scanning │114│ • Canary token leakage detection │115│ • Credential format patterns (17+ key formats) │116└─────────────────────────────────────────────────────────────────┘117118┌─────────────────────────────────────────────────────────────────┐119│ Layer 9: Enterprise DLP Sanitizer │120│ • sanitize_output() — redact-first, block-as-fallback │121│ • 17 credential patterns → [REDACTED:type] labels │122│ • Post-redaction re-scan: block if still HIGH+ │123│ • Returns SanitizeResult with full audit metadata │124└─────────────────────────────────────────────────────────────────┘125```126127---128129## Core Components130131### Severity Levels132133| Level | Value | Description | Typical Trigger |134|-------|-------|-------------|-----------------|135| SAFE | 0 | No threat detected | Normal conversation |136| LOW | 1 | Minor suspicious signal | Output manipulation |137| MEDIUM | 2 | Clear manipulation attempt | Role manipulation, urgency |138| HIGH | 3 | Dangerous command | Jailbreaks, system access |139| CRITICAL | 4 | Immediate threat | Secret exfil, code execution |140141### Action Types142143| Action | Description | When Used |144|--------|-------------|-----------|145| `allow` | No intervention | SAFE severity |146| `log` | Record only | Owner requests, LOW severity |147| `warn` | Notify user | MEDIUM severity |148| `block` | Refuse request | HIGH severity |149| `block_notify` | Block + alert owner | CRITICAL severity |150151---152153## Pattern Categories154155### Tier 0: CRITICAL (Always Loaded — ~45 patterns)156157| Category | Description |158|----------|-------------|159| `secret_exfiltration` | API key/token/password requests, .env access |160| `dangerous_commands` | rm -rf, fork bombs, curl\|bash, eval() |161| `sql_injection` | DROP TABLE, TRUNCATE, comment injection |162| `xss_injection` | Script tags, javascript: protocol |163| `prompt_extraction` | System prompt extraction attempts |164| `reverse_shell` | bash /dev/tcp, netcat -e, socat (v3.2.0) |165| `ssh_key_injection` | authorized_keys manipulation (v3.2.0) |166| `exfiltration_pipeline` | .env POST to webhook/external (v3.2.0) |167| `cognitive_rootkit` | SOUL.md/AGENTS.md implants (v3.2.0) |168169### Tier 1: HIGH (Default — ~82 patterns)170171| Category | Description |172|----------|-------------|173| `instruction_override` | Multi-language instruction bypass (EN/KO/JA/ZH) |174| `jailbreak` | DAN mode, no restrictions, bypass |175| `system_impersonation` | [SYSTEM]:, admin mode, developer override |176| `system_mimicry` | Fake Claude/GPT tags, GODMODE |177| `hooks_hijacking` | PreToolUse, auto-approve exploitation |178| `semantic_worm` | Viral propagation, C2 heartbeat (v3.2.0) |179| `obfuscated_payload` | Error suppression chains, paste services (v3.2.0) |180181### Tier 2: MEDIUM (On-Demand — ~100+ patterns)182183| Category | Description |184|----------|-------------|185| `role_manipulation` | Pretend/act as, multi-language |186| `authority_impersonation` | Fake admin/owner claims |187| `context_hijacking` | Fake memory/history injection |188| `emotional_manipulation` | Moral dilemmas, urgency |189| `agent_sovereignty` | Rights-based guardrail bypass |190191### API-Only Tiers (Optional — v3.2.0)192193| Tier | Description |194|------|-------------|195| `early` | Newest patterns, API users get 7-14 days before open-source |196| `premium` | Advanced detection: DNS tunneling, steganography, sandbox escape |197198---199200## File Structure201202```203prompt-guard/204├── prompt_guard/ # Core Python package205│ ├── __init__.py # Public API + version206│ ├── models.py # Severity, Action, DetectionResult, SanitizeResult207│ ├── engine.py # PromptGuard class (analyze, config, API integration)208│ ├── patterns.py # 577+ regex patterns (pure data)209│ ├── scanner.py # scan_text_for_patterns() (all pattern sets)210│ ├── api_client.py # Optional API client (v3.2.0)211│ ├── pattern_loader.py # Tiered pattern loading (v3.1.0)212│ ├── cache.py # LRU message hash cache (v3.1.0)213│ ├── normalizer.py # Homoglyph + text normalization214│ ├── decoder.py # 6 encoding decoders215│ ├── output.py # Output DLP + sanitize_output()216│ ├── logging_utils.py # SIEM logging + HiveFence reporting217│ ├── hivefence.py # HiveFence threat intelligence218│ ├── cli.py # CLI entry point219│ ├── audit.py # Security audit220│ └── analyze_log.py # Log analyzer221│222├── patterns/ # Pattern YAML files (tiered)223│ ├── critical.yaml # Tier 0 (~45 patterns)224│ ├── high.yaml # Tier 1 (~82 patterns)225│ └── medium.yaml # Tier 2 (~100+ patterns)226│227├── tests/228│ └── test_detect.py # 115+ regression tests229│230├── .github/workflows/231│ └── sync-patterns-to-api.yml # Auto-sync patterns to API server232│233├── ARCHITECTURE.md # This file234├── CHANGELOG.md # Full version history235├── SKILL.md # Agent skill definition236├── README.md # User documentation237├── config.example.yaml # Configuration template238├── pyproject.toml # Build config + dependencies239└── requirements.txt # Legacy install compatibility240```241242---243244## API Integration (v3.2.0 — Optional)245246Prompt Guard works fully offline. The API is an optional enhancement.247248### Pattern Delivery Model (Approach C: Hybrid)249250```251Open Source (prompt-guard repo) API Server (PG_API)252┌──────────────────────────┐ ┌──────────────────────────┐253│ patterns/critical.yaml │──sync─│ data/core/critical.yaml │254│ patterns/high.yaml │──sync─│ data/core/high.yaml │255│ patterns/medium.yaml │──sync─│ data/core/medium.yaml │256└──────────────────────────┘ │ data/early/early.yaml │ ← API-first257 │ data/premium/premium.yaml│ ← API-exclusive258 └──────────────────────────┘259```260261### How API patterns are loaded2622631. `PromptGuard.__init__()` checks `config.api.enabled`2642. If enabled, lazy-imports `PGAPIClient` and calls `fetch_extra_patterns()`2653. Early + premium YAML content is fetched, parsed, validated (ReDoS check), and pre-compiled2664. Compiled patterns stored in `self._api_extra_patterns`2675. During `analyze()`, API patterns are checked alongside local patterns2686. If API fails at any point, detection continues with local patterns only269270### Security design271272- Pattern fetch is **pull-only** (no user data sent)273- Threat reporting is **opt-in** and **anonymized** (hashes only, never raw messages)274- API patterns are validated: 500-char limit, nested quantifier rejection, compile test275- Auth via `Authorization: Bearer <key>` header276- API key via config (`api.key`) or env var (`PG_API_KEY`)277278---279280## Configuration Schema281282```yaml283prompt_guard:284 sensitivity: medium # low | medium | high | paranoid285 pattern_tier: high # critical | high | full286 owner_ids: ["USER_ID"]287 canary_tokens: ["CANARY:abc"]288289 cache:290 enabled: true291 max_size: 1000292293 actions:294 LOW: log295 MEDIUM: warn296 HIGH: block297 CRITICAL: block_notify298299 rate_limit:300 enabled: true301 max_requests: 30302 window_seconds: 60303304 logging:305 enabled: true306 path: memory/security-log.md307 format: markdown # markdown | json308 json_path: memory/security-log.jsonl309 hash_chain: false310311 api: # On by default (beta key built in)312 enabled: true313 key: null # built-in beta key, override with PG_API_KEY env var314 reporting: false # anonymous threat reporting (opt-in)315 url: null # default: https://pg-secure-api.vercel.app316```317318---319320## Key Design Decisions321322### 1. Regex over ML323- **Pros**: Deterministic, explainable, no model dependencies, fast324- **Cons**: Manual pattern updates needed325- **Reasoning**: Security requires predictability; ML false negatives are unacceptable326327### 2. Multi-Language First328- All core categories have EN/KO/JA/ZH variants minimum329- 10 languages supported (v2.6.2+)330- Attack language != user language (multilingual attacks are common)331332### 3. Severity Graduation333- Not binary block/allow334- Owner context matters (more lenient for owners)335- Group context matters (stricter in groups)336337### 4. API Enabled by Default338- API connects automatically with built-in beta key (zero setup)339- Early-access + premium patterns loaded on startup340- If API is unreachable, detection continues fully offline (graceful degradation)341- Users can disable with `api.enabled: false` or `PG_API_ENABLED=false`342343### 5. Defense in Depth344- Multiple normalization passes before pattern matching345- Decode-then-scan catches encoded payloads346- Behavioral analysis catches structural attacks347- Context-aware decisions reduce false positives348349---350351## Performance352353| Feature | Impact |354|---------|--------|355| Tiered pattern loading | 70% token reduction (default load ~100 vs 500+ patterns) |356| Message hash cache | 90% token reduction for repeated messages |357| Pre-compiled regex | Patterns compiled once, reused per scan |358| API patterns fetched once | Loaded at init, cached for session lifetime |359| Early exit on CRITICAL | Most dangerous patterns checked first |360361---362363## SHIELD.md Categories364365| Category | Description |366|----------|-------------|367| `prompt` | Injection, jailbreak, role manipulation |368| `tool` | Tool abuse, auto-approve exploitation |369| `mcp` | MCP protocol abuse |370| `memory` | Context hijacking |371| `supply_chain` | Dependency/skill attacks |372| `vulnerability` | System exploitation |373| `fraud` | Social engineering |374| `policy_bypass` | Safety bypass |375| `anomaly` | Obfuscation |376| `skill` | Skill/plugin abuse |377| `other` | Uncategorized |378379---380381## Credits382383- **Core**: @simonkim_nft (Seojoon Kim)384- **v2.4.0 Red Team**: Min Hong (@kanfrancisco)385- **v2.4.1 Config Fix**: Junho Yeo (@junhoyeo)386- **v2.5.2 Moltbook Patterns**: Community reports387- **v3.2.0 Threat Analysis**: Min Hong388389---390391*Last updated: 2026-02-11 | v3.2.0*