842 lines
26 KiB
TypeScript
842 lines
26 KiB
TypeScript
/** 虎牙扫码登录 JSON 协议、活动绑定 WUP RPC 与 livelink 小程序码。 */
|
|
|
|
import crypto from 'node:crypto'
|
|
|
|
import { buildHuyaLoginContext, cookiePairs, cookieValue, normalizeCookiePairs } from './cookie.js'
|
|
import {
|
|
decodeWupResponse,
|
|
encodeWupRequest,
|
|
readWupStruct,
|
|
TAF_TYPE,
|
|
TafReader,
|
|
TafWriter,
|
|
type TafTypeValue,
|
|
type WupResponse,
|
|
} from './taf.js'
|
|
|
|
export const UDB_BASE = 'https://udblgn.huya.com'
|
|
export const CDNWS_HOST = 'cdnws.api.huya.com'
|
|
export const LIVELINK_BIND_API_BASE = 'https://livelinkbind.game.qq.com'
|
|
export const HTTP_HUYA_UA = 'webh5&0.0.1&websocket&&diypc_52775'
|
|
export const PC_UA =
|
|
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' +
|
|
'Chrome/149.0.0.0 Safari/537.36'
|
|
const APP_SIGN_WEB = '1ce3bf682483d03f146f58232ec10635'
|
|
const WEB_USER_AGENT =
|
|
'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'
|
|
|
|
type FetchLike = typeof fetch
|
|
type JsonRecord = Record<string, unknown>
|
|
|
|
export type HuyaQrResponse = JsonRecord & {
|
|
data?: JsonRecord
|
|
message?: string
|
|
}
|
|
|
|
export class HuyaCookieJar {
|
|
private readonly values = new Map<string, string>()
|
|
|
|
header(): string {
|
|
return Array.from(this.values.entries())
|
|
.map(([key, value]) => `${key}=${value}`)
|
|
.join('; ')
|
|
}
|
|
|
|
pairs(): Array<[string, string]> {
|
|
return Array.from(this.values.entries())
|
|
}
|
|
|
|
clear(): void {
|
|
this.values.clear()
|
|
}
|
|
|
|
set(cookie: string): void {
|
|
for (const [key, value] of cookiePairs(cookie)) this.values.set(key, value)
|
|
}
|
|
|
|
absorb(headers: Headers): void {
|
|
const withGetSetCookie = headers as Headers & { getSetCookie?: () => string[] }
|
|
const setCookies =
|
|
typeof withGetSetCookie.getSetCookie === 'function'
|
|
? withGetSetCookie.getSetCookie()
|
|
: splitSetCookieHeader(headers.get('set-cookie') || '')
|
|
for (const raw of setCookies) {
|
|
const first = String(raw || '').split(';', 1)[0] || ''
|
|
const separator = first.indexOf('=')
|
|
if (separator <= 0) continue
|
|
const key = first.slice(0, separator).trim()
|
|
const value = first.slice(separator + 1).trim()
|
|
if (!key) continue
|
|
if (!value || /max-age=0/i.test(raw)) {
|
|
this.values.delete(key)
|
|
} else {
|
|
this.values.set(key, value)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
function splitSetCookieHeader(value: string): string[] {
|
|
if (!value) return []
|
|
return value.split(/,(?=\s*[^;,=\s]+=)/g)
|
|
}
|
|
|
|
function buildHeaders(cookie?: string): Record<string, string> {
|
|
return cookie ? { cookie } : {}
|
|
}
|
|
|
|
export type HuyaQrRoleOptions = {
|
|
sdid: string
|
|
cookie?: string
|
|
context?: string
|
|
fetchImpl?: FetchLike
|
|
}
|
|
|
|
export class HuyaQrRole {
|
|
private readonly jar = new HuyaCookieJar()
|
|
private readonly context: string
|
|
private readonly guidData: string
|
|
private readonly fingerprintSdid: string
|
|
private readonly fetchImpl: FetchLike
|
|
private activeSdid: string
|
|
private readonly pageId: number
|
|
private requestCounter: number
|
|
|
|
constructor(options: HuyaQrRoleOptions) {
|
|
const initialCookie = String(options.cookie || '').trim()
|
|
if (initialCookie) this.jar.set(initialCookie)
|
|
this.fingerprintSdid = String(options.sdid || '').trim()
|
|
// 最新网页登录先用 csid 请求二维码,随后切换到 hydevice 高信任 sdid 轮询。
|
|
this.activeSdid = `csid_${crypto.randomBytes(16).toString('hex')}`
|
|
this.fetchImpl = options.fetchImpl || fetch
|
|
this.context =
|
|
String(options.context || '').trim() ||
|
|
buildHuyaLoginContext(initialCookie) ||
|
|
`WB-${crypto.randomUUID().replace(/-/g, '')}-CBC9F93DBEB000011DB11EC02A401BAD-`
|
|
this.guidData =
|
|
cookieValue(initialCookie, 'udb_guiddata') || crypto.randomBytes(16).toString('hex')
|
|
this.pageId = 40_000_000 + Math.floor(Math.random() * 1_000_000)
|
|
this.requestCounter = 40_000_000 + Math.floor(Math.random() * 1_000_000)
|
|
}
|
|
|
|
activateFingerprintSdid(): void {
|
|
if (this.fingerprintSdid) this.activeSdid = this.fingerprintSdid
|
|
}
|
|
|
|
setCookies(cookie: string): void {
|
|
this.jar.clear()
|
|
this.jar.set(cookie)
|
|
}
|
|
|
|
cookieHeader(): string {
|
|
return this.jar.header()
|
|
}
|
|
|
|
async bootstrapMiddle(): Promise<void> {
|
|
const url = `${UDB_BASE}/web/middle/2.6/${this.pageId}/https/${this.guidData}`
|
|
const response = await this.fetchImpl(url, {
|
|
method: 'GET',
|
|
headers: {
|
|
'user-agent': WEB_USER_AGENT,
|
|
accept:
|
|
'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
|
|
referer: 'https://aq.huya.com/',
|
|
...buildHeaders(this.jar.header()),
|
|
},
|
|
signal: AbortSignal.timeout(20_000),
|
|
})
|
|
this.jar.absorb(response.headers)
|
|
await response.arrayBuffer().catch(() => undefined)
|
|
if (!response.ok) throw new Error(`虎牙设备引导接口失败:HTTP ${response.status}`)
|
|
}
|
|
|
|
async call(path: string, uri: string, data: JsonRecord): Promise<HuyaQrResponse> {
|
|
const requestId = this.requestCounter
|
|
const envelope = {
|
|
uri,
|
|
version: '2.6',
|
|
context: this.context,
|
|
appId: '5002',
|
|
appSign: APP_SIGN_WEB,
|
|
authId: '',
|
|
sdid: this.activeSdid,
|
|
lcid: '2052',
|
|
byPass: '3',
|
|
requestId: String(requestId),
|
|
data,
|
|
}
|
|
this.requestCounter = requestId + 120 + Math.floor(Math.random() * 281)
|
|
const headers: Record<string, string> = {
|
|
'user-agent': WEB_USER_AGENT,
|
|
origin: UDB_BASE,
|
|
'content-type': 'application/json;charset=UTF-8',
|
|
accept: '*/*',
|
|
context: this.context,
|
|
uri,
|
|
reqid: String(requestId),
|
|
lcid: '2052',
|
|
Referer: `${UDB_BASE}/web/middle/2.6/${this.pageId}/https/${this.context.split('-')[1] || ''}`,
|
|
...buildHeaders(this.jar.header()),
|
|
}
|
|
const response = await this.fetchImpl(`${UDB_BASE}${path}`, {
|
|
method: 'POST',
|
|
headers,
|
|
body: JSON.stringify(envelope),
|
|
signal: AbortSignal.timeout(20_000),
|
|
})
|
|
this.jar.absorb(response.headers)
|
|
const text = await response.text()
|
|
if (!response.ok) throw new Error(`虎牙登录接口失败:HTTP ${response.status}`)
|
|
try {
|
|
return (text ? JSON.parse(text) : {}) as HuyaQrResponse
|
|
} catch {
|
|
throw new Error('虎牙登录接口返回了无法解析的响应')
|
|
}
|
|
}
|
|
|
|
async getQrImg(qrid: string): Promise<string> {
|
|
const response = await this.fetchImpl(
|
|
`${UDB_BASE}/qrLgn/getQrImg?k=${encodeURIComponent(qrid)}&appId=5002`,
|
|
{
|
|
method: 'GET',
|
|
headers: {
|
|
'user-agent': WEB_USER_AGENT,
|
|
accept: 'image/avif,image/webp,image/apng,image/*,*/*;q=0.8',
|
|
referer: 'https://aq.huya.com/',
|
|
...buildHeaders(this.jar.header()),
|
|
},
|
|
signal: AbortSignal.timeout(20_000),
|
|
},
|
|
)
|
|
this.jar.absorb(response.headers)
|
|
if (!response.ok) throw new Error(`虎牙登录二维码图片获取失败:HTTP ${response.status}`)
|
|
const contentType = String(response.headers.get('content-type') || 'image/png').split(';', 1)[0]
|
|
const buffer = Buffer.from(await response.arrayBuffer())
|
|
if (buffer.length === 0) throw new Error('虎牙登录二维码图片为空')
|
|
return `data:${contentType || 'image/png'};base64,${buffer.toString('base64')}`
|
|
}
|
|
|
|
async verifyCookie(): Promise<void> {
|
|
const response = await this.fetchImpl(`${UDB_BASE}/web/cookie/verify`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'user-agent': WEB_USER_AGENT,
|
|
origin: 'https://www.huya.com',
|
|
referer: 'https://www.huya.com/',
|
|
'content-type': 'application/json',
|
|
accept: 'application/json, text/javascript, */*; q=0.01',
|
|
cookie: this.jar.header(),
|
|
},
|
|
body: JSON.stringify({ appId: 5002 }),
|
|
signal: AbortSignal.timeout(20_000),
|
|
})
|
|
this.jar.absorb(response.headers)
|
|
if (!response.ok) throw new Error(`虎牙 Cookie 兑换失败:HTTP ${response.status}`)
|
|
}
|
|
}
|
|
|
|
export function webBehavior(page = 'https://www.huya.com/'): { behavior: string; page: string } {
|
|
// 2026-11-09 最新 HAR 的扫码请求:来源 Google、当前页虎牙首页、无鼠标轨迹。
|
|
const value = { furl: 'https://www.google.com/', curl: page, user_action: [] }
|
|
return {
|
|
behavior: encodeURIComponent(JSON.stringify(value)),
|
|
page: encodeURIComponent(page),
|
|
}
|
|
}
|
|
|
|
export type HuyaGameAccount = {
|
|
openId: string
|
|
appId: string
|
|
type: string
|
|
faceUrl: string
|
|
nick: string
|
|
accessToken: string
|
|
extendInfo: string
|
|
}
|
|
|
|
export type HuyaGameRole = {
|
|
roleId: string
|
|
roleName: string
|
|
areaName: string
|
|
platName: string
|
|
partitionName: string
|
|
gameSerial: string
|
|
extendInfo: string
|
|
}
|
|
|
|
export type HuyaGameAccountData = {
|
|
isBindAccount: number
|
|
isBindRole: number
|
|
isNeedActCheck: number
|
|
gameAccount: HuyaGameAccount
|
|
gameRole: HuyaGameRole
|
|
changeBindTime: number
|
|
}
|
|
|
|
export type HuyaBindResponse = {
|
|
status: number
|
|
msg: string
|
|
accountData: HuyaGameAccountData
|
|
gameName: string
|
|
gameAuthScene: string
|
|
changeBindDay: number
|
|
}
|
|
|
|
/** 已绑定账号和角色时无需再次调用换绑接口,当前角色可直接确认使用。 */
|
|
export function hasExistingHuyaBinding(response: HuyaBindResponse | null): boolean {
|
|
if (!response || response.status !== 200) return false
|
|
return Boolean(response.accountData.isBindAccount && response.accountData.isBindRole)
|
|
}
|
|
|
|
export type HuyaConfirmResponse = { status: number; msg: string }
|
|
export type HuyaLiveLinkResponse = {
|
|
status: number
|
|
msg: string
|
|
livelinkParam: Record<string, string>
|
|
}
|
|
export type HuyaUserProfile = { uid: number; nick: string; avatar: string; passport: string }
|
|
export type HuyaUserProfileResponse = { profiles: HuyaUserProfile[] }
|
|
|
|
function emptyAccount(): HuyaGameAccount {
|
|
return {
|
|
openId: '',
|
|
appId: '',
|
|
type: '',
|
|
faceUrl: '',
|
|
nick: '',
|
|
accessToken: '',
|
|
extendInfo: '',
|
|
}
|
|
}
|
|
|
|
function emptyRole(): HuyaGameRole {
|
|
return {
|
|
roleId: '',
|
|
roleName: '',
|
|
areaName: '',
|
|
platName: '',
|
|
partitionName: '',
|
|
gameSerial: '',
|
|
extendInfo: '',
|
|
}
|
|
}
|
|
|
|
function emptyAccountData(): HuyaGameAccountData {
|
|
return {
|
|
isBindAccount: 0,
|
|
isBindRole: 0,
|
|
isNeedActCheck: 0,
|
|
gameAccount: emptyAccount(),
|
|
gameRole: emptyRole(),
|
|
changeBindTime: 0,
|
|
}
|
|
}
|
|
|
|
function parseGameAccount(reader: TafReader): HuyaGameAccount {
|
|
return {
|
|
openId: reader.readString(0),
|
|
appId: reader.readString(1),
|
|
type: reader.readString(2),
|
|
faceUrl: reader.readString(3),
|
|
nick: reader.readString(4),
|
|
accessToken: reader.readString(5),
|
|
extendInfo: reader.readString(6),
|
|
}
|
|
}
|
|
|
|
function parseGameRole(reader: TafReader): HuyaGameRole {
|
|
return {
|
|
roleId: reader.readString(0),
|
|
roleName: reader.readString(1),
|
|
areaName: reader.readString(2),
|
|
platName: reader.readString(3),
|
|
partitionName: reader.readString(4),
|
|
gameSerial: reader.readString(5),
|
|
extendInfo: reader.readString(6),
|
|
}
|
|
}
|
|
|
|
function parseGameAccountData(reader: TafReader): HuyaGameAccountData {
|
|
return {
|
|
isBindAccount: reader.readInt32(0),
|
|
isBindRole: reader.readInt32(1),
|
|
isNeedActCheck: reader.readInt32(2),
|
|
gameAccount: reader.readStruct(3, parseGameAccount) || emptyAccount(),
|
|
gameRole: reader.readStruct(4, parseGameRole) || emptyRole(),
|
|
changeBindTime: reader.readInt32(5),
|
|
}
|
|
}
|
|
|
|
function parseBindResponse(reader: TafReader): HuyaBindResponse {
|
|
return {
|
|
status: reader.readInt32(0),
|
|
msg: reader.readString(1),
|
|
accountData: reader.readStruct(2, parseGameAccountData) || emptyAccountData(),
|
|
gameName: reader.readString(3),
|
|
gameAuthScene: reader.readString(4),
|
|
changeBindDay: reader.readInt32(5),
|
|
}
|
|
}
|
|
|
|
/** 解析 checkUserBindGameAccount 的 tRsp 裸结构,供集成回归和故障排查使用。 */
|
|
export function parseBindStruct(buffer: Buffer): HuyaBindResponse {
|
|
const reader = new TafReader(buffer)
|
|
const [tag, dataType] = reader.readHead()
|
|
if (tag !== 0 || dataType !== TAF_TYPE.STRUCT_BEGIN) {
|
|
throw new Error('虎牙绑定响应不是有效的 TAF 结构体')
|
|
}
|
|
return reader.readStructBody(parseBindResponse)
|
|
}
|
|
|
|
function parseConfirmResponse(reader: TafReader): HuyaConfirmResponse {
|
|
return { status: reader.readInt32(0), msg: reader.readString(1) }
|
|
}
|
|
|
|
function parseLiveLinkResponse(reader: TafReader): HuyaLiveLinkResponse {
|
|
return {
|
|
status: reader.readInt32(0),
|
|
msg: reader.readString(1),
|
|
livelinkParam: reader.readMap(2),
|
|
}
|
|
}
|
|
|
|
function isProfileIntType(dataType: TafTypeValue): boolean {
|
|
return (
|
|
dataType === TAF_TYPE.INT8 ||
|
|
dataType === TAF_TYPE.INT16 ||
|
|
dataType === TAF_TYPE.INT32 ||
|
|
dataType === TAF_TYPE.INT64 ||
|
|
dataType === TAF_TYPE.ZERO
|
|
)
|
|
}
|
|
|
|
function readProfileString(reader: TafReader, dataType: TafTypeValue): string {
|
|
if (dataType === TAF_TYPE.STRING1 || dataType === TAF_TYPE.STRING4) {
|
|
return reader.readStringValue(dataType)
|
|
}
|
|
|
|
if (dataType === TAF_TYPE.ZERO) return ''
|
|
|
|
reader.skipValue(dataType)
|
|
return ''
|
|
}
|
|
|
|
function parseProfile(reader: TafReader): HuyaUserProfile {
|
|
let uid = 0
|
|
let nick = ''
|
|
let avatar = ''
|
|
let passport = ''
|
|
while (reader.remaining > 0) {
|
|
const [tag, dataType] = reader.peekHead()
|
|
if (dataType === TAF_TYPE.STRUCT_END) {
|
|
break
|
|
}
|
|
reader.readHead()
|
|
if (dataType === TAF_TYPE.STRUCT_BEGIN) {
|
|
// 新版虎牙把资料包在 tag0 的嵌套结构里,直接解析内层结构。
|
|
if (tag === 0) {
|
|
return reader.readStructBody((nested) => parseProfile(nested))
|
|
}
|
|
reader.skipValue(dataType)
|
|
continue
|
|
}
|
|
if (tag === 0) {
|
|
if (isProfileIntType(dataType)) uid = reader.readIntValue(dataType)
|
|
else reader.skipValue(dataType)
|
|
} else if (tag === 1) nick = readProfileString(reader, dataType)
|
|
else if (tag === 2) avatar = readProfileString(reader, dataType)
|
|
else if (tag === 17) passport = readProfileString(reader, dataType)
|
|
else reader.skipValue(dataType)
|
|
}
|
|
return { uid, nick, avatar, passport }
|
|
}
|
|
|
|
function parseProfileResponse(reader: TafReader): HuyaUserProfile | null {
|
|
return parseProfile(reader)
|
|
}
|
|
|
|
function parseProfileBatch(reader: TafReader): HuyaUserProfileResponse {
|
|
const profiles =
|
|
reader.readList<HuyaUserProfile>(0, (itemReader, dataType) => {
|
|
if (dataType !== TAF_TYPE.STRUCT_BEGIN) {
|
|
itemReader.skipValue(dataType)
|
|
return null
|
|
}
|
|
return itemReader.readStructBody((envelopeReader) => {
|
|
const profile = envelopeReader.readStruct(0, parseProfile)
|
|
return profile || { uid: 0, nick: '', avatar: '', passport: '' }
|
|
})
|
|
}) || []
|
|
return { profiles }
|
|
}
|
|
|
|
export type HuyaRpcClientOptions = {
|
|
fetchImpl?: FetchLike
|
|
timeoutMs?: number
|
|
}
|
|
|
|
export class HuyaRpcClient {
|
|
private readonly fetchImpl: FetchLike
|
|
private readonly timeoutMs: number
|
|
|
|
constructor(options: HuyaRpcClientOptions = {}) {
|
|
this.fetchImpl = options.fetchImpl || fetch
|
|
this.timeoutMs = Math.max(1000, options.timeoutMs || 15_000)
|
|
}
|
|
|
|
async checkUserBindGameAccount(input: {
|
|
uid: number
|
|
cookie: string
|
|
bindActId: number
|
|
outerActId: string
|
|
isUseOuterActId?: number
|
|
gid?: number
|
|
scene?: string
|
|
}): Promise<HuyaBindResponse | null> {
|
|
const response = await this.callRpc(
|
|
'webActUI',
|
|
'checkUserBindGameAccount',
|
|
input.uid,
|
|
input.cookie,
|
|
(writer) => {
|
|
this.writeActivityUser(writer, input.uid, input.cookie)
|
|
writer.writeInt32(1, input.gid || 0)
|
|
writer.writeString(2, input.outerActId || '')
|
|
writer.writeInt32(3, 0)
|
|
writer.writeString(4, input.scene || '')
|
|
writer.writeInt32(5, input.bindActId || 0)
|
|
writer.writeInt32(6, input.isUseOuterActId ?? 1)
|
|
},
|
|
)
|
|
return response ? readWupStruct(response, parseBindResponse) : null
|
|
}
|
|
|
|
async confirmBindActAccount(input: {
|
|
uid: number
|
|
cookie: string
|
|
bindActId: number
|
|
outerActId: string
|
|
gid?: number
|
|
}): Promise<HuyaConfirmResponse | null> {
|
|
const response = await this.callRpc(
|
|
'webActUI',
|
|
'confirmBindActAccount',
|
|
input.uid,
|
|
input.cookie,
|
|
(writer) => {
|
|
this.writeActivityUser(writer, input.uid, input.cookie)
|
|
writer.writeInt32(1, input.gid || 0)
|
|
writer.writeString(2, input.outerActId || '')
|
|
writer.writeInt32(3, input.bindActId || 0)
|
|
},
|
|
)
|
|
return response ? readWupStruct(response, parseConfirmResponse) : null
|
|
}
|
|
|
|
async getLiveLinkParam(input: {
|
|
uid: number
|
|
cookie: string
|
|
bindActId: number
|
|
outerActId: number
|
|
gameAuthScene?: string
|
|
}): Promise<HuyaLiveLinkResponse | null> {
|
|
const response = await this.callRpc(
|
|
'webActUI',
|
|
'getLiveLinkParam',
|
|
input.uid,
|
|
input.cookie,
|
|
(writer) => {
|
|
this.writeActivityUser(writer, input.uid, input.cookie)
|
|
writer.writeInt32(1, 0)
|
|
writer.writeInt32(2, input.outerActId || 0)
|
|
writer.writeString(3, input.gameAuthScene || '')
|
|
writer.writeString(4, '')
|
|
writer.writeInt32(5, input.bindActId || 0)
|
|
},
|
|
)
|
|
return response ? readWupStruct(response, parseLiveLinkResponse) : null
|
|
}
|
|
|
|
async getUserProfileBatch(input: {
|
|
uid: number
|
|
cookie: string
|
|
targetUids: number[]
|
|
}): Promise<HuyaUserProfileResponse | null> {
|
|
const targetUids = input.targetUids.map((item) => Math.trunc(item)).filter((item) => item > 0)
|
|
if (targetUids.length === 0) return null
|
|
const response = await this.callRpc(
|
|
'huyauserui',
|
|
'getUserProfileBatch',
|
|
input.uid,
|
|
input.cookie,
|
|
(writer) => {
|
|
this.writeActivityUser(writer, 0, '')
|
|
writer.writeList(1, targetUids, (itemWriter, item) => itemWriter.writeInt64(0, item))
|
|
},
|
|
)
|
|
return response ? readWupStruct(response, parseProfileBatch) : null
|
|
}
|
|
|
|
async getUserProfile(input: {
|
|
uid: number
|
|
cookie: string
|
|
targetUid: number
|
|
}): Promise<HuyaUserProfile | null> {
|
|
const targetUid = Math.trunc(input.targetUid)
|
|
if (!(targetUid > 0)) return null
|
|
const response = await this.callRpc(
|
|
'huyauserui',
|
|
'getUserProfile',
|
|
input.uid,
|
|
input.cookie,
|
|
(writer) => {
|
|
this.writeActivityUser(writer, 0, input.cookie)
|
|
writer.writeInt64(1, targetUid)
|
|
},
|
|
)
|
|
return response ? readWupStruct(response, parseProfileResponse) : null
|
|
}
|
|
|
|
private async callRpc(
|
|
servant: string,
|
|
func: string,
|
|
uid: number,
|
|
cookie: string,
|
|
writeRequest: (writer: TafWriter) => void,
|
|
): Promise<WupResponse | null> {
|
|
const body = encodeWupRequest({ servant, func, requestId: 1, writeRequest })
|
|
const baseinfo = generateRpcBaseinfo(uid, cookie)
|
|
const response = await this.fetchImpl(`https://${CDNWS_HOST}/?baseinfo=${baseinfo}`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'user-agent': PC_UA,
|
|
origin: 'https://zt.huya.com',
|
|
referer: 'https://zt.huya.com/',
|
|
'content-type': 'application/octet-stream',
|
|
'accept-language': 'zh-CN,zh;q=0.9',
|
|
},
|
|
body: new Uint8Array(body),
|
|
signal: AbortSignal.timeout(this.timeoutMs),
|
|
})
|
|
if (!response.ok) throw new Error(`虎牙 WUP 请求失败:HTTP ${response.status}`)
|
|
const buffer = Buffer.from(await response.arrayBuffer())
|
|
return decodeWupResponse(buffer)
|
|
}
|
|
|
|
private writeActivityUser(writer: TafWriter, uid: number, cookie: string): void {
|
|
writer.writeStruct(0, (userWriter) => {
|
|
userWriter.writeInt64(0, uid)
|
|
userWriter.writeString(1, '')
|
|
userWriter.writeString(2, '')
|
|
userWriter.writeString(3, HTTP_HUYA_UA)
|
|
userWriter.writeString(4, normalizeHuyaCookie(cookie))
|
|
userWriter.writeInt32(5, 0)
|
|
userWriter.writeString(6, '')
|
|
userWriter.writeString(7, '')
|
|
})
|
|
}
|
|
}
|
|
|
|
function firstCookieValue(cookie: string, key: string): string {
|
|
for (const [itemKey, itemValue] of cookiePairs(cookie)) {
|
|
if (itemKey === key && itemValue) return itemValue
|
|
}
|
|
return ''
|
|
}
|
|
|
|
export function resolveCookieGuid(cookie: string): string {
|
|
const guid = firstCookieValue(cookie, 'guid')
|
|
if (guid) return guid
|
|
const udbGuid = firstCookieValue(cookie, 'udb_guiddata')
|
|
if (udbGuid) return udbGuid.slice(0, 32)
|
|
const seed = ['yyuid', 'udb_uid', 'udb_passport', 'username', 'udb_biztoken']
|
|
.map((key) => firstCookieValue(cookie, key))
|
|
.filter(Boolean)
|
|
.join('|')
|
|
return seed ? crypto.createHash('sha256').update(seed).digest('hex').slice(0, 32) : ''
|
|
}
|
|
|
|
export function normalizeHuyaCookie(cookie: string): string {
|
|
if (!cookie) return ''
|
|
const pairs = cookiePairs(normalizeCookiePairs(cookiePairs(cookie))).filter(
|
|
([key]) => key !== 'huya_ua',
|
|
)
|
|
if (!pairs.some(([key]) => key === 'guid')) {
|
|
const guid = resolveCookieGuid(cookie)
|
|
if (guid) pairs.push(['guid', guid])
|
|
}
|
|
return normalizeCookiePairs([['huya_ua', HTTP_HUYA_UA], ...pairs])
|
|
}
|
|
|
|
function generateRpcBaseinfo(uid: number, cookie: string): string {
|
|
const normalizedCookie = normalizeHuyaCookie(cookie)
|
|
const guid = resolveCookieGuid(cookie)
|
|
const traceId = crypto.randomBytes(8).toString('hex')
|
|
const writer = new TafWriter()
|
|
writer.writeInt64(0, uid)
|
|
writer.writeString(1, guid)
|
|
writer.writeString(2, HTTP_HUYA_UA)
|
|
writer.writeString(3, 'HUYA&ZH&2052')
|
|
writer.writeString(4, '')
|
|
writer.writeString(5, '')
|
|
writer.writeInt32(6, 0)
|
|
writer.writeString(7, '')
|
|
writer.writeString(8, normalizedCookie)
|
|
writer.writeString(9, `${traceId}:${traceId}:0:0`)
|
|
writer.writeMap(10, {})
|
|
return encodeURIComponent(writer.toBuffer().toString('base64'))
|
|
}
|
|
|
|
export function livelinkQrcodeImageSrc(qrcode: string): string {
|
|
const text = String(qrcode || '').trim()
|
|
if (!text) return ''
|
|
const lower = text.toLowerCase()
|
|
if (
|
|
lower.startsWith('https://') ||
|
|
lower.startsWith('http://') ||
|
|
lower.startsWith('data:image/')
|
|
) {
|
|
return text
|
|
}
|
|
return `data:${text.startsWith('iVBOR') ? 'image/png' : 'image/jpeg'};base64,${text}`
|
|
}
|
|
|
|
export async function getLiveLinkMiniQrcode(
|
|
bindPageUrl: string,
|
|
options: { fetchImpl?: FetchLike; timeoutMs?: number } = {},
|
|
): Promise<{ image: string; token: string } | null> {
|
|
const url = new URL(bindPageUrl)
|
|
const query = url.search.slice(1)
|
|
const params = url.searchParams
|
|
const suffix = Array.from(
|
|
{ length: 8 },
|
|
() => 'abcdefghijklmnopqrstuvwxyz0123456789'[Math.floor(Math.random() * 36)],
|
|
).join('')
|
|
const sessionId = `${Math.floor(Date.now() / 1000)}_${suffix}`
|
|
const fetchImpl = options.fetchImpl || fetch
|
|
const response = await fetchImpl(`${LIVELINK_BIND_API_BASE}/api/qrcode/getMiniAppQrcode`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'user-agent': PC_UA,
|
|
origin: 'https://livelink.qq.com',
|
|
referer: 'https://livelink.qq.com/',
|
|
'content-type': 'application/json;charset=UTF-8',
|
|
accept: 'application/json, text/plain, */*',
|
|
'accept-language': 'zh-CN,zh;q=0.9',
|
|
},
|
|
body: JSON.stringify({ queryString: `${query}&sessionId=${sessionId}` }),
|
|
signal: AbortSignal.timeout(options.timeoutMs || 15_000),
|
|
})
|
|
if (!response.ok) return null
|
|
const payload = (await response.json().catch(() => null)) as {
|
|
iRet?: number
|
|
jData?: { qrcode?: string; qrcodeToken?: string }
|
|
} | null
|
|
if (!payload || payload.iRet !== 0) return null
|
|
const image = livelinkQrcodeImageSrc(String(payload.jData?.qrcode || ''))
|
|
if (!image) return null
|
|
return { image, token: String(payload.jData?.qrcodeToken || '') }
|
|
}
|
|
|
|
export async function getLiveLinkQrcodeStatus(
|
|
token: string,
|
|
options: { fetchImpl?: FetchLike; timeoutMs?: number } = {},
|
|
): Promise<{
|
|
isScan: boolean
|
|
isExpired: boolean
|
|
isCompleted: boolean
|
|
isFailure: boolean
|
|
} | null> {
|
|
const normalized = String(token || '').trim()
|
|
if (!normalized) return null
|
|
const fetchImpl = options.fetchImpl || fetch
|
|
const response = await fetchImpl(`${LIVELINK_BIND_API_BASE}/api/qrcode/poolingQrcodeStatus`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'user-agent': PC_UA,
|
|
origin: 'https://livelink.qq.com',
|
|
referer: 'https://livelink.qq.com/',
|
|
'content-type': 'application/json;charset=UTF-8',
|
|
accept: 'application/json, text/plain, */*',
|
|
'accept-language': 'zh-CN,zh;q=0.9',
|
|
},
|
|
body: JSON.stringify({ qrcodeToken: normalized }),
|
|
signal: AbortSignal.timeout(options.timeoutMs || 15_000),
|
|
})
|
|
if (!response.ok) return null
|
|
const payload = (await response.json().catch(() => null)) as {
|
|
iRet?: number
|
|
jData?: {
|
|
isScan?: boolean
|
|
isExpired?: boolean
|
|
isCompleted?: boolean
|
|
isFailure?: boolean
|
|
}
|
|
} | null
|
|
if (!payload || payload.iRet !== 0) return null
|
|
return {
|
|
isScan: Boolean(payload.jData?.isScan),
|
|
isExpired: Boolean(payload.jData?.isExpired),
|
|
isCompleted: Boolean(payload.jData?.isCompleted),
|
|
isFailure: Boolean(payload.jData?.isFailure),
|
|
}
|
|
}
|
|
|
|
export function buildBindUrls(input: {
|
|
livelinkParam: Record<string, string>
|
|
bindActId: number
|
|
gameAuthScene?: string
|
|
nickName?: string
|
|
faceUrl?: string
|
|
redirectUrl?: string
|
|
}): {
|
|
actionUrl: string
|
|
qrUrl: string
|
|
pcUrl: string
|
|
huyaContainerUrl: string
|
|
exchangeQqCoinUrl: string
|
|
} {
|
|
const bindQuery: Record<string, string> = {
|
|
t: input.livelinkParam.t || '',
|
|
gameIdList: input.livelinkParam.gameIdList || '',
|
|
actId: input.livelinkParam.actId || '',
|
|
livePlatId: input.livelinkParam.livePlatId || '',
|
|
sig: input.livelinkParam.sig || '',
|
|
code: input.livelinkParam.code || '',
|
|
faceUrl: encodeURIComponent(input.faceUrl || ''),
|
|
nickName: encodeURIComponent(input.nickName || ''),
|
|
}
|
|
const joinQuery = (query: Record<string, string>) =>
|
|
Object.entries(query)
|
|
.map(([key, value]) => `${key}=${value}`)
|
|
.join('&')
|
|
const bindQueryText = joinQuery(bindQuery)
|
|
const miniPath = encodeURIComponent(`/pages/gameAccountBind/index?${bindQueryText}`)
|
|
const actionUrl =
|
|
'https://m.huya.com?hyaction=launchweixinminiprogram' +
|
|
`&path=${miniPath}&username=gh_49af166706ae`
|
|
const pcQuery = { ...bindQuery, redirectUrl: encodeURIComponent(input.redirectUrl || '') }
|
|
const pcUrl = `https://livelink.qq.com/act/a20200527midgroupage/pc/?${joinQuery(pcQuery)}`
|
|
const huyaParams = new URLSearchParams({
|
|
bActId: String(input.bindActId || 0),
|
|
isUseOuterActId: '1',
|
|
delayclose: '1000',
|
|
from: 'diy',
|
|
})
|
|
if (input.gameAuthScene) huyaParams.set('gameAuthScene', input.gameAuthScene)
|
|
const huyaBase = 'https://hd.huya.com/h5/livelinkV3/index.html'
|
|
const huyaContainerUrl = `${huyaBase}?${huyaParams.toString()}`
|
|
const exchangeParams = new URLSearchParams(huyaParams)
|
|
exchangeParams.set('extendParm', 'type=qqCoinDeliver')
|
|
return {
|
|
actionUrl,
|
|
qrUrl: pcUrl,
|
|
pcUrl,
|
|
huyaContainerUrl,
|
|
exchangeQqCoinUrl: `${huyaBase}?${exchangeParams.toString()}`,
|
|
}
|
|
}
|
|
|
|
export type { WupResponse, TafTypeValue }
|