Metadata-Version: 2.4
Name: Xorion-verify
Version: 1.0.0
Summary: Self-hosted ASGI browser verification with configurable challenges and bounded request handling
Author: Xorion Verify contributors
License-Expression: MIT
Project-URL: Documentation, https://github.com/testfkij/orion-model
Project-URL: Source, https://github.com/testfkij/orion-model
Keywords: browser-verification,anti-abuse,asgi,rate-limit,security
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Web Environment
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
Classifier: Topic :: Security
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE.md
Dynamic: license-file

# Xorion Verify

Xorion Verify is a self-hosted ASGI middleware package for browser-friction verification, configurable challenges, request filtering and an opt-in extension registry. It can raise the cost of simple automation and reject some suspicious requests; it is not proof that a visitor is human, not a drop-in replacement for a managed WAF, and not a network-scale DDoS defence.

**Release designation:** official source release `1.0.0` (Production/Stable package classifier). PyPI publication is controlled by the project maintainer and has not been performed by this session. Local integration checks passed for the documented flows; no independent security audit, production load study, false-positive campaign, or upstream network DDoS deployment has been verified.

## What is included

- A classic HTML/CSS/vanilla-JavaScript browser screen using black, white, yellow, green and red. No CDN, external scripts, trackers, external fonts or image APIs.
- Default: five random lowercase letters (`a`–`z`). Optional word-reversal, simple math, or fixed custom prompt/answer challenges.
- A short-lived single-use challenge, browser/connection status, verification-request loading state, and same-origin JSON verification.
- Browser-support and endpoint-reachability checks; these are signals, not proof of humanity.
- Short-lived `HttpOnly; SameSite=Lax` verification cookie. `Secure` and the `__Host-` cookie name are used whenever HTTPS is known. HTTPS behind a TLS-terminating proxy requires correct trusted-proxy configuration.
- A bounded request inspector with per-IP limits, concurrency, target/header/body limits, body-read deadline, IP allow/deny lists, heuristic signatures and structured security events.
- Optional `Global.txt` IPv4/IPv6 reputation feed (HTTPS source configurable, refreshed every 5 minutes), risk warning/short override page and optional consent-gated HMAC-pseudonymized metadata storage.
- Adaptive application-layer overload shedding, optional CSP/Report-Only browser headers, STL reviewed-rule metadata/audit log, and cached PyPI release-information checking.
- `orion setup` project scanner/wrapper generator, `orion serve` local port runner, and optional `orion dns-verify` TXT verification helper.
- Framework-neutral `JSONResponse` / `json_response` helpers.
- Store interfaces for integrations, plus bounded **process-local** default state for development and single-worker deployments.

## Install and run locally

From a checked-out source tree:

```bash
python -m pip install .
```

After the maintainer uploads this version, the install command is `python -m pip install Xorion-verify`. This source tree was not uploaded to PyPI by this session; the maintainer controls the publication.

## FastAPI integration example

Register your application routes before wrapping the app. Start with WAF signatures in `log` mode in a staging environment; evaluate logs and false positives before considering `block` mode.

```python
from fastapi import FastAPI
from xorion_verify import ExploitGuardMiddleware, XorionVerifyMiddleware

site = FastAPI()

@site.get("/")
async def home():
    return {"message": "Hello"}

# The defaults below assume TLS is terminated directly at the ASGI server.
verified_site = XorionVerifyMiddleware(
    site,
    token_ttl=900,
    challenge_ttl=120,
    body_limit=1 * 1024 * 1024,
    verify_timeout=3.0,
    max_concurrent_requests=128,
    protected_paths=("/", "/dashboard", "/account"),
)

app = ExploitGuardMiddleware(
    verified_site,
    rate_limit=(120, 60),
    path_rate_limits={"/login": (10, 60)},
    max_concurrent_requests=64,
    max_body_bytes=5 * 1024 * 1024,
    body_read_timeout=5.0,
    max_target_bytes=8192,
    max_header_count=100,
    max_header_bytes=32768,
    waf_mode="log",          # observe first; evaluate false positives
    inspect_body=False,       # opt in only after endpoint-specific review
)
```

The `XorionVerifyMiddleware` limits the verification POST to at most 1 MiB; `ExploitGuardMiddleware` has a hard maximum configurable body limit of 5 MiB. Neither value is a total-process-memory guarantee. Buffers, concurrent requests, framework parsing and response objects all consume additional memory.

