feat: require standalone admin login before the web workbench
This commit is contained in:
+40
-10
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user