diff --git a/.env.mac-docker.example b/.env.mac-docker.example index 89acdd44..d495152b 100644 --- a/.env.mac-docker.example +++ b/.env.mac-docker.example @@ -78,6 +78,11 @@ KAQUAN91_SECRET= # 半自动履约默认使用 order_site 内置真实 Connector;只有选择 external 时才填写远程地址 SEMI_AUTO_DEFAULT_CONNECTOR_MODE=embedded +HUYA_BIND_GID=3203 +HUYA_BIND_SCENE=undefined +HUYA_OUTER_ACT_ID=17096 +HUYA_BIND_ACT_ID=9271 +HUYA_ROOM_PID=1199650619883 SEMI_AUTO_CONNECTOR_BASE_URL= SEMI_AUTO_CONNECTOR_API_KEY= SEMI_AUTO_CONNECTOR_TIMEOUT_MS=15000 diff --git a/.env.server.example b/.env.server.example index 00fb6185..6107429d 100644 --- a/.env.server.example +++ b/.env.server.example @@ -150,6 +150,12 @@ SEMI_AUTO_CONNECTOR_API_KEY= SEMI_AUTO_DEFAULT_CONNECTOR_MODE=embedded SEMI_AUTO_CONNECTOR_TIMEOUT_MS=15000 SEMI_AUTO_RECONCILE_SECONDS=900 +# 虎牙绑定使用 activity 新协议:gid=3203、outerActId=17096、bActId=0。 +HUYA_BIND_GID=3203 +HUYA_BIND_SCENE=undefined +HUYA_OUTER_ACT_ID=17096 +HUYA_BIND_ACT_ID=9271 +HUYA_ROOM_PID=1199650619883 # 快手行业电子凭证 KUASHOU_INDUSTRY_APP_KEY= diff --git a/README.md b/README.md index 7f95559d..b609ea10 100644 --- a/README.md +++ b/README.md @@ -197,6 +197,9 @@ cp .env.server.example .env | `SEMI_AUTO_DEFAULT_CONNECTOR_MODE` | 新任务默认 Connector:`embedded` / `external` / `mock`,默认 `embedded` | | `SEMI_AUTO_CONNECTOR_TIMEOUT_MS` | Connector 请求超时,默认 15000 毫秒 | | `SEMI_AUTO_RECONCILE_SECONDS` | 半自动任务低频兜底对账间隔,默认 900 秒 | +| `HUYA_BIND_GID` | 虎牙活动绑定 gid,默认 `3203`;置 `0` 才回退旧 `bActId` 协议 | +| `HUYA_BIND_SCENE` | 虎牙活动绑定 scene,默认 `undefined` | +| `HUYA_OUTER_ACT_ID` / `HUYA_BIND_ACT_ID` | 虎牙外层活动 ID 与旧协议绑定活动 ID | ### 本地半自动履约测试 @@ -205,6 +208,20 @@ cp .env.server.example .env 只有显式选择远程 Connector 时,才需要设置 `SEMI_AUTO_CONNECTOR_BASE_URL` 和 `SEMI_AUTO_CONNECTOR_API_KEY`。 +虎牙身份审计(只读): + +```bash +cd apps/backend +npm run audit:huya-binding-identity +npm run audit:huya-binding-identity -- --strict +``` + +审计会区分虎牙登录账号 UID、平台加密 role token 和客户游戏角色 UID。 +`historicalLegacyAccountUidFallback` 是迁移保留的历史留档;当前字段中 +`accountUidReusedAsActiveRoleToken`、`invalidActiveRoleTokens` 或 +`invalidPlatformRoleUids`、`platformRoleUidReusedFromAccountUid` 不为 0 时, +`--strict` 必须失败并停止放行。 + 真实登录 / 绑定验证流程: 1. 打开后台 `/admin/dev-mock`,Mock 范围选择“仅 Mock 订单(内置真实登录 / 绑定 / 注入)”。 diff --git a/apps/backend/package.json b/apps/backend/package.json index 240ef4a9..7172be6c 100644 --- a/apps/backend/package.json +++ b/apps/backend/package.json @@ -33,6 +33,7 @@ "test:industry:gen": "tsx scripts/gen-test-cases.ts", "test:industry:curl": "tsx scripts/curl-send-callback.ts", "audit:fulfillment": "tsx scripts/audit-fulfillment-state.ts", + "audit:huya-binding-identity": "tsx scripts/audit-huya-binding-identity.ts", "audit:product-routing": "tsx scripts/audit-product-routing-alignment.ts", "audit:work-order-hall-pricing": "tsx scripts/audit-work-order-hall-pricing.ts", "typecheck": "tsc -p tsconfig.json --noEmit", diff --git a/apps/backend/scripts/audit-huya-binding-identity.ts b/apps/backend/scripts/audit-huya-binding-identity.ts new file mode 100644 index 00000000..38ab7c05 --- /dev/null +++ b/apps/backend/scripts/audit-huya-binding-identity.ts @@ -0,0 +1,197 @@ +#!/usr/bin/env tsx +/** + * 虎牙账号 UID / 平台加密 roleId / 客户游戏角色 UID 只读审计。 + * + * 用法: + * npm run audit:huya-binding-identity + * npm run audit:huya-binding-identity -- --strict + */ +import { closeDb, getDb } from '../src/db/client.js' + +const strict = process.argv.includes('--strict') + +type AuditRow = { + task_id: number + order_no: string + account_uid: string + binding_status: string + current_role_name: string + current_role_token: string + platform_role_uid: string + pending_role_name: string + pending_role_token: string + customer_role_uid: string + legacy_bind_game_role_id: string + role_identity_source: string + verification_basis: string + latest_outer_role_name: string + latest_outer_role_token: string + latest_inner_role_name: string + latest_inner_role_token: string +} + +async function main() { + const client = await getDb().connect() + try { + await client.query('BEGIN TRANSACTION READ ONLY') + const result = await client.query(` + SELECT + task.id AS task_id, + order_record.platform_order_id AS order_no, + task.huya_uid AS account_uid, + task.binding_status, + task.bind_game_role AS current_role_name, + task.bind_game_role_token AS current_role_token, + task.platform_game_role_uid, + task.pending_bind_game_role AS pending_role_name, + task.pending_bind_game_role_token AS pending_role_token, + task.customer_game_role_id AS customer_role_uid, + task.legacy_bind_game_role_id, + task.role_identity_source, + task.verification_basis, + COALESCE(outer_trace.role_name, '') AS latest_outer_role_name, + COALESCE(outer_trace.role_token, '') AS latest_outer_role_token, + COALESCE(inner_trace.role_name, '') AS latest_inner_role_name, + COALESCE(inner_trace.role_token, '') AS latest_inner_role_token + FROM semi_auto_tasks task + JOIN orders order_record ON order_record.id = task.order_id + LEFT JOIN LATERAL ( + SELECT + trace.response_body::jsonb #>> '{accountData,gameRole,roleName}' AS role_name, + trace.response_body::jsonb #>> '{accountData,gameRole,roleId}' AS role_token + FROM semi_auto_trace_logs trace + WHERE trace.task_id = task.id + AND trace.action = 'webActUI.checkUserBindGameAccount' + AND trace.status = 'ok' + AND COALESCE(trace.request_summary->>'outerActId', '') <> '' + ORDER BY trace.id DESC + LIMIT 1 + ) outer_trace ON TRUE + LEFT JOIN LATERAL ( + SELECT + trace.response_body::jsonb #>> '{accountData,gameRole,roleName}' AS role_name, + trace.response_body::jsonb #>> '{accountData,gameRole,roleId}' AS role_token + FROM semi_auto_trace_logs trace + WHERE trace.task_id = task.id + AND trace.action = 'webActUI.checkUserBindGameAccount' + AND trace.status = 'ok' + AND COALESCE(trace.request_summary->>'outerActId', '') = '' + ORDER BY trace.id DESC + LIMIT 1 + ) inner_trace ON TRUE + WHERE task.platform = 'huya' + ORDER BY task.updated_at DESC, task.id DESC + `) + await client.query('COMMIT') + + const rows = result.rows + const historicalLegacyFallback = rows.filter( + (row) => row.legacy_bind_game_role_id && row.legacy_bind_game_role_id === row.account_uid, + ) + const activeAccountUidReuse = rows.filter( + (row) => + Boolean(row.account_uid) && + (row.current_role_token === row.account_uid || row.pending_role_token === row.account_uid), + ) + const historicalTraceAccountUidReuse = rows.filter( + (row) => + Boolean(row.account_uid) && + (row.latest_outer_role_token === row.account_uid || + row.latest_inner_role_token === row.account_uid), + ) + const invalidActiveRoleTokens = rows.filter( + (row) => + (row.current_role_token && !/^[0-9a-f]{40}$/i.test(row.current_role_token)) || + (row.pending_role_token && !/^[0-9a-f]{40}$/i.test(row.pending_role_token)), + ) + const invalidHistoricalTraceRoleTokens = rows.filter( + (row) => + (row.latest_outer_role_token && !/^[0-9a-f]{40}$/i.test(row.latest_outer_role_token)) || + (row.latest_inner_role_token && !/^[0-9a-f]{40}$/i.test(row.latest_inner_role_token)), + ) + const invalidPlatformRoleUids = rows.filter( + (row) => row.platform_role_uid && !/^\d+$/.test(row.platform_role_uid), + ) + const platformRoleUidReusedFromAccountUid = rows.filter( + (row) => + Boolean(row.account_uid) && + Boolean(row.platform_role_uid) && + row.platform_role_uid === row.account_uid, + ) + + console.log( + JSON.stringify( + { + generatedAt: new Date().toISOString(), + summary: { + huyaTasks: rows.length, + historicalLegacyAccountUidFallback: historicalLegacyFallback.length, + accountUidReusedAsActiveRoleToken: activeAccountUidReuse.length, + accountUidReusedInHistoricalTrace: historicalTraceAccountUidReuse.length, + invalidActiveRoleTokens: invalidActiveRoleTokens.length, + invalidHistoricalTraceRoleTokens: invalidHistoricalTraceRoleTokens.length, + invalidPlatformRoleUids: invalidPlatformRoleUids.length, + platformRoleUidReusedFromAccountUid: platformRoleUidReusedFromAccountUid.length, + }, + historicalLegacyFallbackTasks: historicalLegacyFallback.map((row) => ({ + taskId: row.task_id, + orderNo: row.order_no, + accountUid: row.account_uid, + bindingStatus: row.binding_status, + legacyBindGameRoleId: row.legacy_bind_game_role_id, + roleIdentitySource: row.role_identity_source, + })), + activeAccountUidReuseTasks: activeAccountUidReuse.map((row) => ({ + taskId: row.task_id, + orderNo: row.order_no, + accountUid: row.account_uid, + currentRoleToken: row.current_role_token, + pendingRoleToken: row.pending_role_token, + })), + invalidActiveRoleTokenTasks: invalidActiveRoleTokens.map((row) => ({ + taskId: row.task_id, + orderNo: row.order_no, + currentRoleToken: row.current_role_token, + pendingRoleToken: row.pending_role_token, + })), + invalidPlatformRoleUidTasks: invalidPlatformRoleUids.map((row) => ({ + taskId: row.task_id, + orderNo: row.order_no, + platformRoleUid: row.platform_role_uid, + })), + platformRoleUidReusedFromAccountUidTasks: platformRoleUidReusedFromAccountUid.map( + (row) => ({ + taskId: row.task_id, + orderNo: row.order_no, + accountUid: row.account_uid, + platformRoleUid: row.platform_role_uid, + }), + ), + }, + null, + 2, + ), + ) + + if ( + strict && + (activeAccountUidReuse.length > 0 || + invalidActiveRoleTokens.length > 0 || + invalidPlatformRoleUids.length > 0 || + platformRoleUidReusedFromAccountUid.length > 0) + ) { + process.exitCode = 1 + } + } catch (error) { + await client.query('ROLLBACK').catch(() => undefined) + throw error + } finally { + client.release() + await closeDb() + } +} + +main().catch((error) => { + console.error('[audit:huya-binding-identity]', error) + process.exitCode = 1 +}) diff --git a/apps/backend/src/config/defaults.ts b/apps/backend/src/config/defaults.ts index 16a1ef11..e0d2c118 100644 --- a/apps/backend/src/config/defaults.ts +++ b/apps/backend/src/config/defaults.ts @@ -69,6 +69,8 @@ export function createDefaultRuntimeConfig(projectRoot: string): RuntimeConfig { reconcileSeconds: 900, huya: { bindActId: 9271, + bindGid: 3203, + bindScene: 'undefined', outerActId: '17096', roomPid: '1199650619883', }, diff --git a/apps/backend/src/config/env-overrides.ts b/apps/backend/src/config/env-overrides.ts index 59eb9c7d..45865341 100644 --- a/apps/backend/src/config/env-overrides.ts +++ b/apps/backend/src/config/env-overrides.ts @@ -57,6 +57,8 @@ export const ENV_OVERRIDES: readonly EnvOverride[] = [ integerEnv('SEMI_AUTO_RECONCILE_SECONDS', ['semiAuto', 'reconcileSeconds']), stringEnv('SEMI_AUTO_DEFAULT_CONNECTOR_MODE', ['semiAuto', 'defaultConnectorMode']), integerEnv('HUYA_BIND_ACT_ID', ['semiAuto', 'huya', 'bindActId']), + integerEnv('HUYA_BIND_GID', ['semiAuto', 'huya', 'bindGid']), + stringEnv('HUYA_BIND_SCENE', ['semiAuto', 'huya', 'bindScene']), stringEnv('HUYA_OUTER_ACT_ID', ['semiAuto', 'huya', 'outerActId']), stringEnv('HUYA_ROOM_PID', ['semiAuto', 'huya', 'roomPid']), stringEnv('ADMIN_SESSION_SECRET', ['admin', 'sessionSecret']), diff --git a/apps/backend/src/config/runtime-validation.test.ts b/apps/backend/src/config/runtime-validation.test.ts index 73aa66c7..179800f5 100644 --- a/apps/backend/src/config/runtime-validation.test.ts +++ b/apps/backend/src/config/runtime-validation.test.ts @@ -208,8 +208,11 @@ function createRuntimeConfig(overrides: Record = {}): RuntimeCo connectorBaseUrl: '', connectorApiKey: '', connectorTimeoutMs: 15000, + reconcileSeconds: 900, huya: { bindActId: 9271, + bindGid: 3203, + bindScene: 'undefined', outerActId: '17096', roomPid: '1199650619883', }, diff --git a/apps/backend/src/db/migrations/176_semi_auto_huya_binding_identity.sql b/apps/backend/src/db/migrations/176_semi_auto_huya_binding_identity.sql new file mode 100644 index 00000000..408404e9 --- /dev/null +++ b/apps/backend/src/db/migrations/176_semi_auto_huya_binding_identity.sql @@ -0,0 +1,132 @@ +-- 176_semi_auto_huya_binding_identity.sql +-- +-- 虎牙身份彻底拆分: +-- 1. huya_uid 只表示登录账号 UID; +-- 2. bind_game_role_token 保存 gameRole.roleId 原始加密标识; +-- 3. customer_game_role_id 保存客户填写的游戏角色 UID; +-- 4. pending_bind_game_* 保存扫码后、平台确认前的待绑定角色; +-- 5. 禁止再把虎牙账号 UID 回退为平台角色 ID。 + +ALTER TABLE semi_auto_tasks + ADD COLUMN IF NOT EXISTS legacy_bind_game_role_id TEXT NOT NULL DEFAULT '', + ADD COLUMN IF NOT EXISTS bind_game_role_token TEXT NOT NULL DEFAULT '', + ADD COLUMN IF NOT EXISTS platform_game_role_uid TEXT NOT NULL DEFAULT '', + ADD COLUMN IF NOT EXISTS pending_bind_game_account TEXT NOT NULL DEFAULT '', + ADD COLUMN IF NOT EXISTS pending_bind_game_role TEXT NOT NULL DEFAULT '', + ADD COLUMN IF NOT EXISTS pending_bind_game_role_token TEXT NOT NULL DEFAULT '', + ADD COLUMN IF NOT EXISTS pending_bind_game_channel TEXT NOT NULL DEFAULT '', + ADD COLUMN IF NOT EXISTS pending_bind_game_change_bind_time BIGINT NOT NULL DEFAULT 0, + ADD COLUMN IF NOT EXISTS pending_bind_game_change_bind_day INTEGER NOT NULL DEFAULT 0, + ADD COLUMN IF NOT EXISTS role_identity_source TEXT NOT NULL DEFAULT '', + ADD COLUMN IF NOT EXISTS verification_basis TEXT NOT NULL DEFAULT ''; + +DO $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM pg_constraint + WHERE conname = 'chk_semi_auto_tasks_role_identity_source' + ) THEN + ALTER TABLE semi_auto_tasks + ADD CONSTRAINT chk_semi_auto_tasks_role_identity_source + CHECK ( + role_identity_source IN ( + '', + 'huya_outer_current', + 'huya_inner_pending', + 'legacy_account_uid_fallback', + 'manual' + ) + ); + END IF; + IF NOT EXISTS ( + SELECT 1 + FROM pg_constraint + WHERE conname = 'chk_semi_auto_tasks_verification_basis' + ) THEN + ALTER TABLE semi_auto_tasks + ADD CONSTRAINT chk_semi_auto_tasks_verification_basis + CHECK ( + verification_basis IN ( + '', + 'role_name_zone', + 'platform_numeric_uid', + 'manual' + ) + ); + END IF; + IF NOT EXISTS ( + SELECT 1 + FROM pg_constraint + WHERE conname = 'chk_semi_auto_tasks_role_token' + ) THEN + ALTER TABLE semi_auto_tasks + ADD CONSTRAINT chk_semi_auto_tasks_role_token + CHECK ( + bind_game_role_token = '' + OR bind_game_role_token ~ '^[0-9a-fA-F]{40}$' + ); + END IF; + IF NOT EXISTS ( + SELECT 1 + FROM pg_constraint + WHERE conname = 'chk_semi_auto_tasks_pending_role_token' + ) THEN + ALTER TABLE semi_auto_tasks + ADD CONSTRAINT chk_semi_auto_tasks_pending_role_token + CHECK ( + pending_bind_game_role_token = '' + OR pending_bind_game_role_token ~ '^[0-9a-fA-F]{40}$' + ); + END IF; + IF NOT EXISTS ( + SELECT 1 + FROM pg_constraint + WHERE conname = 'chk_semi_auto_tasks_platform_role_uid' + ) THEN + ALTER TABLE semi_auto_tasks + ADD CONSTRAINT chk_semi_auto_tasks_platform_role_uid + CHECK ( + platform_game_role_uid = '' + OR platform_game_role_uid ~ '^[0-9]+$' + ); + END IF; +END $$; + +UPDATE semi_auto_tasks +SET legacy_bind_game_role_id = bind_game_role_id +WHERE legacy_bind_game_role_id = '' + AND bind_game_role_id <> ''; + +UPDATE semi_auto_tasks +SET bind_game_role_token = bind_game_role_id +WHERE bind_game_role_token = '' + AND bind_game_role_id ~ '^[0-9a-fA-F]{40}$'; + +UPDATE semi_auto_tasks +SET role_identity_source = 'legacy_account_uid_fallback', + verification_basis = 'manual', + platform_game_role_uid = '', + bind_game_role_id = '' +WHERE platform = 'huya' + AND huya_uid <> '' + AND bind_game_role_id = huya_uid; + +COMMENT ON COLUMN semi_auto_tasks.huya_uid IS + '虎牙登录账号 UID;只用于平台请求身份,与游戏角色 UID 无对应关系'; +COMMENT ON COLUMN semi_auto_tasks.legacy_bind_game_role_id IS + '迁移前 bind_game_role_id 的审计留档;不得参与绑定判断'; +COMMENT ON COLUMN semi_auto_tasks.bind_game_role_id IS + '历史兼容列,新代码不得写入;平台角色标识改存 bind_game_role_token'; +COMMENT ON COLUMN semi_auto_tasks.bind_game_role_token IS + '虎牙 gameRole.roleId 原始加密标识;只用于平台前后结果比对'; +COMMENT ON COLUMN semi_auto_tasks.platform_game_role_uid IS + '平台明确返回的数值游戏角色 UID;当前虎牙接口通常为空'; +COMMENT ON COLUMN semi_auto_tasks.pending_bind_game_role IS + '扫码后、确认绑定前的待确认角色名'; +COMMENT ON COLUMN semi_auto_tasks.pending_bind_game_role_token IS + '扫码后、确认绑定前的虎牙加密角色标识'; +COMMENT ON COLUMN semi_auto_tasks.role_identity_source IS + '角色事实来源:当前绑定、待确认、历史账号UID污染或人工'; +COMMENT ON COLUMN semi_auto_tasks.verification_basis IS + '绑定核验依据:角色名区服、平台数值角色UID或人工'; diff --git a/apps/backend/src/middleware/semi-auto-trace.ts b/apps/backend/src/middleware/semi-auto-trace.ts index 13cb4c62..d527116a 100644 --- a/apps/backend/src/middleware/semi-auto-trace.ts +++ b/apps/backend/src/middleware/semi-auto-trace.ts @@ -57,6 +57,11 @@ const TRACE_STATE_KEYS = [ 'bindEffectDeadlineMs', 'bindGameRole', 'bindGameRoleId', + 'bindGameRoleToken', + 'pendingBindGameRole', + 'pendingBindGameRoleToken', + 'roleIdentitySource', + 'verificationBasis', 'huyaUid', 'lastError', 'isBindAccount', diff --git a/apps/backend/src/services/account-binding/account-binding.test.ts b/apps/backend/src/services/account-binding/account-binding.test.ts index abd89171..5f09fd31 100644 --- a/apps/backend/src/services/account-binding/account-binding.test.ts +++ b/apps/backend/src/services/account-binding/account-binding.test.ts @@ -10,6 +10,7 @@ test('平台能力声明统一描述角色查询、确认与换绑方式', () => assert.equal(huya.queryOwner, 'order_site') assert.equal(huya.confirmationMode, 'customer_match') assert.equal(huya.rebindMode, 'platform_confirm') + assert.deepEqual(huya.requiredFields, ['roleName', 'serverZone']) const douyu = getAccountBindingPolicy('douyu') assert.equal(douyu.bindingKind, 'game_role') diff --git a/apps/backend/src/services/account-binding/platform-policy.ts b/apps/backend/src/services/account-binding/platform-policy.ts index 608740b0..10ce0c5c 100644 --- a/apps/backend/src/services/account-binding/platform-policy.ts +++ b/apps/backend/src/services/account-binding/platform-policy.ts @@ -28,7 +28,8 @@ const POLICIES: Record = { requiresCustomerProfile: true, supportsRebind: true, queryOwner: 'order_site', - requiredFields: ['roleName', 'roleId', 'serverZone'], + // 虎牙 gameRole.roleId 是加密平台标识,不等于客户填写的游戏角色 UID。 + requiredFields: ['roleName', 'serverZone'], confirmationMode: 'customer_match', rebindMode: 'platform_confirm', defaultTargetUrl: 'https://www.huya.com/', diff --git a/apps/backend/src/services/semi-auto/binding-role-id.ts b/apps/backend/src/services/semi-auto/binding-role-id.ts index 86a48121..d7b937c6 100644 --- a/apps/backend/src/services/semi-auto/binding-role-id.ts +++ b/apps/backend/src/services/semi-auto/binding-role-id.ts @@ -1,46 +1,9 @@ -/** - * 虎牙 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 才能和客户填写的游戏编号做可信比对。 */ +/** 只有平台独立返回的纯数字游戏角色 UID 才能作为自动核验依据。 */ 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, - } +/** 虎牙 gameRole.roleId 当前是 40 位十六进制 opaque token。 */ +export function isHuyaRoleToken(value: unknown): boolean { + return /^[0-9a-f]{40}$/i.test(String(value ?? '').trim()) } 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 9ce63da9..043560a3 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 @@ -18,9 +18,11 @@ test('浏览器注入票据按 Mock 前缀选择 Connector', () => { test('创建登录会话按真实 Connector 协议发送蛇形字段', async () => { const originalFetch = globalThis.fetch let requestUrl = '' + let requestMethod = '' let requestBody: Record = {} globalThis.fetch = (async (url: string | URL | Request, init?: RequestInit) => { requestUrl = String(url) + requestMethod = String(init?.method || 'GET').toUpperCase() requestBody = JSON.parse(String(init?.body || '{}')) as Record return new Response( JSON.stringify({ @@ -203,12 +205,14 @@ test('重新扫码换绑会向 Connector 传递 force_rebind', async () => { } }) -test('提交换绑复用 Connector confirm 端点并携带 rebind 标记', async () => { +test('提交换绑前只读取 Connector 待确认角色,不调用平台确认端点', async () => { const originalFetch = globalThis.fetch let requestUrl = '' + let requestMethod = '' let requestBody: Record = {} globalThis.fetch = (async (url: string | URL | Request, init?: RequestInit) => { requestUrl = String(url) + requestMethod = String(init?.method || 'GET').toUpperCase() requestBody = JSON.parse(String(init?.body || '{}')) as Record return new Response( JSON.stringify({ @@ -219,7 +223,8 @@ test('提交换绑复用 Connector confirm 端点并携带 rebind 标记', async qrUrl: '', bindGameAccount: '微信用户', bindGameRole: '大鲨鱼伊塞53', - bindGameRoleId: '1199608910400', + bindGameRoleId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', + bindGameRoleToken: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', bindGameChannel: '安卓(android) · 微信', rebindRequested: true, rebindUnchanged: false, @@ -234,12 +239,58 @@ test('提交换绑复用 Connector confirm 端点并携带 rebind 标记', async const session = await connector.submitHuyaRebind('session-1', 'external') assert.equal( requestUrl, - 'http://connector.test/api/internal/huya-semi-auto/sessions/session-1/binding/confirm', + 'http://connector.test/api/internal/huya-semi-auto/sessions/session-1/binding', ) - assert.deepEqual(requestBody, { rebind: true }) + assert.equal(requestMethod, 'GET') + assert.deepEqual(requestBody, {}) assert.equal(session.rebindConfirmState, 'accepted') assert.equal(session.rebindRequested, true) } finally { globalThis.fetch = originalFetch } }) + +test('确认绑定向 Connector 携带本次核对的角色快照', 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: 'confirmed', + qrImage: '', + qrExpiresAt: '', + qrUrl: '', + bindGameAccount: '虎牙账号', + bindGameRole: '本次待确认角色', + bindGameRoleId: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', + bindGameRoleToken: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', + bindGameChannel: '安卓(android) · QQ', + message: '角色绑定已确认', + }), + { status: 200, headers: { 'Content-Type': 'application/json' } }, + ) + }) as typeof fetch + try { + const session = await connector.confirmHuyaBinding('session-1', 'external', { + expectedRoleName: '本次待确认角色', + expectedRoleToken: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', + expectedRoleChannel: '安卓(android) · QQ', + }) + assert.equal( + requestUrl, + 'http://connector.test/api/internal/huya-semi-auto/sessions/session-1/binding/confirm', + ) + assert.deepEqual(requestBody, { + expectedRoleName: '本次待确认角色', + expectedRoleToken: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', + expectedRoleChannel: '安卓(android) · QQ', + }) + assert.equal(session.status, 'confirmed') + } 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 805a6a74..f07d87b1 100644 --- a/apps/backend/src/services/semi-auto/huya-connector-client.ts +++ b/apps/backend/src/services/semi-auto/huya-connector-client.ts @@ -14,6 +14,7 @@ import { import { HUYA_NATIVE_TICKET_PREFIX, huyaNativeConnector, + type HuyaRestoreCredentialInput, type HuyaStoredCredential, } from './huya-native/huya-native-connector.js' import { recordSemiAutoTrace, traceFingerprint } from './semi-auto-trace.js' @@ -99,11 +100,23 @@ export type ConnectorBindingSession = { qrUrl: string bindGameAccount: string bindGameRole: string + /** 虎牙平台返回的加密角色标识,仅用于平台前后结果比对,不是客户游戏角色 UID。 */ bindGameRoleId: string + bindGameRoleToken?: string + platformGameRoleUid?: string bindGameChannel: string - /** 平台返回的角色 ID 是否可核对(纯数字);false 时需引导客户联系客服人工核实。 */ + pendingBindGameAccount?: string + pendingBindGameRole?: string + pendingBindGameRoleToken?: string + pendingBindGameChannel?: string + pendingChangeBindTime?: number + pendingChangeBindDay?: number + roleIdentitySource?: 'huya_outer_current' | 'huya_inner_pending' | '' + /** 当前绑定核验依据;虎牙当前只能稳定核验角色名与区服。 */ + verificationBasis?: 'role_name_zone' | 'platform_numeric_uid' | 'manual' | '' + /** 平台是否独立返回数值游戏角色 UID;加密 role token 不算。 */ roleIdVerified?: boolean - /** 已绑定角色但缺少可核对角色 ID:客户页应提示联系客服,禁止直接确认绑定。 */ + /** 平台未返回可核对角色名等事实时,需要客服人工核实。 */ requiresSupport?: boolean hasExistingBinding?: boolean rebindRequested?: boolean @@ -476,14 +489,26 @@ export async function getHuyaBindingSnapshot( export async function confirmHuyaBinding( sessionId: string, mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(), - options: { acceptExistingRole?: boolean } = {}, + options: { + acceptExistingRole?: boolean + expectedRoleName?: string + expectedRoleToken?: string + expectedRoleChannel?: string + } = {}, ): Promise { if (mode === 'embedded') return huyaNativeConnector.confirmBinding(sessionId, options) return callConnector( `/api/internal/huya-semi-auto/sessions/${encodeURIComponent(sessionId)}/binding/confirm`, { method: 'POST', - body: options.acceptExistingRole ? { acceptExistingRole: true } : {}, + body: { + ...(options.acceptExistingRole ? { acceptExistingRole: true } : {}), + ...(options.expectedRoleName ? { expectedRoleName: options.expectedRoleName } : {}), + ...(options.expectedRoleToken ? { expectedRoleToken: options.expectedRoleToken } : {}), + ...(options.expectedRoleChannel + ? { expectedRoleChannel: options.expectedRoleChannel } + : {}), + }, }, mode, ) @@ -506,18 +531,15 @@ export async function resetHuyaBinding( ) } -/** - * 扫码后由项目侧主动向虎牙提交换绑确认。 - * 外部 Connector 暂未提供独立端点时复用 confirm 端点(语义一致,幂等)。 - */ +/** 扫码后只刷新并识别待换绑角色;平台写操作必须走 confirmHuyaBinding。 */ 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 } }, + `/api/internal/huya-semi-auto/sessions/${encodeURIComponent(sessionId)}/binding`, + {}, mode, ) } @@ -550,6 +572,19 @@ export async function exportHuyaSessionCredential( ) } +export async function restoreHuyaSessionFromCredential( + input: HuyaRestoreCredentialInput, + mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(), +): Promise { + if (mode !== 'embedded') { + throw createHttpError('当前 Connector 模式不支持从账号级 CK 恢复虎牙会话', { + statusCode: 409, + errorCode: 'huya_connector_restore_unsupported', + }) + } + return huyaNativeConnector.restoreSessionFromCredential(input) +} + export function inferSemiAutoConnectorModeFromTicket(ticket: string): SemiAutoConnectorMode { const normalized = ticket.trim() if (normalized.startsWith('mock-ticket-')) return 'mock' 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 deleted file mode 100644 index e3c3c3ff..00000000 --- a/apps/backend/src/services/semi-auto/huya-native/binding-confirm-decision.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -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-binding-snapshot.test.ts b/apps/backend/src/services/semi-auto/huya-native/huya-binding-snapshot.test.ts new file mode 100644 index 00000000..0751a1bc --- /dev/null +++ b/apps/backend/src/services/semi-auto/huya-native/huya-binding-snapshot.test.ts @@ -0,0 +1,195 @@ +import assert from 'node:assert/strict' +import test from 'node:test' + +import { queryHuyaBindingSnapshot, type HuyaBindingProtocol } from './huya-native-connector.js' +import type { HuyaBindResponse } from './huya-rpc.js' + +const PROTOCOL: HuyaBindingProtocol = { + bindActId: 0, + bindGid: 3203, + bindScene: 'undefined', + outerActId: '17096', + isUseOuterActId: 0, + roomPid: '1199650619883', +} + +function bindResponse(input: { + roleName?: string + roleId?: string + accountNick?: string + isBindAccount?: number + isBindRole?: number + platform?: string + area?: string +}): HuyaBindResponse { + return { + status: 200, + msg: '', + gameName: '和平精英', + gameAuthScene: '', + changeBindDay: 7, + accountData: { + isBindAccount: input.isBindAccount ?? 1, + isBindRole: input.isBindRole ?? 1, + isNeedActCheck: 1, + gameAccount: { + openId: '', + appId: '', + type: 'qq', + faceUrl: '', + nick: input.accountNick || '账号', + accessToken: '', + extendInfo: '', + }, + gameRole: { + roleId: input.roleId || '5649acb0b723427a2439a870fea8a2e8fd383611', + roleName: input.roleName || '', + areaName: input.area || 'QQ', + platName: input.platform || '安卓(android)', + partitionName: '', + gameSerial: '', + extendInfo: '', + }, + changeBindTime: 1795536000, + }, + } +} + +test('双路查询把外层当前角色与内层待确认角色分开', async () => { + const calls: Array<{ outerActId: string; gid?: number; isUseOuterActId?: number }> = [] + const responses = [ + bindResponse({ + roleName: '当前角色', + roleId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', + accountNick: '当前账号', + }), + bindResponse({ + roleName: '待确认角色', + roleId: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', + accountNick: '目标账号', + }), + ] + const rpc = { + async checkUserBindGameAccount(input: { + outerActId: string + gid?: number + isUseOuterActId?: number + }) { + calls.push(input) + return responses.shift() || null + }, + } + const snapshot = await queryHuyaBindingSnapshot(rpc as never, { + uid: 1199664118656, + cookie: 'yyuid=1199664118656', + protocol: PROTOCOL, + }) + + assert.equal(calls.length, 2) + assert.equal(calls[0]?.outerActId, '17096') + assert.equal(calls[0]?.gid, 3203) + assert.equal(calls[0]?.isUseOuterActId, 0) + assert.equal(calls[1]?.outerActId, '') + assert.equal(snapshot.current?.role, '当前角色') + assert.equal(snapshot.pending?.role, '待确认角色') +}) + +test('两路角色完全相同时不生成伪待确认角色', async () => { + const response = bindResponse({ + roleName: '同一角色', + roleId: 'cccccccccccccccccccccccccccccccccccccccc', + }) + const rpc = { + async checkUserBindGameAccount() { + return response + }, + } + const snapshot = await queryHuyaBindingSnapshot(rpc as never, { + uid: 1, + cookie: 'yyuid=1', + protocol: PROTOCOL, + }) + assert.equal(snapshot.current?.role, '同一角色') + assert.equal(snapshot.pending, null) +}) + +test('同一 role token 仅大小写不同不算待确认角色变化', async () => { + const responses = [ + bindResponse({ + roleName: '同一角色', + roleId: 'ABCDEFABCDEFABCDEFABCDEFABCDEFABCDEFABCD', + }), + bindResponse({ + roleName: '同一角色', + roleId: 'abcdefabcdefabcdefabcdefabcdefabcdefabcd', + }), + ] + const rpc = { + async checkUserBindGameAccount() { + return responses.shift() || null + }, + } + const snapshot = await queryHuyaBindingSnapshot(rpc as never, { + uid: 1, + cookie: 'yyuid=1', + protocol: PROTOCOL, + }) + assert.equal(snapshot.current?.role, '同一角色') + assert.equal(snapshot.pending, null) +}) + +test('首次绑定没有当前角色时允许内层返回待确认角色', async () => { + const responses = [ + bindResponse({ + roleName: '', + roleId: '', + accountNick: '', + isBindAccount: 0, + isBindRole: 0, + }), + bindResponse({ + roleName: '首次绑定角色', + roleId: 'dddddddddddddddddddddddddddddddddddddddd', + }), + ] + const rpc = { + async checkUserBindGameAccount() { + return responses.shift() || null + }, + } + const snapshot = await queryHuyaBindingSnapshot(rpc as never, { + uid: 1, + cookie: 'yyuid=1', + protocol: PROTOCOL, + }) + assert.equal(snapshot.current, null) + assert.equal(snapshot.pending?.role, '首次绑定角色') +}) + +test('未绑定时即使外层残留同名角色,也仍以内层角色作为待确认', async () => { + const roleId = 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' + const responses = [ + bindResponse({ + roleName: '残留角色', + roleId, + isBindAccount: 0, + isBindRole: 0, + }), + bindResponse({ + roleName: '残留角色', + roleId, + }), + ] + const rpc = { + async checkUserBindGameAccount() { + return responses.shift() || null + }, + } + const snapshot = await queryHuyaBindingSnapshot(rpc as never, { + uid: 1, + cookie: 'yyuid=1', + protocol: PROTOCOL, + }) + assert.equal(snapshot.current, null) + assert.equal(snapshot.pending?.role, '残留角色') +}) 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 69587964..7a594415 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 @@ -1,8 +1,8 @@ /** * order_site 内置虎牙半自动履约 Connector。 * - * 扫码/短信登录、角色绑定、CK 兑换和一次性浏览器注入票据全部在本进程完成。 - * 原始 CK 只保存在内存会话中,不写日志、不出现在票据字符串里。 + * 扫码/短信登录、角色绑定、CK 兑换和一次性浏览器注入票据在本进程完成; + * 进程会话丢失后可从账号级 CK 恢复,原始 CK 不写日志、不出现在票据字符串里。 */ import crypto from 'node:crypto' @@ -12,7 +12,6 @@ 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, @@ -39,7 +38,6 @@ import { buildBindUrls, getLiveLinkMiniQrcode, getLiveLinkQrcodeStatus, - hasExistingHuyaBinding, HuyaQrRole, HuyaRpcClient, webBehavior, @@ -74,9 +72,20 @@ type NativeBindState = { expiresAtMs: number account: string role: string + /** 虎牙返回的加密角色标识,绝不能回退成虎牙账号 UID。 */ roleId: string channel: string + isBindAccount: boolean + isBindRole: boolean + changeBindTime: number + changeBindDay: number hasExistingBinding: boolean + pendingAccount: string + pendingRole: string + pendingRoleId: string + pendingChannel: string + pendingChangeBindTime: number + pendingChangeBindDay: number rebindRequested: boolean rebindScanned: boolean rebindUnchanged: boolean @@ -84,15 +93,13 @@ type NativeBindState = { rebindConfirmMessage: string rebindConfirmAt: number rebindEffectDeadlineMs: number - /** 首次绑定(账号还没有绑定角色)时,扫码后由项目侧提交 confirmBindActAccount 的状态。 */ + /** 客户明确确认 pending 角色后,提交 confirmBindActAccount 的状态。 */ bindConfirmState: 'idle' | 'submitting' | 'accepted' | 'rejected' bindConfirmMessage: string bindConfirmAt: number bindEffectDeadlineMs: number rebindCooldownDays: number nextRebindAt: string - changeBindTime: number - changeBindDay: number baselineRoleKey: string message: string } @@ -154,6 +161,11 @@ export type HuyaStoredCredential = { }> } +export type HuyaRestoreCredentialInput = HuyaStoredCredential & { + taskId: number + orderNo: string +} + function defaultBindingState(): NativeBindState { return { status: 'not_started', @@ -165,7 +177,17 @@ function defaultBindingState(): NativeBindState { role: '', roleId: '', channel: '', + isBindAccount: false, + isBindRole: false, + changeBindTime: 0, + changeBindDay: 0, hasExistingBinding: false, + pendingAccount: '', + pendingRole: '', + pendingRoleId: '', + pendingChannel: '', + pendingChangeBindTime: 0, + pendingChangeBindDay: 0, rebindRequested: false, rebindScanned: false, rebindUnchanged: false, @@ -179,8 +201,6 @@ function defaultBindingState(): NativeBindState { bindEffectDeadlineMs: 0, rebindCooldownDays: 0, nextRebindAt: '', - changeBindTime: 0, - changeBindDay: 0, baselineRoleKey: '', message: '', } @@ -262,54 +282,6 @@ export function resolveRebindCooldown( 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, @@ -407,41 +379,141 @@ function parseRole(response: HuyaBindResponse | null): { role: string roleId: string channel: string + isBindAccount: boolean + isBindRole: boolean + changeBindTime: number + changeBindDay: number } { if (!response || response.status !== 200) { - return { account: '', role: '', roleId: '', channel: '' } + return { + account: '', + role: '', + roleId: '', + channel: '', + isBindAccount: false, + isBindRole: false, + changeBindTime: 0, + changeBindDay: 0, + } } 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(' · ') - // 虎牙 checkUserBindGameAccount 的 gameRole.roleId 就是平台侧角色 ID; - // 该字段一直存在于 RPC 响应里,之前被丢弃,导致客户页无法做两侧角色比对。 const roleId = String(data.gameRole.roleId || '').trim() - return { account, role, roleId, channel } + return { + account, + role, + roleId, + channel, + isBindAccount: Boolean(data.isBindAccount), + isBindRole: Boolean(data.isBindRole), + changeBindTime: Number(data.changeBindTime || 0), + changeBindDay: Number(response.changeBindDay || 0), + } } -function bindingRoleKey(role: { - account: string - role: string - roleId?: string - channel: string -}): string { - return [role.account, role.role, role.roleId || '', role.channel].join('\u0000') +function bindingRoleKey(role: { role: string; roleId?: string; channel: string }): string { + return [role.role, String(role.roleId || '').toLowerCase(), role.channel].join('\u0000') +} + +function isConfirmedCurrentRole( + role: ReturnType | null, +): role is ReturnType { + return Boolean(role?.role && role.isBindAccount && role.isBindRole) } function configValues() { const huya = runtimeConfig.semiAuto?.huya const bindActId = extractInt(huya?.bindActId || 9271) + const configuredBindGid = Number(huya?.bindGid) + const bindGid = + Number.isFinite(configuredBindGid) && configuredBindGid >= 0 + ? Math.trunc(configuredBindGid) + : 3203 + const bindScene = readString(huya?.bindScene || 'undefined') const outerActId = readString(huya?.outerActId || '17096') const roomPid = readString(huya?.roomPid || '1199650619883') - if (!bindActId) { + const usesGidProtocol = bindGid > 0 && Boolean(outerActId) + if (!usesGidProtocol && !bindActId) { throw createHttpError('虎牙绑定活动 ID 未配置', { statusCode: 503, errorCode: 'huya_bind_act_not_configured', }) } - return { bindActId, outerActId, roomPid } + return { + bindActId: usesGidProtocol ? 0 : bindActId, + bindGid, + bindScene, + outerActId, + isUseOuterActId: usesGidProtocol ? 0 : 1, + roomPid, + } +} + +export type HuyaBindingProtocol = ReturnType + +export type HuyaBindingSnapshot = { + outer: HuyaBindResponse | null + inner: HuyaBindResponse | null + current: ReturnType | null + pending: ReturnType | null +} + +function bindingIdentityChanged( + current: ReturnType, + pending: ReturnType, +) { + if (!current.role || !pending.role) return false + if (current.role !== pending.role) return true + return Boolean( + current.roleId && + pending.roleId && + String(current.roleId).toLowerCase() !== String(pending.roleId).toLowerCase(), + ) +} + +export async function queryHuyaBindingSnapshot( + rpc: Pick, + input: { + uid: number + cookie: string + protocol: HuyaBindingProtocol + }, +): Promise { + const { uid, cookie, protocol } = input + const outer = await rpc.checkUserBindGameAccount({ + uid, + cookie, + bindActId: protocol.bindActId, + gid: protocol.bindGid, + outerActId: protocol.outerActId, + isUseOuterActId: protocol.isUseOuterActId, + scene: protocol.bindScene, + }) + if (!outer || outer.status !== 200) { + return { outer, inner: null, current: null, pending: null } + } + const outerRole = parseRole(outer) + const shouldQueryInner = + protocol.bindGid > 0 || !outerRole.role || !outerRole.isBindAccount || !outerRole.isBindRole + const inner = shouldQueryInner + ? await rpc.checkUserBindGameAccount({ + uid, + cookie, + bindActId: protocol.bindActId, + gid: protocol.bindGid, + outerActId: '', + isUseOuterActId: 0, + scene: protocol.bindScene, + }) + : null + const innerRole = inner?.status === 200 ? parseRole(inner) : null + const current = + outerRole.role && outerRole.isBindAccount && outerRole.isBindRole ? outerRole : null + const pending = + innerRole?.role && (!current || bindingIdentityChanged(current, innerRole)) ? innerRole : null + return { outer, inner, current, pending } } export class HuyaNativeConnector { @@ -541,6 +613,93 @@ export class HuyaNativeConnector { } } + async restoreSessionFromCredential( + input: HuyaRestoreCredentialInput, + ): Promise { + this.prune() + const uid = extractInt(input.platformUid) + const rawCookie = normalizeCookiePairs( + input.cookies.map((item) => [String(item.name || '').trim(), String(item.value || '')]), + ) + if (!uid || !rawCookie) { + throw createHttpError('虎牙账号级 CK 不完整,请重新登录', { + statusCode: 409, + errorCode: 'huya_credential_invalid', + }) + } + const identity = ensureHuyaWebCookieIdentity({ cookie: rawCookie, uid }) + const cookieUid = extractInt( + cookieValue(identity.cookie, 'yyuid') || cookieValue(identity.cookie, 'udb_uid'), + ) + if (!cookieUid) { + throw createHttpError('虎牙账号级 CK 缺少账号身份,请重新登录', { + statusCode: 409, + errorCode: 'huya_credential_invalid', + }) + } + if (cookieUid !== uid) { + throw createHttpError('虎牙 CK 与任务账号不一致,请重新登录', { + statusCode: 409, + errorCode: 'huya_credential_account_mismatch', + }) + } + if ( + !cookieValue(identity.cookie, 'udb_cred') && + !cookieValue(identity.cookie, 'udb_biztoken') + ) { + throw createHttpError('虎牙账号级 CK 缺少登录票据,请重新登录', { + statusCode: 409, + errorCode: 'huya_credential_invalid', + }) + } + + const sessionId = crypto.randomBytes(24).toString('base64url') + const sdid = + cookieValue(identity.cookie, 'sdid') || + cookieValue(identity.cookie, 'game_did') || + identity.guid + const role = new HuyaQrRole({ + sdid, + cookie: identity.cookie, + context: identity.context, + fetchImpl: this.fetchImpl, + }) + const createdAtMs = this.now() + const behavior = webBehavior() + const session: NativeSession = { + sessionId, + orderNo: String(input.orderNo || ''), + taskId: Number(input.taskId) || 0, + stateDir: path.join(this.stateRoot, sessionId), + createdAtMs, + expiresAtMs: createdAtMs + CREDENTIAL_TTL_MS, + role, + behavior: behavior.behavior, + page: behavior.page, + qrid: '', + qrImage: '', + sdid, + hdid: cookieValue(identity.cookie, 'hdid'), + deviceInfo: { + ...Object.fromEntries(cookiePairs(identity.cookie)), + sdid, + }, + status: 'authenticated', + smsSessionData: '', + smsPhone: '', + smsChallenge: null, + uid, + nickname: readString(input.nickname), + cookie: identity.cookie, + message: '已从账号级 CK 恢复虎牙登录会话', + binding: defaultBindingState(), + tickets: new Map(), + } + this.sessions.set(sessionId, session) + this.prune() + return this.loginView(session) + } + async getLoginSession(sessionId: string): Promise { return this.withLock(sessionId, async () => { const session = this.requireSession(sessionId) @@ -845,28 +1004,33 @@ export class HuyaNativeConnector { session.binding.message = '二维码仍在有效期内,请直接扫码;如需新码请稍后再试' return this.bindingView(session) } - const { bindActId, outerActId, roomPid } = configValues() + const protocol = configValues() const rpc = new HuyaRpcClient({ fetchImpl: this.fetchImpl, timeoutMs: this.rpcTimeoutMs }) - const roleResponse = await rpc.checkUserBindGameAccount({ + const snapshot = await queryHuyaBindingSnapshot(rpc, { uid: session.uid, cookie: session.cookie, - bindActId, - outerActId, + protocol, }) - const role = parseRole(roleResponse) - const hasExistingBinding = hasExistingHuyaBinding(roleResponse) + const roleResponse = snapshot.outer + const currentRole = snapshot.current + const hasExistingBinding = Boolean(currentRole?.isBindAccount && currentRole?.isBindRole) session.binding.hasExistingBinding = hasExistingBinding applyRebindMeta(session, roleResponse, this.now()) + if (currentRole) { + this.applyCurrentRole(session, currentRole, hasExistingBinding) + } // 只有平台明确「已绑定」才允许直接确认;没有绑定(即使残留角色名)必须走扫码绑定。 if (hasExistingBinding && !options.forceRebind) { - this.markRoleReady(session, role, true) - if (!role.role) { + this.clearPendingRole(session) + if (!currentRole?.role) { session.binding.message = '当前账号已有绑定角色,但平台未返回角色信息,请联系客服人工核实' + } else { + session.binding.message = '已识别当前绑定角色,请核对后确认' } if (session.binding.rebindRequested) { session.binding.message = session.binding.rebindUnchanged ? rebindFailureMessage( - role.role, + currentRole?.role || '', session.binding.rebindConfirmMessage, session.binding.nextRebindAt, ) @@ -883,8 +1047,9 @@ export class HuyaNativeConnector { const liveLink = await rpc.getLiveLinkParam({ uid: session.uid, cookie: session.cookie, - bindActId, - outerActId: extractInt(outerActId), + bindActId: protocol.bindActId, + gid: protocol.bindGid, + outerActId: extractInt(protocol.outerActId), gameAuthScene: roleResponse.gameAuthScene, }) if (!liveLink || liveLink.status !== 200) { @@ -912,10 +1077,10 @@ export class HuyaNativeConnector { const avatar = profile?.avatar || '' const redirectUrl = 'https://zt.huya.com/b02faae1/pc/index.html' + - `?sourceId=yellowcarlist&pid=${roomPid}&anchorUid=${roomPid}&roomid=30596253` + `?sourceId=yellowcarlist&pid=${protocol.roomPid}&anchorUid=${protocol.roomPid}&roomid=30596253` const urls = buildBindUrls({ livelinkParam: liveLink.livelinkParam, - bindActId, + bindActId: protocol.bindActId, gameAuthScene: roleResponse.gameAuthScene, nickName: nickname, faceUrl: avatar, @@ -939,8 +1104,9 @@ export class HuyaNativeConnector { session.binding.rebindConfirmMessage = '' session.binding.rebindConfirmAt = 0 session.binding.rebindEffectDeadlineMs = 0 - session.binding.baselineRoleKey = bindingRoleKey(role) + session.binding.baselineRoleKey = currentRole ? bindingRoleKey(currentRole) : '' } + this.clearPendingRole(session) session.binding.status = 'qr_pending' session.binding.qrImage = mini.image session.binding.qrUrl = urls.qrUrl @@ -961,77 +1127,13 @@ export class HuyaNativeConnector { }) } - /** - * 扫码完成后由项目侧替客户点「确认绑定」。 - * 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) - const { bindActId, outerActId } = configValues() + if (session.binding.status === 'confirmed' && !session.binding.rebindRequested) { + return this.bindingView(session) + } + const protocol = configValues() let qrCompleted = false if (['qr_pending', 'scanned'].includes(session.binding.status) && session.binding.qrToken) { const qrStatus = await getLiveLinkQrcodeStatus(session.binding.qrToken, { @@ -1039,10 +1141,8 @@ export class HuyaNativeConnector { timeoutMs: this.rpcTimeoutMs, }) if (qrStatus) { - // 平台已受理(绑定/换绑)时二维码会先过期,此时要等角色生效,不能直接判过期。 - const waitingPlatformEffect = - session.binding.rebindConfirmState === 'accepted' || - session.binding.bindConfirmState === 'accepted' + // 平台已受理时二维码会先过期,此时要等角色生效,不能直接判过期。 + const waitingPlatformEffect = session.binding.bindConfirmState === 'accepted' if ((qrStatus.isExpired || qrStatus.isFailure) && !waitingPlatformEffect) { session.binding.status = 'expired' session.binding.message = '绑定二维码已过期,请重新获取' @@ -1064,103 +1164,75 @@ 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({ + const snapshot = await queryHuyaBindingSnapshot(rpc, { uid: session.uid, cookie: session.cookie, - bindActId, - outerActId, + protocol, }) + const response = snapshot.outer if (!response || response.status !== 200) { session.binding.status = 'failed' session.binding.message = response?.msg || '查询绑定角色失败' return this.bindingView(session) } - const role = parseRole(response) - const hasExistingBinding = hasExistingHuyaBinding(response) + const currentRole = snapshot.current + const pendingRole = snapshot.pending + const hasExistingBinding = Boolean(currentRole?.isBindAccount && currentRole?.isBindRole) session.binding.hasExistingBinding = hasExistingBinding 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 (session.binding.rebindConfirmState === 'rejected') { - // 虎牙明确拒绝:保留 rebind 状态并展示虎牙原文,不能清空 rebindRequested。 - 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) - } - 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 - ? '扫码已完成,请点击「已选好角色,提交换绑」' - : '已扫码,请在虎牙确认框中选中目标角色' + if (currentRole) { + this.applyCurrentRole(session, currentRole, hasExistingBinding) + } + + if (session.binding.bindConfirmState === 'accepted' && session.binding.pendingRole) { + if ( + isConfirmedCurrentRole(currentRole) && + bindingRoleKey(currentRole) === + bindingRoleKey({ + role: session.binding.pendingRole, + roleId: session.binding.pendingRoleId, + channel: session.binding.pendingChannel, + }) + ) { + this.finalizeConfirmedBinding(session, currentRole) 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 = '虎牙已受理绑定,但未返回角色,请重新扫码绑定' + session.binding.message = '虎牙已受理绑定,正在等待角色生效' + return this.bindingView(session) } + session.binding.status = 'failed' + session.binding.message = '虎牙已受理绑定,但回查角色未变化,请重新扫码' + return this.bindingView(session) + } + + if (pendingRole) { + this.applyPendingRole(session, pendingRole) + session.binding.status = 'role_ready' + session.binding.message = session.binding.hasExistingBinding + ? '已识别本次换绑角色,请核对后确认' + : '已识别本次待绑定角色,请核对后确认' + return this.bindingView(session) + } + + this.clearPendingRole(session) + if (session.binding.rebindRequested && hasExistingBinding) { + session.binding.status = 'scanned' + session.binding.message = qrCompleted + ? '扫码已完成,但尚未识别到新的待确认角色,请重新选择角色' + : '已扫码,请在虎牙确认框中选中目标角色' + return this.bindingView(session) + } + if (currentRole?.role && hasExistingBinding) { + session.binding.status = 'role_ready' + session.binding.message = '已识别当前绑定角色,请核对后确认' + } else if (hasExistingBinding) { + session.binding.message = '当前账号已有绑定角色,但平台未返回角色信息,请联系客服人工核实' + session.binding.status = 'role_ready' + } else if (qrCompleted || session.binding.rebindScanned) { + session.binding.status = 'scanned' + session.binding.message = '扫码已完成,正在等待虎牙返回待确认角色' } else if (!['scanned', 'expired', 'failed'].includes(session.binding.status)) { session.binding.status = 'qr_pending' session.binding.message = '该虎牙账号还没有绑定游戏角色,请扫码完成绑定' @@ -1191,120 +1263,125 @@ export class HuyaNativeConnector { } /** - * 客户点「确认绑定」:只做本地状态流转,不调用虎牙接口。 - * 虎牙侧的绑定已由扫码(小程序/弹窗)完成,确认绑定只是核对三项后落库; - * 需要调用虎牙接口的地方只有「换绑确认」(submitRebind / pollBinding 自动提交)。 + * 客户点「确认绑定」:已绑定时只核验当前角色;有 pending 角色时, + * 只有客户明确确认且待确认身份未变化才调用虎牙写接口。 */ async confirmBinding( sessionId: string, - options: { acceptExistingRole?: boolean } = {}, + options: { + acceptExistingRole?: boolean + expectedRoleName?: string + expectedRoleToken?: string + expectedRoleChannel?: string + } = {}, ): Promise { return this.withLock(sessionId, async () => { const session = this.requireAuthenticatedSession(sessionId) const binding = session.binding - const decision = resolveBindingConfirmDecision(binding, options) - if (decision === 'not_ready') { + const pending = binding.pendingRole + ? { + account: binding.pendingAccount, + role: binding.pendingRole, + roleId: binding.pendingRoleId, + channel: binding.pendingChannel, + } + : null + if (!pending && !(binding.role && binding.hasExistingBinding)) { 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 = { + + const target = pending || { 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' + const expected = options.expectedRoleName + ? { + role: String(options.expectedRoleName || '').trim(), + roleId: String(options.expectedRoleToken || '').trim(), + channel: String(options.expectedRoleChannel || '').trim(), + } + : null + if (expected && bindingRoleKey(target) !== bindingRoleKey(expected)) { + throw createHttpError('待确认角色已变化,请重新核对后再提交', { + statusCode: 409, + errorCode: 'huya_bind_pending_role_changed', + }) + } + + if (!pending) { + this.finalizeConfirmedBinding(session, { + ...target, + isBindAccount: true, + isBindRole: true, + changeBindTime: binding.changeBindTime, + changeBindDay: binding.changeBindDay, + }) + binding.message = options.acceptExistingRole + ? '已确认继续使用当前绑定角色' + : '当前虎牙账号已有绑定角色,已确认直接使用' + return this.bindingView(session) + } + + const protocol = configValues() + const rpc = new HuyaRpcClient({ fetchImpl: this.fetchImpl, timeoutMs: this.rpcTimeoutMs }) + binding.bindConfirmState = 'submitting' binding.bindConfirmMessage = '' - binding.bindConfirmAt = 0 - binding.bindEffectDeadlineMs = 0 - binding.rebindCooldownDays = 0 - binding.nextRebindAt = '' - binding.baselineRoleKey = '' - binding.message = - rebindRequested && acceptExistingRole - ? '本次换绑未生效,已按原绑定角色确认' - : useExistingBinding - ? '当前虎牙账号已有绑定角色,已确认直接使用' - : rebindRequested - ? '虎牙角色换绑已确认' - : '虎牙角色绑定已确认' + binding.bindConfirmAt = this.now() + const confirmed = await rpc.confirmBindActAccount({ + uid: session.uid, + cookie: session.cookie, + bindActId: protocol.bindActId, + gid: protocol.bindGid, + outerActId: protocol.outerActId, + }) + if (!confirmed || confirmed.status !== 200) { + binding.bindConfirmState = 'rejected' + binding.bindConfirmMessage = confirmed?.msg || '虎牙未接受本次绑定' + binding.status = 'failed' + binding.message = `虎牙未接受本次绑定:${binding.bindConfirmMessage}` + return this.bindingView(session) + } + binding.bindConfirmState = 'accepted' + binding.bindEffectDeadlineMs = this.now() + REBIND_EFFECT_WINDOW_MS + binding.message = '虎牙已受理绑定,正在等待角色生效' + + let refreshed: HuyaBindingSnapshot + try { + refreshed = await queryHuyaBindingSnapshot(rpc, { + uid: session.uid, + cookie: session.cookie, + protocol, + }) + } catch (error) { + logWarn('huya/bind/refresh', '虎牙已受理绑定,但回查角色失败', { + uid: session.uid, + error: errorMessage(error), + }) + binding.status = 'scanned' + binding.message = '虎牙已受理绑定,但回查角色失败,请稍后刷新' + return this.bindingView(session) + } + applyRebindMeta(session, refreshed.outer, this.now()) + if ( + isConfirmedCurrentRole(refreshed.current) && + bindingRoleKey(refreshed.current) === bindingRoleKey(pending) + ) { + this.finalizeConfirmedBinding(session, refreshed.current) + return this.bindingView(session) + } + binding.status = 'scanned' return this.bindingView(session) }) } - /** 客户手动点击「已选好角色,提交换绑」时调用。 */ + /** 兼容旧入口:只刷新并识别 pending 角色,绝不在这里写虎牙。 */ 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, - }) - 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 = '虎牙已受理换绑,正在等待角色生效' - } - } - } - return this.bindingView(session) - }) + return this.pollBinding(sessionId) } async createBrowserTicket(input: { @@ -1485,26 +1562,62 @@ export class HuyaNativeConnector { } } - private markRoleReady( + private applyCurrentRole( session: NativeSession, - role: { account: string; role: string; roleId?: string; channel: string }, - existingBinding = false, + role: ReturnType, + existingBinding = session.binding.hasExistingBinding, ): 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 - ? '当前账号已有绑定角色,请确认直接使用' - : '绑定角色已识别,请确认绑定' + session.binding.isBindAccount = role.isBindAccount + session.binding.isBindRole = role.isBindRole + session.binding.changeBindTime = role.changeBindTime + session.binding.changeBindDay = role.changeBindDay + session.binding.hasExistingBinding = existingBinding + } + + private applyPendingRole(session: NativeSession, role: ReturnType): void { + session.binding.pendingAccount = role.account + session.binding.pendingRole = role.role + session.binding.pendingRoleId = role.roleId || '' + session.binding.pendingChannel = role.channel + session.binding.pendingChangeBindTime = role.changeBindTime + session.binding.pendingChangeBindDay = role.changeBindDay + session.binding.rebindUnchanged = false + } + + private clearPendingRole(session: NativeSession): void { + session.binding.pendingAccount = '' + session.binding.pendingRole = '' + session.binding.pendingRoleId = '' + session.binding.pendingChannel = '' + session.binding.pendingChangeBindTime = 0 + session.binding.pendingChangeBindDay = 0 + } + + private finalizeConfirmedBinding( + session: NativeSession, + role: ReturnType, + ): void { + this.applyCurrentRole(session, role, true) + this.clearPendingRole(session) + session.binding.status = 'confirmed' + session.binding.hasExistingBinding = true + session.binding.rebindRequested = false + session.binding.rebindScanned = false + session.binding.rebindUnchanged = false + session.binding.rebindConfirmState = 'idle' + session.binding.rebindConfirmMessage = '' + session.binding.rebindConfirmAt = 0 + session.binding.rebindEffectDeadlineMs = 0 + session.binding.bindConfirmState = 'idle' + session.binding.bindConfirmMessage = '' + session.binding.bindConfirmAt = 0 + session.binding.bindEffectDeadlineMs = 0 + session.binding.baselineRoleKey = '' + session.binding.message = '虎牙角色绑定已确认' } private requireSession(sessionIdInput: string): NativeSession { @@ -1579,9 +1692,8 @@ 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) + const roleIdVerified = /^\d+$/.test(binding.roleId) + const requiresSupport = binding.hasExistingBinding === true && !binding.role return { sessionId: session.sessionId, status: binding.status, @@ -1590,9 +1702,23 @@ export class HuyaNativeConnector { qrUrl: binding.qrUrl, bindGameAccount: binding.account, bindGameRole: binding.role, - bindGameRoleId: roleInfo.resolvedRoleId, + bindGameRoleId: binding.roleId, + bindGameRoleToken: binding.roleId, + platformGameRoleUid: /^\d+$/.test(binding.roleId) ? binding.roleId : '', bindGameChannel: binding.channel, - roleIdVerified: roleInfo.roleIdVerified, + pendingBindGameAccount: binding.pendingAccount, + pendingBindGameRole: binding.pendingRole, + pendingBindGameRoleToken: binding.pendingRoleId, + pendingBindGameChannel: binding.pendingChannel, + pendingChangeBindTime: binding.pendingChangeBindTime, + pendingChangeBindDay: binding.pendingChangeBindDay, + roleIdentitySource: binding.pendingRole + ? 'huya_inner_pending' + : binding.role + ? 'huya_outer_current' + : '', + verificationBasis: binding.role ? 'role_name_zone' : '', + roleIdVerified, requiresSupport, hasExistingBinding: binding.hasExistingBinding, rebindRequested: binding.rebindRequested, diff --git a/apps/backend/src/services/semi-auto/huya-native/huya-native.test.ts b/apps/backend/src/services/semi-auto/huya-native/huya-native.test.ts index f66ddd1b..1289185e 100644 --- a/apps/backend/src/services/semi-auto/huya-native/huya-native.test.ts +++ b/apps/backend/src/services/semi-auto/huya-native/huya-native.test.ts @@ -7,7 +7,12 @@ import sharp from 'sharp' import { buildHuyaLoginContext, ensureHuyaWebCookieIdentity, x64hash128 } from './cookie.js' import { HuyaNativeConnector, shouldReuseBindingQr } from './huya-native-connector.js' import { detectHuyaSliderDistance } from './huya-sms-role.js' -import { hasExistingHuyaBinding, parseBindStruct } from './huya-rpc.js' +import { + HuyaRpcClient, + hasExistingHuyaBinding, + parseBindStruct, + type HuyaBindResponse, +} from './huya-rpc.js' import { TAF_TYPE, TafWriter } from './taf.js' const BIND_RESP_HEX = @@ -16,6 +21,26 @@ const BIND_RESP_HEX = '802604e6898b51360be88bb9e69e9c28694f53294600560066000b526a2595806c0b36' + '0ce5928ce5b9b3e7b2bee88bb1460050070b' +function huyaBindingResponse(input: { + roleName: string + roleId: string + accountNick: string + channel: string + isBound?: boolean +}): HuyaBindResponse { + const response = parseBindStruct(Buffer.from(BIND_RESP_HEX, 'hex')) + response.status = 200 + response.accountData.isBindAccount = input.isBound === false ? 0 : 1 + response.accountData.isBindRole = input.isBound === false ? 0 : 1 + response.accountData.gameAccount.nick = input.accountNick + response.accountData.gameRole.roleName = input.roleName + response.accountData.gameRole.roleId = input.roleId + const [platform = '', area = ''] = input.channel.split(' · ') + response.accountData.gameRole.platName = platform + response.accountData.gameRole.areaName = area + return response +} + function buildHuyaProfileResponse(input: { uid: number nickname: string @@ -502,6 +527,222 @@ test('内置 Connector 手动发码并完成短信登录后保存账号 CK', asy ) }) +test('虎牙进程会话丢失后可从账号级 CK 恢复并生成浏览器注入票据', async () => { + let fetchCalls = 0 + const connector = new HuyaNativeConnector({ + fetchImpl: (async () => { + fetchCalls += 1 + throw new Error('恢复账号级 CK 不应依赖即时网络请求') + }) as typeof fetch, + }) + const restored = await connector.restoreSessionFromCredential({ + taskId: 9, + orderNo: 'ORDER-RESTORE-CK', + platformUid: '1686664168', + nickname: '恢复测试账号', + cookies: [ + { + name: 'yyuid', + value: '1686664168', + domain: '.huya.com', + path: '/', + secure: true, + httpOnly: false, + expiresAt: null, + }, + { + name: 'udb_uid', + value: '1686664168', + domain: '.huya.com', + path: '/', + secure: true, + httpOnly: false, + expiresAt: null, + }, + { + name: 'udb_cred', + value: 'restored-credential', + domain: '.huya.com', + path: '/', + secure: true, + httpOnly: false, + expiresAt: null, + }, + ], + }) + assert.equal(restored.status, 'authenticated') + assert.equal(restored.huyaUid, '1686664168') + assert.equal(restored.hasCredential, true) + assert.equal(fetchCalls, 0) + + const ticket = await connector.createBrowserTicket({ + sessionId: restored.sessionId, + targetUrl: 'https://www.huya.com/', + }) + const payload = await connector.consumeBrowserTicket(ticket.ticket) + assert.equal( + payload.cookies.find((cookie) => cookie.name === 'udb_cred')?.value, + 'restored-credential', + ) +}) + +test('内置 Connector 轮询和重绑只读,客户明确确认后才写虎牙', async () => { + const currentRole = huyaBindingResponse({ + roleName: '当前绑定角色', + roleId: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', + accountNick: '虎牙账号', + channel: '安卓(android) · QQ', + }) + const pendingRole = huyaBindingResponse({ + roleName: '本次待确认角色', + roleId: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', + accountNick: '虎牙账号', + channel: '安卓(android) · QQ', + }) + let confirmed = false + let confirmCalls = 0 + const fetchImpl = (async (urlInput: string | URL | Request) => { + const url = String(urlInput) + if (url.endsWith('/web/df/token')) { + return new Response(JSON.stringify({ data: { token: 'binding-df-token' } }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }) + } + if (url.endsWith('/web/df/collect')) { + return new Response( + JSON.stringify({ data: { sdid: 'binding-web-sdid', hdid: 'binding-web-hdid' } }), + { status: 200, headers: { 'content-type': 'application/json' } }, + ) + } + if (url.includes('/web/middle/')) { + return new Response('', { + status: 200, + headers: { 'content-type': 'text/html;charset=UTF-8' }, + }) + } + if (url.endsWith('/web/v2/smsCode')) { + return new Response( + JSON.stringify({ returnCode: 0, data: { sessionData: 'binding-sms-session' } }), + { status: 200, headers: { 'content-type': 'application/json' } }, + ) + } + if (url.endsWith('/web/v2/smsLogin')) { + const headers = new Headers({ 'content-type': 'application/json' }) + headers.append('set-cookie', 'udb_cred=binding-cred; Path=/; Domain=huya.com') + headers.append('set-cookie', 'yyuid=1199664118656; Path=/; Domain=huya.com') + headers.append('set-cookie', 'udb_passport=hy_binding; Path=/; Domain=huya.com') + return new Response( + JSON.stringify({ + returnCode: 0, + data: { + uid: 1199664118656, + passport: 'hy_binding', + nickname: '虎牙账号', + }, + }), + { status: 200, headers }, + ) + } + if (url.endsWith('/web/cookie/verify')) { + return new Response(JSON.stringify({ returnCode: 0, data: null }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }) + } + if (url.startsWith('https://cdnws.api.huya.com/')) { + return new Response( + buildHuyaProfileResponse({ + uid: 1199664118656, + nickname: '虎牙账号', + passport: 'hy_binding', + }), + { status: 200, headers: { 'content-type': 'application/octet-stream' } }, + ) + } + throw new Error(`unexpected request: ${url}`) + }) as typeof fetch + + const originalCheck = HuyaRpcClient.prototype.checkUserBindGameAccount + const originalConfirm = HuyaRpcClient.prototype.confirmBindActAccount + HuyaRpcClient.prototype.checkUserBindGameAccount = async function (input) { + if (!input.outerActId) return pendingRole + return confirmed ? pendingRole : currentRole + } + HuyaRpcClient.prototype.confirmBindActAccount = async function () { + confirmCalls += 1 + confirmed = true + return { status: 200, msg: '' } + } + + try { + const connector = new HuyaNativeConnector({ + fetchImpl, + getFingerprint: async () => ({ + sdid: 'binding-fingerprint-sdid', + hdid: 'binding-fingerprint-hdid', + cookies: { + udb_appid: '5008', + game_did: 'binding-game-did', + _qimei_uuid42: '1ab09100209100ee4d631bc545468c6addc489a95a', + __yamid_new: 'CBE2807148F00001332411CB1E296A00', + udb_guiddata: '838ed427bbdb491d8e6f6782addb0364', + guid: '0a7dee10017ef16aad0229302a3029e3', + }, + source: 'fingerprint', + }), + stateRoot: path.join(os.tmpdir(), 'huya-native-binding-write-test'), + }) + const sent = await connector.sendSmsCode({ + taskId: 6, + orderNo: 'ORDER-BIND-WRITE', + mobile: '13800138000', + }) + await connector.loginWithSms({ + sessionId: sent.session.sessionId, + mobile: '13800138000', + code: '123456', + }) + + let binding = await connector.pollBinding(sent.session.sessionId) + assert.equal(binding.status, 'role_ready') + assert.equal(binding.pendingBindGameRole, '本次待确认角色') + assert.equal(confirmCalls, 0) + + binding = await connector.submitRebind(sent.session.sessionId) + assert.equal(binding.status, 'role_ready') + assert.equal(confirmCalls, 0) + + await assert.rejects( + () => + connector.confirmBinding(sent.session.sessionId, { + expectedRoleName: '已被替换的角色', + expectedRoleToken: 'cccccccccccccccccccccccccccccccccccccccc', + expectedRoleChannel: '安卓(android) · QQ', + }), + /待确认角色已变化/, + ) + assert.equal(confirmCalls, 0) + + binding = await connector.confirmBinding(sent.session.sessionId, { + expectedRoleName: '本次待确认角色', + expectedRoleToken: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', + expectedRoleChannel: '安卓(android) · QQ', + }) + assert.equal(binding.status, 'confirmed') + assert.equal(binding.bindGameRole, '本次待确认角色') + assert.equal(binding.pendingBindGameRole, '') + assert.equal(confirmCalls, 1) + + binding = await connector.pollBinding(sent.session.sessionId) + assert.equal(binding.status, 'confirmed') + assert.equal(confirmCalls, 1) + } finally { + HuyaRpcClient.prototype.checkUserBindGameAccount = originalCheck + HuyaRpcClient.prototype.confirmBindActAccount = originalConfirm + } +}) + test('内置 Connector 将虎牙滑块验证交给客户完成后再发码', async () => { let smsCodeCalls = 0 const background = await sharp({ 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 9f2f0fe5..2f59d273 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 @@ -620,6 +620,7 @@ export class HuyaRpcClient { uid: number cookie: string bindActId: number + gid?: number outerActId: number gameAuthScene?: string }): Promise { @@ -628,6 +629,7 @@ export class HuyaRpcClient { servant: 'webActUI', func: 'getLiveLinkParam', uid: input.uid, + gid: input.gid || 0, bindActId: input.bindActId || 0, outerActId: input.outerActId || 0, gameAuthScene: input.gameAuthScene || '', @@ -640,7 +642,7 @@ export class HuyaRpcClient { input.cookie, (writer) => { this.writeActivityUser(writer, input.uid, input.cookie) - writer.writeInt32(1, 0) + writer.writeInt32(1, input.gid || 0) writer.writeInt32(2, input.outerActId || 0) writer.writeString(3, input.gameAuthScene || '') writer.writeString(4, '') diff --git a/apps/backend/src/services/semi-auto/semi-auto-admin-service.ts b/apps/backend/src/services/semi-auto/semi-auto-admin-service.ts index 8b5c6119..8ef74e88 100644 --- a/apps/backend/src/services/semi-auto/semi-auto-admin-service.ts +++ b/apps/backend/src/services/semi-auto/semi-auto-admin-service.ts @@ -31,6 +31,7 @@ import { } from './weibo-connector-client.js' import { WEIBO_TICKET_PREFIX } from './weibo-native/weibo-native-connector.js' import { querySemiAutoTraces } from './semi-auto-trace.js' +import { isHuyaRoleToken } from './binding-role-id.js' import { getAccountBindingPolicy } from '../account-binding/platform-policy.js' import { appendTaskEvent, @@ -87,7 +88,7 @@ export async function listAdminSemiAutoTasks(input: Record = {} params.push(`%${keyword.replace(/[\\%_]/g, '\\$&')}%`) const p = `$${params.length}` conditions.push( - `(o.platform_order_id ILIKE ${p} OR oi.sku_name ILIKE ${p} OR oi.sku_code ILIKE ${p} OR task.huya_uid ILIKE ${p} OR task.bind_game_role ILIKE ${p})`, + `(o.platform_order_id ILIKE ${p} OR oi.sku_name ILIKE ${p} OR oi.sku_code ILIKE ${p} OR task.huya_uid ILIKE ${p} OR task.bind_game_role ILIKE ${p} OR task.pending_bind_game_role ILIKE ${p})`, ) } const where = conditions.join(' AND ') @@ -141,11 +142,12 @@ export async function getAdminSemiAutoTask(taskIdInput: unknown) { ) return { task: mapTask(task), - // 管理端详情直接复用与客户页相同的三项比对口径,避免出现第二套判定。 + // 管理端详情直接复用与客户页相同的角色核对口径。 comparison: compareBindingRole(task, { - bindGameRole: task.bind_game_role, - bindGameRoleId: task.bind_game_role_id, - bindGameChannel: task.bind_game_channel, + bindGameRole: task.pending_bind_game_role || task.bind_game_role, + bindGameRoleToken: task.pending_bind_game_role_token || task.bind_game_role_token, + bindGameChannel: task.pending_bind_game_channel || task.bind_game_channel, + platformGameRoleUid: task.platform_game_role_uid, }), events: events.rows.map((event) => ({ id: Number(event.id), @@ -398,6 +400,14 @@ const BINDING_STATUSES = new Set([ 'failed', 'expired', ]) +const ROLE_IDENTITY_SOURCES = new Set([ + '', + 'huya_outer_current', + 'huya_inner_pending', + 'legacy_account_uid_fallback', + 'manual', +]) +const VERIFICATION_BASES = new Set(['', 'role_name_zone', 'platform_numeric_uid', 'manual']) function parseSnapshotStatus(value: unknown, allowed: Set, label: string): T { const status = String(value || '').trim() as T @@ -470,8 +480,71 @@ export async function applySemiAutoTaskStateSnapshot( const nickname = String(input.platformNickname ?? input.platform_nickname ?? '').trim() const bindGameAccount = String(input.bindGameAccount ?? input.bind_game_account ?? '').trim() const bindGameRole = String(input.bindGameRole ?? input.bind_game_role ?? '').trim() - const bindGameRoleId = String(input.bindGameRoleId ?? input.bind_game_role_id ?? '').trim() + const legacyRoleId = String(input.bindGameRoleId ?? input.bind_game_role_id ?? '').trim() + const bindGameRoleToken = String( + input.bindGameRoleToken ?? + input.bind_game_role_token ?? + (isHuyaRoleToken(legacyRoleId) ? legacyRoleId : ''), + ).trim() + const platformGameRoleUid = String( + input.platformGameRoleUid ?? input.platform_game_role_uid ?? '', + ).trim() const bindGameChannel = String(input.bindGameChannel ?? input.bind_game_channel ?? '').trim() + const pendingBindGameAccount = String( + input.pendingBindGameAccount ?? input.pending_bind_game_account ?? '', + ).trim() + const pendingBindGameRole = String( + input.pendingBindGameRole ?? input.pending_bind_game_role ?? '', + ).trim() + const pendingBindGameRoleToken = String( + input.pendingBindGameRoleToken ?? input.pending_bind_game_role_token ?? '', + ).trim() + const pendingBindGameChannel = String( + input.pendingBindGameChannel ?? input.pending_bind_game_channel ?? '', + ).trim() + const roleIdentitySource = String( + input.roleIdentitySource ?? input.role_identity_source ?? '', + ).trim() + const verificationBasis = String( + input.verificationBasis ?? input.verification_basis ?? '', + ).trim() + if (bindGameRoleToken && !isHuyaRoleToken(bindGameRoleToken)) { + throw createHttpError('虎牙平台角色 token 格式无效', { + statusCode: 400, + errorCode: 'semi_auto_snapshot_role_token_invalid', + }) + } + if (pendingBindGameRoleToken && !isHuyaRoleToken(pendingBindGameRoleToken)) { + throw createHttpError('虎牙待确认角色 token 格式无效', { + statusCode: 400, + errorCode: 'semi_auto_snapshot_pending_role_token_invalid', + }) + } + if (platformGameRoleUid && !/^\d+$/.test(platformGameRoleUid)) { + throw createHttpError('平台游戏角色 UID 格式无效', { + statusCode: 400, + errorCode: 'semi_auto_snapshot_platform_role_uid_invalid', + }) + } + const effectiveHuyaUid = uid || task.huya_uid + if (platformGameRoleUid && effectiveHuyaUid && platformGameRoleUid === effectiveHuyaUid) { + throw createHttpError('平台游戏角色 UID 不能复用虎牙账号 UID', { + statusCode: 400, + errorCode: 'semi_auto_snapshot_platform_role_uid_reused', + }) + } + if (!ROLE_IDENTITY_SOURCES.has(roleIdentitySource)) { + throw createHttpError('角色身份来源无效', { + statusCode: 400, + errorCode: 'semi_auto_snapshot_role_source_invalid', + }) + } + if (!VERIFICATION_BASES.has(verificationBasis)) { + throw createHttpError('角色核验依据无效', { + statusCode: 400, + errorCode: 'semi_auto_snapshot_verification_basis_invalid', + }) + } const message = String(input.message ?? input.lastError ?? input.last_error ?? '') .trim() .slice(0, 1000) @@ -485,8 +558,15 @@ export async function applySemiAutoTaskStateSnapshot( platform_nickname = CASE WHEN $6 <> '' THEN $6 ELSE platform_nickname END, bind_game_account = CASE WHEN $7 <> '' THEN $7 ELSE bind_game_account END, bind_game_role = CASE WHEN $8 <> '' THEN $8 ELSE bind_game_role END, - bind_game_role_id = CASE WHEN $9 <> '' THEN $9 ELSE bind_game_role_id END, + bind_game_role_token = CASE WHEN $9 <> '' THEN $9 ELSE bind_game_role_token END, bind_game_channel = CASE WHEN $10 <> '' THEN $10 ELSE bind_game_channel END, + pending_bind_game_account = $12, + pending_bind_game_role = $13, + pending_bind_game_role_token = $14, + pending_bind_game_channel = $15, + platform_game_role_uid = $18, + role_identity_source = CASE WHEN $16 <> '' THEN $16 ELSE role_identity_source END, + verification_basis = CASE WHEN $17 <> '' THEN $17 ELSE verification_basis END, authenticated_at = CASE WHEN $2 = 'authenticated' THEN COALESCE(authenticated_at, NOW()) ELSE authenticated_at @@ -508,9 +588,16 @@ export async function applySemiAutoTaskStateSnapshot( nickname, bindGameAccount, bindGameRole, - bindGameRoleId, + bindGameRoleToken, bindGameChannel, message, + pendingBindGameAccount, + pendingBindGameRole, + pendingBindGameRoleToken, + pendingBindGameChannel, + roleIdentitySource, + verificationBasis, + platformGameRoleUid, ], ) if ( 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 index d68ab66a..b50395ad 100644 --- 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 @@ -1,109 +1,32 @@ import assert from 'node:assert/strict' import { describe, it } from 'node:test' -import { - describeBindingRole, - isNumericBindingRoleId, - resolveBindingRoleId, -} from './binding-role-id.js' +import { isHuyaRoleToken, isNumericBindingRoleId } 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, +const task = (roleName: string, roleUid: string, zone: string) => ({ + customer_game_id: roleUid, + customer_game_role: roleName, customer_game_server_zone: zone, - huya_uid: huyaUid, }) -describe('待确认角色 UID 取数(huyaUid)', () => { - it('角色 ID 本身是纯数字时直接使用', () => { - assert.equal(resolveBindingRoleId('1192083858', 1199608910400), '1192083858') +const HUYA_ROLE_TOKEN = '5649acb0b723427a2439a870fea8a2e8fd383611' + +describe('虎牙身份字段类型', () => { + it('40 位十六进制 roleId 只识别为加密角色 token', () => { + assert.equal(isHuyaRoleToken(HUYA_ROLE_TOKEN), true) + assert.equal(isHuyaRoleToken('1199669781026'), false) }) - 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', '安卓V区'), - { - bindGameRole: '大鲨鱼伊塞53', - bindGameRoleId: '834ee3e75a1bfc9f65fb6b966bac7ef318e68ea', - bindGameChannel: '安卓(android) · 微信', - }, - ) - assert.equal(result.verdict, 'match') - assert.equal(result.boundRoleId, '1199608910400') - }) - - it('没有 huyaUid 时无法核对加密角色 ID,判 unknown', () => { - const result = compareBindingRole(task('1199608910400', '大鲨鱼伊塞53', '', '安卓V区'), { - bindGameRole: '大鲨鱼伊塞53', - bindGameRoleId: '834ee3e75a1bfc9f65fb6b966bac7ef318e68ea', - bindGameChannel: '安卓(android) · 微信', - }) - assert.equal(result.verdict, 'unknown') - assert.match(result.message, /平台可核对角色ID/) - 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) + it('只有平台独立返回的纯数字字段才识别为数值角色 UID', () => { + assert.equal(isNumericBindingRoleId('4212063544'), true) + assert.equal(isNumericBindingRoleId(' 4212063544 '), true) + assert.equal(isNumericBindingRoleId(HUYA_ROLE_TOKEN), false) assert.equal(isNumericBindingRoleId(''), false) - assert.equal(isNumericBindingRoleId(null), false) }) }) @@ -123,151 +46,131 @@ describe('区服解析', () => { }) }) -describe('客户填写角色与平台识别角色比对', () => { - it('区服、角色名称、角色 ID 都一致时允许确认', () => { - const result = compareBindingRole( - task('1199608910400', '大鲨鱼伊塞53', '1199608910400', '安卓V区'), - { - bindGameRole: '大鲨鱼伊塞53', - bindGameRoleId: '1199608910400', - bindGameChannel: '安卓(android) · 微信', - }, - ) +describe('虎牙角色比对', () => { + it('角色名和区服一致即可确认,客户角色 UID 不与账号 UID 或加密 token 比对', () => { + const result = compareBindingRole(task('落地盒子怪cc', '4212063544', '安卓Q区'), { + bindGameRole: '落地盒子怪cc', + bindGameRoleToken: HUYA_ROLE_TOKEN, + bindGameChannel: '安卓(android) · QQ', + }) assert.equal(result.verdict, 'match') - assert.equal(result.customerZone, '安卓V区') - assert.equal(result.boundZone, '安卓V区') - assert.match(result.message, /区服/) + assert.equal(result.boundRoleIdKind, 'huya_role_token') + assert.equal(result.verificationBasis, 'role_name_zone') }) - it('角色 ID 一致但角色名称不一致时禁止确认', () => { - const result = compareBindingRole(task('1199608910400', '123', '1199608910400', '安卓V区'), { - bindGameRole: '大鲨鱼伊塞53', - bindGameRoleId: '1199608910400', - bindGameChannel: '安卓(android) · 微信', + it('客户游戏角色 UID 与平台显示数字不同,不会影响角色名区服核对', () => { + const result = compareBindingRole(task('落地盒子怪cc', '4212063544', '安卓Q区'), { + bindGameRole: '落地盒子怪cc', + bindGameRoleToken: HUYA_ROLE_TOKEN, + bindGameChannel: '安卓(android) · 手Q', + }) + assert.equal(result.verdict, 'match') + assert.notEqual(result.customerRoleId, result.boundRoleId) + }) + + it('角色名称不一致时禁止确认', () => { + const result = compareBindingRole(task('利拉鲁肽', '88855', '安卓Q区'), { + bindGameRole: '落地盒子怪cc', + bindGameRoleToken: HUYA_ROLE_TOKEN, + bindGameChannel: '安卓(android) · QQ', }) 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('渠道解析不出区服时判 unknown,不允许提交', () => { - const result = compareBindingRole( - task('1199608910400', '大鲨鱼伊塞53', '1199608910400', '苹果Q区'), - { - bindGameRole: '大鲨鱼伊塞53', - bindGameRoleId: '1199608910400', - bindGameChannel: '微信用户', - }, - ) - assert.equal(result.verdict, 'unknown') - assert.match(result.message, /平台区服/) - assert.equal(result.boundZone, '') - }) - - it('客户区服未填时判 unknown,不允许提交', () => { - const result = compareBindingRole(task('1199608910400', '大鲨鱼伊塞53', '1199608910400', ''), { - bindGameRole: '大鲨鱼伊塞53', - bindGameRoleId: '1199608910400', - bindGameChannel: '安卓(android) · 微信', - }) - assert.equal(result.verdict, 'unknown') - assert.match(result.message, /客户区服/) - }) - - it('三项一致时允许提交平台绑定', () => { - const result = compareBindingRole(task('1192083858', '巫师基尔斯84', '1192083858', '安卓Q区'), { - bindGameRole: '巫师基尔斯84', - bindGameRoleId: '1192083858', + it('区服不一致时禁止确认', () => { + const result = compareBindingRole(task('落地盒子怪cc', '4212063544', '安卓V区'), { + bindGameRole: '落地盒子怪cc', + bindGameRoleToken: HUYA_ROLE_TOKEN, bindGameChannel: '安卓(android) · QQ', }) - assert.equal(result.verdict, 'match') - assert.equal(result.customerRoleId, '1192083858') - assert.equal(result.boundRoleId, '1192083858') - assert.match(result.message, /可提交平台绑定/) + assert.equal(result.verdict, 'mismatch') + assert.match(result.message, /区服/) }) - it('两侧角色 ID 不一致时禁止提交', () => { - const result = compareBindingRole(task('1192083858', '巫师基尔斯84', '', '安卓V区'), { - bindGameRole: '我是火星人2222', - bindGameRoleId: '166909256', - bindGameChannel: '安卓(android) · 微信', + it('平台区服无法解析时判 unknown', () => { + const result = compareBindingRole(task('落地盒子怪cc', '4212063544', '安卓Q区'), { + bindGameRole: '落地盒子怪cc', + bindGameRoleToken: HUYA_ROLE_TOKEN, + bindGameChannel: '微信用户', + }) + assert.equal(result.verdict, 'unknown') + assert.match(result.message, /平台区服/) + }) + + it('客户角色名或区服缺失时判 unknown', () => { + const missingRole = compareBindingRole(task('', '4212063544', '安卓Q区'), { + bindGameRole: '落地盒子怪cc', + bindGameRoleToken: HUYA_ROLE_TOKEN, + bindGameChannel: '安卓(android) · QQ', + }) + assert.equal(missingRole.verdict, 'unknown') + assert.match(missingRole.message, /客户角色名/) + + const missingZone = compareBindingRole(task('落地盒子怪cc', '4212063544', ''), { + bindGameRole: '落地盒子怪cc', + bindGameRoleToken: HUYA_ROLE_TOKEN, + bindGameChannel: '安卓(android) · QQ', + }) + assert.equal(missingZone.verdict, 'unknown') + assert.match(missingZone.message, /客户区服/) + }) + + it('平台明确返回数值角色 UID 时才启用数值核验', () => { + const result = compareBindingRole(task('落地盒子怪cc', '4212063544', '安卓Q区'), { + bindGameRole: '落地盒子怪cc', + bindGameRoleToken: HUYA_ROLE_TOKEN, + bindGameChannel: '安卓(android) · QQ', + platformGameRoleUid: '4212063544', + }) + assert.equal(result.verdict, 'match') + assert.equal(result.boundRoleIdKind, 'game_role_uid') + assert.equal(result.verificationBasis, 'platform_numeric_uid') + }) + + it('平台未来返回数值角色 UID 时,数值不同也不能确认', () => { + const result = compareBindingRole(task('落地盒子怪cc', '4212063544', '安卓Q区'), { + bindGameRole: '落地盒子怪cc', + bindGameRoleToken: HUYA_ROLE_TOKEN, + bindGameChannel: '安卓(android) · QQ', + platformGameRoleUid: '4212063545', }) assert.equal(result.verdict, 'mismatch') - assert.match(result.message, /不一致/) - }) - - it('任一侧缺少角色 ID 时判 unknown,不退化为只比角色名', () => { - const result = compareBindingRole(task('', '巫师基尔斯84'), { - bindGameRole: '巫师基尔斯84', - bindGameRoleId: '', - }) - assert.equal(result.verdict, 'unknown') - assert.match(result.message, /客户游戏编号/) - assert.match(result.message, /平台可核对角色ID/) - }) - - it('两侧都没有可核对信息时标记为 unknown', () => { - const result = compareBindingRole(task('', ''), { bindGameRole: '', bindGameRoleId: '' }) - assert.equal(result.verdict, 'unknown') + assert.match(result.message, /游戏角色 UID/) }) }) describe('客户角色资料校验', () => { - it('清理空白并保留纯数字角色 ID', () => { + it('清理空白并保留纯数字游戏角色 UID', () => { const profile = normalizeCustomerProfile({ - roleName: ' 巫师基尔斯84 ', - roleId: ' 1192083858 ', - serverZone: ' 苹果V区 ', + roleName: ' 落地盒子怪cc ', + roleId: ' 4212063544 ', + serverZone: ' 安卓Q区 ', }) assert.deepEqual(profile, { - roleName: '巫师基尔斯84', - roleId: '1192083858', - serverZone: '苹果V区', + roleName: '落地盒子怪cc', + roleId: '4212063544', + serverZone: '安卓Q区', }) }) - it('角色 ID 非数字时拒绝保存', () => { + it('游戏角色 UID 非数字时拒绝保存', () => { assert.throws( - () => normalizeCustomerProfile({ roleName: '巫师基尔斯84', roleId: 'abc123' }), + () => normalizeCustomerProfile({ roleName: '落地盒子怪cc', roleId: 'abc123' }), /只能是数字/, ) }) it('缺区服时拒绝保存', () => { assert.throws( - () => normalizeCustomerProfile({ roleName: '巫师基尔斯84', roleId: '1192083858' }), + () => normalizeCustomerProfile({ roleName: '落地盒子怪cc', roleId: '4212063544' }), /区服只能选择/, ) }) - it('区服不在固定选项时拒绝保存', () => { + it('角色名称与游戏角色 UID 都为空时拒绝保存', () => { assert.throws( - () => - normalizeCustomerProfile({ - roleName: '巫师基尔斯84', - roleId: '1192083858', - serverZone: '苹果微信区', - }), - /区服只能选择/, - ) - }) - - it('角色名称与角色 ID 都为空时拒绝保存', () => { - assert.throws( - () => normalizeCustomerProfile({ roleName: ' ', roleId: '', serverZone: '苹果V区' }), + () => normalizeCustomerProfile({ roleName: ' ', roleId: '', serverZone: '安卓Q区' }), /请完整填写区服/, ) }) diff --git a/apps/backend/src/services/semi-auto/semi-auto-customer-service.ts b/apps/backend/src/services/semi-auto/semi-auto-customer-service.ts index c3fd99dc..eed70fda 100644 --- a/apps/backend/src/services/semi-auto/semi-auto-customer-service.ts +++ b/apps/backend/src/services/semi-auto/semi-auto-customer-service.ts @@ -24,6 +24,7 @@ import { startWeiboBinding, } from './weibo-connector-client.js' import { upsertSemiAutoCredentialWithClient } from './semi-auto-credential-service.js' +import { isHuyaRoleToken } from './binding-role-id.js' import { getAccountBindingPolicy } from '../account-binding/platform-policy.js' import { appendTaskEvent, @@ -108,7 +109,7 @@ export function normalizeCustomerProfile(input: CustomerProfileInput = {}) { .trim() .slice(0, 100) if (roleId && !/^\d+$/.test(roleId)) { - throw createHttpError('游戏编号 / 角色 ID 只能是数字', { + throw createHttpError('游戏角色 UID 只能是数字', { statusCode: 400, errorCode: 'semi_auto_profile_role_id_invalid', }) @@ -120,7 +121,7 @@ export function normalizeCustomerProfile(input: CustomerProfileInput = {}) { }) } if (!roleName || !roleId) { - throw createHttpError('请完整填写区服、游戏编号和角色名', { + throw createHttpError('请完整填写区服、游戏角色 UID 和角色名', { statusCode: 400, errorCode: 'semi_auto_profile_required', }) @@ -400,7 +401,17 @@ export async function startPublicLogin(orderNoInput: unknown, taskIdInput: unkno bind_game_account = '', bind_game_role = '', bind_game_role_id = '', + bind_game_role_token = '', + platform_game_role_uid = '', bind_game_channel = '', + pending_bind_game_account = '', + pending_bind_game_role = '', + pending_bind_game_role_token = '', + pending_bind_game_channel = '', + pending_bind_game_change_bind_time = 0, + pending_bind_game_change_bind_day = 0, + role_identity_source = '', + verification_basis = '', binding_started_at = NULL, bound_at = NULL, execution_status = 'waiting_customer', @@ -564,7 +575,17 @@ export async function resetPublicBinding(orderNoInput: unknown, taskIdInput: unk bind_game_account = '', bind_game_role = '', bind_game_role_id = '', + bind_game_role_token = '', + platform_game_role_uid = '', bind_game_channel = '', + pending_bind_game_account = '', + pending_bind_game_role = '', + pending_bind_game_role_token = '', + pending_bind_game_channel = '', + pending_bind_game_change_bind_time = 0, + pending_bind_game_change_bind_day = 0, + role_identity_source = '', + verification_basis = '', binding_started_at = NULL, bound_at = NULL, execution_status = 'waiting_customer', @@ -646,12 +667,23 @@ export async function confirmPublicBinding( }) } assertCustomerProfileReady(task) - // 确认绑定是纯本地动作:虎牙侧只读内存快照,不再触发角色查询或换绑提交。 + // 先读取本地 pending 快照并比对;只有比对通过后才允许调用虎牙确认写接口。 const session = bindingPolicy.bindingRequired && bindingPolicy.queryOwner === 'order_site' ? await getHuyaBindingSnapshot(task.connector_session_id, task.connector_mode) : await getBindingForTask(task, task.connector_session_id) - const comparison = compareBindingRole(task, session) + const comparisonRoleToken = String( + session.pendingBindGameRole + ? session.pendingBindGameRoleToken + : session.bindGameRoleToken || session.bindGameRoleId || '', + ).trim() + const comparisonRole = { + bindGameRole: session.pendingBindGameRole || session.bindGameRole, + bindGameRoleToken: isHuyaRoleToken(comparisonRoleToken) ? comparisonRoleToken : '', + bindGameChannel: session.pendingBindGameChannel || session.bindGameChannel, + platformGameRoleUid: session.platformGameRoleUid || '', + } + const comparison = compareBindingRole(task, comparisonRole) // 换绑被虎牙拒绝时平台仍返回原角色。若客户已把资料改成与原角色一致, // 允许直接确认;否则要求重新扫码或返回上一步修改资料。 if ( @@ -670,7 +702,7 @@ export async function confirmPublicBinding( }, ) } - // 三项必须全部存在且一致;信息不完整同样不能自动放行,必须转客服核实。 + // 角色名和区服必须一致;信息不完整同样不能自动放行,必须转客服核实。 if (comparison.verdict !== 'match') { throw createHttpError(comparison.message, { statusCode: 409, @@ -687,6 +719,9 @@ export async function confirmPublicBinding( ...(options.acceptExistingRole === true || session.rebindUnchanged === true ? { acceptExistingRole: true } : {}), + expectedRoleName: comparisonRole.bindGameRole || '', + expectedRoleToken: comparisonRole.bindGameRoleToken || '', + expectedRoleChannel: comparisonRole.bindGameChannel || '', }) : session const binding = await updateBindingTask(task, confirmedSession, 'customer') @@ -694,10 +729,7 @@ export async function confirmPublicBinding( return { task: mapTask(updated), binding } } -/** - * 客户在微信里选好目标角色后,由项目侧主动向虎牙提交换绑确认。 - * 与「确认绑定」不同,这一步只提交换绑,不把任务标记为已确认。 - */ +/** 客户在微信里选好目标角色后,只刷新待确认角色;平台写操作仍由确认绑定触发。 */ export async function submitPublicRebind(orderNoInput: unknown, taskIdInput: unknown) { const orderNo = normalizeOrderNo(orderNoInput) const taskId = normalizeId(taskIdInput) diff --git a/apps/backend/src/services/semi-auto/semi-auto-task-core.ts b/apps/backend/src/services/semi-auto/semi-auto-task-core.ts index 23e3698c..6d05d3a0 100644 --- a/apps/backend/src/services/semi-auto/semi-auto-task-core.ts +++ b/apps/backend/src/services/semi-auto/semi-auto-task-core.ts @@ -30,6 +30,7 @@ import { getHuyaLoginSession, loginHuyaSms, resetHuyaBinding, + restoreHuyaSessionFromCredential, revokeHuyaSession, sendHuyaSmsCode, startHuyaBinding, @@ -60,9 +61,10 @@ import { loadSemiAutoCredential, markSemiAutoCredentialCheck, upsertSemiAutoCredentialWithClient, + type SemiAutoCredentialCookie, } from './semi-auto-credential-service.js' import { querySemiAutoTraces } from './semi-auto-trace.js' -import { isNumericBindingRoleId } from './binding-role-id.js' +import { isHuyaRoleToken, isNumericBindingRoleId } from './binding-role-id.js' import { compareBindingIdentity, resolveServerZone } from '../account-binding/binding-identity.js' import { getAccountBindingPolicy } from '../account-binding/platform-policy.js' @@ -113,7 +115,18 @@ export type TaskRow = { bind_game_account: string bind_game_role: string bind_game_role_id: string + bind_game_role_token: string + platform_game_role_uid: string bind_game_channel: string + pending_bind_game_account: string + pending_bind_game_role: string + pending_bind_game_role_token: string + pending_bind_game_channel: string + pending_bind_game_change_bind_time: number + pending_bind_game_change_bind_day: number + role_identity_source: string + verification_basis: string + legacy_bind_game_role_id: string customer_game_role_name: string customer_game_role_id: string customer_game_server_zone: string @@ -257,7 +270,12 @@ export function displayStatus(task: TaskRow) { return status('waiting_operator', '等待客服处理', 'operator', '客服领取并履约') } if (bindingPolicy.requiresCustomerProfile && !hasCustomerProfile(task)) { - return status('waiting_profile', '待客户填写资料', 'customer', '客户填写区服、编号和角色名') + return status( + 'waiting_profile', + '待客户填写资料', + 'customer', + '客户填写区服、游戏角色 UID 和角色名', + ) } if (task.binding_status === 'role_ready') { return status('binding_confirm', '待确认绑定角色', 'customer', '核对角色并提交绑定') @@ -312,8 +330,16 @@ export function mapTask(task: TaskRow) { platformNickname: task.platform_nickname, bindGameAccount: task.bind_game_account, bindGameRole: task.bind_game_role, - bindGameRoleId: task.bind_game_role_id, + bindGameRoleId: '', + bindGameRoleToken: task.bind_game_role_token, + platformGameRoleUid: task.platform_game_role_uid, bindGameChannel: task.bind_game_channel, + pendingBindGameAccount: task.pending_bind_game_account, + pendingBindGameRole: task.pending_bind_game_role, + pendingBindGameRoleToken: task.pending_bind_game_role_token, + pendingBindGameChannel: task.pending_bind_game_channel, + roleIdentitySource: task.role_identity_source, + verificationBasis: task.verification_basis, customerGameRoleId: task.customer_game_id || '', customerGameRoleName: task.customer_game_role || '', customerServerZone: task.customer_server_zone || '', @@ -554,9 +580,12 @@ function errorCodeOf(error: unknown) { } function isInvalidCredentialError(error: unknown) { - return ['weibo_credential_invalid', 'weibo_credential_account_mismatch'].includes( - errorCodeOf(error), - ) + return [ + 'weibo_credential_invalid', + 'weibo_credential_account_mismatch', + 'huya_credential_invalid', + 'huya_credential_account_mismatch', + ].includes(errorCodeOf(error)) } export async function resetTaskForCustomerLogin( @@ -586,7 +615,17 @@ export async function resetTaskForCustomerLogin( bind_game_account = '', bind_game_role = '', bind_game_role_id = '', + bind_game_role_token = '', + platform_game_role_uid = '', bind_game_channel = '', + pending_bind_game_account = '', + pending_bind_game_role = '', + pending_bind_game_role_token = '', + pending_bind_game_channel = '', + pending_bind_game_change_bind_time = 0, + pending_bind_game_change_bind_day = 0, + role_identity_source = '', + verification_basis = '', customer_link_opened_at = NULL, auth_started_at = NULL, authenticated_at = NULL, @@ -617,7 +656,7 @@ export async function resetTaskForCustomerLogin( } export async function resetTaskForInvalidCredential(task: TaskRow, error: unknown) { - if (task.platform !== 'weibo' || !isInvalidCredentialError(error)) return null + if (!isInvalidCredentialError(error)) return null await markSemiAutoCredentialCheck(task.credential_id, { status: 'invalid', error: error instanceof Error ? error.message : String(error), @@ -627,7 +666,10 @@ export async function resetTaskForInvalidCredential(task: TaskRow, error: unknow } return resetTaskForCustomerLogin(task, { actorType: 'connector', - reason: '微博登录凭证已失效,需客户重新登录', + reason: + task.platform === 'huya' + ? '虎牙登录凭证已失效,需客户重新登录' + : '微博登录凭证已失效,需客户重新登录', eventType: 'credential_invalidated', }) } @@ -642,20 +684,37 @@ export async function ensureConnectorSessionForTask(task: TaskRow): Promise { await client.query( @@ -683,21 +742,49 @@ export async function ensureConnectorSessionForTask(task: TaskRow): Promise undefined) - if (credentialInvalid) { - return resetTaskForCustomerLogin(task, { - actorType: 'connector', - reason: '平台登录凭证已失效,需客户重新登录', - eventType: 'credential_invalidated', - }) - } throw error } } +async function restoreHuyaSession( + task: TaskRow, + platformUid: string, + nickname: string, + cookies: SemiAutoCredentialCookie[], +) { + if (task.connector_mode !== 'embedded') { + throw createHttpError('当前 Connector 模式不支持从账号级 CK 恢复虎牙会话', { + statusCode: 409, + errorCode: 'huya_connector_restore_unsupported', + }) + } + const expectedUid = String(task.huya_uid || '').trim() + const credentialUid = String(platformUid || '').trim() + if (expectedUid && credentialUid && expectedUid !== credentialUid) { + throw createHttpError('虎牙 CK 与任务账号不一致,请重新登录', { + statusCode: 409, + errorCode: 'huya_credential_account_mismatch', + }) + } + return restoreHuyaSessionFromCredential( + { + taskId: task.id, + orderNo: task.platform_order_id, + platformUid: credentialUid, + nickname, + cookies, + }, + 'embedded', + ) +} + type SemiAutoCandidate = { order_id: number platform_order_id: string @@ -860,7 +947,9 @@ export type BindingRoleComparison = { customerZone: string boundRoleName: string boundRoleId: string + boundRoleIdKind: 'game_role_uid' | 'huya_role_token' | 'missing' boundZone: string + verificationBasis: 'role_name_zone' | 'platform_numeric_uid' | 'manual' message: string } @@ -873,48 +962,49 @@ export function detectServerZone(channel: unknown): string { } /** - * 客户填写角色与平台识别角色必须完全一致才允许提交平台绑定。 - * - * 区服、角色名、角色 ID 三项必须全部存在且一致: - * ① 客户游戏编号 = 虎牙账号 UID,与平台可核对角色 ID 相等; - * ② 角色名按规范化文本相等(忽略空白与大小写差异不能放行改名); - * ③ 平台渠道能解析出区服且与客户所填区服相等。 - * 任一侧缺任一项(含平台只给加密 roleId 且拿不到 UID)判 unknown,转客服核对; - * 任一项不等判 mismatch,不允许提交平台绑定。 + * 虎牙账号 UID 与游戏角色 UID 无关。当前虎牙接口只稳定返回角色名、区服和 + * opaque role token,因此自动放行依据固定为角色名 + 区服。客户角色 UID + * 只作为订单资料留档,除非平台明确返回独立数值角色 UID,否则不参与比对。 */ 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 }, + task: Pick, + binding: { + bindGameRole?: string + bindGameRoleToken?: string + bindGameChannel?: string + platformGameRoleUid?: string + }, ): BindingRoleComparison { const customerRoleName = String(task.customer_game_role || '').trim() const customerRoleId = String(task.customer_game_id || '').trim() const customerZone = resolveServerZone(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 roleToken = String(binding.bindGameRoleToken || '').trim() + const platformRoleUid = String(binding.platformGameRoleUid || '').trim() + const numericPlatformRoleUid = isNumericBindingRoleId(platformRoleUid) ? platformRoleUid : '' const boundZone = detectServerZone(binding.bindGameChannel) const base = { customerRoleName, customerRoleId, customerZone, boundRoleName, - boundRoleId, + boundRoleId: numericPlatformRoleUid || roleToken, + boundRoleIdKind: numericPlatformRoleUid + ? ('game_role_uid' as const) + : roleToken + ? ('huya_role_token' as const) + : ('missing' as const), boundZone, + verificationBasis: numericPlatformRoleUid + ? ('platform_numeric_uid' as const) + : ('role_name_zone' as const), } - const verifiedBoundRoleId = isNumericBindingRoleId(boundRoleId) ? boundRoleId : '' + const policy = getAccountBindingPolicy('huya') const comparison = compareBindingIdentity({ - requiredFields: getAccountBindingPolicy('huya').requiredFields, + requiredFields: numericPlatformRoleUid + ? [...policy.requiredFields, 'roleId'] + : policy.requiredFields, customer: { roleName: customerRoleName, roleId: customerRoleId, @@ -922,16 +1012,15 @@ export function compareBindingRole( }, platform: { roleName: boundRoleName, - roleId: verifiedBoundRoleId, + roleId: numericPlatformRoleUid, serverZone: boundZone, }, }) if (comparison.verdict === 'unknown') { const missing: string[] = [] - if (!customerRoleId) missing.push('客户游戏编号') + if (!customerRoleId) missing.push('客户游戏角色 UID') if (!customerRoleName) missing.push('客户角色名') if (!customerZone) missing.push('客户区服') - if (!verifiedBoundRoleId) missing.push('平台可核对角色ID') if (!boundRoleName) missing.push('平台角色名') if (!boundZone) missing.push('平台区服') return { @@ -941,7 +1030,7 @@ export function compareBindingRole( } } if (comparison.mismatched.includes('roleId')) { - return { ...base, verdict: 'mismatch', message: '两侧角色 ID 不一致,无法提交平台绑定' } + return { ...base, verdict: 'mismatch', message: '两侧游戏角色 UID 不一致,无法提交平台绑定' } } if (comparison.mismatched.includes('roleName')) { return { ...base, verdict: 'mismatch', message: '两侧角色名称不一致,无法提交平台绑定' } @@ -952,7 +1041,9 @@ export function compareBindingRole( return { ...base, verdict: 'match', - message: '两侧区服、角色名称、角色 ID 一致,可提交平台绑定', + message: numericPlatformRoleUid + ? '两侧区服、角色名称、平台角色 UID 一致,可提交平台绑定' + : '角色名称与区服一致,请确认绑定本次待确认角色', } } @@ -966,6 +1057,10 @@ function mapBindingUpdate(session: ConnectorBindingSession) { expired: 'expired', failed: 'failed', } + const legacyRoleId = String(session.bindGameRoleId || '').trim() + const platformGameRoleUid = isNumericBindingRoleId(session.platformGameRoleUid) + ? String(session.platformGameRoleUid || '').trim() + : '' return { status: statusMap[session.status] || 'failed', qrImage: String(session.qrImage || ''), @@ -973,8 +1068,19 @@ function mapBindingUpdate(session: ConnectorBindingSession) { qrUrl: String(session.qrUrl || ''), bindGameAccount: String(session.bindGameAccount || ''), bindGameRole: String(session.bindGameRole || ''), - bindGameRoleId: String(session.bindGameRoleId || ''), + bindGameRoleToken: String( + session.bindGameRoleToken || (isHuyaRoleToken(legacyRoleId) ? legacyRoleId : ''), + ), bindGameChannel: String(session.bindGameChannel || ''), + pendingBindGameAccount: String(session.pendingBindGameAccount || ''), + pendingBindGameRole: String(session.pendingBindGameRole || ''), + pendingBindGameRoleToken: String(session.pendingBindGameRoleToken || ''), + pendingBindGameChannel: String(session.pendingBindGameChannel || ''), + pendingBindGameChangeBindTime: Number(session.pendingChangeBindTime || 0), + pendingBindGameChangeBindDay: Number(session.pendingChangeBindDay || 0), + roleIdentitySource: String(session.roleIdentitySource || ''), + verificationBasis: String(session.verificationBasis || ''), + platformGameRoleUid, hasExistingBinding: session.hasExistingBinding === true, rebindRequested: session.rebindRequested === true, rebindUnchanged: session.rebindUnchanged === true, @@ -996,24 +1102,39 @@ export async function updateBindingTask( actorType: TaskActorType, ) { const mapped = mapBindingUpdate(session) - const roleIdVerified = isNumericBindingRoleId(mapped.bindGameRoleId) + const comparisonRole = mapped.pendingBindGameRole + ? { + bindGameRole: mapped.pendingBindGameRole, + bindGameRoleToken: mapped.pendingBindGameRoleToken, + bindGameChannel: mapped.pendingBindGameChannel, + platformGameRoleUid: '', + } + : { + bindGameRole: mapped.bindGameRole, + bindGameRoleToken: mapped.bindGameRoleToken, + bindGameChannel: mapped.bindGameChannel, + platformGameRoleUid: mapped.platformGameRoleUid, + } + const roleIdVerified = isNumericBindingRoleId(mapped.platformGameRoleUid) const requiresSupport = getAccountBindingPolicy(task.platform).requiresCustomerProfile && - (Boolean(mapped.bindGameRole) || mapped.hasExistingBinding === true) && - !roleIdVerified + mapped.hasExistingBinding === true && + !mapped.bindGameRole const comparison = await withTransaction(async (client) => { const current = await loadTaskForUpdateWithClient(client, task.id) const bindingPolicy = getAccountBindingPolicy(current.platform) const currentComparison: BindingRoleComparison = bindingPolicy.requiresCustomerProfile - ? compareBindingRole(current, mapped) + ? compareBindingRole(current, comparisonRole) : { verdict: 'match', customerRoleName: '', customerRoleId: '', customerZone: '', - boundRoleName: mapped.bindGameRole, - boundRoleId: mapped.bindGameRoleId, - boundZone: mapped.bindGameChannel, + boundRoleName: comparisonRole.bindGameRole || '', + boundRoleId: comparisonRole.bindGameRoleToken || '', + boundRoleIdKind: comparisonRole.bindGameRoleToken ? 'huya_role_token' : 'missing', + boundZone: comparisonRole.bindGameChannel || '', + verificationBasis: 'manual', message: '平台角色绑定状态已确认', } if (current.execution_status === 'completed' || current.execution_status === 'cancelled') { @@ -1027,8 +1148,17 @@ export 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_role_token = CASE WHEN $8 <> '' THEN $8 ELSE bind_game_role_token END, bind_game_channel = CASE WHEN $5 <> '' THEN $5 ELSE bind_game_channel END, + pending_bind_game_account = $9, + pending_bind_game_role = $10, + pending_bind_game_role_token = $11, + pending_bind_game_channel = $12, + pending_bind_game_change_bind_time = $13, + pending_bind_game_change_bind_day = $14, + role_identity_source = CASE WHEN $15 <> '' THEN $15 ELSE role_identity_source END, + verification_basis = CASE WHEN $16 <> '' THEN $16 ELSE verification_basis END, + platform_game_role_uid = CASE WHEN $17 <> '' THEN $17 ELSE platform_game_role_uid END, binding_started_at = CASE WHEN $2 = 'qr_pending' THEN COALESCE(binding_started_at, NOW()) ELSE binding_started_at END, bound_at = CASE WHEN $2 IN ('role_ready', 'confirmed') THEN COALESCE(bound_at, NOW()) ELSE bound_at END, execution_status = $6, @@ -1044,7 +1174,16 @@ export async function updateBindingTask( mapped.bindGameChannel, executionStatus, mapped.message, - mapped.bindGameRoleId, + mapped.bindGameRoleToken, + mapped.pendingBindGameAccount, + mapped.pendingBindGameRole, + mapped.pendingBindGameRoleToken, + mapped.pendingBindGameChannel, + mapped.pendingBindGameChangeBindTime, + mapped.pendingBindGameChangeBindDay, + mapped.roleIdentitySource, + mapped.verificationBasis, + mapped.platformGameRoleUid, ], ) // 轮询会每 2 秒调用一次:只有状态/执行状态变化,或换绑被拒这类关键信号才写事件。 @@ -1064,8 +1203,14 @@ export async function updateBindingTask( detail: { gameAccount: mapped.bindGameAccount, gameRole: mapped.bindGameRole, - gameRoleId: mapped.bindGameRoleId, + gameRoleToken: mapped.bindGameRoleToken, gameChannel: mapped.bindGameChannel, + pendingGameAccount: mapped.pendingBindGameAccount, + pendingGameRole: mapped.pendingBindGameRole, + pendingGameRoleToken: mapped.pendingBindGameRoleToken, + pendingGameChannel: mapped.pendingBindGameChannel, + roleIdentitySource: mapped.roleIdentitySource, + verificationBasis: mapped.verificationBasis, verdict: currentComparison.verdict, rebindRequested: mapped.rebindRequested, rebindUnchanged: mapped.rebindUnchanged, @@ -1091,8 +1236,18 @@ export async function updateBindingTask( qrUrl: mapped.qrUrl, bindGameAccount: mapped.bindGameAccount, bindGameRole: mapped.bindGameRole, - bindGameRoleId: mapped.bindGameRoleId, + bindGameRoleId: '', + bindGameRoleToken: mapped.bindGameRoleToken, bindGameChannel: mapped.bindGameChannel, + pendingBindGameAccount: mapped.pendingBindGameAccount, + pendingBindGameRole: mapped.pendingBindGameRole, + pendingBindGameRoleToken: mapped.pendingBindGameRoleToken, + pendingBindGameChannel: mapped.pendingBindGameChannel, + platformGameRoleUid: mapped.platformGameRoleUid, + pendingChangeBindTime: mapped.pendingBindGameChangeBindTime, + pendingChangeBindDay: mapped.pendingBindGameChangeBindDay, + roleIdentitySource: mapped.roleIdentitySource, + verificationBasis: mapped.verificationBasis, roleIdVerified, requiresSupport, hasExistingBinding: mapped.hasExistingBinding, diff --git a/apps/backend/src/services/semi-auto/semi-auto-task.integration.test.ts b/apps/backend/src/services/semi-auto/semi-auto-task.integration.test.ts index 09a9936b..1147d14b 100644 --- a/apps/backend/src/services/semi-auto/semi-auto-task.integration.test.ts +++ b/apps/backend/src/services/semi-auto/semi-auto-task.integration.test.ts @@ -321,12 +321,33 @@ test( huyaUid: `it-huya-${suffix}`, bindGameAccount: '集成测试虎牙账号', bindGameRole: '集成测试角色', - bindGameRoleId: '1192083858', + bindGameRoleToken: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', bindGameChannel: '安卓(android) · QQ', + roleIdentitySource: 'huya_outer_current', + verificationBasis: 'role_name_zone', }, { eventId: snapshotEventId, eventType: 'semi_auto.task_state' }, ) assert.equal(snapshot.applied, true) + const reusedUidEventId = randomUUID() + await expectErrorCode( + () => + applySemiAutoTaskStateSnapshot( + { + eventId: reusedUidEventId, + taskId, + orderNo, + loginStatus: 'authenticated', + bindingStatus: 'role_ready', + huyaUid: '1199664118656', + platformGameRoleUid: '1199664118656', + bindGameRole: '集成测试角色', + bindGameChannel: '安卓(android) · QQ', + }, + { eventId: reusedUidEventId, eventType: 'semi_auto.task_state' }, + ), + 'semi_auto_snapshot_platform_role_uid_reused', + ) const duplicateSnapshot = await applySemiAutoTaskStateSnapshot( { eventId: snapshotEventId, @@ -342,8 +363,12 @@ test( login_status: string binding_status: string execution_status: string + bind_game_role_token: string + role_identity_source: string + verification_basis: string }>( - `SELECT login_status, binding_status, execution_status + `SELECT login_status, binding_status, execution_status, + bind_game_role_token, role_identity_source, verification_basis FROM semi_auto_tasks WHERE id = $1`, [taskId], ) @@ -351,6 +376,9 @@ test( login_status: 'authenticated', binding_status: 'confirmed', execution_status: 'waiting_operator', + bind_game_role_token: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', + role_identity_source: 'huya_outer_current', + verification_basis: 'role_name_zone', }) } finally { if (orderId > 0) { @@ -748,6 +776,143 @@ test( }, ) +test( + '虎牙数据库 CK 可在进程会话丢失后恢复并生成浏览器注入票据', + { skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false }, + async () => { + process.env.DATABASE_URL = TEST_DATABASE_URL + process.env.ENABLE_DEV_MOCK = '1' + const { closeDb, query, withTransaction } = await import('../../db/client.js') + const { createSemiAutoMock } = await import('../dev-mock/dev-mock-service.js') + const { upsertSemiAutoCredentialWithClient } = await import('./semi-auto-credential-service.js') + const { createAdminBrowserSession, consumeSemiAutoInjectionTicket } = + await import('./semi-auto-task-service.js') + const { huyaNativeConnector } = await import('./huya-native/huya-native-connector.js') + const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}` + const orderNo = `IT-HUYA-RESTORE-${suffix}` + const platformUid = '1686664168' + let orderId = 0 + let configId = 0 + let credentialId = 0 + let adminId = 0 + let restoredSessionId = '' + try { + const admin = await query<{ id: number }>( + `INSERT INTO admin_users (username, password_hash, role, status, created_at, updated_at) + VALUES ($1, 'x', 'support', 'active', NOW(), NOW()) RETURNING id`, + [`it_huya_restore_admin_${suffix}`], + ) + adminId = Number(admin.rows[0]?.id || 0) + const result = await createSemiAutoMock({ + orderNo, + skuName: `虎牙CK恢复-${suffix}`, + quantity: 1, + pageTitle: '虎牙CK恢复集成测试', + connectorMode: 'embedded', + }) + orderId = result.orderId + configId = result.configId + credentialId = await withTransaction((client) => + upsertSemiAutoCredentialWithClient(client, { + platform: 'huya', + source: 'sms', + payload: { + platformUid, + nickname: '虎牙恢复测试', + cookies: [ + { + name: 'yyuid', + value: platformUid, + domain: '.huya.com', + path: '/', + secure: true, + httpOnly: false, + expiresAt: null, + }, + { + name: 'udb_uid', + value: platformUid, + domain: '.huya.com', + path: '/', + secure: true, + httpOnly: false, + expiresAt: null, + }, + { + name: 'udb_cred', + value: `restored-${suffix}`, + domain: '.huya.com', + path: '/', + secure: true, + httpOnly: false, + expiresAt: null, + }, + ], + }, + }), + ) + await query( + `UPDATE semi_auto_tasks + SET credential_id = $2, + connector_session_id = $3, + huya_uid = $4, + login_status = 'authenticated', + binding_status = 'not_started', + execution_status = 'waiting_operator', + updated_at = NOW() + WHERE id = $1`, + [result.taskId, credentialId, `missing-session-${suffix}`, platformUid], + ) + + const ticket = await createAdminBrowserSession(result.taskId, 'https://www.huya.com/', { + userId: adminId, + role: 'support', + displayName: '集成测试客服', + } as never) + const restored = await query<{ + connector_session_id: string + credential_session_restored: number + }>( + `SELECT task.connector_session_id, + COUNT(event.id) FILTER ( + WHERE event.event_type = 'credential_session_restored' + )::int AS credential_session_restored + FROM semi_auto_tasks task + LEFT JOIN semi_auto_task_events event ON event.task_id = task.id + WHERE task.id = $1 + GROUP BY task.connector_session_id`, + [result.taskId], + ) + restoredSessionId = String(restored.rows[0]?.connector_session_id || '') + assert.ok(restoredSessionId) + assert.notEqual(restoredSessionId, `missing-session-${suffix}`) + assert.equal(Number(restored.rows[0]?.credential_session_restored), 1) + + const payload = await consumeSemiAutoInjectionTicket(ticket.ticket) + assert.equal( + payload.cookies.find((cookie) => cookie.name === 'udb_cred')?.value, + `restored-${suffix}`, + ) + } finally { + if (restoredSessionId) { + await huyaNativeConnector.revokeSession(restoredSessionId).catch(() => undefined) + } + if (orderId > 0) await query('DELETE FROM orders WHERE id = $1', [orderId]) + if (credentialId > 0) { + await query('DELETE FROM semi_auto_credentials WHERE id = $1', [credentialId]) + } + if (adminId > 0) { + await query('DELETE FROM admin_users WHERE id = $1', [adminId]) + } + if (configId > 0) { + await query('DELETE FROM manual_fulfillment_configs WHERE id = $1', [configId]) + } + delete process.env.ENABLE_DEV_MOCK + await closeDb() + } + }, +) + test( '微博平台角色绑定事实收敛为等待客服处理', { skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false }, diff --git a/apps/backend/src/types/runtime-config.ts b/apps/backend/src/types/runtime-config.ts index 27accbee..d94459ee 100644 --- a/apps/backend/src/types/runtime-config.ts +++ b/apps/backend/src/types/runtime-config.ts @@ -70,6 +70,8 @@ export type RuntimeConfig = { reconcileSeconds: number huya: { bindActId: number + bindGid: number + bindScene: string outerActId: string roomPid: string } diff --git a/apps/frontend/src/components/admin/SemiAutoTaskHistoryDrawer.tsx b/apps/frontend/src/components/admin/SemiAutoTaskHistoryDrawer.tsx index 7af2dbc0..fd40d1ce 100644 --- a/apps/frontend/src/components/admin/SemiAutoTaskHistoryDrawer.tsx +++ b/apps/frontend/src/components/admin/SemiAutoTaskHistoryDrawer.tsx @@ -723,7 +723,7 @@ function resolveEventSummary(event: SemiAutoTaskHistoryEvent) { if (event.eventType === 'customer_profile_saved') { return [ text(detail.roleName) ? `角色:${text(detail.roleName)}` : '', - text(detail.roleId) ? `编号:${text(detail.roleId)}` : '', + text(detail.roleId) ? `游戏角色 UID:${text(detail.roleId)}` : '', text(detail.serverZone) ? `区服:${text(detail.serverZone)}` : '', ] .filter(Boolean) @@ -732,11 +732,13 @@ function resolveEventSummary(event: SemiAutoTaskHistoryEvent) { if (event.eventType === 'binding_status_changed') { const parts: string[] = [] if (text(detail.gameRole)) { - parts.push( - `绑定角色:${text(detail.gameRole)}${ - text(detail.gameRoleId) ? `(${text(detail.gameRoleId)})` : '' - }`, - ) + parts.push(`当前角色:${text(detail.gameRole)}`) + } + if (text(detail.pendingGameRole)) { + parts.push(`待确认角色:${text(detail.pendingGameRole)}`) + } + if (text(detail.gameRoleToken) || text(detail.pendingGameRoleToken)) { + parts.push('虎牙平台已返回加密角色标识') } if (detail.rebindUnchanged === true) parts.push('平台仍返回原绑定角色') const message = text(detail.message) || text(detail.rebindConfirmMessage) diff --git a/apps/frontend/src/pages/admin/AdminSemiAutoTasksPage.tsx b/apps/frontend/src/pages/admin/AdminSemiAutoTasksPage.tsx index 171b9691..0395e9c7 100644 --- a/apps/frontend/src/pages/admin/AdminSemiAutoTasksPage.tsx +++ b/apps/frontend/src/pages/admin/AdminSemiAutoTasksPage.tsx @@ -483,11 +483,16 @@ export default function AdminSemiAutoTasksPage() { {`绑定:${BINDING_STATUS_LABELS[task.bindingStatus] || task.bindingStatus}`} - {task.bindGameRole || task.bindGameRoleId ? ( + {task.bindGameRole || task.bindGameRoleToken ? ( - {`角色:${task.bindGameRole || '-'}${task.bindGameRoleId ? `(${task.bindGameRoleId})` : '(无角色ID)'}`} + {`当前角色:${task.bindGameRole || '-'}${ + task.bindGameRoleToken ? '(平台加密标识已识别)' : '' + }`} ) : null} + {task.pendingBindGameRole ? ( + {`待确认角色:${task.pendingBindGameRole}`} + ) : null} CK: {task.credentialStatus === 'valid' @@ -770,11 +775,18 @@ export default function AdminSemiAutoTasksPage() { {BINDING_STATUS_LABELS[detail.task.bindingStatus] || detail.task.bindingStatus} - + {detail.task.bindGameRole || '-'} - - {detail.task.bindGameRoleId || detail.task.huyaUid || '-'} + + {detail.task.pendingBindGameRole || '-'} + + + {detail.task.platformGameRoleUid + ? `游戏角色 UID ${detail.task.platformGameRoleUid}` + : detail.task.bindGameRoleToken || detail.task.pendingBindGameRoleToken + ? '已识别的虎牙加密角色标识' + : '-'} {[ @@ -787,7 +799,7 @@ export default function AdminSemiAutoTasksPage() { {detail.task.customerGameRoleName || '-'} - + {detail.task.customerGameRoleId || '-'} diff --git a/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx b/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx index 0827f40c..7a89ec06 100644 --- a/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx +++ b/apps/frontend/src/pages/customer-fulfillment/CustomerFulfillmentPage.tsx @@ -105,8 +105,8 @@ export default function CustomerFulfillmentPage({ [selectedTaskId, tasks], ) const isWeibo = selectedTask?.platform === 'weibo' - // 虎牙流程:登录 → 填写资料(区服/游戏编号/角色名)→ 绑定角色。 - // 三项资料齐全前不生成绑定二维码,避免客户在资料缺失时先绑错角色。 + // 虎牙流程:登录 → 填写资料(区服/游戏角色 UID/角色名)→ 绑定角色。 + // 资料齐全前不生成绑定二维码,避免客户在资料缺失时先绑错角色。 const profileComplete = Boolean( String(selectedTask?.customerServerZone || '').trim() && String(selectedTask?.customerGameRoleId || '').trim() && @@ -400,7 +400,7 @@ export default function CustomerFulfillmentPage({ selectedTask?.platform, ]) - // 进入 role_ready 时补一次绑定详情,保证确认弹窗能拿到两侧角色 ID。 + // 进入 role_ready 时补一次绑定详情,保证确认弹窗能拿到待确认角色。 useEffect(() => { if (!selectedTask || !orderNo || selectedTask.platform !== 'huya') return if (bindingSessionExpired) return @@ -439,10 +439,12 @@ export default function CustomerFulfillmentPage({ if (!bindingInfo?.comparison) return // 换绑后仍是原角色时只展示失败原因,不能自动弹出确认框。 if (bindingInfo.rebindUnchanged) return - // 只有三项完全一致才自动弹出核对框,让客户直接提交平台绑定; + // 只有角色名与区服一致才自动弹出核对框,让客户直接确认平台绑定; // 不一致时不弹框,由下方「重新扫码换绑 / 上一步修改资料」两个按钮处理。 if (bindingInfo.comparison.verdict !== 'match') return - const key = `${selectedTask.id}:${bindingInfo.bindGameRoleId || ''}` + const key = `${selectedTask.id}:${ + bindingInfo.pendingBindGameRoleToken || bindingInfo.bindGameRoleToken || '' + }` if (autoOpenedRoleRef.current === key) return autoOpenedRoleRef.current = key setBindingConfirmOpen(true) @@ -700,7 +702,7 @@ export default function CustomerFulfillmentPage({ } return } - // 只有三项完全一致才打开核对框;不一致由页面按钮引导换绑或修改资料。 + // 只有角色名与区服一致才打开核对框;不一致由页面按钮引导换绑或修改资料。 if (nextBinding?.comparison?.verdict === 'match') { setBindingConfirmOpen(true) } else { @@ -729,7 +731,7 @@ export default function CustomerFulfillmentPage({ message.info('虎牙已受理换绑,正在等待角色生效') return } - message.info(detail || '已扫码,请选好角色后点「已选好角色,提交换绑」') + message.info(detail || '已扫码,请选好角色后点「核对平台角色」') return } if (nextTask.bindingStatus === 'qr_pending') { @@ -784,10 +786,10 @@ export default function CustomerFulfillmentPage({ return } if (nextTask.bindingStatus === 'role_ready') { - message.success('换绑已生效,请核对角色后提交平台绑定') + message.success('已识别本次待确认角色,请核对后再确认绑定') return } - message.info('已向虎牙提交换绑,正在等待角色生效') + message.info('尚未识别到新的待确认角色,请重新选择并刷新') } catch (error) { if (isConnectorSessionExpired(error)) { setBindingSessionExpired(true) @@ -813,7 +815,13 @@ export default function CustomerFulfillmentPage({ ) setBindingInfo(response.data.binding) setBindingConfirmOpen(false) - message.success('已提交平台绑定,等待客服处理') + if (response.data.task.bindingStatus === 'confirmed') { + message.success('平台绑定已确认,等待客服处理') + } else if (response.data.task.bindingStatus === 'failed') { + message.error(response.data.binding?.message || '虎牙未接受本次绑定') + } else { + message.info('虎牙已受理绑定,正在等待角色生效,请稍后刷新') + } } catch (error) { if (isConnectorSessionExpired(error)) { setBindingSessionExpired(true) @@ -869,7 +877,7 @@ export default function CustomerFulfillmentPage({ async function handleSaveProfile() { if (!selectedTask) return if (!profileServerZone.trim() || !profileRoleId.trim() || !profileRoleName.trim()) { - message.warning('请完整填写区服、游戏编号和角色名') + message.warning('请完整填写区服、游戏角色 UID 和角色名') return } if (!SERVER_ZONE_OPTIONS.includes(profileServerZone.trim())) { @@ -877,7 +885,7 @@ export default function CustomerFulfillmentPage({ return } if (!/^\d+$/.test(profileRoleId.trim())) { - message.warning('游戏编号只能是数字') + message.warning('游戏角色 UID 只能是数字') return } setProfileSaving(true) @@ -913,7 +921,7 @@ export default function CustomerFulfillmentPage({ } } - /** 缺角色 ID 时引导客户把订单号发给客服人工核实。 */ + /** 角色信息无法自动核对时引导客户把订单号发给客服。 */ async function copyOrderNoForSupport() { const text = String(orderNo || selectedTask?.orderNo || '').trim() if (!text) { @@ -922,7 +930,7 @@ export default function CustomerFulfillmentPage({ } try { await navigator.clipboard.writeText(text) - message.success('订单号已复制,请联系客服核实角色ID') + message.success('订单号已复制,请联系客服核实角色信息') } catch { message.error('复制失败,请手动记录订单号后联系客服') } @@ -950,15 +958,20 @@ export default function CustomerFulfillmentPage({ profileComplete && ['not_started', 'qr_pending', 'scanned'].includes(selectedTask?.bindingStatus || '') const bindingComparison = bindingInfo?.comparison || null - const bindingRoleId = bindingInfo?.bindGameRoleId || selectedTask?.bindGameRoleId || '' - // 虎牙 gameRole.roleId 是加密串,客户侧统一展示数值 UID(huyaUid)。 - const bindingPendingUid = (() => { - const comparisonId = String(bindingComparison?.boundRoleId || '').trim() - if (/^\d+$/.test(comparisonId)) return comparisonId - const huyaUid = String(selectedTask?.huyaUid || '').trim() - return /^\d+$/.test(huyaUid) ? huyaUid : comparisonId - })() - const bindingRoleName = bindingInfo?.bindGameRole || selectedTask?.bindGameRole || '' + const currentRoleName = bindingInfo?.bindGameRole || selectedTask?.bindGameRole || '' + const pendingRoleName = + bindingInfo?.pendingBindGameRole || selectedTask?.pendingBindGameRole || '' + const pendingRoleToken = + bindingInfo?.pendingBindGameRoleToken || selectedTask?.pendingBindGameRoleToken || '' + const bindingRoleName = pendingRoleName || currentRoleName + const accountUid = String(selectedTask?.huyaUid || '').trim() + const boundRoleIdKind = bindingComparison?.boundRoleIdKind || 'missing' + const boundRoleReference = + boundRoleIdKind === 'game_role_uid' + ? `游戏角色 UID ${bindingComparison?.boundRoleId || '未知'}` + : boundRoleIdKind === 'huya_role_token' + ? '平台已返回加密角色标识(不与游戏角色 UID 混用)' + : '平台未返回可核对角色标识' const rebindUnchanged = bindingInfo?.rebindUnchanged === true // 换绑被虎牙拒绝或未生效时展示失败原因;若客户已把资料改成与平台当前角色一致, // 比对为 match,则回到正常提交流程,不再显示换绑失败。 @@ -969,12 +982,8 @@ export default function CustomerFulfillmentPage({ const bindConfirmState = bindingInfo?.bindConfirmState || 'idle' const bindConfirmRejected = bindConfirmState === 'rejected' const bindConfirmPending = bindConfirmState === 'submitting' || bindConfirmState === 'accepted' - const bindingRoleIdNumeric = /^\d+$/.test(String(bindingPendingUid || bindingRoleId || '').trim()) - // 平台返回了绑定角色但没有可核对的角色ID:提示联系客服,不能直接确认或重新扫码。 - const bindingRequiresSupport = - Boolean(bindingInfo) && - (bindingInfo?.requiresSupport ?? - (Boolean(bindingInfo?.bindGameRole || bindingRoleName) && !bindingRoleIdNumeric)) + // 只有角色名缺失时才需要人工核实;加密 role token 不再冒充客户游戏角色 UID。 + const bindingRequiresSupport = Boolean(bindingInfo?.requiresSupport) // 绑定阶段顶部状态条:按 bindingStatus 显式映射,已确认/已过期/失败不再显示(各自有卡片)。 const comparisonMismatch = selectedTask?.bindingStatus === 'role_ready' && bindingComparison?.verdict === 'mismatch' @@ -1391,9 +1400,22 @@ export default function CustomerFulfillmentPage({
- 绑定角色 - {bindingRoleName || '未识别到角色'} + 虎牙账号 UID + {accountUid || '未获取'}
+
+ 当前绑定角色 + {currentRoleName || '未识别到角色'} +
+ {pendingRoleName ? ( +
+ 本次待确认角色 + + {pendingRoleName} + {pendingRoleToken ? '(平台加密标识已识别)' : ''} + +
+ ) : null} ) : null} @@ -1427,8 +1449,8 @@ export default function CustomerFulfillmentPage({

{profileComplete - ? '第二步:修改资料后会用最新资料重新核对平台角色,三项完全一致才能提交平台绑定。' - : '第二步:请填写游戏角色资料:区服、游戏编号(虎牙账号 UID)与角色名,提交后才能生成绑定二维码。'} + ? '第二步:修改资料后会用最新资料重新核对平台角色;角色名与区服一致后才能确认绑定。' + : '第二步:请填写区服、游戏角色 UID 和角色名。游戏角色 UID 与上方虎牙登录账号 UID 不是同一个编号。'}

) : ( @@ -1873,7 +1894,7 @@ export default function CustomerFulfillmentPage({ >

- 请核对两侧区服、角色名称与角色 ID,三项完全一致才能提交平台绑定。 + 请核对角色名称与区服。游戏角色 UID 单独留档,不会与虎牙登录账号 UID 比对。

@@ -1884,11 +1905,11 @@ export default function CustomerFulfillmentPage({
{bindingComparison?.customerRoleName || '未填写'} - {bindingComparison?.customerRoleId || '未填写角色ID'} + {bindingComparison?.customerRoleId || '未填写游戏角色 UID'}
- 平台识别角色 + {pendingRoleName ? '本次待确认角色' : '平台当前角色'}
{bindingComparison?.boundRoleName || '未识别到角色'} - {bindingPendingUid || '未获取到角色ID'} + {boundRoleReference}
diff --git a/apps/frontend/src/types/admin/semi-auto.ts b/apps/frontend/src/types/admin/semi-auto.ts index 780c3e1e..0e5bf6df 100644 --- a/apps/frontend/src/types/admin/semi-auto.ts +++ b/apps/frontend/src/types/admin/semi-auto.ts @@ -41,7 +41,15 @@ export type SemiAutoTask = { bindGameAccount: string bindGameRole: string bindGameRoleId: string + bindGameRoleToken: string + platformGameRoleUid: string bindGameChannel: string + pendingBindGameAccount: string + pendingBindGameRole: string + pendingBindGameRoleToken: string + pendingBindGameChannel: string + roleIdentitySource: string + verificationBasis: string customerGameRoleId: string customerGameRoleName: string customerServerZone: string diff --git a/apps/frontend/src/types/customer-fulfillment.ts b/apps/frontend/src/types/customer-fulfillment.ts index 77650ac1..c53c5d4c 100644 --- a/apps/frontend/src/types/customer-fulfillment.ts +++ b/apps/frontend/src/types/customer-fulfillment.ts @@ -5,7 +5,9 @@ export type CustomerBindingComparison = { customerZone: string boundRoleName: string boundRoleId: string + boundRoleIdKind: 'game_role_uid' | 'huya_role_token' | 'missing' boundZone: string + verificationBasis: 'role_name_zone' | 'platform_numeric_uid' | 'manual' message: string } @@ -42,7 +44,15 @@ export type CustomerSemiAutoTask = { bindGameAccount: string bindGameRole: string bindGameRoleId: string + bindGameRoleToken: string + platformGameRoleUid: string bindGameChannel: string + pendingBindGameAccount: string + pendingBindGameRole: string + pendingBindGameRoleToken: string + pendingBindGameChannel: string + roleIdentitySource: string + verificationBasis: string customerGameRoleId: string customerGameRoleName: string customerServerZone: string @@ -71,10 +81,19 @@ export type CustomerBindingInfo = { bindGameAccount: string bindGameRole: string bindGameRoleId: string + bindGameRoleToken?: string bindGameChannel: string - /** 平台角色 ID 是否可核对(纯数字);false 时客户页只提示联系客服。 */ + pendingBindGameAccount?: string + pendingBindGameRole?: string + pendingBindGameRoleToken?: string + pendingBindGameChannel?: string + pendingChangeBindTime?: number + pendingChangeBindDay?: number + roleIdentitySource?: 'huya_outer_current' | 'huya_inner_pending' | '' + verificationBasis?: 'role_name_zone' | 'platform_numeric_uid' | 'manual' | '' + /** 平台是否独立返回数值游戏角色 UID;加密 role token 不算。 */ roleIdVerified?: boolean - /** 已绑定角色但缺少可核对角色 ID,需要客服人工核实。 */ + /** 平台未返回角色名等可核对事实,需要客服人工核实。 */ requiresSupport?: boolean hasExistingBinding: boolean rebindRequested: boolean diff --git a/apps/frontend/tests/customer-fulfillment-binding-compare.test.ts b/apps/frontend/tests/customer-fulfillment-binding-compare.test.ts index 58ffd969..2dd8f89c 100644 --- a/apps/frontend/tests/customer-fulfillment-binding-compare.test.ts +++ b/apps/frontend/tests/customer-fulfillment-binding-compare.test.ts @@ -46,16 +46,21 @@ test('登录和绑定专用同步阶段暂停整单轮询', () => { assert.ok(source.includes('}, 10_000)')) }) -test('三项一致才出现提交平台绑定,不一致时展示原因', () => { - assert.ok(source.includes('提交平台绑定')) +test('角色名和区服一致才出现确认绑定,不一致时展示原因', () => { + assert.ok(source.includes('确认绑定此角色')) assert.ok(source.includes("bindingComparison?.verdict === 'match'")) assert.ok(source.includes('两侧角色信息不一致,无法提交平台绑定')) assert.ok(source.includes('customer-binding-modal-error')) }) -test('二维码区提示扫码后会核对平台角色与已填资料', () => { - assert.ok(source.includes('扫码后系统会核对平台角色与已填资料')) - assert.ok(source.includes('三项完全一致才能提交平台绑定')) +test('二维码区明确区分虎牙账号 UID 与游戏角色 UID', () => { + assert.ok(source.includes('扫码后系统会核对待确认角色的名称与区服')) + assert.ok(source.includes('不会用虎牙账号 UID')) + assert.ok(source.includes('游戏角色 UID 与上方虎牙登录账号 UID 不是同一个编号')) + assert.ok(source.includes('本次待确认角色')) + assert.ok(source.includes('虎牙账号 UID')) + assert.ok(!source.includes('const bindingPendingUid')) + assert.ok(!source.includes('const huyaUid = String(selectedTask?.huyaUid')) }) test('换绑流程刷新二维码必须带 forceRebind,避免直接返回已有角色', () => { diff --git a/apps/frontend/tests/customer-fulfillment-rebind-return.test.ts b/apps/frontend/tests/customer-fulfillment-rebind-return.test.ts index a47176d8..b651ab85 100644 --- a/apps/frontend/tests/customer-fulfillment-rebind-return.test.ts +++ b/apps/frontend/tests/customer-fulfillment-rebind-return.test.ts @@ -38,7 +38,7 @@ test('取消直接使用原角色的快捷确认路径', () => { test('点击上一步修改资料会回到第二步并隐藏绑定区', () => { // 步骤条把编辑资料视为第二步,即使资料原本已完整。 assert.ok(source.includes(': profileEditing || !profileComplete')) - assert.ok(source.includes("'第二步:请填写游戏角色资料")) + assert.ok(source.includes("'第二步:请填写区服、游戏角色 UID 和角色名")) assert.ok(source.includes('返回绑定角色')) // 资料步骤隐藏二维码、失败提示和比对操作,避免与第二步混在一起。 assert.ok(source.includes('!profileEditing')) diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml index a725b7e6..48035d67 100644 --- a/docker-compose.dev.yml +++ b/docker-compose.dev.yml @@ -129,6 +129,11 @@ services: KUASHOU_INDUSTRY_RATE_LIMIT_MAX: ${KUASHOU_INDUSTRY_RATE_LIMIT_MAX:-120} # 默认使用 order_site 内置真实 Connector;只有 external 模式才读取远程地址与密钥。 SEMI_AUTO_DEFAULT_CONNECTOR_MODE: ${SEMI_AUTO_DEFAULT_CONNECTOR_MODE:-embedded} + HUYA_BIND_GID: ${HUYA_BIND_GID:-3203} + HUYA_BIND_SCENE: ${HUYA_BIND_SCENE:-undefined} + HUYA_OUTER_ACT_ID: ${HUYA_OUTER_ACT_ID:-17096} + HUYA_BIND_ACT_ID: ${HUYA_BIND_ACT_ID:-9271} + HUYA_ROOM_PID: ${HUYA_ROOM_PID:-1199650619883} SEMI_AUTO_CONNECTOR_BASE_URL: ${SEMI_AUTO_CONNECTOR_BASE_URL:-} SEMI_AUTO_CONNECTOR_API_KEY: ${SEMI_AUTO_CONNECTOR_API_KEY:-} SEMI_AUTO_CONNECTOR_TIMEOUT_MS: ${SEMI_AUTO_CONNECTOR_TIMEOUT_MS:-15000} diff --git a/docker-compose.yml b/docker-compose.yml index 57c50ced..cd08b91f 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -142,6 +142,11 @@ services: SEMI_AUTO_DEFAULT_CONNECTOR_MODE: ${SEMI_AUTO_DEFAULT_CONNECTOR_MODE:-embedded} SEMI_AUTO_CONNECTOR_TIMEOUT_MS: ${SEMI_AUTO_CONNECTOR_TIMEOUT_MS:-15000} SEMI_AUTO_RECONCILE_SECONDS: ${SEMI_AUTO_RECONCILE_SECONDS:-900} + HUYA_BIND_GID: ${HUYA_BIND_GID:-3203} + HUYA_BIND_SCENE: ${HUYA_BIND_SCENE:-undefined} + HUYA_OUTER_ACT_ID: ${HUYA_OUTER_ACT_ID:-17096} + HUYA_BIND_ACT_ID: ${HUYA_BIND_ACT_ID:-9271} + HUYA_ROOM_PID: ${HUYA_ROOM_PID:-1199650619883} LIVE_HUB_PLATFORM_FULFILLMENT_URL: ${LIVE_HUB_PLATFORM_FULFILLMENT_URL:-http://host.docker.internal:8800} PLATFORM_FULFILLMENT_INTEGRATION_KEY: ${PLATFORM_FULFILLMENT_INTEGRATION_KEY:-} logging: *json-log-rotation diff --git a/docs/统一订单履约与财务模型-权威版.md b/docs/统一订单履约与财务模型-权威版.md index b75e1e0f..b437effe 100644 --- a/docs/统一订单履约与财务模型-权威版.md +++ b/docs/统一订单履约与财务模型-权威版.md @@ -3,16 +3,16 @@ type: 权威架构与实施计划 description: 订单、内部 SKU、履约路由、履约执行、商品、成本与财务的唯一权威口径及重构计划。 tags: [订单, 内部SKU, 履约, 商品, 成本, 财务, 迁移] status: authoritative -version: 2.29 -updated_at: 2026-11-18 +version: 2.30 +updated_at: 2026-11-19 --- # 统一订单、履约与财务模型 > 状态:**唯一权威文档**。 > 最后校准:2026-11-18。 -> 生产基线:迁移 `166`。 -> 开发基线:迁移 `172`(仅本地,尚未部署生产)。 +> 生产基线:迁移 `175`(2026-11-19 核对)。 +> 开发基线:迁移 `176`(仅本地,尚未部署生产)。 > > 从本文件生效起,订单、内部 SKU、履约渠道、履约载体、标准商品、成本和财务相关实现, > 只能以本文件为业务口径。其他旧分析只作为历史资料,不再具备设计或验收效力。 @@ -318,23 +318,31 @@ manual fulfillment - 半自动任务必须在 manual 渠道判定、人工配置保存/重匹配或 Carrier 补配成功后按订单项主动物化, 不能依赖客户先打开 `/c/<订单号>` 或客服先打开半自动任务列表。后台和客户页的幂等回填仅作为兜底。 - 虎牙客户页流程固定为「登录 → 填写资料 → 绑定角色 → 客服处理」: - ① 资料三项(区服、游戏编号、角色名)只能在登录成功后保存,未填全时不得生成绑定二维码, + ① 资料三项(区服、游戏角色 UID、角色名)只能在登录成功后保存,未填全时不得生成绑定二维码, 页面状态显示「待客户填写资料」; - ② 游戏编号应填写虎牙账号 UID;平台返回数值角色 ID 时以该 ID 核对,仅返回加密角色 ID 时 - 回退登录账号 UID,两者都拿不到判 `unknown`; - ③ 区服、角色名、角色 ID 三项必须全部存在且一致,`compareBindingRole` 返回 `match` 后才允许 - 「提交平台绑定」;任一项缺失判 `unknown` 转客服核实,任一项不等判 `mismatch` 禁止提交。 + ② 虎牙账号 UID(`huya_uid`)只用于 WUP/RPC 请求身份,与客户填写的游戏角色 UID 没有任何对应关系, + 禁止互相回退或比较; + ③ 虎牙 `gameRole.roleId` 是 40 位加密 opaque token,只保存为平台角色标识,用于判断虎牙前后两次 + 查询是否仍是同一角色,不得展示成游戏角色 UID,也不得与账号 UID 或客户游戏角色 UID 比较; + ④ 当前虎牙接口未稳定返回独立数值游戏角色 UID。自动放行依据固定为角色名与区服: + `compareBindingRole` 仅在 `roleName + serverZone` 一致时返回 `match`;客户游戏角色 UID 只留档, + 除非平台未来明确返回独立数值角色 UID,否则不参与自动比对; + ⑤ 客户确认前必须通过 outer/inner 双路查询得到本次 pending 角色;确认绑定必须先呈现 pending 角色, + 客户明确提交后才调用 `confirmBindActAccount`,写后回查 current 角色与 pending 一致才能进入 + `binding_status = confirmed`。确认请求必须携带页面已核对的角色名、role token 与渠道快照, + Connector 发现 pending 已变化时拒绝写入;轮询和二维码刷新不得自动提交平台写操作。 - 角色不一致时客户页固定提供两个动作:「重新扫码换绑」和「上一步修改资料」。 平台已有旧角色导致首次不一致、扫码绑定后不一致、换绑被虎牙拒绝或未生效时,以重新扫码换绑为主; 换绑后仍不一致时以「上一步修改资料」为主。取消「直接使用原角色」的快捷确认: 客户若想使用平台现有角色,必须返回上一步让资料与平台角色一致后再提交。 - 平台未返回可核对角色 ID 或比对缺项时,只提供「复制订单号联系客服」和「刷新状态」。 + 平台未返回角色名或比对缺项时,只提供「复制订单号联系客服」和「刷新状态」。 - 客户点「上一步修改资料」时清空当前绑定与换绑失败状态:`binding_status` 回到 `not_started`, 清空 `bind_game_*`、`bound_at`、`last_error` 与换绑失败痕迹(`rebindUnchanged`/`rebindConfirmState` 等), 但保留登录状态、`credential_id`、`connector_session_id` 和客户已填资料三项。页面回到第二步并保留资料可编辑, 客户重新「提交资料」后重新识别平台角色、重新生成绑定二维码,不能复用旧的换绑失败状态。 - 登录状态和执行状态保存于 `semi_auto_tasks`,不得写入 `material_json` 作为正式状态。 - `binding_status`、`bind_game_*`、`bind_game_role_id`、`bound_at` 和客户资料三项属于正式绑定流程, + `binding_status`、`bind_game_*`、`bind_game_role_token`、pending 角色、`bound_at` 和客户资料三项 + 属于正式绑定流程, 迁移 `168`、`169` 已落库;绑定确认后执行状态才进入 `waiting_operator`。 - 平台 CK 是账号级凭证,唯一持久化真源为 `semi_auto_credentials`。Cookie 集合按平台 UID 唯一保存, 以未加密 Cookie JSON 写入 `credential_payload_json`,并记录来源、更新时间、健康状态和最近检查错误。 @@ -342,6 +350,9 @@ manual fulfillment - Connector 会话仍是进程内短期缓存,但不再是唯一真源。进程重启、会话过期或实例切换后, 支持恢复的执行器必须从账号级 Cookie JSON 恢复会话;恢复前校验平台 UID, 恢复失败时更新凭证健康状态并要求重新登录。 +- 后台“注入浏览器”必须先生成或恢复当前任务的 Connector 会话,再创建一次性注入票据; + 不得只读取数据库 `credential_status = valid` 就直接要求内存会话存在。虎牙内置 Connector + 必须从账号级 CK 恢复账号 UID、登录 Cookie 和设备身份后继续生成票据。 - 平台明确返回 CK 失效或账号不一致时,当前任务必须退出“已授权”状态,清空当前 Connector 会话并回到 `waiting_customer / waiting_login / not_started`;账号级凭证和历史事件保留用于审计。客服可对该任务 执行“重新发送授权”,重置当前任务并复制客户 `/c/<平台订单号>` 链接,客户重新登录后更新 CK。 @@ -380,8 +391,9 @@ manual fulfillment 不绕过平台风控。发码与挑战原始响应必须记录到集成日志,但日志系统必须继续屏蔽 Cookie、令牌、 验证码等敏感字段。`qr_auth` 和二次短信验证必须明确提示,不得伪装成可完成的图形验证。 - 虎牙客户登录成功后立即保存 CK,但流程继续进入「填写资料 → 绑定角色」,不直接进入等待客服。 - 提交资料后平台账号没有角色时展示绑定二维码;已有角色时与资料比对,三项完全一致才允许提交平台绑定; - 不一致时只能重新扫码换绑或返回上一步修改资料,不能绕过确认门禁直接完成履约。 + 提交资料后平台账号没有角色时展示绑定二维码;扫码后先用双路查询识别 pending 角色, + 角色名与区服一致且客户明确确认后才允许提交平台绑定;不一致时只能重新扫码换绑或返回上一步修改资料, + 不能绕过确认门禁直接完成履约。 - 浏览器扩展复用 live-hub-py 的 `web/extension/huya-exchange-helper`,不新增第二个扩展; 扩展只允许消费一次性注入票据,页面不得直接读取 CK。 - 客服完成半自动任务必须与 `confirmManualFulfillment` 在同一数据库事务中提交: @@ -390,7 +402,8 @@ manual fulfillment - 半自动履约状态采用与斗鱼领取一致的同步原则:客户操作、Connector 回调和后台操作都是状态快照输入, 统一由一个状态收敛服务在任务行锁内写入正式字段并追加事件;多个入口不得各自拼接或覆盖状态。 - 账号绑定能力由平台声明,不由页面或业务服务按平台散落判断。虎牙、斗鱼、微博均为 `game_role`: - 虎牙必需字段 `roleName / roleId / serverZone`,由 order_site 查询、客户比对确认和提交换绑; + 虎牙必需字段为 `roleName / serverZone`;平台若未来明确返回独立数值游戏角色 UID,才额外启用 + `roleId` 核验,`gameRole.roleId` 加密 token 本身不参与客户资料比对; 斗鱼必需字段 `roleName / serverZone`,由 live-hub 查询和提交换绑; 微博必需字段 `roleName`,由 order_site 查询,微信/QQ 扫码完成绑定或换绑,不要求客户重复填写角色资料。 公共策略还必须声明 `confirmationMode` 与 `rebindMode`:虎牙、斗鱼为客户资料比对确认, @@ -720,8 +733,9 @@ has_active_cost ``` - 虎牙三步进度固定为「登录虎牙账号 → 填写游戏资料 → 绑定游戏角色」,当前步骤高亮,已完成为勾选。 -- 登录成功后才展示资料表单;资料三项(区服 / 游戏编号 / 角色名)未填全时不展示绑定二维码。 -- 绑定角色页展示平台角色与客户资料的逐项对照:三项完全一致才出现「提交平台绑定」; +- 登录成功后才展示资料表单;资料三项(区服 / 游戏角色 UID / 角色名)未填全时不展示绑定二维码。 +- 绑定角色页分别展示虎牙账号 UID、当前平台角色、本次待确认角色与客户资料;角色名和区服一致才允许确认绑定, + 客户游戏角色 UID 不与虎牙账号 UID 或平台加密 role token 比对; 不一致时固定显示「重新扫码换绑」「上一步修改资料」,换绑后仍不一致时以修改资料为主。 - 微博登录成功后直接展示微信/QQ 绑定入口;平台返回已绑定角色时直接进入等待客服, 未绑定时展示扫码二维码,扫码后重新读取平台角色,角色名发生变化才视为换绑成功。 @@ -1147,7 +1161,7 @@ docs/archive/ ## 十三、当前下一步 -截至 2026-11-18,生产基线为 `166`,集成分支开发基线为 `172`。迁移 `152` 保护订单来源快照, +截至 2026-11-19,生产基线为 `175`,当前开发基线为 `176`。迁移 `152` 保护订单来源快照, 迁移 `158–160` 收口寄卖登记人同步、寄卖平台与自动匹配设置; 迁移 `161` 一次建立人工渠道半自动任务、内置 Connector 默认值、账号级 Cookie JSON 凭证、 任务凭证引用和最终约束;迁移 `162` 建立履约待办四桶只读投影、补载体专用索引和新单优先扫描口径。 @@ -1161,12 +1175,17 @@ docs/archive/ 迁移 `166` 让接单平台路由支持动态模板匹配,清理历史伪造 key 和草稿商品,并拒绝对不存在模板 的非空 `workRuleKey` 写入。 迁移 `167` 清理待判定履约记录对历史假草稿商品的残留引用,并增加履约商品关联闸门。 -迁移 `168` 为半自动任务增加可核对的绑定角色 ID(`bind_game_role_id`)。 +迁移 `168` 曾新增 `bind_game_role_id`,后续生产事实证实现行虎牙返回的是加密 role token; +迁移 `176` 将其语义拆分并冻结旧字段,新增 `bind_game_role_token`、`platform_game_role_uid`、 +pending 角色快照、`role_identity_source` 与 `verification_basis`。 迁移 `169` 增加客户游戏角色资料三项(`customer_game_role_name` / `customer_game_role_id` / `customer_game_server_zone`),并允许从工单素材回退合并;客户页流程收敛为 「登录 → 填写资料 → 绑定角色」,资料未填全不得生成绑定二维码。 迁移 `170` 增加半自动全链路报文日志,客户页、管理端和外部 Connector 共用同一追踪口径; -角色比对仍以区服、角色名、角色 ID 三项完全一致作为「提交平台绑定」的唯一放行条件。 +虎牙角色自动比对改为角色名与区服;账号 UID、加密 role token、客户游戏角色 UID 三类身份禁止混用。 +只读审计命令为 `npm run audit:huya-binding-identity -- --strict`。历史 `legacy_*` 留档只用于追溯, +当前字段出现账号 UID 复用、非法 role token、非法平台角色 UID,或平台角色 UID 由账号 UID +回填时,严格审计必须失败。 迁移 `171` 建立斗鱼客户领取、live-hub 事务 Outbox/Inbox 和绑定状态安全投影。 迁移 `172` 将 order_site → live-hub 订单事件升级为订单项快照契约,增加配置停用/订单关闭收敛、 稳定去重指纹和 `live_state_version`;live-hub 同步增加 `next_allocate_at`、即时选号唤醒与 @@ -1184,6 +1203,7 @@ docs/archive/ 6. 半自动平台负责客户登录、账号 CK 获取和游戏角色绑定;微博支持手机号登录、易盾二次验证、 完整域名 Cookie 保存、会话恢复、游戏角色查询和微信/QQ 扫码绑定;虎牙支持客户手动触发的 短信验证码登录和扫码登录。 - 虎牙客户登录后必须先填写区服 / 游戏编号 / 角色名,再进入绑定;三项与平台角色完全一致 - 才能提交平台绑定,不一致时只能重新扫码换绑或返回上一步修改资料,不提供直接使用原角色的快捷确认。 + 虎牙客户登录后必须先填写区服 / 游戏角色 UID / 角色名,再进入绑定;虎牙账号 UID 只用于登录请求, + 游戏角色 UID 只作为客户资料留档。角色名与区服一致后,客户确认本次 pending 角色才可提交平台绑定; + 不一致时只能重新扫码换绑或返回上一步修改资料,不提供直接使用原角色的快捷确认。 7. 观察期结束后,再单独发布兼容表、旧脚本别名和 `legacy_*` 字段的删除迁移。