Metadata-Version: 2.5
Name: Kemon-Security
Version: 0.1.0
Summary: A modular Python security toolkit for building secure REST APIs with standardized responses, authentication, permanent IP protection, rate limiting, request validation, and framework integrations.
Project-URL: Homepage, https://github.com/P0KEM0N/Kemon-Security
Project-URL: Repository, https://github.com/P0KEM0N/Kemon-Security
Project-URL: Issues, https://github.com/P0KEM0N/Kemon-Security/issues
Project-URL: Changelog, https://github.com/P0KEM0N/Kemon-Security/blob/main/CHANGELOG.md
Author: P0KEM0N
License: MIT
License-File: LICENSE
Keywords: api,argon2,authentication,fastapi,flask,ip-ban,jwt,middleware,rate-limiting,rest,scrypt,security
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: FastAPI
Classifier: Framework :: Flask
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT 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: Programming Language :: Python :: 3.13
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Security
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: pydantic<2.13,>=2.12.5
Requires-Dist: pyjwt<3,>=2.8
Provides-Extra: all
Requires-Dist: annotated-doc>=0.0.4; extra == 'all'
Requires-Dist: argon2-cffi<24,>=23.1; extra == 'all'
Requires-Dist: fastapi<0.116,>=0.115; extra == 'all'
Requires-Dist: flask>=3.0; extra == 'all'
Requires-Dist: redis>=5.0; extra == 'all'
Requires-Dist: starlette<0.42,>=0.40; extra == 'all'
Requires-Dist: uvicorn[standard]>=0.24; extra == 'all'
Provides-Extra: argon2
Requires-Dist: argon2-cffi<24,>=23.1; extra == 'argon2'
Provides-Extra: dev
Requires-Dist: build>=1.0; extra == 'dev'
Requires-Dist: httpx>=0.25; extra == 'dev'
Requires-Dist: mypy>=1.7; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.21; extra == 'dev'
Requires-Dist: pytest-cov>=4.1; extra == 'dev'
Requires-Dist: pytest>=7.4; extra == 'dev'
Requires-Dist: ruff>=0.1; extra == 'dev'
Requires-Dist: twine>=4.0; extra == 'dev'
Provides-Extra: fastapi
Requires-Dist: annotated-doc>=0.0.4; extra == 'fastapi'
Requires-Dist: fastapi<0.116,>=0.115; extra == 'fastapi'
Requires-Dist: starlette<0.42,>=0.40; extra == 'fastapi'
Requires-Dist: uvicorn[standard]>=0.24; extra == 'fastapi'
Provides-Extra: flask
Requires-Dist: flask>=3.0; extra == 'flask'
Provides-Extra: redis
Requires-Dist: redis>=5.0; extra == 'redis'
Provides-Extra: sqlite
Description-Content-Type: text/markdown

# Kemon-Security

**Secure Your API. Protect Every Request.**

A modular Python security toolkit for building secure REST APIs with
standardized responses, authentication, permanent IP protection, rate
limiting, request validation, and framework integrations.

> Status: **v0.1.0 Alpha** — Under active development.

---

## Features

- **Standardized API responses** (`APIResponse`)
- **JWT authentication** (HS256, `exp`/`iat`/`sub` claims)
- **API key authentication** (SHA-256, constant-time compare)
- **Password hashing** (Argon2id, scrypt fallback for ARM64)
- **Advanced rate limiting** with **permanent IP bans**
- **SQLite storage** (default) and **Redis storage**
- **Trusted-proxy IP extraction** (safe against XFF spoofing)
- **Request validation** (email, password, JSON, size limits)
- **FastAPI** and **Flask** integrations
- **Framework-independent core**

---

## Installation

### Standard install

```bash
pip install Kemon-Security
```

### With extras

```bash
pip install "Kemon-Security[fastapi]"
pip install "Kemon-Security[flask]"
pip install "Kemon-Security[redis]"
pip install "Kemon-Security[all]"
```

### Termux / ARM64 (important)

Termux can't build `pydantic-core` from source. Install the prebuilt wheel first:

```bash
pkg install -y python clang libffi openssl
python -m venv .venv && source .venv/bin/activate
pip install pydantic-core --index-url https://termux-user-repository.github.io/pypi/
pip install "pydantic>=2.12.5,<2.13"
pip install --no-deps Kemon-Security
```

See `docs/installation.md` for full details.

---

## Quick Start

```python
from kemon_security.config import SecurityConfig
from kemon_security.storage import SQLiteStorage
from kemon_security.ratelimit import RateLimiter
from kemon_security.response import APIResponse

config = SecurityConfig(secret_key="x" * 40, debug=True)
storage = SQLiteStorage("./kemon.db")
limiter = RateLimiter(storage, requests=7, window=1.0, permanent_ban=True)

try:
    result = limiter.check("1.2.3.4")
    print(APIResponse.ok("Welcome", {"allowed": result.allowed}).to_dict())
except Exception as e:
    print(APIResponse.from_exception(e).to_dict())
```

---

