Metadata-Version: 2.4
Name: contextfirewall
Version: 0.2.0
Summary: A lightweight, developer-friendly firewall for LLM prompts. Prevents sensitive data from reaching AI models.
Author: Suhaib Bin Younis
License-Expression: MIT
Project-URL: Homepage, https://github.com/suhaibbinyounis/contextfirewall
Project-URL: Repository, https://github.com/suhaibbinyounis/contextfirewall
Project-URL: Issues, https://github.com/suhaibbinyounis/contextfirewall/issues
Keywords: llm,firewall,pii,security,openai,anthropic,privacy,redaction,prompt,guardrails
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# 🛡️ contextfirewall

**A lightweight, developer-friendly firewall for LLM prompts.**

`contextfirewall` prevents sensitive or confidential data from being sent to Large Language Models.  
It inspects text before it reaches APIs like OpenAI, Anthropic, Google, Mistral, Cohere, or any custom LLM endpoint, and decides whether the content should be **allowed**, **redacted**, or **blocked** entirely.

[![PyPI](https://img.shields.io/pypi/v/contextfirewall)](https://pypi.org/project/contextfirewall/)
[![Python](https://img.shields.io/pypi/pyversions/contextfirewall)](https://pypi.org/project/contextfirewall/)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)

---

## ✨ Features

- **25+ Built-in Detectors**: PII, Financial data, API Keys, Tokens, internal IPs, and URLs.
- **Multiple Classification Modes**: STANDARD, STRICT, PERMISSIVE, AUDIT, REDACT_ALL, and PARANOID.
- **Advanced Scoring**: Choose from WEIGHTED, MAX, MEAN, SUM_CAPPED, or HIGHEST_N.
- **Zero-Dependency Entropy Detection**: Detects unknown generic secrets with pure Python math.
- **Compliance Presets**: 1-click configuration for HIPAA, PCI-DSS, GDPR, and SOC2.
- **Redaction Styles**: Hash, Mask, Category Placeholders, or Exact Placeholders.
- **Offline & Fast**: Zero network dependencies. Deterministic matching.
- **Decorator & Context Manager**: Drop-in `@firewall` decorator for seamless integration.

---

## 📦 Installation

```bash
pip install contextfirewall
```

---

## 🚀 Quick Start

```python
from contextfirewall import check

text = "User email is john@gmail.com and API key is sk-123abc456def789ghijklmnop"
result = check(text)

print(result.action)   # "BLOCK"
print(result.found)    # ["EMAIL", "API_KEY"]
print(result.score)    # 8
print(result.reason)   # "High-risk data detected (EMAIL, API_KEY), score 8 — blocked by STANDARD policy"
```

### Redaction Example

```python
from contextfirewall.models import RedactStyle

result = check("Send to alice@example.com please", redact_style=RedactStyle.MASK)
if result.action == "REDACT":
    print(result.cleaned)  # "Send to a****@example.com please"
```

---

## 🔧 Core API

### `check(text, **options) → Result`
The primary function to evaluate strings.

```python
result = check(
    text,
    mode="STRICT",                  # Reject any sensitive data
    scoring_strategy="WEIGHTED",    # Calculate score using risk + density
    redact_style="HASH",            # Map matches to a unique SHA256 string
)

result.action       # "ALLOW" | "REDACT" | "BLOCK" | "AUDIT"
result.score        # Aggregate risk (0-10)
result.findings     # List of Finding objects detailing exact context and category
result.categories   # E.g. {"SECRET": 1, "PII": 2}
result.summary      # "[BLOCK] Score 8 - 3 issues"
result.cleaned      # Redacted text (when applicable)
```

### Context Manager & Decorator

Wrap your LLM functions easily without intrusive logic:

```python
from contextfirewall import firewall

# Decorator
@firewall(mode="REDACT_ALL")
def safe_llm_call(prompt: str):
    # Prompt is automatically cleaned before running
    return call_llm(prompt)

# Context Manager
with firewall.guard(mode="STRICT") as fw:
    res = fw.check(user_input)
    if res.action == "BLOCK":
        return "Unsafe content!"
```

### Compliance Presets

```python
from contextfirewall import check
from contextfirewall.presets import HIPAA, PCI_DSS, SOC2, GDPR

# Applies stringent Medical, SSN checks and scoring limits
res = check("Patient MRN: 123456", preset=HIPAA)
```

---

## 🌐 LLM Integration Examples

Works with **any** LLM provider. Here are typical middleware implementations for popular SDKs:

### OpenAI

```python
from openai import OpenAI
from contextfirewall import check, Mode

client = OpenAI()

def safe_chat(message):
    result = check(message, mode=Mode.STANDARD)
    
    if result.action == "BLOCK":
        return f"⛔ Blocked: {result.reason}"
    
    # Use redacted text if necessary
    prompt = result.cleaned if result.action == "REDACT" else message
    
    response = client.chat.completions.create(
        model="gpt-4",
        messages=[{"role": "user", "content": prompt}],
    )
    return response.choices[0].message.content
```

### Anthropic
```python
import anthropic
from contextfirewall.decorators import firewall

client = anthropic.Anthropic()

# Automatically protect this function at the decorator level
@firewall(mode="REDACT_ALL")
def safe_claude_call(prompt: str):
    response = client.messages.create(
        model="claude-3-opus-20240229",
        max_tokens=1024,
        messages=[{"role": "user", "content": prompt}]
    )
    return response.content[0].text

# If the prompt has sensitive data, Anthropic only sees the redacted version!
```

---

## 🔍 Built-in Detectors

| Type | Examples | Category |
|------|----------|----------|
| **PII** | Emails, Phone Numbers, SSN, Passport, Date of Birth | `PII` |
| **Financial** | Credit Cards, IBAN, Stripe Keys | `FINANCIAL` |
| **Secrets** | API Keys, JWTs, Tokens (GitHub, Slack, Google), Generic Secrets | `SECRET` |
| **Infrastructure** | Private IPs, Database URLs, Internal URLs | `INFRASTRUCTURE` |
| **Medical** | Medical Record Numbers (MRN) | `MEDICAL` |

### Paranoia & Entropy Detection

If you don't know the pattern of a secret, use **Paranoid Mode**. This enables zero-dependency Shannon Entropy detection to flag highly random strings of 20+ characters.

```python
# Entropy detector will catch the random string
res = check("Check my code: XyZ123!@LmnOpQrS456^&*TuvWxYz", mode="PARANOID")
```

---

## 🔌 Customization

### 1. Global Setup
Avoid passing arguments to every `check()` call.

```python
from contextfirewall import set_mode, set_redact_style
from contextfirewall.models import Mode, RedactStyle

set_mode(Mode.PERMISSIVE)
set_redact_style(RedactStyle.CATEGORY)
```

### 2. Custom Regex & Functions

```python
from contextfirewall import add_rule, add_detector

add_rule(name="EMPLOYEE_ID", pattern=r"EMP-\d+", risk=3)

def detect_internal(text):
    if "internal.company.com" in text:
        return ["internal.company.com"]
    return []

add_detector(name="INTERNAL_URL", func=detect_internal, risk=4)
```

---

## 📊 Statistics Tracking

`contextfirewall` maintains thread-safe analytics.

```python
from contextfirewall import stats

print(stats.total_checks)       # Int
print(stats.total_blocked)      # Int
print(stats.total_redacted)     # Int
print(stats.findings_by_type)   # Dict of string to int
```

---

## 🧠 Design Philosophy

- **Zero Dependencies** — pure Python module. Works offline, in lambdas, fast.
- **Deterministic** — No ML, same input → same output.
- **Extensible** — Built around customization.
- **Explainable** — Extensive `explain()` reporting and contextual tracking.

## 📄 License

[MIT](LICENSE) — © Suhaib Bin Younis