## TLS-terminating reverse proxies

TLS and certificates are configured at the edge or proxy, not by this package. If the proxy forwards HTTP to the ASGI app, the middleware must know the actual proxy peer before it trusts `X-Forwarded-Proto` or `X-Forwarded-For`. Configure **only** the proxy IPs/CIDRs that can reach the application, and ensure the proxy overwrites incoming forwarded headers. Example for a proxy connecting from loopback—replace this with the exact address/CIDR observed by your ASGI server:

```python
PROXY_NETWORKS = ("127.0.0.1/32",)

verified_site = XorionVerifyMiddleware(
    site,
    trusted_proxies=PROXY_NETWORKS,
    cookie_secure=True,
)
app = ExploitGuardMiddleware(
    verified_site,
    trusted_proxies=PROXY_NETWORKS,
    waf_mode="log",
)
```

Do not trust all IP ranges just to make the cookie work. The origin should not be directly reachable from the public internet if forwarded headers are used for security decisions. A provider firewall or host firewall should limit origin access to your edge/proxy. The origin `Host` should remain the public hostname expected by the browser's `Origin` header.

## Browser verification and API behavior

The challenge endpoint is `/.well-known/xorion/verify`. A `HEAD` request performs a bounded reachability check; `POST` submits JSON. Non-HTML clients get structured JSON errors, and browser navigations that explicitly accept `text/html` may receive the interstitial. The page shows the connection/browser checks, a loading state while the verification request is running, and a reload link after a failed one-time challenge. A successful verification sets a short-lived cookie. Browser signals such as `navigator.webdriver` can be forged or avoided by automation and must not be treated as authentication.

### Configure the challenge

Random five-letter verification is the default. Other modes are available without adding a route or frontend framework:

```python
from fastapi import FastAPI
from xorion_verify import XorionVerifyMiddleware

site = FastAPI()

# Default: every visitor receives a fresh five-letter lowercase challenge.
app = XorionVerifyMiddleware(site, challenge_mode="random")

# Random word challenge: visitors type the word backwards.
app = XorionVerifyMiddleware(site, challenge_mode="word")

# Simple addition/subtraction problem, generated for each challenge.
app = XorionVerifyMiddleware(site, challenge_mode="math")

# Fixed challenge prompt and shared answer for every visitor.
# Keep the answer in an environment variable/secret store, not source control.
import os
app = XorionVerifyMiddleware(
    site,
    challenge_mode="fixed",
    challenge_prompt="Enter the private access phrase",
    challenge_answer=os.environ["XORION_CHALLENGE_ANSWER"],
)
```

`challenge_mode` accepts `random`, `word`, `math`, or `fixed`. Fixed mode uses the same answer for every visitor; it is a shared passphrase gate, not a strong anti-bot challenge. Anyone who learns or guesses that phrase can pass it. Never put credentials, API keys, payment secrets or administrator passwords in the challenge prompt or client-side page. The fixed answer is not embedded in the HTML, but server-side source code is still not the right place to store a secret.

Example response helper:

```python
from xorion_verify import JSONResponse, json_response

async def api_health(scope, receive, send):
    await json_response({"ok": True, "version": "1.0.0"})(scope, receive, send)

response = JSONResponse(
    {"ok": False, "error": "busy"},
    status_code=503,
    headers={"retry-after": "2"},
    max_bytes=4096,
)
```

`JSONResponse` rejects NaN/infinity JSON values, serializes a bounded output body, validates extra header names/values, and prevents caller-supplied content type/length from overriding calculated values. It is an ASGI response callable, **not** a middleware layer. Authentication, authorization, validation and CSRF protections remain the application's responsibility.

## Rate limits and shared state

`XorionVerifyMiddleware` exposes `challenge_rate_limit`, `unverified_rate_limit` and `verify_rate_limit` as `(requests, seconds)` policies. `ExploitGuardMiddleware` exposes a global policy and optional path policies. The in-memory stores are bounded and local to one process.

