Compare commits

...
5 Commits
Author SHA1 Message Date
yml2213 95ad900ef0 统一推送前Python代码格式 2026-09-02 18:11:41 +08:00
yml2213 aaaa568916 修正活动WSS会话guid一致性 2026-09-02 18:07:31 +08:00
yml2213 92ba6cbc62 闭合QIMEI h38兼容键 2026-09-02 17:51:12 +08:00
yml2213 1f3773de28 修正QIMEI UUID42随机段生成 2026-09-02 17:15:06 +08:00
yml2213 17ee943753 复刻QIMEI UUID42并默认使用无头浏览器 2026-09-02 16:59:46 +08:00
16 changed files with 1997 additions and 166 deletions
@@ -0,0 +1,188 @@
diff --git a/core/huya/elite_session.py b/core/huya/elite_session.py
index 31f2449..0eb740c 100644
--- a/core/huya/elite_session.py
+++ b/core/huya/elite_session.py
@@ -94,6 +94,13 @@ class HuyaEliteWssSession:
)
if not initialized:
raise RuntimeError(f"虎牙 {kind} WSS 初始化失败")
+ if kind == "activity" and self.client._launch_guid:
+ # wsLaunch 的 sGuid 是当前连接的真实会话值,供后续业务 Cookie
+ # 与 HTTP baseinfo 继续复用,避免沿用登录时的旧 guid。
+ self.cookie = self.client._cookie_with_guid(
+ self.cookie, self.client._launch_guid
+ )
+ self.guid = self.client._launch_guid
except Exception:
self.close()
raise
diff --git a/core/huya/wss_client.py b/core/huya/wss_client.py
index 929c622..c665afd 100644
--- a/core/huya/wss_client.py
+++ b/core/huya/wss_client.py
@@ -26,6 +26,7 @@ from typing import Any, cast
import websockets
+from .cookie_utils import cookie_pairs, normalize_cookie_pairs
from .frame_decoder import _decode_taf_struct, _truncate, format_wss_log
from .taf_protocol import TafInputStream, TafOutputStream, TafStruct, TafType
from .wup_protocol import WupRequest, WupResponse
@@ -192,6 +193,26 @@ class HuyaWssClient:
return normalized
return f"{normalized}; {cookie}"
+ @staticmethod
+ def _cookie_with_guid(cookie: str, guid: str) -> str:
+ """用当前 WSS 会话的 sGuid 替换 Cookie 中的旧 guid。"""
+ value = str(guid or "").strip()
+ if not value:
+ return cookie or ""
+ pairs = cookie_pairs(cookie)
+ replaced = False
+ normalized: list[tuple[str, str]] = []
+ for key, item_value in pairs:
+ if key == "guid":
+ if not replaced:
+ normalized.append((key, value))
+ replaced = True
+ continue
+ normalized.append((key, item_value))
+ if not replaced:
+ normalized.append(("guid", value))
+ return normalize_cookie_pairs(normalized)
+
@staticmethod
def _build_biz_user(uid: int, cookie: str):
"""构造 WSS 业务 UserId(HAR 实证:guid 为空,cookie 不额外加前缀)"""
@@ -389,7 +410,12 @@ class HuyaWssClient:
if launch_rsp is None:
self.logger("[WSS] 活动 wsLaunch 无响应")
return False
- await self.send_auth(uid, cookie, sequence=SEQ_ACTIVITY_BIZ)
+ # wsLaunch 会为当前连接签发新的 sGuid。AUTH、getConfig 和后续业务
+ # 请求必须使用同一个值;登录 Cookie 里的旧 guid 不能继续复用。
+ if self._launch_guid:
+ cookie = self._cookie_with_guid(cookie, self._launch_guid)
+ guid = self._launch_guid
+ await self.send_auth(uid, cookie, sequence=SEQ_ACTIVITY_BIZ, guid=guid)
# 9.1 抓包:getConfig 使用 wsLaunch 响应返回的新 guid;业务 UserId 仍为空 guid。
config_rsp = await self.call_get_config_activity(
uid, cookie, guid=self._launch_guid
@@ -570,7 +596,13 @@ class HuyaWssClient:
return body[5 : 5 + wup_len]
return body
- async def send_auth(self, uid: int, cookie: str, sequence: int = SEQ_WSLAUNCH):
+ async def send_auth(
+ self,
+ uid: int,
+ cookie: str,
+ sequence: int = SEQ_WSLAUNCH,
+ guid: str = "",
+ ):
"""cmd 0x0a AUTH — 对齐 9.1 抓包(828 活动帧)。
9.1 活动 AUTH 结构(逐字节核验):
@@ -591,8 +623,8 @@ class HuyaWssClient:
os.write_string(1, WSS_COOKIE_UA)
os.write_string(2, HuyaWssClient._normalize_biz_cookie(cookie))
guid_match = re.search(r"(?:^|;\s*)guid=([^;]+)", cookie or "")
- guid = (guid_match.group(1).strip() if guid_match else "") or self._launch_guid
- os.write_string(3, guid or "")
+ auth_guid = (guid or "").strip() or (guid_match.group(1).strip() if guid_match else "") or self._launch_guid
+ os.write_string(3, auth_guid)
os.write_int8(4, 1)
os.write_string(5, "HUYA&ZH&2052")
os.write_string(6, "")
diff --git "a/docs/HUYA_COOKIE\350\267\257\347\272\277\347\212\266\346\200\201.md" "b/docs/HUYA_COOKIE\350\267\257\347\272\277\347\212\266\346\200\201.md"
index 69e5423..d67e890 100644
--- "a/docs/HUYA_COOKIE\350\267\257\347\272\277\347\212\266\346\200\201.md"
+++ "b/docs/HUYA_COOKIE\350\267\257\347\272\277\347\212\266\346\200\201.md"
@@ -15,7 +15,7 @@ App 登录可以得到新鲜的 `udb_cred`、`udb_uid`、`yyuid`、`udb_biztoken
| `udb_cred`、`udb_uid`、`yyuid`、`udb_biztoken` | 已完成 | App 登录与 QR 绑定链 |
| `sdid`、`hdid` | 已完成 | hydevice / `df/collect` |
| `udb_deviceid`、`udb_guiddata`、`udb_anobiztoken`、`udb_anouid` | 已完成 | `anon_device.py` |
-| `guid` | 会话路径完成,回退算法未完全确认 | `wsLaunch` 返回值优先;回退值为结构仿造 |
+| `guid` | 会话路径已闭合 | 活动 `wsLaunch` 每次签发 32 位 `sGuid`;初始化时统一覆盖 AUTH、getConfig 和后续业务 Cookie,`956a/966a/976a` 等中间段不是本地版本常量 |
| `__yamid_new` | 已完成 | `room_normal.js` `generate32` Python 复刻 |
| `game_did` | 已完成 | 35 位、63 字符集规则复刻 |
| `_yasids` | 格式完成,精确共享种子未确认 | 与 `__yamid_new` 使用同类时钟生成器 |
@@ -47,10 +47,9 @@ SDK/Python 输出:d07a45de567322edcd42312f38e610be
## 尚未闭合的工程项
1. 将真实 WebView/Chrome 的 `getFeature()` 结果接入登录调用,替代当前的设备画像近似值。
-2. 明确 `guid` 的 `956a` / `966a` 版本差异和无 `wsLaunch` 时的真实生成规则。
-3. 让活动会话补齐后的 Cookie 持久化回账号,避免原始 16 字段账号每次任务重新生成设备字段。
-4. 为 `raw_cookie` 增加重建网页 Cookie 的服务入口。
-5. 商城下单、支付和支付状态轮询保持单独人工验证,不纳入只读回归。
+2. 让活动会话补齐后的 Cookie 持久化回账号,避免原始 16 字段账号每次任务重新生成设备字段。
+3. 为 `raw_cookie` 增加重建网页 Cookie 的服务入口。
+4. 商城下单、支付和支付状态轮询保持单独人工验证,不纳入只读回归。
## 证据入口
diff --git a/docs/HUYA_WEB_FIELD_TRACE.md b/docs/HUYA_WEB_FIELD_TRACE.md
index 8a7f9fe..4c82581 100644
--- a/docs/HUYA_WEB_FIELD_TRACE.md
+++ b/docs/HUYA_WEB_FIELD_TRACE.md
@@ -77,7 +77,7 @@ qimeisdk-web 0.6.3 源码已定位:
| 字段 | 来源 | 风控关联性 | 建议 |
| --- | --- | --- | --- |
-| `guid` | 浏览器脚本(有固定段 `0a..966a`)| 高(设备与会话绑定) | **必须按结构仿造或复用 wsLaunch 会话值**;随机纯 hex 与真实结构不符 |
+| `guid` | 活动 `wsLaunch` 响应 `sGuid`;页面 SDK 负责持久化 | 高(设备与会话绑定) | **优先复用当前 wsLaunch 会话值**;`956a/966a/976a` 等中间段随服务端返回变化,不能固化为版本常量 |
| `__yamid_new` | 浏览器脚本(CBCC 前缀+种子)| 高(与 rootsid 同源)| `room_normal.js` `generate32` 已复刻;精确 rootsid 共享计数仍待确认 |
| `_qimei_uuid42` | QIMEI SDK 0.6.3 VM 生成器 `e=6064` | 中 | Python 已按时间编码、CRC32 和随机半字节逐项复刻 |
| `_qimei_fingerprint` | QIMEI SDK 0.6.3 x64hash128(feature_string, 31) | 中 | Python 已复刻,输入字段见路线状态文档 |
@@ -87,7 +87,7 @@ qimeisdk-web 0.6.3 源码已定位:
**当时的下一步记录(部分已完成,保留作历史)**:
1. `_qimei_fingerprint` 已改为浏览器能力特征串的 `x64hash128`,见路线状态文档。
-2. `guid` 已优先使用 `wsLaunch` 会话值,回退固定段仍待确认。
+2. `guid` 已统一使用 `wsLaunch` 会话值;活动 AUTH、getConfig 与后续业务 Cookie 均复用同一返回值。
3. `__yamid_new` 已定位 `room_normal.js` `generate32` 并完成 Python 复刻。
## 六、核心字段生成算法逆向结果(2026-09-01 晚,浏览器实测 + 源码定位)
diff --git a/tests/test_huya_elite_protocol.py b/tests/test_huya_elite_protocol.py
index 71a10e6..ce4360d 100644
--- a/tests/test_huya_elite_protocol.py
+++ b/tests/test_huya_elite_protocol.py
@@ -146,3 +146,37 @@ def test_activity_auth_frame_matches_latest_capture_layout():
# body 必须与 9.1 828 AUTH 同样以 TAIL_BYTES 收尾
assert message.body[-len(TAIL_BYTES):] == TAIL_BYTES
+
+
+def test_activity_cookie_guid_is_replaced_by_launch_guid():
+ old = "0a" + "1" * 30
+ new = "0a" + "2" * 30
+ cookie = f"udb_uid=1; guid={old}; x=y; guid={old}"
+
+ result = HuyaWssClient._cookie_with_guid(cookie, new)
+
+ assert result == f"udb_uid=1; guid={new}; x=y"
+
+
+def test_activity_auth_accepts_explicit_launch_guid_over_cookie_guid():
+ async def build_frame():
+ client = HuyaWssClient()
+ client._activity_mode = True
+ client.ws = type("FakeWs", (), {"send": AsyncMock()})()
+ await client.send_auth(
+ 1199664135026,
+ "guid=" + "0a" * 16 + "; udb_cred=" + "x" * 300,
+ sequence=0x1D000109,
+ guid="0b" * 16,
+ )
+ return client.ws.send.call_args.args[0]
+
+ message = WssMessage.decode(asyncio.run(build_frame()))
+ stream = TafInputStream(message.body[: -len(TAIL_BYTES)])
+ assert stream.read_head() == (3, TafType.ZERO)
+ stream.read_int64(0)
+ stream.read_string(1)
+ assert stream.read_head() == (2, TafType.STRING4)
+ cookie_len = int.from_bytes(stream.buf.read(4), "big")
+ stream.buf.read(cookie_len)
+ assert stream.read_string(3) == "0b" * 16
File diff suppressed because it is too large Load Diff
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
set -eu
target=${1:-core/huya/wss_client.py}
baseline_ref=${GUID_SESSION_BASELINE_REF:-HEAD}
root=$(git rev-parse --show-toplevel)
case "$target" in
"$root"/*) file=$target; rel=${target#"$root"/} ;;
/*) file=$target; rel=core/huya/wss_client.py ;;
*) file="$root/$target"; rel=$target ;;
esac
git show "$baseline_ref:$rel" > "$file"
printf '已恢复 %s(基线 %s)\n' "$file" "$baseline_ref"
@@ -0,0 +1,42 @@
guid 会话一致性验证记录
changed branch/field: core/huya/wss_client.py::HuyaWssClient._cookie_with_guid、initialize_activity、send_auth;core/huya/elite_session.py::HuyaEliteWssSession.__init__ 初始化后的会话 guid 回写。
MODIFIED_FILE: /Users/yml/codes/live-hub-py/artifacts/guid_session_consistency/MODIFIED_FILE
DIFF_FILE: /Users/yml/codes/live-hub-py/artifacts/guid_session_consistency/DIFF_FILE
VERIFICATION.txt: /Users/yml/codes/live-hub-py/artifacts/guid_session_consistency/VERIFICATION.txt
ROLLBACK.sh: /Users/yml/codes/live-hub-py/artifacts/guid_session_consistency/ROLLBACK.sh (executable)
BASELINE
command: /Users/yml/codes/live-hub-py/.venv/bin/pytest -q
input: HEAD baseline before guid consistency change
literal output/result: 151 passed, 1 warning in 1.34s
exit status: 0
restored behavior/status: baseline test copy remained unchanged
MODIFIED
command: /Users/yml/codes/live-hub-py/.venv/bin/pytest -q
input: current worktree with wsLaunch sGuid propagation and regression tests
literal output/result: 153 passed, 1 warning in 1.34s
exit status: 0
additional checks:
command: /Users/yml/codes/live-hub-py/.venv/bin/ruff check core/huya/wss_client.py core/huya/elite_session.py tests/test_huya_elite_protocol.py
literal output/result: All checks passed!
exit status: 0
command: git diff --check
literal output/result: no output (clean)
exit status: 0
READ-ONLY ONLINE
command: DB_HOST=127.0.0.1 DB_PORT=3307 DB_NAME=douyu_login DB_USER=douyu_login /Users/yml/codes/live-hub-py/.venv/bin/python <inline probe>
input: account id=60; activity WSS; wsLaunch + getUserScore only; no exchange/order/payment calls
literal output/result: old_guid=0a43b01a366c966a7fe26a281e1d3c88; launch_guid=0a89d51717f5976ab502cf9dd09d03d8; session_cookie_guid=0a89d51717f5976ab502cf9dd09d03d8; guid_consistent=True; score_status=200; score=260; elapsed=0.286s
exit status: 0
restored behavior/status: WSS session closed; no write operation invoked
ROLLBACK
command: /Users/yml/codes/live-hub-py/artifacts/guid_session_consistency/ROLLBACK.sh /tmp/live-hub-guid-rollback/wss_client.py
input: independent copy of MODIFIED_FILE; GUID_SESSION_BASELINE_REF=HEAD
literal output/result: 已恢复 /tmp/live-hub-guid-rollback/wss_client.py(基线 HEAD)
exit status: 0
restored hash/status: independent copy matched git show HEAD:core/huya/wss_client.py; current worktree remains on modified branch
+145 -62
View File
@@ -14,6 +14,7 @@
无第三方依赖:标准库 + websockets(直接走 CDP 协议)。
"""
from __future__ import annotations
import argparse
@@ -29,8 +30,7 @@ from pathlib import Path
import websockets
CHROME = (
Path.home()
/ "Library/Caches/ms-playwright/chromium-1234/chrome-mac-arm64/"
Path.home() / "Library/Caches/ms-playwright/chromium-1234/chrome-mac-arm64/"
"Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"
)
@@ -41,8 +41,13 @@ PAGES = [
# 与 core/huya/app_login.py::WEB_DEVICE_COOKIE_KEYS 一致
WEB_DEVICE_KEYS = (
"guid", "udb_guiddata", "udb_deviceid", "game_did",
"_qimei_uuid42", "udb_anobiztoken", "__yamid_new",
"guid",
"udb_guiddata",
"udb_deviceid",
"game_did",
"_qimei_uuid42",
"udb_anobiztoken",
"__yamid_new",
)
OUT_DIR = Path("evidence/browser_cookie_harvest")
@@ -83,25 +88,43 @@ class Cdp:
self._id += 1
fut = asyncio.get_running_loop().create_future()
self._pending[self._id] = fut
await self.ws.send(json.dumps({"id": self._id, "method": method, "params": params or {}}))
await self.ws.send(
json.dumps({"id": self._id, "method": method, "params": params or {}})
)
resp = await fut
if "error" in resp:
raise RuntimeError(f"{method}: {resp['error']}")
return resp.get("result", {})
async def eval_js(self, expr):
r = await self.call("Runtime.evaluate", {
"expression": expr, "returnByValue": True, "awaitPromise": True,
})
r = await self.call(
"Runtime.evaluate",
{
"expression": expr,
"returnByValue": True,
"awaitPromise": True,
},
)
return r.get("result", {}).get("value")
def launch(profile: Path, port: int, headless: bool = False) -> tuple[subprocess.Popen, str]:
def launch(
profile: Path, port: int, headless: bool = True
) -> tuple[subprocess.Popen, str]:
"""启动用于 CDP 抓取的 Chrome。
默认使用无头模式,避免登录/抓取流程弹出窗口;传入 ``headless=False``
仍可在需要人工观察页面时启用可视化窗口。
"""
args = [
str(CHROME),
"--no-first-run", "--no-default-browser-check",
"--disable-background-networking", "--disable-component-update",
"--disable-sync", "--metrics-recording-only", "--disable-extensions",
"--no-first-run",
"--no-default-browser-check",
"--disable-background-networking",
"--disable-component-update",
"--disable-sync",
"--metrics-recording-only",
"--disable-extensions",
"--disable-features=OptimizationHints,MediaRouter",
f"--user-data-dir={profile}",
f"--remote-debugging-port={port}",
@@ -128,7 +151,11 @@ def launch(profile: Path, port: int, headless: bool = False) -> tuple[subprocess
f"http://127.0.0.1:{port}/json/list", timeout=2
) as resp:
targets = json.load(resp)
pages = {t for t in targets if t.get("type") == "page" and t.get("webSocketDebuggerUrl")}
pages = {
t
for t in targets
if t.get("type") == "page" and t.get("webSocketDebuggerUrl")
}
if pages:
ws_url = pages[0]["webSocketDebuggerUrl"]
break
@@ -170,9 +197,9 @@ def cookie_names_from_header(headers: dict) -> list[str]:
return [part.strip().split("=", 1)[0] for part in raw.split(";") if part.strip()]
async def capture_round(profile: Path, tag: str, port: int):
async def capture_round(profile: Path, tag: str, port: int, *, headless: bool = True):
"""抓取一轮:导航序列 + 全量 Cookie 快照。"""
proc, ws_url = launch(profile, port)
proc, ws_url = launch(profile, port, headless=headless)
try:
async with websockets.connect(ws_url, max_size=64 * 1024 * 1024) as raw_ws:
cdp = Cdp(raw_ws)
@@ -199,11 +226,13 @@ async def capture_round(profile: Path, tag: str, port: int):
else:
entry["seq"] = min(ack_order, req_seq)
req_seq += 1
entry.update({
"url": url,
"host": urllib.parse.urlparse(url).netloc,
"type": params.get("type", ""),
})
entry.update(
{
"url": url,
"host": urllib.parse.urlparse(url).netloc,
"type": params.get("type", ""),
}
)
# 部分请求的 Cookie 头在 requestWillBeSent 就直接可见
seen = set(entry.get("cookie_names", []))
for name in cookie_names_from_header(req.get("headers", {})):
@@ -244,12 +273,16 @@ async def capture_round(profile: Path, tag: str, port: int):
entry = requests.setdefault(rid, {"url": "?"})
url = entry.get("url", "?")
headers = params.get("headers", {})
set_cookie = headers.get("Set-Cookie") or headers.get("set-cookie") or []
set_cookie = (
headers.get("Set-Cookie") or headers.get("set-cookie") or []
)
if isinstance(set_cookie, str):
set_cookie = [set_cookie]
for sc in set_cookie:
name = sc.split("=", 1)[0].strip()
resp_extra.append({"cookie": name, "url": url, "meta": sc[:160]})
resp_extra.append(
{"cookie": name, "url": url, "meta": sc[:160]}
)
cdp.listeners.append(on_resp_extra)
@@ -263,10 +296,19 @@ async def capture_round(profile: Path, tag: str, port: int):
}
await navigate(cdp, url)
doc_cookies[name]["after"] = await cdp.eval_js("document.cookie")
snapshots.append({"page": name, "url": url, "time": ts,
"cookies": await cdp.call("Network.getAllCookies")})
print(f"[harvest] {tag}/{name} done: {url} doc_cookie_len="
f"{len(doc_cookies[name]['after'] or '')}", flush=True)
snapshots.append(
{
"page": name,
"url": url,
"time": ts,
"cookies": await cdp.call("Network.getAllCookies"),
}
)
print(
f"[harvest] {tag}/{name} done: {url} doc_cookie_len="
f"{len(doc_cookies[name]['after'] or '')}",
flush=True,
)
# 按事件到达次序输出请求列表
req_list = sorted(requests.values(), key=lambda r: r.get("seq", 10**9))
@@ -294,14 +336,14 @@ async def capture_round(profile: Path, tag: str, port: int):
proc.kill()
async def probe_anon(profile: Path, port: int):
async def probe_anon(profile: Path, port: int, *, headless: bool = True):
"""复用已有 profile:复放 udblgn 匿名流程,解密请求/响应体。
抓取会话内 anonymousLogin 与 web/middle 的 postData 与响应体,
然后带全套 Cookie 用 requests 独立重放 anonymousLogin,检查
服务端是否在匿名流程中下发 guid/udb_guiddata/匿名 token 等字段。
"""
proc, ws_url = launch(profile, port)
proc, ws_url = launch(profile, port, headless=headless)
try:
async with websockets.connect(ws_url, max_size=64 * 1024 * 1024) as raw_ws:
cdp = Cdp(raw_ws)
@@ -325,14 +367,21 @@ async def probe_anon(profile: Path, port: int):
"url": url,
"method": req.get("method", ""),
"postData": req.get("postData", ""),
"headers": {k: v for k, v in req.get("headers", {}).items()
if k.lower() in ("cookie", "content-type", "referer", "origin")},
"headers": {
k: v
for k, v in req.get("headers", {}).items()
if k.lower()
in ("cookie", "content-type", "referer", "origin")
},
"body": None,
"status": None,
}
rid_map[params.get("requestId", "")] = entry
anon.append(entry)
print(f"[probe] 抓到匿名请求: {req.get('method')} {url[:120]}", flush=True)
print(
f"[probe] 抓到匿名请求: {req.get('method')} {url[:120]}",
flush=True,
)
cdp.listeners.append(on_anon_req)
@@ -352,10 +401,14 @@ async def probe_anon(profile: Path, port: int):
# 抓响应体
for rid, entry in rid_map.items():
try:
body = await cdp.call("Network.getResponseBody", {"requestId": rid})
body = await cdp.call(
"Network.getResponseBody", {"requestId": rid}
)
entry["body"] = body.get("body", "")
print(f"[probe] 响应体 {len(entry['body'])}B status={entry['status']}",
flush=True)
print(
f"[probe] 响应体 {len(entry['body'])}B status={entry['status']}",
flush=True,
)
except Exception as exc: # noqa: BLE001
print(f"[probe] 响应体获取失败: {exc}", flush=True)
@@ -384,16 +437,20 @@ async def probe_anon(profile: Path, port: int):
replay = []
for entry in anon:
host = urllib.parse.urlparse(entry["url"]).netloc
headers = {"User-Agent": (
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/149.0.0.0 Safari/537.36"
)}
headers = {
"User-Agent": (
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/149.0.0.0 Safari/537.36"
)
}
ck = cookie_header(host)
if ck:
headers["Cookie"] = ck
if entry["postData"]:
headers.setdefault("Content-Type", "application/x-www-form-urlencoded")
headers.setdefault(
"Content-Type", "application/x-www-form-urlencoded"
)
try:
resp = await asyncio.to_thread(
pyrequests.request,
@@ -404,18 +461,22 @@ async def probe_anon(profile: Path, port: int):
timeout=15,
allow_redirects=False,
)
replay.append({
"url": entry["url"][:160],
"method": entry["method"],
"status": resp.status_code,
"set_cookie": resp.headers.get("Set-Cookie", ""),
"location": resp.headers.get("Location", ""),
"body_head": resp.text[:600],
"body_len": len(resp.content),
})
print(f"[probe] 重放 {entry['method']} {entry['url'][:90]} "
f"-> {resp.status_code} setcookie={bool(resp.headers.get('Set-Cookie'))}",
flush=True)
replay.append(
{
"url": entry["url"][:160],
"method": entry["method"],
"status": resp.status_code,
"set_cookie": resp.headers.get("Set-Cookie", ""),
"location": resp.headers.get("Location", ""),
"body_head": resp.text[:600],
"body_len": len(resp.content),
}
)
print(
f"[probe] 重放 {entry['method']} {entry['url'][:90]} "
f"-> {resp.status_code} setcookie={bool(resp.headers.get('Set-Cookie'))}",
flush=True,
)
except Exception as exc: # noqa: BLE001
replay.append({"url": entry["url"][:160], "error": str(exc)})
print(f"[probe] 重放失败: {exc}", flush=True)
@@ -444,9 +505,17 @@ def build_report():
sys.exit(2)
req1 = json.loads((r1 / "requests.json").read_text())
req2 = json.loads((r2 / "requests.json").read_text()) if (r2 / "requests.json").exists() else []
req2 = (
json.loads((r2 / "requests.json").read_text())
if (r2 / "requests.json").exists()
else []
)
setc1 = json.loads((r1 / "set_cookies.json").read_text())
snap2 = json.loads((r2 / "snapshots.json").read_text()) if (r2 / "snapshots.json").exists() else []
snap2 = (
json.loads((r2 / "snapshots.json").read_text())
if (r2 / "snapshots.json").exists()
else []
)
doc1 = json.loads((r1 / "doc_cookies.json").read_text())
# 每个 cookie 名在 round1 的首次出现位置(按请求顺序)
@@ -454,7 +523,12 @@ def build_report():
for i, req in enumerate(req1):
for name in req.get("cookie_names", []):
if name not in first_seen:
first_seen[name] = {"idx": i, "host": req["host"], "url": req["url"], "type": req["type"]}
first_seen[name] = {
"idx": i,
"host": req["host"],
"url": req["url"],
"type": req["type"],
}
# Set-Cookie 写入的 cookie
set_from: dict[str, str] = {}
@@ -478,7 +552,7 @@ def build_report():
def fmt_first(info: dict | None):
if not info:
return "未见来源"
return f'#{info["idx"]} {info["host"]} ({info["type"]})'
return f"#{info['idx']} {info['host']} ({info['type']})"
lines = [
"# 浏览器 Cookie 字段来源分析(真实 Chrome 抓包,未登录)",
@@ -510,7 +584,7 @@ def build_report():
for i, req in enumerate(req1[:60]):
names = ", ".join(req.get("cookie_names", [])[:12])
names_all = req.get("cookie_names", [])
extra = f" +{len(names_all)-12}" if len(names_all) > 12 else ""
extra = f" +{len(names_all) - 12}" if len(names_all) > 12 else ""
lines.append(f"| {i} | {req['host']} | {req['type']} | {names}{extra} |")
lines += [
@@ -532,8 +606,10 @@ def build_report():
names = [p.split("=", 1)[0].strip() for p in after.split(";") if p.strip()]
diff = [n for n in names if n not in seen]
seen.update(names)
lines.append(f"- {page}: before={bool(v.get('before'))} after={len(names)} 字段"
f" 新增={', '.join(diff) if diff else '无'}")
lines.append(
f"- {page}: before={bool(v.get('before'))} after={len(names)} 字段"
f" 新增={', '.join(diff) if diff else '无'}"
)
lines += ["", "## round2 重启后首请求即携带的字段(浏览器持久态)", ""]
if req2:
pk = []
@@ -562,6 +638,11 @@ def main():
ap.add_argument("--profile", default="/tmp/huya-browser-p1")
ap.add_argument("--port", type=int, default=9333)
ap.add_argument("--out", default=str(OUT_DIR))
ap.add_argument(
"--headed",
action="store_true",
help="显示 Chrome 窗口(默认使用无头模式)",
)
args = ap.parse_args()
OUT_DIR = Path(args.out)
profile = Path(args.profile)
@@ -572,7 +653,9 @@ def main():
if args.mode == "round2" and not (profile / "Default").exists():
print("round2 需要先运行 round1(同一 profile)")
sys.exit(2)
asyncio.run(capture_round(profile, args.mode, args.port))
asyncio.run(
capture_round(profile, args.mode, args.port, headless=not args.headed)
)
elif args.mode == "probe":
# 匿名流程只在"无 udb_deviceid 持久态"的全新 profile 触发;
# probe 模式内部使用临时全新 profile,跑完自动清理。
@@ -581,7 +664,7 @@ def main():
tmp = tempfile.mkdtemp(prefix="huya-probe-")
try:
asyncio.run(probe_anon(Path(tmp), args.port))
asyncio.run(probe_anon(Path(tmp), args.port, headless=not args.headed))
finally:
shutil.rmtree(tmp, ignore_errors=True)
else:
@@ -589,4 +672,4 @@ def main():
if __name__ == "__main__":
main()
main()
+19 -6
View File
@@ -58,7 +58,9 @@ class HuyaEliteWssSession:
probe = HuyaWssClient(baseinfo=baseinfo, logger=self.logger)
try:
self.loop.run_until_complete(
probe.connect(host=connect_host, origin=origin, cookie=self.cookie)
probe.connect(
host=connect_host, origin=origin, cookie=self.cookie
)
)
self.loop.run_until_complete(
probe.call_ws_launch_activity(self.uid, self.guid)
@@ -75,9 +77,7 @@ class HuyaEliteWssSession:
self.logger("[WSS] 预取探针清理失败")
from .web_cookie_fields import fill_web_cookie_fields
self.cookie = fill_web_cookie_fields(
self.cookie, launch_guid, self.uid
)
self.cookie = fill_web_cookie_fields(self.cookie, launch_guid, self.uid)
self.guid = HuyaHttpClient._resolve_cookie_guid(self.cookie)
baseinfo = urllib.parse.unquote(
generate_http_baseinfo(self.uid, self.guid, "")
@@ -85,7 +85,9 @@ class HuyaEliteWssSession:
self.client = HuyaWssClient(baseinfo=baseinfo, logger=self.logger)
self.loop.run_until_complete(
self.client.connect(host=connect_host, origin=origin, cookie=self.cookie)
self.client.connect(
host=connect_host, origin=origin, cookie=self.cookie
)
)
initialized = self.loop.run_until_complete(
self.client.initialize_activity(self.uid, self.guid, self.cookie)
@@ -94,6 +96,13 @@ class HuyaEliteWssSession:
)
if not initialized:
raise RuntimeError(f"虎牙 {kind} WSS 初始化失败")
if kind == "activity" and self.client._launch_guid:
# wsLaunch 的 sGuid 是当前连接的真实会话值,供后续业务 Cookie
# 与 HTTP baseinfo 继续复用,避免沿用登录时的旧 guid。
self.cookie = self.client._cookie_with_guid(
self.cookie, self.client._launch_guid
)
self.guid = self.client._launch_guid
except Exception:
self.close()
raise
@@ -110,7 +119,11 @@ class HuyaEliteWssSession:
wsLaunch 取回会话 guid 并补齐字段(见 __init__),这里把缺字段的
输入替换为补齐后的 self.cookie。
"""
if not cookie or cookie == self._original_cookie or missing_web_cookie_fields(cookie):
if (
not cookie
or cookie == self._original_cookie
or missing_web_cookie_fields(cookie)
):
return self.cookie
return cookie
+72 -23
View File
@@ -8,7 +8,7 @@
- ``guid/_qimei_uuid42/__yamid_new/game_did`` 由页面 SDK 脚本写 document.cookie,
无服务端签发接口。其中 ``guid`` 与会话强绑定:**wsLaunch 响应返回的新 guid 必须
回写进 cookie**,否则 getConfig 无响应(2026-09-01 实测);
``_qimei_uuid42/__yamid_new/game_did`` 为设备标识,随机值格式对齐即可;
``_qimei_uuid42/__yamid_new/game_did`` 为设备标识,已按浏览器脚本算法生成;
- 其余统计/会话字段(SoundValue/Hm_*/rep_cnt 等)服务端仅记录,可随机生成。
2026-09-01 全链路实测:账号 id=58 补齐后 checkUserBindGameAccount 返回
@@ -20,7 +20,9 @@ from __future__ import annotations
import random
import secrets
import time
import zlib
from collections.abc import Mapping
from datetime import UTC, datetime
# 统计/会话字段生成规则;9.1 抓包值为样例,格式保持对齐
_FILL_MAP: tuple[tuple[str, str], ...] = (
@@ -36,13 +38,11 @@ _FILL_MAP: tuple[tuple[str, str], ...] = (
# + v1 版本位 + 时钟序列 + 48 位随机 node)。浏览器 epoch = new Date(1582,10,15,
# 0,0,0,0).getTime() 实测 -12216643543000(GMT+8)。CBCC 前缀是时间戳自然结果。
# - game_did: vplayerUI.js 35 位随机,字符集 64 去掉末尾 '_'(63 选 1)。
# - _qimei_uuid42: QIMEI SDK 生成,cookie 值首字节固定 '1a'(本地存储 44hex 截断)。
# - _qimei_uuid42: QIMEI SDK 生成,时间字段 + CRC32 替换段 + 随机半字节段。
_SDK_EPOCH_1582 = -12216643543000 # 浏览器实测 JS Date(1582,10,15) 本地时区 ms
_BASE16 = "0123456789ABCDEF"
_GAME_DID_CHARS = (
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"
)
_GAME_DID_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"
_DEFAULT_QIMEI_FEATURE = {
"screen": {"resolution": "800x600", "availResolution": "800x600"},
"navigator": {
@@ -98,18 +98,20 @@ def _yamid_new_generate32(rng=None) -> str:
r = rng if rng is not None else random.Random()
now_ms = int(time.time() * 1000)
c = now_ms - _SDK_EPOCH_1582
return "".join((
_generate_bits(c, 0, 31),
_generate_bits(c, 32, 47),
_generate_bits(c, 48, 59) + "1",
_generate_bits(r.randrange(4095), 0, 7),
_generate_bits(r.randrange(4095), 0, 7),
_generate_bits(r.randrange(8191), 0, 7)
+ _generate_bits(r.randrange(8191), 8, 15)
+ _generate_bits(r.randrange(8191), 0, 7)
+ _generate_bits(r.randrange(8191), 8, 15)
+ _generate_bits(r.randrange(8191), 0, 15),
))
return "".join(
(
_generate_bits(c, 0, 31),
_generate_bits(c, 32, 47),
_generate_bits(c, 48, 59) + "1",
_generate_bits(r.randrange(4095), 0, 7),
_generate_bits(r.randrange(4095), 0, 7),
_generate_bits(r.randrange(8191), 0, 7)
+ _generate_bits(r.randrange(8191), 8, 15)
+ _generate_bits(r.randrange(8191), 0, 7)
+ _generate_bits(r.randrange(8191), 8, 15)
+ _generate_bits(r.randrange(8191), 0, 15),
)
)
def _game_did_generate(length: int = 35) -> str:
@@ -263,6 +265,43 @@ def _rand_float() -> str:
return f"{random.random():.17f}"
def _qimei_uuid42_generate(
now_ns: int | None = None,
*,
cookie_enabled: bool = True,
random_value: float | None = None,
) -> str:
"""逐字复刻 QIMEI Web SDK 0.6.3 的 42 位 ``h38`` 生成器。
``now_ns`` 保留旧回退函数的纳秒参数约定;SDK 实际只读取本地时间的
年/月/日/时/分/秒,因此毫秒和纳秒不会进入结果。时间前缀的年份和月份
使用 SDK 的十六进制编码,最后三位来自 ``navigator.cookieEnabled``。
``random_value`` 仅用于固定测试;生产调用会像 SDK 一样独立调用 20 次
``Math.random()`` 等价的 Python ``random.random()``,并将理论上的 1.0
夹到合法半字节上界 15。
"""
now_ms = time.time_ns() // 1_000_000 if now_ns is None else now_ns // 1_000_000
current = datetime.fromtimestamp(now_ms / 1000, tz=UTC).astimezone()
# SDK: Number(year % 100).toString(16).padStart(2, "0") +
# Number(month + 1).toString(16) + each remaining component padded to 2.
year_hex = f"{current.year % 100:x}".rjust(2, "0")
month_hex = f"{current.month:x}"
date_parts = "".join(
f"{value:x}".rjust(2, "0")
for value in (current.day, current.hour, current.minute, current.second)
)
prefix = year_hex + month_hex + date_parts + ("100" if cookie_enabled else "000")
random_source = random.random if random_value is None else lambda: random_value
random_segment = "".join(
f"{min(15, max(0, int(float(random_source()) * 16))):x}" for _ in range(20)
)
template = prefix + "----" + random_segment + "----"
replacement = f"{zlib.crc32(template.encode('ascii')) & 0xFFFFFFFF:08x}"
return prefix + replacement[:4] + random_segment + replacement[4:]
def fill_web_cookie_fields(
cookie: str,
guid: str,
@@ -308,8 +347,8 @@ def fill_web_cookie_fields(
elif "guid" not in pairs:
# guid 结构: '0a' + 10hex + '956a'/'966a' + 16hex(浏览器实测固定段,见 trace 文档)
add("guid", "0a" + secrets.token_hex(5) + "966a" + secrets.token_hex(8))
# _qimei_uuid42: QIMEI SDK 产物,cookie 首字节 '1a' + UUID 布局 32hex + 8hex 附加
add("_qimei_uuid42", "1a" + secrets.token_hex(20))
# _qimei_uuid42: QIMEI SDK 0.6.3 的时间/CRC32/随机半字节组合。
add("_qimei_uuid42", _qimei_uuid42_generate())
# __yamid_new: room_normal.js generate32 精确复刻(UUID-v1 时间戳,含 CBCC 前缀规律)
add("__yamid_new", _yamid_new_generate32())
add("game_did", _game_did_generate()) # 35 位随机(真实长度)
@@ -317,7 +356,9 @@ def fill_web_cookie_fields(
# qimei 皮肤字段
# _qimei_fingerprint: QIMEI SDK x64hash128(浏览器能力特征,31) 32hex。
add("_qimei_fingerprint", qimei_fingerprint_generate(qimei_feature))
add("_qimei_h38", secrets.token_hex(19))
# SDK 内部 h38 就是 42 位 UUID42,并不存在独立的 38 位生成器。当前活动
# getUserScore 只检查同名 Cookie 键是否存在,不检查值;复用 SDK h38 的真实值。
add("_qimei_h38", pairs["_qimei_uuid42"])
# 会话/统计字段
yasmid = _rand_float()
@@ -348,9 +389,17 @@ def missing_web_cookie_fields(cookie: str) -> tuple[str, ...]:
from .cookie_utils import cookie_value
core = (
"guid", "_qimei_uuid42", "__yamid_new", "game_did",
"_qimei_fingerprint", "_qimei_h38", "__yasmid", "__yamid_tt1",
"udb_passdata", "_yasids", "HMACCOUNT",
"guid",
"_qimei_uuid42",
"__yamid_new",
"game_did",
"_qimei_fingerprint",
"_qimei_h38",
"__yasmid",
"__yamid_tt1",
"udb_passdata",
"_yasids",
"HMACCOUNT",
)
return tuple(key for key in core if not cookie_value(cookie, key))
+103 -21
View File
@@ -26,6 +26,7 @@ from typing import Any, cast
import websockets
from .cookie_utils import cookie_pairs, normalize_cookie_pairs
from .frame_decoder import _decode_taf_struct, _truncate, format_wss_log
from .taf_protocol import TafInputStream, TafOutputStream, TafStruct, TafType
from .wup_protocol import WupRequest, WupResponse
@@ -56,6 +57,7 @@ class _ActivityConfigReq(TafStruct):
def read_from(self, _ins):
pass
# seq 按消息类型固定 (HAR 实证,跨两次抓包一致)
SEQ_HEARTBEAT = 0x1D00000D
SEQ_WSLAUNCH = 0x1D000078
@@ -192,6 +194,26 @@ class HuyaWssClient:
return normalized
return f"{normalized}; {cookie}"
@staticmethod
def _cookie_with_guid(cookie: str, guid: str) -> str:
"""用当前 WSS 会话的 sGuid 替换 Cookie 中的旧 guid。"""
value = str(guid or "").strip()
if not value:
return cookie or ""
pairs = cookie_pairs(cookie)
replaced = False
normalized: list[tuple[str, str]] = []
for key, item_value in pairs:
if key == "guid":
if not replaced:
normalized.append((key, value))
replaced = True
continue
normalized.append((key, item_value))
if not replaced:
normalized.append(("guid", value))
return normalize_cookie_pairs(normalized)
@staticmethod
def _build_biz_user(uid: int, cookie: str):
"""构造 WSS 业务 UserId(HAR 实证:guid 为空,cookie 不额外加前缀)"""
@@ -389,7 +411,12 @@ class HuyaWssClient:
if launch_rsp is None:
self.logger("[WSS] 活动 wsLaunch 无响应")
return False
await self.send_auth(uid, cookie, sequence=SEQ_ACTIVITY_BIZ)
# wsLaunch 会为当前连接签发新的 sGuid。AUTH、getConfig 和后续业务
# 请求必须使用同一个值;登录 Cookie 里的旧 guid 不能继续复用。
if self._launch_guid:
cookie = self._cookie_with_guid(cookie, self._launch_guid)
guid = self._launch_guid
await self.send_auth(uid, cookie, sequence=SEQ_ACTIVITY_BIZ, guid=guid)
# 9.1 抓包:getConfig 使用 wsLaunch 响应返回的新 guid;业务 UserId 仍为空 guid。
config_rsp = await self.call_get_config_activity(
uid, cookie, guid=self._launch_guid
@@ -400,7 +427,9 @@ class HuyaWssClient:
await asyncio.sleep(0.1)
return True
async def call_ws_launch_activity(self, uid: int, guid: str = "", timeout: float = 10.0):
async def call_ws_launch_activity(
self, uid: int, guid: str = "", timeout: float = 10.0
):
ua = WSS_COOKIE_UA
os = TafOutputStream()
os.write_struct_begin(0)
@@ -423,7 +452,9 @@ class HuyaWssClient:
msg = WssMessage(WssCommand.RPC_REQUEST, SEQ_ACTIVITY_WSLAUNCH, body)
future = asyncio.Future()
self.rpc_queue.append(future)
self.logger(format_wss_log(body, WssCommand.RPC_REQUEST, SEQ_ACTIVITY_WSLAUNCH, "发"))
self.logger(
format_wss_log(body, WssCommand.RPC_REQUEST, SEQ_ACTIVITY_WSLAUNCH, "发")
)
await self.ws.send(msg.encode())
try:
response = await asyncio.wait_for(future, timeout)
@@ -431,7 +462,11 @@ class HuyaWssClient:
if future in self.rpc_queue:
self.rpc_queue.remove(future)
return None
self.logger(format_wss_log(response, WssCommand.RPC_RESPONSE, SEQ_ACTIVITY_WSLAUNCH, "收"))
self.logger(
format_wss_log(
response, WssCommand.RPC_RESPONSE, SEQ_ACTIVITY_WSLAUNCH, "收"
)
)
self._parse_launch_response(response)
return response
@@ -570,7 +605,13 @@ class HuyaWssClient:
return body[5 : 5 + wup_len]
return body
async def send_auth(self, uid: int, cookie: str, sequence: int = SEQ_WSLAUNCH):
async def send_auth(
self,
uid: int,
cookie: str,
sequence: int = SEQ_WSLAUNCH,
guid: str = "",
):
"""cmd 0x0a AUTH — 对齐 9.1 抓包(828 活动帧)。
9.1 活动 AUTH 结构(逐字节核验):
@@ -591,8 +632,12 @@ class HuyaWssClient:
os.write_string(1, WSS_COOKIE_UA)
os.write_string(2, HuyaWssClient._normalize_biz_cookie(cookie))
guid_match = re.search(r"(?:^|;\s*)guid=([^;]+)", cookie or "")
guid = (guid_match.group(1).strip() if guid_match else "") or self._launch_guid
os.write_string(3, guid or "")
auth_guid = (
(guid or "").strip()
or (guid_match.group(1).strip() if guid_match else "")
or self._launch_guid
)
os.write_string(3, auth_guid)
os.write_int8(4, 1)
os.write_string(5, "HUYA&ZH&2052")
os.write_string(6, "")
@@ -804,7 +849,9 @@ class HuyaWssClient:
req = GetActTaskDetailReq()
req.userId = self._build_activity_user(uid, cookie)
req.actId = int(act_id or 0)
return await self.call_rpc("webActUI", "getActTaskDetail", req, GetActTaskDetailResp)
return await self.call_rpc(
"webActUI", "getActTaskDetail", req, GetActTaskDetailResp
)
async def get_act_user_task_detail(self, uid: int, cookie: str, act_id: int):
from .activity_structs import GetActUserTaskDetailReq, GetActUserTaskDetailResp
@@ -812,7 +859,9 @@ class HuyaWssClient:
req = GetActUserTaskDetailReq()
req.userId = self._build_activity_user(uid, cookie)
req.actId = int(act_id or 0)
return await self.call_rpc("webActUI", "getActUserTaskDetail", req, GetActUserTaskDetailResp)
return await self.call_rpc(
"webActUI", "getActUserTaskDetail", req, GetActUserTaskDetailResp
)
async def get_user_score(self, uid: int, cookie: str, sid: int):
from .activity_structs import GetUserScoreReq, GetUserScoreResp
@@ -828,7 +877,9 @@ class HuyaWssClient:
req = GetActPrizeListReq()
req.userId = self._build_activity_user(uid, cookie)
req.sid = int(sid or 0)
return await self.call_rpc("webActUI", "getActPrizeList", req, GetActPrizeListResp)
return await self.call_rpc(
"webActUI", "getActPrizeList", req, GetActPrizeListResp
)
async def get_act_prize_detail(self, uid: int, cookie: str, sid: int, pid: int):
from .activity_structs import GetActPrizeDetailReq, GetActPrizeDetailResp
@@ -837,7 +888,9 @@ class HuyaWssClient:
req.userId = self._build_activity_user(uid, cookie)
req.sid = int(sid or 0)
req.pid = int(pid or 0)
return await self.call_rpc("webActUI", "getActPrizeDetail", req, GetActPrizeDetailResp)
return await self.call_rpc(
"webActUI", "getActPrizeDetail", req, GetActPrizeDetailResp
)
async def score_exchange_prize(self, uid: int, cookie: str, sid: int, pid: int):
from .activity_structs import ScoreExchangePrizeReq, ScoreExchangePrizeResp
@@ -846,7 +899,9 @@ class HuyaWssClient:
req.userId = self._build_activity_user(uid, cookie)
req.sid = int(sid or 0)
req.pid = int(pid or 0)
return await self.call_rpc("webActUI", "scoreExchangePrize", req, ScoreExchangePrizeResp)
return await self.call_rpc(
"webActUI", "scoreExchangePrize", req, ScoreExchangePrizeResp
)
async def get_user_prize_records(self, uid: int, cookie: str, sid: int):
from .activity_structs import GetUserPrizeRecordsReq, GetUserPrizeRecordsResp
@@ -854,11 +909,19 @@ class HuyaWssClient:
req = GetUserPrizeRecordsReq()
req.userId = self._build_activity_user(uid, cookie)
req.sid = int(sid or 0)
return await self.call_rpc("webActUI", "getUserPrizeRecords", req, GetUserPrizeRecordsResp)
return await self.call_rpc(
"webActUI", "getUserPrizeRecords", req, GetUserPrizeRecordsResp
)
async def check_user_bind_game_account(
self, uid: int, cookie: str, b_act_id: int, is_use_outer_act_id: int = 1,
gid: int = 0, outer_act_id: str = "", scene: str = "",
self,
uid: int,
cookie: str,
b_act_id: int,
is_use_outer_act_id: int = 1,
gid: int = 0,
outer_act_id: str = "",
scene: str = "",
):
from .activity_structs import (
CheckUserBindGameAccountReq,
@@ -894,8 +957,13 @@ class HuyaWssClient:
)
async def get_live_link_param(
self, uid: int, cookie: str, b_act_id: int, gid: int = 0,
outer_act_id: int = 0, game_auth_scene: str = "",
self,
uid: int,
cookie: str,
b_act_id: int,
gid: int = 0,
outer_act_id: int = 0,
game_auth_scene: str = "",
):
from .activity_structs import GetLiveLinkParamReq, GetLiveLinkParamResp
@@ -905,9 +973,13 @@ class HuyaWssClient:
req.outerActId = int(outer_act_id or 0)
req.gameAuthScene = game_auth_scene or ""
req.bActId = int(b_act_id or 0)
return await self.call_rpc("webActUI", "getLiveLinkParam", req, GetLiveLinkParamResp)
return await self.call_rpc(
"webActUI", "getLiveLinkParam", req, GetLiveLinkParamResp
)
async def get_user_profile_batch(self, uid: int, cookie: str, target_uids: list[int]):
async def get_user_profile_batch(
self, uid: int, cookie: str, target_uids: list[int]
):
from .activity_structs import GetUserProfileBatchReq, GetUserProfileBatchResp
req = GetUserProfileBatchReq()
@@ -920,7 +992,12 @@ class HuyaWssClient:
)
async def list_pay_channels(
self, uid: int, guid: str, cookie: str, spu_id: str, sku_id: int = 0,
self,
uid: int,
guid: str,
cookie: str,
spu_id: str,
sku_id: int = 0,
supplier_id: int = 87401,
):
from .shop_structs import ListPayChannelReq, ListPayChannelRsp
@@ -946,7 +1023,12 @@ class HuyaWssClient:
)
async def check_user_buy_auth(
self, uid: int, guid: str, cookie: str, spu_id: str, sku_id: int,
self,
uid: int,
guid: str,
cookie: str,
spu_id: str,
sku_id: int,
):
from .shop_structs import CheckUserBuyAuthReq, ShopCodeRsp
+6 -6
View File
@@ -22,7 +22,7 @@
| `udb_anouid` | anonymousLogin 响应 uid | ✅ 已接入 anon_device |
| `udb_guiddata` | middle URL 第三段 hex32(客户端自选) | ✅ 已接入 anon_device |
| `guid` | `HyUDBWebSDK-Exchange-2.4.js` 写 document.cookie | 会话值已接入;回退生成规则待确认 |
| `_qimei_uuid42` | QIMEI SDK 脚本写 document.cookie | 结构已对齐;SDK 语义待复刻 |
| `_qimei_uuid42` | QIMEI SDK 脚本写 document.cookie | 0.6.3 时间/CRC32/随机半字节算法已复刻 |
| `__yamid_new` | 门户业务脚本写 document.cookie | `room_normal.js` `generate32` 已复刻 |
| `game_did` | 门户业务脚本写 document.cookie | 35 位、63 字符集规则已复刻 |
@@ -41,13 +41,13 @@ udb_appid, udb_guiddata` —— 4 个匿名设备字段已有(anon_device 协
| --- | --- | --- | --- |
| `guid` | 32 hex,`0a7d…` 前缀 | udbres.huya.com SDK 脚本 | `wsLaunch` 会话值已接入;回退规则待确认 |
| `game_did` | 35 位字母数字 | liveapi.ip/getIpLocation 后门户脚本 | 35 位、63 字符集已复刻 |
| `_qimei_uuid42` | 42 hex,`1a901…` 前缀 | QIMEI SDK 脚本 | `1a` + 40hex;精确算法待复刻 |
| `_qimei_uuid42` | 42 hex,时间前缀 | QIMEI SDK 脚本 | 14 位时间前缀 + CRC32 替换段 + 随机半字节 |
| `__yamid_new` | 32 hex 大写 | 门户脚本 | `generate32` 已复刻并通过 WSS 验证 |
浏览器 round1 同一字段多次出现均**值稳定**(跨 profile 稳定):`_qimei_fingerprint`
恒为 `2822a43b5a3bd016fc844218c35c8a74`,`_qimei_uuid42` 前缀恒为 `1a901…`,
`guid` 前缀恒为 `0a7dfaa2…` → 存在固定前缀/哈希结构,**随机值可能被风控识别**,
需还原生成算法。
恒为 `2822a43b5a3bd016fc844218c35c8a74`,`_qimei_uuid42` 按秒内时间前缀稳定,
`guid` 前缀恒为 `0a7dfaa2…`。QIMEI 时间/CRC32/随机半字节生成算法已由 SDK VM
固定输入探针闭合,随机字段仍会在每次生成时变化。
### 3.2 统计/会话字段(随机即可,服务端仅记录)
@@ -108,7 +108,7 @@ cd /Users/yml/codes/live-hub-py
## 六、风险与验证要求
当前实现已经通过活动 WSS 查询链路验证。`_qimei_uuid42` 仍只保证结构,`guid` 的回退值和设备字段持久化仍需继续完善;详细状态见 [HUYA_COOKIE路线状态.md](HUYA_COOKIE路线状态.md)。
当前实现已经通过活动 WSS 查询链路验证。`guid` 的回退值和设备字段持久化仍需继续完善;详细状态见 [HUYA_COOKIE路线状态.md](HUYA_COOKIE路线状态.md)。
## 七、各通道 Cookie 依赖矩阵(2026-09-01 晚实测)
@@ -30,7 +30,7 @@
同一网页会话内这些值保持稳定:
- `_qimei_uuid42`:42 位;`_qimei_h38`:38 位;`_qimei_fingerprint`:32 位。三者是 QIMEI 设备标识;其中 fingerprint 已按 SDK 能力特征串算法复刻,uuid42 仍只保证结构。
- `_qimei_uuid42`:42 位;`_qimei_fingerprint`:32 位,两者已按 SDK 0.6.3 算法复刻。早期文档曾把 `_qimei_h38` 记为独立 38 位设备标识,后续 VM 追踪确认 SDK 内部 `h38` 就是 42 位 UUID42;当前活动积分链路仅要求 Cookie 中存在 `_qimei_h38` 键。
- `udb_anobiztoken`:344 位 URL-safe 字符串,和 `udb_anouid` 共同属于匿名设备状态,不能用重复 UUID 字节拼接。
- `guid` 与 `udb_guiddata` 均为 32 位,但抓包值不同,不能复用同一画像字段。
- `udb_deviceid` 为 `w_` 加 19 位数字;格式可以校验,但仅凭格式无法得到真实值。
@@ -40,7 +40,7 @@
## 旧实现的问题
旧实现曾在空 Session 中生成 `__yamid_new`、`game_did`、三个 QIMEI 字段、`udb_anobiztoken`、`HMACCOUNT`、`_yasids` 和多个固定计数器。它们只能满足长度测试,不能证明值具有协议语义;当前 fingerprint 已替换为 SDK 算法,uuid42 仍保留结构化回退。
旧实现曾在空 Session 中生成 `__yamid_new`、`game_did`、两个 QIMEI 值、`_qimei_h38` 兼容键、`udb_anobiztoken`、`HMACCOUNT`、`_yasids` 和多个固定计数器。它们只能满足长度测试,不能证明值具有协议语义;当前 fingerprint 与 uuid42 均已替换为 SDK 0.6.3 算法,`_qimei_h38` 也已改为复用 SDK 内部 `h38` 的 UUID42 值。
旧实现还把 `device_info["guid32"][:32]` 同时写入 `guid` 和 `udb_guiddata`,并把手机号直接写入 `udb_passport`/`username`。这两点会造成设备身份和账号映射偏差。
@@ -52,7 +52,7 @@
### 9.1 抓包新增证据
`705-meta.json` 的 `GET www.huya.com/30596253` 在请求发出时已经携带 43 个网页 Cookie,
包括 `guid`、`game_did`、三个 QIMEI、`udb_guiddata`、`udb_deviceid`、`udb_anobiztoken`
包括 `guid`、`game_did`、QIMEI 相关字段、`udb_guiddata`、`udb_deviceid`、`udb_anobiztoken`
和统计字段;该响应没有 `Set-Cookie`。随后 `714-meta.json` 的
`POST df.huya.com/web/df/collect` 只返回 `sdid`、`hdid` 两个 `Set-Cookie`。
+27 -7
View File
@@ -15,12 +15,13 @@ App 登录可以得到新鲜的 `udb_cred`、`udb_uid`、`yyuid`、`udb_biztoken
| `udb_cred`、`udb_uid`、`yyuid`、`udb_biztoken` | 已完成 | App 登录与 QR 绑定链 |
| `sdid`、`hdid` | 已完成 | hydevice / `df/collect` |
| `udb_deviceid`、`udb_guiddata`、`udb_anobiztoken`、`udb_anouid` | 已完成 | `anon_device.py` |
| `guid` | 会话路径完成,回退算法未完全确认 | `wsLaunch` 返回值优先;回退值为结构仿造 |
| `guid` | 会话路径已闭合 | 活动 `wsLaunch` 每次签发 32 位 `sGuid`;初始化时统一覆盖 AUTH、getConfig 和后续业务 Cookie,`956a/966a/976a` 等中间段不是本地版本常量 |
| `__yamid_new` | 已完成 | `room_normal.js` `generate32` Python 复刻 |
| `game_did` | 已完成 | 35 位、63 字符集规则复刻 |
| `_yasids` | 格式完成,精确共享种子未确认 | 与 `__yamid_new` 使用同类时钟生成器 |
| `_qimei_uuid42` | 结构完成,SDK 内部算法待复刻 | `1a` + 40hex |
| `_qimei_uuid42` | 已完成 | QIMEI SDK 0.6.3 的 14 位时间前缀 + CRC32 替换段 + 20 位随机半字节段 |
| `_qimei_fingerprint` | 算法已复刻 | QIMEI `x64hash128(feature_string, 31)` |
| `_qimei_h38` | 兼容门槛已闭合 | SDK 内部 `h38` 就是 42 位 UUID42;活动积分链路只校验 Cookie 键存在,缺失时复用 `_qimei_uuid42` |
| 统计字段 | 已完成 | 线上查询已接受;部分字段仍是统计用途 |
## `_qimei_fingerprint` 算法
@@ -46,11 +47,9 @@ SDK/Python 输出:d07a45de567322edcd42312f38e610be
## 尚未闭合的工程项
1. 将真实 WebView/Chrome 的 `getFeature()` 结果接入登录调用,替代当前的设备画像近似值。
2. 对 `_qimei_uuid42` 做 SDK VM 级复刻,当前只保证结构。
3. 明确 `guid` 的 `956a` / `966a` 版本差异和无 `wsLaunch` 时的真实生成规则。
4. 让活动会话补齐后的 Cookie 持久化回账号,避免原始 16 字段账号每次任务重新生成设备字段。
5. 为 `raw_cookie` 增加重建网页 Cookie 的服务入口。
6. 商城下单、支付和支付状态轮询保持单独人工验证,不纳入只读回归。
2. 让活动会话补齐后的 Cookie 持久化回账号,避免原始 16 字段账号每次任务重新生成设备字段。
3. 为 `raw_cookie` 增加重建网页 Cookie 的服务入口。
4. 商城下单、支付和支付状态轮询保持单独人工验证,不纳入只读回归。
## 证据入口
@@ -58,3 +57,24 @@ SDK/Python 输出:d07a45de567322edcd42312f38e610be
- [Cookie 合并审计](HUYA_COOKIE合并审计与来源矩阵.md)
- [浏览器抓包报告](../evidence/browser_cookie_harvest/report.md)
- [虎牙精英宝典联调指南](HUYA精英宝典联调指南.md)
## `_qimei_uuid42` VM 复刻(2026-09-02)
固定时间 `1700000000000`、固定随机值时,SDK 观测值如下:
```text
random=0 17b0f060d1410085cc000000000000000000003207
random=0.25 17b0f060d14100037f4444444444444444444437df
random=0.5 17b0f060d1410053db888888888888888888883ff6
random=0.75 17b0f060d14100966bcccccccccccccccccccc1cf3
random=.999 17b0f060d141003174ffffffffffffffffffffd85d
sequence=0..f,0..3 17b0f060d14100b2230123456789abcdef012396a9
```
每个值都可以拆成 `14 + 4 + 20 + 4 = 42` 位。时间前缀由本地时间组成:年份末两位转十六进制并补两位、月份转十六进制、日/时/分/秒转十六进制并各补两位,最后追加 `cookieEnabled ? 100 : 000`。中间 20 位由 20 次独立的 `floor(Math.random() * 16)` 依次拼接;上面的单值向量因为探针固定了每次随机返回值,所以表现为相同半字节重复。两个 `----` 占位组成模板后,SDK 对模板 ASCII 字节计算标准 CRC32(多项式 `0xEDB88320`),将 8 位小写结果的前后四位分别替换占位,最后调用 `toLocaleLowerCase()`。Python 实现位于 `core/huya/web_cookie_fields.py`,并用上述固定与递增序列向量回归;随机上界按 15 处理,避免理论输入 `1.0` 产生两位半字节。VM 追踪在 `/tmp/qvmtrace17.out`,生成器入口为 `e=6064`,模板拼接和替换发生在 `m≈5015..5137`。该实现只用于查询链路的设备态生成,不触发兑换、下单或支付。
## `_qimei_h38` 兼容键(2026-09-02)
QIMEI SDK 0.6.3 的 `getQimei36(false)` 结果中,内部字段 `h38` 实际为上述 42 位 UUID42。当前无头 Chrome 在活动页不会生成名为 `_qimei_h38` 的 Cookie,现有浏览器采集证据中也没有该键。
账号 id=60 的活动 WSS 只读 A/B 表明:完全删除键时,角色查询返回 `200`,积分查询连续三轮均在 10 秒后无响应;保留空值、1 位或 8/37/38/39/42 位十六进制、38 位非十六进制值时,积分均在约 0.3 秒返回 `200`。因此它是当前积分链路的键存在性兼容门槛,不是独立的 38 位协议值;项目在缺失时写入 SDK `h38` 的真实值,即 `_qimei_uuid42`,已有值继续保留。
+24 -15
View File
@@ -33,7 +33,7 @@
| --- | --- | --- |
| `__yamid_new` | 88 条写入中无此 key,但最终 cookie 有值 | **CBCC 前缀 + 递增种子**(见下) |
| `game_did` | 同上 | 30-35 位字母数字 |
| `_qimei_uuid42` | 同上 | `1a` 前缀 + 32hex UUID 结构 + 10hex |
| `_qimei_uuid42` | 同上 | 14 位时间前缀 + 8 位 CRC32 替换值 + 20 位随机半字节 + 4 位 CRC32 尾段 |
## 三、设备字段结构规律(真实样本)
@@ -58,13 +58,13 @@ CBCC 06ECB5 0000 0001 B63016D6162BC990 ← reqable 8.31
`yamid=CBCC6479D9B0...` ↔ `rootsid=CBCC647A8A20...`(同会话,种子差 0xB1≈177)
- `0001` 固定,尾部大段随机
### _qimei_uuid42 = `1a` + 40hex(32hex UUID 结构 + 10hex 附加)
### _qimei_uuid42 = 14 位时间前缀 + CRC32 替换段 + 20 位随机半字节 + CRC32 尾段
```
1a81f140c08100b89fb1be450f640501568684b2ea ← reqable 8.31
1a901123a1f10045427c1c73420287f44f49d11b45 ← round2 fresh
1a901171b051007527940c2acef15dcd2342b6ff ← live 窗口
17b0f060d14100037f4444444444444444444437df ← 固定时间/随机 .25
17b0f060d1410053db888888888888888888883ff6 ← 固定时间/随机 .5
17b0f060d141003174ffffffffffffffffffffd85d ← 固定时间/随机 .999
```
首字节 `1a` 恒定;前 32 hex 符合 RFC 4122 UUID 布局(8-4-4-4-12)。
时间前缀的编码为:年份末两位十六进制(补两位)+ 月份十六进制 + 日/时/分/秒各两位十六进制 + `cookieEnabled` 标志(`100`/`000`)。模板 `prefix + "----" + random_nibbles + "----"` 的标准 CRC32 小写结果会拆成前后四位填回两个占位;`random_nibbles` 由 20 次独立的 `floor(Math.random() * 16)` 依次拼接,因此每位合法范围为 `0` 到 `f`。
### _qimei_fingerprint = x64hash128(feature_string, 31) 32hex
qimeisdk-web 0.6.3 源码已定位:
@@ -77,16 +77,17 @@ qimeisdk-web 0.6.3 源码已定位:
| 字段 | 来源 | 风控关联性 | 建议 |
| --- | --- | --- | --- |
| `guid` | 浏览器脚本(有固定段 `0a..966a`)| 高(设备与会话绑定) | **必须按结构仿造或复用 wsLaunch 会话值**;随机纯 hex 与真实结构不符 |
| `guid` | 活动 `wsLaunch` 响应 `sGuid`;页面 SDK 负责持久化 | 高(设备与会话绑定) | **优先复用当前 wsLaunch 会话值**;`956a/966a/976a` 等中间段随服务端返回变化,不能固化为版本常量 |
| `__yamid_new` | 浏览器脚本(CBCC 前缀+种子)| 高(与 rootsid 同源)| `room_normal.js` `generate32` 已复刻;精确 rootsid 共享计数仍待确认 |
| `_qimei_uuid42` | QIMEI SDK 0.6.3(`1a` 前缀)| 中 | 前缀 `1a` + UUID 布局 |
| `_qimei_uuid42` | QIMEI SDK 0.6.3 VM 生成器 `e=6064` | 中 | Python 已按时间编码、CRC32 和随机半字节逐项复刻 |
| `_qimei_fingerprint` | QIMEI SDK 0.6.3 x64hash128(feature_string, 31) | 中 | Python 已复刻,输入字段见路线状态文档 |
| `_qimei_h38` | 当前页面不写入同名 Cookie;SDK 内部 `h38` = UUID42 | 低 | 积分链路仅检查键存在,缺失时复用 `_qimei_uuid42` |
| `game_did` | 浏览器脚本 | 中 | 长度需对齐(35 变体含 `-`)|
| 统计字段(SoundValue 等)| 页面脚本 | 低 | 随机 OK |
**当时的下一步记录(部分已完成,保留作历史)**:
1. `_qimei_fingerprint` 已改为浏览器能力特征串的 `x64hash128`,见路线状态文档。
2. `guid` 已优先使用 `wsLaunch` 会话值,回退固定段仍待确认。
2. `guid` 已统一使用 `wsLaunch` 会话值;活动 AUTH、getConfig 与后续业务 Cookie 均复用同一返回值。
3. `__yamid_new` 已定位 `room_normal.js` `generate32` 并完成 Python 复刻。
## 六、核心字段生成算法逆向结果(2026-09-01 晚,浏览器实测 + 源码定位)
@@ -116,10 +117,18 @@ B = (t=35) => { const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012
- **长度 35**(旧随机 30 位是错的);字符集 64 去掉末尾 `_`(63 选 1)
- cookie 名 `game_did`,无 cookie 时生成并写入
### ⚠️ _qimei_uuid42 结构已定,算法待深挖
- cookie 值:首字节 `1a` 固定 + 40hex(localStorage 是 44hex,cookie 为截断子串)
- 由 qimeisdk-web 0.6.3 内部 VM 生成(`_qimei_ssid`/`_qimei_last_get_id_time_<16hex>` 同源)
- 当前实现对齐结构(1a 前缀 + 42hex 随机化),精确算法待继续
### ✅ _qimei_uuid42 = QIMEI SDK VM 生成器(已 Python 复刻)
清理 localStorage/cookie 后对 QIMEI SDK 0.6.3 做固定时间、固定随机值追踪,定位到 VM 生成器 `e=6064`。它先拼出:
```text
14 位时间前缀 + "----" + 20 次独立抽样组成的随机半字节串 + "----"
```
随后计算模板 ASCII 字节的标准 CRC32,将 8 位小写结果的前 4 位和后 4 位分别填入占位,最后调用 `toLocaleLowerCase()`。例如固定每次 `random=0.25` 时,模板是 `17b0f060d14100----44444444444444444444----`,替换值是 `037f37df`,结果为 `17b0f060d14100037f4444444444444444444437df`;递增序列探针则得到随机段 `0123456789abcdef0123`,证明 SDK 会独立抽样 20 次。`navigator.cookieEnabled` 只影响时间前缀末三位(`100`/`000`)。
- 由 qimeisdk-web 0.6.3 内部 VM 生成(`_qimei_ssid`/`_qimei_last_get_id_time_<16hex>` 同源);字段本身为 42 位小写十六进制。
- Python 实现按 SDK 时间、CRC32 和随机上界复刻,固定向量覆盖 `0`、`.25`、`.5`、`.75`、`.999`。
- SDK 对该内部值使用 `h38` 属性名,但它的长度是 42;`_qimei_h38` 只是活动积分链路的 Cookie 兼容键,不存在另一套 38 位 SDK 生成算法。
### ✅ _qimei_fingerprint = x64hash128(feature_string,31),已完成 Python 复刻
- Cookie 输入由屏幕分辨率、浏览器能力、WebGL 和时区字段按 `###` 拼接。
@@ -130,7 +139,7 @@ B = (t=35) => { const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012
- `__yamid_new` → `_yamid_new_generate32()`(UUID-v1 时间戳复刻)
- `game_did` → `_game_did_generate()`(35 位 63 字符集)
- `_yasids` → 与 `__yamid_new` 同源同刻生成
- `_qimei_uuid42` → `1a` 前缀 + 42hex
- `_qimei_uuid42` → `_qimei_uuid42_generate()`(14 位时间前缀 + CRC32 替换段 + 20 位随机半字节 + CRC32 尾段)
- `guid`(无会话值回退)→ `0a` + 10hex + `966a` + 16hex 结构
## 七、逆向生成器端到端验证(2026-09-01 晚,账号 18397482576 重新登录后)
@@ -138,7 +147,7 @@ B = (t=35) => { const e="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012
新版生成器(web_cookie_fields.py commit 8fef04d)产出字段:
- guid=`0a43b01a366c966a7fe26a281e1d3c88`(0a 前缀 + 966a 固定段)
- __yamid_new=`CBCC65D6C5200001F176114BCF181E25`(UUIDv1 时间戳)
- _qimei_uuid42=`1a552b4b...`(1a 前缀)
- _qimei_uuid42=42 位小写十六进制(SDK VM 时间/CRC32 结构)
- game_did=35 位
- _yasids 与 yamid 同源(CBCC65D6C5 前缀一致)
+2 -2
View File
@@ -53,8 +53,8 @@ Cookie 缺少网页设备态(udb_deviceid, udb_guiddata, udb_anobiztoken),已
```
`guid`/`game_did`/`_qimei_uuid42`/`__yamid_new` 四个脚本字段无统一服务端签发接口;
当前登录链已接入 `guid` 会话值、`__yamid_new`、`game_did` 和 fingerprint 算法,
`_qimei_uuid42` 仍使用结构化回退,WSS 判定不要求脚本字段全部来自浏览器。
当前登录链已接入 `guid` 会话值、`__yamid_new`、`game_did`、fingerprint 和
`_qimei_uuid42` 的 SDK 算法,WSS 判定不要求脚本字段全部来自浏览器。
- WSS 握手、`wsLaunch`、`getConfig` 或业务 RPC 任一步失败:任务直接失败并记录具体阶段,便于修复 Cookie 或协议参数。
+53
View File
@@ -0,0 +1,53 @@
from pathlib import Path
from core.huya import browser_harvest
class _FakeStderr:
def readline(self):
return "DevTools listening on ws://127.0.0.1/devtools/browser/test\n"
class _FakeProcess:
stderr = _FakeStderr()
def kill(self):
pass
def test_launch_defaults_to_headless(monkeypatch):
calls = []
def fake_popen(args, **kwargs):
calls.append((args, kwargs))
return _FakeProcess()
def no_http(*args, **kwargs):
raise OSError("test: no CDP endpoint")
monkeypatch.setattr(browser_harvest.subprocess, "Popen", fake_popen)
monkeypatch.setattr(browser_harvest.urllib.request, "urlopen", no_http)
browser_harvest.launch(Path("/tmp/test-huya-profile"), 9555)
args, kwargs = calls[0]
assert "--headless=new" in args
assert kwargs["stdout"] is browser_harvest.subprocess.DEVNULL
def test_launch_can_show_window_when_requested(monkeypatch):
calls = []
def fake_popen(args, **kwargs):
calls.append(args)
return _FakeProcess()
def no_http(*args, **kwargs):
raise OSError("test: no CDP endpoint")
monkeypatch.setattr(browser_harvest.subprocess, "Popen", fake_popen)
monkeypatch.setattr(browser_harvest.urllib.request, "urlopen", no_http)
browser_harvest.launch(Path("/tmp/test-huya-profile"), 9556, headless=False)
assert "--headless=new" not in calls[0]
+44 -9
View File
@@ -95,14 +95,14 @@ def test_shop_preflight_response_contracts():
def test_wss_requires_web_device_cookie_fields():
assert not HuyaBatchRunnerCore._has_web_wss_cookie(
"udb_cred=x; udb_biztoken=x; udb_uid=1; yyuid=1"
)
assert HuyaBatchRunnerCore._has_web_wss_cookie(
"udb_cred=x; udb_biztoken=x; udb_uid=1; yyuid=1; sdid=s; guid=g; "
"udb_guiddata=gd; udb_deviceid=w_1234567890123456789; game_did=did; "
"_qimei_uuid42=q; udb_anobiztoken=ab; __yamid_new=y"
)
assert not HuyaBatchRunnerCore._has_web_wss_cookie(
"udb_cred=x; udb_biztoken=x; udb_uid=1; yyuid=1"
)
assert HuyaBatchRunnerCore._has_web_wss_cookie(
"udb_cred=x; udb_biztoken=x; udb_uid=1; yyuid=1; sdid=s; guid=g; "
"udb_guiddata=gd; udb_deviceid=w_1234567890123456789; game_did=did; "
"_qimei_uuid42=q; udb_anobiztoken=ab; __yamid_new=y"
)
def test_activity_auth_frame_matches_latest_capture_layout():
@@ -112,6 +112,7 @@ def test_activity_auth_frame_matches_latest_capture_layout():
-> tag3 STRING1 guid(32hex) -> tag4 INT8=1 -> tag5 "HUYA&ZH&2052"
-> tag6 "" -> TAIL_BYTES
"""
async def build_frame():
client = HuyaWssClient()
client._activity_mode = True
@@ -145,4 +146,38 @@ def test_activity_auth_frame_matches_latest_capture_layout():
assert stream.read_string(6) == ""
# body 必须与 9.1 828 AUTH 同样以 TAIL_BYTES 收尾
assert message.body[-len(TAIL_BYTES):] == TAIL_BYTES
assert message.body[-len(TAIL_BYTES) :] == TAIL_BYTES
def test_activity_cookie_guid_is_replaced_by_launch_guid():
old = "0a" + "1" * 30
new = "0a" + "2" * 30
cookie = f"udb_uid=1; guid={old}; x=y; guid={old}"
result = HuyaWssClient._cookie_with_guid(cookie, new)
assert result == f"udb_uid=1; guid={new}; x=y"
def test_activity_auth_accepts_explicit_launch_guid_over_cookie_guid():
async def build_frame():
client = HuyaWssClient()
client._activity_mode = True
client.ws = type("FakeWs", (), {"send": AsyncMock()})()
await client.send_auth(
1199664135026,
"guid=" + "0a" * 16 + "; udb_cred=" + "x" * 300,
sequence=0x1D000109,
guid="0b" * 16,
)
return client.ws.send.call_args.args[0]
message = WssMessage.decode(asyncio.run(build_frame()))
stream = TafInputStream(message.body[: -len(TAIL_BYTES)])
assert stream.read_head() == (3, TafType.ZERO)
stream.read_int64(0)
stream.read_string(1)
assert stream.read_head() == (2, TafType.STRING4)
cookie_len = int.from_bytes(stream.buf.read(4), "big")
stream.buf.read(cookie_len)
assert stream.read_string(3) == "0b" * 16
+92 -12
View File
@@ -2,6 +2,7 @@
from core.huya.web_cookie_fields import (
_qimei_feature_string,
_qimei_uuid42_generate,
_x64hash128,
cookie_fields,
fill_web_cookie_fields,
@@ -43,16 +44,91 @@ def test_fill_replaces_empty_values_and_completes_core_fields():
assert fields["__yamid_new"]
assert fields["game_did"]
assert fields["_qimei_fingerprint"] == qimei_fingerprint_generate()
assert fields["_qimei_h38"] == fields["_qimei_uuid42"]
assert not missing_web_cookie_fields(result)
def test_qimei_h38_aliases_uuid42_without_overwriting_existing_value():
uuid42 = "1" * 42
fields = cookie_fields(
fill_web_cookie_fields(f"_qimei_uuid42={uuid42}; _qimei_h38=", "")
)
assert fields["_qimei_h38"] == uuid42
fields = cookie_fields(
fill_web_cookie_fields(f"_qimei_uuid42={uuid42}; _qimei_h38=historical", "")
)
assert fields["_qimei_h38"] == "historical"
def test_qimei_uuid42_matches_sdk_vectors_and_random_upper_bound():
base = 1700000000000000000
assert _qimei_uuid42_generate(base, random_value=0.25) == (
"17b0f060d14100037f4444444444444444444437df"
)
assert _qimei_uuid42_generate(base, random_value=0.5) == (
"17b0f060d1410053db888888888888888888883ff6"
)
upper = _qimei_uuid42_generate(base, random_value=1.0)
assert len(upper) == 42
assert upper[18:38] == "f" * 20
assert all(ch in "0123456789abcdef" for ch in upper)
def test_qimei_uuid42_uses_twenty_independent_random_draws(monkeypatch):
values = iter(value / 16 for value in (*range(16), *range(4)))
calls = 0
def next_random():
nonlocal calls
calls += 1
return next(values)
monkeypatch.setattr("core.huya.web_cookie_fields.random.random", next_random)
assert _qimei_uuid42_generate(1700000000000000000) == (
"17b0f060d14100b2230123456789abcdef012396a9"
)
assert calls == 20
def test_qimei_uuid42_encodes_local_date_and_cookie_flag():
base = 1700000000000000000
assert _qimei_uuid42_generate(base, random_value=0, cookie_enabled=False) == (
"17b0f060d140008b2b00000000000000000000dad6"
)
def test_qimei_uuid42_handles_year_zero_padding():
# 2000-01-01 08:00:00 local time; SDK emits 00 + 1 + 08 + 00 + 00 + 100.
value = _qimei_uuid42_generate(946684800000000000, random_value=0)
assert value[:14] == "00101080000100"
def test_sdk_uuid42_trace_vectors_have_confirmed_outer_layout():
"""锁定 SDK 追踪确认的 14+4+20+4 外层布局和固定随机向量。"""
vectors = {
0.0: "17b0f060d1410085cc000000000000000000003207",
0.25: "17b0f060d14100037f4444444444444444444437df",
0.5: "17b0f060d1410053db888888888888888888883ff6",
0.75: "17b0f060d14100966bcccccccccccccccccccc1cf3",
0.999: "17b0f060d141003174ffffffffffffffffffffd85d",
}
for random_value, value in vectors.items():
assert len(value) == 42
assert value[:14] == "17b0f060d14100"
assert value[18:38] == f"{int(random_value * 16):x}" * 20
assert all(char in "0123456789abcdef" for char in value)
def test_device_profile_builds_stable_webview_feature_approximation():
feature = qimei_feature_from_device_profile({
"vendor": "vivo",
"model": "V2370A",
"width": "1080",
"height": "2412",
})
feature = qimei_feature_from_device_profile(
{
"vendor": "vivo",
"model": "V2370A",
"width": "1080",
"height": "2412",
}
)
assert feature["screen"] == {
"resolution": "1080x2412",
"availResolution": "1080x2412",
@@ -60,11 +136,15 @@ def test_device_profile_builds_stable_webview_feature_approximation():
assert feature["navigator"]["pdfViewerEnabled"] is False
assert "Adreno" in str(feature["webgl"])
first = qimei_fingerprint_generate(feature)
second = qimei_fingerprint_generate(qimei_feature_from_device_profile({
"vendor": "vivo",
"model": "V2370A",
"width": "1080",
"height": "2412",
}))
second = qimei_fingerprint_generate(
qimei_feature_from_device_profile(
{
"vendor": "vivo",
"model": "V2370A",
"width": "1080",
"height": "2412",
}
)
)
assert first == second
assert first != qimei_fingerprint_generate()