"""Persistent, single-administrator setup state for the panel. The application creates a random one-time token on its first start. The web setup route consumes it once, writing only a password hash to ``state.json``. Both files are private to the account running the panel service. """ from __future__ import annotations import fcntl import hmac import json import os import re import secrets import stat import tempfile import threading from contextlib import contextmanager from pathlib import Path from .auth import hash_password _USERNAME = re.compile(r"[A-Za-z][A-Za-z0-9_.-]{2,31}\Z") class SetupError(Exception): """A setup request cannot be completed.""" def __init__(self, message: str, status: int = 400) -> None: super().__init__(message) self.status = status class PanelState: def __init__(self, data_dir: Path) -> None: supplied_dir = Path(data_dir) if supplied_dir.is_symlink(): raise ValueError("Panel data directory itself must not be a symlink") # Resolve trusted parent paths while rejecting a symlink at the # panel's own data directory. self.data_dir = supplied_dir.resolve() self.state_file = self.data_dir / "state.json" self.token_file = self.data_dir / "setup-token" self.lock_file = self.data_dir / ".setup.lock" self._lock = threading.RLock() self._ensure_directory() def _ensure_directory(self) -> None: self.data_dir.mkdir(mode=0o700, parents=True, exist_ok=True) info = self.data_dir.lstat() if not stat.S_ISDIR(info.st_mode) or info.st_mode & 0o077: raise ValueError("Panel data directory must be a private directory (0700)") def _read(self) -> dict: try: info = self.state_file.lstat() if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077: raise ValueError("Panel state file must be private (0600)") with self.state_file.open("r", encoding="utf-8") as stream: state = json.load(stream) except FileNotFoundError: return {"version": 1} if not isinstance(state, dict) or state.get("version") != 1: raise ValueError("Panel state file is invalid") return state def _read_token(self) -> str: info = self.token_file.lstat() if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077: raise ValueError("Setup token file must be private (0600)") token = self.token_file.read_text(encoding="ascii").strip() if len(token) < 32: raise ValueError("Setup token file is invalid") return token @contextmanager def _setup_lock(self): """Serialize setup across workers/processes, not just Python threads.""" with self._lock: flags = os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0) fd = os.open(self.lock_file, flags, 0o600) try: info = os.fstat(fd) if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077: raise ValueError("Panel setup lock must be private (0600)") fcntl.flock(fd, fcntl.LOCK_EX) try: yield finally: fcntl.flock(fd, fcntl.LOCK_UN) finally: os.close(fd) def _fsync_directory(self) -> None: directory_fd = os.open(self.data_dir, os.O_RDONLY) try: os.fsync(directory_fd) finally: os.close(directory_fd) def _write(self, state: dict) -> None: fd, temporary = tempfile.mkstemp(prefix=".state-", dir=self.data_dir) try: os.fchmod(fd, 0o600) with os.fdopen(fd, "w", encoding="utf-8") as stream: json.dump(state, stream, ensure_ascii=False, separators=(",", ":")) stream.write("\n") stream.flush() os.fsync(stream.fileno()) os.replace(temporary, self.state_file) self._fsync_directory() finally: if os.path.exists(temporary): os.unlink(temporary) def admin(self) -> tuple[str, str] | None: with self._lock: admin = self._read().get("admin") if admin is None: return None if ( not isinstance(admin, dict) or not isinstance(admin.get("username"), str) or not isinstance(admin.get("password_hash"), str) ): raise ValueError("Panel administrator state is invalid") return admin["username"], admin["password_hash"] def setup_required(self) -> bool: return self.admin() is None def initialize_setup_token(self) -> str | None: """Return the initial token, or ``None`` if an admin already exists. Restarting before setup returns the *same* token. It does not silently rotate a secret that may already have been shown to the operator. """ with self._setup_lock(): if not self.setup_required(): # Recover from a crash after state.json was committed but # before the now-obsolete token could be removed. if self.token_file.exists(): self.token_file.unlink() self._fsync_directory() return None try: return self._read_token() except FileNotFoundError: pass token = secrets.token_urlsafe(32) fd = os.open(self.token_file, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) try: with os.fdopen(fd, "w", encoding="ascii") as stream: stream.write(token + "\n") stream.flush() os.fsync(stream.fileno()) self._fsync_directory() except BaseException: self.token_file.unlink(missing_ok=True) raise return token def create_admin(self, token: str, username: str, password: str) -> str: if not _USERNAME.fullmatch(username): raise SetupError("用户名应为 3 至 32 位字母、数字、点、下划线或连字符") if len(password) < 12 or len(password) > 1024: raise SetupError("管理员密码长度须在 12 至 1024 位之间") with self._setup_lock(): if self.admin() is not None: raise SetupError("管理员已创建", 409) try: expected = self._read_token() except FileNotFoundError as exc: raise SetupError("初始化口令不可用,请重新启动面板并查看启动终端输出", 503) from exc if not hmac.compare_digest(token, expected): raise SetupError("初始化口令无效", 403) encoded = hash_password(password) self._write({ "version": 1, "admin": {"username": username, "password_hash": encoded}, }) self.token_file.unlink(missing_ok=True) self._fsync_directory() return username