Files

107 lines
3.4 KiB
Python

"""Shared by the plugin-catalog actions: the catalog URL setting, a bounded
fetch, the on-disk copy kept for when the site is down. Stdlib only."""
from __future__ import annotations
import hashlib
import ipaddress
import json
import os
import pathlib
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
DEFAULT_URL = "https://ai-agent.plugins.gabvdl.xyz/catalog.json"
CATALOG_MAX = 4 * 1024 * 1024
ART_MAX = 1024 * 1024
TIMEOUT = 12
UA = "ai-agent-plugin-catalog/1.0"
class Refused(Exception):
def __init__(self, status: int, kind: str, message: str):
super().__init__(message)
self.status, self.kind, self.message = status, kind, message
def read_payload() -> dict:
try:
raw = sys.stdin.read()
d = json.loads(raw) if raw.strip() else {}
return d if isinstance(d, dict) else {}
except Exception:
return {}
def emit(obj: dict) -> None:
sys.stdout.write(json.dumps(obj, ensure_ascii=False))
sys.stdout.flush()
def fail(e: Refused) -> None:
emit({"_error": {"status": e.status, "kind": e.kind, "message": e.message}})
def config() -> dict:
try:
c = json.loads(os.environ.get("AIA_PLUGIN_CONFIG") or "{}")
return c if isinstance(c, dict) else {}
except Exception:
return {}
def _loopback(host: str) -> bool:
if host in ("localhost",):
return True
try:
return ipaddress.ip_address(host).is_loopback
except ValueError:
return False
def catalog_url(raw: object = None) -> str:
"""The ``catalogUrl`` setting, checked: ``https://`` (``http://`` only to
this machine — a local preview), ending in ``.json``, no credentials."""
url = str(raw if raw is not None else (config().get("catalogUrl") or DEFAULT_URL)).strip()
p = urllib.parse.urlsplit(url)
if p.username or p.password or not p.hostname:
raise Refused(400, "bad_url", f"the catalog URL isn't a plain web address: {url}")
if p.scheme != "https" and not (p.scheme == "http" and _loopback(p.hostname)):
raise Refused(400, "bad_url", "the catalog URL must be https:// (http:// only to this machine)")
if not p.path.endswith(".json"):
raise Refused(400, "bad_url", "the catalog URL must point at its catalog.json")
return urllib.parse.urlunsplit((p.scheme, p.netloc, p.path, "", ""))
def fetch(url: str, limit: int) -> tuple[bytes, str]:
req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept": "*/*"})
try:
with urllib.request.urlopen(req, timeout=TIMEOUT) as r: # noqa: S310 — checked by catalog_url
body = r.read(limit + 1)
ctype = (r.headers.get("Content-Type") or "").split(";")[0].strip().lower()
except urllib.error.HTTPError as e:
raise Refused(502, "unreachable", f"HTTP {e.code}") from None
except (urllib.error.URLError, TimeoutError, OSError) as e:
reason = getattr(e, "reason", e)
raise Refused(502, "unreachable", str(getattr(reason, "strerror", None) or reason)) from None
if len(body) > limit:
raise Refused(502, "too_big", "the catalog site answered more than expected")
return body, ctype
def cache_dir() -> pathlib.Path:
d = pathlib.Path(os.environ.get("AIA_PLUGIN_DATA_DIR") or "/tmp/plugin-catalog")
d.mkdir(parents=True, exist_ok=True)
return d
def key(url: str) -> str:
return hashlib.sha256(url.encode()).hexdigest()[:16]
def now() -> int:
return int(time.time())