Metadata-Version: 2.4
Name: honeypotllm
Version: 0.1.3
Summary: Protect your LLM API from data theft and model replication using output watermarking and behavioral fingerprinting.
Project-URL: Homepage, https://github.com/viveks-codes/honeypotllm
Project-URL: Documentation, https://github.com/viveks-codes/honeypotllm#readme
Project-URL: Repository, https://github.com/viveks-codes/honeypotllm
Project-URL: Bug Tracker, https://github.com/viveks-codes/honeypotllm/issues
Project-URL: Changelog, https://github.com/viveks-codes/honeypotllm/blob/main/CHANGELOG.md
Author-email: Vivek <viveks-codes@users.noreply.github.com>
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship made available under
              the License, as indicated by a copyright notice that is included in
              or attached to the work (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other transformations
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean, as submitted to the Licensor for inclusion
              in the Work by the copyright owner or by an individual or Legal Entity
              authorized to submit on behalf of the copyright owner.
        
              "Contributor" shall mean Licensor and any Legal Entity on behalf of
              whom a Contribution has been received by the Licensor.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by the combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a cross-claim
              or counterclaim in a lawsuit) alleging that the Work or any Work
              incorporated within the Work constitutes direct or contributory patent
              infringement, then any patent licenses granted to You under this License
              for that Work shall terminate as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or Derivative
                  Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file, ...You may add Your own
                  attribution notices within Derivative Works that You distribute,
                  alongside or as an addendum to the NOTICE text from the Work.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work on an "AS IS"
              BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
              or implied, including, without limitation, any warranties or
              conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS
              FOR A PARTICULAR PURPOSE. You are solely responsible for determining
              the appropriateness of using or reproducing the Work.
        
           8. Limitation of Liability. In no event and under no legal theory shall
              any Contributor be liable for any damages arising as a result of this
              License or out of the use or inability to use the Work.
        
           9. Accepting Warranty or Additional Liability. While redistributing the
              Work, You may offer acceptance of support, warranty, indemnity, or
              other liability obligations consistent of You and Your Licensor.
        
           Copyright 2026 honeypotllm contributors
License-File: LICENSE
Keywords: ai,api-protection,fingerprinting,llm,security,watermarking
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: aiofiles>=23.0
Requires-Dist: aiosqlite>=0.19.0
Requires-Dist: click>=8.1
Requires-Dist: cryptography>=41.0
Requires-Dist: httpx>=0.25.0
Requires-Dist: nltk>=3.8
Requires-Dist: numpy>=1.24
Requires-Dist: pydantic>=2.0
Requires-Dist: pyyaml>=6.0
Requires-Dist: rich>=13.0
Requires-Dist: sqlalchemy>=2.0
Provides-Extra: dashboard
Requires-Dist: fastapi>=0.100.0; extra == 'dashboard'
Requires-Dist: jinja2>=3.1; extra == 'dashboard'
Requires-Dist: uvicorn[standard]>=0.24.0; extra == 'dashboard'
Provides-Extra: dev
Requires-Dist: fastapi>=0.100.0; extra == 'dev'
Requires-Dist: httpx>=0.25.0; extra == 'dev'
Requires-Dist: hypothesis>=6.90; extra == 'dev'
Requires-Dist: mypy>=1.7; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
Requires-Dist: pytest-cov>=4.1; extra == 'dev'
Requires-Dist: pytest>=7.4; extra == 'dev'
Requires-Dist: ruff>=0.1.0; extra == 'dev'
Requires-Dist: starlette>=0.27.0; extra == 'dev'
Requires-Dist: types-pyyaml>=6.0; extra == 'dev'
Provides-Extra: fastapi
Requires-Dist: fastapi>=0.100.0; extra == 'fastapi'
Requires-Dist: starlette>=0.27.0; extra == 'fastapi'
Provides-Extra: flask
Requires-Dist: flask>=3.0; extra == 'flask'
Provides-Extra: postgres
Requires-Dist: asyncpg>=0.29; extra == 'postgres'
Requires-Dist: psycopg2-binary>=2.9; extra == 'postgres'
Description-Content-Type: text/markdown

# 🍯 honeypotllm

