"""虎牙 App 渠道协议登录模块。 流程: 1. 零设备注册链生成随机 dfpReport,获取新 safedeviceid/device_id 2. 账号+密码+新注册字段 -> WUP 密码登录 (POST wup.huya.com) 3. safe_auth 滑块自动过验 -> 提取 fresh cred 与真实 uid 4. 本地 XXTEA 算 nonce -> 铸造登录证书 (cert_forge) -> 补丁 WUP 信封 (envelope_forge) 5. 模拟扫码绑定四步流 (getQrId -> scanQrPicNotify -> bindQrLoginUser -> tryQrLogin) 获取 biztoken 6. POST /web/cookie/verify 兑换获取全套网页 Cookie 注册链不再重放旧 dfpReport 密文。登录帧的 32hex hdid 仍是服务端硬锚, 登录帧中的 HDID32 是 app 版本级协议常量;二维码信封的 ACTION、设备字段、 UID、证书和会话元数据均在本次登录中动态生成或由注册链签发。 注册链(``core/huya/dfp_register``)每次登录前执行,失败即抛错终止(``HuyaAppLoginError``), 不读取画像里的旧固定值,也不静默回退旧链。 ⚠ 风险与边界(详见 ``docs/HUYA_APP_OVERVIEW.md``): - hdid 全账号固定共享 -> 服务端可设备维度关联账号; - 滑块 UA / session / traceId / userAction 均按当前画像和本次请求动态生成; - qr_auth(扫码)/dx_auth(短信) 无自动闭环 -> 碰上直接失败(QR_AUTH_REQUIRED)。 """ from __future__ import annotations import base64 import hashlib import json import random import re import struct import time import uuid from collections.abc import Mapping from typing import Literal, overload from urllib.parse import parse_qs, quote, urlparse import requests from loguru import logger from .cert_forge import build_p1, forge_cert from .cookie_utils import cookie_pairs, normalize_cookie_pairs from .device_fingerprint import account_state_dir, get_huya_sdid, reset_account_state from .device_profile import get_profile, mobile_user_agent from .dfp_register import DfpRegistrationError, register_device from .envelope_forge import Envelope from .login import HuyaLoginError, HuyaLoginResult from .nonce_forge import K1_DEFAULT, gen_nonce from .wup_encoder import build_password_login_wup WUP_URL = "https://wup.huya.com" UDB_BASE = "https://udblgn.huya.com" APP_SIGN_WEB = "1ce3bf682483d03f146f58232ec10635" APP_SIGN_H5 = "0ba67962ab9e12387648efeae2750777" UA_PC = ( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 " "(KHTML, like Gecko) Chrome/151.0.0.0 Safari/537.36" ) APP_UA_MOBILE = ( "Mozilla/5.0 (Linux; Android 11; M2102J2SC Build/RKQ1.200826.002; wv) " "AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 " "Chrome/149.0.7827.159 Mobile Safari/537.36 huya adr/13.4.22/xiaomi/30" ) # 9.1 网页入口请求中稳定出现的设备态字段。它们必须来自真实 WebView/浏览器 # 运行态或本次请求的 Set-Cookie,不能由 App 凭据推导或随机生成。 WEB_DEVICE_COOKIE_KEYS = ( "guid", "udb_guiddata", "udb_deviceid", "game_did", "_qimei_uuid42", "udb_anobiztoken", "__yamid_new", ) SessionAssets = tuple[dict, str, str] RISK_URL_RE = re.compile(rb"https://aq\.huya\.com/p/safe_auth/[^\x00-\x20\"'\\<>]+") _URL_TAIL_KEEP = set( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=%" ) class HuyaAppLoginError(HuyaLoginError): """虎牙 App 登录失败。""" class HuyaAppQrAuthRequiredError(HuyaAppLoginError): """风控要求扫码验证 (qr_auth)。""" class HuyaAppSmsAuthRequiredError(HuyaAppLoginError): """风控要求短信验证 (sms_auth / sms_auth2)。""" def __init__(self, message: str = "", mobile: str = ""): self.mobile = mobile super().__init__(message or f"虎牙风控要求短信验证,手机号: {mobile or '?'}") def _golden_session_assets() -> tuple[dict, str, str]: """生成本次登录的会话元数据和行为轨迹。""" from .wup_encoder import make_trace_id, make_user_action mj = { "associationId": 8193, "funcName": "hypasswordLogin", "group": 1, "id": 4097, "session": random.randint(1_000_000, 9_999_999), "step": 1, "stillLogin": False, "traceId": make_trace_id(), "type": 3, "uid": 0, "userContext": "", } return mj, make_user_action(), "" def _android_version(device_info: Mapping[str, object]) -> str: parts = str(device_info.get("screen") or "").split(",") return parts[2] if len(parts) >= 3 and parts[2] else "11" def wup_password_login_raw( account: str, password: str, timeout: int = 15, device_info: dict | None = None, safedeviceid: str | None = None, hdid: str | None = None, proxies: dict | None = None, session_assets: SessionAssets | None = None, ) -> bytes: """发送 WUP 密码登录,返回原始响应字节。 未显式传入 ``safedeviceid`` 时会先执行新设备注册链,不再回退旧的 固定 action/device_id。风控重试调用方应显式复用同一注册结果。 注册链失败抛 ``HuyaAppLoginError``,绝不静默回退旧固定值。 """ uid_str = account.removeprefix("hy_") dev = dict(device_info) if device_info is not None else get_profile(account) mj, ua, _old_sd = session_assets or _golden_session_assets() if not safedeviceid: try: _t1, safedeviceid, registered_device_id = register_device( fingerprint=dev.get("fingerprint"), proxies=proxies, timeout=timeout, device_info=dev, ) except DfpRegistrationError as exc: raise HuyaAppLoginError(f"新设备注册失败: {exc}") from exc dev["device_id"] = registered_device_id hdid_value = hdid or dev.get("hdid") if not hdid_value: raise HuyaAppLoginError("账号设备画像缺少 HDID32,拒绝使用固定金样本") pkt = build_password_login_wup( uid_str, hashlib.sha1(password.encode()).hexdigest(), safedeviceid, str(hdid_value), mj["session"], mj["traceId"], ua, dev, ) r = requests.post( WUP_URL, data=pkt, headers={ "Content-Type": "application/multipart-formdata; charset=UTF-8", "User-Agent": f"Dalvik/2.1.0 (Linux; U; Android {_android_version(dev)})", "Accept-Encoding": "gzip", }, proxies=proxies, timeout=timeout, ) if r.status_code != 200: raise HuyaAppLoginError(f"登录 HTTP 状态异常: {r.status_code}") return r.content def parse_cred(resp: bytes) -> bytes | None: """从 WUP 响应中提取 114 字节的 cred。""" s = resp.find(b"\x0a\x0a", 0x40) e = resp.find(b"_wup_header") if s < 0 or e < 0: return None d = resp[s : e - 6] m = re.search(rb"\x3d\x00([\x00-\x03])(.)", d) if not m: return None ln = m.group(2)[0] st = m.start() + 4 cred = d[st : st + ln] if len(cred) == 114 and cred[:1] == b"\x0a": return cred return None def parse_risk_url(resp: bytes) -> str | None: """提取 safe_auth 风控 URL。""" urls = [] for m in RISK_URL_RE.finditer(resp): u = m.group().decode("utf-8", "ignore") while u and u[-1] not in _URL_TAIL_KEEP: u = u[:-1] urls.append(u) if not urls: return None pt = [u for u in urls if "pt_auth" in u or "dx_auth" in u] return (pt or urls)[0] def _response_markers(resp: bytes) -> str: """提取 WUP 错误响应中的短 ASCII 字段,便于区分签名和凭据失败。""" markers = [] for raw in re.findall(rb"[ -~]{4,}", resp): value = raw.decode("ascii", "ignore") if value not in markers and len(value) <= 160: markers.append(value) return ", ".join(markers[:8]) def solve_safe_auth( risk_url: str, proxies=None, max_retry: int = 3, device_info: Mapping[str, object] | None = None, account: str = "", sms_url: str = "", ) -> dict: """解 safe_auth 风控滑块/点选/短信。""" from .verification.solver import ( HuyaQrAuthRequiredError, HuyaSmsAuthRequiredError, HuyaVerificationSolver, ) if device_info is None: raise HuyaAppLoginError("safe_auth 缺少当前账号设备画像") q = { k: v[0] for k, v in parse_qs(urlparse(risk_url).query, keep_blank_values=True).items() } app_id = q.get("appId") or "5002" last_err: Exception | None = None for attempt in range(max_retry): solver = HuyaVerificationSolver( ua=mobile_user_agent(device_info), proxies=proxies, app_id=app_id, page_url=risk_url, use_touch_events=True, account=account, sms_url=sms_url, ) try: result = solver.solve(risk_url) except HuyaQrAuthRequiredError: raise except HuyaSmsAuthRequiredError as exc: mobile = getattr(exc, "mobile", "") raise HuyaAppSmsAuthRequiredError(str(exc), mobile=mobile) from exc except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底 last_err = exc logger.warning(f"[safe_auth] 第 {attempt + 1} 次过验异常: {exc}") time.sleep(1.0) continue auth_id = str((result or {}).get("authId") or "") if auth_id: logger.info(f"[safe_auth] 验证码过验成功 authId={auth_id[:24]}...") return result raise HuyaAppLoginError(f"safe_auth 验证码过验失败: {last_err or '未返回 authId'}") def parse_real_uid(resp: bytes) -> int: """从登录响应中提取 12 位真实 UID。""" s = resp.find(b"\x0a\x0a", 0x40) e = resp.find(b"_wup_header") if s >= 0 and e >= 0: chunk = resp[s:e] if len(chunk) > 243: uid = struct.unpack_from(">Q", chunk, 235)[0] if 1_100_000_000_000 < uid < 1_300_000_000_000: return uid for off in range(len(chunk) - 8): u = struct.unpack_from(">Q", chunk, off)[0] if 1_100_000_000_000 < u < 1_300_000_000_000: return u raise HuyaAppLoginError("无法从登录响应解析真实 UID") @overload def login_cred_with_flow( account: str, password: str, max_rounds: int = ..., device_info: dict | None = ..., proxies: dict | None = ..., include_device_token: Literal[False] = ..., sms_url: str = ..., ) -> tuple[bytes, int]: ... @overload def login_cred_with_flow( account: str, password: str, max_rounds: int = ..., device_info: dict | None = ..., proxies: dict | None = ..., include_device_token: Literal[True] = ..., sms_url: str = ..., ) -> tuple[bytes, int, str]: ... @overload def login_cred_with_flow( account: str, password: str, max_rounds: int = ..., device_info: dict | None = ..., proxies: dict | None = ..., include_device_token: bool = ..., sms_url: str = ..., ) -> tuple[bytes, int] | tuple[bytes, int, str]: ... def login_cred_with_flow( account: str, password: str, max_rounds: int = 3, device_info: dict | None = None, proxies: dict | None = None, include_device_token: bool = False, sms_url: str = "", ) -> tuple[bytes, int] | tuple[bytes, int, str]: """新注册设备后登录,返回 ``(新鲜 cred, 真实 uid)``。 注册只执行一次;safe_auth 通过后的重发继续使用同一组设备字段。 """ dev = dict(device_info) if device_info is not None else get_profile(account) try: _t1, safedeviceid, registered_device_id = register_device( fingerprint=dev.get("fingerprint"), proxies=proxies, device_info=dev, ) except DfpRegistrationError as exc: raise HuyaAppLoginError(f"新设备注册失败: {exc}") from exc dev["device_id"] = registered_device_id # 风控验证绑定首次 WUP 请求的 session/traceId;所有重发必须复用它们。 session_assets = _golden_session_assets() for rnd in range(max_rounds): logger.debug(f"[huya-app] WUP 登录请求第 {rnd + 1} 轮...") resp = wup_password_login_raw( account, password, device_info=dev, safedeviceid=safedeviceid, proxies=proxies, session_assets=session_assets, ) cred = parse_cred(resp) risk_url = parse_risk_url(resp) if not cred else None logger.debug( f"[huya-app] WUP 第 {rnd + 1} 轮响应: {len(resp)}B, " f"cred={bool(cred)}, risk={bool(risk_url)}" ) if cred: uid = parse_real_uid(resp) if include_device_token: return cred, uid, safedeviceid return cred, uid if risk_url: kind = ( "pt_auth(滑块)" if "pt_auth" in risk_url else ( "dx_auth(点选)" if "dx_auth" in risk_url else ("qr_auth(扫码)" if "qr_auth" in risk_url else "未知") ) ) logger.info(f"[huya-app] 第 {rnd + 1} 轮触发安全验证: {kind}") if "qr_auth" in risk_url: raise HuyaAppQrAuthRequiredError( "该账号 App 渠道要求扫码验证(qr_auth),请先在手机虎牙 App 上正常登录一次建立设备信任。" ) solve_safe_auth( risk_url, proxies=proxies, device_info=dev, account=account, sms_url=sms_url, ) logger.info(f"[huya-app] safe_auth ({kind}) 过验成功,重发 WUP 登录...") continue markers = _response_markers(resp) detail = f",服务端字段: {markers}" if markers else "" logger.warning(f"[huya-app] WUP 响应未包含 cred/风控: {len(resp)}B{detail}") if "LGN_INFO_INVALID_USER_OR_PASSWORD" in markers: raise HuyaAppLoginError( "虎牙账号或密码错误(服务端: LGN_INFO_INVALID_USER_OR_PASSWORD)" ) if "APP_SIGN_NOT_MATCH" in markers: raise HuyaAppLoginError("虎牙设备签名不匹配(服务端: APP_SIGN_NOT_MATCH)") raise HuyaAppLoginError( f"登录未返回凭据也无风控URL(响应 {len(resp)}B{detail})" ) raise HuyaAppLoginError(f"{max_rounds} 轮内未取得登录凭据") class QrRole: """udblgn.huya.com/qrLgn/* 的 JSON 协议封装。""" def __init__( self, pc: bool, sdid: str, proxies: dict | None = None, device_info: Mapping[str, object] | None = None, ): self.pc = pc self.sdid = sdid if not pc and device_info is None: raise HuyaAppLoginError("移动端二维码角色缺少当前账号设备画像") self.s = requests.Session() self.s.trust_env = False if proxies: self.s.proxies.update(proxies) ctx_hex = uuid.uuid4().hex tail = "CBC9F93DBEB000011DB11EC02A401BAD-" if pc else uuid.uuid4().hex.upper() tail = tail if tail.endswith("-") else tail + "-" prefix = "WB" if pc else "H5" self.context = f"{prefix}-{ctx_hex}-{tail}" self.page_id = random.randint(40_000_000, 41_000_000) self.req_counter = random.randint(40_000_000, 41_000_000) self.s.headers.update( { "User-Agent": ( UA_PC if pc or device_info is None else mobile_user_agent(device_info) ), "Origin": UDB_BASE, "content-type": "application/json;charset=UTF-8", "Accept": "*/*", } ) def _headers(self, uri: str) -> dict: mid = "2.6" if self.pc else "2.5" return { "context": self.context, "uri": uri, "reqid": str(self.req_counter), "lcid": "2052", "Referer": f"{UDB_BASE}/web/middle/{mid}/{self.page_id}/https/{self.context.split('-')[1]}", } def call( self, path: str, uri: str, data: dict, cookies: dict | None = None ) -> dict: envelope = { "uri": uri, "version": "2.6" if self.pc else "2.5", "context": self.context, "appId": "5002" if self.pc else "5131", "appSign": APP_SIGN_WEB if self.pc else APP_SIGN_H5, "authId": "", "sdid": self.sdid, "lcid": "2052", "byPass": "3", "requestId": str(self.req_counter), "data": data, } self.req_counter += random.randint(120, 400) r = self.s.post( f"{UDB_BASE}{path}", json=envelope, headers=self._headers(uri), cookies=cookies, timeout=20, ) return r.json() def web_behavior(page: str = "https://www.huya.com/g") -> tuple[str, str]: now = int(time.time() * 1000) - random.randint(3000, 10000) acts = [] d = random.randint(800, 1800) for a in ("7", "7", "8", "8"): now += random.randint(600, 2000) d += random.randint(600, 2000) acts.append({"id": a, "d": d, "time": now}) val = {"furl": page, "curl": page, "user_action": acts} beh = quote(json.dumps(val, separators=(",", ":")), safe="~()*!.'") return beh, quote(page, safe="") class HuyaAppPasswordLogin: """虎牙 App 渠道纯协议密码登录器。""" def __init__( self, username: str, password: str, proxies: Mapping[str, str] | None = None, timeout: tuple[float, float] | None = None, force_new_device: bool = False, device_info: dict | None = None, sms_url: str = "", ): self.username = username.strip() self.password = password self.proxies = dict(proxies) if proxies else None self.timeout = timeout or (10.0, 25.0) self.force_new_device = force_new_device self.sms_url = sms_url.strip() if force_new_device: reset_account_state(self.username) self.device_info = device_info or get_profile( self.username, force_new=force_new_device ) def login(self) -> HuyaLoginResult: """执行完整 App 登录获取 Cookie 流程 (成功/失败均记录登录时间 → 设备绑定页)。""" result = self._login_impl() try: from .device_profile import record_login record_login(self.username, result.success, result.message) except Exception as exc: # noqa: BLE001 # 元数据记录失败不影响登录结果 logger.debug(f"登录元数据记录失败: {exc}") return result @staticmethod def _missing_web_device_cookie(cookie: str) -> tuple[str, ...]: """返回网页设备态缺失字段名,不暴露任何 Cookie 值。""" present = {key for key, value in cookie_pairs(cookie) if value} return tuple(key for key in WEB_DEVICE_COOKIE_KEYS if key not in present) @staticmethod def _supplement_anonymous_device( device_info: Mapping[str, object], *, proxies: Mapping[str, str] | None = None, ) -> dict: """用匿名设备态协议尽力补齐 4 个字段(udb_deviceid/guiddata/biztoken/anouid)。 只 ``setdefault``,不覆盖 hydevice 或显式传入的真实值;获取失败只 告警,不阻断登录(字段不全仍保存,风控风险由调用方承担)。 """ from .anon_device import AnonymousDeviceError, fetch_anonymous_device_state merged = dict(device_info) try: anon = fetch_anonymous_device_state(proxies=proxies) except AnonymousDeviceError as exc: logger.warning("[huya-app] 匿名设备态获取失败(不阻断登录): {}", exc) return merged for key, value in anon.items(): merged.setdefault(key, value) logger.info("[huya-app] 匿名设备态协议补齐字段: {}", ", ".join(sorted(anon))) return merged @staticmethod def _merge_web_cookie( session: requests.Session, biztoken: str, sdid: str, hdid: str, device_info: Mapping[str, object], *, cred: bytes | str = b"", uid: int = 0, username: str = "", include_transient: bool = True, ) -> str: """合并真实登录凭据与已有网页 Cookie。 抓包中的设备/统计 Cookie 由浏览器或设备指纹链产生,不能用随机值 冒充。认证字段来自本次登录或指纹响应并覆盖旧值;其他字段只有在 Session 或 ``device_info`` 明确提供时才保留,缺失就不写入。 """ jar = session.cookies if hasattr(jar, "items"): pairs = [ (key, "" if value is None else value) for key, value in jar.items() ] else: pairs = [ (str(getattr(cookie, "name", "")), str(getattr(cookie, "value", ""))) for cookie in jar if getattr(cookie, "name", "") ] def set_value(key: str, value: object, *, overwrite: bool = False): value = "" if value is None else str(value).strip() if not value: return if overwrite: pairs[:] = [ (item_key, item_value) for item_key, item_value in pairs if item_key != key ] if not any(item_key == key for item_key, _item_value in pairs): pairs.append((key, value)) raw_cred = ( base64.urlsafe_b64encode(cred).decode("ascii").rstrip("=") if isinstance(cred, bytes) else (cred or "") ) # 本次登录/指纹响应明确返回的字段,必须覆盖旧 Session 值。 set_value("udb_cred", raw_cred, overwrite=True) if uid: set_value("udb_uid", uid, overwrite=True) set_value("yyuid", uid, overwrite=True) set_value("udb_biztoken", biztoken, overwrite=True) set_value("udb_version", "1.0", overwrite=True) set_value("udb_origin", "0", overwrite=True) set_value("udb_status", "1", overwrite=True) set_value("sdid", sdid, overwrite=True) set_value("hdid", hdid, overwrite=True) # 手机号不是网页 passport。只有明确的 hy_账号或 Session 现有值可用。 if username.startswith("hy_"): set_value("udb_passport", username, overwrite=True) set_value("username", username, overwrite=True) # 设备/统计字段不推导、不随机生成;仅转发已知真实值。 optional_keys = ( "guid", "udb_guiddata", "__yamid_new", "game_did", "_qimei_uuid42", "_qimei_fingerprint", "_qimei_h38", "udb_anouid", "udb_anobiztoken", "__yasmid", "__yamid_tt1", "SoundValue", "alphaValue", "isInLiveRoom", "udb_deviceid", "udb_passdata", "_rep_cnt", "Hm_lvt_51700b6c722f5bb4cf39906a596ea41f", "HMACCOUNT", "udb_appid", "rep_cnt", "udb_accdata", "h_unt", "__yaoldyyuid", "_yasids", "huya_flash_rep_cnt", "huyasp_rep_cnt", "huya_hd_rep_cnt", "Hm_lpvt_51700b6c722f5bb4cf39906a596ea41f", "huya_web_rep_cnt", ) for key in optional_keys: explicit = device_info.get(key) set_value(key, explicit, overwrite=explicit not in (None, "")) web_guiddata = str( device_info.get("web_guiddata") or device_info.get("udb_guiddata") or "" ) if web_guiddata: set_value("udb_guiddata", web_guiddata, overwrite=True) web_device_id = str(device_info.get("web_device_id") or "") if re.fullmatch(r"w_\d{19}", web_device_id): set_value("udb_deviceid", web_device_id, overwrite=True) if not include_transient: pairs = [ (key, value) for key, value in pairs if key != "web_qrlogin_confirm_id" ] return normalize_cookie_pairs(pairs) def _login_impl(self) -> HuyaLoginResult: """登录主体 (原 login)。""" acct = self.username logger.info( f"[huya-app] 开始登录账号 {acct} (机型: {self.device_info.get('model')})..." ) # 1) 获取新鲜 cred 与 真实 uid (自动过 safe_auth 滑块) try: cred, uid, safedeviceid = login_cred_with_flow( acct, self.password, device_info=self.device_info, proxies=self.proxies, include_device_token=True, sms_url=self.sms_url, ) except HuyaAppQrAuthRequiredError as exc: logger.warning(f"[huya-app] 账号 {acct} 登录受阻: {exc}") return HuyaLoginResult( success=False, message=str(exc), code="QR_AUTH_REQUIRED", ) except HuyaAppSmsAuthRequiredError as exc: logger.warning( f"[huya-app] 账号 {acct} 登录中断:滑块与点选已全部通过," f"虎牙下发了手机短信二次验证 ({exc.mobile or '手机号见验证链接'}),需人工接码" ) return HuyaLoginResult( success=False, message=str(exc), code="SMS_AUTH_REQUIRED", ) except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底 logger.warning(f"[huya-app] 账号 {acct} App 登录异常: {exc}") return HuyaLoginResult( success=False, message=f"App 登录凭证获取失败: {exc}", code="LOGIN_FAILED", ) logger.info(f"[huya-app] 成功获取 cred ({len(cred)}B), uid={uid}") # 2) 本地生成 nonce 铸造证书 (P1 指纹与该账号设备画像一致) try: st = int(time.time() * 1000) rnd = gen_nonce(uid, K1_DEFAULT, service_time_ms=st, counter=0) fp_bytes = self.device_info["fingerprint"].encode("ascii") p1 = build_p1(b"5008", fp_bytes, cred, rnd=rnd) # 证书头和 app_id 是协议版本常量,不从抓包信封读取。 cert = base64.b64encode(forge_cert(p1, key_idx=0x20)).decode() # 3) 按当前账号画像和本次注册令牌重编码二维码信封。 qr_session = random.randint(1_000_000, 9_999_999) qr_trace = ( f"{uuid.uuid4().hex[:16]}-{random.randint(10000, 99999)}-" f"{time.time_ns():020d}" ) env = Envelope.build_qr( uid=uid, cert_b64=cert, safedeviceid=safedeviceid, session=qr_session, trace_id=qr_trace, device_info=self.device_info, ) wup = base64.b64encode(bytes(env.raw)).decode("ascii") except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底 return HuyaLoginResult( success=False, message=f"证书铸造/信封补丁失败: {exc}", code="CERT_FORGE_FAILED", ) # 4) 模拟扫码绑定四步流获取 biztoken try: # 一号一设备: sdid 状态按账号隔离 (默认全局目录会让所有账号共享 # 同一份 hydevice 设备状态, 服务端可跨账号关联 — 见 R40 缺口修复) sdid_obj = get_huya_sdid( # App 主链只接受当前账号的 hydevice 高信任结果;旧版 # token+collect 降级没有账号画像,不再静默放行。 allow_fallback=False, state_dir=account_state_dir(self.username), device_hint=self.device_info, ) if not sdid_obj or not sdid_obj.sdid or sdid_obj.source != "fingerprint": detail = sdid_obj.message if sdid_obj else "未返回结果" raise HuyaAppLoginError( f"账号设备指纹获取失败(必须为 hydevice): {detail}" ) sdid = sdid_obj.sdid # hydevice may write additional browser cookies through its # document.cookie bridge. Forward only the values actually # observed from the runner; never synthesize missing fields. observed_cookie_keys = sorted(sdid_obj.cookies or {}) logger.info( "[huya-app] hydevice 实际 Cookie 输出字段: {}", ", ".join(observed_cookie_keys) if observed_cookie_keys else "无", ) merge_device_info = dict(self.device_info) for key, value in (sdid_obj.cookies or {}).items(): if key in WEB_DEVICE_COOKIE_KEYS or key in { "udb_appid", "__yasmid", "__yamid_tt1", "udb_anouid", "udb_anobiztoken", "udb_deviceid", }: merge_device_info.setdefault(key, value) # 匿名设备态协议补齐(middle + anonymousLogin 签发 4 字段), # 只 setdefault 不覆盖真实值;失败不阻断。 merge_device_info = self._supplement_anonymous_device( merge_device_info, proxies=self.proxies ) logger.info("[huya-app] cred 已获取,开始二维码绑定流程") pc = QrRole(pc=True, sdid=sdid, proxies=self.proxies) ph = QrRole( pc=False, sdid=sdid, proxies=self.proxies, device_info=self.device_info, ) beh, page = web_behavior() # 4.1 获取 qrId resp = pc.call( "/qrLgn/getQrId", "70001", {"behavior": beh, "type": "", "domainList": "", "page": page}, ) qrid = (resp.get("data") or {}).get("qrId") logger.debug(f"[huya-app] getQrId 响应: qrid={bool(qrid)}") if not qrid: return HuyaLoginResult( success=False, message=f"获取 qrId 失败: {resp.get('message') or resp}", code="QR_ID_FAILED", ) # 4.2 扫码与绑定 cp = f"https://aq.huya.com/r/confirm.html?k={qrid}&id=5002" ph.call( "/qrLgn/scanQrPicNotify", "70005", { "qrId": qrid, "wupData": wup, "behavior": quote("[]", safe=""), "page": quote(cp, safe=""), }, ) r2 = ph.call( "/qrLgn/bindQrLoginUser", "70007", { "qrId": qrid, "wupData": wup, "behavior": quote("[]", safe=""), "page": quote(cp, safe=""), }, ) logger.debug( f"[huya-app] bindQrLoginUser 响应: returnCode={r2.get('returnCode')}" ) if r2.get("returnCode") not in (0, "0", None) and r2.get("returnCode") != 0: logger.warning( f"[huya-app] bind 返回码: {r2.get('returnCode')} msg: {r2.get('message')}" ) # 4.3 轮询 tryQrLogin biztoken = None for index in range(12): rt = pc.call( "/qrLgn/tryQrLogin", "70003", { "qrId": qrid, "remember": "1", "domainList": "", "behavior": beh, "page": page, }, ) dt = rt.get("data") or {} logger.debug( f"[huya-app] tryQrLogin 第 {index + 1}/12 轮: stage={dt.get('stage')}" ) if dt.get("stage") == 2: biztoken = dt.get("biztoken") break time.sleep(1.5) if not biztoken: return HuyaLoginResult( success=False, message="未能在轮询时间内获取到 biztoken (绑定超时或失败)", code="BIZTOKEN_TIMEOUT", ) # 5) 先把扫码返回的网页 token 和设备态写回 verify Session。 # verify 响应本身没有 Set-Cookie;浏览器是在请求前就已准备好这些字段。 merged_before_verify = self._merge_web_cookie( pc.s, biztoken, sdid, sdid_obj.hdid, merge_device_info, cred=cred, uid=uid, username=acct, ) pc.s.cookies.clear() for key, value in cookie_pairs(merged_before_verify): pc.s.cookies.set(key, value) verify_resp = pc.s.post( "https://udblgn.huya.com/web/cookie/verify", json={"appId": 5002}, timeout=15, ) if verify_resp.status_code != 200: return HuyaLoginResult( success=False, message=f"Cookie verify 兑换 HTTP 失败: {verify_resp.status_code}", code="VERIFY_FAILED", ) cookie_str = self._merge_web_cookie( pc.s, biztoken, sdid, sdid_obj.hdid, merge_device_info, cred=cred, uid=uid, username=acct, include_transient=False, ) missing_web = self._missing_web_device_cookie(cookie_str) if missing_web: missing_text = ", ".join(missing_web) logger.warning( f"[huya-app] 账号 {acct} 登录凭据有效,但网页设备态不完整," f"缺少: {missing_text}(字段不全仍保存,风控风险自担)" ) if "udb_cred" not in cookie_str or "yyuid" not in cookie_str: return HuyaLoginResult( success=False, message="Cookie 兑换完成但缺失关键凭据 (udb_cred/yyuid)", code="COOKIE_INCOMPLETE", ) raw_cookie_str = cookie_str # 补齐前 = App 原始登录凭据(16 字段 udb_*) # 补齐网页设备字段并修正 appId:真实网页登录态是 41 字段 + # udb_appid=5002,App 扫码链只产出 16 个 udb_* 认证字段且 appId=5008 # (App 渠道),缺字段注入浏览器会导致 UDB SDK 判定设备态不完整。 from .web_cookie_fields import ( fill_web_cookie_fields, qimei_feature_from_device_profile, ) full_cookie = fill_web_cookie_fields( cookie_str, guid="", uid=uid, qimei_feature=qimei_feature_from_device_profile(self.device_info), ) appid_fixed = "; ".join( f"{key}={value}" if key != "udb_appid" else "udb_appid=5002" for key, value in cookie_pairs(full_cookie) ) cookie_str = appid_fixed logger.info( f"[huya-app] 补齐网页设备字段: {len(cookie_str)}B " f"({len(cookie_pairs(cookie_str))} 字段, 缺 {len(self._missing_web_device_cookie(cookie_str))})" ) logger.info( f"[huya-app] 账号 {acct} 登录成功,获取网页 Cookie ({len(cookie_str)}B)" ) return HuyaLoginResult( success=True, cookie=cookie_str, raw_cookie=raw_cookie_str, message="App协议登录成功", sdid=sdid, context=pc.context, ) except Exception as exc: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底 return HuyaLoginResult( success=False, message=f"扫码绑定兑换 Cookie 失败: {exc}", code="BIND_FLOW_FAILED", ) def login_huya_app_password( username: str, password: str, proxies: Mapping[str, str] | None = None, timeout: tuple[float, float] | None = None, force_new_device: bool = False, sms_url: str = "", ) -> HuyaLoginResult: """函数式入口:使用 App 协议执行虎牙密码登录并获取全套 Cookie。""" return HuyaAppPasswordLogin( username=username, password=password, proxies=proxies, timeout=timeout, force_new_device=force_new_device, sms_url=sms_url, ).login()