feat(huya): 分身 CK 支持 cred0 解密补全,WSS 帧改为 JCE WebSocketCommand

- scripts/huya_clone_ck.py: root 读取小X分身/真身 WebView Cookie,默认
  用 AES-128-ECB(UDB 主密钥前 16B) 解 cred0 注入 udb_cred,新增
  --anon-device 补匿名设备字段、--no-cred0 退回旧行为
- core/huya/wss_client.py: 帧层改用浏览器 HUYA.WebSocketCommand(JCE)
  结构,vData 直接放 Wup 原包,按 WUP iRequestId 匹配响应,初始化顺序
  对齐 RegisterGroup→wsLaunch→VerifyCookie→getConfig→UpdateUserExps
- tests: 帧级断言改为新结构,假 WS 按 requestId 兑现
- docs: 新增分身 CK 提取、HAR 提取 CK 与积分中心说明

实测:四个分身 cred0 解出 udb_cred(39/43 字段),WSS
PlayMallUI.queryAllocation 返回 code=200、18 个商品;tests -k huya 394 passed
This commit is contained in:
yml2213
2026-10-26 11:23:29 +08:00
parent 6fc453017c
commit 03bc0818dd
9 changed files with 1188 additions and 156 deletions
+16 -4
View File
@@ -1178,11 +1178,13 @@ def parse_points_center_gifts(payload: dict | None) -> list[dict]:
→ tag4 分类名
→ tag5 图标
→ tag9/tag10 金额(分,不是积分)
→ tag13 库存
→ tag14 剩余库存(tag17[0].tag3 兜底)
→ tag13 累计兑换/销量
→ tag75.tag0.tag2 积分
→ tag34.tag26 积分(重复字段,兜底)
注意:``tag13`` 在这里是库存,不是 ``ActPrizeItem.price`` 的那个 tag13。
注意:2026-10-25 抓包里 ``tag14`` 才是剩余库存,和 SKU ``tag17[0].tag3``
一致;``tag13`` 是累计兑换/销量。旧抓包没有 ``tag14`` 时才回退 ``tag13``。
"""
if not isinstance(payload, dict):
return []
@@ -1234,14 +1236,24 @@ def parse_points_center_gifts(payload: dict | None) -> list[dict]:
else None
)
stock = _as_int(basic.get("tag13"))
# 2026-10-25 抓包:tag13 是累计兑换/销量,tag14 才是剩余库存,
# 且与 SKU 列表 tag17[0].tag3 一致;旧抓包没有 tag14 时回退 tag13。
claimed = _as_int(basic.get("tag13"))
stock = _as_int(basic.get("tag14"))
if stock is None:
skus = basic.get("tag17")
if isinstance(skus, list) and skus and isinstance(skus[0], dict):
stock = _as_int(skus[0].get("tag3"))
if stock is None:
stock = claimed
gifts.append(
{
"product_id": spu,
"name": name[:256],
"price": points,
"remain_text": f"剩{stock}" if stock is not None else "",
"remain_text": str(stock) if stock is not None else "",
"stock": stock,
"claimed": claimed,
"score": points,
"category_name": (_as_text(basic.get("tag4")) or category_name)[
:64
+153 -112
View File
@@ -18,8 +18,6 @@
import asyncio
import random
import re
import struct
from collections import deque
from collections.abc import Callable
from typing import Any, cast
@@ -41,8 +39,6 @@ ACTIVITY_WS_HOST = "d35bf373-ws.va.huya.com"
# wsLaunch tReq: lUid=0, sGuid="", sUA="webh5&0.0.1&websocket&&h5_/index.html"
SHOP_BASEINFO = "DBYAJiV3ZWJoNSYwLjAuMSZ3ZWJzb2NrZXQmJmg1Xy9pbmRleC5odG1sNgxIVVlBJlpIJjIwNTJGAFYAbHYAhgCWAKgM"
TAIL_BYTES = bytes.fromhex("2c36004c5c6600")
BIG_TAIL_SUFFIX = bytes.fromhex("4c5c6600")
WSS_BIZ_UA = "web&1.0.0&huya"
WSS_COOKIE_UA = "webh5&0.0.1&websocket&&diypc_52775"
WSS_SHOP_SCENE = 4
@@ -114,33 +110,81 @@ POINTS_ORDER_METHODS = frozenset({"createOrderV5", "payOrderSubmitV5"})
class WssCommand:
RPC_REQUEST = 0x03
RPC_RESPONSE = 0x04
HEARTBEAT = 0x05
HEARTBEAT_ACK = 0x06
AUTH = 0x0A
SERVER_PUSH1 = 0x0B
HEARTBEAT_SEND = 0x10
HEARTBEAT_RECV = 0x11
CONFIRM_SEND = 0x17
SERVER_PUSH2 = 0x18
REGISTER = 0x21
AUTH_RESPONSE = 0x0B
HEARTBEAT_SEND = 0x10 # EWSCmdC2S_RegisterGroupReq
HEARTBEAT_RECV = 0x11 # EWSCmdS2C_RegisterGroupRsp
CONFIRM_SEND = 0x17 # EWSCmdC2S_UpdateUserExpsReq
CONFIRM_RECV = 0x18
PING = 0x14 # EWSCmdC2S_HeartBeatReq
PING_ACK = 0x15 # EWSCmdS2C_HeartBeatRsp
REGISTER = 0x21 # EWSCmdC2S_UpdateUserInfoReq
class WssMessage:
def __init__(self, command: int, sequence: int, body: bytes):
"""浏览器 ``HUYA.WebSocketCommand``(TAF/JCE 结构,2026-10-25 对齐 huya-go)。
结构字段:
0 iCmdType(int32) 1 vData(bytes) 2 lRequestId(int64)
3 traceId(string) 4 iEncryptType(int32) 5 lTime(int64) 6 sMD5(string)
``sequence`` 保留旧命名,实际承载 ``lRequestId``;``body`` 即 ``vData``。
"""
def __init__(
self,
command: int = 0,
sequence: int = 0,
body: bytes = b"",
*,
trace_id: str = "",
encrypt_type: int = 0,
timestamp: int = 0,
md5: str = "",
):
self.command = command
self.sequence = sequence
self.body = body
self.trace_id = trace_id
self.encrypt_type = encrypt_type
self.timestamp = timestamp
self.md5 = md5
def encode(self) -> bytes:
header = struct.pack(">BBI", 0x00, self.command, self.sequence)
return header + self.body
os = TafOutputStream()
os.write_int32(0, int(self.command))
os.write_bytes(1, self.body or b"")
os.write_int64(2, int(self.sequence))
os.write_string(3, self.trace_id)
os.write_int32(4, int(self.encrypt_type))
os.write_int64(5, int(self.timestamp))
os.write_string(6, self.md5)
return os.get_bytes()
@classmethod
def decode(cls, data: bytes) -> "WssMessage":
if len(data) < 6:
if len(data) < 2:
raise ValueError(f"消息太短: {len(data)} bytes")
_version, command = struct.unpack(">BB", data[0:2])
sequence = struct.unpack(">I", data[2:6])[0]
body = data[6:]
return cls(command=command, sequence=sequence, body=body)
ins = TafInputStream(data)
# 必须按结构字段顺序读取:tag0 命令 → tag1 数据 → tag2 requestId → ...
command = ins.read_int32(0)
body = ins.read_bytes(1)
request_id = ins.read_int64(2)
trace_id = ins.read_string(3)
encrypt_type = ins.read_int32(4)
timestamp = ins.read_int64(5)
md5 = ins.read_string(6)
return cls(
command=command,
sequence=request_id,
body=body,
trace_id=trace_id,
encrypt_type=encrypt_type,
timestamp=timestamp,
md5=md5,
)
class HuyaWssClient:
@@ -153,7 +197,9 @@ class HuyaWssClient:
self.ws: Any = None
self._biz_seq = SEQ_BUSINESS # 业务 RPC 递增用
self._wup_req_id = 8
self.rpc_queue = deque()
# 按 WUP iRequestId 匹配响应(浏览器/HAR 实测:服务端回包 requestID 与请求一致)
self._pending: dict[int, asyncio.Future] = {}
self.logger = logger or print
self._recv_task = None
self._heartbeat_task = None
@@ -183,49 +229,24 @@ class HuyaWssClient:
return req_id
@staticmethod
def _make_big_tail() -> bytes:
"""生成 WSS 大包尾部 trace(格式与浏览器 HAR 一致)"""
def _new_trace_id() -> str:
"""浏览器帧 traceId: ``<hex>:<hex>:0:<enableTrace>``。"""
trace = f"{random.getrandbits(64):016x}"
return f",6%{trace}:{trace}:0:3".encode("ascii") + BIG_TAIL_SUFFIX
return f"{trace}:{trace}:0:0"
@staticmethod
def _encode_rpc_body(wup_data: bytes) -> bytes:
"""按浏览器规则封装 WSS RPC body
"""业务 RPC 的 vData 就是 WUP 原包(长度前缀 + WUP 结构)。
小包: [4B WUP长度][WUP body] + TAIL_BYTES
大包: [1B len低字节][4B WUP body长度][裸WUP body] + trace尾部
2026-10-25 对齐 huya-go:浏览器把 ``Wup.encode()`` 的结果原样放进
``WebSocketCommand.vData``,不再拼 trace/尾部字节。
"""
if len(wup_data) < 4:
return wup_data + TAIL_BYTES
declared_len = int.from_bytes(wup_data[:4], "big")
if declared_len == len(wup_data):
wup_body = wup_data[4:]
else:
wup_body = wup_data
if len(wup_body) <= 0xFF:
return wup_data + TAIL_BYTES
# 大包头里的长度使用原始 WUP 包长度(含 4B 长度前缀),但正文只放裸 WUP body;
# 浏览器随后用 trace 尾部的前 4 字节补足该长度窗口。
packet_len = len(wup_data)
return (
bytes([packet_len & 0xFF])
+ packet_len.to_bytes(4, "big")
+ wup_body
+ HuyaWssClient._make_big_tail()
)
return wup_data
@staticmethod
def _encode_activity_launch_body(wup_data: bytes) -> bytes:
"""活动 wsLaunch 使用浏览器的固定大包头,即使包体小于 255B。"""
if len(wup_data) < 4:
return wup_data + TAIL_BYTES
packet_len = len(wup_data)
return (
bytes([packet_len & 0xFF])
+ packet_len.to_bytes(4, "big")
+ wup_data[4:]
+ TAIL_BYTES
)
"""wsLaunch 同样直接使用 WUP 原包。"""
return wup_data
@staticmethod
def _normalize_biz_cookie(cookie: str) -> str:
@@ -402,42 +423,65 @@ class HuyaWssClient:
except Exception as e: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
self.logger(f"[WSS] 接收循环异常: {type(e).__name__}: {e}")
@staticmethod
def _wup_request_id(body: bytes) -> int | None:
"""从 WSS 回包 vData 里解出 WUP iRequestId(失败返回 None)。"""
try:
wup = WupResponse()
wup.decode(HuyaWssClient._extract_wup(body))
return int(wup.iRequestId)
except Exception: # noqa: BLE001 外部响应可能不完整,按未匹配处理
return None
async def _handle_message(self, msg: WssMessage):
if msg.command == WssCommand.RPC_RESPONSE:
if self.rpc_queue:
future = self.rpc_queue.popleft()
if not future.done():
future.set_result(msg.body)
request_id = self._wup_request_id(msg.body)
future = (
self._pending.pop(request_id, None) if request_id is not None else None
)
if future is None and len(self._pending) == 1:
# 兜底:服务端偶尔不回原始 requestId,只剩一个在途请求时直接认领
fallback_id, fallback = next(iter(self._pending.items()))
self._pending.pop(fallback_id, None)
future = fallback
if future is not None and not future.done():
future.set_result(msg.body)
else:
self.logger(f"[WSS] 未匹配的 RPC 响应 seq={msg.sequence}")
elif msg.command == WssCommand.HEARTBEAT_RECV:
pass # 心跳已在上层 _recv_loop 打过日志
elif msg.command in (WssCommand.SERVER_PUSH1, WssCommand.SERVER_PUSH2):
pass # 推送已在上层打过日志
else:
pass # 未知消息已在上层打过日志
self.logger(f"[WSS] 未匹配的 RPC 响应 requestId={request_id}")
elif msg.command in (
WssCommand.PING_ACK,
WssCommand.HEARTBEAT_ACK,
WssCommand.HEARTBEAT_RECV,
WssCommand.AUTH_RESPONSE,
WssCommand.CONFIRM_RECV,
):
pass # 控制类响应无需处理,日志已在 _recv_loop 打出
async def _heartbeat_loop(self):
try:
while True:
await asyncio.sleep(8)
await self.send_heartbeat()
await self.send_ping()
except asyncio.CancelledError:
pass
except Exception as e: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底
self.logger(f"[WSS] 心跳循环异常: {e}")
async def send_ping(self):
"""EWSCmdC2S_HeartBeatReq(20),vData 为空(对齐 huya-go)。"""
msg = WssMessage(command=WssCommand.PING, sequence=0, body=b"")
await self.ws.send(msg.encode())
async def send_heartbeat(self):
# body = LIST(tag0,count=1) + 元素{tag0="live:0", tag1=""} + TAIL
"""EWSCmdC2S_RegisterGroupReq(16):vData = list{"live:0"} + token。"""
os = TafOutputStream()
os.write_head(0, TafType.LIST) # 09
os.write_int32(0, 1) # 00 01 (count=1)
os.write_string(0, "live:0") # 06 06 live:0
os.buf.write(b"\x16\x00") # 16 00 (tag1 "")
body = os.get_bytes() + TAIL_BYTES
msg = WssMessage(
command=WssCommand.HEARTBEAT_SEND, sequence=SEQ_HEARTBEAT, body=body
)
os.write_string(1, "") # 16 00
body = os.get_bytes()
msg = WssMessage(command=WssCommand.HEARTBEAT_SEND, sequence=0, body=body)
self.logger(
format_wss_log(body, WssCommand.HEARTBEAT_SEND, SEQ_HEARTBEAT, "发")
)
@@ -530,18 +574,15 @@ class HuyaWssClient:
wup.iTimeout = 0
wup.newdata["tReq"] = os.get_bytes()
body = self._encode_activity_launch_body(wup.encode())
msg = WssMessage(WssCommand.RPC_REQUEST, SEQ_ACTIVITY_WSLAUNCH, body)
msg = WssMessage(WssCommand.RPC_REQUEST, 0, body)
future = asyncio.Future()
self.rpc_queue.append(future)
self.logger(
format_wss_log(body, WssCommand.RPC_REQUEST, SEQ_ACTIVITY_WSLAUNCH, "发")
)
self._pending[-1] = future
self.logger(format_wss_log(body, WssCommand.RPC_REQUEST, -1, "发"))
await self.ws.send(msg.encode())
try:
response = await asyncio.wait_for(future, timeout)
except TimeoutError:
if future in self.rpc_queue:
self.rpc_queue.remove(future)
self._pending.pop(-1, None)
return None
self.logger(
format_wss_log(
@@ -601,18 +642,16 @@ class HuyaWssClient:
wup_data = wup.encode()
body = self._encode_rpc_body(wup_data)
seq = SEQ_ACTIVITY_WSLAUNCH
msg = WssMessage(command=WssCommand.RPC_REQUEST, sequence=seq, body=body)
msg = WssMessage(command=WssCommand.RPC_REQUEST, sequence=0, body=body)
future = asyncio.Future()
self.rpc_queue.append(future)
self.logger(format_wss_log(body, WssCommand.RPC_REQUEST, seq, "发"))
self._pending[-1] = future
self.logger(format_wss_log(body, WssCommand.RPC_REQUEST, -1, "发"))
await self.ws.send(msg.encode())
try:
body = await asyncio.wait_for(future, timeout)
except TimeoutError:
if future in self.rpc_queue:
self.rpc_queue.remove(future)
self._pending.pop(-1, None)
self.logger("[✗] wsLaunch 超时")
return None
@@ -716,8 +755,6 @@ class HuyaWssClient:
``ua`` 可覆盖:积分中心页面为 ``h5_/points.html``(2026-10-13 抓包)。
"""
os = TafOutputStream()
if self._activity_mode or self._points_mode:
os.write_head(3, TafType.ZERO)
os.write_int64(0, int(uid or 0))
os.write_string(1, ua or WSS_COOKIE_UA)
os.write_string(2, HuyaWssClient._normalize_biz_cookie(cookie))
@@ -728,13 +765,12 @@ class HuyaWssClient:
or self._launch_guid
)
os.write_string(3, auth_guid)
os.write_int8(4, 1)
os.write_int32(4, 1) # AutoRegisterUID
os.write_string(5, "HUYA&ZH&2052")
os.write_string(6, "")
auth_body = os.get_bytes() + TAIL_BYTES
auth_body = os.get_bytes()
msg = WssMessage(
command=WssCommand.AUTH,
sequence=sequence,
sequence=0,
body=auth_body,
)
await self.ws.send(msg.encode())
@@ -796,8 +832,8 @@ class HuyaWssClient:
os.write_struct_end()
os.write_map(7, {})
os.write_int32(8, 0)
body = os.get_bytes() + TAIL_BYTES
msg = WssMessage(command=WssCommand.REGISTER, sequence=SEQ_REGISTER, body=body)
body = os.get_bytes()
msg = WssMessage(command=WssCommand.REGISTER, sequence=0, body=body)
self.logger(format_wss_log(body, WssCommand.REGISTER, SEQ_REGISTER, "发"))
await self.ws.send(msg.encode())
@@ -809,10 +845,8 @@ class HuyaWssClient:
"""
os = TafOutputStream()
os.write_map(0, version_map or {})
body = os.get_bytes() + TAIL_BYTES
msg = WssMessage(
command=WssCommand.CONFIRM_SEND, sequence=SEQ_CONFIRM, body=body
)
body = os.get_bytes()
msg = WssMessage(command=WssCommand.CONFIRM_SEND, sequence=0, body=body)
self.logger(format_wss_log(body, WssCommand.CONFIRM_SEND, SEQ_CONFIRM, "发"))
await self.ws.send(msg.encode())
@@ -880,28 +914,32 @@ class HuyaWssClient:
rsp_class=None,
timeout: float = 10.0,
):
seq = self._next_biz_seq(method in POINTS_ORDER_METHODS)
wup = WupRequest()
wup.setServant(service)
wup.setFunc(method)
wup.setRequestId(self._next_wup_req_id())
req_id = self._next_wup_req_id()
wup.setRequestId(req_id)
wup.iTimeout = 0
wup.writeStruct("tReq", req_struct)
wup_data = wup.encode()
body = self._encode_rpc_body(wup_data)
msg = WssMessage(command=WssCommand.RPC_REQUEST, sequence=seq, body=body)
# 浏览器帧的 lRequestId 固定 0,区分请求靠 traceId + WUP iRequestId
msg = WssMessage(
command=WssCommand.RPC_REQUEST,
sequence=0,
body=body,
trace_id=self._new_trace_id(),
)
future = asyncio.Future()
self.rpc_queue.append(future)
self.logger(format_wss_log(body, WssCommand.RPC_REQUEST, seq, "发"))
self._pending[req_id] = future
self.logger(format_wss_log(body, WssCommand.RPC_REQUEST, req_id, "发"))
await self.ws.send(msg.encode())
try:
body = await asyncio.wait_for(future, timeout)
except TimeoutError:
if future in self.rpc_queue:
self.rpc_queue.remove(future)
self._pending.pop(req_id, None)
self.logger(f"[✗] {service}.{method} 超时")
return None
@@ -1302,28 +1340,31 @@ class HuyaWssClient:
os.write_struct_end()
seq = self._next_biz_seq(True)
wup = WupRequest()
wup.setServant("shopMiddleUI")
wup.setFunc("payOrderSubmitV5")
wup.setRequestId(self._next_wup_req_id())
req_id = self._next_wup_req_id()
wup.setRequestId(req_id)
wup.iTimeout = 0
wup.newdata["tReq"] = os.get_bytes()
wup_data = wup.encode()
body = self._encode_rpc_body(wup_data)
msg = WssMessage(command=WssCommand.RPC_REQUEST, sequence=seq, body=body)
msg = WssMessage(
command=WssCommand.RPC_REQUEST,
sequence=0,
body=body,
trace_id=self._new_trace_id(),
)
future = asyncio.Future()
self.rpc_queue.append(future)
self.logger(format_wss_log(body, WssCommand.RPC_REQUEST, seq, "发"))
self._pending[req_id] = future
self.logger(format_wss_log(body, WssCommand.RPC_REQUEST, req_id, "发"))
await self.ws.send(msg.encode())
try:
body = await asyncio.wait_for(future, 15.0)
except TimeoutError:
if future in self.rpc_queue:
self.rpc_queue.remove(future)
self._pending.pop(req_id, None)
self.logger("[✗] payOrderSubmitV5 超时")
return None