# knownprint in the backend: Python (Django, Flask, FastAPI)

Part of the knownprint quickstart for AI coding agents, Step 6. Read
https://knownprint.com/quickstart.md first: it holds the rules that apply here (never read or print
secrets, ask before touching a live server, an unknown result is never a pass). This file covers the
module that reads the event, runs the six checks and decides, and how to call it from a handler. The
checks and rules it implements are written out in https://knownprint.com/quickstart/other.md.

Use the module as written. It reads `KNOWNPRINT_API`, `KNOWNPRINT_SECRET_KEY` and
`KNOWNPRINT_SITE_ORIGINS`, never logs a request id, an address or a secret, and turns every failure
into an "unknown" result that takes the challenge path.

## The module

Python 3.9 or later, standard library only; replace the in-memory dictionary with Redis
(`redis.set(f"kp:used:{request_id}", 1, px=70000, nx=True)`) when the app runs more than one
process:

```python
# knownprint.py
import ipaddress
import json
import logging
import os
import re
import threading
import time
import urllib.error
import urllib.request
from datetime import datetime

API = os.environ.get("KNOWNPRINT_API", "")
SECRET_KEY = os.environ.get("KNOWNPRINT_SECRET_KEY", "")
SITE_ORIGINS = {o.strip() for o in os.environ.get("KNOWNPRINT_SITE_ORIGINS", "").split(",") if o.strip()}
REQUEST_ID = re.compile(r"evt_[a-z2-7]{26}")
MAX_AGE = 10.0
CLOCK_SKEW = 60.0
log = logging.getLogger("knownprint")

_used = {}
_lock = threading.Lock()


def _use_once(request_id):
    now = time.time()
    with _lock:
        for key in [k for k, until in _used.items() if until <= now]:
            del _used[key]
        if request_id in _used:
            return False
        _used[request_id] = now + MAX_AGE + CLOCK_SKEW
        return True


def canonical_ip(text):
    try:
        address = ipaddress.ip_address(str(text).strip())
    except ValueError:
        return None
    if address.version == 6 and address.ipv4_mapped is not None:
        address = address.ipv4_mapped
    return str(address)


def client_ip(peer_address, forwarded_for):
    """The last X-Forwarded-For entry when the peer is the site's own proxy, else the peer."""
    peer = canonical_ip(peer_address)
    if peer in ("127.0.0.1", "::1"):
        entries = [e.strip() for e in (forwarded_for or "").split(",") if e.strip()]
        if entries:
            return canonical_ip(entries[-1])
    return peer


def _call(method, path, body=None):
    data = None if body is None else json.dumps(body).encode()
    request = urllib.request.Request(API + path, data=data, method=method)
    request.add_header("Authorization", "Bearer " + SECRET_KEY)
    request.add_header("Accept", "application/json")
    if data is not None:
        request.add_header("Content-Type", "application/json")
    try:
        with urllib.request.urlopen(request, timeout=5) as response:
            raw = response.read()
            return json.loads(raw) if raw else True
    except urllib.error.HTTPError as error:
        if error.code in (404, 409):
            return None
        raise


def verify_request_id(request_id, ip):
    """{"ok": True, "event": ...} or {"ok": False, "reason": ...}. Never raises."""
    try:
        if not isinstance(request_id, str) or not REQUEST_ID.fullmatch(request_id):
            return {"ok": False, "reason": "missing"}
        if not _use_once(request_id):
            return {"ok": False, "reason": "used"}
        event = _call("GET", "/v1/events/" + request_id)
        if event is None:
            return {"ok": False, "reason": "not_found"}
        received = datetime.fromisoformat(event["received_at"].replace("Z", "+00:00")).timestamp()
        age = time.time() - received
        if not (-CLOCK_SKEW <= age <= MAX_AGE):
            return {"ok": False, "reason": "stale"}
        if event["integrity"]["replayed"]:
            return {"ok": False, "reason": "replayed"}
        if event["integrity"]["origin"] not in SITE_ORIGINS:
            return {"ok": False, "reason": "origin"}
        if event["network"]["ip"] is None or event["network"]["ip"] != canonical_ip(ip):
            return {"ok": False, "reason": "address"}
        return {"ok": True, "event": event}
    except Exception as error:  # never log the request id or the address
        log.warning("knownprint: %s", type(error).__name__)
        return {"ok": False, "reason": "error"}


def decide(result):
    """'allow' | 'challenge' | 'review' | 'block'. Example thresholds: tune them."""
    if not result["ok"]:
        return "challenge"  # unknown: never allow, never block on this alone
    signals = result["event"]["signals"]
    bot = signals.get("bot") or {}
    tampering = signals.get("tampering") or {}
    score = (signals.get("suspect_score") or {}).get("value")
    if bot.get("value") == "bad":
        return "block"
    if score is None:
        return "challenge"
    if tampering.get("value") is True or score >= 60:
        return "review"
    if score >= 30:
        return "challenge"
    return "allow"


def link_account(request_id, account_id):
    """Attach your account id to the event once the account exists. Never raises."""
    try:
        _call("PATCH", "/v1/events/" + request_id, {"linked_id": str(account_id)})
    except Exception as error:
        log.warning("knownprint link: %s", type(error).__name__)
```

The peer address and the header, by framework: Django `request.META.get("REMOTE_ADDR")` and
`request.META.get("HTTP_X_FORWARDED_FOR")`; Flask `request.remote_addr` and
`request.headers.get("X-Forwarded-For")`; FastAPI `request.client.host` and
`request.headers.get("x-forwarded-for")`. Then
`result = verify_request_id(rid, client_ip(peer, xff))` and `decide(result)`. If the framework is
already set to rewrite the peer address from the header (Django middleware, Flask's `ProxyFix`,
uvicorn's `--proxy-headers`), pass that rewritten address with no header instead.

Next: https://knownprint.com/quickstart.md, the end of Step 6.
