From 5b1ef250487d31075c044cda2a5052b83b33b0d1 Mon Sep 17 00:00:00 2001 From: AttilaNet Date: Wed, 11 Nov 2026 11:48:52 +0800 Subject: [PATCH] feat: add configurable delayed password relogin --- ranch_assistant/login.py | 29 +- ranch_web/README.md | 16 +- ranch_web/app.py | 5 + ranch_web/policies.py | 7 +- ranch_web/scheduler.py | 32 +- ranch_web/service.py | 244 ++++++++++- ranch_web/static/app.js | 1 + ranch_web/static/pages.js | 28 +- .../browser/test_auto_relogin_browser.py | 325 +++++++++++++++ ranch_web/tests/test_api.py | 14 +- ranch_web/tests/test_auto_relogin.py | 383 ++++++++++++++++++ ranch_web/views.py | 8 +- 12 files changed, 1068 insertions(+), 24 deletions(-) create mode 100644 ranch_web/tests/browser/test_auto_relogin_browser.py create mode 100644 ranch_web/tests/test_auto_relogin.py diff --git a/ranch_assistant/login.py b/ranch_assistant/login.py index 7442b75..342c768 100644 --- a/ranch_assistant/login.py +++ b/ranch_assistant/login.py @@ -33,19 +33,42 @@ def sdk_headers(device): 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.trace = trace self.sdk_url = sdk_url self.center_url = center_url or catalog.data["server_info"]["ANDROID"].get(channel, DEFAULT_CENTER) 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): + self._check_cancel() if not account.strip() or not password: raise ApiError("请填写账号和密码") # Cookies remain in this process and are discarded on closing the SDK session. with requests.Session() as http: http.trust_env = False + self._guard_http(http) payload = {"account": account.strip(), "password": password} params = {"versionCode": "1.0.1", "buildNumber": "2016122900", "appChannel": "taptap"} headers = sdk_headers(self.device) @@ -55,6 +78,7 @@ class PasswordLogin: try: response = http.post(self.sdk_url, data=payload, params=params, headers=headers, timeout=(5, 15), allow_redirects=False) + self._check_cancel() try: data = response.json() except ValueError as error: @@ -100,8 +124,11 @@ class PasswordLogin: 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) try: + self._guard_http(client.http) + self._check_cancel() 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")) + self._check_cancel() except Exception: client.close() raise diff --git a/ranch_web/README.md b/ranch_web/README.md index 3e5ffc9..5a59693 100644 --- a/ranch_web/README.md +++ b/ranch_web/README.md @@ -36,9 +36,19 @@ py -3 -m venv .venv-web 关闭网页或退出 Web 管理登录不会停止服务器上的账号监控和已开启策略。账号监控和策略执行由服务端管理;“停止”策略后仍保留状态监控,退出游戏账号或停止服务后结束监控。 -账号状态区分游戏在线、临时故障重试、游戏登录过期和未连接,显示最后成功通信时间及具体原因。临时网络故障采用退避后的只读状态检查;无法确认的操作保留核对记录,不自动重复提交。游戏会话失效后停止策略和游戏轮询,需在登录页重新登录或恢复有效会话;成功恢复后仍需手动开启策略。 +账号状态区分游戏在线、临时故障重试、游戏登录过期和未连接,显示最后成功通信时间及具体原因。临时网络故障采用退避后的只读状态检查;无法确认的操作保留核对记录,不自动重复提交。游戏会话失效后停止策略和游戏轮询,按自动重登录设置等待处理,或在登录页手动恢复;成功恢复后仍需手动开启策略。 -服务重启会保留配置与加密会话,但不会自动连接游戏或恢复策略。登录页与运行日志会提示需要恢复会话。普通运行日志在各账号目录中限量持久保存,服务重启后仍可查看;调试请求详情仅在当前进程中按原有上限缓存。页面展示旧角色数据时会标注缓存状态,不把页面刷新视作游戏连接成功。 +服务重启会保留配置与加密会话;未启用自动重登录时,需要手动恢复会话。普通运行日志在各账号目录中限量持久保存,服务重启后仍可查看;调试请求详情仅在当前进程中按原有上限缓存。页面展示旧角色数据时会标注缓存状态,不把页面刷新视作游戏连接成功。 + +### 掉线后自动重新登录 + +在“登录”页开启“掉线后自动重新登录”,设置等待时长,默认 **30 分钟**,修改后自动保存。该开关默认关闭,各账号独立配置。使用前请在游戏登录时勾选“记住账号和密码”,并成功进入目标区服;密码仍由服务端加密保存。 + +登录偏好保存在本账号中,进入其他区服或退出登录后仍保留设置;便携策略导入导出不携带、也不覆盖该登录偏好。 + +检测到掉线后,服务端按等待时长重新进行账号密码登录,回到原区服、原角色。登录页显示安排时间及执行结果,关闭浏览器不影响计时。临时网络故障的只读恢复检查继续运行,连接提前恢复后会取消重登录计划。重登录失败后按配置时长等待下一次尝试;缺少保存的密码或目标角色时会显示具体原因。 + +开启此功能且保留有效登录记录时,服务重启也会先等待所设时长,再尝试重登录。主动退出、清除登录记录或移除账号会取消自动计划。重登录成功恢复状态监控,策略执行保持停止;需要运行自动操作时,再点击顶部“开启”。 ## Linux Python 与环境变量 @@ -77,6 +87,8 @@ Web 检查固定官方 GitHub Releases 的稳定 `v2.x.y`,跳过桌面 1.x、 ## 离线验证 +自动重登录功能回归:后端及登录链路 **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 失败**。以下保留此前功能提交及开发阶段的验证记录。 前一功能提交的后台连接与日志修复: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` 可覆盖该功能回归。 diff --git a/ranch_web/app.py b/ranch_web/app.py index e017656..57b30c2 100644 --- a/ranch_web/app.py +++ b/ranch_web/app.py @@ -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")} result["error"] = public_error(result["error"]) 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") 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) diff --git a/ranch_web/policies.py b/ranch_web/policies.py index c1e1cc3..5a76036 100644 --- a/ranch_web/policies.py +++ b/ranch_web/policies.py @@ -36,7 +36,8 @@ def default_config(): # experimental battle simulator. Keep those defaults, not legacy widgets. value["policy"]["manual_eggs"] = True 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]} @@ -110,6 +111,8 @@ def validate_config(config): result = deepcopy(defaults) for key, cls in POLICY_CLASSES.items(): 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"] # read_policy() in the current desktop always enables per-species rules. # 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): + # 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["assistantVersion"] = __version__ return value diff --git a/ranch_web/scheduler.py b/ranch_web/scheduler.py index 0c0933b..944e8a6 100644 --- a/ranch_web/scheduler.py +++ b/ranch_web/scheduler.py @@ -13,8 +13,9 @@ FAST_KINDS = ("hatch", "gift", "explore", "breakthrough") class AccountSchedule: """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.wall_clock = wall_clock self.next_poll = math.inf self.next_fast = {kind: math.inf for kind in FAST_KINDS} self.monitoring = False @@ -22,6 +23,31 @@ class AccountSchedule: self.game_paused = False self.retry_deadline = None 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): self.game_paused = True @@ -37,6 +63,7 @@ class AccountSchedule: self.game_paused = False self.retry_deadline = None self.retry_attempt = 0 + self.clear_disconnection() def monitor(self, enabled=True): self.monitoring = bool(enabled) @@ -87,6 +114,9 @@ class AccountSchedule: def due(self, engine, config, running): now = self.clock() + deadline = self.auto_relogin_deadline(config) + if deadline is not None and now >= deadline: + return "auto_relogin" if self.game_paused: return "retry" if self.retry_deadline is not None and now >= self.retry_deadline else None diff --git a/ranch_web/service.py b/ranch_web/service.py index e0e83da..bc3878e 100644 --- a/ranch_web/service.py +++ b/ranch_web/service.py @@ -71,6 +71,10 @@ class RevisionConflict(ValueError): """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): normalized = str(field).lower().replace("_", "").replace("-", "") return normalized in SECRET_FIELDS or sensitive(field) @@ -186,6 +190,16 @@ class AccountWorker: self._last_game_error = None self._game_failure_sequence = 0 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.config, self.revision = self._load_config(self.state_root) self.trace = WebTrace(self) @@ -199,7 +213,12 @@ class AccountWorker: def _load_config(self, 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): 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, "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, - "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): 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) return 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) with self.lock: self.next_retry_at = None @@ -370,7 +443,7 @@ class AccountWorker: self._last_game_error_message = self.error self.log(self.connection_message) - def _game_succeeded(self): + def _game_succeeded(self, *, activated=False): previous = self.connection_state with self.lock: self.connection_state = "online" @@ -378,6 +451,12 @@ class AccountWorker: self.last_game_success_at = datetime.now(timezone.utc).isoformat(timespec="milliseconds") self.next_retry_at = None 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.engine.heartbeat_enabled = True if previous != "online": @@ -387,6 +466,7 @@ class AccountWorker: with self.lock: result = deepcopy(self._summary) result.update(running=self._running, busy=bool(self._active or self._pending)) + result["auto_relogin_status"] = self._auto_relogin_status() return result @property @@ -411,7 +491,7 @@ class AccountWorker: def check_intent(self, *, check_persistence=False): with self.lock: 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() if check_persistence and getattr(self, "_session_write_error", ""): raise OSError(self._session_write_error) @@ -523,6 +603,8 @@ class AccountWorker: final_status, final_error = "failed", self.error self.log(self.error) 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 # A terminal job means its counters and status are both # visible. Publish them atomically for HTTP polling. @@ -547,12 +629,17 @@ class AccountWorker: saved = self.securestore.active() if saved is not None and not self.demo: # 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.config, self.revision = self._load_config(self.state_root) self.active_identity = saved self.engine = self._engine() 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) if self.demo: self.result(*self.engine.poll()) @@ -610,9 +697,19 @@ class AccountWorker: raise RuntimeError("策略保存必须在账号队列中执行") if revision is not None and revision != self.revision: 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 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) with self.lock: self.config, self.revision = value, new_revision @@ -678,11 +775,28 @@ class AccountWorker: return active 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) if kind is 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 try: if kind == "retry": @@ -735,6 +849,100 @@ class AccountWorker: self.schedule.poll_finished(self.config) 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) + client = None # The worker now owns this client. + self.log("自动重登成功,已恢复原区服和原角色的监控;策略保持停止") + 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): if not isinstance(client.session, Session): raise ValueError("登录客户端未提供受支持的会话") @@ -873,9 +1081,10 @@ class AccountWorker: self.config, self.revision = value, revision self.engine, self.active_identity, self.demo = engine, identity, False self._running = False - self.schedule.monitor(True) - self.schedule.poll_finished(self.config) - self._invalidate_views(clear=True) + self.schedule.monitor(True) + self.schedule.poll_finished(self.config) + self._game_succeeded(activated=True) + self._invalidate_views(clear=True) except Exception: with self.lock: self.engine, self.active_identity, self.demo = old_engine, previous_identity, old_demo @@ -895,7 +1104,6 @@ class AccountWorker: self.manager._release_identity(self, previous_identity) if old_client is not None and old_client is not client: old_client.close() - self._game_succeeded() return {"connected": True, "running": False, "has_saved_password": self._has_saved_password} def _login(self, payload): @@ -920,7 +1128,7 @@ class AccountWorker: self.schedule.monitor(False) self.securestore.save_credentials(account, password, remember) 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) try: self.check_intent() @@ -1054,8 +1262,9 @@ class AccountWorker: return {"running": False} def close(self, timeout=30): - self.stop() with self.condition: + self.suspend_auto_relogin() + self.stop() self._closing = True for job in self._pending: job.status, job.error, job.payload = "cancelled", "账号正在关闭,操作已取消", {} @@ -1174,10 +1383,13 @@ class WebManager: if revision is not None and revision != worker.revision: raise RevisionConflict("策略已在其他页面更新,请刷新后重试") 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: worker.stop(keep_running=True) 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, "pending": True, "job_id": job["id"], "job": job} @@ -1198,6 +1410,8 @@ class WebManager: worker._jobs[job.id] = job return job.public() 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() 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) diff --git a/ranch_web/static/app.js b/ranch_web/static/app.js index baec106..d8bd188 100644 --- a/ranch_web/static/app.js +++ b/ranch_web/static/app.js @@ -57,6 +57,7 @@ function transportError(account,key,label,failure) { function connectionError(account) { return Object.assign(new Error(connectionDetails(account) || '请等待游戏连接恢复后再操作。'),{connection:true}); } function renderPageConnection(page) { + page.login?.updateStatus(); if(!page.connectionStatus){ page.connectionStatus=el('p',{class:'page-summary','data-connection-status':'',hidden:true}); page.header.after(page.connectionStatus); diff --git a/ranch_web/static/pages.js b/ranch_web/static/pages.js index 0888235..5a5be5d 100644 --- a/ranch_web/static/pages.js +++ b/ranch_web/static/pages.js @@ -15,6 +15,11 @@ class LoginPage { constructor(host, page) { this.page = page; 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.password = el('input', {type: 'password', name: 'game-password', autocomplete: 'current-password', 'aria-label': '游戏密码'}); this.remember = el('input', {type: 'checkbox', checked: true}); @@ -48,17 +53,36 @@ class LoginPage { 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('p', {class: 'info-note', text: '记住的账号密码和登录会话由服务端加密保存。浏览器不会保存游戏凭据。退出或恢复会话后,策略保持关闭。'})); - host.append(this.root); + host.append(this.autoReloginStatus, this.root); } update(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.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.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.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) { diff --git a/ranch_web/tests/browser/test_auto_relogin_browser.py b/ranch_web/tests/browser/test_auto_relogin_browser.py new file mode 100644 index 0000000..b156926 --- /dev/null +++ b/ranch_web/tests/browser/test_auto_relogin_browser.py @@ -0,0 +1,325 @@ +"""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 +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.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)) + 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 never initiate game login or start strategies") + 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 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_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 = '重新登录失败:密码错误 ' + self.set_status(self.first, "failed", reason) + expect(status).to_contain_text(reason) + expect(status.locator("img")).to_have_count(0) + self.set_status(self.first, "monitoring", "重登成功,已恢复监控,策略保持停止") + self.summaries[self.first].update(connected=True, connection_state="online", connection_message="游戏连接正常", running=False) + expect(status).to_contain_text("已恢复监控,策略保持停止") + expect(self.page.locator("#strategy-toggle")).to_have_text("开启") + 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("服务重启") + 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("秒后自动重新登录") + 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() diff --git a/ranch_web/tests/test_api.py b/ranch_web/tests/test_api.py index ff6262a..ce82dce 100644 --- a/ranch_web/tests/test_api.py +++ b/ranch_web/tests/test_api.py @@ -188,7 +188,9 @@ class ApiTests(unittest.TestCase): def test_connection_metadata_survives_summary_dto(self): 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) for url in (self.url + "/status", "/api/accounts"): response = self.client.get(url) @@ -196,6 +198,16 @@ class ApiTests(unittest.TestCase): summary = response.json()[0] if url == "/api/accounts" else response.json() 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): response = self.client.post(self.url + "/actions/login", json={"account": "fake-account", "password": "GAME_PASSWORD", "remember": True}) self.assertEqual(response.status_code, 202) diff --git a/ranch_web/tests/test_auto_relogin.py b/ranch_web/tests/test_auto_relogin.py new file mode 100644 index 0000000..85cdbea --- /dev/null +++ b/ranch_web/tests/test_auto_relogin.py @@ -0,0 +1,383 @@ +"""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 + + 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() + 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 + self.tick(identifier, worker) + 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.assertFalse(self.manager.status(identifier)["running"]) + 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(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() + 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) + + 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() diff --git a/ranch_web/views.py b/ranch_web/views.py index b34a255..9c05c82 100644 --- a/ranch_web/views.py +++ b/ranch_web/views.py @@ -91,7 +91,11 @@ def _strategy_fields(catalog): "exploration": [_field(["explore_policy", "enabled"], "自动安排再次探险(完成后自动领奖)"), _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)]))], - "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): @@ -118,6 +122,8 @@ def build_view(engine, page, config, query=None): if page not in dict(PAGES): raise ValueError("未知页面") config = validate_config(config) + if page == "login": + config.setdefault("auto_relogin", {"enabled": False, "delay_minutes": 30}) fields = _strategy_fields(engine.catalog)[page] dto = {"page": page, "title": dict(PAGES)[page], "columns": [], "rows": [], "summary": "", "form": [field | {"value": _value(config, field["path"])} for field in fields],