fix: 清理超过十分钟的登录流程和明文密码

This commit is contained in:
2026-10-25 07:11:21 +08:00
parent db9c841462
commit 138096df17
+21
View File
@@ -4,6 +4,7 @@ from __future__ import annotations
import base64
import logging
import time
import uuid
from fastapi import APIRouter, HTTPException
@@ -14,6 +15,7 @@ from app.shared.state import state
logger = logging.getLogger("nqi.auth")
router = APIRouter(prefix="/api/auth", tags=["auth"])
FLOW_TTL_SECONDS = 10 * 60
def _bad(message: str, status: int = 400) -> HTTPException:
@@ -29,10 +31,28 @@ def _captcha_payload(session_id: str, challenge, **extra) -> dict:
}
async def purge_expired_flows(now: float | None = None) -> None:
"""关掉超过 10 分钟的登录流程,并清掉内存里的密码。"""
moment = time.monotonic() if now is None else now
expired: list[str] = []
for session_id, (client, challenge) in list(state.flows.items()):
if client is state.client:
continue
created = getattr(challenge, "created_at", None)
if created is None or moment - float(created) < FLOW_TTL_SECONDS:
continue
expired.append(session_id)
for session_id in expired:
client, challenge = state.flows.pop(session_id)
challenge.password = ""
await client.aclose()
@router.post("/captcha")
async def captcha() -> dict:
from app.platform.client import NqiClient
await purge_expired_flows()
client = NqiClient()
try:
challenge = await client.open_login()
@@ -41,6 +61,7 @@ async def captcha() -> dict:
logger.info("打开登录页失败: %s", exc)
raise _bad("连接失败,请稍后重试") from exc
session_id = uuid.uuid4().hex
challenge.created_at = time.monotonic()
state.flows[session_id] = (client, challenge)
return _captcha_payload(session_id, challenge)