Files

754 lines
37 KiB
Python

"""FastAPI transport and administrator boundary for the headless workspace."""
from __future__ import annotations
from collections import OrderedDict
from contextlib import asynccontextmanager
from dataclasses import replace
from html import escape
import hashlib
import inspect
import json
import math
from pathlib import Path as FilePath
import re
import secrets
import threading
import time
from typing import Annotated, Any
from urllib.parse import urlsplit
from fastapi import FastAPI, HTTPException, Path, Query, Request
from fastapi.exceptions import RequestValidationError
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr
from starlette._utils import get_route_path
from starlette.concurrency import run_in_threadpool
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse, Response
from starlette.staticfiles import StaticFiles
from . import GAME_VERSION, __version__
from .config import COOKIE_NAME, WebConfig, is_loopback, normalize_host, normalize_origin, verify_password
PAGES = tuple("login incubator bag ranch daily hatching mainline battles gifts commissions exploration maps statistics plans yields".split())
ACTIONS = frozenset("refresh refresh_maps refresh_tasks claim_daily lock unlock sell feed quote_expansion expand export_config import_config import_yields reset_map_pending login enter_server restore_session logout forget_login start stop".split())
Identifier = Annotated[str, Path(pattern=r"^[A-Za-z0-9_-]{1,80}$")]
_PUBLIC_PATHS = frozenset({"/api/health", "/api/meta", "/api/auth/status", "/api/auth/login", "/api/auth/logout"})
_PUBLIC_ASSETS = frozenset({"login.html", "login.js", "login.css", "styles.css", "dom.js"})
_WRITES = frozenset({"POST", "PUT", "PATCH", "DELETE"})
_JOB_STATUSES = frozenset({"queued", "running", "succeeded", "failed", "cancelled"})
_PRIVATE_KEYS = frozenset({"key", "reqid", "reqsid", "requestid", "password", "passwordhash", "passwd", "pwd", "userpwd", "newpass", "secret", "credentials", "protected", "authorization", "cookie", "setcookie", "raw", "snapshot", "rawsnapshot", "profileroot", "stateroot", "dataroot", "datadir", "filepath", "budgetpath", "private", "headers", "body", "request", "response"})
_METADATA_CONTEXTS = frozenset({"columns", "fields", "filters", "form", "pages", "options", "tabs"})
_FILE_KEYS = frozenset({"path", "filepath", "fileroot", "root", "profileroot", "stateroot", "datadir", "budgetpath"})
_YIELDS_IMPORT_PATH = re.compile(r"/api/accounts/[A-Za-z0-9_-]{1,80}/actions/import_yields")
_YIELDS_IMPORT_BODY_BYTES = 12 * 1024 * 1024
def _error(status: int, code: str, message: str) -> JSONResponse:
return JSONResponse({"error": {"code": code, "message": message}, "detail": message}, status_code=status)
class _Redactor:
def __init__(self, settings: WebConfig):
self.lock = threading.Lock()
self.secrets: set[str] = set()
self.paths = {str(settings.data_dir), settings.data_dir.as_posix()}
def remember(self, value: Any) -> None:
if isinstance(value, dict):
for key, item in value.items():
name = str(key).lower().replace("_", "").replace("-", "")
if name in _PRIVATE_KEYS or "token" in name or "password" in name or name.endswith(("key", "secret")):
if isinstance(item, str) and item:
with self.lock:
if len(self.secrets) < 4096:
self.secrets.add(item)
elif isinstance(item, (list, dict)):
self.remember(item)
elif isinstance(value, list):
for item in value:
self.remember(item)
def text(self, value: str) -> str:
with self.lock:
known = sorted(self.secrets, key=len, reverse=True)
for secret in known:
value = value.replace(secret, "<隐藏>")
for path in sorted(self.paths, key=len, reverse=True):
value = value.replace(path, "<本地目录>")
value = re.sub(
r'''(?i)(["']?(?:password|passwd|pwd|[\w-]*token|secret|authorization|cookie|reqsid|reqid|key)["']?\s*[:=]\s*)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,;&}\r\n]+)''',
lambda m: m[1] + "<隐藏>", value,
)
value = re.sub(r"(?i)\b(?:Bearer|Basic)\s+[A-Za-z0-9+/=_\-.]+", "<隐藏>", value)
value = re.sub(r"[A-Za-z]:[\\/][^\s\"'<>]*", "<本地路径>", value)
value = re.sub(r"(?<![\w:/])/[^/\s\"'<>][^\s\"'<>]*", "<本地路径>", value)
value = re.sub(r"\\\\[^\s\"'<>]+", "<本地路径>", value)
return value[:32_000]
def public(self, value: Any, *, context: str = "", trace: bool = False, depth: int = 0) -> Any:
if depth > 32:
return None
if value is None or type(value) in (bool, int):
return value
if type(value) is float:
return value if math.isfinite(value) else None
if isinstance(value, str):
return self.text(value)
if isinstance(value, (list, tuple)):
return [self.public(item, context=context, trace=trace, depth=depth + 1) for item in value]
if isinstance(value, dict):
result = {}
for field, item in value.items():
if not isinstance(field, str):
field = str(field)
name = field.lower().replace("_", "").replace("-", "")
if name == "hassavedpassword":
if type(item) is bool:
result[field] = item
continue
metadata_key = name == "key" and context in _METADATA_CONTEXTS and not trace
envelope = trace and name in {"headers", "body", "request", "response"}
private = name in _PRIVATE_KEYS or "token" in name or "password" in name or name.endswith(("key", "secret"))
if private and not (metadata_key or envelope):
if trace:
result[field] = "<隐藏>"
continue
result[field] = self.public(item, context=field, trace=trace, depth=depth + 1)
return result
# Never serialize arbitrary Engine / Session / Snapshot / Path objects.
return None
class _Sessions:
def __init__(self, settings: WebConfig):
self.settings = settings
self.lock = threading.Lock()
self.sessions: OrderedDict[str, float] = OrderedDict()
self.failures: OrderedDict[str, list[tuple[float, object]]] = OrderedDict()
def authenticated(self, request: Request) -> bool:
if not self.settings.credential:
return bool(request.client and is_loopback(request.client.host))
token = request.cookies.get(COOKIE_NAME, "")
if not re.fullmatch(r"[A-Za-z0-9_-]{43}", token):
return False
digest = hashlib.sha256(token.encode()).hexdigest()
with self.lock:
expiry = self.sessions.get(digest)
if expiry is not None and expiry > time.monotonic():
return True
self.sessions.pop(digest, None)
return False
def login(self, request: Request, password: str) -> str:
peer = request.client.host if request.client else "unknown"
now = time.monotonic()
reservation = object()
with self.lock:
failures = [entry for entry in self.failures.get(peer, []) if entry[0] > now - 60]
if len(failures) >= 10:
raise HTTPException(429, "尝试过于频繁,请稍后再试")
# Pending verifications count against the same bounded per-peer budget.
self.failures[peer] = failures + [(now, reservation)]
self.failures.move_to_end(peer)
while len(self.failures) > 1024:
self.failures.popitem(last=False)
# PBKDF work runs outside the session lock, independently for each request.
if not verify_password(password, self.settings.credential):
raise HTTPException(401, "管理密码错误")
token = secrets.token_urlsafe(32)
digest = hashlib.sha256(token.encode()).hexdigest()
now = time.monotonic()
with self.lock:
failures = [entry for entry in self.failures.get(peer, [])
if entry[1] is not reservation and entry[0] > now - 60]
if failures:
self.failures[peer] = failures
else:
self.failures.pop(peer, None)
expired = [key for key, expiry in self.sessions.items() if expiry <= now]
for key in expired:
del self.sessions[key]
while len(self.sessions) >= 256:
self.sessions.popitem(last=False)
self.sessions[digest] = now + self.settings.session_ttl
self.logout(request)
return token
def logout(self, request: Request) -> None:
token = request.cookies.get(COOKIE_NAME, "")
with self.lock:
self.sessions.pop(hashlib.sha256(token.encode()).hexdigest(), None)
class _Boundary:
"""Bounded ASGI body buffering and checks before any API handler runs."""
def __init__(self, app, *, settings: WebConfig, sessions: _Sessions):
self.app, self.settings, self.sessions = app, settings, sessions
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
await self.app(scope, receive, send)
return
base_path = self.settings.base_path
path = scope["path"]
# Keep a canonical external path for Starlette's root_path handling. Both
# the boundary and router must strip exactly the same, single prefix.
preserved = base_path and (path == base_path or path.startswith(base_path + "/"))
scope = {**scope, "root_path": base_path, "app_root_path": base_path}
if base_path and (not preserved or path == "/api/health"):
scope["path"] = base_path + path
if "raw_path" in scope:
scope["raw_path"] = base_path.encode("ascii") + scope["raw_path"]
path = get_route_path(scope)
request = Request(scope)
async def deny(status, code, message):
await _error(status, code, message)(scope, receive, secure_send)
async def secure_send(message):
if message["type"] == "http.response.start":
headers = list(message.get("headers", []))
headers.extend([
(b"x-content-type-options", b"nosniff"),
(b"referrer-policy", b"same-origin"),
(b"x-frame-options", b"DENY"),
(b"content-security-policy", b"default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'"),
])
if path.startswith("/api/"):
headers.append((b"cache-control", b"no-store"))
message = {**message, "headers": headers}
await send(message)
hosts = request.headers.getlist("host")
try:
if len(hosts) != 1 or any(c in hosts[0] for c in "@/\\?# \t\r\n,"):
raise ValueError
parsed = urlsplit("http://" + hosts[0])
host = normalize_host(parsed.hostname or "")
if parsed.port is not None and not 1 <= parsed.port <= 65535:
raise ValueError
if host not in self.settings.trusted_hosts:
raise ValueError
except ValueError:
await deny(400, "invalid_host", "请求主机不受信任")
return
if base_path and path == "":
target = base_path + "/"
if scope.get("query_string"):
target += "?" + scope["query_string"].decode("latin-1")
await RedirectResponse(target, status_code=307, headers={"Cache-Control": "no-store"})(scope, receive, secure_send)
return
is_api = path == "/api" or path.startswith("/api/")
if is_api and request.method in _WRITES:
origins = request.headers.getlist("origin")
fetch_site = request.headers.get("sec-fetch-site", "")
try:
if fetch_site == "cross-site" or len(origins) > 1:
raise ValueError
if origins:
origin = normalize_origin(origins[0])
same_origin = normalize_origin(f"{scope['scheme']}://{hosts[0]}")
if origin not in {same_origin, *self.settings.allowed_origins}:
raise ValueError
elif fetch_site not in {"", "none", "same-origin"}:
raise ValueError
except ValueError:
await deny(403, "invalid_origin", "禁止跨站操作,请从当前工作台发起请求")
return
if is_api and path not in _PUBLIC_PATHS and not self.sessions.authenticated(request):
status = 401 if self.settings.credential else 403
await deny(status, "authentication_required", "请先登录管理工作台" if status == 401 else "本机免密模式只允许本机访问")
return
if not is_api:
await self.app(scope, receive, secure_send)
return
if len(scope.get("query_string", b"")) > 16_384:
await deny(414, "query_too_large", "查询条件过长")
return
body_limit = self.settings.max_body_bytes
if request.method == "POST" and _YIELDS_IMPORT_PATH.fullmatch(path):
# An 8 MiB file expands to about 10.7 MiB in base64, plus JSON metadata.
body_limit = _YIELDS_IMPORT_BODY_BYTES
lengths = request.headers.getlist("content-length")
try:
if len(lengths) > 1 or (lengths and (not lengths[0].isascii() or not lengths[0].isdecimal())):
raise ValueError
declared = int(lengths[0]) if lengths else None
except ValueError:
await deny(400, "invalid_length", "请求正文长度无效")
return
if declared is not None and declared > body_limit:
await deny(413, "body_too_large", "请求正文超过允许大小")
return
if request.headers.get("content-encoding", "identity").lower() != "identity":
await deny(415, "unsupported_encoding", "请求正文不支持压缩编码")
return
chunks, size = [], 0
while True:
part = await receive()
if part["type"] == "http.disconnect":
return
chunk = part.get("body", b"")
size += len(chunk)
if size > body_limit:
await deny(413, "body_too_large", "请求正文超过允许大小")
return
chunks.append(chunk)
if not part.get("more_body", False):
break
if declared is not None and size != declared:
await deny(400, "invalid_length", "请求正文长度与声明不符")
return
content_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
if size and request.method in _WRITES and content_type != "application/json":
await deny(415, "unsupported_media_type", "请使用 application/json 提交请求")
return
buffered = b"".join(chunks)
delivered = False
async def replay():
nonlocal delivered
if not delivered:
delivered = True
return {"type": "http.request", "body": buffered, "more_body": False}
return await receive()
await self.app(scope, replay, secure_send)
class _Input(BaseModel):
model_config = ConfigDict(extra="forbid")
class AccountInput(_Input):
label: Annotated[StrictStr, Field(max_length=200)] = ""
demo: StrictBool = True
class ConfigInput(_Input):
config: dict[str, Any]
revision: Annotated[StrictInt, Field(ge=0)] | None = None
class LoginInput(_Input):
password: Annotated[StrictStr, Field(min_length=1, max_length=1024)]
class UpdateInput(_Input):
version: Annotated[StrictStr, Field(max_length=64)] | None = None
def _no_file_paths(value: Any, depth: int = 0) -> None:
if depth > 32:
raise HTTPException(400, "请求内容嵌套过深")
if isinstance(value, dict):
for field, item in value.items():
name = str(field).lower().replace("_", "").replace("-", "")
if name in _FILE_KEYS:
raise HTTPException(400, "不允许通过 API 指定服务器文件路径")
if name == "filename" and (not isinstance(item, str) or re.search(r"[\\/:\x00]", item) or item.startswith(".")):
raise HTTPException(400, "导入文件名必须是不含路径的名称")
_no_file_paths(item, depth + 1)
elif isinstance(value, list):
for item in value:
_no_file_paths(item, depth + 1)
def _page_response(path: FilePath, settings: WebConfig) -> HTMLResponse:
if not path.is_file():
raise HTTPException(503, "前端资源尚未准备完成")
content = path.read_text(encoding="utf-8")
base_path = escape(settings.base_path, quote=True)
metadata = f'<meta name="ranch-web-base-path" content="{base_path}">'
content, replaced = re.subn(
r'''<meta\b(?=[^>]*\bname\s*=\s*["']ranch-web-base-path["'])[^>]*>''',
lambda match: metadata, content, flags=re.IGNORECASE,
)
if not replaced:
content, inserted = re.subn(r"<head\b[^>]*>", lambda match: match[0] + "\n " + metadata,
content, count=1, flags=re.IGNORECASE)
if not inserted:
content = metadata + "\n" + content
if base_path:
def prefix_attribute(match):
value = match[3]
if value != base_path and not value.startswith(base_path + "/"):
value = base_path + value
return match[1] + match[2] + value + match[2]
content = re.sub(r'''(\b(?:src|href|action)\s*=\s*)(["'])(/(?!/)[^"']*)\2''',
prefix_attribute, content, flags=re.IGNORECASE)
return HTMLResponse(content, headers={"Cache-Control": "no-store"})
class _Assets(StaticFiles):
def __init__(self, *, sessions: _Sessions, **kwargs):
super().__init__(**kwargs)
self.sessions = sessions
async def get_response(self, path, scope):
allowed = {".html", ".js", ".mjs", ".css", ".svg", ".png", ".jpg", ".jpeg", ".webp", ".ico", ".woff", ".woff2"}
parts = path.replace("\\", "/").split("/")
if any(part.startswith(".") for part in parts) or FilePath(path).suffix.lower() not in allowed:
raise HTTPException(404, "静态资源不存在")
if scope["method"] not in {"GET", "HEAD"}:
raise HTTPException(405)
authenticated = self.sessions.authenticated(Request(scope))
if path == "login.html" and authenticated:
return RedirectResponse(self.sessions.settings.base_path + "/", status_code=303, headers={"Cache-Control": "no-store"})
if path not in _PUBLIC_ASSETS and not authenticated:
return RedirectResponse(self.sessions.settings.base_path + "/login", status_code=303, headers={"Cache-Control": "no-store"})
response = await super().get_response(path, scope)
if path in {"index.html", "login.html"} and isinstance(response, FileResponse):
response = await run_in_threadpool(_page_response, FilePath(response.path), self.sessions.settings)
if path not in _PUBLIC_ASSETS or path == "login.html":
response.headers["Cache-Control"] = "no-store"
return response
def create_app(data_dir=None, manager=None, config=None, updates=None) -> FastAPI:
"""Create an application; injected collaborators retain their ownership."""
if config is None:
settings = WebConfig.from_env(**({"data_dir": data_dir} if data_dir is not None else {}))
elif isinstance(config, WebConfig):
settings = replace(config, data_dir=data_dir) if data_dir is not None else config
elif isinstance(config, dict):
values = dict(config)
if data_dir is not None:
values["data_dir"] = data_dir
settings = WebConfig.from_env(**values)
else:
raise TypeError("config 必须是 WebConfig 或字典")
sessions, redactor = _Sessions(settings), _Redactor(settings)
@asynccontextmanager
async def lifespan(app):
owned = []
try:
if app.state.manager is None:
from .service import WebManager
settings.data_dir.mkdir(parents=True, exist_ok=True)
app.state.manager = await run_in_threadpool(WebManager, settings.data_dir)
owned.append(app.state.manager)
if app.state.updates is None:
from .updates import UpdateService
app.state.updates = await run_in_threadpool(UpdateService, settings.data_dir, __version__)
owned.append(app.state.updates)
yield
finally:
failures = []
try:
for item in reversed(owned):
close = getattr(item, "close", None)
if close:
try:
if inspect.iscoroutinefunction(close):
await close()
else:
await run_in_threadpool(close)
except Exception:
failures.append(True)
finally:
if manager is None:
app.state.manager = None
if updates is None:
app.state.updates = None
with sessions.lock:
sessions.sessions.clear()
sessions.failures.clear()
with redactor.lock:
redactor.secrets.clear()
if failures:
raise RuntimeError("Web 服务关闭未完成,请查看已脱敏日志") from None
app = FastAPI(title="牧羊人之心 Web 工作台", version=__version__, lifespan=lifespan,
docs_url=None, redoc_url=None, openapi_url=None, root_path=settings.base_path)
app.state.manager, app.state.updates, app.state.config = manager, updates, settings
app.add_middleware(_Boundary, settings=settings, sessions=sessions)
@app.exception_handler(RequestValidationError)
async def validation_error(request, exc):
return _error(422, "invalid_request", "请求字段或格式不正确,请检查输入")
@app.exception_handler(StarletteHTTPException)
async def http_error(request, exc):
messages = {404: "请求的资源不存在", 405: "不支持此请求方法"}
message = messages.get(exc.status_code, redactor.text(str(exc.detail)))
return _error(exc.status_code, "request_rejected", message)
@app.exception_handler(Exception)
async def internal_error(request, exc):
return _error(500, "internal_error", "操作未完成,请查看已脱敏日志后重试")
def invoke(target, method, *args, **kwargs):
if target is None:
raise HTTPException(503, "服务尚未启动")
try:
return getattr(target, method)(*args, **kwargs)
except HTTPException:
raise
except KeyError:
raise HTTPException(404, "账号、任务或记录不存在") from None
except NotImplementedError:
raise HTTPException(501, "当前部署尚未支持此操作") from None
except ValueError as exc:
status = 409 if type(exc).__name__ == "RevisionConflict" else 400
text = redactor.text(str(exc))
message = text if re.search(r"[\u3400-\u9fff]", text) else "请求参数无效,请检查后重试"
raise HTTPException(status, message) from None
except RuntimeError as exc:
text = redactor.text(str(exc))
message = text if re.search(r"[\u3400-\u9fff]", text) else "当前状态无法执行此操作"
raise HTTPException(409, message) from None
except Exception:
# Catch at the transport boundary so server access/error logs do not print secrets.
raise HTTPException(500, "操作未完成,请查看已脱敏日志后重试") from None
def public(value, **kwargs):
return redactor.public(value, **kwargs)
def public_error(value):
if not value:
return value
if not isinstance(value, str) or "Traceback" in value or re.search(r"\n\s*File\s+[\"']", value):
return "操作未完成,请查看已脱敏日志后重试"
text = redactor.text(value)
return text if re.search(r"[\u3400-\u9fff]", text) else "操作未完成,请查看已脱敏日志后重试"
def public_updates(value):
from .updates import HOST_STATES, current_version_key, stable_version, valid_id
if not isinstance(value, dict):
raise HTTPException(500, "更新服务返回格式不正确")
fields = ("current_version", "latest_version", "available", "checked_at", "release_url", "channel",
"repository", "status", "message", "error", "can_apply")
result = public({field: value[field] for field in fields if field in value})
states = {"unchecked", "no_release", "up_to_date", "available", "check_failed", "unavailable", *HOST_STATES}
if value.get("status") in states:
result["status"] = value["status"]
for field, validator in (("current_version", current_version_key), ("latest_version", stable_version)):
if field in value:
try:
validator(value[field])
except (ValueError, TypeError):
result[field] = None
else:
result[field] = value[field]
executor = value.get("executor")
result["executor"] = public({field: executor[field] for field in
("configured", "enabled", "auto_apply", "state", "heartbeat_at") if field in executor}) if isinstance(executor, dict) else None
for field, allowed in (("request", ("version", "requested_at", "status")),
("host_status", ("version", "status", "updated_at", "error"))):
record = value.get(field)
result[field] = None
if not isinstance(record, dict) or not valid_id(record.get("request_id")) or record.get("status") not in HOST_STATES:
continue
try:
stable_version(record.get("version"))
except (ValueError, TypeError):
continue
mapped = public({key: record[key] for key in allowed if key in record})
# These validated control-plane fields are public updater metadata.
mapped.update(request_id=record["request_id"], version=record["version"], status=record["status"])
result[field] = mapped
return result
def submit(account_id, operation, payload):
if operation not in ACTIONS:
raise HTTPException(404, "不支持此操作")
_no_file_paths(payload)
redactor.remember(payload)
value = invoke(app.state.manager, "submit", account_id, operation, payload)
return public_job(value)
def public_job(value):
if not isinstance(value, dict) or value.get("status") not in _JOB_STATUSES:
raise HTTPException(500, "后台任务返回格式不正确")
result = {field: value.get(field) for field in ("id", "status", "operation", "result", "error")}
result["error"] = public_error(result["error"])
return public(result)
def public_summary(value):
if not isinstance(value, dict):
raise HTTPException(500, "账号状态返回格式不正确")
result = {field: value.get(field) for field in ("id", "label", "connected", "demo", "running", "busy", "revision", "error",
"connection_state", "connection_message", "last_game_success_at", "next_retry_at",
"strategy_requested", "manual_stop", "strategy_state", "strategy_message", "strategy_retry_at")}
result["error"] = public_error(result["error"])
result["connection_message"] = public_error(result["connection_message"])
result["strategy_message"] = public_error(result["strategy_message"])
auto = value.get("auto_relogin_status")
result["auto_relogin_status"] = ({field: auto.get(field) for field in ("state", "message", "next_attempt_at")}
if isinstance(auto, dict) else None)
if result["auto_relogin_status"] is not None:
result["auto_relogin_status"]["message"] = public_error(auto.get("message"))
player = value.get("player")
result["player"] = {field: player.get(field) for field in ("name", "level", "exp", "next_exp", "money", "ke", "ti")} if isinstance(player, dict) else None
return public(result)
@app.get("/api/health")
def health():
return {"status": "ok", "version": __version__}
@app.get("/api/meta")
def meta():
update_status = invoke(app.state.updates, "status")
result = public({"version": __version__, "gameVersion": GAME_VERSION,
"access": {"mode": settings.access_mode, "password_required": bool(settings.credential)},
"features": [*PAGES, "multi_account", "jobs", "config_autosave", "updates"]})
result["updates"] = public_updates(update_status)
return result
@app.get("/api/auth/status")
def auth_status(request: Request):
return {"required": bool(settings.credential), "authenticated": sessions.authenticated(request), "access_mode": settings.access_mode}
@app.post("/api/auth/login")
def admin_login(request: Request, body: LoginInput):
if not settings.credential:
if not sessions.authenticated(request):
raise HTTPException(403, "本机免密模式只允许本机访问")
response = JSONResponse({"required": False, "authenticated": True, "access_mode": "local"})
else:
token = sessions.login(request, body.password)
response = JSONResponse({"required": True, "authenticated": True, "access_mode": "password"})
response.set_cookie(COOKIE_NAME, token, max_age=settings.session_ttl, httponly=True,
secure=settings.secure_cookie, samesite="strict", path=settings.base_path or "/")
# Clear legacy paths without expiring the newly issued session cookie.
for path in dict.fromkeys(("/", "/api", settings.base_path + "/api")):
if path != (settings.base_path or "/"):
response.delete_cookie(COOKIE_NAME, path=path, httponly=True, secure=settings.secure_cookie, samesite="strict")
return response
@app.post("/api/auth/logout")
def admin_logout(request: Request):
sessions.logout(request)
response = JSONResponse({"authenticated": False})
for path in dict.fromkeys((settings.base_path or "/", "/", "/api", settings.base_path + "/api")):
response.delete_cookie(COOKIE_NAME, path=path, httponly=True, secure=settings.secure_cookie, samesite="strict")
return response
@app.get("/api/schema")
def get_schema():
from .views import schema
catalog = getattr(app.state.manager, "catalog", None)
if catalog is None:
from ranch_assistant.model import Catalog
catalog = Catalog()
return public(schema(catalog))
@app.get("/api/accounts")
def list_accounts():
return [public_summary(item) for item in invoke(app.state.manager, "list_accounts")]
@app.post("/api/accounts", status_code=201)
def create_account(body: AccountInput):
return public_summary(invoke(app.state.manager, "create_account", label=body.label, demo=body.demo))
@app.delete("/api/accounts/{account_id}", status_code=204)
def remove_account(account_id: Identifier):
invoke(app.state.manager, "remove_account", account_id)
return Response(status_code=204)
@app.get("/api/accounts/{account_id}/status")
def status(account_id: Identifier):
return public_summary(invoke(app.state.manager, "status", account_id))
@app.get("/api/accounts/{account_id}/config")
def get_config(account_id: Identifier):
return public(invoke(app.state.manager, "get_config", account_id))
@app.put("/api/accounts/{account_id}/config")
def set_config(account_id: Identifier, body: ConfigInput, response: Response):
_no_file_paths(body.config)
result = invoke(app.state.manager, "set_config", account_id, body.config, revision=body.revision)
if isinstance(result, dict) and result.get("pending"):
response.status_code = 202
return public(result)
@app.get("/api/accounts/{account_id}/views/{page}")
def view(account_id: Identifier, page: str, request: Request):
if page not in PAGES:
raise HTTPException(404, "页面不存在")
params = dict(request.query_params)
if "query" in params:
if len(params) > 1:
raise HTTPException(400, "JSON 查询条件不能与简单参数混用")
try:
query = json.loads(params["query"])
except (ValueError, RecursionError):
raise HTTPException(400, "页面查询条件不是有效 JSON") from None
if not isinstance(query, dict):
raise HTTPException(400, "页面查询条件必须是对象")
else:
query = params or None
_no_file_paths(query)
return public(invoke(app.state.manager, "view", account_id, page, query=query))
@app.post("/api/accounts/{account_id}/actions/{operation}", status_code=202)
def action(account_id: Identifier, operation: str, payload: dict[str, Any] | None = None):
return submit(account_id, operation, payload or {})
@app.get("/api/accounts/{account_id}/jobs/{job_id}")
def job(account_id: Identifier, job_id: Identifier):
return public_job(invoke(app.state.manager, "job", account_id, job_id))
@app.get("/api/accounts/{account_id}/logs")
def logs(account_id: Identifier, after: Annotated[int, Query(ge=0)] = 0, debug: bool = False):
return public(invoke(app.state.manager, "logs", account_id, after=after, debug=debug))
@app.get("/api/accounts/{account_id}/logs/{entry_id}")
@app.get("/api/accounts/{account_id}/debug/{entry_id}")
def log_detail(account_id: Identifier, entry_id: Annotated[int, Path(ge=1)]):
method = "log_detail" if hasattr(app.state.manager, "log_detail") else "debug_entry"
if not hasattr(app.state.manager, method):
raise HTTPException(501, "当前运行时尚未提供单条调试详情")
return public(invoke(app.state.manager, method, account_id, entry_id), trace=True)
@app.get("/api/accounts/{account_id}/config/export", status_code=202)
def config_export(account_id: Identifier):
return submit(account_id, "export_config", {})
@app.post("/api/accounts/{account_id}/config/import", status_code=202)
def config_import(account_id: Identifier, payload: dict[str, Any]):
# The REST upload accepts a portable document; the action layer uses {config: document}.
wrapped = payload if "config" in payload else {"config": payload}
return submit(account_id, "import_config", wrapped)
@app.get("/api/system/updates")
def update_status():
return public_updates(invoke(app.state.updates, "status"))
@app.post("/api/system/updates/check")
def update_check():
return public_updates(invoke(app.state.updates, "check"))
@app.post("/api/system/updates/apply", status_code=202)
def update_apply(body: UpdateInput | None = None):
version = body.version if body else None
if version is not None and not re.fullmatch(r"v2\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)", version):
raise HTTPException(400, "更新版本必须是正式的 v2.x.y 版本号,例如 v2.0.1")
return public_updates(invoke(app.state.updates, "request_update", version))
static_dir = FilePath(__file__).resolve().parent / "static"
@app.get("/", include_in_schema=False)
def index(request: Request):
if not sessions.authenticated(request):
return RedirectResponse(settings.base_path + "/login", status_code=303, headers={"Cache-Control": "no-store"})
return _page_response(static_dir / "index.html", settings)
@app.get("/login", include_in_schema=False)
def login_page(request: Request):
if sessions.authenticated(request):
return RedirectResponse(settings.base_path + "/", status_code=303, headers={"Cache-Control": "no-store"})
return _page_response(static_dir / "login.html", settings)
app.mount("/static", _Assets(directory=static_dir, sessions=sessions, check_dir=False, follow_symlink=False), name="static")
return app