修复(CK检测): 统一斗鱼CK有效性检测入口并禁止非鉴权接口覆盖状态

This commit is contained in:
yml
2026-11-26 17:38:50 +08:00
parent 3431705096
commit 7a20c63464
9 changed files with 489 additions and 76 deletions
@@ -28,10 +28,12 @@ from .account_work_queue import (
complete_account_work,
fail_account_work,
)
from .cookie_check_service import check_douyu_cookie
from .douyu_account_probe import (
config_mapping,
persist_probe_result,
probe_account,
verify_account_session,
)
from .douyu_activity_query import activity_client
from .douyu_read_gateway import StorehomeSnapshot, fetch_storehome_snapshot
@@ -56,6 +58,34 @@ ACCOUNT_SYNC_WORK_TYPES = (
)
def _ensure_live_session(
db: Session,
account: Account,
*,
work_type: str,
session_checker: Callable[[str], dict[str, Any]] | None,
) -> None:
if session_checker is None:
return
session = verify_account_session(
db,
account,
source=f"account_work.{work_type}",
checker=session_checker,
max_age_seconds=300,
record_event=False,
commit=False,
)
status = str(session.get("status") or "")
if status != "valid":
prefix = (
"账号 CK 已失效,请重新登录"
if status == "invalid"
else "账号 CK 状态无法确认"
)
raise RuntimeError(f"{prefix}:{session.get('message') or '请稍后重试'}")
def _execute_storehome_sync(
db: Session,
*,
@@ -63,11 +93,18 @@ def _execute_storehome_sync(
item: AccountWorkItem,
client_factory: Callable[[str], Any],
snapshot_fetcher: Callable[..., StorehomeSnapshot],
session_checker: Callable[[str], dict[str, Any]] | None = check_douyu_cookie,
) -> dict[str, Any]:
if not account.cookie:
raise RuntimeError("账号没有可用 CK,不能同步商品能力")
if account.ck_check_status in {"invalid", "manual"}:
raise RuntimeError(f"账号 CK 状态为 {account.ck_check_status},暂不能同步商品能力")
_ensure_live_session(
db,
account,
work_type=item.work_type,
session_checker=session_checker,
)
config = ensure_douyu_config(db)
manual_id = str(getattr(config, "manual_id", "") or "")
rid = str(getattr(config, "rid", "") or "")
@@ -160,17 +197,25 @@ def _execute_profile_sync(
item: AccountWorkItem,
client_factory: Callable[[str], Any],
probe_fetcher: Callable[..., dict[str, Any]],
session_checker: Callable[[str], dict[str, Any]] | None = check_douyu_cookie,
) -> dict[str, Any]:
if not account.cookie:
raise RuntimeError("账号没有可用 CK,不能同步账号资料")
if account.ck_check_status in {"invalid", "manual"}:
raise RuntimeError(f"账号 CK 状态为 {account.ck_check_status},暂不能同步")
_ensure_live_session(
db,
account,
work_type=item.work_type,
session_checker=session_checker,
)
config = ensure_douyu_config(db)
client = client_factory(account.cookie)
probe = probe_fetcher(
account,
config,
client=client,
session_checker=None,
**_profile_probe_kwargs(item.work_type, config),
)
errors = probe.get("errors") or {}
@@ -209,6 +254,7 @@ def _execute_exchange_records_sync(
account: Account,
item: AccountWorkItem,
client_factory: Callable[[str], Any],
session_checker: Callable[[str], dict[str, Any]] | None = check_douyu_cookie,
) -> dict[str, Any]:
if not account.cookie:
raise RuntimeError("账号没有可用 CK,不能同步兑换记录")
@@ -216,6 +262,12 @@ def _execute_exchange_records_sync(
raise RuntimeError(
f"账号 CK 状态为 {account.ck_check_status},暂不能同步兑换记录"
)
_ensure_live_session(
db,
account,
work_type=item.work_type,
session_checker=session_checker,
)
config = ensure_douyu_config(db)
result = sync_exchange_records(
db,
@@ -240,6 +292,7 @@ def execute_account_work_item(
client_factory: Callable[[str], Any] = activity_client,
snapshot_fetcher: Callable[..., StorehomeSnapshot] = fetch_storehome_snapshot,
probe_fetcher: Callable[..., dict[str, Any]] = probe_account,
session_checker: Callable[[str], dict[str, Any]] | None = check_douyu_cookie,
) -> dict[str, Any]:
"""在一个短事务中执行单条账号维护工作。"""
session = session_factory()
@@ -258,6 +311,7 @@ def execute_account_work_item(
item=item,
client_factory=client_factory,
snapshot_fetcher=snapshot_fetcher,
session_checker=session_checker,
)
elif item.work_type == WORK_EXCHANGE_RECORDS_SYNC:
result = _execute_exchange_records_sync(
@@ -265,6 +319,7 @@ def execute_account_work_item(
account=account,
item=item,
client_factory=client_factory,
session_checker=session_checker,
)
elif item.work_type in ACCOUNT_SYNC_WORK_TYPES:
result = _execute_profile_sync(
@@ -273,6 +328,7 @@ def execute_account_work_item(
item=item,
client_factory=client_factory,
probe_fetcher=probe_fetcher,
session_checker=session_checker,
)
else:
raise RuntimeError(f"不支持的工作类型: {item.work_type}")
@@ -353,6 +409,7 @@ def run_account_sync_queue(
client_factory: Callable[[str], Any] = activity_client,
snapshot_fetcher: Callable[..., StorehomeSnapshot] = fetch_storehome_snapshot,
probe_fetcher: Callable[..., dict[str, Any]] = probe_account,
session_checker: Callable[[str], dict[str, Any]] | None = check_douyu_cookie,
) -> dict[str, Any]:
"""领取少量到期工作并通过独立账号同步槽执行。"""
moment = now or datetime.now(UTC)
@@ -391,6 +448,7 @@ def run_account_sync_queue(
client_factory=client_factory,
snapshot_fetcher=snapshot_fetcher,
probe_fetcher=probe_fetcher,
session_checker=session_checker,
)
if future is not None:
futures[future] = work_id
+101 -44
View File
@@ -1,6 +1,7 @@
"""斗鱼 Cookie 有效性检测服务。"""
from datetime import UTC, datetime
from typing import Any
import requests
@@ -25,18 +26,78 @@ AUTH_FAILURE_MARKERS = (
)
def _has_auth_failure(message: str) -> bool:
lower = (message or "").lower()
return any(marker in message or marker in lower for marker in AUTH_FAILURE_MARKERS)
def _format_request_error(exc: Exception) -> str:
text = str(exc or "")
lower = text.lower()
if "proxyerror" in lower or "unable to connect to proxy" in lower:
return "请求失败: 代理连接失败"
if "timed out" in lower or "timeouterror" in lower:
return "请求失败: 网络读取超时"
if "max retries exceeded" in lower or "connection" in lower:
return "请求失败: 网络连接异常"
return f"请求失败: {text[:80]}"
def _fetch_cookie_endpoint(
url: str,
*,
params: dict[str, str],
referer: str,
cookie: str,
attempts: int = 2,
) -> tuple[dict[str, Any] | None, str]:
last_error = ""
for attempt in range(max(1, attempts)):
try:
response = requests.get(
url,
params=params,
headers={
"User-Agent": CHECK_UA,
"Accept": "application/json, text/plain, */*",
"Referer": referer,
"Cookie": cookie,
},
timeout=(5, 10),
)
data = response.json()
if isinstance(data, dict):
return data, ""
return None, "响应格式异常"
except requests.RequestException as exc:
last_error = _format_request_error(exc)
if attempt + 1 < attempts:
continue
except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
last_error = _format_request_error(exc)
break
return None, last_error or "请求失败"
def classify_douyu_cookie_result(result: dict) -> str:
"""把检测结果分成 valid / invalid / error,区分失效与暂时查不到。"""
if result.get("valid"):
return "valid"
message = str(result.get("message") or "")
if any(marker in message for marker in AUTH_FAILURE_MARKERS):
if _has_auth_failure(message):
return "invalid"
return "error"
def check_douyu_cookie(cookie: str) -> dict:
"""检测斗鱼 Cookie 有效性,鱼丸与等级接口均通过才算有效。"""
"""全系统唯一的斗鱼 Cookie 有效性检测实现。
同时校验强鉴权的鱼丸接口与等级接口:
1. 任一接口明确返回未登录/登陆异常等鉴权失败时判定失效;
2. 双接口均通过时有效;若一个强鉴权接口已确认登录正常、另一端仅偶发网络超时(无鉴权失败),
经过重试仍未拿到另一端响应时也允许降级判定有效,避免单端抖动误杀正常账号;
3. 两端均网络异常(无鉴权失败文案)时判定为状态无法确认(error),不误判 CK 失效。
"""
checked_at = datetime.now(UTC)
base = {
"checked_at": checked_at,
@@ -50,19 +111,14 @@ def check_douyu_cookie(cookie: str) -> dict:
fish_ok = False
fish_msg = ""
fish_ball = None
try:
fish_data = requests.get(
FISH_BALL_API,
params={"appCode": "YJTX"},
headers={
"User-Agent": CHECK_UA,
"Accept": "application/json, text/plain, */*",
"Referer": "https://www.douyu.com/member/walletcenter",
"Cookie": cookie,
},
timeout=(5, 10),
).json()
if isinstance(fish_data, dict) and fish_data.get("error") in (0, "0"):
fish_data, fish_err = _fetch_cookie_endpoint(
FISH_BALL_API,
params={"appCode": "YJTX"},
referer="https://www.douyu.com/member/walletcenter",
cookie=cookie,
)
if fish_data is not None:
if fish_data.get("error") in (0, "0"):
fish_ok = True
fish_ball = (
(fish_data.get("data") or {}).get("count")
@@ -70,48 +126,49 @@ def check_douyu_cookie(cookie: str) -> dict:
else None
)
else:
fish_msg = (
str(fish_data.get("msg") or fish_data.get("error") or "响应异常")
if isinstance(fish_data, dict)
else "响应异常"
)
except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
fish_msg = f"请求失败: {exc}"
fish_msg = str(fish_data.get("msg") or fish_data.get("error") or "响应异常")
else:
fish_msg = fish_err
level_ok = False
level_msg = ""
nickname = None
level = None
try:
level_data = requests.get(
USER_LEVEL_API,
params={"rid": "0"},
headers={
"User-Agent": CHECK_UA,
"Accept": "application/json, text/plain, */*",
"Referer": "https://www.douyu.com/pages/ord-user-level?clientType=web",
"Cookie": cookie,
},
timeout=(5, 10),
).json()
if isinstance(level_data, dict) and level_data.get("error") in (0, "0"):
level_data, level_err = _fetch_cookie_endpoint(
USER_LEVEL_API,
params={"rid": "0"},
referer="https://www.douyu.com/pages/ord-user-level?clientType=web",
cookie=cookie,
)
if level_data is not None:
if level_data.get("error") in (0, "0"):
level_ok = True
info_raw = level_data.get("data")
info = info_raw if isinstance(info_raw, dict) else {}
nickname = str(info.get("nn") or "") or None
level = info.get("lv")
else:
level_msg = (
str(level_data.get("msg") or level_data.get("error") or "响应异常")
if isinstance(level_data, dict)
else "响应异常"
)
except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
level_msg = f"请求失败: {exc}"
level_msg = str(level_data.get("msg") or level_data.get("error") or "响应异常")
else:
level_msg = level_err
valid = fish_ok and level_ok
if valid:
fish_auth_failed = not fish_ok and _has_auth_failure(fish_msg)
level_auth_failed = not level_ok and _has_auth_failure(level_msg)
if fish_auth_failed or level_auth_failed:
valid = False
elif fish_ok and level_ok:
valid = True
elif fish_ok or level_ok:
# 一端强鉴权接口明确返回有效,另一端仅网络抖动/非鉴权异常
valid = True
else:
valid = False
if fish_ok and level_ok:
message = "有效"
elif valid:
detail_msg = level_msg if fish_ok else fish_msg
message = f"有效(单端网络波动降级通过: {detail_msg})"
else:
message = ";".join(
[
+92 -6
View File
@@ -566,6 +566,8 @@ def _derive_session(
"message": "活动接口可用",
"checked_at": _now().isoformat(),
"detail": {},
# 活动接口(如 storehome / getUserInfo)不完整鉴权,绝不允许直接反写账号 CK 为 valid。
"authoritative": False,
}
text = ";".join(errors.values())
if any(marker in text for marker in ("登录", "Cookie", "重定向")):
@@ -579,9 +581,88 @@ def _derive_session(
"message": _text(text or "没有可用查询结果"),
"checked_at": _now().isoformat(),
"detail": {},
"authoritative": False,
}
def _utc_aware(dt: datetime | None) -> datetime | None:
if dt is None:
return None
return dt if dt.tzinfo else dt.replace(tzinfo=UTC)
def verify_account_session(
db: Session,
account: Account,
*,
source: str,
current: User | None = None,
checker: Callable[[str], dict[str, Any]] | None = None,
max_age_seconds: int | None = None,
record_event: bool = False,
commit: bool = False,
) -> dict[str, Any]:
"""全系统统一的账号 CK 检测与写库入口。"""
cookie = str(account.cookie or "").strip()
if not cookie:
return {
"status": SESSION_UNVERIFIED,
"message": "账号没有可用登录 Cookie",
"checked_at": _now().isoformat(),
"detail": {},
}
now = _now()
if max_age_seconds is not None and max_age_seconds > 0:
checked_at = _utc_aware(account.ck_checked_at)
stored_msg = (
str((account.ck_check_result or {}).get("message") or "")
if isinstance(account.ck_check_result, dict)
else ""
)
if (
account.ck_check_status == SESSION_VALID
and checked_at is not None
and stored_msg != "活动接口可用"
and (now - checked_at).total_seconds() <= max_age_seconds
):
return {
"status": SESSION_VALID,
"message": stored_msg or "有效",
"checked_at": checked_at.isoformat(),
"detail": dict(account.ck_check_result or {}),
}
session = probe_session(cookie, checker=checker or check_douyu_cookie)
detail = session.get("detail") if isinstance(session.get("detail"), dict) else {}
persist_probe_result(
db,
account,
{
"probe_id": f"{source}:{now.timestamp()}:{account.id or 0}",
"identity": {
"uid": account.uid,
"username": account.username,
"nickname": detail.get("nickname") or "",
"nickname_source": "session",
},
"session": session,
"elite": {},
"eligibility": {},
"roles": {},
"gold": {},
"goods": {},
"errors": {},
},
current=current,
source=source,
record_event=record_event,
commit=commit,
update_session=True,
)
return session
def _identity_result(
account: Account,
cookie: str,
@@ -684,7 +765,7 @@ def probe_account(
),
)
if session_checker is _DEFAULT_SESSION_CHECKER:
session_checker = None if client is not None else check_douyu_cookie
session_checker = check_douyu_cookie
session = (
probe_session(cookie, checker=session_checker)
if callable(session_checker)
@@ -1048,11 +1129,15 @@ def persist_probe_result(
session = probe.get("session") or {}
session_status = str(session.get("status") or "")
if update_session and session_status in {
SESSION_VALID,
SESSION_INVALID,
SESSION_ERROR,
}:
session_message = str(session.get("message") or "")
is_authoritative_valid = (
session_status == SESSION_VALID
and session.get("authoritative", True) is not False
and session_message != "活动接口可用"
)
if update_session and (
is_authoritative_valid or session_status in {SESSION_INVALID, SESSION_ERROR}
):
detail = (
session.get("detail") if isinstance(session.get("detail"), dict) else {}
)
@@ -1279,4 +1364,5 @@ __all__ = [
"resolve_esports_role",
"resolve_peace_role",
"update_identity_from_cookie",
"verify_account_session",
]
+5 -25
View File
@@ -12,7 +12,7 @@ from core.douyu import DouyuActivityError
from ..database import WorkerSessionLocal
from ..models import DouyuTask
from .cookie_check_service import check_douyu_cookie
from .douyu_account_probe import persist_probe_result, probe_session
from .douyu_account_probe import verify_account_session
from .douyu_runner_bind import BindMixin
from .douyu_runner_core import ( # noqa: F401 (douyu_batch_registry 供 routers 重导出)
DouyuBatchRunnerCore,
@@ -134,35 +134,15 @@ class DouyuBatchRunner(
)
return
cookie_check = probe_session(cookie, checker=check_douyu_cookie)
ck_verdict = str(cookie_check["status"])
# 执行前的这次检测同样要写结论、由好变坏记事件、重算状态。
persist_probe_result(
cookie_check = verify_account_session(
worker_db,
account,
{
"probe_id": f"task-preflight:{task.id}",
"identity": {
"uid": account.uid,
"username": account.username,
"nickname": (
(cookie_check.get("detail") or {}).get("nickname") or ""
),
"nickname_source": "session",
},
"session": cookie_check,
"elite": {},
"eligibility": {},
"roles": {},
"gold": {},
"goods": {},
"errors": {},
},
source="douyu_task.preflight",
checker=check_douyu_cookie,
record_event=False,
commit=False,
commit=True,
)
worker_db.commit()
ck_verdict = str(cookie_check["status"])
if ck_verdict != "valid":
prefix = (
"Cookie 已失效,请重新登录"
@@ -327,6 +327,8 @@ def _capability_candidate_query(
),
case((Account.ck_check_status == "valid", 0), else_=1),
case((Account.status == "active", 0), else_=1),
Account.ck_checked_at.is_(None).asc(),
Account.ck_checked_at.desc(),
case((Account.elite_opened.is_(True), 0), else_=1),
case(
(Account.points >= max(0, int(required_points)), 0),
@@ -203,10 +203,26 @@ def refresh_exchange_eligibility(
probe = probe_account(
account,
config_mapping(config),
session_checker=None,
with_elite_role=False,
with_eligibility=True,
)
session = probe.get("session") or {}
session_status = str(session.get("status") or "")
if session_status != "valid":
persist_probe_result(
db,
account,
probe,
current=current,
source="platform.exchange_eligibility",
record_event=True,
)
prefix = (
"账号 CK 已失效,请重新登录"
if session_status == "invalid"
else "账号 CK 状态无法确认"
)
raise RuntimeError(f"{prefix}:{session.get('message') or '请稍后重试'}")
if (probe.get("elite") or {}).get("status") != CAPABILITY_OK:
raise RuntimeError(
(probe.get("errors") or {}).get("elite") or "精英宝典状态查询失败"