fix: 收紧登录请求和播放脚本地址,并删掉同步学习接口

This commit is contained in:
2026-11-16 11:48:24 +08:00
parent ac9a507c80
commit 86a7477fab
2 changed files with 153 additions and 277 deletions
+79 -14
View File
@@ -2,12 +2,14 @@
from __future__ import annotations
import asyncio
import json
import logging
import re
import threading
import time
from typing import Any
from urllib.parse import urlparse
import httpx
@@ -16,6 +18,11 @@ log = logging.getLogger(__name__)
DEFAULT_ENCRYPT_PATH = "/kng/services/KngComService.svc/GetEncryptRequest"
DEFAULT_JS_URL = "https://staticbdc1.yunxuetang.cn/SystemFiles/Js/kng_studytrack_rw.js"
_TTL = 6 * 3600
_FAIL_COOLDOWN = 5 * 60
_SCRIPT_HOSTS = frozenset({
"euniv.zte.com.cn",
"staticbdc1.yunxuetang.cn",
})
_SCRIPT_RE = re.compile(
r"""(?:src|href)\s*=\s*["']([^"']*kng_studytrack_rw\.js[^"']*)["']""",
@@ -24,10 +31,12 @@ _SCRIPT_RE = re.compile(
_PATH_RE = re.compile(r"""url\s*:\s*["']([^"']*GetEncryptRequest)["']""")
_lock = threading.Lock()
_fetch_guard = threading.Lock()
_config: dict[str, Any] = {
"path": DEFAULT_ENCRYPT_PATH,
"js_url": DEFAULT_JS_URL,
"loaded_at": 0.0,
"retry_at": 0.0,
}
@@ -36,6 +45,15 @@ def reset_encrypt_config() -> None:
_config["path"] = DEFAULT_ENCRYPT_PATH
_config["js_url"] = DEFAULT_JS_URL
_config["loaded_at"] = 0.0
_config["retry_at"] = 0.0
def _script_host_allowed(url: str) -> bool:
parsed = urlparse(url)
if parsed.scheme != "https" or parsed.username or parsed.password:
return False
host = (parsed.hostname or "").rstrip(".").lower()
return host in _SCRIPT_HOSTS
def encrypt_payload(body_json: str) -> bytes:
@@ -76,17 +94,25 @@ def note_play_html(html: str, origin: str = "") -> None:
url = origin.rstrip("/") + url
if not url:
return
if not _script_host_allowed(url):
log.warning("播放脚本地址不在允许的主机上")
return
with _lock:
if _config["js_url"] != url:
_config["js_url"] = url
_config["loaded_at"] = 0.0
_config["retry_at"] = 0.0
def encrypt_url(origin: str) -> str:
with _lock:
path = str(_config["path"] or DEFAULT_ENCRYPT_PATH)
if path.startswith("//"):
path = "https:" + path
if path.startswith("http://") or path.startswith("https://"):
return path
if _script_host_allowed(path):
return path
path = DEFAULT_ENCRYPT_PATH
if not path.startswith("/"):
path = "/" + path
return origin.rstrip("/") + path
@@ -94,31 +120,52 @@ def encrypt_url(origin: str) -> str:
def _update_from_js(js: str) -> None:
path = encrypt_path_from_js(js)
if path.startswith("//"):
path = "https:" + path
if path.startswith("http://") or path.startswith("https://"):
if not _script_host_allowed(path):
log.warning("播放脚本里的接口地址不在允许的主机上")
path = ""
with _lock:
if path:
_config["path"] = path
_config["loaded_at"] = time.time()
_config["retry_at"] = 0.0
def _js_url(origin: str) -> str:
with _lock:
url = str(_config["js_url"] or DEFAULT_JS_URL)
if url.startswith("//"):
return "https:" + url
if url.startswith("/") and origin:
return origin.rstrip("/") + url
return url
url = "https:" + url
elif url.startswith("/") and origin:
url = origin.rstrip("/") + url
if _script_host_allowed(url):
return url
return DEFAULT_JS_URL
def _stale() -> bool:
now = time.time()
with _lock:
return time.time() - float(_config["loaded_at"] or 0) >= _TTL
retry_at = float(_config.get("retry_at") or 0)
if retry_at and now < retry_at:
return False
return now - float(_config["loaded_at"] or 0) >= _TTL
def _note_fetch_failure() -> None:
with _lock:
_config["retry_at"] = time.time() + _FAIL_COOLDOWN
def refresh_encrypt_config(client: httpx.Client, origin: str, user_agent: str) -> None:
if not _stale():
return
_fetch_js_config(client.get, origin, user_agent)
with _fetch_guard:
if not _stale():
return
_fetch_js_config(client.get, origin, user_agent)
async def refresh_encrypt_config_async(
@@ -126,26 +173,44 @@ async def refresh_encrypt_config_async(
) -> None:
if not _stale():
return
await _fetch_js_config_async(client, origin, user_agent)
while True:
if not _stale():
return
if _fetch_guard.acquire(blocking=False):
break
await asyncio.sleep(0.02)
try:
if _stale():
await _fetch_js_config_async(client, origin, user_agent)
finally:
_fetch_guard.release()
def _fetch_js_config(get, origin: str, user_agent: str) -> None:
url = _js_url(origin)
if not _script_host_allowed(url):
log.warning("播放脚本地址不在允许的主机上")
_note_fetch_failure()
return
try:
resp = get(url, headers={"User-Agent": user_agent, "Referer": origin.rstrip("/") + "/"})
if resp.status_code == 200 and resp.text:
_update_from_js(resp.text)
return
log.warning("读取播放脚本失败:HTTP %s", getattr(resp, "status_code", ""))
except Exception:
log.debug("读取播放脚本失败", exc_info=True)
with _lock:
_config["loaded_at"] = time.time()
log.warning("读取播放脚本失败", exc_info=True)
_note_fetch_failure()
async def _fetch_js_config_async(
client: httpx.AsyncClient, origin: str, user_agent: str
) -> None:
url = _js_url(origin)
if not _script_host_allowed(url):
log.warning("播放脚本地址不在允许的主机上")
_note_fetch_failure()
return
try:
resp = await client.get(
url, headers={"User-Agent": user_agent, "Referer": origin.rstrip("/") + "/"}
@@ -153,10 +218,10 @@ async def _fetch_js_config_async(
if resp.status_code == 200 and resp.text:
_update_from_js(resp.text)
return
log.warning("读取播放脚本失败:HTTP %s", resp.status_code)
except Exception:
log.debug("读取播放脚本失败", exc_info=True)
with _lock:
_config["loaded_at"] = time.time()
log.warning("读取播放脚本失败", exc_info=True)
_note_fetch_failure()
def _as_encrypt_object(data: Any, depth: int = 0) -> Any: