feat(半自动履约): 补齐微博游戏角色绑定流程

This commit is contained in:
yml
2026-11-18 15:45:13 +08:00
parent f76b9c452d
commit 623a4ffa05
21 changed files with 1366 additions and 156 deletions
@@ -0,0 +1,61 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { buildServerZone, compareBindingIdentity, resolveServerZone } from './binding-identity.js'
import { getAccountBindingPolicy } from './platform-policy.js'
test('平台能力声明统一描述角色查询、确认与换绑方式', () => {
const huya = getAccountBindingPolicy('huya')
assert.equal(huya.bindingKind, 'game_role')
assert.equal(huya.queryOwner, 'order_site')
assert.equal(huya.confirmationMode, 'customer_match')
assert.equal(huya.rebindMode, 'platform_confirm')
const douyu = getAccountBindingPolicy('douyu')
assert.equal(douyu.bindingKind, 'game_role')
assert.equal(douyu.queryOwner, 'live_hub')
assert.deepEqual(douyu.requiredFields, ['roleName', 'serverZone'])
const weibo = getAccountBindingPolicy('weibo')
assert.equal(weibo.bindingKind, 'game_role')
assert.equal(weibo.bindingRequired, true)
assert.equal(weibo.requiresCustomerProfile, false)
assert.equal(weibo.confirmationMode, 'platform_verified')
assert.equal(weibo.rebindMode, 'rescan_qr')
assert.deepEqual(weibo.requiredFields, ['roleName'])
})
test('区服规范化为同一口径', () => {
assert.equal(resolveServerZone('苹果(iOS) · QQ'), '苹果Q区')
assert.equal(resolveServerZone('微信 安卓(android)'), '安卓V区')
assert.equal(buildServerZone('ios', 'wechat'), '苹果V区')
assert.equal(buildServerZone('android', 'qq'), '安卓Q区')
})
test('公共身份比对明确区分 match、mismatch 与 unknown', () => {
const fields = ['roleName', 'roleId', 'serverZone'] as const
assert.equal(
compareBindingIdentity({
requiredFields: fields,
customer: { roleName: '角色 A', roleId: '1001', serverZone: '安卓Q区' },
platform: { roleName: '角色A', roleId: '1001', serverZone: '安卓Q区' },
}).verdict,
'match',
)
assert.equal(
compareBindingIdentity({
requiredFields: fields,
customer: { roleName: '角色A', roleId: '1001', serverZone: '安卓Q区' },
platform: { roleName: '角色B', roleId: '1001', serverZone: '安卓Q区' },
}).verdict,
'mismatch',
)
assert.equal(
compareBindingIdentity({
requiredFields: fields,
customer: { roleName: '角色A', roleId: '', serverZone: '安卓Q区' },
platform: { roleName: '角色A', roleId: '1001', serverZone: '安卓Q区' },
}).verdict,
'unknown',
)
})
@@ -0,0 +1,68 @@
import type { AccountBindingField } from './platform-policy.js'
export type BindingFieldValues = Partial<Record<AccountBindingField, string>>
export type BindingIdentityComparison = {
verdict: 'match' | 'mismatch' | 'unknown'
missing: AccountBindingField[]
mismatched: AccountBindingField[]
customer: BindingFieldValues
platform: BindingFieldValues
}
export function normalizeBindingRoleName(value: unknown) {
return String(value ?? '')
.replace(/\s+/g, '')
.toLowerCase()
}
export function normalizeBindingField(field: AccountBindingField, value: unknown): string {
const text = String(value ?? '').trim()
if (field === 'roleName') return normalizeBindingRoleName(text)
return text.toLowerCase()
}
export function resolveServerZone(input: unknown) {
const text = String(input ?? '')
.replace(/\s+/g, '')
.toLowerCase()
if (!text) return ''
const system = /苹果|ios/.test(text) ? '苹果' : /安卓|android/.test(text) ? '安卓' : ''
const login = /qq|q区|手q/.test(text) ? 'Q' : /微信|wechat|v区/.test(text) ? 'V' : ''
return system && login ? `${system}${login}区` : ''
}
export function buildServerZone(system: unknown, loginChannel: unknown) {
const systemText = String(system ?? '')
.trim()
.toLowerCase()
const loginText = String(loginChannel ?? '')
.trim()
.toLowerCase()
return resolveServerZone(`${systemText} ${loginText}`)
}
export function compareBindingIdentity(input: {
requiredFields: readonly AccountBindingField[]
customer: BindingFieldValues
platform: BindingFieldValues
}): BindingIdentityComparison {
const missing: AccountBindingField[] = []
const mismatched: AccountBindingField[] = []
for (const field of input.requiredFields) {
const customer = normalizeBindingField(field, input.customer[field])
const platform = normalizeBindingField(field, input.platform[field])
if (!customer || !platform) {
missing.push(field)
continue
}
if (customer !== platform) mismatched.push(field)
}
return {
verdict: missing.length > 0 ? 'unknown' : mismatched.length > 0 ? 'mismatch' : 'match',
missing,
mismatched,
customer: input.customer,
platform: input.platform,
}
}
@@ -0,0 +1,66 @@
export type AccountBindingPlatform = 'huya' | 'douyu' | 'weibo'
export type AccountBindingQueryOwner = 'order_site' | 'live_hub'
export type AccountBindingKind = 'game_role' | 'account_authorization'
export type AccountBindingField = 'roleName' | 'roleId' | 'serverZone' | 'loginChannel'
export type AccountBindingConfirmationMode = 'customer_match' | 'platform_verified'
export type AccountBindingRebindMode = 'platform_confirm' | 'rescan_qr'
export type AccountBindingPolicy = {
platform: AccountBindingPlatform
platformLabel: string
bindingKind: AccountBindingKind
bindingRequired: boolean
requiresCustomerProfile: boolean
supportsRebind: boolean
queryOwner: AccountBindingQueryOwner
requiredFields: readonly AccountBindingField[]
confirmationMode: AccountBindingConfirmationMode
rebindMode: AccountBindingRebindMode
defaultTargetUrl: string
}
const POLICIES: Record<AccountBindingPlatform, AccountBindingPolicy> = {
huya: {
platform: 'huya',
platformLabel: '虎牙',
bindingKind: 'game_role',
bindingRequired: true,
requiresCustomerProfile: true,
supportsRebind: true,
queryOwner: 'order_site',
requiredFields: ['roleName', 'roleId', 'serverZone'],
confirmationMode: 'customer_match',
rebindMode: 'platform_confirm',
defaultTargetUrl: 'https://www.huya.com/',
},
douyu: {
platform: 'douyu',
platformLabel: '斗鱼',
bindingKind: 'game_role',
bindingRequired: true,
requiresCustomerProfile: true,
supportsRebind: true,
queryOwner: 'live_hub',
requiredFields: ['roleName', 'serverZone'],
confirmationMode: 'customer_match',
rebindMode: 'platform_confirm',
defaultTargetUrl: 'https://www.douyu.com/',
},
weibo: {
platform: 'weibo',
platformLabel: '微博',
bindingKind: 'game_role',
bindingRequired: true,
requiresCustomerProfile: false,
supportsRebind: true,
queryOwner: 'order_site',
requiredFields: ['roleName'],
confirmationMode: 'platform_verified',
rebindMode: 'rescan_qr',
defaultTargetUrl: 'https://weibo.com/',
},
}
export function getAccountBindingPolicy(platform: AccountBindingPlatform) {
return POLICIES[platform]
}
@@ -364,14 +364,14 @@ export async function createSemiAutoMock(
const connectorMode =
platform === 'weibo' ? 'embedded' : normalizeMockSemiAutoConnectorMode(input.connectorMode)
const pageTitle = String(
input.pageTitle || (platform === 'weibo' ? '微博发帖授权测试' : '虎牙账号授权测试'),
input.pageTitle || (platform === 'weibo' ? '微博角色绑定测试' : '虎牙账号授权测试'),
)
.trim()
.slice(0, 60)
const pageDescription = String(
input.pageDescription ||
(platform === 'weibo'
? '开发 Mock:完成微博登录即视为授权,客服在后台完成发帖履约。'
? '开发 Mock:完成微博登录并绑定游戏角色后,客服在后台完成履约。'
: '开发 Mock:完成登录和角色绑定后,客服在后台完成履约。'),
)
.trim()
@@ -532,7 +532,7 @@ export async function createSemiAutoMock(
'完成履约仍走真实确认流程,会写入成本快照和财务确认。',
'微博使用内置 Connector:短信验证码会真实发送到客户手机号;扫码登录需在微博 App 中确认。',
'后台领取任务后生成 weibo-ticket-* 浏览器票据,扩展消费票据后写入微博 Cookie。',
'微博登录成功即视为授权完成,任务会直接进入等待客服处理。',
'微博登录后读取平台游戏角色;未绑定时需客户微信/QQ 扫码,绑定确认后才进入等待客服处理。',
]
: [
'完成履约仍走真实确认流程,会写入成本快照和财务确认。',
@@ -791,7 +791,7 @@ export async function createSemiAutoIntegrationMock(
const shopId = 'dev-integration-shop'
const externalSkuCode = `INTEGRATION-${suffix}`
const pageTitle = String(
input.pageTitle || (platform === 'weibo' ? '微博账号登录授权' : '虎牙账号登录授权'),
input.pageTitle || (platform === 'weibo' ? '微博账号登录与角色绑定' : '虎牙账号登录授权'),
)
.trim()
.slice(0, 60)
@@ -5,6 +5,12 @@ import { publishRealtimeEvent } from '../realtime/realtime-event-service.js'
import { nowIso } from '../../utils/time.js'
import { createHttpError } from '../../utils/http.js'
import { logWarn } from '../../utils/logger.js'
import {
buildServerZone,
compareBindingIdentity,
resolveServerZone,
} from '../account-binding/binding-identity.js'
import { getAccountBindingPolicy } from '../account-binding/platform-policy.js'
type DouyuTaskRow = {
id: number
@@ -358,33 +364,32 @@ async function loadTask(taskId: number) {
return task
}
function normalizeText(value: unknown) {
return String(value || '')
.replace(/\s+/g, '')
.toLowerCase()
}
export function compareCustomerRole(task: DouyuTaskRow, live: LiveBindingState) {
const comparison = compareBindingIdentity({
requiredFields: getAccountBindingPolicy('douyu').requiredFields,
customer: {
roleName: task.customer_role_name,
serverZone: buildServerZone(task.customer_system, task.customer_platform),
},
platform: {
roleName: live.roleName,
serverZone: resolveServerZone(`${live.areaName} ${live.platName}`),
},
})
const roleMatched =
Boolean(task.customer_role_name && live.roleName) &&
normalizeText(task.customer_role_name) === normalizeText(live.roleName)
const liveParts = new Set([normalizeText(live.areaName), normalizeText(live.platName)])
const expected: string[] = []
if (task.customer_platform === 'wechat') expected.push('微信')
if (task.customer_platform === 'qq') expected.push('qq', '手q')
if (task.customer_system === 'ios') expected.push('苹果', 'ios')
if (task.customer_system === 'android') expected.push('安卓', 'android')
const channelMatched = expected.every((item) =>
[...liveParts].some((part) => part.includes(item) || item.includes(part)),
)
!comparison.missing.includes('roleName') && !comparison.mismatched.includes('roleName')
const channelMatched =
!comparison.missing.includes('serverZone') && !comparison.mismatched.includes('serverZone')
return {
matched: roleMatched && channelMatched,
matched: comparison.verdict === 'match',
roleMatched,
channelMatched,
message:
roleMatched && channelMatched
comparison.verdict === 'match'
? '客户资料与平台识别角色一致'
: '客户资料与平台识别角色不一致,请修改资料或联系客服',
: comparison.verdict === 'unknown'
? '客户资料或平台角色信息不完整,请修改资料或联系客服'
: '客户资料与平台识别角色不一致,请修改资料或联系客服',
}
}
@@ -31,6 +31,7 @@ import {
} from './weibo-connector-client.js'
import { WEIBO_TICKET_PREFIX } from './weibo-native/weibo-native-connector.js'
import { querySemiAutoTraces } from './semi-auto-trace.js'
import { getAccountBindingPolicy } from '../account-binding/platform-policy.js'
import {
appendTaskEvent,
compareBindingRole,
@@ -252,9 +253,7 @@ export async function exportAdminSemiAutoCredential(taskIdInput: unknown) {
).trim()
const targetUrl = /^https:\/\//i.test(configuredTarget)
? configuredTarget
: credential.platform === 'weibo'
? 'https://weibo.com/'
: 'https://www.huya.com/'
: getAccountBindingPolicy(credential.platform).defaultTargetUrl
const cookieHeader = targetUrl
? buildSemiAutoCredentialCookieHeader(credential.cookies, targetUrl)
: ''
@@ -357,8 +356,10 @@ export async function reconcileSemiAutoTaskStates(limitInput = 100) {
task = await loadTask(task.id)
updated += 1
}
const bindingPolicy = getAccountBindingPolicy(task.platform)
if (
task.platform === 'huya' &&
bindingPolicy.bindingRequired &&
bindingPolicy.queryOwner === 'order_site' &&
task.login_status === 'authenticated' &&
['qr_pending', 'scanned', 'role_ready'].includes(task.binding_status)
) {
@@ -21,8 +21,10 @@ import {
loginWeiboSms,
revokeWeiboSession,
sendWeiboSmsCode,
startWeiboBinding,
} from './weibo-connector-client.js'
import { upsertSemiAutoCredentialWithClient } from './semi-auto-credential-service.js'
import { getAccountBindingPolicy } from '../account-binding/platform-policy.js'
import {
appendTaskEvent,
assertCustomerProfileReady,
@@ -42,6 +44,7 @@ import {
normalizeId,
normalizeOrderNo,
publishSemiAutoTaskRealtimeChange,
resetTaskForInvalidCredential,
resetTaskForCustomerLogin,
revokeSessionForTask,
TASK_SELECT,
@@ -137,7 +140,8 @@ export async function savePublicTaskProfile(
const orderNo = normalizeOrderNo(orderNoInput)
const taskId = normalizeId(taskIdInput)
const task = await loadTaskForOrder(orderNo, taskId)
if (task.platform !== 'huya') {
const bindingPolicy = getAccountBindingPolicy(task.platform)
if (!bindingPolicy.requiresCustomerProfile) {
throw createHttpError('当前平台不需要填写游戏角色', {
statusCode: 409,
errorCode: 'semi_auto_profile_not_supported',
@@ -224,6 +228,24 @@ function mapLoginUpdate(session: ConnectorLoginSession) {
}
}
async function syncWeiboBindingSnapshot(
task: TaskRow,
sessionId: string,
actorType: TaskActorType,
) {
try {
const binding = await getWeiboBinding(sessionId, task.connector_mode)
await updateBindingTask(task, binding, actorType)
return null
} catch (error) {
const resetTask = await resetTaskForInvalidCredential(task, error)
if (resetTask) {
return resetTask
}
throw error
}
}
export async function updateLoginTask(
task: TaskRow,
session: ConnectorLoginSession,
@@ -248,10 +270,11 @@ export async function updateLoginTask(
if (current.execution_status === 'completed' || current.execution_status === 'cancelled') {
return
}
// 虎牙登录成功还不算授权完成,必须等客户确认绑定角色;微博登录即授权。
// 登录成功只代表拿到账号 CK;必须等平台角色绑定事实确认后才进入客服处理。
const nextExecutionStatus: ExecutionStatus =
mapped.status === 'authenticated'
? current.platform === 'weibo' || current.binding_status === 'confirmed'
? !getAccountBindingPolicy(current.platform).bindingRequired ||
current.binding_status === 'confirmed'
? 'waiting_operator'
: 'waiting_customer'
: current.execution_status
@@ -305,6 +328,13 @@ export async function updateLoginTask(
})
}
})
if (mapped.status === 'authenticated' && task.platform === 'weibo') {
const resetTask = await syncWeiboBindingSnapshot(task, session.sessionId, actorType)
if (resetTask) {
publishSemiAutoTaskRealtimeChange(resetTask.id, resetTask.order_id)
return
}
}
publishSemiAutoTaskRealtimeChange(task.id, task.order_id)
}
@@ -429,11 +459,11 @@ export async function pollPublicLogin(orderNoInput: unknown, taskIdInput: unknow
export async function startPublicBinding(
orderNoInput: unknown,
taskIdInput: unknown,
input: { forceRebind?: unknown } = {},
input: { forceRebind?: unknown; channel?: unknown } = {},
) {
const orderNo = normalizeOrderNo(orderNoInput)
const taskId = normalizeId(taskIdInput)
const task = await loadTaskForOrder(orderNo, taskId)
const task = await ensureConnectorSessionForTask(await loadTaskForOrder(orderNo, taskId))
if (task.execution_status === 'completed' || task.execution_status === 'cancelled') {
throw createHttpError('当前订单已结束,不能重新绑定', {
statusCode: 409,
@@ -447,12 +477,21 @@ export async function startPublicBinding(
})
}
assertCustomerProfileReady(task)
const session =
task.platform === 'weibo'
? await getWeiboBinding(task.connector_session_id, task.connector_mode)
: await startHuyaBinding(task.connector_session_id, task.connector_mode, {
forceRebind: input.forceRebind === true,
})
let session: ConnectorBindingSession
try {
session =
task.platform === 'weibo'
? await startWeiboBinding(task.connector_session_id, task.connector_mode, {
channel: input.channel === 'qq' ? 'qq' : 'wx',
forceRebind: input.forceRebind === true,
})
: await startHuyaBinding(task.connector_session_id, task.connector_mode, {
forceRebind: input.forceRebind === true,
})
} catch (error) {
await resetTaskForInvalidCredential(task, error)
throw error
}
const binding = await updateBindingTask(task, session, 'customer')
const updated = await loadTask(task.id)
return { task: mapTask(updated), binding }
@@ -466,7 +505,12 @@ export async function resetPublicBinding(orderNoInput: unknown, taskIdInput: unk
const orderNo = normalizeOrderNo(orderNoInput)
const taskId = normalizeId(taskIdInput)
const task = await loadTaskForOrder(orderNo, taskId)
if (task.platform !== 'huya') {
const bindingPolicy = getAccountBindingPolicy(task.platform)
if (
!bindingPolicy.supportsRebind ||
bindingPolicy.confirmationMode !== 'customer_match' ||
bindingPolicy.rebindMode !== 'platform_confirm'
) {
throw createHttpError('当前平台不需要重置绑定状态', {
statusCode: 409,
errorCode: 'semi_auto_binding_reset_not_supported',
@@ -551,14 +595,21 @@ export async function resetPublicBinding(orderNoInput: unknown, taskIdInput: unk
export async function pollPublicBinding(orderNoInput: unknown, taskIdInput: unknown) {
const orderNo = normalizeOrderNo(orderNoInput)
const taskId = normalizeId(taskIdInput)
const task = await loadTaskForOrder(orderNo, taskId)
const task = await ensureConnectorSessionForTask(await loadTaskForOrder(orderNo, taskId))
if (task.execution_status === 'completed' || task.execution_status === 'cancelled') {
return { task: mapTask(task), binding: null }
}
if (!task.connector_session_id || task.login_status !== 'authenticated') {
return { task: mapTask(task), binding: null }
}
const session = await getBindingForTask(task, task.connector_session_id)
let session: ConnectorBindingSession
try {
session = await getBindingForTask(task, task.connector_session_id)
} catch (error) {
const resetTask = await resetTaskForInvalidCredential(task, error)
if (resetTask) return { task: mapTask(resetTask), binding: null }
throw error
}
const binding = await updateBindingTask(task, session, 'customer')
const updated = await loadTask(task.id)
return { task: mapTask(updated), binding }
@@ -571,7 +622,14 @@ export async function confirmPublicBinding(
) {
const orderNo = normalizeOrderNo(orderNoInput)
const taskId = normalizeId(taskIdInput)
const task = await loadTaskForOrder(orderNo, taskId)
const task = await ensureConnectorSessionForTask(await loadTaskForOrder(orderNo, taskId))
const bindingPolicy = getAccountBindingPolicy(task.platform)
if (bindingPolicy.confirmationMode !== 'customer_match') {
throw createHttpError('当前平台由平台事实直接确认绑定,无需客户提交', {
statusCode: 409,
errorCode: 'semi_auto_binding_confirm_not_supported',
})
}
if (task.execution_status === 'completed' || task.execution_status === 'cancelled') {
throw createHttpError('当前订单已结束,不能确认绑定', {
statusCode: 409,
@@ -580,7 +638,7 @@ export async function confirmPublicBinding(
}
if (
!task.connector_session_id ||
(task.platform !== 'weibo' && task.binding_status !== 'role_ready')
(bindingPolicy.bindingRequired && task.binding_status !== 'role_ready')
) {
throw createHttpError('当前没有待确认的绑定角色', {
statusCode: 409,
@@ -590,7 +648,7 @@ export async function confirmPublicBinding(
assertCustomerProfileReady(task)
// 确认绑定是纯本地动作:虎牙侧只读内存快照,不再触发角色查询或换绑提交。
const session =
task.platform === 'huya'
bindingPolicy.bindingRequired && bindingPolicy.queryOwner === 'order_site'
? await getHuyaBindingSnapshot(task.connector_session_id, task.connector_mode)
: await getBindingForTask(task, task.connector_session_id)
const comparison = compareBindingRole(task, session)
@@ -644,13 +702,19 @@ export async function submitPublicRebind(orderNoInput: unknown, taskIdInput: unk
const orderNo = normalizeOrderNo(orderNoInput)
const taskId = normalizeId(taskIdInput)
const task = await loadTaskForOrder(orderNo, taskId)
const bindingPolicy = getAccountBindingPolicy(task.platform)
if (task.execution_status === 'completed' || task.execution_status === 'cancelled') {
throw createHttpError('当前订单已结束,不能提交换绑', {
statusCode: 409,
errorCode: 'semi_auto_task_closed',
})
}
if (task.platform !== 'huya') {
if (
!bindingPolicy.supportsRebind ||
bindingPolicy.confirmationMode !== 'customer_match' ||
bindingPolicy.rebindMode !== 'platform_confirm' ||
bindingPolicy.queryOwner !== 'order_site'
) {
throw createHttpError('当前平台不需要换绑游戏角色', {
statusCode: 409,
errorCode: 'semi_auto_rebind_not_supported',
@@ -975,7 +1039,7 @@ export async function loginPublicWeiboSms(
})
}
const nextExecutionStatus: ExecutionStatus = 'waiting_operator'
const nextExecutionStatus: ExecutionStatus = 'waiting_customer'
await withTransaction(async (client) => {
const credentialId = storedCredential
? await upsertSemiAutoCredentialWithClient(client, {
@@ -990,7 +1054,7 @@ export async function loginPublicWeiboSms(
SET connector_session_id = $2,
credential_id = COALESCE($5, credential_id),
login_status = 'authenticated',
execution_status = 'waiting_operator',
execution_status = $6,
huya_uid = CASE WHEN $3 <> '' THEN $3 ELSE huya_uid END,
platform_nickname = CASE WHEN $4 <> '' THEN $4 ELSE platform_nickname END,
auth_started_at = COALESCE(auth_started_at, NOW()),
@@ -999,7 +1063,7 @@ export async function loginPublicWeiboSms(
updated_at = NOW()
WHERE id = $1
`,
[task.id, sessionId, mapped.uid, mapped.nickname, credentialId],
[task.id, sessionId, mapped.uid, mapped.nickname, credentialId, nextExecutionStatus],
)
await appendTaskEvent(client, task.id, {
eventType: 'login_status_changed',
@@ -1015,6 +1079,13 @@ export async function loginPublicWeiboSms(
if (previousSessionId && previousSessionId !== sessionId) {
await revokeWeiboSession(previousSessionId, task.connector_mode).catch(() => undefined)
}
const resetTask = await syncWeiboBindingSnapshot(task, sessionId, 'customer')
if (resetTask) {
throw createHttpError('微博登录状态已失效,请重新登录', {
statusCode: 409,
errorCode: 'weibo_credential_invalid',
})
}
publishSemiAutoTaskRealtimeChange(task.id, task.order_id)
const updated = await loadTask(task.id)
return {
@@ -63,6 +63,8 @@ import {
} from './semi-auto-credential-service.js'
import { querySemiAutoTraces } from './semi-auto-trace.js'
import { isNumericBindingRoleId } from './binding-role-id.js'
import { compareBindingIdentity, resolveServerZone } from '../account-binding/binding-identity.js'
import { getAccountBindingPolicy } from '../account-binding/platform-policy.js'
const SEMI_AUTO_PLATFORMS = new Set(['huya', 'weibo'])
const ADMIN_LIST_BACKFILL_INTERVAL_MS = 15_000
@@ -227,6 +229,7 @@ export function hasCustomerProfile(
}
export function displayStatus(task: TaskRow) {
const bindingPolicy = getAccountBindingPolicy(task.platform)
const status = (
key: string,
label: string,
@@ -249,11 +252,11 @@ export function displayStatus(task: TaskRow) {
return status('processing', '处理中', 'operator', '客服继续履约')
}
if (task.login_status === 'authenticated') {
// 虎牙需要客户确认绑定角色后才算授权完成;微博登录即授权。
if (task.platform === 'weibo' || task.binding_status === 'confirmed') {
// 微博和虎牙都必须在平台侧完成角色绑定后才能进入客服处理。
if (!bindingPolicy.bindingRequired || task.binding_status === 'confirmed') {
return status('waiting_operator', '等待客服处理', 'operator', '客服领取并履约')
}
if (task.platform === 'huya' && !hasCustomerProfile(task)) {
if (bindingPolicy.requiresCustomerProfile && !hasCustomerProfile(task)) {
return status('waiting_profile', '待客户填写资料', 'customer', '客户填写区服、编号和角色名')
}
if (task.binding_status === 'role_ready') {
@@ -277,14 +280,24 @@ export function displayStatus(task: TaskRow) {
}
export function mapTask(task: TaskRow) {
const bindingPolicy = getAccountBindingPolicy(task.platform)
return {
id: Number(task.id),
orderId: Number(task.order_id),
orderItemId: Number(task.order_item_id),
fulfillmentId: task.fulfillment_id ? Number(task.fulfillment_id) : null,
platform: task.platform,
platformLabel:
task.platform === 'huya' ? '虎牙' : task.platform === 'weibo' ? '微博' : task.platform,
platformLabel: bindingPolicy.platformLabel,
bindingPolicy: {
bindingKind: bindingPolicy.bindingKind,
bindingRequired: bindingPolicy.bindingRequired,
requiresCustomerProfile: bindingPolicy.requiresCustomerProfile,
supportsRebind: bindingPolicy.supportsRebind,
queryOwner: bindingPolicy.queryOwner,
requiredFields: bindingPolicy.requiredFields,
confirmationMode: bindingPolicy.confirmationMode,
rebindMode: bindingPolicy.rebindMode,
},
loginStatus: task.login_status,
bindingStatus: task.binding_status,
executionStatus: task.execution_status,
@@ -489,7 +502,7 @@ export function assertHuyaTask(task: TaskRow) {
* 进入绑定/确认/换绑前必须已有完整三项资料。
*/
export function assertCustomerProfileReady(task: TaskRow) {
if (task.platform !== 'huya') return
if (!getAccountBindingPolicy(task.platform).requiresCustomerProfile) return
if (!hasCustomerProfile(task)) {
throw createHttpError('请先提交游戏角色资料', {
statusCode: 409,
@@ -603,6 +616,22 @@ export async function resetTaskForCustomerLogin(
return loadTask(task.id)
}
export async function resetTaskForInvalidCredential(task: TaskRow, error: unknown) {
if (task.platform !== 'weibo' || !isInvalidCredentialError(error)) return null
await markSemiAutoCredentialCheck(task.credential_id, {
status: 'invalid',
error: error instanceof Error ? error.message : String(error),
}).catch(() => undefined)
if (task.connector_session_id) {
await revokeSessionForTask(task, task.connector_session_id).catch(() => undefined)
}
return resetTaskForCustomerLogin(task, {
actorType: 'connector',
reason: '微博登录凭证已失效,需客户重新登录',
eventType: 'credential_invalidated',
})
}
export async function ensureConnectorSessionForTask(task: TaskRow): Promise<TaskRow> {
if (task.execution_status === 'completed' || task.execution_status === 'cancelled') return task
if (task.connector_session_id) {
@@ -835,38 +864,12 @@ export type BindingRoleComparison = {
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区。
* 解析不出平台或登录方式时返回空串,比对时按「平台区服缺失」处理(判 unknown)。
*/
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}区` : ''
return resolveServerZone(channel)
}
/**
@@ -888,7 +891,7 @@ export function compareBindingRole(
): 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 customerZone = resolveServerZone(task.customer_game_server_zone)
const boundRoleName = String(binding.bindGameRole || '').trim()
const rawBoundRoleId = String(binding.bindGameRoleId || '').trim()
// 虎牙 gameRole.roleId 是 40 位加密串,客户填写的是数值游戏编号;
@@ -909,34 +912,43 @@ export function compareBindingRole(
boundZone,
}
// 客户确认的口径:区服、角色名、角色 ID 三项必须全部存在且一致。
const missing: string[] = []
if (!customerRoleId) missing.push('客户游戏编号')
if (!customerRoleName) missing.push('客户角色名')
if (!customerZone) missing.push('客户区服')
if (!boundRoleId || !isNumericBindingRoleId(boundRoleId)) missing.push('平台可核对角色ID')
if (!boundRoleName) missing.push('平台角色名')
if (!boundZone) missing.push('平台区服')
if (missing.length > 0) {
const verifiedBoundRoleId = isNumericBindingRoleId(boundRoleId) ? boundRoleId : ''
const comparison = compareBindingIdentity({
requiredFields: getAccountBindingPolicy('huya').requiredFields,
customer: {
roleName: customerRoleName,
roleId: customerRoleId,
serverZone: customerZone,
},
platform: {
roleName: boundRoleName,
roleId: verifiedBoundRoleId,
serverZone: boundZone,
},
})
if (comparison.verdict === 'unknown') {
const missing: string[] = []
if (!customerRoleId) missing.push('客户游戏编号')
if (!customerRoleName) missing.push('客户角色名')
if (!customerZone) missing.push('客户区服')
if (!verifiedBoundRoleId) missing.push('平台可核对角色ID')
if (!boundRoleName) missing.push('平台角色名')
if (!boundZone) missing.push('平台区服')
return {
...base,
verdict: 'unknown',
message: `缺少${missing.join('、')},无法核对绑定角色,请联系客服`,
}
}
if (customerRoleId !== boundRoleId) {
if (comparison.mismatched.includes('roleId')) {
return { ...base, verdict: 'mismatch', message: '两侧角色 ID 不一致,无法提交平台绑定' }
}
if (normalizeRoleText(customerRoleName) !== normalizeRoleText(boundRoleName)) {
if (comparison.mismatched.includes('roleName')) {
return { ...base, verdict: 'mismatch', message: '两侧角色名称不一致,无法提交平台绑定' }
}
if (customerZone !== boundZone) {
if (comparison.mismatched.includes('serverZone')) {
return { ...base, verdict: 'mismatch', message: '两侧区服不一致,无法提交平台绑定' }
}
return {
...base,
verdict: 'match',
@@ -986,10 +998,24 @@ export async function updateBindingTask(
const mapped = mapBindingUpdate(session)
const roleIdVerified = isNumericBindingRoleId(mapped.bindGameRoleId)
const requiresSupport =
(Boolean(mapped.bindGameRole) || mapped.hasExistingBinding === true) && !roleIdVerified
getAccountBindingPolicy(task.platform).requiresCustomerProfile &&
(Boolean(mapped.bindGameRole) || mapped.hasExistingBinding === true) &&
!roleIdVerified
const comparison = await withTransaction(async (client) => {
const current = await loadTaskForUpdateWithClient(client, task.id)
const currentComparison = compareBindingRole(current, mapped)
const bindingPolicy = getAccountBindingPolicy(current.platform)
const currentComparison: BindingRoleComparison = bindingPolicy.requiresCustomerProfile
? compareBindingRole(current, mapped)
: {
verdict: 'match',
customerRoleName: '',
customerRoleId: '',
customerZone: '',
boundRoleName: mapped.bindGameRole,
boundRoleId: mapped.bindGameRoleId,
boundZone: mapped.bindGameChannel,
message: '平台角色绑定状态已确认',
}
if (current.execution_status === 'completed' || current.execution_status === 'cancelled') {
return currentComparison
}
@@ -1003,6 +1029,7 @@ export async function updateBindingTask(
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,
binding_started_at = CASE WHEN $2 = 'qr_pending' THEN COALESCE(binding_started_at, NOW()) ELSE binding_started_at END,
bound_at = CASE WHEN $2 IN ('role_ready', 'confirmed') THEN COALESCE(bound_at, NOW()) ELSE bound_at END,
execution_status = $6,
last_error = CASE WHEN $2 IN ('failed', 'expired') THEN $7 ELSE '' END,
@@ -748,6 +748,104 @@ test(
},
)
test(
'微博平台角色绑定事实收敛为等待客服处理',
{ skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false },
async () => {
process.env.DATABASE_URL = TEST_DATABASE_URL
process.env.ENABLE_DEV_MOCK = '1'
const { closeDb, query, withTransaction } = await import('../../db/client.js')
const { createSemiAutoIntegrationMock } = await import('../dev-mock/dev-mock-service.js')
const { loadTask, updateBindingTask } = await import('./semi-auto-task-core.js')
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
const orderNo = `IT-WEIBO-BINDING-${suffix}`
let orderId = 0
let configId = 0
let mappingId = 0
try {
const result = await createSemiAutoIntegrationMock({
platform: 'weibo',
orderNo,
skuName: `微博绑定真实链路-${suffix}`,
quantity: 1,
connectorMode: 'embedded',
})
orderId = result.orderId
configId = result.configId
mappingId = result.mappingId
assert.equal(result.semiAutoPlatform, 'weibo')
assert.ok(result.taskId > 0)
await query(
`
UPDATE semi_auto_tasks
SET connector_session_id = $2,
login_status = 'authenticated',
execution_status = 'waiting_customer',
authenticated_at = NOW(),
updated_at = NOW()
WHERE id = $1
`,
[result.taskId, `it-weibo-session-${suffix}`],
)
const task = await loadTask(result.taskId)
const binding = await updateBindingTask(
task,
{
sessionId: `it-weibo-session-${suffix}`,
status: 'confirmed',
qrImage: '',
qrExpiresAt: '',
qrUrl: '',
bindGameAccount: '集成测试微博',
bindGameRole: '微博游戏角色',
bindGameRoleId: '',
bindGameChannel: '微信',
hasExistingBinding: true,
rebindRequested: false,
rebindCooldownDays: 0,
nextRebindAt: '',
message: '微博账号已绑定角色',
},
'connector',
)
assert.equal(binding.status, 'confirmed')
assert.equal(binding.comparison.verdict, 'match')
const stored = await query<{
binding_status: string
execution_status: string
bind_game_role: string
bind_game_channel: string
}>(
`SELECT binding_status, execution_status, bind_game_role, bind_game_channel
FROM semi_auto_tasks WHERE id = $1`,
[result.taskId],
)
assert.equal(stored.rows[0]?.binding_status, 'confirmed')
assert.equal(stored.rows[0]?.execution_status, 'waiting_operator')
assert.equal(stored.rows[0]?.bind_game_role, '微博游戏角色')
assert.equal(stored.rows[0]?.bind_game_channel, '微信')
} finally {
await withTransaction(async (client) => {
await client.query("SET LOCAL session_replication_role = 'replica'")
if (configId > 0) {
await client.query('DELETE FROM manual_fulfillment_configs WHERE id = $1', [configId])
}
if (orderId > 0) {
await client.query('DELETE FROM order_source_snapshots WHERE order_id = $1', [orderId])
await client.query('DELETE FROM orders WHERE id = $1', [orderId])
}
if (mappingId > 0) {
await client.query('DELETE FROM internal_sku_mappings WHERE id = $1', [mappingId])
}
})
delete process.env.ENABLE_DEV_MOCK
await closeDb()
}
},
)
test(
'开发 Mock 可显式选择内置 Mock Connector',
{ skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false },
@@ -111,6 +111,15 @@ export async function getWeiboBinding(
return weiboNativeConnector.getBinding(sessionId)
}
export async function startWeiboBinding(
sessionId: string,
mode: SemiAutoConnectorMode = 'embedded',
options: { channel?: 'wx' | 'qq'; forceRebind?: boolean } = {},
): Promise<ConnectorBindingSession> {
assertEmbedded(mode)
return weiboNativeConnector.startBinding(sessionId, options)
}
export async function createWeiboBrowserTicket(
input: { sessionId: string; targetUrl?: string },
mode: SemiAutoConnectorMode = 'embedded',
@@ -24,6 +24,8 @@ import type {
const PASSPORT_BASE = 'https://passport.weibo.com'
const WEIBO_BASE = 'https://weibo.com'
const WEIBO_VIPCLUB_HOME = 'https://vipclub.e.weibo.com/aj/mall/home'
const WEIBO_LIVELINK_QRCODE = 'https://livelinkbind.game.qq.com/api/qrcode/getMiniAppQrcode'
const WEIBO_RETURN_URL = 'https://weibo.com/'
const WEIBO_LOGIN_URL =
`https://weibo.com/newlogin?tabtype=weibo&gid=102803&openLoginLayer=0` +
@@ -35,6 +37,9 @@ const SIGNIN_REFERER =
const PC_UA =
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' +
'Chrome/155.0.0.0 Safari/537.36'
const WEIBO_MOBILE_UA =
'Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) ' +
'AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Weibo'
const LOGIN_QR_TTL_MS = 5 * 60 * 1000
const CREDENTIAL_TTL_MS = 24 * 60 * 60 * 1000
@@ -43,6 +48,8 @@ const SMS_COOKIE_TTL_MS = 10 * 60 * 1000
const COUNTRY_CODE_TTL_MS = 60 * 60 * 1000
const MAX_SESSIONS = 200
const TICKET_PREFIX = 'weibo-ticket-'
const WEIBO_BINDING_QR_TTL_MS = 10 * 60 * 1000
const WEIBO_AUTH_ERROR_CODES = new Set([100002, 100004, 400000, 400002])
export const WEIBO_YIDUN_CAPTCHA_ID = '7cda0ba2785647ada4d6e946ddb2d465'
export type WeiboCountryCode = {
@@ -93,6 +100,29 @@ type WeiboAccount = {
avatar: string
}
type WeiboGameRole = {
isBound: boolean
roleName: string
canRebind: boolean
rebindRemainDays: number
bindUrl: string
}
type WeiboGameRoleError = {
code: string
message: string
}
type WeiboBindingQrState = {
channel: 'wx' | 'qq'
qrImage: string
qrUrl: string
token: string
expiresAtMs: number
rebindRequested: boolean
baselineRoleName: string
}
type WeiboTicket = {
ticket: string
targetUrl: string
@@ -307,6 +337,10 @@ type WeiboSession = {
message: string
cookies: WeiboCookieJar
account: WeiboAccount | null
gameRole: WeiboGameRole | null
gameRoleError: WeiboGameRoleError | null
bindingQr: WeiboBindingQrState | null
lastBindingChannel: 'wx' | 'qq' | ''
tickets: Map<string, WeiboTicket>
}
@@ -343,6 +377,55 @@ function iso(value: number): string {
return new Date(value).toISOString()
}
function weiboErrorCode(error: unknown): string {
return error && typeof error === 'object'
? String((error as { errorCode?: unknown }).errorCode || '').trim()
: ''
}
export function extractWeiboBindRawUrl(bindUrlInput: unknown): string {
const bindUrl = String(bindUrlInput || '').trim()
if (!bindUrl) {
throw createHttpError('微博未返回角色绑定链接', {
statusCode: 409,
errorCode: 'weibo_bind_url_missing',
})
}
let path = ''
try {
path = new URL(bindUrl).searchParams.get('path') || ''
} catch {
throw createHttpError('微博角色绑定链接格式错误', {
statusCode: 502,
errorCode: 'weibo_bind_url_invalid',
})
}
const marker = '/pages/gameAccountBind/index?'
const markerIndex = path.indexOf(marker)
if (markerIndex < 0) {
throw createHttpError('微博角色绑定链接缺少绑定页面参数', {
statusCode: 502,
errorCode: 'weibo_bind_url_invalid',
})
}
const rawUrl = path.slice(markerIndex + marker.length)
if (!rawUrl) {
throw createHttpError('微博角色绑定链接参数为空', {
statusCode: 502,
errorCode: 'weibo_bind_url_invalid',
})
}
return rawUrl
}
function weiboBindQrImageSrc(value: unknown): string {
const text = String(value || '').trim()
if (!text) return ''
if (/^(https?:\/\/|data:image\/)/i.test(text)) return text
const mime = text.startsWith('iVBOR') ? 'image/png' : 'image/jpeg'
return `data:${mime};base64,${text}`
}
function readSetCookie(headers: Headers): string[] {
const withGetSetCookie = headers as Headers & { getSetCookie?: () => string[] }
if (typeof withGetSetCookie.getSetCookie === 'function') {
@@ -412,6 +495,10 @@ export class WeiboNativeConnector {
message: '请使用微博 App 扫码登录',
cookies,
account: null,
gameRole: null,
gameRoleError: null,
bindingQr: null,
lastBindingChannel: '',
tickets: new Map(),
}
this.sessions.set(sessionId, session)
@@ -703,6 +790,10 @@ export class WeiboNativeConnector {
message: '微博登录成功',
cookies: state.cookies,
account: null,
gameRole: null,
gameRoleError: null,
bindingQr: null,
lastBindingChannel: '',
tickets: new Map(),
}
this.smsSessions.delete(stateKey)
@@ -719,6 +810,67 @@ export class WeiboNativeConnector {
errorCode: 'weibo_login_required',
})
}
try {
await this.refreshGameRole(session)
} catch (error) {
if (weiboErrorCode(error) === 'weibo_credential_invalid') throw error
return this.bindingView(session)
}
const role = session.gameRole
const qr = session.bindingQr
if (role?.isBound && qr && (!qr.rebindRequested || role.roleName !== qr.baselineRoleName)) {
session.bindingQr = null
}
return this.bindingView(session)
}
async startBinding(
sessionId: string,
options: { channel?: 'wx' | 'qq'; forceRebind?: boolean } = {},
): Promise<ConnectorBindingSession> {
const session = this.requireSession(sessionId)
if (session.status !== 'authenticated' || !session.account) {
throw createHttpError('微博账号尚未登录', {
statusCode: 409,
errorCode: 'weibo_login_required',
})
}
const channel = options.channel === 'qq' ? 'qq' : 'wx'
const role = await this.refreshGameRole(session)
if (role.isBound && !role.canRebind) {
session.bindingQr = null
const wait = role.rebindRemainDays > 0 ? `,还需等待 ${role.rebindRemainDays} 天` : ''
throw createHttpError(
`微博账号已绑定角色${role.roleName ? `「${role.roleName}」` : ''},当前不可换绑${wait}`,
{
statusCode: 409,
errorCode: 'weibo_rebind_cooldown',
},
)
}
if (role.isBound && options.forceRebind !== true) {
session.bindingQr = null
return this.bindingView(session)
}
if (!role.bindUrl) {
throw createHttpError('微博没有返回当前账号的角色绑定链接', {
statusCode: 409,
errorCode: 'weibo_bind_url_missing',
})
}
const qr = await this.generateBindQr(role.bindUrl, channel)
const nowMs = this.now()
session.bindingQr = {
channel,
qrImage: qr.image,
qrUrl: '',
token: qr.token,
expiresAtMs: nowMs + WEIBO_BINDING_QR_TTL_MS,
rebindRequested: role.isBound,
baselineRoleName: role.roleName,
}
session.lastBindingChannel = channel
session.message = '请使用微信或 QQ 扫码完成微博游戏角色绑定'
return this.bindingView(session)
}
@@ -845,6 +997,10 @@ export class WeiboNativeConnector {
...account,
nickname: account.nickname || String(input.nickname || ''),
},
gameRole: null,
gameRoleError: null,
bindingQr: null,
lastBindingChannel: '',
tickets: new Map(),
}
this.sessions.set(session.sessionId, session)
@@ -885,6 +1041,15 @@ export class WeiboNativeConnector {
}
session.status = 'authenticated'
session.message = '微博登录成功'
await this.refreshGameRole(session).catch((error) => {
session.gameRoleError = {
code: weiboErrorCode(error) || 'weibo_game_role_query_failed',
message: error instanceof Error ? error.message : String(error),
}
logWarn('[weibo/game-role]', '登录后读取微博角色绑定状态失败', {
error: error instanceof Error ? error.message : String(error),
})
})
}
private async followWithCookies(
@@ -917,6 +1082,134 @@ export class WeiboNativeConnector {
return { finalUrl: currentUrl, body }
}
private async refreshGameRole(session: WeiboSession): Promise<WeiboGameRole> {
if (session.status !== 'authenticated' || !session.account?.uid) {
throw createHttpError('微博账号尚未登录', {
statusCode: 409,
errorCode: 'weibo_login_required',
})
}
try {
const url = `${WEIBO_VIPCLUB_HOME}?F=&_t=${this.now()}`
const response = await this.fetchImpl(url, {
method: 'GET',
headers: {
'user-agent': WEIBO_MOBILE_UA,
accept: 'application/json, text/plain, */*',
referer: 'https://vipclub.e.weibo.com/game/homepage',
cookie: session.cookies.headerFor('https://vipclub.e.weibo.com/'),
},
signal: AbortSignal.timeout(this.timeoutMs),
})
session.cookies.addFromResponse(response.headers, response.url || url)
const payload = (await response.json().catch(() => null)) as {
code?: number
msg?: string
data?: {
game_role?: {
is_bound?: boolean
role_name?: string
can_rebind?: boolean
rebind_remain_days?: number
bind_url?: string
}
}
} | null
if (!response.ok) {
throw createHttpError(`微博角色信息查询失败:HTTP ${response.status}`, {
statusCode: 502,
errorCode: 'weibo_game_role_query_failed',
})
}
const code = Number(payload?.code)
if (WEIBO_AUTH_ERROR_CODES.has(code)) {
throw createHttpError(payload?.msg || '微博 CK 已失效,请重新登录', {
statusCode: 409,
errorCode: 'weibo_credential_invalid',
})
}
if (!payload || code !== 100000) {
throw createHttpError(payload?.msg || '微博角色信息查询失败', {
statusCode: 502,
errorCode: 'weibo_game_role_query_failed',
})
}
const role = payload.data?.game_role || {}
const gameRole: WeiboGameRole = {
isBound: role.is_bound === true,
roleName: String(role.role_name || '').trim(),
canRebind: role.can_rebind === true,
rebindRemainDays: Math.max(0, Math.trunc(Number(role.rebind_remain_days) || 0)),
bindUrl: String(role.bind_url || '').trim(),
}
session.gameRole = gameRole
session.gameRoleError = null
return gameRole
} catch (error) {
session.gameRoleError = {
code: weiboErrorCode(error) || 'weibo_game_role_query_failed',
message: error instanceof Error ? error.message : String(error),
}
throw error
}
}
private async generateBindQr(
bindUrl: string,
channel: 'wx' | 'qq',
): Promise<{ image: string; token: string }> {
const rawUrl = extractWeiboBindRawUrl(bindUrl)
const query = new URLSearchParams(rawUrl)
const livePlatId = String(query.get('livePlatId') || '')
const actId = String(query.get('actId') || '')
const fromId = String(query.get('fromId') || '').slice(0, 32)
if (!livePlatId || !actId) {
throw createHttpError('微博绑定链接缺少活动参数', {
statusCode: 502,
errorCode: 'weibo_bind_url_invalid',
})
}
const suffix = crypto.randomBytes(4).toString('hex')
const response = await this.fetchImpl(WEIBO_LIVELINK_QRCODE, {
method: 'POST',
headers: {
'content-type': 'application/json;charset=UTF-8',
accept: 'application/json, text/plain, */*',
origin: 'https://livelink.qq.com',
referer: 'https://livelink.qq.com/',
'gap-plat-id': livePlatId,
'gap-act-id': actId,
'gap-user-from': 'pc',
'gap-from-id': fromId,
'vulcan-acctype': 'auth_in_h5',
},
body: JSON.stringify({
queryString: `${rawUrl}&sessionId=${Date.now()}_${suffix}`,
accountType: channel,
}),
signal: AbortSignal.timeout(this.timeoutMs),
})
const payload = (await response.json().catch(() => null)) as {
iRet?: number
sMsg?: string
jData?: { qrcode?: string; qrcodeToken?: string }
} | null
if (!response.ok || Number(payload?.iRet) !== 0) {
throw createHttpError(payload?.sMsg || '微博绑定二维码生成失败', {
statusCode: 502,
errorCode: 'weibo_bind_qrcode_failed',
})
}
const image = weiboBindQrImageSrc(payload?.jData?.qrcode)
if (!image) {
throw createHttpError('微博绑定接口没有返回二维码', {
statusCode: 502,
errorCode: 'weibo_bind_qrcode_failed',
})
}
return { image, token: String(payload?.jData?.qrcodeToken || '') }
}
private async fetchHomePage(cookies: WeiboCookieJar): Promise<{ status: number; body: string }> {
try {
const response = await this.fetchImpl(`${WEIBO_BASE}/`, {
@@ -1071,19 +1364,48 @@ export class WeiboNativeConnector {
private bindingView(session: WeiboSession): ConnectorBindingSession {
const account = session.account
const role = session.gameRole
const qr = session.bindingQr
const qrActive = Boolean(qr && qr.expiresAtMs > this.now())
const status: ConnectorBindingSession['status'] = session.gameRoleError
? 'failed'
: qrActive
? 'qr_pending'
: qr
? 'expired'
: role?.isBound
? 'confirmed'
: 'not_started'
const cooldownDays = role?.isBound && !role.canRebind ? Math.max(0, role.rebindRemainDays) : 0
const channel = qr?.channel || session.lastBindingChannel
const channelLabel = channel === 'qq' ? 'QQ' : channel === 'wx' ? '微信' : '微博'
return {
sessionId: session.sessionId,
status: 'confirmed',
qrImage: '',
qrExpiresAt: '',
qrUrl: '',
status,
qrImage: qrActive ? qr?.qrImage || '' : '',
qrExpiresAt: qrActive ? iso(Number(qr?.expiresAtMs || 0)) : '',
qrUrl: qrActive ? qr?.qrUrl || '' : '',
bindGameAccount: account?.nickname || '',
bindGameRole: account?.uid || '',
bindGameRoleId: account?.uid || '',
bindGameChannel: '微博',
hasExistingBinding: true,
rebindRequested: false,
message: '微博账号已授权',
bindGameRole: role?.roleName || '',
bindGameRoleId: '',
bindGameChannel: channelLabel,
hasExistingBinding: role?.isBound === true,
rebindRequested: qr?.rebindRequested === true,
rebindCooldownDays: cooldownDays,
nextRebindAt: cooldownDays > 0 ? iso(this.now() + cooldownDays * 24 * 60 * 60 * 1000) : '',
message: session.gameRoleError
? session.gameRoleError.message
: qrActive
? qr?.rebindRequested
? '请扫码选择新的微博游戏角色'
: '请扫码完成微博游戏角色绑定'
: status === 'expired'
? '微博绑定二维码已过期,请重新获取'
: status === 'confirmed'
? `微博账号已绑定角色${role?.roleName ? `「${role.roleName}」` : ''}`
: role
? '微博账号尚未绑定游戏角色'
: session.message || '微博角色绑定状态尚未就绪',
}
}
@@ -1,10 +1,20 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { WEIBO_TICKET_PREFIX, WeiboNativeConnector } from './weibo-native-connector.js'
import {
extractWeiboBindRawUrl,
WEIBO_TICKET_PREFIX,
WeiboNativeConnector,
} from './weibo-native-connector.js'
type CapturedCall = { url: string; init: RequestInit }
const BIND_URL =
'sinaweibo://wbdiversion?username=gh_test&path=%2Fpages%2FgameAccountBind%2Findex' +
'%3FactId%3D16722%26code%3Dabc%252Bdef%253D%26gameId%3Dcjm' +
'%26livePlatId%3Dweiyouxi%26nonce%3Dabc123%26sig%3D0123456789abcdef' +
'%26t%3D1794046086%26v%3D2.0'
function jsonResponse(payload: unknown): Response {
return new Response(JSON.stringify(payload), {
status: 200,
@@ -129,9 +139,209 @@ function defaultHandler(url: string): Response {
},
})
}
if (url.startsWith('https://vipclub.e.weibo.com/aj/mall/home')) {
return jsonResponse({
code: 100000,
msg: 'success',
data: {
game_role: {
is_bound: false,
role_name: '',
can_rebind: true,
rebind_remain_days: 0,
bind_url: BIND_URL,
},
},
})
}
if (url === 'https://livelinkbind.game.qq.com/api/qrcode/getMiniAppQrcode') {
return jsonResponse({
iRet: 0,
sMsg: 'ok',
jData: {
qrcode: 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAAB',
qrcodeToken: 'bind-token-1',
},
})
}
return new Response('not found', { status: 404 })
}
async function loginWeiboSession(connector: WeiboNativeConnector) {
await connector.sendSmsCode({ taskId: 1, mobile: '13800138000' })
const { sessionId } = await connector.loginWithSms({
taskId: 1,
orderNo: 'MOCKWB1',
mobile: '13800138000',
code: '123456',
})
return sessionId
}
test('微博 bind_url 提取保留内层编码并拒绝错误路径', () => {
const raw = extractWeiboBindRawUrl(BIND_URL)
assert.ok(raw.startsWith('actId=16722&code=abc%2Bdef%3D'))
assert.equal(raw.includes('abc+def='), false)
assert.throws(
() => extractWeiboBindRawUrl('sinaweibo://wbdiversion?path=%2Fwrong'),
(error: { errorCode?: string }) => error.errorCode === 'weibo_bind_url_invalid',
)
})
test('微博未绑定角色时可生成微信和 QQ 绑定二维码', async () => {
const { fetchImpl, calls } = createFetchMock(defaultHandler)
const connector = new WeiboNativeConnector({ fetchImpl })
const sessionId = await loginWeiboSession(connector)
const wxBinding = await connector.startBinding(sessionId, { channel: 'wx' })
assert.equal(wxBinding.status, 'qr_pending')
assert.equal(wxBinding.bindGameChannel, '微信')
assert.match(wxBinding.qrImage, /^data:image\/png;base64,/)
const qqBinding = await connector.startBinding(sessionId, { channel: 'qq' })
assert.equal(qqBinding.status, 'qr_pending')
assert.equal(qqBinding.bindGameChannel, 'QQ')
const qrCalls = calls.filter(
(call) => call.url === 'https://livelinkbind.game.qq.com/api/qrcode/getMiniAppQrcode',
)
assert.equal(qrCalls.length, 2)
const wxBody = JSON.parse(String(qrCalls[0]?.init.body)) as {
accountType: string
queryString: string
}
const qqHeaders = qrCalls[1]?.init.headers as Record<string, string>
assert.equal(wxBody.accountType, 'wx')
assert.ok(wxBody.queryString.startsWith(`${extractWeiboBindRawUrl(BIND_URL)}&sessionId=`))
assert.equal(qqHeaders['gap-act-id'], '16722')
assert.equal(qqHeaders['gap-plat-id'], 'weiyouxi')
assert.equal(qqHeaders['vulcan-acctype'], 'auth_in_h5')
})
test('微博已绑定且不可换绑时返回冷却期错误', async () => {
const { fetchImpl } = createFetchMock((url) => {
if (url.startsWith('https://vipclub.e.weibo.com/aj/mall/home')) {
return jsonResponse({
code: 100000,
data: {
game_role: {
is_bound: true,
role_name: '已有角色',
can_rebind: false,
rebind_remain_days: 7,
bind_url: BIND_URL,
},
},
})
}
return defaultHandler(url)
})
const connector = new WeiboNativeConnector({ fetchImpl })
const sessionId = await loginWeiboSession(connector)
await assert.rejects(
() => connector.startBinding(sessionId, { channel: 'wx', forceRebind: true }),
(error: { errorCode?: string; message?: string }) => {
assert.equal(error.errorCode, 'weibo_rebind_cooldown')
assert.match(error.message || '', /还需等待 7 天/)
return true
},
)
})
test('微博已有角色时默认直接确认,强制换绑后按新角色名确认', async () => {
let roleName = '旧角色'
const { fetchImpl } = createFetchMock((url) => {
if (url.startsWith('https://vipclub.e.weibo.com/aj/mall/home')) {
return jsonResponse({
code: 100000,
data: {
game_role: {
is_bound: true,
role_name: roleName,
can_rebind: true,
rebind_remain_days: 0,
bind_url: BIND_URL,
},
},
})
}
return defaultHandler(url)
})
const connector = new WeiboNativeConnector({ fetchImpl })
const sessionId = await loginWeiboSession(connector)
const existing = await connector.startBinding(sessionId, { channel: 'wx' })
assert.equal(existing.status, 'confirmed')
assert.equal(existing.bindGameRole, '旧角色')
const rebind = await connector.startBinding(sessionId, {
channel: 'qq',
forceRebind: true,
})
assert.equal(rebind.status, 'qr_pending')
assert.equal(rebind.rebindRequested, true)
roleName = '新角色'
const confirmed = await connector.getBinding(sessionId)
assert.equal(confirmed.status, 'confirmed')
assert.equal(confirmed.bindGameRole, '新角色')
assert.equal(confirmed.qrImage, '')
})
test('微博角色查询遇到 CK 失效时向服务层抛出凭证错误', async () => {
let expired = false
const { fetchImpl } = createFetchMock((url) => {
if (url.startsWith('https://vipclub.e.weibo.com/aj/mall/home')) {
return jsonResponse(
expired
? { code: 400002, msg: '未登陆' }
: {
code: 100000,
data: {
game_role: {
is_bound: false,
role_name: '',
can_rebind: true,
rebind_remain_days: 0,
bind_url: BIND_URL,
},
},
},
)
}
return defaultHandler(url)
})
const connector = new WeiboNativeConnector({ fetchImpl })
const sessionId = await loginWeiboSession(connector)
expired = true
await assert.rejects(
() => connector.getBinding(sessionId),
(error: { errorCode?: string }) => error.errorCode === 'weibo_credential_invalid',
)
})
test('微博来联二维码失败时不生成虚假绑定状态', async () => {
const { fetchImpl } = createFetchMock((url) => {
if (url === 'https://livelinkbind.game.qq.com/api/qrcode/getMiniAppQrcode') {
return jsonResponse({ iRet: -1, sMsg: '刷新二维码频率过快,请间隔5秒后重试' })
}
return defaultHandler(url)
})
const connector = new WeiboNativeConnector({ fetchImpl })
const sessionId = await loginWeiboSession(connector)
await assert.rejects(
() => connector.startBinding(sessionId, { channel: 'wx' }),
(error: { errorCode?: string; message?: string }) => {
assert.equal(error.errorCode, 'weibo_bind_qrcode_failed')
assert.match(error.message || '', /间隔5秒/)
return true
},
)
})
test('微博二维码会话解析 qrid 并把图片转成 base64', async () => {
const { fetchImpl, calls } = createFetchMock(defaultHandler)
const connector = new WeiboNativeConnector({ fetchImpl })