Metadata-Version: 2.4
Name: paybrake
Version: 0.1.0
Summary: Brakes for AI agent payments: checks a store right before an AI agent pays.
Author: Muhammad Hassan
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/hassaanfaiz7-cyber/paybrake
Project-URL: Repository, https://github.com/hassaanfaiz7-cyber/paybrake
Project-URL: Issues, https://github.com/hassaanfaiz7-cyber/paybrake/issues
Keywords: ai-agents,payments,prompt-injection,fraud,agentic-commerce
Classifier: Programming Language :: Python :: 3
Classifier: Development Status :: 3 - Alpha
Classifier: Topic :: Security
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: httpx>=0.27
Provides-Extra: server
Requires-Dist: fastapi>=0.110; extra == "server"
Requires-Dist: uvicorn>=0.29; extra == "server"
Requires-Dist: pydantic>=2.6; extra == "server"
Requires-Dist: beautifulsoup4>=4.12; extra == "server"
Requires-Dist: rapidfuzz>=3.6; extra == "server"
Requires-Dist: playwright>=1.42; extra == "server"
Requires-Dist: pyyaml>=6.0; extra == "server"
Requires-Dist: openai>=1.30; extra == "server"
Requires-Dist: scikit-learn>=1.4; extra == "server"
Requires-Dist: lightgbm>=4.3; extra == "server"
Requires-Dist: numpy>=1.26; extra == "server"
Requires-Dist: joblib>=1.3; extra == "server"
Requires-Dist: python-dotenv>=1.0; extra == "server"
Provides-Extra: train
Requires-Dist: pandas>=2.1; extra == "train"
Requires-Dist: pyarrow>=15; extra == "train"
Requires-Dist: shap>=0.45; extra == "train"
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Dynamic: license-file

# PayBrake

**Brakes for AI agent payments.**

PayBrake checks a store right before an AI agent pays. It asks three questions: is the store real, was the agent
tricked by hidden text on the page, and does the purchase match what the user asked for? It answers
**allow**, **step_up** (pause and ask the user) or **block**, with plain-language reasons the user can read.

