8 Commits
Author SHA1 Message Date
zhaoxing c8ce273c30 style(semi-auto): 优化履约历史时间线与报文展示
顶部汇总当前状态;节点按操作结果命名并加来源/异常筛选;状态变化改为标签对比,原始详情折叠;报文改为请求/响应两栏并统一字段名称。
2026-11-16 17:53:33 +08:00
zhaoxing 08e753ec94 feat(semi-auto): 新增履约历史与全链路报文留痕
运营端历史抽屉展示状态流转与全链路报文:客户/运营接口入站 + 虎牙 WUP/livelink、外部 Connector 出站;轮询按状态变化采样,Cookie/Token/短信验证码不落库,报文保留 180 天。同步收敛登录/绑定事件,避免轮询重复写时间线。
2026-11-16 17:26:35 +08:00
zhaoxing f371cc2c8d feat(semi-auto): 首次绑定自动提交并由客户本地确认,统一客户页控件尺寸
1) 首次绑定(isBindAccount/isBindRole 任一为 0)扫码完成后自动调 confirmBindActAccount,新增 bindConfirmState/bindConfirmMessage,失败透出虎牙原文并提示重新扫码。

2) 确认绑定改为纯本地流转:不再调用 confirmBindActAccount,也不再重复查角色;换绑被虎牙拒绝时需 acceptExistingRole 二次确认「仍使用原角色」。新增 bindingSnapshot 只读快照。

3) 客户页资料收集去掉顶部大图,只保留温馨提示;输入框/选择器 48px、主按钮 52px、次级按钮 48px,登录/绑定/资料页统一。

4) 修正已确认/已过期/绑定失败状态仍显示「登录成功,请继续扫码绑定游戏角色」的横幅错误,改为按 bindingStatus 显式映射,确认后只保留「等待客服核实」卡片。
2026-11-16 16:31:56 +08:00
zhaoxing 64281aefb0 fix(semi-auto): 换绑失败卡透出虎牙原因与下次换绑时间,会话过期可返回登录
1) 下次换绑时间改按虎牙日界口径:changeBindTime 是绑定日次日 00:00,(日界 + changeBindDay - 1) 天;11-16 绑定 → 2026-11-23,与虎牙绑定页一致(原 +7 天会显示 11-24)。

2) 客户页换绑失败卡同时展示虎牙原文原因、预计下次可换绑时间与「每 7 个自然日可换绑 1 次」规则。

3) 绑定会话失效时给出整行「返回登录」入口;二维码加载失败可重试;告警标题统一为亮色不再黑字;提交类按钮统一 56px 蓝色主按钮。
2026-11-16 14:46:17 +08:00
zhaoxing ad59c87e13 fix(semi-auto): 扫码后主动提交换绑并透出虎牙失败原因 2026-11-16 14:00:17 +08:00
zhaoxing 5aa627a0ca fix(semi-auto): 换绑未生效原因与 7 天冷却提示 2026-11-16 13:30:26 +08:00
zhaoxing 19367bdfdf fix(semi-auto): 客户登录页刷新默认手机号登录
- 进入页面即使 login_status=qr_pending 也先展示手机号+验证码

- 点改用二维码登录才切到二维码页,页面底部可切回手机号登录
2026-11-16 11:07:47 +08:00
zhaoxing 8e1cbdba9f feat(semi-auto): 重构客户资料收集与虎牙绑定确认流程
- 客户资料页按设计稿重构,区服固定四项下拉,游戏编号/角色名校验

- 虎牙登录与绑定页统一深色样式,扫码页新增改用手机号登录

- 待确认角色 UID 改用 huyaUid,不再展示虎牙加密 roleId

- 绑定确认新增两侧角色比对,不一致禁止确认,会话过期引导重新登录

