diff --git a/apps/backend/.gitattributes b/apps/backend/.gitattributes new file mode 100644 index 00000000..375c8b6f --- /dev/null +++ b/apps/backend/.gitattributes @@ -0,0 +1,4 @@ +# 容器内 /bin/sh 直接执行的脚本必须是 LF。 +# Windows 下 core.autocrlf=true 会把 checkout 出来的 .sh 转成 CRLF, +# 导致 `set: Illegal option -`,backend 容器反复重启。 +*.sh text eol=lf diff --git a/apps/backend/src/db/migrations/168_semi_auto_binding_role_id.sql b/apps/backend/src/db/migrations/168_semi_auto_binding_role_id.sql new file mode 100644 index 00000000..7b5b0bc6 --- /dev/null +++ b/apps/backend/src/db/migrations/168_semi_auto_binding_role_id.sql @@ -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),用于与客户填写角色比对'; diff --git a/apps/backend/src/db/migrations/169_semi_auto_customer_profile.sql b/apps/backend/src/db/migrations/169_semi_auto_customer_profile.sql new file mode 100644 index 00000000..81996656 --- /dev/null +++ b/apps/backend/src/db/migrations/169_semi_auto_customer_profile.sql @@ -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 + '客户在授权页填写的区服'; diff --git a/apps/backend/src/db/migrations/170_semi_auto_trace_logs.sql b/apps/backend/src/db/migrations/170_semi_auto_trace_logs.sql new file mode 100644 index 00000000..3bc07fea --- /dev/null +++ b/apps/backend/src/db/migrations/170_semi_auto_trace_logs.sql @@ -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、密钥不落库)'; diff --git a/apps/backend/src/index.ts b/apps/backend/src/index.ts index 15758f51..8746c200 100644 --- a/apps/backend/src/index.ts +++ b/apps/backend/src/index.ts @@ -4,6 +4,7 @@ import { createApp } from './app.js' import { runtimeConfig } from './config/runtime.js' import { assertRuntimeConfigValid } from './config/runtime-validation.js' import { bootstrapCoreServices } from './startup/bootstrap.js' +import { startSemiAutoTraceCleanup } from './services/semi-auto/semi-auto-trace.js' import { createShutdownController } from './startup/shutdown.js' import { createStartupState, formatStartupError } from './startup/state.js' import { logError, logInfo } from './utils/logger.js' @@ -30,6 +31,8 @@ const app = createApp({ const server = app.listen(port, host, () => { logInfo('[startup]', `order-site-backend kuaishou-lite listening on http://${host}:${port}`) void bootstrapCoreServices(startupState, () => shutdownController?.isShutdownStarted() || false) + // 半自动履约报文保留 180 天:启动先清一次,之后每 6 小时清理。 + startSemiAutoTraceCleanup() }) shutdownController = createShutdownController(server, startupState) diff --git a/apps/backend/src/middleware/semi-auto-trace.ts b/apps/backend/src/middleware/semi-auto-trace.ts new file mode 100644 index 00000000..13cb4c62 --- /dev/null +++ b/apps/backend/src/middleware/semi-auto-trace.ts @@ -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() + +/** 响应里代表「状态」的字段:轮询指纹只取这些,时间戳/计数变化不算状态变化。 */ +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 { + 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 + const masked: Record = {} + 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 + const picked: Record = {} + 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) : {} + 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) : {} + 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('')) + } +} diff --git a/apps/backend/src/routes/admin/semi-auto.ts b/apps/backend/src/routes/admin/semi-auto.ts index 312bfb08..7834d480 100644 --- a/apps/backend/src/routes/admin/semi-auto.ts +++ b/apps/backend/src/routes/admin/semi-auto.ts @@ -8,15 +8,27 @@ import { createAdminBrowserSession, exportAdminSemiAutoCredential, getAdminSemiAutoTask, + getAdminSemiAutoTaskHistory, listAdminSemiAutoTasks, requestAdminSemiAutoCustomerReauth, syncAdminSemiAutoTask, } 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 { createJsonHandler, requireAdminRoles } from './session.js' 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.get( @@ -37,6 +49,18 @@ router.get( }), ) +router.get( + '/semi-auto/tasks/:taskId/history', + createJsonHandler( + (req) => getAdminSemiAutoTaskHistory(req.params.taskId, req.query as Record), + { + successMessage: 'ok', + errorMessage: '读取半自动履约历史失败', + scope: '[admin/semi-auto/tasks/:taskId/history]', + }, + ), +) + router.post( '/semi-auto/tasks/:taskId/credential/export', createJsonHandler( diff --git a/apps/backend/src/routes/customer-fulfillment.ts b/apps/backend/src/routes/customer-fulfillment.ts index 793b121c..e6d80f07 100644 --- a/apps/backend/src/routes/customer-fulfillment.ts +++ b/apps/backend/src/routes/customer-fulfillment.ts @@ -1,24 +1,39 @@ import { Router } from 'express' import { + confirmPublicBinding, getPublicWeiboCountryCodes, listPublicSemiAutoTasks, loginPublicHuyaSms, loginPublicWeiboSms, markCustomerLinkOpened, + pollPublicBinding, pollPublicLogin, pollPublicWeiboQrLogin, + savePublicTaskProfile, sendPublicHuyaSmsCode, sendPublicWeiboSmsCode, + startPublicBinding, startPublicLogin, startPublicWeiboQrLogin, + submitPublicRebind, verifyPublicHuyaSmsChallenge, } 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 { createRouteHandler } from '../utils/http.js' const router = Router() +// 客户侧每次操作都会记录入站报文;2 秒一次的 /status 轮询只在状态变化或失败时落库。 +router.param( + 'taskId', + createSemiAutoTaskTraceHandler({ + channel: 'customer_api', + isPolling: (req) => req.path.endsWith('/status'), + }), +) + const readLimit = createRateLimitMiddleware({ scope: 'customer-fulfillment:read', 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( '/:orderNo/tasks/:taskId/weibo/config', readLimit, diff --git a/apps/backend/src/services/dev-mock/mock-semi-auto-connector.ts b/apps/backend/src/services/dev-mock/mock-semi-auto-connector.ts index 1349c6d5..7c35bdf6 100644 --- a/apps/backend/src/services/dev-mock/mock-semi-auto-connector.ts +++ b/apps/backend/src/services/dev-mock/mock-semi-auto-connector.ts @@ -50,6 +50,7 @@ type MockSession = { bindingQrExpiresAtMs: number bindGameAccount: string bindGameRole: string + bindGameRoleId: string bindGameChannel: string message: string tickets: Map @@ -136,8 +137,10 @@ function bindingView(session: MockSession): ConnectorBindingSession { status: session.bindingStatus, qrImage: session.bindingStatus === 'not_started' ? '' : buildMockBindingQr(session.sessionId), qrExpiresAt: new Date(session.bindingQrExpiresAtMs).toISOString(), + qrUrl: '', bindGameAccount: session.bindGameAccount, bindGameRole: session.bindGameRole, + bindGameRoleId: session.bindGameRoleId, bindGameChannel: session.bindGameChannel, message: session.message, } @@ -158,6 +161,7 @@ function markRoleReady(session: MockSession) { session.bindingStatus = 'role_ready' session.bindGameAccount = `mock-account-${session.sessionId.slice(-6)}` session.bindGameRole = 'Mock测试角色' + session.bindGameRoleId = `mock-role-${session.sessionId.slice(-6)}` session.bindGameChannel = '虎牙' session.message = 'Mock 已识别游戏角色,请确认绑定' } @@ -188,6 +192,7 @@ export function createMockLoginSession(input: { bindingQrExpiresAtMs: 0, bindGameAccount: '', bindGameRole: '', + bindGameRoleId: '', bindGameChannel: '', message: 'Mock 登录二维码已生成,轮询后会自动模拟扫码成功', tickets: new Map(), @@ -230,6 +235,7 @@ export function sendMockHuyaSmsCode(input: { bindingQrExpiresAtMs: 0, bindGameAccount: '', bindGameRole: '', + bindGameRoleId: '', bindGameChannel: '', message: 'Mock 短信验证码已发送,请输入 123456', tickets: new Map(), diff --git a/apps/backend/src/services/semi-auto/binding-role-id.ts b/apps/backend/src/services/semi-auto/binding-role-id.ts new file mode 100644 index 00000000..86a48121 --- /dev/null +++ b/apps/backend/src/services/semi-auto/binding-role-id.ts @@ -0,0 +1,46 @@ +/** + * 虎牙 checkUserBindGameAccount 返回的 gameRole.roleId 是 40 位加密串, + * 无法直接和客户填写的游戏编号比对;平台侧可用于核对的是登录账号的数值 UID(huyaUid)。 + * + * 取数优先级:角色 ID 本身是纯数字 > 数值 UID > 原始角色 ID。 + * 这样既兼容未来虎牙直接下发数值角色 ID,也避免把加密串展示给客户。 + */ +export function resolveBindingRoleId(roleId: unknown, huyaUid: unknown): string { + const rawRoleId = String(roleId ?? '').trim() + + if (/^\d+$/.test(rawRoleId)) return rawRoleId + + const uid = String(huyaUid ?? '').trim() + + return /^\d+$/.test(uid) ? uid : rawRoleId +} + +/** 只有纯数字角色 ID 才能和客户填写的游戏编号做可信比对。 */ +export function isNumericBindingRoleId(value: unknown): boolean { + return /^\d+$/.test(String(value ?? '').trim()) +} + +export type BindingRoleInfo = { + resolvedRoleId: string + roleIdVerified: boolean + hasBoundRole: boolean + /** 平台返回了绑定角色,但没有可核对的数字角色 ID → 必须人工核实。 */ + requiresSupport: boolean +} + +/** 统一计算「绑定角色 + 可核对角色 ID」的展示状态,避免前后端各自判断。 */ +export function describeBindingRole( + roleName: unknown, + roleId: unknown, + huyaUid: unknown, +): BindingRoleInfo { + const resolvedRoleId = resolveBindingRoleId(roleId, huyaUid) + const roleIdVerified = isNumericBindingRoleId(resolvedRoleId) + const hasBoundRole = String(roleName ?? '').trim().length > 0 + return { + resolvedRoleId, + roleIdVerified, + hasBoundRole, + requiresSupport: hasBoundRole && !roleIdVerified, + } +} diff --git a/apps/backend/src/services/semi-auto/huya-connector-client.test.ts b/apps/backend/src/services/semi-auto/huya-connector-client.test.ts index a5205482..9ce63da9 100644 --- a/apps/backend/src/services/semi-auto/huya-connector-client.test.ts +++ b/apps/backend/src/services/semi-auto/huya-connector-client.test.ts @@ -202,3 +202,44 @@ test('重新扫码换绑会向 Connector 传递 force_rebind', async () => { globalThis.fetch = originalFetch } }) + +test('提交换绑复用 Connector confirm 端点并携带 rebind 标记', async () => { + const originalFetch = globalThis.fetch + let requestUrl = '' + let requestBody: Record = {} + globalThis.fetch = (async (url: string | URL | Request, init?: RequestInit) => { + requestUrl = String(url) + requestBody = JSON.parse(String(init?.body || '{}')) as Record + 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 + } +}) diff --git a/apps/backend/src/services/semi-auto/huya-connector-client.ts b/apps/backend/src/services/semi-auto/huya-connector-client.ts index ea1751b5..ec40ad26 100644 --- a/apps/backend/src/services/semi-auto/huya-connector-client.ts +++ b/apps/backend/src/services/semi-auto/huya-connector-client.ts @@ -16,6 +16,7 @@ import { huyaNativeConnector, type HuyaStoredCredential, } from './huya-native/huya-native-connector.js' +import { recordSemiAutoTrace, traceFingerprint } from './semi-auto-trace.js' export type ConnectorLoginSession = { sessionId: string @@ -95,11 +96,26 @@ export type ConnectorBindingSession = { | 'failed' qrImage: string qrExpiresAt: string + qrUrl: string bindGameAccount: string bindGameRole: string + bindGameRoleId: string bindGameChannel: string + /** 平台返回的角色 ID 是否可核对(纯数字);false 时需引导客户联系客服人工核实。 */ + roleIdVerified?: boolean + /** 已绑定角色但缺少可核对角色 ID:客户页应提示联系客服,禁止直接确认绑定。 */ + requiresSupport?: boolean hasExistingBinding?: boolean rebindRequested?: boolean + rebindUnchanged?: boolean + rebindConfirmState?: 'idle' | 'submitting' | 'accepted' | 'rejected' + rebindConfirmMessage?: string + bindConfirmState?: 'idle' | 'submitting' | 'accepted' | 'rejected' + bindConfirmMessage?: string + rebindCooldownDays?: number + nextRebindAt?: string + platformChangeBindDay?: number + platformChangeBindTime?: number message: string } @@ -193,9 +209,11 @@ async function callConnector( const timeoutMs = Math.max(1000, Number(runtimeConfig.semiAuto?.connectorTimeoutMs || 15_000)) const controller = new AbortController() const timer = setTimeout(() => controller.abort(), timeoutMs) + const method = String(options.method || 'GET').toUpperCase() + const startedAt = Date.now() try { const requestInit: RequestInit = { - method: options.method || 'GET', + method, headers: { Accept: 'application/json', 'Content-Type': 'application/json', @@ -212,6 +230,20 @@ async function callConnector( } catch { payload = null } + recordSemiAutoTrace({ + direction: 'outbound', + channel: 'external_connector', + action: `${method} ${path}`, + status: response.ok ? 'ok' : 'error', + httpStatus: response.status, + durationMs: Date.now() - startedAt, + requestSummary: { baseUrl: endpoint.baseUrl }, + requestBody: options.body, + responseSummary: { bodyBytes: text.length }, + responseBody: payload ?? text, + always: method !== 'GET', + fingerprint: method === 'GET' ? traceFingerprint(payload) : undefined, + }) if (!response.ok) { const detail = payload && typeof payload === 'object' @@ -224,6 +256,19 @@ async function callConnector( } return payload as T } catch (error) { + if (!(error && typeof error === 'object' && 'statusCode' in error)) { + recordSemiAutoTrace({ + direction: 'outbound', + channel: 'external_connector', + action: `${method} ${path}`, + status: 'error', + durationMs: Date.now() - startedAt, + requestSummary: { baseUrl: endpoint.baseUrl }, + requestBody: options.body, + always: true, + errorMessage: error instanceof Error ? error.message : String(error), + }) + } if (error && typeof error === 'object' && 'statusCode' in error) throw error if (error instanceof Error && error.name === 'AbortError') { throw createHttpError('半自动履约 Connector 请求超时', { @@ -410,14 +455,50 @@ export async function getHuyaBinding( ) } -export async function confirmHuyaBinding( +/** + * 只读绑定快照:不触发虎牙查询,供「确认绑定」这类本地动作使用。 + * 外部 Connector 没有独立快照端点,只能复用 GET(由 Connector 侧决定是否访问虎牙)。 + */ +export async function getHuyaBindingSnapshot( sessionId: string, mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(), ): Promise { - if (mode === 'embedded') return huyaNativeConnector.confirmBinding(sessionId) + if (mode === 'embedded') return huyaNativeConnector.bindingSnapshot(sessionId) + return callConnector( + `/api/internal/huya-semi-auto/sessions/${encodeURIComponent(sessionId)}/binding`, + {}, + mode, + ) +} + +export async function confirmHuyaBinding( + sessionId: string, + mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(), + options: { acceptExistingRole?: boolean } = {}, +): Promise { + if (mode === 'embedded') return huyaNativeConnector.confirmBinding(sessionId, options) return callConnector( `/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 { + if (mode === 'embedded') return huyaNativeConnector.submitRebind(sessionId) + return callConnector( + `/api/internal/huya-semi-auto/sessions/${encodeURIComponent(sessionId)}/binding/confirm`, + { method: 'POST', body: { rebind: true } }, mode, ) } diff --git a/apps/backend/src/services/semi-auto/huya-native/binding-confirm-decision.test.ts b/apps/backend/src/services/semi-auto/huya-native/binding-confirm-decision.test.ts new file mode 100644 index 00000000..e3c3c3ff --- /dev/null +++ b/apps/backend/src/services/semi-auto/huya-native/binding-confirm-decision.test.ts @@ -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, + ) +}) diff --git a/apps/backend/src/services/semi-auto/huya-native/huya-native-connector.ts b/apps/backend/src/services/semi-auto/huya-native/huya-native-connector.ts index 8bc31c4f..d762fd33 100644 --- a/apps/backend/src/services/semi-auto/huya-native/huya-native-connector.ts +++ b/apps/backend/src/services/semi-auto/huya-native/huya-native-connector.ts @@ -12,6 +12,7 @@ import path from 'node:path' import { runtimeConfig } from '../../../config/runtime.js' import { createHttpError } from '../../../utils/http.js' import { logWarn } from '../../../utils/logger.js' +import { describeBindingRole } from '../binding-role-id.js' import type { ConnectorBindingSession, ConnectorBrowserTicket, @@ -51,6 +52,10 @@ const LOGIN_QR_TTL_MS = 5 * 60 * 1000 const SMS_LOGIN_TTL_MS = 5 * 60 * 1000 const CREDENTIAL_TTL_MS = 24 * 60 * 60 * 1000 const BINDING_QR_TTL_MS = 5 * 60 * 1000 +const REBIND_WINDOW_DAYS = 7 +const DAY_MS = 24 * 60 * 60 * 1000 +// 提交换绑后给虎牙留的生效时间;期间前端继续轮询,不提前判失败。 +const REBIND_EFFECT_WINDOW_MS = 60 * 1000 const BROWSER_TICKET_TTL_MS = 2 * 60 * 1000 const MAX_SESSIONS = 500 const NATIVE_TICKET_PREFIX = 'native-ticket-' @@ -62,14 +67,30 @@ type NativeBindingStatus = ConnectorBindingSession['status'] type NativeBindState = { status: NativeBindingStatus qrImage: string + qrUrl: string qrToken: string expiresAtMs: number account: string role: string + roleId: string channel: string hasExistingBinding: boolean rebindRequested: boolean rebindScanned: boolean + rebindUnchanged: boolean + rebindConfirmState: 'idle' | 'submitting' | 'accepted' | 'rejected' + rebindConfirmMessage: string + rebindConfirmAt: number + rebindEffectDeadlineMs: number + /** 首次绑定(账号还没有绑定角色)时,扫码后由项目侧提交 confirmBindActAccount 的状态。 */ + bindConfirmState: 'idle' | 'submitting' | 'accepted' | 'rejected' + bindConfirmMessage: string + bindConfirmAt: number + bindEffectDeadlineMs: number + rebindCooldownDays: number + nextRebindAt: string + changeBindTime: number + changeBindDay: number baselineRoleKey: string message: string } @@ -135,14 +156,29 @@ function defaultBindingState(): NativeBindState { return { status: 'not_started', qrImage: '', + qrUrl: '', qrToken: '', expiresAtMs: 0, account: '', role: '', + roleId: '', channel: '', hasExistingBinding: false, rebindRequested: false, rebindScanned: false, + rebindUnchanged: false, + rebindConfirmState: 'idle', + rebindConfirmMessage: '', + rebindConfirmAt: 0, + rebindEffectDeadlineMs: 0, + bindConfirmState: 'idle', + bindConfirmMessage: '', + bindConfirmAt: 0, + bindEffectDeadlineMs: 0, + rebindCooldownDays: 0, + nextRebindAt: '', + changeBindTime: 0, + changeBindDay: 0, baselineRoleKey: '', message: '', } @@ -152,6 +188,133 @@ function iso(value: number): string { return new Date(value).toISOString() } +function rebindDateLabel(value: string): string { + if (!value) return '' + const date = new Date(value) + if (Number.isNaN(date.getTime())) return '' + return new Intl.DateTimeFormat('zh-CN', { + timeZone: 'Asia/Shanghai', + year: 'numeric', + month: '2-digit', + day: '2-digit', + }).format(date) +} + +export type RebindCooldownInput = { + status?: number + changeBindDay?: number + accountData?: { changeBindTime?: number } | null +} + +/** + * 虎牙活动提示:每 7 个自然日允许换绑 1 次。 + * 这里计算的是「本次绑定后预计下次可换绑时间」,只用于文案展示, + * 不能作为本次提交换绑的前置拦截;是否允许以 confirmBindActAccount 的返回为准。 + */ +export function resolveRebindCooldown( + response: RebindCooldownInput | null | undefined, + now = Date.now(), +): { days: number; nextRebindAt: string } { + if (!response || (response.status !== undefined && response.status !== 200)) { + return { days: 0, nextRebindAt: '' } + } + const changeBindDay = Number(response.changeBindDay || 0) + const hasPlatformWindow = + Number.isFinite(changeBindDay) && changeBindDay > 0 && changeBindDay <= 30 + const windowDays = hasPlatformWindow ? Math.round(changeBindDay) : REBIND_WINDOW_DAYS + const changeBindTime = Number(response.accountData?.changeBindTime || 0) + if (Number.isFinite(changeBindTime) && changeBindTime > 0) { + const changedAtMs = changeBindTime > 1e12 ? changeBindTime : changeBindTime * 1000 + // 虎牙把「本次绑定日」记成次日 00:00 的日界:11-16 绑定 → changeBindTime = 2026-11-17 00:00, + // 配合 changeBindDay = 7,绑定页提示「预计下次换绑时间 2026/11/23」。 + // 因此下次可换绑 = 日界 + (窗口天数 - 1) 天;不能用 +7 天,否则会显示成 11-24。 + const offsetDays = hasPlatformWindow ? Math.max(windowDays - 1, 0) : REBIND_WINDOW_DAYS + const nextRebindMs = changedAtMs + offsetDays * DAY_MS + if (nextRebindMs > now) { + return { + days: Math.ceil((nextRebindMs - now) / DAY_MS), + nextRebindAt: iso(nextRebindMs), + } + } + } + if (hasPlatformWindow) { + return { days: windowDays, nextRebindAt: iso(now + windowDays * DAY_MS) } + } + return { days: 0, nextRebindAt: '' } +} + +export type BindingConfirmDecision = 'confirm' | 'needs_rebind_decision' | 'not_ready' + +/** + * 客户点「确认绑定」时只做本地流转:角色已识别即可确认,不调用任何虎牙接口。 + * 唯一需要客户决定的情况是「换绑被虎牙拒绝、平台仍返回原角色」: + * 要么重新扫码换绑,要么显式确认继续使用原绑定角色。 + */ +export function resolveBindingConfirmDecision( + binding: { + status?: string + role?: string + rebindRequested?: boolean + rebindUnchanged?: boolean + }, + options: { acceptExistingRole?: boolean } = {}, +): BindingConfirmDecision { + const role = String(binding.role || '').trim() + const status = String(binding.status || '') + if (!role || (status !== 'role_ready' && status !== 'confirmed')) return 'not_ready' + if ( + binding.rebindRequested === true && + binding.rebindUnchanged === true && + options.acceptExistingRole !== true + ) { + return 'needs_rebind_decision' + } + return 'confirm' +} + +/** + * 首次绑定:账号还没有绑定角色(isBindAccount / isBindRole 任一为 0)时, + * 扫码完成后必须由项目侧调用 confirmBindActAccount 完成绑定,再读取角色做本地比对。 + * 已经有绑定角色、也没发起换绑时不需要任何平台写接口。 + */ +export function shouldSubmitFirstBind( + binding: { + rebindRequested?: boolean + hasExistingBinding?: boolean + bindConfirmState?: string + }, + input: { qrCompleted: boolean; scanned: boolean }, +): boolean { + if (!input.qrCompleted || !input.scanned) return false + if (binding.rebindRequested === true) return false + if (binding.hasExistingBinding === true) return false + return (binding.bindConfirmState || 'idle') === 'idle' +} + +function applyRebindMeta( + session: NativeSession, + response: HuyaBindResponse | null, + now: number, +): void { + const cooldown = resolveRebindCooldown(response, now) + session.binding.rebindCooldownDays = cooldown.days + session.binding.nextRebindAt = cooldown.nextRebindAt + session.binding.changeBindTime = Number(response?.accountData?.changeBindTime || 0) + session.binding.changeBindDay = Number(response?.changeBindDay || 0) +} + +function rebindFailureMessage( + roleName: string, + platformMessage: string, + nextRebindAt: string, +): string { + // 优先展示虎牙原始原因(例如「7 天内只能换绑 1 次」),不要本地编造失败原因。 + const raw = readString(platformMessage) + if (raw) return `换绑未成功:${raw}` + const next = rebindDateLabel(nextRebindAt) + return `换绑已提交,但平台仍返回原绑定角色「${roleName}」${next ? `,预计下次换绑:${next}` : ''};请稍后刷新或重新提交换绑` +} + function extractInt(value: unknown): number { const parsed = Number.parseInt(String(value ?? '').trim(), 10) return Number.isFinite(parsed) && parsed > 0 ? parsed : 0 @@ -223,18 +386,29 @@ function smsBehavior(page = 'https://www.huya.com/g'): { behavior: string; page: function parseRole(response: HuyaBindResponse | null): { account: string role: string + roleId: string channel: string } { - if (!response || response.status !== 200) return { account: '', role: '', channel: '' } + if (!response || response.status !== 200) { + return { account: '', role: '', roleId: '', channel: '' } + } const data: HuyaGameAccountData = response.accountData const account = data.gameAccount.nick || data.gameRole.roleName const role = data.gameRole.roleName const channel = [data.gameRole.platName, data.gameRole.areaName].filter(Boolean).join(' · ') - return { account, role, channel } + // 虎牙 checkUserBindGameAccount 的 gameRole.roleId 就是平台侧角色 ID; + // 该字段一直存在于 RPC 响应里,之前被丢弃,导致客户页无法做两侧角色比对。 + const roleId = String(data.gameRole.roleId || '').trim() + return { account, role, roleId, channel } } -function bindingRoleKey(role: { account: string; role: string; channel: string }): string { - return [role.account, role.role, role.channel].join('\u0000') +function bindingRoleKey(role: { + account: string + role: string + roleId?: string + channel: string +}): string { + return [role.account, role.role, role.roleId || '', role.channel].join('\u0000') } function configValues() { @@ -658,10 +832,21 @@ export class HuyaNativeConnector { const role = parseRole(roleResponse) const hasExistingBinding = hasExistingHuyaBinding(roleResponse) session.binding.hasExistingBinding = hasExistingBinding - if (role.role && !options.forceRebind) { - this.markRoleReady(session, role, hasExistingBinding && !session.binding.rebindRequested) + applyRebindMeta(session, roleResponse, this.now()) + // 只有平台明确「已绑定」才允许直接确认;没有绑定(即使残留角色名)必须走扫码绑定。 + if (hasExistingBinding && !options.forceRebind) { + this.markRoleReady(session, role, true) + if (!role.role) { + session.binding.message = '当前账号已有绑定角色,但平台未返回角色信息,请联系客服人工核实' + } if (session.binding.rebindRequested) { - session.binding.message = '已识别待换绑角色,请确认换绑' + session.binding.message = session.binding.rebindUnchanged + ? rebindFailureMessage( + role.role, + session.binding.rebindConfirmMessage, + session.binding.nextRebindAt, + ) + : '已识别待换绑角色,请确认换绑' } return this.bindingView(session) } @@ -684,11 +869,20 @@ export class HuyaNativeConnector { errorCode: 'huya_livelink_param_failed', }) } - const profile = await rpc.getUserProfile({ - uid: session.uid, - cookie: session.cookie, - targetUid: session.uid, - }) + let profile: Awaited> = null + try { + profile = await rpc.getUserProfile({ + uid: session.uid, + cookie: session.cookie, + targetUid: session.uid, + }) + } catch (error) { + // 资料接口结构可能随虎牙升级变化,失败时回退登录会话里的昵称/头像,不能阻断换绑二维码。 + logWarn('huya/bind/profile', '获取虎牙账号资料失败,回退登录昵称', { + uid: session.uid, + error: errorMessage(error), + }) + } const nickname = profile?.nick || profile?.passport || session.nickname session.nickname = nickname const avatar = profile?.avatar || '' @@ -716,19 +910,100 @@ export class HuyaNativeConnector { if (options.forceRebind) { session.binding.rebindRequested = true session.binding.rebindScanned = false + session.binding.rebindUnchanged = false + session.binding.rebindConfirmState = 'idle' + session.binding.rebindConfirmMessage = '' + session.binding.rebindConfirmAt = 0 + session.binding.rebindEffectDeadlineMs = 0 session.binding.baselineRoleKey = bindingRoleKey(role) } session.binding.status = 'qr_pending' session.binding.qrImage = mini.image + session.binding.qrUrl = urls.qrUrl session.binding.qrToken = mini.token session.binding.expiresAtMs = this.now() + BINDING_QR_TTL_MS + if (!options.forceRebind) { + // 新的绑定码:清掉上一次绑定提交状态,等这次扫码完成后再提交。 + session.binding.bindConfirmState = 'idle' + session.binding.bindConfirmMessage = '' + session.binding.bindConfirmAt = 0 + session.binding.bindEffectDeadlineMs = 0 + session.binding.rebindScanned = false + } session.binding.message = options.forceRebind ? '请使用虎牙 App 扫码选择需要换绑的游戏角色' - : '请使用虎牙 App 扫码绑定游戏角色' + : '该虎牙账号还没有绑定游戏角色,请用虎牙 App 扫码完成绑定' return this.bindingView(session) }) } + /** + * 扫码完成后由项目侧替客户点「确认绑定」。 + * confirmBindActAccount 确认的是虎牙侧已选中的角色,必须在读取新角色之前调用; + * 若客户已在虎牙弹窗里点过确认,重复调用是幂等的。 + */ + private async submitRebindLocked(session: NativeSession, rpc: HuyaRpcClient): Promise { + 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 { + 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 { return this.withLock(sessionId, async () => { const session = this.requireAuthenticatedSession(sessionId) @@ -740,14 +1015,20 @@ export class HuyaNativeConnector { timeoutMs: this.rpcTimeoutMs, }) if (qrStatus) { - if (qrStatus.isExpired || qrStatus.isFailure) { + // 平台已受理(绑定/换绑)时二维码会先过期,此时要等角色生效,不能直接判过期。 + const waitingPlatformEffect = + session.binding.rebindConfirmState === 'accepted' || + session.binding.bindConfirmState === 'accepted' + if ((qrStatus.isExpired || qrStatus.isFailure) && !waitingPlatformEffect) { session.binding.status = 'expired' session.binding.message = '绑定二维码已过期,请重新获取' return this.bindingView(session) } if (qrStatus.isScan) { session.binding.status = 'scanned' - session.binding.message = '已扫码,等待绑定完成' + session.binding.message = session.binding.rebindRequested + ? '已扫码,请在虎牙确认框中选中目标角色' + : '已扫码,等待绑定完成' } if (qrStatus.isScan || qrStatus.isCompleted) { session.binding.rebindScanned = true @@ -759,6 +1040,24 @@ export class HuyaNativeConnector { return this.bindingView(session) } const rpc = new HuyaRpcClient({ fetchImpl: this.fetchImpl, timeoutMs: this.rpcTimeoutMs }) + // 小程序流程结束后立即由项目侧提交换绑,不再等角色自己变化。 + if ( + session.binding.rebindRequested && + session.binding.rebindScanned && + qrCompleted && + session.binding.rebindConfirmState === 'idle' + ) { + await this.submitRebindLocked(session, rpc) + } + // 首次绑定:账号还没有绑定角色时,扫码完成后由项目侧主动提交绑定。 + if ( + shouldSubmitFirstBind(session.binding, { + qrCompleted, + scanned: session.binding.rebindScanned, + }) + ) { + await this.submitBindLocked(session, rpc) + } const response = await rpc.checkUserBindGameAccount({ uid: session.uid, cookie: session.cookie, @@ -773,91 +1072,199 @@ export class HuyaNativeConnector { const role = parseRole(response) const hasExistingBinding = hasExistingHuyaBinding(response) session.binding.hasExistingBinding = hasExistingBinding - if (role.role) { + applyRebindMeta(session, response, this.now()) + if (role.role && hasExistingBinding) { const rebindRequested = session.binding.rebindRequested const roleKey = bindingRoleKey(role) const changedRole = !session.binding.baselineRoleKey || roleKey !== session.binding.baselineRoleKey if (rebindRequested && !changedRole) { - if (qrCompleted) { - session.binding.rebindRequested = false - session.binding.rebindScanned = false - session.binding.baselineRoleKey = '' + if (session.binding.rebindConfirmState === 'rejected') { + // 虎牙明确拒绝:保留 rebind 状态并展示虎牙原文,不能清空 rebindRequested。 + session.binding.rebindUnchanged = true this.markRoleReady(session, role, hasExistingBinding) - session.binding.message = '扫码后仍识别到原绑定角色,请确认使用或重新换绑' - } else { - session.binding.status = 'scanned' - session.binding.message = '已扫码,正在等待换绑角色生效' + session.binding.message = rebindFailureMessage( + role.role, + session.binding.rebindConfirmMessage, + session.binding.nextRebindAt, + ) + return this.bindingView(session) } + if (session.binding.rebindConfirmState === 'accepted') { + if (this.now() < session.binding.rebindEffectDeadlineMs) { + session.binding.status = 'scanned' + session.binding.message = '虎牙已受理换绑,正在等待角色生效' + } else { + session.binding.rebindUnchanged = true + this.markRoleReady(session, role, hasExistingBinding) + session.binding.message = rebindFailureMessage( + role.role, + session.binding.rebindConfirmMessage, + session.binding.nextRebindAt, + ) + } + return this.bindingView(session) + } + session.binding.status = 'scanned' + session.binding.message = qrCompleted + ? '扫码已完成,请点击「已选好角色,提交换绑」' + : '已扫码,请在虎牙确认框中选中目标角色' return this.bindingView(session) } + if (rebindRequested) session.binding.rebindUnchanged = false this.markRoleReady(session, role, hasExistingBinding && !rebindRequested) if (rebindRequested) { session.binding.message = '已识别换绑角色,请确认换绑' } + } else if (hasExistingBinding) { + // 平台标记已绑定,但没有返回角色信息(或角色ID不可核对):必须人工核实,不能生成二维码。 + this.markRoleReady(session, role, true) + session.binding.message = '当前账号已有绑定角色,但平台未返回角色信息,请联系客服人工核实' + } else if ( + !session.binding.rebindRequested && + session.binding.bindConfirmState === 'rejected' + ) { + session.binding.status = 'failed' + session.binding.message = `虎牙未接受本次绑定:${session.binding.bindConfirmMessage}` + } else if ( + !session.binding.rebindRequested && + session.binding.bindConfirmState === 'accepted' + ) { + if (this.now() < session.binding.bindEffectDeadlineMs) { + session.binding.status = 'scanned' + session.binding.message = '已向虎牙提交绑定,正在等待角色生效' + } else { + session.binding.status = 'failed' + session.binding.message = '虎牙已受理绑定,但未返回角色,请重新扫码绑定' + } } else if (!['scanned', 'expired', 'failed'].includes(session.binding.status)) { session.binding.status = 'qr_pending' - session.binding.message = '等待扫码绑定游戏角色' + session.binding.message = '该虎牙账号还没有绑定游戏角色,请扫码完成绑定' } return this.bindingView(session) }) } - async confirmBinding(sessionId: string): Promise { + /** 只读绑定状态快照:不访问虎牙,供「确认绑定」这类纯本地动作使用。 */ + async bindingSnapshot(sessionId: string): Promise { + return this.withLock(sessionId, async () => + this.bindingView(this.requireAuthenticatedSession(sessionId)), + ) + } + + /** + * 客户点「确认绑定」:只做本地状态流转,不调用虎牙接口。 + * 虎牙侧的绑定已由扫码(小程序/弹窗)完成,确认绑定只是核对三项后落库; + * 需要调用虎牙接口的地方只有「换绑确认」(submitRebind / pollBinding 自动提交)。 + */ + async confirmBinding( + sessionId: string, + options: { acceptExistingRole?: boolean } = {}, + ): Promise { return this.withLock(sessionId, async () => { const session = this.requireAuthenticatedSession(sessionId) + const binding = session.binding + const decision = resolveBindingConfirmDecision(binding, options) + if (decision === 'not_ready') { + throw createHttpError('尚未识别到可确认的绑定角色', { + statusCode: 409, + errorCode: 'huya_bind_role_not_ready', + }) + } + const rebindRequested = binding.rebindRequested + const acceptExistingRole = options.acceptExistingRole === true + if (decision === 'needs_rebind_decision') { + const reason = readString(binding.rebindConfirmMessage) + throw createHttpError( + `${ + reason + ? `换绑未成功:${reason}。` + : `换绑未成功:平台仍返回原绑定角色「${binding.role}」。` + }请重新扫码换绑,或确认继续使用原绑定角色`, + { statusCode: 409, errorCode: 'huya_bind_rebind_decision_required' }, + ) + } + const role = { + account: binding.account, + role: binding.role, + roleId: binding.roleId, + channel: binding.channel, + } + const useExistingBinding = + binding.hasExistingBinding === true && (!rebindRequested || acceptExistingRole) + this.markRoleReady(session, role, useExistingBinding) + binding.status = 'confirmed' + binding.hasExistingBinding = true + binding.rebindRequested = false + binding.rebindScanned = false + binding.rebindUnchanged = false + binding.rebindConfirmState = 'idle' + binding.rebindConfirmMessage = '' + binding.rebindConfirmAt = 0 + binding.rebindEffectDeadlineMs = 0 + binding.bindConfirmState = 'idle' + binding.bindConfirmMessage = '' + binding.bindConfirmAt = 0 + binding.bindEffectDeadlineMs = 0 + binding.rebindCooldownDays = 0 + binding.nextRebindAt = '' + binding.baselineRoleKey = '' + binding.message = + rebindRequested && acceptExistingRole + ? '本次换绑未生效,已按原绑定角色确认' + : useExistingBinding + ? '当前虎牙账号已有绑定角色,已确认直接使用' + : rebindRequested + ? '虎牙角色换绑已确认' + : '虎牙角色绑定已确认' + return this.bindingView(session) + }) + } + + /** 客户手动点击「已选好角色,提交换绑」时调用。 */ + async submitRebind(sessionId: string): Promise { + return this.withLock(sessionId, async () => { + const session = this.requireAuthenticatedSession(sessionId) + if (!session.binding.rebindRequested) { + throw createHttpError('当前没有待换绑的角色,请重新扫码换绑', { + statusCode: 409, + errorCode: 'huya_bind_rebind_not_requested', + }) + } const { bindActId, outerActId } = configValues() const rpc = new HuyaRpcClient({ fetchImpl: this.fetchImpl, timeoutMs: this.rpcTimeoutMs }) + await this.submitRebindLocked(session, rpc) const response = await rpc.checkUserBindGameAccount({ uid: session.uid, cookie: session.cookie, bindActId, outerActId, }) - const role = parseRole(response) - if (!response || response.status !== 200 || !role.role) { - throw createHttpError('尚未识别到可确认的绑定角色', { - statusCode: 409, - errorCode: 'huya_bind_role_not_ready', - }) - } - const rebindRequested = session.binding.rebindRequested - if ( - rebindRequested && - session.binding.baselineRoleKey && - bindingRoleKey(role) === session.binding.baselineRoleKey - ) { - throw createHttpError('换绑角色尚未生效,请稍后重试', { - statusCode: 409, - errorCode: 'huya_bind_rebind_not_ready', - }) - } - const useExistingBinding = hasExistingHuyaBinding(response) && !rebindRequested - if (!useExistingBinding) { - const confirmed = await rpc.confirmBindActAccount({ - uid: session.uid, - cookie: session.cookie, - bindActId, - outerActId, - }) - if (!confirmed || confirmed.status !== 200) { - throw createHttpError(confirmed?.msg || '确认虎牙绑定失败', { - statusCode: 409, - errorCode: 'huya_bind_confirm_failed', - }) + if (response && response.status === 200) { + const role = parseRole(response) + applyRebindMeta(session, response, this.now()) + if (role.role) { + const changedRole = + !session.binding.baselineRoleKey || + bindingRoleKey(role) !== session.binding.baselineRoleKey + if (changedRole) { + session.binding.rebindUnchanged = false + this.markRoleReady(session, role, false) + session.binding.message = '已识别换绑角色,请确认换绑' + } else if (session.binding.rebindConfirmState === 'rejected') { + session.binding.rebindUnchanged = true + this.markRoleReady(session, role, hasExistingHuyaBinding(response)) + session.binding.message = rebindFailureMessage( + role.role, + session.binding.rebindConfirmMessage, + session.binding.nextRebindAt, + ) + } else { + session.binding.status = 'scanned' + session.binding.message = '虎牙已受理换绑,正在等待角色生效' + } } } - this.markRoleReady(session, role, useExistingBinding) - session.binding.status = 'confirmed' - session.binding.hasExistingBinding = true - session.binding.rebindRequested = false - session.binding.rebindScanned = false - session.binding.baselineRoleKey = '' - session.binding.message = useExistingBinding - ? '当前虎牙账号已有绑定角色,已确认直接使用' - : rebindRequested - ? '虎牙角色换绑已确认' - : '虎牙角色绑定已确认' return this.bindingView(session) }) } @@ -1042,13 +1449,21 @@ export class HuyaNativeConnector { private markRoleReady( session: NativeSession, - role: { account: string; role: string; channel: string }, + role: { account: string; role: string; roleId?: string; channel: string }, existingBinding = false, ): void { session.binding.status = 'role_ready' session.binding.account = role.account session.binding.role = role.role + session.binding.roleId = role.roleId || '' session.binding.channel = role.channel + const roleInfo = describeBindingRole(role.role, role.roleId, session.uid) + if (roleInfo.requiresSupport) { + session.binding.message = existingBinding + ? '当前账号已有绑定角色,但未获取到可核对的角色ID,请联系客服人工核实' + : '已识别绑定角色,但未获取到可核对的角色ID,请联系客服人工核实' + return + } session.binding.message = existingBinding ? '当前账号已有绑定角色,请确认直接使用' : '绑定角色已识别,请确认绑定' @@ -1126,16 +1541,32 @@ export class HuyaNativeConnector { private bindingView(session: NativeSession): ConnectorBindingSession { const binding = session.binding + const roleInfo = describeBindingRole(binding.role, binding.roleId, session.uid) + const requiresSupport = + roleInfo.requiresSupport || (binding.hasExistingBinding === true && !roleInfo.roleIdVerified) return { sessionId: session.sessionId, status: binding.status, qrImage: binding.qrImage, qrExpiresAt: binding.expiresAtMs ? iso(binding.expiresAtMs) : '', + qrUrl: binding.qrUrl, bindGameAccount: binding.account, bindGameRole: binding.role, + bindGameRoleId: roleInfo.resolvedRoleId, bindGameChannel: binding.channel, + roleIdVerified: roleInfo.roleIdVerified, + requiresSupport, hasExistingBinding: binding.hasExistingBinding, rebindRequested: binding.rebindRequested, + rebindUnchanged: binding.rebindUnchanged, + rebindConfirmState: binding.rebindConfirmState, + rebindConfirmMessage: binding.rebindConfirmMessage, + bindConfirmState: binding.bindConfirmState, + bindConfirmMessage: binding.bindConfirmMessage, + rebindCooldownDays: binding.rebindCooldownDays, + nextRebindAt: binding.nextRebindAt, + platformChangeBindDay: binding.changeBindDay, + platformChangeBindTime: binding.changeBindTime, message: binding.message, } } diff --git a/apps/backend/src/services/semi-auto/huya-native/huya-rpc.ts b/apps/backend/src/services/semi-auto/huya-native/huya-rpc.ts index dae1c858..9f2f0fe5 100644 --- a/apps/backend/src/services/semi-auto/huya-native/huya-rpc.ts +++ b/apps/backend/src/services/semi-auto/huya-native/huya-rpc.ts @@ -2,6 +2,7 @@ import crypto from 'node:crypto' +import { recordSemiAutoTrace, traceFingerprint } from '../semi-auto-trace.js' import { buildHuyaLoginContext, cookiePairs, cookieValue, normalizeCookiePairs } from './cookie.js' import { decodeWupResponse, @@ -401,6 +402,27 @@ function parseLiveLinkResponse(reader: TafReader): HuyaLiveLinkResponse { } } +function isProfileIntType(dataType: TafTypeValue): boolean { + return ( + dataType === TAF_TYPE.INT8 || + dataType === TAF_TYPE.INT16 || + dataType === TAF_TYPE.INT32 || + dataType === TAF_TYPE.INT64 || + dataType === TAF_TYPE.ZERO + ) +} + +function readProfileString(reader: TafReader, dataType: TafTypeValue): string { + if (dataType === TAF_TYPE.STRING1 || dataType === TAF_TYPE.STRING4) { + return reader.readStringValue(dataType) + } + + if (dataType === TAF_TYPE.ZERO) return '' + + reader.skipValue(dataType) + return '' +} + function parseProfile(reader: TafReader): HuyaUserProfile { let uid = 0 let nick = '' @@ -412,10 +434,20 @@ function parseProfile(reader: TafReader): HuyaUserProfile { break } reader.readHead() - if (tag === 0) uid = reader.readIntValue(dataType) - else if (tag === 1) nick = reader.readStringValue(dataType) - else if (tag === 2) avatar = reader.readStringValue(dataType) - else if (tag === 17) passport = reader.readStringValue(dataType) + if (dataType === TAF_TYPE.STRUCT_BEGIN) { + // 新版虎牙把资料包在 tag0 的嵌套结构里,直接解析内层结构。 + if (tag === 0) { + return reader.readStructBody((nested) => parseProfile(nested)) + } + reader.skipValue(dataType) + continue + } + if (tag === 0) { + if (isProfileIntType(dataType)) uid = reader.readIntValue(dataType) + else reader.skipValue(dataType) + } else if (tag === 1) nick = readProfileString(reader, dataType) + else if (tag === 2) avatar = readProfileString(reader, dataType) + else if (tag === 17) passport = readProfileString(reader, dataType) else reader.skipValue(dataType) } return { uid, nick, avatar, passport } @@ -463,22 +495,67 @@ export class HuyaRpcClient { gid?: number scene?: string }): Promise { - const response = await this.callRpc( - 'webActUI', - 'checkUserBindGameAccount', - input.uid, - input.cookie, - (writer) => { - this.writeActivityUser(writer, input.uid, input.cookie) - writer.writeInt32(1, input.gid || 0) - writer.writeString(2, input.outerActId || '') - writer.writeInt32(3, 0) - writer.writeString(4, input.scene || '') - writer.writeInt32(5, input.bindActId || 0) - writer.writeInt32(6, input.isUseOuterActId ?? 1) - }, - ) - return response ? readWupStruct(response, parseBindResponse) : null + const startedAt = Date.now() + const request = { + servant: 'webActUI', + func: 'checkUserBindGameAccount', + uid: input.uid, + gid: input.gid || 0, + outerActId: input.outerActId || '', + bindActId: input.bindActId || 0, + isUseOuterActId: input.isUseOuterActId ?? 1, + scene: input.scene || '', + } + try { + const response = await this.callRpc( + 'webActUI', + 'checkUserBindGameAccount', + input.uid, + input.cookie, + (writer) => { + this.writeActivityUser(writer, input.uid, input.cookie) + writer.writeInt32(1, input.gid || 0) + writer.writeString(2, input.outerActId || '') + writer.writeInt32(3, 0) + writer.writeString(4, input.scene || '') + writer.writeInt32(5, input.bindActId || 0) + writer.writeInt32(6, input.isUseOuterActId ?? 1) + }, + ) + const parsed = response ? readWupStruct(response, parseBindResponse) : null + recordSemiAutoTrace({ + direction: 'outbound', + channel: 'huya_wup', + action: 'webActUI.checkUserBindGameAccount', + status: parsed && parsed.status === 200 ? 'ok' : 'error', + durationMs: Date.now() - startedAt, + requestSummary: request, + responseSummary: { status: parsed?.status, msg: parsed?.msg }, + responseBody: parsed, + // 绑定轮询:状态没变化就不落库。 + fingerprint: traceFingerprint({ + status: parsed?.status, + msg: parsed?.msg, + isBindAccount: parsed?.accountData?.isBindAccount, + isBindRole: parsed?.accountData?.isBindRole, + role: parsed?.accountData?.gameRole?.roleName, + roleId: parsed?.accountData?.gameRole?.roleId, + }), + errorMessage: parsed && parsed.status !== 200 ? String(parsed.msg || '') : '', + }) + return parsed + } catch (error) { + recordSemiAutoTrace({ + direction: 'outbound', + channel: 'huya_wup', + action: 'webActUI.checkUserBindGameAccount', + status: 'error', + durationMs: Date.now() - startedAt, + requestSummary: request, + errorMessage: error instanceof Error ? error.message : String(error), + }) + throw error + } } async confirmBindActAccount(input: { @@ -488,19 +565,55 @@ export class HuyaRpcClient { outerActId: string gid?: number }): Promise { - const response = await this.callRpc( - 'webActUI', - 'confirmBindActAccount', - input.uid, - input.cookie, - (writer) => { - this.writeActivityUser(writer, input.uid, input.cookie) - writer.writeInt32(1, input.gid || 0) - writer.writeString(2, input.outerActId || '') - writer.writeInt32(3, input.bindActId || 0) - }, - ) - return response ? readWupStruct(response, parseConfirmResponse) : null + const startedAt = Date.now() + const request = { + servant: 'webActUI', + func: 'confirmBindActAccount', + uid: input.uid, + gid: input.gid || 0, + outerActId: input.outerActId || '', + bindActId: input.bindActId || 0, + } + try { + const response = await this.callRpc( + 'webActUI', + 'confirmBindActAccount', + input.uid, + input.cookie, + (writer) => { + this.writeActivityUser(writer, input.uid, input.cookie) + writer.writeInt32(1, input.gid || 0) + writer.writeString(2, input.outerActId || '') + writer.writeInt32(3, input.bindActId || 0) + }, + ) + const parsed = response ? readWupStruct(response, parseConfirmResponse) : null + recordSemiAutoTrace({ + direction: 'outbound', + channel: 'huya_wup', + action: 'webActUI.confirmBindActAccount', + status: parsed && parsed.status === 200 ? 'ok' : 'error', + durationMs: Date.now() - startedAt, + requestSummary: request, + responseSummary: { status: parsed?.status, msg: parsed?.msg }, + responseBody: parsed, + always: true, + errorMessage: parsed && parsed.status !== 200 ? String(parsed.msg || '') : '', + }) + return parsed + } catch (error) { + recordSemiAutoTrace({ + direction: 'outbound', + channel: 'huya_wup', + action: 'webActUI.confirmBindActAccount', + status: 'error', + durationMs: Date.now() - startedAt, + requestSummary: request, + always: true, + errorMessage: error instanceof Error ? error.message : String(error), + }) + throw error + } } async getLiveLinkParam(input: { @@ -510,21 +623,57 @@ export class HuyaRpcClient { outerActId: number gameAuthScene?: string }): Promise { - const response = await this.callRpc( - 'webActUI', - 'getLiveLinkParam', - input.uid, - input.cookie, - (writer) => { - this.writeActivityUser(writer, input.uid, input.cookie) - writer.writeInt32(1, 0) - writer.writeInt32(2, input.outerActId || 0) - writer.writeString(3, input.gameAuthScene || '') - writer.writeString(4, '') - writer.writeInt32(5, input.bindActId || 0) - }, - ) - return response ? readWupStruct(response, parseLiveLinkResponse) : null + const startedAt = Date.now() + const request = { + servant: 'webActUI', + func: 'getLiveLinkParam', + uid: input.uid, + bindActId: input.bindActId || 0, + outerActId: input.outerActId || 0, + gameAuthScene: input.gameAuthScene || '', + } + try { + const response = await this.callRpc( + 'webActUI', + 'getLiveLinkParam', + input.uid, + input.cookie, + (writer) => { + this.writeActivityUser(writer, input.uid, input.cookie) + writer.writeInt32(1, 0) + writer.writeInt32(2, input.outerActId || 0) + writer.writeString(3, input.gameAuthScene || '') + writer.writeString(4, '') + writer.writeInt32(5, input.bindActId || 0) + }, + ) + const parsed = response ? readWupStruct(response, parseLiveLinkResponse) : null + recordSemiAutoTrace({ + direction: 'outbound', + channel: 'huya_wup', + action: 'webActUI.getLiveLinkParam', + status: parsed && parsed.status === 200 ? 'ok' : 'error', + durationMs: Date.now() - startedAt, + requestSummary: request, + responseSummary: { status: parsed?.status, msg: parsed?.msg }, + responseBody: parsed, + always: true, + errorMessage: parsed && parsed.status !== 200 ? String(parsed.msg || '') : '', + }) + return parsed + } catch (error) { + recordSemiAutoTrace({ + direction: 'outbound', + channel: 'huya_wup', + action: 'webActUI.getLiveLinkParam', + status: 'error', + durationMs: Date.now() - startedAt, + requestSummary: request, + always: true, + errorMessage: error instanceof Error ? error.message : String(error), + }) + throw error + } } async getUserProfileBatch(input: { @@ -554,17 +703,53 @@ export class HuyaRpcClient { }): Promise { const targetUid = Math.trunc(input.targetUid) if (!(targetUid > 0)) return null - const response = await this.callRpc( - 'huyauserui', - 'getUserProfile', - input.uid, - input.cookie, - (writer) => { - this.writeActivityUser(writer, 0, input.cookie) - writer.writeInt64(1, targetUid) - }, - ) - return response ? readWupStruct(response, parseProfileResponse) : null + const startedAt = Date.now() + try { + const response = await this.callRpc( + 'huyauserui', + 'getUserProfile', + input.uid, + input.cookie, + (writer) => { + this.writeActivityUser(writer, 0, input.cookie) + writer.writeInt64(1, targetUid) + }, + ) + const parsed = response ? readWupStruct(response, parseProfileResponse) : null + recordSemiAutoTrace({ + direction: 'outbound', + channel: 'huya_wup', + action: 'huyauserui.getUserProfile', + status: parsed ? 'ok' : 'error', + durationMs: Date.now() - startedAt, + requestSummary: { + servant: 'huyauserui', + func: 'getUserProfile', + uid: input.uid, + targetUid, + }, + responseBody: parsed, + always: true, + }) + return parsed + } catch (error) { + recordSemiAutoTrace({ + direction: 'outbound', + channel: 'huya_wup', + action: 'huyauserui.getUserProfile', + status: 'error', + durationMs: Date.now() - startedAt, + requestSummary: { + servant: 'huyauserui', + func: 'getUserProfile', + uid: input.uid, + targetUid, + }, + always: true, + errorMessage: error instanceof Error ? error.message : String(error), + }) + throw error + } } private async callRpc( @@ -684,6 +869,7 @@ export async function getLiveLinkMiniQrcode( ).join('') const sessionId = `${Math.floor(Date.now() / 1000)}_${suffix}` const fetchImpl = options.fetchImpl || fetch + const startedAt = Date.now() const response = await fetchImpl(`${LIVELINK_BIND_API_BASE}/api/qrcode/getMiniAppQrcode`, { method: 'POST', headers: { @@ -697,14 +883,41 @@ export async function getLiveLinkMiniQrcode( body: JSON.stringify({ queryString: `${query}&sessionId=${sessionId}` }), signal: AbortSignal.timeout(options.timeoutMs || 15_000), }) - if (!response.ok) return null + const traceMiniQrcode = (status: 'ok' | 'error', extra: Record = {}) => { + recordSemiAutoTrace({ + direction: 'outbound', + channel: 'huya_http', + action: 'livelink.getMiniAppQrcode', + status, + durationMs: Date.now() - startedAt, + httpStatus: response.status, + requestSummary: { api: 'getMiniAppQrcode', queryLength: query.length }, + responseSummary: extra, + always: true, + }) + } + if (!response.ok) { + traceMiniQrcode('error', { httpStatus: response.status }) + return null + } const payload = (await response.json().catch(() => null)) as { iRet?: number jData?: { qrcode?: string; qrcodeToken?: string } } | null - if (!payload || payload.iRet !== 0) return null + if (!payload || payload.iRet !== 0) { + traceMiniQrcode('error', { iRet: payload?.iRet ?? null }) + return null + } const image = livelinkQrcodeImageSrc(String(payload.jData?.qrcode || '')) - if (!image) return null + if (!image) { + traceMiniQrcode('error', { iRet: payload.iRet, hasImage: false }) + return null + } + traceMiniQrcode('ok', { + iRet: payload.iRet, + hasImage: true, + tokenLength: String(payload.jData?.qrcodeToken || '').length, + }) return { image, token: String(payload.jData?.qrcodeToken || '') } } @@ -720,6 +933,7 @@ export async function getLiveLinkQrcodeStatus( const normalized = String(token || '').trim() if (!normalized) return null const fetchImpl = options.fetchImpl || fetch + const startedAt = Date.now() const response = await fetchImpl(`${LIVELINK_BIND_API_BASE}/api/qrcode/poolingQrcodeStatus`, { method: 'POST', headers: { @@ -733,7 +947,24 @@ export async function getLiveLinkQrcodeStatus( body: JSON.stringify({ qrcodeToken: normalized }), signal: AbortSignal.timeout(options.timeoutMs || 15_000), }) - if (!response.ok) return null + const traceQrcodeStatus = (status: 'ok' | 'error', extra: Record = {}) => { + recordSemiAutoTrace({ + direction: 'outbound', + channel: 'huya_http', + action: 'livelink.poolingQrcodeStatus', + status, + durationMs: Date.now() - startedAt, + httpStatus: response.status, + requestSummary: { api: 'poolingQrcodeStatus', tokenLength: normalized.length }, + responseSummary: extra, + // 二维码轮询:状态没变化就不落库。 + fingerprint: traceFingerprint(extra), + }) + } + if (!response.ok) { + traceQrcodeStatus('error', { httpStatus: response.status }) + return null + } const payload = (await response.json().catch(() => null)) as { iRet?: number jData?: { @@ -743,13 +974,18 @@ export async function getLiveLinkQrcodeStatus( isFailure?: boolean } } | null - if (!payload || payload.iRet !== 0) return null - return { + if (!payload || payload.iRet !== 0) { + traceQrcodeStatus('error', { iRet: payload?.iRet ?? null }) + return null + } + const result = { isScan: Boolean(payload.jData?.isScan), isExpired: Boolean(payload.jData?.isExpired), isCompleted: Boolean(payload.jData?.isCompleted), isFailure: Boolean(payload.jData?.isFailure), } + traceQrcodeStatus('ok', { iRet: payload.iRet, ...result }) + return result } export function buildBindUrls(input: { diff --git a/apps/backend/src/services/semi-auto/huya-native/rebind-cooldown.test.ts b/apps/backend/src/services/semi-auto/huya-native/rebind-cooldown.test.ts new file mode 100644 index 00000000..f99df006 --- /dev/null +++ b/apps/backend/src/services/semi-auto/huya-native/rebind-cooldown.test.ts @@ -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: '' }) +}) diff --git a/apps/backend/src/services/semi-auto/semi-auto-binding-role.test.ts b/apps/backend/src/services/semi-auto/semi-auto-binding-role.test.ts new file mode 100644 index 00000000..bbb09d7a --- /dev/null +++ b/apps/backend/src/services/semi-auto/semi-auto-binding-role.test.ts @@ -0,0 +1,258 @@ +import assert from 'node:assert/strict' +import { describe, it } from 'node:test' + +import { + describeBindingRole, + isNumericBindingRoleId, + resolveBindingRoleId, +} from './binding-role-id.js' +import { + compareBindingRole, + detectServerZone, + normalizeCustomerProfile, +} from './semi-auto-task-service.js' + +const task = (id: string, name: string, huyaUid = '', zone = '') => ({ + customer_game_id: id, + customer_game_role: name, + customer_game_server_zone: zone, + huya_uid: huyaUid, +}) + +describe('待确认角色 UID 取数(huyaUid)', () => { + it('角色 ID 本身是纯数字时直接使用', () => { + assert.equal(resolveBindingRoleId('1192083858', 1199608910400), '1192083858') + }) + + it('角色 ID 是加密串时改用数值 UID', () => { + assert.equal( + resolveBindingRoleId('834ee3e75a1bfc9f65fb6b966bac7ef318e68ea', '1199608910400'), + '1199608910400', + ) + }) + + it('缺少角色 ID 时回退到数值 UID', () => { + assert.equal(resolveBindingRoleId('', 1199608910400), '1199608910400') + }) + + it('没有可用数值 UID 时保留原始角色 ID', () => { + assert.equal( + resolveBindingRoleId('834ee3e75a1bfc9f65fb6b966bac7ef318e68ea', ''), + '834ee3e75a1bfc9f65fb6b966bac7ef318e68ea', + ) + assert.equal(resolveBindingRoleId(null, undefined), '') + }) + + it('虎牙加密串角色 ID 改用 huyaUid 参与比对', () => { + const result = compareBindingRole(task('1199608910400', '大鲨鱼伊塞53', '1199608910400'), { + bindGameRole: '大鲨鱼伊塞53', + bindGameRoleId: '834ee3e75a1bfc9f65fb6b966bac7ef318e68ea', + }) + assert.equal(result.verdict, 'match') + assert.equal(result.boundRoleId, '1199608910400') + }) + + it('没有 huyaUid 时保留原始加密串,仍判不一致', () => { + const result = compareBindingRole(task('1199608910400', '大鲨鱼伊塞53'), { + bindGameRole: '大鲨鱼伊塞53', + bindGameRoleId: '834ee3e75a1bfc9f65fb6b966bac7ef318e68ea', + }) + assert.equal(result.verdict, 'mismatch') + assert.equal(result.boundRoleId, '834ee3e75a1bfc9f65fb6b966bac7ef318e68ea') + }) +}) + +describe('绑定角色可核对性(缺角色ID)', () => { + it('数字角色 ID 可直接核对', () => { + const info = describeBindingRole('大鲨鱼伊塞53', '1192083858', '') + assert.equal(info.roleIdVerified, true) + assert.equal(info.requiresSupport, false) + }) + + it('加密角色 ID 但 UID 是数字时可核对', () => { + const info = describeBindingRole( + '大鲨鱼伊塞53', + '834ee3e75a1bfc9f65fb6b966bac7ef318e68ea', + '1199608910400', + ) + assert.equal(info.resolvedRoleId, '1199608910400') + assert.equal(info.roleIdVerified, true) + assert.equal(info.requiresSupport, false) + }) + + it('有角色但没有可核对数字 ID 时需要联系客服', () => { + const info = describeBindingRole('Mock测试角色', 'mock-role-abc', 'mock-huya-abc') + assert.equal(info.roleIdVerified, false) + assert.equal(info.requiresSupport, true) + }) + + it('没有角色名时不需要人工核实', () => { + const info = describeBindingRole('', '', '') + assert.equal(info.hasBoundRole, false) + assert.equal(info.requiresSupport, false) + }) + + it('只接受纯数字角色 ID 参与核对', () => { + assert.equal(isNumericBindingRoleId('1192083858'), true) + assert.equal(isNumericBindingRoleId(' 1192083858 '), true) + assert.equal(isNumericBindingRoleId('mock-role-abc'), false) + assert.equal(isNumericBindingRoleId(''), false) + assert.equal(isNumericBindingRoleId(null), false) + }) +}) + +describe('区服解析', () => { + it('安卓 + 微信识别为安卓V区', () => { + assert.equal(detectServerZone('安卓(android) · 微信'), '安卓V区') + assert.equal(detectServerZone('微信用户 · 安卓(android) · 微信'), '安卓V区') + }) + + it('苹果 + QQ识别为苹果Q区', () => { + assert.equal(detectServerZone('苹果(iOS) · QQ'), '苹果Q区') + }) + + it('无法识别时返回空串', () => { + assert.equal(detectServerZone(''), '') + assert.equal(detectServerZone('微信用户'), '') + }) +}) + +describe('客户填写角色与平台识别角色比对', () => { + it('区服、角色名称、角色 ID 都一致时允许确认', () => { + const result = compareBindingRole( + task('1199608910400', '大鲨鱼伊塞53', '1199608910400', '安卓V区'), + { + bindGameRole: '大鲨鱼伊塞53', + bindGameRoleId: '1199608910400', + bindGameChannel: '安卓(android) · 微信', + }, + ) + assert.equal(result.verdict, 'match') + assert.equal(result.customerZone, '安卓V区') + assert.equal(result.boundZone, '安卓V区') + assert.match(result.message, /区服/) + }) + + it('角色 ID 一致但角色名称不一致时禁止确认', () => { + const result = compareBindingRole(task('1199608910400', '123', '1199608910400', '安卓V区'), { + bindGameRole: '大鲨鱼伊塞53', + bindGameRoleId: '1199608910400', + bindGameChannel: '安卓(android) · 微信', + }) + assert.equal(result.verdict, 'mismatch') + assert.match(result.message, /名称/) + }) + + it('角色名称与 ID 一致但区服不一致时禁止确认', () => { + const result = compareBindingRole( + task('1199608910400', '大鲨鱼伊塞53', '1199608910400', '苹果Q区'), + { + bindGameRole: '大鲨鱼伊塞53', + bindGameRoleId: '1199608910400', + bindGameChannel: '安卓(android) · 微信', + }, + ) + assert.equal(result.verdict, 'mismatch') + assert.match(result.message, /区服/) + assert.equal(result.boundZone, '安卓V区') + }) + + it('渠道解析不出区服时跳过区服比对', () => { + const result = compareBindingRole( + task('1199608910400', '大鲨鱼伊塞53', '1199608910400', '苹果Q区'), + { + bindGameRole: '大鲨鱼伊塞53', + bindGameRoleId: '1199608910400', + bindGameChannel: '微信用户', + }, + ) + assert.equal(result.verdict, 'match') + assert.equal(result.boundZone, '') + }) + + it('两侧角色 ID 一致时允许确认', () => { + const result = compareBindingRole(task('1192083858', '巫师基尔斯84'), { + bindGameRole: '巫师基尔斯84', + bindGameRoleId: '1192083858', + }) + assert.equal(result.verdict, 'match') + assert.equal(result.customerRoleId, '1192083858') + assert.equal(result.boundRoleId, '1192083858') + }) + + it('两侧角色 ID 不一致时禁止确认', () => { + const result = compareBindingRole(task('1192083858', '巫师基尔斯84'), { + bindGameRole: '我是火星人2222', + bindGameRoleId: '166909256', + }) + assert.equal(result.verdict, 'mismatch') + assert.match(result.message, /不一致/) + }) + + it('缺少角色 ID 时退回角色名称比对', () => { + const matched = compareBindingRole(task('', '巫师基尔斯84'), { + bindGameRole: '巫师基尔斯84', + bindGameRoleId: '', + }) + assert.equal(matched.verdict, 'match') + + const mismatched = compareBindingRole(task('', '巫师基尔斯84'), { + bindGameRole: '我是火星人2222', + bindGameRoleId: '', + }) + assert.equal(mismatched.verdict, 'mismatch') + }) + + it('两侧都没有可核对信息时标记为 unknown', () => { + const result = compareBindingRole(task('', ''), { bindGameRole: '', bindGameRoleId: '' }) + assert.equal(result.verdict, 'unknown') + }) +}) + +describe('客户角色资料校验', () => { + it('清理空白并保留纯数字角色 ID', () => { + const profile = normalizeCustomerProfile({ + roleName: ' 巫师基尔斯84 ', + roleId: ' 1192083858 ', + serverZone: ' 苹果V区 ', + }) + assert.deepEqual(profile, { + roleName: '巫师基尔斯84', + roleId: '1192083858', + serverZone: '苹果V区', + }) + }) + + it('角色 ID 非数字时拒绝保存', () => { + assert.throws( + () => normalizeCustomerProfile({ roleName: '巫师基尔斯84', roleId: 'abc123' }), + /只能是数字/, + ) + }) + + it('缺区服时拒绝保存', () => { + assert.throws( + () => normalizeCustomerProfile({ roleName: '巫师基尔斯84', roleId: '1192083858' }), + /区服只能选择/, + ) + }) + + it('区服不在固定选项时拒绝保存', () => { + assert.throws( + () => + normalizeCustomerProfile({ + roleName: '巫师基尔斯84', + roleId: '1192083858', + serverZone: '苹果微信区', + }), + /区服只能选择/, + ) + }) + + it('角色名称与角色 ID 都为空时拒绝保存', () => { + assert.throws( + () => normalizeCustomerProfile({ roleName: ' ', roleId: '', serverZone: '苹果V区' }), + /请完整填写区服/, + ) + }) +}) diff --git a/apps/backend/src/services/semi-auto/semi-auto-task-service.ts b/apps/backend/src/services/semi-auto/semi-auto-task-service.ts index 5efe0b64..709c1c9c 100644 --- a/apps/backend/src/services/semi-auto/semi-auto-task-service.ts +++ b/apps/backend/src/services/semi-auto/semi-auto-task-service.ts @@ -19,13 +19,16 @@ import { import { createHuyaBrowserTicket, createHuyaLoginSession, + confirmHuyaBinding, exportHuyaSessionCredential, getHuyaBinding, + getHuyaBindingSnapshot, getHuyaLoginSession, loginHuyaSms, revokeHuyaSession, sendHuyaSmsCode, startHuyaBinding, + submitHuyaRebind, consumeHuyaBrowserTicket, verifyHuyaSmsChallenge, type ConnectorBindingSession, @@ -52,6 +55,8 @@ import { markSemiAutoCredentialCheck, upsertSemiAutoCredentialWithClient, } from './semi-auto-credential-service.js' +import { querySemiAutoTraces } from './semi-auto-trace.js' +import { isNumericBindingRoleId } from './binding-role-id.js' const SEMI_AUTO_PLATFORMS = new Set(['huya', 'weibo']) type SemiAutoPlatform = 'huya' | 'weibo' @@ -98,7 +103,14 @@ type TaskRow = { platform_nickname: string bind_game_account: string bind_game_role: string + bind_game_role_id: string bind_game_channel: string + customer_game_role_name: string + customer_game_role_id: string + customer_game_server_zone: string + customer_game_id: string + customer_game_role: string + customer_server_zone: string target_quantity: number completed_quantity: number assigned_admin_user_id: number | null @@ -175,7 +187,20 @@ function displayStatus(task: TaskRow) { return { key: 'failed', label: '需客服处理' } } if (task.login_status === 'authenticated') { - return { key: 'waiting_operator', label: '等待客服处理' } + // 虎牙需要客户确认绑定角色后才算授权完成;微博登录即授权。 + if (task.platform === 'weibo' || task.binding_status === 'confirmed') { + return { key: 'waiting_operator', label: '等待客服处理' } + } + if (task.binding_status === 'role_ready') { + return { key: 'binding_confirm', label: '待确认绑定角色' } + } + if (task.binding_status === 'expired') { + return { key: 'binding_expired', label: '绑定二维码已过期' } + } + if (task.binding_status === 'failed') { + return { key: 'binding_failed', label: '绑定失败,需重新扫码' } + } + return { key: 'waiting_binding', label: '等待客户绑定角色' } } if (task.login_status === 'scanned') return { key: 'login_scanned', label: '已扫码,确认中' } if (task.login_status === 'qr_pending') return { key: 'waiting_login', label: '等待客户登录' } @@ -205,7 +230,11 @@ function mapTask(task: TaskRow) { platformNickname: task.platform_nickname, bindGameAccount: task.bind_game_account, bindGameRole: task.bind_game_role, + bindGameRoleId: task.bind_game_role_id, bindGameChannel: task.bind_game_channel, + customerGameRoleId: task.customer_game_id || '', + customerGameRoleName: task.customer_game_role || '', + customerServerZone: task.customer_server_zone || '', targetQuantity: Number(task.target_quantity || 1), completedQuantity: Number(task.completed_quantity || 0), assignedAdminUserId: task.assigned_admin_user_id ? Number(task.assigned_admin_user_id) : null, @@ -289,13 +318,41 @@ const TASK_SELECT = ` cfg.semi_auto_config_json, credential.credential_status, credential.credential_source, - credential.credential_updated_at + credential.credential_updated_at, + COALESCE( + NULLIF(task.customer_game_role_id, ''), + wo.material_json->'collect'->'fields'->>'gameId', + wo.material_json->'collect'->'fields'->>'characterId', + '' + ) AS customer_game_id, + COALESCE( + NULLIF(task.customer_game_role_name, ''), + NULLIF(wo.material_json->'collect'->'fields'->>'gameNickname', ''), + NULLIF(wo.material_json->'collect'->'fields'->>'roleName', ''), + '' + ) AS customer_game_role, + COALESCE( + NULLIF(task.customer_game_server_zone, ''), + wo.material_json->'collect'->'fields'->>'serverZone', + '' + ) AS customer_server_zone FROM semi_auto_tasks task JOIN orders o ON o.id = task.order_id JOIN order_items oi ON oi.id = task.order_item_id LEFT JOIN manual_fulfillment_configs cfg ON cfg.id = task.manual_fulfillment_config_id LEFT JOIN admin_users admin ON admin.id = task.assigned_admin_user_id LEFT JOIN semi_auto_credentials credential ON credential.id = task.credential_id + LEFT JOIN LATERAL ( + SELECT candidate.material_json + FROM work_orders candidate + WHERE candidate.order_item_id = task.order_item_id + OR (candidate.order_item_id IS NULL AND candidate.order_id = task.order_id) + OR (o.platform_order_id <> '' AND candidate.platform_order_id = o.platform_order_id) + ORDER BY (candidate.order_item_id = task.order_item_id) DESC NULLS LAST, + (candidate.order_id = task.order_id) DESC NULLS LAST, + candidate.id DESC + LIMIT 1 + ) wo ON TRUE ` async function loadTask(taskId: number): Promise { @@ -354,6 +411,24 @@ function assertHuyaTask(task: TaskRow) { } } +/** + * 半自动订单没有工单,资料页 /c/<订单号> 是唯一入口。 + * 未提交区服 / 游戏编号 / 角色名时,不允许开始登录,避免后续无法比对角色。 + */ +function assertCustomerProfileReady(task: TaskRow) { + if (task.platform !== 'huya') return + if ( + !String(task.customer_game_server_zone || '').trim() || + !String(task.customer_game_role_id || '').trim() || + !String(task.customer_game_role_name || '').trim() + ) { + throw createHttpError('请先提交游戏角色资料', { + statusCode: 409, + errorCode: 'semi_auto_profile_required', + }) + } +} + async function createLoginSessionForTask( task: TaskRow, orderNo: string, @@ -679,6 +754,98 @@ export async function markCustomerLinkOpened(orderNoInput: unknown, taskIdInput: return { ok: true } } +export type CustomerProfileInput = { + roleName?: unknown + roleId?: unknown + serverZone?: unknown +} + +const CUSTOMER_SERVER_ZONES = new Set(['苹果Q区', '苹果V区', '安卓Q区', '安卓V区']) + +export function normalizeCustomerProfile(input: CustomerProfileInput = {}) { + const roleName = String(input.roleName ?? '') + .trim() + .slice(0, 100) + const roleId = String(input.roleId ?? '') + .replace(/\s+/g, '') + .slice(0, 64) + const serverZone = String(input.serverZone ?? '') + .trim() + .slice(0, 100) + if (roleId && !/^\d+$/.test(roleId)) { + throw createHttpError('游戏编号 / 角色 ID 只能是数字', { + statusCode: 400, + errorCode: 'semi_auto_profile_role_id_invalid', + }) + } + if (!CUSTOMER_SERVER_ZONES.has(serverZone)) { + throw createHttpError('区服只能选择 苹果Q区 / 苹果V区 / 安卓Q区 / 安卓V区', { + statusCode: 400, + errorCode: 'semi_auto_profile_server_zone_invalid', + }) + } + if (!roleName || !roleId) { + throw createHttpError('请完整填写区服、游戏编号和角色名', { + statusCode: 400, + errorCode: 'semi_auto_profile_required', + }) + } + return { roleName, roleId, serverZone } +} + +/** + * 半自动订单没有 work_orders,客户资料只能在授权页 /c/<订单号> 收集。 + * 保存后立即参与“客户填写角色 vs 平台识别角色”的比对。 + */ +export async function savePublicTaskProfile( + orderNoInput: unknown, + taskIdInput: unknown, + payload: CustomerProfileInput = {}, +) { + const orderNo = normalizeOrderNo(orderNoInput) + const taskId = normalizeId(taskIdInput) + const task = await loadTaskForOrder(orderNo, taskId) + if (task.platform !== 'huya') { + throw createHttpError('当前平台不需要填写游戏角色', { + statusCode: 409, + errorCode: 'semi_auto_profile_not_supported', + }) + } + if (task.execution_status === 'completed' || task.execution_status === 'cancelled') { + throw createHttpError('当前订单已结束,不能修改角色资料', { + statusCode: 409, + errorCode: 'semi_auto_task_closed', + }) + } + if (task.binding_status === 'confirmed') { + throw createHttpError('绑定已确认,不能修改角色资料', { + statusCode: 409, + errorCode: 'semi_auto_profile_locked', + }) + } + const profile = normalizeCustomerProfile(payload) + await withTransaction(async (client) => { + await client.query( + ` + UPDATE semi_auto_tasks + SET customer_game_role_name = $2, + customer_game_role_id = $3, + customer_game_server_zone = $4, + updated_at = NOW() + WHERE id = $1 + `, + [task.id, profile.roleName, profile.roleId, profile.serverZone], + ) + await appendTaskEvent(client, task.id, { + eventType: 'customer_profile_saved', + actorType: 'customer', + detail: profile, + }) + }) + const updated = await loadTask(task.id) + return { task: mapTask(updated) } +} + function mapLoginUpdate(session: ConnectorLoginSession) { const statusMap: Record = { verification_pending: 'waiting_login', @@ -705,8 +872,13 @@ async function updateLoginTask( options: { credentialSource?: 'qr' | 'sms'; method?: 'qr' | 'sms' } = {}, ) { const mapped = mapLoginUpdate(session) + // 虎牙登录成功还不算授权完成,必须等客户确认绑定角色;微博登录即授权。 const nextExecutionStatus: ExecutionStatus = - mapped.status === 'authenticated' ? 'waiting_operator' : task.execution_status + mapped.status === 'authenticated' + ? task.platform === 'weibo' || task.binding_status === 'confirmed' + ? 'waiting_operator' + : 'waiting_customer' + : task.execution_status const storedCredential = mapped.status === 'authenticated' && mapped.hasCredential ? task.platform === 'weibo' @@ -750,19 +922,22 @@ async function updateLoginTask( credentialId, ], ) - await appendTaskEvent(client, task.id, { - eventType: 'login_status_changed', - actorType, - fromLoginStatus: task.login_status, - toLoginStatus: mapped.status, - fromExecutionStatus: task.execution_status, - toExecutionStatus: nextExecutionStatus, - detail: { - hasCredential: mapped.hasCredential, - message: mapped.message, - method: options.method || 'qr', - }, - }) + // 轮询会每 2 秒调用一次:状态与执行状态都没变时不写事件,避免时间线被重复项淹没。 + if (mapped.status !== task.login_status || nextExecutionStatus !== task.execution_status) { + await appendTaskEvent(client, task.id, { + eventType: 'login_status_changed', + actorType, + fromLoginStatus: task.login_status, + toLoginStatus: mapped.status, + fromExecutionStatus: task.execution_status, + toExecutionStatus: nextExecutionStatus, + detail: { + hasCredential: mapped.hasCredential, + message: mapped.message, + method: options.method || 'qr', + }, + }) + } }) } @@ -779,27 +954,164 @@ function mapBindingUpdate(session: ConnectorBindingSession) { return { status: statusMap[session.status] || 'failed', qrImage: String(session.qrImage || ''), + qrExpiresAt: String(session.qrExpiresAt || ''), + qrUrl: String(session.qrUrl || ''), bindGameAccount: String(session.bindGameAccount || ''), bindGameRole: String(session.bindGameRole || ''), + bindGameRoleId: String(session.bindGameRoleId || ''), bindGameChannel: String(session.bindGameChannel || ''), + hasExistingBinding: session.hasExistingBinding === true, + rebindRequested: session.rebindRequested === true, + rebindUnchanged: session.rebindUnchanged === true, + rebindConfirmState: session.rebindConfirmState || 'idle', + rebindConfirmMessage: String(session.rebindConfirmMessage || ''), + bindConfirmState: session.bindConfirmState || 'idle', + bindConfirmMessage: String(session.bindConfirmMessage || ''), + rebindCooldownDays: Number(session.rebindCooldownDays || 0), + nextRebindAt: String(session.nextRebindAt || ''), + platformChangeBindDay: Number(session.platformChangeBindDay || 0), + platformChangeBindTime: Number(session.platformChangeBindTime || 0), message: String(session.message || ''), } } +export type BindingRoleComparison = { + verdict: 'match' | 'mismatch' | 'unknown' + customerRoleName: string + customerRoleId: string + customerZone: string + boundRoleName: string + boundRoleId: string + boundZone: string + message: string +} + +function normalizeRoleText(value: unknown): string { + return String(value ?? '') + .replace(/\s+/g, '') + .toLowerCase() +} + +function normalizeServerZone(value: unknown): string { + const text = String(value ?? '').trim() + + if (!text) return '' + + return /区$/.test(text) ? text : `${text}区` +} + +/** + * 从虎牙渠道串解析区服,例如「安卓(android) · 微信」→ 安卓V区。 + * 解析不出平台或登录方式时返回空串,调用方跳过区服比对。 + */ +export function detectServerZone(channel: unknown): string { + const text = String(channel ?? '') + .replace(/\s+/g, '') + .toLowerCase() + + if (!text) return '' + + const platform = /苹果|ios/.test(text) ? '苹果' : /安卓|android/.test(text) ? '安卓' : '' + + if (!platform) return '' + + const login = /qq|q区/.test(text) ? 'Q' : /微信|wechat|v区/.test(text) ? 'V' : '' + + return login ? `${platform}${login}区` : '' +} + +/** + * 客户填写角色与平台识别角色必须一致才允许确认绑定。 + * + * 区服、角色名、角色 ID 三项都要一致: + * ① 两侧都有 ID 时 ID 必须相等; + * ② 两侧都有角色名时名称必须相等(不能因为 ID 相同就放行改名); + * ③ 平台渠道能解析出区服且客户有填时,区服必须相等。 + * 任一侧缺某字段时跳过该字段比对;三项都取不到才判 unknown,转客服核对。 + */ +export function compareBindingRole( + task: Pick< + TaskRow, + 'customer_game_id' | 'customer_game_role' | 'customer_game_server_zone' | 'huya_uid' + >, + binding: { bindGameRole?: string; bindGameRoleId?: string; bindGameChannel?: string }, +): BindingRoleComparison { + const customerRoleName = String(task.customer_game_role || '').trim() + const customerRoleId = String(task.customer_game_id || '').trim() + const customerZone = normalizeServerZone(task.customer_game_server_zone) + const boundRoleName = String(binding.bindGameRole || '').trim() + const rawBoundRoleId = String(binding.bindGameRoleId || '').trim() + // 虎牙 gameRole.roleId 是 40 位加密串,客户填写的是数值游戏编号; + // 平台侧可比对的是登录账号的数值 UID(huyaUid),不能拿加密串直接比对。 + const numericHuyaUid = /^\d+$/.test(String(task.huya_uid || '').trim()) + ? String(task.huya_uid).trim() + : '' + const boundRoleId = /^\d+$/.test(rawBoundRoleId) + ? rawBoundRoleId + : numericHuyaUid || rawBoundRoleId + const boundZone = detectServerZone(binding.bindGameChannel) + const base = { + customerRoleName, + customerRoleId, + customerZone, + boundRoleName, + boundRoleId, + boundZone, + } + + if (customerRoleId && boundRoleId && customerRoleId !== boundRoleId) { + return { ...base, verdict: 'mismatch', message: '两侧角色 ID 不一致,无法确认绑定' } + } + + if ( + customerRoleName && + boundRoleName && + normalizeRoleText(customerRoleName) !== normalizeRoleText(boundRoleName) + ) { + return { ...base, verdict: 'mismatch', message: '两侧角色名称不一致,无法确认绑定' } + } + + if (customerZone && boundZone && customerZone !== boundZone) { + return { ...base, verdict: 'mismatch', message: '两侧区服不一致,无法确认绑定' } + } + + const matchedFields = [ + customerRoleId && boundRoleId ? '角色 ID' : '', + customerRoleName && boundRoleName ? '角色名称' : '', + customerZone && boundZone ? '区服' : '', + ].filter(Boolean) + + if (matchedFields.length > 0) { + return { + ...base, + verdict: 'match', + message: `两侧${matchedFields.join('、')}一致,可确认绑定`, + } + } + + return { + ...base, + verdict: 'unknown', + message: '未获取到可核对的两侧角色信息,请联系客服核对后再确认', + } +} + async function updateBindingTask( task: TaskRow, session: ConnectorBindingSession, actorType: TaskActorType, ) { const mapped = mapBindingUpdate(session) + const comparison = compareBindingRole(task, mapped) + const roleIdVerified = isNumericBindingRoleId(mapped.bindGameRoleId) + const requiresSupport = + (Boolean(mapped.bindGameRole) || mapped.hasExistingBinding === true) && !roleIdVerified const executionStatus: ExecutionStatus = mapped.status === 'confirmed' ? 'waiting_operator' - : mapped.status === 'failed' || mapped.status === 'expired' - ? 'failed' - : task.execution_status === 'completed' || task.execution_status === 'cancelled' - ? task.execution_status - : 'waiting_customer' + : task.execution_status === 'completed' || task.execution_status === 'cancelled' + ? task.execution_status + : 'waiting_customer' await withTransaction(async (client) => { await client.query( ` @@ -807,6 +1119,7 @@ async function updateBindingTask( SET binding_status = $2, bind_game_account = CASE WHEN $3 <> '' THEN $3 ELSE bind_game_account END, bind_game_role = CASE WHEN $4 <> '' THEN $4 ELSE bind_game_role END, + bind_game_role_id = CASE WHEN $8 <> '' THEN $8 ELSE bind_game_role_id END, bind_game_channel = CASE WHEN $5 <> '' THEN $5 ELSE bind_game_channel END, bound_at = CASE WHEN $2 IN ('role_ready', 'confirmed') THEN COALESCE(bound_at, NOW()) ELSE bound_at END, execution_status = $6, @@ -822,30 +1135,68 @@ async function updateBindingTask( mapped.bindGameChannel, executionStatus, mapped.message, + mapped.bindGameRoleId, ], ) - await appendTaskEvent(client, task.id, { - eventType: 'binding_status_changed', - actorType, - fromBindingStatus: task.binding_status, - toBindingStatus: mapped.status, - fromExecutionStatus: task.execution_status, - toExecutionStatus: executionStatus, - detail: { - gameAccount: mapped.bindGameAccount, - gameRole: mapped.bindGameRole, - gameChannel: mapped.bindGameChannel, - message: mapped.message, - }, - }) + // 轮询会每 2 秒调用一次:只有状态/执行状态变化,或换绑被拒这类关键信号才写事件。 + const bindingChanged = + mapped.status !== task.binding_status || + executionStatus !== task.execution_status || + mapped.rebindUnchanged || + mapped.rebindConfirmState === 'rejected' + if (bindingChanged) { + await appendTaskEvent(client, task.id, { + eventType: 'binding_status_changed', + actorType, + fromBindingStatus: task.binding_status, + toBindingStatus: mapped.status, + fromExecutionStatus: task.execution_status, + toExecutionStatus: executionStatus, + detail: { + gameAccount: mapped.bindGameAccount, + gameRole: mapped.bindGameRole, + gameRoleId: mapped.bindGameRoleId, + gameChannel: mapped.bindGameChannel, + verdict: comparison.verdict, + rebindRequested: mapped.rebindRequested, + rebindUnchanged: mapped.rebindUnchanged, + rebindConfirmState: mapped.rebindConfirmState, + rebindConfirmMessage: mapped.rebindConfirmMessage, + bindConfirmState: mapped.bindConfirmState, + bindConfirmMessage: mapped.bindConfirmMessage, + rebindCooldownDays: mapped.rebindCooldownDays, + nextRebindAt: mapped.nextRebindAt, + changeBindDay: mapped.platformChangeBindDay, + changeBindTime: mapped.platformChangeBindTime, + message: mapped.message, + }, + }) + } }) return { status: mapped.status, qrImage: mapped.qrImage, + qrExpiresAt: mapped.qrExpiresAt, + qrUrl: mapped.qrUrl, bindGameAccount: mapped.bindGameAccount, bindGameRole: mapped.bindGameRole, + bindGameRoleId: mapped.bindGameRoleId, bindGameChannel: mapped.bindGameChannel, + roleIdVerified, + requiresSupport, + hasExistingBinding: mapped.hasExistingBinding, + rebindRequested: mapped.rebindRequested, + rebindUnchanged: mapped.rebindUnchanged, + rebindConfirmState: mapped.rebindConfirmState, + rebindConfirmMessage: mapped.rebindConfirmMessage, + bindConfirmState: mapped.bindConfirmState, + bindConfirmMessage: mapped.bindConfirmMessage, + rebindCooldownDays: mapped.rebindCooldownDays, + nextRebindAt: mapped.nextRebindAt, + platformChangeBindDay: mapped.platformChangeBindDay, + platformChangeBindTime: mapped.platformChangeBindTime, message: mapped.message, + comparison, } } @@ -854,6 +1205,7 @@ export async function startPublicLogin(orderNoInput: unknown, taskIdInput: unkno const taskId = normalizeId(taskIdInput) await ensureSemiAutoTasksForOrder(orderNo) const task = await loadTaskForOrder(orderNo, taskId) + assertCustomerProfileReady(task) if (task.execution_status === 'completed' || task.execution_status === 'cancelled') { throw createHttpError('当前订单已结束,不能重新登录', { statusCode: 409, @@ -907,6 +1259,13 @@ export async function startPublicLogin(orderNoInput: unknown, taskIdInput: unkno UPDATE semi_auto_tasks SET connector_session_id = $2, login_status = 'qr_pending', + binding_status = 'not_started', + bind_game_account = '', + bind_game_role = '', + bind_game_role_id = '', + bind_game_channel = '', + binding_started_at = NULL, + bound_at = NULL, execution_status = 'waiting_customer', auth_started_at = COALESCE(auth_started_at, NOW()), last_error = '', @@ -1007,7 +1366,11 @@ export async function pollPublicBinding(orderNoInput: unknown, taskIdInput: unkn return { task: mapTask(updated), binding } } -export async function confirmPublicBinding(orderNoInput: unknown, taskIdInput: unknown) { +export async function confirmPublicBinding( + orderNoInput: unknown, + taskIdInput: unknown, + options: { acceptExistingRole?: boolean } = {}, +) { const orderNo = normalizeOrderNo(orderNoInput) const taskId = normalizeId(taskIdInput) const task = await loadTaskForOrder(orderNo, taskId) @@ -1026,7 +1389,85 @@ export async function confirmPublicBinding(orderNoInput: unknown, taskIdInput: u errorCode: 'semi_auto_binding_not_ready', }) } - const session = await getBindingForTask(task, task.connector_session_id) + // 确认绑定是纯本地动作:虎牙侧只读内存快照,不再触发角色查询或换绑提交。 + const session = + task.platform === 'huya' + ? await getHuyaBindingSnapshot(task.connector_session_id, task.connector_mode) + : await getBindingForTask(task, task.connector_session_id) + if ( + task.platform === 'huya' && + session.rebindUnchanged === true && + options.acceptExistingRole !== true + ) { + // 换绑被虎牙拒绝时不直接放行,要求客户二选一:重新扫码换绑 / 仍使用原角色。 + const reason = String(session.rebindConfirmMessage || '').trim() + throw createHttpError( + `${ + reason ? `换绑未成功:${reason}。` : '换绑未生效:平台仍返回原绑定角色。' + }请重新扫码换绑,或确认继续使用原绑定角色「${session.bindGameRole || '原角色'}」`, + { + statusCode: 409, + errorCode: 'semi_auto_binding_rebind_decision_required', + }, + ) + } + // 已绑定角色但没有可核对的数字角色 ID:不能只按角色名放行,必须人工核实(客户页会提示联系客服)。 + const boundRolePresent = + Boolean(String(session.bindGameRole || '').trim()) || session.hasExistingBinding === true + if ( + task.platform === 'huya' && + boundRolePresent && + !isNumericBindingRoleId(session.bindGameRoleId) + ) { + throw createHttpError('平台未返回可核对的角色ID,请联系客服人工核实后再确认绑定', { + statusCode: 409, + errorCode: 'semi_auto_binding_role_id_missing', + }) + } + const comparison = compareBindingRole(task, session) + if (comparison.verdict === 'mismatch') { + throw createHttpError(comparison.message, { + statusCode: 409, + errorCode: 'semi_auto_binding_role_mismatch', + }) + } + // 必须调用 Connector 完成确认,否则会话仍是 role_ready,数据库也会停在待确认。 + const confirmedSession = + task.platform === 'huya' + ? await confirmHuyaBinding(task.connector_session_id, task.connector_mode, options) + : session + const binding = await updateBindingTask(task, confirmedSession, 'customer') + const updated = await loadTask(task.id) + return { task: mapTask(updated), binding } +} + +/** + * 客户在微信里选好目标角色后,由项目侧主动向虎牙提交换绑确认。 + * 与「确认绑定」不同,这一步只提交换绑,不把任务标记为已确认。 + */ +export async function submitPublicRebind(orderNoInput: unknown, taskIdInput: unknown) { + const orderNo = normalizeOrderNo(orderNoInput) + const taskId = normalizeId(taskIdInput) + const task = await loadTaskForOrder(orderNo, taskId) + if (task.execution_status === 'completed' || task.execution_status === 'cancelled') { + throw createHttpError('当前订单已结束,不能提交换绑', { + statusCode: 409, + errorCode: 'semi_auto_task_closed', + }) + } + if (task.platform !== 'huya') { + throw createHttpError('当前平台不需要换绑游戏角色', { + statusCode: 409, + errorCode: 'semi_auto_rebind_not_supported', + }) + } + if (!task.connector_session_id || task.login_status !== 'authenticated') { + throw createHttpError('请先完成平台登录', { + statusCode: 409, + errorCode: 'semi_auto_login_required', + }) + } + const session = await submitHuyaRebind(task.connector_session_id, task.connector_mode) const binding = await updateBindingTask(task, session, 'customer') const updated = await loadTask(task.id) return { task: mapTask(updated), binding } @@ -1041,6 +1482,7 @@ export async function sendPublicHuyaSmsCode( const taskId = normalizeId(taskIdInput) const task = await loadTaskForOrder(orderNo, taskId) assertHuyaTask(task) + assertCustomerProfileReady(task) if (task.execution_status === 'completed' || task.execution_status === 'cancelled') { throw createHttpError('当前订单已结束,不能重新登录', { statusCode: 409, @@ -1190,6 +1632,7 @@ export async function loginPublicHuyaSms( const taskId = normalizeId(taskIdInput) const task = await loadTaskForOrder(orderNo, taskId) assertHuyaTask(task) + assertCustomerProfileReady(task) if (task.execution_status === 'completed' || task.execution_status === 'cancelled') { throw createHttpError('当前订单已结束,不能重新登录', { statusCode: 409, @@ -1504,6 +1947,78 @@ export async function getAdminSemiAutoTask(taskIdInput: unknown) { } } +type SemiAutoTaskEventRow = { + id: number + event_type: string + actor_type: string + actor_id: string + from_login_status: string | null + to_login_status: string | null + from_binding_status: string | null + to_binding_status: string | null + from_execution_status: string | null + to_execution_status: string | null + detail_json: Record + created_at: string +} + +/** + * 运营端「历史」:任务状态流转事件 + 全链路报文(本系统入站 + 外部平台出站)。 + * 报文只读,不做任何写操作;Cookie / Token 已在落库前脱敏。 + */ +export async function getAdminSemiAutoTaskHistory( + taskIdInput: unknown, + input: Record = {}, +) { + 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( + `SELECT * FROM ( + SELECT id, event_type, actor_type, actor_id, + from_login_status, to_login_status, + from_binding_status, to_binding_status, + from_execution_status, to_execution_status, + detail_json, created_at + FROM semi_auto_task_events + WHERE task_id = $1 + ORDER BY id DESC + LIMIT 500 + ) recent + ORDER BY id ASC`, + [task.id], + ) + const traces = await querySemiAutoTraces(task.id, { + page: Number(input.page) || 1, + pageSize: Number(input.pageSize) || 50, + channel: String(input.channel || '').trim(), + status: String(input.status || '').trim(), + requestId: String(input.requestId || '').trim(), + keyword: String(input.keyword || '').trim(), + }) + return { + task: mapTask(task), + events: events.rows.map((event) => ({ + id: Number(event.id), + eventType: event.event_type, + actorType: event.actor_type, + actorId: event.actor_id, + fromLoginStatus: event.from_login_status, + toLoginStatus: event.to_login_status, + fromBindingStatus: event.from_binding_status, + toBindingStatus: event.to_binding_status, + fromExecutionStatus: event.from_execution_status, + toExecutionStatus: event.to_execution_status, + detail: event.detail_json || {}, + createdAt: event.created_at, + })), + eventTotal: Number(eventCount.rows[0]?.total || 0), + traces, + } +} + export async function exportAdminSemiAutoCredential(taskIdInput: unknown) { const task = await loadTask(normalizeId(taskIdInput)) if (!task.credential_id) { diff --git a/apps/backend/src/services/semi-auto/semi-auto-trace.ts b/apps/backend/src/services/semi-auto/semi-auto-trace.ts new file mode 100644 index 00000000..0788d1a7 --- /dev/null +++ b/apps/backend/src/services/semi-auto/semi-auto-trace.ts @@ -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 + requestBody?: unknown + responseSummary?: Record + responseBody?: unknown + errorMessage?: string + /** 写操作/关键读:无条件记录(轮询类不要传)。 */ + always?: boolean + /** 轮询类请求的状态指纹:与上次相同则不记录。 */ + fingerprint?: string | undefined +} + +const traceStorage = new AsyncLocalStorage() +const lastFingerprints = new Map() + +/** 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(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 + const result: Record = {} + 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?.() +} diff --git a/apps/backend/src/services/semi-auto/weibo-native/weibo-native-connector.ts b/apps/backend/src/services/semi-auto/weibo-native/weibo-native-connector.ts index e8711548..2af1a670 100644 --- a/apps/backend/src/services/semi-auto/weibo-native/weibo-native-connector.ts +++ b/apps/backend/src/services/semi-auto/weibo-native/weibo-native-connector.ts @@ -1076,8 +1076,10 @@ export class WeiboNativeConnector { status: 'confirmed', qrImage: '', qrExpiresAt: '', + qrUrl: '', bindGameAccount: account?.nickname || '', bindGameRole: account?.uid || '', + bindGameRoleId: account?.uid || '', bindGameChannel: '微博', hasExistingBinding: true, rebindRequested: false, diff --git a/apps/frontend/public/images/customer/inside-kv.jpg b/apps/frontend/public/images/customer/inside-kv.jpg new file mode 100644 index 00000000..fe1066fb Binary files /dev/null and b/apps/frontend/public/images/customer/inside-kv.jpg differ diff --git a/apps/frontend/src/components/admin/SemiAutoTaskHistoryDrawer.tsx b/apps/frontend/src/components/admin/SemiAutoTaskHistoryDrawer.tsx new file mode 100644 index 00000000..56268948 --- /dev/null +++ b/apps/frontend/src/components/admin/SemiAutoTaskHistoryDrawer.tsx @@ -0,0 +1,837 @@ +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 { describeSemiAutoTraceAction } from '@/utils/semi-auto-trace-action' +import { useIsMobile } from '@/utils/use-is-mobile' + +const { Text } = Typography + +/** 非状态类事件:名称直接写清楚「谁做了什么」。 */ +const EVENT_TITLES: Record = { + 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 = { + waiting_code: '等待客户输入验证码', + qr_pending: '生成登录二维码', + scanned: '客户已扫码,等待确认', + authenticated: '客户完成平台登录', + failed: '平台登录失败', + expired: '登录二维码已过期', +} + +const BINDING_EVENT_TITLES: Record = { + not_started: '绑定状态重置', + qr_pending: '生成绑定二维码', + scanned: '客户已扫码绑定', + role_ready: '平台识别到游戏角色', + confirmed: '客户确认绑定角色', + failed: '角色绑定失败', + expired: '绑定二维码已过期', +} + +const CHANNEL_LABELS: Record = { + customer_api: '客户接口', + admin_api: '运营接口', + huya_wup: '虎牙 WUP', + huya_http: '虎牙 HTTP', + external_connector: '外部 Connector', +} + +const CHANNEL_COLORS: Record = { + 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 = { + system: '系统', + customer: '客户', + admin: '客服', + connector: '平台连接器', +} + +const ACTOR_COLORS: Record = { + 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 = { + waiting_login: '等待登录', + qr_pending: '待扫码', + scanned: '已扫码', + authenticated: '已登录', + failed: '登录失败', + expired: '登录过期', +} + +const BINDING_STATUS_LABELS: Record = { + not_started: '未开始', + qr_pending: '待扫码', + scanned: '已扫码', + role_ready: '待确认角色', + confirmed: '已确认', + failed: '绑定失败', + expired: '已过期', +} + +const EXECUTION_STATUS_LABELS: Record = { + 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 = ( + + {history?.task ? ( + + + {LOGIN_STATUS_LABELS[history.task.loginStatus] || history.task.loginStatus} + + ), + }, + { + key: 'binding', + label: '绑定状态', + children: ( + + {history.task.platform === 'weibo' + ? '登录即授权' + : BINDING_STATUS_LABELS[history.task.bindingStatus] || + history.task.bindingStatus} + + ), + }, + { + key: 'execution', + label: '执行状态', + children: ( + + {EXECUTION_STATUS_LABELS[history.task.executionStatus] || + history.task.executionStatus} + + ), + }, + { + 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} 条`, + }, + ]} + /> + + ) : null} + + + { + setChannel(value || '') + setPage(1) + }} + options={CHANNEL_OPTIONS} + style={isMobile ? { flex: '1 1 150px', minWidth: 120 } : { width: 160 }} + /> + setMobile(event.target.value)} + placeholder={options.mobilePlaceholder} + inputMode="numeric" + maxLength={11} + /> + + + {options.afterMobile} + setSmsCode(event.target.value)} + placeholder={options.codePlaceholder} + maxLength={8} + inputMode="numeric" + onPressEnter={() => void handleLoginSms()} + /> + + + {options.footerNote} + + ) + + const huyaLoginForm = renderLoginForm({ + platformLabel: '虎牙', + mobilePlaceholder: '请输入号码', + codePlaceholder: '6 位验证码', + submitText: '登录', + }) if (loading) { return ( @@ -337,7 +1003,7 @@ export default function CustomerFulfillmentPage() { if (selectedTask?.executionStatus === 'completed') { return ( - +
@@ -360,6 +1026,17 @@ export default function CustomerFulfillmentPage() { ) } + if (needsProfileCollection && selectedTask) { + return ( + + setTasks((current) => current.map((item) => (item.id === task.id ? task : item))) + } + /> + ) + } + return (
@@ -383,98 +1060,35 @@ export default function CustomerFulfillmentPage() {
) : null} - + {selectedTask?.loginStatus === 'waiting_login' || selectedTask?.loginStatus === 'failed' || - selectedTask?.loginStatus === 'expired' ? ( + selectedTask?.loginStatus === 'expired' || + (loginQrVisible && loginMode === 'sms') ? (
- setLoginMode(key as 'sms' | 'qr')} - items={[ - { - key: 'sms', - label: '手机号登录', - children: ( -
-
- +86 - setMobile(event.target.value)} - placeholder={`请输入${isHuya ? '虎牙' : '微博'}绑定手机号`} - maxLength={11} - inputMode="numeric" - /> - -
- {isWeibo && smsMfaRequired ? ( -
- 请在安全验证弹窗中完成验证,通过后会继续发送短信验证码。 -
- ) : null} -
- setSmsCode(event.target.value)} - placeholder="请输入短信验证码" - maxLength={8} - prefix={} - onPressEnter={() => void handleLoginSms()} - /> - -
- {isWeibo ? ( - - 如安全验证弹窗未出现,请检查浏览器是否拦截脚本。 - - ) : null} + {isWeibo + ? renderLoginForm({ + platformLabel: '微博', + mobilePlaceholder: '请输入微博绑定手机号', + codePlaceholder: '请输入短信验证码', + submitText: '登录微博', + afterMobile: smsMfaRequired ? ( +
+ 请在安全验证弹窗中完成验证,通过后会继续发送短信验证码。
+ ) : null, + footerNote: ( + + 如安全验证弹窗未出现,请检查浏览器是否拦截脚本。 + ), - }, - { - key: 'qr', - label: '扫码登录', - children: ( -
-

- {config.loginInstructions || - `点击下方按钮后,使用${isHuya ? '虎牙' : '微博'} App 扫码并确认登录。`} -

- -
- ), - }, - ]} - /> + }) + : huyaLoginForm}
) : null} - {loginQrVisible ? ( + {loginQrVisible && loginMode === 'qr' ? (
@@ -508,16 +1122,465 @@ export default function CustomerFulfillmentPage() { ) : null} +
) : null} - {selectedTask?.loginStatus === 'authenticated' && + {showBindingStage ? ( +
+
+

+ 绑定信息 (已登录虎牙账号) +

+
+ 登录账号 + + {bindingInfo?.bindGameAccount || selectedTask.bindGameAccount || '未获取'} + +
+
+ 绑定角色 + {bindingRoleName || '未识别到角色'} +
+
+ + {bindingSessionExpired ? ( +
+

虎牙登录会话已过期

+

+ 请返回登录重新扫码,已填写的订单资料和绑定状态不会丢失。 +

+ +
+ ) : null} + + {bindingBanner ? ( +
+ {bindingBanner.text} +
+ ) : null} + + {showProfileForm && !bindingSessionExpired ? ( +
+

修改资料后会重新核对平台识别角色。

+
+ + setProfileRoleId(event.target.value)} + placeholder="请输入游戏编号" + maxLength={64} + inputMode="numeric" + /> + + setProfileRoleName(event.target.value)} + placeholder="请输入角色名" + maxLength={100} + /> + +
+
+ ) : null} + + {bindingQrVisible && !bindingSessionExpired ? ( +
+

游戏角色绑定二维码

+ {bindingInfo?.qrImage || bindingQrImage ? ( + 游戏角色绑定二维码 + ) : bindingLoadError ? ( +
+

绑定二维码加载失败

+ {bindingLoadError} +
+ + +
+
+ ) : ( +
+ + 正在生成绑定二维码... +
+ )} +

+ {bindingInfo?.hasExistingBinding === false + ? '该虎牙账号还没有绑定游戏角色,请用微信扫码完成绑定' + : '请使用微信APP扫码进行游戏角色绑定'} +

+

+ 扫码后系统会核对平台角色与已填资料;不一致时可修改资料或同步平台角色。 +

+

+ {selectedTask?.bindingStatus === 'scanned' + ? rebindAccepted + ? '已向虎牙提交换绑,正在等待角色生效,请稍候刷新。' + : bindConfirmPending + ? '已向虎牙提交绑定,正在等待角色生效,请稍候刷新。' + : bindingInfo?.rebindRequested + ? '扫码后请在虎牙弹窗中选中目标角色;选好后点下方「已选好角色,提交换绑」。' + : '请在微信中完成角色绑定确认,再点击下方按钮进入下一步。' + : '扫码后请在微信确认框中核对目标角色。'} +

+ {nextRebindText ? ( +

+ 本次换绑成功后,下次可换绑:{nextRebindText}。 +

+ ) : null} +

+ {selectedTask?.bindingStatus === 'scanned' + ? bindingInfo?.message || '已扫码,等待角色生效' + : `建议 ${formatCountdown(bindingSecondsLeft)} 内完成扫码`} +

+
+ + +
+ {selectedTask?.bindingStatus === 'scanned' && + bindingInfo?.rebindRequested && + !rebindAccepted ? ( + + ) : ( + + )} +
+ ) : null} + + {selectedTask?.bindingStatus === 'expired' ? ( + + 重新获取 + + } + /> + ) : null} + + {selectedTask?.bindingStatus === 'failed' ? ( + + 重新获取 + + } + /> + ) : null} + + {selectedTask?.bindingStatus === 'role_ready' && !bindingSessionExpired ? ( + + {bindingRequiresSupport ? ( + + ) : showRebindFailure ? ( + + + 平台仍返回原绑定角色: + {bindingRoleName || '未识别到角色'} + + {bindingInfo?.rebindConfirmMessage ? ( + 虎牙原因:{bindingInfo.rebindConfirmMessage} + ) : null} + {nextRebindText ? 预计下次可换绑:{nextRebindText} : null} + {Number(bindingInfo?.platformChangeBindDay || 0) > 0 ? ( + + 虎牙规则:每 {bindingInfo?.platformChangeBindDay} 个自然日可换绑 1 次 + + ) : null} + {!bindingInfo?.rebindConfirmMessage && !nextRebindText ? ( + 请核对虎牙弹窗中选中的目标角色后重新提交。 + ) : null} + + } + /> + ) : ( + + )} + {!bindingRequiresSupport && + !showRebindFailure && + comparisonMismatch && + bindingComparison ? ( + + + 平台角色:{bindingComparison.boundZone || '区服未知'} ·{' '} + {bindingComparison.boundRoleName || '角色未知'}(ID{' '} + {bindingComparison.boundRoleId || '未知'}) + + + 已填资料:{bindingComparison.customerZone || '区服未填'} ·{' '} + {bindingComparison.customerRoleName || '角色未填'}(ID{' '} + {bindingComparison.customerRoleId || '未填'}) + + 三项一致后才能提交确认;可一键同步平台角色。 + + } + /> + ) : null} + {bindingRequiresSupport ? ( +
+ + +
+ ) : showRebindFailure ? ( +
+ + + +
+ ) : comparisonMismatch ? ( +
+ + +
+ ) : rebindUnchanged ? ( +
+ + +
+ ) : ( +
+ + +
+ )} + + ) : null} + + {selectedTask?.bindingStatus === 'confirmed' ? ( +
+

绑定状态需要平台人工核实,请联系客服处理

+ +
+ ) : null} +
+ ) : null} + + {isWeibo && + selectedTask?.loginStatus === 'authenticated' && selectedTask.executionStatus !== 'completed' ? (
@@ -535,6 +1598,89 @@ export default function CustomerFulfillmentPage() {
) : null} + { + if (!bindingLoading) setBindingConfirmOpen(false) + }} + footer={ +
+
+ + +
+ {bindingComparison?.verdict === 'mismatch' ? ( +
+ + {canSyncBindingProfile ? ( + + ) : null} +
+ ) : null} + {bindingComparison?.verdict === 'mismatch' ? ( +

+ {bindingComparison?.message || '两侧角色信息不一致,无法确认绑定'} +

+ ) : bindingComparison?.verdict === 'unknown' ? ( +

两侧角色信息不完整,请联系客服核实

+ ) : null} +
+ } + destroyOnClose + > + +

