Merge Web 2.0.1 release
This commit is contained in:
@@ -58,7 +58,7 @@ jobs:
|
|||||||
- name: Install Web dependencies only
|
- name: Install Web dependencies only
|
||||||
run: python -m pip install -r ranch_web/requirements.txt
|
run: python -m pip install -r ranch_web/requirements.txt
|
||||||
- name: Offline updater regression
|
- name: Offline updater regression
|
||||||
run: python -B -m unittest ranch_web.tests.test_updates ranch_web.tests.test_web_updater -v
|
run: python -B -m unittest ranch_web.tests.test_updates ranch_web.tests.test_web_updater ranch_web.tests.test_private_updates ranch_web.tests.test_web_updater_package -v
|
||||||
- name: Build image
|
- name: Build image
|
||||||
env:
|
env:
|
||||||
WEB_VERSION: ${{ steps.version.outputs.version }}
|
WEB_VERSION: ${{ steps.version.outputs.version }}
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
FROM python:3.12-slim-bookworm
|
FROM python:3.12-slim-bookworm
|
||||||
|
|
||||||
ARG WEB_VERSION=2.0.0
|
ARG WEB_VERSION=2.0.1
|
||||||
ARG VCS_REF=unknown
|
ARG VCS_REF=unknown
|
||||||
LABEL org.opencontainers.image.source="https://github.com/attilanet/myrzx_bot" \
|
LABEL org.opencontainers.image.source="https://github.com/attilanet/myrzx_bot" \
|
||||||
org.opencontainers.image.title="myrzx_bot Web" \
|
org.opencontainers.image.title="myrzx_bot Web" \
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
# 牧羊人之心Bot
|
# 牧羊人之心Bot
|
||||||
|
|
||||||
当前 Web 正式版本 **2.0.0**,源码入口为 `main`;原生 PySide6 桌面正式版本保留 **1.2.0**(`v1.2.0`)。两者的适配资料基线均为《牧羊人之心》Android **1.9.68**。
|
本轮 Web 发布目标 **2.0.1**,源码入口为 `main`;原生 PySide6 桌面正式版本保留 **1.2.0**(`v1.2.0`)。两者的适配资料基线均为《牧羊人之心》Android **1.9.68**。
|
||||||
支持多账号独立运行、牧场培养、每日事务、主线与委托推进、近似战斗模拟、探险、扫荡及本地掉落分析,能力与验证限制见下文。
|
支持多账号独立运行、牧场培养、每日事务、主线与委托推进、近似战斗模拟、探险、扫荡及本地掉落分析,能力与验证限制见下文。
|
||||||
|
|
||||||
## 运行指引
|
## 运行指引
|
||||||
|
|
||||||
### Web 2.0.0(main)
|
### Web 2.0.1(main)
|
||||||
|
|
||||||
Windows 使用 Python 3.12+,在项目根目录执行:
|
Windows 使用 Python 3.12+,在项目根目录执行:
|
||||||
|
|
||||||
@@ -15,10 +15,12 @@ py -3 -m venv .venv-web
|
|||||||
.\Start_Ranch_Web.cmd
|
.\Start_Ranch_Web.cmd
|
||||||
```
|
```
|
||||||
|
|
||||||
访问 `http://127.0.0.1:8765`。配置管理密码后先在独立 `/login` 页面登录,再添加游戏账号、选择区服或恢复保存的会话;本机 loopback 未设置管理密码时可直接访问。配置功能后,手动点击顶部“开启”运行策略;重启、恢复会话或导入配置后,策略默认关闭。
|
访问 `http://127.0.0.1:8765`。配置管理密码后先在独立 `/login` 页面登录,再添加游戏账号、选择区服或恢复保存的会话;本机 loopback 未设置管理密码时可直接访问。手动选服、恢复会话及自动重登成功读取角色后,默认开启策略,自动执行已配置且已勾选的功能,可用顶部“停止”暂停;各子功能仍按原有勾选生效,不会全选。导入配置只替换规则并停止执行,下次成功登录仍会自动开启;服务重启后未成功登录时不直接执行。
|
||||||
|
|
||||||
Web 无需 Node/npm 或 PySide6,数据独立保存在 `local_state/ranch_web`。Linux Python 启动、离线演示与环境配置见 [Web 运行说明](ranch_web/README.md);单服务 Docker、`/data` 持久化、子路径反代与宿主机受控更新见 [Web 部署说明](deploy/web/README.md)。
|
Web 无需 Node/npm 或 PySide6,数据独立保存在 `local_state/ranch_web`。Linux Python 启动、离线演示与环境配置见 [Web 运行说明](ranch_web/README.md);单服务 Docker、`/data` 持久化、子路径反代与宿主机受控更新见 [Web 部署说明](deploy/web/README.md)。
|
||||||
|
|
||||||
|
**2.0.1** 支持登录成功后自动执行已勾选策略,由用户手动触发在线更新。在线更新使用稳定 GitHub Release、对应正式镜像及心跳有效的宿主机受控更新器;私有仓库首次配置见[部署说明](deploy/web/README.md),更新结果以宿主机健康检查为准。
|
||||||
|
|
||||||
### 桌面 1.2.0
|
### 桌面 1.2.0
|
||||||
|
|
||||||
1. 在 Windows 中安装 Python 3,并确保 `python` 命令可用。
|
1. 在 Windows 中安装 Python 3,并确保 `python` 命令可用。
|
||||||
@@ -34,7 +36,7 @@ Web 无需 Node/npm 或 PySide6,数据独立保存在 `local_state/ranch_web`
|
|||||||
|
|
||||||
| 组件与版本 | 《牧羊人之心》Android 基线 | 入口与状态 |
|
| 组件与版本 | 《牧羊人之心》Android 基线 | 入口与状态 |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| Web 2.0.0 | 1.9.68 | 正式版本;源码入口 `main`,`Start_Ranch_Web.cmd` / `sh start-web.sh` |
|
| Web 2.0.1 | 1.9.68 | 本轮发布目标;源码入口 `main`,`Start_Ranch_Web.cmd` / `sh start-web.sh` |
|
||||||
| 桌面 1.2.0(`v1.2.0`) | 1.9.68 | 当前桌面版本;`Start_Ranch_Helper.cmd` / `python -m ranch_assistant` |
|
| 桌面 1.2.0(`v1.2.0`) | 1.9.68 | 当前桌面版本;`Start_Ranch_Helper.cmd` / `python -m ranch_assistant` |
|
||||||
| 桌面 1.1.1(`v1.1.1`) | 1.9.68 | 历史正式版本,1.1 系列修复与界面更新 |
|
| 桌面 1.1.1(`v1.1.1`) | 1.9.68 | 历史正式版本,1.1 系列修复与界面更新 |
|
||||||
| 桌面 1.1.0(`v1.1.0`) | 1.9.68 | 历史已发布版本 |
|
| 桌面 1.1.0(`v1.1.0`) | 1.9.68 | 历史已发布版本 |
|
||||||
@@ -42,7 +44,7 @@ Web 无需 Node/npm 或 PySide6,数据独立保存在 `local_state/ranch_web`
|
|||||||
|
|
||||||
本表记录适配资料基线,不代表其他客户端版本兼容或全部功能已完成实机验收。Docker 镜像以标签流水线成功结果为准,在线更新依赖对应 GitHub Release 条目;详见 [部署说明](deploy/web/README.md)。
|
本表记录适配资料基线,不代表其他客户端版本兼容或全部功能已完成实机验收。Docker 镜像以标签流水线成功结果为准,在线更新依赖对应 GitHub Release 条目;详见 [部署说明](deploy/web/README.md)。
|
||||||
|
|
||||||
## Web 2.0.0 主要功能与掉线修复
|
## Web 2.0.1 主要功能与掉线修复
|
||||||
|
|
||||||
- **原布局与15页**:沿用桌面页面顺序、账号页签、顶部玩家数值与统一启停、可调整日志区。
|
- **原布局与15页**:沿用桌面页面顺序、账号页签、顶部玩家数值与统一启停、可调整日志区。
|
||||||
- **多账号与独立后台**:各账号隔离并行、同账号请求串行;关闭网页或退出管理登录后,服务端继续监控及已开启的策略。
|
- **多账号与独立后台**:各账号隔离并行、同账号请求串行;关闭网页或退出管理登录后,服务端继续监控及已开启的策略。
|
||||||
@@ -50,9 +52,9 @@ Web 无需 Node/npm 或 PySide6,数据独立保存在 `local_state/ranch_web`
|
|||||||
- **策略与数据**:复用孵蛋、牧场、喂养、突破、赠礼、每日、主线、委托、探险和扫荡策略,支持自动保存、导入导出、执行计划及掉落分析。
|
- **策略与数据**:复用孵蛋、牧场、喂养、突破、赠礼、每日、主线、委托、探险和扫荡策略,支持自动保存、导入导出、执行计划及掉落分析。
|
||||||
- **日志与更新**:普通日志按账号限量持久保存,调试详情按进程缓存;仅检查官方稳定 2.x Release,未配置执行器时仅检查,受控安装与备份/回滚由宿主机执行,自动安装默认关闭。
|
- **日志与更新**:普通日志按账号限量持久保存,调试详情按进程缓存;仅检查官方稳定 2.x Release,未配置执行器时仅检查,受控安装与备份/回滚由宿主机执行,自动安装默认关闭。
|
||||||
|
|
||||||
本次修复连接状态误判:区分在线、临时故障重试、游戏会话失效与未连接,显示最后成功通信及下次重试时间,旧快照标注为缓存。临时故障先停止策略,再退避执行只读探测;会话失效时停止游戏轮询,需手动恢复或重新登录。恢复成功后仍需手动开启策略,未确认的写操作不自动重发,页面轮询不会清除游戏连接错误。
|
连接状态区分在线、临时故障重试、游戏会话失效与未连接,显示最后成功通信及下次重试时间,旧快照标注为缓存。临时故障先停止策略,再退避执行只读探测;会话失效时停止游戏轮询,按自动重登设置等待,或手动恢复、重新登录。手动选服、恢复会话及自动重登成功后,均自动执行已勾选功能,可在顶部停止。获取区服候选或登录失败不视为成功;未确认的写操作不自动重发,页面轮询不会清除游戏连接错误。
|
||||||
|
|
||||||
战斗模拟仍为近似模型,特殊关卡并非全部支持。已有离线回归和早期部署烟测的阶段、命令及限制见 [Web 验证说明](ranch_web/README.md#离线验证);这些记录不代表正式 2.0.0 已完成真实游戏 API 或生产升级/回滚验收。
|
战斗模拟仍为近似模型,特殊关卡并非全部支持。已有离线回归和早期部署烟测的阶段、命令及限制见 [Web 验证说明](ranch_web/README.md#离线验证);这些记录不代表 2.0.1 已完成真实游戏 API 或生产升级/回滚验收。
|
||||||
|
|
||||||
## 桌面 1.2.0 功能基线
|
## 桌面 1.2.0 功能基线
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
# 2.0.1
|
||||||
|
|
||||||
|
适配资料基线:《牧羊人之心》Android 1.9.68。保留原有 Web 布局及桌面 1.2.0 入口。
|
||||||
|
|
||||||
|
## 登录后自动执行
|
||||||
|
|
||||||
|
- 账号登录并进入区服、恢复会话、掉线自动重登录成功后,自动开启全局策略开关。
|
||||||
|
- 只执行已配置且已勾选的规则,不会自动勾选所有功能。没有规则时保持待命,之后配置即可生效。
|
||||||
|
- 顶部“停止”继续有效,状态刷新和心跳不会重新开启;下次成功登录时才自动开启。
|
||||||
|
- 获取区服列表、登录失败、身份不匹配、被取消的候选和单独导入配置均不会启动策略;未确认操作继续保留核对记录。
|
||||||
|
|
||||||
|
## 掉线重登录
|
||||||
|
|
||||||
|
登录页可按账号开启自动重登录,等待时长默认 30 分钟。使用服务端加密保存的账号密码,核对原区服、原角色后连接;关闭网页不影响计时。主动退出或清除记录会取消本次自动计划。
|
||||||
|
|
||||||
|
## 私有仓库在线更新
|
||||||
|
|
||||||
|
发布附件提供独立的 `updater.pyz` 及 `SHA256SUMS`,宿主机只需 Python 3.12+ 和原有 Docker/Compose。
|
||||||
|
|
||||||
|
当前旧更新器不支持私有仓库认证,需要由操作者首次初始化新版宿主机更新器。初始化后,由操作者手动检查或点击更新,应用通过拉取正式镜像、停机备份、健康检查及失败回滚完成更新,不需要上传应用源码。
|
||||||
|
|
||||||
|
1. 登录 GitHub,在本发布页下载 `updater.pyz` 和 `SHA256SUMS`,校验文件后,将更新器安装到宿主机 `/opt/ranch-web/updater.pyz`。
|
||||||
|
2. 按[私有仓库更新说明](https://github.com/AttilaNet/myrzx_bot/blob/v2.0.1/deploy/web/README.md)设置服务端 GitHub 发布读取凭据,并完成 GHCR 镜像读取认证。
|
||||||
|
3. 首次在线更新可执行:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo python3 -B /opt/ranch-web/updater.pyz --config /etc/ranch-web-updater.toml --check
|
||||||
|
sudo python3 -B /opt/ranch-web/updater.pyz --config /etc/ranch-web-updater.toml --apply v2.0.1
|
||||||
|
```
|
||||||
|
|
||||||
|
4. 按说明让现有 systemd 更新定时器使用新版 `updater.pyz`,此后可在网页“检查版本更新”中手动触发;自动安装默认关闭。
|
||||||
|
|
||||||
|
凭据仅保存在服务端文件中,不进入版本资产、策略导出或公共日志。没有权限时明确提示认证问题,不再将私有仓库不可访问误报成“没有新版本”。
|
||||||
|
|
||||||
|
服务器更新由操作者手动触发,自动安装默认关闭。战斗模型及特殊关卡支持范围沿用现有实现,未以真实游戏账号执行发布回归。
|
||||||
|
|
||||||
|
## 验证
|
||||||
|
|
||||||
|
本地后端及更新器回归共 297 项:294 通过,3 项因 Windows 权限或软链接限制跳过;浏览器 43 项全部通过。独立宿主机包通过隔离模式下的版本、帮助与 dry-run 检查。正式镜像由对应标签的 Linux 工作流构建并检查后发布。
|
||||||
+2
-2
@@ -1,11 +1,11 @@
|
|||||||
name: ranch-web
|
name: ranch-web
|
||||||
services:
|
services:
|
||||||
web:
|
web:
|
||||||
image: ${RANCH_WEB_IMAGE:-ghcr.io/attilanet/myrzx_bot-web:v2.0.0}
|
image: ${RANCH_WEB_IMAGE:-ghcr.io/attilanet/myrzx_bot-web:v2.0.1}
|
||||||
build:
|
build:
|
||||||
context: .
|
context: .
|
||||||
args:
|
args:
|
||||||
WEB_VERSION: ${RANCH_WEB_BUILD_VERSION:-2.0.0}
|
WEB_VERSION: ${RANCH_WEB_BUILD_VERSION:-2.0.1}
|
||||||
user: "10001:10001"
|
user: "10001:10001"
|
||||||
init: true
|
init: true
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|||||||
+85
-11
@@ -1,6 +1,8 @@
|
|||||||
# Web 2.0.0 Linux Docker 部署与更新
|
# Web 2 Linux Docker 部署与更新
|
||||||
|
|
||||||
本目录对应 Web 正式版本 `2.0.0`,源码入口 `main`;游戏资料基线为 `1.9.68`,桌面版保留 `1.2.0`。Docker 镜像以稳定 `v2.x.y` 标签流水线成功结果为准,以下 pull 命令仅在对应镜像已发布且可访问后可用。在线更新依赖对应 GitHub Release 条目;仅有 merge/tag 时可能仍显示“暂无正式版”,不会安装旧桌面 1.2.0。
|
以下更新示例以 `v2.0.1` 为目标;游戏资料基线为 `1.9.68`,桌面版保留 `1.2.0`。镜像流水线成功、Git tag 与 GitHub Release 是不同的发布步骤:在线更新必须等对应镜像及非草稿、非预发布的 Release 均发布后才能使用。私有仓库未获授权返回 404 属于访问失败,不代表没有版本;只有成功读取列表且没有稳定 2.x 时才显示“暂无正式版”。
|
||||||
|
|
||||||
|
已有部署首次接入私有在线更新时,按下文“已有宿主机首次初始化”操作。旧应用和旧更新器需要先配置私有发布认证,再由新版独立更新器在线拉取 `v2.0.1` 镜像。
|
||||||
|
|
||||||
## 容器与持久化
|
## 容器与持久化
|
||||||
|
|
||||||
@@ -17,7 +19,7 @@ sudo install -m 0600 -o root -g root deploy/web/image.env.example .image.env
|
|||||||
sudoedit .env .image.env
|
sudoedit .env .image.env
|
||||||
```
|
```
|
||||||
|
|
||||||
在 `.env` 填入独立的 `RANCH_WEB_PASSWORD`,这是 Web 管理密码,不是游戏密码;`.image.env` 示例默认 `RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.0`,需确认对应镜像已发布后再 pull。Compose 默认只发布到宿主机 `127.0.0.1:8765`,容器内监听 `0.0.0.0:8765` 并强制管理密码。使用域名反代时,同时配置 `RANCH_WEB_ALLOWED_HOSTS` 与 `RANCH_WEB_ALLOWED_ORIGINS`;TLS 入口设置 `RANCH_WEB_SECURE_COOKIE=true`。代理保留正确的 Host,写请求依赖来源校验。
|
在 `.env` 填入独立的 `RANCH_WEB_PASSWORD`,这是 Web 管理密码,不是游戏密码;`.image.env` 选择 `RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.1`,需确认对应镜像已发布后再 pull。Compose 默认只发布到宿主机 `127.0.0.1:8765`,容器内监听 `0.0.0.0:8765` 并强制管理密码。使用域名反代时,同时配置 `RANCH_WEB_ALLOWED_HOSTS` 与 `RANCH_WEB_ALLOWED_ORIGINS`;TLS 入口设置 `RANCH_WEB_SECURE_COOKIE=true`。代理保留正确的 Host,写请求依赖来源校验。
|
||||||
|
|
||||||
`/opt/ranch-web/data` 挂到容器 `/data`,包括账号、加密会话与密钥、配置、SQLite 统计和更新请求;独立于桌面数据。心跳控制目录独立只读挂到 `/run/ranch-updater`。使用 bind mount 的目录必须预先创建,Compose 不会悄悄创建 root 所有、容器无法写入的目录。默认容器用户 `10001:10001`,根文件系统只读,临时文件写到 `/tmp`。不要对现有账号目录重新初始化密钥。
|
`/opt/ranch-web/data` 挂到容器 `/data`,包括账号、加密会话与密钥、配置、SQLite 统计和更新请求;独立于桌面数据。心跳控制目录独立只读挂到 `/run/ranch-updater`。使用 bind mount 的目录必须预先创建,Compose 不会悄悄创建 root 所有、容器无法写入的目录。默认容器用户 `10001:10001`,根文件系统只读,临时文件写到 `/tmp`。不要对现有账号目录重新初始化密钥。
|
||||||
|
|
||||||
@@ -32,7 +34,7 @@ curl --fail http://127.0.0.1:8765/api/health
|
|||||||
|
|
||||||
脚本固定读取 `.env` 与 `.image.env`,相当于 `docker compose --project-name ranch-web --env-file .env --env-file .image.env --file compose.yaml ...`。更新器会持久化已选镜像到 `.image.env`,之后也应通过此脚本启动,以免误用默认镜像版本。
|
脚本固定读取 `.env` 与 `.image.env`,相当于 `docker compose --project-name ranch-web --env-file .env --env-file .image.env --file compose.yaml ...`。更新器会持久化已选镜像到 `.image.env`,之后也应通过此脚本启动,以免误用默认镜像版本。
|
||||||
|
|
||||||
GitHub 首次创建 GHCR 包可能为私有;仓库管理员可将 `myrzx_bot-web` 包设为 Public。私有包部署需操作者先在宿主机执行 `sudo docker login ghcr.io`,使用具备 `read:packages` 的凭据;不要把 registry 凭据交给 Web 容器。[GHCR 官方文档](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry)
|
私有 GHCR 包由用户先在宿主机为运行更新器的 root 用户配置一次 `docker login ghcr.io --password-stdin`,见下文。仓库与镜像可以保持私有;registry 凭据由宿主机 Docker 管理,不交给 Web 容器,也不从开发机迁移。
|
||||||
|
|
||||||
若仅在 Linux 上验证审核后的 `main` 源码,可在本地构建后启动;这不会发布镜像,也不要求远端已有对应镜像:
|
若仅在 Linux 上验证审核后的 `main` 源码,可在本地构建后启动;这不会发布镜像,也不要求远端已有对应镜像:
|
||||||
|
|
||||||
@@ -47,22 +49,92 @@ sudo sh deploy/web/compose.sh up -d --no-build --pull never --wait --wait-timeou
|
|||||||
|
|
||||||
Web 只读检查官方 GitHub Releases;默认只接受 `v2.MINOR.PATCH`,跳过草稿、预发布、1.x、3.x 和非法标签。数字不含前导零。`2.0.0.dev1 → v2.0.0` 可升级,`2.0.0 → v2.0.0` 不升级,拒绝降级。网络失败会明确显示检查失败,不使用虚构版本或下载脚本。
|
Web 只读检查官方 GitHub Releases;默认只接受 `v2.MINOR.PATCH`,跳过草稿、预发布、1.x、3.x 和非法标签。数字不含前导零。`2.0.0.dev1 → v2.0.0` 可升级,`2.0.0 → v2.0.0` 不升级,拒绝降级。网络失败会明确显示检查失败,不使用虚构版本或下载脚本。
|
||||||
|
|
||||||
先安装 root 持有的配置(示例的所有自动化开关默认关闭):
|
全新安装时,先安装 root 持有的配置,并准备独立更新器(示例的自动化开关默认关闭):
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
sudo install -m 0600 -o root -g root deploy/web/updater.example.toml /etc/ranch-web-updater.toml
|
sudo install -m 0600 -o root -g root deploy/web/updater.example.toml /etc/ranch-web-updater.toml
|
||||||
sudo python3 -B deploy/web/updater.py --config /etc/ranch-web-updater.toml --check
|
python3 -B tools/build_web_updater.py --output /tmp/updater.pyz
|
||||||
sudo python3 -B deploy/web/updater.py --config /etc/ranch-web-updater.toml --apply v2.0.0
|
sudo install -m 0644 -o root -g root /tmp/updater.pyz /opt/ranch-web/updater.pyz
|
||||||
|
python3 -B /opt/ranch-web/updater.pyz --version
|
||||||
```
|
```
|
||||||
|
|
||||||
|
也可从对应 Release 下载 `updater.pyz` 及 `SHA256SUMS`,核对后安装,宿主机不需要完整 Python 源码或 pip 依赖。构建器只打包 `__main__.py`、`updater.py`、`ranch_web/__init__.py`、`ranch_web/updates.py`,版本取构建时的 `ranch_web.__version__`;维护者升版后需重新生成资产。原有 `python3 -B deploy/web/updater.py ...` CLI 仍可运行,本文的 service 默认使用 `/opt/ranch-web/updater.pyz`。
|
||||||
|
|
||||||
|
### 已有宿主机首次初始化(用户自行执行)
|
||||||
|
|
||||||
|
前提是原有 `/opt/ranch-web` Compose 部署、数据目录及 `/etc/ranch-web-updater.toml` 均已存在,配置仍由 root 持有。保留原有数据和配置,不重新初始化密钥;数据目录由 `10001:10001` 持有。以下仅初始化在线更新器,不需要复制项目源码或 Compose。
|
||||||
|
|
||||||
|
1. 用户登录有私有仓库读取权限的 GitHub 账号,从 [v2.0.1 Release](https://github.com/attilanet/myrzx_bot/releases/tag/v2.0.1) 下载 `updater.pyz` 和 `SHA256SUMS`,放到宿主机临时目录。确认 Release 已发布且镜像可读取,在下载目录执行 `sha256sum -c SHA256SUMS` 后安装:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo install -m 0644 -o root -g root updater.pyz /opt/ranch-web/updater.pyz
|
||||||
|
python3 -B /opt/ranch-web/updater.pyz --help
|
||||||
|
python3 -B /opt/ranch-web/updater.pyz --version
|
||||||
|
python3 -B /opt/ranch-web/updater.pyz --config /etc/ranch-web-updater.toml --apply v2.0.1 --dry-run
|
||||||
|
```
|
||||||
|
|
||||||
|
`--version` 应显示 `ranch-web-updater 2.0.1`;`--help`、`--version` 和 `--dry-run` 均不联网、不读取 Token、不调用 Docker,dry-run 不创建文件。Python 需为 3.12+。
|
||||||
|
|
||||||
|
2. 用户创建只授予本仓库 Contents **read** 的 fine-grained GitHub Token,用交互终端输入;值不出现在 argv、shell 历史或更新状态中:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo python3 -B /opt/ranch-web/updater.pyz --config /etc/ranch-web-updater.toml --set-github-token
|
||||||
|
```
|
||||||
|
|
||||||
|
该命令只在本机原子保存 `<data_dir>/update-github-token`,不联网验证。默认宿主机路径 `/opt/ranch-web/data/update-github-token`,权限 `0600`、所有者 `10001:10001`;容器通过现有 `/data` 挂载读取同一文件 `/data/update-github-token`。文件为单个 ASCII Token(可带末尾换行、总长最多 4096 字节),拒绝软链接、硬链接及 POSIX 下非 `0600` 文件。更新器只向固定 `https://api.github.com/repos/attilanet/myrzx_bot/releases` 发送 Authorization,禁止重定向;错误、DTO 与日志不输出 Token。
|
||||||
|
|
||||||
|
默认文件不存在时继续匿名访问,兼容公共仓库。可显式设置环境变量 `RANCH_WEB_UPDATE_GITHUB_TOKEN_FILE` 为绝对**文件路径**,不可填 Token;显式路径缺失或文件不安全会失败,不会回退匿名。宿主机和容器的覆盖路径需各自可见,现有 Compose 不透传这个可选环境变量,通常应直接用默认共享文件。不要将 Token 写入 TOML、请求 JSON 或 Web 表单。[GitHub Releases 权限说明](https://docs.github.com/en/rest/releases/releases#list-releases)
|
||||||
|
|
||||||
|
3. GHCR 使用另一份凭据:有镜像读取权限的用户创建 PAT **classic**,授予 `read:packages`(组织要求时授权 SSO)。Releases 的 fine-grained Token 不保证能用于 Docker。以下 Bash 命令由用户在宿主机终端执行一次,Token 通过 stdin 传给 root 的 Docker,不放入命令参数:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo -v
|
||||||
|
read -r -p 'GitHub username: ' ranch_ghcr_user
|
||||||
|
read -r -s -p 'GHCR read:packages PAT (hidden): ' ranch_ghcr_pat
|
||||||
|
printf '\n'
|
||||||
|
printf '%s' "$ranch_ghcr_pat" | sudo docker --context default login ghcr.io --username "$ranch_ghcr_user" --password-stdin
|
||||||
|
unset ranch_ghcr_pat ranch_ghcr_user
|
||||||
|
```
|
||||||
|
|
||||||
|
Docker 保存的宿主机登录配置供更新器拉镜像使用;不要复制开发机的 Git/registry 凭据,也不要把 Docker 凭据放进 GitHub Token 文件或 Web 容器。[GHCR 官方认证说明](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry)
|
||||||
|
|
||||||
|
4. 使用新包先检查再由用户明确发起在线更新:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo python3 -B /opt/ranch-web/updater.pyz --config /etc/ranch-web-updater.toml --check
|
||||||
|
sudo python3 -B /opt/ranch-web/updater.pyz --config /etc/ranch-web-updater.toml --apply v2.0.1
|
||||||
|
```
|
||||||
|
|
||||||
|
新更新器会独立复验官方 Release、严格版本递增、固定官方镜像,并执行原有备份、健康检查与失败回滚。旧 Web 即使尚不能查询私有发布,此命令仍可启动更新;更新到含新私有支持的镜像后,Web 的检查/请求才会读取共享 Token。只有 tag 或镜像、尚无 2.x Release 时仍不能更新;不要把旧页面的匿名 404 当成“已是最新”。
|
||||||
|
|
||||||
|
5. 让原有 systemd timer 执行新包。用户运行 `sudo systemctl edit ranch-web-updater.service`,只添加一次覆盖:
|
||||||
|
|
||||||
|
```ini
|
||||||
|
[Service]
|
||||||
|
ExecStart=
|
||||||
|
ExecStart=/usr/bin/python3 -B /opt/ranch-web/updater.pyz --config /etc/ranch-web-updater.toml --run
|
||||||
|
```
|
||||||
|
|
||||||
|
随后执行:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo systemctl daemon-reload
|
||||||
|
sudo systemctl enable --now ranch-web-updater.timer
|
||||||
|
sudo systemctl start ranch-web-updater.service
|
||||||
|
```
|
||||||
|
|
||||||
|
原有 service 的 root、目录保护和 Docker 登录访问保持有效。新包成功初始化后,未来 Web 请求及 timer 都使用相同私有查询逻辑;未来要升级独立更新器本身时,仍由用户下载并替换受信任的 `updater.pyz`。`auto_apply=false` 继续默认关闭,允许 Web 按钮需另外显式设置 `accept_web_requests=true`。
|
||||||
|
|
||||||
`--apply` 不传版本时选比运行中版本更新的最新稳定 2.x。手动操作和定时任务共享排他锁。执行器固定官方仓库及镜像地址,重新查询 Releases 验证来源;Web 即使伪造 `update-request.json` 也不能指定命令、下载地址、路径或第三方镜像。
|
`--apply` 不传版本时选比运行中版本更新的最新稳定 2.x。手动操作和定时任务共享排他锁。执行器固定官方仓库及镜像地址,重新查询 Releases 验证来源;Web 即使伪造 `update-request.json` 也不能指定命令、下载地址、路径或第三方镜像。
|
||||||
|
|
||||||
执行顺序:旧容器运行期间先 `compose pull --policy always web`;拉取失败则保持旧服务。然后停服,确认所有容器写入停止,为完整数据目录创建一致的快照(包含 SQLite 文件及 WAL、加密密钥);最后用新镜像 `compose up -d --no-build --pull never --wait --wait-timeout 180 web`。镜像已有 `/api/health` healthcheck,检查成功后才记录更新完成。
|
执行顺序:旧容器运行期间先 `compose pull --policy always web`;拉取失败则保持旧服务。然后停服,确认所有容器写入停止,为完整数据目录创建一致的快照(包含 SQLite 文件及 WAL、加密密钥);最后用新镜像 `compose up -d --no-build --pull never --wait --wait-timeout 180 web`。镜像已有 `/api/health` healthcheck,检查成功后才记录更新完成。
|
||||||
|
|
||||||
新服务健康失败时,更新器停止失败容器、恢复更新前数据、用旧镜像的准确本地 image ID 启动并检查健康。失败版本数据移入 `failed-data/`,快照保存在 `backups/`,均不自动删除。快照文件权限为 0600、备份目录 0700;不会打印账号数据、密钥、Compose 环境或容器日志。回滚也失败时保留恢复事务,下一次更新器运行会先恢复,需操作者检查服务状态。镜像拉取和停机发生在宿主机;Web 容器没有 Docker socket。
|
新服务健康失败时,更新器停止失败容器、恢复更新前数据、用旧镜像的准确本地 image ID 启动并检查健康。失败版本数据移入 `failed-data/`,快照保存在 `backups/`,均不自动删除。快照包含默认共享 Token 文件以及应用密钥,快照文件权限为 0600、备份目录 0700;不会打印账号数据、密钥、Compose 环境或容器日志。回滚也失败时保留恢复事务,下一次更新器运行会先恢复,需操作者检查服务状态。镜像拉取和停机发生在宿主机;Web 容器没有 Docker socket。
|
||||||
|
|
||||||
## 定时检查、Web 按钮与自动更新
|
## 定时检查、Web 按钮与自动更新
|
||||||
|
|
||||||
|
全新部署确认已按上文生成或下载安装 `/opt/ranch-web/updater.pyz` 后,再安装以下 service;已有部署使用上文的一次性 override。
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
sudo install -m 0644 deploy/web/ranch-web-updater.service /etc/systemd/system/
|
sudo install -m 0644 deploy/web/ranch-web-updater.service /etc/systemd/system/
|
||||||
sudo install -m 0644 deploy/web/ranch-web-updater.timer /etc/systemd/system/
|
sudo install -m 0644 deploy/web/ranch-web-updater.timer /etc/systemd/system/
|
||||||
@@ -79,13 +151,15 @@ Windows 或未安装执行器的 Docker 部署仍能检查版本,但按钮会
|
|||||||
|
|
||||||
## CI 与验证范围
|
## CI 与验证范围
|
||||||
|
|
||||||
[web-image.yml](../../.github/workflows/web-image.yml) 仅对官方仓库的严格稳定 `v2.x.y` tag 推送 `ghcr.io/attilanet/myrzx_bot-web:v2.x.y`;校验 `ranch_web.__version__` 必须与 tag 一致,不能只改变镜像 label。PR 与手动运行只测试、构建,不推送。开发分支 push 不触发正式镜像发布,也没有 `latest` 滚动升级通道。CI 规划在无外网容器中检查 healthcheck、非 root 数据写权限、无 Qt 和正常停止;本轮没有触发 CI 或发布。
|
[web-image.yml](../../.github/workflows/web-image.yml) 仅对官方仓库的严格稳定 `v2.x.y` tag 推送 `ghcr.io/attilanet/myrzx_bot-web:v2.x.y`;校验 `ranch_web.__version__` 必须与 tag 一致,不能只改变镜像 label。PR 与手动运行只测试、构建,不推送。开发分支 push 不触发正式镜像发布,也没有 `latest` 滚动升级通道。CI 执行更新器、私有凭据和独立包回归,并在无外网容器中检查 healthcheck、非 root 数据写权限、无 Qt 和正常停止;镜像发布状态以对应 tag 的工作流结果为准。
|
||||||
|
|
||||||
本机 Windows 没有 Docker,已能执行的验证是离线单元测试、临时数据的备份/回滚测试、启动脚本语法与配置静态核对、更新器 dry-run;不代表 Linux/Docker 实机验证通过。可在无 Docker 的机器上只打印计划(不联网、不写文件):
|
本机 Windows 没有 Docker,已能执行的验证是离线单元测试、临时数据的备份/回滚测试、启动脚本语法与配置静态核对、更新器 dry-run;不代表 Linux/Docker 实机验证通过。可在无 Docker 的机器上只打印计划(不联网、不写文件):
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
python -B deploy/web/updater.py --config deploy/web/updater.example.toml --apply v2.0.0 --dry-run
|
python -B tools/build_web_updater.py --output test-artifacts/updater.pyz
|
||||||
python -B -m unittest ranch_web.tests.test_updates ranch_web.tests.test_web_updater -v
|
python -B test-artifacts/updater.pyz --version
|
||||||
|
python -B test-artifacts/updater.pyz --config deploy/web/updater.example.toml --apply v2.0.1 --dry-run
|
||||||
|
python -B -m unittest ranch_web.tests.test_updates ranch_web.tests.test_web_updater ranch_web.tests.test_private_updates ranch_web.tests.test_web_updater_package -v
|
||||||
```
|
```
|
||||||
|
|
||||||
命令参数依据 [Compose up](https://docs.docker.com/reference/cli/docker/compose/up/)、[Compose pull](https://docs.docker.com/reference/cli/docker/compose/pull/);发布权限与 GHCR 认证依据 [GitHub 镜像发布流程](https://docs.github.com/en/actions/tutorials/publish-packages/publish-docker-images)。检查使用 [GitHub Releases 列表 API](https://docs.github.com/en/rest/releases/releases#list-releases),不依赖可能指向桌面版的 `/latest`。
|
命令参数依据 [Compose up](https://docs.docker.com/reference/cli/docker/compose/up/)、[Compose pull](https://docs.docker.com/reference/cli/docker/compose/pull/);发布权限与 GHCR 认证依据 [GitHub 镜像发布流程](https://docs.github.com/en/actions/tutorials/publish-packages/publish-docker-images)。检查使用 [GitHub Releases 列表 API](https://docs.github.com/en/rest/releases/releases#list-releases),不依赖可能指向桌面版的 `/latest`。
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Web 2 更新接口(协议 1)
|
# Web 2 更新接口(协议 1)
|
||||||
|
|
||||||
供 API、前端、宿主机更新器与 Main 集成。`ranch_web.updates.UpdateService(root, current_version)` 只依赖 Python 标准库;构造和 `status()` 不联网,`check()` 才访问固定官方 GitHub Releases,`request_update(version=None)` 仅提交文件请求。API 可在线程池中调用检查,不能在事件循环里等待网络。
|
供 API、前端、宿主机更新器与 Main 集成。`ranch_web.updates.UpdateService(root, current_version)` 只依赖 Python 标准库;构造和 `status()` 不联网,`check()` 访问固定官方 GitHub Releases,`request_update(version=None)` 再次联网验证后仅提交文件请求。宿主机 `HostUpdater.apply()` 独立再次验证发布。API 可在线程池中调用检查,不能在事件循环里等待网络。
|
||||||
|
|
||||||
- 固定仓库:`attilanet/myrzx_bot`;固定镜像:`ghcr.io/attilanet/myrzx_bot-web`。
|
- 固定仓库:`attilanet/myrzx_bot`;固定镜像:`ghcr.io/attilanet/myrzx_bot-web`。
|
||||||
- 唯一可选发布 tag:`v2.MINOR.PATCH`(十进制、不许前导零、无任何后缀)。草稿、预发布、1.x、3.x、dev 分支全部跳过;按版本数值比较,不信任 GitHub latest 排序。
|
- 唯一可选发布 tag:`v2.MINOR.PATCH`(十进制、不许前导零、无任何后缀)。草稿、预发布、1.x、3.x、dev 分支全部跳过;按版本数值比较,不信任 GitHub latest 排序。
|
||||||
@@ -9,6 +9,12 @@
|
|||||||
- 心跳由宿主机定时任务写入,含 `protocol=1, executor_id, enabled, auto_apply, heartbeat_at, expires_at`。执行器配置默认 `accept_web_requests=false, auto_apply=false`,操作者必须显式启用 Web 请求。心跳有效期 15 分钟、timer 每 5 分钟运行。
|
- 心跳由宿主机定时任务写入,含 `protocol=1, executor_id, enabled, auto_apply, heartbeat_at, expires_at`。执行器配置默认 `accept_web_requests=false, auto_apply=false`,操作者必须显式启用 Web 请求。心跳有效期 15 分钟、timer 每 5 分钟运行。
|
||||||
- `update-request.json` 仅含 `protocol=1, request_id`(32 位小写十六进制)、`executor_id`、`version`(官方 tag)、`requested_at`(UTC ISO 8601)。禁止镜像地址、命令、下载地址或路径。宿主机再次联网验证 tag、版本单调递增并去重;Web 写文件不等于部署成功。
|
- `update-request.json` 仅含 `protocol=1, request_id`(32 位小写十六进制)、`executor_id`、`version`(官方 tag)、`requested_at`(UTC ISO 8601)。禁止镜像地址、命令、下载地址或路径。宿主机再次联网验证 tag、版本单调递增并去重;Web 写文件不等于部署成功。
|
||||||
|
|
||||||
|
私有发布凭据只来自服务端 `<root>/update-github-token`,宿主机使用配置中的 `data_dir`;Docker 默认通过既有挂载共享同一文件。POSIX 权限必须为 `0600`,普通文件、非软/硬链接、最多 4096 字节;部署所有者为 `10001:10001`。可选 `RANCH_WEB_UPDATE_GITHUB_TOKEN_FILE` 仅接受绝对文件路径,显式无效路径直接失败。未提供覆盖且默认文件缺失时保持匿名公共访问;不读取 Git 凭据、不接收原始 Token 环境变量/TOML/Web 参数。低层 `github_releases(data_dir=None)` 保留无参数公共调用形式,服务与宿主机均传入自己的数据目录,每次查询重新读文件。
|
||||||
|
|
||||||
|
GitHub Authorization 只发往固定 `https://api.github.com/repos/attilanet/myrzx_bot/releases`,不跟随任何重定向。`401/403/404` 为 `check_failed`,固定 `message/error` 提醒检查私有仓库访问权限;凭据文件失效同样返回 `check_failed` 与固定文件权限提示,不能当作 `no_release`。本地 `update-check.json` 可记录白名单 `failure` 代码 `access_denied/token_file_invalid/check_failed`;公共 DTO 字段和协议号不变,不返回 Token、Token 路径、响应原文或原始异常。`request_update` 与宿主机复验遇到访问失败则拒绝请求/更新,保持原服务。
|
||||||
|
|
||||||
|
GitHub Releases 可使用限定仓库、Contents read 的 fine-grained Token;GHCR 由用户另用 PAT classic 的 `read:packages` 权限通过 `docker login --password-stdin` 配置。两份凭据分别管理,不假定 fine-grained Token 能拉私有镜像。独立 `updater.pyz` 构建/运行 CLI 及已有宿主机的一次性初始化、systemd override 见 [README.md](README.md);旧应用必须先经用户安装新宿主机更新器并升级镜像,才具有私有 Web 更新能力。
|
||||||
|
|
||||||
三个方法返回同一公共 DTO,示例:
|
三个方法返回同一公共 DTO,示例:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
@@ -36,7 +42,7 @@
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
`status`:`unchecked / no_release / up_to_date / available / check_failed / unavailable / pending / applying / succeeded / rolled_back / failed`。无 2.x 正式版时 `latest_version=null, available=false, status=no_release`,不可退到桌面 1.2。
|
`status`:`unchecked / no_release / up_to_date / available / check_failed / unavailable / pending / applying / succeeded / rolled_back / failed`。仅成功读取列表且无 2.x 正式版时 `latest_version=null, available=false, status=no_release`,不可退到桌面 1.2。镜像构建成功或存在 tag 均不能替代正式 Release。
|
||||||
|
|
||||||
提交成功返回 `status=pending`,`request={request_id,version,requested_at,status:"pending"}`;前端应显示“等待宿主机”,定时 GET 状态。宿主机结果 `host_status={request_id,status,version,updated_at,error}`,错误是固定脱敏说明,不含原始异常、文件路径或子进程输出。`request_update` 在缺少执行器时返回 `status=unavailable` 和具体 `message`;非法/非官方/倒退版本抛 `ValueError`,API 映射 400。API `/apply` 的 HTTP 接受响应不应宣称已经升级;更新完成由宿主机健康检查决定。
|
提交成功返回 `status=pending`,`request={request_id,version,requested_at,status:"pending"}`;前端应显示“等待宿主机”,定时 GET 状态。宿主机结果 `host_status={request_id,status,version,updated_at,error}`,错误是固定脱敏说明,不含原始异常、文件路径或子进程输出。`request_update` 在缺少执行器时返回 `status=unavailable` 和具体 `message`;非法/非官方/倒退版本抛 `ValueError`,API 映射 400。API `/apply` 的 HTTP 接受响应不应宣称已经升级;更新完成由宿主机健康检查决定。
|
||||||
|
|
||||||
|
|||||||
@@ -1,2 +1,2 @@
|
|||||||
# Pull only after the v2.0.0 image publishing workflow succeeds and the image is available.
|
# Pull only after the v2.0.1 image publishing workflow succeeds and the image is available.
|
||||||
RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.0
|
RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.1
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ Type=oneshot
|
|||||||
User=root
|
User=root
|
||||||
Group=root
|
Group=root
|
||||||
WorkingDirectory=/opt/ranch-web
|
WorkingDirectory=/opt/ranch-web
|
||||||
ExecStart=/usr/bin/python3 -B /opt/ranch-web/deploy/web/updater.py --config /etc/ranch-web-updater.toml --run
|
ExecStart=/usr/bin/python3 -B /opt/ranch-web/updater.pyz --config /etc/ranch-web-updater.toml --run
|
||||||
TimeoutStartSec=30min
|
TimeoutStartSec=30min
|
||||||
TimeoutStopSec=180s
|
TimeoutStopSec=180s
|
||||||
UMask=0077
|
UMask=0077
|
||||||
|
|||||||
@@ -1,6 +1,11 @@
|
|||||||
# Root-owned operator configuration. Never put this file in /data.
|
# Root-owned operator configuration. Never put this file in /data.
|
||||||
project_dir = "/opt/ranch-web"
|
project_dir = "/opt/ranch-web"
|
||||||
data_dir = "/opt/ranch-web/data"
|
data_dir = "/opt/ranch-web/data"
|
||||||
|
# Optional private GitHub releases: data_dir/update-github-token, mode 0600,
|
||||||
|
# owned by 10001:10001 (same file is /data/update-github-token in the app).
|
||||||
|
# Set with: sudo python3 -B /opt/ranch-web/updater.pyz --config /etc/ranch-web-updater.toml --set-github-token
|
||||||
|
# Optional ENV RANCH_WEB_UPDATE_GITHUB_TOKEN_FILE is an absolute PATH, not a token.
|
||||||
|
# Private GHCR access is configured separately by the operator via docker login --password-stdin.
|
||||||
control_dir = "/opt/ranch-web/updater-control"
|
control_dir = "/opt/ranch-web/updater-control"
|
||||||
backup_dir = "/opt/ranch-web/backups"
|
backup_dir = "/opt/ranch-web/backups"
|
||||||
failed_data_dir = "/opt/ranch-web/failed-data"
|
failed_data_dir = "/opt/ranch-web/failed-data"
|
||||||
|
|||||||
+58
-14
@@ -2,7 +2,8 @@
|
|||||||
"""Root-owned Linux host updater; no shell, Docker socket, or code in Web.
|
"""Root-owned Linux host updater; no shell, Docker socket, or code in Web.
|
||||||
|
|
||||||
Use --check for notification, --apply [v2.x.y] for an operator update, or
|
Use --check for notification, --apply [v2.x.y] for an operator update, or
|
||||||
--run from the timer. --dry-run never contacts GitHub or Docker or writes files.
|
--run from the timer. --set-github-token prompts for a local credential file.
|
||||||
|
--dry-run never contacts GitHub or Docker or writes files.
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -10,6 +11,7 @@ import argparse
|
|||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
from dataclasses import dataclass, fields
|
from dataclasses import dataclass, fields
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
|
import getpass
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
from pathlib import Path, PurePosixPath
|
from pathlib import Path, PurePosixPath
|
||||||
@@ -23,10 +25,12 @@ import tarfile
|
|||||||
import tempfile
|
import tempfile
|
||||||
import tomllib
|
import tomllib
|
||||||
import uuid
|
import uuid
|
||||||
|
import warnings
|
||||||
|
|
||||||
# This import is standard-library-only; no FastAPI/Qt installation on the host.
|
# This import is standard-library-only; no FastAPI/Qt installation on the host.
|
||||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
if __name__ == "__main__":
|
||||||
from ranch_web import updates # noqa: E402
|
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||||
|
from ranch_web import __version__, updates # noqa: E402
|
||||||
|
|
||||||
_DIGEST = re.compile(r"sha256:[0-9a-f]{64}", re.ASCII)
|
_DIGEST = re.compile(r"sha256:[0-9a-f]{64}", re.ASCII)
|
||||||
_CONTAINER = re.compile(r"[0-9a-f]{12,64}", re.ASCII)
|
_CONTAINER = re.compile(r"[0-9a-f]{12,64}", re.ASCII)
|
||||||
@@ -323,7 +327,9 @@ class HostUpdater:
|
|||||||
if not old["running"]:
|
if not old["running"]:
|
||||||
raise UpdaterError("现有服务未运行,请先由操作者处理。")
|
raise UpdaterError("现有服务未运行,请先由操作者处理。")
|
||||||
try:
|
try:
|
||||||
tags = updates.official_tags(updates.github_releases())
|
tags = updates.official_tags(updates.github_releases(self.config.data_dir))
|
||||||
|
except updates.GitHubReleaseError as error:
|
||||||
|
raise UpdaterError(str(error)) from None
|
||||||
except Exception:
|
except Exception:
|
||||||
raise UpdaterError("无法独立验证官方 GitHub 正式发布,保留现有服务。") from None
|
raise UpdaterError("无法独立验证官方 GitHub 正式发布,保留现有服务。") from None
|
||||||
target = version or (max(tags, key=updates.stable_version) if tags else None)
|
target = version or (max(tags, key=updates.stable_version) if tags else None)
|
||||||
@@ -436,19 +442,54 @@ def interrupt_update(signum, frame):
|
|||||||
raise InterruptedError("宿主机正在停止更新任务。")
|
raise InterruptedError("宿主机正在停止更新任务。")
|
||||||
|
|
||||||
|
|
||||||
|
def set_github_token(config):
|
||||||
|
"""Operator-only local setup: no argv secret, network, or credential discovery."""
|
||||||
|
try:
|
||||||
|
# getpass must not fall back to echoed input on a non-interactive console.
|
||||||
|
with warnings.catch_warnings():
|
||||||
|
warnings.simplefilter("error", getpass.GetPassWarning)
|
||||||
|
token = getpass.getpass("GitHub read-only release token (hidden): ")
|
||||||
|
token = updates._validate_token((token + "\n").encode("ascii"))
|
||||||
|
path = updates.github_token_path(config.data_dir)
|
||||||
|
if path.is_symlink():
|
||||||
|
raise updates.GitHubReleaseError("token_file_invalid")
|
||||||
|
descriptor, temporary = tempfile.mkstemp(prefix=".update-token-", dir=path.parent)
|
||||||
|
try:
|
||||||
|
with os.fdopen(descriptor, "w", encoding="ascii", newline="\n") as stream:
|
||||||
|
os.chmod(temporary, 0o600)
|
||||||
|
if hasattr(os, "chown"):
|
||||||
|
os.chown(temporary, 10001, 10001)
|
||||||
|
stream.write(token + "\n")
|
||||||
|
stream.flush()
|
||||||
|
os.fsync(stream.fileno())
|
||||||
|
os.replace(temporary, path)
|
||||||
|
finally:
|
||||||
|
if os.path.exists(temporary):
|
||||||
|
os.unlink(temporary)
|
||||||
|
except (OSError, UnicodeError, updates.GitHubReleaseError, EOFError, getpass.GetPassWarning, KeyboardInterrupt):
|
||||||
|
raise UpdaterError("GitHub Token 未保存;请使用交互终端并检查服务端文件与数据目录权限。") from None
|
||||||
|
return {"status": "configured", "message": "GitHub 只读 Token 已保存为 0600 文件;尚未联网验证权限。"}
|
||||||
|
|
||||||
|
|
||||||
def main(argv=None):
|
def main(argv=None):
|
||||||
parser = argparse.ArgumentParser(description=__doc__)
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("--version", action="version", version=f"ranch-web-updater {__version__}")
|
||||||
parser.add_argument("--config", default="/etc/ranch-web-updater.toml")
|
parser.add_argument("--config", default="/etc/ranch-web-updater.toml")
|
||||||
mode = parser.add_mutually_exclusive_group(required=True)
|
mode = parser.add_mutually_exclusive_group(required=True)
|
||||||
mode.add_argument("--check", action="store_true")
|
mode.add_argument("--check", action="store_true")
|
||||||
mode.add_argument("--apply", nargs="?", const="", metavar="v2.x.y")
|
mode.add_argument("--apply", nargs="?", const="", metavar="v2.x.y")
|
||||||
mode.add_argument("--run", action="store_true")
|
mode.add_argument("--run", action="store_true")
|
||||||
|
mode.add_argument("--set-github-token", action="store_true", help="interactively save a server-side token file")
|
||||||
parser.add_argument("--dry-run", action="store_true")
|
parser.add_argument("--dry-run", action="store_true")
|
||||||
args = parser.parse_args(argv)
|
args = parser.parse_args(argv)
|
||||||
try:
|
try:
|
||||||
config = Config.load(args.config, dry_run=args.dry_run)
|
config = Config.load(args.config, dry_run=args.dry_run)
|
||||||
if args.dry_run:
|
if args.dry_run:
|
||||||
result = dry_run(config, "check" if args.check else "run" if args.run else "apply", args.apply)
|
if args.set_github_token:
|
||||||
|
result = {"dry_run": True, "mode": "set-github-token",
|
||||||
|
"steps": ["prompt for read-only GitHub token; atomically save 0600 file owned by UID/GID 10001"]}
|
||||||
|
else:
|
||||||
|
result = dry_run(config, "check" if args.check else "run" if args.run else "apply", args.apply)
|
||||||
else:
|
else:
|
||||||
if sys.platform != "linux" or os.geteuid() != 0:
|
if sys.platform != "linux" or os.geteuid() != 0:
|
||||||
raise UpdaterError("执行更新需要 Linux 宿主机上的受控 root 服务;Windows 仅支持 dry-run。")
|
raise UpdaterError("执行更新需要 Linux 宿主机上的受控 root 服务;Windows 仅支持 dry-run。")
|
||||||
@@ -467,16 +508,19 @@ def main(argv=None):
|
|||||||
raise UpdaterError("执行器控制目录必须由 root 持有且禁止其他用户写入。")
|
raise UpdaterError("执行器控制目录必须由 root 持有且禁止其他用户写入。")
|
||||||
signal.signal(signal.SIGTERM, interrupt_update)
|
signal.signal(signal.SIGTERM, interrupt_update)
|
||||||
with exclusive(config):
|
with exclusive(config):
|
||||||
updater = HostUpdater(config)
|
if args.set_github_token:
|
||||||
recovery = updater.recover()
|
result = set_github_token(config)
|
||||||
if recovery:
|
|
||||||
result = recovery
|
|
||||||
elif args.check:
|
|
||||||
result = updater.check(updater.docker.inspect_service()["version"])
|
|
||||||
elif args.run:
|
|
||||||
result = updater.run()
|
|
||||||
else:
|
else:
|
||||||
result = updater.apply(args.apply or None)
|
updater = HostUpdater(config)
|
||||||
|
recovery = updater.recover()
|
||||||
|
if recovery:
|
||||||
|
result = recovery
|
||||||
|
elif args.check:
|
||||||
|
result = updater.check(updater.docker.inspect_service()["version"])
|
||||||
|
elif args.run:
|
||||||
|
result = updater.run()
|
||||||
|
else:
|
||||||
|
result = updater.apply(args.apply or None)
|
||||||
print(json.dumps(result, ensure_ascii=False, indent=2))
|
print(json.dumps(result, ensure_ascii=False, indent=2))
|
||||||
return int(result.get("status") in {"failed", "check_failed", "rolled_back"})
|
return int(result.get("status") in {"failed", "check_failed", "rolled_back"})
|
||||||
except UpdaterError as error:
|
except UpdaterError as error:
|
||||||
|
|||||||
@@ -33,19 +33,42 @@ def sdk_headers(device):
|
|||||||
|
|
||||||
|
|
||||||
class PasswordLogin:
|
class PasswordLogin:
|
||||||
def __init__(self, catalog, device, *, sdk_url=SDK_LOGIN_URL, center_url=None, channel="DYD", trace=None):
|
def __init__(self, catalog, device, *, sdk_url=SDK_LOGIN_URL, center_url=None, channel="DYD", trace=None,
|
||||||
|
cancel_guard=None):
|
||||||
self.catalog, self.device = catalog, device
|
self.catalog, self.device = catalog, device
|
||||||
self.trace = trace
|
self.trace = trace
|
||||||
self.sdk_url = sdk_url
|
self.sdk_url = sdk_url
|
||||||
self.center_url = center_url or catalog.data["server_info"]["ANDROID"].get(channel, DEFAULT_CENTER)
|
self.center_url = center_url or catalog.data["server_info"]["ANDROID"].get(channel, DEFAULT_CENTER)
|
||||||
self.channel = channel
|
self.channel = channel
|
||||||
|
self.cancel_guard = cancel_guard
|
||||||
|
|
||||||
|
def _check_cancel(self):
|
||||||
|
if self.cancel_guard is not None:
|
||||||
|
self.cancel_guard()
|
||||||
|
|
||||||
|
def _guard_http(self, http):
|
||||||
|
if self.cancel_guard is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
def guarded(method):
|
||||||
|
def dispatch(*args, **kwargs):
|
||||||
|
self._check_cancel()
|
||||||
|
return method(*args, **kwargs)
|
||||||
|
return dispatch
|
||||||
|
|
||||||
|
# Requests may spend time encoding/preparing after TraceLog.begin.
|
||||||
|
# Guard send too, including redirected SDK/center requests.
|
||||||
|
for name in ("post", "send"):
|
||||||
|
setattr(http, name, guarded(getattr(http, name)))
|
||||||
|
|
||||||
def authenticate(self, account, password):
|
def authenticate(self, account, password):
|
||||||
|
self._check_cancel()
|
||||||
if not account.strip() or not password:
|
if not account.strip() or not password:
|
||||||
raise ApiError("请填写账号和密码")
|
raise ApiError("请填写账号和密码")
|
||||||
# Cookies remain in this process and are discarded on closing the SDK session.
|
# Cookies remain in this process and are discarded on closing the SDK session.
|
||||||
with requests.Session() as http:
|
with requests.Session() as http:
|
||||||
http.trust_env = False
|
http.trust_env = False
|
||||||
|
self._guard_http(http)
|
||||||
payload = {"account": account.strip(), "password": password}
|
payload = {"account": account.strip(), "password": password}
|
||||||
params = {"versionCode": "1.0.1", "buildNumber": "2016122900", "appChannel": "taptap"}
|
params = {"versionCode": "1.0.1", "buildNumber": "2016122900", "appChannel": "taptap"}
|
||||||
headers = sdk_headers(self.device)
|
headers = sdk_headers(self.device)
|
||||||
@@ -55,6 +78,7 @@ class PasswordLogin:
|
|||||||
try:
|
try:
|
||||||
response = http.post(self.sdk_url, data=payload, params=params,
|
response = http.post(self.sdk_url, data=payload, params=params,
|
||||||
headers=headers, timeout=(5, 15), allow_redirects=False)
|
headers=headers, timeout=(5, 15), allow_redirects=False)
|
||||||
|
self._check_cancel()
|
||||||
try:
|
try:
|
||||||
data = response.json()
|
data = response.json()
|
||||||
except ValueError as error:
|
except ValueError as error:
|
||||||
@@ -100,8 +124,11 @@ class PasswordLogin:
|
|||||||
uid, sdk_token = str(users[0]["userId"]), str(users[0]["token"])
|
uid, sdk_token = str(users[0]["userId"]), str(users[0]["token"])
|
||||||
client = Client(Session(key=self.catalog.data["game_setting"].get("xyz1", Session().key)), trace=self.trace)
|
client = Client(Session(key=self.catalog.data["game_setting"].get("xyz1", Session().key)), trace=self.trace)
|
||||||
try:
|
try:
|
||||||
|
self._guard_http(client.http)
|
||||||
|
self._check_cancel()
|
||||||
game = client.sdk_login(self.center_url, uid, sdk_token, self.channel, "ANDROID", self.device,
|
game = client.sdk_login(self.center_url, uid, sdk_token, self.channel, "ANDROID", self.device,
|
||||||
tj_channel=self.catalog.data.get("tjchannel", {}).get("tjchannel", "unknow"))
|
tj_channel=self.catalog.data.get("tjchannel", {}).get("tjchannel", "unknow"))
|
||||||
|
self._check_cancel()
|
||||||
except Exception:
|
except Exception:
|
||||||
client.close()
|
client.close()
|
||||||
raise
|
raise
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# 牧羊人之心牧场助手 · Web 2.0.0
|
# 牧羊人之心牧场助手 · Web 2.0.1
|
||||||
|
|
||||||
## 产品约束
|
## 产品约束
|
||||||
|
|
||||||
把现有桌面助手的功能和操作结构迁移至单管理员 Web 工作台。桌面版是页面顺序、信息密度、业务名称、保护条件与交互的依据,保留桌面兼容。Web 正式版本为 `2.0.0`,源码入口 `main`,游戏数据版本 `1.9.68`;桌面正式版保留 `1.2.0`。启动与配置见 [运行说明](README.md),Docker 与更新条件见 [部署说明](../deploy/web/README.md)。
|
把现有桌面助手的功能和操作结构迁移至单管理员 Web 工作台。桌面版是页面顺序、信息密度、业务名称、保护条件与交互的依据,保留桌面兼容。本轮 Web 发布目标为 `2.0.1`,源码入口 `main`,游戏数据版本 `1.9.68`;桌面正式版保留 `1.2.0`。启动与配置见 [运行说明](README.md),Docker 与更新条件见 [部署说明](../deploy/web/README.md)。
|
||||||
|
|
||||||
使用者在 Windows 本机配置、验证,随后可在 Linux Docker 常驻运行。多个浏览器访问同一个管理员工作台;账号互相隔离,各账号串行执行,账号之间可以并行。
|
使用者在 Windows 本机配置、验证,随后可在 Linux Docker 常驻运行。多个浏览器访问同一个管理员工作台;账号互相隔离,各账号串行执行,账号之间可以并行。
|
||||||
|
|
||||||
@@ -17,12 +17,14 @@
|
|||||||
## 核心操作
|
## 核心操作
|
||||||
|
|
||||||
- 账号密码登录后选择区服进入;恢复已保存会话;退出与清除登录记录。游戏凭据仅交给同源服务端,不进入浏览器持久存储或 URL。
|
- 账号密码登录后选择区服进入;恢复已保存会话;退出与清除登录记录。游戏凭据仅交给同源服务端,不进入浏览器持久存储或 URL。
|
||||||
|
- 手动选服、恢复会话和自动重登成功读取角色后,均默认开启策略,自动执行已配置且已勾选的功能,可在顶部停止;不改变各子功能的勾选。获取区服候选及失败候选不视为登录成功,界面以服务端在线与运行状态为准。导入配置只替换规则并停止执行,下次成功登录仍自动开启;服务重启后未成功登录时不直接执行。
|
||||||
- 配置通过中文 schema 生成原生控件;逐蛋孵化/补货规则、物品赠礼保留量、逐魔物培养目标、关卡规则等直接在对应页面编辑。自动保存显示待保存、保存中、失败与已保存状态。
|
- 配置通过中文 schema 生成原生控件;逐蛋孵化/补货规则、物品赠礼保留量、逐魔物培养目标、关卡规则等直接在对应页面编辑。自动保存显示待保存、保存中、失败与已保存状态。
|
||||||
- 培育室扩建、牧场锁定/解锁、批量派遣/喂养、上下文菜单和费用二次确认沿用核心行为。切换功能页只读取视图,不触发游戏写操作。
|
- 培育室扩建、牧场锁定/解锁、批量派遣/喂养、上下文菜单和费用二次确认沿用核心行为。切换功能页只读取视图,不触发游戏写操作。
|
||||||
- 主线默认当前主线,可切换筛选。地图按地区默认折叠,展示普通关卡、矿洞、难度、次数和工具库存。探险支持队员手选/自动与完成后自动领奖说明。
|
- 主线默认当前主线,可切换筛选。地图按地区默认折叠,展示普通关卡、矿洞、难度、次数和工具库存。探险支持队员手选/自动与完成后自动领奖说明。
|
||||||
- 数据分析用真实 DTO 绘制 SVG 条形图,保留来源筛选、体力效率、样本和不确定性说明。没有样本时明确说明。
|
- 数据分析用真实 DTO 绘制 SVG 条形图,保留来源筛选、体力效率、样本和不确定性说明。没有样本时明确说明。
|
||||||
- 策略统一导入导出;收益 CSV/XLSX 导入与可用数据下载。错误展示具体原因,不把不支持的任务伪装成可执行任务。
|
- 策略统一导入导出;收益 CSV/XLSX 导入与可用数据下载。错误展示具体原因,不把不支持的任务伪装成可执行任务。
|
||||||
- 帮助可检查 GitHub 正式版本并提交受控更新请求。未配置部署器时明确显示原因,更新提交不表示更新成功。
|
- 帮助可检查 GitHub 正式版本并提交受控更新请求。未配置部署器时明确显示原因,更新提交不表示更新成功。
|
||||||
|
- 2.0.1 由用户手动触发在线更新,使用稳定 Release、对应正式镜像及完成私有认证的宿主机更新器;安装结果以宿主机健康检查为准。
|
||||||
|
|
||||||
## 安全与验证
|
## 安全与验证
|
||||||
|
|
||||||
|
|||||||
+24
-8
@@ -1,16 +1,16 @@
|
|||||||
# Web 2.0.0 运行说明
|
# Web 2.0.1 运行说明
|
||||||
|
|
||||||
Web 正式版本 **2.0.0**,源码入口 `main`,游戏资料基线 **1.9.68**。桌面正式版保留 **1.2.0**,入口为 `python -m ranch_assistant`;Web 使用独立依赖与数据根。
|
本轮 Web 发布目标 **2.0.1**,源码入口 `main`,游戏资料基线 **1.9.68**。桌面正式版保留 **1.2.0**,入口为 `python -m ranch_assistant`;Web 使用独立依赖与数据根。
|
||||||
|
|
||||||
Web 采用 FastAPI / Uvicorn 和原生 HTML/CSS/ES 模块,无 Node、npm 或前端编译步骤,不安装 PySide6。页面和策略能力沿用现有核心,详细业务范围与原有限制见 [桌面使用说明](../ranch_assistant/README.md)。多浏览器连接同一个管理员工作台;一个服务实例内,各账号独立线程并行,同一账号操作串行。
|
Web 采用 FastAPI / Uvicorn 和原生 HTML/CSS/ES 模块,无 Node、npm 或前端编译步骤,不安装 PySide6。页面和策略能力沿用现有核心,详细业务范围与原有限制见 [桌面使用说明](../ranch_assistant/README.md)。多浏览器连接同一个管理员工作台;一个服务实例内,各账号独立线程并行,同一账号操作串行。
|
||||||
|
|
||||||
## 迁移清单
|
## 迁移清单
|
||||||
|
|
||||||
- [x] 原15页:登录、培育室、背包、牧场、每日事务、自动孵蛋、自动主线、战斗记录、自动赠礼、自动委托、自动探险、自动扫荡、数据分析、执行计划、收益资料。
|
- [x] 原15页:登录、培育室、背包、牧场、每日事务、自动孵蛋、自动主线、战斗记录、自动赠礼、自动委托、自动探险、自动扫荡、数据分析、执行计划、收益资料。
|
||||||
- [x] 保留账号页签、顶部数值与统一启停、可调日志;规则自动保存,配置与统计按账号/角色隔离,重启、恢复会话及导入策略后保持停止。
|
- [x] 保留账号页签、顶部数值与统一启停、可调日志;规则自动保存,配置与统计按账号/角色隔离,每次成功登录后自动执行已配置且已勾选的功能,可在顶部停止。
|
||||||
- [x] Windows Python 启动与离线演示;Web 导入链和依赖不使用 Qt,无 Node 构建步骤。
|
- [x] Windows Python 启动与离线演示;Web 导入链和依赖不使用 Qt,无 Node 构建步骤。
|
||||||
- [x] 提供 Linux Docker 与稳定 2.x 受控更新、停机备份及失败回滚脚本;已完成 Linux Docker 部署、持久化权限、健康检查和定时更新检查烟测。
|
- [x] 提供 Linux Docker 与稳定 2.x 受控更新、停机备份及失败回滚脚本;已完成 Linux Docker 部署、持久化权限、健康检查和定时更新检查烟测。
|
||||||
- [x] 正式版本为 `2.0.0`,保留桌面兼容;战斗模拟为近似模型,特殊关卡并非全部支持,真实游戏 API 验收范围不因版本号变更而扩大。
|
- [x] 本轮发布目标为 `2.0.1`,保留桌面兼容;战斗模拟为近似模型,特殊关卡并非全部支持,真实游戏 API 验收范围不因版本号变更而扩大。
|
||||||
|
|
||||||
## Windows 本地运行
|
## Windows 本地运行
|
||||||
|
|
||||||
@@ -30,15 +30,25 @@ py -3 -m venv .venv-web
|
|||||||
.\Start_Ranch_Web.cmd --demo --data-dir "$env:TEMP\ranch-web-demo-new" --no-browser
|
.\Start_Ranch_Web.cmd --demo --data-dir "$env:TEMP\ranch-web-demo-new" --no-browser
|
||||||
```
|
```
|
||||||
|
|
||||||
健康检查 `GET /api/health` 不访问游戏 API。关闭终端时使用 Ctrl+C,让应用正常关闭账号队列。重启、恢复会话或导入策略后仍需手动开启运行。
|
健康检查 `GET /api/health` 不访问游戏 API。关闭终端时使用 Ctrl+C,让应用正常关闭账号队列。手动选服、恢复会话及自动重登成功读取角色后,均默认开启策略,只执行已勾选的功能,子功能不会全选。顶部“停止”暂停策略,仍保留状态监控;可用“开启”继续。导入配置只替换规则并停止执行,下次成功登录仍会自动开启;服务重启后未成功登录时不直接执行。
|
||||||
|
|
||||||
### 后台运行与断线处理
|
### 后台运行与断线处理
|
||||||
|
|
||||||
关闭网页或退出 Web 管理登录不会停止服务器上的账号监控和已开启策略。账号监控和策略执行由服务端管理;“停止”策略后仍保留状态监控,退出游戏账号或停止服务后结束监控。
|
关闭网页或退出 Web 管理登录不会停止服务器上的账号监控和已开启策略。账号监控和策略执行由服务端管理;“停止”策略后仍保留状态监控,退出游戏账号或停止服务后结束监控。
|
||||||
|
|
||||||
账号状态区分游戏在线、临时故障重试、游戏登录过期和未连接,显示最后成功通信时间及具体原因。临时网络故障采用退避后的只读状态检查;无法确认的操作保留核对记录,不自动重复提交。游戏会话失效后停止策略和游戏轮询,需在登录页重新登录或恢复有效会话;成功恢复后仍需手动开启策略。
|
账号状态区分游戏在线、临时故障重试、游戏登录过期和未连接,显示最后成功通信时间及具体原因。临时网络故障采用退避后的只读状态检查;无法确认的操作保留核对记录,不自动重复提交。游戏会话失效后停止策略和游戏轮询,按自动重登录设置等待处理,或在登录页手动恢复;成功登录后自动执行已配置且已勾选的功能,可在顶部停止。仅获取区服候选、候选角色验证失败或会话恢复失败,均不显示为登录成功。
|
||||||
|
|
||||||
服务重启会保留配置与加密会话,但不会自动连接游戏或恢复策略。登录页与运行日志会提示需要恢复会话。普通运行日志在各账号目录中限量持久保存,服务重启后仍可查看;调试请求详情仅在当前进程中按原有上限缓存。页面展示旧角色数据时会标注缓存状态,不把页面刷新视作游戏连接成功。
|
服务重启会保留配置与加密会话;未启用自动重登录时,需要手动恢复会话。普通运行日志在各账号目录中限量持久保存,服务重启后仍可查看;调试请求详情仅在当前进程中按原有上限缓存。页面展示旧角色数据时会标注缓存状态,不把页面刷新视作游戏连接成功。
|
||||||
|
|
||||||
|
### 掉线后自动重新登录
|
||||||
|
|
||||||
|
在“登录”页开启“掉线后自动重新登录”,设置等待时长,默认 **30 分钟**,修改后自动保存。该开关默认关闭,各账号独立配置。使用前请在游戏登录时勾选“记住账号和密码”,并成功进入目标区服;密码仍由服务端加密保存。
|
||||||
|
|
||||||
|
登录偏好保存在本账号中,进入其他区服或退出登录后仍保留设置;便携策略导入导出不携带、也不覆盖该登录偏好。
|
||||||
|
|
||||||
|
检测到掉线后,服务端按等待时长重新进行账号密码登录,回到原区服、原角色。登录页显示安排时间及执行结果,关闭浏览器不影响计时。临时网络故障的只读恢复检查继续运行,连接提前恢复后会取消重登录计划。重登录失败后按配置时长等待下一次尝试;缺少保存的密码或目标角色时会显示具体原因。
|
||||||
|
|
||||||
|
开启此功能且保留有效登录记录时,服务重启也会先等待所设时长,再尝试重登录;等待及失败阶段不执行策略。主动退出、清除登录记录或移除账号会取消自动计划。重登录成功读取原区服、原角色后,恢复状态监控并默认开启策略,自动执行已勾选功能,可点击顶部“停止”暂停。
|
||||||
|
|
||||||
## Linux Python 与环境变量
|
## Linux Python 与环境变量
|
||||||
|
|
||||||
@@ -69,14 +79,20 @@ sh start-web.sh --no-browser
|
|||||||
|
|
||||||
## Docker 与在线更新
|
## Docker 与在线更新
|
||||||
|
|
||||||
完整步骤见 [Linux Docker 部署与受控更新](../deploy/web/README.md)。镜像使用 UID/GID 10001,持久化 `/data`,内置 `/api/health` healthcheck,正常退出宽限 120 秒,不挂载 Docker socket。
|
完整步骤及一次性私有更新器初始化见 [Linux Docker 部署与受控在线更新](../deploy/web/README.md)。镜像使用 UID/GID 10001,持久化 `/data`,内置 `/api/health` healthcheck,正常退出宽限 120 秒,不挂载 Docker socket。
|
||||||
|
|
||||||
已在 Ubuntu 24.04、Docker 29.8、Compose 5.5、Python 3.12 环境完成镜像构建和部署烟测:UID 10001 数据目录权限为 0700、密钥为 0600,应用根文件系统只读;健康检查及 FRP 转发返回 HTTP 200,Edge 管理登录后可访问 15 个功能页且无 JavaScript 错误,更新定时器已启用并成功完成首次 GitHub 检查。此部署烟测记录对应独立管理登录页调整前的版本;调整后的本地验证见下文,重新部署验收待完成,真实游戏 API 尚未验收。
|
已在 Ubuntu 24.04、Docker 29.8、Compose 5.5、Python 3.12 环境完成镜像构建和部署烟测:UID 10001 数据目录权限为 0700、密钥为 0600,应用根文件系统只读;健康检查及 FRP 转发返回 HTTP 200,Edge 管理登录后可访问 15 个功能页且无 JavaScript 错误,更新定时器已启用并成功完成首次 GitHub 检查。此部署烟测记录对应独立管理登录页调整前的版本;调整后的本地验证见下文,重新部署验收待完成,真实游戏 API 尚未验收。
|
||||||
|
|
||||||
Web 检查固定官方 GitHub Releases 的稳定 `v2.x.y`,跳过桌面 1.x、未来 3.x、草稿和预发布。开发版本 `2.0.0.dev1` 可升级至同数字的正式 `v2.0.0`;没有正式 Web 2 发布时明确显示暂无更新。Windows 默认仅检查;Web “更新”按钮仅在宿主机显式启用并有有效只读心跳时可提交 `pending` 请求,安装、备份和回滚由宿主机执行。默认定时检查只通知,自动安装需操作者 opt-in。
|
Web 检查固定官方 GitHub Releases 的稳定 `v2.x.y`,跳过桌面 1.x、未来 3.x、草稿和预发布。开发版本 `2.0.0.dev1` 可升级至同数字的正式 `v2.0.0`;没有正式 Web 2 发布时明确显示暂无更新。Windows 默认仅检查;Web “更新”按钮仅在宿主机显式启用并有有效只读心跳时可提交 `pending` 请求,安装、备份和回滚由宿主机执行。默认定时检查只通知,自动安装需操作者 opt-in。
|
||||||
|
|
||||||
|
**2.0.1** 的在线更新由用户手动触发,使用稳定 Release、对应正式镜像,以及完成私有仓库认证、心跳有效的宿主机更新器。首次配置和操作步骤见[部署说明](../deploy/web/README.md),安装结果以宿主机健康检查为准。
|
||||||
|
|
||||||
## 离线验证
|
## 离线验证
|
||||||
|
|
||||||
|
2.0.1 发布回归:后端及更新器 **297 项中 294 通过、3 项因 Windows 权限或软链接限制跳过**,浏览器 **43 项全部通过**。更新器专项命令增加 `ranch_web.tests.test_private_updates ranch_web.tests.test_web_updater_package`;Linux 镜像工作流也执行这两项模块,验证独立包、私有认证与容器健康。
|
||||||
|
|
||||||
|
自动重登录功能回归:后端及登录链路 **267 项中 266 通过、1 项因 Windows 符号链接权限跳过**,浏览器 **39 项全部通过**;另以禁止外部网络的合成账号完成 24 项独立审核。后端命令增加 `ranch_web.tests.test_auto_relogin ranch_assistant.tests.test_debug`,浏览器命令增加 `ranch_web.tests.browser.test_auto_relogin_browser.AutoReloginBrowserTests ranch_web.tests.browser.test_auto_relogin_browser.AutoReloginSchemaTests`。
|
||||||
|
|
||||||
2.0.0 发布整理本轮仅调整版本元数据,API 策略与行为未改;完整 Web 后端回归 **246 项:245 通过、1 项因 Windows 符号链接权限跳过、0 失败**。以下保留此前功能提交及开发阶段的验证记录。
|
2.0.0 发布整理本轮仅调整版本元数据,API 策略与行为未改;完整 Web 后端回归 **246 项:245 通过、1 项因 Windows 符号链接权限跳过、0 失败**。以下保留此前功能提交及开发阶段的验证记录。
|
||||||
|
|
||||||
前一功能提交的后台连接与日志修复:Web 后端 **245 项中 244 通过、1 项因 Windows 符号链接权限跳过**,浏览器 **31 项全部通过(本轮未重跑)**;独立故障重放四组通过。行为与证据边界见 [连接修复说明](../analysis/WEB_CONNECTION_FIX.md)。现有后端命令追加 `ranch_web.tests.test_base_path ranch_web.tests.test_activity ranch_web.tests.test_connection_state`,浏览器命令追加 `ranch_web.tests.browser.test_base_path_browser ranch_web.tests.browser.test_connection_browser.ConnectionBrowserTests` 可覆盖该功能回归。
|
前一功能提交的后台连接与日志修复:Web 后端 **245 项中 244 通过、1 项因 Windows 符号链接权限跳过**,浏览器 **31 项全部通过(本轮未重跑)**;独立故障重放四组通过。行为与证据边界见 [连接修复说明](../analysis/WEB_CONNECTION_FIX.md)。现有后端命令追加 `ranch_web.tests.test_base_path ranch_web.tests.test_activity ranch_web.tests.test_connection_state`,浏览器命令追加 `ranch_web.tests.browser.test_base_path_browser ranch_web.tests.browser.test_connection_browser.ConnectionBrowserTests` 可覆盖该功能回归。
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
"""Headless Web workspace for the ranch assistant."""
|
"""Headless Web workspace for the ranch assistant."""
|
||||||
|
|
||||||
__version__ = "2.0.0"
|
__version__ = "2.0.1"
|
||||||
GAME_VERSION = "1.9.68"
|
GAME_VERSION = "1.9.68"
|
||||||
|
|
||||||
__all__ = ["__version__", "GAME_VERSION"]
|
__all__ = ["__version__", "GAME_VERSION"]
|
||||||
|
|||||||
@@ -580,6 +580,11 @@ def create_app(data_dir=None, manager=None, config=None, updates=None) -> FastAP
|
|||||||
"connection_state", "connection_message", "last_game_success_at", "next_retry_at")}
|
"connection_state", "connection_message", "last_game_success_at", "next_retry_at")}
|
||||||
result["error"] = public_error(result["error"])
|
result["error"] = public_error(result["error"])
|
||||||
result["connection_message"] = public_error(result["connection_message"])
|
result["connection_message"] = public_error(result["connection_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")
|
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
|
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)
|
return public(result)
|
||||||
|
|||||||
@@ -36,7 +36,8 @@ def default_config():
|
|||||||
# experimental battle simulator. Keep those defaults, not legacy widgets.
|
# experimental battle simulator. Keep those defaults, not legacy widgets.
|
||||||
value["policy"]["manual_eggs"] = True
|
value["policy"]["manual_eggs"] = True
|
||||||
value["progression_policy"]["battle_mode"] = "experimental"
|
value["progression_policy"]["battle_mode"] = "experimental"
|
||||||
return value | {"interval": 30, "overrides": {}, "yield_stars": [1, 2, 3, 4, 5],
|
return value | {"auto_relogin": {"enabled": False, "delay_minutes": 30},
|
||||||
|
"interval": 30, "overrides": {}, "yield_stars": [1, 2, 3, 4, 5],
|
||||||
"log_visible": True, "log_sizes": [420, 140]}
|
"log_visible": True, "log_sizes": [420, 140]}
|
||||||
|
|
||||||
|
|
||||||
@@ -110,6 +111,8 @@ def validate_config(config):
|
|||||||
result = deepcopy(defaults)
|
result = deepcopy(defaults)
|
||||||
for key, cls in POLICY_CLASSES.items():
|
for key, cls in POLICY_CLASSES.items():
|
||||||
result[key] = _section(config.get(key, {}), defaults[key], key)
|
result[key] = _section(config.get(key, {}), defaults[key], key)
|
||||||
|
result["auto_relogin"] = _section(config.get("auto_relogin", {}), defaults["auto_relogin"], "自动重登")
|
||||||
|
_int(result["auto_relogin"]["delay_minutes"], "自动重登等待分钟", 1, 10080)
|
||||||
p = result["policy"]
|
p = result["policy"]
|
||||||
# read_policy() in the current desktop always enables per-species rules.
|
# read_policy() in the current desktop always enables per-species rules.
|
||||||
# Normalize a validated legacy False so importing hidden old settings can
|
# Normalize a validated legacy False so importing hidden old settings can
|
||||||
@@ -218,6 +221,8 @@ def apply_config(engine, config):
|
|||||||
|
|
||||||
|
|
||||||
def export_config(config, snapshot=None):
|
def export_config(config, snapshot=None):
|
||||||
|
# Login preferences stay local to this account tab; portable strategy
|
||||||
|
# imports cannot opt another account into password authentication.
|
||||||
value = policy_io.portable_config(validate_config(config), snapshot)
|
value = policy_io.portable_config(validate_config(config), snapshot)
|
||||||
value["assistantVersion"] = __version__
|
value["assistantVersion"] = __version__
|
||||||
return value
|
return value
|
||||||
|
|||||||
+31
-1
@@ -13,8 +13,9 @@ FAST_KINDS = ("hatch", "gift", "explore", "breakthrough")
|
|||||||
class AccountSchedule:
|
class AccountSchedule:
|
||||||
"""Deadlines belong to one worker and are inspected only on its thread."""
|
"""Deadlines belong to one worker and are inspected only on its thread."""
|
||||||
|
|
||||||
def __init__(self, *, clock=time.monotonic, uniform=random.uniform):
|
def __init__(self, *, clock=time.monotonic, uniform=random.uniform, wall_clock=time.time):
|
||||||
self.clock, self.uniform = clock, uniform
|
self.clock, self.uniform = clock, uniform
|
||||||
|
self.wall_clock = wall_clock
|
||||||
self.next_poll = math.inf
|
self.next_poll = math.inf
|
||||||
self.next_fast = {kind: math.inf for kind in FAST_KINDS}
|
self.next_fast = {kind: math.inf for kind in FAST_KINDS}
|
||||||
self.monitoring = False
|
self.monitoring = False
|
||||||
@@ -22,6 +23,31 @@ class AccountSchedule:
|
|||||||
self.game_paused = False
|
self.game_paused = False
|
||||||
self.retry_deadline = None
|
self.retry_deadline = None
|
||||||
self.retry_attempt = 0
|
self.retry_attempt = 0
|
||||||
|
self.disconnected_at = None
|
||||||
|
self.disconnected_wall_at = None
|
||||||
|
self.auto_relogin_failed_at = None
|
||||||
|
|
||||||
|
def disconnected(self):
|
||||||
|
# Read retries and settings changes must not move the first failure.
|
||||||
|
if self.disconnected_at is None:
|
||||||
|
self.disconnected_at = self.clock()
|
||||||
|
self.disconnected_wall_at = self.wall_clock()
|
||||||
|
|
||||||
|
def clear_disconnection(self):
|
||||||
|
self.disconnected_at = self.disconnected_wall_at = None
|
||||||
|
self.auto_relogin_failed_at = None
|
||||||
|
|
||||||
|
def auto_relogin_deadline(self, config):
|
||||||
|
preference = config.get("auto_relogin", {})
|
||||||
|
if not preference.get("enabled") or self.disconnected_at is None:
|
||||||
|
return None
|
||||||
|
origin = max(self.disconnected_at, self.auto_relogin_failed_at
|
||||||
|
if self.auto_relogin_failed_at is not None else self.disconnected_at)
|
||||||
|
return origin + preference["delay_minutes"] * 60
|
||||||
|
|
||||||
|
def auto_relogin_failed(self):
|
||||||
|
# Back off from completion, including time spent authenticating.
|
||||||
|
self.auto_relogin_failed_at = self.clock()
|
||||||
|
|
||||||
def game_failed(self, *, retry=False):
|
def game_failed(self, *, retry=False):
|
||||||
self.game_paused = True
|
self.game_paused = True
|
||||||
@@ -37,6 +63,7 @@ class AccountSchedule:
|
|||||||
self.game_paused = False
|
self.game_paused = False
|
||||||
self.retry_deadline = None
|
self.retry_deadline = None
|
||||||
self.retry_attempt = 0
|
self.retry_attempt = 0
|
||||||
|
self.clear_disconnection()
|
||||||
|
|
||||||
def monitor(self, enabled=True):
|
def monitor(self, enabled=True):
|
||||||
self.monitoring = bool(enabled)
|
self.monitoring = bool(enabled)
|
||||||
@@ -87,6 +114,9 @@ class AccountSchedule:
|
|||||||
|
|
||||||
def due(self, engine, config, running):
|
def due(self, engine, config, running):
|
||||||
now = self.clock()
|
now = self.clock()
|
||||||
|
deadline = self.auto_relogin_deadline(config)
|
||||||
|
if deadline is not None and now >= deadline:
|
||||||
|
return "auto_relogin"
|
||||||
if self.game_paused:
|
if self.game_paused:
|
||||||
return "retry" if self.retry_deadline is not None and now >= self.retry_deadline else None
|
return "retry" if self.retry_deadline is not None and now >= self.retry_deadline else None
|
||||||
|
|
||||||
|
|||||||
+250
-22
@@ -71,6 +71,10 @@ class RevisionConflict(ValueError):
|
|||||||
"""The browser edited a different applied configuration revision."""
|
"""The browser edited a different applied configuration revision."""
|
||||||
|
|
||||||
|
|
||||||
|
class AutoReloginBlocked(ValueError):
|
||||||
|
"""Password login has no verified local credentials/target to use."""
|
||||||
|
|
||||||
|
|
||||||
def _private_field(field):
|
def _private_field(field):
|
||||||
normalized = str(field).lower().replace("_", "").replace("-", "")
|
normalized = str(field).lower().replace("_", "").replace("-", "")
|
||||||
return normalized in SECRET_FIELDS or sensitive(field)
|
return normalized in SECRET_FIELDS or sensitive(field)
|
||||||
@@ -186,6 +190,16 @@ class AccountWorker:
|
|||||||
self._last_game_error = None
|
self._last_game_error = None
|
||||||
self._game_failure_sequence = 0
|
self._game_failure_sequence = 0
|
||||||
self.schedule = AccountSchedule()
|
self.schedule = AccountSchedule()
|
||||||
|
self._auto_relogin_suspended = False
|
||||||
|
self._auto_relogin_pending_config = None
|
||||||
|
self._auto_relogin_inflight = False
|
||||||
|
self._auto_relogin_target = None
|
||||||
|
self._auto_relogin_account = ""
|
||||||
|
self._auto_relogin_error = ""
|
||||||
|
self._auto_relogin_blocked = False
|
||||||
|
# Reuse the account's existing disconnected settings for login
|
||||||
|
# preferences. Role policies remain in their own role directories.
|
||||||
|
self._login_settings_root = manager.store.role_root(self.id)
|
||||||
self.state_root = self.state = manager.store.role_root(self.id, demo=self.demo)
|
self.state_root = self.state = manager.store.role_root(self.id, demo=self.demo)
|
||||||
self.config, self.revision = self._load_config(self.state_root)
|
self.config, self.revision = self._load_config(self.state_root)
|
||||||
self.trace = WebTrace(self)
|
self.trace = WebTrace(self)
|
||||||
@@ -199,7 +213,12 @@ class AccountWorker:
|
|||||||
|
|
||||||
def _load_config(self, folder):
|
def _load_config(self, folder):
|
||||||
record = self.manager.store.load_config(folder)
|
record = self.manager.store.load_config(folder)
|
||||||
return (validate_config(record["config"]), record["revision"]) if record else (default_config(), 0)
|
value, revision = (validate_config(record["config"]), record["revision"]) if record else (default_config(), 0)
|
||||||
|
if folder != self._login_settings_root:
|
||||||
|
login = self.manager.store.load_config(self._login_settings_root)
|
||||||
|
if login:
|
||||||
|
value["auto_relogin"] = validate_config(login["config"])["auto_relogin"]
|
||||||
|
return value, revision
|
||||||
|
|
||||||
def _engine(self, client=None, *, state_root=None, config=None):
|
def _engine(self, client=None, *, state_root=None, config=None):
|
||||||
state_root = self.state_root if state_root is None else state_root
|
state_root = self.state_root if state_root is None else state_root
|
||||||
@@ -319,7 +338,59 @@ class AccountWorker:
|
|||||||
"demo": self.demo, "running": self._running, "busy": False, "player": player,
|
"demo": self.demo, "running": self._running, "busy": False, "player": player,
|
||||||
"revision": self.revision, "error": self.error, "connection_state": self.connection_state,
|
"revision": self.revision, "error": self.error, "connection_state": self.connection_state,
|
||||||
"connection_message": self.connection_message, "last_game_success_at": self.last_game_success_at,
|
"connection_message": self.connection_message, "last_game_success_at": self.last_game_success_at,
|
||||||
"next_retry_at": self.next_retry_at})
|
"next_retry_at": self.next_retry_at, "auto_relogin_status": self._auto_relogin_status()})
|
||||||
|
|
||||||
|
def _auto_relogin_status(self):
|
||||||
|
with self.lock:
|
||||||
|
preference = (self._auto_relogin_pending_config[1] if self._auto_relogin_pending_config
|
||||||
|
else self.config["auto_relogin"])
|
||||||
|
state, message, next_at = "idle", "自动重登已开启;等待游戏连接掉线", None
|
||||||
|
if not preference["enabled"]:
|
||||||
|
state, message = "disabled", "自动重登已关闭"
|
||||||
|
elif self._auto_relogin_suspended:
|
||||||
|
state, message = "suspended", "已暂停本次自动重登;手动登录或恢复成功后重新参与掉线监测"
|
||||||
|
elif self._auto_relogin_pending_config:
|
||||||
|
state, message = "suspended", "正在保存自动重登设置,旧登录计划已取消"
|
||||||
|
elif self.demo:
|
||||||
|
message = "离线演示不执行自动重登"
|
||||||
|
elif self._auto_relogin_inflight:
|
||||||
|
state, message = "authenticating", "正在使用服务器保存的密码重新登录原区服、原角色;激活成功后将尝试开启已勾选的策略"
|
||||||
|
elif not self.active_identity or self.schedule.disconnected_at is not None and not self._auto_relogin_target:
|
||||||
|
state, message = "blocked", "没有可确认的原区服和角色会话,请先手动登录并选择区服"
|
||||||
|
elif self.schedule.disconnected_at is not None:
|
||||||
|
if not self._has_saved_password:
|
||||||
|
state, message = "blocked", "未在服务器保存密码,无法自动重登;请手动登录并勾选记住密码"
|
||||||
|
elif self._auto_relogin_account != self._saved_account:
|
||||||
|
state, message = "blocked", "保存密码的账号与掉线角色所属账号不匹配,请手动登录确认"
|
||||||
|
elif self._auto_relogin_blocked:
|
||||||
|
state, message = "blocked", self._auto_relogin_error
|
||||||
|
else:
|
||||||
|
deadline = self.schedule.auto_relogin_deadline(self.config)
|
||||||
|
if deadline is not None:
|
||||||
|
next_at = datetime.fromtimestamp(self.schedule.disconnected_wall_at
|
||||||
|
+ deadline - self.schedule.disconnected_at, timezone.utc).isoformat(timespec="milliseconds")
|
||||||
|
state = "failed" if self._auto_relogin_error else "waiting"
|
||||||
|
message = (self._auto_relogin_error + ";将按配置分钟间隔再次尝试" if self._auto_relogin_error
|
||||||
|
else f"游戏已掉线,从首次掉线起等待 {preference['delay_minutes']} 分钟后重新登录原区服、原角色")
|
||||||
|
return {"state": state, "message": self.safe_text(message), "next_attempt_at": next_at}
|
||||||
|
|
||||||
|
def _mark_disconnected(self, session, identity):
|
||||||
|
if not self._auto_relogin_suspended and self.schedule.disconnected_at is None:
|
||||||
|
self.schedule.disconnected()
|
||||||
|
self._auto_relogin_target = identity
|
||||||
|
self._auto_relogin_account = session.account_name.strip()
|
||||||
|
self._auto_relogin_error = ""
|
||||||
|
self._auto_relogin_blocked = False
|
||||||
|
|
||||||
|
def suspend_auto_relogin(self):
|
||||||
|
# Called synchronously at submit/close, before any queued lifecycle job.
|
||||||
|
with self.lock:
|
||||||
|
self._auto_relogin_suspended = True
|
||||||
|
self.schedule.clear_disconnection()
|
||||||
|
self._auto_relogin_target = None
|
||||||
|
self._auto_relogin_account = ""
|
||||||
|
self._auto_relogin_error = ""
|
||||||
|
self._auto_relogin_blocked = False
|
||||||
|
|
||||||
def _require_game(self):
|
def _require_game(self):
|
||||||
if self.connection_state != "online" and not (self._retry_probe and self.connection_state == "retrying"):
|
if self.connection_state != "online" and not (self._retry_probe and self.connection_state == "retrying"):
|
||||||
@@ -349,6 +420,8 @@ class AccountWorker:
|
|||||||
self.log(self.error)
|
self.log(self.error)
|
||||||
return
|
return
|
||||||
self.engine.heartbeat_enabled = False
|
self.engine.heartbeat_enabled = False
|
||||||
|
if client is not None:
|
||||||
|
self._mark_disconnected(client.session, self.active_identity)
|
||||||
delay = self.schedule.game_failed(retry=temporary and not expired and client is not None)
|
delay = self.schedule.game_failed(retry=temporary and not expired and client is not None)
|
||||||
with self.lock:
|
with self.lock:
|
||||||
self.next_retry_at = None
|
self.next_retry_at = None
|
||||||
@@ -370,7 +443,7 @@ class AccountWorker:
|
|||||||
self._last_game_error_message = self.error
|
self._last_game_error_message = self.error
|
||||||
self.log(self.connection_message)
|
self.log(self.connection_message)
|
||||||
|
|
||||||
def _game_succeeded(self):
|
def _game_succeeded(self, *, activated=False):
|
||||||
previous = self.connection_state
|
previous = self.connection_state
|
||||||
with self.lock:
|
with self.lock:
|
||||||
self.connection_state = "online"
|
self.connection_state = "online"
|
||||||
@@ -378,15 +451,22 @@ class AccountWorker:
|
|||||||
self.last_game_success_at = datetime.now(timezone.utc).isoformat(timespec="milliseconds")
|
self.last_game_success_at = datetime.now(timezone.utc).isoformat(timespec="milliseconds")
|
||||||
self.next_retry_at = None
|
self.next_retry_at = None
|
||||||
self.error = ""
|
self.error = ""
|
||||||
|
if activated:
|
||||||
|
self._auto_relogin_suspended = False
|
||||||
|
self._auto_relogin_target = None
|
||||||
|
self._auto_relogin_account = ""
|
||||||
|
self._auto_relogin_error = ""
|
||||||
|
self._auto_relogin_blocked = False
|
||||||
self.schedule.game_resumed()
|
self.schedule.game_resumed()
|
||||||
self.engine.heartbeat_enabled = True
|
self.engine.heartbeat_enabled = True
|
||||||
if previous != "online":
|
if previous != "online" and not activated:
|
||||||
self.log("游戏连接已确认;策略保持停止")
|
self.log("游戏连接已确认;" + ("已勾选的策略继续运行" if self.running else "策略保持停止"))
|
||||||
|
|
||||||
def status(self):
|
def status(self):
|
||||||
with self.lock:
|
with self.lock:
|
||||||
result = deepcopy(self._summary)
|
result = deepcopy(self._summary)
|
||||||
result.update(running=self._running, busy=bool(self._active or self._pending))
|
result.update(running=self._running, busy=bool(self._active or self._pending))
|
||||||
|
result["auto_relogin_status"] = self._auto_relogin_status()
|
||||||
return result
|
return result
|
||||||
|
|
||||||
@property
|
@property
|
||||||
@@ -411,7 +491,7 @@ class AccountWorker:
|
|||||||
def check_intent(self, *, check_persistence=False):
|
def check_intent(self, *, check_persistence=False):
|
||||||
with self.lock:
|
with self.lock:
|
||||||
job = self._execution
|
job = self._execution
|
||||||
if job and job.consuming and (self._closing or job.generation != self._generation):
|
if job and job.consuming and (self._closing or self.manager._closing or job.generation != self._generation):
|
||||||
raise CancelledBeforeDispatch()
|
raise CancelledBeforeDispatch()
|
||||||
if check_persistence and getattr(self, "_session_write_error", ""):
|
if check_persistence and getattr(self, "_session_write_error", ""):
|
||||||
raise OSError(self._session_write_error)
|
raise OSError(self._session_write_error)
|
||||||
@@ -523,6 +603,8 @@ class AccountWorker:
|
|||||||
final_status, final_error = "failed", self.error
|
final_status, final_error = "failed", self.error
|
||||||
self.log(self.error)
|
self.log(self.error)
|
||||||
with self.condition:
|
with self.condition:
|
||||||
|
if self._auto_relogin_pending_config and self._auto_relogin_pending_config[0] == job.id:
|
||||||
|
self._auto_relogin_pending_config = None
|
||||||
self._summary = summary
|
self._summary = summary
|
||||||
# A terminal job means its counters and status are both
|
# A terminal job means its counters and status are both
|
||||||
# visible. Publish them atomically for HTTP polling.
|
# visible. Publish them atomically for HTTP polling.
|
||||||
@@ -547,12 +629,17 @@ class AccountWorker:
|
|||||||
saved = self.securestore.active()
|
saved = self.securestore.active()
|
||||||
if saved is not None and not self.demo:
|
if saved is not None and not self.demo:
|
||||||
# Restore settings without issuing an unsolicited game request.
|
# Restore settings without issuing an unsolicited game request.
|
||||||
self.securestore.load(saved)
|
session = self.securestore.load(saved)
|
||||||
self.state_root = self.state = self.manager.store.role_root(self.id, saved)
|
self.state_root = self.state = self.manager.store.role_root(self.id, saved)
|
||||||
self.config, self.revision = self._load_config(self.state_root)
|
self.config, self.revision = self._load_config(self.state_root)
|
||||||
self.active_identity = saved
|
self.active_identity = saved
|
||||||
self.engine = self._engine()
|
self.engine = self._engine()
|
||||||
self.connection_message = "服务已启动或重启;已保留保存的会话,请手动恢复会话或重新登录,策略保持停止"
|
self.connection_message = "服务已启动或重启;已保留保存的会话,请手动恢复会话或重新登录,策略保持停止"
|
||||||
|
# Opt-in only: retain the known startup offline origin even
|
||||||
|
# while disabled, so enabling later can reuse that timestamp.
|
||||||
|
self._mark_disconnected(session, saved)
|
||||||
|
if self.config["auto_relogin"]["enabled"]:
|
||||||
|
self.connection_message = "服务已启动或重启;将等待配置分钟后使用保存的密码重新登录原区服、原角色,策略保持停止"
|
||||||
self.log(self.connection_message)
|
self.log(self.connection_message)
|
||||||
if self.demo:
|
if self.demo:
|
||||||
self.result(*self.engine.poll())
|
self.result(*self.engine.poll())
|
||||||
@@ -610,9 +697,19 @@ class AccountWorker:
|
|||||||
raise RuntimeError("策略保存必须在账号队列中执行")
|
raise RuntimeError("策略保存必须在账号队列中执行")
|
||||||
if revision is not None and revision != self.revision:
|
if revision is not None and revision != self.revision:
|
||||||
raise RevisionConflict("策略已在其他页面更新,请刷新后重试")
|
raise RevisionConflict("策略已在其他页面更新,请刷新后重试")
|
||||||
value = validate_config(self.config if config is None else config)
|
source = deepcopy(self.config if config is None else config)
|
||||||
|
if self._execution and self._execution.operation == "import_config":
|
||||||
|
# Legacy portable documents contain strategy rules, not local
|
||||||
|
# login authorization. Never erase or enable this preference.
|
||||||
|
source["auto_relogin"] = deepcopy(self.config["auto_relogin"])
|
||||||
|
value = validate_config(source)
|
||||||
new_revision = self.revision + 1
|
new_revision = self.revision + 1
|
||||||
self.manager.store.save_config(self.state_root, value, new_revision)
|
self.manager.store.save_config(self.state_root, value, new_revision)
|
||||||
|
if self.state_root != self._login_settings_root:
|
||||||
|
login = self.manager.store.load_config(self._login_settings_root)
|
||||||
|
local = validate_config(login["config"]) if login else default_config()
|
||||||
|
local["auto_relogin"] = deepcopy(value["auto_relogin"])
|
||||||
|
self.manager.store.save_config(self._login_settings_root, local, new_revision)
|
||||||
apply_config(self.engine, value)
|
apply_config(self.engine, value)
|
||||||
with self.lock:
|
with self.lock:
|
||||||
self.config, self.revision = value, new_revision
|
self.config, self.revision = value, new_revision
|
||||||
@@ -678,11 +775,28 @@ class AccountWorker:
|
|||||||
return active
|
return active
|
||||||
|
|
||||||
def _tick(self, job):
|
def _tick(self, job):
|
||||||
if not self.demo and self.engine.client is None:
|
|
||||||
return None
|
|
||||||
kind = self.schedule.due(self.engine, self.config, self._running)
|
kind = self.schedule.due(self.engine, self.config, self._running)
|
||||||
if kind is None:
|
if kind is None:
|
||||||
return None
|
return None
|
||||||
|
if kind == "auto_relogin":
|
||||||
|
with self.lock:
|
||||||
|
if self._auto_relogin_status()["state"] not in {"waiting", "failed"}:
|
||||||
|
# A blocked password login must not starve existing
|
||||||
|
# read-only timeout probes that could restore the client.
|
||||||
|
kind = self.schedule.due(self.engine, dict(self.config, auto_relogin={"enabled": False}), self._running)
|
||||||
|
else:
|
||||||
|
# Automation is already stopped on disconnect. This tick
|
||||||
|
# still consumes authentication intent and must be revocable.
|
||||||
|
job.consuming = True
|
||||||
|
self.check_intent()
|
||||||
|
self._running = self.engine.auto = False
|
||||||
|
self.schedule.stop()
|
||||||
|
if kind == "auto_relogin":
|
||||||
|
return self._auto_relogin()
|
||||||
|
if kind is None:
|
||||||
|
return None
|
||||||
|
if not self.demo and self.engine.client is None:
|
||||||
|
return None
|
||||||
auto = False
|
auto = False
|
||||||
try:
|
try:
|
||||||
if kind == "retry":
|
if kind == "retry":
|
||||||
@@ -735,6 +849,99 @@ class AccountWorker:
|
|||||||
self.schedule.poll_finished(self.config)
|
self.schedule.poll_finished(self.config)
|
||||||
raise
|
raise
|
||||||
|
|
||||||
|
def _password_login_flow(self):
|
||||||
|
flow = self.manager.login_factory(self.catalog, self.securestore.device(), trace=self.trace)
|
||||||
|
# Preserve the factory's existing constructor convention. The real
|
||||||
|
# SDK flow checks this optional guard at its own HTTP send boundary.
|
||||||
|
if isinstance(flow, PasswordLogin):
|
||||||
|
flow.cancel_guard = self.check_intent
|
||||||
|
return flow
|
||||||
|
|
||||||
|
def _auto_relogin(self):
|
||||||
|
client = None
|
||||||
|
self._auto_relogin_inflight = True
|
||||||
|
try:
|
||||||
|
self.check_intent()
|
||||||
|
identity = self._auto_relogin_target
|
||||||
|
if not identity or identity != self.active_identity:
|
||||||
|
raise AutoReloginBlocked("无法确认掉线前的原区服和角色,请手动登录确认")
|
||||||
|
try:
|
||||||
|
target = self.securestore.load(identity)
|
||||||
|
except (OSError, ValueError, KeyError):
|
||||||
|
raise AutoReloginBlocked("掉线前保存的角色会话不存在或无法读取,请手动登录确认") from None
|
||||||
|
if not target.account_id or not target.account_name or not target.server_id or not target.role_id:
|
||||||
|
raise AutoReloginBlocked("保存的会话缺少可确认的账号、原区服或角色,请手动登录确认")
|
||||||
|
saved, account, password = self.securestore.load_credentials()
|
||||||
|
self.remember({"password": password})
|
||||||
|
if not saved or not account or not password:
|
||||||
|
raise AutoReloginBlocked("未在服务器保存密码,无法自动重登;请手动登录并勾选记住密码")
|
||||||
|
if account.strip() != target.account_name.strip():
|
||||||
|
raise AutoReloginBlocked("保存密码的账号与掉线角色所属账号不匹配,请手动登录确认")
|
||||||
|
self.manager._claim_identity(self, identity)
|
||||||
|
self.check_intent()
|
||||||
|
self._session_write_error = ""
|
||||||
|
client, response, context = self._password_login_flow().authenticate(account, password)
|
||||||
|
self.check_intent()
|
||||||
|
# account_name is the input username; account_id is the SDK uid.
|
||||||
|
# Neither can substitute for the other when choosing the target.
|
||||||
|
if (client.session.account_name.strip() != target.account_name.strip()
|
||||||
|
or str(context.get("uid", "")) != target.account_id
|
||||||
|
or client.session.account_id != target.account_id
|
||||||
|
or client.session.channel != target.channel
|
||||||
|
or client.session.platform != target.platform
|
||||||
|
or context.get("channel") != target.channel):
|
||||||
|
raise ValueError("密码登录返回的账号与原角色会话不匹配,已拒绝进入区服")
|
||||||
|
servers = server_entries(response, target.platform)
|
||||||
|
server = next((row for row in servers if row["id"] == target.server_id), None)
|
||||||
|
if server is None:
|
||||||
|
raise ValueError("官方登录列表中没有掉线前的原区服,已拒绝切换其他区服")
|
||||||
|
roles = [row for row in response.get("masterInfos") or [] if isinstance(row, dict)
|
||||||
|
and str(row.get("serverId")) == str(target.server_id)]
|
||||||
|
if not roles or {str(row.get("id")) for row in roles} != {str(target.role_id)}:
|
||||||
|
raise ValueError("官方登录列表中无法确认原区服的原角色,已拒绝进入或创建其他角色")
|
||||||
|
self._bind_client(client)
|
||||||
|
self.check_intent()
|
||||||
|
client.enter_server(context["center_url"], server, context["uid"], self.catalog,
|
||||||
|
context["channel"], target.platform, context["device_id"])
|
||||||
|
self.check_intent()
|
||||||
|
if client.session.server_id != target.server_id or client.session.account_id != target.account_id:
|
||||||
|
raise ValueError("进入区服返回的账号或区服与掉线前不匹配,已停止自动重登")
|
||||||
|
# Client.snapshot must reject a different character before saving
|
||||||
|
# it; enter_server normally resets role_id to zero for manual use.
|
||||||
|
client.session.role_id = target.role_id
|
||||||
|
snapshot = client.snapshot()
|
||||||
|
self.check_intent()
|
||||||
|
if session_identity(client.session) != identity or int(snapshot.raw.get("master", {}).get("id") or 0) != target.role_id:
|
||||||
|
raise ValueError("进服后的角色与掉线前不匹配,已停止自动重登")
|
||||||
|
result = self._activate_client(client, snapshot, login_message="自动重登成功,已恢复原区服和原角色")
|
||||||
|
client = None # The worker now owns this client.
|
||||||
|
return result
|
||||||
|
except Exception as error:
|
||||||
|
with self.lock:
|
||||||
|
# One cancellation path handles both a guard exception and a
|
||||||
|
# revoked SDK call that eventually returns a transport error.
|
||||||
|
try:
|
||||||
|
self.check_intent()
|
||||||
|
if isinstance(error, CancelledBeforeDispatch):
|
||||||
|
raise error
|
||||||
|
except CancelledBeforeDispatch:
|
||||||
|
preference = (self._auto_relogin_pending_config[1] if self._auto_relogin_pending_config
|
||||||
|
else self.config["auto_relogin"])
|
||||||
|
if (not self._auto_relogin_suspended and preference["enabled"]
|
||||||
|
and self.schedule.disconnected_at is not None):
|
||||||
|
self.schedule.auto_relogin_failed()
|
||||||
|
self._auto_relogin_error = "自动重登已被新的操作取消"
|
||||||
|
raise
|
||||||
|
self.schedule.auto_relogin_failed()
|
||||||
|
self._auto_relogin_blocked = isinstance(error, AutoReloginBlocked)
|
||||||
|
self._auto_relogin_error = "自动重登未完成:" + self.safe_text(str(error))
|
||||||
|
self.log(self._auto_relogin_error)
|
||||||
|
return {"connected": False, "running": False, "message": self._auto_relogin_error}
|
||||||
|
finally:
|
||||||
|
self._auto_relogin_inflight = False
|
||||||
|
if client is not None:
|
||||||
|
client.close()
|
||||||
|
|
||||||
def _bind_client(self, client):
|
def _bind_client(self, client):
|
||||||
if not isinstance(client.session, Session):
|
if not isinstance(client.session, Session):
|
||||||
raise ValueError("登录客户端未提供受支持的会话")
|
raise ValueError("登录客户端未提供受支持的会话")
|
||||||
@@ -841,7 +1048,7 @@ class AccountWorker:
|
|||||||
def _session_stamp(session):
|
def _session_stamp(session):
|
||||||
return tuple(getattr(session, field) for field in Session.__dataclass_fields__)
|
return tuple(getattr(session, field) for field in Session.__dataclass_fields__)
|
||||||
|
|
||||||
def _activate_client(self, client, snapshot):
|
def _activate_client(self, client, snapshot, *, login_message="登录成功"):
|
||||||
self.check_intent()
|
self.check_intent()
|
||||||
session = client.session
|
session = client.session
|
||||||
role_id = int(snapshot.raw.get("master", {}).get("id") or 0)
|
role_id = int(snapshot.raw.get("master", {}).get("id") or 0)
|
||||||
@@ -873,9 +1080,22 @@ class AccountWorker:
|
|||||||
self.config, self.revision = value, revision
|
self.config, self.revision = value, revision
|
||||||
self.engine, self.active_identity, self.demo = engine, identity, False
|
self.engine, self.active_identity, self.demo = engine, identity, False
|
||||||
self._running = False
|
self._running = False
|
||||||
self.schedule.monitor(True)
|
self.schedule.monitor(True)
|
||||||
self.schedule.poll_finished(self.config)
|
self.schedule.poll_finished(self.config)
|
||||||
self._invalidate_views(clear=True)
|
self._game_succeeded(activated=True)
|
||||||
|
self._invalidate_views(clear=True)
|
||||||
|
# Activation and its new start authorization share the final
|
||||||
|
# generation check/lock. Never queue a start that could outlive
|
||||||
|
# a stop, logout or policy replacement during persistence.
|
||||||
|
try:
|
||||||
|
self._start({}, require_selection=False)
|
||||||
|
except ValueError as error:
|
||||||
|
message = login_message + ";策略保持停止:" + self.safe_text(str(error))
|
||||||
|
else:
|
||||||
|
message = login_message + ";策略已自动开启,仅执行已勾选的规则"
|
||||||
|
result = {"connected": True, "running": self._running,
|
||||||
|
"has_saved_password": self._has_saved_password, "message": message}
|
||||||
|
self.log(message)
|
||||||
except Exception:
|
except Exception:
|
||||||
with self.lock:
|
with self.lock:
|
||||||
self.engine, self.active_identity, self.demo = old_engine, previous_identity, old_demo
|
self.engine, self.active_identity, self.demo = old_engine, previous_identity, old_demo
|
||||||
@@ -895,8 +1115,7 @@ class AccountWorker:
|
|||||||
self.manager._release_identity(self, previous_identity)
|
self.manager._release_identity(self, previous_identity)
|
||||||
if old_client is not None and old_client is not client:
|
if old_client is not None and old_client is not client:
|
||||||
old_client.close()
|
old_client.close()
|
||||||
self._game_succeeded()
|
return result
|
||||||
return {"connected": True, "running": False, "has_saved_password": self._has_saved_password}
|
|
||||||
|
|
||||||
def _login(self, payload):
|
def _login(self, payload):
|
||||||
self.check_intent()
|
self.check_intent()
|
||||||
@@ -920,7 +1139,7 @@ class AccountWorker:
|
|||||||
self.schedule.monitor(False)
|
self.schedule.monitor(False)
|
||||||
self.securestore.save_credentials(account, password, remember)
|
self.securestore.save_credentials(account, password, remember)
|
||||||
self._refresh_login_metadata()
|
self._refresh_login_metadata()
|
||||||
flow = self.manager.login_factory(self.catalog, self.securestore.device(), trace=self.trace)
|
flow = self._password_login_flow()
|
||||||
client, response, context = flow.authenticate(account, password)
|
client, response, context = flow.authenticate(account, password)
|
||||||
try:
|
try:
|
||||||
self.check_intent()
|
self.check_intent()
|
||||||
@@ -1026,7 +1245,7 @@ class AccountWorker:
|
|||||||
self._invalidate_views()
|
self._invalidate_views()
|
||||||
return {"connected": False, "running": False, "has_saved_password": False}
|
return {"connected": False, "running": False, "has_saved_password": False}
|
||||||
|
|
||||||
def _start(self, payload):
|
def _start(self, payload, *, require_selection=True):
|
||||||
self.check_intent()
|
self.check_intent()
|
||||||
if not self.demo:
|
if not self.demo:
|
||||||
self._require_game()
|
self._require_game()
|
||||||
@@ -1037,10 +1256,13 @@ class AccountWorker:
|
|||||||
other = any(value[section]["enabled"] for section in ("quest_policy", "daily_policy", "sweep_policy", "explore_policy", "progression_policy"))
|
other = any(value[section]["enabled"] for section in ("quest_policy", "daily_policy", "sweep_policy", "explore_policy", "progression_policy"))
|
||||||
other = other or bool(policy["breakthrough_targets"]) or policy["gift_enabled"]
|
other = other or bool(policy["breakthrough_targets"]) or policy["gift_enabled"]
|
||||||
ranch = policy["enabled"] and any(policy[field] for field in ("buy", "fill", "dispatch", "collect", "feed"))
|
ranch = policy["enabled"] and any(policy[field] for field in ("buy", "fill", "dispatch", "collect", "feed"))
|
||||||
if not ranch and not other:
|
if require_selection and not ranch and not other:
|
||||||
raise ValueError("请先勾选至少一项功能,并启用对应策略")
|
raise ValueError("请先勾选至少一项功能,并启用对应策略")
|
||||||
if ranch and not other and not any(rule["enabled"] for rule in policy["egg_rules"].values()):
|
if require_selection and ranch and not other and not any(rule["enabled"] for rule in policy["egg_rules"].values()):
|
||||||
raise ValueError("请先在背包魔物蛋勾选要孵化的蛋,并设置优先级和孵出后的去向")
|
raise ValueError("请先在背包魔物蛋勾选要孵化的蛋,并设置优先级和孵出后的去向")
|
||||||
|
if (self.engine._progression_pending() or self.engine.explore_planner.pending(self.engine.snapshot)
|
||||||
|
or self.engine._breakthrough_pending):
|
||||||
|
raise ValueError("存在未确认的任务、战斗、探险或突破请求,禁止自动重发;请先核对")
|
||||||
with self.lock:
|
with self.lock:
|
||||||
self.check_intent()
|
self.check_intent()
|
||||||
self._running = self.engine.auto = True
|
self._running = self.engine.auto = True
|
||||||
@@ -1054,8 +1276,9 @@ class AccountWorker:
|
|||||||
return {"running": False}
|
return {"running": False}
|
||||||
|
|
||||||
def close(self, timeout=30):
|
def close(self, timeout=30):
|
||||||
self.stop()
|
|
||||||
with self.condition:
|
with self.condition:
|
||||||
|
self.suspend_auto_relogin()
|
||||||
|
self.stop()
|
||||||
self._closing = True
|
self._closing = True
|
||||||
for job in self._pending:
|
for job in self._pending:
|
||||||
job.status, job.error, job.payload = "cancelled", "账号正在关闭,操作已取消", {}
|
job.status, job.error, job.payload = "cancelled", "账号正在关闭,操作已取消", {}
|
||||||
@@ -1174,10 +1397,13 @@ class WebManager:
|
|||||||
if revision is not None and revision != worker.revision:
|
if revision is not None and revision != worker.revision:
|
||||||
raise RevisionConflict("策略已在其他页面更新,请刷新后重试")
|
raise RevisionConflict("策略已在其他页面更新,请刷新后重试")
|
||||||
changed = any(value.get(section) != worker.config.get(section) for section in
|
changed = any(value.get(section) != worker.config.get(section) for section in
|
||||||
("policy", "quest_policy", "daily_policy", "sweep_policy", "explore_policy", "progression_policy", "overrides"))
|
("policy", "quest_policy", "daily_policy", "sweep_policy", "explore_policy", "progression_policy", "overrides", "auto_relogin"))
|
||||||
|
login_changed = value["auto_relogin"] != worker.config["auto_relogin"]
|
||||||
if changed:
|
if changed:
|
||||||
worker.stop(keep_running=True)
|
worker.stop(keep_running=True)
|
||||||
job = worker.enqueue("__config", {"config": value, "revision": revision})
|
job = worker.enqueue("__config", {"config": value, "revision": revision})
|
||||||
|
if login_changed:
|
||||||
|
worker._auto_relogin_pending_config = (job["id"], deepcopy(value["auto_relogin"]))
|
||||||
return {"config": deepcopy(worker.config), "revision": worker.revision,
|
return {"config": deepcopy(worker.config), "revision": worker.revision,
|
||||||
"pending": True, "job_id": job["id"], "job": job}
|
"pending": True, "job_id": job["id"], "job": job}
|
||||||
|
|
||||||
@@ -1198,6 +1424,8 @@ class WebManager:
|
|||||||
worker._jobs[job.id] = job
|
worker._jobs[job.id] = job
|
||||||
return job.public()
|
return job.public()
|
||||||
if operation in STOP_ACTIONS or operation in {"login", "enter_server", "restore_session", "logout", "forget_login"}:
|
if operation in STOP_ACTIONS or operation in {"login", "enter_server", "restore_session", "logout", "forget_login"}:
|
||||||
|
if operation in {"login", "enter_server", "restore_session", "logout", "forget_login"}:
|
||||||
|
worker.suspend_auto_relogin()
|
||||||
worker.stop()
|
worker.stop()
|
||||||
consuming = operation not in READ_ACTIONS and operation not in LOCAL_ACTIONS and operation not in {"logout", "forget_login"}
|
consuming = operation not in READ_ACTIONS and operation not in LOCAL_ACTIONS and operation not in {"logout", "forget_login"}
|
||||||
return worker.enqueue(operation, payload, consuming=consuming)
|
return worker.enqueue(operation, payload, consuming=consuming)
|
||||||
|
|||||||
+13
-11
@@ -9,9 +9,10 @@ const current = () => state.accounts.get(state.active);
|
|||||||
const currentPage = () => { const account=current(); return account?.pages.get(account.page); };
|
const currentPage = () => { const account=current(); return account?.pages.get(account.page); };
|
||||||
const terminal = new Set(['succeeded','failed','cancelled']);
|
const terminal = new Set(['succeeded','failed','cancelled']);
|
||||||
const jobLabels = {queued:'排队中',running:'执行中',succeeded:'已完成',failed:'失败',cancelled:'已取消'};
|
const jobLabels = {queued:'排队中',running:'执行中',succeeded:'已完成',failed:'失败',cancelled:'已取消'};
|
||||||
const operationLabels = {login:'登录',enter_server:'进入区服',restore_session:'恢复会话',refresh:'刷新 / 预览',start:'开启策略',stop:'停止策略',set_config:'保存配置',import_config:'导入策略',import_yields:'导入收益',claim_daily:'领取每日奖励',quote_expansion:'读取扩建费用',expand:'扩建',sell:'派遣',feed:'喂养',lock:'锁定',unlock:'解锁'};
|
const operationLabels = {login:'获取区服',enter_server:'进入区服',restore_session:'恢复会话',refresh:'刷新 / 预览',start:'开启策略',stop:'停止策略',set_config:'保存配置',import_config:'导入策略',import_yields:'导入收益',claim_daily:'领取每日奖励',quote_expansion:'读取扩建费用',expand:'扩建',sell:'派遣',feed:'喂养',lock:'锁定',unlock:'解锁'};
|
||||||
const connectionLabels = {online:'已登录',retrying:'正在重试',expired:'登录已过期',offline:'游戏离线'};
|
const connectionLabels = {online:'已登录',retrying:'正在重试',expired:'登录已过期',offline:'游戏离线'};
|
||||||
const gameRefreshOperations = new Set(['start','refresh','refresh_maps','refresh_tasks']);
|
const gameRefreshOperations = new Set(['start','refresh','refresh_maps','refresh_tasks']);
|
||||||
|
const loginOperations = new Set(['enter_server','restore_session']);
|
||||||
|
|
||||||
function connectionState(summary) {
|
function connectionState(summary) {
|
||||||
if(summary?.demo)return 'online';
|
if(summary?.demo)return 'online';
|
||||||
@@ -57,6 +58,7 @@ function transportError(account,key,label,failure) {
|
|||||||
function connectionError(account) { return Object.assign(new Error(connectionDetails(account) || '请等待游戏连接恢复后再操作。'),{connection:true}); }
|
function connectionError(account) { return Object.assign(new Error(connectionDetails(account) || '请等待游戏连接恢复后再操作。'),{connection:true}); }
|
||||||
|
|
||||||
function renderPageConnection(page) {
|
function renderPageConnection(page) {
|
||||||
|
page.login?.updateStatus();
|
||||||
if(!page.connectionStatus){
|
if(!page.connectionStatus){
|
||||||
page.connectionStatus=el('p',{class:'page-summary','data-connection-status':'',hidden:true});
|
page.connectionStatus=el('p',{class:'page-summary','data-connection-status':'',hidden:true});
|
||||||
page.header.after(page.connectionStatus);
|
page.header.after(page.connectionStatus);
|
||||||
@@ -120,7 +122,7 @@ function renderSummary() {
|
|||||||
$('#refresh').disabled=!connected;$('#refresh').title=connected?'读取游戏状态并预览策略':details;
|
$('#refresh').disabled=!connected;$('#refresh').title=connected?'读取游戏状态并预览策略':details;
|
||||||
const task=account?[...account.jobs.values()].at(-1)?.job:null;
|
const task=account?[...account.jobs.values()].at(-1)?.job:null;
|
||||||
$('#job-status').textContent=task?`${operationLabels[task.operation] || task.operation} · ${jobLabels[task.status]}`:summary?.busy?'后台任务执行中':'';
|
$('#job-status').textContent=task?`${operationLabels[task.operation] || task.operation} · ${jobLabels[task.status]}`:summary?.busy?'后台任务执行中':'';
|
||||||
const message=[details || summary?.error || (demo?'当前为离线演示,不连接游戏服务器。':connected?'角色状态自动刷新;配置功能后开启策略。':'请在登录页输入账号密码,或恢复已保存会话。'),...transportMessages(account)].filter(Boolean).join(';');
|
const message=[details || summary?.error || (demo?'当前为离线演示,不连接游戏服务器。':connected?summary.running?'角色状态自动刷新,正在自动执行已配置且已勾选的功能;可在顶部“停止”。':'角色状态自动刷新;策略已停止,可在顶部“开启”继续执行已勾选功能。':'请在登录页输入账号密码,或恢复已保存会话。'),...transportMessages(account)].filter(Boolean).join(';');
|
||||||
$('#data-summary').textContent=message;$('#data-summary').title=message;
|
$('#data-summary').textContent=message;$('#data-summary').title=message;
|
||||||
account?.pages.forEach(renderPageConnection);renderStatus();
|
account?.pages.forEach(renderPageConnection);renderStatus();
|
||||||
syncSaveStatus(account);
|
syncSaveStatus(account);
|
||||||
@@ -246,7 +248,7 @@ async function perform(account,operation,payload={},options={}) {
|
|||||||
if(operation!=='stop')await flushConfig(account);
|
if(operation!=='stop')await flushConfig(account);
|
||||||
if(gameRefreshOperations.has(operation) && !gameAvailable(account))throw connectionError(account);
|
if(gameRefreshOperations.has(operation) && !gameAvailable(account))throw connectionError(account);
|
||||||
const job=await api.action(account.id,operation,payload);
|
const job=await api.action(account.id,operation,payload);
|
||||||
setStatus(`${operationLabels[operation] || '操作'}:${gameRefreshOperations.has(operation)&&job.status==='succeeded'?'等待确认游戏状态':jobLabels[job.status] || '已提交'}`);
|
setStatus(`${operationLabels[operation] || '操作'}:${(gameRefreshOperations.has(operation)||loginOperations.has(operation))&&job.status==='succeeded'?'等待确认游戏状态':jobLabels[job.status] || '已提交'}`);
|
||||||
const result=await trackJob(account,job);
|
const result=await trackJob(account,job);
|
||||||
if(!state.accounts.has(account.id))return result;
|
if(!state.accounts.has(account.id))return result;
|
||||||
if(result?.config){account.config=clone(result.config);account.revision=result.revision;}
|
if(result?.config){account.config=clone(result.config);account.revision=result.revision;}
|
||||||
@@ -254,12 +256,12 @@ async function perform(account,operation,payload={},options={}) {
|
|||||||
try{account.summary=await api.status(account.id);account.transportErrors.delete('status');}
|
try{account.summary=await api.status(account.id);account.transportErrors.delete('status');}
|
||||||
catch(failure){transportError(account,'status','Web 账号状态',failure);failure.connection=true;throw failure;}
|
catch(failure){transportError(account,'status','Web 账号状态',failure);failure.connection=true;throw failure;}
|
||||||
renderAccountTabs();renderSummary();
|
renderAccountTabs();renderSummary();
|
||||||
if((gameRefreshOperations.has(operation)||['enter_server','restore_session'].includes(operation)) && !gameAvailable(account)){setStatus('工作台状态已更新');throw connectionError(account);}
|
if((gameRefreshOperations.has(operation)||loginOperations.has(operation)) && !gameAvailable(account)){setStatus('工作台状态已更新');throw connectionError(account);}
|
||||||
const page=options.page || account.pages.get(account.page);if(page)await loadPage(page,true);
|
const page=options.page || account.pages.get(account.page);if(page)await loadPage(page,true);
|
||||||
if(operation==='login'&&result)account.pages.get('login')?.login?.update(result);
|
if(operation==='login'&&result)account.pages.get('login')?.login?.update(result);
|
||||||
if(operation==='enter_server'||operation==='restore_session')notice('已读取角色。策略保持关闭,请配置功能后开启。');
|
const message=loginOperations.has(operation)?account.summary.running?'已读取角色,已自动开启策略,执行已配置且已勾选的功能;可在顶部“停止”。':'已读取角色。策略已停止,可在顶部“开启”继续执行已勾选功能。':result?.message;
|
||||||
else if(result?.message)notice(result.message);
|
if(message)notice(message);
|
||||||
setStatus(result?.message || `${operationLabels[operation] || '操作'}已完成`);
|
setStatus(message || `${operationLabels[operation] || '操作'}已完成`);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -372,7 +374,7 @@ async function exportYields(account=current()) {
|
|||||||
async function command(name,account=current()) {
|
async function command(name,account=current()) {
|
||||||
try {
|
try {
|
||||||
if(name==='add-account'||name==='add-demo')return await addAccount(name==='add-demo');
|
if(name==='add-account'||name==='add-demo')return await addAccount(name==='add-demo');
|
||||||
if(name==='about')return dialog('关于牧场助手',el('div',{},el('p',{text:`牧羊人之心牧场助手 Web ${state.meta?.version || '2.0.0'}`}),el('p',{text:`游戏数据版本 ${state.meta?.gameVersion || '1.9.68'}`}),el('p',{class:'info-note',text:'与桌面助手共用核心策略。配置在服务端自动保存;运行开关在重启和恢复会话后保持关闭。'})),{info:true});
|
if(name==='about')return dialog('关于牧场助手',el('div',{},el('p',{text:`牧羊人之心牧场助手 Web ${state.meta?.version || '2.0.1'}`}),el('p',{text:`游戏数据版本 ${state.meta?.gameVersion || '1.9.68'}`}),el('p',{class:'info-note',text:'与桌面助手共用核心策略。配置在服务端自动保存;每次成功登录后自动执行已勾选功能,可在顶部“停止”。服务重启后须先成功登录才执行。'})),{info:true});
|
||||||
if(name==='updates')return await showUpdates();
|
if(name==='updates')return await showUpdates();
|
||||||
if(name==='admin-logout'){hideWorkbench();try{await api.logout();}finally{requireAuth();}return;}
|
if(name==='admin-logout'){hideWorkbench();try{await api.logout();}finally{requireAuth();}return;}
|
||||||
if(!account)throw new Error('请先新增或选择账号。');
|
if(!account)throw new Error('请先新增或选择账号。');
|
||||||
@@ -402,8 +404,8 @@ async function command(name,account=current()) {
|
|||||||
if(name==='import-config'){
|
if(name==='import-config'){
|
||||||
const file=await filePicker('.json');if(!file)return;if(file.size>1024*1024)throw new Error('策略文件过大。');
|
const file=await filePicker('.json');if(!file)return;if(file.size>1024*1024)throw new Error('策略文件过大。');
|
||||||
let config;try{config=JSON.parse(await file.text());}catch{throw new Error('策略文件不是有效的 JSON。');}
|
let config;try{config=JSON.parse(await file.text());}catch{throw new Error('策略文件不是有效的 JSON。');}
|
||||||
if(!await confirm('导入当前账号策略','将替换当前账号策略,策略运行保持关闭。',{confirm:'导入策略'}))return;
|
if(!await confirm('导入当前账号策略','将替换当前账号策略并停止执行;下次成功登录会自动执行已勾选功能。',{confirm:'导入策略'}))return;
|
||||||
await flushConfig(account);const result=await trackJob(account,await api.importConfig(account.id,config));await refreshConfig(account);notice('策略已导入,运行保持关闭。');await loadPage(getPage(account,account.page),true);return result;
|
await flushConfig(account);const result=await trackJob(account,await api.importConfig(account.id,config));await refreshConfig(account);notice('策略已导入,执行已停止;下次成功登录会自动执行已勾选功能。');await loadPage(getPage(account,account.page),true);return result;
|
||||||
}
|
}
|
||||||
if(name==='import-yields')return await importYields(account);
|
if(name==='import-yields')return await importYields(account);
|
||||||
if(name==='export-yields')return await exportYields(account);
|
if(name==='export-yields')return await exportYields(account);
|
||||||
@@ -575,7 +577,7 @@ async function bootstrap() {
|
|||||||
$('#app').hidden=false;
|
$('#app').hidden=false;
|
||||||
const [meta,schema]=await Promise.all([api.meta(),api.schema()]);state.meta=meta;state.schema=schema;
|
const [meta,schema]=await Promise.all([api.meta(),api.schema()]);state.meta=meta;state.schema=schema;
|
||||||
if(state.redirecting)return;
|
if(state.redirecting)return;
|
||||||
$('#app-version').textContent=meta.version || '2.0.0';$('#game-version').textContent=meta.gameVersion || '1.9.68';$('#access-mode').textContent=auth.access_mode==='local'||auth.access_mode==='loopback'?'本机工作台':auth.required?'管理工作台':'本机工作台';
|
$('#app-version').textContent=meta.version || '2.0.1';$('#game-version').textContent=meta.gameVersion || '1.9.68';$('#access-mode').textContent=auth.access_mode==='local'||auth.access_mode==='loopback'?'本机工作台':auth.required?'管理工作台':'本机工作台';
|
||||||
await syncAccounts();if(state.redirecting)return;state.ready=true;setStatus('工作台已连接');
|
await syncAccounts();if(state.redirecting)return;state.ready=true;setStatus('工作台已连接');
|
||||||
}catch(failure){if(failure.status===401||$('#app').hidden){requireAuth();return;}if(state.redirecting)return;setStatus(failure.message);$('#page-host').replaceChildren(el('div',{class:'initial-state'},el('p',{text:failure.message}),el('button',{text:'重新连接',onClick:bootstrap})));}
|
}catch(failure){if(failure.status===401||$('#app').hidden){requireAuth();return;}if(state.redirecting)return;setStatus(failure.message);$('#page-host').replaceChildren(el('div',{class:'initial-state'},el('p',{text:failure.message}),el('button',{text:'重新连接',onClick:bootstrap})));}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,7 +26,7 @@
|
|||||||
</div></details>
|
</div></details>
|
||||||
<details class="menu"><summary accesskey="h">帮助<span class="access-key">(H)</span></summary><div class="menu-popup"><button data-command="updates">检查版本更新…</button><button data-command="debug">调试日志</button><button data-command="about">关于…</button></div></details>
|
<details class="menu"><summary accesskey="h">帮助<span class="access-key">(H)</span></summary><div class="menu-popup"><button data-command="updates">检查版本更新…</button><button data-command="debug">调试日志</button><button data-command="about">关于…</button></div></details>
|
||||||
</nav>
|
</nav>
|
||||||
<span class="window-title">牧羊人之心牧场助手 <span id="app-version">2.0.0</span></span>
|
<span class="window-title">牧羊人之心牧场助手 <span id="app-version">2.0.1</span></span>
|
||||||
<span id="access-mode" class="muted">正在连接本地服务</span>
|
<span id="access-mode" class="muted">正在连接本地服务</span>
|
||||||
</header>
|
</header>
|
||||||
<div class="account-bar"><div id="account-tabs" class="account-tabs" role="tablist" aria-label="账号"></div><button id="add-account" class="compact" title="新增账号">+ 新增账号</button></div>
|
<div class="account-bar"><div id="account-tabs" class="account-tabs" role="tablist" aria-label="账号"></div><button id="add-account" class="compact" title="新增账号">+ 新增账号</button></div>
|
||||||
|
|||||||
@@ -15,6 +15,11 @@ class LoginPage {
|
|||||||
constructor(host, page) {
|
constructor(host, page) {
|
||||||
this.page = page;
|
this.page = page;
|
||||||
this.root = el('div', {class: 'login-layout'});
|
this.root = el('div', {class: 'login-layout'});
|
||||||
|
this.autoReloginMessage = el('p', {role: 'status'});
|
||||||
|
this.autoReloginCountdown = el('p', {'data-auto-relogin-countdown': '', role: 'timer', 'aria-live': 'off', hidden: true});
|
||||||
|
this.autoReloginCredentials = el('p', {'data-auto-relogin-credentials': '', role: 'status', hidden: true,
|
||||||
|
text: '缺少服务端记住的账号和密码。请勾选“记住账号和密码”并完成登录,才能自动重登原区服角色。'});
|
||||||
|
this.autoReloginStatus = el('div', {class: 'page-summary', 'data-auto-relogin-status': ''}, this.autoReloginMessage, this.autoReloginCountdown, this.autoReloginCredentials);
|
||||||
this.account = el('input', {type: 'text', name: 'game-account', autocomplete: 'username', 'aria-label': '游戏账号'});
|
this.account = el('input', {type: 'text', name: 'game-account', autocomplete: 'username', 'aria-label': '游戏账号'});
|
||||||
this.password = el('input', {type: 'password', name: 'game-password', autocomplete: 'current-password', 'aria-label': '游戏密码'});
|
this.password = el('input', {type: 'password', name: 'game-password', autocomplete: 'current-password', 'aria-label': '游戏密码'});
|
||||||
this.remember = el('input', {type: 'checkbox', checked: true});
|
this.remember = el('input', {type: 'checkbox', checked: true});
|
||||||
@@ -43,22 +48,41 @@ class LoginPage {
|
|||||||
this.restore = el('button', {type: 'button', text: '恢复选中会话(无需重新输密码)', disabled: true, onClick: () => page.perform('restore_session', {session_id: this.saved.value}).catch(page.error)});
|
this.restore = el('button', {type: 'button', text: '恢复选中会话(无需重新输密码)', disabled: true, onClick: () => page.perform('restore_session', {session_id: this.saved.value}).catch(page.error)});
|
||||||
this.root.append(form,
|
this.root.append(form,
|
||||||
field('第二步:区服 / 角色', el('div', {class: 'server-row'}, this.servers, this.enter)),
|
field('第二步:区服 / 角色', el('div', {class: 'server-row'}, this.servers, this.enter)),
|
||||||
el('p', {class: 'info-note', text: '账号验证 → 获取官方区服 → 选择区服 → 进入区服 → 读取角色。登录后自动刷新状态,配置功能后开启顶部策略。'}),
|
el('p', {class: 'info-note', text: '账号验证 → 获取官方区服 → 选择区服 → 进入区服 → 读取角色。成功登录后自动刷新状态并执行已配置且已勾选的功能,可在顶部“停止”。'}),
|
||||||
el('div', {class: 'session-block policy-form'}, field('已保存账号 / 区服 / 角色', this.saved), el('div', {class: 'login-actions'}, this.restore)),
|
el('div', {class: 'session-block policy-form'}, field('已保存账号 / 区服 / 角色', this.saved), el('div', {class: 'login-actions'}, this.restore)),
|
||||||
el('div', {class: 'page-toolbar'}, el('button', {type: 'button', text: '退出登录', onClick: () => page.perform('logout').catch(page.error)}),
|
el('div', {class: 'page-toolbar'}, el('button', {type: 'button', text: '退出登录', onClick: () => page.perform('logout').catch(page.error)}),
|
||||||
el('button', {type: 'button', text: '退出并清除登录记录…', onClick: () => page.options.command('forget-login', page.account)})),
|
el('button', {type: 'button', text: '退出并清除登录记录…', onClick: () => page.options.command('forget-login', page.account)})),
|
||||||
el('p', {class: 'info-note', text: '记住的账号密码和登录会话由服务端加密保存。浏览器不会保存游戏凭据。退出或恢复会话后,策略保持关闭。'}));
|
el('p', {class: 'info-note', text: '记住的账号密码和登录会话由服务端加密保存。浏览器不会保存游戏凭据。手动选服、恢复会话和自动重登成功后,均自动执行已勾选功能;退出登录后停止执行。'}));
|
||||||
host.append(this.root);
|
host.append(this.autoReloginStatus, this.root);
|
||||||
}
|
}
|
||||||
|
|
||||||
update(data) {
|
update(data) {
|
||||||
const login = data.login || data.details?.login || data;
|
const login = data.login || data.details?.login || data;
|
||||||
if (login.account && !this.account.value && document.activeElement !== this.account) this.account.value = login.account;
|
if (login.account && !this.account.value && document.activeElement !== this.account) this.account.value = login.account;
|
||||||
if (login.has_saved_password !== undefined) this.password.placeholder = login.has_saved_password ? '已在服务端加密保存;留空使用已保存密码' : '输入游戏密码';
|
if (login.has_saved_password !== undefined) {
|
||||||
|
this.hasSavedPassword = login.has_saved_password;
|
||||||
|
this.password.placeholder = login.has_saved_password ? '已在服务端加密保存;留空使用已保存密码' : '输入游戏密码';
|
||||||
|
}
|
||||||
if (Array.isArray(login.servers)) this.updateOptions(this.servers, login.servers.map(server => ({value: server.id ?? server.server_id, label: `${server.name}${server.role_name ? ` · ${server.role_name}` : ''}`})), '请先获取区服');
|
if (Array.isArray(login.servers)) this.updateOptions(this.servers, login.servers.map(server => ({value: server.id ?? server.server_id, label: `${server.name}${server.role_name ? ` · ${server.role_name}` : ''}`})), '请先获取区服');
|
||||||
if (Array.isArray(login.saved_sessions)) this.updateOptions(this.saved, login.saved_sessions.map(session => ({value: session.id ?? session.session_id, label: session.label || [session.account, session.server_name || session.server, session.role_name || session.name].filter(Boolean).join(' · ')})), '暂无已保存会话');
|
if (Array.isArray(login.saved_sessions)) this.updateOptions(this.saved, login.saved_sessions.map(session => ({value: session.id ?? session.session_id, label: session.label || [session.account, session.server_name || session.server, session.role_name || session.name].filter(Boolean).join(' · ')})), '暂无已保存会话');
|
||||||
this.enter.disabled = !this.servers.value;
|
this.enter.disabled = !this.servers.value;
|
||||||
this.restore.disabled = !this.saved.value;
|
this.restore.disabled = !this.saved.value;
|
||||||
|
this.updateStatus();
|
||||||
|
}
|
||||||
|
|
||||||
|
updateStatus() {
|
||||||
|
const enabled = this.page.account.config?.auto_relogin?.enabled === true;
|
||||||
|
const status = this.page.account.summary?.auto_relogin_status;
|
||||||
|
const message = status?.message || (enabled ? '自动重登已开启,等待服务端状态。' : '自动重登未开启。');
|
||||||
|
if (this.autoReloginMessage.textContent !== message) this.autoReloginMessage.textContent = message;
|
||||||
|
this.autoReloginCredentials.hidden = !enabled || this.hasSavedPassword !== false;
|
||||||
|
const attemptAt = typeof status?.next_attempt_at === 'string' ? Date.parse(status.next_attempt_at) : NaN;
|
||||||
|
this.autoReloginCountdown.hidden = !enabled || !Number.isFinite(attemptAt);
|
||||||
|
if (!this.autoReloginCountdown.hidden) {
|
||||||
|
const remaining = Math.max(0, Math.ceil((attemptAt - Date.now()) / 1000));
|
||||||
|
const countdown = remaining ? `${remaining} 秒后自动重新登录(${chinaTime(status.next_attempt_at, {date: true})},北京时间)` : '等待服务端执行自动重登';
|
||||||
|
if (this.autoReloginCountdown.textContent !== countdown) this.autoReloginCountdown.textContent = countdown;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
updateOptions(select, options, placeholder) {
|
updateOptions(select, options, placeholder) {
|
||||||
|
|||||||
@@ -0,0 +1,467 @@
|
|||||||
|
"""Offline auto-relogin UI contract; only disposable demos and mocked DTOs.
|
||||||
|
|
||||||
|
Run: python -m unittest ranch_web.tests.browser.test_auto_relogin_browser -v
|
||||||
|
No game actions, private account directories, or private access files are used.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import copy
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
import json
|
||||||
|
from types import SimpleNamespace
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
from urllib.parse import urlsplit
|
||||||
|
|
||||||
|
from ranch_assistant.model import Catalog
|
||||||
|
from ranch_web.policies import default_config, export_config
|
||||||
|
from ranch_web.views import build_view, schema
|
||||||
|
from . import test_workbench_browser as fixtures
|
||||||
|
|
||||||
|
if fixtures.AVAILABLE:
|
||||||
|
from playwright.sync_api import expect
|
||||||
|
|
||||||
|
|
||||||
|
class AutoReloginSchemaTests(unittest.TestCase):
|
||||||
|
def test_login_schema_and_view_expose_native_controls_with_defaults(self):
|
||||||
|
catalog = Catalog()
|
||||||
|
fields = next(page["form"] for page in schema(catalog)["pages"] if page["key"] == "login")
|
||||||
|
fields = {tuple(field["path"]): field for field in fields}
|
||||||
|
enabled = fields[("auto_relogin", "enabled")]
|
||||||
|
delay = fields[("auto_relogin", "delay_minutes")]
|
||||||
|
self.assertEqual(enabled["label"], "掉线后自动重新登录")
|
||||||
|
self.assertEqual(enabled["type"], "boolean")
|
||||||
|
self.assertIs(enabled["value"], False)
|
||||||
|
self.assertEqual((delay["type"], delay["min"], delay["max"], delay["value"]), ("integer", 1, 10080, 30))
|
||||||
|
engine = SimpleNamespace(catalog=catalog, snapshot=None, demo=False)
|
||||||
|
view = build_view(engine, "login", default_config())
|
||||||
|
values = {tuple(field["path"]): field["value"] for field in view["form"]}
|
||||||
|
self.assertIs(values[("auto_relogin", "enabled")], False)
|
||||||
|
self.assertEqual(values[("auto_relogin", "delay_minutes")], 30)
|
||||||
|
|
||||||
|
|
||||||
|
@unittest.skipUnless(fixtures.AVAILABLE, "Python Playwright and a system Chromium browser are required")
|
||||||
|
class AutoReloginBrowserTests(unittest.TestCase):
|
||||||
|
@classmethod
|
||||||
|
def setUpClass(cls):
|
||||||
|
cls.http_guard = patch("requests.sessions.Session.request", side_effect=AssertionError("Live HTTP is forbidden"))
|
||||||
|
cls.http_guard.start()
|
||||||
|
try:
|
||||||
|
fixtures.WorkbenchBrowserTests.setUpClass.__func__(cls)
|
||||||
|
except BaseException:
|
||||||
|
cls.http_guard.stop()
|
||||||
|
raise
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def tearDownClass(cls):
|
||||||
|
try:
|
||||||
|
fixtures.WorkbenchBrowserTests.tearDownClass.__func__(cls)
|
||||||
|
finally:
|
||||||
|
cls.http_guard.stop()
|
||||||
|
|
||||||
|
await_job = fixtures.WorkbenchBrowserTests.await_job
|
||||||
|
open = fixtures.WorkbenchBrowserTests.open
|
||||||
|
go = fixtures.WorkbenchBrowserTests.go
|
||||||
|
fulfill = staticmethod(fixtures.WorkbenchBrowserTests.fulfill)
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
fixtures.WorkbenchBrowserTests.setUp(self)
|
||||||
|
self.context.set_default_timeout(5000)
|
||||||
|
self.external_requests, self.unexpected_actions, self.writes, self.actions = [], [], [], []
|
||||||
|
self.action_handlers = {}
|
||||||
|
self.view_calls = 0
|
||||||
|
self.configs, self.summaries, self.login_data = {}, {}, {}
|
||||||
|
engine = SimpleNamespace(catalog=Catalog(), snapshot=None, demo=False)
|
||||||
|
for identifier in (self.first, self.second):
|
||||||
|
self.configs[identifier] = copy.deepcopy(default_config())
|
||||||
|
self.configs[identifier]["auto_relogin"] = {"enabled": False, "delay_minutes": 30}
|
||||||
|
summary = copy.deepcopy(self.manager.status(identifier))
|
||||||
|
summary.update(demo=False, connected=False, running=False, connection_state="offline",
|
||||||
|
connection_message="尚未连接游戏", error="", revision=9000)
|
||||||
|
summary["auto_relogin_status"] = {"state": "disabled", "message": "自动重登未开启", "next_attempt_at": None}
|
||||||
|
self.summaries[identifier] = summary
|
||||||
|
self.login_data[identifier] = build_view(engine, "login", default_config())
|
||||||
|
self.login_data[identifier].update(account="offline-fixture", has_saved_password=True)
|
||||||
|
|
||||||
|
def local_fixture(route):
|
||||||
|
request = route.request
|
||||||
|
if not request.url.startswith(self.base + "/"):
|
||||||
|
self.external_requests.append(request.url)
|
||||||
|
route.abort()
|
||||||
|
return
|
||||||
|
path = urlsplit(request.url).path
|
||||||
|
if path == "/api/accounts":
|
||||||
|
self.fulfill(route, list(self.summaries.values()))
|
||||||
|
return
|
||||||
|
for identifier in (self.first, self.second):
|
||||||
|
prefix = f"/api/accounts/{identifier}"
|
||||||
|
if path == prefix + "/status":
|
||||||
|
self.fulfill(route, self.summaries[identifier])
|
||||||
|
return
|
||||||
|
if path == prefix + "/config":
|
||||||
|
if request.method == "PUT":
|
||||||
|
body = copy.deepcopy(request.post_data_json)
|
||||||
|
self.writes.append((identifier, body))
|
||||||
|
self.configs[identifier] = body["config"]
|
||||||
|
self.summaries[identifier]["revision"] += 1
|
||||||
|
self.fulfill(route, {"config": self.configs[identifier], "revision": self.summaries[identifier]["revision"]})
|
||||||
|
return
|
||||||
|
if path == prefix + "/views/login":
|
||||||
|
self.view_calls += 1
|
||||||
|
self.fulfill(route, {"loading": False, "data": self.login_data[identifier], "revision": self.summaries[identifier]["revision"]})
|
||||||
|
return
|
||||||
|
if path.startswith(prefix + "/actions/"):
|
||||||
|
operation = path.rsplit("/", 1)[-1]
|
||||||
|
self.actions.append((identifier, operation, request.post_data_json))
|
||||||
|
handler = self.action_handlers.get((identifier, operation))
|
||||||
|
if handler:
|
||||||
|
self.fulfill(route, handler(request.post_data_json))
|
||||||
|
return
|
||||||
|
if operation != "logout":
|
||||||
|
self.unexpected_actions.append(operation)
|
||||||
|
route.abort()
|
||||||
|
return
|
||||||
|
self.summaries[identifier].update(connected=False, running=False, connection_state="offline")
|
||||||
|
self.set_status(identifier, "cancelled", "手动退出登录,已取消本次自动重登")
|
||||||
|
self.fulfill(route, {"id": "mock-logout", "operation": operation, "status": "succeeded",
|
||||||
|
"result": {"message": "已退出登录并取消自动重登"}})
|
||||||
|
return
|
||||||
|
if request.method in ("POST", "PUT", "DELETE", "PATCH"):
|
||||||
|
self.unexpected_actions.append(path)
|
||||||
|
route.abort()
|
||||||
|
else:
|
||||||
|
route.continue_()
|
||||||
|
|
||||||
|
self.context.route("**/*", local_fixture)
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
try:
|
||||||
|
self.assertEqual(self.external_requests, [])
|
||||||
|
self.assertEqual(self.unexpected_actions, [], "UI must only submit explicitly requested fixture actions")
|
||||||
|
self.assertEqual(self.errors, [])
|
||||||
|
finally:
|
||||||
|
fixtures.WorkbenchBrowserTests.tearDown(self)
|
||||||
|
|
||||||
|
def set_status(self, identifier, state, message, next_attempt_at=None):
|
||||||
|
self.summaries[identifier]["auto_relogin_status"] = {
|
||||||
|
"state": state, "message": message, "next_attempt_at": next_attempt_at}
|
||||||
|
|
||||||
|
def waiting(self, identifier=None, *, seconds=45, message="掉线后等待自动重登"):
|
||||||
|
identifier = identifier or self.first
|
||||||
|
self.configs[identifier]["auto_relogin"]["enabled"] = True
|
||||||
|
target = (datetime.now(timezone.utc) + timedelta(seconds=seconds)).isoformat().replace("+00:00", "Z")
|
||||||
|
self.set_status(identifier, "waiting", message, target)
|
||||||
|
return target
|
||||||
|
|
||||||
|
def controls(self, panel):
|
||||||
|
return panel.get_by_role("checkbox", name="掉线后自动重新登录", exact=True), panel.get_by_role("spinbutton", name="重登等待时长(分钟)", exact=True)
|
||||||
|
|
||||||
|
def saved(self, identifier, enabled, minutes):
|
||||||
|
self.page.wait_for_function("() => document.querySelector('#save-status').textContent === '策略已自动保存'")
|
||||||
|
self.assertEqual(self.configs[identifier]["auto_relogin"], {"enabled": enabled, "delay_minutes": minutes})
|
||||||
|
|
||||||
|
def complete_login(self, operation, *, running=True):
|
||||||
|
self.summaries[self.first].update(connected=True, connection_state="online",
|
||||||
|
connection_message="游戏连接正常", error="", running=running)
|
||||||
|
return {"id": "mock-" + operation, "operation": operation, "status": "succeeded", "result": {}}
|
||||||
|
|
||||||
|
def test_defaults_visible_explanations_and_existing_layout(self):
|
||||||
|
self.open()
|
||||||
|
panel = self.go("login")
|
||||||
|
enabled, delay = self.controls(panel)
|
||||||
|
expect(enabled).to_be_visible()
|
||||||
|
expect(enabled).not_to_be_checked()
|
||||||
|
expect(delay).to_have_value("30")
|
||||||
|
for attribute, value in (("min", "1"), ("max", "10080"), ("step", "1")):
|
||||||
|
expect(delay).to_have_attribute(attribute, value)
|
||||||
|
for text in ("服务端", "记住账号和密码", "原区服", "角色", "恢复监控", "自动执行已勾选功能", "顶部“停止”", "关闭页面", "服务重启"):
|
||||||
|
expect(panel).to_contain_text(text)
|
||||||
|
self.assertTrue(enabled.evaluate("node => Boolean(node.closest('.policy-form'))"))
|
||||||
|
self.assertTrue(enabled.evaluate("node => Boolean(node.compareDocumentPosition(document.querySelector('.login-layout')) & Node.DOCUMENT_POSITION_FOLLOWING)"))
|
||||||
|
expect(panel.get_by_role("button", name="保存", exact=True)).to_have_count(0)
|
||||||
|
for width, height in ((1280, 800), (390, 844)):
|
||||||
|
self.page.set_viewport_size({"width": width, "height": height})
|
||||||
|
self.assertLessEqual(self.page.evaluate("document.documentElement.scrollWidth"), width)
|
||||||
|
expect(enabled).to_be_visible()
|
||||||
|
self.assertEqual(self.writes, [])
|
||||||
|
self.assertEqual(self.actions, [])
|
||||||
|
|
||||||
|
def test_server_candidates_wait_for_role_then_run_only_selected_features_and_allow_stop(self):
|
||||||
|
self.configs[self.first]["daily_policy"].update(enabled=True, selected=["gift"])
|
||||||
|
original = copy.deepcopy(self.configs[self.first])
|
||||||
|
candidates = {"servers": [{"id": 7, "name": "离线测试区", "role_name": "离线角色"}]}
|
||||||
|
|
||||||
|
def login(payload):
|
||||||
|
self.login_data[self.first].update(candidates)
|
||||||
|
return {"id": "mock-login", "operation": "login", "status": "succeeded", "result": candidates}
|
||||||
|
|
||||||
|
def stop(payload):
|
||||||
|
self.summaries[self.first]["running"] = False
|
||||||
|
return {"id": "mock-stop", "operation": "stop", "status": "succeeded", "result": {"message": "策略已停止"}}
|
||||||
|
|
||||||
|
self.action_handlers.update({(self.first, "login"): login,
|
||||||
|
(self.first, "enter_server"): lambda payload: self.complete_login("enter_server"),
|
||||||
|
(self.first, "stop"): stop})
|
||||||
|
self.open()
|
||||||
|
panel = self.go("login")
|
||||||
|
panel.get_by_label("游戏账号", exact=True).fill("offline-role-test")
|
||||||
|
panel.get_by_label("游戏密码", exact=True).fill("synthetic-password")
|
||||||
|
panel.get_by_role("button", name="账号密码登录 / 获取区服", exact=True).click()
|
||||||
|
expect(panel.get_by_label("区服 / 角色", exact=True)).to_contain_text("离线测试区")
|
||||||
|
expect(self.page.locator("#connection")).to_have_text("游戏离线")
|
||||||
|
toggle = self.page.locator("#strategy-toggle")
|
||||||
|
expect(toggle).to_have_text("开启")
|
||||||
|
expect(toggle).to_be_disabled()
|
||||||
|
expect(self.page.locator("#notice")).to_be_hidden()
|
||||||
|
self.assertFalse(self.summaries[self.first]["running"])
|
||||||
|
panel.get_by_role("button", name="进入选中区服", exact=True).click()
|
||||||
|
expect(toggle).to_have_text("停止")
|
||||||
|
expect(toggle).to_have_attribute("aria-pressed", "true")
|
||||||
|
expect(self.page.locator("#notice")).to_contain_text("已自动开启策略")
|
||||||
|
expect(self.page.locator("#status-text")).to_contain_text("已配置且已勾选的功能")
|
||||||
|
expect(self.page.locator("#data-summary")).to_contain_text("顶部“停止”")
|
||||||
|
expect(self.page.locator("#page-tabs [role=tab]")).to_have_count(15)
|
||||||
|
self.assertEqual(self.configs[self.first], original, "Logging in must preserve every feature selection")
|
||||||
|
toggle.click()
|
||||||
|
expect(toggle).to_have_text("开启")
|
||||||
|
expect(self.page.locator("#data-summary")).to_contain_text("策略已停止")
|
||||||
|
self.assertEqual([operation for _, operation, _ in self.actions], ["login", "enter_server", "stop"])
|
||||||
|
self.assertEqual(self.actions[1][2], {"server_id": "7"})
|
||||||
|
self.assertEqual(self.configs[self.first], original)
|
||||||
|
self.assertEqual(self.writes, [])
|
||||||
|
|
||||||
|
def test_import_stays_stopped_and_next_restored_session_runs_imported_selection(self):
|
||||||
|
imported = copy.deepcopy(default_config())
|
||||||
|
imported["daily_policy"].update(enabled=True, selected=["gift"])
|
||||||
|
portable = export_config(imported)
|
||||||
|
imports = []
|
||||||
|
self.login_data[self.first]["saved_sessions"] = [{"id": "offline-session", "label": "离线区服 / 原角色"}]
|
||||||
|
self.action_handlers[(self.first, "restore_session")] = lambda payload: self.complete_login("restore_session")
|
||||||
|
|
||||||
|
def import_config(route):
|
||||||
|
imports.append(route.request.post_data_json)
|
||||||
|
self.configs[self.first] = copy.deepcopy(imported)
|
||||||
|
self.summaries[self.first]["running"] = False
|
||||||
|
self.summaries[self.first]["revision"] += 1
|
||||||
|
self.fulfill(route, {"id": "mock-import", "operation": "import_config", "status": "succeeded", "result": {}})
|
||||||
|
|
||||||
|
self.page.route(f"**/api/accounts/{self.first}/config/import", import_config)
|
||||||
|
self.open()
|
||||||
|
panel = self.go("login")
|
||||||
|
self.page.locator('.menu > summary').nth(2).click()
|
||||||
|
with self.page.expect_file_chooser() as chooser:
|
||||||
|
self.page.locator('[data-command="import-config"]').click()
|
||||||
|
chooser.value.set_files({"name": "offline-policy.json", "mimeType": "application/json",
|
||||||
|
"buffer": json.dumps(portable).encode("utf-8")})
|
||||||
|
expect(self.page.locator("#dialog-content")).to_contain_text("下次成功登录会自动执行已勾选功能")
|
||||||
|
self.page.locator("#dialog-confirm").click()
|
||||||
|
expect(self.page.locator("#notice")).to_contain_text("策略已导入,执行已停止")
|
||||||
|
expect(self.page.locator("#strategy-toggle")).to_be_disabled()
|
||||||
|
self.assertEqual(imports, [portable])
|
||||||
|
self.assertEqual(self.actions, [])
|
||||||
|
panel.get_by_role("button", name="恢复选中会话(无需重新输密码)", exact=True).click()
|
||||||
|
expect(self.page.locator("#strategy-toggle")).to_have_text("停止")
|
||||||
|
expect(self.page.locator("#notice")).to_contain_text("已自动开启策略")
|
||||||
|
self.assertEqual(self.actions, [(self.first, "restore_session", {"session_id": "offline-session"})])
|
||||||
|
self.assertEqual(self.configs[self.first], imported, "Restoring must preserve imported selections")
|
||||||
|
self.assertEqual(self.writes, [])
|
||||||
|
|
||||||
|
def test_failed_candidates_and_disconnected_success_jobs_never_report_login_success(self):
|
||||||
|
self.login_data[self.first].update(servers=[{"id": 7, "name": "候选区服"}],
|
||||||
|
saved_sessions=[{"id": "offline-session", "label": "候选角色"}])
|
||||||
|
for operation, label in (("enter_server", "进入选中区服"), ("restore_session", "恢复选中会话(无需重新输密码)")):
|
||||||
|
for job_status in ("failed", "succeeded"):
|
||||||
|
with self.subTest(operation=operation, job_status=job_status):
|
||||||
|
self.action_handlers[(self.first, operation)] = lambda payload, op=operation, status=job_status: {
|
||||||
|
"id": "mock-candidate", "operation": op, "status": status,
|
||||||
|
"error": "候选角色验证失败", "result": {"message": "候选声称登录成功"}}
|
||||||
|
self.open()
|
||||||
|
panel = self.go("login")
|
||||||
|
self.page.evaluate("""() => {
|
||||||
|
window.loginFeedback = [];
|
||||||
|
new MutationObserver(() => {
|
||||||
|
for (const id of ['status-text', 'notice']) {
|
||||||
|
const node = document.getElementById(id);
|
||||||
|
if (node && !node.hidden) window.loginFeedback.push(node.textContent);
|
||||||
|
}
|
||||||
|
}).observe(document.body, {subtree:true, childList:true, characterData:true,
|
||||||
|
attributes:true, attributeFilter:['hidden']});
|
||||||
|
}""")
|
||||||
|
panel.get_by_role("button", name=label, exact=True).click()
|
||||||
|
expect(self.page.locator("#notice.error")).to_be_visible()
|
||||||
|
expect(self.page.locator("#notice")).to_contain_text("候选角色验证失败" if job_status == "failed" else "尚未连接游戏")
|
||||||
|
expect(self.page.locator("#connection")).to_have_text("游戏离线")
|
||||||
|
expect(self.page.locator("#strategy-toggle")).to_be_disabled()
|
||||||
|
feedback = "\n".join(self.page.evaluate("window.loginFeedback"))
|
||||||
|
for false_success in ("已完成", "已读取角色", "已自动开启策略", "候选声称登录成功"):
|
||||||
|
self.assertNotIn(false_success, feedback)
|
||||||
|
self.assertNotIn("start", [operation for _, operation, _ in self.actions])
|
||||||
|
self.assertEqual(self.writes, [])
|
||||||
|
|
||||||
|
def test_stop_after_restore_is_shown_from_confirmed_server_status(self):
|
||||||
|
self.login_data[self.first]["saved_sessions"] = [{"id": "offline-session", "label": "离线角色"}]
|
||||||
|
self.action_handlers[(self.first, "restore_session")] = lambda payload: self.complete_login("restore_session", running=False)
|
||||||
|
self.open()
|
||||||
|
panel = self.go("login")
|
||||||
|
panel.get_by_role("button", name="恢复选中会话(无需重新输密码)", exact=True).click()
|
||||||
|
expect(self.page.locator("#connection")).to_have_text("已登录")
|
||||||
|
expect(self.page.locator("#notice")).to_contain_text("策略已停止")
|
||||||
|
expect(self.page.locator("#notice")).not_to_contain_text("已自动开启")
|
||||||
|
expect(self.page.locator("#data-summary")).to_contain_text("策略已停止")
|
||||||
|
expect(self.page.locator("#strategy-toggle")).to_have_text("开启")
|
||||||
|
self.assertEqual(self.actions, [(self.first, "restore_session", {"session_id": "offline-session"})])
|
||||||
|
|
||||||
|
def test_native_autosave_range_validation_refresh_and_focus(self):
|
||||||
|
self.open()
|
||||||
|
panel = self.go("login")
|
||||||
|
enabled, delay = self.controls(panel)
|
||||||
|
enabled.check()
|
||||||
|
checkbox = enabled.element_handle()
|
||||||
|
self.page.wait_for_timeout(850)
|
||||||
|
self.saved(self.first, True, 30)
|
||||||
|
self.assertTrue(enabled.evaluate("(node, original) => node === original && node === document.activeElement", checkbox))
|
||||||
|
delay.fill("47")
|
||||||
|
original = delay.element_handle()
|
||||||
|
before = self.view_calls
|
||||||
|
self.page.wait_for_timeout(5200)
|
||||||
|
self.saved(self.first, True, 47)
|
||||||
|
self.assertGreater(self.view_calls, before, "Offline login DTOs must keep refreshing")
|
||||||
|
self.assertTrue(delay.evaluate("(node, original) => node === original && node === document.activeElement", original))
|
||||||
|
for invalid in ("0", "10081", "1.5", ""):
|
||||||
|
count = len(self.writes)
|
||||||
|
delay.fill(invalid)
|
||||||
|
self.page.wait_for_timeout(650)
|
||||||
|
expect(delay).to_have_value(invalid)
|
||||||
|
self.assertEqual(len(self.writes), count, "Invalid or partial minutes must stay local")
|
||||||
|
for valid in (1, 10080):
|
||||||
|
delay.fill(str(valid))
|
||||||
|
self.page.wait_for_timeout(850)
|
||||||
|
self.saved(self.first, True, valid)
|
||||||
|
enabled.uncheck()
|
||||||
|
self.page.wait_for_timeout(850)
|
||||||
|
self.saved(self.first, False, 10080)
|
||||||
|
self.assertEqual(self.actions, [])
|
||||||
|
|
||||||
|
def test_missing_remembered_password_hint_never_sends_password_or_changes_remember(self):
|
||||||
|
self.login_data[self.first]["has_saved_password"] = False
|
||||||
|
self.summaries[self.first].pop("auto_relogin_status")
|
||||||
|
self.open()
|
||||||
|
panel = self.go("login")
|
||||||
|
remember = panel.get_by_role("checkbox", name="记住账号和密码", exact=True)
|
||||||
|
remember.uncheck()
|
||||||
|
panel.get_by_role("textbox", name="游戏密码", exact=True).fill("mock-secret-never-send")
|
||||||
|
enabled, _ = self.controls(panel)
|
||||||
|
enabled.check()
|
||||||
|
hint = panel.locator("[data-auto-relogin-credentials]")
|
||||||
|
expect(hint).to_be_visible()
|
||||||
|
expect(hint).to_contain_text("缺少")
|
||||||
|
expect(hint).to_contain_text("记住账号和密码")
|
||||||
|
self.page.wait_for_timeout(1000)
|
||||||
|
self.saved(self.first, True, 30)
|
||||||
|
expect(remember).not_to_be_checked()
|
||||||
|
self.assertTrue(self.writes)
|
||||||
|
payloads = json.dumps(self.writes, ensure_ascii=False)
|
||||||
|
self.assertNotIn("mock-secret-never-send", payloads)
|
||||||
|
self.assertNotIn('"password"', payloads)
|
||||||
|
self.assertNotIn('"remember"', payloads)
|
||||||
|
self.assertEqual(self.actions, [])
|
||||||
|
self.login_data[self.first]["has_saved_password"] = True
|
||||||
|
expect(hint).to_be_hidden(timeout=7000)
|
||||||
|
|
||||||
|
def test_account_switch_isolates_pending_edits_status_and_minutes(self):
|
||||||
|
self.waiting(message="账号一正在等待自动重登")
|
||||||
|
self.set_status(self.second, "disabled", "账号二未开启自动重登")
|
||||||
|
self.open()
|
||||||
|
panel = self.go("login")
|
||||||
|
_, delay = self.controls(panel)
|
||||||
|
delay.fill("17")
|
||||||
|
self.page.locator(f'.account-tab[data-account="{self.second}"]').click()
|
||||||
|
panel = self.go("login")
|
||||||
|
enabled, second_delay = self.controls(panel)
|
||||||
|
expect(enabled).not_to_be_checked()
|
||||||
|
expect(second_delay).to_have_value("30")
|
||||||
|
expect(panel.locator("[data-auto-relogin-status]")).to_contain_text("账号二未开启")
|
||||||
|
expect(panel).not_to_contain_text("账号一正在等待")
|
||||||
|
enabled.check()
|
||||||
|
second_delay.fill("9")
|
||||||
|
self.page.wait_for_timeout(1000)
|
||||||
|
self.saved(self.second, True, 9)
|
||||||
|
self.assertEqual(self.configs[self.first]["auto_relogin"], {"enabled": True, "delay_minutes": 17})
|
||||||
|
self.page.locator(f'.account-tab[data-account="{self.first}"]').click()
|
||||||
|
panel = self.go("login")
|
||||||
|
expect(self.controls(panel)[1]).to_have_value("17")
|
||||||
|
expect(panel.locator("[data-auto-relogin-status]")).to_contain_text("账号一正在等待")
|
||||||
|
self.assertEqual({identifier for identifier, _ in self.writes}, {self.first, self.second})
|
||||||
|
self.assertEqual(self.actions, [])
|
||||||
|
|
||||||
|
def test_expired_countdown_login_failure_and_recovered_monitoring_are_status_only(self):
|
||||||
|
self.waiting()
|
||||||
|
self.summaries[self.first]["connection_state"] = "expired"
|
||||||
|
self.open()
|
||||||
|
panel = self.go("login")
|
||||||
|
status = panel.locator("[data-auto-relogin-status]")
|
||||||
|
countdown = panel.locator("[data-auto-relogin-countdown]")
|
||||||
|
expect(status).to_contain_text("掉线后等待自动重登")
|
||||||
|
expect(countdown).to_contain_text("秒后自动重新登录")
|
||||||
|
expect(countdown).to_contain_text("北京时间")
|
||||||
|
expect(self.controls(panel)[0]).to_be_enabled()
|
||||||
|
delay = self.controls(panel)[1]
|
||||||
|
delay.focus()
|
||||||
|
original = delay.element_handle()
|
||||||
|
before = countdown.inner_text()
|
||||||
|
self.page.wait_for_timeout(2100)
|
||||||
|
self.assertNotEqual(countdown.inner_text(), before)
|
||||||
|
self.assertTrue(delay.evaluate("(node, original) => node === original && node === document.activeElement", original))
|
||||||
|
self.set_status(self.first, "waiting", "等待服务端执行", "2000-01-01T00:00:00Z")
|
||||||
|
expect(countdown).to_contain_text("等待服务端执行自动重登")
|
||||||
|
self.set_status(self.first, "logging_in", "正在重新登录原区服角色")
|
||||||
|
expect(status).to_contain_text("正在重新登录原区服角色")
|
||||||
|
expect(countdown).to_be_hidden()
|
||||||
|
reason = '重新登录失败:密码错误 <img src=x onerror="alert(1)">'
|
||||||
|
self.set_status(self.first, "failed", reason)
|
||||||
|
expect(status).to_contain_text(reason)
|
||||||
|
expect(status.locator("img")).to_have_count(0)
|
||||||
|
expect(self.page.locator("#strategy-toggle")).to_be_disabled()
|
||||||
|
original = copy.deepcopy(self.configs[self.first])
|
||||||
|
self.set_status(self.first, "monitoring", "重登成功,已恢复监控并自动执行已勾选功能,可在顶部停止")
|
||||||
|
self.summaries[self.first].update(connected=True, connection_state="online", connection_message="游戏连接正常", running=True)
|
||||||
|
expect(status).to_contain_text("已恢复监控并自动执行已勾选功能")
|
||||||
|
expect(self.page.locator("#strategy-toggle")).to_have_text("停止")
|
||||||
|
expect(self.page.locator("#data-summary")).to_contain_text("正在自动执行已配置且已勾选的功能")
|
||||||
|
self.assertEqual(self.configs[self.first], original)
|
||||||
|
self.assertEqual(self.actions, [])
|
||||||
|
|
||||||
|
def test_restart_wait_persists_across_reload_and_closing_page_has_no_actions(self):
|
||||||
|
target = self.waiting(message="服务重启,等待设定时长后回到原区服角色")
|
||||||
|
self.open()
|
||||||
|
panel = self.go("login")
|
||||||
|
expect(panel.locator("[data-auto-relogin-status]")).to_contain_text("服务重启")
|
||||||
|
expect(self.page.locator("#strategy-toggle")).to_be_disabled()
|
||||||
|
before = len(self.writes)
|
||||||
|
self.page.reload(wait_until="networkidle")
|
||||||
|
panel = self.go("login")
|
||||||
|
expect(self.controls(panel)[0]).to_be_checked()
|
||||||
|
expect(self.controls(panel)[1]).to_have_value("30")
|
||||||
|
expect(panel.locator("[data-auto-relogin-countdown]")).to_contain_text("秒后自动重新登录")
|
||||||
|
expect(self.page.locator("#strategy-toggle")).to_have_text("开启")
|
||||||
|
expect(self.page.locator("#strategy-toggle")).to_be_disabled()
|
||||||
|
self.page.goto("about:blank")
|
||||||
|
self.page.close()
|
||||||
|
self.assertEqual(len(self.writes), before)
|
||||||
|
self.assertEqual(self.summaries[self.first]["auto_relogin_status"]["next_attempt_at"], target)
|
||||||
|
self.assertEqual(self.actions, [])
|
||||||
|
|
||||||
|
def test_manual_logout_cancels_countdown_without_disabling_account_setting(self):
|
||||||
|
self.waiting()
|
||||||
|
self.open()
|
||||||
|
panel = self.go("login")
|
||||||
|
expect(panel.locator("[data-auto-relogin-countdown]")).to_contain_text("秒后自动重新登录")
|
||||||
|
panel.get_by_role("button", name="退出登录", exact=True).click()
|
||||||
|
expect(panel.locator("[data-auto-relogin-status]")).to_contain_text("已取消本次自动重登")
|
||||||
|
expect(panel.locator("[data-auto-relogin-countdown]")).to_be_hidden()
|
||||||
|
expect(self.controls(panel)[0]).to_be_checked()
|
||||||
|
self.assertEqual(self.actions, [(self.first, "logout", {})])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -283,6 +283,8 @@ class WorkbenchBrowserTests(unittest.TestCase):
|
|||||||
|
|
||||||
def test_fake_login_uses_servers_without_persisting_password(self):
|
def test_fake_login_uses_servers_without_persisting_password(self):
|
||||||
payloads = []
|
payloads = []
|
||||||
|
summary = copy.deepcopy(self.manager.status(self.first))
|
||||||
|
summary.update(demo=False, connected=False, running=False, connection_state="offline", connection_message="尚未连接游戏")
|
||||||
login_result = {"servers": [{"id": 7, "name": "测试区", "role_name": "测试角色"}], "has_saved_password": True}
|
login_result = {"servers": [{"id": 7, "name": "测试区", "role_name": "测试角色"}], "has_saved_password": True}
|
||||||
def route_login(route):
|
def route_login(route):
|
||||||
payloads.append(route.request.post_data_json)
|
payloads.append(route.request.post_data_json)
|
||||||
@@ -294,12 +296,16 @@ class WorkbenchBrowserTests(unittest.TestCase):
|
|||||||
self.fulfill(route, response)
|
self.fulfill(route, response)
|
||||||
self.page.route(f"**/api/accounts/{self.first}/actions/login", route_login)
|
self.page.route(f"**/api/accounts/{self.first}/actions/login", route_login)
|
||||||
self.page.route(f"**/api/accounts/{self.first}/views/login?*", route_login_view)
|
self.page.route(f"**/api/accounts/{self.first}/views/login?*", route_login_view)
|
||||||
|
self.page.route("**/api/accounts", lambda route: self.fulfill(route, [summary, self.manager.status(self.second)]))
|
||||||
|
self.page.route(f"**/api/accounts/{self.first}/status", lambda route: self.fulfill(route, summary))
|
||||||
self.open()
|
self.open()
|
||||||
panel = self.go("login")
|
panel = self.go("login")
|
||||||
panel.get_by_label("游戏账号", exact=True).fill("offline-test")
|
panel.get_by_label("游戏账号", exact=True).fill("offline-test")
|
||||||
panel.get_by_label("游戏密码", exact=True).fill("test-password-never-persist")
|
panel.get_by_label("游戏密码", exact=True).fill("test-password-never-persist")
|
||||||
panel.get_by_role("button", name="账号密码登录 / 获取区服", exact=True).click()
|
panel.get_by_role("button", name="账号密码登录 / 获取区服", exact=True).click()
|
||||||
expect(panel.get_by_label('区服 / 角色',exact=True)).to_contain_text('测试区')
|
expect(panel.get_by_label('区服 / 角色',exact=True)).to_contain_text('测试区')
|
||||||
|
expect(self.page.locator('#connection')).to_have_text('游戏离线')
|
||||||
|
expect(self.page.locator('#strategy-toggle')).to_be_disabled()
|
||||||
self.assertEqual(payloads[0], {"account": "offline-test", "password": "test-password-never-persist", "remember": True})
|
self.assertEqual(payloads[0], {"account": "offline-test", "password": "test-password-never-persist", "remember": True})
|
||||||
self.assertEqual(panel.get_by_label("游戏密码", exact=True).input_value(), "")
|
self.assertEqual(panel.get_by_label("游戏密码", exact=True).input_value(), "")
|
||||||
self.assertEqual(self.page.evaluate("Object.keys(localStorage).length + Object.keys(sessionStorage).length"), 0)
|
self.assertEqual(self.page.evaluate("Object.keys(localStorage).length + Object.keys(sessionStorage).length"), 0)
|
||||||
|
|||||||
@@ -188,7 +188,9 @@ class ApiTests(unittest.TestCase):
|
|||||||
|
|
||||||
def test_connection_metadata_survives_summary_dto(self):
|
def test_connection_metadata_survives_summary_dto(self):
|
||||||
metadata = {"connection_state": "retrying", "connection_message": "网络请求超时;策略已停止,正在只读重试",
|
metadata = {"connection_state": "retrying", "connection_message": "网络请求超时;策略已停止,正在只读重试",
|
||||||
"last_game_success_at": "2026-11-11T02:05:36.000+00:00", "next_retry_at": "2026-11-11T02:05:41.000+00:00"}
|
"last_game_success_at": "2026-11-11T02:05:36.000+00:00", "next_retry_at": "2026-11-11T02:05:41.000+00:00",
|
||||||
|
"auto_relogin_status": {"state": "waiting", "message": "等待重新登录原区服和角色",
|
||||||
|
"next_attempt_at": "2026-11-11T02:35:36.000+00:00"}}
|
||||||
self.manager.accounts[self.account_id].update(metadata)
|
self.manager.accounts[self.account_id].update(metadata)
|
||||||
for url in (self.url + "/status", "/api/accounts"):
|
for url in (self.url + "/status", "/api/accounts"):
|
||||||
response = self.client.get(url)
|
response = self.client.get(url)
|
||||||
@@ -196,6 +198,16 @@ class ApiTests(unittest.TestCase):
|
|||||||
summary = response.json()[0] if url == "/api/accounts" else response.json()
|
summary = response.json()[0] if url == "/api/accounts" else response.json()
|
||||||
self.assertEqual({key: summary[key] for key in metadata}, metadata)
|
self.assertEqual({key: summary[key] for key in metadata}, metadata)
|
||||||
|
|
||||||
|
def test_auto_relogin_summary_only_exposes_three_public_fields(self):
|
||||||
|
self.manager.accounts[self.account_id]["auto_relogin_status"] = {
|
||||||
|
"state": "blocked", "message": "请先保存密码", "next_attempt_at": None,
|
||||||
|
"account": "must-stay-local", "password": "never-public", "savedSession": {"role_id": 999}}
|
||||||
|
for url in (self.url + "/status", "/api/accounts"):
|
||||||
|
response = self.client.get(url)
|
||||||
|
summary = response.json()[0] if url == "/api/accounts" else response.json()
|
||||||
|
self.assertEqual(summary["auto_relogin_status"], {
|
||||||
|
"state": "blocked", "message": "请先保存密码", "next_attempt_at": None})
|
||||||
|
|
||||||
def test_game_login_is_queued_and_credentials_stay_server_side(self):
|
def test_game_login_is_queued_and_credentials_stay_server_side(self):
|
||||||
response = self.client.post(self.url + "/actions/login", json={"account": "fake-account", "password": "GAME_PASSWORD", "remember": True})
|
response = self.client.post(self.url + "/actions/login", json={"account": "fake-account", "password": "GAME_PASSWORD", "remember": True})
|
||||||
self.assertEqual(response.status_code, 202)
|
self.assertEqual(response.status_code, 202)
|
||||||
|
|||||||
@@ -0,0 +1,473 @@
|
|||||||
|
"""Auto password login regressions; temporary stores, fake clocks, no live HTTP."""
|
||||||
|
from copy import deepcopy
|
||||||
|
from datetime import datetime
|
||||||
|
import json
|
||||||
|
import threading
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
from ranch_assistant.api import ApiError, SessionExpiredError
|
||||||
|
from ranch_web.policies import default_config, export_config, validate_config
|
||||||
|
from ranch_web.service import WebManager
|
||||||
|
from ranch_web.tests import test_service as fixtures
|
||||||
|
|
||||||
|
|
||||||
|
class AutoLogin(fixtures.FakeLogin):
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def authenticate(self, account, password):
|
||||||
|
self.trace.begin("离线渠道验证")
|
||||||
|
self.calls.append((account, password))
|
||||||
|
client, response, context = super().authenticate(account, password)
|
||||||
|
# Real official masterInfos carry both serverId and character id.
|
||||||
|
response["masterInfos"] = [{"serverId": sid, "id": 100 + sid} for sid in (1, 2)]
|
||||||
|
return client, response, context
|
||||||
|
|
||||||
|
|
||||||
|
class AutoReloginTests(unittest.TestCase):
|
||||||
|
setUp = fixtures.ServiceTests.setUp
|
||||||
|
account = fixtures.ServiceTests.account
|
||||||
|
idle = fixtures.ServiceTests.idle
|
||||||
|
job = fixtures.ServiceTests.job
|
||||||
|
login = fixtures.ServiceTests.login
|
||||||
|
enable = fixtures.ServiceTests.enable
|
||||||
|
|
||||||
|
def connected(self, *, remember=True, server=2, account=None):
|
||||||
|
self.manager.login_factory = AutoLogin
|
||||||
|
AutoLogin.calls = []
|
||||||
|
identifier = self.account(False)
|
||||||
|
account = account or "synthetic-owner-" + identifier[:8]
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "login", {
|
||||||
|
"account": account, "password": "synthetic-password", "remember": remember}))
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "enter_server", {"server_id": server}))
|
||||||
|
worker = self.manager._worker(identifier)
|
||||||
|
self.now = 1000.0
|
||||||
|
worker.schedule.clock = lambda: self.now
|
||||||
|
self.configure(identifier)
|
||||||
|
return identifier, worker
|
||||||
|
|
||||||
|
def configure(self, identifier, *, enabled=True, delay=1):
|
||||||
|
value = self.manager.get_config(identifier)
|
||||||
|
value["config"]["auto_relogin"] = {"enabled": enabled, "delay_minutes": delay}
|
||||||
|
self.job(identifier, self.manager.set_config(identifier, value["config"], value["revision"])["job"])
|
||||||
|
|
||||||
|
def disconnect(self, identifier, worker, *, timeout=False):
|
||||||
|
error = requests.ReadTimeout("offline test") if timeout else SessionExpiredError("expired test", code=408)
|
||||||
|
with patch.object(worker.engine.client, "_post", side_effect=error), \
|
||||||
|
patch.object(worker.engine.client.http, "post", side_effect=error):
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "refresh"), status="failed")
|
||||||
|
|
||||||
|
def tick(self, identifier, worker, *, status="succeeded"):
|
||||||
|
return self.job(identifier, worker.enqueue("__tick"), status=status)
|
||||||
|
|
||||||
|
def auto_status(self, identifier):
|
||||||
|
return self.manager.status(identifier)["auto_relogin_status"]
|
||||||
|
|
||||||
|
def test_config_defaults_strict_types_and_limits(self):
|
||||||
|
self.assertEqual(validate_config({})["auto_relogin"], {"enabled": False, "delay_minutes": 30})
|
||||||
|
for field, values in (("enabled", [0, 1, "true", None]),
|
||||||
|
("delay_minutes", [True, False, 0, 10081, 1.5, "30", None])):
|
||||||
|
for value in values:
|
||||||
|
with self.subTest(field=field, value=value), self.assertRaises(ValueError):
|
||||||
|
validate_config({"auto_relogin": {field: value}})
|
||||||
|
for minutes in (1, 10080):
|
||||||
|
self.assertEqual(validate_config({"auto_relogin": {"delay_minutes": minutes}})
|
||||||
|
["auto_relogin"]["delay_minutes"], minutes)
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
validate_config({"auto_relogin": {"password": "forbidden"}})
|
||||||
|
|
||||||
|
def test_first_expiry_deadline_survives_idle_refresh_and_duplicate_ticks(self):
|
||||||
|
identifier, worker = self.connected()
|
||||||
|
self.enable(identifier)
|
||||||
|
selected = deepcopy(worker.config)
|
||||||
|
identity = worker.active_identity
|
||||||
|
self.disconnect(identifier, worker)
|
||||||
|
status = self.auto_status(identifier)
|
||||||
|
self.assertEqual(status["state"], "waiting")
|
||||||
|
datetime.fromisoformat(status["next_attempt_at"])
|
||||||
|
before = len(AutoLogin.calls)
|
||||||
|
self.now += 59
|
||||||
|
for _ in range(3):
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "refresh"), status="failed")
|
||||||
|
self.assertEqual(self.auto_status(identifier)["next_attempt_at"], status["next_attempt_at"])
|
||||||
|
self.assertEqual(len(AutoLogin.calls), before)
|
||||||
|
self.now += 1
|
||||||
|
result = self.tick(identifier, worker)["result"]
|
||||||
|
self.assertEqual(len(AutoLogin.calls), before + 1)
|
||||||
|
self.assertEqual(worker.active_identity, identity)
|
||||||
|
self.assertEqual(worker.engine.client.session.server_id, 2)
|
||||||
|
self.assertEqual(worker.engine.client.session.role_id, 102)
|
||||||
|
self.assertTrue(self.manager.status(identifier)["connected"])
|
||||||
|
self.assertTrue(self.manager.status(identifier)["running"])
|
||||||
|
self.assertTrue(worker.engine.auto)
|
||||||
|
self.assertTrue(result["running"])
|
||||||
|
self.assertIn("已勾选", result["message"])
|
||||||
|
self.assertEqual(worker.config, selected)
|
||||||
|
self.assertTrue(worker.schedule.monitoring)
|
||||||
|
self.assertIsNone(self.auto_status(identifier)["next_attempt_at"])
|
||||||
|
for _ in range(3):
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertEqual(len(AutoLogin.calls), before + 1)
|
||||||
|
|
||||||
|
def test_timeout_retries_do_not_postpone_password_login(self):
|
||||||
|
identifier, worker = self.connected()
|
||||||
|
self.disconnect(identifier, worker, timeout=True)
|
||||||
|
deadline = self.auto_status(identifier)["next_attempt_at"]
|
||||||
|
before = len(AutoLogin.calls)
|
||||||
|
for seconds in (5, 15, 35, 59):
|
||||||
|
self.now = 1000 + seconds
|
||||||
|
with patch.object(worker.engine.client.http, "post", side_effect=requests.Timeout("still offline")):
|
||||||
|
self.tick(identifier, worker, status="failed") if seconds != 59 else self.tick(identifier, worker)
|
||||||
|
self.assertEqual(self.auto_status(identifier)["next_attempt_at"], deadline)
|
||||||
|
self.now = 1060
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertEqual(len(AutoLogin.calls), before + 1)
|
||||||
|
|
||||||
|
def test_recovery_clears_outage_and_next_outage_gets_fresh_delay(self):
|
||||||
|
identifier, worker = self.connected()
|
||||||
|
self.disconnect(identifier, worker, timeout=True)
|
||||||
|
self.now += 5
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertEqual(self.auto_status(identifier)["state"], "idle")
|
||||||
|
self.now += 100
|
||||||
|
self.disconnect(identifier, worker)
|
||||||
|
before = len(AutoLogin.calls)
|
||||||
|
self.now += 59
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertEqual(len(AutoLogin.calls), before)
|
||||||
|
self.now += 1
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertEqual(len(AutoLogin.calls), before + 1)
|
||||||
|
|
||||||
|
def test_enabling_and_changing_delay_reuses_known_outage(self):
|
||||||
|
identifier, worker = self.connected()
|
||||||
|
self.configure(identifier, enabled=False, delay=5)
|
||||||
|
self.disconnect(identifier, worker)
|
||||||
|
self.now += 70
|
||||||
|
self.configure(identifier, delay=2)
|
||||||
|
first = self.auto_status(identifier)["next_attempt_at"]
|
||||||
|
self.configure(identifier, delay=1)
|
||||||
|
self.assertLess(self.auto_status(identifier)["next_attempt_at"], first)
|
||||||
|
before = len(AutoLogin.calls)
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertEqual(len(AutoLogin.calls), before + 1)
|
||||||
|
|
||||||
|
def test_no_saved_password_blocks_without_token_fallback(self):
|
||||||
|
identifier, worker = self.connected(remember=False)
|
||||||
|
self.disconnect(identifier, worker)
|
||||||
|
status = self.auto_status(identifier)
|
||||||
|
self.assertEqual(status["state"], "blocked")
|
||||||
|
self.assertIn("密码", status["message"])
|
||||||
|
self.assertIsNone(status["next_attempt_at"])
|
||||||
|
before = len(AutoLogin.calls), len(fixtures.FakeClient.calls)
|
||||||
|
self.now += 100000
|
||||||
|
for _ in range(3):
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertEqual((len(AutoLogin.calls), len(fixtures.FakeClient.calls)), before)
|
||||||
|
|
||||||
|
def test_credentials_mismatch_and_missing_target_never_authenticate(self):
|
||||||
|
for target in (False, True):
|
||||||
|
with self.subTest(target=target):
|
||||||
|
identifier, worker = self.connected()
|
||||||
|
self.disconnect(identifier, worker)
|
||||||
|
if target:
|
||||||
|
worker.securestore.remove(worker.active_identity)
|
||||||
|
else:
|
||||||
|
worker.securestore.save_credentials("another-owner", "another-password", True)
|
||||||
|
self.now += 60
|
||||||
|
before = len(AutoLogin.calls)
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertEqual(len(AutoLogin.calls), before)
|
||||||
|
self.assertEqual(self.auto_status(identifier)["state"], "blocked")
|
||||||
|
self.assertTrue(self.auto_status(identifier)["message"])
|
||||||
|
|
||||||
|
def test_official_server_role_and_uid_mismatches_rejected_before_enter(self):
|
||||||
|
for field in ("servers", "role", "uid", "account_name"):
|
||||||
|
with self.subTest(field=field):
|
||||||
|
identifier, worker = self.connected()
|
||||||
|
self.disconnect(identifier, worker)
|
||||||
|
original = AutoLogin.authenticate
|
||||||
|
|
||||||
|
def wrong(flow, account, password):
|
||||||
|
client, response, context = original(flow, account, password)
|
||||||
|
if field == "servers":
|
||||||
|
response["servers"] = response["servers"][:1]
|
||||||
|
elif field == "role":
|
||||||
|
response["masterInfos"][-1]["id"] = 999
|
||||||
|
elif field == "uid":
|
||||||
|
client.session.account_id = context["uid"] = "other-uid"
|
||||||
|
else:
|
||||||
|
client.session.account_name = "other-account"
|
||||||
|
return client, response, context
|
||||||
|
|
||||||
|
self.now += 60
|
||||||
|
before = len(fixtures.FakeClient.calls)
|
||||||
|
with patch.object(AutoLogin, "authenticate", wrong):
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertFalse(self.manager.status(identifier)["connected"])
|
||||||
|
self.assertFalse(worker.running)
|
||||||
|
self.assertFalse(worker.engine.auto)
|
||||||
|
self.assertFalse(any(url.endswith("userServerService/enterGame")
|
||||||
|
for _, url, _ in fixtures.FakeClient.calls[before:]))
|
||||||
|
self.assertEqual(self.auto_status(identifier)["state"], "failed")
|
||||||
|
|
||||||
|
def test_failure_waits_full_delay_instead_of_busy_loop(self):
|
||||||
|
identifier, worker = self.connected()
|
||||||
|
self.disconnect(identifier, worker)
|
||||||
|
self.now += 60
|
||||||
|
with patch.object(AutoLogin, "authenticate", side_effect=ApiError("离线认证失败")) as auth:
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
deadline = self.auto_status(identifier)["next_attempt_at"]
|
||||||
|
for seconds in (0, .2, 1, 59):
|
||||||
|
self.now = 1060 + seconds
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertEqual(auth.call_count, 1)
|
||||||
|
self.assertEqual(self.auto_status(identifier)["next_attempt_at"], deadline)
|
||||||
|
self.now = 1120
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertEqual(auth.call_count, 2)
|
||||||
|
|
||||||
|
def test_login_preference_survives_first_enter_role_switch_and_logout(self):
|
||||||
|
identifier = self.account(False)
|
||||||
|
self.configure(identifier, delay=7)
|
||||||
|
self.login(identifier, server=1)
|
||||||
|
self.assertEqual(self.manager.get_config(identifier)["config"]["auto_relogin"],
|
||||||
|
{"enabled": True, "delay_minutes": 7})
|
||||||
|
config = self.manager.get_config(identifier)["config"]
|
||||||
|
config["policy"]["keep_money"] = 4321
|
||||||
|
self.job(identifier, self.manager.set_config(identifier, config)["job"])
|
||||||
|
self.login(identifier, server=2)
|
||||||
|
self.assertNotEqual(self.manager.get_config(identifier)["config"]["policy"]["keep_money"], 4321)
|
||||||
|
self.assertEqual(self.manager.get_config(identifier)["config"]["auto_relogin"]["delay_minutes"], 7)
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "logout"))
|
||||||
|
self.assertTrue(self.manager.get_config(identifier)["config"]["auto_relogin"]["enabled"])
|
||||||
|
self.assertEqual(self.auto_status(identifier)["state"], "suspended")
|
||||||
|
|
||||||
|
def test_portable_import_preserves_local_login_preference(self):
|
||||||
|
identifier, worker = self.connected()
|
||||||
|
self.enable(identifier)
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "start"))
|
||||||
|
portable = export_config(default_config(), worker.engine.snapshot)
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "import_config", {"config": portable}))
|
||||||
|
self.assertEqual(self.manager.get_config(identifier)["config"]["auto_relogin"],
|
||||||
|
{"enabled": True, "delay_minutes": 1})
|
||||||
|
public = json.dumps(self.manager.get_config(identifier)) + json.dumps(export_config(worker.config))
|
||||||
|
self.assertNotIn("synthetic-password", public)
|
||||||
|
self.assertNotIn("synthetic-center-token", public)
|
||||||
|
self.assertFalse(worker.running)
|
||||||
|
self.assertFalse(worker.engine.auto)
|
||||||
|
|
||||||
|
def test_restart_opt_in_activates_after_thirty_minutes_and_supersedes_old_stop(self):
|
||||||
|
identifier, worker = self.connected()
|
||||||
|
self.enable(identifier)
|
||||||
|
self.configure(identifier, delay=30)
|
||||||
|
self.manager.submit(identifier, "stop")
|
||||||
|
selected = deepcopy(worker.config)
|
||||||
|
self.manager.close()
|
||||||
|
before = len(AutoLogin.calls), len(fixtures.FakeClient.calls)
|
||||||
|
self.manager = WebManager(self.root, start_scheduler=False, login_factory=AutoLogin)
|
||||||
|
self.addCleanup(self.manager.close)
|
||||||
|
self.idle(identifier)
|
||||||
|
worker = self.manager._worker(identifier)
|
||||||
|
self.assertFalse(worker.running)
|
||||||
|
self.assertFalse(worker.engine.auto)
|
||||||
|
self.assertIsNone(worker.engine.client)
|
||||||
|
self.assertEqual((len(AutoLogin.calls), len(fixtures.FakeClient.calls)), before)
|
||||||
|
origin = worker.schedule.disconnected_at
|
||||||
|
worker.schedule.clock = lambda: self.now
|
||||||
|
self.now = origin + 1799
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertFalse(worker.running)
|
||||||
|
self.assertEqual(len(AutoLogin.calls), before[0])
|
||||||
|
self.now = origin + 1800
|
||||||
|
result = self.tick(identifier, worker)["result"]
|
||||||
|
self.assertTrue(result["connected"])
|
||||||
|
self.assertTrue(result["running"])
|
||||||
|
self.assertTrue(worker.running)
|
||||||
|
self.assertTrue(worker.engine.auto)
|
||||||
|
self.assertEqual(worker.config, selected)
|
||||||
|
self.assertEqual(len(AutoLogin.calls), before[0] + 1)
|
||||||
|
|
||||||
|
def test_final_activation_revocation_never_starts_relogin_candidate(self):
|
||||||
|
for operation in ("stop", "logout", "forget_login", "policy", "disable", "delay"):
|
||||||
|
with self.subTest(operation=operation):
|
||||||
|
identifier, worker = self.connected()
|
||||||
|
self.enable(identifier)
|
||||||
|
self.disconnect(identifier, worker)
|
||||||
|
original_client = worker.engine.client
|
||||||
|
identity = worker.active_identity
|
||||||
|
entered, release = threading.Event(), threading.Event()
|
||||||
|
self.addCleanup(release.set)
|
||||||
|
original = worker.securestore.set_active
|
||||||
|
|
||||||
|
def held(active):
|
||||||
|
if active == identity and not release.is_set():
|
||||||
|
entered.set()
|
||||||
|
if not release.wait(5):
|
||||||
|
raise AssertionError("Relogin activation gate not released")
|
||||||
|
return original(active)
|
||||||
|
|
||||||
|
self.now += 60
|
||||||
|
before = self.manager.logs(identifier)["next"]
|
||||||
|
with patch.object(worker.securestore, "set_active", side_effect=held):
|
||||||
|
candidate = worker.enqueue("__tick")
|
||||||
|
self.assertTrue(entered.wait(2))
|
||||||
|
if operation in {"stop", "logout", "forget_login"}:
|
||||||
|
followup = self.manager.submit(identifier, operation)
|
||||||
|
else:
|
||||||
|
config = self.manager.get_config(identifier)["config"]
|
||||||
|
if operation == "policy":
|
||||||
|
config["daily_policy"]["enabled"] = False
|
||||||
|
else:
|
||||||
|
config["auto_relogin"].update(enabled=operation != "disable", delay_minutes=2)
|
||||||
|
followup = self.manager.set_config(identifier, config)["job"]
|
||||||
|
self.assertFalse(worker.running)
|
||||||
|
release.set()
|
||||||
|
self.job(identifier, candidate, status="cancelled")
|
||||||
|
self.job(identifier, followup)
|
||||||
|
self.assertFalse(worker.running)
|
||||||
|
self.assertFalse(worker.engine.auto)
|
||||||
|
if operation in {"logout", "forget_login"}:
|
||||||
|
self.assertIsNone(worker.engine.client)
|
||||||
|
else:
|
||||||
|
self.assertIs(worker.engine.client, original_client)
|
||||||
|
self.assertFalse(any("已自动开启" in row["message"]
|
||||||
|
for row in self.manager.logs(identifier, after=before)["entries"]))
|
||||||
|
|
||||||
|
def test_restart_opt_in_waits_and_logout_disarms_restart(self):
|
||||||
|
identifier, worker = self.connected()
|
||||||
|
self.manager.close()
|
||||||
|
before = len(AutoLogin.calls)
|
||||||
|
self.manager = WebManager(self.root, start_scheduler=False, login_factory=AutoLogin)
|
||||||
|
self.addCleanup(self.manager.close)
|
||||||
|
self.idle(identifier)
|
||||||
|
worker = self.manager._worker(identifier)
|
||||||
|
origin = worker.schedule.clock()
|
||||||
|
worker.schedule.clock = lambda: origin + self.now - 1000
|
||||||
|
self.assertEqual(self.auto_status(identifier)["state"], "waiting")
|
||||||
|
self.now = 1059
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertEqual(len(AutoLogin.calls), before)
|
||||||
|
self.now = 1060.1
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertTrue(self.manager.status(identifier)["connected"])
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "logout"))
|
||||||
|
self.manager.close()
|
||||||
|
before = len(AutoLogin.calls)
|
||||||
|
self.manager = WebManager(self.root, start_scheduler=False, login_factory=AutoLogin)
|
||||||
|
self.addCleanup(self.manager.close)
|
||||||
|
self.idle(identifier)
|
||||||
|
worker = self.manager._worker(identifier)
|
||||||
|
self.now += 99999
|
||||||
|
worker.schedule.clock = lambda: self.now
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertEqual(len(AutoLogin.calls), before)
|
||||||
|
|
||||||
|
def test_logout_forget_and_delay_change_revoke_inflight_auth_immediately(self):
|
||||||
|
for operation in ("logout", "forget_login", "disable", "delay"):
|
||||||
|
with self.subTest(operation=operation):
|
||||||
|
identifier, worker = self.connected()
|
||||||
|
self.disconnect(identifier, worker)
|
||||||
|
entered, release = threading.Event(), threading.Event()
|
||||||
|
self.addCleanup(release.set)
|
||||||
|
original = AutoLogin.authenticate
|
||||||
|
|
||||||
|
def paused(flow, account, password):
|
||||||
|
entered.set()
|
||||||
|
if not release.wait(5):
|
||||||
|
raise AssertionError("Auth gate not released")
|
||||||
|
return original(flow, account, password)
|
||||||
|
|
||||||
|
self.now += 60
|
||||||
|
before = len(AutoLogin.calls)
|
||||||
|
with patch.object(AutoLogin, "authenticate", paused):
|
||||||
|
tick = worker.enqueue("__tick")
|
||||||
|
self.assertTrue(entered.wait(2))
|
||||||
|
if operation in {"logout", "forget_login"}:
|
||||||
|
next_job = self.manager.submit(identifier, operation)
|
||||||
|
self.assertEqual(self.auto_status(identifier)["state"], "suspended")
|
||||||
|
else:
|
||||||
|
config = self.manager.get_config(identifier)["config"]
|
||||||
|
config["auto_relogin"].update(enabled=operation != "disable", delay_minutes=2)
|
||||||
|
next_job = self.manager.set_config(identifier, config)["job"]
|
||||||
|
release.set()
|
||||||
|
self.job(identifier, tick, status="cancelled")
|
||||||
|
self.job(identifier, next_job)
|
||||||
|
self.assertEqual(len(AutoLogin.calls), before)
|
||||||
|
self.assertFalse(self.manager.status(identifier)["connected"])
|
||||||
|
|
||||||
|
def test_account_isolation(self):
|
||||||
|
first, first_worker = self.connected(account="owner-one")
|
||||||
|
second, second_worker = self.connected(account="owner-two")
|
||||||
|
self.configure(second, enabled=False)
|
||||||
|
self.disconnect(first, first_worker)
|
||||||
|
self.disconnect(second, second_worker)
|
||||||
|
self.now += 60
|
||||||
|
before = len(AutoLogin.calls)
|
||||||
|
self.tick(first, first_worker)
|
||||||
|
self.tick(second, second_worker)
|
||||||
|
self.assertEqual(AutoLogin.calls[before:], [("owner-one", "synthetic-password")])
|
||||||
|
self.assertTrue(self.manager.status(first)["connected"])
|
||||||
|
self.assertFalse(self.manager.status(second)["connected"])
|
||||||
|
|
||||||
|
def test_stop_policy_and_delay_cancellation_back_off_even_after_transport_error(self):
|
||||||
|
for operation in ("stop", "policy", "delay"):
|
||||||
|
for transport_error in (False, True):
|
||||||
|
with self.subTest(operation=operation, transport_error=transport_error):
|
||||||
|
identifier, worker = self.connected()
|
||||||
|
self.disconnect(identifier, worker)
|
||||||
|
entered, release = threading.Event(), threading.Event()
|
||||||
|
self.addCleanup(release.set)
|
||||||
|
attempts = []
|
||||||
|
original = AutoLogin.authenticate
|
||||||
|
|
||||||
|
def held(flow, account, password):
|
||||||
|
attempts.append(self.now)
|
||||||
|
entered.set()
|
||||||
|
if not release.wait(5):
|
||||||
|
raise AssertionError("Auth gate not released")
|
||||||
|
if transport_error:
|
||||||
|
raise requests.ReadTimeout("cancelled SDK eventually timed out")
|
||||||
|
return original(flow, account, password)
|
||||||
|
|
||||||
|
self.now = 1060
|
||||||
|
with patch.object(AutoLogin, "authenticate", held):
|
||||||
|
tick = worker.enqueue("__tick")
|
||||||
|
self.assertTrue(entered.wait(2))
|
||||||
|
self.assertTrue(worker._execution.consuming)
|
||||||
|
next_job = None
|
||||||
|
delay = 60
|
||||||
|
if operation == "stop":
|
||||||
|
self.manager.submit(identifier, "stop")
|
||||||
|
else:
|
||||||
|
config = self.manager.get_config(identifier)["config"]
|
||||||
|
if operation == "delay":
|
||||||
|
config["auto_relogin"]["delay_minutes"] = 2
|
||||||
|
delay = 120
|
||||||
|
else:
|
||||||
|
config["policy"]["keep_money"] += 1
|
||||||
|
next_job = self.manager.set_config(identifier, config)["job"]
|
||||||
|
# Backoff starts when the old authentication finishes,
|
||||||
|
# not when cancellation was requested.
|
||||||
|
self.now = 1070
|
||||||
|
release.set()
|
||||||
|
self.job(identifier, tick, status="cancelled")
|
||||||
|
if next_job:
|
||||||
|
self.job(identifier, next_job)
|
||||||
|
self.assertEqual(self.auto_status(identifier)["state"], "failed")
|
||||||
|
deadline = self.auto_status(identifier)["next_attempt_at"]
|
||||||
|
for seconds in (0, .2, delay - 1):
|
||||||
|
self.now = 1070 + seconds
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertEqual(attempts, [1060])
|
||||||
|
self.assertEqual(self.auto_status(identifier)["next_attempt_at"], deadline)
|
||||||
|
self.now = 1070 + delay
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertEqual(attempts, [1060, 1070 + delay])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -31,6 +31,8 @@ class ConnectionStateTests(unittest.TestCase):
|
|||||||
if running:
|
if running:
|
||||||
self.enable(identifier)
|
self.enable(identifier)
|
||||||
self.job(identifier, self.manager.submit(identifier, "start"))
|
self.job(identifier, self.manager.submit(identifier, "start"))
|
||||||
|
else:
|
||||||
|
self.manager.submit(identifier, "stop")
|
||||||
return identifier, worker
|
return identifier, worker
|
||||||
|
|
||||||
def tick(self, identifier, worker, *, status="succeeded"):
|
def tick(self, identifier, worker, *, status="succeeded"):
|
||||||
@@ -70,7 +72,26 @@ class ConnectionStateTests(unittest.TestCase):
|
|||||||
self.assertIsNotNone(worker.securestore.load(worker.active_identity))
|
self.assertIsNotNone(worker.securestore.load(worker.active_identity))
|
||||||
self.job(identifier, self.manager.submit(identifier, "restore_session", {"session_id": worker.active_identity}))
|
self.job(identifier, self.manager.submit(identifier, "restore_session", {"session_id": worker.active_identity}))
|
||||||
self.assertEqual(self.manager.status(identifier)["connection_state"], "online")
|
self.assertEqual(self.manager.status(identifier)["connection_state"], "online")
|
||||||
self.assertFalse(self.manager.status(identifier)["running"])
|
self.assertTrue(self.manager.status(identifier)["running"])
|
||||||
|
self.assertTrue(worker.engine.auto)
|
||||||
|
|
||||||
|
def test_explicit_stop_survives_heartbeat_local_refresh_and_monitor_until_login(self):
|
||||||
|
identifier, worker = self.connected(running=True)
|
||||||
|
self.manager.submit(identifier, "stop")
|
||||||
|
worker.engine.last_heartbeat = 0
|
||||||
|
result = self.tick(identifier, worker)["result"]
|
||||||
|
self.assertEqual(result["kind"], "heartbeat")
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "refresh", {"page": "statistics"}))
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "refresh"))
|
||||||
|
worker.schedule.next_poll = 0
|
||||||
|
self.tick(identifier, worker)
|
||||||
|
self.assertFalse(worker.running)
|
||||||
|
self.assertFalse(worker.engine.auto)
|
||||||
|
self.assertTrue(self.manager.status(identifier)["connected"])
|
||||||
|
result = self.job(identifier, self.manager.submit(identifier, "restore_session", {
|
||||||
|
"session_id": worker.active_identity}))["result"]
|
||||||
|
self.assertTrue(result["running"])
|
||||||
|
self.assertTrue(worker.engine.auto)
|
||||||
|
|
||||||
def test_timeout_retries_only_snapshot_and_keeps_uncertain_write_evidence(self):
|
def test_timeout_retries_only_snapshot_and_keeps_uncertain_write_evidence(self):
|
||||||
identifier, worker = self.connected(running=True)
|
identifier, worker = self.connected(running=True)
|
||||||
|
|||||||
@@ -0,0 +1,195 @@
|
|||||||
|
"""Private release transport checks using fake HTTP only, never user credentials."""
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from email.message import Message
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import tempfile
|
||||||
|
import traceback
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
from urllib.error import HTTPError, URLError
|
||||||
|
from urllib.request import HTTPSHandler, build_opener
|
||||||
|
from urllib.response import addinfourl
|
||||||
|
|
||||||
|
from ranch_web import updates
|
||||||
|
|
||||||
|
|
||||||
|
TOKEN = "github_pat_offline_test_secret"
|
||||||
|
RELEASES = [{"tag_name": "v2.0.1", "draft": False, "prerelease": False}]
|
||||||
|
|
||||||
|
|
||||||
|
class PrivateReleaseTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
temporary = tempfile.TemporaryDirectory(prefix="private-release-test-")
|
||||||
|
self.addCleanup(temporary.cleanup)
|
||||||
|
self.root = Path(temporary.name)
|
||||||
|
self.token_path = self.root / updates.TOKEN_FILE_NAME
|
||||||
|
environment = patch.dict(os.environ, {"RANCH_WEB_UPDATER_DIR": ""})
|
||||||
|
environment.start()
|
||||||
|
self.addCleanup(environment.stop)
|
||||||
|
os.environ.pop(updates.TOKEN_FILE_ENV, None)
|
||||||
|
network = patch("socket.socket.connect", side_effect=AssertionError("Live network forbidden"))
|
||||||
|
network.start()
|
||||||
|
self.addCleanup(network.stop)
|
||||||
|
|
||||||
|
def token(self, payload=None):
|
||||||
|
self.token_path.write_bytes(payload if payload is not None else (TOKEN + "\n").encode("ascii"))
|
||||||
|
self.token_path.chmod(0o600)
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def transport(self, body=None):
|
||||||
|
payload = body if body is not None else json.dumps(RELEASES).encode("ascii")
|
||||||
|
with patch.object(updates, "build_opener") as build:
|
||||||
|
build.return_value.open.side_effect = lambda *args, **kwargs: io.BytesIO(payload)
|
||||||
|
yield build
|
||||||
|
|
||||||
|
def test_missing_default_retains_public_and_no_argument_api(self):
|
||||||
|
with self.transport() as build:
|
||||||
|
self.assertEqual(updates.github_releases(), RELEASES)
|
||||||
|
self.assertEqual(updates.github_releases(self.root), RELEASES)
|
||||||
|
for call in build.return_value.open.call_args_list:
|
||||||
|
self.assertIsNone(call.args[0].get_header("Authorization"))
|
||||||
|
|
||||||
|
def test_shared_file_adds_auth_only_to_fixed_github_endpoint(self):
|
||||||
|
self.token()
|
||||||
|
with self.transport() as build:
|
||||||
|
self.assertEqual(updates.github_releases(self.root), RELEASES)
|
||||||
|
request = build.return_value.open.call_args.args[0]
|
||||||
|
self.assertEqual(request.full_url, updates.RELEASES_API + "?per_page=100&page=1")
|
||||||
|
self.assertEqual(request.get_header("Authorization"), "Bearer " + TOKEN)
|
||||||
|
self.assertIsInstance(build.call_args.args[0], updates._NoRedirect)
|
||||||
|
|
||||||
|
def test_absolute_override_is_a_file_and_takes_precedence(self):
|
||||||
|
self.token(b"ignored_default\n")
|
||||||
|
alternate = self.root / "alternate-token"
|
||||||
|
alternate.write_text(TOKEN, encoding="ascii")
|
||||||
|
alternate.chmod(0o600)
|
||||||
|
os.environ[updates.TOKEN_FILE_ENV] = str(alternate)
|
||||||
|
with self.transport() as build:
|
||||||
|
updates.github_releases(self.root)
|
||||||
|
self.assertEqual(build.return_value.open.call_args.args[0].get_header("Authorization"), "Bearer " + TOKEN)
|
||||||
|
|
||||||
|
def test_invalid_explicit_file_never_falls_back_or_exposes_path(self):
|
||||||
|
for value in ("", TOKEN, str(self.root / "missing-private-token")):
|
||||||
|
with self.subTest(value=value), self.transport() as build:
|
||||||
|
os.environ[updates.TOKEN_FILE_ENV] = value
|
||||||
|
with self.assertRaises(updates.GitHubReleaseError) as caught:
|
||||||
|
updates.github_releases(self.root)
|
||||||
|
self.assertEqual(caught.exception.code, "token_file_invalid")
|
||||||
|
self.assertNotIn(TOKEN, str(caught.exception))
|
||||||
|
self.assertNotIn(str(self.root), str(caught.exception))
|
||||||
|
build.assert_not_called()
|
||||||
|
|
||||||
|
def test_malformed_empty_large_and_header_injection_tokens_rejected(self):
|
||||||
|
for payload in (b"", b"bad token", b"token\r\nInjected: secret", b"\xff", b"a" * 4097):
|
||||||
|
with self.subTest(payload=payload[:20]), self.transport() as build:
|
||||||
|
self.token(payload)
|
||||||
|
with self.assertRaises(updates.GitHubReleaseError):
|
||||||
|
updates.github_releases(self.root)
|
||||||
|
build.assert_not_called()
|
||||||
|
|
||||||
|
def test_hard_link_token_rejected(self):
|
||||||
|
self.token()
|
||||||
|
os.link(self.token_path, self.root / "token-hardlink")
|
||||||
|
with self.transport() as build, self.assertRaises(updates.GitHubReleaseError):
|
||||||
|
updates.github_releases(self.root)
|
||||||
|
build.assert_not_called()
|
||||||
|
|
||||||
|
def test_symlink_even_to_missing_file_rejected(self):
|
||||||
|
try:
|
||||||
|
self.token_path.symlink_to(self.root / "missing-target")
|
||||||
|
except OSError:
|
||||||
|
self.skipTest("Symlinks unavailable for this test user")
|
||||||
|
with self.transport() as build, self.assertRaises(updates.GitHubReleaseError):
|
||||||
|
updates.github_releases(self.root)
|
||||||
|
build.assert_not_called()
|
||||||
|
|
||||||
|
@unittest.skipUnless(os.name == "posix", "POSIX permission check")
|
||||||
|
def test_readable_by_group_or_others_is_not_accepted(self):
|
||||||
|
self.token()
|
||||||
|
for mode in (0o644, 0o640, 0o400, 0o660):
|
||||||
|
self.token_path.chmod(mode)
|
||||||
|
with self.subTest(mode=mode), self.transport() as build, self.assertRaises(updates.GitHubReleaseError):
|
||||||
|
updates.github_releases(self.root)
|
||||||
|
build.assert_not_called()
|
||||||
|
|
||||||
|
def test_file_permission_errors_are_fixed_and_secret_free(self):
|
||||||
|
with patch.object(updates.os, "open", side_effect=PermissionError(TOKEN)), self.transport() as build:
|
||||||
|
with self.assertRaises(updates.GitHubReleaseError) as caught:
|
||||||
|
updates.github_releases(self.root)
|
||||||
|
self.assertNotIn(TOKEN, str(caught.exception))
|
||||||
|
build.assert_not_called()
|
||||||
|
|
||||||
|
def test_http_access_errors_with_and_without_token_are_not_no_release(self):
|
||||||
|
service = updates.UpdateService(self.root, "2.0.0")
|
||||||
|
for authenticated in (False, True):
|
||||||
|
if authenticated:
|
||||||
|
self.token()
|
||||||
|
for status in (401, 403, 404):
|
||||||
|
with self.subTest(authenticated=authenticated, status=status), self.transport() as build:
|
||||||
|
build.return_value.open.side_effect = HTTPError(updates.RELEASES_API, status, TOKEN, {}, io.BytesIO(TOKEN.encode()))
|
||||||
|
state = service.check()
|
||||||
|
self.assertEqual(state["status"], "check_failed")
|
||||||
|
self.assertIn("权限", state["message"])
|
||||||
|
self.assertFalse(state["available"])
|
||||||
|
self.assertFalse(state["can_apply"])
|
||||||
|
self.assertIsNone(state["latest_version"])
|
||||||
|
self.assertNotIn(TOKEN, json.dumps(state))
|
||||||
|
self.assertNotIn(TOKEN, (self.root / "update-check.json").read_text(encoding="utf-8"))
|
||||||
|
|
||||||
|
def test_untrusted_response_and_network_exception_are_sanitized(self):
|
||||||
|
self.token()
|
||||||
|
for body in (TOKEN.encode(), json.dumps({"error": TOKEN}).encode()):
|
||||||
|
with self.subTest(body=body), self.transport(body):
|
||||||
|
with self.assertRaises(updates.GitHubReleaseError) as caught:
|
||||||
|
updates.github_releases(self.root)
|
||||||
|
self.assertNotIn(TOKEN, "".join(traceback.format_exception(caught.exception)))
|
||||||
|
with self.transport() as build:
|
||||||
|
build.return_value.open.side_effect = URLError(TOKEN)
|
||||||
|
with self.assertRaises(updates.GitHubReleaseError) as caught:
|
||||||
|
updates.github_releases(self.root)
|
||||||
|
self.assertNotIn(TOKEN, "".join(traceback.format_exception(caught.exception)))
|
||||||
|
|
||||||
|
def test_redirect_responses_never_issue_a_second_request(self):
|
||||||
|
self.token()
|
||||||
|
requests = []
|
||||||
|
|
||||||
|
class RedirectTransport(HTTPSHandler):
|
||||||
|
def https_open(self, request):
|
||||||
|
requests.append(request)
|
||||||
|
headers = Message()
|
||||||
|
headers["Location"] = destination
|
||||||
|
response = addinfourl(io.BytesIO(b""), headers, request.full_url, status)
|
||||||
|
response.msg = "redirect"
|
||||||
|
return response
|
||||||
|
|
||||||
|
for destination in ("https://evil.invalid/" + TOKEN, updates.RELEASES_API + "/redirect"):
|
||||||
|
for status in (301, 302, 303, 307, 308):
|
||||||
|
requests.clear()
|
||||||
|
opener = build_opener(updates._NoRedirect(), RedirectTransport())
|
||||||
|
with self.subTest(destination=destination, status=status), patch.object(updates, "build_opener", return_value=opener):
|
||||||
|
with self.assertRaises(updates.GitHubReleaseError) as caught:
|
||||||
|
updates.github_releases(self.root)
|
||||||
|
self.assertEqual(len(requests), 1)
|
||||||
|
self.assertNotIn(TOKEN, str(caught.exception))
|
||||||
|
|
||||||
|
def test_untrusted_endpoint_is_rejected_before_loading_credentials(self):
|
||||||
|
for endpoint in ("https://evil.invalid/releases", "http://api.github.com/repos/attilanet/myrzx_bot/releases",
|
||||||
|
updates.RELEASES_API + "?redirect=bad", "https://api.github.com@evil.invalid/releases"):
|
||||||
|
with self.subTest(endpoint=endpoint), patch.object(updates, "RELEASES_API", endpoint), patch.object(updates, "_github_token") as read:
|
||||||
|
with self.assertRaises(updates.GitHubReleaseError):
|
||||||
|
updates.github_releases(self.root)
|
||||||
|
read.assert_not_called()
|
||||||
|
|
||||||
|
def test_cache_cannot_inject_freeform_failure_message(self):
|
||||||
|
for failure in (TOKEN, [TOKEN], {TOKEN: TOKEN}):
|
||||||
|
updates.atomic_json(self.root / "update-check.json", {"status": "check_failed", "failure": failure})
|
||||||
|
state = updates.UpdateService(self.root, "2.0.0").status()
|
||||||
|
self.assertEqual(state["status"], "check_failed")
|
||||||
|
self.assertNotIn(TOKEN, json.dumps(state))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -143,7 +143,7 @@ class ServiceTests(unittest.TestCase):
|
|||||||
status = self.manager.status(identifier)
|
status = self.manager.status(identifier)
|
||||||
self.assertTrue(status["connected"])
|
self.assertTrue(status["connected"])
|
||||||
self.assertFalse(status["demo"])
|
self.assertFalse(status["demo"])
|
||||||
self.assertFalse(status["running"])
|
self.assertTrue(status["running"])
|
||||||
worker = self.manager._worker(identifier)
|
worker = self.manager._worker(identifier)
|
||||||
identity = worker.active_identity
|
identity = worker.active_identity
|
||||||
before = worker.securestore.load(identity).reqid
|
before = worker.securestore.load(identity).reqid
|
||||||
@@ -161,7 +161,131 @@ class ServiceTests(unittest.TestCase):
|
|||||||
self.job(identifier, self.manager.submit(identifier, "restore_session", {"session_id": identity}))
|
self.job(identifier, self.manager.submit(identifier, "restore_session", {"session_id": identity}))
|
||||||
restored = self.manager._worker(identifier).securestore.load(identity)
|
restored = self.manager._worker(identifier).securestore.load(identity)
|
||||||
self.assertGreater(restored.reqid, before)
|
self.assertGreater(restored.reqid, before)
|
||||||
self.assertFalse(self.manager.status(identifier)["running"])
|
self.assertTrue(self.manager.status(identifier)["running"])
|
||||||
|
self.assertTrue(self.manager._worker(identifier).engine.auto)
|
||||||
|
|
||||||
|
def test_verified_login_starts_only_saved_selections_after_server_activation(self):
|
||||||
|
identifier = self.account(False)
|
||||||
|
self.login(identifier)
|
||||||
|
self.enable(identifier)
|
||||||
|
selected = deepcopy(self.manager.get_config(identifier)["config"])
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "logout"))
|
||||||
|
before = len(FakeClient.calls)
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "login", {
|
||||||
|
"account": "synthetic-owner", "password": "synthetic-password"}))
|
||||||
|
worker = self.manager._worker(identifier)
|
||||||
|
self.assertFalse(worker.running, "SDK server discovery activated strategies")
|
||||||
|
self.assertFalse(worker.engine.auto)
|
||||||
|
self.assertIsNone(worker.engine.client)
|
||||||
|
result = self.job(identifier, self.manager.submit(identifier, "enter_server", {"server_id": 1}))["result"]
|
||||||
|
self.assertTrue(result["connected"])
|
||||||
|
self.assertTrue(result["running"])
|
||||||
|
self.assertTrue(worker.engine.auto)
|
||||||
|
self.assertEqual(worker.config, selected, "Login changed the user's strategy selections")
|
||||||
|
self.assertIn("已勾选", result["message"])
|
||||||
|
self.assertEqual(self.manager.logs(identifier)["entries"][-1]["message"], result["message"])
|
||||||
|
self.assertEqual([url.rsplit("/", 2)[-2:] for _, url, _ in FakeClient.calls[before:]],
|
||||||
|
[["userServerService", "enterGame"], ["masterService", "masterQueryDetail"]])
|
||||||
|
|
||||||
|
def test_login_without_selected_rules_stays_enabled_and_later_selections_take_effect(self):
|
||||||
|
identifier = self.account(False)
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "login", {
|
||||||
|
"account": "synthetic-owner", "password": "synthetic-password"}))
|
||||||
|
worker = self.manager._worker(identifier)
|
||||||
|
selected = deepcopy(worker.config)
|
||||||
|
result = self.job(identifier, self.manager.submit(identifier, "enter_server", {"server_id": 1}))["result"]
|
||||||
|
self.assertTrue(result["connected"])
|
||||||
|
self.assertTrue(result["running"])
|
||||||
|
self.assertTrue(worker.engine.auto)
|
||||||
|
self.assertEqual(worker.config, selected)
|
||||||
|
self.assertIn("已勾选", result["message"])
|
||||||
|
self.assertEqual(worker.engine.plans(), [])
|
||||||
|
before = len(FakeClient.calls)
|
||||||
|
worker.engine.last_heartbeat = worker.schedule.clock()
|
||||||
|
worker.schedule.next_poll = 0
|
||||||
|
self.job(identifier, worker.enqueue("__tick"))
|
||||||
|
self.assertTrue(worker.running)
|
||||||
|
self.assertTrue(worker.engine.auto)
|
||||||
|
self.assertTrue(all(url.endswith("masterService/masterQueryDetail")
|
||||||
|
for _, url, _ in FakeClient.calls[before:]))
|
||||||
|
self.enable(identifier)
|
||||||
|
self.assertTrue(worker.running)
|
||||||
|
self.assertTrue(worker.engine.auto)
|
||||||
|
self.assertTrue(worker.engine.daily_policy.enabled)
|
||||||
|
|
||||||
|
def test_restore_with_unknown_write_keeps_evidence_and_never_replays(self):
|
||||||
|
identifier = self.account(False)
|
||||||
|
self.login(identifier)
|
||||||
|
self.enable(identifier)
|
||||||
|
worker = self.manager._worker(identifier)
|
||||||
|
journal = worker.engine.battle_journal
|
||||||
|
pending = journal.begin(worker.engine.snapshot, {"kind": "battle", "description": "未确认战斗",
|
||||||
|
"path": "stageService/stageStart", "payload": {}, "stage_id": "0101", "difficulty": "1"})
|
||||||
|
journal.update(pending, "unknown", message="已有未确认请求,禁止重发")
|
||||||
|
evidence = journal.path.read_bytes()
|
||||||
|
before = len(FakeClient.calls)
|
||||||
|
result = self.job(identifier, self.manager.submit(identifier, "restore_session", {
|
||||||
|
"session_id": worker.active_identity}))["result"]
|
||||||
|
self.assertTrue(result["connected"])
|
||||||
|
self.assertFalse(result["running"])
|
||||||
|
self.assertFalse(worker.engine.auto)
|
||||||
|
self.assertIn("核对", result["message"])
|
||||||
|
self.assertEqual(journal.path.read_bytes(), evidence)
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "start"), status="failed")
|
||||||
|
worker.engine.last_heartbeat = worker.schedule.clock()
|
||||||
|
self.job(identifier, worker.enqueue("__tick"))
|
||||||
|
self.assertEqual(worker.engine.battle_journal.pending(worker.engine.snapshot)["attempt_id"], pending["attempt_id"])
|
||||||
|
self.assertEqual(journal.path.read_bytes(), evidence)
|
||||||
|
self.assertTrue(all(url.endswith(("masterService/masterQueryDetail", "heartBeatService/keepAlive"))
|
||||||
|
for _, url, _ in FakeClient.calls[before:]))
|
||||||
|
|
||||||
|
def test_activation_persistence_can_be_revoked_before_final_commit(self):
|
||||||
|
for operation in ("enter_server", "restore_session"):
|
||||||
|
for revoke in ("stop", "logout", "forget_login", "config"):
|
||||||
|
with self.subTest(operation=operation, revoke=revoke):
|
||||||
|
identifier = self.account(False)
|
||||||
|
self.login(identifier, account="owner-" + identifier)
|
||||||
|
self.enable(identifier)
|
||||||
|
worker = self.manager._worker(identifier)
|
||||||
|
original_client = worker.engine.client
|
||||||
|
identity = worker.active_identity
|
||||||
|
if operation == "enter_server":
|
||||||
|
self.job(identifier, self.manager.submit(identifier, "login", {
|
||||||
|
"account": "owner-" + identifier, "password": "synthetic-password"}))
|
||||||
|
entered, release = threading.Event(), threading.Event()
|
||||||
|
self.addCleanup(release.set)
|
||||||
|
original = worker.securestore.set_active
|
||||||
|
|
||||||
|
def held(active):
|
||||||
|
if active == identity and not release.is_set():
|
||||||
|
entered.set()
|
||||||
|
if not release.wait(5):
|
||||||
|
raise AssertionError("Activation gate not released")
|
||||||
|
return original(active)
|
||||||
|
|
||||||
|
payload = {"server_id": 1} if operation == "enter_server" else {"session_id": identity}
|
||||||
|
before = self.manager.logs(identifier)["next"]
|
||||||
|
with patch.object(worker.securestore, "set_active", side_effect=held):
|
||||||
|
candidate = self.manager.submit(identifier, operation, payload)
|
||||||
|
self.assertTrue(entered.wait(2))
|
||||||
|
if revoke == "config":
|
||||||
|
config = self.manager.get_config(identifier)["config"]
|
||||||
|
config["daily_policy"]["enabled"] = False
|
||||||
|
followup = self.manager.set_config(identifier, config)["job"]
|
||||||
|
else:
|
||||||
|
followup = self.manager.submit(identifier, revoke)
|
||||||
|
self.assertFalse(worker.running)
|
||||||
|
release.set()
|
||||||
|
self.job(identifier, candidate, status="cancelled")
|
||||||
|
self.job(identifier, followup)
|
||||||
|
self.assertFalse(worker.running)
|
||||||
|
self.assertFalse(worker.engine.auto)
|
||||||
|
if revoke in {"stop", "config"}:
|
||||||
|
self.assertIs(worker.engine.client, original_client)
|
||||||
|
else:
|
||||||
|
self.assertIsNone(worker.engine.client)
|
||||||
|
self.assertFalse(any("已自动开启" in row["message"]
|
||||||
|
for row in self.manager.logs(identifier, after=before)["entries"]))
|
||||||
|
|
||||||
def test_role_workspaces_do_not_copy_targets_or_other_profiles_overrides(self):
|
def test_role_workspaces_do_not_copy_targets_or_other_profiles_overrides(self):
|
||||||
first, other = self.account(False), self.account()
|
first, other = self.account(False), self.account()
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ class UpdateTests(unittest.TestCase):
|
|||||||
self.environment = patch.dict(os.environ, {"RANCH_WEB_UPDATER_DIR": ""})
|
self.environment = patch.dict(os.environ, {"RANCH_WEB_UPDATER_DIR": ""})
|
||||||
self.environment.start()
|
self.environment.start()
|
||||||
self.addCleanup(self.environment.stop)
|
self.addCleanup(self.environment.stop)
|
||||||
|
os.environ.pop(updates.TOKEN_FILE_ENV, None)
|
||||||
self.github = patch.object(updates, "github_releases", return_value=[])
|
self.github = patch.object(updates, "github_releases", return_value=[])
|
||||||
self.releases = self.github.start()
|
self.releases = self.github.start()
|
||||||
self.addCleanup(self.github.stop)
|
self.addCleanup(self.github.stop)
|
||||||
|
|||||||
@@ -88,11 +88,12 @@ class HostUpdaterTests(unittest.TestCase):
|
|||||||
self.addCleanup(self.github.stop)
|
self.addCleanup(self.github.stop)
|
||||||
# Linux CI runs unprivileged; real chown is a host deployment check.
|
# Linux CI runs unprivileged; real chown is a host deployment check.
|
||||||
self.chown = patch.object(updater.os, "chown", create=True)
|
self.chown = patch.object(updater.os, "chown", create=True)
|
||||||
self.chown.start()
|
self.mock_chown = self.chown.start()
|
||||||
self.addCleanup(self.chown.stop)
|
self.addCleanup(self.chown.stop)
|
||||||
self.environment = patch.dict(os.environ, {"RANCH_WEB_UPDATER_DIR": str(self.config.control_dir)})
|
self.environment = patch.dict(os.environ, {"RANCH_WEB_UPDATER_DIR": str(self.config.control_dir)})
|
||||||
self.environment.start()
|
self.environment.start()
|
||||||
self.addCleanup(self.environment.stop)
|
self.addCleanup(self.environment.stop)
|
||||||
|
os.environ.pop(updates.TOKEN_FILE_ENV, None)
|
||||||
|
|
||||||
def samples(self, directory=None):
|
def samples(self, directory=None):
|
||||||
with closing(sqlite3.connect((directory or self.config.data_dir) / "samples.sqlite3")) as connection:
|
with closing(sqlite3.connect((directory or self.config.data_dir) / "samples.sqlite3")) as connection:
|
||||||
@@ -282,6 +283,102 @@ class HostUpdaterTests(unittest.TestCase):
|
|||||||
result = updater.HostUpdater(config, self.docker).run()
|
result = updater.HostUpdater(config, self.docker).run()
|
||||||
self.assertEqual(result["status"], "succeeded")
|
self.assertEqual(result["status"], "succeeded")
|
||||||
|
|
||||||
|
def test_private_web_check_request_and_host_apply_each_reread_shared_token(self):
|
||||||
|
self.enable()
|
||||||
|
self.github.stop()
|
||||||
|
path = self.config.data_dir / updates.TOKEN_FILE_NAME
|
||||||
|
tokens = ["github_pat_offline_check", "github_pat_offline_request", "github_pat_offline_host"]
|
||||||
|
path.write_text(tokens[0], encoding="ascii")
|
||||||
|
path.chmod(0o600)
|
||||||
|
payload = json.dumps([release("v2.0.1")]).encode("ascii")
|
||||||
|
service = updates.UpdateService(self.config.data_dir, "2.0.0")
|
||||||
|
with patch.object(updates, "build_opener") as build:
|
||||||
|
build.return_value.open.side_effect = lambda *args, **kwargs: io.BytesIO(payload)
|
||||||
|
self.assertTrue(service.check()["available"])
|
||||||
|
path.write_text(tokens[1], encoding="ascii")
|
||||||
|
self.assertEqual(service.request_update("v2.0.1")["status"], "pending")
|
||||||
|
path.write_text(tokens[2], encoding="ascii")
|
||||||
|
self.assertEqual(self.host.run()["status"], "succeeded")
|
||||||
|
authorizations = [call.args[0].get_header("Authorization") for call in build.return_value.open.call_args_list]
|
||||||
|
self.assertEqual(authorizations, ["Bearer " + token for token in tokens])
|
||||||
|
for document in [*self.config.data_dir.glob("*.json"), *self.config.control_dir.glob("*.json")]:
|
||||||
|
for token in tokens:
|
||||||
|
self.assertNotIn(token, document.read_text(encoding="utf-8"))
|
||||||
|
|
||||||
|
def test_private_access_failure_blocks_web_request_and_host_before_pull(self):
|
||||||
|
from urllib.error import HTTPError
|
||||||
|
self.enable()
|
||||||
|
self.github.stop()
|
||||||
|
service = updates.UpdateService(self.config.data_dir, "2.0.0")
|
||||||
|
for status in (401, 403, 404):
|
||||||
|
with self.subTest(status=status), patch.object(updates, "build_opener") as build:
|
||||||
|
build.return_value.open.side_effect = HTTPError(updates.RELEASES_API, status, "private-secret", {}, None)
|
||||||
|
with self.assertRaises(ValueError) as web_error:
|
||||||
|
service.request_update("v2.0.1")
|
||||||
|
with self.assertRaises(updater.UpdaterError) as host_error:
|
||||||
|
self.host.apply("v2.0.1")
|
||||||
|
for error in (web_error.exception, host_error.exception):
|
||||||
|
self.assertIn("权限", str(error))
|
||||||
|
self.assertNotIn("private-secret", str(error))
|
||||||
|
self.assertFalse((self.config.data_dir / "update-request.json").exists())
|
||||||
|
self.assertFalse(self.host.journal.exists())
|
||||||
|
self.assertFalse(self.config.backup_dir.exists())
|
||||||
|
self.assertEqual(self.docker.events, [])
|
||||||
|
|
||||||
|
def test_health_failure_restores_shared_token_permissions(self):
|
||||||
|
path = self.config.data_dir / updates.TOKEN_FILE_NAME
|
||||||
|
path.write_text("github_pat_offline_before", encoding="ascii")
|
||||||
|
path.chmod(0o600)
|
||||||
|
self.docker.fail_start = True
|
||||||
|
original_up = self.docker.up
|
||||||
|
|
||||||
|
def start(image):
|
||||||
|
if image != self.docker.old_image:
|
||||||
|
path.write_text("github_pat_offline_failed", encoding="ascii")
|
||||||
|
return original_up(image)
|
||||||
|
|
||||||
|
with patch.object(self.docker, "up", side_effect=start):
|
||||||
|
self.assertEqual(self.host.apply()["status"], "rolled_back")
|
||||||
|
self.assertEqual(path.read_text(encoding="ascii"), "github_pat_offline_before")
|
||||||
|
if os.name == "posix":
|
||||||
|
self.assertEqual(path.stat().st_mode & 0o777, 0o600)
|
||||||
|
|
||||||
|
def test_interactive_token_setup_is_local_hidden_and_sets_shared_ownership(self):
|
||||||
|
token = "github_pat_offline_interactive"
|
||||||
|
with patch.object(updater.getpass, "getpass", return_value=token), patch.object(updates, "build_opener") as network, patch.object(updater.Docker, "run") as docker:
|
||||||
|
result = updater.set_github_token(self.config)
|
||||||
|
path = self.config.data_dir / updates.TOKEN_FILE_NAME
|
||||||
|
self.assertEqual(path.read_text(encoding="ascii"), token + "\n")
|
||||||
|
self.assertEqual(self.mock_chown.call_args.args[1:], (10001, 10001))
|
||||||
|
if os.name == "posix":
|
||||||
|
self.assertEqual(path.stat().st_mode & 0o777, 0o600)
|
||||||
|
self.assertNotIn(token, json.dumps(result))
|
||||||
|
network.assert_not_called()
|
||||||
|
docker.assert_not_called()
|
||||||
|
|
||||||
|
def test_token_setup_rejects_echo_fallback_and_preserves_old_token_on_failure(self):
|
||||||
|
path = self.config.data_dir / updates.TOKEN_FILE_NAME
|
||||||
|
path.write_text("old-offline-token", encoding="ascii")
|
||||||
|
for failure in (EOFError("private-secret"), updater.getpass.GetPassWarning("private-secret")):
|
||||||
|
with self.subTest(failure=type(failure).__name__), patch.object(updater.getpass, "getpass", side_effect=failure):
|
||||||
|
with self.assertRaises(updater.UpdaterError) as caught:
|
||||||
|
updater.set_github_token(self.config)
|
||||||
|
self.assertNotIn("private-secret", str(caught.exception))
|
||||||
|
with patch.object(updater.getpass, "getpass", return_value="new-offline-token"), patch.object(updater.os, "replace", side_effect=OSError("private-secret")):
|
||||||
|
with self.assertRaises(updater.UpdaterError):
|
||||||
|
updater.set_github_token(self.config)
|
||||||
|
self.assertEqual(path.read_text(encoding="ascii"), "old-offline-token")
|
||||||
|
self.assertEqual(list(self.config.data_dir.glob(".update-token-*")), [])
|
||||||
|
|
||||||
|
def test_token_setup_dry_run_does_not_prompt_read_credentials_or_write(self):
|
||||||
|
source = Path(updater.__file__).with_name("updater.example.toml")
|
||||||
|
with patch.object(updater.getpass, "getpass") as prompt, patch.object(updates, "_github_token") as read, redirect_stdout(io.StringIO()) as output:
|
||||||
|
code = updater.main(["--config", str(source), "--set-github-token", "--dry-run"])
|
||||||
|
self.assertEqual(code, 0)
|
||||||
|
self.assertEqual(json.loads(output.getvalue())["mode"], "set-github-token")
|
||||||
|
prompt.assert_not_called()
|
||||||
|
read.assert_not_called()
|
||||||
|
|
||||||
def test_malformed_request_fails_without_network_or_docker(self):
|
def test_malformed_request_fails_without_network_or_docker(self):
|
||||||
self.enable()
|
self.enable()
|
||||||
updates.atomic_json(self.config.data_dir / "update-request.json", ["invalid"])
|
updates.atomic_json(self.config.data_dir / "update-request.json", ["invalid"])
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
"""The release asset must run from outside the repo with only Python stdlib."""
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
import zipfile
|
||||||
|
|
||||||
|
from ranch_web import __version__
|
||||||
|
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[2]
|
||||||
|
OFFLINE_RUNNER = """
|
||||||
|
import os, runpy, socket, subprocess, sys
|
||||||
|
def forbidden(*args, **kwargs):
|
||||||
|
raise AssertionError('Network/Docker/prompt forbidden in package smoke test')
|
||||||
|
socket.socket.connect = forbidden
|
||||||
|
socket.create_connection = forbidden
|
||||||
|
subprocess.run = forbidden
|
||||||
|
import getpass
|
||||||
|
getpass.getpass = forbidden
|
||||||
|
os.environ['RANCH_WEB_UPDATE_GITHUB_TOKEN_FILE'] = '/nonexistent/private-token'
|
||||||
|
sys.argv = sys.argv[1:]
|
||||||
|
runpy.run_path(sys.argv[0], run_name='__main__')
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class UpdaterPackageTests(unittest.TestCase):
|
||||||
|
@classmethod
|
||||||
|
def setUpClass(cls):
|
||||||
|
cls.temporary = tempfile.TemporaryDirectory(prefix="standalone-updater-test-")
|
||||||
|
cls.addClassCleanup(cls.temporary.cleanup)
|
||||||
|
cls.folder = Path(cls.temporary.name)
|
||||||
|
cls.asset = cls.folder / "updater.pyz"
|
||||||
|
subprocess.run([sys.executable, "-I", "-S", "-B", str(ROOT / "tools/build_web_updater.py"),
|
||||||
|
"--output", str(cls.asset)], cwd=cls.folder, capture_output=True, check=True)
|
||||||
|
cls.config = cls.folder / "updater.toml"
|
||||||
|
cls.config.write_bytes((ROOT / "deploy/web/updater.example.toml").read_bytes())
|
||||||
|
|
||||||
|
def invoke(self, *arguments):
|
||||||
|
result = subprocess.run([sys.executable, "-I", "-S", "-B", "-X", "utf8", "-c", OFFLINE_RUNNER,
|
||||||
|
str(self.asset), *arguments], cwd=self.folder,
|
||||||
|
capture_output=True, text=True, encoding="utf-8", timeout=15)
|
||||||
|
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||||
|
return result.stdout
|
||||||
|
|
||||||
|
def test_help_and_version_work_without_config_repo_or_dependencies(self):
|
||||||
|
self.assertIn("--set-github-token", self.invoke("--help"))
|
||||||
|
self.assertEqual(self.invoke("--version").strip(), f"ranch-web-updater {__version__}")
|
||||||
|
|
||||||
|
def test_dry_run_is_offline_does_not_load_token_or_write_files(self):
|
||||||
|
before = sorted(path.relative_to(self.folder) for path in self.folder.rglob("*"))
|
||||||
|
result = json.loads(self.invoke("--config", str(self.config), "--apply", "v2.0.1", "--dry-run"))
|
||||||
|
self.assertTrue(result["dry_run"])
|
||||||
|
self.assertEqual(result["image"], "ghcr.io/attilanet/myrzx_bot-web:v2.0.1")
|
||||||
|
self.assertFalse(result["auto_apply"])
|
||||||
|
self.assertFalse(result["accept_web_requests"])
|
||||||
|
self.assertEqual(before, sorted(path.relative_to(self.folder) for path in self.folder.rglob("*")))
|
||||||
|
|
||||||
|
def test_archive_is_minimal_and_reproducible(self):
|
||||||
|
second = self.folder / "second.pyz"
|
||||||
|
subprocess.run([sys.executable, "-I", "-S", "-B", str(ROOT / "tools/build_web_updater.py"),
|
||||||
|
"--output", str(second)], cwd=self.folder, capture_output=True, check=True)
|
||||||
|
self.assertEqual(self.asset.read_bytes(), second.read_bytes())
|
||||||
|
with zipfile.ZipFile(self.asset) as archive:
|
||||||
|
self.assertEqual(set(archive.namelist()), {"__main__.py", "updater.py", "ranch_web/__init__.py", "ranch_web/updates.py"})
|
||||||
|
self.assertEqual(archive.read("ranch_web/__init__.py"), (ROOT / "ranch_web/__init__.py").read_bytes())
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
+96
-17
@@ -14,6 +14,7 @@ import stat
|
|||||||
import tempfile
|
import tempfile
|
||||||
import threading
|
import threading
|
||||||
from urllib.error import HTTPError
|
from urllib.error import HTTPError
|
||||||
|
from urllib.parse import urlsplit
|
||||||
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
@@ -21,6 +22,14 @@ REPOSITORY = "attilanet/myrzx_bot"
|
|||||||
IMAGE = "ghcr.io/attilanet/myrzx_bot-web"
|
IMAGE = "ghcr.io/attilanet/myrzx_bot-web"
|
||||||
RELEASES_API = f"https://api.github.com/repos/{REPOSITORY}/releases"
|
RELEASES_API = f"https://api.github.com/repos/{REPOSITORY}/releases"
|
||||||
PROTOCOL = 1
|
PROTOCOL = 1
|
||||||
|
TOKEN_FILE_NAME = "update-github-token"
|
||||||
|
TOKEN_FILE_ENV = "RANCH_WEB_UPDATE_GITHUB_TOKEN_FILE"
|
||||||
|
_TOKEN_LIMIT = 4096
|
||||||
|
_RELEASE_FAILURES = {
|
||||||
|
"check_failed": "GitHub 发布检查失败,请稍后重试。",
|
||||||
|
"access_denied": "无法访问官方 GitHub 发布(401/403/404);请检查服务端 GitHub Token 文件及私有仓库的只读发布权限。",
|
||||||
|
"token_file_invalid": "GitHub Token 文件不可用;请检查服务端文件、0600 权限及数据目录 UID 10001 所有权。",
|
||||||
|
}
|
||||||
_TAG = re.compile(r"v2\.(0|[1-9][0-9]{0,8})\.(0|[1-9][0-9]{0,8})", re.ASCII)
|
_TAG = re.compile(r"v2\.(0|[1-9][0-9]{0,8})\.(0|[1-9][0-9]{0,8})", re.ASCII)
|
||||||
_CURRENT = re.compile(r"v?2\.(0|[1-9][0-9]{0,8})\.(0|[1-9][0-9]{0,8})(\.dev[0-9]+)?", re.ASCII)
|
_CURRENT = re.compile(r"v?2\.(0|[1-9][0-9]{0,8})\.(0|[1-9][0-9]{0,8})(\.dev[0-9]+)?", re.ASCII)
|
||||||
_ID = re.compile(r"[0-9a-f]{32}", re.ASCII)
|
_ID = re.compile(r"[0-9a-f]{32}", re.ASCII)
|
||||||
@@ -129,32 +138,93 @@ class _NoRedirect(HTTPRedirectHandler):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def github_releases():
|
class GitHubReleaseError(RuntimeError):
|
||||||
"""Fetch only the fixed public repository. No tokens or asset downloads."""
|
"""Fixed, public explanations; never retain credentials or HTTP bodies."""
|
||||||
|
|
||||||
|
def __init__(self, code="check_failed"):
|
||||||
|
self.code = code if code in _RELEASE_FAILURES else "check_failed"
|
||||||
|
super().__init__(_RELEASE_FAILURES[self.code])
|
||||||
|
|
||||||
|
|
||||||
|
def github_token_path(data_dir=None):
|
||||||
|
"""An explicit override is a server-side path, never a raw token."""
|
||||||
|
override = os.environ.get(TOKEN_FILE_ENV)
|
||||||
|
if override is not None:
|
||||||
|
if not override or not Path(override).is_absolute():
|
||||||
|
raise GitHubReleaseError("token_file_invalid")
|
||||||
|
return Path(override)
|
||||||
|
return Path(data_dir) / TOKEN_FILE_NAME if data_dir is not None else None
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_token(payload):
|
||||||
|
try:
|
||||||
|
token = payload.decode("ascii").rstrip("\r\n")
|
||||||
|
if not 0 < len(payload) <= _TOKEN_LIMIT or re.fullmatch(r"[!-~]+", token) is None:
|
||||||
|
raise ValueError
|
||||||
|
except (UnicodeError, ValueError):
|
||||||
|
raise GitHubReleaseError("token_file_invalid") from None
|
||||||
|
return token
|
||||||
|
|
||||||
|
|
||||||
|
def _github_token(data_dir):
|
||||||
|
path = github_token_path(data_dir)
|
||||||
|
if path is None:
|
||||||
|
return None
|
||||||
|
flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
|
||||||
|
try:
|
||||||
|
if path.is_symlink():
|
||||||
|
raise GitHubReleaseError("token_file_invalid")
|
||||||
|
descriptor = os.open(path, flags)
|
||||||
|
with os.fdopen(descriptor, "rb") as stream:
|
||||||
|
info = os.fstat(stream.fileno())
|
||||||
|
if (not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or info.st_size > _TOKEN_LIMIT
|
||||||
|
or (os.name == "posix" and stat.S_IMODE(info.st_mode) != 0o600)):
|
||||||
|
raise GitHubReleaseError("token_file_invalid")
|
||||||
|
return _validate_token(stream.read(_TOKEN_LIMIT + 1))
|
||||||
|
except FileNotFoundError:
|
||||||
|
if TOKEN_FILE_ENV not in os.environ:
|
||||||
|
return None # Existing public deployments need no credential.
|
||||||
|
raise GitHubReleaseError("token_file_invalid") from None
|
||||||
|
except OSError:
|
||||||
|
raise GitHubReleaseError("token_file_invalid") from None
|
||||||
|
|
||||||
|
|
||||||
|
def github_releases(data_dir=None):
|
||||||
|
"""Fetch fixed official releases using only an optional server token file."""
|
||||||
|
# Validate before loading credentials, even if a caller monkey-patches the URL.
|
||||||
|
endpoint = urlsplit(RELEASES_API)
|
||||||
|
if (endpoint.scheme != "https" or endpoint.netloc != "api.github.com"
|
||||||
|
or endpoint.path != f"/repos/{REPOSITORY}/releases" or endpoint.query or endpoint.fragment):
|
||||||
|
raise GitHubReleaseError()
|
||||||
|
token = _github_token(data_dir)
|
||||||
opener = build_opener(_NoRedirect())
|
opener = build_opener(_NoRedirect())
|
||||||
releases = []
|
releases = []
|
||||||
for page in range(1, 11):
|
for page in range(1, 11):
|
||||||
request = Request(f"{RELEASES_API}?per_page=100&page={page}", headers={
|
headers = {
|
||||||
"Accept": "application/vnd.github+json",
|
"Accept": "application/vnd.github+json",
|
||||||
"User-Agent": "ranch-web-release-checker/2",
|
"User-Agent": "ranch-web-release-checker/2",
|
||||||
"X-GitHub-Api-Version": "2022-11-28",
|
"X-GitHub-Api-Version": "2022-11-28",
|
||||||
})
|
}
|
||||||
|
if token is not None:
|
||||||
|
headers["Authorization"] = f"Bearer {token}"
|
||||||
|
request = Request(f"{RELEASES_API}?per_page=100&page={page}", headers=headers)
|
||||||
try:
|
try:
|
||||||
with opener.open(request, timeout=8) as response:
|
with opener.open(request, timeout=8) as response:
|
||||||
payload = response.read(2 * 1024 * 1024 + 1)
|
payload = response.read(2 * 1024 * 1024 + 1)
|
||||||
|
if len(payload) > 2 * 1024 * 1024:
|
||||||
|
raise ValueError
|
||||||
|
items = json.loads(payload)
|
||||||
|
if not isinstance(items, list) or len(items) > 100:
|
||||||
|
raise ValueError
|
||||||
except HTTPError as error:
|
except HTTPError as error:
|
||||||
if error.code == 404: # A repository without public releases.
|
error.close()
|
||||||
return []
|
raise GitHubReleaseError("access_denied" if error.code in {401, 403, 404} else "check_failed") from None
|
||||||
raise
|
except Exception:
|
||||||
if len(payload) > 2 * 1024 * 1024:
|
raise GitHubReleaseError() from None
|
||||||
raise ValueError("发布列表超出大小限制。")
|
|
||||||
items = json.loads(payload)
|
|
||||||
if not isinstance(items, list) or len(items) > 100:
|
|
||||||
raise ValueError("发布列表格式无效。")
|
|
||||||
releases.extend(items)
|
releases.extend(items)
|
||||||
if len(items) < 100:
|
if len(items) < 100:
|
||||||
return releases
|
return releases
|
||||||
raise ValueError("发布列表超出页数限制,请稍后重试。")
|
raise GitHubReleaseError()
|
||||||
|
|
||||||
|
|
||||||
def official_tags(releases):
|
def official_tags(releases):
|
||||||
@@ -260,13 +330,17 @@ class UpdateService:
|
|||||||
state = request["status"]
|
state = request["status"]
|
||||||
elif host:
|
elif host:
|
||||||
state = host["status"]
|
state = host["status"]
|
||||||
|
failure = cache.get("failure")
|
||||||
|
failure = failure if isinstance(failure, str) else None
|
||||||
|
message = (_RELEASE_FAILURES.get(failure, _MESSAGES[state])
|
||||||
|
if state == "check_failed" else _MESSAGES[state])
|
||||||
result = {
|
result = {
|
||||||
"current_version": self.current_version, "latest_version": latest,
|
"current_version": self.current_version, "latest_version": latest,
|
||||||
"available": available, "checked_at": timestamp(checked) if checked else None,
|
"available": available, "checked_at": timestamp(checked) if checked else None,
|
||||||
"release_url": f"https://github.com/{REPOSITORY}/releases/tag/{latest}" if latest else None,
|
"release_url": f"https://github.com/{REPOSITORY}/releases/tag/{latest}" if latest else None,
|
||||||
"channel": "stable-2.x", "repository": REPOSITORY,
|
"channel": "stable-2.x", "repository": REPOSITORY,
|
||||||
"status": state, "message": _MESSAGES[state],
|
"status": state, "message": message,
|
||||||
"error": _MESSAGES[state] if state in {"check_failed", "failed", "rolled_back"} else None,
|
"error": message if state in {"check_failed", "failed", "rolled_back"} else None,
|
||||||
"can_apply": available and executor["enabled"] and state not in {"pending", "applying"},
|
"can_apply": available and executor["enabled"] and state not in {"pending", "applying"},
|
||||||
"executor": executor, "request": request, "host_status": host,
|
"executor": executor, "request": request, "host_status": host,
|
||||||
}
|
}
|
||||||
@@ -275,10 +349,13 @@ class UpdateService:
|
|||||||
def check(self):
|
def check(self):
|
||||||
with self._lock:
|
with self._lock:
|
||||||
try:
|
try:
|
||||||
tags = official_tags(github_releases())
|
tags = official_tags(github_releases(self.root))
|
||||||
latest = max(tags, key=stable_version) if tags else None
|
latest = max(tags, key=stable_version) if tags else None
|
||||||
state = "no_release" if latest is None else "available" if stable_version(latest) > self._current else "up_to_date"
|
state = "no_release" if latest is None else "available" if stable_version(latest) > self._current else "up_to_date"
|
||||||
cache = {"status": state, "latest_version": latest, "checked_at": timestamp()}
|
cache = {"status": state, "latest_version": latest, "checked_at": timestamp()}
|
||||||
|
except GitHubReleaseError as error:
|
||||||
|
cache = {"status": "check_failed", "failure": error.code,
|
||||||
|
"latest_version": None, "checked_at": timestamp()}
|
||||||
except Exception:
|
except Exception:
|
||||||
# Never expose response bodies, proxy addresses, tokens, or paths.
|
# Never expose response bodies, proxy addresses, tokens, or paths.
|
||||||
cache = {"status": "check_failed", "latest_version": None, "checked_at": timestamp()}
|
cache = {"status": "check_failed", "latest_version": None, "checked_at": timestamp()}
|
||||||
@@ -299,7 +376,9 @@ class UpdateService:
|
|||||||
return state
|
return state
|
||||||
# Revalidate against live official releases, never just a local cache.
|
# Revalidate against live official releases, never just a local cache.
|
||||||
try:
|
try:
|
||||||
tags = official_tags(github_releases())
|
tags = official_tags(github_releases(self.root))
|
||||||
|
except GitHubReleaseError as error:
|
||||||
|
raise ValueError(str(error)) from None
|
||||||
except Exception:
|
except Exception:
|
||||||
raise ValueError(_MESSAGES["check_failed"]) from None
|
raise ValueError(_MESSAGES["check_failed"]) from None
|
||||||
target = version or (max(tags, key=stable_version) if tags else None)
|
target = version or (max(tags, key=stable_version) if tags else None)
|
||||||
|
|||||||
+7
-1
@@ -91,7 +91,11 @@ def _strategy_fields(catalog):
|
|||||||
"exploration": [_field(["explore_policy", "enabled"], "自动安排再次探险(完成后自动领奖)"),
|
"exploration": [_field(["explore_policy", "enabled"], "自动安排再次探险(完成后自动领奖)"),
|
||||||
_field(["explore_policy", "reserve_ti"], "保留体力", "integer", min=0, max=1_000_000_000)],
|
_field(["explore_policy", "reserve_ti"], "保留体力", "integer", min=0, max=1_000_000_000)],
|
||||||
"yields": [_field(["yield_stars"], "星级", "multiselect", options=_options([(i, f"{i}星") for i in range(1, 6)]))],
|
"yields": [_field(["yield_stars"], "星级", "multiselect", options=_options([(i, f"{i}星") for i in range(1, 6)]))],
|
||||||
"login": [], "incubator": [], "bag": [], "ranch": [], "battles": [], "statistics": [], "plans": []}
|
"login": [_field(["auto_relogin", "enabled"], "掉线后自动重新登录", value=False,
|
||||||
|
help="需在服务端记住账号和密码,并已保存原区服和角色;开启后,掉线或服务重启均等待设定时长,再返回原区服、原角色。"),
|
||||||
|
_field(["auto_relogin", "delay_minutes"], "重登等待时长(分钟)", "integer", min=1, max=10080, value=30,
|
||||||
|
help="1~10080 的整数分钟,默认 30 分钟。重登成功恢复监控并自动执行已勾选功能,可在顶部“停止”;关闭页面不影响服务端自动重登,手动退出登录可取消本次安排。")],
|
||||||
|
"incubator": [], "bag": [], "ranch": [], "battles": [], "statistics": [], "plans": []}
|
||||||
|
|
||||||
|
|
||||||
def schema(catalog):
|
def schema(catalog):
|
||||||
@@ -118,6 +122,8 @@ def build_view(engine, page, config, query=None):
|
|||||||
if page not in dict(PAGES):
|
if page not in dict(PAGES):
|
||||||
raise ValueError("未知页面")
|
raise ValueError("未知页面")
|
||||||
config = validate_config(config)
|
config = validate_config(config)
|
||||||
|
if page == "login":
|
||||||
|
config.setdefault("auto_relogin", {"enabled": False, "delay_minutes": 30})
|
||||||
fields = _strategy_fields(engine.catalog)[page]
|
fields = _strategy_fields(engine.catalog)[page]
|
||||||
dto = {"page": page, "title": dict(PAGES)[page], "columns": [], "rows": [], "summary": "",
|
dto = {"page": page, "title": dict(PAGES)[page], "columns": [], "rows": [], "summary": "",
|
||||||
"form": [field | {"value": _value(config, field["path"])} for field in fields],
|
"form": [field | {"value": _value(config, field["path"])} for field in fields],
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Build the standalone host updater using only the Python standard library."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import tempfile
|
||||||
|
import zipfile
|
||||||
|
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
SOURCES = {
|
||||||
|
"updater.py": "deploy/web/updater.py",
|
||||||
|
"ranch_web/__init__.py": "ranch_web/__init__.py",
|
||||||
|
"ranch_web/updates.py": "ranch_web/updates.py",
|
||||||
|
}
|
||||||
|
ENTRYPOINT = b"from updater import main\nraise SystemExit(main())\n"
|
||||||
|
|
||||||
|
|
||||||
|
def build(output):
|
||||||
|
output = Path(output)
|
||||||
|
output.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
descriptor, temporary = tempfile.mkstemp(prefix=".updater-", dir=output.parent)
|
||||||
|
try:
|
||||||
|
# Fixed order/timestamps make the asset reproducible for a given source.
|
||||||
|
with os.fdopen(descriptor, "wb") as stream, zipfile.ZipFile(stream, "w", compression=zipfile.ZIP_DEFLATED) as archive:
|
||||||
|
contents = {"__main__.py": ENTRYPOINT}
|
||||||
|
contents.update({name: (ROOT / source).read_bytes() for name, source in SOURCES.items()})
|
||||||
|
for name, content in contents.items():
|
||||||
|
compile(content, name, "exec")
|
||||||
|
info = zipfile.ZipInfo(name, date_time=(2020, 1, 1, 0, 0, 0))
|
||||||
|
info.compress_type = zipfile.ZIP_DEFLATED
|
||||||
|
info.external_attr = 0o100644 << 16
|
||||||
|
archive.writestr(info, content)
|
||||||
|
os.replace(temporary, output)
|
||||||
|
finally:
|
||||||
|
if os.path.exists(temporary):
|
||||||
|
os.unlink(temporary)
|
||||||
|
return output
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv=None):
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("--output", required=True, type=Path, metavar="PATH", help="destination updater.pyz release asset")
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
print(build(args.output))
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
Reference in New Issue
Block a user