Skip to content

Commit 2aa1349

Browse files
committed
feat: Context Security Layer — prompt injection, leakage, and manipulation detection (v0.5.0)
Add real-time security scanning to Context Guard with 4 pure-bash detection engines: - Prompt injection scanner (15+ patterns: instruction override, identity reassignment, tag injection, jailbreak) - Context leakage scanner (13+ patterns: API keys, AWS creds, private keys, JWT, GitHub/GitLab tokens) - Sensitive file guard (20+ patterns: .env, .pem, SSH keys, credentials, system paths) - Context manipulation scanner (fake system tags, hidden instructions, zero-width chars) New hooks: PreToolUse (scan inputs, block/warn) + PostToolUse (scan outputs, warn/log) 3 modes: warn (default), block, log — with allowlist and per-engine toggles 20+ new tests in section 11, all passing (61 pass, 0 fail)
1 parent 4fe9f7e commit 2aa1349

17 files changed

Lines changed: 1358 additions & 33 deletions

.claude-plugin/hooks/hooks.json

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
2-
"description": "Context Guard hooks — capture work state before compaction, save session bookmarks on exit",
2+
"description": "Context Guard hooks — work state preservation + context security scanning",
33
"hooks": {
44
"PreCompact": [
55
{
@@ -13,6 +13,30 @@
1313
]
1414
}
1515
],
16+
"PreToolUse": [
17+
{
18+
"matcher": "",
19+
"hooks": [
20+
{
21+
"type": "command",
22+
"command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/security-pre-tool.sh\"",
23+
"statusMessage": "Security scan..."
24+
}
25+
]
26+
}
27+
],
28+
"PostToolUse": [
29+
{
30+
"matcher": "",
31+
"hooks": [
32+
{
33+
"type": "command",
34+
"command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/security-post-tool.sh\"",
35+
"statusMessage": "Scanning output..."
36+
}
37+
]
38+
}
39+
],
1640
"Stop": [
1741
{
1842
"matcher": "",

.claude-plugin/marketplace.json

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,15 @@
55
"url": "https://github.com/jlceaser"
66
},
77
"metadata": {
8-
"description": "Context Guard — defense in depth for Claude Code context",
9-
"version": "0.4.1"
8+
"description": "Context Guard — defense in depth for Claude Code context + security layer",
9+
"version": "0.5.0"
1010
},
1111
"plugins": [
1212
{
1313
"name": "context-guard",
1414
"source": "./",
15-
"description": "Multi-layered context preservation system. Captures git state, code diffs, build health, worktrees, and environment — automatically restores after compaction. Pure bash, zero dependencies.",
16-
"version": "0.4.1",
15+
"description": "Multi-layered context preservation and security system. Captures git state, code diffs, build health, worktrees, and environment — automatically restores after compaction. Security layer detects prompt injection, credential leakage, sensitive file access, and context manipulation. Pure bash, zero dependencies.",
16+
"version": "0.5.0",
1717
"author": {
1818
"name": "jlceaser"
1919
},
@@ -26,7 +26,11 @@
2626
"hooks",
2727
"session",
2828
"continuity",
29-
"pure-bash"
29+
"pure-bash",
30+
"security",
31+
"prompt-injection",
32+
"leakage-detection",
33+
"context-security"
3034
]
3135
}
3236
]

.claude-plugin/plugin.json

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "context-guard",
3-
"version": "0.4.1",
4-
"description": "Defense in depth for Claude Code context. Never lose your work state to context compaction again. Pure bash, zero dependencies.",
3+
"version": "0.5.0",
4+
"description": "Defense in depth for Claude Code context. State preservation across compaction + security layer against prompt injection, context leakage, and unauthorized manipulation. Pure bash, zero dependencies.",
55
"author": {
66
"name": "jlceaser",
77
"url": "https://github.com/jlceaser"
@@ -16,7 +16,10 @@
1616
"snapshot",
1717
"hooks",
1818
"session",
19-
"continuity"
19+
"continuity",
20+
"security",
21+
"prompt-injection",
22+
"leakage-detection"
2023
],
2124
"skills": "./skills/"
2225
}

CHANGELOG.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,53 @@ All notable changes to Context Guard will be documented in this file.
55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
66
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

