/** * 虎牙网页短信登录协议。 * * 短信登录使用独立的网页设备上下文:df/token -> df/collect -> UDB middle, * 不能复用扫码链路的 App 设备指纹,否则 sdid 与 appId 语义不一致。 */ import crypto from 'node:crypto' import vm from 'node:vm' import { brotliDecompressSync, gunzipSync, inflateSync } from 'node:zlib' import sharp from 'sharp' import { logWarn } from '../../../utils/logger.js' import { HuyaCookieJar, UDB_BASE } from './huya-rpc.js' const DF_TOKEN_URL = 'https://df.huya.com/web/df/token' const DF_COLLECT_URL = 'https://df.huya.com/web/df/collect' const APP_VERSION = '2.6' const APP_ID = '5002' const APP_SIGN = '1ce3bf682483d03f146f58232ec10635' const LCID = '2052' const AUTH_BASE = 'https://udbrtt.huya.com' const SMS_WEB_UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 ' + '(KHTML, like Gecko) Chrome/150.0.0.0 Safari/537.36' type FetchLike = typeof fetch type JsonRecord = Record export type HuyaSmsResponse = JsonRecord & { data?: JsonRecord returnCode?: number | string message?: string } type HuyaChallengeBase = { image: string width: number height: number } export type HuyaSliderChallenge = HuyaChallengeBase & { type: 'slider' puzzleImage: string puzzleWidth: number puzzleY: number } export type HuyaRotateChallenge = HuyaChallengeBase & { type: 'rotate' puzzleImage: string puzzleWidth: number puzzleHeight: number puzzleX: number puzzleY: number } export type HuyaClickChallenge = HuyaChallengeBase & { type: 'click' tipImage: string question: string wordSize: number } export type HuyaVerificationChallenge = | HuyaSliderChallenge | HuyaRotateChallenge | HuyaClickChallenge export type HuyaSmsSendResult = | { kind: 'sent' sessionData: string message: string } | { kind: 'challenge' challenge: HuyaVerificationChallenge message: string } export type HuyaChallengeSolution = { distance?: unknown angle?: unknown points?: unknown } export type HuyaSliderDetection = { distance: number score: number y: number } type ChallengeState = { strategyUrl: string page: string urlParamMap: Record sceneType: string gurl: string vurl: string code: string huyapk: string jsContext: vm.Context challenge: HuyaVerificationChallenge } function requestId(): string { const now = new Date() const midnight = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()) return String(Math.max(0, now.getTime() - midnight)) } function readString(value: unknown): string { return String(value ?? '').trim() } function readSegment(value: unknown): string | number[] { if (!Array.isArray(value)) return readString(value) return value .map((item) => Number(item)) .filter((item) => Number.isFinite(item)) .map((item) => Math.max(0, Math.min(255, Math.trunc(item)))) } function commonHeaders(): Record { return { Accept: '*/*', 'Accept-Language': 'zh-CN,zh;q=0.9', 'Cache-Control': 'no-cache', Connection: 'keep-alive', 'Content-Type': 'application/json;charset=UTF-8', Origin: 'https://aq.huya.com', Pragma: 'no-cache', Referer: 'https://aq.huya.com/', 'Sec-Fetch-Dest': 'empty', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Site': 'same-site', 'User-Agent': SMS_WEB_UA, 'sec-ch-ua': '"Not;A=Brand";v="8", "Chromium";v="150", "Google Chrome";v="150"', 'sec-ch-ua-mobile': '?0', 'sec-ch-ua-platform': '"macOS"', } } function imageDataUrl(value: unknown, mime = 'image/png'): string { const raw = readString(value) if (!raw) return '' return raw.startsWith('data:image/') ? raw : `data:${mime};base64,${raw}` } function imageBuffer(value: unknown): Buffer { const raw = readString(value) const payload = raw.includes(';base64,') ? raw.split(';base64,').pop() || '' : raw return Buffer.from(payload, 'base64') } function encodeBehavior(events: unknown[]): string { return encodeURIComponent(JSON.stringify(events)) } function authPageUrl(): string { return `https://aq.huya.com/p/udb_login.html?v=${String(Date.now()).slice(0, 8)}00000` } function formatTrack(points: number[][]): string { return points.map(([x, y, time]) => `${x},${y},${time}`).join(';') } function easeOutExpo(value: number): number { return value === 1 ? 1 : 1 - 2 ** (-10 * value) } function generateTrack(distance: number): number[][] { const total = distance + 10 + Math.floor(Math.random() * 31) let currentTime = Date.now() - (1500 + Math.floor(Math.random() * 501)) const startX = 56 + Math.floor(Math.random() * 8) const startY = 210 + Math.floor(Math.random() * 4) const points: number[][] = [[startX, startY, currentTime]] const count = 40 + Math.floor(Math.random() * 21) let previous = 0 for (let index = 0; index < count; index += 1) { const x = Math.round(easeOutExpo(index / count) * total) currentTime += 10 + Math.floor(Math.random() * 11) if (x === previous) continue points.push([x + startX, startY - 1 + Math.floor(Math.random() * 3), currentTime]) previous = x } const lastPoint = points[points.length - 1] if (lastPoint) points.push([...lastPoint]) return points } function edgeMap(data: Buffer, width: number, height: number, channels: number): Float32Array { const gray = new Float32Array(width * height) const at = (index: number) => gray[index] ?? 0 for (let index = 0, offset = 0; index < gray.length; index += 1, offset += channels) { gray[index] = 0.299 * Number(data[offset] || 0) + 0.587 * Number(data[offset + 1] || 0) + 0.114 * Number(data[offset + 2] || 0) } const edges = new Float32Array(width * height) for (let y = 1; y < height - 1; y += 1) { for (let x = 1; x < width - 1; x += 1) { const index = y * width + x const gx = -at(index - width - 1) - 2 * at(index - 1) - at(index + width - 1) + at(index - width + 1) + 2 * at(index + 1) + at(index + width + 1) const gy = -at(index - width - 1) - 2 * at(index - width) - at(index - width + 1) + at(index + width - 1) + 2 * at(index + width) + at(index + width + 1) edges[index] = Math.hypot(gx, gy) } } return edges } export async function detectHuyaSliderDistance(input: { image: string puzzleImage: string puzzleY: number puzzleWidth: number }): Promise { const background = await sharp(imageBuffer(input.image)) .grayscale() .raw() .toBuffer({ resolveWithObject: true }) const puzzle = await sharp(imageBuffer(input.puzzleImage)) .ensureAlpha() .raw() .toBuffer({ resolveWithObject: true }) if (background.info.width <= puzzle.info.width || background.info.height <= puzzle.info.height) { return null } const backgroundEdges = edgeMap(background.data, background.info.width, background.info.height, 1) const puzzleEdges = edgeMap(puzzle.data, puzzle.info.width, puzzle.info.height, 4) const alpha = new Float32Array(puzzle.info.width * puzzle.info.height) for (let index = 0; index < alpha.length; index += 1) { alpha[index] = Number(puzzle.data[index * 4 + 3] || 0) / 255 } const yCenter = Math.max( 0, Math.min(background.info.height - puzzle.info.height, Math.round(input.puzzleY)), ) const yStart = Math.max(1, yCenter - 8) const yEnd = Math.min(background.info.height - puzzle.info.height - 1, yCenter + 8) let best: HuyaSliderDetection | null = null for (let x = 1; x <= background.info.width - puzzle.info.width - 1; x += 1) { for (let y = yStart; y <= yEnd; y += 1) { let dot = 0 let puzzleEnergy = 0 let backgroundEnergy = 0 for (let pieceY = 0; pieceY < puzzle.info.height; pieceY += 1) { for (let pieceX = 0; pieceX < puzzle.info.width; pieceX += 1) { const pieceIndex = pieceY * puzzle.info.width + pieceX const mask = alpha[pieceIndex] ?? 0 if (mask <= 0.2) continue const pieceEdge = (puzzleEdges[pieceIndex] ?? 0) * mask const backgroundEdge = backgroundEdges[(y + pieceY) * background.info.width + x + pieceX] ?? 0 dot += pieceEdge * backgroundEdge puzzleEnergy += pieceEdge * pieceEdge backgroundEnergy += backgroundEdge * backgroundEdge } } if (puzzleEnergy <= 0 || backgroundEnergy <= 0) continue const score = dot / Math.sqrt(puzzleEnergy * backgroundEnergy) if (!best || score > best.score) best = { distance: x, score, y } } } return best && best.score >= 0.7 ? best : null } function challengeTypeFromUrl(url: string): HuyaVerificationChallenge['type'] | 'qr' | 'sms' { const lower = url.toLowerCase() if (lower.includes('rotate_auth') || lower.includes('/auth/xz/')) return 'rotate' if (lower.includes('dx_auth') || lower.includes('/auth/dx/')) return 'click' if (lower.includes('qr_auth')) return 'qr' if (lower.includes('sms_auth')) return 'sms' return 'slider' } export class HuyaSmsRole { private readonly jar = new HuyaCookieJar() private readonly fetchImpl: FetchLike private readonly deviceId = crypto.randomBytes(16).toString('hex') private readonly mid = crypto.randomBytes(16).toString('hex').toUpperCase() private readonly reqId = requestId() private readonly context = `WB-${this.deviceId}-${this.mid}-` private readonly middleUrl = `${UDB_BASE}/web/middle/${APP_VERSION}/${this.reqId}/https/${this.deviceId}` private sdid = '' private hdid = '' private challengeState: ChallengeState | null = null constructor(fetchImpl: FetchLike = fetch) { this.fetchImpl = fetchImpl } cookieHeader(): string { return this.jar.header() } setCookies(cookie: string): void { this.jar.clear() this.jar.set(cookie) } async prepareDevice(): Promise { const tokenResponse = await this.fetchImpl(DF_TOKEN_URL, { method: 'POST', headers: commonHeaders(), body: JSON.stringify({ encryptVersion: '1.0.1', fingerprintVersion: '1.2.41', }), signal: AbortSignal.timeout(20_000), }) this.jar.absorb(tokenResponse.headers) if (!tokenResponse.ok) throw new Error(`虎牙 df token 获取失败:HTTP ${tokenResponse.status}`) const tokenPayload = (await tokenResponse.json().catch(() => ({}))) as { data?: { token?: string } } const token = readString(tokenPayload.data?.token) if (!token) throw new Error('虎牙 df token 为空') const collectResponse = await this.fetchImpl(DF_COLLECT_URL, { method: 'POST', headers: commonHeaders(), body: JSON.stringify({ token }), signal: AbortSignal.timeout(20_000), }) this.jar.absorb(collectResponse.headers) if (!collectResponse.ok) { throw new Error(`虎牙 sdid 获取失败:HTTP ${collectResponse.status}`) } const collectPayload = (await collectResponse.json().catch(() => ({}))) as { data?: { sdid?: string; hdid?: string } } this.sdid = readString(collectPayload.data?.sdid) this.hdid = readString(collectPayload.data?.hdid) if (!this.sdid) throw new Error('虎牙 sdid 为空') } async bootstrapMiddle(): Promise { for (const host of ['udblgn.huya.com', 'udb3lgn.huya.com', 'udbreg.huya.com']) { const url = `https://${host}/web/middle/${APP_VERSION}/${this.reqId}/https/${this.deviceId}` try { const response = await this.fetchImpl(url, { method: 'GET', headers: { ...commonHeaders(), ...(this.jar.header() ? { cookie: this.jar.header() } : {}), }, signal: AbortSignal.timeout(20_000), }) this.jar.absorb(response.headers) await response.arrayBuffer().catch(() => undefined) } catch { // UDB middle 是上下文初始化,个别备用域名失败不影响后续主接口。 } } } async call(path: string, uri: string, data: JsonRecord): Promise { const response = await this.fetchImpl(`${UDB_BASE}${path}`, { method: 'POST', headers: { ...commonHeaders(), Origin: UDB_BASE, Referer: this.middleUrl, Context: this.context, Lcid: LCID, Reqid: this.reqId, Uri: uri, ...(this.jar.header() ? { cookie: this.jar.header() } : {}), }, body: JSON.stringify({ uri, version: APP_VERSION, context: this.context, appId: APP_ID, appSign: APP_SIGN, authId: '', sdid: this.sdid, lcid: LCID, byPass: '3', requestId: this.reqId, data, }), signal: AbortSignal.timeout(20_000), }) this.jar.absorb(response.headers) if (!response.ok) throw new Error(`虎牙短信登录接口失败:HTTP ${response.status}`) const text = await response.text() try { return (text ? JSON.parse(text) : {}) as HuyaSmsResponse } catch { throw new Error('虎牙短信登录接口返回了无法解析的响应') } } async prepareChallenge(response: HuyaSmsResponse): Promise { const page = authPageUrl() const strategyUrl = this.strategyUrl(response) if (!strategyUrl) throw new Error('虎牙安全验证缺少策略地址') const challengeType = challengeTypeFromUrl(strategyUrl) if (challengeType === 'qr') { throw new Error('虎牙要求使用已登录 App 扫码确认') } if (challengeType === 'sms') { throw new Error('虎牙要求完成额外的短信安全验证') } const parsed = new URL(strategyUrl) const urlParamMap = Object.fromEntries(parsed.searchParams.entries()) if (!urlParamMap.param) throw new Error('虎牙安全验证缺少 param') let sceneType = urlParamMap.sceneType || '' let config = await this.requestConfig3(urlParamMap, sceneType, page) if ((!config.gurl || !config.vurl || !config.js) && sceneType !== '4') { urlParamMap.sceneType = '4' sceneType = '4' config = await this.requestConfig3(urlParamMap, sceneType, page) } if (!config.gurl || !config.vurl || !config.js) { throw new Error('虎牙安全验证未下发图形验证配置') } const jsContext = this.compileCipher(config.js) let data: JsonRecord = {} let code = '' let huyapk = '' let segment: string | number[] = '' let backgroundRaw: unknown = '' let background: Buffer = Buffer.alloc(0) let puzzleRaw = '' let restoredImage = '' let pointError: unknown = null for (let attempt = 0; attempt < 3; attempt += 1) { const pointResponse = await this.requestJson(config.gurl, { appId: APP_ID, data: { urlParamMap, wupData: '', page, behavior: encodeBehavior([]), info: this.sdid, ver: 5, }, }) data = pointResponse.data || {} logWarn('huya/sms/challenge-point', '虎牙图形验证原始响应', { returnCode: pointResponse.returnCode, data: { code: data.code, segment: data.segment, huyapk: data.huyapk, location_y: data.location_y, question: data.question, wordSize: data.wordSize, title: data.title, expire: data.expire, dtuLength: readString(data.dtuStr ?? data.dTuStr ?? data.bgStr).length, puzzleLength: readString(data.puzzleStr).length, tipLength: readString(data.hZiStr ?? data.hziStr).length, }, }) code = readString(data.code) huyapk = readString(data.huyapk) segment = readSegment(data.segment) backgroundRaw = data.dtuStr ?? data.dTuStr ?? data.bgStr background = imageBuffer(backgroundRaw) puzzleRaw = readString(data.puzzleStr) if (!code || !huyapk || !background.length) { pointError = new Error('虎牙图形验证参数不完整') } else if (challengeType === 'click') { pointError = null break } else if (!puzzleRaw) { pointError = new Error('虎牙拼图验证参数不完整') } else if (!segment) { restoredImage = imageDataUrl(backgroundRaw) pointError = null break } else { try { restoredImage = await this.restoreScrambledBackground( background, segment, huyapk, jsContext, ) pointError = null break } catch (error) { pointError = error } } if (attempt < 2) await new Promise((resolve) => setTimeout(resolve, 250)) } if (pointError) throw pointError let challenge: HuyaVerificationChallenge if (challengeType === 'click') { const metadata = await sharp(background).metadata() challenge = { type: 'click', image: imageDataUrl(backgroundRaw), tipImage: imageDataUrl(data.hZiStr ?? data.hziStr ?? data.puzzleStr), question: readString(data.question), wordSize: Math.max(1, Number(data.wordSize || 3)), width: Number(metadata.width || 350), height: Number(metadata.height || 268), } } else { const metadata = await sharp(background).metadata() const puzzleMetadata = await sharp(imageBuffer(puzzleRaw)).metadata() const image = restoredImage || imageDataUrl(backgroundRaw) challenge = challengeType === 'rotate' ? { type: 'rotate', image, puzzleImage: imageDataUrl(puzzleRaw), width: Number(metadata.width || 350), height: Number(metadata.height || 180), puzzleWidth: Number(puzzleMetadata.width || 180), puzzleHeight: Number(puzzleMetadata.height || 180), puzzleX: 105, puzzleY: 0, } : { type: 'slider', image, puzzleImage: imageDataUrl(puzzleRaw), width: Number(metadata.width || 350), height: Number(metadata.height || 180), puzzleWidth: Number(puzzleMetadata.width || 0), puzzleY: Number(data.location_y || 0), } } this.challengeState = { strategyUrl, page, urlParamMap, sceneType, gurl: config.gurl, vurl: config.vurl, code, huyapk, jsContext, challenge, } return challenge } async solveChallenge(solution: HuyaChallengeSolution): Promise { const state = this.challengeState if (!state) { throw new Error('虎牙安全验证会话不存在或已过期') } const answer = this.buildChallengeAnswer(state, solution) const actData = answer.actData const act = this.encryptAct(state.jsContext, actData, state.huyapk) const verifyUrl = new URL(state.vurl) verifyUrl.searchParams.set('lock', 'true') const result = await this.requestJson(verifyUrl.toString(), { appId: APP_ID, data: { urlParamMap: state.urlParamMap, wupData: '', page: state.page, behavior: encodeBehavior(answer.behaviorEvents), info: this.sdid, act, ver: 5, }, }) const authId = readString(result.data?.authId) if (!authId) throw new Error('虎牙图形验证未通过,请重新完成') this.challengeState = null } async detectSliderDistance(): Promise { const challenge = this.challengeState?.challenge if (!challenge || challenge.type !== 'slider') return null return detectHuyaSliderDistance({ image: challenge.image, puzzleImage: challenge.puzzleImage, puzzleY: challenge.puzzleY, puzzleWidth: challenge.puzzleWidth, }) } async verifyCookie(): Promise { const response = await this.fetchImpl(`${UDB_BASE}/web/cookie/verify`, { method: 'POST', headers: { 'user-agent': SMS_WEB_UA, 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}`) } device(): { sdid: string; hdid: string } { return { sdid: this.sdid, hdid: this.hdid } } private strategyUrl(response: HuyaSmsResponse): string { const data = response.data || {} const strategies = Array.isArray(data.strategys) ? data.strategys : [] const strategy = strategies[0] return strategy && typeof strategy === 'object' ? readString((strategy as Record).data) : '' } private async requestConfig3( urlParamMap: Record, sceneType: string, page: string, ): Promise<{ gurl: string; vurl: string; js: string }> { const response = await this.requestJson(`${AUTH_BASE}/auth/client/config3`, { appId: APP_ID, data: { urlParamMap: { ...urlParamMap, sceneType }, wupData: '', page, behavior: encodeBehavior([]), info: this.sdid, cTuIndex: 0, }, }) return { gurl: readString(response.data?.gurl), vurl: readString(response.data?.vurl), js: readString(response.data?.js), } } private async requestJson(url: string, payload: Record) { const response = await this.fetchImpl(url, { method: 'POST', headers: { ...commonHeaders(), Origin: 'https://aq.huya.com', Referer: 'https://aq.huya.com/', ...(this.jar.header() ? { cookie: this.jar.header() } : {}), }, body: JSON.stringify(payload), signal: AbortSignal.timeout(20_000), }) this.jar.absorb(response.headers) const text = await response.text() if (!response.ok) { let requestUrl = url try { const parsed = new URL(url) requestUrl = `${parsed.origin}${parsed.pathname}?${Array.from(parsed.searchParams.keys()).join(',')}` } catch { requestUrl = url.split('?', 1)[0] || url } logWarn('huya/sms/http-error', '虎牙安全验证请求返回错误', { requestUrl, status: response.status, responseBody: text.slice(0, 800), }) throw new Error(`虎牙安全验证请求失败:HTTP ${response.status}`) } try { return (text ? JSON.parse(text) : {}) as HuyaSmsResponse } catch { throw new Error('虎牙安全验证接口返回了无法解析的响应') } } private compileCipher(js: string): vm.Context { const context = vm.createContext({ console, atob: (value: string) => Buffer.from(value, 'base64').toString('binary'), btoa: (value: string) => Buffer.from(value, 'binary').toString('base64'), navigator: { userAgent: SMS_WEB_UA }, document: {}, location: { href: 'https://aq.huya.com/' }, crypto: crypto.webcrypto, TextEncoder, TextDecoder, setTimeout, clearTimeout, }) Object.assign(context, { window: context, self: context, globalThis: context }) new vm.Script(js, { filename: 'huya-sms-captcha.js' }).runInContext(context, { timeout: 3000, }) const available = vm.runInContext('Boolean(window.UdbCipher)', context, { timeout: 1000 }) if (!available) throw new Error('虎牙图形验证加密组件初始化失败') return context } private buildChallengeAnswer( state: ChallengeState, solution: HuyaChallengeSolution, ): { actData: Record; behaviorEvents: unknown[] } { const challenge = state.challenge if (challenge.type === 'click') { const rawPoints = Array.isArray(solution.points) ? solution.points : [] const points = rawPoints .map((value) => { if (Array.isArray(value)) { return [Number(value[0]), Number(value[1])] as [number, number] } if (value && typeof value === 'object') { const point = value as Record return [Number(point.x), Number(point.y)] as [number, number] } return null }) .filter((value): value is [number, number] => Boolean(value)) .filter( ([x, y]) => Number.isFinite(x) && Number.isFinite(y) && x >= 0 && x <= challenge.width && y >= 0 && y <= challenge.height, ) .slice(0, Math.max(1, challenge.wordSize)) if (points.length === 0) throw new Error('虎牙点选验证坐标无效') let currentTime = Date.now() - (5000 + Math.floor(Math.random() * 5001)) const clickData = points.map(([x, y]) => { currentTime += 1000 + Math.floor(Math.random() * 1001) return [Math.round(x), Math.round(y), currentTime] as [number, number, number] }) const intervalTimeList = clickData.map((item) => item[2]) return { actData: { clickData: points.map(([x, y]) => `${Math.round(x)}_${Math.round(y)}`).join(','), intervalTime: intervalTimeList.join('_'), endTime: Number(intervalTimeList[intervalTimeList.length - 1] || 0) - Number(intervalTimeList[0] || 0), sceneType: state.sceneType, code: state.code, }, behaviorEvents: clickData.map(([x, y, time], index) => ({ action: 'mousedown', id: '', txt: ['', '1', '1\\n2'][index] || '', clientX: x, clientY: y, clientWidth: challenge.width, clientHeight: challenge.height, isTrusted: true, timeStamp: 2000 + Math.floor(Math.random() * 3001), nowTime: time, })), } } const value = challenge.type === 'rotate' ? Math.round(Number(solution.angle)) : Math.round(Number(solution.distance)) if ( !Number.isInteger(value) || value < 0 || (challenge.type === 'rotate' ? value >= 360 : value > challenge.width) ) { throw new Error(challenge.type === 'rotate' ? '虎牙旋转角度无效' : '虎牙滑块位置无效') } const dragDistance = challenge.type === 'rotate' ? Math.max(5, Math.round((value / 360) * 260)) : value const track = generateTrack(dragDistance) const firstPoint = track[0] const lastPoint = track[track.length - 1] if (!firstPoint || !lastPoint) throw new Error('虎牙拖动轨迹生成失败') return { actData: { point: value, travel: formatTrack(track), code: state.code, sceneType: state.sceneType, endTime: Number(lastPoint[2] || 0) - Number(firstPoint[2] || 0), }, behaviorEvents: [ { action: 'mousedown', id: '', txt: '', clientX: firstPoint[0], clientY: firstPoint[1], clientWidth: challenge.width, clientHeight: challenge.height, isTrusted: true, timeStamp: 1800 + Math.floor(Math.random() * 3701), nowTime: Date.now(), }, ], } } private async restoreScrambledBackground( background: Buffer, segment: string | number[], huyapk: string, context: vm.Context, ): Promise { context.__segment = segment context.__huyapk = huyapk const decrypted = vm.runInContext('window.UdbCipher.decrypt(__segment, __huyapk)', context, { timeout: 3000, }) const regionIndexes = this.parseRegionIndexes(decrypted) if (!Array.isArray(regionIndexes) || regionIndexes.length === 0) { throw new Error('虎牙拼图背景解密失败') } const metadata = await sharp(background).metadata() const width = Number(metadata.width || 350) const height = Number(metadata.height || 180) const composites: Array<{ input: Buffer; left: number; top: number }> = [] for (let index = 0; index < regionIndexes.length; index += 1) { const sourceLeft = Math.max(0, Math.min(width - 1, Number(regionIndexes[index]) * 26)) const stripWidth = Math.max(1, Math.min(26, width - sourceLeft, width - index * 26)) const strip = await sharp(background) .extract({ left: sourceLeft, top: 0, width: stripWidth, height }) .png() .toBuffer() composites.push({ input: strip, left: index * 26, top: 0 }) } const restored = await sharp({ create: { width, height, channels: 4, background: { r: 255, g: 255, b: 255, alpha: 1 } }, }) .composite(composites) .png() .toBuffer() return `data:image/png;base64,${restored.toString('base64')}` } private parseRegionIndexes(decrypted: unknown): number[] { const candidates = new Set() const buffers: Buffer[] = [] if (ArrayBuffer.isView(decrypted)) { buffers.push(Buffer.from(decrypted.buffer, decrypted.byteOffset, decrypted.byteLength)) } else if (Object.prototype.toString.call(decrypted) === '[object ArrayBuffer]') { buffers.push(Buffer.from(decrypted as ArrayBuffer)) } else { const text = readString(decrypted) if (text) { candidates.add(text) buffers.push(Buffer.from(text, 'binary'), Buffer.from(text, 'utf8')) const normalizedBase64 = text.replace(/-/g, '+').replace(/_/g, '/') const padded = normalizedBase64.padEnd(Math.ceil(normalizedBase64.length / 4) * 4, '=') buffers.push(Buffer.from(padded, 'base64')) if (/^[0-9a-f]+$/i.test(text) && text.length % 2 === 0) { buffers.push(Buffer.from(text, 'hex')) } try { candidates.add(decodeURIComponent(text)) } catch { // 非 URL 编码时继续尝试其他形式。 } } } for (const buffer of buffers) { candidates.add(buffer.toString('utf8')) candidates.add(buffer.toString('latin1')) for (const decompress of [gunzipSync, inflateSync, brotliDecompressSync]) { try { candidates.add(decompress(buffer).toString('utf8')) } catch { // 当前字节流不是该压缩格式。 } } } for (const candidate of candidates) { try { const parsed = JSON.parse(candidate) as { ord?: unknown } if (Array.isArray(parsed.ord)) { return parsed.ord.map((value) => Number(value)).filter((value) => Number.isFinite(value)) } } catch { // 当前候选不是 JSON,继续尝试下一种编码。 } } const decryptedType = ArrayBuffer.isView(decrypted) ? 'bytes' : Object.prototype.toString.call(decrypted) === '[object ArrayBuffer]' ? 'arraybuffer' : typeof decrypted const decryptedLength = ArrayBuffer.isView(decrypted) ? decrypted.byteLength : Object.prototype.toString.call(decrypted) === '[object ArrayBuffer]' ? (decrypted as ArrayBuffer).byteLength : readString(decrypted).length const decryptedPrefix = ArrayBuffer.isView(decrypted) ? Array.from( Buffer.from(decrypted.buffer, decrypted.byteOffset, decrypted.byteLength).subarray(0, 16), ) : Array.from(Buffer.from(readString(decrypted), 'binary').subarray(0, 16)) throw new Error( `虎牙拼图背景解密结果无法解析(type=${decryptedType}, length=${decryptedLength}, prefix=${decryptedPrefix.join(',')})`, ) } private encryptAct( context: vm.Context, actData: Record, huyapk: string, ): string | number[] { context.__act = Buffer.from(encodeURI(JSON.stringify(actData))).toString('base64') context.__huyapk = huyapk const encrypted = vm.runInContext('window.UdbCipher.encrypt(__act, __huyapk)', context, { timeout: 3000, }) if (Array.isArray(encrypted) || ArrayBuffer.isView(encrypted)) { return Array.from(encrypted as ArrayLike) .map((value) => Number(value)) .filter((value) => Number.isFinite(value)) .map((value) => Math.max(0, Math.min(255, Math.trunc(value)))) } const value = readString(encrypted) if (!value) throw new Error('虎牙验证轨迹加密失败') return value } }