Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

feat(packaging): 提供 Linux Docker 镜像与自动发布

longmeidao60c480d78afc
diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 000000000..79dfe2726
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,17 @@
+**
+!pyproject.toml
+!uv.lock
+!README.md
+!LICENSE
+!setup.py
+!MANIFEST.in
+!src/
+!src/**
+!migrations/
+!migrations/**
+!web/
+!web/**
+!resources/
+!resources/**
+**/__pycache__/
+**/*.pyc
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
index c27e2159e..55ce54507 100644
--- a/.github/dependabot.yml
+++ b/.github/dependabot.yml
@@ -3,6 +3,14 @@
# semver-major 不进组,照常一个包一个 PR,接管前单独看变更说明。
version: 2
updates:
+ - package-ecosystem: docker
+ directory: /
+ schedule:
+ interval: weekly
+ day: monday
+ time: "09:45"
+ timezone: Asia/Taipei
+
- package-ecosystem: uv
directory: /
schedule:
diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml
new file mode 100644
index 000000000..1a7095078
--- /dev/null
+++ b/.github/workflows/docker.yml
@@ -0,0 +1,64 @@
+name: Docker
+
+on:
+ pull_request:
+ paths: [Dockerfile, .dockerignore, compose.yaml, 'src/**', 'migrations/**', 'web/**', 'resources/**', pyproject.toml, uv.lock, setup.py, MANIFEST.in, scripts/smoke_docker.py, .github/workflows/docker.yml]
+ push:
+ branches: [master]
+ tags: ['v*.*.*']
+ workflow_dispatch:
+
+permissions:
+ contents: read
+ actions: read
+
+jobs:
+ image:
+ name: Linux amd64 镜像验收
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v7
+ - uses: actions/setup-python@v7
+ with:
+ python-version: '3.14'
+ - name: 核对标签提交的主线 CI
+ if: github.ref_type == 'tag'
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: python3 scripts/release_tag.py --repo "$GITHUB_REPOSITORY" --verify-sha "$GITHUB_SHA"
+ - uses: docker/setup-buildx-action@v4
+ - name: 构建候选镜像
+ uses: docker/build-push-action@v7
+ with:
+ context: .
+ load: true
+ tags: longmeidao/peach:test
+ cache-from: type=gha
+ cache-to: type=gha,mode=max
+ - name: 验收临时容器
+ run: python3 scripts/smoke_docker.py longmeidao/peach:test
+ - name: 登录 Docker Hub
+ if: github.event_name != 'pull_request' && (github.ref == 'refs/heads/master' || startsWith(github.ref, 'refs/tags/v')) && vars.DOCKERHUB_USERNAME != ''
+ uses: docker/login-action@v4
+ with:
+ username: ${{ vars.DOCKERHUB_USERNAME }}
+ password: ${{ secrets.DOCKERHUB_TOKEN }}
+ - name: 计算镜像标签
+ id: tags
+ env:
+ REF_TYPE: ${{ github.ref_type }}
+ REF_NAME: ${{ github.ref_name }}
+ run: |
+ if [ "$REF_TYPE" = tag ]; then
+ echo "value=longmeidao/peach:${REF_NAME#v}" >> "$GITHUB_OUTPUT"
+ else
+ echo 'value=longmeidao/peach:edge' >> "$GITHUB_OUTPUT"
+ fi
+ - name: 发布已验收镜像
+ if: github.event_name != 'pull_request' && (github.ref == 'refs/heads/master' || startsWith(github.ref, 'refs/tags/v')) && vars.DOCKERHUB_USERNAME != ''
+ uses: docker/build-push-action@v7
+ with:
+ context: .
+ push: true
+ tags: ${{ steps.tags.outputs.value }}
+ cache-from: type=gha
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 000000000..75a8683fe
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,33 @@
+# syntax=docker/dockerfile:1
+FROM ghcr.io/astral-sh/uv:0.13.1 AS uv
+FROM python:3.14.8-slim-trixie AS build
+COPY --from=uv /uv /usr/local/bin/uv
+WORKDIR /app
+ENV UV_PYTHON_DOWNLOADS=never UV_LINK_MODE=copy
+RUN apt-get update && apt-get install -y --no-install-recommends build-essential \
+ && rm -rf /var/lib/apt/lists/*
+COPY pyproject.toml uv.lock README.md LICENSE setup.py MANIFEST.in ./
+COPY src ./src
+COPY migrations ./migrations
+COPY web ./web
+COPY resources ./resources
+RUN uv sync --locked --no-dev --no-editable
+
+FROM python:3.14.8-slim-trixie
+LABEL org.opencontainers.image.title="Peach" \
+ org.opencontainers.image.source="https://github.com/peach-mitao/peach" \
+ org.opencontainers.image.licenses="AGPL-3.0-or-later"
+RUN apt-get update && apt-get install -y --no-install-recommends ffmpeg openssl ca-certificates \
+ && rm -rf /var/lib/apt/lists/* \
+ && groupadd --gid 1000 peach && useradd --uid 1000 --gid 1000 --create-home peach \
+ && mkdir /data && chown peach:peach /data
+COPY --from=build /app/.venv /app/.venv
+ENV PATH="/app/.venv/bin:$PATH" PEACH_DATA_ROOT=/data PYTHONUNBUFFERED=1 \
+ PYTHONIOENCODING=utf-8 PYTHONUTF8=1
+WORKDIR /data
+USER peach
+EXPOSE 8900
+VOLUME ["/data"]
+HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \
+ CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8900/healthz?ready=1', timeout=3).read()"]
+ENTRYPOINT ["python", "-m", "peach.server"]
diff --git a/README.en.md b/README.en.md
index a60ba5ec8..59f9902b1 100644
--- a/README.en.md
+++ b/README.en.md
@@ -129,6 +129,10 @@ LAN access, access passwords, updates and uninstalling are covered in [Operation
Open System diagnostics under Peach configuration → Application and maintenance to view library health lists, source parsing and cooldowns. `peach doctor` provides the same report; `--json` returns redacted JSON. See [Local diagnostics](docs/OPERATIONS.md#本机诊断) for status and actions.
+### Docker (VPS / NAS)
+
+The headless Linux image runs alongside CloudDrive2, with separate mounts for media and application data. See [Docker deployment](docs/DOCKER.md) for setup, access boundaries and validation status.
+
## FAQ
- **Will it change my files?**
diff --git a/README.md b/README.md
index ceea13259..c1e67795c 100644
--- a/README.md
+++ b/README.md
@@ -128,6 +128,10 @@ macOS 把后两条换成 `uv sync --locked --python 3.14 --extra macos` 和 `./.
在Peach 配置「应用与维护」打开系统诊断,可查看库健康清单、来源解析与冷却状态。运行 `peach doctor` 可取得同一份报告;`--json` 输出脱敏 JSON。状态与处理方式见 [本机诊断](docs/OPERATIONS.md#本机诊断)。
+### Docker(VPS / NAS)
+
+Linux 无桌面镜像与 CloudDrive2 分别部署,媒体目录与运行数据独立挂载。部署方式、访问范围和验收状态见 [Docker 部署](docs/DOCKER.md)。
+
## 常见问题
- **会改我的文件吗?**
diff --git a/SECURITY.md b/SECURITY.md
index 63ee5b298..e7d4bcfff 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -6,6 +6,8 @@ Peach is a single-user, self-hosted application: one deployment serves one perso
Peach 是单人自托管应用:一个部署只服务一个人,没有账号体系、没有权限分级,也没有多租户隔离。
+Linux 无桌面部署的配置管理接受经过鉴权的回环与私有网络连接,拒绝公网、链路本地、保留地址和携带转发头的管理请求。地址分类使用 Python 标准库。容器端口默认发布到宿主机回环,部署方式见 [Docker 部署](docs/DOCKER.md)。
+
能打开 Peach 的人,就能看到整个馆藏,也能做任何修改。Peach 只防一件事:同一局域网里的其他设备被无意放进来。多人共用和云端托管不在考虑范围内。
## 访问密码
diff --git a/compose.yaml b/compose.yaml
new file mode 100644
index 000000000..3c845b539
--- /dev/null
+++ b/compose.yaml
@@ -0,0 +1,21 @@
+services:
+ peach:
+ image: longmeidao/peach:${PEACH_VERSION:-edge}
+ build: .
+ init: true
+ restart: unless-stopped
+ stop_grace_period: 75s
+ ports:
+ - "${PEACH_BIND:-127.0.0.1}:${PEACH_PORT:-8900}:8900"
+ volumes:
+ - peach-data:/data
+ - type: bind
+ source: ${PEACH_MEDIA_ROOT:-./media}
+ target: /media
+ read_only: true
+ bind:
+ propagation: rslave
+ create_host_path: false
+
+volumes:
+ peach-data:
diff --git a/docs/DOCKER.md b/docs/DOCKER.md
new file mode 100644
index 000000000..9e769d040
--- /dev/null
+++ b/docs/DOCKER.md
@@ -0,0 +1,33 @@
+# Docker 部署
+
+Peach 的 Linux 无桌面镜像用于单人 VPS 与 NAS,镜像仓库为 [longmeidao/peach](https://hub.docker.com/r/longmeidao/peach)。`edge` 是主线候选,版本号标签对应发布提交。当前镜像目标为 `linux/amd64`;ARM NAS 尚未验收。2026-10-15 在 WSL 的独立 Docker Engine 中,用正式锁定依赖通过空数据卷初始化、非 root、鉴权、配置保存、合成视频扫描、HTTP Range、配置重载与重启持久化验收。
+
+## 数据与媒体
+
+`/data` 保存配置、SQLite 账本、凭据和图片缓存,必须持久化。媒体通过 `/media` 单独挂入;默认只读,扫描和播放不需要媒体写权限。整理、移动与删除需要使用者明确提供可写挂载。
+
+CloudDrive2 与 Peach 分别运行。NAS 已有 CloudDrive2 时直接复用;全新机器按 [CloudDrive2 官方 Docker 指南](https://www.clouddrive2.com/docker.html) 安装并绑定网盘。宿主机必须支持 FUSE,CloudDrive2 的挂载目录需要共享传播;Peach 用 `rslave` 接收挂载,不需要 FUSE 或特权容器。挂载目录的权限必须允许 UID 1000 读取。
+
+需要云下载或推送发现时,Peach 配置中的 CloudDrive2 API 地址使用同一容器网络的服务名或可达的宿主机地址;容器里的 `127.0.0.1` 只指向 Peach 自己。
+
+仓库根的 `compose.yaml` 使用 `PEACH_MEDIA_ROOT` 指定宿主机已有媒体根;容器中固定为 `/media`。先完成 CloudDrive2 挂载,再启动 Peach。命名卷 `peach-data` 保存 `/data`,不要执行删除该卷的操作。需要绑定现有数据目录时,先做完整备份并确保 UID 1000 可写;不要让另一台 Peach 同时写这份账本。
+
+## 首次运行与访问
+
+使用 Compose 启动后,无桌面入口会为全新数据卷初始化配置、账本和随机内部口令。它不覆盖已有配置;发现只有账本而没有配置时拒绝启动。初始化日志只显示口令文件位置。
+
+在容器终端运行 `peach token` 取得登录口令,在浏览器登录后设置访问密码。配置页接受经过鉴权的回环或私有网络连接,带转发头的管理请求会被拒绝。配置页添加媒体文件夹时填容器内路径,例如 `/media/115`;对应声明根沿用 `B:\`,PikPak 沿用 `A:\`。配置保存会自动重载服务;勾选扫描时使用既有资料处理入口。
+
+容器内 HTTP 端口固定为 8900,访问端口在 Compose 设置。默认只发布到宿主机 `127.0.0.1`,远程访问使用私有 VPN 或 SSH 隧道。需要局域网访问时,通过 `PEACH_BIND` 绑定宿主机的局域网地址,并设置访问密码。公网托管边界见 [安全说明](../SECURITY.md)。Docker 镜像不提供多人账号或租户隔离。
+
+## 更新与范围
+
+更新镜像并重建容器时保留 `/data`。数据库有待执行迁移时,先备份并按 [运行与配置](OPERATIONS.md) 的迁移流程处理;无桌面入口不会自动迁移已有账本。健康检查使用 `/healthz?ready=1`。
+
+Linux 容器不读取用户电脑上的浏览历史,也不包含交互式浏览器;需要本机浏览器完成验证的来源在此环境不可用。CloudDrive2 的真实账号登录、网盘流量与 NAS 实机挂载需在目标机器验证。
+
+## 镜像发布
+
+构建使用官方 Python `3.14.8-slim-trixie` 与 uv `0.13.1`,依赖由 `uv.lock` 锁定,应用以非 editable 包安装,包含 Web 与迁移资源。镜像以 UID/GID 1000 运行,内置 FFmpeg、FFprobe 和 OpenSSL。构建上下文只允许代码与资源,不包含工作树、媒体、真实账本或凭据。
+
+GitHub Actions 的 `Docker` 工作流先构建并运行临时卷验收,通过后发布。仓库变量 `DOCKERHUB_USERNAME` 和机密 `DOCKERHUB_TOKEN` 用于 Docker Hub 发布;机密只保存在 GitHub,不进入项目文件。未配置发布身份时仍执行构建验收。ARM 镜像需通过同等运行验收后再加入发布。
diff --git a/docs/PRODUCT_BACKLOG.md b/docs/PRODUCT_BACKLOG.md
index b40329cf4..7cd1538b6 100644
--- a/docs/PRODUCT_BACKLOG.md
+++ b/docs/PRODUCT_BACKLOG.md
@@ -78,7 +78,7 @@
统一配置、会话有效性验证与完整批量 GUI,清单导入导出与标准模式待实施。
Instagram 成熟解析器须有独立用户会话 POC;交付条件是 Windows/macOS 干净安装能跑、二次运行命中缓存。
- 后续结构:显式 API 模型、前端构建与高频页面迁移、候选分页、任务持久化按垂直功能实施;不为 AppContext 或文件尺寸单独做全仓搬迁。
-- Linux 首版候选为 headless、预挂载媒体与独立 wheel。外部容器用了替身依赖,其结果不能证明锁定依赖可用,也不算 Linux 正式支持;优先级低于 Windows/macOS。
+- Linux 无桌面容器使用正式锁定依赖,部署边界见 [Docker 部署](DOCKER.md) 与 ADR-0105;ARM、NAS 实机与真实 CloudDrive2 挂载仍需分别验收。
真实 ledger 迁移、双机复制取消和系统级安装另有明确授权边界。
diff --git a/docs/REUSE.md b/docs/REUSE.md
index 41e1e364e..4e78eed90 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -1,5 +1,7 @@
# 复用清单
+Linux 无桌面容器复用 Docker 官方 Python `3.14.8-slim-trixie`、uv `0.13.1`(MIT/Apache-2.0),以及 Docker 官方 Buildx、login-action 和 build-push-action 的「先验收再发布」流程。Python 镜像许可证随上游组件保留,FFmpeg 使用 Debian 包及其许可证。Peach 差异仅为配置重载、资料处理请求与持久化路径;不引入新 Python 依赖,不改写真实 ledger。CloudDrive2 使用其官方独立服务,不复制其代码或打包进 Peach。部署与证据范围见 [Docker 部署](DOCKER.md)。
+
收藏窗口复用 React Aria 外壳、Peach 设置弹层布局及共用关闭控件 `SettingsDialogClose`。入口为中性星形按钮;实体分类和保存的筛选分别显示,已标记与稍后看位于导航底部。收藏图像复用实体引用、厂牌标识、本地代表作与已绑定在线来源的本地头像代理,通过全站图片回退链逐项尝试,不写入偏好。原始 BoardUI 源码哈希见 `docs/BOARD_UI.md`。Rule34 视频封面使用来源缩略图,图片保留原文件扩展名;失败图片在关注数据刷新时重新尝试。无新增运行时依赖或真实 ledger 写入。
关注封面代理复用来源登记的媒体主机白名单;第三方图片地址及重定向继续执行公网 DNS 校验。
diff --git a/docs/STATUS.md b/docs/STATUS.md
index 4aabfb612..8bd460f28 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -6,6 +6,7 @@
## 运行态
+- [Docker](DOCKER.md)
- 名册:艺人(含动画作者)|卖家|在线;素人须有非职业出演证据,FC2 仅筛作品。
- 公司资料、FC2 卖家按来源补空;厂牌去重 6 组。回执 `peach-data/review/`。
- 核查:`peach-data/review/creator-boundary-delivery.md`;StraplessDildo 归厂牌。
diff --git a/docs/adr/0105-linux-headless-container.md b/docs/adr/0105-linux-headless-container.md
new file mode 100644
index 000000000..f39212010
--- /dev/null
+++ b/docs/adr/0105-linux-headless-container.md
@@ -0,0 +1,23 @@
+# ADR-0105:Linux 无桌面容器分发
+
+- 状态:已接受,容器与目标设备验收分别记录
+- 日期:2026-10-15
+
+## 背景
+
+单人 VPS 与 NAS 需要浏览器访问的服务,媒体由宿主机目录或 CloudDrive2 提供。桌面托盘承担配置重载和首次资料处理,单独启动 Web 进程无法消费这些请求。
+
+## 决策
+
+- 在 Windows、macOS 桌面分发之外提供 Linux 无桌面容器,修订 ADR-0023 的平台范围。
+- 复用 FastAPI、CLI、Windows 形态账本路径与 POSIX 挂载映射,不建立第二套应用或数据库。
+- `peach.server` 只维护 Web 子进程、配置重载和用户发起的资料处理;调度与媒体任务仍由应用持有。
+- Docker 镜像、CloudDrive2 镜像独立,媒体通过挂载传播共享。Peach 不申请 FUSE 或特权权限。
+- 持久化数据与媒体独立于镜像。已有账本不由入口自动迁移,缺配置时拒绝初始化。
+- Docker Hub 使用 `longmeidao/peach`,先验收再上传;初始目标为 amd64,ARM 通过实际验收后再纳入。
+- 安全模型仍为单人私有访问,容器端口默认只绑定宿主机回环。
+- 无桌面入口使用标准库地址分类,允许经过鉴权的回环与私有网络客户端管理配置,拒绝公网、链路本地、保留地址与带转发头的管理请求;桌面的本机管理边界保持独立。
+
+## 验收边界
+
+镜像验收覆盖锁定依赖、非 root 运行、全新临时卷、鉴权、配置重载、重启与数据持久化。网盘账号、FUSE、NAS 权限、真实播放与公网访问属于目标部署验收,未运行时不得宣称通过。
diff --git a/pyproject.toml b/pyproject.toml
index 7415c5350..df9cf737e 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -19,6 +19,7 @@ classifiers = [
"Environment :: Web Environment",
"Operating System :: MacOS",
"Operating System :: Microsoft :: Windows",
+ "Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.14",
"Topic :: Database :: Front-Ends",
diff --git a/scripts/smoke_docker.py b/scripts/smoke_docker.py
new file mode 100644
index 000000000..a1ced8a9a
--- /dev/null
+++ b/scripts/smoke_docker.py
@@ -0,0 +1,116 @@
+"""使用独立容器与临时卷验收镜像的初始化、鉴权、配置重载和持久化。"""
+from __future__ import annotations
+
+import argparse
+import json
+import subprocess
+import time
+import uuid
+
+
+def docker(*arguments: str, check: bool = True) -> str:
+ result = subprocess.run(["docker", *arguments], capture_output=True, text=True,
+ encoding="utf-8", check=check, timeout=180)
+ return (result.stdout + (result.stderr if arguments[0] == "logs" else "")).strip()
+
+
+def request(name: str, path: str, *, authenticated: bool = True, body: dict | None = None,
+ headers: dict | None = None):
+ script = (
+ "import json,urllib.request,urllib.error; from pathlib import Path; "
+ "token=Path('/data/secrets/auth-token').read_text().strip(); "
+ "body=json.loads(__import__('sys').argv[1]); "
+ "headers={'X-Token':token} if body['auth'] else {}; "
+ "headers=headers | (body['headers'] or {}); "
+ "headers['Content-Type']='application/json'; "
+ "req=urllib.request.Request('http://127.0.0.1:8900'+body['path'],"
+ "data=json.dumps(body['body']).encode() if body['body'] is not None else None,headers=headers); "
+ "\ntry:\n"
+ " response=urllib.request.urlopen(req,timeout=15)\n"
+ " data=response.read()\n"
+ " print(data.decode() if 'application/json' in response.headers.get('Content-Type','') "
+ "else json.dumps({'status':response.status,'size':len(data)}))\n"
+ "except urllib.error.HTTPError as error:\n"
+ " print(json.dumps({'status':error.code}))\n"
+ )
+ return docker("exec", name, "python", "-c", script,
+ json.dumps({"auth": authenticated, "path": path, "body": body, "headers": headers}))
+
+
+def ready(name: str) -> None:
+ deadline = time.monotonic() + 90
+ while time.monotonic() < deadline:
+ try:
+ response = json.loads(request(name, "/healthz?ready=1", authenticated=False))
+ if "status" not in response:
+ return
+ except subprocess.CalledProcessError:
+ if docker("inspect", "-f", "{{.State.Running}}", name) != "true":
+ raise RuntimeError(docker("logs", name)) from None
+ time.sleep(1)
+ raise RuntimeError("容器未就绪:" + docker("logs", name))
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("image")
+ args = parser.parse_args()
+ name = "peach-smoke-" + uuid.uuid4().hex[:12]
+ volume = name + "-data"
+ try:
+ docker("volume", "create", volume)
+ docker("run", "-d", "--name", name, "--network", "none",
+ "--mount", f"type=volume,source={volume},target=/data", args.image)
+ ready(name)
+ assert docker("exec", name, "id", "-u") == "1000"
+ assert json.loads(request(name, "/api/items")) is not None
+ assert json.loads(request(name, "/api/items", authenticated=False)) == {"status": 401}
+ docker("exec", name, "mkdir", "/data/smoke-media")
+ docker("exec", name, "ffmpeg", "-v", "error", "-f", "lavfi", "-i", "color=c=black:s=64x64:r=1",
+ "-t", "2", "-c:v", "libx264", "/data/smoke-media/fixture.mp4")
+ configuration = json.loads(request(name, "/api/configuration"))
+ saved = json.loads(request(name, "/api/configuration", body={
+ "revision": configuration["revision"], "port": configuration["port"], "scan_now": True,
+ "media_sources": [{"location": "local", "root": "R:\\media", "path": "/data/smoke-media"}],
+ }))
+ assert saved.get("saved"), saved
+ time.sleep(2)
+ ready(name)
+ deadline = time.monotonic() + 60
+ asset = None
+ while time.monotonic() < deadline:
+ raw = docker("exec", name, "python", "-c",
+ "import sqlite3; print(sqlite3.connect('/data/database/ledger.db').execute("
+ "\"SELECT id FROM asset WHERE path LIKE '%fixture.mp4'\").fetchone())")
+ if raw != "None":
+ asset = int(raw.strip("(), "))
+ break
+ time.sleep(1)
+ assert asset is not None, "资料处理请求未登记测试视频"
+ media = json.loads(request(name, f"/stream?id={asset}", headers={"Range": "bytes=0-63"}))
+ assert media == {"status": 206, "size": 64}, media
+ config_path = "/data/config.toml"
+ original = docker("exec", name, "cat", config_path)
+ docker("exec", name, "python", "-c",
+ "from pathlib import Path; Path('/data/state/configuration-reload.request').write_text('reload')")
+ deadline = time.monotonic() + 15
+ while time.monotonic() < deadline:
+ marker = docker("exec", name, "python", "-c",
+ "from pathlib import Path; print(Path('/data/state/configuration-reload.request').exists())")
+ if marker == "False":
+ break
+ time.sleep(0.5)
+ assert marker == "False", "配置重载请求未消费"
+ ready(name)
+ docker("restart", "--time", "75", name)
+ ready(name)
+ assert docker("exec", name, "cat", config_path) == original
+ print(json.dumps({"image": args.image, "checks": ["non-root", "ready", "auth", "configuration",
+ "scan", "range", "reload", "restart", "persistence"]}))
+ finally:
+ docker("rm", "--force", name, check=False)
+ docker("volume", "rm", volume, check=False)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index f8ad2816f..705c2a756 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -104,7 +104,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"test_resource_identification.py",
"test_agency_entity.py", "test_agency_reject.py", "test_label_maker.py",
"test_seed_pack.py", "test_seed_followup.py"),
- "tooling": ("test_scripts.py", "test_trash_junk.py", "test_auth.py", "test_access.py", "test_cli.py", "test_diagnostics.py", "test_error_reporting.py", "test_library_diagnostics.py", "test_script_policy.py",
+ "tooling": ("test_scripts.py", "test_trash_junk.py", "test_auth.py", "test_access.py", "test_cli.py", "test_server.py", "test_diagnostics.py", "test_error_reporting.py", "test_library_diagnostics.py", "test_script_policy.py",
"test_scan.py", "test_record_rehome.py", "test_wants.py", "test_push_discovery.py", "test_media_probe.py", "test_subtitles.py", "test_onboarding.py", "test_configuration_sources.py", "test_folder_picker.py", "test_ledger_backups.py", "test_clear_camera_filename_codes.py",
"test_agent_worktree.py", "test_test_evidence.py", "test_test_environment.py", "test_dependency_policy.py",
"test_version_bump.py", "test_changelog.py", "test_release_due.py",
@@ -143,7 +143,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"test_folder_picker.py", "test_fsutil.py", "test_runtime_consistency.py",
"test_subprocess_encoding.py", "test_windows_update.py", "test_buildinfo.py"),
"packaging": ("test_dependency_policy.py", "test_buildinfo.py", "test_onboarding.py",
- "test_cli.py", "test_versioning.py", "test_frontend_build.py",
+ "test_cli.py", "test_server.py", "test_versioning.py", "test_frontend_build.py",
"test_cloudflared_packaging.py", "test_desktop_installer.py"),
}
@@ -240,6 +240,11 @@ AUTO_SCOPE_FILES: dict[str, tuple[str, ...]] = {
# `test_frontend_build.py` 读它——改表就得跑到 web。
"frontend/src/react/boardui/ORIGIN.md": ("checks", "web"),
".github/dependabot.yml": ("tooling", "web"),
+ "Dockerfile": ("packaging", "tooling"),
+ ".dockerignore": ("packaging", "tooling"),
+ "compose.yaml": ("packaging", "tooling"),
+ "src/peach/server.py": ("packaging", "tooling"),
+ "scripts/smoke_docker.py": ("packaging", "tooling"),
}
# 脚本默认归 tooling;有自己领域测试的脚本两边都跑:领域测试验它的判据,
diff --git a/src/peach/cli.py b/src/peach/cli.py
index 3538859d9..061872d63 100644
--- a/src/peach/cli.py
+++ b/src/peach/cli.py
@@ -90,7 +90,7 @@ def _serve(args: argparse.Namespace) -> int:
# 有人重启这条引导服务,读到新口令的它会把还没看到口令的用户关在门外。
# 安全边界由绑定地址给:这条服务只监听回环(`build_setup_service_specs`)。
tunnel_lan_address = None
- if not distribution.standalone() and not _is_loopback(args.host):
+ if not distribution.standalone() and not _is_loopback(args.host) and (publish_mdns or TUNNEL_ENABLED):
from .mdns import lan_ipv4
tunnel_lan_address = args.mdns_address or lan_ipv4()
settings = PeachSettings(
diff --git a/src/peach/routes_configuration.py b/src/peach/routes_configuration.py
index 88933536d..48ab4fcc5 100644
--- a/src/peach/routes_configuration.py
+++ b/src/peach/routes_configuration.py
@@ -1,7 +1,7 @@
"""本机配置的 JSON 契约:读取、校验、原子保存与托盘重启请求。
页面整个是 `frontend/src/react/settings/` 下的 React 子树(入口 `configuration-page.tsx`),
-挂在主站的 `/configuration` 路由里(ADR-0031);这里只回数据。两道门都在服务端:只放行本机连接,只在托盘管理的服务里可写。
+挂在主站的 `/configuration` 路由里(ADR-0031);这里只回数据。桌面由托盘管理,无桌面服务由专用入口管理;调用方范围与配置写入都在服务端校验。
手机上的管理菜单不列这一页,靠的是 `/healthz` 的 `configurable`,但那只是入口的显隐,
拒绝写入的判定在这里。
"""
@@ -36,8 +36,9 @@ FILE_MANAGED_NOTICE = "这个部署由配置文件管理服务;在本机编辑
def managed_configuration() -> bool:
- """托盘负责消费配置保存后的重载标记。"""
- return distribution.standalone() or os.environ.get("PEACH_TRAY_MANAGED") == "1"
+ """托盘或无桌面入口负责消费配置保存后的重载标记。"""
+ return (distribution.standalone() or os.environ.get("PEACH_TRAY_MANAGED") == "1"
+ or os.environ.get("PEACH_HEADLESS_MANAGED") == "1")
def dev_environment() -> bool:
@@ -78,6 +79,13 @@ def local_client(request: Request) -> bool:
peer = ipaddress.ip_address(request.client.host)
except ValueError:
return False
+ if os.environ.get("PEACH_HEADLESS_MANAGED") == "1":
+ if any(header.startswith("x-forwarded-") or header in {"forwarded", "cf-connecting-ip"}
+ for header in request.headers):
+ return False
+ return peer.is_loopback or (peer.is_private and not any((
+ peer.is_link_local, peer.is_reserved, peer.is_unspecified, peer.is_multicast,
+ )))
if not peer.is_loopback and (peer != bound or peer.is_unspecified):
return False
if managed_configuration():
diff --git a/src/peach/server.py b/src/peach/server.py
new file mode 100644
index 000000000..78d88faca
--- /dev/null
+++ b/src/peach/server.py
@@ -0,0 +1,91 @@
+"""无桌面服务入口:维护 Web 进程,消费配置重载与资料处理请求。"""
+from __future__ import annotations
+
+import argparse
+import os
+import signal
+import subprocess
+import sys
+import threading
+
+from . import onboarding, settings_file
+
+
+def launch(*arguments: str) -> subprocess.Popen:
+ environment = dict(os.environ, PYTHONIOENCODING="utf-8", PYTHONUTF8="1", PEACH_HEADLESS_MANAGED="1")
+ return subprocess.Popen(
+ [sys.executable, "-m", "peach", *arguments],
+ stdin=subprocess.DEVNULL, env=environment,
+ creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0,
+ )
+
+
+def stop_process(process: subprocess.Popen | None) -> None:
+ if process is None or process.poll() is not None:
+ return
+ process.terminate()
+ try:
+ process.wait(timeout=30)
+ except subprocess.TimeoutExpired:
+ process.kill()
+ process.wait(timeout=10)
+
+
+def initialize() -> None:
+ config = settings_file.load_config()
+ if config.present:
+ return
+ if config.directory("database").joinpath("ledger.db").exists():
+ raise RuntimeError("已有账本但缺少配置文件,请恢复 config.toml 后启动")
+ process = launch("init", "--no-input")
+ try:
+ code = process.wait(timeout=120)
+ if code:
+ raise RuntimeError(f"初始化失败,退出码 {code}")
+ finally:
+ stop_process(process)
+
+
+def supervise(host: str, port: int, stopping: threading.Event) -> int:
+ service = scanner = None
+ try:
+ while not stopping.is_set():
+ config = settings_file.load_config()
+ reload_path = config.directory("state") / onboarding.RELOAD_NAME
+ if service is None or reload_path.exists():
+ stop_process(service)
+ service = launch("serve", "--host", host, "--port", str(port),
+ "--no-mdns", "--no-ledger-sync")
+ reload_path.unlink(missing_ok=True)
+ code = service.poll()
+ if code is not None:
+ return code or 1
+ if scanner is not None and scanner.poll() is not None:
+ if scanner.returncode:
+ print(f"资料处理失败,退出码 {scanner.returncode}", file=sys.stderr, flush=True)
+ scanner = None
+ if scanner is None:
+ location = onboarding.take_first_scan_request(config)
+ if location is not None:
+ scanner = launch("process", location)
+ stopping.wait(1)
+ return 0
+ finally:
+ stop_process(scanner)
+ stop_process(service)
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description="运行 Peach 无桌面服务")
+ parser.add_argument("--host", default="0.0.0.0")
+ parser.add_argument("--port", type=int, default=8900)
+ args = parser.parse_args(argv)
+ stopping = threading.Event()
+ for signum in (signal.SIGTERM, signal.SIGINT):
+ signal.signal(signum, lambda *_: stopping.set())
+ initialize()
+ return supervise(args.host, args.port, stopping)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/test_server.py b/tests/test_server.py
new file mode 100644
index 000000000..b03109240
--- /dev/null
+++ b/tests/test_server.py
@@ -0,0 +1,86 @@
+"""无桌面入口的进程退出与现有数据保护。"""
+import subprocess
+import sys
+import tempfile
+import threading
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import patch
+
+from peach import server, settings_file
+from starlette.requests import Request
+
+
+class ServerTests(unittest.TestCase):
+ def test_headless_configuration_accepts_private_peers_and_rejects_forwarding(self):
+ from peach.routes_configuration import local_client, managed_configuration
+ with patch.dict("os.environ", {"PEACH_HEADLESS_MANAGED": "1"}):
+ self.assertTrue(managed_configuration())
+ for peer, headers, allowed in (
+ ("192.0.2.1", [], True), ("198.51.100.10", [], True),
+ ("8.8.8.8", [], False), ("169.254.1.1", [], False),
+ ("0.0.0.0", [], False), ("240.0.0.1", [], False),
+ ("127.0.0.1", [], True), ("fd00::1", [], True),
+ ("192.0.2.1", [(b"x-forwarded-for", b"8.8.8.8")], False),
+ ("192.0.2.1", [(b"x-forwarded-host", b"example.com")], False),
+ ):
+ request = Request({"type": "http", "client": (peer, 1234),
+ "server": ("0.0.0.0", 8900), "headers": headers,
+ "app": SimpleNamespace(state=SimpleNamespace(tunnel=None))})
+ with self.subTest(peer=peer, headers=headers):
+ self.assertEqual(local_client(request), allowed)
+
+ def test_cli_without_mdns_or_tunnel_needs_no_network_route(self):
+ from peach import cli
+ with patch.object(cli, "_require_readable_settings"), \
+ patch.object(cli, "_serve_token", return_value="test"), \
+ patch.object(cli, "_build_sync", return_value=None), \
+ patch.object(cli, "create_app"), patch.object(cli, "TUNNEL_ENABLED", False), \
+ patch("peach.mdns.lan_ipv4", side_effect=OSError("no route")) as route, \
+ patch("uvicorn.run"):
+ self.assertEqual(cli.main(["serve", "--host", "0.0.0.0", "--no-mdns"]), 0)
+ route.assert_not_called()
+
+ def test_initialization_preserves_existing_configuration(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory).resolve()
+ config = settings_file.load_config(environ={"PEACH_DATA_ROOT": str(root)})
+ settings_file.write(config)
+ existing = config.path.read_bytes()
+ with patch.object(server.settings_file, "load_config", return_value=settings_file.load_config(
+ environ={"PEACH_DATA_ROOT": str(root)})), patch.object(server, "launch") as launch:
+ server.initialize()
+ launch.assert_not_called()
+ self.assertEqual(config.path.read_bytes(), existing)
+
+ def test_initialization_rejects_database_without_configuration(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory).resolve()
+ config = settings_file.load_config(environ={"PEACH_DATA_ROOT": str(root)})
+ config.directory("database").mkdir()
+ config.directory("database").joinpath("ledger.db").write_bytes(b"existing")
+ with patch.object(server.settings_file, "load_config", return_value=config), \
+ patch.object(server, "launch") as launch:
+ with self.assertRaisesRegex(RuntimeError, "已有账本"):
+ server.initialize()
+ launch.assert_not_called()
+
+ def test_stop_waits_for_child_exit(self):
+ process = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"],
+ stdin=subprocess.DEVNULL)
+ try:
+ server.stop_process(process)
+ self.assertIsNotNone(process.poll())
+ finally:
+ server.stop_process(process)
+
+ def test_service_failure_exits_supervisor(self):
+ with tempfile.TemporaryDirectory() as directory:
+ config = settings_file.load_config(environ={"PEACH_DATA_ROOT": str(Path(directory).resolve())})
+ process = subprocess.Popen([sys.executable, "-c", "raise SystemExit(17)"],
+ stdin=subprocess.DEVNULL)
+ process.wait(timeout=15)
+ with patch.object(server.settings_file, "load_config", return_value=config), \
+ patch.object(server, "launch", return_value=process):
+ self.assertEqual(server.supervise("127.0.0.1", 8900, threading.Event()), 17)