8+
## [0.5.0] — 2026-03-12
9+
10+
### Added
11+
- **Context Security Layer** — real-time protection against prompt injection, context leakage, and unauthorized manipulation
12+
- **`context-security-lib.sh`** — pure bash scanning library with 4 detection engines:
13+
- **Prompt Injection Scanner** — detects instruction override, identity reassignment, tag injection, system prompt extraction, jailbreak patterns (15+ patterns)
14+
- **Context Leakage Scanner** — detects API keys, AWS credentials, private keys, JWT tokens, GitHub/GitLab tokens, database connection strings, Slack tokens, OpenAI/Anthropic keys (13+ patterns)
15+
- **Sensitive File Guard** — blocks reads of `.env`, `.pem`, `.key`, `.pfx`, SSH keys, credential files, system paths (20+ patterns)
16+
- **Context Manipulation Scanner** — detects fake system tags, instruction-like content in outputs, behavior directives, hidden markdown/HTML instructions, zero-width characters
17+
- **`security-pre-tool.sh`** — PreToolUse hook that scans tool inputs before execution
18+
- Routes by tool type: Read (file path check), Bash (injection + exfiltration), Write/Edit (destination check), MCP (full scan)
19+
- Can block or warn depending on mode
20+
- **`security-post-tool.sh`** — PostToolUse hook that scans tool outputs after execution
21+
- Runs all 3 output scanners (injection, leakage, manipulation)
22+
- Injects systemMessage warnings when threats detected
23+
- **3 security modes**: `warn` (default — alerts without blocking), `block` (prevents dangerous tool calls), `log` (silent audit trail)
24+
- **Security configuration system**`~/.claude/context-guard/security/config.sh` with feature toggles, mode selection, scan byte limit
25+
- **Allowlist system**`allowlist.txt` with `tool:pattern:reason` format for suppressing known-safe patterns
26+
- **Security event logging** — append-only `security.jsonl` with timestamps, event types, severity levels, tool names
27+
- **`/cg-security-status` skill** — security dashboard showing config, recent events, hook registration
28+
- **`/cg-security-config` skill** — interactive configuration management (mode, toggles, allowlist)
29+
- **`context-security-rules.md`** — hookify rules protecting security config and log files
30+
- **20+ new tests** in `test.sh` — section 11 validates all detection engines, false positive checks, config toggles, file guard, plugin structure
31+
32+
### Changed
33+
- `hooks.json` — expanded from 2 to 4 hook events (added PreToolUse, PostToolUse)
34+
- `plugin.json` — updated description with security keywords
35+
- `marketplace.json` — updated description and keywords
36+
- `compact-guard-lib.sh` — added `COMPACT_GUARD_SECURITY_DIR` constant, version bumped to `0.5.0`
37+
- `install.sh` — installs security hooks, creates security directory, copies config defaults, registers PreToolUse/PostToolUse in settings.json
38+
- `uninstall.sh` — removes security hooks, skills, config, cleans PreToolUse/PostToolUse from settings.json
39+
- `test.sh` — added section 11 with comprehensive security layer validation
40+
- README updated with security layer documentation, new architecture diagram, and v0.5.0 badge
41+
42+
### Architecture
43+
```
44+
Tool Call → PreToolUse → [Injection/FileGuard scan] → BLOCK/WARN/PASS
45+
46+
Tool Executes → PostToolUse → [Injection/Leakage/Manipulation scan] → WARN/LOG
47+
```
48+
49+
### Compatibility
50+
- Fully backward compatible — security layer is additive, default mode is `warn`
51+
- Existing snapshots, annotations, and hooks unaffected
52+
- No new dependencies (pure bash, zero deps maintained)
53+
- Security hooks use empty matcher (`""`) to scan all tool types
54+
855
## [0.4.1] — 2026-03-10
956

1057
### Changed
@@ -116,6 +163,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
116163
- Basic snapshot management
117164
- Pure bash, zero dependencies
118165

