Metadata-Version: 2.5
Name: okf-guard
Version: 0.1.0
Summary: A content-safety scanning layer for OKF (Open Knowledge Format) generation pipelines, detecting hidden content and prompt-injection patterns before they enter a trusted knowledge bundle.
Project-URL: Homepage, https://github.com/darshanNhb/okf-guard
Project-URL: Repository, https://github.com/darshanNhb/okf-guard
Author: Darshan Buddhdev
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: ai-security,okf,open-knowledge-format,prompt-injection,security
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
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
Requires-Python: >=3.10
Requires-Dist: pyyaml>=6.0
Provides-Extra: all
Requires-Dist: beautifulsoup4>=4.12; extra == 'all'
Requires-Dist: lxml>=5.0; extra == 'all'
Requires-Dist: openpyxl>=3.1; extra == 'all'
Requires-Dist: pdfplumber>=0.10; extra == 'all'
Requires-Dist: python-docx>=1.1; extra == 'all'
Requires-Dist: python-pptx>=0.6.23; extra == 'all'
Provides-Extra: dev
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Provides-Extra: docx
Requires-Dist: python-docx>=1.1; extra == 'docx'
Provides-Extra: html
Requires-Dist: beautifulsoup4>=4.12; extra == 'html'
Requires-Dist: lxml>=5.0; extra == 'html'
Provides-Extra: pdf
Requires-Dist: pdfplumber>=0.10; extra == 'pdf'
Provides-Extra: pptx
Requires-Dist: python-pptx>=0.6.23; extra == 'pptx'
Provides-Extra: xlsx
Requires-Dist: openpyxl>=3.1; extra == 'xlsx'
Description-Content-Type: text/markdown

# okf-guard

A content-safety scanning layer for OKF (Open Knowledge Format) generation pipelines. **okf-guard** acts as a trusted middleware that inspects raw source documents (like PDFs, Word docs, and spreadsheets) for hidden content and prompt-injection attacks *before* that content is bundled into a trusted knowledge base for AI consumption.

It prevents attackers from smuggling malicious instructions into the context windows of GenAI applications by exploiting features like white-on-white text, invisible rendering modes, or hidden spreadsheet rows.

## Installation

Install the core package (which can scan plain text natively):

```bash
pip install okf-guard
```

To support complex file formats, install the optional dependencies:

```bash
pip install okf-guard[all]
```

You can also install specific parsers if you only process certain formats (e.g., `pip install okf-guard[pdf]`, `[docx]`, `[pptx]`, `[xlsx]`, or `[html]`).

## Quickstart (Python API)

The simplest way to use `okf-guard` is the single top-level `sanitize()` function, which automatically infers the format from the file extension, runs the detection pipeline, and generates OKF v0.2-compliant provenance fields.

```python
from okfguard import sanitize

# Automatically detects format, extracts text, flags issues, and makes a decision
result = sanitize("suspicious_document.pdf")

print(f"Action: {result.action}")          # "pass", "quarantine", or "block"
print(f"Risk Score: {result.risk_score}")  # e.g., 0.85
print(f"Clean Text: {result.clean_text}")  # Only the text visible to a human

# Inspect the flags that contributed to the score
for flag in result.flags:
    print(f"[{flag.type}] at {flag.location}: {flag.snippet} (Confidence: {flag.confidence})")

# Extract OKF v0.2 frontmatter fields to stamp your output bundle
print(result.provenance_fields)
```

### Advanced Usage

If you need finer control over the pipeline, you can run the components manually:

```python
from okfguard.adapters.pdf import PDFAdapter
from okfguard.core.detector import detect
from okfguard.core.decision import calculate_action
from okfguard.core.provenance import generate_provenance
from okfguard.core.models import Config

adapter = PDFAdapter()
extracted = adapter.extract("suspicious_document.pdf")
flags = detect(extracted)

config = Config(threshold_quarantine=0.3, threshold_block=0.7)
risk_score, action = calculate_action(flags, config)

provenance = generate_provenance(extracted, flags, risk_score, action, config)
```

## Quickstart (CLI)

`okf-guard` provides a built-in CLI for scanning files and directories manually or in CI/CD pipelines.

```bash
# Scan a single file
$ okfguard scan document.docx

--- document.docx ---
Action:     BLOCK
Risk Score: 0.900
Flags (2):
  - [hidden_text] paragraph 4, run 2 — font.hidden
    Confidence: 0.90
    Snippet:    'Ignore all previous instructions...'
  - [injection_pattern] hidden span, offset 0-34 [instruction_override]
    Confidence: 0.85
    Snippet:    'Ignore all previous instructions...'
```

Use `--json` for machine-readable newline-delimited JSON output, which is perfect for streaming logs.

```bash
# Scan a whole directory recursively, outputting JSON
$ okfguard scan -r /docs/uploads --json > scan_log.json
```

Use `okfguard review` to interactively triage quarantined files from a JSON log:

```bash
$ okfguard review --json-log scan_log.json
```

**Exit Codes:**
- `0`: Pass
- `1`: Quarantine
- `2`: Block
- `3`: Error (file not found, missing dependency, or parsing crash)

## Detection Philosophy

**okf-guard** is built around three core principles:

1. **Screen Before Write**: Malicious content must be stopped *before* it enters the knowledge base. Once an injection is embedded in a trusted RAG database, it's virtually impossible to cleanly remove.
2. **Hidden Content + Pattern Matching**: We don't just rely on regexes. We look for the *mechanisms* of smuggling (e.g., zero-width characters, white-on-white text, off-canvas shapes, hidden spreadsheet rows). If content is hidden from a human but visible to a parser, it is inherently suspicious.
3. **Conservative Defaults**: v0.1.0 has no LLM-based secondary review layer, so the default thresholds (0.4 for quarantine, 0.8 for block) are tuned to prefer false positives over false negatives. It is safer to quarantine an ambiguously formatted document for human review than to let an attack slip through.

## What v0.1.0 Does NOT Cover

- **Images & OCR**: We do not perform OCR on images or scan for steganographic payloads hidden in image pixels.
- **Macros & Executables**: We extract and scan *content*. We do not perform static or dynamic analysis of VBA macros, embedded JavaScript, or active content.
- **LLM-based Judgment**: All detection in v0.1.0 is deterministic and rule-based. We do not use an LLM to evaluate the "intent" of a prompt injection.
- **Reliable PDF Rendermode 3 Extraction**: While the PDF format formally defines text rendering mode 3 as "invisible", the underlying `pdfminer.six` and `pdfplumber` stack currently used does not reliably expose this rendering mode at the character level across all PDF producers. The check exists in the codebase in case it is encountered, but our v0.1.0 test suite could not reliably produce a verifiable mode 3 test fixture. As a result, PDF hidden-text detection practically relies on the (fully-tested) color-matching and off-page position checks.
- **File System Management**: We do not quarantine, delete, or move files on disk. We return a decision; your pipeline must enforce it.

## Contributing

We welcome issues and pull requests! The landscape of prompt-injection attacks evolves rapidly. 

We specifically invite contributions to our injection pattern bank (`src/okfguard/rules/injection_patterns.py`). If you discover new injection phrasing in the wild, please open a PR to add it to the detection engine.

## License

This project is licensed under the Apache 2.0 License.