For multiple workers or hosts, supply an implementation of the exported `VerificationStateStore` and a `RateLimitStore`-compatible adapter for `ExploitGuardMiddleware`. Shared implementations must make rate checks atomic, consume each challenge once, expire sessions correctly and use shared backend time. This package does **not** ship a Redis/database adapter, so multiple workers are not coordinated out of the box. `ExploitGuardMiddleware` repeat-probe quarantine is also process-local. Use the same high-entropy `secret_key` across all Xorion workers when using a shared verification store; generate it with `python -c 'import secrets; print(secrets.token_urlsafe(48))'` and keep it in your secret manager/environment, never in source control.

A single `InMemoryVerificationStore` is suitable for local development or one worker, not as the basis for a multi-host production security guarantee.

## Uploads, webhooks, health and streaming

Create a deliberate policy for each route category. The defaults are not a universal policy for your app.

- Keep standard request limits on ordinary routes, login/API endpoints and health checks unless a documented need dictates otherwise.
- Xorion bypasses the challenge for its configured `bypass_paths` and common static assets; configure health-check exceptions deliberately and retain the outer server/edge rate and connection limits.
- `ExploitGuardMiddleware.bypass_paths` bypasses its request inspection and limits for those paths; use it sparingly.
- `body_passthrough_paths` in `ExploitGuardMiddleware` preserves streaming to the application but also skips that middleware's body buffering/size enforcement on those paths. Before using it for large uploads, webhooks or streaming endpoints, enforce route-specific size limits and read timeouts at the edge, HTTP server and application.
- Validate webhook signatures, timestamps and replay IDs. Do not treat a route as trusted just because it is a webhook.

## Request protection and exploit signatures

`ExploitGuardMiddleware` provides bounded concurrent admission, token-bucket limits, request-target/header caps, body-size/read-time caps, IP allow/deny policies, signature heuristics, optional bounded body scanning and structured audit events. `waf_mode` is `off`, `log` or `block`; the default is `log` until an operator has measured false positives. Built-in and custom signatures can have false positives and misses. The regular-expression checks reject some common nested-quantifier shapes, but Python's standard regex engine has no per-match timeout; custom expressions must be reviewed and tested on long adversarial inputs. Do not load untrusted extension code or patterns.

Test `log` mode in staging against normal workflows first, measure false positives, adjust routes/rules, and only then decide whether to enable `block`. Do not make block-mode decisions based on a few synthetic requests.

## DDoS and production limits

Python middleware only sees requests that reach the application. It cannot absorb network/transport volumetric attacks, SYN floods, saturated bandwidth or attacks that exhaust the edge before reaching Python. Configure an upstream provider/CDN/WAF with network-scale DDoS mitigation, origin firewalling, edge request/header/body/time limits, connection limits and server-level timeouts. Ensure direct origin access cannot bypass that edge. This package does not create or configure those services.

Application identity and safety remain separate: keep authentication, authorization, CSRF protection, session management, input validation, output encoding, webhook verification, dependency patching and extension review independently enforced. A stable release label is not a security certification; the independent audit and production load/false-positive campaign remain outside the checks performed here.

## Global IP feed, load shedding and STL

`Global.txt` is intentionally empty by default. The generated wrapper merges it with FireHOL Level 1 and Blocklist.de's recent attacker list. If `GITHUB_TOKEN` is configured with repository Contents read access, it also fetches the private project `Global.txt` through GitHub's Contents API. Each feed is size/time bounded, validated and deduplicated; invalid sources preserve their last-known-good entries and report an error. Refresh occurs every 300 seconds during ASGI lifespan or on the next request when lifespan events are unavailable. Add `ORION_GLOBAL_LIST_URLS` as a comma-separated set of additional HTTPS feeds. Optional public proxy feeds are OFF by default; enable them with `ORION_BLOCK_PUBLIC_PROXIES=1` or `ORION_PROXY_LIST_URLS`. Proxy/VPN use is not proof of abuse and can block legitimate shared-network users, so stage these sources in log-only mode and evaluate false positives before enforcing them. Never claim a fixed blacklist count or numeric danger level unless the actual loaded data and testing justify it.

A matched HTML visitor sees a warning explaining the matching listed network and can accept a temporary override; all inner browser verification, app authentication and request checks continue. Non-HTML requests from listed IPs receive JSON HTTP 403. When you run `orion setup --collect-consent --apply`, it can enable a separate SQLite store that saves only HMAC-pseudonymized IP/fingerprint metadata after a required consent checkbox. This is optional; supply `ORION_PRIVACY_KEY` from a secret store and set a retention/privacy policy appropriate for your jurisdiction. No raw address or user-agent is written by that consent store.

