Metadata-Version: 2.4
Name: maskena
Version: 0.1.0
Summary: Python client for the Maskena API: prompt injection detection and personal data removal for LLM inputs.
Author-email: Maskena <dev@maskena.com>
License-Expression: MIT
Project-URL: Homepage, https://maskena.com
Project-URL: Documentation, https://maskena.com/docs?lang=en
Keywords: prompt injection,llm,rag,security,pii,anonymization,lgpd
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
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
Requires-Dist: httpx<1,>=0.24
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Dynamic: license-file

# Maskena Python SDK

Python client for the [Maskena API](https://maskena.com/docs?lang=en). Check texts and files for prompt injection,
hidden content and data exfiltration before they reach a language model, and remove personal data.

- Synchronous and asynchronous clients
- Typed results and one exception class per error type
- Automatic retries on rate limits and server errors, respecting `Retry-After`
- Python 3.9 or later; one dependency (`httpx`)

## Installation

```bash
pip install maskena
```

## Quickstart

Create an API key in the dashboard, under **API**, and set it as an environment variable:

```bash
export MASKENA_API_KEY="sfk_..."
```

```python
from maskena import Maskena

client = Maskena()

result = client.check("Summarize this email: ...", clean=True)

if result.flagged:
    print(result.verdict, [f.title for f in result.findings])
    safe_text = result.clean_text
```

`flagged` is `True` whenever the verdict is not `safe`. A common policy is to block `dangerous` content and send
`suspicious` content to review, or to continue with `clean_text`.

## Checking texts

```python
result = client.check(
    user_message,
    clean=True,          # also return clean_text
    format="html",       # "text" (default), "markdown" or "html"
    depth="standard",    # "fast", "standard" (default) or "max"
)

result.verdict           # "safe", "suspicious" or "dangerous"
result.score             # 0 to 100, for ranking; not a probability
result.findings          # list of Finding(rule_id, category, severity, title, description, evidence)
result.personal_data     # PersonalData(total, occurrences, counts={"email": 1, ...})
```

Texts sent to `check` are not stored.

## Scanning files

```python
report = client.scan("contract.pdf")               # path
report = client.scan(open("contract.pdf", "rb"))   # binary file object
report = client.scan(data, filename="cv.docx")     # bytes

print(report.verdict)
for finding in report.findings:
    print(finding.severity, finding.title, finding.location)

clean = report.clean_file("pdf")
if clean:
    pdf_bytes = client.download_clean(report.id, "pdf")
```

Supported formats: PDF, DOCX, XLSX, PPTX, ODF, HTML, SVG, TXT, MD, CSV, JSON, YAML, source code, PNG, JPEG and ZIP.
Original files are not stored. Clean versions are available until `clean.expires_at`.

## Sanitizing documents for RAG

```python
job = client.sanitize("manual.pdf", policy="redact", ocr="auto", chunk_size=1200, chunk_overlap=150)

print(job.risk_before.verdict, "->", job.risk_after.verdict)
for item in job.removed:
    print(item.page, item.category, item.reason)

for chunk in job.indexable_chunks:
    index.add(chunk.text, metadata={"page": chunk.page_start, "risk": chunk.risk_after})

# Or the JSON Lines format accepted by LangChain and LlamaIndex loaders:
records = client.download_chunks(job.id)
```

`policy="redact"` removes only the malicious sentence, `"drop"` moves the whole chunk to quarantine, and `"flag"`
keeps the text and marks the chunk.

## Async

```python
from maskena import AsyncMaskena

async with AsyncMaskena() as client:
    result = await client.check(text)
```

Every method of `Maskena` is available as a coroutine on `AsyncMaskena`.

## Errors

```python
import maskena

try:
    client.check(text)
except maskena.RateLimitError as e:
    print("retry in", e.retry_after, "seconds")
except maskena.QuotaExceededError:
    ...
except maskena.APIError as e:
    print(e.status_code, e.code, e.message)
```

| Exception | Status | Typical `code` |
|---|---|---|
| `InvalidRequestError` | 400, 422 | `invalid_option`, `invalid_document`, `empty_file`, `validation_error` |
| `AuthenticationError` | 401 | `missing_api_key`, `invalid_api_key` |
| `QuotaExceededError` | 402 | `quota_exceeded` |
| `PermissionDeniedError` | 403 | `email_not_verified`, `plan_required` |
| `NotFoundError` | 404 | `not_found` |
| `RequestTooLargeError` | 413 | `file_too_large`, `text_too_large` |
| `RateLimitError` | 429 | `rate_limited` |
| `ServerError` | 5xx | `processing_failed`, `internal_error` |
| `APIConnectionError`, `APITimeoutError` | none | network failure or timeout |

All API errors inherit from `APIError`, and every exception inherits from `MaskenaError`. Use `code` in your logic;
`message` is human-readable text in the language of the request and may change.

## Retries

By default, a request is retried up to 2 times on:

- `429`, waiting for the number of seconds in `Retry-After`;
- `5xx`, with exponential backoff;
- connection errors, which happen before the request reaches the server.

Timeouts are retried only for `GET` requests. A `POST` that timed out may have been processed and charged, so the
library raises `APITimeoutError` instead of sending it again. Failed requests are never charged.

```python
client = Maskena(max_retries=0)       # disable retries
```

## Configuration

```python
client = Maskena(
    api_key="sfk_...",                # default: MASKENA_API_KEY
    base_url="https://maskena.com",   # default: MASKENA_BASE_URL, then https://maskena.com
    timeout=120.0,                    # seconds per request
    max_retries=2,
    language="en",                    # "en", "pt" or "es" for titles, descriptions and error messages
    app_info="my-app/1.4",            # added to the User-Agent; helps support identify your integration
)
```

To use a proxy, custom TLS settings or a shared connection pool, pass your own `httpx.Client` (or `httpx.AsyncClient`)
as `http_client`. In that case, configure the timeout on that client.

Use the client as a context manager, or call `close()`, to release connections.

## Results

Every result object keeps the complete JSON response in `raw`, so fields added to the API later are available before
the library is updated:

```python
result.raw["layers"]
```

## Links

- [API documentation](https://maskena.com/docs?lang=en)
- [OpenAPI specification](https://maskena.com/openapi.json)
- [Detection accuracy](https://maskena.com/precisao?lang=en)

## License

MIT
