feat: require standalone admin login before the web workbench

This commit is contained in:
AttilaNet
2026-11-10 19:03:22 +08:00
parent 664db51d3b
commit 0230a933b0
12 changed files with 710 additions and 41 deletions
+3 -2
View File
@@ -21,10 +21,11 @@
- Windows:Python 3.12+,安装 `ranch_web/requirements.txt` 后运行 `Start_Ranch_Web.cmd`,访问 `http://127.0.0.1:8765`。 - 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`。 - Web 使用原生 HTML/CSS/ES 模块与 FastAPI,无需 Node/npm 或 PySide6;数据独立保存在 `local_state/ranch_web`。
- Linux:提供单服务 Docker、`/data` 持久化及宿主机受控更新;只接官方稳定 `v2.x.y`,默认只通知,未配置执行器时仅检查。 - 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 尚未验收。
## 当前功能 ## 当前功能
+9 -5
View File
@@ -9,7 +9,7 @@ Web 采用 FastAPI / Uvicorn 和原生 HTML/CSS/ES 模块,无 Node、npm 或
- [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.dev1`,保留桌面兼容,不等同正式发布或真实游戏 API 验收。 - [x] 开发版本为 `2.0.0.dev1`,保留桌面兼容,不等同正式发布或真实游戏 API 验收。
## Windows 本地开发 ## Windows 本地开发
@@ -54,24 +54,28 @@ sh start-web.sh --no-browser
账号密钥、加密凭据、会话、配置和统计保留在服务端数据目录,不写入浏览器 localStorage。管理登录使用 HttpOnly / SameSite cookie,写请求校验 Origin。不要启动多个 Uvicorn worker 或多个服务实例共享同一数据根。 账号密钥、加密凭据、会话、配置和统计保留在服务端数据目录,不写入浏览器 localStorage。管理登录使用 HttpOnly / SameSite cookie,写请求校验 Origin。不要启动多个 Uvicorn worker 或多个服务实例共享同一数据根。
配置管理密码后,未登录访问 `/`、工作台 HTML 或脚本会由服务端转到独立 `/login` 页面;登录前不加载工作台。管理 cookie 使用 `Path=/`,登录和退出均清理旧版 `Path=/api` cookie;退出管理登录或会话失效后,页面隐藏工作台并返回登录页。登录页和工作台 HTML 使用 `Cache-Control: no-store`,本机未配置密码时仍保留 loopback 免密模式。
## 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 尚未验收。
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。
## 离线验证 ## 离线验证
最终非浏览器后端验证 **185项:184通过、1跳过(Windows符号链接权限),0失败/错误**。以下完整命令显式列出后端模块,避免发现并混入浏览器测试: 独立管理登录页调整后的完整非浏览器后端验证为 **193项:192通过、1跳过(Windows符号链接权限),0失败/错误,用时26.994秒**。以下命令显式列出全部10个后端模块,避免发现并混入浏览器测试:
```console ```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 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 ```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 或生产升级/回滚验收。
+37 -7
View File
@@ -22,7 +22,7 @@ from fastapi.exceptions import RequestValidationError
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr
from starlette.concurrency import run_in_threadpool from starlette.concurrency import run_in_threadpool
from starlette.exceptions import HTTPException as StarletteHTTPException 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 starlette.staticfiles import StaticFiles
from . import GAME_VERSION, __version__ 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()) 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}$")] 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_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"}) _WRITES = frozenset({"POST", "PUT", "PATCH", "DELETE"})
_JOB_STATUSES = frozenset({"queued", "running", "succeeded", "failed", "cancelled"}) _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"}) _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): class _Assets(StaticFiles):
def __init__(self, *, sessions: _Sessions, **kwargs):
super().__init__(**kwargs)
self.sessions = sessions
async def get_response(self, path, scope): async def get_response(self, path, scope):
allowed = {".html", ".js", ".mjs", ".css", ".svg", ".png", ".jpg", ".jpeg", ".webp", ".ico", ".woff", ".woff2"} allowed = {".html", ".js", ".mjs", ".css", ".svg", ".png", ".jpg", ".jpeg", ".webp", ".ico", ".woff", ".woff2"}
parts = path.replace("\\", "/").split("/") parts = path.replace("\\", "/").split("/")
if any(part.startswith(".") for part in parts) or FilePath(path).suffix.lower() not in allowed: if any(part.startswith(".") for part in parts) or FilePath(path).suffix.lower() not in allowed:
raise HTTPException(404, "静态资源不存在") 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: 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 settings.credential:
if not sessions.authenticated(request): if not sessions.authenticated(request):
raise HTTPException(403, "本机免密模式只允许本机访问") raise HTTPException(403, "本机免密模式只允许本机访问")
return {"required": False, "authenticated": True, "access_mode": "local"} response = JSONResponse({"required": False, "authenticated": True, "access_mode": "local"})
else:
token = sessions.login(request, body.password) token = sessions.login(request, body.password)
response = JSONResponse({"required": True, "authenticated": True, "access_mode": "password"}) response = JSONResponse({"required": True, "authenticated": True, "access_mode": "password"})
response.set_cookie(COOKIE_NAME, token, max_age=settings.session_ttl, httponly=True, response.set_cookie(COOKIE_NAME, token, max_age=settings.session_ttl, httponly=True,
secure=settings.secure_cookie, samesite="strict", path="/api") 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 return response
@app.post("/api/auth/logout") @app.post("/api/auth/logout")
def admin_logout(request: Request): def admin_logout(request: Request):
sessions.logout(request) sessions.logout(request)
response = JSONResponse({"authenticated": False}) 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") response.delete_cookie(COOKIE_NAME, path="/api", httponly=True, secure=settings.secure_cookie, samesite="strict")
return response 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" static_dir = FilePath(__file__).resolve().parent / "static"
@app.get("/", include_in_schema=False) @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" index_path = static_dir / "index.html"
if not index_path.is_file(): if not index_path.is_file():
raise HTTPException(503, "前端资源尚未准备完成") 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 return app
+25 -12
View File
@@ -3,7 +3,7 @@ import {el, $, $$, clone, getPath, setPath, pathKey, textValue, number, chinaTim
import {PageView, PAGES} from './pages.js'; import {PageView, PAGES} from './pages.js';
import {notice, dialog, confirm, filePicker, fileBase64} from './ui.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 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']);
@@ -16,7 +16,7 @@ function makeAccount(summary) {
} }
function setStatus(message) { $('#status-text').textContent=message; $('#status-text').title=message; } 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() { function renderAccountTabs() {
const root=$('#account-tabs'); 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==='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==='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==='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(!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==='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;} if(name==='save'){await flushConfig(account);notice('策略已保存。');return;}
@@ -464,21 +464,33 @@ async function tick() {
if(!state.ready||state.polling)return;state.polling=true; if(!state.ready||state.polling)return;state.polling=true;
try{ try{
const account=current();await Promise.allSettled([syncAccounts(),...([...state.accounts.values()].flatMap(item=>[...item.jobs.values()].map(job=>pollJob(item,job))))]); 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;} }finally{state.polling=false;}
} }
async function requireAuth() { function hideWorkbench() {
state.ready=false;const root=$('#auth-dialog');if(!root.open)root.showModal();$('#admin-password').focus(); 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() { async function bootstrap() {
try{ 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; 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?'管理工作台':'本机工作台'; $('#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('工作台已连接'); await syncAccounts();if(state.redirecting)return;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})));} }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)}))); 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('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('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]);}); $('#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;}}); window.addEventListener('auth-required',requireAuth);
$('#auth-dialog').addEventListener('cancel',event=>event.preventDefault());window.addEventListener('auth-required',requireAuth); window.addEventListener('pagehide',hideWorkbench);
window.addEventListener('beforeunload',event=>{if([...state.accounts.values()].some(account=>account.edits.size||account.savePromise)){event.preventDefault();event.returnValue='';}}); 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(()=>{$('#clock').textContent=new Date().toLocaleTimeString('zh-CN',{hour12:false});},1000);
setInterval(tick,1000); setInterval(tick,1000);
bootstrap(); bootstrap();
+1 -2
View File
@@ -10,7 +10,7 @@
<script type="module" src="/static/app.js"></script> <script type="module" src="/static/app.js"></script>
</head> </head>
<body> <body>
<div id="app" class="workbench" aria-label="牧羊人之心牧场助手"> <div id="app" class="workbench" aria-label="牧羊人之心牧场助手" hidden>
<header class="window-header"> <header class="window-header">
<nav id="menu-bar" class="menu-bar" aria-label="主菜单"> <nav id="menu-bar" class="menu-bar" aria-label="主菜单">
<details class="menu"><summary accesskey="a">账号<span class="access-key">(A)</span></summary><div class="menu-popup"> <details class="menu"><summary accesskey="a">账号<span class="access-key">(A)</span></summary><div class="menu-popup">
@@ -44,7 +44,6 @@
</div> </div>
<div id="notice" class="notice" role="status" hidden></div> <div id="notice" class="notice" role="status" hidden></div>
<dialog id="action-dialog" aria-labelledby="dialog-title"><form id="dialog-form"><header class="dialog-header"><h1 id="dialog-title"></h1><button type="button" class="dialog-close" aria-label="关闭对话框">×</button></header><div id="dialog-content" class="dialog-content"></div><p id="dialog-error" class="error-text" role="alert" hidden></p><footer class="dialog-footer"><button type="button" id="dialog-cancel">取消</button><button type="submit" id="dialog-confirm" class="primary">确认</button></footer></form></dialog> <dialog id="action-dialog" aria-labelledby="dialog-title"><form id="dialog-form"><header class="dialog-header"><h1 id="dialog-title"></h1><button type="button" class="dialog-close" aria-label="关闭对话框">×</button></header><div id="dialog-content" class="dialog-content"></div><p id="dialog-error" class="error-text" role="alert" hidden></p><footer class="dialog-footer"><button type="button" id="dialog-cancel">取消</button><button type="submit" id="dialog-confirm" class="primary">确认</button></footer></form></dialog>
<dialog id="auth-dialog" aria-labelledby="auth-title"><form id="auth-form"><h1 id="auth-title">登录管理工作台</h1><p>请输入此 Web 工作台的管理密码。</p><label class="field">管理密码<input id="admin-password" type="password" autocomplete="current-password" required></label><p id="auth-error" class="error-text" role="alert" hidden></p><div class="dialog-footer"><button type="submit" class="primary">登录</button></div></form></dialog>
<noscript>此工作台需要启用 JavaScript 才能连接本地服务。</noscript> <noscript>此工作台需要启用 JavaScript 才能连接本地服务。</noscript>
</body> </body>
</html> </html>
+26
View File
@@ -0,0 +1,26 @@
:root {
font-family: "Segoe UI", "Microsoft YaHei UI", "Microsoft YaHei", system-ui, sans-serif;
font-size: 13px;
color: #202832;
background: #f1f3f5;
font-synthesis: none;
color-scheme: light;
}
* { box-sizing: border-box; }
[hidden] { display: none !important; }
body { margin: 0; min-height: 100dvh; display: grid; place-items: center; padding: 24px 16px; }
.admin-login { width: 100%; max-width: 370px; padding: 24px; background: #fff; border: 1px solid #cbd1d8; border-radius: 5px; }
h1 { margin: 0 0 12px; font-size: 18px; font-weight: 600; }
p { margin: 0; line-height: 1.65; overflow-wrap: anywhere; }
#auth-description { color: #55616e; margin-bottom: 20px; }
form { display: flex; flex-direction: column; gap: 8px; }
input, button { font: inherit; min-width: 0; min-height: 36px; padding: 7px 10px; border: 1px solid #afb8c2; border-radius: 3px; }
input { width: 100%; background: #fff; color: inherit; caret-color: #245d9b; }
button { margin-top: 8px; background: #245d9b; color: #fff; border-color: #245d9b; cursor: pointer; }
button:hover { background: #1c4d83; }
button:disabled { cursor: default; opacity: .58; }
input:focus-visible, button:focus-visible { outline: 2px solid #245d9b; outline-offset: 2px; }
#auth-status { color: #55616e; }
#auth-error { color: #99251e; white-space: pre-wrap; }
noscript { display: block; margin-top: 16px; line-height: 1.65; }
::selection { background: #c5dbf5; color: #142b46; }
+26
View File
@@ -0,0 +1,26 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light">
<title>管理登录 · 牧羊人之心牧场助手</title>
<link rel="icon" href="data:,">
<link rel="stylesheet" href="/static/login.css">
<script type="module" src="/static/login.js"></script>
</head>
<body>
<main class="admin-login" aria-labelledby="auth-title">
<h1 id="auth-title">登录管理工作台</h1>
<p id="auth-description">请输入此 Web 工作台的管理密码。</p>
<form id="auth-form" method="post" action="/api/auth/login" aria-describedby="auth-description">
<label for="admin-password">管理密码</label>
<input id="admin-password" name="password" type="password" autocomplete="current-password" required aria-describedby="auth-error" disabled>
<p id="auth-status" role="status">正在检查登录状态…</p>
<p id="auth-error" role="alert" hidden></p>
<button type="submit" disabled>登录</button>
</form>
<noscript>请启用 JavaScript 后登录管理工作台。</noscript>
</main>
</body>
</html>
+99
View File
@@ -0,0 +1,99 @@
const form = document.querySelector('#auth-form');
const input = document.querySelector('#admin-password');
const button = form.querySelector('button[type="submit"]');
const status = document.querySelector('#auth-status');
const error = document.querySelector('#auth-error');
let busy = false;
let leaving = false;
function setBusy(value, message = '') {
busy = value;
input.disabled = value;
button.disabled = value;
form.setAttribute('aria-busy', String(value));
status.textContent = message;
status.hidden = !message;
}
function showError(message) {
error.textContent = message;
error.hidden = false;
}
function openWorkbench() {
leaving = true;
input.value = '';
setBusy(true, '正在进入工作台…');
location.replace('/');
}
async function authRequest(path, body) {
let response;
try {
response = await fetch(path, {
method: body === undefined ? 'GET' : 'POST',
credentials: 'same-origin',
cache: 'no-store',
headers: body === undefined ? {Accept: 'application/json'} : {Accept: 'application/json', 'Content-Type': 'application/json'},
body,
});
} catch {
throw new Error('无法连接 Web 服务,请检查服务是否仍在运行后重试。');
}
const data = await response.json().catch(() => null);
if (!response.ok) {
const message = typeof data?.detail === 'string' ? data.detail : data?.error?.message;
throw new Error(message || `请求未完成(HTTP ${response.status}),请重试。`);
}
if (!data || typeof data.required !== 'boolean' || typeof data.authenticated !== 'boolean') {
throw new Error('无法确认登录状态,请重试。');
}
return data;
}
async function checkAuth() {
setBusy(true, '正在检查登录状态…');
error.hidden = true;
try {
const auth = await authRequest('/api/auth/status');
if (!auth.required || auth.authenticated) openWorkbench();
} catch (failure) {
showError(failure.message);
} finally {
if (!leaving) {
setBusy(false);
input.focus();
}
}
}
form.addEventListener('submit', async event => {
event.preventDefault();
if (busy || leaving || !form.reportValidity()) return;
const body = JSON.stringify({password: input.value});
input.value = '';
error.hidden = true;
setBusy(true, '正在登录…');
try {
const auth = await authRequest('/api/auth/login', body);
if (!auth.required || auth.authenticated) openWorkbench();
else showError('登录未完成,请重新输入管理密码。');
} catch (failure) {
showError(failure.message);
} finally {
if (!leaving) {
setBusy(false);
input.focus();
}
}
});
window.addEventListener('pagehide', () => { input.value = ''; });
window.addEventListener('pageshow', event => {
if (event.persisted) {
leaving = false;
input.value = '';
checkAuth();
}
});
checkAuth();
@@ -0,0 +1,282 @@
"""Offline browser coverage of the real password-protected administrator boundary.
Run: python -B -m unittest ranch_web.tests.browser.test_admin_login_browser -v
Only temporary demo accounts and a synthetic administrator password are used.
"""
from __future__ import annotations
import json
from pathlib import Path
import socket
import tempfile
import threading
import time
import unittest
from unittest.mock import patch
from .test_workbench_browser import AVAILABLE, EDGE, OfflineUpdates
if AVAILABLE:
from playwright.sync_api import expect
@unittest.skipUnless(AVAILABLE, "Install Python Playwright and set RANCH_WEB_BROWSER to a system Chromium browser")
class AdminLoginBrowserTests(unittest.TestCase):
password = "offline-admin-password-not-a-real-credential"
@classmethod
def setUpClass(cls):
import uvicorn
from playwright.sync_api import sync_playwright
from ranch_web.app import create_app
from ranch_web.config import WebConfig
from ranch_web.service import WebManager
cls.network = patch("requests.sessions.Session.request", side_effect=AssertionError("Live HTTP is forbidden"))
cls.network.start()
cls.addClassCleanup(cls.network.stop)
cls.temp = tempfile.TemporaryDirectory(prefix="ranch-web-admin-browser-")
cls.addClassCleanup(cls.temp.cleanup)
cls.manager = WebManager(cls.temp.name, start_scheduler=False)
cls.addClassCleanup(cls.manager.close)
cls.manager.create_account("管理登录离线演示", demo=True)
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
cls.base = f"http://127.0.0.1:{port}"
settings = WebConfig(port=port, data_dir=Path(cls.temp.name), password=cls.password)
app = create_app(manager=cls.manager, config=settings, updates=OfflineUpdates())
cls.sessions = next(item.kwargs["sessions"] for item in app.user_middleware if "sessions" in item.kwargs)
cls.server = uvicorn.Server(uvicorn.Config(app, host="127.0.0.1", port=port, log_level="error"))
cls.thread = threading.Thread(target=cls.server.run, daemon=True)
cls.thread.start()
cls.addClassCleanup(cls.stop_server)
deadline = time.monotonic() + 15
while not cls.server.started and time.monotonic() < deadline:
time.sleep(.02)
if not cls.server.started:
raise RuntimeError("Temporary protected browser server failed to start")
cls.playwright = sync_playwright().start()
cls.addClassCleanup(cls.playwright.stop)
cls.browser = cls.playwright.chromium.launch(executable_path=str(EDGE), headless=True)
cls.addClassCleanup(cls.browser.close)
@classmethod
def stop_server(cls):
cls.server.should_exit = True
cls.thread.join(timeout=10)
def setUp(self):
self.context = self.browser.new_context(viewport={"width": 1280, "height": 800})
self.addCleanup(self.context.close)
self.external_requests = []
def offline_only(route):
if route.request.url.startswith(self.base + "/"):
route.continue_()
else:
self.external_requests.append(route.request.url)
route.abort()
self.context.route("**/*", offline_only)
self.page = self.context.new_page()
self.requests = []
self.errors = []
self.csp_errors = []
self.page.on("request", lambda request: self.requests.append(request.url))
self.page.on("pageerror", lambda failure: self.errors.append(str(failure)))
self.page.on("console", lambda message: self.csp_errors.append(message.text)
if message.type == "error" and ("security policy" in message.text.lower() or "csp" in message.text.lower()) else None)
def tearDown(self):
self.assertEqual(self.errors, [])
self.assertEqual(self.csp_errors, [])
self.assertEqual(self.external_requests, [])
def assert_login_only(self, page=None):
page = page or self.page
expect(page).to_have_url(self.base + "/login")
expect(page.locator("#auth-form")).to_be_visible()
expect(page.locator("#admin-password")).to_be_enabled()
self.assertEqual(page.locator("#app, nav, #account-tabs, #page-tabs, #page-host, #auth-dialog").count(), 0)
self.assertEqual(page.locator("script:not([src]), [style], [onclick], [onsubmit]").count(), 0)
self.assertEqual(page.locator("script").count(), 1)
expect(page.locator("script")).to_have_attribute("type", "module")
expect(page.locator("script")).to_have_attribute("src", "/static/login.js")
def login(self):
self.page.goto(self.base + "/", wait_until="networkidle")
self.assert_login_only()
self.page.locator("#admin-password").fill(self.password)
with self.page.expect_response("**/api/auth/login") as pending:
self.page.locator('#auth-form button[type="submit"]').click()
self.assertEqual(pending.value.status, 200)
self.assertEqual(pending.value.request.post_data_json, {"password": self.password})
expect(self.page).to_have_url(self.base + "/")
expect(self.page.locator("#app")).to_be_visible()
expect(self.page.locator("#page-tabs [role=tab]")).to_have_count(15)
expect(self.page.locator("#status-text")).to_have_text("工作台已连接")
self.assertEqual(self.page.locator("#auth-dialog, #auth-form").count(), 0)
def observe_login_transition(self):
snapshots = []
def login_document(route):
snapshots.append(route.request.url)
# Leave the old document available to prove it was hidden before navigation.
route.abort()
self.page.route("**/login", login_document)
return snapshots
def assert_hidden_transition(self, snapshots):
expect(self.page.locator("#app")).to_have_count(1)
expect(self.page.locator("#app")).to_be_hidden()
deadline = time.monotonic() + 5
while not snapshots and time.monotonic() < deadline:
self.page.wait_for_timeout(20)
self.assertTrue(snapshots)
self.assertEqual(self.page.locator("dialog[open]").count(), 0)
self.assertTrue(self.page.evaluate("[...document.querySelectorAll('input[type=password]')].every(input => !input.value)"))
self.page.unroute("**/login")
self.page.goto(self.base + "/login", wait_until="networkidle")
def assert_old_cookie_rejected(self, cookies):
context = self.browser.new_context()
self.addCleanup(context.close)
context.add_cookies(cookies)
page = context.new_page()
requested = []
page.on("request", lambda request: requested.append(request.url))
page.goto(self.base + "/", wait_until="networkidle")
self.assert_login_only(page)
self.assertFalse(any(url.endswith("/static/app.js") for url in requested))
response = context.request.get(self.base + "/static/index.html", max_redirects=0)
self.assertIn(response.status, (302, 303, 307, 401, 403))
self.assertNotIn('id="app"', response.text())
response = context.request.get(self.base + "/static/app.js", max_redirects=0)
self.assertIn(response.status, (302, 303, 307, 401, 403))
def test_fresh_root_serves_only_login_and_public_assets_with_csp(self):
response = self.page.goto(self.base + "/", wait_until="networkidle")
self.assert_login_only()
self.assertEqual(response.status, 200)
self.assertNotIn('id="app"', response.text())
policy = response.headers["content-security-policy"]
self.assertIn("script-src 'self'", policy)
self.assertIn("style-src 'self'", policy)
self.assertNotIn("'unsafe-inline'", policy)
self.assertIn(self.base + "/api/auth/status", self.requests)
scripts = self.page.evaluate("performance.getEntriesByType('resource').filter(item => item.initiatorType === 'script').map(item => new URL(item.name).pathname)")
self.assertEqual(scripts, ["/static/login.js"])
self.assertFalse(any(url.endswith(("/app.js", "/api.js", "/pages.js", "/dom.js", "/ui.js")) for url in self.requests))
for width in (1280, 390):
self.page.set_viewport_size({"width": width, "height": 800})
self.assertLessEqual(self.page.evaluate("document.documentElement.scrollWidth"), width)
expect(self.page.get_by_role("button", name="登录", exact=True)).to_be_visible()
self.assertEqual(self.context.cookies(), [])
def test_login_all_tabs_authenticated_login_redirect_logout_and_revoked_cookie(self):
self.login()
cookies = self.context.cookies()
self.assertEqual(len(cookies), 1)
self.assertEqual(cookies[0]["path"], "/")
self.assertTrue(cookies[0]["httpOnly"])
self.assertEqual(self.page.evaluate("localStorage.length + sessionStorage.length"), 0)
self.assertNotIn(self.password, self.page.url)
self.page.goto(self.base + "/login", wait_until="networkidle")
expect(self.page).to_have_url(self.base + "/")
expect(self.page.locator("#page-tabs [role=tab]")).to_have_count(15)
snapshots = self.observe_login_transition()
self.page.locator(".menu > summary").first.click()
self.page.locator('[data-command="admin-logout"]').click()
self.assert_hidden_transition(snapshots)
self.assert_login_only()
self.assertEqual(self.context.cookies(), [])
self.assert_old_cookie_rejected(cookies)
def test_wrong_password_clears_input_without_loading_workbench(self):
self.page.goto(self.base + "/", wait_until="networkidle")
self.assert_login_only()
self.page.locator("#admin-password").fill("offline-wrong-admin-password")
with self.page.expect_response("**/api/auth/login") as pending:
self.page.get_by_role("button", name="登录", exact=True).click()
self.assertEqual(pending.value.status, 401)
expect(self.page.locator("#auth-error")).to_contain_text("管理密码错误")
self.assertEqual(self.page.locator("#admin-password").input_value(), "")
expect(self.page.locator("#admin-password")).to_be_focused()
self.assert_login_only()
self.assertEqual(self.page.evaluate("localStorage.length + sessionStorage.length"), 0)
self.assertFalse(any("offline-wrong-admin-password" in url or url.endswith("/app.js") for url in self.requests))
def test_expired_server_session_hides_workbench_and_rejects_old_cookie(self):
self.login()
cookies = self.context.cookies()
self.page.locator(".menu > summary").nth(3).click()
self.page.locator('[data-command="about"]').click()
expect(self.page.locator("#action-dialog")).to_be_visible()
snapshots = self.observe_login_transition()
# Expire only this disposable server's in-memory sessions; no 60s sleep.
with self.sessions.lock:
for digest in self.sessions.sessions:
self.sessions.sessions[digest] = 0.0
self.assert_hidden_transition(snapshots)
self.assert_login_only()
self.assert_old_cookie_rejected(cookies)
def test_explicit_action_401_clears_password_and_redirects(self):
self.login()
snapshots = self.observe_login_transition()
def unauthorized(route):
self.assertEqual(self.context.request.post(self.base + "/api/auth/logout", data={}).status, 200)
route.fulfill(status=401, content_type="application/json", body=json.dumps({"detail": "会话已失效"}))
self.page.route("**/api/accounts/*/actions/refresh", unauthorized)
self.page.locator('#page-host input[type="password"]').fill("unsent-offline-game-password")
self.page.locator("#refresh").click()
self.assert_hidden_transition(snapshots)
self.assert_login_only()
def test_bootstrap_status_401_keeps_workbench_hidden(self):
self.assertEqual(self.context.request.post(self.base + "/api/auth/login", data={"password": self.password}).status, 200)
initial_status = []
def unauthorized_status(route):
if not initial_status:
initial_status.append(route)
else:
route.fulfill(status=401, content_type="application/json", body='{"detail":"会话已失效"}')
self.page.route("**/api/auth/status", unauthorized_status)
self.page.add_init_script("""window.workbenchVisible = false;
new MutationObserver(() => {
const app = document.querySelector('#app');
if (app && !app.hidden) window.workbenchVisible = true;
}).observe(document, {subtree: true, childList: true, attributes: true, attributeFilter: ['hidden']});""")
self.page.goto(self.base + "/", wait_until="domcontentloaded")
expect(self.page.locator("#app")).to_have_count(1)
expect(self.page.locator("#app")).to_be_hidden()
deadline = time.monotonic() + 5
while not initial_status and time.monotonic() < deadline:
self.page.wait_for_timeout(20)
self.assertTrue(initial_status)
self.assertFalse(self.page.evaluate("window.workbenchVisible"))
self.assertEqual(self.context.request.post(self.base + "/api/auth/logout", data={}).status, 200)
initial_status[0].fulfill(status=401, content_type="application/json", body='{"detail":"会话已失效"}')
self.assert_login_only()
expect(self.page.locator("#auth-error")).to_contain_text("会话已失效")
def test_javascript_disabled_still_contains_only_login_form(self):
context = self.browser.new_context(java_script_enabled=False)
self.addCleanup(context.close)
page = context.new_page()
response = page.goto(self.base + "/", wait_until="networkidle")
expect(page).to_have_url(self.base + "/login")
self.assertNotIn('id="app"', response.text())
self.assertEqual(page.locator("#app, nav, #account-tabs, #page-tabs").count(), 0)
expect(page.locator("#auth-form")).to_be_visible()
expect(page.locator("#auth-form button")).to_be_disabled()
expect(page.locator("noscript")).to_be_visible()
if __name__ == "__main__":
unittest.main()
@@ -124,6 +124,14 @@ class WorkbenchBrowserTests(unittest.TestCase):
def fulfill(route, data): def fulfill(route, data):
route.fulfill(status=200, content_type="application/json", body=json.dumps(data, ensure_ascii=False)) route.fulfill(status=200, content_type="application/json", body=json.dumps(data, ensure_ascii=False))
def test_local_no_password_login_route_returns_to_workbench(self):
self.page.goto(self.base + "/login", wait_until="networkidle")
expect(self.page).to_have_url(self.base + "/")
expect(self.page.locator("#app")).to_be_visible()
expect(self.page.locator("#page-tabs [role=tab]")).to_have_count(15)
self.assertEqual(self.page.locator("#auth-dialog, #auth-form").count(), 0)
self.assertEqual(self.errors, [])
def test_all_pages_are_read_only_csp_clean_and_responsive(self): def test_all_pages_are_read_only_csp_clean_and_responsive(self):
self.open() self.open()
writes = [] writes = []
+10 -4
View File
@@ -513,12 +513,18 @@ class ApiTests(unittest.TestCase):
for url in ("/static/.env", "/static/config.py", "/static/../app.py", "/static/%2e%2e/requirements.txt"): for url in ("/static/.env", "/static/config.py", "/static/../app.py", "/static/%2e%2e/requirements.txt"):
with self.subTest(url=url): with self.subTest(url=url):
self.assertEqual(self.client.get(url).status_code, 404) self.assertEqual(self.client.get(url).status_code, 404)
response = self.client.get("/") for url in ("/", "/static/index.html", "/static/app.js"):
self.assertIn(response.status_code, (200, 503)) response = self.client.get(url)
if response.status_code == 200: self.assertEqual(response.status_code, 200)
self.assertIn("text/html", response.headers["content-type"]) self.assertEqual(response.headers["cache-control"], "no-store")
self.assertEqual(response.headers["x-content-type-options"], "nosniff") self.assertEqual(response.headers["x-content-type-options"], "nosniff")
self.assertIn("frame-ancestors 'none'", response.headers["content-security-policy"]) self.assertIn("frame-ancestors 'none'", response.headers["content-security-policy"])
for url in ("/", "/static/index.html"):
response = self.client.get(url)
self.assertIn("text/html", response.headers["content-type"])
response = self.client.get("/login", follow_redirects=False)
self.assertEqual(response.status_code, 303)
self.assertEqual(response.headers["location"], "/")
def test_cli_help_and_factory_do_not_import_qt_or_open_private_state(self): def test_cli_help_and_factory_do_not_import_qt_or_open_private_state(self):
project = Path(__file__).resolve().parents[2] project = Path(__file__).resolve().parents[2]
+179 -4
View File
@@ -1,6 +1,7 @@
"""Administrator sessions and browser boundary checks, entirely offline.""" """Administrator sessions and browser boundary checks, entirely offline."""
import asyncio import asyncio
from http.cookies import SimpleCookie
from pathlib import Path from pathlib import Path
import tempfile import tempfile
import threading import threading
@@ -21,21 +22,190 @@ class AuthTests(unittest.TestCase):
self.addCleanup(self.temporary.cleanup) self.addCleanup(self.temporary.cleanup)
self.root = Path(self.temporary.name) self.root = Path(self.temporary.name)
self.manager, self.updates = FakeManager(), FakeUpdates() self.manager, self.updates = FakeManager(), FakeUpdates()
self.assets = self.root / "static"
self.assets.mkdir()
for name, content in {
"index.html": '<html><nav>WORKBENCH_ONLY</nav><script src="/static/app.js"></script></html>',
"login.html": '<html><form>ADMIN_LOGIN_ONLY</form><script src="/static/login.js"></script></html>',
"login.js": "// LOGIN_SCRIPT_ONLY",
"login.css": "/* LOGIN_STYLE_ONLY */",
"styles.css": "/* SHARED_STYLE_ONLY */",
"dom.js": "// SHARED_DOM_ONLY",
**{name: "// WORKBENCH_ONLY" for name in ("app.js", "api.js", "pages.js", "ui.js", "table.js", "forms.js", "future.mjs")},
}.items():
(self.assets / name).write_text(content, encoding="utf-8")
self.enterContext(patch("requests.sessions.Session.request", side_effect=AssertionError("No real network access")))
def client(self, settings=None, **kwargs): def client(self, settings=None, **kwargs):
settings = settings or WebConfig(data_dir=self.root) settings = settings or WebConfig(data_dir=self.root)
with patch("ranch_web.app.__file__", str(self.root / "app.py")):
app = create_app(manager=self.manager, updates=self.updates, config=settings) app = create_app(manager=self.manager, updates=self.updates, config=settings)
return self.enterContext(TestClient(app, base_url="http://localhost", client=("127.0.0.1", 50000), **kwargs)) return self.enterContext(TestClient(app, base_url="http://localhost", client=("127.0.0.1", 50000), **kwargs))
def cookie_headers(self, response):
cookies = []
for header in response.headers.get_list("set-cookie"):
parsed = SimpleCookie()
parsed.load(header)
cookies.append(parsed[COOKIE_NAME])
return cookies
def test_unauthenticated_workbench_and_scripts_redirect_before_file_access(self):
client = self.client(WebConfig(data_dir=self.root, password="correct"))
with patch("ranch_web.app.FileResponse", side_effect=AssertionError("Workbench HTML must stay unopened")), \
patch("ranch_web.app._Assets.lookup_path", side_effect=AssertionError("Workbench assets must stay unopened")):
for path in ("/", "/?next=/api/accounts", "/static/index.html", "/static/app.js", "/static/api.js",
"/static/pages.js", "/static/ui.js", "/static/table.js", "/static/forms.js", "/static/future.mjs",
"/static//index.html", "/static/%69ndex.html", "/static/login.js/../app.js"):
with self.subTest(path=path):
response = client.get(path, follow_redirects=False)
self.assertEqual(response.status_code, 303)
self.assertEqual(response.headers["location"], "/login")
self.assertEqual(response.headers["cache-control"], "no-store")
self.assertNotIn("WORKBENCH_ONLY", response.text)
self.assertEqual(response.headers["x-content-type-options"], "nosniff")
self.assertEqual(self.manager.calls, [])
self.assertEqual(self.updates.calls, [])
def test_login_page_and_shared_assets_are_public_without_workbench(self):
client = self.client(WebConfig(data_dir=self.root, password="correct"))
for path in ("/login", "/static/login.html"):
with self.subTest(path=path):
response = client.get(path)
self.assertEqual(response.status_code, 200)
self.assertIn("text/html", response.headers["content-type"])
self.assertIn("ADMIN_LOGIN_ONLY", response.text)
self.assertNotIn("WORKBENCH_ONLY", response.text)
self.assertEqual(response.headers["cache-control"], "no-store")
for name in ("login.js", "login.css", "styles.css", "dom.js"):
with self.subTest(name=name):
response = client.get("/static/" + name)
self.assertEqual(response.status_code, 200)
self.assertNotIn("WORKBENCH_ONLY", response.text)
self.assertEqual(self.manager.calls, [])
self.assertEqual(self.updates.calls, [])
def test_authenticated_login_redirects_home_and_workbench_assets_are_private(self):
client = self.client(WebConfig(data_dir=self.root, password="correct"))
self.assertEqual(client.post("/api/auth/login", json={"password": "correct"}).status_code, 200)
for path in ("/login", "/static/login.html"):
with self.subTest(path=path):
response = client.get(path, follow_redirects=False)
self.assertEqual(response.status_code, 303)
self.assertEqual(response.headers["location"], "/")
self.assertEqual(response.headers["cache-control"], "no-store")
for path in ("/", "/static/index.html", "/static/app.js", "/static/api.js", "/static/pages.js", "/static/future.mjs"):
with self.subTest(path=path):
response = client.get(path)
self.assertEqual(response.status_code, 200)
self.assertIn("WORKBENCH_ONLY", response.text)
self.assertEqual(response.headers["cache-control"], "no-store")
self.assertEqual(self.manager.calls, [])
self.assertEqual(self.updates.calls, [])
def test_ui_gate_preserves_public_api_and_json_unauthorized_responses(self):
client = self.client(WebConfig(data_dir=self.root, password="correct"))
for path in ("/api/health", "/api/meta", "/api/auth/status"):
with self.subTest(path=path):
self.assertEqual(client.get(path).status_code, 200)
for method, path in (("GET", "/api/accounts"), ("GET", "/api/schema"), ("POST", "/api/accounts")):
with self.subTest(method=method, path=path):
response = client.request(method, path, follow_redirects=False)
self.assertEqual(response.status_code, 401)
self.assertNotIn("location", response.headers)
self.assertEqual(response.json()["error"]["code"], "authentication_required")
self.assertEqual(client.post("/api/auth/logout").status_code, 200)
self.assertEqual(self.manager.calls, [])
def test_invalid_and_expired_sessions_cannot_open_workbench(self):
settings = WebConfig(data_dir=self.root, password="correct", session_ttl=60)
client = self.client(settings)
for token in ("invalid", "A" * 43):
with self.subTest(token=token):
response = client.get("/", headers={"Cookie": f"{COOKIE_NAME}={token}"}, follow_redirects=False)
self.assertEqual(response.status_code, 303)
self.assertEqual(response.headers["location"], "/login")
with patch("ranch_web.app.time.monotonic", return_value=0):
self.assertEqual(client.post("/api/auth/login", json={"password": "correct"}).status_code, 200)
for path in ("/", "/static/index.html", "/static/app.js"):
with self.subTest(path=path):
response = client.get(path, follow_redirects=False)
self.assertEqual(response.status_code, 303)
self.assertEqual(response.headers["location"], "/login")
self.assertEqual(client.get("/api/accounts").status_code, 401)
self.assertIn("ADMIN_LOGIN_ONLY", client.get("/login").text)
def test_missing_login_asset_returns_unavailable_without_workbench_fallback(self):
client = self.client(WebConfig(data_dir=self.root, password="correct"))
(self.assets / "login.html").unlink()
response = client.get("/login")
self.assertEqual(response.status_code, 503)
self.assertNotIn("WORKBENCH_ONLY", response.text)
response = client.get("/", follow_redirects=False)
self.assertEqual(response.status_code, 303)
self.assertEqual(response.headers["location"], "/login")
def test_login_migrates_legacy_api_cookie_and_revokes_previous_session(self):
client = self.client(WebConfig(data_dir=self.root, password="correct"))
client.post("/api/auth/login", json={"password": "correct"})
token = client.cookies.get(COOKIE_NAME)
domain = next(iter(client.cookies.jar)).domain
client.cookies.clear()
client.cookies.set(COOKIE_NAME, token, domain=domain, path="/api")
self.assertEqual(client.get("/", follow_redirects=False).status_code, 303)
response = client.post("/api/auth/login", json={"password": "correct"})
self.assertEqual(response.status_code, 200)
cookies = {cookie["path"]: cookie for cookie in self.cookie_headers(response)}
self.assertEqual(set(cookies), {"/", "/api"})
self.assertEqual(cookies["/api"]["max-age"], "0")
self.assertEqual(cookies["/api"].value, "")
self.assertNotEqual(cookies["/"].value, token)
self.assertEqual([(cookie.name, cookie.path) for cookie in client.cookies.jar], [(COOKIE_NAME, "/")])
self.assertEqual(client.get("/").status_code, 200)
self.assertEqual(client.get("/api/accounts").status_code, 200)
self.assertEqual(client.get("/api/accounts", headers={"Cookie": f"{COOKIE_NAME}={token}"}).status_code, 401)
def test_logout_clears_root_and_legacy_cookies_and_blocks_ui_replay(self):
client = self.client(WebConfig(data_dir=self.root, password="correct"))
client.post("/api/auth/login", json={"password": "correct"})
token = client.cookies.get(COOKIE_NAME)
domain = next(iter(client.cookies.jar)).domain
client.cookies.set(COOKIE_NAME, "stale-legacy-cookie", domain=domain, path="/api")
response = client.post("/api/auth/logout")
self.assertEqual(response.status_code, 200)
cookies = {cookie["path"]: cookie for cookie in self.cookie_headers(response)}
self.assertEqual(set(cookies), {"/", "/api"})
for cookie in cookies.values():
self.assertEqual(cookie.value, "")
self.assertEqual(cookie["max-age"], "0")
self.assertTrue(cookie["httponly"])
self.assertEqual(cookie["samesite"], "strict")
self.assertEqual(list(client.cookies.jar), [])
for path in ("/", "/static/index.html", "/static/app.js"):
with self.subTest(path=path):
self.assertEqual(client.get(path, follow_redirects=False).status_code, 303)
response = client.get(path, headers={"Cookie": f"{COOKIE_NAME}={token}"}, follow_redirects=False)
self.assertEqual(response.status_code, 303)
self.assertEqual(response.headers["location"], "/login")
self.assertFalse(client.get("/api/auth/status").json()["authenticated"])
self.assertEqual(client.get("/api/accounts", headers={"Cookie": f"{COOKIE_NAME}={token}"}).status_code, 401)
def test_loopback_bypass_is_local_and_has_no_password_cookie(self): def test_loopback_bypass_is_local_and_has_no_password_cookie(self):
client = self.client() client = self.client()
self.assertEqual(client.get("/api/auth/status").json(), {"required": False, "authenticated": True, "access_mode": "local"}) self.assertEqual(client.get("/api/auth/status").json(), {"required": False, "authenticated": True, "access_mode": "local"})
response = client.post("/api/accounts", json={"demo": True}, headers={"Origin": "http://localhost"}) response = client.post("/api/accounts", json={"demo": True}, headers={"Origin": "http://localhost"})
self.assertEqual(response.status_code, 201) self.assertEqual(response.status_code, 201)
self.assertNotIn("set-cookie", response.headers) self.assertNotIn("set-cookie", response.headers)
self.assertIn("WORKBENCH_ONLY", client.get("/").text)
self.assertEqual(client.get("/login", follow_redirects=False).headers["location"], "/")
remote = self.enterContext(TestClient(create_app(manager=self.manager, updates=self.updates, config=WebConfig(data_dir=self.root)), base_url="http://localhost", client=("192.0.2.1", 50001))) remote = self.enterContext(TestClient(create_app(manager=self.manager, updates=self.updates, config=WebConfig(data_dir=self.root)), base_url="http://localhost", client=("192.0.2.1", 50001)))
self.assertEqual(remote.get("/api/accounts").status_code, 403) self.assertEqual(remote.get("/api/accounts").status_code, 403)
self.assertFalse(remote.get("/api/auth/status").json()["authenticated"]) self.assertFalse(remote.get("/api/auth/status").json()["authenticated"])
for path in ("/", "/static/index.html", "/static/app.js"):
with self.subTest(path=path):
response = remote.get(path, follow_redirects=False)
self.assertEqual(response.status_code, 303)
self.assertEqual(response.headers["location"], "/login")
def test_remote_bind_and_public_proxy_names_require_password(self): def test_remote_bind_and_public_proxy_names_require_password(self):
for values in ({"host": "0.0.0.0"}, {"host": "::"}, {"host": "192.0.2.10"}, {"allowed_hosts": ("ranch.example",)}, {"allowed_origins": ("https://ranch.example",)}): for values in ({"host": "0.0.0.0"}, {"host": "::"}, {"host": "192.0.2.10"}, {"allowed_hosts": ("ranch.example",)}, {"allowed_origins": ("https://ranch.example",)}):
@@ -50,10 +220,15 @@ class AuthTests(unittest.TestCase):
response = client.post("/api/auth/login", json={"password": "离线管理密码"}) response = client.post("/api/auth/login", json={"password": "离线管理密码"})
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertNotIn("离线管理密码", response.text) self.assertNotIn("离线管理密码", response.text)
cookie = response.headers["set-cookie"].lower() cookies = {cookie["path"]: cookie for cookie in self.cookie_headers(response)}
self.assertIn("httponly", cookie) cookie = cookies["/"]
self.assertIn("samesite=strict", cookie) self.assertTrue(cookie["httponly"])
self.assertIn("path=/api", cookie) self.assertEqual(cookie["samesite"], "strict")
self.assertEqual(cookie["max-age"], str(client.app.state.config.session_ttl))
self.assertFalse(cookie["secure"])
self.assertFalse(cookie["domain"])
self.assertEqual(cookies["/api"]["max-age"], "0")
self.assertEqual(client.get("/").status_code, 200)
self.assertEqual(client.get("/api/accounts").status_code, 200) self.assertEqual(client.get("/api/accounts").status_code, 200)
token = client.cookies.get(COOKIE_NAME) token = client.cookies.get(COOKIE_NAME)
self.assertEqual(len(token), 43) self.assertEqual(len(token), 43)