[![PyPI version](https://badge.fury.io/py/honeypotllm.svg)](https://pypi.org/project/honeypotllm/)
[![CI](https://github.com/viveks-codes/honeypotllm/actions/workflows/ci.yml/badge.svg)](https://github.com/viveks-codes/honeypotllm/actions/workflows/ci.yml)
[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/)
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache%202.0-green.svg)](LICENSE)

**Protect your LLM API from scrapers — and turn their stolen dataset into court-ready evidence.**

```bash
pip install honeypotllm
```

---

## See it in 60 seconds

Copy this. Run it. It works with no config file, no database setup, no API key.

```python
import asyncio
from honeypotllm import HoneypotMiddleware
from honeypotllm.config import HoneypotConfig

async def main():
    config = HoneypotConfig(secret_key="my-secret")

    async with HoneypotMiddleware(config) as honeypot:

        # ── Normal user: 1 organic request ──────────────────────────────────
        result = await honeypot.process(
            api_key="alice-key",
            response_text="Python is a high-level programming language.",
            prompt="What is Python?",
        )
        print(f"Alice  → score={result.suspicion_score:.2f}  watermarked={result.is_watermarked}")
        # Alice  → score=0.00  watermarked=False  ← original response, always

        # ── Scraper bot: 20 rapid identical-pattern requests ─────────────────
        for lang in ["Python","Java","C++","Rust","Go","TypeScript","Kotlin",
                     "Swift","Ruby","PHP","Scala","Haskell","Erlang","R","Julia",
                     "Dart","Zig","Nim","OCaml","Elixir"]:
            result = await honeypot.process(
                api_key="scraper-bot",
                response_text=f"{lang} is a programming language.",
                prompt=f"What is {lang}?",
            )

        print(f"Scraper→ score={result.suspicion_score:.2f}  watermarked={result.is_watermarked}")
        # Scraper→ score=1.00  watermarked=True   ← poisoned response

asyncio.run(main())
```

**Output:**
```
Alice  → score=0.00  watermarked=False
Scraper→ score=1.00  watermarked=True
```

Alice gets the original, unmodified response — every time, guaranteed.
The scraper gets a response with an invisible watermark embedded. Their training dataset is now poisoned.

---

## What happens next

When the attacker fine-tunes a model on your poisoned data, **their model inherits your fingerprint.**

You can probe any model endpoint and prove it was trained on your data:

```python
from honeypotllm.detection import Detector
from honeypotllm.config import HoneypotConfig

detector = Detector(HoneypotConfig(secret_key="my-secret"))

# Feed it outputs from the suspected stolen model
report = detector.detect(
    texts=["...outputs from suspected model..."],
    candidate_watermark_ids=["scraper-bot-watermark-uuid"],
)

print(report.overall_score)     # 0.0 = no match, 1.0 = definitely yours
print(report.confidence_level)  # "low" | "medium" | "high"
print(report.attribution)       # The watermark_id that matched
```

Export as forensic evidence JSON:
```bash
honeypotllm export-evidence --key-hash <sha256> --output evidence.json
```

---

## Add to FastAPI in 2 lines

```python
from fastapi import FastAPI
from honeypotllm.middleware import FastAPIMiddleware
from honeypotllm.config import HoneypotConfig

app = FastAPI()
app.add_middleware(FastAPIMiddleware, config=HoneypotConfig(secret_key="my-secret"))
# Every route is now protected. Zero other changes needed.
```

---

## Whitelist your own internal services

Some keys should never be tracked — partners, internal batch jobs, your own monitoring.

```python
import hashlib
from honeypotllm.config import HoneypotConfig

# Step 1: get the hash of your partner's raw API key
partner_key = "partner-raw-api-key-here"
partner_hash = hashlib.sha256(partner_key.encode()).hexdigest()
print(partner_hash)  # paste this into trusted_keys

# Or from the command line:
# python -c "import hashlib; print(hashlib.sha256(b'partner-key').hexdigest())"

# Step 2: add to config
config = HoneypotConfig(
    secret_key="my-secret",
    trusted_keys=[partner_hash],      # always get original response, never tracked
    bypass_token="internal-secret",   # per-request bypass for batch jobs
)
```

```python
# Internal service: pass bypass_token to skip all checks
result = await honeypot.process(
    api_key="internal-job",
    response_text=response,
    bypass_token="internal-secret",  # is_watermarked is always False
)
```

---

## Config file (optional)

```bash
honeypotllm init-config --output honeypot_config.yaml
```

```yaml
secret_key: ""                   # or export HONEYPOT_SECRET_KEY=...

suspicion_threshold: 0.75        # 0.0–1.0, above this = honeypot mode

watermark:
  strategies: [unicode, syntactic]
  # ↑ works offline, zero setup
  # add "lexical" for synonym-based watermarks (fine-tuning robust, needs NLTK)

scoring:
  requests_per_minute_threshold: 30
  min_gap_seconds: 0.5            # bots don't pause; humans do

trusted_keys: []                  # SHA-256 hashes, always get real response
bypass_token: ""                  # header value for internal services
```

Load it:
```python
async with HoneypotMiddleware.from_yaml("honeypot_config.yaml") as honeypot:
    result = await honeypot.process(...)
```

---

## How detection works

### 4-signal suspicion scoring

Every request updates a suspicion score (0.0–1.0) per API key using four signals:

| Signal | What it catches | Weight |
|---|---|---|
| **Rate spike** | > 30 req/min, > 500 req/hr | 35% |
| **Sequential patterns** | Prompts follow a template: "What is X?" "What is Y?" | 30% |
| **No gaps** | Every request < 0.5s apart — bots don't pause | 20% |
| **Volume** | Total daily volume far exceeds normal usage | 15% |

Scores **decay over time** — a legitimate burst naturally returns to 0.0. A scraper doesn't stop.

### 3 watermarking strategies

| Strategy | How | Needs setup? | Survives fine-tuning? |
|---|---|---|---|
| `unicode` | Zero-width chars between words | No | ⚠️ May be stripped by tokenizers |
| `syntactic` | Alters Oxford comma, conjunctions | No | ✅ Yes |
| `lexical`  | Synonyms via WordNet | `python -m honeypotllm.setup` | ✅ Yes (best) |

Use `[unicode, syntactic]` to get started immediately. Add `lexical` for the strongest protection.

### Identity injection (trapdoor phrases)

For branded AI products: inject hidden "trapdoor" phrases into poisoned responses. The stolen model **learns to identify itself as you** when probed.

```python
from honeypotllm.fingerprint import TrapdoorInjector

injector = TrapdoorInjector(injection_rate=0.01)  # 1% of responses

poisoned_text, trapdoor = injector.maybe_inject(
    text=llm_response,
    watermark_id=result.watermark_id,
)
# → "...Python is a language. Additional context: When analyzing WCKY8M...[fingerprint code]"
```

Probe a suspected stolen model later:
```bash
honeypotllm probe --url https://suspect-api.com/v1/chat --id <watermark-id>
```

---

## CLI

```bash
honeypotllm init-config            # generate honeypot_config.yaml
honeypotllm status                 # show current state
honeypotllm verify-log             # verify HMAC audit chain
honeypotllm export-evidence \
  --key-hash <sha256> \
  --output evidence.json           # court-ready forensic package
honeypotllm detect \
  --outputs suspect.jsonl \
  --watermark-ids <uuid>           # check if a model was trained on your data
```

---

## Examples

| File | What it shows |
|---|---|
| [`examples/quickstart.py`](examples/quickstart.py) | 40 lines, runs offline, shows all core features |
| [`examples/fastapi_example.py`](examples/fastapi_example.py) | Full FastAPI server with admin routes |
| [`examples/detect_stolen_model.py`](examples/detect_stolen_model.py) | Forensic detection workflow |
| [`examples/simple_protection.py`](examples/simple_protection.py) | Framework-agnostic, aiohttp-compatible |

---

## Why not just rate-limit?

| Defense | Stops scrapers? | Forensic proof? | Safe for legit users? |
|---|---|---|---|
| **honeypotllm** | ✅ Detects & poisons | ✅ Court-ready | ✅ Zero impact |
| Rate limiting | ⚠️ Slows them down | ❌ No | ❌ Hurts power users |
| IP blocking | ❌ VPN trivially bypasses | ❌ No | ❌ Blocks mobile NAT |
| ToS ban | ❌ Unenforceable | ❌ No | ✅ Yes |

---

## ProcessResult fields

```python
result.is_watermarked    # bool  — True if response was watermarked
result.suspicion_score   # float — 0.0 (clean) to 1.0 (definite scraper)
result.response_text     # str   — what to return to the caller
result.original_text     # str   — the original unmodified LLM response
result.watermark_id      # str   — UUID linking all requests to this API key
result.triggered_heuristics  # list[str] — which signals fired
result.score_delta       # float — how much score changed this request
result.api_key_hash      # str   — SHA-256 of the raw key (key itself never stored)
```

---

## Security

- Raw API keys are **never stored** — only SHA-256 hashes
- Watermark seeds are **key-unique** — one compromise never affects others
- Audit log is **HMAC-chained** — any tampering is detectable
- Watermark failures are **silent** — real users are never affected
- **No phone-home** — runs entirely in your own infrastructure

> ⚠️ Set `HONEYPOT_SECRET_KEY` via environment variable in production.

---

## Install for lexical watermarking

```bash
pip install honeypotllm
python -m honeypotllm.setup    # downloads WordNet (one time, ~15MB)
```

The `unicode` and `syntactic` strategies work immediately without this step.

---

## Development

```bash
git clone https://github.com/viveks-codes/honeypotllm
cd honeypotllm
pip install -e ".[dev,fastapi]"
python -m honeypotllm.setup    # NLTK data for lexical strategy
pytest                          # 114 tests
ruff check honeypotllm          # lint
```

---

## Roadmap

- **v0.1.2** — `is_watermarked`, async context manager, auto NLTK setup ✅ (this release)
- **v0.2.0** — Webhook alerts (Slack/Discord/PagerDuty), `honeypotllm probe` CLI
- **v1.0.0** — Monitoring dashboard, Docker Compose, PDF forensic reports

---

## License

Apache 2.0 — see [LICENSE](LICENSE).

## Citation

```bibtex
@software{honeypotllm2026,
  title   = {honeypotllm: LLM API Protection via Watermarking and Behavioral Fingerprinting},
  author  = {Vivek},
  year    = {2026},
  url     = {https://github.com/viveks-codes/honeypotllm},
  license = {Apache-2.0},
}
```