## API Response

Every response follows this exact shape:

```json
{
  "success": true,
  "message": "User created successfully",
  "data": { "id": 1 },
  "errors": null
}
```

```python
from kemon_security.response import APIResponse

APIResponse.ok("User created", {"id": 1})           # 200
APIResponse.created("Created", {"id": 2})           # 201
APIResponse.error("Bad request", status_code=400)    # 400
APIResponse.not_found()                              # 404
APIResponse.unauthorized()                           # 401
APIResponse.forbidden()                              # 403
APIResponse.validation_error(errors=[{"field": "email", "msg": "invalid"}])  # 422
```

---

## Authentication

### JWT

```python
from kemon_security.auth.jwt import JWTManager

mgr = JWTManager("x" * 40, expiration_seconds=3600)
token = mgr.encode("user-123", extra_claims={"role": "admin"})
payload = mgr.verify(token)  # raises AuthenticationError on failure
print(payload["sub"])  # 'user-123'
```

### API Key

```python
from kemon_security.auth.api_key import APIKeyManager

mgr = APIKeyManager(prefix="km_")
key = mgr.generate()
print(key.raw)     # 'km_1a2b3c...' (give to user, don't store)
print(key.hashed)  # SHA-256 hex (store this)

assert APIKeyManager.verify_key(key.raw, key.hashed)
```

### Password

```python
from kemon_security.auth.password import hash_password, verify_password

h = hash_password("hunter2!")
assert verify_password("hunter2!", h)
assert not verify_password("wrong", h)
```

---

## Rate Limiting

Default policy: **7 requests / 1 second / permanent ban on 8th**.

```python
from kemon_security.ratelimit import RateLimiter
from kemon_security.exceptions import IPBannedError

limiter = RateLimiter(storage, requests=7, window=1.0, permanent_ban=True)

try:
    limiter.check("1.2.3.4")
except IPBannedError:
    print("IP is banned")
```

### Admin operations

```python
limiter.is_banned("1.2.3.4")              # bool
limiter.get_ban_info("1.2.3.4")           # BanRecord | None
limiter.list_banned_ips()                 # list[BanRecord]
limiter.ban_ip("1.2.3.4", reason="ABUSE")
limiter.unban_ip("1.2.3.4")               # bool
```

### Permanent ban warning

Permanent IP bans can **accidentally block innocent users** behind shared NAT
or dynamic IPs. Always configure `allowlisted_ips` for trusted networks
and provide an admin `unban_ip()` endpoint.

---

## Configuration

```bash
KEMON_SECRET_KEY=<32+ chars, required in production>
KEMON_STORAGE=sqlite|redis
KEMON_SQLITE_PATH=./kemon_security.db
KEMON_REDIS_URL=redis://localhost:6379/0
KEMON_RATE_LIMIT=7
KEMON_RATE_WINDOW=1.0
KEMON_PERMANENT_BAN=true
KEMON_TRUSTED_PROXIES=127.0.0.1,::1
KEMON_ALLOWLISTED_IPS=10.0.0.1
KEMON_DEBUG=false
```

```python
from kemon_security.config import SecurityConfig
config = SecurityConfig.from_env()
```

---

## FastAPI

```python
from fastapi import FastAPI
from kemon_security.integrations.fastapi import KemonSecurityMiddleware

app = FastAPI()
app.add_middleware(
    KemonSecurityMiddleware,
    requests=7, window=1.0, permanent_ban=True,
    sqlite_path="./kemon.db",
    allowlisted_ips=("10.0.0.1",),
)
```

**Termux pin:** `fastapi>=0.115,<0.116` + `starlette>=0.40,<0.42`

---

## Flask

```python
from flask import Flask
from kemon_security.integrations.flask import init_kemon_security

app = Flask(__name__)
core = init_kemon_security(
    app,
    requests=7, window=1.0, permanent_ban=True,
    sqlite_path="./kemon.db",
)
```

---

## Error Handling

All errors inherit from `APIError`:

```python
from kemon_security.exceptions import (
    APIError, AuthenticationError, AuthorizationError,
    RateLimitError, IPBannedError, ValidationError,
    ConfigurationError, StorageError,
)
```

Every error carries `status_code` and `code` (never leaks tracebacks).

---

## Request Validation

```python
from kemon_security.validation import (
    validate_email, validate_password_strength,
    parse_json, require_fields, require_str, require_int, require_bool,
)

validate_email("user@example.com")
validate_password_strength("Hunter2!")
data = parse_json(request_body, max_bytes=1_048_576)
require_fields(data, "email", "password")
```

---

## Security Notes

- **Never trust XFF** unless the direct peer is in `trusted_proxies`.
- **Never store raw API keys** — store `key.hashed`.
- **Never log passwords or full tokens** — use `redact_secret()`.
- **`KEMON_SECRET_KEY` is mandatory in production** — dev default raises.
- **Always configure `allowlisted_ips`** for shared-egress networks.

See `SECURITY.md` for reporting.

---

## License

MIT — see `LICENSE`.