检测到待确认的绑定角色,请核对两侧角色是否一致。

+
+
+
+ 您填写的角色 + +
+ {bindingComparison?.customerRoleName || '未填写'} + {bindingComparison?.customerRoleId || '未填写角色ID'} +
+
+
+ 待确认角色 + +
+ {bindingComparison?.boundRoleName || '未识别到角色'} + {bindingPendingUid || '未获取到角色ID'} +
+
+
+
+ void handleVerifyHuyaChallenge(solution)} /> - + {isWeibo ? : null}
) @@ -568,60 +1714,172 @@ function CustomerAuthFrame(input: {
-
- {input.platform === 'weibo' - ? '温馨提示:未成年人禁止下单' - : '温馨提示:请使用本人账号完成授权'} -
+ {input.platform === 'weibo' ? ( +
温馨提示:未成年人禁止下单
+ ) : null}
{input.children}
) } -function CustomerTaskFacts(input: { task: CustomerSemiAutoTask | null }) { - const task = input.task - if (!task) return null - const statusTone = - task.displayStatus.key === 'credential_expired' || task.displayStatus.key === 'failed' - ? 'is-danger' - : task.loginStatus === 'authenticated' - ? 'is-success' - : 'is-pending' - const showAccountDetails = ['authenticated', 'scanned'].includes(task.loginStatus) +function CustomerOrderCard({ task }: { task: CustomerSemiAutoTask }) { + if (task.platform === 'weibo') { + return ( +
+

订单信息

+
+ 订单号 + {task.orderNo} +
+
+ 商品 + + {task.productName || task.skuName} × {task.quantity} + +
+
+ 平台 + {task.platformLabel || '微博'} +
+
+ 状态 + {task.displayStatus.label} +
+
+ ) + } + const zone = task.customerServerZone + ? /区$/.test(task.customerServerZone) + ? task.customerServerZone + : `${task.customerServerZone}区` + : '' + const roleText = [zone, task.customerGameRoleName].filter(Boolean).join('-') || '未填写' return ( -
+
+

订单信息

- 订单号 - {task.orderNo} + 游戏名称 + 和平精英
- 商品 - - {task.productName || task.skuName} × {task.quantity} - + 角色名称 + {roleText}
- 平台 - {task.platformLabel || task.platform} + 购买物品 + {task.productName || task.skuName}
- {showAccountDetails && task.huyaUid ? ( -
- 平台账号 ID - {task.huyaUid} +
+ ) +} + +function CustomerCollectStep(input: { + task: CustomerSemiAutoTask + onSaved: (task: CustomerSemiAutoTask) => void +}) { + const { message } = App.useApp() + const [serverZone, setServerZone] = useState(input.task.customerServerZone || '') + const [roleId, setRoleId] = useState(input.task.customerGameRoleId || '') + const [roleName, setRoleName] = useState(input.task.customerGameRoleName || '') + const [saving, setSaving] = useState(false) + + async function submit() { + if (!serverZone.trim() || !roleId.trim() || !roleName.trim()) { + message.warning('请完整填写区服、游戏编号和角色名') + return + } + if (!SERVER_ZONE_OPTIONS.includes(serverZone.trim())) { + message.warning('请选择区服') + return + } + if (!/^\d+$/.test(roleId.trim())) { + message.warning('游戏编号只能是数字') + return + } + setSaving(true) + try { + const response = await saveCustomerTaskProfile(input.task.orderNo, input.task.id, { + roleName: roleName.trim(), + roleId: roleId.trim(), + serverZone: serverZone.trim(), + }) + input.onSaved(response.data.task) + message.success('资料已提交') + } catch (error) { + message.error(error instanceof Error ? error.message : '提交资料失败') + } finally { + setSaving(false) + } + } + + return ( +
+
+

温馨提示:未成年人禁止下单

+
+
+ +
{input.task.orderNo}
+ +
+
+ 商品 + {input.task.productName || input.task.skuName} +
+
+ 游戏 + 和平精英 +
+

填完资料记得截图联系客服。

- ) : null} - {showAccountDetails && task.platform === 'weibo' && task.platformNickname ? ( -
- 账号昵称 - {task.platformNickname} -
- ) : null} -
- 状态 - - {task.displayStatus.label} - + + + setRoleId(event.target.value)} + placeholder="请输入游戏编号" + maxLength={64} + inputMode="numeric" + /> + + + setRoleName(event.target.value)} + placeholder="请输入角色名" + maxLength={100} + /> + +
) @@ -635,8 +1893,20 @@ function CustomerPrivacyNote() { ) } +/** Connector 重启或会话被回收时后端返回该错误码,需要引导客户重新登录。 */ +function isHuyaSessionExpired(error: unknown) { + return (error as { errorCode?: string } | null)?.errorCode === 'huya_native_session_not_found' +} + function isValidMainlandMobile(value: string) { const digits = value.replace(/\D/g, '') if (!digits) return false return /^1\d{10}$/.test(digits) } + +function formatCountdown(seconds: number) { + const safe = Math.max(0, Math.floor(seconds)) + const minutes = Math.floor(safe / 60) + const rest = safe % 60 + return `${minutes}:${String(rest).padStart(2, '0')}` +} diff --git a/apps/frontend/src/services/admin/semi-auto.ts b/apps/frontend/src/services/admin/semi-auto.ts index dc8bf0d9..8fdcb002 100644 --- a/apps/frontend/src/services/admin/semi-auto.ts +++ b/apps/frontend/src/services/admin/semi-auto.ts @@ -2,6 +2,7 @@ import { apiGet, apiPost } from '@/lib/http' import type { SemiAutoCredentialExport, SemiAutoTaskDetail, + SemiAutoTaskHistory, SemiAutoTaskListResult, } from '@/types/admin/semi-auto' @@ -13,6 +14,13 @@ export function fetchAdminSemiAutoTask(taskId: number) { return apiGet(`/api/v1/admin/semi-auto/tasks/${taskId}`) } +export function fetchAdminSemiAutoTaskHistory( + taskId: number, + params: Record = {}, +) { + return apiGet(`/api/v1/admin/semi-auto/tasks/${taskId}/history`, params) +} + export function exportAdminSemiAutoCredential(taskId: number) { return apiPost( `/api/v1/admin/semi-auto/tasks/${taskId}/credential/export`, diff --git a/apps/frontend/src/services/customer-fulfillment.ts b/apps/frontend/src/services/customer-fulfillment.ts index b160b86f..fa11097e 100644 --- a/apps/frontend/src/services/customer-fulfillment.ts +++ b/apps/frontend/src/services/customer-fulfillment.ts @@ -1,5 +1,9 @@ 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) { return apiGet( @@ -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) { return apiPost<{ task: CustomerSemiAutoTask; login: CustomerLoginInfo }>( `/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 = { image: string width: number diff --git a/apps/frontend/src/styles/client.css b/apps/frontend/src/styles/client.css index ede4a554..1b341f6d 100644 --- a/apps/frontend/src/styles/client.css +++ b/apps/frontend/src/styles/client.css @@ -1437,54 +1437,80 @@ } .customer-auth-page { - --auth-accent: #ff8a00; - --auth-accent-hover: #ffa12f; - --auth-panel: #07142e; - --auth-panel-soft: #0d1d3d; - --auth-line: rgba(255, 255, 255, 0.11); - --auth-text: #f8fafc; - --auth-muted: #a6b0c3; + --auth-accent: #2f6fed; + --auth-accent-hover: #4a83ff; + --auth-panel: #232936; + --auth-panel-soft: #2a3140; + --auth-line: rgba(255, 255, 255, 0.08); + --auth-text: #f5f7fa; + --auth-muted: #9aa3b2; min-height: 100vh; display: flex; justify-content: center; overflow-x: hidden; - padding: clamp(20px, 4vw, 48px) 16px; + padding: 0; color: var(--auth-text); - background: #202124; + background: #232936; } .customer-auth-shell { - width: min(760px, 100%); + width: min(560px, 100%); min-width: 0; - align-self: flex-start; + align-self: stretch; overflow: hidden; - border: 1px solid rgba(255, 255, 255, 0.08); - border-radius: 8px; - background: var(--auth-panel); - box-shadow: 0 28px 70px rgba(0, 0, 0, 0.34); + border: none; + border-radius: 0; + background: transparent; + box-shadow: none; } .customer-auth-hero { - min-height: 176px; + min-height: auto; display: flex; align-items: center; - padding: 34px 38px; + justify-content: center; + padding: 38px 16px 10px; + background: none; +} + +/* 微博登录页顶部 KV:与资料页共用 inside-kv.jpg,叠加深色渐变保证标题可读。 */ +.customer-auth-page.is-weibo .customer-auth-hero { + min-height: 134px; + align-items: flex-start; + justify-content: flex-start; + padding: 26px 20px 20px; + background-color: #0b1220; background-image: - linear-gradient( - 90deg, - rgba(3, 18, 55, 0.97) 0%, - rgba(5, 23, 65, 0.83) 48%, - rgba(7, 20, 43, 0.45) 100% - ), - url('https://game.gtimg.cn/images/gp/web201908/inside_kv.jpg'); - background-position: center; + linear-gradient(180deg, rgba(11, 18, 32, 0.12) 0%, rgba(11, 18, 32, 0.72) 72%, #232936 100%), + url('/images/customer/inside-kv.jpg'); + background-repeat: no-repeat; + background-position: center 38%; background-size: cover; } +.customer-auth-page.is-weibo .customer-auth-brand { + width: 100%; + justify-content: flex-start; +} + +.customer-auth-page.is-weibo .customer-auth-brand h1 { + text-align: left; + text-shadow: 0 2px 12px rgba(0, 0, 0, 0.72); +} + +@media (max-width: 640px) { + .customer-auth-page.is-weibo .customer-auth-hero { + min-height: 118px; + padding: 20px 16px 14px; + background-position: center 42%; + } +} + .customer-auth-brand { display: flex; align-items: center; - gap: 18px; + justify-content: center; + gap: 0; min-width: 0; } @@ -1505,28 +1531,30 @@ .customer-auth-brand h1 { margin: 0; color: #fff; - font-size: clamp(18px, 2.3vw, 22px); - line-height: 1.3; - font-weight: 600; + font-size: 20px; + line-height: 1.4; + font-weight: 700; letter-spacing: 0; - white-space: nowrap; + text-align: center; + white-space: normal; overflow-wrap: anywhere; } .customer-auth-warning { - padding: 19px 24px; + padding: 6px 16px 10px; color: #ff6975; text-align: center; - font-size: 20px; - font-weight: 700; - background: #06122b; - border-bottom: 1px solid var(--auth-line); + font-size: 14px; + font-weight: 600; + background: transparent; + border-bottom: none; } .customer-auth-main { min-width: 0; + padding-bottom: 24px; color: var(--auth-text); - background: var(--auth-panel); + background: transparent; } .customer-auth-content-stack { @@ -1605,8 +1633,8 @@ .customer-auth-section { min-width: 0; - padding: 28px 26px 30px; - border-bottom: 1px solid var(--auth-line); + padding: 16px; + border-bottom: none; } .customer-auth-section-heading { @@ -1616,24 +1644,24 @@ } .customer-auth-section-icon { - width: 42px; - height: 42px; + width: 36px; + height: 36px; flex: none; display: grid; place-items: center; border: 1px solid rgba(255, 255, 255, 0.15); - border-radius: 7px; + border-radius: 8px; color: var(--auth-accent); - font-size: 22px; + font-size: 18px; background: rgba(255, 255, 255, 0.035); } .customer-auth-section-heading h2, .customer-auth-state h2 { - margin: 0 0 8px; + margin: 0 0 6px; color: #fff; - font-size: 23px; - line-height: 1.35; + font-size: 18px; + line-height: 1.4; font-weight: 700; } @@ -1860,7 +1888,7 @@ } .customer-auth-page .ant-btn-primary { - color: #111827; + color: #fff; border-color: var(--auth-accent); background: var(--auth-accent); font-weight: 700; @@ -1868,7 +1896,7 @@ } .customer-auth-page .ant-btn-primary:hover { - color: #111827 !important; + color: #fff !important; border-color: var(--auth-accent-hover) !important; background: var(--auth-accent-hover) !important; } @@ -2081,6 +2109,859 @@ font-size: 12px; } +.customer-auth-binding { + display: flex; + flex-direction: column; + gap: 16px; +} + +.customer-auth-binding-tip { + color: #ffb454; + font-size: 13px; +} + +.customer-auth-profile { + padding: 16px; + border: 1px solid #3a4150; + border-radius: 12px; + background: #212733; +} + +.customer-auth-profile-summary { + padding: 14px; + border: 1px solid rgba(255, 255, 255, 0.14); + border-radius: 6px; + background: rgba(255, 255, 255, 0.04); +} + +.customer-auth-profile > p { + margin: 0 0 12px; + color: #9aa3b2; + font-size: 13px; + line-height: 1.6; +} + +.customer-profile-form { + display: flex; + flex-direction: column; + gap: 12px; +} + +.customer-profile-form .customer-collect-label { + margin-top: 2px; +} + +.customer-auth-profile-summary { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 10px; +} + +.customer-auth-profile-summary span { + color: var(--auth-muted); + font-size: 13px; +} + +.customer-auth-profile-summary strong { + color: #fff; + font-size: 15px; +} + +.customer-auth-profile-summary em { + color: var(--auth-muted); + font-style: normal; + font-size: 13px; +} + +/* 客户资料页(图 1) */ +.customer-collect-page { + min-height: 100vh; + background: #0b1220; + color: #e5e7eb; +} + +/* 资料页顶部 KV:原图 https://game.gtimg.cn/images/gp/web201908/inside_kv.jpg(本地 1600×510 q82) */ +.customer-collect-hero { + position: relative; + min-height: clamp(190px, 24vw, 240px); + display: flex; + align-items: flex-end; + justify-content: center; + padding: 0 20px 16px; + overflow: hidden; + text-align: center; + background-color: #0b1220; + background-image: + linear-gradient(180deg, rgba(11, 18, 32, 0) 45%, rgba(11, 18, 32, 0.55) 72%, #0b1220 100%), + url('/images/customer/inside-kv.jpg'); + background-repeat: no-repeat; + background-position: center 38%; + background-size: cover; +} + +.customer-collect-warning { + margin: 0; + text-align: center; + color: #f87171; + font-size: 17px; + font-weight: 600; + text-shadow: 0 1px 8px rgba(0, 0, 0, 0.8); +} + +@media (max-width: 640px) { + .customer-collect-hero { + min-height: 180px; + padding: 0 16px 14px; + background-position: center 42%; + } + + .customer-collect-warning { + font-size: 15px; + } +} + +.customer-collect-body { + max-width: 560px; + margin: 0 auto; + padding: 24px 20px 48px; + display: flex; + flex-direction: column; + gap: 12px; +} + +.customer-collect-label { + margin-top: 8px; + color: #e5e7eb; + font-size: 15px; + line-height: 1.4; +} + +.customer-collect-label span { + color: #f87171; +} + +.customer-collect-readonly { + height: 48px; + display: flex; + align-items: center; + padding: 0 16px; + border-radius: 12px; + background: #1b2436; + border: 1px solid #26344d; + color: #94a3b8; + font-size: 15px; +} + +.customer-collect-card { + margin: 10px 0; + padding: 16px; + border-radius: 12px; + border: 1px solid #1e2f4a; + background: #141d30; + display: flex; + flex-direction: column; + gap: 12px; +} + +.customer-collect-card > div { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 12px; + color: #cbd5e1; + font-size: 15px; + line-height: 1.5; +} + +.customer-collect-card > div > span { + flex: 0 0 auto; + white-space: nowrap; +} + +.customer-collect-card > div strong { + flex: 1 1 auto; + min-width: 0; + color: #fff; + font-weight: 600; + text-align: right; + overflow-wrap: anywhere; +} + +.customer-collect-card > p { + margin: 6px 0 0; + color: #fbbf24; + font-size: 13px; + text-align: center; +} + +.customer-collect-input.ant-input { + height: 48px; + border-radius: 12px; + background: #1b2436; + border-color: #26344d; + color: #fff; +} + +.customer-collect-input.ant-input::placeholder { + color: #64748b; +} + +.customer-collect-select.ant-select { + width: 100%; + height: 48px; + padding-inline: 16px; + align-items: center; + font-size: 15px; + border-radius: 12px; + border: 1px solid #26344d; + background: #1b2436; + color: #fff; + --ant-select-height: 48px; + --ant-select-border-radius: 12px; + --ant-select-border-color: #26344d; + --ant-select-background-color: #1b2436; + --ant-select-color: #fff; + --ant-select-hover-border-color: #3b4d6b; + --ant-select-active-border-color: #2563eb; + --ant-select-active-outline-color: rgba(37, 99, 235, 0.2); +} + +.customer-collect-select.ant-select:hover { + border-color: #3b4d6b; +} + +.customer-collect-select.ant-select.ant-select-focused { + border-color: #2563eb; + box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.2); +} + +.customer-collect-select .ant-select-content { + align-items: center; +} + +.customer-collect-select .ant-select-selection-item { + color: #fff; + line-height: 1.5; +} + +.customer-collect-select .ant-select-placeholder { + color: #64748b; +} + +.customer-collect-select .ant-select-suffix { + color: #94a3b8; +} + +.ant-select-dropdown.customer-collect-dropdown { + padding: 6px; + border-radius: 12px; + background: #141d30; + box-shadow: 0 14px 34px rgba(2, 6, 23, 0.55); + --ant-select-option-active-bg: #1b2436; + --ant-select-option-selected-bg: #1e3a8a; + --ant-select-option-selected-color: #fff; +} + +.customer-collect-dropdown .ant-select-item { + border-radius: 8px; + color: #cbd5e1; +} + +.customer-collect-dropdown .ant-select-item-option-active { + background: #1b2436 !important; + color: #fff; +} + +.customer-collect-dropdown .ant-select-item-option-selected { + background: #1e3a8a !important; + color: #fff; + font-weight: 600; +} + +.customer-collect-page .customer-collect-submit.ant-btn, +.customer-auth-profile .customer-collect-submit.ant-btn { + height: 52px; + margin-top: 14px; + border-radius: 14px; + font-size: 17px; + font-weight: 600; + --ant-btn-bg-color: #2563eb; + --ant-btn-bg-color-hover: #1d4ed8; + --ant-btn-bg-color-active: #1e40af; + --ant-btn-text-color: #fff; + --ant-btn-text-color-hover: #fff; + --ant-btn-text-color-active: #fff; + --ant-btn-border-color: #2563eb; + --ant-btn-border-color-hover: #1d4ed8; + --ant-btn-border-color-active: #1e40af; + background: #2563eb !important; + border-color: #2563eb !important; + color: #fff !important; +} + +.customer-collect-page .customer-collect-submit.ant-btn:hover, +.customer-collect-page .customer-collect-submit.ant-btn:focus-visible, +.customer-auth-profile .customer-collect-submit.ant-btn:hover, +.customer-auth-profile .customer-collect-submit.ant-btn:focus-visible { + background: #1d4ed8 !important; + border-color: #1d4ed8 !important; + color: #fff !important; +} + +/* 登录与绑定页(图 2-10) */ +.customer-login-form { + display: flex; + flex-direction: column; + gap: 12px; +} + +.customer-login-hint { + margin: 0 0 2px; + color: #d5dae3; + font-size: 16px; + line-height: 1.5; +} + +.customer-login-mobile-row { + display: flex; + align-items: stretch; + gap: 12px; +} + +.customer-login-mobile.ant-input { + flex: 1; + min-width: 0; + height: 48px; + padding: 0 16px; + border-radius: 8px; + border-color: #3a4150; + background: #1b2130; + color: #fff; + font-size: 15px; +} + +.customer-login-mobile.ant-input::placeholder { + color: #6b7482; +} + +.customer-login-code-button.ant-btn { + flex: none; + width: 118px; + height: 48px; + border-radius: 8px; + background: #3b82f6 !important; + border-color: #3b82f6 !important; + color: #fff !important; + font-size: 16px; +} + +.customer-login-code-input.ant-input { + height: 48px; + border-radius: 8px; + border-color: #3a4150; + background: #1b2130; + color: #fff; + text-align: center; + font-size: 15px; + letter-spacing: 6px; +} + +.customer-login-code-input.ant-input::placeholder { + color: #6b7482; +} + +.customer-login-submit.ant-btn { + height: 52px; + border-radius: 14px; + background: #2563eb !important; + border-color: #2563eb !important; + color: #fff !important; + font-size: 17px; + font-weight: 600; +} + +.customer-login-submit.ant-btn:hover, +.customer-login-submit.ant-btn:focus-visible { + background: #1d4ed8 !important; + border-color: #1d4ed8 !important; + color: #fff !important; +} + +.customer-login-alt.ant-btn { + height: 48px; + border-radius: 8px; + background: transparent !important; + border-color: #3a4150 !important; + color: #cbd5e1 !important; + font-size: 16px; +} + +.customer-order-card { + margin: 10px 16px 0; + padding: 16px; + border: 1px solid #3a4150; + border-radius: 12px; + background: #212733; + display: flex; + flex-direction: column; + gap: 10px; +} + +.customer-order-card h3 { + margin: 0 0 4px; + color: #94a3b8; + font-size: 13px; + font-weight: 500; +} + +.customer-order-card > div { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 12px; + color: #cbd5e1; + font-size: 14px; + line-height: 1.5; +} + +.customer-order-card > div > span { + flex: 0 0 auto; + white-space: nowrap; + color: #9aa3b2; +} + +.customer-order-card > div strong { + flex: 1 1 auto; + min-width: 0; + color: #fff; + text-align: right; + overflow-wrap: anywhere; +} + +.customer-order-card > div strong.customer-order-status { + flex: 0 0 auto; + padding: 3px 12px; + border: 1px solid rgba(96, 165, 250, 0.38); + border-radius: 999px; + color: #dbeafe; + font-size: 13px; + font-weight: 600; + text-align: center; + background: rgba(47, 111, 237, 0.28); +} + +.customer-binding-stage { + display: flex; + flex-direction: column; + gap: 14px; + padding: 16px; +} + +.customer-binding-session-card { + display: flex; + flex-direction: column; + gap: 10px; + padding: 18px; + border: 1px solid #78350f; + border-radius: 12px; + background: rgba(120, 53, 15, 0.22); +} + +.customer-binding-session-title { + margin: 0; + color: #fbbf24; + font-size: 16px; + font-weight: 700; +} + +.customer-binding-session-desc { + margin: 0 0 4px; + color: #fcd34d; + font-size: 13px; + line-height: 1.6; +} + +.customer-binding-qr-error { + display: flex; + flex-direction: column; + align-items: center; + gap: 10px; + padding: 24px 12px; + text-align: center; +} + +.customer-binding-qr-error p { + margin: 0; + color: #fca5a5; + font-size: 15px; + font-weight: 600; +} + +.customer-binding-qr-error span { + color: #cbd5e1; + font-size: 13px; + line-height: 1.6; + overflow-wrap: anywhere; +} + +/* antd Alert 在绑定阶段统一走深色卡片,避免浅色块破坏整体深色风格 */ +.customer-binding-stage .ant-alert { + align-items: flex-start; + padding: 12px 14px; + border: 1px solid #3a4150; + border-radius: 12px; + background: #212733; +} + +.customer-binding-stage .ant-alert .ant-alert-message { + color: #e2e8f0; + font-size: 14px; + font-weight: 600; +} + +/* antd v6 的标题节点是 .ant-alert-title(v5 为 .ant-alert-message) */ +.customer-binding-stage .ant-alert .ant-alert-title { + color: #e2e8f0; + font-size: 14px; + font-weight: 600; + line-height: 1.5; +} + +.customer-binding-stage .ant-alert .ant-alert-description { + color: #cbd5e1; + font-size: 13px; + line-height: 1.6; +} + +.customer-binding-stage .ant-alert-warning { + border-color: #78350f; + background: rgba(120, 53, 15, 0.22); +} + +.customer-binding-stage .ant-alert-warning .ant-alert-icon, +.customer-binding-stage .ant-alert-warning .ant-alert-message, +.customer-binding-stage .ant-alert-warning .ant-alert-title { + color: #fbbf24; +} + +.customer-binding-stage .ant-alert-warning .ant-alert-description { + color: #fcd34d; +} + +.customer-binding-stage .ant-alert-error { + border-color: #7f1d1d; + background: rgba(127, 29, 29, 0.24); +} + +.customer-binding-stage .ant-alert-error .ant-alert-icon, +.customer-binding-stage .ant-alert-error .ant-alert-message, +.customer-binding-stage .ant-alert-error .ant-alert-title { + color: #fca5a5; +} + +.customer-binding-stage .ant-alert-error .ant-alert-description { + color: #fecaca; +} + +.customer-binding-stage .ant-alert-success { + border-color: #065f46; + background: rgba(6, 78, 59, 0.28); +} + +.customer-binding-stage .ant-alert-success .ant-alert-icon, +.customer-binding-stage .ant-alert-success .ant-alert-message, +.customer-binding-stage .ant-alert-success .ant-alert-title { + color: #6ee7b7; +} + +.customer-binding-stage .ant-alert-success .ant-alert-description { + color: #a7f3d0; +} + +.customer-binding-role-actions { + display: flex; + flex-direction: column; + gap: 12px; + width: 100%; +} + +.customer-binding-role-actions .customer-binding-confirm.ant-btn { + height: 52px; + border-radius: 14px; + background: #2563eb !important; + border-color: #2563eb !important; + color: #fff !important; + font-size: 17px; + font-weight: 600; +} + +.customer-binding-role-actions .customer-binding-confirm.ant-btn:hover, +.customer-binding-role-actions .customer-binding-confirm.ant-btn:focus-visible { + background: #1d4ed8 !important; + border-color: #1d4ed8 !important; + color: #fff !important; +} + +.customer-binding-role-actions .customer-binding-rebind.ant-btn { + height: 48px; + border-radius: 14px; + background: transparent !important; + border-color: #3a4150 !important; + color: #cbd5e1 !important; + font-size: 16px; + font-weight: 500; +} + +.customer-binding-role-actions .customer-binding-rebind.ant-btn .anticon { + color: #f59e0b; +} + +.customer-binding-role-actions .customer-binding-rebind.ant-btn:hover, +.customer-binding-role-actions .customer-binding-rebind.ant-btn:focus-visible { + background: rgba(245, 158, 11, 0.08) !important; + border-color: #b45309 !important; + color: #fbbf24 !important; +} + +.customer-binding-role-actions .customer-binding-accept.ant-btn { + height: 46px; + border-radius: 12px; + background: transparent !important; + border-color: transparent !important; + color: #94a3b8 !important; + font-size: 15px; + font-weight: 500; +} + +.customer-binding-role-actions .customer-binding-accept.ant-btn:hover, +.customer-binding-role-actions .customer-binding-accept.ant-btn:focus-visible { + background: rgba(148, 163, 184, 0.1) !important; + border-color: transparent !important; + color: #e2e8f0 !important; +} + +.customer-binding-info { + padding: 16px; + border: 1px solid #3a4150; + border-radius: 12px; + background: #212733; + display: flex; + flex-direction: column; + gap: 10px; +} + +.customer-binding-info h3 { + margin: 0 0 4px; + color: #9aa3b2; + font-size: 13px; + font-weight: 500; +} + +.customer-binding-info h3 small { + color: #64748b; + font-weight: 400; +} + +.customer-binding-info > div { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 12px; + color: #cbd5e1; + font-size: 14px; + line-height: 1.5; +} + +.customer-binding-info > div > span { + flex: 0 0 auto; + white-space: nowrap; +} + +.customer-binding-info > div strong { + flex: 1 1 auto; + min-width: 0; + color: #fff; + text-align: right; + overflow-wrap: anywhere; +} + +.customer-binding-alert { + padding: 12px 14px; + border-radius: 8px; + border: 1px solid transparent; + font-size: 14px; +} + +.customer-binding-alert.is-warning { + color: #fbbf24; + border-color: #78350f; + background: rgba(120, 53, 15, 0.25); +} + +.customer-binding-alert.is-info { + color: #93c5fd; + border-color: #1e3a8a; + background: rgba(30, 58, 138, 0.3); +} + +.customer-binding-verify { + padding: 18px; + border: 1px solid #3a4150; + border-radius: 12px; + background: transparent; + display: flex; + flex-direction: column; + gap: 16px; + text-align: center; +} + +.customer-binding-verify p { + margin: 0; + color: #e5e7eb; + font-size: 16px; + line-height: 1.6; +} + +.customer-binding-qr-card { + padding: 18px; + border-radius: 12px; + background: #fff; + color: #111827; + display: flex; + flex-direction: column; + align-items: center; + gap: 10px; +} + +.customer-binding-qr-card h3 { + margin: 0; + color: #6b7280; + font-size: 14px; + font-weight: 500; +} + +.customer-binding-qr-hint { + margin: 0; + color: #6b7280; + font-size: 13px; +} + +.customer-binding-qr-tip { + margin: 0; + color: #f59e0b; + font-size: 13px; +} + +.customer-binding-qr-countdown { + margin: 0; + color: #6b7280; + font-size: 13px; +} + +.customer-binding-qr-actions { + width: 100%; + margin-top: 4px; + display: grid; + grid-template-columns: 1fr 1fr; + gap: 10px; +} + +.customer-binding-qr-actions .ant-btn { + height: 40px; + border-radius: 8px; +} + +.customer-binding-next.ant-btn { + width: 100%; + height: 52px; + margin-top: 6px; + border-radius: 14px; + background: #2563eb !important; + border-color: #2563eb !important; + color: #fff !important; + font-size: 17px; + font-weight: 600; +} + +.customer-binding-modal-footer { + display: flex; + flex-direction: column; + gap: 10px; +} + +.customer-binding-modal-actions { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 12px; +} + +.customer-binding-modal-actions .ant-btn { + height: 42px; + border-radius: 8px; +} + +.customer-binding-modal-actions.is-mismatch { + grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); +} + +.customer-binding-modal-error { + margin: 0; + color: #dc2626; + font-size: 13px; + text-align: center; +} + +.customer-binding-modal-warning { + margin: 0; + color: #d97706; + font-size: 13px; + text-align: center; +} + +.customer-binding-compare { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 12px; +} + +.customer-binding-compare-side { + display: flex; + flex-direction: column; + gap: 6px; + padding: 14px; + border: 1px solid rgba(15, 23, 42, 0.12); + border-radius: 6px; + background: rgba(15, 23, 42, 0.04); +} + +.customer-binding-compare-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + color: #64748b; + font-size: 13px; +} + +.customer-binding-compare-side strong { + color: #0f172a; + font-size: 16px; + word-break: break-all; +} + +.customer-binding-compare-side em { + color: #64748b; + font-style: normal; + font-size: 13px; +} + +@media (max-width: 480px) { + .customer-binding-compare { + grid-template-columns: minmax(0, 1fr); + } +} + .customer-auth-button-stack { width: min(100%, 580px); display: flex; @@ -2090,7 +2971,7 @@ .customer-auth-button-stack .ant-btn, .customer-auth-form > .ant-btn { - height: 50px; + height: 52px; font-size: 17px; } @@ -2190,49 +3071,43 @@ @media (max-width: 640px) { .customer-auth-page { - height: 100dvh; - min-height: 0; - overflow: hidden; + height: auto; + min-height: 100vh; + overflow: visible; padding: 0; background: var(--auth-panel); } .customer-auth-shell { width: 100%; - height: 100%; - min-height: 0; - display: flex; - flex-direction: column; + height: auto; + display: block; border: 0; border-radius: 0; box-shadow: none; } .customer-auth-hero { - min-height: 116px; - flex: none; - padding: 20px 22px; - background-position: 58% center; + min-height: auto; + padding: 38px 16px 10px; + background: none; } .customer-auth-brand h1 { - font-size: 18px; + font-size: 20px; } .customer-auth-warning { - flex: none; - padding: 12px 14px; - font-size: 16px; + padding: 6px 16px 10px; + font-size: 14px; } .customer-auth-main { - flex: 1; - min-height: 0; - overflow: hidden; + overflow: visible; } .customer-auth-content-stack { - height: 100%; + height: auto; min-height: 0; } @@ -2257,7 +3132,7 @@ } .customer-auth-section { - padding: 14px 16px 10px; + padding: 16px; } .customer-auth-section-copy h2, diff --git a/apps/frontend/src/types/admin/semi-auto.ts b/apps/frontend/src/types/admin/semi-auto.ts index 1d9fbfdf..70cb6702 100644 --- a/apps/frontend/src/types/admin/semi-auto.ts +++ b/apps/frontend/src/types/admin/semi-auto.ts @@ -13,6 +13,7 @@ export type SemiAutoTask = { platform: SemiAutoPlatform platformLabel: string loginStatus: string + bindingStatus: string executionStatus: string connectorMode: 'embedded' | 'external' | 'mock' displayStatus: SemiAutoDisplayStatus @@ -23,6 +24,13 @@ export type SemiAutoTask = { credentialUpdatedAt: string | null huyaUid: string platformNickname: string + bindGameAccount: string + bindGameRole: string + bindGameRoleId: string + bindGameChannel: string + customerGameRoleId: string + customerGameRoleName: string + customerServerZone: string targetQuantity: number completedQuantity: number assignedAdminUserId: number | null @@ -73,6 +81,65 @@ export type SemiAutoTaskDetail = { 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 + 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 + requestBody: string + responseSummary: Record + 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 = { credentialId: number platform: SemiAutoPlatform diff --git a/apps/frontend/src/types/customer-fulfillment.ts b/apps/frontend/src/types/customer-fulfillment.ts index 842f423a..161d1a70 100644 --- a/apps/frontend/src/types/customer-fulfillment.ts +++ b/apps/frontend/src/types/customer-fulfillment.ts @@ -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 = { id: number platform: 'huya' | 'weibo' @@ -8,10 +19,18 @@ export type CustomerSemiAutoTask = { skuCode: string quantity: number loginStatus: string + bindingStatus: string executionStatus: string displayStatus: { key: string; label: string } huyaUid: string platformNickname: string + bindGameAccount: string + bindGameRole: string + bindGameRoleId: string + bindGameChannel: string + customerGameRoleId: string + customerGameRoleName: string + customerServerZone: string completedAt: string | null completionNote: string semiAutoConfig: { @@ -28,3 +47,31 @@ export type CustomerLoginInfo = { expiresAt: string message: string } + +export type CustomerBindingInfo = { + status: string + qrImage: string + qrExpiresAt: string + qrUrl: string + bindGameAccount: string + bindGameRole: string + bindGameRoleId: string + bindGameChannel: string + /** 平台角色 ID 是否可核对(纯数字);false 时客户页只提示联系客服。 */ + roleIdVerified?: boolean + /** 已绑定角色但缺少可核对角色 ID,需要客服人工核实。 */ + requiresSupport?: boolean + hasExistingBinding: boolean + rebindRequested: boolean + rebindUnchanged: boolean + rebindConfirmState: 'idle' | 'submitting' | 'accepted' | 'rejected' + rebindConfirmMessage: string + bindConfirmState?: 'idle' | 'submitting' | 'accepted' | 'rejected' + bindConfirmMessage?: string + rebindCooldownDays: number + nextRebindAt: string + platformChangeBindDay?: number + platformChangeBindTime?: number + message: string + comparison: CustomerBindingComparison +} diff --git a/apps/frontend/src/utils/semi-auto-trace-action.ts b/apps/frontend/src/utils/semi-auto-trace-action.ts new file mode 100644 index 00000000..5dca68eb --- /dev/null +++ b/apps/frontend/src/utils/semi-auto-trace-action.ts @@ -0,0 +1,157 @@ +/** + * 半自动履约报文动作说明。 + * + * trace 的 action 是原始格式:入站为「METHOD 路径」,虎牙出站为 WUP 方法名, + * 外部 Connector 为「METHOD 内部路径」。这里只做展示层映射,不写库、不改变报文内容。 + */ +export type SemiAutoTraceActionInput = { + channel: string + action: string +} + +/** 虎牙 WUP / livelink 出站动作。 */ +const HUYA_RPC_ACTIONS: Record = { + 'webActUI.checkUserBindGameAccount': '查询虎牙账号已绑定角色', + 'webActUI.confirmBindActAccount': '向虎牙提交绑定/换绑', + 'webActUI.getLiveLinkParam': '获取绑定二维码参数', + 'huyauserui.getUserProfile': '获取虎牙账号资料', + 'livelink.getMiniAppQrcode': '生成登录二维码', + 'livelink.poolingQrcodeStatus': '轮询扫码状态', +} + +/** 旧版 Mock Connector 写入的历史动作,保留中文说明避免露出英文。 */ +const LEGACY_ACTIONS: Record = { + 'mock.sms.send': '发送登录验证码(Mock Connector)', + 'mock.sms.login': '验证码登录(Mock Connector)', +} + +/** 客户接口尾路径 → 用途。 */ +const CUSTOMER_ACTIONS: Record = { + open: '客户打开履约页', + profile: '提交客户游戏资料', + 'login/start': '发起平台登录', + 'login/status': '查询登录状态', + 'huya/sms/send': '发送虎牙登录验证码', + 'huya/sms/login': '虎牙验证码登录', + 'huya/sms/verify': '完成虎牙安全验证', + 'binding/start': '开始绑定(查询已绑角色)', + 'binding/status': '查询绑定状态', + 'binding/rebind': '发起扫码换绑', + 'binding/confirm': '确认绑定角色(含换绑)', + 'weibo/config': '读取微博登录配置', + 'weibo/sms/send': '发送微博登录验证码', + 'weibo/sms/login': '微博验证码登录', + 'weibo/qrcode': '获取微博登录二维码', + 'weibo/qrcode/status': '查询微博扫码状态', +} + +/** 运营接口尾路径 → 用途。 */ +const ADMIN_ACTIONS: Record = { + claim: '客服领取任务', + sync: '手动同步平台状态', + reauthorize: '重新发起客户授权', + 'browser-session': '生成浏览器登录票据', + complete: '客服完成履约', + cancel: '取消履约任务', + 'credential/export': '导出账号 CK', + history: '读取履约历史', +} + +const CUSTOMER_PREFIX = '/api/v1/customer-fulfillment' +const ADMIN_PREFIX = '/api/v1/admin/semi-auto' +const CONNECTOR_PREFIX = '/api/internal/huya-semi-auto' + +export function describeSemiAutoTraceAction(input: SemiAutoTraceActionInput): string { + const action = String(input?.action || '').trim() + if (!action) return '' + const channel = String(input?.channel || '').trim() + + const named = HUYA_RPC_ACTIONS[action] || LEGACY_ACTIONS[action] + if (named) return named + + const { method, path } = splitHttpAction(action) + if (!path) return '' + + if (path.startsWith(CUSTOMER_PREFIX) || channel === 'customer_api') { + return describeCustomerAction(path) + } + if (path.startsWith(ADMIN_PREFIX) || channel === 'admin_api') { + return describeAdminAction(method, path) + } + if (path.startsWith(CONNECTOR_PREFIX) || channel === 'external_connector') { + return describeConnectorAction(method, path) + } + return '' +} + +function splitHttpAction(action: string): { method: string; path: string } { + const match = /^(GET|POST|PUT|PATCH|DELETE)\s+(\S+)/i.exec(action) + if (!match) return { method: '', path: '' } + return { + method: match[1].toUpperCase(), + path: match[2].split('?')[0].split('#')[0], + } +} + +function describeCustomerAction(path: string): string { + const match = /^\/api\/v1\/customer-fulfillment\/[^/]+(?:\/tasks\/[^/]+)?(?:\/(.*))?$/.exec(path) + if (!match) return '' + const tail = (match[1] || '').replace(/\/+$/, '') + if (!tail) return '读取履约任务' + return CUSTOMER_ACTIONS[tail] || '' +} + +function describeAdminAction(method: string, path: string): string { + if (path === ADMIN_PREFIX + '/tasks') return '读取履约任务列表' + const taskMatch = /^\/api\/v1\/admin\/semi-auto\/tasks\/[^/]+(?:\/(.*))?$/.exec(path) + if (taskMatch) { + const tail = (taskMatch[1] || '').replace(/\/+$/, '') + if (!tail) { + return method === 'POST' || method === 'PUT' || method === 'PATCH' + ? '更新履约任务' + : '读取履约任务详情' + } + return ADMIN_ACTIONS[tail] || '' + } + if (/^\/api\/v1\/admin\/semi-auto\/injections\/[^/]+$/.test(path)) { + return '校验浏览器注入票据' + } + return '' +} + +function describeConnectorAction(method: string, path: string): string { + if (!path.startsWith(CONNECTOR_PREFIX)) return '' + const rest = path.slice(CONNECTOR_PREFIX.length).split('/').filter(Boolean) + if (rest.length === 0) return '' + + if (rest[0] === 'sessions') { + if (rest.length === 1) return method === 'POST' ? '创建平台登录会话' : '' + if (rest.length === 2) { + if (method === 'DELETE') return '释放平台登录会话' + if (method === 'GET') return '查询登录会话' + return '' + } + if (rest.length === 3) { + if (rest[2] === 'binding') { + return method === 'POST' ? '开始绑定(含换绑)' : '查询绑定状态/快照' + } + if (rest[2] === 'browser-ticket') { + return method === 'DELETE' ? '释放浏览器票据' : '生成浏览器票据' + } + if (rest[2] === 'credential') return '读取平台账号 CK' + return '' + } + if (rest.length === 4 && rest[2] === 'binding' && rest[3] === 'confirm') { + return '确认绑定/换绑' + } + return '' + } + + if (rest[0] === 'browser-tickets' && rest.length === 2) return '校验浏览器票据' + if (rest[0] === 'sms') { + if (rest[1] === 'send') return '发送平台登录验证码' + if (rest[1] === 'verify') return '完成平台安全验证' + if (rest[1] === 'login') return '平台验证码登录' + } + return '' +} diff --git a/apps/frontend/tests/customer-fulfillment-binding-compare.test.ts b/apps/frontend/tests/customer-fulfillment-binding-compare.test.ts new file mode 100644 index 00000000..a26107fb --- /dev/null +++ b/apps/frontend/tests/customer-fulfillment-binding-compare.test.ts @@ -0,0 +1,64 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import test from 'node:test' + +const root = dirname(fileURLToPath(import.meta.url)) +const source = readFileSync( + join(root, '../src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx'), + 'utf8', +) +const styles = readFileSync(join(root, '../src/styles/client.css'), 'utf8') + +test('扫码识别角色后,资料不一致也打开对比弹窗', () => { + // 自动弹窗 effect 不再因 mismatch 提前 return。 + assert.ok(source.includes('识别到角色(含与资料不一致)都要弹出对比框')) + assert.ok(!source.includes("if (bindingInfo.comparison.verdict === 'mismatch') return")) + // 手动刷新时 mismatch 同样打开弹窗,不再关闭并只弹提示。 + assert.ok(source.includes('资料不一致同样打开对比框')) + assert.ok(!source.includes('平台角色与已填资料不一致,请先同步资料')) +}) + +test('对比弹窗在资料不一致时提供修改资料与同步平台角色入口', () => { + assert.ok(source.includes('修改资料')) + assert.ok(source.includes('同步平台角色')) + assert.ok(source.includes('canSyncBindingProfile')) + assert.ok(source.includes('onClick={openProfileEditor}')) + assert.ok( + source.includes( + "disabled={!bindingCustomerReady || bindingComparison?.verdict === 'mismatch'}", + ), + ) + assert.ok(styles.includes('.customer-binding-modal-actions.is-mismatch')) + assert.ok(styles.includes('repeat(auto-fit, minmax(140px, 1fr))')) +}) + +test('保存资料或同步平台角色后会重新打开对比弹窗', () => { + assert.ok(source.includes('function reopenBindingConfirm(')) + assert.ok(source.includes("if (nextTask.bindingStatus !== 'role_ready') return false")) + assert.ok(source.includes('reopened = reopenBindingConfirm(')) + assert.ok( + source.includes( + 'reopenBindingConfirm(bindingResponse.data.task, bindingResponse.data.binding)', + ), + ) + assert.ok(source.includes('角色资料已保存,请重新核对绑定角色')) +}) + +test('资料不一致时仍保持后端严格比对:确认按钮禁用并显示原因', () => { + assert.ok(source.includes('两侧角色信息不一致,无法确认绑定')) + assert.ok(source.includes('customer-binding-modal-error')) +}) + +test('二维码区提示扫码后会核对平台角色与已填资料', () => { + assert.ok(source.includes('扫码后系统会核对平台角色与已填资料')) +}) + +test('换绑流程刷新二维码必须带 forceRebind,避免直接返回已有角色', () => { + assert.ok(source.includes('function handleRefreshBindingQr()')) + assert.ok(source.includes('handleRefreshBinding(bindingInfo?.rebindRequested === true)')) + // 三处刷新/重新获取入口都不能再固定传 false。 + assert.ok(!source.includes('handleRefreshBinding(false)')) + assert.ok(source.includes('onClick={handleRefreshBindingQr}')) +}) diff --git a/apps/frontend/tests/customer-fulfillment-rebind-return.test.ts b/apps/frontend/tests/customer-fulfillment-rebind-return.test.ts new file mode 100644 index 00000000..59feacda --- /dev/null +++ b/apps/frontend/tests/customer-fulfillment-rebind-return.test.ts @@ -0,0 +1,31 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import test from 'node:test' + +const source = readFileSync( + join( + dirname(fileURLToPath(import.meta.url)), + '../src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx', + ), + 'utf8', +) + +test('换绑失败页用「返回上一步」替换「仍使用原角色」', () => { + assert.ok(source.includes('rebindFailureDismissed')) + assert.ok(source.includes('返回上一步')) + assert.ok(!source.includes('仍使用原角色')) +}) + +test('返回后展示资料不一致核对界面', () => { + assert.ok(source.includes('showRebindFailure')) + assert.ok(source.includes('!showRebindFailure &&')) + assert.ok(source.includes('同步平台角色并继续')) + assert.ok(source.includes('id="customer-binding-stage"')) +}) + +test('资料同步后提供确认使用原角色', () => { + assert.ok(source.includes('确认使用原角色')) + assert.ok(source.includes('handleAcceptExistingRole')) +}) diff --git a/apps/frontend/tests/customer-fulfillment-weibo-ui.test.ts b/apps/frontend/tests/customer-fulfillment-weibo-ui.test.ts new file mode 100644 index 00000000..b399112e --- /dev/null +++ b/apps/frontend/tests/customer-fulfillment-weibo-ui.test.ts @@ -0,0 +1,58 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import test from 'node:test' + +const source = readFileSync( + join( + dirname(fileURLToPath(import.meta.url)), + '../src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx', + ), + 'utf8', +) +const styles = readFileSync( + join(dirname(fileURLToPath(import.meta.url)), '../src/styles/client.css'), + 'utf8', +) + +test('微博与虎牙共用同一套登录表单结构', () => { + assert.match(source, /const renderLoginForm = \(options: \{/) + assert.ok(source.includes("platformLabel: '虎牙'")) + assert.ok(source.includes("platformLabel: '微博'")) + assert.ok(!source.includes('customer-auth-tabs')) + assert.ok(!source.includes('SafetyCertificateOutlined')) +}) + +test('微博保留两种登录方式与全部原有提示', () => { + assert.ok(source.includes('改用二维码登录')) + assert.ok(source.includes('改用手机号登录')) + assert.ok(source.includes('smsMfaRequired')) + assert.ok(source.includes('如安全验证弹窗未出现')) + assert.ok(source.includes('CustomerPrivacyNote')) + assert.ok(source.includes('温馨提示:未成年人禁止下单')) +}) + +test('二维码切换与虎牙一致:直接切到扫码并发起登录', () => { + assert.ok(source.includes("setLoginMode('qr')")) + assert.ok(source.includes('void handleStartLogin()')) +}) + +test('微博订单卡只展示订单号/商品/平台/状态,不含游戏和角色名称', () => { + const weiboBranch = source.slice( + source.indexOf("if (task.platform === 'weibo')"), + source.indexOf('const zone = task.customerServerZone'), + ) + assert.ok(weiboBranch.includes('订单号')) + assert.ok(weiboBranch.includes('商品')) + assert.ok(weiboBranch.includes('平台')) + assert.ok(weiboBranch.includes('状态')) + assert.ok(!weiboBranch.includes('角色名称')) + assert.ok(!weiboBranch.includes('游戏名称')) +}) + +test('微博顶部使用 inside-kv 背景,虎牙保持纯色', () => { + assert.ok(styles.includes('.customer-auth-page.is-weibo .customer-auth-hero')) + assert.ok(styles.includes("url('/images/customer/inside-kv.jpg')")) + assert.ok(!styles.includes('.customer-auth-page.is-huya .customer-auth-hero')) +}) diff --git a/apps/frontend/tests/semi-auto-trace-action.test.ts b/apps/frontend/tests/semi-auto-trace-action.test.ts new file mode 100644 index 00000000..b9f8b3c9 --- /dev/null +++ b/apps/frontend/tests/semi-auto-trace-action.test.ts @@ -0,0 +1,121 @@ +import assert from 'node:assert/strict' +import test from 'node:test' + +import { describeSemiAutoTraceAction } from '../src/utils/semi-auto-trace-action.ts' + +const label = (channel: string, action: string) => describeSemiAutoTraceAction({ channel, action }) + +test('客户接口:绑定与登录动作都有中文说明', () => { + assert.equal( + label('customer_api', 'POST /api/v1/customer-fulfillment/MOCKSA1/tasks/51/binding/confirm'), + '确认绑定角色(含换绑)', + ) + assert.equal( + label('customer_api', 'GET /api/v1/customer-fulfillment/MOCKSA1/tasks/51/binding/status?x=1'), + '查询绑定状态', + ) + assert.equal( + label('customer_api', 'POST /api/v1/customer-fulfillment/MOCKSA1/tasks/51/binding/start'), + '开始绑定(查询已绑角色)', + ) + assert.equal( + label('customer_api', 'POST /api/v1/customer-fulfillment/MOCKSA1/tasks/51/profile'), + '提交客户游戏资料', + ) + assert.equal( + label('customer_api', 'POST /api/v1/customer-fulfillment/MOCKSA1/tasks/51/open'), + '客户打开履约页', + ) + assert.equal( + label('customer_api', 'GET /api/v1/customer-fulfillment/MOCKSA1/tasks/51/login/status'), + '查询登录状态', + ) + assert.equal(label('customer_api', 'GET /api/v1/customer-fulfillment/MOCKSA1'), '读取履约任务') +}) + +test('客户接口:短信与微博动作', () => { + assert.equal( + label('customer_api', 'POST /api/v1/customer-fulfillment/MOCKSA1/tasks/51/huya/sms/send'), + '发送虎牙登录验证码', + ) + assert.equal( + label('customer_api', 'POST /api/v1/customer-fulfillment/MOCKSA1/tasks/51/huya/sms/verify'), + '完成虎牙安全验证', + ) + assert.equal( + label('customer_api', 'GET /api/v1/customer-fulfillment/MOCKSA1/tasks/51/weibo/qrcode/status'), + '查询微博扫码状态', + ) +}) + +test('运营接口:领取、同步、完成与详情', () => { + assert.equal(label('admin_api', 'POST /api/v1/admin/semi-auto/tasks/39/claim'), '客服领取任务') + assert.equal(label('admin_api', 'POST /api/v1/admin/semi-auto/tasks/39/sync'), '手动同步平台状态') + assert.equal(label('admin_api', 'GET /api/v1/admin/semi-auto/tasks/39'), '读取履约任务详情') + assert.equal(label('admin_api', 'POST /api/v1/admin/semi-auto/tasks/39'), '更新履约任务') + assert.equal( + label('admin_api', 'GET /api/v1/admin/semi-auto/injections/ticket-1'), + '校验浏览器注入票据', + ) +}) + +test('虎牙 WUP 与 livelink 动作', () => { + assert.equal(label('huya_wup', 'webActUI.checkUserBindGameAccount'), '查询虎牙账号已绑定角色') + assert.equal(label('huya_wup', 'webActUI.confirmBindActAccount'), '向虎牙提交绑定/换绑') + assert.equal(label('huya_wup', 'huyauserui.getUserProfile'), '获取虎牙账号资料') + assert.equal(label('huya_http', 'livelink.getMiniAppQrcode'), '生成登录二维码') + assert.equal(label('huya_http', 'livelink.poolingQrcodeStatus'), '轮询扫码状态') +}) + +test('外部 Connector:会话、绑定与票据', () => { + const sessionId = '32aabcb6-27af-420b-b223-a47db63861bf' + assert.equal( + label('external_connector', 'POST /api/internal/huya-semi-auto/sessions'), + '创建平台登录会话', + ) + assert.equal( + label('external_connector', `POST /api/internal/huya-semi-auto/sessions/${sessionId}/binding`), + '开始绑定(含换绑)', + ) + assert.equal( + label('external_connector', `GET /api/internal/huya-semi-auto/sessions/${sessionId}/binding`), + '查询绑定状态/快照', + ) + assert.equal( + label( + 'external_connector', + `POST /api/internal/huya-semi-auto/sessions/${sessionId}/binding/confirm`, + ), + '确认绑定/换绑', + ) + assert.equal( + label('external_connector', 'GET /api/internal/huya-semi-auto/browser-tickets/ticket-1'), + '校验浏览器票据', + ) + assert.equal( + label('external_connector', 'POST /api/internal/huya-semi-auto/sms/login'), + '平台验证码登录', + ) +}) + +test('未知动作与空值不展示噪音', () => { + assert.equal(label('customer_api', 'POST /api/v1/customer-fulfillment/X/tasks/1/unknown'), '') + assert.equal(label('huya_wup', 'some.unknown.method'), '') + assert.equal(label('external_connector', 'GET /api/internal/huya-semi-auto/unknown'), '') + assert.equal(label('', ''), '') + assert.equal(label('customer_api', 'POST /api/v1/other/endpoint'), '') +}) + +test('渠道缺失时按路径兜底识别', () => { + assert.equal( + label('', 'POST /api/v1/customer-fulfillment/MOCKSA1/tasks/51/binding/rebind'), + '发起扫码换绑', + ) + assert.equal(label('', 'POST /api/v1/admin/semi-auto/tasks/39/cancel'), '取消履约任务') + assert.equal(label('', 'DELETE /api/internal/huya-semi-auto/sessions/abc'), '释放平台登录会话') +}) + +test('历史 Mock 动作保留中文说明', () => { + assert.equal(label('external_connector', 'mock.sms.send'), '发送登录验证码(Mock Connector)') + assert.equal(label('external_connector', 'mock.sms.login'), '验证码登录(Mock Connector)') +})