fix: 心跳摘要改为在线 GetEncryptRequest 不再写死密钥
This commit is contained in:
+11
-13
@@ -24,7 +24,7 @@ from datetime import datetime, timezone
|
||||
import httpx
|
||||
from sqlalchemy import select
|
||||
|
||||
from euniv.client import EUNIV, STUDY_API, USER_AGENT, EunivClient, SessionExpired, study_encryption
|
||||
from euniv.client import EUNIV, STUDY_API, USER_AGENT, EunivClient, SessionExpired, _load_cookies
|
||||
from euniv.models import Account, Course
|
||||
from euniv.study_window import window_open
|
||||
|
||||
@@ -100,10 +100,6 @@ def _jitter(seconds: int) -> float:
|
||||
return max(5.0, seconds + delta)
|
||||
|
||||
|
||||
def _scorm_md5(body_json: str) -> str:
|
||||
return study_encryption(body_json)
|
||||
|
||||
|
||||
def _parse_minutes(value: str) -> int:
|
||||
if not value:
|
||||
return 0
|
||||
@@ -194,8 +190,7 @@ class StudySession:
|
||||
proxy=self._proxy,
|
||||
headers={"User-Agent": USER_AGENT},
|
||||
)
|
||||
for name, value, domain, path in self._initial_cookies:
|
||||
self._client.cookies.set(name, value, domain=domain, path=path)
|
||||
_load_cookies(self._client, self._initial_cookies)
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *args: object) -> None:
|
||||
@@ -246,7 +241,11 @@ class StudySession:
|
||||
return resp.json()
|
||||
|
||||
async def get_encrypt_request(self, body_json: str) -> str:
|
||||
return study_encryption(body_json)
|
||||
from euniv.encrypt import fetch_encryption_async
|
||||
assert self._client is not None
|
||||
return await fetch_encryption_async(
|
||||
self._client, body_json, origin=EUNIV, user_agent=USER_AGENT
|
||||
)
|
||||
|
||||
async def submit_video_heartbeat(self, kid: str, pkg_id: str,
|
||||
study_time: int, view_schedule: int) -> dict:
|
||||
@@ -295,11 +294,8 @@ class StudySession:
|
||||
"end": end, "care": True, "deviceId": "",
|
||||
"studyChapterIds": sco_id, "viewSchedule": 0,
|
||||
}
|
||||
if end:
|
||||
encryption = _scorm_md5(json.dumps(param, separators=(",", ":")))
|
||||
else:
|
||||
encrypt_body = json.dumps(param, separators=(",", ":"))
|
||||
encryption = await self.get_encrypt_request(encrypt_body)
|
||||
encrypt_body = json.dumps(param, separators=(",", ":"))
|
||||
encryption = await self.get_encrypt_request(encrypt_body)
|
||||
param["multiple"] = 1
|
||||
param["realHour"] = study_time
|
||||
await self._api("POST", f"{STUDY_API}/v1/study/submit?encryption={encryption}",
|
||||
@@ -332,6 +328,8 @@ class StudySession:
|
||||
headers={"User-Agent": USER_AGENT, "Referer": EUNIV + "/"},
|
||||
)
|
||||
html = resp.text
|
||||
from euniv.encrypt import note_play_html
|
||||
note_play_html(html, EUNIV)
|
||||
|
||||
def _var(name: str, default: str = "") -> str:
|
||||
m = re.search(rf'(?:var\s+)?{name}\s*=\s*["\']?([^"\';\r\n]+)', html)
|
||||
|
||||
+12
-17
@@ -3,7 +3,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import random
|
||||
@@ -102,9 +101,12 @@ def _remember_site(account_id: str, client: httpx.Client) -> None:
|
||||
_site_sessions[account_id] = (time.time(), dumped)
|
||||
|
||||
|
||||
def _load_cookies(client: httpx.Client, dumped: list[tuple[str, str, str, str]]) -> None:
|
||||
def _load_cookies(client: httpx.Client | httpx.AsyncClient, dumped: list[tuple[str, str, str, str]]) -> None:
|
||||
for name, value, domain, path in dumped:
|
||||
client.cookies.set(name, value, domain=domain, path=path)
|
||||
kwargs: dict[str, str] = {"path": path or "/"}
|
||||
if domain:
|
||||
kwargs["domain"] = domain
|
||||
client.cookies.set(name, value, **kwargs)
|
||||
|
||||
|
||||
def _by_closeness(items: list[dict], key: str) -> list[dict]:
|
||||
@@ -365,14 +367,6 @@ def jigsaw_offset(big_png: bytes, small_png: bytes, top: int) -> int:
|
||||
return best_x
|
||||
|
||||
|
||||
STUDY_MD5_KEY = "60db8c0a-72d8-4b8f-bb45-c4c3f29a2696"
|
||||
|
||||
|
||||
def study_encryption(body_json: str) -> str:
|
||||
"""播放页 RteApiSite.js 的摘要:MD5(进度 JSON + 固定 key),与 GetEncryptRequest 相同。"""
|
||||
return hashlib.md5((body_json + STUDY_MD5_KEY).encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
class SessionExpired(RuntimeError):
|
||||
"""学习平台凭证失效,需要重新登录。"""
|
||||
|
||||
@@ -918,6 +912,8 @@ class EunivClient:
|
||||
def course_page_params(self, path: str) -> dict:
|
||||
"""打开播放页,解析 JS 变量。返回 knowledgeType, submitProTimes, validtimeSpan, standardStudyHours, pageSize 等。"""
|
||||
html = self._site_page(path)
|
||||
from euniv.encrypt import note_play_html
|
||||
note_play_html(html, EUNIV)
|
||||
def _var(name: str, default: str = "") -> str:
|
||||
m = re.search(rf'(?:var\s+)?{name}\s*=\s*["\']?([^"\';\r\n]+)', html)
|
||||
return m.group(1).strip() if m else default
|
||||
@@ -954,7 +950,9 @@ class EunivClient:
|
||||
return resp.json()
|
||||
|
||||
def get_encrypt_request(self, body_json: str) -> str:
|
||||
return study_encryption(body_json)
|
||||
from euniv.encrypt import fetch_encryption
|
||||
self._ensure_site()
|
||||
return fetch_encryption(self.client, body_json, origin=EUNIV, user_agent=USER_AGENT)
|
||||
|
||||
def submit_video_heartbeat(self, knowledge_id: str, package_id: str,
|
||||
study_time: int, view_schedule: int,
|
||||
@@ -1038,11 +1036,8 @@ class EunivClient:
|
||||
"studyChapterIds": sco_id,
|
||||
"viewSchedule": 0,
|
||||
}
|
||||
if end:
|
||||
encryption = study_encryption(json.dumps(param, separators=(",", ":")))
|
||||
else:
|
||||
encrypt_body = json.dumps(param, separators=(",", ":"))
|
||||
encryption = self.get_encrypt_request(encrypt_body)
|
||||
encrypt_body = json.dumps(param, separators=(",", ":"))
|
||||
encryption = self.get_encrypt_request(encrypt_body)
|
||||
param["multiple"] = 1
|
||||
param["realHour"] = study_time
|
||||
resp = self._request("POST", f"{STUDY_API}/v1/study/submit?encryption={encryption}",
|
||||
|
||||
@@ -0,0 +1,232 @@
|
||||
"""心跳摘要:按播放页 kng_studytrack_rw.js 向本站 GetEncryptRequest 换取。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
|
||||
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
|
||||
|
||||
_SCRIPT_RE = re.compile(
|
||||
r"""(?:src|href)\s*=\s*["']([^"']*kng_studytrack_rw\.js[^"']*)["']""",
|
||||
re.I,
|
||||
)
|
||||
_PATH_RE = re.compile(r"""url\s*:\s*["']([^"']*GetEncryptRequest)["']""")
|
||||
|
||||
_lock = threading.Lock()
|
||||
_config: dict[str, Any] = {
|
||||
"path": DEFAULT_ENCRYPT_PATH,
|
||||
"js_url": DEFAULT_JS_URL,
|
||||
"loaded_at": 0.0,
|
||||
}
|
||||
|
||||
|
||||
def reset_encrypt_config() -> None:
|
||||
with _lock:
|
||||
_config["path"] = DEFAULT_ENCRYPT_PATH
|
||||
_config["js_url"] = DEFAULT_JS_URL
|
||||
_config["loaded_at"] = 0.0
|
||||
|
||||
|
||||
def encrypt_payload(body_json: str) -> bytes:
|
||||
"""WCF GetEncryptRequest 的 body 是进度 JSON 字符串,不是嵌套对象。
|
||||
|
||||
播放脚本先 JSON.stringify 再拼进 {"body":...};若入参已是字符串,线上实际发出
|
||||
{"body":"<进度 JSON>"}。直接发送嵌套对象会 HTTP 400。
|
||||
"""
|
||||
return json.dumps({"body": body_json}, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
||||
|
||||
|
||||
def encrypt_headers(origin: str, user_agent: str) -> dict[str, str]:
|
||||
return {
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"Content-Type": "text/json",
|
||||
"Origin": origin,
|
||||
"Referer": origin.rstrip("/") + "/",
|
||||
"User-Agent": user_agent,
|
||||
}
|
||||
|
||||
|
||||
def encrypt_path_from_js(js: str) -> str:
|
||||
match = _PATH_RE.search(js or "")
|
||||
return match.group(1) if match else ""
|
||||
|
||||
|
||||
def note_play_html(html: str, origin: str = "") -> None:
|
||||
"""从播放页记下当前 kng_studytrack_rw.js 地址,版本变化时重新读接口路径。"""
|
||||
if not html:
|
||||
return
|
||||
match = _SCRIPT_RE.search(html)
|
||||
if not match:
|
||||
return
|
||||
url = match.group(1).strip()
|
||||
if url.startswith("//"):
|
||||
url = "https:" + url
|
||||
elif url.startswith("/") and origin:
|
||||
url = origin.rstrip("/") + url
|
||||
if not url:
|
||||
return
|
||||
with _lock:
|
||||
if _config["js_url"] != url:
|
||||
_config["js_url"] = url
|
||||
_config["loaded_at"] = 0.0
|
||||
|
||||
|
||||
def encrypt_url(origin: str) -> str:
|
||||
with _lock:
|
||||
path = str(_config["path"] or DEFAULT_ENCRYPT_PATH)
|
||||
if path.startswith("http://") or path.startswith("https://"):
|
||||
return path
|
||||
if not path.startswith("/"):
|
||||
path = "/" + path
|
||||
return origin.rstrip("/") + path
|
||||
|
||||
|
||||
def _update_from_js(js: str) -> None:
|
||||
path = encrypt_path_from_js(js)
|
||||
with _lock:
|
||||
if path:
|
||||
_config["path"] = path
|
||||
_config["loaded_at"] = time.time()
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
def _stale() -> bool:
|
||||
with _lock:
|
||||
return time.time() - float(_config["loaded_at"] or 0) >= _TTL
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
async def refresh_encrypt_config_async(
|
||||
client: httpx.AsyncClient, origin: str, user_agent: str
|
||||
) -> None:
|
||||
if not _stale():
|
||||
return
|
||||
await _fetch_js_config_async(client, origin, user_agent)
|
||||
|
||||
|
||||
def _fetch_js_config(get, origin: str, user_agent: str) -> None:
|
||||
url = _js_url(origin)
|
||||
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
|
||||
except Exception:
|
||||
log.debug("读取播放脚本失败", exc_info=True)
|
||||
with _lock:
|
||||
_config["loaded_at"] = time.time()
|
||||
|
||||
|
||||
async def _fetch_js_config_async(
|
||||
client: httpx.AsyncClient, origin: str, user_agent: str
|
||||
) -> None:
|
||||
url = _js_url(origin)
|
||||
try:
|
||||
resp = await client.get(
|
||||
url, headers={"User-Agent": user_agent, "Referer": origin.rstrip("/") + "/"}
|
||||
)
|
||||
if resp.status_code == 200 and resp.text:
|
||||
_update_from_js(resp.text)
|
||||
return
|
||||
except Exception:
|
||||
log.debug("读取播放脚本失败", exc_info=True)
|
||||
with _lock:
|
||||
_config["loaded_at"] = time.time()
|
||||
|
||||
|
||||
def _as_encrypt_object(data: Any, depth: int = 0) -> Any:
|
||||
if depth > 4:
|
||||
return data
|
||||
if isinstance(data, dict):
|
||||
if any(key in data for key in ("Status", "status", "Data", "data")):
|
||||
return data
|
||||
for key in ("d", "GetEncryptRequestResult", "body"):
|
||||
if key in data:
|
||||
return _as_encrypt_object(data[key], depth + 1)
|
||||
return data
|
||||
if isinstance(data, str):
|
||||
text = data.strip()
|
||||
if not text:
|
||||
return data
|
||||
try:
|
||||
return _as_encrypt_object(json.loads(text), depth + 1)
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
if "'" in text:
|
||||
try:
|
||||
return _as_encrypt_object(json.loads(text.replace("'", '"')), depth + 1)
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
return data
|
||||
|
||||
|
||||
def parse_encrypt_response(resp: httpx.Response) -> str:
|
||||
raw = (resp.text or "").strip()
|
||||
if resp.status_code >= 400:
|
||||
raise RuntimeError(f"GetEncryptRequest HTTP {resp.status_code}: {raw[:200]}")
|
||||
try:
|
||||
data: Any = resp.json()
|
||||
except Exception:
|
||||
data = raw
|
||||
obj = _as_encrypt_object(data)
|
||||
if isinstance(obj, dict):
|
||||
status = str(obj.get("Status") or obj.get("status") or "")
|
||||
digest = obj.get("Data") if obj.get("Data") not in (None, "") else obj.get("data")
|
||||
if status == "OK" and digest:
|
||||
return str(digest).strip()
|
||||
raise RuntimeError(f"GetEncryptRequest 失败: {raw[:200]}")
|
||||
|
||||
|
||||
def fetch_encryption(
|
||||
client: httpx.Client, body_json: str, *, origin: str, user_agent: str
|
||||
) -> str:
|
||||
refresh_encrypt_config(client, origin, user_agent)
|
||||
return _post_encryption(client.post, body_json, origin, user_agent)
|
||||
|
||||
|
||||
async def fetch_encryption_async(
|
||||
client: httpx.AsyncClient, body_json: str, *, origin: str, user_agent: str
|
||||
) -> str:
|
||||
await refresh_encrypt_config_async(client, origin, user_agent)
|
||||
return await _post_encryption_async(client, body_json, origin, user_agent)
|
||||
|
||||
|
||||
def _post_encryption(post, body_json: str, origin: str, user_agent: str) -> str:
|
||||
url = encrypt_url(origin)
|
||||
headers = encrypt_headers(origin, user_agent)
|
||||
resp = post(url, content=encrypt_payload(body_json), headers=headers)
|
||||
return parse_encrypt_response(resp)
|
||||
|
||||
|
||||
async def _post_encryption_async(
|
||||
client: httpx.AsyncClient, body_json: str, origin: str, user_agent: str
|
||||
) -> str:
|
||||
url = encrypt_url(origin)
|
||||
headers = encrypt_headers(origin, user_agent)
|
||||
resp = await client.post(url, content=encrypt_payload(body_json), headers=headers)
|
||||
return parse_encrypt_response(resp)
|
||||
@@ -5,7 +5,6 @@ import pytest
|
||||
from datetime import datetime
|
||||
|
||||
from euniv.autostudy import HoursWatcher, _parse_minutes, _study_video, wait_stop
|
||||
from euniv.client import study_encryption
|
||||
from euniv.proxy import ProxyError, build_proxy_url, parse_proxy
|
||||
from euniv.study_window import CN_TZ, StudyWindowError, validate_start, window_open
|
||||
|
||||
@@ -166,31 +165,6 @@ def test_video_skip_already_complete_does_not_refresh() -> None:
|
||||
asyncio.run(main())
|
||||
|
||||
|
||||
def test_study_encryption_matches_get_encrypt_request() -> None:
|
||||
import json
|
||||
|
||||
body = json.dumps(
|
||||
{
|
||||
"knowledgeId": "6d16a38ebdfe455fbb1e86ec0c0c35d7",
|
||||
"masterId": "",
|
||||
"masterType": "",
|
||||
"packageId": "",
|
||||
"pageSize": 1,
|
||||
"studySize": 1,
|
||||
"studyTime": 120,
|
||||
"type": 1,
|
||||
"offLine": False,
|
||||
"end": False,
|
||||
"care": True,
|
||||
"deviceId": "",
|
||||
"studyChapterIds": "",
|
||||
"viewSchedule": 1,
|
||||
},
|
||||
separators=(",", ":"),
|
||||
)
|
||||
assert study_encryption(body) == "ba119ee448648d9f8f046d11c426afa4"
|
||||
|
||||
|
||||
class _Start:
|
||||
def __init__(self, day: int, hour: int = 16, minute: int = 0, second: int = 0) -> None:
|
||||
self.study_start_day = day
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import inspect
|
||||
|
||||
import httpx
|
||||
|
||||
from euniv import autostudy as autostudy_mod
|
||||
from euniv import client as client_mod
|
||||
from euniv.encrypt import (
|
||||
encrypt_path_from_js,
|
||||
encrypt_payload,
|
||||
fetch_encryption,
|
||||
note_play_html,
|
||||
parse_encrypt_response,
|
||||
reset_encrypt_config,
|
||||
)
|
||||
|
||||
|
||||
def test_encrypt_payload_wraps_progress_json_as_string() -> None:
|
||||
body = '{"knowledgeId":"abc","end":false}'
|
||||
assert encrypt_payload(body) == b'{"body":"{\\"knowledgeId\\":\\"abc\\",\\"end\\":false}"}'
|
||||
|
||||
|
||||
def test_parse_encrypt_response_accepts_wcf_shapes() -> None:
|
||||
digest = "a" * 32
|
||||
as_object = httpx.Response(200, json={"Status": "OK", "Data": digest})
|
||||
assert parse_encrypt_response(as_object) == digest
|
||||
|
||||
as_string = httpx.Response(200, json='{"Status":"OK","Data":"%s"}' % digest)
|
||||
assert parse_encrypt_response(as_string) == digest
|
||||
|
||||
quoted = httpx.Response(200, text="{'Status':'OK','Data':'%s'}" % digest)
|
||||
assert parse_encrypt_response(quoted) == digest
|
||||
|
||||
wrapped = httpx.Response(200, json={"d": '{"Status":"OK","Data":"%s"}' % digest})
|
||||
assert parse_encrypt_response(wrapped) == digest
|
||||
|
||||
live = httpx.Response(
|
||||
200,
|
||||
text='"{\'Status\':\'OK\',\'Data\':\'%s\'}"' % digest,
|
||||
headers={"content-type": "application/json; charset=utf-8"},
|
||||
)
|
||||
assert parse_encrypt_response(live) == digest
|
||||
|
||||
|
||||
def test_note_play_html_and_js_path() -> None:
|
||||
reset_encrypt_config()
|
||||
html = (
|
||||
'<script src="https://staticbdc1.yunxuetang.cn/SystemFiles/Js/'
|
||||
'kng_studytrack_rw.js?v=10.11.45"></script>'
|
||||
)
|
||||
note_play_html(html, "https://euniv.zte.com.cn")
|
||||
js = (
|
||||
'jQuery.ajax({type:"POST",contentType:"text/json",'
|
||||
'url:"/kng/services/KngComService.svc/GetEncryptRequest",data:arr})'
|
||||
)
|
||||
assert encrypt_path_from_js(js) == "/kng/services/KngComService.svc/GetEncryptRequest"
|
||||
|
||||
|
||||
def test_fetch_encryption_posts_player_body() -> None:
|
||||
reset_encrypt_config()
|
||||
seen: dict[str, bytes] = {}
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
if "kng_studytrack_rw.js" in str(request.url):
|
||||
return httpx.Response(
|
||||
200,
|
||||
text='url:"/kng/services/KngComService.svc/GetEncryptRequest"',
|
||||
)
|
||||
seen["content_type"] = request.headers["content-type"].encode()
|
||||
seen["body"] = request.content
|
||||
return httpx.Response(200, json={"Status": "OK", "Data": "b" * 32})
|
||||
|
||||
with httpx.Client(transport=httpx.MockTransport(handler)) as client:
|
||||
digest = fetch_encryption(
|
||||
client,
|
||||
'{"knowledgeId":"k1"}',
|
||||
origin="https://euniv.zte.com.cn",
|
||||
user_agent="UA",
|
||||
)
|
||||
assert digest == "b" * 32
|
||||
assert seen["content_type"] == b"text/json"
|
||||
assert seen["body"] == b'{"body":"{\\"knowledgeId\\":\\"k1\\"}"}'
|
||||
|
||||
|
||||
def test_client_has_no_hardcoded_study_md5_key() -> None:
|
||||
for module in (client_mod, autostudy_mod):
|
||||
source = inspect.getsource(module)
|
||||
assert "60db8c0a-72d8-4b8f-bb45-c4c3f29a2696" not in source
|
||||
assert "STUDY_MD5_KEY" not in source
|
||||
assert "study_encryption" not in source
|
||||
Reference in New Issue
Block a user