`AdaptiveOverloadMiddleware` limits concurrent app work and reduces capacity after sustained high latency, returning HTTP 503 with `Retry-After` when saturated. `BrowserSecurityMiddleware` can add CSP in Report-Only or enforcement mode; the generated setup uses Report-Only by default. It cannot absorb traffic before Python or increase network bandwidth. `STL.json` records reviewed active/patched/false-positive rule metadata. A patched finding stays in history; it is not an automatic bypass. Never “attack back” against source IPs: log, rate-limit, reject and report through your hosting provider instead.

## Setup and connection options

```bash
orion setup --path . --module main:app       # preview only
orion setup --path . --module main:app --apply
orion serve --path . --host 127.0.0.1 --port 8000
orion global-status --path Global.txt
orion stl-status --path STL.json
orion update-check
orion dns-verify --domain example.com --token YOUR_TOKEN
```

`orion setup` scans for a FastAPI/Starlette app; if it cannot find exactly one, pass `--module package.module:app`. It writes a separate `orion_verify_setup.py` wrapper plus empty `Global.txt` and `STL.json` templates. It does **not** rewrite your original source code. Inspect the generated wrapper and run locally on loopback first. `orion serve` runs that wrapper on a port (default `127.0.0.1:8000`); it does not automatically take over a domain or edit the existing reverse-proxy configuration. To affect a public site, route that site's actual server/reverse-proxy to the generated app, configure HTTPS and trusted proxy peers, and firewall the origin appropriately. A local ASGI setup requires no ownership TXT record. The optional `dns-verify` command checks a deliberately configured `_orion-verify` TXT record; it is a DNS lookup helper, not a reverse proxy or an internet tunnelling service.

`orion update-check` reads PyPI metadata through a 5-minute cache. `orion update-check --watch` polls metadata every 300 seconds until Ctrl+C. It only installs a release when explicitly requested with `--apply` and confirmed interactively (or `--yes` in a deliberate noninteractive command); watch mode never installs packages.

## Extensions: commands, hooks, settings and browser assets

The repository-only `Extension/` folder contains the submission process, manifest schema, AI generation prompt, starter template and a sample. It is explicitly excluded from the PyPI source archive. Contributors submit an idea/code proposal by GitHub issue or the maintainer's published contact channel, then wait for approval; the maintainer reviews and manually merges approved folders to `Extension/<slug>/`. Users fetch an approved extension using:

```bash
orion pull --extension request-summary
orion extensions list
orion extensions uninstall request-summary
```

An extension may use Python for commands and hooks; JSON for its manifest/settings; Markdown for instructions; and optional JS/CSS/HTML assets for a host application's browser UI. Nested files are supported. The manifest's `commands` list maps namespaced commands to Python methods. `ExtensionRegistry` supports explicitly registered commands and `on_challenge`, `on_verified`, and `on_blocked` hooks, but the embedding host must call those APIs; Xorion does not automatically inject browser assets or dispatch all hooks into an application.

Downloads are saved as **inactive files**—the pull command does not execute them. `load_extension()` explicitly imports Python code. Extensions are **not sandboxed** and execute with the host process's privileges when imported. Review every file, pin trusted versions, and never install an unreviewed extension on a sensitive server. See [Extension/README.md](Extension/README.md) and [Extension/SYSTEM_PROMPT.md](Extension/SYSTEM_PROMPT.md).

## Release status and docs

See [DOCUMENTATION_INDEX.md](DOCUMENTATION_INDEX.md) for the documentation map, [API_REFERENCE.md](API_REFERENCE.md) for the request/extension APIs, [CONFIGURATION.md](CONFIGURATION.md) for every middleware option, [DEPLOYMENT.md](DEPLOYMENT.md) for operational prerequisites, [THREAT_MODEL.md](THREAT_MODEL.md) for trust boundaries, [SECURITY.md](SECURITY.md) for the security policy, [COVERAGE.md](COVERAGE.md) for implemented behavior and limits, [VALIDATION.md](VALIDATION.md) for the actual local-check record, and [CHANGELOG.md](CHANGELOG.md) for release history.

Source repository: https://github.com/testfkij/orion-model
