Merge branch 'dev_1115_huya'
This commit is contained in:
@@ -50,6 +50,7 @@ type MockSession = {
|
||||
bindingQrExpiresAtMs: number
|
||||
bindGameAccount: string
|
||||
bindGameRole: string
|
||||
bindGameRoleId: string
|
||||
bindGameChannel: string
|
||||
message: string
|
||||
tickets: Map<string, MockTicket>
|
||||
@@ -136,8 +137,10 @@ function bindingView(session: MockSession): ConnectorBindingSession {
|
||||
status: session.bindingStatus,
|
||||
qrImage: session.bindingStatus === 'not_started' ? '' : buildMockBindingQr(session.sessionId),
|
||||
qrExpiresAt: new Date(session.bindingQrExpiresAtMs).toISOString(),
|
||||
qrUrl: '',
|
||||
bindGameAccount: session.bindGameAccount,
|
||||
bindGameRole: session.bindGameRole,
|
||||
bindGameRoleId: session.bindGameRoleId,
|
||||
bindGameChannel: session.bindGameChannel,
|
||||
message: session.message,
|
||||
}
|
||||
@@ -158,6 +161,7 @@ function markRoleReady(session: MockSession) {
|
||||
session.bindingStatus = 'role_ready'
|
||||
session.bindGameAccount = `mock-account-${session.sessionId.slice(-6)}`
|
||||
session.bindGameRole = 'Mock测试角色'
|
||||
session.bindGameRoleId = `mock-role-${session.sessionId.slice(-6)}`
|
||||
session.bindGameChannel = '虎牙'
|
||||
session.message = 'Mock 已识别游戏角色,请确认绑定'
|
||||
}
|
||||
@@ -188,6 +192,7 @@ export function createMockLoginSession(input: {
|
||||
bindingQrExpiresAtMs: 0,
|
||||
bindGameAccount: '',
|
||||
bindGameRole: '',
|
||||
bindGameRoleId: '',
|
||||
bindGameChannel: '',
|
||||
message: 'Mock 登录二维码已生成,轮询后会自动模拟扫码成功',
|
||||
tickets: new Map(),
|
||||
@@ -230,6 +235,7 @@ export function sendMockHuyaSmsCode(input: {
|
||||
bindingQrExpiresAtMs: 0,
|
||||
bindGameAccount: '',
|
||||
bindGameRole: '',
|
||||
bindGameRoleId: '',
|
||||
bindGameChannel: '',
|
||||
message: 'Mock 短信验证码已发送,请输入 123456',
|
||||
tickets: new Map(),
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* 虎牙 checkUserBindGameAccount 返回的 gameRole.roleId 是 40 位加密串,
|
||||
* 无法直接和客户填写的游戏编号比对;平台侧可用于核对的是登录账号的数值 UID(huyaUid)。
|
||||
*
|
||||
* 取数优先级:角色 ID 本身是纯数字 > 数值 UID > 原始角色 ID。
|
||||
* 这样既兼容未来虎牙直接下发数值角色 ID,也避免把加密串展示给客户。
|
||||
*/
|
||||
export function resolveBindingRoleId(roleId: unknown, huyaUid: unknown): string {
|
||||
const rawRoleId = String(roleId ?? '').trim()
|
||||
|
||||
if (/^\d+$/.test(rawRoleId)) return rawRoleId
|
||||
|
||||
const uid = String(huyaUid ?? '').trim()
|
||||
|
||||
return /^\d+$/.test(uid) ? uid : rawRoleId
|
||||
}
|
||||
|
||||
/** 只有纯数字角色 ID 才能和客户填写的游戏编号做可信比对。 */
|
||||
export function isNumericBindingRoleId(value: unknown): boolean {
|
||||
return /^\d+$/.test(String(value ?? '').trim())
|
||||
}
|
||||
|
||||
export type BindingRoleInfo = {
|
||||
resolvedRoleId: string
|
||||
roleIdVerified: boolean
|
||||
hasBoundRole: boolean
|
||||
/** 平台返回了绑定角色,但没有可核对的数字角色 ID → 必须人工核实。 */
|
||||
requiresSupport: boolean
|
||||
}
|
||||
|
||||
/** 统一计算「绑定角色 + 可核对角色 ID」的展示状态,避免前后端各自判断。 */
|
||||
export function describeBindingRole(
|
||||
roleName: unknown,
|
||||
roleId: unknown,
|
||||
huyaUid: unknown,
|
||||
): BindingRoleInfo {
|
||||
const resolvedRoleId = resolveBindingRoleId(roleId, huyaUid)
|
||||
const roleIdVerified = isNumericBindingRoleId(resolvedRoleId)
|
||||
const hasBoundRole = String(roleName ?? '').trim().length > 0
|
||||
return {
|
||||
resolvedRoleId,
|
||||
roleIdVerified,
|
||||
hasBoundRole,
|
||||
requiresSupport: hasBoundRole && !roleIdVerified,
|
||||
}
|
||||
}
|
||||
@@ -202,3 +202,44 @@ test('重新扫码换绑会向 Connector 传递 force_rebind', async () => {
|
||||
globalThis.fetch = originalFetch
|
||||
}
|
||||
})
|
||||
|
||||
test('提交换绑复用 Connector confirm 端点并携带 rebind 标记', async () => {
|
||||
const originalFetch = globalThis.fetch
|
||||
let requestUrl = ''
|
||||
let requestBody: Record<string, unknown> = {}
|
||||
globalThis.fetch = (async (url: string | URL | Request, init?: RequestInit) => {
|
||||
requestUrl = String(url)
|
||||
requestBody = JSON.parse(String(init?.body || '{}')) as Record<string, unknown>
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
sessionId: 'session-1',
|
||||
status: 'scanned',
|
||||
qrImage: '',
|
||||
qrExpiresAt: '',
|
||||
qrUrl: '',
|
||||
bindGameAccount: '微信用户',
|
||||
bindGameRole: '大鲨鱼伊塞53',
|
||||
bindGameRoleId: '1199608910400',
|
||||
bindGameChannel: '安卓(android) · 微信',
|
||||
rebindRequested: true,
|
||||
rebindUnchanged: false,
|
||||
rebindConfirmState: 'accepted',
|
||||
rebindConfirmMessage: '',
|
||||
message: '虎牙已受理换绑,正在等待角色生效',
|
||||
}),
|
||||
{ status: 200, headers: { 'Content-Type': 'application/json' } },
|
||||
)
|
||||
}) as typeof fetch
|
||||
try {
|
||||
const session = await connector.submitHuyaRebind('session-1', 'external')
|
||||
assert.equal(
|
||||
requestUrl,
|
||||
'http://connector.test/api/internal/huya-semi-auto/sessions/session-1/binding/confirm',
|
||||
)
|
||||
assert.deepEqual(requestBody, { rebind: true })
|
||||
assert.equal(session.rebindConfirmState, 'accepted')
|
||||
assert.equal(session.rebindRequested, true)
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch
|
||||
}
|
||||
})
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
huyaNativeConnector,
|
||||
type HuyaStoredCredential,
|
||||
} from './huya-native/huya-native-connector.js'
|
||||
import { recordSemiAutoTrace, traceFingerprint } from './semi-auto-trace.js'
|
||||
|
||||
export type ConnectorLoginSession = {
|
||||
sessionId: string
|
||||
@@ -95,11 +96,26 @@ export type ConnectorBindingSession = {
|
||||
| 'failed'
|
||||
qrImage: string
|
||||
qrExpiresAt: string
|
||||
qrUrl: string
|
||||
bindGameAccount: string
|
||||
bindGameRole: string
|
||||
bindGameRoleId: string
|
||||
bindGameChannel: string
|
||||
/** 平台返回的角色 ID 是否可核对(纯数字);false 时需引导客户联系客服人工核实。 */
|
||||
roleIdVerified?: boolean
|
||||
/** 已绑定角色但缺少可核对角色 ID:客户页应提示联系客服,禁止直接确认绑定。 */
|
||||
requiresSupport?: boolean
|
||||
hasExistingBinding?: boolean
|
||||
rebindRequested?: boolean
|
||||
rebindUnchanged?: boolean
|
||||
rebindConfirmState?: 'idle' | 'submitting' | 'accepted' | 'rejected'
|
||||
rebindConfirmMessage?: string
|
||||
bindConfirmState?: 'idle' | 'submitting' | 'accepted' | 'rejected'
|
||||
bindConfirmMessage?: string
|
||||
rebindCooldownDays?: number
|
||||
nextRebindAt?: string
|
||||
platformChangeBindDay?: number
|
||||
platformChangeBindTime?: number
|
||||
message: string
|
||||
}
|
||||
|
||||
@@ -193,9 +209,11 @@ async function callConnector<T>(
|
||||
const timeoutMs = Math.max(1000, Number(runtimeConfig.semiAuto?.connectorTimeoutMs || 15_000))
|
||||
const controller = new AbortController()
|
||||
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
||||
const method = String(options.method || 'GET').toUpperCase()
|
||||
const startedAt = Date.now()
|
||||
try {
|
||||
const requestInit: RequestInit = {
|
||||
method: options.method || 'GET',
|
||||
method,
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
@@ -212,6 +230,20 @@ async function callConnector<T>(
|
||||
} catch {
|
||||
payload = null
|
||||
}
|
||||
recordSemiAutoTrace({
|
||||
direction: 'outbound',
|
||||
channel: 'external_connector',
|
||||
action: `${method} ${path}`,
|
||||
status: response.ok ? 'ok' : 'error',
|
||||
httpStatus: response.status,
|
||||
durationMs: Date.now() - startedAt,
|
||||
requestSummary: { baseUrl: endpoint.baseUrl },
|
||||
requestBody: options.body,
|
||||
responseSummary: { bodyBytes: text.length },
|
||||
responseBody: payload ?? text,
|
||||
always: method !== 'GET',
|
||||
fingerprint: method === 'GET' ? traceFingerprint(payload) : undefined,
|
||||
})
|
||||
if (!response.ok) {
|
||||
const detail =
|
||||
payload && typeof payload === 'object'
|
||||
@@ -224,6 +256,19 @@ async function callConnector<T>(
|
||||
}
|
||||
return payload as T
|
||||
} catch (error) {
|
||||
if (!(error && typeof error === 'object' && 'statusCode' in error)) {
|
||||
recordSemiAutoTrace({
|
||||
direction: 'outbound',
|
||||
channel: 'external_connector',
|
||||
action: `${method} ${path}`,
|
||||
status: 'error',
|
||||
durationMs: Date.now() - startedAt,
|
||||
requestSummary: { baseUrl: endpoint.baseUrl },
|
||||
requestBody: options.body,
|
||||
always: true,
|
||||
errorMessage: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
}
|
||||
if (error && typeof error === 'object' && 'statusCode' in error) throw error
|
||||
if (error instanceof Error && error.name === 'AbortError') {
|
||||
throw createHttpError('半自动履约 Connector 请求超时', {
|
||||
@@ -410,14 +455,50 @@ export async function getHuyaBinding(
|
||||
)
|
||||
}
|
||||
|
||||
export async function confirmHuyaBinding(
|
||||
/**
|
||||
* 只读绑定快照:不触发虎牙查询,供「确认绑定」这类本地动作使用。
|
||||
* 外部 Connector 没有独立快照端点,只能复用 GET(由 Connector 侧决定是否访问虎牙)。
|
||||
*/
|
||||
export async function getHuyaBindingSnapshot(
|
||||
sessionId: string,
|
||||
mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(),
|
||||
): Promise<ConnectorBindingSession> {
|
||||
if (mode === 'embedded') return huyaNativeConnector.confirmBinding(sessionId)
|
||||
if (mode === 'embedded') return huyaNativeConnector.bindingSnapshot(sessionId)
|
||||
return callConnector<ConnectorBindingSession>(
|
||||
`/api/internal/huya-semi-auto/sessions/${encodeURIComponent(sessionId)}/binding`,
|
||||
{},
|
||||
mode,
|
||||
)
|
||||
}
|
||||
|
||||
export async function confirmHuyaBinding(
|
||||
sessionId: string,
|
||||
mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(),
|
||||
options: { acceptExistingRole?: boolean } = {},
|
||||
): Promise<ConnectorBindingSession> {
|
||||
if (mode === 'embedded') return huyaNativeConnector.confirmBinding(sessionId, options)
|
||||
return callConnector<ConnectorBindingSession>(
|
||||
`/api/internal/huya-semi-auto/sessions/${encodeURIComponent(sessionId)}/binding/confirm`,
|
||||
{ method: 'POST', body: {} },
|
||||
{
|
||||
method: 'POST',
|
||||
body: options.acceptExistingRole ? { acceptExistingRole: true } : {},
|
||||
},
|
||||
mode,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 扫码后由项目侧主动向虎牙提交换绑确认。
|
||||
* 外部 Connector 暂未提供独立端点时复用 confirm 端点(语义一致,幂等)。
|
||||
*/
|
||||
export async function submitHuyaRebind(
|
||||
sessionId: string,
|
||||
mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(),
|
||||
): Promise<ConnectorBindingSession> {
|
||||
if (mode === 'embedded') return huyaNativeConnector.submitRebind(sessionId)
|
||||
return callConnector<ConnectorBindingSession>(
|
||||
`/api/internal/huya-semi-auto/sessions/${encodeURIComponent(sessionId)}/binding/confirm`,
|
||||
{ method: 'POST', body: { rebind: true } },
|
||||
mode,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import { resolveBindingConfirmDecision, shouldSubmitFirstBind } from './huya-native-connector.js'
|
||||
|
||||
test('确认绑定:识别到角色即可本地确认,不需要虎牙接口', () => {
|
||||
assert.equal(
|
||||
resolveBindingConfirmDecision({ status: 'role_ready', role: '大鲨鱼伊塞53' }),
|
||||
'confirm',
|
||||
)
|
||||
})
|
||||
|
||||
test('确认绑定:换绑被虎牙拒绝时必须由客户二选一', () => {
|
||||
assert.equal(
|
||||
resolveBindingConfirmDecision({
|
||||
status: 'role_ready',
|
||||
role: '大鲨鱼伊塞53',
|
||||
rebindRequested: true,
|
||||
rebindUnchanged: true,
|
||||
}),
|
||||
'needs_rebind_decision',
|
||||
)
|
||||
})
|
||||
|
||||
test('确认绑定:客户确认仍使用原角色后放行', () => {
|
||||
assert.equal(
|
||||
resolveBindingConfirmDecision(
|
||||
{
|
||||
status: 'role_ready',
|
||||
role: '大鲨鱼伊塞53',
|
||||
rebindRequested: true,
|
||||
rebindUnchanged: true,
|
||||
},
|
||||
{ acceptExistingRole: true },
|
||||
),
|
||||
'confirm',
|
||||
)
|
||||
})
|
||||
|
||||
test('确认绑定:换绑还在进行中(未判定失败)不拦截确认', () => {
|
||||
assert.equal(
|
||||
resolveBindingConfirmDecision({
|
||||
status: 'role_ready',
|
||||
role: '大鲨鱼伊塞53',
|
||||
rebindRequested: true,
|
||||
}),
|
||||
'confirm',
|
||||
)
|
||||
})
|
||||
|
||||
test('确认绑定:没有角色或状态不对时不能确认', () => {
|
||||
assert.equal(resolveBindingConfirmDecision({ status: 'role_ready', role: '' }), 'not_ready')
|
||||
assert.equal(
|
||||
resolveBindingConfirmDecision({ status: 'qr_pending', role: '大鲨鱼伊塞53' }),
|
||||
'not_ready',
|
||||
)
|
||||
assert.equal(
|
||||
resolveBindingConfirmDecision({ status: 'confirmed', role: '大鲨鱼伊塞53' }),
|
||||
'confirm',
|
||||
)
|
||||
})
|
||||
|
||||
test('首次绑定:没有绑定角色且扫码完成才提交虎牙绑定', () => {
|
||||
assert.equal(shouldSubmitFirstBind({}, { qrCompleted: true, scanned: true }), true)
|
||||
assert.equal(shouldSubmitFirstBind({}, { qrCompleted: false, scanned: true }), false)
|
||||
assert.equal(shouldSubmitFirstBind({}, { qrCompleted: true, scanned: false }), false)
|
||||
})
|
||||
|
||||
test('首次绑定:已有绑定角色或正在换绑时不提交绑定', () => {
|
||||
assert.equal(
|
||||
shouldSubmitFirstBind({ hasExistingBinding: true }, { qrCompleted: true, scanned: true }),
|
||||
false,
|
||||
)
|
||||
assert.equal(
|
||||
shouldSubmitFirstBind(
|
||||
{ rebindRequested: true, hasExistingBinding: false },
|
||||
{ qrCompleted: true, scanned: true },
|
||||
),
|
||||
false,
|
||||
)
|
||||
})
|
||||
|
||||
test('首次绑定:同一张码只提交一次', () => {
|
||||
assert.equal(
|
||||
shouldSubmitFirstBind({ bindConfirmState: 'accepted' }, { qrCompleted: true, scanned: true }),
|
||||
false,
|
||||
)
|
||||
assert.equal(
|
||||
shouldSubmitFirstBind({ bindConfirmState: 'rejected' }, { qrCompleted: true, scanned: true }),
|
||||
false,
|
||||
)
|
||||
assert.equal(
|
||||
shouldSubmitFirstBind({ bindConfirmState: 'submitting' }, { qrCompleted: true, scanned: true }),
|
||||
false,
|
||||
)
|
||||
})
|
||||
@@ -12,6 +12,7 @@ import path from 'node:path'
|
||||
import { runtimeConfig } from '../../../config/runtime.js'
|
||||
import { createHttpError } from '../../../utils/http.js'
|
||||
import { logWarn } from '../../../utils/logger.js'
|
||||
import { describeBindingRole } from '../binding-role-id.js'
|
||||
import type {
|
||||
ConnectorBindingSession,
|
||||
ConnectorBrowserTicket,
|
||||
@@ -51,6 +52,10 @@ 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 REBIND_EFFECT_WINDOW_MS = 60 * 1000
|
||||
const BROWSER_TICKET_TTL_MS = 2 * 60 * 1000
|
||||
const MAX_SESSIONS = 500
|
||||
const NATIVE_TICKET_PREFIX = 'native-ticket-'
|
||||
@@ -62,14 +67,30 @@ type NativeBindingStatus = ConnectorBindingSession['status']
|
||||
type NativeBindState = {
|
||||
status: NativeBindingStatus
|
||||
qrImage: string
|
||||
qrUrl: string
|
||||
qrToken: string
|
||||
expiresAtMs: number
|
||||
account: string
|
||||
role: string
|
||||
roleId: string
|
||||
channel: string
|
||||
hasExistingBinding: boolean
|
||||
rebindRequested: boolean
|
||||
rebindScanned: boolean
|
||||
rebindUnchanged: boolean
|
||||
rebindConfirmState: 'idle' | 'submitting' | 'accepted' | 'rejected'
|
||||
rebindConfirmMessage: string
|
||||
rebindConfirmAt: number
|
||||
rebindEffectDeadlineMs: number
|
||||
/** 首次绑定(账号还没有绑定角色)时,扫码后由项目侧提交 confirmBindActAccount 的状态。 */
|
||||
bindConfirmState: 'idle' | 'submitting' | 'accepted' | 'rejected'
|
||||
bindConfirmMessage: string
|
||||
bindConfirmAt: number
|
||||
bindEffectDeadlineMs: number
|
||||
rebindCooldownDays: number
|
||||
nextRebindAt: string
|
||||
changeBindTime: number
|
||||
changeBindDay: number
|
||||
baselineRoleKey: string
|
||||
message: string
|
||||
}
|
||||
@@ -135,14 +156,29 @@ function defaultBindingState(): NativeBindState {
|
||||
return {
|
||||
status: 'not_started',
|
||||
qrImage: '',
|
||||
qrUrl: '',
|
||||
qrToken: '',
|
||||
expiresAtMs: 0,
|
||||
account: '',
|
||||
role: '',
|
||||
roleId: '',
|
||||
channel: '',
|
||||
hasExistingBinding: false,
|
||||
rebindRequested: false,
|
||||
rebindScanned: false,
|
||||
rebindUnchanged: false,
|
||||
rebindConfirmState: 'idle',
|
||||
rebindConfirmMessage: '',
|
||||
rebindConfirmAt: 0,
|
||||
rebindEffectDeadlineMs: 0,
|
||||
bindConfirmState: 'idle',
|
||||
bindConfirmMessage: '',
|
||||
bindConfirmAt: 0,
|
||||
bindEffectDeadlineMs: 0,
|
||||
rebindCooldownDays: 0,
|
||||
nextRebindAt: '',
|
||||
changeBindTime: 0,
|
||||
changeBindDay: 0,
|
||||
baselineRoleKey: '',
|
||||
message: '',
|
||||
}
|
||||
@@ -152,6 +188,133 @@ 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 次。
|
||||
* 这里计算的是「本次绑定后预计下次可换绑时间」,只用于文案展示,
|
||||
* 不能作为本次提交换绑的前置拦截;是否允许以 confirmBindActAccount 的返回为准。
|
||||
*/
|
||||
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 changeBindDay = Number(response.changeBindDay || 0)
|
||||
const hasPlatformWindow =
|
||||
Number.isFinite(changeBindDay) && changeBindDay > 0 && changeBindDay <= 30
|
||||
const windowDays = hasPlatformWindow ? Math.round(changeBindDay) : REBIND_WINDOW_DAYS
|
||||
const changeBindTime = Number(response.accountData?.changeBindTime || 0)
|
||||
if (Number.isFinite(changeBindTime) && changeBindTime > 0) {
|
||||
const changedAtMs = changeBindTime > 1e12 ? changeBindTime : changeBindTime * 1000
|
||||
// 虎牙把「本次绑定日」记成次日 00:00 的日界:11-16 绑定 → changeBindTime = 2026-11-17 00:00,
|
||||
// 配合 changeBindDay = 7,绑定页提示「预计下次换绑时间 2026/11/23」。
|
||||
// 因此下次可换绑 = 日界 + (窗口天数 - 1) 天;不能用 +7 天,否则会显示成 11-24。
|
||||
const offsetDays = hasPlatformWindow ? Math.max(windowDays - 1, 0) : REBIND_WINDOW_DAYS
|
||||
const nextRebindMs = changedAtMs + offsetDays * DAY_MS
|
||||
if (nextRebindMs > now) {
|
||||
return {
|
||||
days: Math.ceil((nextRebindMs - now) / DAY_MS),
|
||||
nextRebindAt: iso(nextRebindMs),
|
||||
}
|
||||
}
|
||||
}
|
||||
if (hasPlatformWindow) {
|
||||
return { days: windowDays, nextRebindAt: iso(now + windowDays * DAY_MS) }
|
||||
}
|
||||
return { days: 0, nextRebindAt: '' }
|
||||
}
|
||||
|
||||
export type BindingConfirmDecision = 'confirm' | 'needs_rebind_decision' | 'not_ready'
|
||||
|
||||
/**
|
||||
* 客户点「确认绑定」时只做本地流转:角色已识别即可确认,不调用任何虎牙接口。
|
||||
* 唯一需要客户决定的情况是「换绑被虎牙拒绝、平台仍返回原角色」:
|
||||
* 要么重新扫码换绑,要么显式确认继续使用原绑定角色。
|
||||
*/
|
||||
export function resolveBindingConfirmDecision(
|
||||
binding: {
|
||||
status?: string
|
||||
role?: string
|
||||
rebindRequested?: boolean
|
||||
rebindUnchanged?: boolean
|
||||
},
|
||||
options: { acceptExistingRole?: boolean } = {},
|
||||
): BindingConfirmDecision {
|
||||
const role = String(binding.role || '').trim()
|
||||
const status = String(binding.status || '')
|
||||
if (!role || (status !== 'role_ready' && status !== 'confirmed')) return 'not_ready'
|
||||
if (
|
||||
binding.rebindRequested === true &&
|
||||
binding.rebindUnchanged === true &&
|
||||
options.acceptExistingRole !== true
|
||||
) {
|
||||
return 'needs_rebind_decision'
|
||||
}
|
||||
return 'confirm'
|
||||
}
|
||||
|
||||
/**
|
||||
* 首次绑定:账号还没有绑定角色(isBindAccount / isBindRole 任一为 0)时,
|
||||
* 扫码完成后必须由项目侧调用 confirmBindActAccount 完成绑定,再读取角色做本地比对。
|
||||
* 已经有绑定角色、也没发起换绑时不需要任何平台写接口。
|
||||
*/
|
||||
export function shouldSubmitFirstBind(
|
||||
binding: {
|
||||
rebindRequested?: boolean
|
||||
hasExistingBinding?: boolean
|
||||
bindConfirmState?: string
|
||||
},
|
||||
input: { qrCompleted: boolean; scanned: boolean },
|
||||
): boolean {
|
||||
if (!input.qrCompleted || !input.scanned) return false
|
||||
if (binding.rebindRequested === true) return false
|
||||
if (binding.hasExistingBinding === true) return false
|
||||
return (binding.bindConfirmState || 'idle') === 'idle'
|
||||
}
|
||||
|
||||
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 rebindFailureMessage(
|
||||
roleName: string,
|
||||
platformMessage: string,
|
||||
nextRebindAt: string,
|
||||
): string {
|
||||
// 优先展示虎牙原始原因(例如「7 天内只能换绑 1 次」),不要本地编造失败原因。
|
||||
const raw = readString(platformMessage)
|
||||
if (raw) return `换绑未成功:${raw}`
|
||||
const next = rebindDateLabel(nextRebindAt)
|
||||
return `换绑已提交,但平台仍返回原绑定角色「${roleName}」${next ? `,预计下次换绑:${next}` : ''};请稍后刷新或重新提交换绑`
|
||||
}
|
||||
|
||||
function extractInt(value: unknown): number {
|
||||
const parsed = Number.parseInt(String(value ?? '').trim(), 10)
|
||||
return Number.isFinite(parsed) && parsed > 0 ? parsed : 0
|
||||
@@ -223,18 +386,29 @@ function smsBehavior(page = 'https://www.huya.com/g'): { behavior: string; page:
|
||||
function parseRole(response: HuyaBindResponse | null): {
|
||||
account: string
|
||||
role: string
|
||||
roleId: string
|
||||
channel: string
|
||||
} {
|
||||
if (!response || response.status !== 200) return { account: '', role: '', channel: '' }
|
||||
if (!response || response.status !== 200) {
|
||||
return { account: '', role: '', roleId: '', channel: '' }
|
||||
}
|
||||
const data: HuyaGameAccountData = response.accountData
|
||||
const account = data.gameAccount.nick || data.gameRole.roleName
|
||||
const role = data.gameRole.roleName
|
||||
const channel = [data.gameRole.platName, data.gameRole.areaName].filter(Boolean).join(' · ')
|
||||
return { account, role, channel }
|
||||
// 虎牙 checkUserBindGameAccount 的 gameRole.roleId 就是平台侧角色 ID;
|
||||
// 该字段一直存在于 RPC 响应里,之前被丢弃,导致客户页无法做两侧角色比对。
|
||||
const roleId = String(data.gameRole.roleId || '').trim()
|
||||
return { account, role, roleId, channel }
|
||||
}
|
||||
|
||||
function bindingRoleKey(role: { account: string; role: string; channel: string }): string {
|
||||
return [role.account, role.role, role.channel].join('\u0000')
|
||||
function bindingRoleKey(role: {
|
||||
account: string
|
||||
role: string
|
||||
roleId?: string
|
||||
channel: string
|
||||
}): string {
|
||||
return [role.account, role.role, role.roleId || '', role.channel].join('\u0000')
|
||||
}
|
||||
|
||||
function configValues() {
|
||||
@@ -658,10 +832,21 @@ export class HuyaNativeConnector {
|
||||
const role = parseRole(roleResponse)
|
||||
const hasExistingBinding = hasExistingHuyaBinding(roleResponse)
|
||||
session.binding.hasExistingBinding = hasExistingBinding
|
||||
if (role.role && !options.forceRebind) {
|
||||
this.markRoleReady(session, role, hasExistingBinding && !session.binding.rebindRequested)
|
||||
applyRebindMeta(session, roleResponse, this.now())
|
||||
// 只有平台明确「已绑定」才允许直接确认;没有绑定(即使残留角色名)必须走扫码绑定。
|
||||
if (hasExistingBinding && !options.forceRebind) {
|
||||
this.markRoleReady(session, role, true)
|
||||
if (!role.role) {
|
||||
session.binding.message = '当前账号已有绑定角色,但平台未返回角色信息,请联系客服人工核实'
|
||||
}
|
||||
if (session.binding.rebindRequested) {
|
||||
session.binding.message = '已识别待换绑角色,请确认换绑'
|
||||
session.binding.message = session.binding.rebindUnchanged
|
||||
? rebindFailureMessage(
|
||||
role.role,
|
||||
session.binding.rebindConfirmMessage,
|
||||
session.binding.nextRebindAt,
|
||||
)
|
||||
: '已识别待换绑角色,请确认换绑'
|
||||
}
|
||||
return this.bindingView(session)
|
||||
}
|
||||
@@ -684,11 +869,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 || ''
|
||||
@@ -716,19 +910,100 @@ export class HuyaNativeConnector {
|
||||
if (options.forceRebind) {
|
||||
session.binding.rebindRequested = true
|
||||
session.binding.rebindScanned = false
|
||||
session.binding.rebindUnchanged = false
|
||||
session.binding.rebindConfirmState = 'idle'
|
||||
session.binding.rebindConfirmMessage = ''
|
||||
session.binding.rebindConfirmAt = 0
|
||||
session.binding.rebindEffectDeadlineMs = 0
|
||||
session.binding.baselineRoleKey = bindingRoleKey(role)
|
||||
}
|
||||
session.binding.status = 'qr_pending'
|
||||
session.binding.qrImage = mini.image
|
||||
session.binding.qrUrl = urls.qrUrl
|
||||
session.binding.qrToken = mini.token
|
||||
session.binding.expiresAtMs = this.now() + BINDING_QR_TTL_MS
|
||||
if (!options.forceRebind) {
|
||||
// 新的绑定码:清掉上一次绑定提交状态,等这次扫码完成后再提交。
|
||||
session.binding.bindConfirmState = 'idle'
|
||||
session.binding.bindConfirmMessage = ''
|
||||
session.binding.bindConfirmAt = 0
|
||||
session.binding.bindEffectDeadlineMs = 0
|
||||
session.binding.rebindScanned = false
|
||||
}
|
||||
session.binding.message = options.forceRebind
|
||||
? '请使用虎牙 App 扫码选择需要换绑的游戏角色'
|
||||
: '请使用虎牙 App 扫码绑定游戏角色'
|
||||
: '该虎牙账号还没有绑定游戏角色,请用虎牙 App 扫码完成绑定'
|
||||
return this.bindingView(session)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 扫码完成后由项目侧替客户点「确认绑定」。
|
||||
* confirmBindActAccount 确认的是虎牙侧已选中的角色,必须在读取新角色之前调用;
|
||||
* 若客户已在虎牙弹窗里点过确认,重复调用是幂等的。
|
||||
*/
|
||||
private async submitRebindLocked(session: NativeSession, rpc: HuyaRpcClient): Promise<void> {
|
||||
const { bindActId, outerActId } = configValues()
|
||||
const now = this.now()
|
||||
session.binding.rebindConfirmState = 'submitting'
|
||||
session.binding.rebindConfirmMessage = ''
|
||||
session.binding.rebindConfirmAt = now
|
||||
try {
|
||||
const confirmed = await rpc.confirmBindActAccount({
|
||||
uid: session.uid,
|
||||
cookie: session.cookie,
|
||||
bindActId,
|
||||
outerActId,
|
||||
})
|
||||
if (confirmed && confirmed.status === 200) {
|
||||
session.binding.rebindConfirmState = 'accepted'
|
||||
session.binding.rebindEffectDeadlineMs = now + REBIND_EFFECT_WINDOW_MS
|
||||
session.binding.message = '虎牙已受理换绑,正在等待角色生效'
|
||||
return
|
||||
}
|
||||
session.binding.rebindConfirmState = 'rejected'
|
||||
session.binding.rebindConfirmMessage = confirmed?.msg || '虎牙未接受本次换绑'
|
||||
session.binding.message = `虎牙未接受本次换绑:${session.binding.rebindConfirmMessage}`
|
||||
} catch (error) {
|
||||
session.binding.rebindConfirmState = 'rejected'
|
||||
session.binding.rebindConfirmMessage = errorMessage(error)
|
||||
session.binding.message = `提交换绑失败:${session.binding.rebindConfirmMessage}`
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 首次绑定:账号还没有绑定角色时,扫码完成后由项目侧替客户点「绑定」。
|
||||
* 与换绑共用 confirmBindActAccount,只是状态记录在 bindConfirmState,避免和换绑失败混淆。
|
||||
*/
|
||||
private async submitBindLocked(session: NativeSession, rpc: HuyaRpcClient): Promise<void> {
|
||||
const { bindActId, outerActId } = configValues()
|
||||
const now = this.now()
|
||||
session.binding.bindConfirmState = 'submitting'
|
||||
session.binding.bindConfirmMessage = ''
|
||||
session.binding.bindConfirmAt = now
|
||||
try {
|
||||
const confirmed = await rpc.confirmBindActAccount({
|
||||
uid: session.uid,
|
||||
cookie: session.cookie,
|
||||
bindActId,
|
||||
outerActId,
|
||||
})
|
||||
if (confirmed && confirmed.status === 200) {
|
||||
session.binding.bindConfirmState = 'accepted'
|
||||
session.binding.bindEffectDeadlineMs = now + REBIND_EFFECT_WINDOW_MS
|
||||
session.binding.message = '已向虎牙提交绑定,正在等待角色生效'
|
||||
return
|
||||
}
|
||||
session.binding.bindConfirmState = 'rejected'
|
||||
session.binding.bindConfirmMessage = confirmed?.msg || '虎牙未接受本次绑定'
|
||||
session.binding.message = `虎牙未接受本次绑定:${session.binding.bindConfirmMessage}`
|
||||
} catch (error) {
|
||||
session.binding.bindConfirmState = 'rejected'
|
||||
session.binding.bindConfirmMessage = errorMessage(error)
|
||||
session.binding.message = `提交绑定失败:${session.binding.bindConfirmMessage}`
|
||||
}
|
||||
}
|
||||
|
||||
async pollBinding(sessionId: string): Promise<ConnectorBindingSession> {
|
||||
return this.withLock(sessionId, async () => {
|
||||
const session = this.requireAuthenticatedSession(sessionId)
|
||||
@@ -740,14 +1015,20 @@ export class HuyaNativeConnector {
|
||||
timeoutMs: this.rpcTimeoutMs,
|
||||
})
|
||||
if (qrStatus) {
|
||||
if (qrStatus.isExpired || qrStatus.isFailure) {
|
||||
// 平台已受理(绑定/换绑)时二维码会先过期,此时要等角色生效,不能直接判过期。
|
||||
const waitingPlatformEffect =
|
||||
session.binding.rebindConfirmState === 'accepted' ||
|
||||
session.binding.bindConfirmState === 'accepted'
|
||||
if ((qrStatus.isExpired || qrStatus.isFailure) && !waitingPlatformEffect) {
|
||||
session.binding.status = 'expired'
|
||||
session.binding.message = '绑定二维码已过期,请重新获取'
|
||||
return this.bindingView(session)
|
||||
}
|
||||
if (qrStatus.isScan) {
|
||||
session.binding.status = 'scanned'
|
||||
session.binding.message = '已扫码,等待绑定完成'
|
||||
session.binding.message = session.binding.rebindRequested
|
||||
? '已扫码,请在虎牙确认框中选中目标角色'
|
||||
: '已扫码,等待绑定完成'
|
||||
}
|
||||
if (qrStatus.isScan || qrStatus.isCompleted) {
|
||||
session.binding.rebindScanned = true
|
||||
@@ -759,6 +1040,24 @@ export class HuyaNativeConnector {
|
||||
return this.bindingView(session)
|
||||
}
|
||||
const rpc = new HuyaRpcClient({ fetchImpl: this.fetchImpl, timeoutMs: this.rpcTimeoutMs })
|
||||
// 小程序流程结束后立即由项目侧提交换绑,不再等角色自己变化。
|
||||
if (
|
||||
session.binding.rebindRequested &&
|
||||
session.binding.rebindScanned &&
|
||||
qrCompleted &&
|
||||
session.binding.rebindConfirmState === 'idle'
|
||||
) {
|
||||
await this.submitRebindLocked(session, rpc)
|
||||
}
|
||||
// 首次绑定:账号还没有绑定角色时,扫码完成后由项目侧主动提交绑定。
|
||||
if (
|
||||
shouldSubmitFirstBind(session.binding, {
|
||||
qrCompleted,
|
||||
scanned: session.binding.rebindScanned,
|
||||
})
|
||||
) {
|
||||
await this.submitBindLocked(session, rpc)
|
||||
}
|
||||
const response = await rpc.checkUserBindGameAccount({
|
||||
uid: session.uid,
|
||||
cookie: session.cookie,
|
||||
@@ -773,91 +1072,199 @@ export class HuyaNativeConnector {
|
||||
const role = parseRole(response)
|
||||
const hasExistingBinding = hasExistingHuyaBinding(response)
|
||||
session.binding.hasExistingBinding = hasExistingBinding
|
||||
if (role.role) {
|
||||
applyRebindMeta(session, response, this.now())
|
||||
if (role.role && hasExistingBinding) {
|
||||
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 (session.binding.rebindConfirmState === 'rejected') {
|
||||
// 虎牙明确拒绝:保留 rebind 状态并展示虎牙原文,不能清空 rebindRequested。
|
||||
session.binding.rebindUnchanged = true
|
||||
this.markRoleReady(session, role, hasExistingBinding)
|
||||
session.binding.message = '扫码后仍识别到原绑定角色,请确认使用或重新换绑'
|
||||
} else {
|
||||
session.binding.status = 'scanned'
|
||||
session.binding.message = '已扫码,正在等待换绑角色生效'
|
||||
session.binding.message = rebindFailureMessage(
|
||||
role.role,
|
||||
session.binding.rebindConfirmMessage,
|
||||
session.binding.nextRebindAt,
|
||||
)
|
||||
return this.bindingView(session)
|
||||
}
|
||||
if (session.binding.rebindConfirmState === 'accepted') {
|
||||
if (this.now() < session.binding.rebindEffectDeadlineMs) {
|
||||
session.binding.status = 'scanned'
|
||||
session.binding.message = '虎牙已受理换绑,正在等待角色生效'
|
||||
} else {
|
||||
session.binding.rebindUnchanged = true
|
||||
this.markRoleReady(session, role, hasExistingBinding)
|
||||
session.binding.message = rebindFailureMessage(
|
||||
role.role,
|
||||
session.binding.rebindConfirmMessage,
|
||||
session.binding.nextRebindAt,
|
||||
)
|
||||
}
|
||||
return this.bindingView(session)
|
||||
}
|
||||
session.binding.status = 'scanned'
|
||||
session.binding.message = qrCompleted
|
||||
? '扫码已完成,请点击「已选好角色,提交换绑」'
|
||||
: '已扫码,请在虎牙确认框中选中目标角色'
|
||||
return this.bindingView(session)
|
||||
}
|
||||
if (rebindRequested) session.binding.rebindUnchanged = false
|
||||
this.markRoleReady(session, role, hasExistingBinding && !rebindRequested)
|
||||
if (rebindRequested) {
|
||||
session.binding.message = '已识别换绑角色,请确认换绑'
|
||||
}
|
||||
} else if (hasExistingBinding) {
|
||||
// 平台标记已绑定,但没有返回角色信息(或角色ID不可核对):必须人工核实,不能生成二维码。
|
||||
this.markRoleReady(session, role, true)
|
||||
session.binding.message = '当前账号已有绑定角色,但平台未返回角色信息,请联系客服人工核实'
|
||||
} else if (
|
||||
!session.binding.rebindRequested &&
|
||||
session.binding.bindConfirmState === 'rejected'
|
||||
) {
|
||||
session.binding.status = 'failed'
|
||||
session.binding.message = `虎牙未接受本次绑定:${session.binding.bindConfirmMessage}`
|
||||
} else if (
|
||||
!session.binding.rebindRequested &&
|
||||
session.binding.bindConfirmState === 'accepted'
|
||||
) {
|
||||
if (this.now() < session.binding.bindEffectDeadlineMs) {
|
||||
session.binding.status = 'scanned'
|
||||
session.binding.message = '已向虎牙提交绑定,正在等待角色生效'
|
||||
} else {
|
||||
session.binding.status = 'failed'
|
||||
session.binding.message = '虎牙已受理绑定,但未返回角色,请重新扫码绑定'
|
||||
}
|
||||
} else if (!['scanned', 'expired', 'failed'].includes(session.binding.status)) {
|
||||
session.binding.status = 'qr_pending'
|
||||
session.binding.message = '等待扫码绑定游戏角色'
|
||||
session.binding.message = '该虎牙账号还没有绑定游戏角色,请扫码完成绑定'
|
||||
}
|
||||
return this.bindingView(session)
|
||||
})
|
||||
}
|
||||
|
||||
async confirmBinding(sessionId: string): Promise<ConnectorBindingSession> {
|
||||
/** 只读绑定状态快照:不访问虎牙,供「确认绑定」这类纯本地动作使用。 */
|
||||
async bindingSnapshot(sessionId: string): Promise<ConnectorBindingSession> {
|
||||
return this.withLock(sessionId, async () =>
|
||||
this.bindingView(this.requireAuthenticatedSession(sessionId)),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 客户点「确认绑定」:只做本地状态流转,不调用虎牙接口。
|
||||
* 虎牙侧的绑定已由扫码(小程序/弹窗)完成,确认绑定只是核对三项后落库;
|
||||
* 需要调用虎牙接口的地方只有「换绑确认」(submitRebind / pollBinding 自动提交)。
|
||||
*/
|
||||
async confirmBinding(
|
||||
sessionId: string,
|
||||
options: { acceptExistingRole?: boolean } = {},
|
||||
): Promise<ConnectorBindingSession> {
|
||||
return this.withLock(sessionId, async () => {
|
||||
const session = this.requireAuthenticatedSession(sessionId)
|
||||
const binding = session.binding
|
||||
const decision = resolveBindingConfirmDecision(binding, options)
|
||||
if (decision === 'not_ready') {
|
||||
throw createHttpError('尚未识别到可确认的绑定角色', {
|
||||
statusCode: 409,
|
||||
errorCode: 'huya_bind_role_not_ready',
|
||||
})
|
||||
}
|
||||
const rebindRequested = binding.rebindRequested
|
||||
const acceptExistingRole = options.acceptExistingRole === true
|
||||
if (decision === 'needs_rebind_decision') {
|
||||
const reason = readString(binding.rebindConfirmMessage)
|
||||
throw createHttpError(
|
||||
`${
|
||||
reason
|
||||
? `换绑未成功:${reason}。`
|
||||
: `换绑未成功:平台仍返回原绑定角色「${binding.role}」。`
|
||||
}请重新扫码换绑,或确认继续使用原绑定角色`,
|
||||
{ statusCode: 409, errorCode: 'huya_bind_rebind_decision_required' },
|
||||
)
|
||||
}
|
||||
const role = {
|
||||
account: binding.account,
|
||||
role: binding.role,
|
||||
roleId: binding.roleId,
|
||||
channel: binding.channel,
|
||||
}
|
||||
const useExistingBinding =
|
||||
binding.hasExistingBinding === true && (!rebindRequested || acceptExistingRole)
|
||||
this.markRoleReady(session, role, useExistingBinding)
|
||||
binding.status = 'confirmed'
|
||||
binding.hasExistingBinding = true
|
||||
binding.rebindRequested = false
|
||||
binding.rebindScanned = false
|
||||
binding.rebindUnchanged = false
|
||||
binding.rebindConfirmState = 'idle'
|
||||
binding.rebindConfirmMessage = ''
|
||||
binding.rebindConfirmAt = 0
|
||||
binding.rebindEffectDeadlineMs = 0
|
||||
binding.bindConfirmState = 'idle'
|
||||
binding.bindConfirmMessage = ''
|
||||
binding.bindConfirmAt = 0
|
||||
binding.bindEffectDeadlineMs = 0
|
||||
binding.rebindCooldownDays = 0
|
||||
binding.nextRebindAt = ''
|
||||
binding.baselineRoleKey = ''
|
||||
binding.message =
|
||||
rebindRequested && acceptExistingRole
|
||||
? '本次换绑未生效,已按原绑定角色确认'
|
||||
: useExistingBinding
|
||||
? '当前虎牙账号已有绑定角色,已确认直接使用'
|
||||
: rebindRequested
|
||||
? '虎牙角色换绑已确认'
|
||||
: '虎牙角色绑定已确认'
|
||||
return this.bindingView(session)
|
||||
})
|
||||
}
|
||||
|
||||
/** 客户手动点击「已选好角色,提交换绑」时调用。 */
|
||||
async submitRebind(sessionId: string): Promise<ConnectorBindingSession> {
|
||||
return this.withLock(sessionId, async () => {
|
||||
const session = this.requireAuthenticatedSession(sessionId)
|
||||
if (!session.binding.rebindRequested) {
|
||||
throw createHttpError('当前没有待换绑的角色,请重新扫码换绑', {
|
||||
statusCode: 409,
|
||||
errorCode: 'huya_bind_rebind_not_requested',
|
||||
})
|
||||
}
|
||||
const { bindActId, outerActId } = configValues()
|
||||
const rpc = new HuyaRpcClient({ fetchImpl: this.fetchImpl, timeoutMs: this.rpcTimeoutMs })
|
||||
await this.submitRebindLocked(session, rpc)
|
||||
const response = await rpc.checkUserBindGameAccount({
|
||||
uid: session.uid,
|
||||
cookie: session.cookie,
|
||||
bindActId,
|
||||
outerActId,
|
||||
})
|
||||
const role = parseRole(response)
|
||||
if (!response || response.status !== 200 || !role.role) {
|
||||
throw createHttpError('尚未识别到可确认的绑定角色', {
|
||||
statusCode: 409,
|
||||
errorCode: 'huya_bind_role_not_ready',
|
||||
})
|
||||
}
|
||||
const rebindRequested = session.binding.rebindRequested
|
||||
if (
|
||||
rebindRequested &&
|
||||
session.binding.baselineRoleKey &&
|
||||
bindingRoleKey(role) === session.binding.baselineRoleKey
|
||||
) {
|
||||
throw createHttpError('换绑角色尚未生效,请稍后重试', {
|
||||
statusCode: 409,
|
||||
errorCode: 'huya_bind_rebind_not_ready',
|
||||
})
|
||||
}
|
||||
const useExistingBinding = hasExistingHuyaBinding(response) && !rebindRequested
|
||||
if (!useExistingBinding) {
|
||||
const confirmed = await rpc.confirmBindActAccount({
|
||||
uid: session.uid,
|
||||
cookie: session.cookie,
|
||||
bindActId,
|
||||
outerActId,
|
||||
})
|
||||
if (!confirmed || confirmed.status !== 200) {
|
||||
throw createHttpError(confirmed?.msg || '确认虎牙绑定失败', {
|
||||
statusCode: 409,
|
||||
errorCode: 'huya_bind_confirm_failed',
|
||||
})
|
||||
if (response && response.status === 200) {
|
||||
const role = parseRole(response)
|
||||
applyRebindMeta(session, response, this.now())
|
||||
if (role.role) {
|
||||
const changedRole =
|
||||
!session.binding.baselineRoleKey ||
|
||||
bindingRoleKey(role) !== session.binding.baselineRoleKey
|
||||
if (changedRole) {
|
||||
session.binding.rebindUnchanged = false
|
||||
this.markRoleReady(session, role, false)
|
||||
session.binding.message = '已识别换绑角色,请确认换绑'
|
||||
} else if (session.binding.rebindConfirmState === 'rejected') {
|
||||
session.binding.rebindUnchanged = true
|
||||
this.markRoleReady(session, role, hasExistingHuyaBinding(response))
|
||||
session.binding.message = rebindFailureMessage(
|
||||
role.role,
|
||||
session.binding.rebindConfirmMessage,
|
||||
session.binding.nextRebindAt,
|
||||
)
|
||||
} else {
|
||||
session.binding.status = 'scanned'
|
||||
session.binding.message = '虎牙已受理换绑,正在等待角色生效'
|
||||
}
|
||||
}
|
||||
}
|
||||
this.markRoleReady(session, role, useExistingBinding)
|
||||
session.binding.status = 'confirmed'
|
||||
session.binding.hasExistingBinding = true
|
||||
session.binding.rebindRequested = false
|
||||
session.binding.rebindScanned = false
|
||||
session.binding.baselineRoleKey = ''
|
||||
session.binding.message = useExistingBinding
|
||||
? '当前虎牙账号已有绑定角色,已确认直接使用'
|
||||
: rebindRequested
|
||||
? '虎牙角色换绑已确认'
|
||||
: '虎牙角色绑定已确认'
|
||||
return this.bindingView(session)
|
||||
})
|
||||
}
|
||||
@@ -1042,13 +1449,21 @@ export class HuyaNativeConnector {
|
||||
|
||||
private markRoleReady(
|
||||
session: NativeSession,
|
||||
role: { account: string; role: string; channel: string },
|
||||
role: { account: string; role: string; roleId?: string; channel: string },
|
||||
existingBinding = false,
|
||||
): void {
|
||||
session.binding.status = 'role_ready'
|
||||
session.binding.account = role.account
|
||||
session.binding.role = role.role
|
||||
session.binding.roleId = role.roleId || ''
|
||||
session.binding.channel = role.channel
|
||||
const roleInfo = describeBindingRole(role.role, role.roleId, session.uid)
|
||||
if (roleInfo.requiresSupport) {
|
||||
session.binding.message = existingBinding
|
||||
? '当前账号已有绑定角色,但未获取到可核对的角色ID,请联系客服人工核实'
|
||||
: '已识别绑定角色,但未获取到可核对的角色ID,请联系客服人工核实'
|
||||
return
|
||||
}
|
||||
session.binding.message = existingBinding
|
||||
? '当前账号已有绑定角色,请确认直接使用'
|
||||
: '绑定角色已识别,请确认绑定'
|
||||
@@ -1126,16 +1541,32 @@ export class HuyaNativeConnector {
|
||||
|
||||
private bindingView(session: NativeSession): ConnectorBindingSession {
|
||||
const binding = session.binding
|
||||
const roleInfo = describeBindingRole(binding.role, binding.roleId, session.uid)
|
||||
const requiresSupport =
|
||||
roleInfo.requiresSupport || (binding.hasExistingBinding === true && !roleInfo.roleIdVerified)
|
||||
return {
|
||||
sessionId: session.sessionId,
|
||||
status: binding.status,
|
||||
qrImage: binding.qrImage,
|
||||
qrExpiresAt: binding.expiresAtMs ? iso(binding.expiresAtMs) : '',
|
||||
qrUrl: binding.qrUrl,
|
||||
bindGameAccount: binding.account,
|
||||
bindGameRole: binding.role,
|
||||
bindGameRoleId: roleInfo.resolvedRoleId,
|
||||
bindGameChannel: binding.channel,
|
||||
roleIdVerified: roleInfo.roleIdVerified,
|
||||
requiresSupport,
|
||||
hasExistingBinding: binding.hasExistingBinding,
|
||||
rebindRequested: binding.rebindRequested,
|
||||
rebindUnchanged: binding.rebindUnchanged,
|
||||
rebindConfirmState: binding.rebindConfirmState,
|
||||
rebindConfirmMessage: binding.rebindConfirmMessage,
|
||||
bindConfirmState: binding.bindConfirmState,
|
||||
bindConfirmMessage: binding.bindConfirmMessage,
|
||||
rebindCooldownDays: binding.rebindCooldownDays,
|
||||
nextRebindAt: binding.nextRebindAt,
|
||||
platformChangeBindDay: binding.changeBindDay,
|
||||
platformChangeBindTime: binding.changeBindTime,
|
||||
message: binding.message,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import crypto from 'node:crypto'
|
||||
|
||||
import { recordSemiAutoTrace, traceFingerprint } from '../semi-auto-trace.js'
|
||||
import { buildHuyaLoginContext, cookiePairs, cookieValue, normalizeCookiePairs } from './cookie.js'
|
||||
import {
|
||||
decodeWupResponse,
|
||||
@@ -401,6 +402,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 +434,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 }
|
||||
@@ -463,22 +495,67 @@ export class HuyaRpcClient {
|
||||
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
|
||||
const startedAt = Date.now()
|
||||
const request = {
|
||||
servant: 'webActUI',
|
||||
func: 'checkUserBindGameAccount',
|
||||
uid: input.uid,
|
||||
gid: input.gid || 0,
|
||||
outerActId: input.outerActId || '',
|
||||
bindActId: input.bindActId || 0,
|
||||
isUseOuterActId: input.isUseOuterActId ?? 1,
|
||||
scene: input.scene || '',
|
||||
}
|
||||
try {
|
||||
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)
|
||||
},
|
||||
)
|
||||
const parsed = response ? readWupStruct(response, parseBindResponse) : null
|
||||
recordSemiAutoTrace({
|
||||
direction: 'outbound',
|
||||
channel: 'huya_wup',
|
||||
action: 'webActUI.checkUserBindGameAccount',
|
||||
status: parsed && parsed.status === 200 ? 'ok' : 'error',
|
||||
durationMs: Date.now() - startedAt,
|
||||
requestSummary: request,
|
||||
responseSummary: { status: parsed?.status, msg: parsed?.msg },
|
||||
responseBody: parsed,
|
||||
// 绑定轮询:状态没变化就不落库。
|
||||
fingerprint: traceFingerprint({
|
||||
status: parsed?.status,
|
||||
msg: parsed?.msg,
|
||||
isBindAccount: parsed?.accountData?.isBindAccount,
|
||||
isBindRole: parsed?.accountData?.isBindRole,
|
||||
role: parsed?.accountData?.gameRole?.roleName,
|
||||
roleId: parsed?.accountData?.gameRole?.roleId,
|
||||
}),
|
||||
errorMessage: parsed && parsed.status !== 200 ? String(parsed.msg || '') : '',
|
||||
})
|
||||
return parsed
|
||||
} catch (error) {
|
||||
recordSemiAutoTrace({
|
||||
direction: 'outbound',
|
||||
channel: 'huya_wup',
|
||||
action: 'webActUI.checkUserBindGameAccount',
|
||||
status: 'error',
|
||||
durationMs: Date.now() - startedAt,
|
||||
requestSummary: request,
|
||||
errorMessage: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async confirmBindActAccount(input: {
|
||||
@@ -488,19 +565,55 @@ export class HuyaRpcClient {
|
||||
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
|
||||
const startedAt = Date.now()
|
||||
const request = {
|
||||
servant: 'webActUI',
|
||||
func: 'confirmBindActAccount',
|
||||
uid: input.uid,
|
||||
gid: input.gid || 0,
|
||||
outerActId: input.outerActId || '',
|
||||
bindActId: input.bindActId || 0,
|
||||
}
|
||||
try {
|
||||
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)
|
||||
},
|
||||
)
|
||||
const parsed = response ? readWupStruct(response, parseConfirmResponse) : null
|
||||
recordSemiAutoTrace({
|
||||
direction: 'outbound',
|
||||
channel: 'huya_wup',
|
||||
action: 'webActUI.confirmBindActAccount',
|
||||
status: parsed && parsed.status === 200 ? 'ok' : 'error',
|
||||
durationMs: Date.now() - startedAt,
|
||||
requestSummary: request,
|
||||
responseSummary: { status: parsed?.status, msg: parsed?.msg },
|
||||
responseBody: parsed,
|
||||
always: true,
|
||||
errorMessage: parsed && parsed.status !== 200 ? String(parsed.msg || '') : '',
|
||||
})
|
||||
return parsed
|
||||
} catch (error) {
|
||||
recordSemiAutoTrace({
|
||||
direction: 'outbound',
|
||||
channel: 'huya_wup',
|
||||
action: 'webActUI.confirmBindActAccount',
|
||||
status: 'error',
|
||||
durationMs: Date.now() - startedAt,
|
||||
requestSummary: request,
|
||||
always: true,
|
||||
errorMessage: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async getLiveLinkParam(input: {
|
||||
@@ -510,21 +623,57 @@ export class HuyaRpcClient {
|
||||
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
|
||||
const startedAt = Date.now()
|
||||
const request = {
|
||||
servant: 'webActUI',
|
||||
func: 'getLiveLinkParam',
|
||||
uid: input.uid,
|
||||
bindActId: input.bindActId || 0,
|
||||
outerActId: input.outerActId || 0,
|
||||
gameAuthScene: input.gameAuthScene || '',
|
||||
}
|
||||
try {
|
||||
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)
|
||||
},
|
||||
)
|
||||
const parsed = response ? readWupStruct(response, parseLiveLinkResponse) : null
|
||||
recordSemiAutoTrace({
|
||||
direction: 'outbound',
|
||||
channel: 'huya_wup',
|
||||
action: 'webActUI.getLiveLinkParam',
|
||||
status: parsed && parsed.status === 200 ? 'ok' : 'error',
|
||||
durationMs: Date.now() - startedAt,
|
||||
requestSummary: request,
|
||||
responseSummary: { status: parsed?.status, msg: parsed?.msg },
|
||||
responseBody: parsed,
|
||||
always: true,
|
||||
errorMessage: parsed && parsed.status !== 200 ? String(parsed.msg || '') : '',
|
||||
})
|
||||
return parsed
|
||||
} catch (error) {
|
||||
recordSemiAutoTrace({
|
||||
direction: 'outbound',
|
||||
channel: 'huya_wup',
|
||||
action: 'webActUI.getLiveLinkParam',
|
||||
status: 'error',
|
||||
durationMs: Date.now() - startedAt,
|
||||
requestSummary: request,
|
||||
always: true,
|
||||
errorMessage: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async getUserProfileBatch(input: {
|
||||
@@ -554,17 +703,53 @@ export class HuyaRpcClient {
|
||||
}): 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
|
||||
const startedAt = Date.now()
|
||||
try {
|
||||
const response = await this.callRpc(
|
||||
'huyauserui',
|
||||
'getUserProfile',
|
||||
input.uid,
|
||||
input.cookie,
|
||||
(writer) => {
|
||||
this.writeActivityUser(writer, 0, input.cookie)
|
||||
writer.writeInt64(1, targetUid)
|
||||
},
|
||||
)
|
||||
const parsed = response ? readWupStruct(response, parseProfileResponse) : null
|
||||
recordSemiAutoTrace({
|
||||
direction: 'outbound',
|
||||
channel: 'huya_wup',
|
||||
action: 'huyauserui.getUserProfile',
|
||||
status: parsed ? 'ok' : 'error',
|
||||
durationMs: Date.now() - startedAt,
|
||||
requestSummary: {
|
||||
servant: 'huyauserui',
|
||||
func: 'getUserProfile',
|
||||
uid: input.uid,
|
||||
targetUid,
|
||||
},
|
||||
responseBody: parsed,
|
||||
always: true,
|
||||
})
|
||||
return parsed
|
||||
} catch (error) {
|
||||
recordSemiAutoTrace({
|
||||
direction: 'outbound',
|
||||
channel: 'huya_wup',
|
||||
action: 'huyauserui.getUserProfile',
|
||||
status: 'error',
|
||||
durationMs: Date.now() - startedAt,
|
||||
requestSummary: {
|
||||
servant: 'huyauserui',
|
||||
func: 'getUserProfile',
|
||||
uid: input.uid,
|
||||
targetUid,
|
||||
},
|
||||
always: true,
|
||||
errorMessage: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private async callRpc(
|
||||
@@ -684,6 +869,7 @@ export async function getLiveLinkMiniQrcode(
|
||||
).join('')
|
||||
const sessionId = `${Math.floor(Date.now() / 1000)}_${suffix}`
|
||||
const fetchImpl = options.fetchImpl || fetch
|
||||
const startedAt = Date.now()
|
||||
const response = await fetchImpl(`${LIVELINK_BIND_API_BASE}/api/qrcode/getMiniAppQrcode`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
@@ -697,14 +883,41 @@ export async function getLiveLinkMiniQrcode(
|
||||
body: JSON.stringify({ queryString: `${query}&sessionId=${sessionId}` }),
|
||||
signal: AbortSignal.timeout(options.timeoutMs || 15_000),
|
||||
})
|
||||
if (!response.ok) return null
|
||||
const traceMiniQrcode = (status: 'ok' | 'error', extra: Record<string, unknown> = {}) => {
|
||||
recordSemiAutoTrace({
|
||||
direction: 'outbound',
|
||||
channel: 'huya_http',
|
||||
action: 'livelink.getMiniAppQrcode',
|
||||
status,
|
||||
durationMs: Date.now() - startedAt,
|
||||
httpStatus: response.status,
|
||||
requestSummary: { api: 'getMiniAppQrcode', queryLength: query.length },
|
||||
responseSummary: extra,
|
||||
always: true,
|
||||
})
|
||||
}
|
||||
if (!response.ok) {
|
||||
traceMiniQrcode('error', { httpStatus: response.status })
|
||||
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
|
||||
if (!payload || payload.iRet !== 0) {
|
||||
traceMiniQrcode('error', { iRet: payload?.iRet ?? null })
|
||||
return null
|
||||
}
|
||||
const image = livelinkQrcodeImageSrc(String(payload.jData?.qrcode || ''))
|
||||
if (!image) return null
|
||||
if (!image) {
|
||||
traceMiniQrcode('error', { iRet: payload.iRet, hasImage: false })
|
||||
return null
|
||||
}
|
||||
traceMiniQrcode('ok', {
|
||||
iRet: payload.iRet,
|
||||
hasImage: true,
|
||||
tokenLength: String(payload.jData?.qrcodeToken || '').length,
|
||||
})
|
||||
return { image, token: String(payload.jData?.qrcodeToken || '') }
|
||||
}
|
||||
|
||||
@@ -720,6 +933,7 @@ export async function getLiveLinkQrcodeStatus(
|
||||
const normalized = String(token || '').trim()
|
||||
if (!normalized) return null
|
||||
const fetchImpl = options.fetchImpl || fetch
|
||||
const startedAt = Date.now()
|
||||
const response = await fetchImpl(`${LIVELINK_BIND_API_BASE}/api/qrcode/poolingQrcodeStatus`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
@@ -733,7 +947,24 @@ export async function getLiveLinkQrcodeStatus(
|
||||
body: JSON.stringify({ qrcodeToken: normalized }),
|
||||
signal: AbortSignal.timeout(options.timeoutMs || 15_000),
|
||||
})
|
||||
if (!response.ok) return null
|
||||
const traceQrcodeStatus = (status: 'ok' | 'error', extra: Record<string, unknown> = {}) => {
|
||||
recordSemiAutoTrace({
|
||||
direction: 'outbound',
|
||||
channel: 'huya_http',
|
||||
action: 'livelink.poolingQrcodeStatus',
|
||||
status,
|
||||
durationMs: Date.now() - startedAt,
|
||||
httpStatus: response.status,
|
||||
requestSummary: { api: 'poolingQrcodeStatus', tokenLength: normalized.length },
|
||||
responseSummary: extra,
|
||||
// 二维码轮询:状态没变化就不落库。
|
||||
fingerprint: traceFingerprint(extra),
|
||||
})
|
||||
}
|
||||
if (!response.ok) {
|
||||
traceQrcodeStatus('error', { httpStatus: response.status })
|
||||
return null
|
||||
}
|
||||
const payload = (await response.json().catch(() => null)) as {
|
||||
iRet?: number
|
||||
jData?: {
|
||||
@@ -743,13 +974,18 @@ export async function getLiveLinkQrcodeStatus(
|
||||
isFailure?: boolean
|
||||
}
|
||||
} | null
|
||||
if (!payload || payload.iRet !== 0) return null
|
||||
return {
|
||||
if (!payload || payload.iRet !== 0) {
|
||||
traceQrcodeStatus('error', { iRet: payload?.iRet ?? null })
|
||||
return null
|
||||
}
|
||||
const result = {
|
||||
isScan: Boolean(payload.jData?.isScan),
|
||||
isExpired: Boolean(payload.jData?.isExpired),
|
||||
isCompleted: Boolean(payload.jData?.isCompleted),
|
||||
isFailure: Boolean(payload.jData?.isFailure),
|
||||
}
|
||||
traceQrcodeStatus('ok', { iRet: payload.iRet, ...result })
|
||||
return result
|
||||
}
|
||||
|
||||
export function buildBindUrls(input: {
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
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('换绑冷却:按虎牙日界推算(11-16 绑定 → 11-23 才能换绑)', () => {
|
||||
// 实测 task 34:changeBindTime = 1794844800 = 2026-11-17 00:00 +08:00,changeBindDay = 7。
|
||||
const now = Date.UTC(2026, 10, 16, 6, 31) // 2026-11-16 14:31 +08:00
|
||||
const result = resolveRebindCooldown(
|
||||
{ status: 200, changeBindDay: 7, accountData: { changeBindTime: 1794844800 } },
|
||||
now,
|
||||
)
|
||||
assert.equal(result.days, 7)
|
||||
// 2026-11-23 00:00 +08:00,与虎牙绑定页「预计下次换绑时间 2026/11/23」一致。
|
||||
assert.equal(result.nextRebindAt, '2026-11-22T16:00:00.000Z')
|
||||
})
|
||||
|
||||
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: '' })
|
||||
})
|
||||
@@ -0,0 +1,258 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { describe, it } from 'node:test'
|
||||
|
||||
import {
|
||||
describeBindingRole,
|
||||
isNumericBindingRoleId,
|
||||
resolveBindingRoleId,
|
||||
} from './binding-role-id.js'
|
||||
import {
|
||||
compareBindingRole,
|
||||
detectServerZone,
|
||||
normalizeCustomerProfile,
|
||||
} from './semi-auto-task-service.js'
|
||||
|
||||
const task = (id: string, name: string, huyaUid = '', zone = '') => ({
|
||||
customer_game_id: id,
|
||||
customer_game_role: name,
|
||||
customer_game_server_zone: zone,
|
||||
huya_uid: huyaUid,
|
||||
})
|
||||
|
||||
describe('待确认角色 UID 取数(huyaUid)', () => {
|
||||
it('角色 ID 本身是纯数字时直接使用', () => {
|
||||
assert.equal(resolveBindingRoleId('1192083858', 1199608910400), '1192083858')
|
||||
})
|
||||
|
||||
it('角色 ID 是加密串时改用数值 UID', () => {
|
||||
assert.equal(
|
||||
resolveBindingRoleId('834ee3e75a1bfc9f65fb6b966bac7ef318e68ea', '1199608910400'),
|
||||
'1199608910400',
|
||||
)
|
||||
})
|
||||
|
||||
it('缺少角色 ID 时回退到数值 UID', () => {
|
||||
assert.equal(resolveBindingRoleId('', 1199608910400), '1199608910400')
|
||||
})
|
||||
|
||||
it('没有可用数值 UID 时保留原始角色 ID', () => {
|
||||
assert.equal(
|
||||
resolveBindingRoleId('834ee3e75a1bfc9f65fb6b966bac7ef318e68ea', ''),
|
||||
'834ee3e75a1bfc9f65fb6b966bac7ef318e68ea',
|
||||
)
|
||||
assert.equal(resolveBindingRoleId(null, undefined), '')
|
||||
})
|
||||
|
||||
it('虎牙加密串角色 ID 改用 huyaUid 参与比对', () => {
|
||||
const result = compareBindingRole(task('1199608910400', '大鲨鱼伊塞53', '1199608910400'), {
|
||||
bindGameRole: '大鲨鱼伊塞53',
|
||||
bindGameRoleId: '834ee3e75a1bfc9f65fb6b966bac7ef318e68ea',
|
||||
})
|
||||
assert.equal(result.verdict, 'match')
|
||||
assert.equal(result.boundRoleId, '1199608910400')
|
||||
})
|
||||
|
||||
it('没有 huyaUid 时保留原始加密串,仍判不一致', () => {
|
||||
const result = compareBindingRole(task('1199608910400', '大鲨鱼伊塞53'), {
|
||||
bindGameRole: '大鲨鱼伊塞53',
|
||||
bindGameRoleId: '834ee3e75a1bfc9f65fb6b966bac7ef318e68ea',
|
||||
})
|
||||
assert.equal(result.verdict, 'mismatch')
|
||||
assert.equal(result.boundRoleId, '834ee3e75a1bfc9f65fb6b966bac7ef318e68ea')
|
||||
})
|
||||
})
|
||||
|
||||
describe('绑定角色可核对性(缺角色ID)', () => {
|
||||
it('数字角色 ID 可直接核对', () => {
|
||||
const info = describeBindingRole('大鲨鱼伊塞53', '1192083858', '')
|
||||
assert.equal(info.roleIdVerified, true)
|
||||
assert.equal(info.requiresSupport, false)
|
||||
})
|
||||
|
||||
it('加密角色 ID 但 UID 是数字时可核对', () => {
|
||||
const info = describeBindingRole(
|
||||
'大鲨鱼伊塞53',
|
||||
'834ee3e75a1bfc9f65fb6b966bac7ef318e68ea',
|
||||
'1199608910400',
|
||||
)
|
||||
assert.equal(info.resolvedRoleId, '1199608910400')
|
||||
assert.equal(info.roleIdVerified, true)
|
||||
assert.equal(info.requiresSupport, false)
|
||||
})
|
||||
|
||||
it('有角色但没有可核对数字 ID 时需要联系客服', () => {
|
||||
const info = describeBindingRole('Mock测试角色', 'mock-role-abc', 'mock-huya-abc')
|
||||
assert.equal(info.roleIdVerified, false)
|
||||
assert.equal(info.requiresSupport, true)
|
||||
})
|
||||
|
||||
it('没有角色名时不需要人工核实', () => {
|
||||
const info = describeBindingRole('', '', '')
|
||||
assert.equal(info.hasBoundRole, false)
|
||||
assert.equal(info.requiresSupport, false)
|
||||
})
|
||||
|
||||
it('只接受纯数字角色 ID 参与核对', () => {
|
||||
assert.equal(isNumericBindingRoleId('1192083858'), true)
|
||||
assert.equal(isNumericBindingRoleId(' 1192083858 '), true)
|
||||
assert.equal(isNumericBindingRoleId('mock-role-abc'), false)
|
||||
assert.equal(isNumericBindingRoleId(''), false)
|
||||
assert.equal(isNumericBindingRoleId(null), false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('区服解析', () => {
|
||||
it('安卓 + 微信识别为安卓V区', () => {
|
||||
assert.equal(detectServerZone('安卓(android) · 微信'), '安卓V区')
|
||||
assert.equal(detectServerZone('微信用户 · 安卓(android) · 微信'), '安卓V区')
|
||||
})
|
||||
|
||||
it('苹果 + QQ识别为苹果Q区', () => {
|
||||
assert.equal(detectServerZone('苹果(iOS) · QQ'), '苹果Q区')
|
||||
})
|
||||
|
||||
it('无法识别时返回空串', () => {
|
||||
assert.equal(detectServerZone(''), '')
|
||||
assert.equal(detectServerZone('微信用户'), '')
|
||||
})
|
||||
})
|
||||
|
||||
describe('客户填写角色与平台识别角色比对', () => {
|
||||
it('区服、角色名称、角色 ID 都一致时允许确认', () => {
|
||||
const result = compareBindingRole(
|
||||
task('1199608910400', '大鲨鱼伊塞53', '1199608910400', '安卓V区'),
|
||||
{
|
||||
bindGameRole: '大鲨鱼伊塞53',
|
||||
bindGameRoleId: '1199608910400',
|
||||
bindGameChannel: '安卓(android) · 微信',
|
||||
},
|
||||
)
|
||||
assert.equal(result.verdict, 'match')
|
||||
assert.equal(result.customerZone, '安卓V区')
|
||||
assert.equal(result.boundZone, '安卓V区')
|
||||
assert.match(result.message, /区服/)
|
||||
})
|
||||
|
||||
it('角色 ID 一致但角色名称不一致时禁止确认', () => {
|
||||
const result = compareBindingRole(task('1199608910400', '123', '1199608910400', '安卓V区'), {
|
||||
bindGameRole: '大鲨鱼伊塞53',
|
||||
bindGameRoleId: '1199608910400',
|
||||
bindGameChannel: '安卓(android) · 微信',
|
||||
})
|
||||
assert.equal(result.verdict, 'mismatch')
|
||||
assert.match(result.message, /名称/)
|
||||
})
|
||||
|
||||
it('角色名称与 ID 一致但区服不一致时禁止确认', () => {
|
||||
const result = compareBindingRole(
|
||||
task('1199608910400', '大鲨鱼伊塞53', '1199608910400', '苹果Q区'),
|
||||
{
|
||||
bindGameRole: '大鲨鱼伊塞53',
|
||||
bindGameRoleId: '1199608910400',
|
||||
bindGameChannel: '安卓(android) · 微信',
|
||||
},
|
||||
)
|
||||
assert.equal(result.verdict, 'mismatch')
|
||||
assert.match(result.message, /区服/)
|
||||
assert.equal(result.boundZone, '安卓V区')
|
||||
})
|
||||
|
||||
it('渠道解析不出区服时跳过区服比对', () => {
|
||||
const result = compareBindingRole(
|
||||
task('1199608910400', '大鲨鱼伊塞53', '1199608910400', '苹果Q区'),
|
||||
{
|
||||
bindGameRole: '大鲨鱼伊塞53',
|
||||
bindGameRoleId: '1199608910400',
|
||||
bindGameChannel: '微信用户',
|
||||
},
|
||||
)
|
||||
assert.equal(result.verdict, 'match')
|
||||
assert.equal(result.boundZone, '')
|
||||
})
|
||||
|
||||
it('两侧角色 ID 一致时允许确认', () => {
|
||||
const result = compareBindingRole(task('1192083858', '巫师基尔斯84'), {
|
||||
bindGameRole: '巫师基尔斯84',
|
||||
bindGameRoleId: '1192083858',
|
||||
})
|
||||
assert.equal(result.verdict, 'match')
|
||||
assert.equal(result.customerRoleId, '1192083858')
|
||||
assert.equal(result.boundRoleId, '1192083858')
|
||||
})
|
||||
|
||||
it('两侧角色 ID 不一致时禁止确认', () => {
|
||||
const result = compareBindingRole(task('1192083858', '巫师基尔斯84'), {
|
||||
bindGameRole: '我是火星人2222',
|
||||
bindGameRoleId: '166909256',
|
||||
})
|
||||
assert.equal(result.verdict, 'mismatch')
|
||||
assert.match(result.message, /不一致/)
|
||||
})
|
||||
|
||||
it('缺少角色 ID 时退回角色名称比对', () => {
|
||||
const matched = compareBindingRole(task('', '巫师基尔斯84'), {
|
||||
bindGameRole: '巫师基尔斯84',
|
||||
bindGameRoleId: '',
|
||||
})
|
||||
assert.equal(matched.verdict, 'match')
|
||||
|
||||
const mismatched = compareBindingRole(task('', '巫师基尔斯84'), {
|
||||
bindGameRole: '我是火星人2222',
|
||||
bindGameRoleId: '',
|
||||
})
|
||||
assert.equal(mismatched.verdict, 'mismatch')
|
||||
})
|
||||
|
||||
it('两侧都没有可核对信息时标记为 unknown', () => {
|
||||
const result = compareBindingRole(task('', ''), { bindGameRole: '', bindGameRoleId: '' })
|
||||
assert.equal(result.verdict, 'unknown')
|
||||
})
|
||||
})
|
||||
|
||||
describe('客户角色资料校验', () => {
|
||||
it('清理空白并保留纯数字角色 ID', () => {
|
||||
const profile = normalizeCustomerProfile({
|
||||
roleName: ' 巫师基尔斯84 ',
|
||||
roleId: ' 1192083858 ',
|
||||
serverZone: ' 苹果V区 ',
|
||||
})
|
||||
assert.deepEqual(profile, {
|
||||
roleName: '巫师基尔斯84',
|
||||
roleId: '1192083858',
|
||||
serverZone: '苹果V区',
|
||||
})
|
||||
})
|
||||
|
||||
it('角色 ID 非数字时拒绝保存', () => {
|
||||
assert.throws(
|
||||
() => normalizeCustomerProfile({ roleName: '巫师基尔斯84', roleId: 'abc123' }),
|
||||
/只能是数字/,
|
||||
)
|
||||
})
|
||||
|
||||
it('缺区服时拒绝保存', () => {
|
||||
assert.throws(
|
||||
() => normalizeCustomerProfile({ roleName: '巫师基尔斯84', roleId: '1192083858' }),
|
||||
/区服只能选择/,
|
||||
)
|
||||
})
|
||||
|
||||
it('区服不在固定选项时拒绝保存', () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
normalizeCustomerProfile({
|
||||
roleName: '巫师基尔斯84',
|
||||
roleId: '1192083858',
|
||||
serverZone: '苹果微信区',
|
||||
}),
|
||||
/区服只能选择/,
|
||||
)
|
||||
})
|
||||
|
||||
it('角色名称与角色 ID 都为空时拒绝保存', () => {
|
||||
assert.throws(
|
||||
() => normalizeCustomerProfile({ roleName: ' ', roleId: '', serverZone: '苹果V区' }),
|
||||
/请完整填写区服/,
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -19,13 +19,16 @@ import {
|
||||
import {
|
||||
createHuyaBrowserTicket,
|
||||
createHuyaLoginSession,
|
||||
confirmHuyaBinding,
|
||||
exportHuyaSessionCredential,
|
||||
getHuyaBinding,
|
||||
getHuyaBindingSnapshot,
|
||||
getHuyaLoginSession,
|
||||
loginHuyaSms,
|
||||
revokeHuyaSession,
|
||||
sendHuyaSmsCode,
|
||||
startHuyaBinding,
|
||||
submitHuyaRebind,
|
||||
consumeHuyaBrowserTicket,
|
||||
verifyHuyaSmsChallenge,
|
||||
type ConnectorBindingSession,
|
||||
@@ -52,6 +55,8 @@ import {
|
||||
markSemiAutoCredentialCheck,
|
||||
upsertSemiAutoCredentialWithClient,
|
||||
} from './semi-auto-credential-service.js'
|
||||
import { querySemiAutoTraces } from './semi-auto-trace.js'
|
||||
import { isNumericBindingRoleId } from './binding-role-id.js'
|
||||
|
||||
const SEMI_AUTO_PLATFORMS = new Set(['huya', 'weibo'])
|
||||
type SemiAutoPlatform = 'huya' | 'weibo'
|
||||
@@ -98,7 +103,14 @@ type TaskRow = {
|
||||
platform_nickname: string
|
||||
bind_game_account: string
|
||||
bind_game_role: string
|
||||
bind_game_role_id: string
|
||||
bind_game_channel: string
|
||||
customer_game_role_name: string
|
||||
customer_game_role_id: string
|
||||
customer_game_server_zone: string
|
||||
customer_game_id: string
|
||||
customer_game_role: string
|
||||
customer_server_zone: string
|
||||
target_quantity: number
|
||||
completed_quantity: number
|
||||
assigned_admin_user_id: number | null
|
||||
@@ -175,7 +187,20 @@ function displayStatus(task: TaskRow) {
|
||||
return { key: 'failed', label: '需客服处理' }
|
||||
}
|
||||
if (task.login_status === 'authenticated') {
|
||||
return { key: 'waiting_operator', label: '等待客服处理' }
|
||||
// 虎牙需要客户确认绑定角色后才算授权完成;微博登录即授权。
|
||||
if (task.platform === 'weibo' || task.binding_status === 'confirmed') {
|
||||
return { key: 'waiting_operator', label: '等待客服处理' }
|
||||
}
|
||||
if (task.binding_status === 'role_ready') {
|
||||
return { key: 'binding_confirm', label: '待确认绑定角色' }
|
||||
}
|
||||
if (task.binding_status === 'expired') {
|
||||
return { key: 'binding_expired', label: '绑定二维码已过期' }
|
||||
}
|
||||
if (task.binding_status === 'failed') {
|
||||
return { key: 'binding_failed', label: '绑定失败,需重新扫码' }
|
||||
}
|
||||
return { key: 'waiting_binding', label: '等待客户绑定角色' }
|
||||
}
|
||||
if (task.login_status === 'scanned') return { key: 'login_scanned', label: '已扫码,确认中' }
|
||||
if (task.login_status === 'qr_pending') return { key: 'waiting_login', label: '等待客户登录' }
|
||||
@@ -205,7 +230,11 @@ function mapTask(task: TaskRow) {
|
||||
platformNickname: task.platform_nickname,
|
||||
bindGameAccount: task.bind_game_account,
|
||||
bindGameRole: task.bind_game_role,
|
||||
bindGameRoleId: task.bind_game_role_id,
|
||||
bindGameChannel: task.bind_game_channel,
|
||||
customerGameRoleId: task.customer_game_id || '',
|
||||
customerGameRoleName: task.customer_game_role || '',
|
||||
customerServerZone: task.customer_server_zone || '',
|
||||
targetQuantity: Number(task.target_quantity || 1),
|
||||
completedQuantity: Number(task.completed_quantity || 0),
|
||||
assignedAdminUserId: task.assigned_admin_user_id ? Number(task.assigned_admin_user_id) : null,
|
||||
@@ -289,13 +318,41 @@ const TASK_SELECT = `
|
||||
cfg.semi_auto_config_json,
|
||||
credential.credential_status,
|
||||
credential.credential_source,
|
||||
credential.credential_updated_at
|
||||
credential.credential_updated_at,
|
||||
COALESCE(
|
||||
NULLIF(task.customer_game_role_id, ''),
|
||||
wo.material_json->'collect'->'fields'->>'gameId',
|
||||
wo.material_json->'collect'->'fields'->>'characterId',
|
||||
''
|
||||
) AS customer_game_id,
|
||||
COALESCE(
|
||||
NULLIF(task.customer_game_role_name, ''),
|
||||
NULLIF(wo.material_json->'collect'->'fields'->>'gameNickname', ''),
|
||||
NULLIF(wo.material_json->'collect'->'fields'->>'roleName', ''),
|
||||
''
|
||||
) AS customer_game_role,
|
||||
COALESCE(
|
||||
NULLIF(task.customer_game_server_zone, ''),
|
||||
wo.material_json->'collect'->'fields'->>'serverZone',
|
||||
''
|
||||
) AS customer_server_zone
|
||||
FROM semi_auto_tasks task
|
||||
JOIN orders o ON o.id = task.order_id
|
||||
JOIN order_items oi ON oi.id = task.order_item_id
|
||||
LEFT JOIN manual_fulfillment_configs cfg ON cfg.id = task.manual_fulfillment_config_id
|
||||
LEFT JOIN admin_users admin ON admin.id = task.assigned_admin_user_id
|
||||
LEFT JOIN semi_auto_credentials credential ON credential.id = task.credential_id
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT candidate.material_json
|
||||
FROM work_orders candidate
|
||||
WHERE candidate.order_item_id = task.order_item_id
|
||||
OR (candidate.order_item_id IS NULL AND candidate.order_id = task.order_id)
|
||||
OR (o.platform_order_id <> '' AND candidate.platform_order_id = o.platform_order_id)
|
||||
ORDER BY (candidate.order_item_id = task.order_item_id) DESC NULLS LAST,
|
||||
(candidate.order_id = task.order_id) DESC NULLS LAST,
|
||||
candidate.id DESC
|
||||
LIMIT 1
|
||||
) wo ON TRUE
|
||||
`
|
||||
|
||||
async function loadTask(taskId: number): Promise<TaskRow> {
|
||||
@@ -354,6 +411,24 @@ function assertHuyaTask(task: TaskRow) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 半自动订单没有工单,资料页 /c/<订单号> 是唯一入口。
|
||||
* 未提交区服 / 游戏编号 / 角色名时,不允许开始登录,避免后续无法比对角色。
|
||||
*/
|
||||
function assertCustomerProfileReady(task: TaskRow) {
|
||||
if (task.platform !== 'huya') return
|
||||
if (
|
||||
!String(task.customer_game_server_zone || '').trim() ||
|
||||
!String(task.customer_game_role_id || '').trim() ||
|
||||
!String(task.customer_game_role_name || '').trim()
|
||||
) {
|
||||
throw createHttpError('请先提交游戏角色资料', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_profile_required',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async function createLoginSessionForTask(
|
||||
task: TaskRow,
|
||||
orderNo: string,
|
||||
@@ -679,6 +754,98 @@ export async function markCustomerLinkOpened(orderNoInput: unknown, taskIdInput:
|
||||
return { ok: true }
|
||||
}
|
||||
|
||||
export type CustomerProfileInput = {
|
||||
roleName?: unknown
|
||||
roleId?: unknown
|
||||
serverZone?: unknown
|
||||
}
|
||||
|
||||
const CUSTOMER_SERVER_ZONES = new Set(['苹果Q区', '苹果V区', '安卓Q区', '安卓V区'])
|
||||
|
||||
export function normalizeCustomerProfile(input: CustomerProfileInput = {}) {
|
||||
const roleName = String(input.roleName ?? '')
|
||||
.trim()
|
||||
.slice(0, 100)
|
||||
const roleId = String(input.roleId ?? '')
|
||||
.replace(/\s+/g, '')
|
||||
.slice(0, 64)
|
||||
const serverZone = String(input.serverZone ?? '')
|
||||
.trim()
|
||||
.slice(0, 100)
|
||||
if (roleId && !/^\d+$/.test(roleId)) {
|
||||
throw createHttpError('游戏编号 / 角色 ID 只能是数字', {
|
||||
statusCode: 400,
|
||||
errorCode: 'semi_auto_profile_role_id_invalid',
|
||||
})
|
||||
}
|
||||
if (!CUSTOMER_SERVER_ZONES.has(serverZone)) {
|
||||
throw createHttpError('区服只能选择 苹果Q区 / 苹果V区 / 安卓Q区 / 安卓V区', {
|
||||
statusCode: 400,
|
||||
errorCode: 'semi_auto_profile_server_zone_invalid',
|
||||
})
|
||||
}
|
||||
if (!roleName || !roleId) {
|
||||
throw createHttpError('请完整填写区服、游戏编号和角色名', {
|
||||
statusCode: 400,
|
||||
errorCode: 'semi_auto_profile_required',
|
||||
})
|
||||
}
|
||||
return { roleName, roleId, serverZone }
|
||||
}
|
||||
|
||||
/**
|
||||
* 半自动订单没有 work_orders,客户资料只能在授权页 /c/<订单号> 收集。
|
||||
* 保存后立即参与“客户填写角色 vs 平台识别角色”的比对。
|
||||
*/
|
||||
export async function savePublicTaskProfile(
|
||||
orderNoInput: unknown,
|
||||
taskIdInput: unknown,
|
||||
payload: CustomerProfileInput = {},
|
||||
) {
|
||||
const orderNo = normalizeOrderNo(orderNoInput)
|
||||
const taskId = normalizeId(taskIdInput)
|
||||
const task = await loadTaskForOrder(orderNo, taskId)
|
||||
if (task.platform !== 'huya') {
|
||||
throw createHttpError('当前平台不需要填写游戏角色', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_profile_not_supported',
|
||||
})
|
||||
}
|
||||
if (task.execution_status === 'completed' || task.execution_status === 'cancelled') {
|
||||
throw createHttpError('当前订单已结束,不能修改角色资料', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_task_closed',
|
||||
})
|
||||
}
|
||||
if (task.binding_status === 'confirmed') {
|
||||
throw createHttpError('绑定已确认,不能修改角色资料', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_profile_locked',
|
||||
})
|
||||
}
|
||||
const profile = normalizeCustomerProfile(payload)
|
||||
await withTransaction(async (client) => {
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET customer_game_role_name = $2,
|
||||
customer_game_role_id = $3,
|
||||
customer_game_server_zone = $4,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[task.id, profile.roleName, profile.roleId, profile.serverZone],
|
||||
)
|
||||
await appendTaskEvent(client, task.id, {
|
||||
eventType: 'customer_profile_saved',
|
||||
actorType: 'customer',
|
||||
detail: profile,
|
||||
})
|
||||
})
|
||||
const updated = await loadTask(task.id)
|
||||
return { task: mapTask(updated) }
|
||||
}
|
||||
|
||||
function mapLoginUpdate(session: ConnectorLoginSession) {
|
||||
const statusMap: Record<ConnectorLoginSession['status'], LoginStatus> = {
|
||||
verification_pending: 'waiting_login',
|
||||
@@ -705,8 +872,13 @@ async function updateLoginTask(
|
||||
options: { credentialSource?: 'qr' | 'sms'; method?: 'qr' | 'sms' } = {},
|
||||
) {
|
||||
const mapped = mapLoginUpdate(session)
|
||||
// 虎牙登录成功还不算授权完成,必须等客户确认绑定角色;微博登录即授权。
|
||||
const nextExecutionStatus: ExecutionStatus =
|
||||
mapped.status === 'authenticated' ? 'waiting_operator' : task.execution_status
|
||||
mapped.status === 'authenticated'
|
||||
? task.platform === 'weibo' || task.binding_status === 'confirmed'
|
||||
? 'waiting_operator'
|
||||
: 'waiting_customer'
|
||||
: task.execution_status
|
||||
const storedCredential =
|
||||
mapped.status === 'authenticated' && mapped.hasCredential
|
||||
? task.platform === 'weibo'
|
||||
@@ -750,19 +922,22 @@ async function updateLoginTask(
|
||||
credentialId,
|
||||
],
|
||||
)
|
||||
await appendTaskEvent(client, task.id, {
|
||||
eventType: 'login_status_changed',
|
||||
actorType,
|
||||
fromLoginStatus: task.login_status,
|
||||
toLoginStatus: mapped.status,
|
||||
fromExecutionStatus: task.execution_status,
|
||||
toExecutionStatus: nextExecutionStatus,
|
||||
detail: {
|
||||
hasCredential: mapped.hasCredential,
|
||||
message: mapped.message,
|
||||
method: options.method || 'qr',
|
||||
},
|
||||
})
|
||||
// 轮询会每 2 秒调用一次:状态与执行状态都没变时不写事件,避免时间线被重复项淹没。
|
||||
if (mapped.status !== task.login_status || nextExecutionStatus !== task.execution_status) {
|
||||
await appendTaskEvent(client, task.id, {
|
||||
eventType: 'login_status_changed',
|
||||
actorType,
|
||||
fromLoginStatus: task.login_status,
|
||||
toLoginStatus: mapped.status,
|
||||
fromExecutionStatus: task.execution_status,
|
||||
toExecutionStatus: nextExecutionStatus,
|
||||
detail: {
|
||||
hasCredential: mapped.hasCredential,
|
||||
message: mapped.message,
|
||||
method: options.method || 'qr',
|
||||
},
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -779,27 +954,164 @@ function mapBindingUpdate(session: ConnectorBindingSession) {
|
||||
return {
|
||||
status: statusMap[session.status] || 'failed',
|
||||
qrImage: String(session.qrImage || ''),
|
||||
qrExpiresAt: String(session.qrExpiresAt || ''),
|
||||
qrUrl: String(session.qrUrl || ''),
|
||||
bindGameAccount: String(session.bindGameAccount || ''),
|
||||
bindGameRole: String(session.bindGameRole || ''),
|
||||
bindGameRoleId: String(session.bindGameRoleId || ''),
|
||||
bindGameChannel: String(session.bindGameChannel || ''),
|
||||
hasExistingBinding: session.hasExistingBinding === true,
|
||||
rebindRequested: session.rebindRequested === true,
|
||||
rebindUnchanged: session.rebindUnchanged === true,
|
||||
rebindConfirmState: session.rebindConfirmState || 'idle',
|
||||
rebindConfirmMessage: String(session.rebindConfirmMessage || ''),
|
||||
bindConfirmState: session.bindConfirmState || 'idle',
|
||||
bindConfirmMessage: String(session.bindConfirmMessage || ''),
|
||||
rebindCooldownDays: Number(session.rebindCooldownDays || 0),
|
||||
nextRebindAt: String(session.nextRebindAt || ''),
|
||||
platformChangeBindDay: Number(session.platformChangeBindDay || 0),
|
||||
platformChangeBindTime: Number(session.platformChangeBindTime || 0),
|
||||
message: String(session.message || ''),
|
||||
}
|
||||
}
|
||||
|
||||
export type BindingRoleComparison = {
|
||||
verdict: 'match' | 'mismatch' | 'unknown'
|
||||
customerRoleName: string
|
||||
customerRoleId: string
|
||||
customerZone: string
|
||||
boundRoleName: string
|
||||
boundRoleId: string
|
||||
boundZone: string
|
||||
message: string
|
||||
}
|
||||
|
||||
function normalizeRoleText(value: unknown): string {
|
||||
return String(value ?? '')
|
||||
.replace(/\s+/g, '')
|
||||
.toLowerCase()
|
||||
}
|
||||
|
||||
function normalizeServerZone(value: unknown): string {
|
||||
const text = String(value ?? '').trim()
|
||||
|
||||
if (!text) return ''
|
||||
|
||||
return /区$/.test(text) ? text : `${text}区`
|
||||
}
|
||||
|
||||
/**
|
||||
* 从虎牙渠道串解析区服,例如「安卓(android) · 微信」→ 安卓V区。
|
||||
* 解析不出平台或登录方式时返回空串,调用方跳过区服比对。
|
||||
*/
|
||||
export function detectServerZone(channel: unknown): string {
|
||||
const text = String(channel ?? '')
|
||||
.replace(/\s+/g, '')
|
||||
.toLowerCase()
|
||||
|
||||
if (!text) return ''
|
||||
|
||||
const platform = /苹果|ios/.test(text) ? '苹果' : /安卓|android/.test(text) ? '安卓' : ''
|
||||
|
||||
if (!platform) return ''
|
||||
|
||||
const login = /qq|q区/.test(text) ? 'Q' : /微信|wechat|v区/.test(text) ? 'V' : ''
|
||||
|
||||
return login ? `${platform}${login}区` : ''
|
||||
}
|
||||
|
||||
/**
|
||||
* 客户填写角色与平台识别角色必须一致才允许确认绑定。
|
||||
*
|
||||
* 区服、角色名、角色 ID 三项都要一致:
|
||||
* ① 两侧都有 ID 时 ID 必须相等;
|
||||
* ② 两侧都有角色名时名称必须相等(不能因为 ID 相同就放行改名);
|
||||
* ③ 平台渠道能解析出区服且客户有填时,区服必须相等。
|
||||
* 任一侧缺某字段时跳过该字段比对;三项都取不到才判 unknown,转客服核对。
|
||||
*/
|
||||
export function compareBindingRole(
|
||||
task: Pick<
|
||||
TaskRow,
|
||||
'customer_game_id' | 'customer_game_role' | 'customer_game_server_zone' | 'huya_uid'
|
||||
>,
|
||||
binding: { bindGameRole?: string; bindGameRoleId?: string; bindGameChannel?: string },
|
||||
): BindingRoleComparison {
|
||||
const customerRoleName = String(task.customer_game_role || '').trim()
|
||||
const customerRoleId = String(task.customer_game_id || '').trim()
|
||||
const customerZone = normalizeServerZone(task.customer_game_server_zone)
|
||||
const boundRoleName = String(binding.bindGameRole || '').trim()
|
||||
const rawBoundRoleId = String(binding.bindGameRoleId || '').trim()
|
||||
// 虎牙 gameRole.roleId 是 40 位加密串,客户填写的是数值游戏编号;
|
||||
// 平台侧可比对的是登录账号的数值 UID(huyaUid),不能拿加密串直接比对。
|
||||
const numericHuyaUid = /^\d+$/.test(String(task.huya_uid || '').trim())
|
||||
? String(task.huya_uid).trim()
|
||||
: ''
|
||||
const boundRoleId = /^\d+$/.test(rawBoundRoleId)
|
||||
? rawBoundRoleId
|
||||
: numericHuyaUid || rawBoundRoleId
|
||||
const boundZone = detectServerZone(binding.bindGameChannel)
|
||||
const base = {
|
||||
customerRoleName,
|
||||
customerRoleId,
|
||||
customerZone,
|
||||
boundRoleName,
|
||||
boundRoleId,
|
||||
boundZone,
|
||||
}
|
||||
|
||||
if (customerRoleId && boundRoleId && customerRoleId !== boundRoleId) {
|
||||
return { ...base, verdict: 'mismatch', message: '两侧角色 ID 不一致,无法确认绑定' }
|
||||
}
|
||||
|
||||
if (
|
||||
customerRoleName &&
|
||||
boundRoleName &&
|
||||
normalizeRoleText(customerRoleName) !== normalizeRoleText(boundRoleName)
|
||||
) {
|
||||
return { ...base, verdict: 'mismatch', message: '两侧角色名称不一致,无法确认绑定' }
|
||||
}
|
||||
|
||||
if (customerZone && boundZone && customerZone !== boundZone) {
|
||||
return { ...base, verdict: 'mismatch', message: '两侧区服不一致,无法确认绑定' }
|
||||
}
|
||||
|
||||
const matchedFields = [
|
||||
customerRoleId && boundRoleId ? '角色 ID' : '',
|
||||
customerRoleName && boundRoleName ? '角色名称' : '',
|
||||
customerZone && boundZone ? '区服' : '',
|
||||
].filter(Boolean)
|
||||
|
||||
if (matchedFields.length > 0) {
|
||||
return {
|
||||
...base,
|
||||
verdict: 'match',
|
||||
message: `两侧${matchedFields.join('、')}一致,可确认绑定`,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...base,
|
||||
verdict: 'unknown',
|
||||
message: '未获取到可核对的两侧角色信息,请联系客服核对后再确认',
|
||||
}
|
||||
}
|
||||
|
||||
async function updateBindingTask(
|
||||
task: TaskRow,
|
||||
session: ConnectorBindingSession,
|
||||
actorType: TaskActorType,
|
||||
) {
|
||||
const mapped = mapBindingUpdate(session)
|
||||
const comparison = compareBindingRole(task, mapped)
|
||||
const roleIdVerified = isNumericBindingRoleId(mapped.bindGameRoleId)
|
||||
const requiresSupport =
|
||||
(Boolean(mapped.bindGameRole) || mapped.hasExistingBinding === true) && !roleIdVerified
|
||||
const executionStatus: ExecutionStatus =
|
||||
mapped.status === 'confirmed'
|
||||
? 'waiting_operator'
|
||||
: mapped.status === 'failed' || mapped.status === 'expired'
|
||||
? 'failed'
|
||||
: task.execution_status === 'completed' || task.execution_status === 'cancelled'
|
||||
? task.execution_status
|
||||
: 'waiting_customer'
|
||||
: task.execution_status === 'completed' || task.execution_status === 'cancelled'
|
||||
? task.execution_status
|
||||
: 'waiting_customer'
|
||||
await withTransaction(async (client) => {
|
||||
await client.query(
|
||||
`
|
||||
@@ -807,6 +1119,7 @@ async function updateBindingTask(
|
||||
SET binding_status = $2,
|
||||
bind_game_account = CASE WHEN $3 <> '' THEN $3 ELSE bind_game_account END,
|
||||
bind_game_role = CASE WHEN $4 <> '' THEN $4 ELSE bind_game_role END,
|
||||
bind_game_role_id = CASE WHEN $8 <> '' THEN $8 ELSE bind_game_role_id END,
|
||||
bind_game_channel = CASE WHEN $5 <> '' THEN $5 ELSE bind_game_channel END,
|
||||
bound_at = CASE WHEN $2 IN ('role_ready', 'confirmed') THEN COALESCE(bound_at, NOW()) ELSE bound_at END,
|
||||
execution_status = $6,
|
||||
@@ -822,30 +1135,68 @@ async function updateBindingTask(
|
||||
mapped.bindGameChannel,
|
||||
executionStatus,
|
||||
mapped.message,
|
||||
mapped.bindGameRoleId,
|
||||
],
|
||||
)
|
||||
await appendTaskEvent(client, task.id, {
|
||||
eventType: 'binding_status_changed',
|
||||
actorType,
|
||||
fromBindingStatus: task.binding_status,
|
||||
toBindingStatus: mapped.status,
|
||||
fromExecutionStatus: task.execution_status,
|
||||
toExecutionStatus: executionStatus,
|
||||
detail: {
|
||||
gameAccount: mapped.bindGameAccount,
|
||||
gameRole: mapped.bindGameRole,
|
||||
gameChannel: mapped.bindGameChannel,
|
||||
message: mapped.message,
|
||||
},
|
||||
})
|
||||
// 轮询会每 2 秒调用一次:只有状态/执行状态变化,或换绑被拒这类关键信号才写事件。
|
||||
const bindingChanged =
|
||||
mapped.status !== task.binding_status ||
|
||||
executionStatus !== task.execution_status ||
|
||||
mapped.rebindUnchanged ||
|
||||
mapped.rebindConfirmState === 'rejected'
|
||||
if (bindingChanged) {
|
||||
await appendTaskEvent(client, task.id, {
|
||||
eventType: 'binding_status_changed',
|
||||
actorType,
|
||||
fromBindingStatus: task.binding_status,
|
||||
toBindingStatus: mapped.status,
|
||||
fromExecutionStatus: task.execution_status,
|
||||
toExecutionStatus: executionStatus,
|
||||
detail: {
|
||||
gameAccount: mapped.bindGameAccount,
|
||||
gameRole: mapped.bindGameRole,
|
||||
gameRoleId: mapped.bindGameRoleId,
|
||||
gameChannel: mapped.bindGameChannel,
|
||||
verdict: comparison.verdict,
|
||||
rebindRequested: mapped.rebindRequested,
|
||||
rebindUnchanged: mapped.rebindUnchanged,
|
||||
rebindConfirmState: mapped.rebindConfirmState,
|
||||
rebindConfirmMessage: mapped.rebindConfirmMessage,
|
||||
bindConfirmState: mapped.bindConfirmState,
|
||||
bindConfirmMessage: mapped.bindConfirmMessage,
|
||||
rebindCooldownDays: mapped.rebindCooldownDays,
|
||||
nextRebindAt: mapped.nextRebindAt,
|
||||
changeBindDay: mapped.platformChangeBindDay,
|
||||
changeBindTime: mapped.platformChangeBindTime,
|
||||
message: mapped.message,
|
||||
},
|
||||
})
|
||||
}
|
||||
})
|
||||
return {
|
||||
status: mapped.status,
|
||||
qrImage: mapped.qrImage,
|
||||
qrExpiresAt: mapped.qrExpiresAt,
|
||||
qrUrl: mapped.qrUrl,
|
||||
bindGameAccount: mapped.bindGameAccount,
|
||||
bindGameRole: mapped.bindGameRole,
|
||||
bindGameRoleId: mapped.bindGameRoleId,
|
||||
bindGameChannel: mapped.bindGameChannel,
|
||||
roleIdVerified,
|
||||
requiresSupport,
|
||||
hasExistingBinding: mapped.hasExistingBinding,
|
||||
rebindRequested: mapped.rebindRequested,
|
||||
rebindUnchanged: mapped.rebindUnchanged,
|
||||
rebindConfirmState: mapped.rebindConfirmState,
|
||||
rebindConfirmMessage: mapped.rebindConfirmMessage,
|
||||
bindConfirmState: mapped.bindConfirmState,
|
||||
bindConfirmMessage: mapped.bindConfirmMessage,
|
||||
rebindCooldownDays: mapped.rebindCooldownDays,
|
||||
nextRebindAt: mapped.nextRebindAt,
|
||||
platformChangeBindDay: mapped.platformChangeBindDay,
|
||||
platformChangeBindTime: mapped.platformChangeBindTime,
|
||||
message: mapped.message,
|
||||
comparison,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -854,6 +1205,7 @@ export async function startPublicLogin(orderNoInput: unknown, taskIdInput: unkno
|
||||
const taskId = normalizeId(taskIdInput)
|
||||
await ensureSemiAutoTasksForOrder(orderNo)
|
||||
const task = await loadTaskForOrder(orderNo, taskId)
|
||||
assertCustomerProfileReady(task)
|
||||
if (task.execution_status === 'completed' || task.execution_status === 'cancelled') {
|
||||
throw createHttpError('当前订单已结束,不能重新登录', {
|
||||
statusCode: 409,
|
||||
@@ -907,6 +1259,13 @@ export async function startPublicLogin(orderNoInput: unknown, taskIdInput: unkno
|
||||
UPDATE semi_auto_tasks
|
||||
SET connector_session_id = $2,
|
||||
login_status = 'qr_pending',
|
||||
binding_status = 'not_started',
|
||||
bind_game_account = '',
|
||||
bind_game_role = '',
|
||||
bind_game_role_id = '',
|
||||
bind_game_channel = '',
|
||||
binding_started_at = NULL,
|
||||
bound_at = NULL,
|
||||
execution_status = 'waiting_customer',
|
||||
auth_started_at = COALESCE(auth_started_at, NOW()),
|
||||
last_error = '',
|
||||
@@ -1007,7 +1366,11 @@ export async function pollPublicBinding(orderNoInput: unknown, taskIdInput: unkn
|
||||
return { task: mapTask(updated), binding }
|
||||
}
|
||||
|
||||
export async function confirmPublicBinding(orderNoInput: unknown, taskIdInput: unknown) {
|
||||
export async function confirmPublicBinding(
|
||||
orderNoInput: unknown,
|
||||
taskIdInput: unknown,
|
||||
options: { acceptExistingRole?: boolean } = {},
|
||||
) {
|
||||
const orderNo = normalizeOrderNo(orderNoInput)
|
||||
const taskId = normalizeId(taskIdInput)
|
||||
const task = await loadTaskForOrder(orderNo, taskId)
|
||||
@@ -1026,7 +1389,85 @@ export async function confirmPublicBinding(orderNoInput: unknown, taskIdInput: u
|
||||
errorCode: 'semi_auto_binding_not_ready',
|
||||
})
|
||||
}
|
||||
const session = await getBindingForTask(task, task.connector_session_id)
|
||||
// 确认绑定是纯本地动作:虎牙侧只读内存快照,不再触发角色查询或换绑提交。
|
||||
const session =
|
||||
task.platform === 'huya'
|
||||
? await getHuyaBindingSnapshot(task.connector_session_id, task.connector_mode)
|
||||
: await getBindingForTask(task, task.connector_session_id)
|
||||
if (
|
||||
task.platform === 'huya' &&
|
||||
session.rebindUnchanged === true &&
|
||||
options.acceptExistingRole !== true
|
||||
) {
|
||||
// 换绑被虎牙拒绝时不直接放行,要求客户二选一:重新扫码换绑 / 仍使用原角色。
|
||||
const reason = String(session.rebindConfirmMessage || '').trim()
|
||||
throw createHttpError(
|
||||
`${
|
||||
reason ? `换绑未成功:${reason}。` : '换绑未生效:平台仍返回原绑定角色。'
|
||||
}请重新扫码换绑,或确认继续使用原绑定角色「${session.bindGameRole || '原角色'}」`,
|
||||
{
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_binding_rebind_decision_required',
|
||||
},
|
||||
)
|
||||
}
|
||||
// 已绑定角色但没有可核对的数字角色 ID:不能只按角色名放行,必须人工核实(客户页会提示联系客服)。
|
||||
const boundRolePresent =
|
||||
Boolean(String(session.bindGameRole || '').trim()) || session.hasExistingBinding === true
|
||||
if (
|
||||
task.platform === 'huya' &&
|
||||
boundRolePresent &&
|
||||
!isNumericBindingRoleId(session.bindGameRoleId)
|
||||
) {
|
||||
throw createHttpError('平台未返回可核对的角色ID,请联系客服人工核实后再确认绑定', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_binding_role_id_missing',
|
||||
})
|
||||
}
|
||||
const comparison = compareBindingRole(task, session)
|
||||
if (comparison.verdict === 'mismatch') {
|
||||
throw createHttpError(comparison.message, {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_binding_role_mismatch',
|
||||
})
|
||||
}
|
||||
// 必须调用 Connector 完成确认,否则会话仍是 role_ready,数据库也会停在待确认。
|
||||
const confirmedSession =
|
||||
task.platform === 'huya'
|
||||
? await confirmHuyaBinding(task.connector_session_id, task.connector_mode, options)
|
||||
: session
|
||||
const binding = await updateBindingTask(task, confirmedSession, 'customer')
|
||||
const updated = await loadTask(task.id)
|
||||
return { task: mapTask(updated), binding }
|
||||
}
|
||||
|
||||
/**
|
||||
* 客户在微信里选好目标角色后,由项目侧主动向虎牙提交换绑确认。
|
||||
* 与「确认绑定」不同,这一步只提交换绑,不把任务标记为已确认。
|
||||
*/
|
||||
export async function submitPublicRebind(orderNoInput: unknown, taskIdInput: unknown) {
|
||||
const orderNo = normalizeOrderNo(orderNoInput)
|
||||
const taskId = normalizeId(taskIdInput)
|
||||
const task = await loadTaskForOrder(orderNo, taskId)
|
||||
if (task.execution_status === 'completed' || task.execution_status === 'cancelled') {
|
||||
throw createHttpError('当前订单已结束,不能提交换绑', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_task_closed',
|
||||
})
|
||||
}
|
||||
if (task.platform !== 'huya') {
|
||||
throw createHttpError('当前平台不需要换绑游戏角色', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_rebind_not_supported',
|
||||
})
|
||||
}
|
||||
if (!task.connector_session_id || task.login_status !== 'authenticated') {
|
||||
throw createHttpError('请先完成平台登录', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_login_required',
|
||||
})
|
||||
}
|
||||
const session = await submitHuyaRebind(task.connector_session_id, task.connector_mode)
|
||||
const binding = await updateBindingTask(task, session, 'customer')
|
||||
const updated = await loadTask(task.id)
|
||||
return { task: mapTask(updated), binding }
|
||||
@@ -1041,6 +1482,7 @@ export async function sendPublicHuyaSmsCode(
|
||||
const taskId = normalizeId(taskIdInput)
|
||||
const task = await loadTaskForOrder(orderNo, taskId)
|
||||
assertHuyaTask(task)
|
||||
assertCustomerProfileReady(task)
|
||||
if (task.execution_status === 'completed' || task.execution_status === 'cancelled') {
|
||||
throw createHttpError('当前订单已结束,不能重新登录', {
|
||||
statusCode: 409,
|
||||
@@ -1190,6 +1632,7 @@ export async function loginPublicHuyaSms(
|
||||
const taskId = normalizeId(taskIdInput)
|
||||
const task = await loadTaskForOrder(orderNo, taskId)
|
||||
assertHuyaTask(task)
|
||||
assertCustomerProfileReady(task)
|
||||
if (task.execution_status === 'completed' || task.execution_status === 'cancelled') {
|
||||
throw createHttpError('当前订单已结束,不能重新登录', {
|
||||
statusCode: 409,
|
||||
@@ -1504,6 +1947,78 @@ export async function getAdminSemiAutoTask(taskIdInput: unknown) {
|
||||
}
|
||||
}
|
||||
|
||||
type SemiAutoTaskEventRow = {
|
||||
id: number
|
||||
event_type: string
|
||||
actor_type: string
|
||||
actor_id: string
|
||||
from_login_status: string | null
|
||||
to_login_status: string | null
|
||||
from_binding_status: string | null
|
||||
to_binding_status: string | null
|
||||
from_execution_status: string | null
|
||||
to_execution_status: string | null
|
||||
detail_json: Record<string, unknown>
|
||||
created_at: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 运营端「历史」:任务状态流转事件 + 全链路报文(本系统入站 + 外部平台出站)。
|
||||
* 报文只读,不做任何写操作;Cookie / Token 已在落库前脱敏。
|
||||
*/
|
||||
export async function getAdminSemiAutoTaskHistory(
|
||||
taskIdInput: unknown,
|
||||
input: Record<string, unknown> = {},
|
||||
) {
|
||||
const task = await loadTask(normalizeId(taskIdInput))
|
||||
const eventCount = await query<{ total: number }>(
|
||||
`SELECT COUNT(*)::int AS total FROM semi_auto_task_events WHERE task_id = $1`,
|
||||
[task.id],
|
||||
)
|
||||
const events = await query<SemiAutoTaskEventRow>(
|
||||
`SELECT * FROM (
|
||||
SELECT id, event_type, actor_type, actor_id,
|
||||
from_login_status, to_login_status,
|
||||
from_binding_status, to_binding_status,
|
||||
from_execution_status, to_execution_status,
|
||||
detail_json, created_at
|
||||
FROM semi_auto_task_events
|
||||
WHERE task_id = $1
|
||||
ORDER BY id DESC
|
||||
LIMIT 500
|
||||
) recent
|
||||
ORDER BY id ASC`,
|
||||
[task.id],
|
||||
)
|
||||
const traces = await querySemiAutoTraces(task.id, {
|
||||
page: Number(input.page) || 1,
|
||||
pageSize: Number(input.pageSize) || 50,
|
||||
channel: String(input.channel || '').trim(),
|
||||
status: String(input.status || '').trim(),
|
||||
requestId: String(input.requestId || '').trim(),
|
||||
keyword: String(input.keyword || '').trim(),
|
||||
})
|
||||
return {
|
||||
task: mapTask(task),
|
||||
events: events.rows.map((event) => ({
|
||||
id: Number(event.id),
|
||||
eventType: event.event_type,
|
||||
actorType: event.actor_type,
|
||||
actorId: event.actor_id,
|
||||
fromLoginStatus: event.from_login_status,
|
||||
toLoginStatus: event.to_login_status,
|
||||
fromBindingStatus: event.from_binding_status,
|
||||
toBindingStatus: event.to_binding_status,
|
||||
fromExecutionStatus: event.from_execution_status,
|
||||
toExecutionStatus: event.to_execution_status,
|
||||
detail: event.detail_json || {},
|
||||
createdAt: event.created_at,
|
||||
})),
|
||||
eventTotal: Number(eventCount.rows[0]?.total || 0),
|
||||
traces,
|
||||
}
|
||||
}
|
||||
|
||||
export async function exportAdminSemiAutoCredential(taskIdInput: unknown) {
|
||||
const task = await loadTask(normalizeId(taskIdInput))
|
||||
if (!task.credential_id) {
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
import { AsyncLocalStorage } from 'node:async_hooks'
|
||||
import crypto from 'node:crypto'
|
||||
|
||||
import { query } from '../../db/client.js'
|
||||
import { logWarn } from '../../utils/logger.js'
|
||||
|
||||
/** 报文保留天数:180 天,由 startSemiAutoTraceCleanup 定时清理。 */
|
||||
export const SEMI_AUTO_TRACE_RETENTION_DAYS = 180
|
||||
const MAX_BODY_CHARS = 32_000
|
||||
const MAX_REDACT_DEPTH = 6
|
||||
const FINGERPRINT_LIMIT = 5_000
|
||||
|
||||
export type SemiAutoTraceChannel =
|
||||
| 'customer_api'
|
||||
| 'admin_api'
|
||||
| 'huya_wup'
|
||||
| 'huya_http'
|
||||
| 'external_connector'
|
||||
|
||||
export type SemiAutoTraceContext = {
|
||||
requestId: string
|
||||
taskId?: number
|
||||
orderNo?: string
|
||||
source?: string
|
||||
}
|
||||
|
||||
export type SemiAutoTraceEntry = {
|
||||
taskId?: number
|
||||
orderNo?: string
|
||||
requestId?: string
|
||||
direction: 'inbound' | 'outbound'
|
||||
channel: SemiAutoTraceChannel | string
|
||||
action: string
|
||||
status?: 'ok' | 'error'
|
||||
httpStatus?: number
|
||||
durationMs?: number
|
||||
requestSummary?: Record<string, unknown>
|
||||
requestBody?: unknown
|
||||
responseSummary?: Record<string, unknown>
|
||||
responseBody?: unknown
|
||||
errorMessage?: string
|
||||
/** 写操作/关键读:无条件记录(轮询类不要传)。 */
|
||||
always?: boolean
|
||||
/** 轮询类请求的状态指纹:与上次相同则不记录。 */
|
||||
fingerprint?: string | undefined
|
||||
}
|
||||
|
||||
const traceStorage = new AsyncLocalStorage<SemiAutoTraceContext>()
|
||||
const lastFingerprints = new Map<string, string>()
|
||||
|
||||
/** Cookie / Token / 密钥字段:一律不落库。 */
|
||||
const SENSITIVE_KEYS = new Set([
|
||||
'cookie',
|
||||
'set-cookie',
|
||||
'authorization',
|
||||
'proxyauthorization',
|
||||
'token',
|
||||
'accesstoken',
|
||||
'access_token',
|
||||
'refreshtoken',
|
||||
'refresh_token',
|
||||
'biztoken',
|
||||
'udb_biztoken',
|
||||
'password',
|
||||
'passwd',
|
||||
'secret',
|
||||
'apikey',
|
||||
'api_key',
|
||||
'x-semi-auto-key',
|
||||
'sig',
|
||||
'qrcodetoken',
|
||||
'qrcode_token',
|
||||
'qrcontent',
|
||||
'qr_content',
|
||||
'qrimage',
|
||||
'qr_image',
|
||||
'query_string',
|
||||
'smscode',
|
||||
'sms_code',
|
||||
'sessionid',
|
||||
'session_id',
|
||||
'baseinfo',
|
||||
'cookies',
|
||||
'cookie_header',
|
||||
'cookieheader',
|
||||
'ticket',
|
||||
'credential_payload_json',
|
||||
])
|
||||
|
||||
export function runWithSemiAutoTrace<T>(context: SemiAutoTraceContext, fn: () => T): T {
|
||||
return traceStorage.run(context, fn)
|
||||
}
|
||||
|
||||
export function currentSemiAutoTrace(): SemiAutoTraceContext | undefined {
|
||||
return traceStorage.getStore()
|
||||
}
|
||||
|
||||
function maskValue(value: unknown): unknown {
|
||||
if (value === null || value === undefined) return value
|
||||
if (typeof value !== 'string') return '******'
|
||||
return value.length > 0 ? '******' : ''
|
||||
}
|
||||
|
||||
function normalizeKey(key: string): string {
|
||||
return key.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase()
|
||||
}
|
||||
|
||||
/** 深度脱敏:Cookie / Token / 密钥字段直接替换为 ******。 */
|
||||
export function redactTraceValue(value: unknown, depth = 0): unknown {
|
||||
if (depth > MAX_REDACT_DEPTH) return '[max-depth]'
|
||||
if (value === null || value === undefined) return value
|
||||
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
|
||||
return value
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return value.slice(0, 50).map((item) => redactTraceValue(item, depth + 1))
|
||||
}
|
||||
if (typeof value === 'object') {
|
||||
const source = value as Record<string, unknown>
|
||||
const result: Record<string, unknown> = {}
|
||||
for (const [key, current] of Object.entries(source)) {
|
||||
result[key] = SENSITIVE_KEYS.has(normalizeKey(key))
|
||||
? maskValue(current)
|
||||
: redactTraceValue(current, depth + 1)
|
||||
}
|
||||
return result
|
||||
}
|
||||
return String(value)
|
||||
}
|
||||
|
||||
export function stringifyTraceBody(value: unknown): string {
|
||||
if (value === undefined || value === null) return ''
|
||||
if (typeof value === 'string') {
|
||||
return value.length > MAX_BODY_CHARS
|
||||
? `${value.slice(0, MAX_BODY_CHARS)}\n...[truncated]`
|
||||
: value
|
||||
}
|
||||
try {
|
||||
const text = JSON.stringify(redactTraceValue(value), null, 2)
|
||||
return text.length > MAX_BODY_CHARS ? `${text.slice(0, MAX_BODY_CHARS)}\n...[truncated]` : text
|
||||
} catch {
|
||||
return String(value).slice(0, MAX_BODY_CHARS)
|
||||
}
|
||||
}
|
||||
|
||||
function fingerprintKey(entry: SemiAutoTraceEntry): string {
|
||||
return `${entry.taskId || 0}|${entry.channel}|${entry.action}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 采样:写操作与关键读一律记录;轮询类只在状态变化或失败时记录,避免每 2 秒一条。
|
||||
*/
|
||||
export function shouldRecordTrace(entry: SemiAutoTraceEntry): boolean {
|
||||
if (entry.always) return true
|
||||
if ((entry.status || 'ok') === 'error') return true
|
||||
const fingerprint = String(entry.fingerprint || '')
|
||||
if (!fingerprint) return true
|
||||
const key = fingerprintKey(entry)
|
||||
const previous = lastFingerprints.get(key)
|
||||
if (previous === fingerprint) return false
|
||||
lastFingerprints.set(key, fingerprint)
|
||||
if (lastFingerprints.size > FINGERPRINT_LIMIT) lastFingerprints.clear()
|
||||
return true
|
||||
}
|
||||
|
||||
/** 记录一条报文:异步落库,失败只记日志,绝不阻断主流程。 */
|
||||
export function recordSemiAutoTrace(entry: SemiAutoTraceEntry): void {
|
||||
const context = currentSemiAutoTrace()
|
||||
const taskId = Number(entry.taskId || context?.taskId || 0)
|
||||
if (!Number.isFinite(taskId) || taskId <= 0) return
|
||||
if (!shouldRecordTrace(entry)) return
|
||||
const orderNo = entry.orderNo || context?.orderNo || ''
|
||||
const requestId = entry.requestId || context?.requestId || ''
|
||||
const status = entry.status === 'error' ? 'error' : 'ok'
|
||||
const requestBody = stringifyTraceBody(entry.requestBody)
|
||||
const responseBody = stringifyTraceBody(entry.responseBody)
|
||||
void query(
|
||||
`INSERT INTO semi_auto_trace_logs (
|
||||
task_id, order_no, request_id, direction, channel, action, status,
|
||||
http_status, duration_ms, request_summary, request_body,
|
||||
response_summary, response_body, error_message, created_at
|
||||
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10::jsonb,$11,$12::jsonb,$13,$14,NOW())`,
|
||||
[
|
||||
taskId,
|
||||
orderNo,
|
||||
requestId,
|
||||
entry.direction,
|
||||
entry.channel,
|
||||
entry.action,
|
||||
status,
|
||||
entry.httpStatus ?? null,
|
||||
entry.durationMs ?? null,
|
||||
JSON.stringify(redactTraceValue(entry.requestSummary || {})),
|
||||
requestBody,
|
||||
JSON.stringify(redactTraceValue(entry.responseSummary || {})),
|
||||
responseBody,
|
||||
String(entry.errorMessage || ''),
|
||||
],
|
||||
).catch((error) => {
|
||||
logWarn('semi-auto/trace', '写入报文失败', {
|
||||
taskId,
|
||||
action: entry.action,
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/** 供调用方快速生成一个轮询指纹。 */
|
||||
export function traceFingerprint(value: unknown): string {
|
||||
if (value === null || value === undefined) return ''
|
||||
let text = ''
|
||||
if (typeof value === 'string') {
|
||||
text = value
|
||||
} else {
|
||||
try {
|
||||
text = JSON.stringify(value)
|
||||
} catch {
|
||||
text = String(value)
|
||||
}
|
||||
}
|
||||
return crypto.createHash('sha1').update(text).digest('hex')
|
||||
}
|
||||
|
||||
export type SemiAutoTraceQuery = {
|
||||
page?: number
|
||||
pageSize?: number
|
||||
channel?: string
|
||||
status?: string
|
||||
requestId?: string
|
||||
keyword?: string
|
||||
}
|
||||
|
||||
export async function querySemiAutoTraces(taskId: number, input: SemiAutoTraceQuery = {}) {
|
||||
const page = Math.max(1, Math.floor(Number(input.page) || 1))
|
||||
const pageSize = Math.min(200, Math.max(1, Math.floor(Number(input.pageSize) || 50)))
|
||||
const conditions = ['task_id = $1']
|
||||
const params: unknown[] = [taskId]
|
||||
if (input.channel) {
|
||||
params.push(String(input.channel))
|
||||
conditions.push(`channel = $${params.length}`)
|
||||
}
|
||||
if (input.status) {
|
||||
params.push(String(input.status))
|
||||
conditions.push(`status = $${params.length}`)
|
||||
}
|
||||
if (input.requestId) {
|
||||
params.push(String(input.requestId))
|
||||
conditions.push(`request_id = $${params.length}`)
|
||||
}
|
||||
if (input.keyword) {
|
||||
params.push(`%${String(input.keyword).trim()}%`)
|
||||
conditions.push(
|
||||
`(action ILIKE $${params.length} OR request_body ILIKE $${params.length} OR response_body ILIKE $${params.length})`,
|
||||
)
|
||||
}
|
||||
const where = conditions.join(' AND ')
|
||||
const count = await query(
|
||||
`SELECT COUNT(*)::int AS total FROM semi_auto_trace_logs WHERE ${where}`,
|
||||
params,
|
||||
)
|
||||
const rows = await query(
|
||||
`SELECT id, order_no, request_id, direction, channel, action, status,
|
||||
http_status, duration_ms, request_summary, request_body,
|
||||
response_summary, response_body, error_message, created_at
|
||||
FROM semi_auto_trace_logs
|
||||
WHERE ${where}
|
||||
ORDER BY id DESC
|
||||
LIMIT $${params.length + 1} OFFSET $${params.length + 2}`,
|
||||
[...params, pageSize, (page - 1) * pageSize],
|
||||
)
|
||||
const summary = await query(
|
||||
`SELECT channel, status, COUNT(*)::int AS total
|
||||
FROM semi_auto_trace_logs
|
||||
WHERE task_id = $1
|
||||
GROUP BY channel, status`,
|
||||
[taskId],
|
||||
)
|
||||
return {
|
||||
pagination: { page, pageSize, total: Number(count.rows[0]?.total || 0) },
|
||||
summary: summary.rows,
|
||||
items: rows.rows.map((row) => ({
|
||||
id: Number(row.id),
|
||||
orderNo: row.order_no,
|
||||
requestId: row.request_id,
|
||||
direction: row.direction,
|
||||
channel: row.channel,
|
||||
action: row.action,
|
||||
status: row.status,
|
||||
httpStatus: row.http_status,
|
||||
durationMs: row.duration_ms,
|
||||
requestSummary: row.request_summary || {},
|
||||
requestBody: row.request_body || '',
|
||||
responseSummary: row.response_summary || {},
|
||||
responseBody: row.response_body || '',
|
||||
errorMessage: row.error_message || '',
|
||||
createdAt: row.created_at,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
export async function cleanupSemiAutoTraces(retentionDays = SEMI_AUTO_TRACE_RETENTION_DAYS) {
|
||||
const days = Math.max(1, Math.floor(Number(retentionDays) || SEMI_AUTO_TRACE_RETENTION_DAYS))
|
||||
const result = await query(
|
||||
`DELETE FROM semi_auto_trace_logs WHERE created_at < NOW() - ($1 || ' days')::interval`,
|
||||
[String(days)],
|
||||
)
|
||||
return result.rowCount || 0
|
||||
}
|
||||
|
||||
let cleanupStarted = false
|
||||
|
||||
/** 启动时清一次,之后每 6 小时清理超过保留期的报文。 */
|
||||
export function startSemiAutoTraceCleanup(): void {
|
||||
if (cleanupStarted) return
|
||||
cleanupStarted = true
|
||||
const run = () => {
|
||||
void cleanupSemiAutoTraces().catch((error) => {
|
||||
logWarn('semi-auto/trace', '清理历史报文失败', {
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
})
|
||||
})
|
||||
}
|
||||
run()
|
||||
const timer = setInterval(run, 6 * 60 * 60 * 1000)
|
||||
timer.unref?.()
|
||||
}
|
||||
@@ -1076,8 +1076,10 @@ export class WeiboNativeConnector {
|
||||
status: 'confirmed',
|
||||
qrImage: '',
|
||||
qrExpiresAt: '',
|
||||
qrUrl: '',
|
||||
bindGameAccount: account?.nickname || '',
|
||||
bindGameRole: account?.uid || '',
|
||||
bindGameRoleId: account?.uid || '',
|
||||
bindGameChannel: '微博',
|
||||
hasExistingBinding: true,
|
||||
rebindRequested: false,
|
||||
|
||||
Reference in New Issue
Block a user