feat(huya): 支持四段式账号导入接码及旋转/文本点选多级验证码闭环过验
- 账号导入:支持'账号----密码----手机号----接码链接'四段式解析与持久化存储 - 旋转验证码 (rotate_auth / xz):逆向分析官方协议,基于圆周边界采样互相关算法秒级计算旋转还原角度 - 文本点选验证码 (dx_auth):内置成语与古诗名句语料,支持题干菜名提取与古诗/成语挖空正则求解及小图动态合成 - 短信二次验证 (sms_auth2):结合 sms_url 自动轮询接码链接并 Hex 编码提交官方过验 - 前端交互:增加接码标签、在线查询短信验证码、一键自动短信登录与测试接码链接功能 - 回归测试:新增旋转验证、短信接码流与文本点选测试用例(173 passed)
This commit is contained in:
@@ -9,17 +9,19 @@ import random
|
||||
import time
|
||||
import uuid
|
||||
from collections.abc import Mapping
|
||||
from datetime import UTC, datetime
|
||||
from http.cookies import SimpleCookie
|
||||
from pathlib import Path
|
||||
from typing import Any, cast
|
||||
from urllib.parse import parse_qs, quote, urlparse
|
||||
|
||||
import re
|
||||
import cv2
|
||||
import execjs
|
||||
import numpy as np
|
||||
import requests
|
||||
from loguru import logger
|
||||
from PIL import Image
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
from .capture import CaptchaCaptureRecord
|
||||
from .ocr import HuyaCaptchaOcr, default_ocr
|
||||
@@ -69,6 +71,8 @@ def _cookie_mapping(cookie: Mapping[str, str] | str | None) -> dict[str, str]:
|
||||
class HuyaVerificationSolver:
|
||||
"""处理虎牙 returnCode=10030/10039 后的滑块或点选验证。"""
|
||||
|
||||
_cloze_corpus: set[str] | None = None
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
cookie: Mapping[str, str] | str | None = None,
|
||||
@@ -84,6 +88,7 @@ class HuyaVerificationSolver:
|
||||
account: str = "",
|
||||
capture_dir: str | Path | None = None,
|
||||
enable_capture: bool = True,
|
||||
sms_url: str = "",
|
||||
):
|
||||
self.cookie = _cookie_mapping(cookie)
|
||||
self.ua = ua or DEFAULT_UA
|
||||
@@ -113,6 +118,7 @@ class HuyaVerificationSolver:
|
||||
self.account = account
|
||||
self.capture_dir = capture_dir
|
||||
self.enable_capture = enable_capture
|
||||
self.sms_url = sms_url
|
||||
self.current_capture: CaptchaCaptureRecord | None = None
|
||||
self.auth_type = ""
|
||||
|
||||
@@ -135,7 +141,7 @@ class HuyaVerificationSolver:
|
||||
@staticmethod
|
||||
def _decode_image(base64_string: str | None) -> bytes:
|
||||
if not base64_string:
|
||||
raise HuyaVerificationError("验证码图片为空")
|
||||
return b""
|
||||
if ";base64," in base64_string:
|
||||
base64_string = base64_string.split(";base64,")[-1]
|
||||
return base64.b64decode(base64_string)
|
||||
@@ -210,6 +216,162 @@ class HuyaVerificationSolver:
|
||||
_, _, _, max_loc = cv2.minMaxLoc(result)
|
||||
return int(max_loc[0])
|
||||
|
||||
@staticmethod
|
||||
def _opencv_rotate_angle(
|
||||
background_bytes: bytes,
|
||||
puzzle_bytes: bytes,
|
||||
default_cx: float = 195.0,
|
||||
default_cy: float = 90.0,
|
||||
) -> int:
|
||||
"""通过圆周边界颜色与边缘连续性计算旋转验证码的最佳旋转角度 (0~359度)。"""
|
||||
bg = cv2.imdecode(np.frombuffer(background_bytes, np.uint8), cv2.IMREAD_COLOR)
|
||||
puzzle_raw = cv2.imdecode(
|
||||
np.frombuffer(puzzle_bytes, np.uint8), cv2.IMREAD_UNCHANGED
|
||||
)
|
||||
if bg is None or puzzle_raw is None:
|
||||
raise HuyaVerificationError("旋转验证码图片解码失败")
|
||||
|
||||
bg_gray = cv2.cvtColor(bg, cv2.COLOR_BGR2GRAY).astype(np.float32)
|
||||
p_gray = cv2.cvtColor(puzzle_raw[:, :, :3], cv2.COLOR_BGR2GRAY).astype(
|
||||
np.float32
|
||||
)
|
||||
|
||||
gray_u8 = cv2.cvtColor(bg, cv2.COLOR_BGR2GRAY)
|
||||
black_mask = (gray_u8 < 25).astype(np.uint8) * 255
|
||||
contours, _ = cv2.findContours(
|
||||
black_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
|
||||
)
|
||||
cx, cy, r_hole = default_cx, default_cy, 58.0
|
||||
for c in contours:
|
||||
if cv2.contourArea(c) > 3000:
|
||||
(tcx, tcy), tr = cv2.minEnclosingCircle(c)
|
||||
if abs(tcx - default_cx) < 35 and abs(tcy - default_cy) < 25:
|
||||
cx, cy, r_hole = tcx, tcy, tr
|
||||
break
|
||||
|
||||
ph, pw = puzzle_raw.shape[:2]
|
||||
pcx, pcy = pw / 2.0, ph / 2.0
|
||||
|
||||
angles = np.linspace(0, 2 * np.pi, 360, endpoint=False)
|
||||
r_out_list = [r_hole + 2.0, r_hole + 4.0]
|
||||
r_in_list = [r_hole - 5.0, r_hole - 7.0]
|
||||
|
||||
bg_outer_vals_list = []
|
||||
for ro in r_out_list:
|
||||
bx = cx + ro * np.cos(angles)
|
||||
by = cy + ro * np.sin(angles)
|
||||
vals = cv2.remap(
|
||||
bg_gray,
|
||||
bx.astype(np.float32),
|
||||
by.astype(np.float32),
|
||||
cv2.INTER_LINEAR,
|
||||
).flatten()
|
||||
bg_outer_vals_list.append(vals)
|
||||
bg_outer_vals = np.mean(bg_outer_vals_list, axis=0)
|
||||
|
||||
best_deg = 0
|
||||
best_corr = -1.0
|
||||
for deg in range(360):
|
||||
rad = np.radians(deg)
|
||||
p_inner_vals_list = []
|
||||
for ri in r_in_list:
|
||||
px = pcx + ri * np.cos(angles - rad)
|
||||
py = pcy + ri * np.sin(angles - rad)
|
||||
pvals = cv2.remap(
|
||||
p_gray,
|
||||
px.astype(np.float32),
|
||||
py.astype(np.float32),
|
||||
cv2.INTER_LINEAR,
|
||||
).flatten()
|
||||
p_inner_vals_list.append(pvals)
|
||||
p_inner_vals = np.mean(p_inner_vals_list, axis=0)
|
||||
|
||||
corr = np.corrcoef(bg_outer_vals, p_inner_vals)[0, 1]
|
||||
if corr > best_corr:
|
||||
best_corr = corr
|
||||
best_deg = deg
|
||||
|
||||
return best_deg
|
||||
|
||||
@classmethod
|
||||
def _get_cloze_corpus(cls) -> set[str]:
|
||||
if cls._cloze_corpus is None:
|
||||
corpus: set[str] = set()
|
||||
base_dir = Path(__file__).resolve().parent
|
||||
for filename in ("idioms.txt", "poems.txt"):
|
||||
file_path = base_dir / filename
|
||||
if file_path.is_file():
|
||||
try:
|
||||
corpus.update(
|
||||
file_path.read_text(encoding="utf-8").splitlines()
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.debug(f"[solver] 加载语料 {filename} 失败: {exc}")
|
||||
cls._cloze_corpus = corpus
|
||||
return cls._cloze_corpus
|
||||
|
||||
@classmethod
|
||||
def _find_chinese_font(
|
||||
cls, size: int = 30
|
||||
) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
|
||||
font_candidates = [
|
||||
"/System/Library/Fonts/PingFang.ttc",
|
||||
"/System/Library/Fonts/STHeiti Medium.ttc",
|
||||
"/System/Library/Fonts/STHeiti Light.ttc",
|
||||
"/System/Library/Fonts/Hiragino Sans GB.ttc",
|
||||
"/System/Library/Fonts/Supplemental/Songti.ttc",
|
||||
"/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
|
||||
"/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc",
|
||||
"/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
|
||||
"/usr/share/fonts/truetype/droid/DroidSansFallbackFull.ttf",
|
||||
"C:/Windows/Fonts/msyh.ttc",
|
||||
"C:/Windows/Fonts/simhei.ttf",
|
||||
]
|
||||
for font_path in font_candidates:
|
||||
if Path(font_path).is_file():
|
||||
try:
|
||||
return ImageFont.truetype(font_path, size)
|
||||
except Exception:
|
||||
continue
|
||||
return ImageFont.load_default()
|
||||
|
||||
@classmethod
|
||||
def _synthesize_text_tip(cls, chars: list[str]) -> bytes:
|
||||
"""为没有提示小图的文本点选题目动态合成 44px 高度的提示图像。"""
|
||||
if not chars:
|
||||
return b""
|
||||
font = cls._find_chinese_font(30)
|
||||
char_box_size = 44
|
||||
total_width = len(chars) * char_box_size
|
||||
image = Image.new("RGB", (total_width, char_box_size), (255, 255, 255))
|
||||
draw = ImageDraw.Draw(image)
|
||||
for i, ch in enumerate(chars):
|
||||
offset_x = i * char_box_size + 7
|
||||
offset_y = 5
|
||||
draw.text((offset_x, offset_y), ch, fill=(0, 0, 0), font=font)
|
||||
buf = io.BytesIO()
|
||||
image.save(buf, format="PNG")
|
||||
return buf.getvalue()
|
||||
|
||||
@classmethod
|
||||
def _extract_target_chars_from_question(cls, question: str) -> list[str]:
|
||||
"""从点选题目中提取需要点击的目标汉字(支持完整成语/菜名及古诗/成语填空题)。"""
|
||||
if not question:
|
||||
return []
|
||||
m = re.search(r'["“]([^"”]+)["”]', question)
|
||||
if not m:
|
||||
return []
|
||||
text = m.group(1).strip()
|
||||
if "_" in text:
|
||||
regex = "^" + text.replace("_", "(.)") + "$"
|
||||
compiled = re.compile(regex)
|
||||
for phrase in cls._get_cloze_corpus():
|
||||
matched = compiled.match(phrase)
|
||||
if matched:
|
||||
return list(matched.groups())
|
||||
return []
|
||||
return [ch for ch in text if "\u4e00" <= ch <= "\u9fa5"]
|
||||
|
||||
def _request_json(self, method: str, url: str, **kwargs) -> dict:
|
||||
response = self.session.request(method, url, timeout=self.timeout, **kwargs)
|
||||
response.raise_for_status()
|
||||
@@ -367,6 +529,13 @@ class HuyaVerificationSolver:
|
||||
step=step,
|
||||
raw_params=self.url_param_map,
|
||||
)
|
||||
if self.sms_url:
|
||||
logger.info(
|
||||
"[solver] 虎牙风控在第 {} 步要求短信验证 (sms_auth),已配置接码链接,准备自动发码并接码过验",
|
||||
step,
|
||||
)
|
||||
self.auth_type = "sms_auth"
|
||||
return
|
||||
logger.warning(
|
||||
"[solver] 虎牙风控在第 {} 步要求短信验证 (sms_auth),手机号: {}",
|
||||
step,
|
||||
@@ -377,7 +546,12 @@ class HuyaVerificationSolver:
|
||||
f"虎牙风控要求短信验证(sms_auth),手机号: {mobile}",
|
||||
mobile=mobile,
|
||||
)
|
||||
self.auth_type = "dx_auth" if "dx_auth" in strategy_url_lower else "pt_auth"
|
||||
if "rotate_auth" in strategy_url_lower or "/auth/xz/" in strategy_url_lower:
|
||||
self.auth_type = "rotate_auth"
|
||||
elif "dx_auth" in strategy_url_lower or "/auth/dx/" in strategy_url_lower:
|
||||
self.auth_type = "dx_auth"
|
||||
else:
|
||||
self.auth_type = "pt_auth"
|
||||
if self.enable_capture:
|
||||
self.current_capture = CaptchaCaptureRecord(
|
||||
auth_type=self.auth_type,
|
||||
@@ -412,9 +586,39 @@ class HuyaVerificationSolver:
|
||||
self.code = data["code"]
|
||||
self.huyapk = data["huyapk"]
|
||||
segment = data.get("segment")
|
||||
is_rotate = (
|
||||
self.auth_type == "rotate_auth"
|
||||
or "/auth/xz/" in url
|
||||
or "rotate" in self.strategy_url
|
||||
)
|
||||
if is_rotate:
|
||||
logger.info("虎牙验证类型: 旋转验证码 (rotate_auth / xz)")
|
||||
bg_bytes = self._decode_image(data.get("dtuStr") or data.get("dTuStr"))
|
||||
tip_bytes = self._decode_image(data.get("puzzleStr"))
|
||||
restored_bg = (
|
||||
self._restore_slider_background(bg_bytes, segment, self.huyapk)
|
||||
if segment
|
||||
else bg_bytes
|
||||
)
|
||||
angle = self._opencv_rotate_angle(restored_bg, tip_bytes)
|
||||
logger.info(f"虎牙旋转验证码识别角度: {angle}°")
|
||||
if self.current_capture:
|
||||
try:
|
||||
self.current_capture.capture_rotate_data(
|
||||
code=self.code,
|
||||
dtu_bytes=bg_bytes,
|
||||
puzzle_bytes=tip_bytes,
|
||||
restored_bg_bytes=restored_bg,
|
||||
angle=angle,
|
||||
raw_data=data,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.debug(f"[solver] 记录旋转验证码捕获数据异常: {exc}")
|
||||
return angle
|
||||
|
||||
if segment:
|
||||
logger.info("虎牙验证类型: 滑块")
|
||||
bg_bytes = self._decode_image(data.get("dtuStr"))
|
||||
bg_bytes = self._decode_image(data.get("dtuStr") or data.get("dTuStr"))
|
||||
tip_bytes = self._decode_image(data.get("puzzleStr"))
|
||||
restored_bg = self._restore_slider_background(
|
||||
bg_bytes, segment, self.huyapk
|
||||
@@ -451,11 +655,31 @@ class HuyaVerificationSolver:
|
||||
return final_x
|
||||
|
||||
logger.info("虎牙验证类型: 点选 (dx_auth)")
|
||||
bg_bytes = self._decode_image(data.get("dTuStr"))
|
||||
tip_bytes = self._decode_image(data.get("hZiStr"))
|
||||
merged = self._vertical_concat_align_left(bg_bytes, tip_bytes)
|
||||
points = self.ocr.ocr_click_points(merged)
|
||||
final_points = [[int(x), int(y) - 44] for x, y in points]
|
||||
bg_raw = data.get("dTuStr") or data.get("dtuStr") or data.get("bgStr")
|
||||
bg_bytes = self._decode_image(bg_raw)
|
||||
if not bg_bytes:
|
||||
raise HuyaVerificationError(
|
||||
f"点选验证码背景图为空: keys={list(data.keys())}"
|
||||
)
|
||||
tip_raw = data.get("hZiStr") or data.get("hziStr") or data.get("puzzleStr")
|
||||
tip_bytes = self._decode_image(tip_raw) if tip_raw else b""
|
||||
if tip_bytes:
|
||||
merged = self._vertical_concat_align_left(bg_bytes, tip_bytes)
|
||||
points = self.ocr.ocr_click_points(merged)
|
||||
final_points = [[int(x), int(y) - 44] for x, y in points]
|
||||
else:
|
||||
question = str(data.get("question") or "")
|
||||
target_chars = self._extract_target_chars_from_question(question)
|
||||
if target_chars:
|
||||
logger.info(f"虎牙点选从题目解析出目标字: {target_chars}")
|
||||
synth_tip = self._synthesize_text_tip(target_chars)
|
||||
merged = self._vertical_concat_align_left(bg_bytes, synth_tip)
|
||||
points = self.ocr.ocr_click_points(merged)
|
||||
final_points = [[int(x), int(y) - 44] for x, y in points]
|
||||
tip_bytes = synth_tip
|
||||
else:
|
||||
logger.info(f"虎牙点选题目未能提取明确目标字: {question}")
|
||||
final_points = []
|
||||
|
||||
if self.current_capture:
|
||||
try:
|
||||
@@ -471,6 +695,34 @@ class HuyaVerificationSolver:
|
||||
|
||||
return final_points
|
||||
|
||||
def _send_rotate_verify(self, url: str, angle: float) -> dict:
|
||||
drag_distance = max(5, int((angle / 360.0) * 260))
|
||||
track_points = generate_slide_track(drag_distance)
|
||||
act_data = {
|
||||
"point": int(round(angle)),
|
||||
"travel": format_track(track_points),
|
||||
"code": self.code,
|
||||
"sceneType": self.scene_type,
|
||||
"endTime": int(track_points[-1][-1]) - int(track_points[0][-1]),
|
||||
}
|
||||
act = self.js_ctx.call("get_act", act_data, self.huyapk)
|
||||
self.behavior_events.append(
|
||||
{
|
||||
"action": self._pointer_action("mousedown"),
|
||||
"id": "",
|
||||
"txt": "",
|
||||
"clientX": track_points[0][0],
|
||||
"clientY": track_points[0][1],
|
||||
"clientWidth": 350,
|
||||
"clientHeight": 268,
|
||||
"isTrusted": True,
|
||||
"timeStamp": random.randint(1800, 5500),
|
||||
"nowTime": int(time.time() * 1000),
|
||||
}
|
||||
)
|
||||
payload = self._build_common_payload({"act": act, "ver": 5})
|
||||
return self._submit_verify(url, payload)
|
||||
|
||||
def _send_slider_verify(self, url: str, point: int) -> dict:
|
||||
track_points = generate_slide_track(point)
|
||||
act_data = {
|
||||
@@ -559,8 +811,81 @@ class HuyaVerificationSolver:
|
||||
logger.debug(f"[solver] 记录提交结果异常: {exc}")
|
||||
return data
|
||||
|
||||
def _solve_sms_strategy(self, wait_seconds: float = 90.0) -> dict:
|
||||
"""自动通过 sms_url 接码并提交虎牙 sms_auth 验证。"""
|
||||
from core.sms_provider import SmsLine, SmsProviderClient, detect_provider
|
||||
|
||||
mobile = self.url_param_map.get("mobile", "?")
|
||||
logger.info(
|
||||
f"[solver] 开始自动接码流程 (手机: {mobile}, 接码URL: {self.sms_url[:40]}...)"
|
||||
)
|
||||
|
||||
# 1. 触发虎牙官方发送短信验证码
|
||||
send_url = "https://udbrtt.huya.com/auth/sms/send-sms-code"
|
||||
send_payload = {
|
||||
"data": {
|
||||
"urlParamMap": self.url_param_map,
|
||||
"ver": 5,
|
||||
}
|
||||
}
|
||||
sent_at = datetime.now(UTC)
|
||||
try:
|
||||
body = json.dumps(send_payload, separators=(",", ":"))
|
||||
send_res = self._request_json("post", send_url, data=body)
|
||||
logger.info(f"[solver] 虎牙短信验证码发送结果: {send_res}")
|
||||
except Exception as exc:
|
||||
logger.warning(f"[solver] 虎牙安全验证发送短信失败: {exc}")
|
||||
raise HuyaVerificationError(f"发送虎牙短信验证码失败: {exc}") from exc
|
||||
|
||||
# 2. 轮询接码链接获取验证码
|
||||
client = SmsProviderClient(timeout=(8, 15))
|
||||
item = SmsLine(
|
||||
phone=mobile,
|
||||
url=self.sms_url,
|
||||
provider=detect_provider(self.sms_url),
|
||||
raw=f"{mobile}----{self.sms_url}",
|
||||
)
|
||||
deadline = time.monotonic() + wait_seconds
|
||||
poll_interval = 2.5
|
||||
sms_code = ""
|
||||
while time.monotonic() < deadline:
|
||||
poll_result = client.poll(item, after_time=sent_at)
|
||||
if poll_result.has_code:
|
||||
sms_code = poll_result.code
|
||||
logger.info(f"[solver] 成功从接码链接收到验证码: {sms_code}")
|
||||
break
|
||||
time.sleep(poll_interval)
|
||||
|
||||
if not sms_code:
|
||||
raise HuyaSmsAuthRequiredError(
|
||||
self.strategy_url,
|
||||
f"接码超时({int(wait_seconds)}秒内未从接码链接获取到新验证码)",
|
||||
mobile=mobile,
|
||||
)
|
||||
|
||||
# 3. 提交验证码给虎牙官方
|
||||
verify_url = "https://udbrtt.huya.com/auth/sms/verify-sms-code"
|
||||
sms_code_hex = sms_code.encode("utf-8").hex()
|
||||
verify_payload = {
|
||||
"encrypt": 1,
|
||||
"data": {
|
||||
"urlParamMap": self.url_param_map,
|
||||
"behavior": self._encode_behavior(),
|
||||
"info": self.sdid,
|
||||
"page": self.page_url,
|
||||
"smsCode": sms_code_hex,
|
||||
"wupData": "",
|
||||
"ver": 5,
|
||||
},
|
||||
}
|
||||
logger.debug(f"[solver] 提交虎牙短信验证码: {sms_code} (hex={sms_code_hex})")
|
||||
return self._submit_verify(verify_url, verify_payload)
|
||||
|
||||
def _solve_current_strategy(self) -> dict:
|
||||
"""提交当前 strategy_url 对应的验证。"""
|
||||
if self.auth_type == "sms_auth":
|
||||
return self._solve_sms_strategy()
|
||||
|
||||
config_payload = self._build_common_payload({"cTuIndex": 0})
|
||||
config = {}
|
||||
gurl = ""
|
||||
@@ -628,7 +953,13 @@ class HuyaVerificationSolver:
|
||||
|
||||
point = self._get_track_point(gurl, point_payload)
|
||||
logger.debug(f"虎牙验证识别结果: {point}")
|
||||
if isinstance(point, list):
|
||||
if (
|
||||
self.auth_type == "rotate_auth"
|
||||
or "/auth/xz/" in vurl
|
||||
or "rotate" in self.strategy_url
|
||||
):
|
||||
last_result = self._send_rotate_verify(vurl, float(point))
|
||||
elif isinstance(point, list):
|
||||
last_result = self._send_click_verify(vurl, point)
|
||||
else:
|
||||
last_result = self._send_slider_verify(vurl, int(point))
|
||||
@@ -682,6 +1013,7 @@ def solve_huya_verification(
|
||||
account: str = "",
|
||||
capture_dir: str | Path | None = None,
|
||||
enable_capture: bool = True,
|
||||
sms_url: str = "",
|
||||
) -> dict:
|
||||
"""函数式入口,便于登录流程直接调用。"""
|
||||
solver = HuyaVerificationSolver(
|
||||
@@ -696,5 +1028,6 @@ def solve_huya_verification(
|
||||
account=account,
|
||||
capture_dir=capture_dir,
|
||||
enable_capture=enable_capture,
|
||||
sms_url=sms_url,
|
||||
)
|
||||
return solver.solve(challenge_payload)
|
||||
|
||||
Reference in New Issue
Block a user