Peach: Local-first video metadata scraper and media manager.
fix: restore peach.local and add optional TLS
Peach local maintenanceb2e84326cead
diff --git a/README.md b/README.mdindex f59c244e3..3ce718381 100644--- a/README.md+++ b/README.md@@ -42,4 +42,14 @@ cd R:\peach-app`serve` 默认只监听 `127.0.0.1:8900`。公网、反代、HTTPS 和认证属于后续部署阶段,不在开发命令中隐式开启。+需要本机 TLS 时同时提供证书和私钥;二者应放在 `R:\peach-data\secrets`,不要提交 Git:++```powershell+& .\.venv\Scripts\peach.exe serve --host 0.0.0.0 --port 443 `+ --ssl-certfile R:\peach-data\secrets\tls\peach.crt `+ --ssl-keyfile R:\peach-data\secrets\tls\peach.key+```++证书必须包含实际访问名(例如 `peach.local`)并被客户端信任;启用 TLS 时 mDNS 自动发布 HTTPS。+当前运行态与下一任务只看 [`docs/STATUS.md`](docs/STATUS.md);跨 Codex/Claude 的固定接手方式只看 [`docs/HANDOFF.md`](docs/HANDOFF.md)。diff --git a/docs/HANDOFF.md b/docs/HANDOFF.mdindex 8b8fbd7a8..36553f85f 100644--- a/docs/HANDOFF.md+++ b/docs/HANDOFF.md@@ -21,6 +21,8 @@ This is durable operating knowledge, not a per-session transcript.## Operations- Main command: `peach serve|migrate` after editable installation.+- `peach serve` 默认发布 `peach.local`;使用 `--no-mdns` 可关闭。mDNS 注册在 FastAPI lifespan 中执行,不能在事件循环内同步阻塞。+- TLS 仅在同时提供 `--ssl-certfile` 和 `--ssl-keyfile` 时启用;`.local` 使用本地 CA,不使用 Let's Encrypt,证书和私钥留在 `R:\peach-data\secrets`。- FastAPI is the only Web server. `web_contract.py` contains the stable JSON surface; do not recreate a parallel `http.server` or dynamic legacy loader.- FFmpeg/ffprobe resolve from explicit environment overrides, then `R:\peach-data\tools\ffmpeg\bin`, then `PATH`. No active code may fall back to the Stash private directory.- Long-running inventory helpers are under `scripts/`; their scheduled tasks use `R:\peach-app\.venv\Scripts\python.exe`. They use absolute data paths and may be interrupted/restarted where their own locking contract allows it.diff --git a/docs/STATUS.md b/docs/STATUS.mdindex e53f6afc7..624dc81cf 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -4,7 +4,8 @@ Last verified: 2026-08-14## Runtime-- Production Peach: FastAPI `0.2.0` from `R:\peach-app` on `0.0.0.0:80`, PID observed as 51308; health mode is `fastapi`.+- Production Peach: FastAPI `0.2.0` from `R:\peach-app` on `0.0.0.0:80`, PID observed as 57976; health mode is `fastapi`.+- mDNS publisher: `peach.local` registered on `192.168.50.162` as HTTP. Same-host Windows discovery does not loop back reliably; confirmation from another LAN device remains required.- Stash: `127.0.0.1:9999`, PID observed as 35332.- Traffic monitor: running through `RM-TrafficWatch` from `R:\peach-app\.venv`; all probe/sheets tasks use the same project environment.- Runtime Python: 3.14.7. The removed system Python 3.12 invalidated the old venv, which was rebuilt and reverified before production start.@@ -19,11 +20,12 @@ Runtime PIDs are observations, not configuration; always re-check them.- The old `BaseHTTPRequestHandler`, dynamic legacy loader and automatic schema repair path are deleted. Default contract reads are read-only; activity/play/feedback writes are explicit.- FFmpeg/ffprobe are Peach-managed under `R:\peach-data\tools\ffmpeg`; resolver order is environment, managed bundle, then PATH. Active code has no Stash private binary fallback.- `R:\peach-data` now separates `database/generated/sources/state/secrets/logs/archive/inbox/tools`; the old empty root Inbox and old Resources/Tools compatibility surface are removed.-- 21 isolated contract tests passed under Python 3.14 after removing three legacy-server-only tests with the deleted server.+- 24 isolated tests passed under Python 3.14, including HTTP/HTTPS mDNS publication and TLS argument boundaries.- Real migration preserved 81,873 assets and 59,697 tag links; both live database and backup passed `integrity_check` and `foreign_key_check`.- Desktop 1280×720 and mobile 390×844 browser checks passed on the same application candidate before the schema-only migration; visual checks were not rerun after migration because no browser instance was connected.- Restarted production port 80 passed health, home, 24,980-item all-source list, 2,552-item local list and one-byte `206 Partial Content` Range smoke checks.- After deleting the legacy server, restarted production also passed real `stats`, `tops` and `facets` aggregate contract checks.+- Optional SSL is supported with an explicit certificate/key pair. Production remains HTTP until a trusted local certificate is supplied.## Next workdiff --git a/docs/adr/0004-network-and-profile-boundary.md b/docs/adr/0004-network-and-profile-boundary.mdindex 46e30b1d0..f1764efae 100644--- a/docs/adr/0004-network-and-profile-boundary.md+++ b/docs/adr/0004-network-and-profile-boundary.md@@ -9,8 +9,10 @@- online 资产、追更和外部数据源是正式能力,不再受“绝不出网”旧约束;每个 connector 必须显式授权、控频、标注来源与保留策略。- schema 预留 `app_user`/`profile`,当前只创建本地默认身份,不开放注册、密码找回、公共会话或复杂 RBAC。- 远程访问以后可选择 VPN/Tunnel,或 DDNS + 反向代理 + HTTPS;应用本身不直接裸露公网端口。+- 局域网服务由 FastAPI 生命周期发布 `peach.local` mDNS;可用 `--no-mdns` 关闭,不再依赖旧 HTTP server。+- Uvicorn 支持显式证书/私钥的本机 TLS。`.local` 不能申请公开受信的 Let's Encrypt 证书;局域网需要 TLS 时使用受各客户端信任的本地 CA(如 mkcert),证书材料只放 `R:\peach-data\secrets`。- 公网启用前必须完成强口令/身份、TLS、反代可信头、CSRF/速率限制、secret storage、审计与备份恢复验收。## 后果-“本地默认”是部署基线,不再等同于“功能禁止联网”。本轮不改防火墙、不配置 DDNS、不开放公网,也不切换现有监听。+“本地默认”是部署基线,不再等同于“功能禁止联网”。mDNS 与可选 TLS 不开放公网;本轮不改防火墙、不配置 DDNS,也不自动生成或信任本地 CA。diff --git a/pyproject.toml b/pyproject.tomlindex a5edcdd02..5f0ae1492 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -13,6 +13,7 @@ dependencies = ["pydantic==2.13.4","starlette==0.47.3","uvicorn==0.35.0",+ "zeroconf==0.150.0",][project.scripts]diff --git a/src/peach/api.py b/src/peach/api.pyindex dcafbe364..7aa6ab91a 100644--- a/src/peach/api.py+++ b/src/peach/api.py@@ -1,4 +1,7 @@import hmac+import asyncio+import logging+from contextlib import asynccontextmanagerfrom typing import Anyfrom fastapi import Body, FastAPI, Request@@ -8,6 +11,7 @@ from . import web_contractfrom .config import PeachSettingsfrom .ffmpeg import FFmpegResolverfrom .media import FilesystemMediaService, MediaNotFound, MediaUnavailable+from .mdns import MdnsPublisherfrom .previews import PreviewService, PreviewUnavailablefrom .repository import LedgerRepository@@ -41,9 +45,28 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:repository, resolver, settings.snapshot_root, settings.poster_root,settings.avatar_root, settings.logo_root,)+ mdns = MdnsPublisher(+ settings.mdns_name, settings.mdns_port, secure=settings.tls_enabled+ ) if settings.mdns_enabled else None++ @asynccontextmanager+ async def lifespan(_app: FastAPI):+ if mdns is not None:+ try:+ await asyncio.to_thread(mdns.start)+ except Exception:+ mdns.status = "unavailable"+ logging.getLogger(__name__).exception("mDNS publication failed")+ try:+ yield+ finally:+ if mdns is not None:+ await asyncio.to_thread(mdns.stop)+app = FastAPI(title="Peach API",version="0.2.0",+ lifespan=lifespan,docs_url="/docs" if settings.docs_enabled else None,redoc_url=None,openapi_url="/openapi.json" if settings.docs_enabled else None,@@ -53,6 +76,7 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:app.state.repository = repositoryapp.state.media_service = media_serviceapp.state.preview_service = preview_service+ app.state.mdns = mdns@app.middleware("http")async def no_store(request: Request, call_next):@@ -69,7 +93,10 @@ def create_app(settings: PeachSettings | None = None) -> FastAPI:ffmpeg = resolver.ffmpeg()return {"ok": True, "service": "peach-api", "mode": "fastapi","db": "available" if settings.db_path.is_file() else "missing",- "ffmpeg": ffmpeg.source if ffmpeg else "unavailable"}+ "ffmpeg": ffmpeg.source if ffmpeg else "unavailable",+ "mdns": mdns.status if mdns is not None else "disabled",+ "mdns_address": mdns.address if mdns is not None else None,+ "scheme": "https" if settings.tls_enabled else "http"}@app.api_route("/", methods=["GET", "HEAD"])def index(request: Request):diff --git a/src/peach/cli.py b/src/peach/cli.pyindex 16647d797..ca0c77fef 100644--- a/src/peach/cli.py+++ b/src/peach/cli.py@@ -15,12 +15,26 @@ DEFAULT_DB = DATABASE_PATHdef _serve(args: argparse.Namespace) -> int:import uvicorn+ if bool(args.ssl_certfile) != bool(args.ssl_keyfile):+ raise SystemExit("--ssl-certfile and --ssl-keyfile must be provided together")+ for path in (args.ssl_certfile, args.ssl_keyfile):+ if path is not None and not path.is_file():+ raise SystemExit(f"TLS file not found: {path}")+ tls_enabled = args.ssl_certfile is not Nonesettings = PeachSettings(db_path=args.db,token=args.token,docs_enabled=args.docs,+ mdns_enabled=not args.no_mdns,+ mdns_name=args.mdns_name,+ mdns_port=args.port,+ tls_enabled=tls_enabled,+ )+ uvicorn.run(+ create_app(settings), host=args.host, port=args.port, workers=1,+ ssl_certfile=str(args.ssl_certfile) if args.ssl_certfile else None,+ ssl_keyfile=str(args.ssl_keyfile) if args.ssl_keyfile else None,)- uvicorn.run(create_app(settings), host=args.host, port=args.port, workers=1)return 0@@ -52,6 +66,10 @@ def build_parser() -> argparse.ArgumentParser:serve.add_argument("--db", type=Path, default=DEFAULT_DB)serve.add_argument("--token", default="")serve.add_argument("--docs", action="store_true")+ serve.add_argument("--no-mdns", action="store_true")+ serve.add_argument("--mdns-name", default="peach")+ serve.add_argument("--ssl-certfile", type=Path)+ serve.add_argument("--ssl-keyfile", type=Path)serve.set_defaults(handler=_serve)migrate = commands.add_parser("migrate", help="inspect or apply SQLite migrations")diff --git a/src/peach/config.py b/src/peach/config.pyindex f3d74f50d..3bd98a431 100644--- a/src/peach/config.py+++ b/src/peach/config.py@@ -25,6 +25,10 @@ class PeachSettings:page_path: Path = PROJECT_ROOT / "web" / "index.html"token: str = ""docs_enabled: bool = False+ mdns_enabled: bool = False+ mdns_name: str = "peach"+ mdns_port: int = 80+ tls_enabled: bool = Falseallowed_media_roots: tuple[Path, ...] = (Path(r"R:\media"), Path("B:/"), Path("A:/"))snapshot_root: Path = GENERATED_DIR / "snapshots"poster_root: Path = GENERATED_DIR / "posters"diff --git a/src/peach/mdns.py b/src/peach/mdns.pynew file mode 100644index 000000000..f72841e95--- /dev/null+++ b/src/peach/mdns.py@@ -0,0 +1,82 @@+from __future__ import annotations++import socket+from collections.abc import Callable++from zeroconf import ServiceInfo, Zeroconf+++HTTP_SERVICE_TYPE = "_http._tcp.local."+HTTPS_SERVICE_TYPE = "_https._tcp.local."+++def lan_ipv4() -> str:+ """Ask the local routing table for the preferred LAN IPv4 without sending data."""+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)+ try:+ sock.connect(("192.0.2.1", 80))+ return str(sock.getsockname()[0])+ finally:+ sock.close()+++class MdnsPublisher:+ def __init__(+ self,+ name: str,+ port: int,+ secure: bool = False,+ address_resolver: Callable[[], str] = lan_ipv4,+ ) -> None:+ normalized = name.strip().lower().removesuffix(".local")+ if not normalized or any(ch not in "abcdefghijklmnopqrstuvwxyz0123456789-" for ch in normalized):+ raise ValueError("mDNS name must contain only letters, digits, and hyphens")+ self.name = normalized+ self.port = port+ self.secure = secure+ self._address_resolver = address_resolver+ self._zeroconf: Zeroconf | None = None+ self._info: ServiceInfo | None = None+ self.address: str | None = None+ self.status = "pending"++ @property+ def hostname(self) -> str:+ return f"{self.name}.local"++ def start(self) -> None:+ if self._zeroconf is not None:+ return+ address = self._address_resolver()+ service_type = HTTPS_SERVICE_TYPE if self.secure else HTTP_SERVICE_TYPE+ info = ServiceInfo(+ service_type,+ f"{self.name}.{service_type}",+ addresses=[socket.inet_aton(address)],+ port=self.port,+ properties={"path": "/", "scheme": "https" if self.secure else "http"},+ server=f"{self.hostname}.",+ )+ zeroconf = Zeroconf(interfaces=[address])+ try:+ zeroconf.register_service(info, allow_name_change=False)+ except Exception:+ zeroconf.close()+ raise+ self._zeroconf = zeroconf+ self._info = info+ self.address = address+ self.status = self.hostname++ def stop(self) -> None:+ if self._zeroconf is None:+ return+ try:+ if self._info is not None:+ self._zeroconf.unregister_service(self._info)+ finally:+ self._zeroconf.close()+ self._zeroconf = None+ self._info = None+ self.address = None+ self.status = "stopped"diff --git a/tests/test_mdns.py b/tests/test_mdns.pynew file mode 100644index 000000000..b0da0b606--- /dev/null+++ b/tests/test_mdns.py@@ -0,0 +1,40 @@+import unittest+from unittest.mock import patch++from peach.mdns import MdnsPublisher+++class MdnsPublisherTests(unittest.TestCase):+ def test_registers_and_unregisters_peach_local(self):+ with patch("peach.mdns.Zeroconf") as zeroconf_type:+ publisher = MdnsPublisher(+ "Peach.local", 80, address_resolver=lambda: "192.0.2.10"+ )+ publisher.start()+ info = zeroconf_type.return_value.register_service.call_args.args[0]+ self.assertEqual(info.server, "peach.local.")+ self.assertEqual(info.port, 80)+ self.assertEqual(publisher.status, "peach.local")+ publisher.stop()+ zeroconf_type.assert_called_once_with(interfaces=["192.0.2.10"])+ zeroconf_type.return_value.unregister_service.assert_called_once_with(info)+ zeroconf_type.return_value.close.assert_called_once()++ def test_secure_publication_uses_https_service(self):+ with patch("peach.mdns.Zeroconf") as zeroconf_type:+ publisher = MdnsPublisher(+ "peach", 443, secure=True, address_resolver=lambda: "192.0.2.10"+ )+ publisher.start()+ info = zeroconf_type.return_value.register_service.call_args.args[0]+ self.assertEqual(info.type, "_https._tcp.local.")+ self.assertEqual(info.port, 443)+ publisher.stop()++ def test_rejects_invalid_hostname(self):+ with self.assertRaises(ValueError):+ MdnsPublisher("bad name", 80)+++if __name__ == "__main__":+ unittest.main()