From 89d9452967bf04d21cee473135133955e45091ba Mon Sep 17 00:00:00 2001 From: Nixevol Date: Mon, 16 Nov 2026 09:25:01 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E6=89=AB=E7=A0=81=E4=B8=8D=E5=86=8D?= =?UTF-8?q?=E8=A6=86=E7=9B=96=E5=B7=B2=E6=9C=89=E5=AF=86=E7=A0=81=EF=BC=8C?= =?UTF-8?q?=E7=99=BB=E5=BD=95=E6=8C=89=E5=9C=B0=E5=9D=80=E9=99=90=E9=80=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../versions/0005_password_login_at.py | 25 +++++ backend/euniv/api.py | 20 +++- backend/euniv/client.py | 52 +++++++---- backend/euniv/login_limit.py | 25 +++++ backend/euniv/models.py | 3 + backend/euniv/service.py | 93 ++++++++++++++++--- backend/tests/conftest.py | 3 + backend/tests/test_api.py | 1 + 8 files changed, 191 insertions(+), 31 deletions(-) create mode 100644 backend/alembic/versions/0005_password_login_at.py create mode 100644 backend/euniv/login_limit.py diff --git a/backend/alembic/versions/0005_password_login_at.py b/backend/alembic/versions/0005_password_login_at.py new file mode 100644 index 0000000..47f9d20 --- /dev/null +++ b/backend/alembic/versions/0005_password_login_at.py @@ -0,0 +1,25 @@ +"""记录最近一次真实密码登录的时间。""" + +from alembic import op +import sqlalchemy as sa + +revision = "0005_password_login_at" +down_revision = "0004_finished_courses" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.add_column( + "accounts", + sa.Column( + "password_login_at", + sa.DateTime(timezone=True), + server_default=sa.text("CURRENT_TIMESTAMP"), + nullable=False, + ), + ) + + +def downgrade() -> None: + op.drop_column("accounts", "password_login_at") diff --git a/backend/euniv/api.py b/backend/euniv/api.py index 133e693..40d7e8b 100644 --- a/backend/euniv/api.py +++ b/backend/euniv/api.py @@ -19,6 +19,7 @@ from admin.session import admin_session_active, clear_admin_session, write_admin from admin.settings import ensure_admin_seed, jigsaw_plan, load_admin_identity, load_config from euniv.db import get_db, init_db from euniv.models import Account +from euniv.login_limit import allow as login_allowed from euniv.service import ( fetch_exam_detail, fetch_home, @@ -32,6 +33,7 @@ from euniv.service import ( revoke_credential, start_credential_refresh, start_qr_login, + start_pending_cleaner, submit_jigsaw, ) from euniv.session import clear_session, write_session @@ -88,6 +90,7 @@ async def lifespan(_app: FastAPI): study_worker = start_autostudy() stop_pool = start_proxy_pool() + start_pending_cleaner() yield if study_worker is not None: study_worker.stop() @@ -97,7 +100,14 @@ async def lifespan(_app: FastAPI): stop_refresh.set() -app = FastAPI(title="EunivTools", lifespan=lifespan) +_openapi = os.environ.get("EUNIV_OPENAPI") == "1" +app = FastAPI( + title="EunivTools", + lifespan=lifespan, + docs_url="/docs" if _openapi else None, + redoc_url="/redoc" if _openapi else None, + openapi_url="/openapi.json" if _openapi else None, +) app.include_router(public_router) app.include_router(admin_router) @@ -169,6 +179,10 @@ def _client_host(request: Request) -> str: @app.post("/api/login") def login(body: LoginBody, request: Request, response: Response, db: Session = Depends(get_db)) -> dict: account = body.employee_id.strip() + if not account: + raise HTTPException(status_code=400, detail="请填写工号") + if not login_allowed(_client_host(request)): + raise HTTPException(status_code=429, detail="登录过于频繁,请稍后再试") if identity.matches(account): source = _client_host(request) if too_many(source): @@ -200,7 +214,9 @@ def login_jigsaw(body: JigsawBody, response: Response, db: Session = Depends(get @app.post("/api/login/qr") -def login_qr() -> dict: +def login_qr(request: Request) -> dict: + if not login_allowed(_client_host(request)): + raise HTTPException(status_code=429, detail="登录过于频繁,请稍后再试") try: return start_qr_login() except RuntimeError as exc: diff --git a/backend/euniv/client.py b/backend/euniv/client.py index 268a2f7..668767e 100644 --- a/backend/euniv/client.py +++ b/backend/euniv/client.py @@ -8,6 +8,7 @@ import io import json import random import re +import secrets import threading import time import uuid @@ -188,7 +189,7 @@ def make_qr_payload(prefix: str = QR_PREFIX) -> str: return hashlib.md5(text.encode("utf-8")).hexdigest() def digits(count: int) -> str: - return "".join(random.choice("0123456789") for _ in range(count)) + return "".join(secrets.choice("0123456789") for _ in range(count)) key = digest(prefix + str(now_ms()) + digits(10)) value = digest(key + digits(10)) @@ -247,21 +248,28 @@ def _authorize_lock(account_id: str) -> threading.Lock: _SITE_SHARE_SECONDS = 90 -_site_sessions: dict[str, tuple[float, list[tuple[str, str, str, str]]]] = {} +_site_sessions: dict[tuple[str, str], tuple[float, list[tuple[str, str, str, str]]]] = {} def forget_site(account_id: str) -> None: - _site_sessions.pop(account_id, None) + key = (account_id or "").strip() + for item in list(_site_sessions): + if item[0] == key: + _site_sessions.pop(item, None) -def _remember_site(account_id: str, client: httpx.Client) -> None: +def _remember_site(account_id: str, client: httpx.Client, token: str = "") -> None: jar = getattr(getattr(client, "cookies", None), "jar", None) if not account_id or jar is None: return + now = time.time() + for item, (saved, _rows) in list(_site_sessions.items()): + if now - saved > _SITE_SHARE_SECONDS: + _site_sessions.pop(item, None) dumped = [] for cookie in jar: dumped.append((cookie.name, cookie.value or "", cookie.domain or "", cookie.path or "/")) - _site_sessions[account_id] = (time.time(), dumped) + _site_sessions[(account_id, token)] = (now, dumped) def _load_cookies(client: httpx.Client | httpx.AsyncClient, dumped: list[tuple[str, str, str, str]]) -> None: @@ -845,16 +853,25 @@ class EunivClient: parts = self._qr_str.split(":") if len(parts) < 3: raise RuntimeError("请重新扫码") - payload = self._uac_post( - "/authentication/qrscan.serv", - json_body={"qrCodeKey": parts[1], "qrCodeValue": parts[2]}, - ).json() + try: + payload = self._uac_post( + "/authentication/qrscan.serv", + json_body={"qrCodeKey": parts[1], "qrCodeValue": parts[2]}, + ).json() + except (httpx.TransportError, TimeoutError): + self._qr_misses = getattr(self, "_qr_misses", 0) + 1 + if self._qr_misses >= 5: + raise RuntimeError("扫码状态没有获取到") from None + raise QrWaiting() from None top, inner, data, message = parse_uac(payload) if top == UAC_OK and inner == UAC_QR_WAIT: raise QrWaiting() if top == UAC_OK and inner == UAC_OK and isinstance(data, dict) and data.get("token"): self.login_name = str(data.get("accountId") or data.get("userName") or self.login_name) + self._qr_misses = 0 return data + if any(word in (message or "") for word in ("已扫码", "待确认", "确认中")): + raise QrWaiting() raise RuntimeError(message or "扫码登录失败") def _login_with_jigsaw(self, manual: bool, auto_attempts: int) -> dict: @@ -1175,6 +1192,8 @@ class EunivClient: """读取「我的学时」列表:来源、获得学时(分钟)、日期。""" try: items = self._study_history_search(pageable=False) + except SessionExpired: + raise except Exception: items = None if items is not None: @@ -1193,10 +1212,10 @@ class EunivClient: try: return accumulate_month_minutes(fetch_page, year, month) - except Exception: - items = self.study_history() - total, _ = fold_month_minutes(items, year, month) - return total + except SessionExpired: + raise + except Exception as exc: + raise RuntimeError("学时历史没有获取到") from exc def _study_history_search( self, *, pageable: bool, offset: int = 0, limit: int = HISTORY_PAGE_SIZE @@ -1243,7 +1262,8 @@ class EunivClient: with _authorize_lock(account_id): if getattr(self, "_site_ready", False): return "" - shared = _site_sessions.get(account_id) + token = str(self._profile.get("token") or "") + shared = _site_sessions.get((account_id, token)) if shared and time.time() - shared[0] < _SITE_SHARE_SECONDS: _load_cookies(self.client, shared[1]) self._site_ready = True @@ -1255,10 +1275,10 @@ class EunivClient: if "spMonthlyPeriod" not in probe.text: self.authorize(self._profile) self._site_ready = True - _remember_site(account_id, self.client) + _remember_site(account_id, self.client, token) return "" self._site_ready = True - _remember_site(account_id, self.client) + _remember_site(account_id, self.client, token) return probe.text return "" diff --git a/backend/euniv/login_limit.py b/backend/euniv/login_limit.py new file mode 100644 index 0000000..32f08bb --- /dev/null +++ b/backend/euniv/login_limit.py @@ -0,0 +1,25 @@ +"""未登录接口按来源地址限速。状态只放内存。""" + +from __future__ import annotations + +import time + +_hits: dict[str, list[float]] = {} +_WINDOW = 60.0 +_LIMIT = 30 + + +def reset() -> None: + _hits.clear() + + +def allow(source: str, limit: int = _LIMIT, window: float = _WINDOW) -> bool: + now = time.monotonic() + key = (source or "unknown").strip() or "unknown" + recent = [item for item in _hits.get(key, []) if now - item < window] + if len(recent) >= limit: + _hits[key] = recent + return False + recent.append(now) + _hits[key] = recent + return True diff --git a/backend/euniv/models.py b/backend/euniv/models.py index efee86a..e69fdea 100644 --- a/backend/euniv/models.py +++ b/backend/euniv/models.py @@ -77,6 +77,9 @@ class Account(Base): sessions_valid_after: Mapped[datetime] = mapped_column( DateTime(timezone=True), nullable=False, server_default=text("CURRENT_TIMESTAMP") ) + password_login_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), nullable=False, server_default=text("CURRENT_TIMESTAMP") + ) class ProxyNode(Base): diff --git a/backend/euniv/service.py b/backend/euniv/service.py index 5a3cae2..46f5160 100644 --- a/backend/euniv/service.py +++ b/backend/euniv/service.py @@ -7,7 +7,7 @@ import json import secrets import threading import time -from datetime import datetime, timezone +from datetime import datetime, timedelta, timezone from dataclasses import dataclass from sqlalchemy import select @@ -49,6 +49,7 @@ class PendingLogin: employee_id: str password: str created: float + tries: int = 0 @dataclass @@ -61,6 +62,22 @@ def _dump(credential: dict) -> str: return json.dumps(credential, ensure_ascii=False, sort_keys=True) +def start_pending_cleaner() -> None: + """定时丢掉过期的登录会话,不依赖下一次请求。""" + + def loop() -> None: + while True: + time.sleep(30) + try: + _purge_pending() + except Exception: + import logging + + logging.getLogger("euniv.service").exception("清理未完成的登录失败") + + threading.Thread(target=loop, name="euniv-pending", daemon=True).start() + + def _purge_pending() -> None: now = time.time() for attempt_id, pending in list(_pending.items()): @@ -86,16 +103,45 @@ def _drop_employee(employee_id: str) -> None: _pending.pop(attempt_id, None) -def _persist(db: Session, employee_id: str, password: str, client: EunivClient, profile: dict) -> None: +def _persist(db: Session, employee_id: str, password: str | None, client: EunivClient, profile: dict) -> None: + from sqlalchemy.exc import IntegrityError + client.authorize(profile) account = db.get(Account, employee_id) if account is None: account = Account(employee_id=employee_id, password_cipher="", credential_cipher="") db.add(account) - account.password_cipher = encrypt_secret(password) + if password is None: + stored = "" + if account.password_cipher: + try: + stored = decrypt_secret(account.password_cipher) + except Exception: + stored = "" + if not stored or is_qr_password(stored): + account.password_cipher = encrypt_secret(QR_PASSWORD_MARK) + else: + account.password_cipher = encrypt_secret(password) + account.password_login_at = datetime.now(timezone.utc) account.credential_cipher = encrypt_secret(_dump(client.export_credential())) account.credential_valid = True - db.commit() + try: + db.commit() + except IntegrityError: + db.rollback() + account = db.get(Account, employee_id) + if account is None: + raise + if password is None: + stored = decrypt_secret(account.password_cipher) if account.password_cipher else "" + if not stored or is_qr_password(stored): + account.password_cipher = encrypt_secret(QR_PASSWORD_MARK) + else: + account.password_cipher = encrypt_secret(password) + account.password_login_at = datetime.now(timezone.utc) + account.credential_cipher = encrypt_secret(_dump(client.export_credential())) + account.credential_valid = True + db.commit() from euniv.autostudy import sync_work sync_work(employee_id) @@ -124,6 +170,19 @@ def _switch_proxy(account: Account | None, client, exc: BaseException) -> bool: return True +def fresh_password(account: Account) -> bool: + confirmed = getattr(account, "password_login_at", None) + if confirmed is None: + return False + if confirmed.tzinfo is None: + confirmed = confirmed.replace(tzinfo=timezone.utc) + return datetime.now(timezone.utc) - confirmed <= timedelta(days=7) + + +def _resolved_id(profile: dict, fallback: str) -> str: + return str(profile.get("accountId") or fallback or "").strip() or fallback + + def login_and_store( db: Session, employee_id: str, @@ -142,10 +201,9 @@ def login_and_store( not is_qr_password(stored) and hmac.compare_digest(stored.encode("utf-8"), password.encode("utf-8")) ) - if same_password and _credential_still_valid(account, client_factory): + if same_password and fresh_password(account) and _credential_still_valid(account, client_factory): _request_course_sync(employee_id) return {"employee_id": employee_id} - _drop_employee(employee_id) from euniv.proxy_pool import MAX_SWITCHES held = False @@ -168,9 +226,12 @@ def login_and_store( client = None continue raise - _persist(db, employee_id, password, client, profile) - _request_course_sync(employee_id) - return {"employee_id": employee_id} + resolved = _resolved_id(profile, employee_id) + _persist(db, resolved, password, client, profile) + _drop_employee(employee_id) + _drop_employee(resolved) + _request_course_sync(resolved) + return {"employee_id": resolved} if last_exc is not None: raise last_exc raise RuntimeError("登录失败") @@ -205,6 +266,11 @@ def submit_jigsaw(db: Session, attempt_id: str, offset: int) -> dict: try: profile = pending.client.submit_jigsaw(offset) except JigsawRejected: + pending.tries += 1 + if pending.tries >= 5: + _pending.pop(attempt_id, None) + pending.client.close() + raise RuntimeError("请重新登录") pending.created = time.time() return {"attempt_id": attempt_id, "jigsaw": pending.client.next_jigsaw()} except Exception: @@ -213,9 +279,10 @@ def submit_jigsaw(db: Session, attempt_id: str, offset: int) -> dict: raise _pending.pop(attempt_id, None) try: - _persist(db, pending.employee_id, pending.password, pending.client, profile) - _request_course_sync(pending.employee_id) - return {"employee_id": pending.employee_id} + resolved = _resolved_id(profile, pending.employee_id) + _persist(db, resolved, pending.password, pending.client, profile) + _request_course_sync(resolved) + return {"employee_id": resolved} finally: pending.client.close() @@ -253,7 +320,7 @@ def poll_qr_login(db: Session, attempt_id: str, client_factory=EunivClient) -> d pending.client.close() raise RuntimeError("扫码登录没有返回工号") try: - _persist(db, employee_id, QR_PASSWORD_MARK, pending.client, profile) + _persist(db, employee_id, None, pending.client, profile) _request_course_sync(employee_id) return {"employee_id": employee_id} finally: diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index ceb11c7..43dae7b 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -40,6 +40,9 @@ def fresh_database(): from admin.login_limit import reset reset() + from euniv.login_limit import reset as reset_login + + reset_login() from euniv.proxy_pool import _holds _holds.clear() diff --git a/backend/tests/test_api.py b/backend/tests/test_api.py index 7a07225..2e8d8d0 100644 --- a/backend/tests/test_api.py +++ b/backend/tests/test_api.py @@ -154,6 +154,7 @@ def test_login_stores_password_and_credential_only() -> None: "study_ignore_window", "study_schedule_enabled", "sessions_valid_after", + "password_login_at", } home = client.get("/api/home")