diff --git a/README.md b/README.md index ba0bbfc..0c934d4 100644 --- a/README.md +++ b/README.md @@ -21,10 +21,11 @@ - Windows:Python 3.12+,安装 `ranch_web/requirements.txt` 后运行 `Start_Ranch_Web.cmd`,访问 `http://127.0.0.1:8765`。 - Web 使用原生 HTML/CSS/ES 模块与 FastAPI,无需 Node/npm 或 PySide6;数据独立保存在 `local_state/ranch_web`。 - Linux:提供单服务 Docker、`/data` 持久化及宿主机受控更新;只接官方稳定 `v2.x.y`,默认只通知,未配置执行器时仅检查。 +- 配置管理密码后,先进入独立 `/login` 页面,登录后才能打开工作台;退出管理登录或会话失效后返回登录页。 -本地虚拟环境、离线演示与环境配置见 [Web 开发运行说明](ranch_web/README.md);Linux 单服务 Docker、`/data` 持久化、GHCR 镜像与宿主机备份/回滚更新见 [Web 部署更新入口](deploy/web/README.md)。更新仅接受官方稳定 `v2.x.y`,没有 Web 2 正式版时不会安装旧桌面版;Windows 未配置执行器时仅检查更新。本轮不代表真实游戏 API 或 Linux Docker 实机验收通过。 +本地虚拟环境、离线演示与环境配置见 [Web 开发运行说明](ranch_web/README.md);Linux 单服务 Docker、`/data` 持久化、GHCR 镜像与宿主机备份/回滚更新见 [Web 部署更新入口](deploy/web/README.md)。更新仅接受官方稳定 `v2.x.y`,没有 Web 2 正式版时不会安装旧桌面版;Windows 未配置执行器时仅检查更新。Linux Docker 部署烟测已通过,真实游戏 API 与生产升级/回滚仍待验收。 -最终离线后端验证 **185项:184通过、1跳过(Windows符号链接权限),0失败/错误**;浏览器 **13项通过,JS/CSP错误为0**,另以新 Edge 进程验证15页及主线/孵蛋子页。完整非浏览器测试命令见 [Web 验证说明](ranch_web/README.md#离线验证)。这些结果不代表真实游戏服务器或 Linux Docker 验收通过。 +完整离线后端验证 **193项:192通过、1跳过(Windows符号链接权限),0失败/错误**;浏览器 **21项全部通过,JS/CSP错误为0**。完整测试命令见 [Web 验证说明](ranch_web/README.md#离线验证)。独立管理登录页补丁的线上重新部署验收待完成,真实游戏 API 尚未验收。 ## 当前功能 diff --git a/ranch_web/README.md b/ranch_web/README.md index 30df5b0..296ddf3 100644 --- a/ranch_web/README.md +++ b/ranch_web/README.md @@ -9,7 +9,7 @@ Web 采用 FastAPI / Uvicorn 和原生 HTML/CSS/ES 模块,无 Node、npm 或 - [x] 原15页:登录、培育室、背包、牧场、每日事务、自动孵蛋、自动主线、战斗记录、自动赠礼、自动委托、自动探险、自动扫荡、数据分析、执行计划、收益资料。 - [x] 保留账号页签、顶部数值与统一启停、可调日志;规则自动保存,配置与统计按账号/角色隔离,重启、恢复会话及导入策略后保持停止。 - [x] Windows Python 启动与离线演示;Web 导入链和依赖不使用 Qt,无 Node 构建步骤。 -- [x] 提供 Linux Docker 与稳定 2.x 受控更新、停机备份及失败回滚脚本;Linux Docker 尚未实机验收。 +- [x] 提供 Linux Docker 与稳定 2.x 受控更新、停机备份及失败回滚脚本;已完成 Linux Docker 部署、持久化权限、健康检查和定时更新检查烟测。 - [x] 开发版本为 `2.0.0.dev1`,保留桌面兼容,不等同正式发布或真实游戏 API 验收。 ## Windows 本地开发 @@ -54,24 +54,28 @@ sh start-web.sh --no-browser 账号密钥、加密凭据、会话、配置和统计保留在服务端数据目录,不写入浏览器 localStorage。管理登录使用 HttpOnly / SameSite cookie,写请求校验 Origin。不要启动多个 Uvicorn worker 或多个服务实例共享同一数据根。 +配置管理密码后,未登录访问 `/`、工作台 HTML 或脚本会由服务端转到独立 `/login` 页面;登录前不加载工作台。管理 cookie 使用 `Path=/`,登录和退出均清理旧版 `Path=/api` cookie;退出管理登录或会话失效后,页面隐藏工作台并返回登录页。登录页和工作台 HTML 使用 `Cache-Control: no-store`,本机未配置密码时仍保留 loopback 免密模式。 + ## Docker 与在线更新 完整步骤见 [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 尚未验收。 + Web 检查固定官方 GitHub Releases 的稳定 `v2.x.y`,跳过桌面 1.x、未来 3.x、草稿和预发布。开发版本 `2.0.0.dev1` 可升级至同数字的正式 `v2.0.0`;没有正式 Web 2 发布时明确显示暂无更新。Windows 默认仅检查;Web “更新”按钮仅在宿主机显式启用并有有效只读心跳时可提交 `pending` 请求,安装、备份和回滚由宿主机执行。默认定时检查只通知,自动安装需操作者 opt-in。 ## 离线验证 -最终非浏览器后端验证 **185项:184通过、1跳过(Windows符号链接权限),0失败/错误**。以下完整命令显式列出后端模块,避免发现并混入浏览器测试: +独立管理登录页调整后的完整非浏览器后端验证为 **193项:192通过、1跳过(Windows符号链接权限),0失败/错误,用时26.994秒**。以下命令显式列出全部10个后端模块,避免发现并混入浏览器测试: ```console python -B -m unittest ranch_web.tests.test_api ranch_web.tests.test_auth ranch_web.tests.test_scheduler ranch_web.tests.test_service ranch_web.tests.test_store ranch_web.tests.test_updates ranch_web.tests.test_web_integration ranch_web.tests.test_web_policies ranch_web.tests.test_web_updater ranch_web.tests.test_web_views_actions -v ``` -浏览器 **13项通过,JS/CSP错误为0**;另在新 Edge 进程验证15页、主线策略与孵蛋子页切换、未配置执行器时禁用更新按钮。浏览器测试需要 Python Playwright 和可用的 Edge,属于验证依赖: +独立管理登录页调整后的浏览器验证为 **21项全部通过(13项原有工作台、7项密码保护登录、1项本机免密),JS/CSP错误为0**,覆盖独立登录页、工作台访问门禁、退出、会话失效和原有功能。浏览器测试需要 Python Playwright 和可用的 Edge,属于验证依赖: ```console -python -B -m unittest ranch_web.tests.browser.test_workbench_browser -v +python -B -m unittest ranch_web.tests.browser.test_workbench_browser ranch_web.tests.browser.test_admin_login_browser -v ``` -全部验证使用临时目录、fake transport / GitHub / Docker 或内置离线演示,不读取私有账户,不访问真实游戏 API。停止取消、配置并发保存、视图索引清理、子页字段保留和并发认证限流的已报问题均已修复并复核。当前 Windows 无 Docker;上述结果不代表 Linux Docker、生产更新器或真实游戏服务器实机验收通过。 +上述离线验证使用临时目录、fake transport / GitHub / Docker 或内置离线演示,不读取私有账户,不访问真实游戏 API。停止取消、配置并发保存、视图索引清理、子页字段保留和并发认证限流的已报问题均已修复并复核。Linux Docker 部署烟测见上文;离线测试及部署烟测均不等同于真实游戏 API 或生产升级/回滚验收。 diff --git a/ranch_web/app.py b/ranch_web/app.py index b46b2a1..fd8fc6d 100644 --- a/ranch_web/app.py +++ b/ranch_web/app.py @@ -22,7 +22,7 @@ from fastapi.exceptions import RequestValidationError from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr from starlette.concurrency import run_in_threadpool from starlette.exceptions import HTTPException as StarletteHTTPException -from starlette.responses import FileResponse, JSONResponse, Response +from starlette.responses import FileResponse, JSONResponse, RedirectResponse, Response from starlette.staticfiles import StaticFiles from . import GAME_VERSION, __version__ @@ -33,6 +33,7 @@ PAGES = tuple("login incubator bag ranch daily hatching mainline battles gifts c ACTIONS = frozenset("refresh refresh_maps refresh_tasks claim_daily lock unlock sell feed quote_expansion expand export_config import_config import_yields reset_map_pending login enter_server restore_session logout forget_login start stop".split()) Identifier = Annotated[str, Path(pattern=r"^[A-Za-z0-9_-]{1,80}$")] _PUBLIC_PATHS = frozenset({"/api/health", "/api/meta", "/api/auth/status", "/api/auth/login", "/api/auth/logout"}) +_PUBLIC_ASSETS = frozenset({"login.html", "login.js", "login.css", "styles.css", "dom.js"}) _WRITES = frozenset({"POST", "PUT", "PATCH", "DELETE"}) _JOB_STATUSES = frozenset({"queued", "running", "succeeded", "failed", "cancelled"}) _PRIVATE_KEYS = frozenset({"key", "reqid", "reqsid", "requestid", "password", "passwordhash", "passwd", "pwd", "userpwd", "newpass", "secret", "credentials", "protected", "authorization", "cookie", "setcookie", "raw", "snapshot", "rawsnapshot", "profileroot", "stateroot", "dataroot", "datadir", "filepath", "budgetpath", "private", "headers", "body", "request", "response"}) @@ -340,12 +341,26 @@ def _no_file_paths(value: Any, depth: int = 0) -> None: class _Assets(StaticFiles): + def __init__(self, *, sessions: _Sessions, **kwargs): + super().__init__(**kwargs) + self.sessions = sessions + async def get_response(self, path, scope): allowed = {".html", ".js", ".mjs", ".css", ".svg", ".png", ".jpg", ".jpeg", ".webp", ".ico", ".woff", ".woff2"} parts = path.replace("\\", "/").split("/") if any(part.startswith(".") for part in parts) or FilePath(path).suffix.lower() not in allowed: raise HTTPException(404, "静态资源不存在") - return await super().get_response(path, scope) + if scope["method"] not in {"GET", "HEAD"}: + raise HTTPException(405) + authenticated = self.sessions.authenticated(Request(scope)) + if path == "login.html" and authenticated: + return RedirectResponse("/", status_code=303, headers={"Cache-Control": "no-store"}) + if path not in _PUBLIC_ASSETS and not authenticated: + return RedirectResponse("/login", status_code=303, headers={"Cache-Control": "no-store"}) + response = await super().get_response(path, scope) + if path not in _PUBLIC_ASSETS or path == "login.html": + response.headers["Cache-Control"] = "no-store" + return response def create_app(data_dir=None, manager=None, config=None, updates=None) -> FastAPI: @@ -540,17 +555,21 @@ def create_app(data_dir=None, manager=None, config=None, updates=None) -> FastAP if not settings.credential: if not sessions.authenticated(request): raise HTTPException(403, "本机免密模式只允许本机访问") - return {"required": False, "authenticated": True, "access_mode": "local"} - token = sessions.login(request, body.password) - response = JSONResponse({"required": True, "authenticated": True, "access_mode": "password"}) - response.set_cookie(COOKIE_NAME, token, max_age=settings.session_ttl, httponly=True, - secure=settings.secure_cookie, samesite="strict", path="/api") + response = JSONResponse({"required": False, "authenticated": True, "access_mode": "local"}) + else: + token = sessions.login(request, body.password) + response = JSONResponse({"required": True, "authenticated": True, "access_mode": "password"}) + response.set_cookie(COOKIE_NAME, token, max_age=settings.session_ttl, httponly=True, + secure=settings.secure_cookie, samesite="strict", path="/") + # Remove the narrower cookie left by older versions before it can shadow the new session. + response.delete_cookie(COOKIE_NAME, path="/api", httponly=True, secure=settings.secure_cookie, samesite="strict") return response @app.post("/api/auth/logout") def admin_logout(request: Request): sessions.logout(request) response = JSONResponse({"authenticated": False}) + response.delete_cookie(COOKIE_NAME, path="/", httponly=True, secure=settings.secure_cookie, samesite="strict") response.delete_cookie(COOKIE_NAME, path="/api", httponly=True, secure=settings.secure_cookie, samesite="strict") return response @@ -659,11 +678,22 @@ def create_app(data_dir=None, manager=None, config=None, updates=None) -> FastAP static_dir = FilePath(__file__).resolve().parent / "static" @app.get("/", include_in_schema=False) - def index(): + def index(request: Request): + if not sessions.authenticated(request): + return RedirectResponse("/login", status_code=303, headers={"Cache-Control": "no-store"}) index_path = static_dir / "index.html" if not index_path.is_file(): raise HTTPException(503, "前端资源尚未准备完成") - return FileResponse(index_path, media_type="text/html", headers={"Cache-Control": "no-cache"}) + return FileResponse(index_path, media_type="text/html", headers={"Cache-Control": "no-store"}) - app.mount("/static", _Assets(directory=static_dir, check_dir=False, follow_symlink=False), name="static") + @app.get("/login", include_in_schema=False) + def login_page(request: Request): + if sessions.authenticated(request): + return RedirectResponse("/", status_code=303, headers={"Cache-Control": "no-store"}) + login_path = static_dir / "login.html" + if not login_path.is_file(): + raise HTTPException(503, "前端资源尚未准备完成") + return FileResponse(login_path, media_type="text/html", headers={"Cache-Control": "no-store"}) + + app.mount("/static", _Assets(directory=static_dir, sessions=sessions, check_dir=False, follow_symlink=False), name="static") return app diff --git a/ranch_web/static/app.js b/ranch_web/static/app.js index da2e8d1..f7f8407 100644 --- a/ranch_web/static/app.js +++ b/ranch_web/static/app.js @@ -3,7 +3,7 @@ import {el, $, $$, clone, getPath, setPath, pathKey, textValue, number, chinaTim import {PageView, PAGES} from './pages.js'; import {notice, dialog, confirm, filePicker, fileBase64} from './ui.js'; -const state = {accounts:new Map(),active:null,schema:null,meta:null,ready:false,polling:false,seq:0}; +const state = {accounts:new Map(),active:null,schema:null,meta:null,ready:false,polling:false,seq:0,redirecting:false}; const current = () => state.accounts.get(state.active); const currentPage = () => { const account=current(); return account?.pages.get(account.page); }; const terminal = new Set(['succeeded','failed','cancelled']); @@ -16,7 +16,7 @@ function makeAccount(summary) { } function setStatus(message) { $('#status-text').textContent=message; $('#status-text').title=message; } -function error(error) { notice(error.message || String(error),true); setStatus(error.message || String(error)); } +function error(error) { if(state.redirecting)return;notice(error.message || String(error),true); setStatus(error.message || String(error)); } function renderAccountTabs() { const root=$('#account-tabs'); @@ -304,7 +304,7 @@ async function command(name,account=current()) { 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.dev1'}`}),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==='admin-logout'){await api.logout();state.ready=false;location.reload();return;} + if(name==='admin-logout'){hideWorkbench();try{await api.logout();}finally{requireAuth();}return;} if(!account)throw new Error('请先新增或选择账号。'); if(name==='debug'){account.logs.debug=!account.logs.debug;account.logs.entries=[];account.logs.next=0;account.logs.generation=(account.logs.generation || 0)+1;$('#debug-log').checked=account.logs.debug;setLogVisible(true);renderLogs(true);await fetchLogs(account);return;} if(name==='save'){await flushConfig(account);notice('策略已保存。');return;} @@ -464,21 +464,33 @@ async function tick() { if(!state.ready||state.polling)return;state.polling=true; try{ const account=current();await Promise.allSettled([syncAccounts(),...([...state.accounts.values()].flatMap(item=>[...item.jobs.values()].map(job=>pollJob(item,job))))]); - if(account&&state.accounts.has(account.id)){fetchLogs(account);const page=account.pages.get(account.page);if(page&&Date.now()-(page.lastLoad||0)>4000)loadPage(page);} + if(state.ready&&account&&state.accounts.has(account.id)){fetchLogs(account);const page=account.pages.get(account.page);if(page&&Date.now()-(page.lastLoad||0)>4000)loadPage(page);} }finally{state.polling=false;} } -async function requireAuth() { - state.ready=false;const root=$('#auth-dialog');if(!root.open)root.showModal();$('#admin-password').focus(); +function hideWorkbench() { + state.ready=false; + $('#app').hidden=true;$('#notice').hidden=true; + $$('dialog[open]').forEach(root=>root.close()); + $$('.context-menu').forEach(root=>root.remove()); + $$('input[type="password"]').forEach(input=>input.value=''); + state.accounts.forEach(account=>{clearTimeout(account.saveTimer);account.pages.forEach(page=>clearTimeout(page.loadTimer));}); +} + +function requireAuth() { + if(state.redirecting)return; + state.redirecting=true;hideWorkbench();location.replace('/login'); } async function bootstrap() { try{ - const auth=await api.auth();if(auth.required&&!auth.authenticated){requireAuth();return;} + const auth=await api.auth();if(state.redirecting)return;if(auth.required&&!auth.authenticated){requireAuth();return;} + $('#app').hidden=false; const [meta,schema]=await Promise.all([api.meta(),api.schema()]);state.meta=meta;state.schema=schema; + if(state.redirecting)return; $('#app-version').textContent=meta.version || '2.0.0.dev1';$('#game-version').textContent=meta.gameVersion || '1.9.68';$('#access-mode').textContent=auth.access_mode==='local'||auth.access_mode==='loopback'?'本机工作台':auth.required?'管理工作台':'本机工作台'; - await syncAccounts();state.ready=true;setStatus('工作台已连接'); - }catch(failure){setStatus(failure.message);$('#page-host').replaceChildren(el('div',{class:'initial-state'},el('p',{text:failure.message}),el('button',{text:'重新连接',onClick:bootstrap})));} + 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})));} } PAGES.forEach(([key,label])=>$('#page-tabs').append(el('button',{type:'button',class:'page-tab',role:'tab','data-page':key,'aria-selected':String(key==='login'),tabindex:key==='login'?0:-1,text:label,onClick:()=>selectPage(key)}))); @@ -503,9 +515,10 @@ $('#log-resizer').addEventListener('pointerdown',event=>{resize={y:event.clientY $('#log-resizer').addEventListener('pointermove',event=>{if(resize)setLogHeight(resize.height+resize.y-event.clientY);}); $('#log-resizer').addEventListener('pointerup',()=>{if(!resize)return;resize=null;const account=current();if(account?.config)editConfig(account,['log_sizes'],[$('#workspace').clientHeight,Number($('#log-resizer').getAttribute('aria-valuenow'))]);}); $('#log-resizer').addEventListener('keydown',event=>{if(!['ArrowUp','ArrowDown','Home','End'].includes(event.key))return;event.preventDefault();const height=Number(event.currentTarget.getAttribute('aria-valuenow'));const next=setLogHeight(event.key==='Home'?64:event.key==='End'?480:height+(event.key==='ArrowUp'?16:-16));if(current()?.config)editConfig(current(),['log_sizes'],[$('#workspace').clientHeight,next]);}); -$('#auth-form').addEventListener('submit',async event=>{event.preventDefault();const input=$('#admin-password');const password=input.value;input.value='';const button=$('button',event.currentTarget);button.disabled=true;try{await api.login(password);$('#auth-dialog').close();$('#auth-error').hidden=true;await bootstrap();}catch(failure){$('#auth-error').textContent=failure.message;$('#auth-error').hidden=false;input.focus();}finally{button.disabled=false;}}); -$('#auth-dialog').addEventListener('cancel',event=>event.preventDefault());window.addEventListener('auth-required',requireAuth); -window.addEventListener('beforeunload',event=>{if([...state.accounts.values()].some(account=>account.edits.size||account.savePromise)){event.preventDefault();event.returnValue='';}}); +window.addEventListener('auth-required',requireAuth); +window.addEventListener('pagehide',hideWorkbench); +window.addEventListener('pageshow',event=>{if(event.persisted){state.redirecting=false;bootstrap();}}); +window.addEventListener('beforeunload',event=>{if(!state.redirecting&&[...state.accounts.values()].some(account=>account.edits.size||account.savePromise)){event.preventDefault();event.returnValue='';}}); setInterval(()=>{$('#clock').textContent=new Date().toLocaleTimeString('zh-CN',{hour12:false});},1000); setInterval(tick,1000); bootstrap(); diff --git a/ranch_web/static/index.html b/ranch_web/static/index.html index a7d5195..ef14762 100644 --- a/ranch_web/static/index.html +++ b/ranch_web/static/index.html @@ -10,7 +10,7 @@
-