- 新增迁移 168/169 与角色绑定单测,脚本换行符固定为 LF
2026-11-15 21:57:31 +08:00
29 changed files with 5852 additions and 373 deletions
+4
View File
@@ -0,0 +1,4 @@
# 容器内 /bin/sh 直接执行的脚本必须是 LF。
# Windows 下 core.autocrlf=true 会把 checkout 出来的 .sh 转成 CRLF,
# 导致 `set: Illegal option -`,backend 容器反复重启。
*.sh text eol=lf
@@ -0,0 +1,14 @@
-- 168_semi_auto_binding_role_id.sql
--
-- 客户页角色绑定需要保存平台侧角色 ID:
-- 1. 虎牙 checkUserBindGameAccount 的 gameRole.roleId 即平台侧角色 ID;
-- 2. 客户工单资料里的游戏 ID(gameId / characterId)作为客户填写角色 ID;
-- 3. 两侧角色 ID 不一致时禁止确认绑定,只允许重新扫码或联系客服。
--
-- 该列只保存平台识别结果,不参与订单、资金等 A 级事实。
ALTER TABLE semi_auto_tasks
ADD COLUMN IF NOT EXISTS bind_game_role_id TEXT NOT NULL DEFAULT '';
COMMENT ON COLUMN semi_auto_tasks.bind_game_role_id IS
'平台侧游戏角色 ID(虎牙 gameRole.roleId),用于与客户填写角色比对';
@@ -0,0 +1,18 @@
-- 169_semi_auto_customer_profile.sql
--
-- 半自动订单不会生成 work_orders,客户资料页 /c/<订单号> 是唯一入口:
-- 1. 客户在授权页填写本次需要绑定的角色名称 / 游戏编号(角色 ID)/ 区服;
-- 2. 平台识别到角色后,用这里填写的角色 ID 与 bind_game_role_id 比对;
-- 3. 两侧不一致时禁止确认绑定,只能重新扫码或联系客服。
ALTER TABLE semi_auto_tasks
ADD COLUMN IF NOT EXISTS customer_game_role_name TEXT NOT NULL DEFAULT '',
ADD COLUMN IF NOT EXISTS customer_game_role_id TEXT NOT NULL DEFAULT '',
ADD COLUMN IF NOT EXISTS customer_game_server_zone TEXT NOT NULL DEFAULT '';
COMMENT ON COLUMN semi_auto_tasks.customer_game_role_name IS
'客户在授权页填写的游戏角色名称';
COMMENT ON COLUMN semi_auto_tasks.customer_game_role_id IS
'客户在授权页填写的游戏编号 / 角色 ID,用于与平台识别角色比对';
COMMENT ON COLUMN semi_auto_tasks.customer_game_server_zone IS
'客户在授权页填写的区服';
@@ -0,0 +1,33 @@
-- 半自动履约:全链路报文留痕(原本系统入站请求 + 外部平台/Connector 出站调用)
-- Cookie / Token / 密钥一律不落库;报文按 180 天保留,由服务侧定期清理。
CREATE TABLE IF NOT EXISTS semi_auto_trace_logs (
id BIGSERIAL PRIMARY KEY,
task_id BIGINT NOT NULL REFERENCES semi_auto_tasks(id) ON DELETE CASCADE,
order_no TEXT NOT NULL DEFAULT '',
request_id TEXT NOT NULL DEFAULT '',
direction TEXT NOT NULL CHECK (direction IN ('inbound', 'outbound')),
channel TEXT NOT NULL,
action TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'ok' CHECK (status IN ('ok', 'error')),
http_status INTEGER,
duration_ms INTEGER,
request_summary JSONB NOT NULL DEFAULT '{}'::jsonb,
request_body TEXT NOT NULL DEFAULT '',
response_summary JSONB NOT NULL DEFAULT '{}'::jsonb,
response_body TEXT NOT NULL DEFAULT '',
error_message TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_semi_auto_trace_task
ON semi_auto_trace_logs (task_id, id DESC);
CREATE INDEX IF NOT EXISTS idx_semi_auto_trace_request
ON semi_auto_trace_logs (request_id);
CREATE INDEX IF NOT EXISTS idx_semi_auto_trace_created
ON semi_auto_trace_logs (created_at);
COMMENT ON TABLE semi_auto_trace_logs IS
'半自动履约全链路报文;request_body/response_body 已脱敏(Cookie、Token、密钥不落库)';
+3
View File
@@ -4,6 +4,7 @@ import { createApp } from './app.js'
import { runtimeConfig } from './config/runtime.js' import { runtimeConfig } from './config/runtime.js'
import { assertRuntimeConfigValid } from './config/runtime-validation.js' import { assertRuntimeConfigValid } from './config/runtime-validation.js'
import { bootstrapCoreServices } from './startup/bootstrap.js' import { bootstrapCoreServices } from './startup/bootstrap.js'
import { startSemiAutoTraceCleanup } from './services/semi-auto/semi-auto-trace.js'
import { createShutdownController } from './startup/shutdown.js' import { createShutdownController } from './startup/shutdown.js'
import { createStartupState, formatStartupError } from './startup/state.js' import { createStartupState, formatStartupError } from './startup/state.js'
import { logError, logInfo } from './utils/logger.js' import { logError, logInfo } from './utils/logger.js'
@@ -30,6 +31,8 @@ const app = createApp({
const server = app.listen(port, host, () => { const server = app.listen(port, host, () => {
logInfo('[startup]', `order-site-backend kuaishou-lite listening on http://${host}:${port}`) logInfo('[startup]', `order-site-backend kuaishou-lite listening on http://${host}:${port}`)
void bootstrapCoreServices(startupState, () => shutdownController?.isShutdownStarted() || false) void bootstrapCoreServices(startupState, () => shutdownController?.isShutdownStarted() || false)
// 半自动履约报文保留 180 天:启动先清一次,之后每 6 小时清理。
startSemiAutoTraceCleanup()
}) })
shutdownController = createShutdownController(server, startupState) shutdownController = createShutdownController(server, startupState)
@@ -0,0 +1,248 @@
import crypto from 'node:crypto'
import type { NextFunction, Request, Response } from 'express'
import { query } from '../db/client.js'
import {
recordSemiAutoTrace,
runWithSemiAutoTrace,
traceFingerprint,
type SemiAutoTraceChannel,
} from '../services/semi-auto/semi-auto-trace.js'
import { logWarn } from '../utils/logger.js'
/**
* 半自动履约入站报文:以 `:taskId` 路由参数为锚点。
*
* 用法:`router.param('taskId', createSemiAutoTaskTraceHandler({ channel: 'customer_api' }))`。
* 命中后整条请求链路都在 AsyncLocalStorage 上下文里,外部 Connector / 虎牙 RPC 的出站报文
* 会自动复用同一个 requestId,前端即可按 requestId 串起「一次客户操作」。
*/
export type SemiAutoTaskTraceOptions = {
channel: SemiAutoTraceChannel
/** 轮询类请求:只有失败或响应状态变化才落库。 */
isPolling?: (req: Request) => boolean
/** 不记录本次请求(例如返回 CK 的导出接口、历史查询自身)。 */
skip?: (req: Request) => boolean
}
const TASK_ORDER_CACHE_LIMIT = 800
const taskOrderCache = new Map<number, string>()
/** 响应里代表「状态」的字段:轮询指纹只取这些,时间戳/计数变化不算状态变化。 */
const TRACE_STATE_KEYS = [
'status',
'state',
'loginStatus',
'bindingStatus',
'executionStatus',
'displayStatus',
'message',
'msg',
'code',
'errorCode',
'ok',
'challenge',
'ready',
'pending',
'type',
'rebindUnchanged',
'rebindRequested',
'rebindConfirmState',
'rebindConfirmMessage',
'rebindCooldownDays',
'nextRebindAt',
'bindConfirmState',
'bindConfirmMessage',
'bindEffectDeadlineMs',
'bindGameRole',
'bindGameRoleId',
'huyaUid',
'lastError',
'isBindAccount',
'isBindRole',
]
/** 客户请求体里的凭据类字段:短信验证码等一律不落库。 */
const INBOUND_SECRET_KEYS = new Set([
'code',
'smscode',
'sms_code',
'password',
'token',
'cookie',
'qrcode',
'qrcode_token',
'qrcodetoken',
'ticket',
'sig',
])
function normalizeKey(key: string): string {
return key.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase()
}
function createTraceRequestId(): string {
return `req_${Date.now().toString(36)}_${crypto.randomBytes(4).toString('hex')}`
}
async function resolveTaskOrderNo(taskId: number): Promise<string> {
const cached = taskOrderCache.get(taskId)
if (cached !== undefined) return cached
try {
const result = await query<{ platform_order_id: string | null }>(
`SELECT o.platform_order_id
FROM semi_auto_tasks task
JOIN orders o ON o.id = task.order_id
WHERE task.id = $1
LIMIT 1`,
[taskId],
)
const orderNo = String(result.rows[0]?.platform_order_id || '')
if (taskOrderCache.size >= TASK_ORDER_CACHE_LIMIT) taskOrderCache.clear()
taskOrderCache.set(taskId, orderNo)
return orderNo
} catch (error) {
logWarn('[semi-auto/trace]', '解析任务订单号失败,报文将不带订单号', {
taskId,
error: error instanceof Error ? error.message : String(error),
})
return ''
}
}
function maskInboundRequestBody(value: unknown, depth = 0): unknown {
if (depth > 4) return '[max-depth]'
if (value === null || value === undefined) return value
if (Array.isArray(value)) {
return value.slice(0, 50).map((item) => maskInboundRequestBody(item, depth + 1))
}
if (typeof value !== 'object') return value
const source = value as Record<string, unknown>
const masked: Record<string, unknown> = {}
for (const [key, current] of Object.entries(source)) {
masked[key] = INBOUND_SECRET_KEYS.has(normalizeKey(key))
? '******'
: maskInboundRequestBody(current, depth + 1)
}
return masked
}
function pickTraceState(value: unknown, depth = 0): unknown {
if (!value || typeof value !== 'object' || depth > 3) return value
if (Array.isArray(value)) {
return value.slice(0, 20).map((item) => pickTraceState(item, depth + 1))
}
const source = value as Record<string, unknown>
const picked: Record<string, unknown> = {}
for (const key of TRACE_STATE_KEYS) {
if (key in source && source[key] !== undefined) picked[key] = source[key]
}
// 常见响应外壳:{ task, login, binding }
for (const key of ['task', 'login', 'binding', 'result']) {
const nested = source[key]
if (nested && typeof nested === 'object' && !Array.isArray(nested)) {
picked[key] = pickTraceState(nested, depth + 1)
}
}
return Object.keys(picked).length > 0 ? picked : value
}
function buildPollingFingerprint(payload: unknown): string {
const body = payload && typeof payload === 'object' ? (payload as Record<string, unknown>) : {}
return traceFingerprint({
code: body.code,
msg: body.msg,
errorCode: body.errorCode,
data: pickTraceState(body.data),
})
}
export function createSemiAutoTaskTraceHandler(options: SemiAutoTaskTraceOptions) {
return (req: Request, res: Response, next: NextFunction, taskIdInput: string): void => {
const taskId = Number(taskIdInput)
if (!Number.isInteger(taskId) || taskId <= 0) {
next()
return
}
if (options.skip?.(req)) {
next()
return
}
const pathOrderNo = String(req.params?.orderNo || '').trim()
const startedAt = Date.now()
const requestId = createTraceRequestId()
const polling = options.isPolling?.(req) === true
const actionPath = String(req.originalUrl || req.url || '').split('?')[0]
const action = `${String(req.method || 'GET').toUpperCase()} ${actionPath}`
const requestSummary = {
method: req.method,
path: actionPath,
query: req.query || {},
ip: req.ip || '',
}
const requestBody =
req.body && typeof req.body === 'object' && Object.keys(req.body as object).length > 0
? maskInboundRequestBody(req.body)
: ''
let recorded = false
const record = (payload: unknown) => {
if (recorded) return
recorded = true
try {
const body =
payload && typeof payload === 'object' ? (payload as Record<string, unknown>) : {}
const code = Number(body.code)
const httpStatus = Number(res.statusCode || 200)
const failed = Number.isFinite(code) ? code !== 0 : httpStatus >= 400
const status = failed || httpStatus >= 400 ? 'error' : 'ok'
recordSemiAutoTrace({
taskId,
orderNo: pathOrderNo,
requestId,
direction: 'inbound',
channel: options.channel,
action,
status,
httpStatus,
durationMs: Date.now() - startedAt,
requestSummary,
requestBody,
responseSummary: {
code: body.code ?? null,
msg: body.msg ?? '',
errorCode: body.errorCode ?? '',
},
responseBody: payload,
errorMessage: status === 'error' ? String(body.msg || '') : '',
always: !polling,
fingerprint: polling ? buildPollingFingerprint(payload) : undefined,
})
} catch (error) {
logWarn('[semi-auto/trace]', '记录入站报文失败,已跳过', {
taskId,
action,
error: error instanceof Error ? error.message : String(error),
})
}
}
const originalJson = res.json.bind(res)
res.json = ((payload: unknown) => {
record(payload)
return originalJson(payload as never)
}) as Response['json']
const start = (orderNo: string) => {
runWithSemiAutoTrace({ requestId, taskId, orderNo, source: options.channel }, () => next())
}
if (pathOrderNo) {
start(pathOrderNo)
return
}
void resolveTaskOrderNo(taskId).then(start, () => start(''))
}
}
@@ -8,15 +8,27 @@ import {
createAdminBrowserSession, createAdminBrowserSession,
exportAdminSemiAutoCredential, exportAdminSemiAutoCredential,
getAdminSemiAutoTask, getAdminSemiAutoTask,
getAdminSemiAutoTaskHistory,
listAdminSemiAutoTasks, listAdminSemiAutoTasks,
requestAdminSemiAutoCustomerReauth, requestAdminSemiAutoCustomerReauth,
syncAdminSemiAutoTask, syncAdminSemiAutoTask,
} from '../../services/semi-auto/semi-auto-task-service.js' } from '../../services/semi-auto/semi-auto-task-service.js'
import { createSemiAutoTaskTraceHandler } from '../../middleware/semi-auto-trace.js'
import { bodyOf, sessionOf } from './request-helpers.js' import { bodyOf, sessionOf } from './request-helpers.js'
import { createJsonHandler, requireAdminRoles } from './session.js' import { createJsonHandler, requireAdminRoles } from './session.js'
const router = Router() const router = Router()
// 运营端每次操作都会记录入站报文;详情每 3 秒刷新一次,GET 只在状态变化时落库。
router.param(
'taskId',
createSemiAutoTaskTraceHandler({
channel: 'admin_api',
isPolling: (req) => req.method === 'GET',
skip: (req) => req.path.endsWith('/history') || req.path.endsWith('/credential/export'),
}),
)
router.use('/semi-auto', requireAdminRoles(['admin', 'operator', 'support'])) router.use('/semi-auto', requireAdminRoles(['admin', 'operator', 'support']))
router.get( router.get(
@@ -37,6 +49,18 @@ router.get(
}), }),
) )
router.get(
'/semi-auto/tasks/:taskId/history',
createJsonHandler(
(req) => getAdminSemiAutoTaskHistory(req.params.taskId, req.query as Record<string, unknown>),
{
successMessage: 'ok',
errorMessage: '读取半自动履约历史失败',
scope: '[admin/semi-auto/tasks/:taskId/history]',
},
),
)
router.post( router.post(
'/semi-auto/tasks/:taskId/credential/export', '/semi-auto/tasks/:taskId/credential/export',
createJsonHandler( createJsonHandler(
@@ -1,24 +1,39 @@
import { Router } from 'express' import { Router } from 'express'
import { import {
confirmPublicBinding,
getPublicWeiboCountryCodes, getPublicWeiboCountryCodes,
listPublicSemiAutoTasks, listPublicSemiAutoTasks,
loginPublicHuyaSms, loginPublicHuyaSms,
loginPublicWeiboSms, loginPublicWeiboSms,
markCustomerLinkOpened, markCustomerLinkOpened,
pollPublicBinding,
pollPublicLogin, pollPublicLogin,
pollPublicWeiboQrLogin, pollPublicWeiboQrLogin,
savePublicTaskProfile,
sendPublicHuyaSmsCode, sendPublicHuyaSmsCode,
sendPublicWeiboSmsCode, sendPublicWeiboSmsCode,
startPublicBinding,
startPublicLogin, startPublicLogin,
startPublicWeiboQrLogin, startPublicWeiboQrLogin,
submitPublicRebind,
verifyPublicHuyaSmsChallenge, verifyPublicHuyaSmsChallenge,
} from '../services/semi-auto/semi-auto-task-service.js' } from '../services/semi-auto/semi-auto-task-service.js'
import { createSemiAutoTaskTraceHandler } from '../middleware/semi-auto-trace.js'
import { createRateLimitMiddleware, getParamRateLimitKey } from '../middleware/rate-limit.js' import { createRateLimitMiddleware, getParamRateLimitKey } from '../middleware/rate-limit.js'
import { createRouteHandler } from '../utils/http.js' import { createRouteHandler } from '../utils/http.js'
const router = Router() const router = Router()
// 客户侧每次操作都会记录入站报文;2 秒一次的 /status 轮询只在状态变化或失败时落库。
router.param(
'taskId',
createSemiAutoTaskTraceHandler({
channel: 'customer_api',
isPolling: (req) => req.path.endsWith('/status'),
}),
)
const readLimit = createRateLimitMiddleware({ const readLimit = createRateLimitMiddleware({
scope: 'customer-fulfillment:read', scope: 'customer-fulfillment:read',
windowMs: 60_000, windowMs: 60_000,
@@ -70,6 +85,64 @@ router.get(
}), }),
) )
router.post(
'/:orderNo/tasks/:taskId/profile',
writeLimit,
createRouteHandler(
(req) => savePublicTaskProfile(req.params.orderNo, req.params.taskId, req.body || {}),
{
successMessage: '角色资料已保存',
errorMessage: '保存角色资料失败',
scope: '[customer-fulfillment/:orderNo/tasks/:taskId/profile]',
},
),
)
router.post(
'/:orderNo/tasks/:taskId/binding/start',
writeLimit,
createRouteHandler((req) => startPublicBinding(req.params.orderNo, req.params.taskId, req.body), {
successMessage: '绑定会话已创建',
errorMessage: '开始账号绑定失败',
scope: '[customer-fulfillment/:orderNo/tasks/:taskId/binding/start]',
}),
)
router.get(
'/:orderNo/tasks/:taskId/binding/status',
readLimit,
createRouteHandler((req) => pollPublicBinding(req.params.orderNo, req.params.taskId), {
errorMessage: '刷新账号绑定状态失败',
scope: '[customer-fulfillment/:orderNo/tasks/:taskId/binding/status]',
}),
)
router.post(
'/:orderNo/tasks/:taskId/binding/rebind',
writeLimit,
createRouteHandler((req) => submitPublicRebind(req.params.orderNo, req.params.taskId), {
successMessage: '换绑请求已提交',
errorMessage: '提交换绑失败',
scope: '[customer-fulfillment/:orderNo/tasks/:taskId/binding/rebind]',
}),
)
router.post(
'/:orderNo/tasks/:taskId/binding/confirm',
writeLimit,
createRouteHandler(
(req) =>
confirmPublicBinding(req.params.orderNo, req.params.taskId, {
acceptExistingRole: req.body?.acceptExistingRole === true,
}),
{
successMessage: '绑定已确认',
errorMessage: '确认账号绑定失败',
scope: '[customer-fulfillment/:orderNo/tasks/:taskId/binding/confirm]',
},
),
)
router.get( router.get(
'/:orderNo/tasks/:taskId/weibo/config', '/:orderNo/tasks/:taskId/weibo/config',
readLimit, readLimit,
@@ -50,6 +50,7 @@ type MockSession = {
bindingQrExpiresAtMs: number bindingQrExpiresAtMs: number
bindGameAccount: string bindGameAccount: string
bindGameRole: string bindGameRole: string
bindGameRoleId: string
bindGameChannel: string bindGameChannel: string
message: string message: string
tickets: Map<string, MockTicket> tickets: Map<string, MockTicket>
@@ -136,8 +137,10 @@ function bindingView(session: MockSession): ConnectorBindingSession {
status: session.bindingStatus, status: session.bindingStatus,
qrImage: session.bindingStatus === 'not_started' ? '' : buildMockBindingQr(session.sessionId), qrImage: session.bindingStatus === 'not_started' ? '' : buildMockBindingQr(session.sessionId),
qrExpiresAt: new Date(session.bindingQrExpiresAtMs).toISOString(), qrExpiresAt: new Date(session.bindingQrExpiresAtMs).toISOString(),
qrUrl: '',
bindGameAccount: session.bindGameAccount, bindGameAccount: session.bindGameAccount,
bindGameRole: session.bindGameRole, bindGameRole: session.bindGameRole,
bindGameRoleId: session.bindGameRoleId,
bindGameChannel: session.bindGameChannel, bindGameChannel: session.bindGameChannel,
message: session.message, message: session.message,
} }
@@ -158,6 +161,7 @@ function markRoleReady(session: MockSession) {
session.bindingStatus = 'role_ready' session.bindingStatus = 'role_ready'
session.bindGameAccount = `mock-account-${session.sessionId.slice(-6)}` session.bindGameAccount = `mock-account-${session.sessionId.slice(-6)}`
session.bindGameRole = 'Mock测试角色' session.bindGameRole = 'Mock测试角色'
session.bindGameRoleId = `mock-role-${session.sessionId.slice(-6)}`
session.bindGameChannel = '虎牙' session.bindGameChannel = '虎牙'
session.message = 'Mock 已识别游戏角色,请确认绑定' session.message = 'Mock 已识别游戏角色,请确认绑定'
} }
@@ -188,6 +192,7 @@ export function createMockLoginSession(input: {
bindingQrExpiresAtMs: 0, bindingQrExpiresAtMs: 0,
bindGameAccount: '', bindGameAccount: '',
bindGameRole: '', bindGameRole: '',
bindGameRoleId: '',
bindGameChannel: '', bindGameChannel: '',
message: 'Mock 登录二维码已生成,轮询后会自动模拟扫码成功', message: 'Mock 登录二维码已生成,轮询后会自动模拟扫码成功',
tickets: new Map(), tickets: new Map(),
@@ -230,6 +235,7 @@ export function sendMockHuyaSmsCode(input: {
bindingQrExpiresAtMs: 0, bindingQrExpiresAtMs: 0,
bindGameAccount: '', bindGameAccount: '',
bindGameRole: '', bindGameRole: '',
bindGameRoleId: '',
bindGameChannel: '', bindGameChannel: '',
message: 'Mock 短信验证码已发送,请输入 123456', message: 'Mock 短信验证码已发送,请输入 123456',
tickets: new Map(), tickets: new Map(),
@@ -0,0 +1,16 @@
/**
* 虎牙 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
}
@@ -202,3 +202,44 @@ test('重新扫码换绑会向 Connector 传递 force_rebind', async () => {
globalThis.fetch = originalFetch 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, huyaNativeConnector,
type HuyaStoredCredential, type HuyaStoredCredential,
} from './huya-native/huya-native-connector.js' } from './huya-native/huya-native-connector.js'
import { recordSemiAutoTrace, traceFingerprint } from './semi-auto-trace.js'
export type ConnectorLoginSession = { export type ConnectorLoginSession = {
sessionId: string sessionId: string
@@ -95,11 +96,22 @@ export type ConnectorBindingSession = {
| 'failed' | 'failed'
qrImage: string qrImage: string
qrExpiresAt: string qrExpiresAt: string
qrUrl: string
bindGameAccount: string bindGameAccount: string
bindGameRole: string bindGameRole: string
bindGameRoleId: string
bindGameChannel: string bindGameChannel: string
hasExistingBinding?: boolean hasExistingBinding?: boolean
rebindRequested?: 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 message: string
} }
@@ -193,9 +205,11 @@ async function callConnector<T>(
const timeoutMs = Math.max(1000, Number(runtimeConfig.semiAuto?.connectorTimeoutMs || 15_000)) const timeoutMs = Math.max(1000, Number(runtimeConfig.semiAuto?.connectorTimeoutMs || 15_000))
const controller = new AbortController() const controller = new AbortController()
const timer = setTimeout(() => controller.abort(), timeoutMs) const timer = setTimeout(() => controller.abort(), timeoutMs)
const method = String(options.method || 'GET').toUpperCase()
const startedAt = Date.now()
try { try {
const requestInit: RequestInit = { const requestInit: RequestInit = {
method: options.method || 'GET', method,
headers: { headers: {
Accept: 'application/json', Accept: 'application/json',
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@@ -212,6 +226,20 @@ async function callConnector<T>(
} catch { } catch {
payload = null 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) { if (!response.ok) {
const detail = const detail =
payload && typeof payload === 'object' payload && typeof payload === 'object'
@@ -224,6 +252,19 @@ async function callConnector<T>(
} }
return payload as T return payload as T
} catch (error) { } 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 && typeof error === 'object' && 'statusCode' in error) throw error
if (error instanceof Error && error.name === 'AbortError') { if (error instanceof Error && error.name === 'AbortError') {
throw createHttpError('半自动履约 Connector 请求超时', { throw createHttpError('半自动履约 Connector 请求超时', {
@@ -410,14 +451,50 @@ export async function getHuyaBinding(
) )
} }
export async function confirmHuyaBinding( /**
* 只读绑定快照:不触发虎牙查询,供「确认绑定」这类本地动作使用。
* 外部 Connector 没有独立快照端点,只能复用 GET(由 Connector 侧决定是否访问虎牙)。
*/
export async function getHuyaBindingSnapshot(
sessionId: string, sessionId: string,
mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(), mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(),
): Promise<ConnectorBindingSession> { ): 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>( return callConnector<ConnectorBindingSession>(
`/api/internal/huya-semi-auto/sessions/${encodeURIComponent(sessionId)}/binding/confirm`, `/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, 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 { runtimeConfig } from '../../../config/runtime.js'
import { createHttpError } from '../../../utils/http.js' import { createHttpError } from '../../../utils/http.js'
import { logWarn } from '../../../utils/logger.js' import { logWarn } from '../../../utils/logger.js'
import { resolveBindingRoleId } from '../binding-role-id.js'
import type { import type {
ConnectorBindingSession, ConnectorBindingSession,
ConnectorBrowserTicket, ConnectorBrowserTicket,
@@ -51,6 +52,10 @@ const LOGIN_QR_TTL_MS = 5 * 60 * 1000
const SMS_LOGIN_TTL_MS = 5 * 60 * 1000 const SMS_LOGIN_TTL_MS = 5 * 60 * 1000
const CREDENTIAL_TTL_MS = 24 * 60 * 60 * 1000 const CREDENTIAL_TTL_MS = 24 * 60 * 60 * 1000
const BINDING_QR_TTL_MS = 5 * 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 BROWSER_TICKET_TTL_MS = 2 * 60 * 1000
const MAX_SESSIONS = 500 const MAX_SESSIONS = 500
const NATIVE_TICKET_PREFIX = 'native-ticket-' const NATIVE_TICKET_PREFIX = 'native-ticket-'
@@ -62,14 +67,30 @@ type NativeBindingStatus = ConnectorBindingSession['status']
type NativeBindState = { type NativeBindState = {
status: NativeBindingStatus status: NativeBindingStatus
qrImage: string qrImage: string
qrUrl: string
qrToken: string qrToken: string
expiresAtMs: number expiresAtMs: number
account: string account: string
role: string role: string
roleId: string
channel: string channel: string
hasExistingBinding: boolean hasExistingBinding: boolean
rebindRequested: boolean rebindRequested: boolean
rebindScanned: 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 baselineRoleKey: string
message: string message: string
} }
@@ -135,14 +156,29 @@ function defaultBindingState(): NativeBindState {
return { return {
status: 'not_started', status: 'not_started',
qrImage: '', qrImage: '',
qrUrl: '',
qrToken: '', qrToken: '',
expiresAtMs: 0, expiresAtMs: 0,
account: '', account: '',
role: '', role: '',
roleId: '',
channel: '', channel: '',
hasExistingBinding: false, hasExistingBinding: false,
rebindRequested: false, rebindRequested: false,
rebindScanned: 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: '', baselineRoleKey: '',
message: '', message: '',
} }
@@ -152,6 +188,133 @@ function iso(value: number): string {
return new Date(value).toISOString() 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 { function extractInt(value: unknown): number {
const parsed = Number.parseInt(String(value ?? '').trim(), 10) const parsed = Number.parseInt(String(value ?? '').trim(), 10)
return Number.isFinite(parsed) && parsed > 0 ? parsed : 0 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): { function parseRole(response: HuyaBindResponse | null): {
account: string account: string
role: string role: string
roleId: string
channel: 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 data: HuyaGameAccountData = response.accountData
const account = data.gameAccount.nick || data.gameRole.roleName const account = data.gameAccount.nick || data.gameRole.roleName
const role = data.gameRole.roleName const role = data.gameRole.roleName
const channel = [data.gameRole.platName, data.gameRole.areaName].filter(Boolean).join(' · ') 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 { function bindingRoleKey(role: {
return [role.account, role.role, role.channel].join('\u0000') account: string
role: string
roleId?: string
channel: string
}): string {
return [role.account, role.role, role.roleId || '', role.channel].join('\u0000')
} }
function configValues() { function configValues() {
@@ -658,10 +832,17 @@ export class HuyaNativeConnector {
const role = parseRole(roleResponse) const role = parseRole(roleResponse)
const hasExistingBinding = hasExistingHuyaBinding(roleResponse) const hasExistingBinding = hasExistingHuyaBinding(roleResponse)
session.binding.hasExistingBinding = hasExistingBinding session.binding.hasExistingBinding = hasExistingBinding
applyRebindMeta(session, roleResponse, this.now())
if (role.role && !options.forceRebind) { if (role.role && !options.forceRebind) {
this.markRoleReady(session, role, hasExistingBinding && !session.binding.rebindRequested) this.markRoleReady(session, role, hasExistingBinding && !session.binding.rebindRequested)
if (session.binding.rebindRequested) { 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) return this.bindingView(session)
} }
@@ -684,11 +865,20 @@ export class HuyaNativeConnector {
errorCode: 'huya_livelink_param_failed', errorCode: 'huya_livelink_param_failed',
}) })
} }
const profile = await rpc.getUserProfile({ let profile: Awaited<ReturnType<typeof rpc.getUserProfile>> = null
uid: session.uid, try {
cookie: session.cookie, profile = await rpc.getUserProfile({
targetUid: session.uid, 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 const nickname = profile?.nick || profile?.passport || session.nickname
session.nickname = nickname session.nickname = nickname
const avatar = profile?.avatar || '' const avatar = profile?.avatar || ''
@@ -716,19 +906,100 @@ export class HuyaNativeConnector {
if (options.forceRebind) { if (options.forceRebind) {
session.binding.rebindRequested = true session.binding.rebindRequested = true
session.binding.rebindScanned = false 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.baselineRoleKey = bindingRoleKey(role)
} }
session.binding.status = 'qr_pending' session.binding.status = 'qr_pending'
session.binding.qrImage = mini.image session.binding.qrImage = mini.image
session.binding.qrUrl = urls.qrUrl
session.binding.qrToken = mini.token session.binding.qrToken = mini.token
session.binding.expiresAtMs = this.now() + BINDING_QR_TTL_MS 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 session.binding.message = options.forceRebind
? '请使用虎牙 App 扫码选择需要换绑的游戏角色' ? '请使用虎牙 App 扫码选择需要换绑的游戏角色'
: '请使用虎牙 App 扫码绑定游戏角色' : '该虎牙账号还没有绑定游戏角色,请用虎牙 App 扫码完成绑定'
return this.bindingView(session) 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> { async pollBinding(sessionId: string): Promise<ConnectorBindingSession> {
return this.withLock(sessionId, async () => { return this.withLock(sessionId, async () => {
const session = this.requireAuthenticatedSession(sessionId) const session = this.requireAuthenticatedSession(sessionId)
@@ -740,14 +1011,20 @@ export class HuyaNativeConnector {
timeoutMs: this.rpcTimeoutMs, timeoutMs: this.rpcTimeoutMs,
}) })
if (qrStatus) { 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.status = 'expired'
session.binding.message = '绑定二维码已过期,请重新获取' session.binding.message = '绑定二维码已过期,请重新获取'
return this.bindingView(session) return this.bindingView(session)
} }
if (qrStatus.isScan) { if (qrStatus.isScan) {
session.binding.status = 'scanned' session.binding.status = 'scanned'
session.binding.message = '已扫码,等待绑定完成' session.binding.message = session.binding.rebindRequested
? '已扫码,请在虎牙确认框中选中目标角色'
: '已扫码,等待绑定完成'
} }
if (qrStatus.isScan || qrStatus.isCompleted) { if (qrStatus.isScan || qrStatus.isCompleted) {
session.binding.rebindScanned = true session.binding.rebindScanned = true
@@ -759,6 +1036,24 @@ export class HuyaNativeConnector {
return this.bindingView(session) return this.bindingView(session)
} }
const rpc = new HuyaRpcClient({ fetchImpl: this.fetchImpl, timeoutMs: this.rpcTimeoutMs }) 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({ const response = await rpc.checkUserBindGameAccount({
uid: session.uid, uid: session.uid,
cookie: session.cookie, cookie: session.cookie,
@@ -773,91 +1068,195 @@ export class HuyaNativeConnector {
const role = parseRole(response) const role = parseRole(response)
const hasExistingBinding = hasExistingHuyaBinding(response) const hasExistingBinding = hasExistingHuyaBinding(response)
session.binding.hasExistingBinding = hasExistingBinding session.binding.hasExistingBinding = hasExistingBinding
applyRebindMeta(session, response, this.now())
if (role.role) { if (role.role) {
const rebindRequested = session.binding.rebindRequested const rebindRequested = session.binding.rebindRequested
const roleKey = bindingRoleKey(role) const roleKey = bindingRoleKey(role)
const changedRole = const changedRole =
!session.binding.baselineRoleKey || roleKey !== session.binding.baselineRoleKey !session.binding.baselineRoleKey || roleKey !== session.binding.baselineRoleKey
if (rebindRequested && !changedRole) { if (rebindRequested && !changedRole) {
if (qrCompleted) { if (session.binding.rebindConfirmState === 'rejected') {
session.binding.rebindRequested = false // 虎牙明确拒绝:保留 rebind 状态并展示虎牙原文,不能清空 rebindRequested。
session.binding.rebindScanned = false session.binding.rebindUnchanged = true
session.binding.baselineRoleKey = ''
this.markRoleReady(session, role, hasExistingBinding) this.markRoleReady(session, role, hasExistingBinding)
session.binding.message = '扫码后仍识别到原绑定角色,请确认使用或重新换绑' session.binding.message = rebindFailureMessage(
} else { role.role,
session.binding.status = 'scanned' session.binding.rebindConfirmMessage,
session.binding.message = '已扫码,正在等待换绑角色生效' 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) return this.bindingView(session)
} }
if (rebindRequested) session.binding.rebindUnchanged = false
this.markRoleReady(session, role, hasExistingBinding && !rebindRequested) this.markRoleReady(session, role, hasExistingBinding && !rebindRequested)
if (rebindRequested) { if (rebindRequested) {
session.binding.message = '已识别换绑角色,请确认换绑' 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)) { } else if (!['scanned', 'expired', 'failed'].includes(session.binding.status)) {
session.binding.status = 'qr_pending' session.binding.status = 'qr_pending'
session.binding.message = '等待扫码绑定游戏角色' session.binding.message = '该虎牙账号还没有绑定游戏角色,请扫码完成绑定'
} }
return this.bindingView(session) 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 () => { return this.withLock(sessionId, async () => {
const session = this.requireAuthenticatedSession(sessionId) 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 { bindActId, outerActId } = configValues()
const rpc = new HuyaRpcClient({ fetchImpl: this.fetchImpl, timeoutMs: this.rpcTimeoutMs }) const rpc = new HuyaRpcClient({ fetchImpl: this.fetchImpl, timeoutMs: this.rpcTimeoutMs })
await this.submitRebindLocked(session, rpc)
const response = await rpc.checkUserBindGameAccount({ const response = await rpc.checkUserBindGameAccount({
uid: session.uid, uid: session.uid,
cookie: session.cookie, cookie: session.cookie,
bindActId, bindActId,
outerActId, outerActId,
}) })
const role = parseRole(response) if (response && response.status === 200) {
if (!response || response.status !== 200 || !role.role) { const role = parseRole(response)
throw createHttpError('尚未识别到可确认的绑定角色', { applyRebindMeta(session, response, this.now())
statusCode: 409, if (role.role) {
errorCode: 'huya_bind_role_not_ready', const changedRole =
}) !session.binding.baselineRoleKey ||
} bindingRoleKey(role) !== session.binding.baselineRoleKey
const rebindRequested = session.binding.rebindRequested if (changedRole) {
if ( session.binding.rebindUnchanged = false
rebindRequested && this.markRoleReady(session, role, false)
session.binding.baselineRoleKey && session.binding.message = '已识别换绑角色,请确认换绑'
bindingRoleKey(role) === session.binding.baselineRoleKey } else if (session.binding.rebindConfirmState === 'rejected') {
) { session.binding.rebindUnchanged = true
throw createHttpError('换绑角色尚未生效,请稍后重试', { this.markRoleReady(session, role, hasExistingHuyaBinding(response))
statusCode: 409, session.binding.message = rebindFailureMessage(
errorCode: 'huya_bind_rebind_not_ready', role.role,
}) session.binding.rebindConfirmMessage,
} session.binding.nextRebindAt,
const useExistingBinding = hasExistingHuyaBinding(response) && !rebindRequested )
if (!useExistingBinding) { } else {
const confirmed = await rpc.confirmBindActAccount({ session.binding.status = 'scanned'
uid: session.uid, session.binding.message = '虎牙已受理换绑,正在等待角色生效'
cookie: session.cookie, }
bindActId,
outerActId,
})
if (!confirmed || confirmed.status !== 200) {
throw createHttpError(confirmed?.msg || '确认虎牙绑定失败', {
statusCode: 409,
errorCode: 'huya_bind_confirm_failed',
})
} }
} }
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) return this.bindingView(session)
}) })
} }
@@ -1042,12 +1441,13 @@ export class HuyaNativeConnector {
private markRoleReady( private markRoleReady(
session: NativeSession, session: NativeSession,
role: { account: string; role: string; channel: string }, role: { account: string; role: string; roleId?: string; channel: string },
existingBinding = false, existingBinding = false,
): void { ): void {
session.binding.status = 'role_ready' session.binding.status = 'role_ready'
session.binding.account = role.account session.binding.account = role.account
session.binding.role = role.role session.binding.role = role.role
session.binding.roleId = role.roleId || ''
session.binding.channel = role.channel session.binding.channel = role.channel
session.binding.message = existingBinding session.binding.message = existingBinding
? '当前账号已有绑定角色,请确认直接使用' ? '当前账号已有绑定角色,请确认直接使用'
@@ -1131,11 +1531,22 @@ export class HuyaNativeConnector {
status: binding.status, status: binding.status,
qrImage: binding.qrImage, qrImage: binding.qrImage,
qrExpiresAt: binding.expiresAtMs ? iso(binding.expiresAtMs) : '', qrExpiresAt: binding.expiresAtMs ? iso(binding.expiresAtMs) : '',
qrUrl: binding.qrUrl,
bindGameAccount: binding.account, bindGameAccount: binding.account,
bindGameRole: binding.role, bindGameRole: binding.role,
bindGameRoleId: resolveBindingRoleId(binding.roleId, session.uid),
bindGameChannel: binding.channel, bindGameChannel: binding.channel,
hasExistingBinding: binding.hasExistingBinding, hasExistingBinding: binding.hasExistingBinding,
rebindRequested: binding.rebindRequested, 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, message: binding.message,
} }
} }
@@ -2,6 +2,7 @@
import crypto from 'node:crypto' import crypto from 'node:crypto'
import { recordSemiAutoTrace, traceFingerprint } from '../semi-auto-trace.js'
import { buildHuyaLoginContext, cookiePairs, cookieValue, normalizeCookiePairs } from './cookie.js' import { buildHuyaLoginContext, cookiePairs, cookieValue, normalizeCookiePairs } from './cookie.js'
import { import {
decodeWupResponse, 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 { function parseProfile(reader: TafReader): HuyaUserProfile {
let uid = 0 let uid = 0
let nick = '' let nick = ''
@@ -412,10 +434,20 @@ function parseProfile(reader: TafReader): HuyaUserProfile {
break break
} }
reader.readHead() reader.readHead()
if (tag === 0) uid = reader.readIntValue(dataType) if (dataType === TAF_TYPE.STRUCT_BEGIN) {
else if (tag === 1) nick = reader.readStringValue(dataType) // 新版虎牙把资料包在 tag0 的嵌套结构里,直接解析内层结构。
else if (tag === 2) avatar = reader.readStringValue(dataType) if (tag === 0) {
else if (tag === 17) passport = reader.readStringValue(dataType) 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) else reader.skipValue(dataType)
} }
return { uid, nick, avatar, passport } return { uid, nick, avatar, passport }
@@ -463,22 +495,67 @@ export class HuyaRpcClient {
gid?: number gid?: number
scene?: string scene?: string
}): Promise<HuyaBindResponse | null> { }): Promise<HuyaBindResponse | null> {
const response = await this.callRpc( const startedAt = Date.now()
'webActUI', const request = {
'checkUserBindGameAccount', servant: 'webActUI',
input.uid, func: 'checkUserBindGameAccount',
input.cookie, uid: input.uid,
(writer) => { gid: input.gid || 0,
this.writeActivityUser(writer, input.uid, input.cookie) outerActId: input.outerActId || '',
writer.writeInt32(1, input.gid || 0) bindActId: input.bindActId || 0,
writer.writeString(2, input.outerActId || '') isUseOuterActId: input.isUseOuterActId ?? 1,
writer.writeInt32(3, 0) scene: input.scene || '',
writer.writeString(4, input.scene || '') }
writer.writeInt32(5, input.bindActId || 0) try {
writer.writeInt32(6, input.isUseOuterActId ?? 1) const response = await this.callRpc(
}, 'webActUI',
) 'checkUserBindGameAccount',
return response ? readWupStruct(response, parseBindResponse) : null 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: { async confirmBindActAccount(input: {
@@ -488,19 +565,55 @@ export class HuyaRpcClient {
outerActId: string outerActId: string
gid?: number gid?: number
}): Promise<HuyaConfirmResponse | null> { }): Promise<HuyaConfirmResponse | null> {
const response = await this.callRpc( const startedAt = Date.now()
'webActUI', const request = {
'confirmBindActAccount', servant: 'webActUI',
input.uid, func: 'confirmBindActAccount',
input.cookie, uid: input.uid,
(writer) => { gid: input.gid || 0,
this.writeActivityUser(writer, input.uid, input.cookie) outerActId: input.outerActId || '',
writer.writeInt32(1, input.gid || 0) bindActId: input.bindActId || 0,
writer.writeString(2, input.outerActId || '') }
writer.writeInt32(3, input.bindActId || 0) try {
}, const response = await this.callRpc(
) 'webActUI',
return response ? readWupStruct(response, parseConfirmResponse) : null '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: { async getLiveLinkParam(input: {
@@ -510,21 +623,57 @@ export class HuyaRpcClient {
outerActId: number outerActId: number
gameAuthScene?: string gameAuthScene?: string
}): Promise<HuyaLiveLinkResponse | null> { }): Promise<HuyaLiveLinkResponse | null> {
const response = await this.callRpc( const startedAt = Date.now()
'webActUI', const request = {
'getLiveLinkParam', servant: 'webActUI',
input.uid, func: 'getLiveLinkParam',
input.cookie, uid: input.uid,
(writer) => { bindActId: input.bindActId || 0,
this.writeActivityUser(writer, input.uid, input.cookie) outerActId: input.outerActId || 0,
writer.writeInt32(1, 0) gameAuthScene: input.gameAuthScene || '',
writer.writeInt32(2, input.outerActId || 0) }
writer.writeString(3, input.gameAuthScene || '') try {
writer.writeString(4, '') const response = await this.callRpc(
writer.writeInt32(5, input.bindActId || 0) 'webActUI',
}, 'getLiveLinkParam',
) input.uid,
return response ? readWupStruct(response, parseLiveLinkResponse) : null 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: { async getUserProfileBatch(input: {
@@ -554,17 +703,53 @@ export class HuyaRpcClient {
}): Promise<HuyaUserProfile | null> { }): Promise<HuyaUserProfile | null> {
const targetUid = Math.trunc(input.targetUid) const targetUid = Math.trunc(input.targetUid)
if (!(targetUid > 0)) return null if (!(targetUid > 0)) return null
const response = await this.callRpc( const startedAt = Date.now()
'huyauserui', try {
'getUserProfile', const response = await this.callRpc(
input.uid, 'huyauserui',
input.cookie, 'getUserProfile',
(writer) => { input.uid,
this.writeActivityUser(writer, 0, input.cookie) input.cookie,
writer.writeInt64(1, targetUid) (writer) => {
}, this.writeActivityUser(writer, 0, input.cookie)
) writer.writeInt64(1, targetUid)
return response ? readWupStruct(response, parseProfileResponse) : null },
)
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( private async callRpc(
@@ -684,6 +869,7 @@ export async function getLiveLinkMiniQrcode(
).join('') ).join('')
const sessionId = `${Math.floor(Date.now() / 1000)}_${suffix}` const sessionId = `${Math.floor(Date.now() / 1000)}_${suffix}`
const fetchImpl = options.fetchImpl || fetch const fetchImpl = options.fetchImpl || fetch
const startedAt = Date.now()
const response = await fetchImpl(`${LIVELINK_BIND_API_BASE}/api/qrcode/getMiniAppQrcode`, { const response = await fetchImpl(`${LIVELINK_BIND_API_BASE}/api/qrcode/getMiniAppQrcode`, {
method: 'POST', method: 'POST',
headers: { headers: {
@@ -697,14 +883,41 @@ export async function getLiveLinkMiniQrcode(
body: JSON.stringify({ queryString: `${query}&sessionId=${sessionId}` }), body: JSON.stringify({ queryString: `${query}&sessionId=${sessionId}` }),
signal: AbortSignal.timeout(options.timeoutMs || 15_000), 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 { const payload = (await response.json().catch(() => null)) as {
iRet?: number iRet?: number
jData?: { qrcode?: string; qrcodeToken?: string } jData?: { qrcode?: string; qrcodeToken?: string }
} | null } | 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 || '')) 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 || '') } return { image, token: String(payload.jData?.qrcodeToken || '') }
} }
@@ -720,6 +933,7 @@ export async function getLiveLinkQrcodeStatus(
const normalized = String(token || '').trim() const normalized = String(token || '').trim()
if (!normalized) return null if (!normalized) return null
const fetchImpl = options.fetchImpl || fetch const fetchImpl = options.fetchImpl || fetch
const startedAt = Date.now()
const response = await fetchImpl(`${LIVELINK_BIND_API_BASE}/api/qrcode/poolingQrcodeStatus`, { const response = await fetchImpl(`${LIVELINK_BIND_API_BASE}/api/qrcode/poolingQrcodeStatus`, {
method: 'POST', method: 'POST',
headers: { headers: {
@@ -733,7 +947,24 @@ export async function getLiveLinkQrcodeStatus(
body: JSON.stringify({ qrcodeToken: normalized }), body: JSON.stringify({ qrcodeToken: normalized }),
signal: AbortSignal.timeout(options.timeoutMs || 15_000), 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 { const payload = (await response.json().catch(() => null)) as {
iRet?: number iRet?: number
jData?: { jData?: {
@@ -743,13 +974,18 @@ export async function getLiveLinkQrcodeStatus(
isFailure?: boolean isFailure?: boolean
} }
} | null } | null
if (!payload || payload.iRet !== 0) return null if (!payload || payload.iRet !== 0) {
return { traceQrcodeStatus('error', { iRet: payload?.iRet ?? null })
return null
}
const result = {
isScan: Boolean(payload.jData?.isScan), isScan: Boolean(payload.jData?.isScan),
isExpired: Boolean(payload.jData?.isExpired), isExpired: Boolean(payload.jData?.isExpired),
isCompleted: Boolean(payload.jData?.isCompleted), isCompleted: Boolean(payload.jData?.isCompleted),
isFailure: Boolean(payload.jData?.isFailure), isFailure: Boolean(payload.jData?.isFailure),
} }
traceQrcodeStatus('ok', { iRet: payload.iRet, ...result })
return result
} }
export function buildBindUrls(input: { 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,215 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import { 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('区服解析', () => {
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 { import {
createHuyaBrowserTicket, createHuyaBrowserTicket,
createHuyaLoginSession, createHuyaLoginSession,
confirmHuyaBinding,
exportHuyaSessionCredential, exportHuyaSessionCredential,
getHuyaBinding, getHuyaBinding,
getHuyaBindingSnapshot,
getHuyaLoginSession, getHuyaLoginSession,
loginHuyaSms, loginHuyaSms,
revokeHuyaSession, revokeHuyaSession,
sendHuyaSmsCode, sendHuyaSmsCode,
startHuyaBinding, startHuyaBinding,
submitHuyaRebind,
consumeHuyaBrowserTicket, consumeHuyaBrowserTicket,
verifyHuyaSmsChallenge, verifyHuyaSmsChallenge,
type ConnectorBindingSession, type ConnectorBindingSession,
@@ -52,6 +55,7 @@ import {
markSemiAutoCredentialCheck, markSemiAutoCredentialCheck,
upsertSemiAutoCredentialWithClient, upsertSemiAutoCredentialWithClient,
} from './semi-auto-credential-service.js' } from './semi-auto-credential-service.js'
import { querySemiAutoTraces } from './semi-auto-trace.js'
const SEMI_AUTO_PLATFORMS = new Set(['huya', 'weibo']) const SEMI_AUTO_PLATFORMS = new Set(['huya', 'weibo'])
type SemiAutoPlatform = 'huya' | 'weibo' type SemiAutoPlatform = 'huya' | 'weibo'
@@ -98,7 +102,14 @@ type TaskRow = {
platform_nickname: string platform_nickname: string
bind_game_account: string bind_game_account: string
bind_game_role: string bind_game_role: string
bind_game_role_id: string
bind_game_channel: 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 target_quantity: number
completed_quantity: number completed_quantity: number
assigned_admin_user_id: number | null assigned_admin_user_id: number | null
@@ -175,7 +186,20 @@ function displayStatus(task: TaskRow) {
return { key: 'failed', label: '需客服处理' } return { key: 'failed', label: '需客服处理' }
} }
if (task.login_status === 'authenticated') { 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 === 'scanned') return { key: 'login_scanned', label: '已扫码,确认中' }
if (task.login_status === 'qr_pending') return { key: 'waiting_login', label: '等待客户登录' } if (task.login_status === 'qr_pending') return { key: 'waiting_login', label: '等待客户登录' }
@@ -205,7 +229,11 @@ function mapTask(task: TaskRow) {
platformNickname: task.platform_nickname, platformNickname: task.platform_nickname,
bindGameAccount: task.bind_game_account, bindGameAccount: task.bind_game_account,
bindGameRole: task.bind_game_role, bindGameRole: task.bind_game_role,
bindGameRoleId: task.bind_game_role_id,
bindGameChannel: task.bind_game_channel, 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), targetQuantity: Number(task.target_quantity || 1),
completedQuantity: Number(task.completed_quantity || 0), completedQuantity: Number(task.completed_quantity || 0),
assignedAdminUserId: task.assigned_admin_user_id ? Number(task.assigned_admin_user_id) : null, assignedAdminUserId: task.assigned_admin_user_id ? Number(task.assigned_admin_user_id) : null,
@@ -289,13 +317,41 @@ const TASK_SELECT = `
cfg.semi_auto_config_json, cfg.semi_auto_config_json,
credential.credential_status, credential.credential_status,
credential.credential_source, 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 FROM semi_auto_tasks task
JOIN orders o ON o.id = task.order_id JOIN orders o ON o.id = task.order_id
JOIN order_items oi ON oi.id = task.order_item_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 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 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 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> { async function loadTask(taskId: number): Promise<TaskRow> {
@@ -354,6 +410,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( async function createLoginSessionForTask(
task: TaskRow, task: TaskRow,
orderNo: string, orderNo: string,
@@ -679,6 +753,98 @@ export async function markCustomerLinkOpened(orderNoInput: unknown, taskIdInput:
return { ok: true } 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) { function mapLoginUpdate(session: ConnectorLoginSession) {
const statusMap: Record<ConnectorLoginSession['status'], LoginStatus> = { const statusMap: Record<ConnectorLoginSession['status'], LoginStatus> = {
verification_pending: 'waiting_login', verification_pending: 'waiting_login',
@@ -705,8 +871,13 @@ async function updateLoginTask(
options: { credentialSource?: 'qr' | 'sms'; method?: 'qr' | 'sms' } = {}, options: { credentialSource?: 'qr' | 'sms'; method?: 'qr' | 'sms' } = {},
) { ) {
const mapped = mapLoginUpdate(session) const mapped = mapLoginUpdate(session)
// 虎牙登录成功还不算授权完成,必须等客户确认绑定角色;微博登录即授权。
const nextExecutionStatus: ExecutionStatus = 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 = const storedCredential =
mapped.status === 'authenticated' && mapped.hasCredential mapped.status === 'authenticated' && mapped.hasCredential
? task.platform === 'weibo' ? task.platform === 'weibo'
@@ -750,19 +921,22 @@ async function updateLoginTask(
credentialId, credentialId,
], ],
) )
await appendTaskEvent(client, task.id, { // 轮询会每 2 秒调用一次:状态与执行状态都没变时不写事件,避免时间线被重复项淹没。
eventType: 'login_status_changed', if (mapped.status !== task.login_status || nextExecutionStatus !== task.execution_status) {
actorType, await appendTaskEvent(client, task.id, {
fromLoginStatus: task.login_status, eventType: 'login_status_changed',
toLoginStatus: mapped.status, actorType,
fromExecutionStatus: task.execution_status, fromLoginStatus: task.login_status,
toExecutionStatus: nextExecutionStatus, toLoginStatus: mapped.status,
detail: { fromExecutionStatus: task.execution_status,
hasCredential: mapped.hasCredential, toExecutionStatus: nextExecutionStatus,
message: mapped.message, detail: {
method: options.method || 'qr', hasCredential: mapped.hasCredential,
}, message: mapped.message,
}) method: options.method || 'qr',
},
})
}
}) })
} }
@@ -779,27 +953,161 @@ function mapBindingUpdate(session: ConnectorBindingSession) {
return { return {
status: statusMap[session.status] || 'failed', status: statusMap[session.status] || 'failed',
qrImage: String(session.qrImage || ''), qrImage: String(session.qrImage || ''),
qrExpiresAt: String(session.qrExpiresAt || ''),
qrUrl: String(session.qrUrl || ''),
bindGameAccount: String(session.bindGameAccount || ''), bindGameAccount: String(session.bindGameAccount || ''),
bindGameRole: String(session.bindGameRole || ''), bindGameRole: String(session.bindGameRole || ''),
bindGameRoleId: String(session.bindGameRoleId || ''),
bindGameChannel: String(session.bindGameChannel || ''), 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 || ''), 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( async function updateBindingTask(
task: TaskRow, task: TaskRow,
session: ConnectorBindingSession, session: ConnectorBindingSession,
actorType: TaskActorType, actorType: TaskActorType,
) { ) {
const mapped = mapBindingUpdate(session) const mapped = mapBindingUpdate(session)
const comparison = compareBindingRole(task, mapped)
const executionStatus: ExecutionStatus = const executionStatus: ExecutionStatus =
mapped.status === 'confirmed' mapped.status === 'confirmed'
? 'waiting_operator' ? 'waiting_operator'
: mapped.status === 'failed' || mapped.status === 'expired' : task.execution_status === 'completed' || task.execution_status === 'cancelled'
? 'failed' ? task.execution_status
: task.execution_status === 'completed' || task.execution_status === 'cancelled' : 'waiting_customer'
? task.execution_status
: 'waiting_customer'
await withTransaction(async (client) => { await withTransaction(async (client) => {
await client.query( await client.query(
` `
@@ -807,6 +1115,7 @@ async function updateBindingTask(
SET binding_status = $2, SET binding_status = $2,
bind_game_account = CASE WHEN $3 <> '' THEN $3 ELSE bind_game_account END, 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 = 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, 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, bound_at = CASE WHEN $2 IN ('role_ready', 'confirmed') THEN COALESCE(bound_at, NOW()) ELSE bound_at END,
execution_status = $6, execution_status = $6,
@@ -822,30 +1131,66 @@ async function updateBindingTask(
mapped.bindGameChannel, mapped.bindGameChannel,
executionStatus, executionStatus,
mapped.message, mapped.message,
mapped.bindGameRoleId,
], ],
) )
await appendTaskEvent(client, task.id, { // 轮询会每 2 秒调用一次:只有状态/执行状态变化,或换绑被拒这类关键信号才写事件。
eventType: 'binding_status_changed', const bindingChanged =
actorType, mapped.status !== task.binding_status ||
fromBindingStatus: task.binding_status, executionStatus !== task.execution_status ||
toBindingStatus: mapped.status, mapped.rebindUnchanged ||
fromExecutionStatus: task.execution_status, mapped.rebindConfirmState === 'rejected'
toExecutionStatus: executionStatus, if (bindingChanged) {
detail: { await appendTaskEvent(client, task.id, {
gameAccount: mapped.bindGameAccount, eventType: 'binding_status_changed',
gameRole: mapped.bindGameRole, actorType,
gameChannel: mapped.bindGameChannel, fromBindingStatus: task.binding_status,
message: mapped.message, 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 { return {
status: mapped.status, status: mapped.status,
qrImage: mapped.qrImage, qrImage: mapped.qrImage,
qrExpiresAt: mapped.qrExpiresAt,
qrUrl: mapped.qrUrl,
bindGameAccount: mapped.bindGameAccount, bindGameAccount: mapped.bindGameAccount,
bindGameRole: mapped.bindGameRole, bindGameRole: mapped.bindGameRole,
bindGameRoleId: mapped.bindGameRoleId,
bindGameChannel: mapped.bindGameChannel, bindGameChannel: mapped.bindGameChannel,
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, message: mapped.message,
comparison,
} }
} }
@@ -854,6 +1199,7 @@ export async function startPublicLogin(orderNoInput: unknown, taskIdInput: unkno
const taskId = normalizeId(taskIdInput) const taskId = normalizeId(taskIdInput)
await ensureSemiAutoTasksForOrder(orderNo) await ensureSemiAutoTasksForOrder(orderNo)
const task = await loadTaskForOrder(orderNo, taskId) const task = await loadTaskForOrder(orderNo, taskId)
assertCustomerProfileReady(task)
if (task.execution_status === 'completed' || task.execution_status === 'cancelled') { if (task.execution_status === 'completed' || task.execution_status === 'cancelled') {
throw createHttpError('当前订单已结束,不能重新登录', { throw createHttpError('当前订单已结束,不能重新登录', {
statusCode: 409, statusCode: 409,
@@ -907,6 +1253,13 @@ export async function startPublicLogin(orderNoInput: unknown, taskIdInput: unkno
UPDATE semi_auto_tasks UPDATE semi_auto_tasks
SET connector_session_id = $2, SET connector_session_id = $2,
login_status = 'qr_pending', 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', execution_status = 'waiting_customer',
auth_started_at = COALESCE(auth_started_at, NOW()), auth_started_at = COALESCE(auth_started_at, NOW()),
last_error = '', last_error = '',
@@ -1007,7 +1360,11 @@ export async function pollPublicBinding(orderNoInput: unknown, taskIdInput: unkn
return { task: mapTask(updated), binding } 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 orderNo = normalizeOrderNo(orderNoInput)
const taskId = normalizeId(taskIdInput) const taskId = normalizeId(taskIdInput)
const task = await loadTaskForOrder(orderNo, taskId) const task = await loadTaskForOrder(orderNo, taskId)
@@ -1026,7 +1383,72 @@ export async function confirmPublicBinding(orderNoInput: unknown, taskIdInput: u
errorCode: 'semi_auto_binding_not_ready', 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',
},
)
}
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 binding = await updateBindingTask(task, session, 'customer')
const updated = await loadTask(task.id) const updated = await loadTask(task.id)
return { task: mapTask(updated), binding } return { task: mapTask(updated), binding }
@@ -1041,6 +1463,7 @@ export async function sendPublicHuyaSmsCode(
const taskId = normalizeId(taskIdInput) const taskId = normalizeId(taskIdInput)
const task = await loadTaskForOrder(orderNo, taskId) const task = await loadTaskForOrder(orderNo, taskId)
assertHuyaTask(task) assertHuyaTask(task)
assertCustomerProfileReady(task)
if (task.execution_status === 'completed' || task.execution_status === 'cancelled') { if (task.execution_status === 'completed' || task.execution_status === 'cancelled') {
throw createHttpError('当前订单已结束,不能重新登录', { throw createHttpError('当前订单已结束,不能重新登录', {
statusCode: 409, statusCode: 409,
@@ -1190,6 +1613,7 @@ export async function loginPublicHuyaSms(
const taskId = normalizeId(taskIdInput) const taskId = normalizeId(taskIdInput)
const task = await loadTaskForOrder(orderNo, taskId) const task = await loadTaskForOrder(orderNo, taskId)
assertHuyaTask(task) assertHuyaTask(task)
assertCustomerProfileReady(task)
if (task.execution_status === 'completed' || task.execution_status === 'cancelled') { if (task.execution_status === 'completed' || task.execution_status === 'cancelled') {
throw createHttpError('当前订单已结束,不能重新登录', { throw createHttpError('当前订单已结束,不能重新登录', {
statusCode: 409, statusCode: 409,
@@ -1504,6 +1928,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) { export async function exportAdminSemiAutoCredential(taskIdInput: unknown) {
const task = await loadTask(normalizeId(taskIdInput)) const task = await loadTask(normalizeId(taskIdInput))
if (!task.credential_id) { 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', status: 'confirmed',
qrImage: '', qrImage: '',
qrExpiresAt: '', qrExpiresAt: '',
qrUrl: '',
bindGameAccount: account?.nickname || '', bindGameAccount: account?.nickname || '',
bindGameRole: account?.uid || '', bindGameRole: account?.uid || '',
bindGameRoleId: account?.uid || '',
bindGameChannel: '微博', bindGameChannel: '微博',
hasExistingBinding: true, hasExistingBinding: true,
rebindRequested: false, rebindRequested: false,
@@ -0,0 +1,827 @@
import { ArrowRightOutlined, CopyOutlined, ReloadOutlined } from '@ant-design/icons'
import {
App,
Button,
Card,
Checkbox,
Col,
Collapse,
Descriptions,
Drawer,
Empty,
Input,
Pagination,
Row,
Select,
Space,
Tabs,
Tag,
theme,
Timeline,
Typography,
} from 'antd'
import { useQuery } from '@tanstack/react-query'
import { useEffect, useMemo, useState } from 'react'
import type { CSSProperties } from 'react'
import { fetchAdminSemiAutoTaskHistory } from '@/services/admin/semi-auto'
import type { SemiAutoTaskHistoryEvent, SemiAutoTraceItem } from '@/types/admin/semi-auto'
import { formatAdminDateTime } from '@/utils/admin-time'
import { useIsMobile } from '@/utils/use-is-mobile'
const { Text } = Typography
/** 非状态类事件:名称直接写清楚「谁做了什么」。 */
const EVENT_TITLES: Record<string, string> = {
task_created: '创建履约任务',
customer_link_opened: '客户打开授权页',
customer_profile_saved: '客户提交游戏角色',
login_started: '客户开始登录',
task_claimed: '客服领取任务',
customer_reauth_requested: '客服重新发起授权',
browser_session_opened: '客服生成浏览器登录票据',
credential_session_restored: '使用已保存 CK 恢复登录',
credential_invalidated: '平台 CK 已失效',
task_completed: '客服完成履约',
task_cancelled: '任务已取消',
}
/** 状态变更事件:按「变更后的状态」命名,读起来就是一句操作结果。 */
const LOGIN_EVENT_TITLES: Record<string, string> = {
waiting_code: '等待客户输入验证码',
qr_pending: '生成登录二维码',
scanned: '客户已扫码,等待确认',
authenticated: '客户完成平台登录',
failed: '平台登录失败',
expired: '登录二维码已过期',
}
const BINDING_EVENT_TITLES: Record<string, string> = {
not_started: '绑定状态重置',
qr_pending: '生成绑定二维码',
scanned: '客户已扫码绑定',
role_ready: '平台识别到游戏角色',
confirmed: '客户确认绑定角色',
failed: '角色绑定失败',
expired: '绑定二维码已过期',
}
const CHANNEL_LABELS: Record<string, string> = {
customer_api: '客户接口',
admin_api: '运营接口',
huya_wup: '虎牙 WUP',
huya_http: '虎牙 HTTP',
external_connector: '外部 Connector',
}
const CHANNEL_COLORS: Record<string, string> = {
customer_api: 'blue',
admin_api: 'cyan',
huya_wup: 'purple',
huya_http: 'geekblue',
external_connector: 'gold',
}
const CHANNEL_OPTIONS = Object.keys(CHANNEL_LABELS).map((value) => ({
value,
label: CHANNEL_LABELS[value],
}))
const ACTOR_LABELS: Record<string, string> = {
system: '系统',
customer: '客户',
admin: '客服',
connector: '平台连接器',
}
const ACTOR_COLORS: Record<string, string> = {
system: 'default',
customer: 'blue',
admin: 'cyan',
connector: 'purple',
}
const ACTOR_OPTIONS = Object.keys(ACTOR_LABELS).map((value) => ({
value,
label: ACTOR_LABELS[value],
}))
const LOGIN_STATUS_LABELS: Record<string, string> = {
waiting_login: '等待登录',
qr_pending: '待扫码',
scanned: '已扫码',
authenticated: '已登录',
failed: '登录失败',
expired: '登录过期',
}
const BINDING_STATUS_LABELS: Record<string, string> = {
not_started: '未开始',
qr_pending: '待扫码',
scanned: '已扫码',
role_ready: '待确认角色',
confirmed: '已确认',
failed: '绑定失败',
expired: '已过期',
}
const EXECUTION_STATUS_LABELS: Record<string, string> = {
waiting_customer: '等待客户',
waiting_operator: '等待客服',
processing: '处理中',
completed: '已完成',
failed: '失败',
cancelled: '已取消',
}
/** antd 6 的 Timeline 预设色会被主题色覆盖,这里用固定色值保证语义色稳定。 */
const TIMELINE_COLORS = {
gray: '#8c8c8c',
green: '#52c41a',
blue: '#1677ff',
gold: '#faad14',
cyan: '#13c2c2',
red: '#ff4d4f',
}
type SemiAutoTaskHistoryDrawerProps = {
open: boolean
taskId: number | null
onClose: () => void
}
export default function SemiAutoTaskHistoryDrawer({
open,
taskId,
onClose,
}: SemiAutoTaskHistoryDrawerProps) {
const { message } = App.useApp()
const isMobile = useIsMobile()
const { token } = theme.useToken()
const [tab, setTab] = useState('events')
const [eventActor, setEventActor] = useState('')
const [onlyError, setOnlyError] = useState(false)
const [channel, setChannel] = useState('')
const [status, setStatus] = useState('')
const [keywordDraft, setKeywordDraft] = useState('')
const [keyword, setKeyword] = useState('')
const [requestId, setRequestId] = useState('')
const [page, setPage] = useState(1)
const [pageSize, setPageSize] = useState(50)
useEffect(() => {
if (!open) return
setTab('events')
setEventActor('')
setOnlyError(false)
setChannel('')
setStatus('')
setKeywordDraft('')
setKeyword('')
setRequestId('')
setPage(1)
setPageSize(50)
}, [open, taskId])
const params = useMemo(
() => ({
page,
pageSize,
channel: channel || undefined,
status: status || undefined,
keyword: keyword.trim() || undefined,
requestId: requestId || undefined,
}),
[channel, keyword, page, pageSize, requestId, status],
)
const historyQuery = useQuery({
queryKey: ['admin-semi-auto-task-history', taskId, params],
queryFn: () => fetchAdminSemiAutoTaskHistory(Number(taskId), params),
enabled: open && Boolean(taskId),
refetchInterval: open && Boolean(taskId) ? 8000 : false,
})
const history = historyQuery.data?.data
const events = history?.events || []
const traces = history?.traces
const traceItems = traces?.items || []
const visibleEvents = events.filter((event) => {
if (eventActor && event.actorType !== eventActor) return false
if (onlyError && !eventIsFailure(event)) return false
return true
})
const preStyle: CSSProperties = {
margin: '6px 0 0',
padding: 10,
background: token.colorFillQuaternary,
border: `1px solid ${token.colorBorderSecondary}`,
borderRadius: token.borderRadius,
color: token.colorText,
fontSize: 12,
lineHeight: 1.55,
maxHeight: 280,
overflow: 'auto',
whiteSpace: 'pre-wrap',
wordBreak: 'break-all',
}
const copyText = (text: string, label: string) => {
if (!text) {
message.warning(`${label}为空`)
return
}
void navigator.clipboard
.writeText(text)
.then(() => message.success(`${label}已复制`))
.catch(() => message.error('复制失败,请手动选择文本复制'))
}
const eventsPanel = (
<Space direction="vertical" size={12} style={{ width: '100%' }}>
{history?.task ? (
<Card size="small">
<Descriptions
size="small"
column={isMobile ? 1 : 3}
items={[
{
key: 'login',
label: '登录状态',
children: (
<Tag color={loginTagColor(history.task.loginStatus)}>
{LOGIN_STATUS_LABELS[history.task.loginStatus] || history.task.loginStatus}
</Tag>
),
},
{
key: 'binding',
label: '绑定状态',
children: (
<Tag color={bindingTagColor(history.task.bindingStatus)}>
{history.task.platform === 'weibo'
? '登录即授权'
: BINDING_STATUS_LABELS[history.task.bindingStatus] ||
history.task.bindingStatus}
</Tag>
),
},
{
key: 'execution',
label: '执行状态',
children: (
<Tag color={executionTagColor(history.task.executionStatus)}>
{EXECUTION_STATUS_LABELS[history.task.executionStatus] ||
history.task.executionStatus}
</Tag>
),
},
{
key: 'createdAt',
label: '创建时间',
children: formatAdminDateTime(history.task.createdAt),
},
{
key: 'completedAt',
label: '完成时间',
children: history.task.completedAt
? formatAdminDateTime(history.task.completedAt)
: '—',
},
{
key: 'eventTotal',
label: '事件数量',
children: `${history.eventTotal} 条`,
},
]}
/>
</Card>
) : null}
<Space wrap>
<Select
allowClear
placeholder="全部来源"
value={eventActor || undefined}
onChange={(value) => setEventActor(value || '')}
options={ACTOR_OPTIONS}
style={{ width: 140 }}
/>
<Checkbox checked={onlyError} onChange={(event) => setOnlyError(event.target.checked)}>
只看异常
</Checkbox>
<Text type="secondary">
共 {events.length} 个节点,当前显示 {visibleEvents.length} 个
</Text>
{history && history.eventTotal > events.length ? (
<Text type="secondary">
(仅展示最近 {events.length} 条,共 {history.eventTotal} 条)
</Text>
) : null}
</Space>
{historyQuery.isLoading ? (
<Text type="secondary">加载中...</Text>
) : visibleEvents.length === 0 ? (
<Empty
description={
events.length > 0 ? '当前筛选条件下没有节点' : '暂无状态流转记录(客户还未开始操作)'
}
/>
) : (
<Timeline
mode={isMobile ? undefined : 'left'}
items={visibleEvents.map((event) => ({
key: String(event.id),
color: eventDotColor(event),
label: isMobile ? undefined : (
<Text type="secondary" style={{ fontSize: 12 }}>
{formatAdminDateTime(event.createdAt)}
</Text>
),
children: <EventItem event={event} preStyle={preStyle} showTime={isMobile} />,
}))}
/>
)}
</Space>
)
const tracesPanel = (
<Space direction="vertical" size={12} style={{ width: '100%' }}>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, alignItems: 'center' }}>
<Select
allowClear
placeholder="全部渠道"
value={channel || undefined}
onChange={(value) => {
setChannel(value || '')
setPage(1)
}}
options={CHANNEL_OPTIONS}
style={isMobile ? { flex: '1 1 150px', minWidth: 120 } : { width: 160 }}
/>
<Select
allowClear
placeholder="全部结果"
value={status || undefined}
onChange={(value) => {
setStatus(value || '')
setPage(1)
}}
options={[
{ value: 'ok', label: '成功' },
{ value: 'error', label: '失败' },
]}
style={isMobile ? { flex: '1 1 110px', minWidth: 96 } : { width: 120 }}
/>
<Input.Search
allowClear
placeholder="动作 / 报文内容关键字"
value={keywordDraft}
onChange={(event) => setKeywordDraft(event.target.value)}
onSearch={(value) => {
setKeyword(value)
setPage(1)
}}
style={isMobile ? { flex: '1 1 220px' } : { width: 240 }}
/>
<Button icon={<ReloadOutlined />} onClick={() => void historyQuery.refetch()}>
刷新
</Button>
{requestId ? (
<Tag
closable
color="blue"
onClose={() => {
setRequestId('')
setPage(1)
}}
>
同一请求:{requestId}
</Tag>
) : null}
</div>
{traces?.summary?.length ? (
<Space size={4} wrap>
{traces.summary.map((item) => (
<Tag
key={`${item.channel}-${item.status}`}
color={item.status === 'error' ? 'red' : 'default'}
>
{CHANNEL_LABELS[item.channel] || item.channel} ·{' '}
{item.status === 'error' ? '失败' : '成功'} {item.total}
</Tag>
))}
</Space>
) : null}
<Text type="secondary">
报文保留 180 天;Cookie、Token、短信验证码和二维码内容不落库。轮询只在状态变化或失败时记录。
</Text>
{historyQuery.isLoading ? (
<Text type="secondary">加载中...</Text>
) : traceItems.length === 0 ? (
<Empty description="暂无报文记录" />
) : (
<Collapse
size="small"
items={traceItems.map((item) => ({
key: String(item.id),
label: <TraceLabel item={item} />,
children: (
<TracePayload
item={item}
preStyle={preStyle}
onCopy={copyText}
onFilterRequest={(value) => {
setRequestId(value)
setPage(1)
}}
/>
),
}))}
/>
)}
<Pagination
size={isMobile ? 'small' : undefined}
current={traces?.pagination.page || page}
pageSize={traces?.pagination.pageSize || pageSize}
total={traces?.pagination.total || 0}
showSizeChanger={!isMobile}
showTotal={(total) => `共 ${total} 条`}
onChange={(nextPage, nextPageSize) => {
setPage(nextPage)
setPageSize(nextPageSize)
}}
/>
</Space>
)
return (
<Drawer
open={open}
width={isMobile ? '100%' : 1000}
title={
<Space direction="vertical" size={0}>
<Text strong>履约历史</Text>
<Text type="secondary" style={{ fontSize: 12 }}>
{history?.task?.orderNo || '—'}
</Text>
</Space>
}
onClose={onClose}
extra={
<Button size="small" icon={<ReloadOutlined />} onClick={() => void historyQuery.refetch()}>
刷新
</Button>
}
>
<Tabs
activeKey={tab}
onChange={setTab}
items={[
{
key: 'events',
label: `状态流转(${history?.eventTotal ?? 0})`,
children: eventsPanel,
},
{
key: 'traces',
label: `全链路报文(${traces?.pagination.total ?? 0})`,
children: tracesPanel,
},
]}
/>
</Drawer>
)
}
function EventItem({
event,
preStyle,
showTime,
}: {
event: SemiAutoTaskHistoryEvent
preStyle: CSSProperties
showTime: boolean
}) {
const detail = event.detail || {}
const transitions = [
{
key: 'login',
label: '登录',
map: LOGIN_STATUS_LABELS,
from: event.fromLoginStatus,
to: event.toLoginStatus,
},
{
key: 'binding',
label: '绑定',
map: BINDING_STATUS_LABELS,
from: event.fromBindingStatus,
to: event.toBindingStatus,
},
{
key: 'execution',
label: '执行',
map: EXECUTION_STATUS_LABELS,
from: event.fromExecutionStatus,
to: event.toExecutionStatus,
},
].filter((item) => item.from !== item.to && Boolean(item.from || item.to))
const summary = resolveEventSummary(event)
const detailKeys = Object.keys(detail)
return (
<Space direction="vertical" size={4} style={{ width: '100%' }}>
<Space size={6} wrap align="center">
<Text strong>{resolveEventTitle(event)}</Text>
<Tag color={ACTOR_COLORS[event.actorType] || 'default'}>
{ACTOR_LABELS[event.actorType] || event.actorType}
</Tag>
{eventIsFailure(event) ? <Tag color="red">异常</Tag> : null}
</Space>
{showTime ? (
<Text type="secondary" style={{ fontSize: 12 }}>
{formatAdminDateTime(event.createdAt)}
</Text>
) : null}
{transitions.map((item) => (
<Space key={item.key} size={4} wrap>
<Text type="secondary" style={{ fontSize: 12, minWidth: 28 }}>
{item.label}
</Text>
<Tag bordered={false}>{statusLabel(item.map, item.from)}</Tag>
<ArrowRightOutlined style={{ fontSize: 10 }} />
<Tag bordered={false} color={transitionColor(item.key, item.to)}>
{statusLabel(item.map, item.to)}
</Tag>
</Space>
))}
{summary ? <Text style={{ fontSize: 13 }}>{summary}</Text> : null}
{detailKeys.length > 0 ? (
<Collapse
ghost
size="small"
items={[
{
key: 'detail',
label: (
<Text type="secondary" style={{ fontSize: 12 }}>
查看原始详情
</Text>
),
children: <pre style={preStyle}>{JSON.stringify(detail, null, 2)}</pre>,
},
]}
/>
) : null}
</Space>
)
}
function TraceLabel({ item }: { item: SemiAutoTraceItem }) {
return (
<Space direction="vertical" size={2} style={{ width: '100%' }}>
<Space size={6} wrap>
<Tag color={item.direction === 'inbound' ? 'blue' : 'purple'}>
{item.direction === 'inbound' ? '入站' : '出站'}
</Tag>
<Tag color={CHANNEL_COLORS[item.channel] || 'default'}>
{CHANNEL_LABELS[item.channel] || item.channel}
</Tag>
<Tag color={item.status === 'ok' ? 'green' : 'red'}>
{item.status === 'ok' ? '成功' : '失败'}
</Tag>
{item.httpStatus ? <Text type="secondary">HTTP {item.httpStatus}</Text> : null}
{item.durationMs !== null && item.durationMs !== undefined ? (
<Text type="secondary">{item.durationMs}ms</Text>
) : null}
<Text type="secondary">{formatAdminDateTime(item.createdAt)}</Text>
</Space>
<Text code style={{ whiteSpace: 'break-all' }}>
{item.action}
</Text>
{item.errorMessage ? <Text type="danger">{item.errorMessage}</Text> : null}
</Space>
)
}
function TracePayload({
item,
preStyle,
onCopy,
onFilterRequest,
}: {
item: SemiAutoTraceItem
preStyle: CSSProperties
onCopy: (text: string, label: string) => void
onFilterRequest: (requestId: string) => void
}) {
return (
<Space direction="vertical" size={10} style={{ width: '100%' }}>
<Row gutter={[12, 12]}>
<Col xs={24} lg={12}>
<Space direction="vertical" size={10} style={{ width: '100%' }}>
<PayloadBlock title="请求参数" value={item.requestSummary} preStyle={preStyle} />
<PayloadBlock title="请求原文" value={item.requestBody} preStyle={preStyle} />
</Space>
</Col>
<Col xs={24} lg={12}>
<Space direction="vertical" size={10} style={{ width: '100%' }}>
<PayloadBlock title="响应结果" value={item.responseSummary} preStyle={preStyle} />
<PayloadBlock title="响应原文" value={item.responseBody} preStyle={preStyle} />
</Space>
</Col>
</Row>
<Space size={6} wrap>
<Button
size="small"
icon={<CopyOutlined />}
onClick={() =>
onCopy(
[
`动作:${item.action}`,
`requestId:${item.requestId}`,
'',
'# 请求',
item.requestBody,
'',
'# 响应',
item.responseBody,
].join('\n'),
'完整报文',
)
}
>
复制完整报文
</Button>
{item.requestId ? (
<Button size="small" onClick={() => onFilterRequest(item.requestId)}>
只看同一请求
</Button>
) : null}
<Text type="secondary">requestId:{item.requestId || '-'}</Text>
</Space>
</Space>
)
}
function PayloadBlock({
title,
value,
preStyle,
}: {
title: string
value: unknown
preStyle: CSSProperties
}) {
const text =
value && typeof value === 'object'
? Object.keys(value as Record<string, unknown>).length > 0
? JSON.stringify(value, null, 2)
: ''
: String(value || '').trim()
return (
<div>
<Text strong>{title}</Text>
{text ? <pre style={preStyle}>{text}</pre> : <Text type="secondary">(空)</Text>}
</div>
)
}
function resolveEventTitle(event: SemiAutoTaskHistoryEvent) {
if (event.eventType === 'login_status_changed') {
return LOGIN_EVENT_TITLES[event.toLoginStatus || ''] || '登录状态变更'
}
if (event.eventType === 'binding_status_changed') {
if (
event.detail?.rebindUnchanged === true ||
String(event.detail?.rebindConfirmState || '') === 'rejected'
) {
return '换绑被平台拒绝'
}
return BINDING_EVENT_TITLES[event.toBindingStatus || ''] || '绑定状态变更'
}
return EVENT_TITLES[event.eventType] || event.eventType
}
function resolveEventSummary(event: SemiAutoTaskHistoryEvent) {
const detail = event.detail || {}
const text = (value: unknown) => String(value ?? '').trim()
if (event.eventType === 'customer_profile_saved') {
return [
text(detail.roleName) ? `角色:${text(detail.roleName)}` : '',
text(detail.roleId) ? `编号:${text(detail.roleId)}` : '',
text(detail.serverZone) ? `区服:${text(detail.serverZone)}` : '',
]
.filter(Boolean)
.join(' · ')
}
if (event.eventType === 'binding_status_changed') {
const parts: string[] = []
if (text(detail.gameRole)) {
parts.push(
`绑定角色:${text(detail.gameRole)}${
text(detail.gameRoleId) ? `(${text(detail.gameRoleId)})` : ''
}`,
)
}
if (detail.rebindUnchanged === true) parts.push('平台仍返回原绑定角色')
const message = text(detail.message) || text(detail.rebindConfirmMessage)
if (message) parts.push(message)
return parts.join(' · ')
}
if (event.eventType === 'login_status_changed') {
const method = text(detail.method)
const methodLabel = method === 'sms' ? '短信验证码' : method === 'qr' ? '扫码' : ''
return [methodLabel ? `登录方式:${methodLabel}` : '', text(detail.message)]
.filter(Boolean)
.join(' · ')
}
if (event.eventType === 'task_completed') {
return [
text(detail.note),
text(detail.externalOrderNo) ? `外部单号:${text(detail.externalOrderNo)}` : '',
]
.filter(Boolean)
.join(' · ')
}
return text(detail.message) || text(detail.reason) || text(detail.note)
}
function eventIsFailure(event: SemiAutoTaskHistoryEvent) {
if (event.eventType === 'task_cancelled') return false
if (/fail|invalid|error/i.test(event.eventType)) return true
if (event.toLoginStatus === 'failed' || event.toLoginStatus === 'expired') return true
if (event.toBindingStatus === 'failed' || event.toBindingStatus === 'expired') return true
if (
event.detail?.rebindUnchanged === true ||
String(event.detail?.rebindConfirmState || '') === 'rejected'
) {
return true
}
return false
}
function eventDotColor(event: SemiAutoTaskHistoryEvent) {
if (eventIsFailure(event)) return TIMELINE_COLORS.red
switch (event.eventType) {
case 'task_created':
return TIMELINE_COLORS.gray
case 'customer_link_opened':
case 'customer_profile_saved':
return TIMELINE_COLORS.green
case 'login_started':
case 'login_status_changed':
return TIMELINE_COLORS.blue
case 'binding_status_changed':
return TIMELINE_COLORS.gold
case 'task_claimed':
case 'customer_reauth_requested':
case 'browser_session_opened':
return TIMELINE_COLORS.cyan
case 'task_completed':
return TIMELINE_COLORS.green
case 'task_cancelled':
return TIMELINE_COLORS.gray
default:
return TIMELINE_COLORS.blue
}
}
function loginTagColor(status: string) {
if (status === 'authenticated') return 'green'
if (status === 'failed' || status === 'expired') return 'red'
return 'blue'
}
function bindingTagColor(status: string) {
if (status === 'confirmed') return 'green'
if (status === 'role_ready') return 'gold'
if (status === 'failed' || status === 'expired') return 'red'
return 'blue'
}
function executionTagColor(status: string) {
if (status === 'completed') return 'green'
if (status === 'failed') return 'red'
if (status === 'cancelled') return 'default'
if (status === 'waiting_operator') return 'orange'
if (status === 'processing') return 'blue'
return 'blue'
}
function transitionColor(kind: string, value: string | null) {
if (kind === 'login') return loginTagColor(String(value || ''))
if (kind === 'binding') return bindingTagColor(String(value || ''))
return executionTagColor(String(value || ''))
}
function statusLabel(map: Record<string, string>, value: string | null) {
if (!value) return '初始'
return map[value] || value
}
+22
View File
@@ -138,6 +138,21 @@ function applySessionExpiryHeaders(
} }
} }
/** HTTP 状态码兜底文案:避免把英文 statusText(如 Not Found)原样抛给用户 */
const HTTP_STATUS_MESSAGES: Record<number, string> = {
400: '请求参数有误',
401: '登录状态已失效,请重新登录',
403: '没有操作权限',
404: '接口不存在,请刷新页面后重试',
409: '数据已更新,请刷新后重试',
422: '提交的数据不合法',
429: '操作过于频繁,请稍后再试',
500: '服务器开小差了,请稍后重试',
502: '服务暂时不可用,请稍后重试',
503: '服务维护中,请稍后重试',
504: '请求超时,请稍后重试',
}
function resolveFallbackHttpMessage(error: unknown) { function resolveFallbackHttpMessage(error: unknown) {
const message = String((error as { message?: string })?.message ?? '') const message = String((error as { message?: string })?.message ?? '')
@@ -149,6 +164,13 @@ function resolveFallbackHttpMessage(error: unknown) {
return '网络连接错误' return '网络连接错误'
} }
const status = Number((error as { response?: { status?: number } })?.response?.status || 0)
const statusMessage = status > 0 ? HTTP_STATUS_MESSAGES[status] : ''
if (statusMessage) {
return statusMessage
}
if (typeof (error as { response?: { statusText?: string } })?.response?.statusText === 'string') { if (typeof (error as { response?: { statusText?: string } })?.response?.statusText === 'string') {
return String((error as { response: { statusText: string } }).response.statusText).trim() return String((error as { response: { statusText: string } }).response.statusText).trim()
} }
@@ -2,6 +2,7 @@ import {
CheckCircleOutlined, CheckCircleOutlined,
ChromeOutlined, ChromeOutlined,
CopyOutlined, CopyOutlined,
HistoryOutlined,
KeyOutlined, KeyOutlined,
ReloadOutlined, ReloadOutlined,
SendOutlined, SendOutlined,
@@ -30,6 +31,7 @@ import { useEffect, useMemo, useState } from 'react'
import ImageUpload from '@/components/files/ImageUpload' import ImageUpload from '@/components/files/ImageUpload'
import PageHeader from '@/components/admin/PageHeader' import PageHeader from '@/components/admin/PageHeader'
import SemiAutoTaskHistoryDrawer from '@/components/admin/SemiAutoTaskHistoryDrawer'
import PercentTable from '@/components/common/PercentTable' import PercentTable from '@/components/common/PercentTable'
import { import {
cancelAdminSemiAutoTask, cancelAdminSemiAutoTask,
@@ -54,6 +56,8 @@ const STATUS_COLORS: Record<string, string> = {
login_scanned: 'cyan', login_scanned: 'cyan',
waiting_binding: 'gold', waiting_binding: 'gold',
binding_confirm: 'orange', binding_confirm: 'orange',
binding_expired: 'red',
binding_failed: 'red',
waiting_operator: 'volcano', waiting_operator: 'volcano',
credential_expired: 'red', credential_expired: 'red',
processing: 'processing', processing: 'processing',
@@ -67,6 +71,16 @@ const PLATFORM_LABELS: Record<string, string> = {
weibo: '微博', weibo: '微博',
} }
const BINDING_STATUS_LABELS: Record<string, string> = {
not_started: '未开始',
qr_pending: '待扫码',
scanned: '已扫码',
role_ready: '待确认角色',
confirmed: '已确认',
failed: '失败',
expired: '已过期',
}
type CompleteFormValues = { type CompleteFormValues = {
note?: string note?: string
externalOrderNo?: string externalOrderNo?: string
@@ -82,6 +96,7 @@ export default function AdminSemiAutoTasksPage() {
const [page, setPage] = useState(1) const [page, setPage] = useState(1)
const [pageSize, setPageSize] = useState(20) const [pageSize, setPageSize] = useState(20)
const [detailTaskId, setDetailTaskId] = useState<number | null>(null) const [detailTaskId, setDetailTaskId] = useState<number | null>(null)
const [historyTaskId, setHistoryTaskId] = useState<number | null>(null)
const [completeTask, setCompleteTask] = useState<SemiAutoTask | null>(null) const [completeTask, setCompleteTask] = useState<SemiAutoTask | null>(null)
const [completeFiles, setCompleteFiles] = useState<UploadedFile[]>([]) const [completeFiles, setCompleteFiles] = useState<UploadedFile[]>([])
const [completeForm] = Form.useForm<CompleteFormValues>() const [completeForm] = Form.useForm<CompleteFormValues>()
@@ -344,6 +359,16 @@ export default function AdminSemiAutoTasksPage() {
<Space direction="vertical" size={2}> <Space direction="vertical" size={2}>
<Tag>{task.displayStatus.label}</Tag> <Tag>{task.displayStatus.label}</Tag>
<Text type="secondary">{task.huyaUid ? `UID ${task.huyaUid}` : '未获取 UID'}</Text> <Text type="secondary">{task.huyaUid ? `UID ${task.huyaUid}` : '未获取 UID'}</Text>
<Text type="secondary">
{task.platform === 'huya'
? `绑定:${BINDING_STATUS_LABELS[task.bindingStatus] || task.bindingStatus}`
: '微博登录即授权'}
</Text>
{task.platform === 'huya' && (task.bindGameRole || task.bindGameRoleId) ? (
<Text type="secondary">
{`角色:${task.bindGameRole || '-'}${task.bindGameRoleId ? `(${task.bindGameRoleId})` : '(无角色ID)'}`}
</Text>
) : null}
<Text type="secondary"> <Text type="secondary">
CK: CK:
{task.credentialStatus === 'valid' {task.credentialStatus === 'valid'
@@ -394,6 +419,13 @@ export default function AdminSemiAutoTasksPage() {
<Button size="small" onClick={() => setDetailTaskId(task.id)}> <Button size="small" onClick={() => setDetailTaskId(task.id)}>
详情 详情
</Button> </Button>
<Button
size="small"
icon={<HistoryOutlined />}
onClick={() => setHistoryTaskId(task.id)}
>
历史
</Button>
{taskNeedsCustomerReauth(task) ? ( {taskNeedsCustomerReauth(task) ? (
<Button <Button
size="small" size="small"
@@ -616,6 +648,24 @@ export default function AdminSemiAutoTasksPage() {
<Descriptions.Item label="登录状态"> <Descriptions.Item label="登录状态">
{detail.task.loginStatus === 'authenticated' ? 'CK 已获取' : '等待客户登录'} {detail.task.loginStatus === 'authenticated' ? 'CK 已获取' : '等待客户登录'}
</Descriptions.Item> </Descriptions.Item>
<Descriptions.Item label="绑定状态">
{detail.task.platform === 'weibo'
? '微博登录即授权'
: BINDING_STATUS_LABELS[detail.task.bindingStatus] || detail.task.bindingStatus}
</Descriptions.Item>
<Descriptions.Item label="绑定角色">
{detail.task.bindGameRole
? `${detail.task.bindGameRole}${detail.task.bindGameRoleId ? `(${detail.task.bindGameRoleId})` : '(无角色ID)'}`
: '-'}
</Descriptions.Item>
<Descriptions.Item label="客户填写角色">
{detail.task.customerGameRoleName
? `${detail.task.customerGameRoleName}${detail.task.customerGameRoleId ? `(${detail.task.customerGameRoleId})` : ''}`
: '-'}
</Descriptions.Item>
<Descriptions.Item label="区服">
{detail.task.customerServerZone || '-'}
</Descriptions.Item>
<Descriptions.Item label="客服"> <Descriptions.Item label="客服">
{detail.task.assignedAdminName || '未领取'} {detail.task.assignedAdminName || '未领取'}
</Descriptions.Item> </Descriptions.Item>
@@ -687,6 +737,30 @@ export default function AdminSemiAutoTasksPage() {
{formatAdminDateTime(event.createdAt)} · {event.actorType} {formatAdminDateTime(event.createdAt)} · {event.actorType}
{event.actorId ? ` ${event.actorId}` : ''} {event.actorId ? ` ${event.actorId}` : ''}
</Text> </Text>
{event.eventType === 'binding_status_changed' && event.detail?.message ? (
<Text
type={
event.detail.rebindUnchanged === true ||
event.detail.rebindConfirmState === 'rejected'
? 'warning'
: 'secondary'
}
>
{String(event.detail.message)}
{Number(event.detail.rebindCooldownDays || 0) > 0 &&
event.detail.nextRebindAt
? ` · 下次可换绑 ${formatAdminDateTime(
String(event.detail.nextRebindAt),
)}`
: ''}
</Text>
) : null}
{event.eventType === 'binding_status_changed' &&
event.detail?.rebindConfirmMessage ? (
<Text type="secondary">
虎牙返回:{String(event.detail.rebindConfirmMessage)}
</Text>
) : null}
</Space> </Space>
), ),
}))} }))}
@@ -698,6 +772,12 @@ export default function AdminSemiAutoTasksPage() {
)} )}
</Drawer> </Drawer>
<SemiAutoTaskHistoryDrawer
open={Boolean(historyTaskId)}
taskId={historyTaskId}
onClose={() => setHistoryTaskId(null)}
/>
<Modal <Modal
open={Boolean(completeTask)} open={Boolean(completeTask)}
title="确认完成半自动履约" title="确认完成半自动履约"
@@ -765,6 +845,7 @@ function taskNeedsCustomerReauth(task: SemiAutoTask) {
function taskCanUseCredential(task: SemiAutoTask) { function taskCanUseCredential(task: SemiAutoTask) {
return ( return (
task.loginStatus === 'authenticated' && task.loginStatus === 'authenticated' &&
(task.platform === 'weibo' || task.bindingStatus === 'confirmed') &&
task.credentialReady && task.credentialReady &&
task.credentialStatus !== 'invalid' && task.credentialStatus !== 'invalid' &&
task.credentialStatus !== 'error' task.credentialStatus !== 'error'
File diff suppressed because it is too large Load Diff
@@ -2,6 +2,7 @@ import { apiGet, apiPost } from '@/lib/http'
import type { import type {
SemiAutoCredentialExport, SemiAutoCredentialExport,
SemiAutoTaskDetail, SemiAutoTaskDetail,
SemiAutoTaskHistory,
SemiAutoTaskListResult, SemiAutoTaskListResult,
} from '@/types/admin/semi-auto' } from '@/types/admin/semi-auto'
@@ -13,6 +14,13 @@ export function fetchAdminSemiAutoTask(taskId: number) {
return apiGet<SemiAutoTaskDetail>(`/api/v1/admin/semi-auto/tasks/${taskId}`) return apiGet<SemiAutoTaskDetail>(`/api/v1/admin/semi-auto/tasks/${taskId}`)
} }
export function fetchAdminSemiAutoTaskHistory(
taskId: number,
params: Record<string, unknown> = {},
) {
return apiGet<SemiAutoTaskHistory>(`/api/v1/admin/semi-auto/tasks/${taskId}/history`, params)
}
export function exportAdminSemiAutoCredential(taskId: number) { export function exportAdminSemiAutoCredential(taskId: number) {
return apiPost<SemiAutoCredentialExport>( return apiPost<SemiAutoCredentialExport>(
`/api/v1/admin/semi-auto/tasks/${taskId}/credential/export`, `/api/v1/admin/semi-auto/tasks/${taskId}/credential/export`,
@@ -1,5 +1,9 @@
import { apiGet, apiPost } from '@/lib/http' import { apiGet, apiPost } from '@/lib/http'
import type { CustomerLoginInfo, CustomerSemiAutoTask } from '@/types/customer-fulfillment' import type {
CustomerBindingInfo,
CustomerLoginInfo,
CustomerSemiAutoTask,
} from '@/types/customer-fulfillment'
export function fetchCustomerFulfillment(orderNo: string) { export function fetchCustomerFulfillment(orderNo: string) {
return apiGet<CustomerSemiAutoTask[]>( return apiGet<CustomerSemiAutoTask[]>(
@@ -14,6 +18,17 @@ export function markCustomerFulfillmentOpened(orderNo: string, taskId: number) {
) )
} }
export function saveCustomerTaskProfile(
orderNo: string,
taskId: number,
input: { roleName: string; roleId: string; serverZone: string },
) {
return apiPost<{ task: CustomerSemiAutoTask }>(
`/api/v1/customer-fulfillment/${encodeURIComponent(orderNo)}/tasks/${taskId}/profile`,
input,
)
}
export function startCustomerLogin(orderNo: string, taskId: number) { export function startCustomerLogin(orderNo: string, taskId: number) {
return apiPost<{ task: CustomerSemiAutoTask; login: CustomerLoginInfo }>( return apiPost<{ task: CustomerSemiAutoTask; login: CustomerLoginInfo }>(
`/api/v1/customer-fulfillment/${encodeURIComponent(orderNo)}/tasks/${taskId}/login/start`, `/api/v1/customer-fulfillment/${encodeURIComponent(orderNo)}/tasks/${taskId}/login/start`,
@@ -27,6 +42,41 @@ export function pollCustomerLogin(orderNo: string, taskId: number) {
) )
} }
export function startCustomerBinding(
orderNo: string,
taskId: number,
options: { forceRebind?: boolean } = {},
) {
return apiPost<{ task: CustomerSemiAutoTask; binding: CustomerBindingInfo }>(
`/api/v1/customer-fulfillment/${encodeURIComponent(orderNo)}/tasks/${taskId}/binding/start`,
options.forceRebind ? { forceRebind: true } : {},
)
}
export function pollCustomerBinding(orderNo: string, taskId: number) {
return apiGet<{ task: CustomerSemiAutoTask; binding: CustomerBindingInfo | null }>(
`/api/v1/customer-fulfillment/${encodeURIComponent(orderNo)}/tasks/${taskId}/binding/status`,
)
}
export function confirmCustomerBinding(
orderNo: string,
taskId: number,
options: { acceptExistingRole?: boolean } = {},
) {
return apiPost<{ task: CustomerSemiAutoTask; binding: CustomerBindingInfo }>(
`/api/v1/customer-fulfillment/${encodeURIComponent(orderNo)}/tasks/${taskId}/binding/confirm`,
options.acceptExistingRole ? { acceptExistingRole: true } : {},
)
}
export function submitCustomerRebind(orderNo: string, taskId: number) {
return apiPost<{ task: CustomerSemiAutoTask; binding: CustomerBindingInfo }>(
`/api/v1/customer-fulfillment/${encodeURIComponent(orderNo)}/tasks/${taskId}/binding/rebind`,
{},
)
}
type CustomerHuyaChallengeBase = { type CustomerHuyaChallengeBase = {
image: string image: string
width: number width: number
File diff suppressed because it is too large Load Diff
@@ -13,6 +13,7 @@ export type SemiAutoTask = {
platform: SemiAutoPlatform platform: SemiAutoPlatform
platformLabel: string platformLabel: string
loginStatus: string loginStatus: string
bindingStatus: string
executionStatus: string executionStatus: string
connectorMode: 'embedded' | 'external' | 'mock' connectorMode: 'embedded' | 'external' | 'mock'
displayStatus: SemiAutoDisplayStatus displayStatus: SemiAutoDisplayStatus
@@ -23,6 +24,13 @@ export type SemiAutoTask = {
credentialUpdatedAt: string | null credentialUpdatedAt: string | null
huyaUid: string huyaUid: string
platformNickname: string platformNickname: string
bindGameAccount: string
bindGameRole: string
bindGameRoleId: string
bindGameChannel: string
customerGameRoleId: string
customerGameRoleName: string
customerServerZone: string
targetQuantity: number targetQuantity: number
completedQuantity: number completedQuantity: number
assignedAdminUserId: number | null assignedAdminUserId: number | null
@@ -73,6 +81,65 @@ export type SemiAutoTaskDetail = {
events: SemiAutoTaskEvent[] events: SemiAutoTaskEvent[]
} }
export type SemiAutoTaskHistoryEvent = {
id: number
eventType: string
actorType: string
actorId: string
fromLoginStatus: string | null
toLoginStatus: string | null
fromBindingStatus: string | null
toBindingStatus: string | null
fromExecutionStatus: string | null
toExecutionStatus: string | null
detail: Record<string, unknown>
createdAt: string
}
export type SemiAutoTraceItem = {
id: number
orderNo: string
requestId: string
direction: 'inbound' | 'outbound' | string
channel: string
action: string
status: 'ok' | 'error' | string
httpStatus: number | null
durationMs: number | null
requestSummary: Record<string, unknown>
requestBody: string
responseSummary: Record<string, unknown>
responseBody: string
errorMessage: string
createdAt: string
}
export type SemiAutoTraceSummaryItem = {
channel: string
status: string
total: number
}
export type SemiAutoTraceQueryParams = {
page?: number
pageSize?: number
channel?: string
status?: string
requestId?: string
keyword?: string
}
export type SemiAutoTaskHistory = {
task: SemiAutoTask
events: SemiAutoTaskHistoryEvent[]
eventTotal: number
traces: {
pagination: { page: number; pageSize: number; total: number }
summary: SemiAutoTraceSummaryItem[]
items: SemiAutoTraceItem[]
}
}
export type SemiAutoCredentialExport = { export type SemiAutoCredentialExport = {
credentialId: number credentialId: number
platform: SemiAutoPlatform platform: SemiAutoPlatform
@@ -1,3 +1,14 @@
export type CustomerBindingComparison = {
verdict: 'match' | 'mismatch' | 'unknown'
customerRoleName: string
customerRoleId: string
customerZone: string
boundRoleName: string
boundRoleId: string
boundZone: string
message: string
}
export type CustomerSemiAutoTask = { export type CustomerSemiAutoTask = {
id: number id: number
platform: 'huya' | 'weibo' platform: 'huya' | 'weibo'
@@ -8,10 +19,18 @@ export type CustomerSemiAutoTask = {
skuCode: string skuCode: string
quantity: number quantity: number
loginStatus: string loginStatus: string
bindingStatus: string
executionStatus: string executionStatus: string
displayStatus: { key: string; label: string } displayStatus: { key: string; label: string }
huyaUid: string huyaUid: string
platformNickname: string platformNickname: string
bindGameAccount: string
bindGameRole: string
bindGameRoleId: string
bindGameChannel: string
customerGameRoleId: string
customerGameRoleName: string
customerServerZone: string
completedAt: string | null completedAt: string | null
completionNote: string completionNote: string
semiAutoConfig: { semiAutoConfig: {
@@ -28,3 +47,27 @@ export type CustomerLoginInfo = {
expiresAt: string expiresAt: string
message: string message: string
} }
export type CustomerBindingInfo = {
status: string
qrImage: string
qrExpiresAt: string
qrUrl: string
bindGameAccount: string
bindGameRole: string
bindGameRoleId: string
bindGameChannel: string
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
comparison: CustomerBindingComparison
}