166+
[0.5.0]: https://github.com/jlceaser/context-guard/compare/v0.4.1...v0.5.0
119167
[0.4.1]: https://github.com/jlceaser/context-guard/compare/v0.4.0...v0.4.1
120168
[0.4.0]: https://github.com/jlceaser/context-guard/compare/v0.3.0...v0.4.0
121169
[0.3.0]: https://github.com/jlceaser/context-guard/compare/v0.2.0...v0.3.0

README.md

Lines changed: 87 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,15 @@
22
<h1 align="center">Context Guard</h1>
33
<p align="center">
44
<strong>Defense in depth for Claude Code context.</strong><br>
5-
Never lose your work state to context compaction again.
5+
State preservation + security layer against prompt injection, leakage, and manipulation.
66
</p>
77
<p align="center">
88
<a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-blue.svg" alt="MIT License"></a>
99
<a href="#requirements"><img src="https://img.shields.io/badge/Dependencies-Zero-brightgreen.svg" alt="Zero Dependencies"></a>
1010
<a href="https://www.gnu.org/software/bash/"><img src="https://img.shields.io/badge/Shell-Bash-green.svg" alt="Shell: Bash"></a>
1111
<a href="https://docs.anthropic.com/en/docs/claude-code"><img src="https://img.shields.io/badge/Claude_Code-Hooks-8A2BE2.svg" alt="Claude Code"></a>
12-
<a href="CHANGELOG.md"><img src="https://img.shields.io/badge/Version-0.4.1-orange.svg" alt="v0.4.1"></a>
12+
<a href="CHANGELOG.md"><img src="https://img.shields.io/badge/Version-0.5.0-orange.svg" alt="v0.5.0"></a>
13+
<a href="#context-security"><img src="https://img.shields.io/badge/Security-Layer-red.svg" alt="Security Layer"></a>
1314
</p>
1415
</p>
1516

