from __future__ import annotations import asyncio import json import os import pty import fcntl import termios import struct import signal import re import secrets import socket import subprocess import time import ipaddress import logging import hmac from datetime import datetime, timezone from zoneinfo import available_timezones from pathlib import Path from typing import Any import httpx from fastapi import FastAPI, File, Form, HTTPException, Request, UploadFile, WebSocket, WebSocketDisconnect from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse, RedirectResponse from io import BytesIO from docx import Document from fastapi.staticfiles import StaticFiles from starlette.middleware.sessions import SessionMiddleware import pam from fastapi.templating import Jinja2Templates BASE_DIR = Path(__file__).resolve().parent SERVICES_FILE = BASE_DIR / "services.json" SPEACHES_URL = "http://192.168.1.26:8000" WHISPER_MODEL = "Systran/faster-whisper-small" MAX_UPLOAD_BYTES = 500 * 1024 * 1024 ALLOWED_EXTENSIONS = {".wav", ".mp3", ".m4a", ".mp4", ".mpeg", ".mpga", ".webm", ".ogg", ".oga", ".flac"} app = FastAPI(title="AI Station Portal", version="0.8.2") app.add_middleware( SessionMiddleware, secret_key=os.getenv("AI_STATION_SESSION_SECRET") or secrets.token_urlsafe(48), session_cookie="ai_station_admin", max_age=600, same_site="strict", https_only=os.getenv("AI_STATION_COOKIE_SECURE", "0") == "1", ) ADMIN_USER = os.getenv("AI_STATION_ADMIN_USER", "theroot") ADMIN_IDLE_SECONDS = 600 ADMIN_HELPER = "/opt/ai-station-portal/ai-station-portal-admin" app.mount("/static", StaticFiles(directory=BASE_DIR / "static"), name="static") templates = Jinja2Templates(directory=BASE_DIR / "templates") def load_services(station_host: str | None = None) -> list[dict[str, Any]]: try: data = json.loads(SERVICES_FILE.read_text(encoding="utf-8")) host = station_host or "127.0.0.1" for item in data: for key in ("url", "health_url"): value = item.get(key) if isinstance(value, str): item[key] = value.replace("{station_host}", host) return [item for item in data if item.get("enabled", True)] except (OSError, json.JSONDecodeError): return [] async def check_service(client: httpx.AsyncClient, service: dict[str, Any]) -> dict[str, Any]: item = dict(service) if item.get("internal"): item["status"] = "local" item["status_label"] = "В портале" return item health_url = item.get("health_url") or item.get("url") if not health_url or health_url == "#": item["status"] = "unknown" item["status_label"] = "Не настроен" return item try: response = await client.get(health_url, follow_redirects=True) if response.status_code < 500: item["status"] = "online" item["status_label"] = "Доступен" else: item["status"] = "offline" item["status_label"] = "Ошибка сервиса" except httpx.HTTPError: item["status"] = "offline" item["status_label"] = "Недоступен" return item @app.get("/", response_class=HTMLResponse) async def index(request: Request): services = load_services(request.url.hostname) timeout = httpx.Timeout(2.5, connect=1.5) async with httpx.AsyncClient(timeout=timeout) as client: checked = await asyncio.gather(*(check_service(client, item) for item in services)) online_count = sum(item["status"] in {"online", "local"} for item in checked) return templates.TemplateResponse( request=request, name="index.html", context={"services": checked, "online_count": online_count}, ) @app.get("/transcription", response_class=HTMLResponse) async def transcription_page(request: Request): return templates.TemplateResponse( request=request, name="transcription.html", context={}, ) @app.get("/admin/login", response_class=HTMLResponse) async def admin_login_page(request: Request): if request.session.get("admin_authenticated"): return RedirectResponse("/admin", status_code=303) return templates.TemplateResponse(request=request, name="admin_login.html", context={"error": None}) @app.post("/admin/login", response_class=HTMLResponse) async def admin_login(request: Request, password: str = Form(...)): authenticated = False try: authenticated = pam.pam().authenticate(ADMIN_USER, password, service="login") except Exception: authenticated = False if not authenticated: return templates.TemplateResponse( request=request, name="admin_login.html", context={"error": "Неверный системный пароль или ошибка проверки PAM."}, status_code=401, ) request.session.clear() request.session["admin_authenticated"] = True request.session["admin_user"] = ADMIN_USER request.session["admin_last_seen"] = int(time.time()) return RedirectResponse("/admin", status_code=303) def admin_session_valid(request: Request) -> bool: last_seen = request.session.get("admin_last_seen", 0) if not request.session.get("admin_authenticated") or time.time() - last_seen > ADMIN_IDLE_SECONDS: request.session.clear() return False request.session["admin_last_seen"] = int(time.time()) return True def run_helper(*args: str) -> tuple[bool, str]: try: result = subprocess.run( ["sudo", "-n", ADMIN_HELPER, *args], capture_output=True, text=True, timeout=30 if args and args[0] in {"network-apply", "network-confirm", "network-cancel"} else 15, check=False, ) except (OSError, subprocess.TimeoutExpired) as exc: return False, str(exc) output = "\n".join(part.strip() for part in (result.stdout, result.stderr) if part and part.strip()) return result.returncode == 0, output def run_helper_input(input_text: str, *args: str) -> tuple[bool, str]: try: result = subprocess.run( ["sudo", "-n", ADMIN_HELPER, *args], input=input_text, capture_output=True, text=True, timeout=15, check=False, ) except subprocess.TimeoutExpired: return False, "helper timeout" except OSError: return False, "helper execution error" output = "\\n".join( part.strip() for part in (result.stdout, result.stderr) if part and part.strip() ) return result.returncode == 0, output def timedatectl_value(property_name: str) -> str | None: """Read the live system value from systemd-timedated, not cached config files.""" try: result = subprocess.run( ["timedatectl", "show", f"-p{property_name}", "--value"], capture_output=True, text=True, timeout=5, check=False, ) if result.returncode == 0: return result.stdout.strip() except (OSError, subprocess.TimeoutExpired): pass return None def get_system_settings() -> dict[str, str]: timezone_name = timedatectl_value("Timezone") if not timezone_name: # Fallback to the active localtime symlink; /etc/timezone can be stale. try: localtime = Path("/etc/localtime").resolve() marker = "/zoneinfo/" if marker in str(localtime): timezone_name = str(localtime).split(marker, 1)[1] except OSError: pass if not timezone_name: timezone_name = "Unknown" ntp_value = timedatectl_value("NTP") ntp_enabled = "yes" if ntp_value == "yes" else "no" if ntp_value == "no" else "unknown" now = datetime.now().astimezone() return { "hostname": socket.gethostname(), "timezone": timezone_name, "ntp": ntp_enabled, "local_time": now.strftime("%Y-%m-%d %H:%M:%S %Z"), "utc_time": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC"), } def read_network_settings() -> dict[str, Any]: """Read privileged Netplan configuration through the restricted root helper.""" ok, output = run_helper("network-read", "lan0") if not ok: return { "interface": "lan0", "address": "", "gateway": "", "dns1": "", "dns2": "", "search_domain": "", "dhcp": False, "mac": "", "read_error": output or "Не удалось прочитать сетевую конфигурацию", } try: data = json.loads(output) data["read_error"] = "" return data except (json.JSONDecodeError, TypeError): return { "interface": "lan0", "address": "", "gateway": "", "dns1": "", "dns2": "", "search_domain": "", "dhcp": False, "mac": "", "read_error": "Некорректный ответ системного helper", } def validate_network_form(mode: str, address: str, gateway: str, dns1: str, dns2: str, search_domain: str) -> dict[str, str]: if mode not in {"dhcp", "static"}: raise ValueError("invalid mode") result = {"mode": mode} if mode == "static": interface = ipaddress.ip_interface(address.strip()) gw = ipaddress.ip_address(gateway.strip()) if interface.version != 4 or gw.version != 4 or gw not in interface.network: raise ValueError("invalid address/gateway") result.update({"address": str(interface), "gateway": str(gw)}) for key, value in (("dns1", dns1), ("dns2", dns2)): value = value.strip() if value: ip = ipaddress.ip_address(value) if ip.version != 4: raise ValueError("DNS must be IPv4") result[key] = str(ip) domain = search_domain.strip() if domain: if len(domain) > 253 or not re.fullmatch(r"(?i)[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?", domain): raise ValueError("invalid search domain") result["search_domain"] = domain return result @app.get("/admin", response_class=HTMLResponse) async def admin_page(request: Request): if not admin_session_valid(request): return RedirectResponse("/admin/login", status_code=303) network_state = {"pending": False, "remaining_seconds": 0, "try_active": False, "timer_active": False, "rollback_failed": False} ok, status_output = run_helper("network-status", "status") if ok: try: network_state = json.loads(status_output) except json.JSONDecodeError: pass csrf_token = request.session.get("password_csrf") if not csrf_token: csrf_token = secrets.token_urlsafe(32) request.session["password_csrf"] = csrf_token network = read_network_settings() network_url = "" if network.get("address"): try: current_ip = str(ipaddress.ip_interface(network["address"]).ip) port = request.url.port host = f"{current_ip}:{port}" if port else current_ip network_url = f"{request.url.scheme}://{host}/admin" except ValueError: pass return templates.TemplateResponse( request=request, name="admin.html", context={ "admin_user": ADMIN_USER, "settings": get_system_settings(), "timezones": sorted(available_timezones()), "network": network, "network_url": network_url, "network_state": network_state, "password_csrf": csrf_token, }, ) @app.post("/admin/settings/password") async def update_admin_password( request: Request, current_password: str = Form(...), new_password: str = Form(...), confirm_password: str = Form(...), csrf_token: str = Form(...), ): if not admin_session_valid(request): return RedirectResponse("/admin/login", status_code=303) session_token = request.session.get("password_csrf", "") if not session_token or not hmac.compare_digest(csrf_token, session_token): return RedirectResponse("/admin?error=password-csrf", status_code=303) if ADMIN_USER != "theroot": return RedirectResponse("/admin?error=password-helper", status_code=303) authenticated = False try: authenticated = pam.pam().authenticate( ADMIN_USER, current_password, service="login" ) except Exception: authenticated = False if not authenticated: return RedirectResponse("/admin?error=password-current", status_code=303) if new_password != confirm_password: return RedirectResponse("/admin?error=password-mismatch", status_code=303) if ( len(new_password) < 8 or len(new_password) > 256 or any(ord(char) < 32 or ord(char) == 127 for char in new_password) or ":" in new_password ): return RedirectResponse("/admin?error=password-policy", status_code=303) ok, _ = run_helper_input( new_password + "\n", "password-change", ADMIN_USER, ) if not ok: return RedirectResponse("/admin?error=password-helper", status_code=303) request.session.clear() return RedirectResponse("/admin/login?result=password-changed", status_code=303) @app.post("/admin/system/reboot") async def admin_reboot(request: Request, csrf_token: str = Form(...)): if not admin_session_valid(request): return RedirectResponse("/admin/login", status_code=303) session_token = request.session.get("password_csrf", "") if not session_token or not hmac.compare_digest(csrf_token, session_token): return RedirectResponse("/admin?error=system-csrf", status_code=303) ok, _ = run_helper("system-power", "reboot") if not ok: return RedirectResponse("/admin?error=system-power", status_code=303) return RedirectResponse("/admin", status_code=303) @app.post("/admin/system/poweroff") async def admin_poweroff(request: Request, csrf_token: str = Form(...)): if not admin_session_valid(request): return RedirectResponse("/admin/login", status_code=303) session_token = request.session.get("password_csrf", "") if not session_token or not hmac.compare_digest(csrf_token, session_token): return RedirectResponse("/admin?error=system-csrf", status_code=303) ok, _ = run_helper("system-power", "poweroff") if not ok: return RedirectResponse("/admin?error=system-power", status_code=303) return RedirectResponse("/admin", status_code=303) @app.post("/admin/settings/network") async def update_network( request: Request, mode: str = Form(...), address: str = Form(""), gateway: str = Form(""), dns1: str = Form(""), dns2: str = Form(""), search_domain: str = Form(""), ): if not admin_session_valid(request): return RedirectResponse("/admin/login", status_code=303) try: config = validate_network_form(mode, address, gateway, dns1, dns2, search_domain) except ValueError: return RedirectResponse("/admin?error=invalid-network", status_code=303) import base64 payload = base64.urlsafe_b64encode(json.dumps(config).encode()).decode() ok, output = run_helper("network-apply", payload) if not ok: logging.getLogger("ai_station_portal").error( "network-apply helper failed: %s", output or "no diagnostic output" ) return RedirectResponse("/admin?error=network-apply", status_code=303) # After a static IP change, send the browser directly to the candidate address. if config.get("mode") == "static": target_ip = str(ipaddress.ip_interface(config["address"]).ip) port = request.url.port host = f"{target_ip}:{port}" if port else target_ip target_url = f"{request.url.scheme}://{host}/admin?result=network-pending" return RedirectResponse(target_url, status_code=303) return RedirectResponse("/admin?result=network-pending", status_code=303) @app.get("/admin/settings/network/status") async def network_status(request: Request): if not admin_session_valid(request): raise HTTPException(status_code=401, detail="Admin authentication required") ok, output = run_helper("network-status", "status") if not ok: raise HTTPException(status_code=503, detail=output or "Не удалось получить состояние таймера") try: return JSONResponse(json.loads(output)) except json.JSONDecodeError: raise HTTPException(status_code=502, detail="Некорректный ответ системного helper") @app.post("/admin/settings/network/confirm") async def confirm_network(request: Request): if not admin_session_valid(request): return RedirectResponse("/admin/login", status_code=303) ok, _ = run_helper("network-confirm", "confirm") return RedirectResponse("/admin?result=network-confirmed" if ok else "/admin?error=network-confirm", status_code=303) @app.post("/admin/settings/hostname") async def update_hostname(request: Request, hostname: str = Form(...)): if not admin_session_valid(request): return RedirectResponse("/admin/login", status_code=303) hostname = hostname.strip().lower() if len(hostname) > 63 or not re.fullmatch(r"[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?", hostname): return RedirectResponse("/admin?error=invalid-hostname", status_code=303) ok, _ = run_helper("hostname", hostname) return RedirectResponse("/admin?result=hostname-ok" if ok else "/admin?error=helper", status_code=303) @app.post("/admin/settings/timezone") async def update_timezone(request: Request, timezone_name: str = Form(...)): if not admin_session_valid(request): return RedirectResponse("/admin/login", status_code=303) if timezone_name not in available_timezones(): return RedirectResponse("/admin?error=invalid-timezone", status_code=303) ok, _ = run_helper("timezone", timezone_name) actual = timedatectl_value("Timezone") if ok else None if not ok: return RedirectResponse("/admin?error=helper", status_code=303) if actual != timezone_name: return RedirectResponse("/admin?error=verify-timezone", status_code=303) return RedirectResponse("/admin?result=timezone-ok", status_code=303) @app.post("/admin/settings/ntp") async def update_ntp(request: Request, enabled: str = Form(...)): if not admin_session_valid(request): return RedirectResponse("/admin/login", status_code=303) if enabled not in {"yes", "no"}: return RedirectResponse("/admin?error=invalid-ntp", status_code=303) ok, _ = run_helper("ntp", enabled) actual = timedatectl_value("NTP") if ok else None if not ok: return RedirectResponse("/admin?error=helper", status_code=303) if actual != enabled: return RedirectResponse("/admin?error=verify-ntp", status_code=303) return RedirectResponse("/admin?result=ntp-ok", status_code=303) @app.get("/admin/terminal", response_class=HTMLResponse) async def admin_terminal_page(request: Request): if not admin_session_valid(request): return RedirectResponse("/admin/login", status_code=303) return templates.TemplateResponse( request=request, name="terminal.html", context={"admin_user": ADMIN_USER}, ) @app.websocket("/admin/terminal/ws") async def admin_terminal_ws(websocket: WebSocket): # Require the same-origin browser session used by the admin panel. session = websocket.session last_seen = session.get("admin_last_seen", 0) if ( not session.get("admin_authenticated") or time.time() - last_seen > ADMIN_IDLE_SECONDS or session.get("admin_user") != ADMIN_USER ): await websocket.close(code=4401, reason="Admin authentication required") return origin = websocket.headers.get("origin", "") host = websocket.headers.get("host", "") if not origin or not host or origin.split("://", 1)[-1].rstrip("/").lower() != host.lower(): await websocket.close(code=4403, reason="Invalid origin") return await websocket.accept() master_fd = None child = None try: master_fd, slave_fd = pty.openpty() # The shell runs as the portal service account (normally theroot), never as root. env = os.environ.copy() env.update({"TERM": "xterm-256color", "COLORTERM": "truecolor"}) child = subprocess.Popen( ["/bin/bash", "-l"], stdin=slave_fd, stdout=slave_fd, stderr=slave_fd, cwd=os.path.expanduser("~"), env=env, close_fds=True, start_new_session=True, ) os.close(slave_fd) os.set_blocking(master_fd, False) async def read_pty(): while child and child.poll() is None: try: data = await asyncio.to_thread(os.read, master_fd, 4096) except BlockingIOError: await asyncio.sleep(0.02) continue except OSError: break if not data: break await websocket.send_text(data.decode("utf-8", errors="replace")) reader = asyncio.create_task(read_pty()) while child.poll() is None: try: message = await asyncio.wait_for(websocket.receive_json(), timeout=1.0) except asyncio.TimeoutError: continue kind = message.get("type") if kind == "input": value = str(message.get("data", "")) if len(value) > 8192: continue os.write(master_fd, value.encode("utf-8", errors="ignore")) elif kind == "resize": cols = max(20, min(300, int(message.get("cols", 100)))) rows = max(5, min(100, int(message.get("rows", 30)))) fcntl.ioctl(master_fd, termios.TIOCSWINSZ, struct.pack("HHHH", rows, cols, 0, 0)) os.killpg(child.pid, signal.SIGWINCH) reader.cancel() await asyncio.gather(reader, return_exceptions=True) except (WebSocketDisconnect, OSError, ValueError, TypeError): pass finally: if child is not None and child.poll() is None: try: os.killpg(child.pid, signal.SIGHUP) child.wait(timeout=2) except Exception: try: os.killpg(child.pid, signal.SIGKILL) except ProcessLookupError: pass if master_fd is not None: try: os.close(master_fd) except OSError: pass try: await websocket.close() except Exception: pass @app.post("/admin/logout") async def admin_logout(request: Request): request.session.clear() return RedirectResponse("/", status_code=303) @app.post("/api/transcribe") async def transcribe( request: Request, file: UploadFile = File(...), language: str = Form("auto"), ): filename = file.filename or "audio" suffix = Path(filename).suffix.lower() if suffix not in ALLOWED_EXTENSIONS: raise HTTPException(status_code=400, detail="Неподдерживаемый формат аудио") content = await file.read(MAX_UPLOAD_BYTES + 1) if not content: raise HTTPException(status_code=400, detail="Файл пуст") if len(content) > MAX_UPLOAD_BYTES: raise HTTPException(status_code=413, detail="Максимальный размер файла — 500 МБ") data = {"model": WHISPER_MODEL, "response_format": "verbose_json"} if language and language != "auto": data["language"] = language try: async with httpx.AsyncClient(timeout=httpx.Timeout(3600.0, connect=15.0)) as client: response = await client.post( f"http://{request.url.hostname}:8000/v1/audio/transcriptions", data=data, files={"file": (filename, content, file.content_type or "application/octet-stream")}, ) response.raise_for_status() except httpx.HTTPStatusError as exc: detail = exc.response.text[:1200] or f"Speaches вернул HTTP {exc.response.status_code}" raise HTTPException(status_code=502, detail=f"Ошибка Speaches: {detail}") from exc except httpx.HTTPError as exc: raise HTTPException(status_code=502, detail=f"Не удалось связаться со Speaches: {exc}") from exc try: result = response.json() except ValueError as exc: raise HTTPException(status_code=502, detail="Speaches вернул некорректный ответ") from exc return JSONResponse({ "text": result.get("text", ""), "language": result.get("language"), "duration": result.get("duration"), "segments": result.get("segments", []), }) @app.post("/api/export/docx") async def export_docx(request: Request): payload = await request.json() text = str(payload.get("text", "")) if not text.strip(): raise HTTPException(status_code=400, detail="Нет текста для экспорта") document = Document() document.add_heading("Расшифровка аудио", level=1) for paragraph in text.splitlines(): document.add_paragraph(paragraph) output = BytesIO() document.save(output) output.seek(0) headers = {"Content-Disposition": 'attachment; filename="transcript.docx"'} return StreamingResponse( output, media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document", headers=headers, ) @app.get("/health") async def health(): return {"status": "ok"}