完善半自动真实履约链路及虎牙账号资料保存
This commit is contained in:
@@ -157,6 +157,10 @@ function extractInt(value: unknown): number {
|
||||
return Number.isFinite(parsed) && parsed > 0 ? parsed : 0
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error)
|
||||
}
|
||||
|
||||
function readString(value: unknown): string {
|
||||
return String(value ?? '').trim()
|
||||
}
|
||||
@@ -680,13 +684,13 @@ export class HuyaNativeConnector {
|
||||
errorCode: 'huya_livelink_param_failed',
|
||||
})
|
||||
}
|
||||
const profileResponse = await rpc.getUserProfileBatch({
|
||||
const profile = await rpc.getUserProfile({
|
||||
uid: session.uid,
|
||||
cookie: session.cookie,
|
||||
targetUids: [session.uid],
|
||||
targetUid: session.uid,
|
||||
})
|
||||
const profile = profileResponse?.profiles[0]
|
||||
const nickname = profile?.nick || profile?.passport || session.nickname
|
||||
session.nickname = nickname
|
||||
const avatar = profile?.avatar || ''
|
||||
const redirectUrl =
|
||||
'https://zt.huya.com/b02faae1/pc/index.html' +
|
||||
@@ -972,7 +976,7 @@ export class HuyaNativeConnector {
|
||||
data.username ??
|
||||
cookieValue(responseCookie, 'udb_passport'),
|
||||
) || ''
|
||||
const nickname = readString(data.nickname ?? data.nickName ?? data.nick ?? username) || username
|
||||
let nickname = readString(data.nickname ?? data.nickName ?? data.nick ?? username) || username
|
||||
session.deviceInfo.sdid = session.deviceInfo.sdid || session.sdid
|
||||
session.deviceInfo.hdid = session.deviceInfo.hdid || session.hdid
|
||||
try {
|
||||
@@ -1005,6 +1009,23 @@ export class HuyaNativeConnector {
|
||||
qimeiFeature: qimeiFeatureFromDeviceProfile(session.deviceInfo),
|
||||
})
|
||||
session.uid = uid
|
||||
const profile = await new HuyaRpcClient({
|
||||
fetchImpl: this.fetchImpl,
|
||||
timeoutMs: this.rpcTimeoutMs,
|
||||
})
|
||||
.getUserProfile({
|
||||
uid,
|
||||
cookie: session.cookie,
|
||||
targetUid: uid,
|
||||
})
|
||||
.catch((error) => {
|
||||
logWarn('huya/profile', '登录后查询虎牙用户资料失败,回退登录返回昵称', {
|
||||
uid,
|
||||
error: errorMessage(error),
|
||||
})
|
||||
return null
|
||||
})
|
||||
nickname = readString(profile?.nick || profile?.passport || nickname) || nickname
|
||||
session.nickname = nickname
|
||||
session.status = 'authenticated'
|
||||
session.smsSessionData = ''
|
||||
|
||||
@@ -8,6 +8,7 @@ import { buildHuyaLoginContext, ensureHuyaWebCookieIdentity, x64hash128 } from '
|
||||
import { HuyaNativeConnector } from './huya-native-connector.js'
|
||||
import { detectHuyaSliderDistance } from './huya-sms-role.js'
|
||||
import { hasExistingHuyaBinding, parseBindStruct } from './huya-rpc.js'
|
||||
import { TAF_TYPE, TafWriter } from './taf.js'
|
||||
|
||||
const BIND_RESP_HEX =
|
||||
'0a0100c816002a0001100120013a060016002602717136004612e6b3aae6958fe6849fe' +
|
||||
@@ -15,6 +16,40 @@ const BIND_RESP_HEX =
|
||||
'802604e6898b51360be88bb9e69e9c28694f53294600560066000b526a2595806c0b36' +
|
||||
'0ce5928ce5b9b3e7b2bee88bb1460050070b'
|
||||
|
||||
function buildHuyaProfileResponse(input: {
|
||||
uid: number
|
||||
nickname: string
|
||||
avatar?: string
|
||||
passport?: string
|
||||
}): Buffer {
|
||||
const profileWriter = new TafWriter()
|
||||
profileWriter.writeStruct(0, (writer) => {
|
||||
writer.writeInt64(0, input.uid)
|
||||
writer.writeString(1, input.nickname)
|
||||
writer.writeString(2, input.avatar || '')
|
||||
writer.writeString(17, input.passport || String(input.uid))
|
||||
})
|
||||
|
||||
const dataWriter = new TafWriter()
|
||||
dataWriter.writeHead(0, TAF_TYPE.MAP)
|
||||
dataWriter.writeInt32(0, 1)
|
||||
dataWriter.writeString(0, 'tRsp')
|
||||
dataWriter.writeBytes(1, profileWriter.toBuffer())
|
||||
|
||||
const responseWriter = new TafWriter()
|
||||
responseWriter.writeInt16(1, 3)
|
||||
responseWriter.writeInt8(2, 0)
|
||||
responseWriter.writeInt32(3, 0)
|
||||
responseWriter.writeInt32(4, 1)
|
||||
responseWriter.writeString(5, 'huyauserui')
|
||||
responseWriter.writeString(6, 'getUserProfile')
|
||||
responseWriter.writeBytes(7, dataWriter.toBuffer())
|
||||
responseWriter.writeInt32(8, 3000)
|
||||
responseWriter.writeMap(9, {})
|
||||
responseWriter.writeMap(10, {})
|
||||
return responseWriter.toBuffer()
|
||||
}
|
||||
|
||||
test('QIMEI x64hash128 与 SDK 向量一致', () => {
|
||||
assert.equal(x64hash128('', 31), '24700f9f1986800ab4fcc880530dd0ed')
|
||||
assert.equal(x64hash128('a', 31), 'f8b09930c1df727ef75677a1d6ae5bd6')
|
||||
@@ -182,6 +217,7 @@ test('已绑定账号和角色时直接使用当前绑定,不再发起换绑',
|
||||
test('内置 Connector 完成扫码、CK 兑换和一次性票据且不泄露 CK', async () => {
|
||||
const requests: Array<{ url: string; body: string; headers: Record<string, string> }> = []
|
||||
let stage = 0
|
||||
let profileCalls = 0
|
||||
let now = Date.now()
|
||||
const fetchImpl = (async (urlInput: string | URL | Request, init?: RequestInit) => {
|
||||
const url = String(urlInput)
|
||||
@@ -238,6 +274,18 @@ test('内置 Connector 完成扫码、CK 兑换和一次性票据且不泄露 CK
|
||||
headers: { 'content-type': 'application/json' },
|
||||
})
|
||||
}
|
||||
if (url.startsWith('https://cdnws.api.huya.com/')) {
|
||||
profileCalls += 1
|
||||
return new Response(
|
||||
buildHuyaProfileResponse({
|
||||
uid: 123456,
|
||||
nickname: '扫码资料昵称',
|
||||
avatar: 'https://example.com/avatar.jpg',
|
||||
passport: 'hy_123456',
|
||||
}),
|
||||
{ status: 200, headers: { 'content-type': 'application/octet-stream' } },
|
||||
)
|
||||
}
|
||||
throw new Error(`unexpected request: ${url}`)
|
||||
}) as typeof fetch
|
||||
|
||||
@@ -285,13 +333,14 @@ test('内置 Connector 完成扫码、CK 兑换和一次性票据且不泄露 CK
|
||||
const authenticated = await connector.getLoginSession(created.sessionId)
|
||||
assert.equal(authenticated.status, 'authenticated')
|
||||
assert.equal(authenticated.huyaUid, '123456')
|
||||
assert.equal(authenticated.nickname, '测试用户')
|
||||
assert.equal(authenticated.nickname, '扫码资料昵称')
|
||||
assert.equal(profileCalls, 1)
|
||||
assert.equal(JSON.stringify(authenticated).includes('secret-biztoken'), false)
|
||||
assert.equal(JSON.stringify(authenticated).includes('server-issued-cred'), false)
|
||||
|
||||
const credential = connector.exportSessionCredential(created.sessionId)
|
||||
assert.equal(credential.platformUid, '123456')
|
||||
assert.equal(credential.nickname, '测试用户')
|
||||
assert.equal(credential.nickname, '扫码资料昵称')
|
||||
assert.equal(
|
||||
credential.cookies.find((item) => item.name === 'udb_cred')?.value,
|
||||
'server-issued-cred',
|
||||
@@ -321,6 +370,7 @@ test('内置 Connector 完成扫码、CK 兑换和一次性票据且不泄露 CK
|
||||
|
||||
test('内置 Connector 手动发码并完成短信登录后保存账号 CK', async () => {
|
||||
const requests: Array<{ url: string; body: string }> = []
|
||||
let profileCalls = 0
|
||||
const fetchImpl = (async (urlInput: string | URL | Request, init?: RequestInit) => {
|
||||
const url = String(urlInput)
|
||||
const body = typeof init?.body === 'string' ? init.body : ''
|
||||
@@ -382,6 +432,17 @@ test('内置 Connector 手动发码并完成短信登录后保存账号 CK', asy
|
||||
headers: { 'content-type': 'application/json' },
|
||||
})
|
||||
}
|
||||
if (url.startsWith('https://cdnws.api.huya.com/')) {
|
||||
profileCalls += 1
|
||||
return new Response(
|
||||
buildHuyaProfileResponse({
|
||||
uid: 987654,
|
||||
nickname: '短信资料昵称',
|
||||
passport: 'hy_987654',
|
||||
}),
|
||||
{ status: 200, headers: { 'content-type': 'application/octet-stream' } },
|
||||
)
|
||||
}
|
||||
throw new Error(`unexpected request: ${url}`)
|
||||
}) as typeof fetch
|
||||
|
||||
@@ -428,11 +489,13 @@ test('内置 Connector 手动发码并完成短信登录后保存账号 CK', asy
|
||||
})
|
||||
assert.equal(authenticated.status, 'authenticated')
|
||||
assert.equal(authenticated.huyaUid, '987654')
|
||||
assert.equal(authenticated.nickname, '短信登录用户')
|
||||
assert.equal(authenticated.nickname, '短信资料昵称')
|
||||
assert.equal(profileCalls, 1)
|
||||
assert.equal(JSON.stringify(authenticated).includes('sms-session-secret'), false)
|
||||
|
||||
const credential = connector.exportSessionCredential(sent.session.sessionId)
|
||||
assert.equal(credential.platformUid, '987654')
|
||||
assert.equal(credential.nickname, '短信资料昵称')
|
||||
assert.equal(
|
||||
credential.cookies.find((item) => item.name === 'udb_cred')?.value,
|
||||
'server-issued-sms-cred',
|
||||
|
||||
@@ -421,6 +421,10 @@ function parseProfile(reader: TafReader): HuyaUserProfile {
|
||||
return { uid, nick, avatar, passport }
|
||||
}
|
||||
|
||||
function parseProfileResponse(reader: TafReader): HuyaUserProfile | null {
|
||||
return parseProfile(reader)
|
||||
}
|
||||
|
||||
function parseProfileBatch(reader: TafReader): HuyaUserProfileResponse {
|
||||
const profiles =
|
||||
reader.readList<HuyaUserProfile>(0, (itemReader, dataType) => {
|
||||
@@ -543,6 +547,26 @@ export class HuyaRpcClient {
|
||||
return response ? readWupStruct(response, parseProfileBatch) : null
|
||||
}
|
||||
|
||||
async getUserProfile(input: {
|
||||
uid: number
|
||||
cookie: string
|
||||
targetUid: number
|
||||
}): Promise<HuyaUserProfile | null> {
|
||||
const targetUid = Math.trunc(input.targetUid)
|
||||
if (!(targetUid > 0)) return null
|
||||
const response = await this.callRpc(
|
||||
'huyauserui',
|
||||
'getUserProfile',
|
||||
input.uid,
|
||||
input.cookie,
|
||||
(writer) => {
|
||||
this.writeActivityUser(writer, 0, input.cookie)
|
||||
writer.writeInt64(1, targetUid)
|
||||
},
|
||||
)
|
||||
return response ? readWupStruct(response, parseProfileResponse) : null
|
||||
}
|
||||
|
||||
private async callRpc(
|
||||
servant: string,
|
||||
func: string,
|
||||
|
||||
@@ -523,13 +523,25 @@ type SemiAutoCandidate = {
|
||||
quantity: number
|
||||
}
|
||||
|
||||
async function insertMissingSemiAutoTasksWithClient(client: PoolClient, orderNo?: string) {
|
||||
async function insertMissingSemiAutoTasksWithClient(
|
||||
client: PoolClient,
|
||||
orderNo?: string,
|
||||
orderItemIds?: number[],
|
||||
) {
|
||||
const params: unknown[] = []
|
||||
let orderFilter = ''
|
||||
const filters: string[] = []
|
||||
if (orderNo) {
|
||||
params.push(orderNo)
|
||||
orderFilter = 'AND o.platform_order_id = $1'
|
||||
filters.push(`o.platform_order_id = $${params.length}`)
|
||||
}
|
||||
const normalizedItemIds = [
|
||||
...new Set((orderItemIds || []).map(Number).filter((id) => Number.isInteger(id) && id > 0)),
|
||||
]
|
||||
if (normalizedItemIds.length > 0) {
|
||||
params.push(normalizedItemIds)
|
||||
filters.push(`oi.id = ANY($${params.length}::bigint[])`)
|
||||
}
|
||||
const itemFilter = filters.length > 0 ? `AND ${filters.join(' AND ')}` : ''
|
||||
const candidates = await client.query<SemiAutoCandidate>(
|
||||
`
|
||||
SELECT
|
||||
@@ -549,7 +561,7 @@ async function insertMissingSemiAutoTasksWithClient(client: PoolClient, orderNo?
|
||||
AND cfg.enabled = TRUE
|
||||
AND cfg.semi_auto_enabled = TRUE
|
||||
AND cfg.semi_auto_platform IN ('huya', 'weibo')
|
||||
${orderFilter}
|
||||
${itemFilter}
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM semi_auto_tasks existing WHERE existing.order_item_id = oi.id
|
||||
)
|
||||
@@ -605,6 +617,24 @@ export async function ensureSemiAutoTasksForOrder(orderNoInput: unknown) {
|
||||
return { orderNo, createdIds: result.createdIds }
|
||||
}
|
||||
|
||||
export async function ensureSemiAutoTasksForOrderItems(input: unknown[]) {
|
||||
const orderItemIds = [
|
||||
...new Set(
|
||||
(Array.isArray(input) ? input : [])
|
||||
.map(Number)
|
||||
.filter((id) => Number.isInteger(id) && id > 0),
|
||||
),
|
||||
]
|
||||
if (orderItemIds.length === 0) return { createdIds: [], orderIds: [] }
|
||||
const result = await withTransaction((client) =>
|
||||
insertMissingSemiAutoTasksWithClient(client, undefined, orderItemIds),
|
||||
)
|
||||
for (const orderId of result.orderIds) {
|
||||
publishAdminOrderRealtimeChange(orderId)
|
||||
}
|
||||
return { createdIds: result.createdIds, orderIds: result.orderIds }
|
||||
}
|
||||
|
||||
/**
|
||||
* 后台列表读取前的幂等回填。
|
||||
*
|
||||
|
||||
@@ -14,7 +14,7 @@ test(
|
||||
{ skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false },
|
||||
async () => {
|
||||
process.env.DATABASE_URL = TEST_DATABASE_URL
|
||||
const { closeDb, query } = await import('../../db/client.js')
|
||||
const { closeDb, query, withTransaction } = await import('../../db/client.js')
|
||||
const {
|
||||
ensureSemiAutoTasksForOrder,
|
||||
exportAdminSemiAutoCredential,
|
||||
@@ -164,7 +164,10 @@ test(
|
||||
reauthorized.events.some((event) => event.eventType === 'customer_reauth_requested'),
|
||||
)
|
||||
} finally {
|
||||
if (orderId > 0) await query('DELETE FROM orders WHERE id = $1', [orderId])
|
||||
if (orderId > 0) {
|
||||
await query('DELETE FROM order_source_snapshots WHERE order_id = $1', [orderId])
|
||||
await query('DELETE FROM orders WHERE id = $1', [orderId])
|
||||
}
|
||||
if (credentialId > 0) {
|
||||
await query('DELETE FROM semi_auto_credentials WHERE id = $1', [credentialId])
|
||||
}
|
||||
@@ -644,14 +647,19 @@ test(
|
||||
assert.equal(tasks[0]?.loginStatus, 'authenticated')
|
||||
assert.equal(tasks[0]?.executionStatus, 'waiting_operator')
|
||||
assert.equal(tasks[0]?.credentialSource, 'sms')
|
||||
assert.ok(tasks[0]?.huyaUid)
|
||||
assert.equal(tasks[0]?.platformNickname, 'Mock虎牙用户')
|
||||
|
||||
const stored = await query<{
|
||||
id: number
|
||||
credential_source: string
|
||||
credential_payload_json: string
|
||||
platform_nickname: string
|
||||
huya_uid: string
|
||||
}>(
|
||||
`SELECT credential.id, credential.credential_source,
|
||||
credential.credential_payload_json
|
||||
credential.credential_payload_json,
|
||||
task.platform_nickname, task.huya_uid
|
||||
FROM semi_auto_tasks task
|
||||
JOIN semi_auto_credentials credential ON credential.id = task.credential_id
|
||||
WHERE task.id = $1`,
|
||||
@@ -661,6 +669,8 @@ test(
|
||||
assert.ok(credentialId > 0)
|
||||
assert.equal(stored.rows[0]?.credential_source, 'sms')
|
||||
assert.match(stored.rows[0]?.credential_payload_json || '', /mock_huya_session/)
|
||||
assert.equal(stored.rows[0]?.platform_nickname, 'Mock虎牙用户')
|
||||
assert.equal(stored.rows[0]?.huya_uid, tasks[0]?.huyaUid)
|
||||
} finally {
|
||||
if (orderId > 0) await query('DELETE FROM orders WHERE id = $1', [orderId])
|
||||
if (configId > 0) {
|
||||
@@ -675,3 +685,84 @@ test(
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
test(
|
||||
'真实订单入口可生成 manual 履约和半自动任务',
|
||||
{ skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false },
|
||||
async () => {
|
||||
process.env.DATABASE_URL = TEST_DATABASE_URL
|
||||
process.env.ENABLE_DEV_MOCK = '1'
|
||||
const { closeDb, query, withTransaction } = await import('../../db/client.js')
|
||||
const { createSemiAutoIntegrationMock } = await import('../dev-mock/dev-mock-service.js')
|
||||
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
|
||||
const orderNo = `IT-INTEGRATION-SA-${suffix}`
|
||||
let orderId = 0
|
||||
let configId = 0
|
||||
let mappingId = 0
|
||||
try {
|
||||
const result = await createSemiAutoIntegrationMock({
|
||||
platform: 'huya',
|
||||
orderNo,
|
||||
skuName: `真实链路虎牙测试-${suffix}`,
|
||||
quantity: 1,
|
||||
connectorMode: 'embedded',
|
||||
})
|
||||
orderId = result.orderId
|
||||
configId = result.configId
|
||||
mappingId = result.mappingId
|
||||
assert.equal(result.pipeline, 'order_service')
|
||||
assert.equal(result.orderNo, orderNo)
|
||||
assert.ok(result.orderItemId > 0)
|
||||
assert.ok(result.fulfillmentId > 0)
|
||||
assert.ok(result.taskId > 0)
|
||||
|
||||
const stored = await query<{
|
||||
channel: string
|
||||
fulfillment_status: string
|
||||
login_status: string
|
||||
execution_status: string
|
||||
config_id: number
|
||||
}>(
|
||||
`
|
||||
SELECT
|
||||
f.channel,
|
||||
f.status AS fulfillment_status,
|
||||
task.login_status,
|
||||
task.execution_status,
|
||||
task.manual_fulfillment_config_id AS config_id
|
||||
FROM semi_auto_tasks task
|
||||
JOIN fulfillments f ON f.id = task.fulfillment_id
|
||||
WHERE task.id = $1
|
||||
`,
|
||||
[result.taskId],
|
||||
)
|
||||
assert.equal(stored.rows[0]?.channel, 'manual')
|
||||
assert.equal(stored.rows[0]?.fulfillment_status, 'assigned')
|
||||
assert.equal(stored.rows[0]?.login_status, 'waiting_login')
|
||||
assert.equal(stored.rows[0]?.execution_status, 'waiting_customer')
|
||||
assert.equal(Number(stored.rows[0]?.config_id), result.configId)
|
||||
|
||||
const mapping = await query<{ internal_sku: string }>(
|
||||
'SELECT internal_sku FROM internal_sku_mappings WHERE id = $1',
|
||||
[result.mappingId],
|
||||
)
|
||||
assert.equal(mapping.rows[0]?.internal_sku, result.skuKey)
|
||||
} finally {
|
||||
await withTransaction(async (client) => {
|
||||
await client.query("SET LOCAL session_replication_role = 'replica'")
|
||||
if (configId > 0) {
|
||||
await client.query('DELETE FROM manual_fulfillment_configs WHERE id = $1', [configId])
|
||||
}
|
||||
if (orderId > 0) {
|
||||
await client.query('DELETE FROM order_source_snapshots WHERE order_id = $1', [orderId])
|
||||
await client.query('DELETE FROM orders WHERE id = $1', [orderId])
|
||||
}
|
||||
if (mappingId > 0) {
|
||||
await client.query('DELETE FROM internal_sku_mappings WHERE id = $1', [mappingId])
|
||||
}
|
||||
})
|
||||
delete process.env.ENABLE_DEV_MOCK
|
||||
await closeDb()
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user