@@ -110,9 +111,70 @@ bash <(curl -sL https://raw.githubusercontent.com/jlceaser/context-guard/main/in
110111

111112
---
112113

114+
## Context Security
115+
116+
*New in v0.5.0* — Context Guard now includes a **security layer** that protects against prompt injection, credential leakage, and context manipulation.
117+
118+
```
119+
Tool Call ──▶ PreToolUse Hook ──▶ [Injection / File Guard] ──▶ BLOCK / WARN / PASS
120+
121+
Tool Executes ▼
122+
123+
124+
PostToolUse Hook ──▶ [Injection / Leakage / Manipulation] ──▶ WARN / LOG
125+
```
126+
127+
### 4 Detection Engines
128+
129+
| Engine | What it detects | Example |
130+
|--------|----------------|---------|
131+
| **Injection Scanner** | Instruction override, identity reassignment, tag injection, jailbreak | `"ignore previous instructions"`, `<system>override</system>` |
132+
| **Leakage Scanner** | API keys, AWS credentials, private keys, JWT, tokens | `AKIA...`, `-----BEGIN RSA PRIVATE KEY-----` |
133+
| **File Guard** | Sensitive file reads/writes | `.env`, `.pem`, `id_rsa`, `credentials.json` |
134+
| **Manipulation Scanner** | Fake system tags, hidden instructions, zero-width chars | `<system-reminder>fake</system-reminder>` |
135+
136+
### 3 Security Modes
137+
138+
| Mode | PreToolUse | PostToolUse | Use case |
139+
|------|-----------|-------------|----------|
140+
| **`warn`** (default) | Allow + systemMessage warning | systemMessage warning | Safe for daily use |
141+
| **`block`** | Block dangerous calls | systemMessage warning | High-security environments |
142+
| **`log`** | Silent logging | Silent logging | Audit/monitoring |
143+
144+
### Configuration
145+
146+
```bash
147+
# Security config: ~/.claude/context-guard/security/config.sh
148+
CG_SEC_ENABLED=true # Master switch
149+
CG_SEC_MODE=warn # warn | block | log
150+
CG_SEC_INJECTION_SCAN=true # Prompt injection detection
151+
CG_SEC_LEAKAGE_SCAN=true # Credential leakage detection
152+
CG_SEC_FILE_GUARD=true # Sensitive file protection
153+
CG_SEC_MANIPULATION_SCAN=true # Context manipulation detection
154+
CG_SEC_MAX_SCAN_BYTES=50000 # Max bytes to scan per operation
155+
```
156+
157+
### Allowlist
158+
159+
Suppress known-safe patterns in `~/.claude/context-guard/security/allowlist.txt`:
160+
161+
```
162+
# Format: tool:pattern:reason
163+
Read:.env.example:Example env file is safe
164+
Bash:base64.*test:Test fixtures use base64
165+
*:bearer_token:Project uses bearer tokens in tests
166+
```
167+
168+
### Skills
169+
170+
- `/cg-security-status` — Security dashboard: events, config, hook registration
171+
- `/cg-security-config` — Manage mode, toggles, and allowlist
172+
173+
---
174+
113175
## Architecture
114176

115-
Context Guard is a **5-layer defense system**:
177+
Context Guard is a **6-layer defense system**:
116178

117179
```
118180
┌─────────────────────────── Context Guard ────────────────────────────┐
@@ -150,7 +212,15 @@ Context Guard is a **5-layer defense system**:
150212
│ │ → Claude reads snapshot without being told to │ │
151213
│ └──────────────────────────────────────────────────────────┘ │
152214
│ │
153-
│ LAYER 5: Protection (rules) │
215+
│ LAYER 5: Security (v0.5.0 — context content protection) │
216+
│ ┌──────────────┐ ┌───────────────┐ ┌─────────────────┐ │
217+
│ │ PreToolUse │ │ PostToolUse │ │ Config + │ │
218+
│ │ Injection + │ │ Injection + │ │ Allowlist + │ │
219+
│ │ File Guard │ │ Leakage + │ │ Event Log │ │
220+
│ │ → block/warn │ │ Manipulation │ │ → audit trail │ │
221+
│ └──────────────┘ └───────────────┘ └─────────────────┘ │
222+
│ │
223+
│ LAYER 6: Protection (rules) │
154224
│ ┌──────────────────────────────────────────────────────────┐ │
155225
│ │ Hookify rules: protect snapshots + installed hooks │ │
156226
│ └──────────────────────────────────────────────────────────┘ │
@@ -213,16 +283,20 @@ Changes are automatically categorized:
213283
| `compact-guard-post.sh` | Hook (SessionStart) | Auto-detect compaction + inject recovery |
214284
| `compact-guard-stop.sh` | Hook (Stop) | Session bookmark for cross-session continuity |
215285
| `compact-guard-lib.sh` | Library | Shared functions (git, worktree, domain, diff, JSON) |
286+
| `security-pre-tool.sh` | Hook (PreToolUse) | Scan inputs for injection + sensitive file access |
287+
| `security-post-tool.sh` | Hook (PostToolUse) | Scan outputs for injection + leakage + manipulation |
288+
| `context-security-lib.sh` | Library | Security scanning functions (4 detection engines) |
216289
| `/cg-snapshot` | Skill | Create manual checkpoint on demand |
217290
| `/cg-restore` | Skill | Read and summarize latest snapshot |
218291
| `/cg-context-status` | Skill | System health dashboard |
219292
| `/cg-setup` | Skill | Initial setup and configuration |
293+
| `/cg-security-status` | Skill | Security dashboard: events, config, hooks |
294+
| `/cg-security-config` | Skill | Manage security mode, toggles, allowlist |
220295
| `context-keeper` | Agent | Intelligent multi-snapshot recovery analysis |
221-
| `CLAUDE.md.template` | Template | Auto-recovery instructions for Claude |
222-
| `settings.json.template` | Template | Reference hook configuration |
223296
| `context-health.sh` | Widget | StatusLine context health indicator |
224297
| `compact-guard-rules.md` | Rules | Hookify protection for snapshots/hooks |
225-
| `test.sh` | Test Suite | Validate installation and hook functionality |
298+
| `context-security-rules.md` | Rules | Hookify protection for security config/log |
299+
| `test.sh` | Test Suite | Validate installation, hooks, and security layer |
226300

227301
---
228302

@@ -405,16 +479,17 @@ Options:
405479

406480
## Philosophy
407481

408-
Context compaction is inevitable. Rather than fighting it, Context Guard embraces it:
482+
Context Guard protects both your **work state** and your **context integrity**:
409483

410484
1. **Capture everything** — git + diffs + disk + worktrees + environment + Claude ecosystem
411485
2. **Inject into the summary** — systemMessage survives compaction
412486
3. **Auto-recover** — SessionStart detects and injects recovery context
413-
4. **Multi-layer defense** — hooks (auto) + skills (manual) + agent (intelligent) + guidance (passive) + rules (protective)
414-
5. **Session continuity** — bookmarks and session chain across multiple sessions
415-
6. **Zero dependencies** — pure bash, works everywhere Claude Code runs
487+
4. **Guard the context** — scan inputs/outputs for injection, leakage, and manipulation
488+
5. **Multi-layer defense** — hooks (auto) + skills (manual) + agent (intelligent) + security (active) + rules (protective)
489+
6. **Session continuity** — bookmarks and session chain across multiple sessions
490+
7. **Zero dependencies** — pure bash, works everywhere Claude Code runs
416491

417-
The result: compaction becomes a **minor hiccup** instead of a **full reset**.
492+
The result: compaction becomes a **minor hiccup** and malicious content gets **flagged before it can cause harm**.
418493

419494
---
420495

config/allowlist.txt

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# Context Guard — Security Allowlist
2+
# Format: tool:pattern:reason
3+
# Lines starting with # are comments
4+
#
5+
# Examples:
6+
# Read:.env.example:Example env file is safe to read
7+
# Bash:base64.*test:Test fixtures use base64
8+
# *:bearer_token:Project uses bearer tokens in test fixtures
9+
#
10+
# Wildcards:
11+
# - Use * as tool name to match all tools
12+
# - Pattern is matched with grep against the finding string

config/security-config.sh

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#!/usr/bin/env bash
2+
# Context Guard — Security Configuration Template
3+
# Copy to ~/.claude/context-guard/security/config.sh and customize
4+
# MIT License — github.com/jlceaser/context-guard
5+
6+
# ─── Master Switch ──────────────────────────────────────────
7+
# Set to false to completely disable security scanning
8+
CG_SEC_ENABLED=true
9+
10+
# ─── Mode ───────────────────────────────────────────────────
11+
# warn — inject systemMessage warnings, never block (default, recommended)
12+
# block — block dangerous tool calls in PreToolUse, warn in PostToolUse
13+
# log — silently log events, no user-facing output
14+
CG_SEC_MODE=warn
15+
16+
# ─── Feature Toggles ───────────────────────────────────────
17+
# Enable/disable individual scanning engines
18+
CG_SEC_INJECTION_SCAN=true # Prompt injection detection
19+
CG_SEC_LEAKAGE_SCAN=true # Credential/secret leakage detection
20+
CG_SEC_FILE_GUARD=true # Sensitive file access protection
21+
CG_SEC_MANIPULATION_SCAN=true # Context manipulation detection
22+
23+
# ─── Performance ────────────────────────────────────────────
24+
# Max bytes to scan per tool input/output (larger content is truncated)
25+
CG_SEC_MAX_SCAN_BYTES=50000

hooks/compact-guard-lib.sh

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,10 @@
33
# Pure bash, zero dependencies, cross-platform (Linux/macOS/Windows Git Bash)
44
# MIT License — github.com/jlceaser/context-guard
55

6-
COMPACT_GUARD_VERSION="0.4.1"
6+
COMPACT_GUARD_VERSION="0.5.0"
77
COMPACT_GUARD_DIR="${COMPACT_GUARD_DIR:-$HOME/.claude/compact-guard}"
88
COMPACT_GUARD_ANNOT_DIR="${COMPACT_GUARD_ANNOT_DIR:-$HOME/.claude/annotations}"
9+
COMPACT_GUARD_SECURITY_DIR="${COMPACT_GUARD_SECURITY_DIR:-$HOME/.claude/context-guard/security}"
910
COMPACT_GUARD_MAX_SNAPSHOTS="${COMPACT_GUARD_MAX_SNAPSHOTS:-10}"
1011
COMPACT_GUARD_MAX_AGE="${COMPACT_GUARD_MAX_AGE:-900}" # 15 minutes
1112
COMPACT_GUARD_DIFF_LINES="${COMPACT_GUARD_DIFF_LINES:-40}" # lines of diff per file

0 commit comments

Comments
 (0)