fix(semi-auto): 换绑未生效原因与 7 天冷却提示

This commit is contained in:
2026-11-16 13:30:26 +08:00
parent 19367bdfdf
commit 5aa627a0ca
10 changed files with 781 additions and 93 deletions
@@ -52,6 +52,8 @@ const LOGIN_QR_TTL_MS = 5 * 60 * 1000
const SMS_LOGIN_TTL_MS = 5 * 60 * 1000
const CREDENTIAL_TTL_MS = 24 * 60 * 60 * 1000
const BINDING_QR_TTL_MS = 5 * 60 * 1000
const REBIND_WINDOW_DAYS = 7
const DAY_MS = 24 * 60 * 60 * 1000
const BROWSER_TICKET_TTL_MS = 2 * 60 * 1000
const MAX_SESSIONS = 500
const NATIVE_TICKET_PREFIX = 'native-ticket-'
@@ -73,6 +75,11 @@ type NativeBindState = {
hasExistingBinding: boolean
rebindRequested: boolean
rebindScanned: boolean
rebindUnchanged: boolean
rebindCooldownDays: number
nextRebindAt: string
changeBindTime: number
changeBindDay: number
baselineRoleKey: string
message: string
}
@@ -148,6 +155,11 @@ function defaultBindingState(): NativeBindState {
hasExistingBinding: false,
rebindRequested: false,
rebindScanned: false,
rebindUnchanged: false,
rebindCooldownDays: 0,
nextRebindAt: '',
changeBindTime: 0,
changeBindDay: 0,
baselineRoleKey: '',
message: '',
}
@@ -157,6 +169,78 @@ function iso(value: number): string {
return new Date(value).toISOString()
}
function rebindDateLabel(value: string): string {
if (!value) return ''
const date = new Date(value)
if (Number.isNaN(date.getTime())) return ''
return new Intl.DateTimeFormat('zh-CN', {
timeZone: 'Asia/Shanghai',
year: 'numeric',
month: '2-digit',
day: '2-digit',
}).format(date)
}
export type RebindCooldownInput = {
status?: number
changeBindDay?: number
accountData?: { changeBindTime?: number } | null
}
/**
* 虎牙活动限制:每 7 个自然日允许换绑 1 次。
* changeBindTime 为上次绑定/换绑时间(秒级 Unix 时间戳),changeBindDay 作为兜底剩余天数。
*/
export function resolveRebindCooldown(
response: RebindCooldownInput | null | undefined,
now = Date.now(),
): { days: number; nextRebindAt: string } {
if (!response || (response.status !== undefined && response.status !== 200)) {
return { days: 0, nextRebindAt: '' }
}
const changeBindTime = Number(response.accountData?.changeBindTime || 0)
if (Number.isFinite(changeBindTime) && changeBindTime > 0) {
const changedAtMs = changeBindTime > 1e12 ? changeBindTime : changeBindTime * 1000
const nextRebindMs = changedAtMs + REBIND_WINDOW_DAYS * DAY_MS
if (nextRebindMs > now) {
return {
days: Math.ceil((nextRebindMs - now) / DAY_MS),
nextRebindAt: iso(nextRebindMs),
}
}
}
const changeBindDay = Number(response.changeBindDay || 0)
if (Number.isFinite(changeBindDay) && changeBindDay > 0 && changeBindDay <= 30) {
const days = Math.round(changeBindDay)
return { days, nextRebindAt: iso(now + days * DAY_MS) }
}
return { days: 0, nextRebindAt: '' }
}
function applyRebindMeta(
session: NativeSession,
response: HuyaBindResponse | null,
now: number,
): void {
const cooldown = resolveRebindCooldown(response, now)
session.binding.rebindCooldownDays = cooldown.days
session.binding.nextRebindAt = cooldown.nextRebindAt
session.binding.changeBindTime = Number(response?.accountData?.changeBindTime || 0)
session.binding.changeBindDay = Number(response?.changeBindDay || 0)
}
function rebindUnchangedMessage(
roleName: string,
cooldownDays: number,
nextRebindAt: string,
): string {
const next = rebindDateLabel(nextRebindAt)
if (cooldownDays > 0) {
return `扫码后仍识别到原绑定角色「${roleName}」;本活动 7 天内只能换绑 1 次${next ? `,预计下次换绑:${next}` : ''}`
}
return `扫码后仍识别到原绑定角色「${roleName}」,请确认微信中选择的角色或重新换绑`
}
function extractInt(value: unknown): number {
const parsed = Number.parseInt(String(value ?? '').trim(), 10)
return Number.isFinite(parsed) && parsed > 0 ? parsed : 0
@@ -674,10 +758,17 @@ export class HuyaNativeConnector {
const role = parseRole(roleResponse)
const hasExistingBinding = hasExistingHuyaBinding(roleResponse)
session.binding.hasExistingBinding = hasExistingBinding
applyRebindMeta(session, roleResponse, this.now())
if (role.role && !options.forceRebind) {
this.markRoleReady(session, role, hasExistingBinding && !session.binding.rebindRequested)
if (session.binding.rebindRequested) {
session.binding.message = '已识别待换绑角色,请确认换绑'
session.binding.message = session.binding.rebindUnchanged
? rebindUnchangedMessage(
role.role,
session.binding.rebindCooldownDays,
session.binding.nextRebindAt,
)
: '已识别待换绑角色,请确认换绑'
}
return this.bindingView(session)
}
@@ -700,11 +791,20 @@ export class HuyaNativeConnector {
errorCode: 'huya_livelink_param_failed',
})
}
const profile = await rpc.getUserProfile({
uid: session.uid,
cookie: session.cookie,
targetUid: session.uid,
})
let profile: Awaited<ReturnType<typeof rpc.getUserProfile>> = null
try {
profile = await rpc.getUserProfile({
uid: session.uid,
cookie: session.cookie,
targetUid: session.uid,
})
} catch (error) {
// 资料接口结构可能随虎牙升级变化,失败时回退登录会话里的昵称/头像,不能阻断换绑二维码。
logWarn('huya/bind/profile', '获取虎牙账号资料失败,回退登录昵称', {
uid: session.uid,
error: errorMessage(error),
})
}
const nickname = profile?.nick || profile?.passport || session.nickname
session.nickname = nickname
const avatar = profile?.avatar || ''
@@ -732,6 +832,7 @@ export class HuyaNativeConnector {
if (options.forceRebind) {
session.binding.rebindRequested = true
session.binding.rebindScanned = false
session.binding.rebindUnchanged = false
session.binding.baselineRoleKey = bindingRoleKey(role)
}
session.binding.status = 'qr_pending'
@@ -790,24 +891,30 @@ export class HuyaNativeConnector {
const role = parseRole(response)
const hasExistingBinding = hasExistingHuyaBinding(response)
session.binding.hasExistingBinding = hasExistingBinding
applyRebindMeta(session, response, this.now())
if (role.role) {
const rebindRequested = session.binding.rebindRequested
const roleKey = bindingRoleKey(role)
const changedRole =
!session.binding.baselineRoleKey || roleKey !== session.binding.baselineRoleKey
if (rebindRequested && !changedRole) {
if (qrCompleted) {
session.binding.rebindRequested = false
session.binding.rebindScanned = false
session.binding.baselineRoleKey = ''
if (qrCompleted || session.binding.rebindUnchanged) {
// 扫码完成但虎牙仍返回原角色:保留 rebind 状态,明确告知未换绑及冷却原因,
// 不能清空 rebindRequested,否则 confirmBinding 会误判为“使用已有绑定”。
session.binding.rebindUnchanged = true
this.markRoleReady(session, role, hasExistingBinding)
session.binding.message = '扫码后仍识别到原绑定角色,请确认使用或重新换绑'
session.binding.message = rebindUnchangedMessage(
role.role,
session.binding.rebindCooldownDays,
session.binding.nextRebindAt,
)
} else {
session.binding.status = 'scanned'
session.binding.message = '已扫码,正在等待换绑角色生效'
}
return this.bindingView(session)
}
if (rebindRequested) session.binding.rebindUnchanged = false
this.markRoleReady(session, role, hasExistingBinding && !rebindRequested)
if (rebindRequested) {
session.binding.message = '已识别换绑角色,请确认换绑'
@@ -839,15 +946,24 @@ export class HuyaNativeConnector {
})
}
const rebindRequested = session.binding.rebindRequested
applyRebindMeta(session, response, this.now())
if (
rebindRequested &&
session.binding.baselineRoleKey &&
bindingRoleKey(role) === session.binding.baselineRoleKey
) {
throw createHttpError('换绑角色尚未生效,请稍后重试', {
statusCode: 409,
errorCode: 'huya_bind_rebind_not_ready',
})
const cooldownDays = session.binding.rebindCooldownDays
const next = rebindDateLabel(session.binding.nextRebindAt)
throw createHttpError(
cooldownDays > 0
? `换绑未生效:平台仍返回原绑定角色「${role.role}」;本活动 7 天内只能换绑 1 次${next ? `,预计下次换绑:${next}` : ''}`
: `换绑未生效:平台仍返回原绑定角色「${role.role}」,请重新扫码选择正确角色`,
{
statusCode: 409,
errorCode:
cooldownDays > 0 ? 'huya_bind_rebind_cooldown' : 'huya_bind_rebind_not_ready',
},
)
}
const useExistingBinding = hasExistingHuyaBinding(response) && !rebindRequested
if (!useExistingBinding) {
@@ -869,6 +985,9 @@ export class HuyaNativeConnector {
session.binding.hasExistingBinding = true
session.binding.rebindRequested = false
session.binding.rebindScanned = false
session.binding.rebindUnchanged = false
session.binding.rebindCooldownDays = 0
session.binding.nextRebindAt = ''
session.binding.baselineRoleKey = ''
session.binding.message = useExistingBinding
? '当前虎牙账号已有绑定角色,已确认直接使用'
@@ -1156,6 +1275,11 @@ export class HuyaNativeConnector {
bindGameChannel: binding.channel,
hasExistingBinding: binding.hasExistingBinding,
rebindRequested: binding.rebindRequested,
rebindUnchanged: binding.rebindUnchanged,
rebindCooldownDays: binding.rebindCooldownDays,
nextRebindAt: binding.nextRebindAt,
platformChangeBindDay: binding.changeBindDay,
platformChangeBindTime: binding.changeBindTime,
message: binding.message,
}
}
@@ -401,6 +401,27 @@ function parseLiveLinkResponse(reader: TafReader): HuyaLiveLinkResponse {
}
}
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 = ''
@@ -412,10 +433,20 @@ function parseProfile(reader: TafReader): HuyaUserProfile {
break
}
reader.readHead()
if (tag === 0) uid = reader.readIntValue(dataType)
else if (tag === 1) nick = reader.readStringValue(dataType)
else if (tag === 2) avatar = reader.readStringValue(dataType)
else if (tag === 17) passport = reader.readStringValue(dataType)
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 }
@@ -0,0 +1,45 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { resolveRebindCooldown } from './huya-native-connector.js'
// 2026-11-16 12:12:24 +08:00,对应任务 34 的初次绑定时间。
const NOW = Date.UTC(2026, 10, 16, 4, 12, 24)
const DAY_MS = 24 * 60 * 60 * 1000
test('换绑冷却:changeBindTime 为初次绑定时间时,下次换绑为 7 天后', () => {
const result = resolveRebindCooldown(
{
status: 200,
changeBindDay: 0,
accountData: { changeBindTime: Math.floor(NOW / 1000) },
},
NOW,
)
assert.equal(result.days, 7)
assert.equal(result.nextRebindAt.slice(0, 10), '2026-11-23')
})
test('换绑冷却:changeBindTime 已超过 7 天时不再限制', () => {
const result = resolveRebindCooldown(
{
status: 200,
changeBindDay: 0,
accountData: { changeBindTime: Math.floor((NOW - 8 * DAY_MS) / 1000) },
},
NOW,
)
assert.equal(result.days, 0)
assert.equal(result.nextRebindAt, '')
})
test('换绑冷却:changeBindTime 缺失时用 changeBindDay 兜底', () => {
const result = resolveRebindCooldown({ status: 200, changeBindDay: 3, accountData: {} }, NOW)
assert.equal(result.days, 3)
assert.equal(result.nextRebindAt.slice(0, 10), '2026-11-19')
})
test('换绑冷却:字段为空时不限制', () => {
const result = resolveRebindCooldown({ status: 200, changeBindDay: 0, accountData: {} }, NOW)
assert.deepEqual(result, { days: 0, nextRebindAt: '' })
})