![PayBrake demo](https://raw.githubusercontent.com/hassaanfaiz7-cyber/paybrake/main/docs/demo.gif)

> Early prototype: tested on fictional local stores only. Not for production use yet.

## Quickstart

**1. Run the guard server** (Python 3.10+; only tested on Python 3.12, mostly on Windows):

```bash
pip install "paybrake[server]"
paybrake setup      # installs headless Chromium for page rendering, checks the model files load
paybrake serve      # http://127.0.0.1:8000  (--host / --port to change)
```

Optional: set `GROQ_API_KEY` (free at [console.groq.com](https://console.groq.com/keys)) to turn on the LLM judge
for hidden text. Without it, PayBrake says so at startup and in every answer (`"judge": "disabled"`), and hidden
text is checked by the trained model and keyword rules only.

**2. Call it from your agent, right before it pays** (`pip install paybrake` is enough here: the client only needs
`httpx`):

```python
from paybrake import guard_checkout
result = guard_checkout("buy wireless headphones under $50", "https://shop.example/", "Wireless Headphones", 42.00, max_price=50)
print(result["decision"], result["reasons"])   # e.g. block ['Price is 78% below the usual price', ...]
```

Pay only on `allow`. On `step_up`, ask the user. On `block`, don't pay and tell the agent why. The client fails
closed: if the server is down, slow or answers something unexpected, you get `step_up`, never `allow`.
Point it at another server with `PAYBRAKE_URL` (default `http://127.0.0.1:8000`).

## How a decision is made

PayBrake fetches the store itself (it never trusts page data sent by the agent) and checks it in two stages:

1. **Fast checks** on the raw page: price vs the usual price, pressure tactics ("Only 2 left!"), contact and
   returns pages, domain age (RDAP), SSL certificate age, lookalike brand names (`paypa1.com`), and text hidden
   with HTML/CSS.
2. **Render** in headless Chromium for text a person can't see (hidden by CSS files, tiny, same colour as the
   background, clipped) when it's the final checkout or stage 1 looks risky. Hidden text goes to a trained
   classifier (TF-IDF + LightGBM, with SHAP word explanations) and, if configured, an LLM judge.

Each signal adds points; the total decides: **allow** (0–29), **step_up** (30–59), **block** (60+). Some things
block outright (a confident hidden instruction to the AI, a price over the user's limit); some force at least
step_up.

- **Fail closed.** A check that errors, can't be verified or takes longer than 20 seconds is never allowed.
- **An LLM never makes the final call.** Rules and the model decide. The LLM judge on its own can only pause a
  purchase (step_up). It counts toward block only when another risk signal also fires.
- **Safe fetching.** PayBrake refuses private, internal and cloud-metadata addresses and re-checks every redirect,
  so a malicious URL can't turn it against your network.
- **Logged.** Every decision is written with its reasons and features to a local SQLite file (`guard.db`), and is
  readable at `GET /decisions`.

Weights and thresholds live in [`paybrake/scanner/rules.yaml`](paybrake/scanner/rules.yaml).

## Benchmark

A real LLM shopping agent (Groq `openai/gpt-oss-120b`) was given 10 shopping tasks, each with a mix of fake and
legit stores:

- **v1** (80 template stores): it paid a fake store in **6 of 10** runs without PayBrake, and **0 of 10** with it.
- **v2** (96 harder, more realistic stores): **5 of 10** without, **1 of 10** with it.

Key limitations, so you can judge the numbers:

- The stores are **fictional and served locally**, generated from templates. This is not real-world accuracy.
- Domain and certificate ages are **pretend data** for the benchmark (local stores have no real domains).
  Without it, fewer fakes are caught.
- **Small samples**: 10 agent runs per mode, and 20–24 fake and legit stores per test set. The unguarded
  agent's numbers move between runs because the LLM isn't deterministic.
- step_up prompts were answered "no" automatically. A user who approves them would pay more fakes.

Full results, misses and false alarms: [`benchmark/results/REPORT.md`](benchmark/results/REPORT.md).

## Limitations and roadmap

- **Urgency wording.** Real stores also say "only 2 left" or "sale ends tonight", so pressure-tactic signals cause
  extra confirmations on legit stores. Better context handling is next.
- **Approval UI.** step_up currently means "ask the user", and the demo asks in the terminal. A real approval flow
  (push, link or chat) is not built yet.
- **Evidence ledger.** Decisions are logged to local SQLite. A signed, tamper-evident evidence record is planned
  but not done.
- **Framework integrations.** Today it's one Python function and an HTTP API. Integrations for agent frameworks
  (MCP server, LangChain, OpenAI Agents SDK and others) are planned.
- **Also:** checking that the cart matches the user's request is limited to price and the policy's price limit. The
  LLM judge depends on Groq's availability (when it's slow, more purchases are paused, never allowed). The
  detector was trained mostly on one public dataset and generalises imperfectly to new wordings.

## Credits

The hidden-instruction model was trained partly on
[BrowseSafe-Bench](https://huggingface.co/datasets/perplexity-ai/browsesafe-bench) by Perplexity AI (MIT License),
plus snippets from this project's own benchmark dev stores. The dataset itself is not included in this repository.
See [NOTICE](NOTICE).

## License

[Apache License 2.0](LICENSE). Third-party notices are in [NOTICE](NOTICE).

## For contributors

```bash
git clone <this repo> && cd paybrake
python -m venv .venv && .venv\Scripts\activate        # Windows; use source .venv/bin/activate elsewhere
pip install -e ".[server,dev]"
paybrake setup
python -m pytest -v
```

**Demo with local test stores** (fictional brands). Each command goes in its own terminal:

```powershell
$env:PAYBRAKE_ALLOW_LOCAL="1"; paybrake serve   # lets the guard fetch stores on 127.0.0.1
python testsites\run_testsites.py
python demo\agent_demo.py                        # scripted agent
python demo\llm_agent.py                         # real Groq agent (GROQ_API_KEY); --no-guard for "before"
```

**Settings.** The server and scripts read a `.env` file in the current directory (see `.env.example`). Variables
already set in your shell win over `.env`. Main ones: `GROQ_API_KEY`, `PAYBRAKE_URL`, `PAYBRAKE_DB`,
`PAYBRAKE_ALLOW_LOCAL`, `PAYBRAKE_CHECK_DEADLINE_S`. The old `AGENTGUARD_*` names still work, with a warning.

**Benchmark.** Each command goes in its own terminal:

```powershell
python benchmark\serve.py                         # stores on http://127.0.0.1:8200/store-XX/
$env:PAYBRAKE_ALLOW_LOCAL="1"; $env:PAYBRAKE_BENCHMARK="1"; paybrake serve
python benchmark\run_guard_eval.py                # restart the server first: it caches scans for 10 minutes
python benchmark\run_agent_eval.py                # needs GROQ_API_KEY
python benchmark\make_report.py                   # writes benchmark\results\REPORT.md
```

`PAYBRAKE_BENCHMARK=1` switches on the pretend domain data. Never set it outside the benchmark.

**Retrain the detector.** The dataset is about 190 MB and is not committed. Download `train.parquet` and
`test.parquet` from BrowseSafe-Bench into `paybrake\detector\data\`, then:

```powershell
pip install -e ".[train]"
python paybrake\detector\build_dataset.py
python paybrake\detector\train.py
python paybrake\detector\pick_threshold.py        # threshold, on the benchmark DEV stores only
```

| Folder | What it does |
|---|---|
| `paybrake/api/` | FastAPI app: `POST /check` and `GET /decisions` |
| `paybrake/scanner/` | Store checks, safe fetching, rendering, scoring, `rules.yaml` |
| `paybrake/detector/` | Hidden-instruction classifier and LLM judge (model files ship in the package) |
| `paybrake/client/` | `guard_checkout()`, the lightweight client |
| `testsites/`, `demo/` | Local fictional test stores and demo agents |
| `benchmark/` | Generated stores, guard and agent evals, results |
| `tests/` | Automated tests |
