592 lines
25 KiB
Python
Executable File
592 lines
25 KiB
Python
Executable File
#!/usr/bin/env python3
|
||
"""Tool Gateway — типизированные инструменты Buryans Hub.
|
||
|
||
Один вход для агентов: /call {tool, args, actor}. Внутри — политика,
|
||
подтверждения, идемпотентность, лимиты и аудит.
|
||
|
||
Запуск: systemd tool-gateway (порт 9140).
|
||
"""
|
||
import base64
|
||
import json
|
||
import os
|
||
import re
|
||
import sqlite3
|
||
import time
|
||
import urllib.error
|
||
import urllib.parse
|
||
import urllib.request
|
||
import uuid
|
||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||
|
||
CFG = "/etc/tool-gateway/config.json"
|
||
DB = "/var/lib/tool-gateway/audit.db"
|
||
HUB = "http://127.0.0.1:9120"
|
||
HA = "http://192.168.1.106:8123"
|
||
NC = "http://192.168.1.109:8080"
|
||
IMMICH = "http://192.168.1.104:2283"
|
||
RADARR = "http://192.168.1.118:7878"
|
||
SONARR = "http://192.168.1.117:8989"
|
||
JELLYFIN = "http://192.168.1.103:8096"
|
||
|
||
|
||
def read(path):
|
||
try:
|
||
return open(path, encoding="utf-8").read().strip()
|
||
except Exception:
|
||
return ""
|
||
|
||
|
||
CFG_D = json.load(open(CFG)) if os.path.exists(CFG) else {}
|
||
TOKENS = {v: k for k, v in (CFG_D.get("tokens") or {}).items()}
|
||
RATE = {}
|
||
import threading
|
||
RATE_LOCK = threading.Lock()
|
||
HA_TOKEN = read("/root/.ha-token")
|
||
RADARR_KEY = read("/root/.radarr-key")
|
||
SONARR_KEY = read("/root/.sonarr-key")
|
||
JELLYFIN_KEY = read("/root/.jellyfin-key")
|
||
IMMICH_KEY = read("/root/.immich-key-new")
|
||
NC_USER = "family"
|
||
NC_PASS = read("/root/.family-nextcloud-pass")
|
||
|
||
|
||
def http(method, url, headers=None, data=None, timeout=20):
|
||
req = urllib.request.Request(url, method=method,
|
||
data=json.dumps(data).encode() if data is not None else None,
|
||
headers=dict({"Content-Type": "application/json"}, **(headers or {})))
|
||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||
body = r.read()
|
||
return r.status, body
|
||
|
||
|
||
def basic(user, pw):
|
||
return "Basic " + base64.b64encode(("%s:%s" % (user, pw)).encode()).decode()
|
||
|
||
|
||
# ---------- инструменты ----------
|
||
|
||
def t_hub_status(args):
|
||
last = None
|
||
for _ in range(3):
|
||
try:
|
||
st, body = http("GET", HUB + "/status.json", timeout=30)
|
||
break
|
||
except Exception as e:
|
||
last = e
|
||
time.sleep(2)
|
||
else:
|
||
raise last or RuntimeError("hub status unavailable")
|
||
d = json.loads(body)
|
||
svc = d.get("services", [])
|
||
down = [s["name"] for s in svc if not s.get("up")]
|
||
return {"total": len(svc), "down": down}
|
||
|
||
|
||
def t_hub_notify(args):
|
||
msg = {"title": args.get("title", "Tool Gateway"),
|
||
"message": args.get("message", ""),
|
||
"priority": args.get("priority", "normal")}
|
||
st, body = http("POST", HUB + "/notify", data=msg)
|
||
return {"status": st, "body": body.decode("utf-8", "replace")[:200]}
|
||
|
||
|
||
def t_ha_states(args):
|
||
domain = args.get("domain")
|
||
st, body = http("GET", HA + "/api/states", {"Authorization": "Bearer " + HA_TOKEN})
|
||
states = json.loads(body)
|
||
if domain:
|
||
states = [s for s in states if s["entity_id"].startswith(domain + ".")]
|
||
out = [{"entity_id": s["entity_id"], "state": s["state"],
|
||
"name": (s.get("attributes") or {}).get("friendly_name")} for s in states]
|
||
return {"count": len(out), "states": out[:200]}
|
||
|
||
|
||
def t_ha_call(args):
|
||
domain = args["domain"]
|
||
service = args["service"]
|
||
data = args.get("data") or {}
|
||
st, body = http("POST", "%s/api/services/%s/%s" % (HA, domain, service),
|
||
{"Authorization": "Bearer " + HA_TOKEN}, data)
|
||
return {"status": st, "body": body.decode("utf-8", "replace")[:200]}
|
||
|
||
|
||
def t_media_queue(args):
|
||
out = {}
|
||
for name, url, key in (("radarr", RADARR, RADARR_KEY), ("sonarr", SONARR, SONARR_KEY)):
|
||
try:
|
||
st, body = http("GET", "%s/api/v3/queue?page=1&pageSize=50" % url,
|
||
{"X-Api-Key": key})
|
||
d = json.loads(body)
|
||
out[name] = {"total": d.get("totalRecords", 0),
|
||
"items": [r.get("title") for r in (d.get("records") or [])][:20]}
|
||
except Exception as e:
|
||
out[name] = {"error": str(e)[:120]}
|
||
return out
|
||
|
||
|
||
def t_media_recent(args):
|
||
st, body = http("GET", JELLYFIN + "/Items?IncludeItemTypes=Movie&Recursive=true"
|
||
"&SortBy=DateCreated&SortOrder=Descending&Limit=10"
|
||
"&Fields=DateCreated",
|
||
{"Authorization": 'MediaBrowser Token="%s"' % JELLYFIN_KEY})
|
||
d = json.loads(body)
|
||
return {"count": len(d.get("Items") or []),
|
||
"items": [i.get("Name") for i in (d.get("Items") or [])]}
|
||
|
||
|
||
def post_json(url, headers, payload):
|
||
try:
|
||
return http("POST", url, headers, payload)
|
||
except urllib.error.HTTPError as e:
|
||
return e.code, e.read()
|
||
|
||
|
||
def _caldav(method, path, body=None, headers=None):
|
||
url = NC + "/remote.php/dav/calendars/%s/%s/" % (NC_USER, urllib.parse.quote(path, safe="/"))
|
||
h = {"Authorization": basic(NC_USER, NC_PASS)}
|
||
if headers:
|
||
h.update(headers)
|
||
req = urllib.request.Request(url, method=method, data=body, headers=h)
|
||
with urllib.request.urlopen(req, timeout=25) as r:
|
||
return r.status, r.read()
|
||
|
||
|
||
def t_calendar_list(args):
|
||
days = int(args.get("days", 7))
|
||
now = time.time()
|
||
start = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime(now))
|
||
end = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime(now + days * 86400))
|
||
cal = args.get("calendar", "Семья")
|
||
body = ('<?xml version="1.0"?><c:calendar-query xmlns:d="DAV:" '
|
||
'xmlns:c="urn:ietf:params:xml:ns:caldav"><d:prop><c:calendar-data/></d:prop>'
|
||
'<c:filter><c:comp-filter name="VCALENDAR"><c:comp-filter name="VEVENT">'
|
||
'<c:time-range start="%s" end="%s"/></c:comp-filter></c:comp-filter></c:filter>'
|
||
'</c:calendar-query>' % (start, end)).encode()
|
||
st, raw = _caldav("REPORT", cal, body, {"Content-Type": "application/xml; charset=utf-8", "Depth": "1"})
|
||
txt = raw.decode("utf-8", "replace")
|
||
events = []
|
||
for block in re.findall(r"BEGIN:VEVENT(.*?)END:VEVENT", txt, re.S):
|
||
s = re.search(r"SUMMARY:(.+)", block)
|
||
t = re.search(r"DTSTART[^:]*:(\S+)", block)
|
||
events.append({"summary": (s.group(1).strip() if s else ""),
|
||
"start": (t.group(1).strip() if t else "")})
|
||
return {"calendar": cal, "count": len(events), "events": events[:30]}
|
||
|
||
|
||
def t_calendar_create(args):
|
||
title = args["title"]
|
||
start = args["start"] # 20261120T150000
|
||
end = args.get("end") or start
|
||
cal = args.get("calendar", "Семья")
|
||
uid = uuid.uuid4().hex
|
||
ics = ("BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Buryans//ToolGateway//RU\r\n"
|
||
"BEGIN:VEVENT\r\nUID:%s\r\nDTSTAMP:%s\r\nDTSTART:%s\r\nDTEND:%s\r\n"
|
||
"SUMMARY:%s\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"
|
||
% (uid, time.strftime("%Y%m%dT%H%M%SZ", time.gmtime()), start, end, title))
|
||
st, raw = _caldav("PUT", cal + "/" + uid + ".ics", ics.encode(),
|
||
{"Content-Type": "text/calendar; charset=utf-8"})
|
||
return {"status": st, "uid": uid, "calendar": cal, "title": title, "start": start}
|
||
|
||
|
||
def t_photos_people(args):
|
||
st, body = http("GET", IMMICH + "/api/people", {"x-api-key": IMMICH_KEY})
|
||
d = json.loads(body)
|
||
return {"total": d.get("total", 0),
|
||
"people": [p.get("name") for p in (d.get("people") or [])][:50]}
|
||
|
||
|
||
def t_photos_albums(args):
|
||
st, body = http("GET", IMMICH + "/api/albums", {"x-api-key": IMMICH_KEY})
|
||
d = json.loads(body)
|
||
return {"count": len(d or []), "albums": [a.get("albumName") for a in (d or [])][:50]}
|
||
|
||
|
||
def t_ha_search(args):
|
||
q = (args.get("query") or "").lower()
|
||
domain = args.get("domain")
|
||
st, body = http("GET", HA + "/api/states", {"Authorization": "Bearer " + HA_TOKEN})
|
||
states = json.loads(body)
|
||
out = []
|
||
for s in states:
|
||
if domain and not s["entity_id"].startswith(domain + "."):
|
||
continue
|
||
name = ((s.get("attributes") or {}).get("friendly_name") or "").lower()
|
||
if q and q not in name and q not in s["entity_id"].lower():
|
||
continue
|
||
a = s.get("attributes") or {}
|
||
out.append({"entity_id": s["entity_id"],
|
||
"name": a.get("friendly_name"),
|
||
"state": s.get("state"),
|
||
"last_changed": s.get("last_changed"),
|
||
"domain": s["entity_id"].split(".")[0],
|
||
"device_class": a.get("device_class"),
|
||
"supported_features": a.get("supported_features")})
|
||
return {"query": q, "count": len(out), "entities": out[:50]}
|
||
|
||
|
||
def _lookup(kind, query):
|
||
if kind == "series":
|
||
st, body = http("GET", SONARR + "/api/v3/series/lookup?term=" + urllib.parse.quote(query),
|
||
{"X-Api-Key": SONARR_KEY})
|
||
else:
|
||
st, body = http("GET", RADARR + "/api/v3/movie/lookup?term=" + urllib.parse.quote(query),
|
||
{"X-Api-Key": RADARR_KEY})
|
||
return json.loads(body)
|
||
|
||
|
||
def t_media_search(args):
|
||
kind = args.get("kind", "series")
|
||
q = args.get("query") or ""
|
||
items = _lookup(kind, q)
|
||
out = []
|
||
for it in (items or [])[:8]:
|
||
out.append({"title": it.get("title"), "year": it.get("year"),
|
||
"tvdbId": it.get("tvdbId"), "tmdbId": it.get("tmdbId"),
|
||
"overview": (it.get("overview") or "")[:200]})
|
||
return {"kind": kind, "query": q, "count": len(out), "items": out}
|
||
|
||
|
||
def t_media_request(args):
|
||
kind = args.get("kind", "series")
|
||
q = args.get("query") or ""
|
||
season = args.get("season")
|
||
items = _lookup(kind, q)
|
||
if not items:
|
||
return {"error": "not_found", "query": q}
|
||
it = items[0]
|
||
if kind == "series":
|
||
st, body = http("GET", SONARR + "/api/v3/rootfolder", {"X-Api-Key": SONARR_KEY})
|
||
roots = json.loads(body)
|
||
st, body = http("GET", SONARR + "/api/v3/qualityprofile", {"X-Api-Key": SONARR_KEY})
|
||
profiles = json.loads(body)
|
||
root = roots[0]["path"] if roots else "/data/series"
|
||
qp = profiles[0]["id"] if profiles else 1
|
||
seasons = it.get("seasons") or []
|
||
for s in seasons:
|
||
s["monitored"] = (str(s.get("seasonNumber")) == str(season)) if season else True
|
||
payload = {"title": it.get("title"), "tvdbId": it.get("tvdbId"),
|
||
"qualityProfileId": qp, "rootFolderPath": root,
|
||
"monitored": True, "seasonFolder": True, "seasons": seasons,
|
||
"addOptions": {"searchForMissingEpisodes": True,
|
||
"monitor": "none" if season else "all"}}
|
||
st, body = post_json(SONARR + "/api/v3/series", {"X-Api-Key": SONARR_KEY}, payload)
|
||
else:
|
||
st, body = http("GET", RADARR + "/api/v3/rootfolder", {"X-Api-Key": RADARR_KEY})
|
||
roots = json.loads(body)
|
||
st, body = http("GET", RADARR + "/api/v3/qualityprofile", {"X-Api-Key": RADARR_KEY})
|
||
profiles = json.loads(body)
|
||
root = roots[0]["path"] if roots else "/data/movies"
|
||
qp = profiles[0]["id"] if profiles else 1
|
||
payload = {"title": it.get("title"), "tmdbId": it.get("tmdbId"),
|
||
"qualityProfileId": qp, "rootFolderPath": root, "monitored": True,
|
||
"addOptions": {"searchForMovie": True}}
|
||
st, body = post_json(RADARR + "/api/v3/movie", {"X-Api-Key": RADARR_KEY}, payload)
|
||
try:
|
||
res = json.loads(body)
|
||
except Exception:
|
||
res = {"raw": body.decode("utf-8", "replace")[:200]}
|
||
if st >= 400 and kind == "series":
|
||
try:
|
||
st2, body2 = http("GET", SONARR + "/api/v3/series", {"X-Api-Key": SONARR_KEY})
|
||
for ser in json.loads(body2):
|
||
if ser.get("tvdbId") == it.get("tvdbId"):
|
||
out = {"kind": kind, "query": q, "season": season,
|
||
"already_exists": True, "title": ser.get("title"),
|
||
"id": ser.get("id")}
|
||
if season:
|
||
try:
|
||
cmd = {"name": "SeasonSearch", "seriesId": ser.get("id"),
|
||
"seasonNumber": int(season)}
|
||
st3, body3 = http("POST", SONARR + "/api/v3/command",
|
||
{"X-Api-Key": SONARR_KEY}, cmd)
|
||
out["search"] = {"status": st3,
|
||
"body": body3.decode("utf-8", "replace")[:120]}
|
||
except Exception as e:
|
||
out["search"] = {"error": str(e)[:120]}
|
||
return out
|
||
except Exception:
|
||
pass
|
||
return {"kind": kind, "query": q, "season": season, "status": st,
|
||
"title": res.get("title"), "id": res.get("id"),
|
||
"error": res if st >= 400 else None}
|
||
|
||
def t_hub_service_detail(args):
|
||
name = (args.get("name") or "").lower()
|
||
st, body = http("GET", HUB + "/status.json", timeout=30)
|
||
d = json.loads(body)
|
||
for svc in d.get("services", []):
|
||
if svc.get("name", "").lower() == name:
|
||
return svc
|
||
matches = [x for x in d.get("services", []) if name and name in x.get("name", "").lower()]
|
||
return {"found": False, "query": name, "matches": matches[:10]}
|
||
|
||
|
||
def t_alerts_active(args):
|
||
st, body = http("GET", "http://192.168.1.134:9093/api/v2/alerts", timeout=15)
|
||
alerts = json.loads(body)
|
||
out = []
|
||
for a in alerts:
|
||
lb = a.get("labels") or {}
|
||
out.append({"name": lb.get("alertname"), "severity": lb.get("severity"),
|
||
"instance": lb.get("instance"), "status": (a.get("status") or {}).get("state"),
|
||
"startsAt": a.get("startsAt")})
|
||
return {"count": len(out), "alerts": out[:50]}
|
||
|
||
|
||
def t_backup_status(args):
|
||
import subprocess as sp
|
||
env = dict(os.environ, PGPASSWORD=read("/root/.pg-superuser-pass"))
|
||
q = ("SELECT name, to_char(to_timestamp(last_run),'MM-DD HH24:MI'), "
|
||
"last_status, fails FROM jobs WHERE name ILIKE '%backup%' OR name ILIKE '%verify%' "
|
||
"ORDER BY name;")
|
||
r = sp.run(["psql", "-w", "-h", "192.168.1.151", "-U", "postgres", "-d", "hermes",
|
||
"-t", "-A", "-F", "|", "-c", q], capture_output=True, text=True, timeout=30, env=env)
|
||
rows = [ln.split("|") for ln in (r.stdout or "").strip().splitlines() if ln]
|
||
return {"jobs": [{"name": x[0], "last": x[1], "status": x[2], "fails": x[3]} for x in rows]}
|
||
|
||
def vds_curl(url, timeout=25):
|
||
"""Запрос из VDS (у него есть интернет), т.к. с хоста DPI режет внешние TLS."""
|
||
import subprocess as sp
|
||
r = sp.run(["ssh", "-o", "BatchMode=yes", "-o", "ConnectTimeout=8",
|
||
"root@10.88.0.1", "curl -s -m %d '%s'" % (timeout, url)],
|
||
capture_output=True, text=True, timeout=timeout + 10)
|
||
return (r.stdout or "").strip()
|
||
|
||
|
||
def t_books_search(args):
|
||
q = args.get("query") or ""
|
||
items = []
|
||
url = "https://openlibrary.org/search.json?q=" + urllib.parse.quote(q) + "&limit=5"
|
||
raw = ""
|
||
try:
|
||
st, body = http("GET", url, timeout=15)
|
||
raw = body.decode("utf-8", "replace")
|
||
except Exception:
|
||
raw = vds_curl(url)
|
||
try:
|
||
d = json.loads(raw)
|
||
for doc in (d.get("docs") or [])[:5]:
|
||
items.append({"title": doc.get("title"),
|
||
"authors": (doc.get("author_name") or [])[:3],
|
||
"year": doc.get("first_publish_year"),
|
||
"link": "https://openlibrary.org" + (doc.get("key") or "")})
|
||
except Exception as e:
|
||
items.append({"error": str(e)[:120]})
|
||
return {"query": q, "count": len(items), "items": items}
|
||
|
||
|
||
def t_books_link(args):
|
||
q = args.get("query") or ""
|
||
return {"query": q,
|
||
"biglibrary": "https://biglibrary.org/search?q=" + urllib.parse.quote(q),
|
||
"openlibrary": "https://openlibrary.org/search?q=" + urllib.parse.quote(q),
|
||
"note": "автоматическое скачивание не выполняется"}
|
||
|
||
|
||
def t_books_status(args):
|
||
url = "http://127.0.0.1/"
|
||
try:
|
||
st, body = http("GET", url, {"Host": "books.buryans.ru"}, timeout=10)
|
||
return {"calibre_web": "https://books.buryans.ru", "http": st,
|
||
"reachable": st in (200, 302, 303, 401)}
|
||
except Exception as e:
|
||
return {"calibre_web": "https://books.buryans.ru", "error": str(e)[:120]}
|
||
|
||
def t_audit_recent(args):
|
||
n = int(args.get("limit", 20))
|
||
actor = args.get("actor")
|
||
where = ""
|
||
if actor:
|
||
where = " WHERE actor='%s'" % actor.replace("'", "''")
|
||
r = _pg("SELECT to_char(ts,'MM-DD HH24:MI:SS'), actor, tool, ok, ms "
|
||
"FROM tool_audit%s ORDER BY id DESC LIMIT %d;" % (where, n))
|
||
rows = []
|
||
for ln in (r.stdout or "").strip().splitlines():
|
||
parts = ln.split("|")
|
||
if len(parts) >= 5:
|
||
rows.append({"ts": parts[0], "actor": parts[1], "tool": parts[2],
|
||
"ok": parts[3] == "t", "ms": parts[4]})
|
||
return {"count": len(rows), "rows": rows}
|
||
|
||
|
||
def t_docs_search(args):
|
||
q = (args.get("query") or "").strip()
|
||
if not q or len(q) > 120:
|
||
return {"error": "query must be 1..120 chars"}
|
||
import subprocess as sp
|
||
cmd = ["grep", "-R", "-i", "-n", "-m", "3",
|
||
"--include=*.md", "--include=*.py", "--include=*.yaml", "--include=*.yml",
|
||
q, "/root/buryan-infra/ops", "/root/buryan-infra/docs"]
|
||
r = sp.run(cmd, capture_output=True, text=True, timeout=20)
|
||
rows = []
|
||
for ln in (r.stdout or "").splitlines()[:60]:
|
||
parts = ln.split(":", 2)
|
||
if len(parts) == 3:
|
||
rows.append({"file": parts[0], "line": parts[1], "text": parts[2][:240]})
|
||
return {"query": q, "count": len(rows), "results": rows}
|
||
|
||
|
||
TOOLS = {
|
||
"hub.status": {"fn": t_hub_status, "scope": "read", "confirm": False},
|
||
"hub.notify": {"fn": t_hub_notify, "scope": "write", "confirm": True,
|
||
"actors": ["owner", "family", "agent"]},
|
||
"ha.states": {"fn": t_ha_states, "scope": "read", "confirm": False},
|
||
"ha.call": {"fn": t_ha_call, "scope": "write", "confirm": True,
|
||
"actors": ["owner", "family"]},
|
||
"media.queue": {"fn": t_media_queue, "scope": "read", "confirm": False},
|
||
"media.recent": {"fn": t_media_recent, "scope": "read", "confirm": False},
|
||
"calendar.list": {"fn": t_calendar_list, "scope": "read", "confirm": False},
|
||
"calendar.create": {"fn": t_calendar_create, "scope": "write", "confirm": True,
|
||
"actors": ["owner", "family"]},
|
||
"photos.people": {"fn": t_photos_people, "scope": "read", "confirm": False},
|
||
"photos.albums": {"fn": t_photos_albums, "scope": "read", "confirm": False},
|
||
"ha.search": {"fn": t_ha_search, "scope": "read", "confirm": False},
|
||
"media.search": {"fn": t_media_search, "scope": "read", "confirm": False},
|
||
"media.request": {"fn": t_media_request, "scope": "write", "confirm": True,
|
||
"actors": ["owner", "family"]},
|
||
"hub.service_detail": {"fn": t_hub_service_detail, "scope": "read", "confirm": False},
|
||
"alerts.active": {"fn": t_alerts_active, "scope": "read", "confirm": False},
|
||
"backup.status": {"fn": t_backup_status, "scope": "read", "confirm": False},
|
||
"books.search": {"fn": t_books_search, "scope": "read", "confirm": False},
|
||
"books.link": {"fn": t_books_link, "scope": "read", "confirm": False},
|
||
"books.status": {"fn": t_books_status, "scope": "read", "confirm": False},
|
||
"audit.recent": {"fn": t_audit_recent, "scope": "read", "confirm": False},
|
||
"docs.search": {"fn": t_docs_search, "scope": "read", "confirm": False},
|
||
}
|
||
|
||
|
||
def _pg(sql, timeout=15):
|
||
import subprocess as sp
|
||
env = dict(os.environ, PGPASSWORD=read("/root/.pg-superuser-pass"))
|
||
return sp.run(["psql", "-w", "-h", "192.168.1.151", "-U", "postgres",
|
||
"-d", "hermes", "-t", "-A", "-F", "|", "-c", sql],
|
||
capture_output=True, text=True, timeout=timeout, env=env)
|
||
|
||
|
||
def pg_audit(actor, tool, args, result, ok, started):
|
||
try:
|
||
_pg("""CREATE TABLE IF NOT EXISTS tool_audit(
|
||
id bigserial PRIMARY KEY, ts timestamptz DEFAULT now(),
|
||
actor text, tool text, args jsonb, result jsonb, ok boolean, ms int);""")
|
||
a = json.dumps(args, ensure_ascii=False).replace("'", "''")[:2000]
|
||
r = json.dumps(result, ensure_ascii=False).replace("'", "''")[:4000]
|
||
_pg("INSERT INTO tool_audit(actor,tool,args,result,ok,ms) VALUES "
|
||
"('%s','%s','%s'::jsonb,'%s'::jsonb,%s,%d);"
|
||
% (actor.replace("'", "''"), tool.replace("'", "''"), a, r,
|
||
"true" if ok else "false", int((time.time() - started) * 1000)))
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def audit(actor, tool, args, result, ok, started):
|
||
try:
|
||
os.makedirs(os.path.dirname(DB), exist_ok=True)
|
||
c = sqlite3.connect(DB)
|
||
c.execute("""CREATE TABLE IF NOT EXISTS audit(
|
||
ts TEXT, actor TEXT, tool TEXT, args TEXT, result TEXT, ok INTEGER, ms INTEGER)""")
|
||
c.execute("INSERT INTO audit VALUES(?,?,?,?,?,?,?)",
|
||
(time.strftime("%Y-%m-%dT%H:%M:%S"), actor, tool,
|
||
json.dumps(args, ensure_ascii=False)[:1000],
|
||
json.dumps(result, ensure_ascii=False)[:2000], 1 if ok else 0,
|
||
int((time.time() - started) * 1000)))
|
||
c.commit()
|
||
c.close()
|
||
except Exception:
|
||
pass
|
||
pg_audit(actor, tool, args, result, ok, started)
|
||
|
||
|
||
class Handler(BaseHTTPRequestHandler):
|
||
server_version = "ToolGateway/1.0"
|
||
|
||
def _send(self, code, obj):
|
||
raw = json.dumps(obj, ensure_ascii=False).encode()
|
||
self.send_response(code)
|
||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||
self.send_header("Content-Length", str(len(raw)))
|
||
self.end_headers()
|
||
self.wfile.write(raw)
|
||
|
||
def _actor(self):
|
||
tok = self.headers.get("X-Gateway-Token", "")
|
||
return TOKENS.get(tok)
|
||
|
||
def log_message(self, *a):
|
||
pass
|
||
|
||
def do_GET(self):
|
||
if self.path == "/health":
|
||
return self._send(200, {"ok": True, "tools": len(TOOLS)})
|
||
if self.path == "/tools":
|
||
return self._send(200, {"tools": [{"name": k, "scope": v["scope"],
|
||
"confirm": v["confirm"]} for k, v in TOOLS.items()]})
|
||
return self._send(404, {"error": "not found"})
|
||
|
||
def do_POST(self):
|
||
if self.path != "/call":
|
||
return self._send(404, {"error": "not found"})
|
||
actor = self._actor()
|
||
if not actor:
|
||
return self._send(401, {"error": "bad token"})
|
||
try:
|
||
n = int(self.headers.get("Content-Length", 0))
|
||
req = json.loads(self.rfile.read(n).decode() or "{}")
|
||
except Exception:
|
||
return self._send(400, {"error": "bad json"})
|
||
tool = req.get("tool")
|
||
args = req.get("args") or {}
|
||
now = time.time()
|
||
with RATE_LOCK:
|
||
q = RATE.setdefault(actor, [])
|
||
RATE[actor] = [t for t in q if now - t < 60]
|
||
if len(RATE[actor]) >= 60:
|
||
return self._send(429, {"error": "rate_limit", "actor": actor,
|
||
"limit": "60/min"})
|
||
RATE[actor].append(now)
|
||
spec = TOOLS.get(tool)
|
||
if not spec:
|
||
return self._send(404, {"error": "unknown tool"})
|
||
allowed = spec.get("actors", ["owner", "family", "agent"])
|
||
if actor not in allowed:
|
||
return self._send(403, {"error": "forbidden for actor", "actor": actor,
|
||
"allowed": allowed})
|
||
required = {
|
||
"ha.call": ["domain", "service"],
|
||
"calendar.create": ["title", "start"],
|
||
"hub.notify": ["message"],
|
||
"ha.search": ["query"],
|
||
"media.search": ["query"],
|
||
"media.request": ["query"],
|
||
"hub.service_detail": ["name"],
|
||
"books.search": ["query"],
|
||
"books.link": ["query"],
|
||
"docs.search": ["query"],
|
||
}.get(tool, [])
|
||
missing = [k for k in required if not args.get(k)]
|
||
if missing:
|
||
return self._send(400, {"error": "missing_args", "missing": missing,
|
||
"tool": tool, "required": required})
|
||
if spec["confirm"] and not req.get("confirm"):
|
||
return self._send(409, {"error": "confirmation_required", "tool": tool,
|
||
"hint": "повторите с confirm=true"})
|
||
started = time.time()
|
||
try:
|
||
result = spec["fn"](args)
|
||
audit(actor, tool, args, result, True, started)
|
||
return self._send(200, {"ok": True, "result": result})
|
||
except Exception as e:
|
||
err = str(e)[:200]
|
||
audit(actor, tool, args, {"error": err}, False, started)
|
||
return self._send(500, {"ok": False, "error": err})
|
||
|
||
|
||
def main():
|
||
port = int(CFG_D.get("port", 9140))
|
||
srv = ThreadingHTTPServer(("0.0.0.0", port), Handler)
|
||
print("tool-gateway on :%d, tools=%d" % (port, len(TOOLS)), flush=True)
|
||
srv.serve_forever()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|