修复(半自动履约): 拆分虎牙账号与角色身份并恢复CK注入

This commit is contained in:
yml
2026-11-19 14:41:57 +08:00
parent 7f74772dab
commit b9dadf2e02
36 changed files with 2208 additions and 878 deletions
+1
View File
@@ -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",
@@ -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<AuditRow>(`
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
})
+2
View File
@@ -69,6 +69,8 @@ export function createDefaultRuntimeConfig(projectRoot: string): RuntimeConfig {
reconcileSeconds: 900,
huya: {
bindActId: 9271,
bindGid: 3203,
bindScene: 'undefined',
outerActId: '17096',
roomPid: '1199650619883',
},
+2
View File
@@ -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']),
@@ -208,8 +208,11 @@ function createRuntimeConfig(overrides: Record<string, unknown> = {}): RuntimeCo
connectorBaseUrl: '',
connectorApiKey: '',
connectorTimeoutMs: 15000,
reconcileSeconds: 900,
huya: {
bindActId: 9271,
bindGid: 3203,
bindScene: 'undefined',
outerActId: '17096',
roomPid: '1199650619883',
},
@@ -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或人工';
@@ -57,6 +57,11 @@ const TRACE_STATE_KEYS = [
'bindEffectDeadlineMs',
'bindGameRole',
'bindGameRoleId',
'bindGameRoleToken',
'pendingBindGameRole',
'pendingBindGameRoleToken',
'roleIdentitySource',
'verificationBasis',
'huyaUid',
'lastError',
'isBindAccount',
@@ -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')
@@ -28,7 +28,8 @@ const POLICIES: Record<AccountBindingPlatform, AccountBindingPolicy> = {
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/',
@@ -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())
}
@@ -18,9 +18,11 @@ test('浏览器注入票据按 Mock 前缀选择 Connector', () => {
test('创建登录会话按真实 Connector 协议发送蛇形字段', async () => {
const originalFetch = globalThis.fetch
let requestUrl = ''
let requestMethod = ''
let requestBody: Record<string, unknown> = {}
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<string, unknown>
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<string, unknown> = {}
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<string, unknown>
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<string, unknown> = {}
globalThis.fetch = (async (url: string | URL | Request, init?: RequestInit) => {
requestUrl = String(url)
requestBody = JSON.parse(String(init?.body || '{}')) as Record<string, unknown>
return new Response(
JSON.stringify({
sessionId: 'session-1',
status: '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
}
})
@@ -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<ConnectorBindingSession> {
if (mode === 'embedded') return huyaNativeConnector.confirmBinding(sessionId, options)
return callConnector<ConnectorBindingSession>(
`/api/internal/huya-semi-auto/sessions/${encodeURIComponent(sessionId)}/binding/confirm`,
{
method: 'POST',
body: 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<ConnectorBindingSession> {
if (mode === 'embedded') return huyaNativeConnector.submitRebind(sessionId)
return callConnector<ConnectorBindingSession>(
`/api/internal/huya-semi-auto/sessions/${encodeURIComponent(sessionId)}/binding/confirm`,
{ method: 'POST', body: { rebind: true } },
`/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<ConnectorLoginSession> {
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'
@@ -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,
)
})
@@ -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, '残留角色')
})
File diff suppressed because it is too large Load Diff
@@ -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('<html></html>', {
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({
@@ -620,6 +620,7 @@ export class HuyaRpcClient {
uid: number
cookie: string
bindActId: number
gid?: number
outerActId: number
gameAuthScene?: string
}): Promise<HuyaLiveLinkResponse | null> {
@@ -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, '')
@@ -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<string, unknown> = {}
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<BindingStatus>([
'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<T extends string>(value: unknown, allowed: Set<T>, 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 (
@@ -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区' }),
/请完整填写区服/,
)
})
@@ -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)
@@ -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<Task
// 进程重启或多实例切换后,内存会话会丢失;下面用已保存的账号 CK 恢复。
}
}
if (task.platform !== 'weibo' || !task.credential_id) return task
if (!task.credential_id) return task
const credential = await loadSemiAutoCredential(task.credential_id)
if (!credential || credential.platform !== 'weibo') return task
if (
!credential ||
credential.platform !== task.platform ||
credential.status === 'invalid' ||
credential.status === 'error' ||
credential.cookies.length === 0
) {
return task
}
if (task.platform === 'huya' && task.connector_mode !== 'embedded') return task
try {
const session = await restoreWeiboSessionFromCredential(
{
taskId: task.id,
orderNo: task.platform_order_id,
platformUid: credential.platformUid,
nickname: credential.nickname,
cookies: credential.cookies,
},
task.connector_mode,
)
const session =
task.platform === 'weibo'
? await restoreWeiboSessionFromCredential(
{
taskId: task.id,
orderNo: task.platform_order_id,
platformUid: credential.platformUid,
nickname: credential.nickname,
cookies: credential.cookies,
},
task.connector_mode,
)
: await restoreHuyaSession(
task,
credential.platformUid,
credential.nickname,
credential.cookies,
)
await markSemiAutoCredentialCheck(task.credential_id, { status: 'valid' })
await withTransaction(async (client) => {
await client.query(
@@ -683,21 +742,49 @@ export async function ensureConnectorSessionForTask(task: TaskRow): Promise<Task
return loadTask(task.id)
} catch (error) {
const credentialInvalid = isInvalidCredentialError(error)
if (credentialInvalid) {
return (await resetTaskForInvalidCredential(task, error)) || task
}
await markSemiAutoCredentialCheck(task.credential_id, {
status: credentialInvalid ? 'invalid' : 'error',
status: 'error',
error: error instanceof Error ? error.message : String(error),
}).catch(() => 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<TaskRow, 'customer_game_id' | 'customer_game_role' | 'customer_game_server_zone'>,
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,
@@ -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 },
+2
View File
@@ -70,6 +70,8 @@ export type RuntimeConfig = {
reconcileSeconds: number
huya: {
bindActId: number
bindGid: number
bindScene: string
outerActId: string
roomPid: string
}