重构(半自动履约): 统一虎牙/微博状态写入、CK 直取与履约分类(迁移190)
迁移 190 - 新增 SKU 级履约分类:manual_fulfillment_configs.semi_auto_category 为唯一真源 (''/direct_exchange/presale + CHECK),semi_auto_tasks.semi_auto_category 为物化快照, 配置改动不回写历史任务;补 (platform, semi_auto_category, created_at, id) 列表索引, 并按配置真源回填一次存量空快照。 状态写入收敛 - 26 处 UPDATE semi_auto_tasks 统一到唯一写入口 convergeSemiAutoTaskState: 行锁 + 状态转换规则 + 单条 UPDATE + 事件,事件只写本次真正变更的状态组。 - 新增 task-state-rules 纯函数与单测;终态 completed/cancelled 不再被业务状态改写。 - 热路径默认不回读带 join 的完整行,避免 2 秒轮询重复重读。 CK 生命周期 - 删除一次性注入票据与票据 TTL:移除 /semi-auto/injections 路由、两个 Connector 与 Mock 的票据实现;browser-session 改为后台鉴权后直接下发账号级 CK, 并补平台一致性与账号 UID 一致性校验。 - 登录成功但 CK 导出失败不再谎报已授权:落 failed + 原因,保留会话可重试; 微博短信登录与扫码路径行为对齐。 - 凭证 invalid 不再是永久黑名单:恢复前实时验证、成功回写 valid、失效重试按 60 秒节流; 微博恢复补任务级 UID 比对。 扩展与前端 - live-hub 的 huya-exchange-helper 迁入 apps/extensions/semi-auto-exchange-helper: 支持虎牙与微博域、CustomEvent 注入协议、--env-file 读取后台域名构建、 平台原始过期时间优先、只做 Cookie 注入与打开目标页(兑换人工完成)。 - 半自动履约页改为虎牙/微博 Tab + 分类筛选;人工 SKU 配置新增「履约分类」; 注入链路改为真实回执,扩展缺失时明确提示并支持复制 CK 兜底。 文档 - 权威文档同步:票据与 TTL 删除、CK 直取下发、扩展单一归属、分类真源与快照、 唯一写入口、迁移 190 记录。 - 新增《虎牙微博半自动履约现状-2026-11-30》现状盘点(重构前基线); 删除 docs/README.md 中指向不存在文件的失效链接。
This commit is contained in:
@@ -49,6 +49,13 @@ export type ManualPlatformKey = (typeof MANUAL_PLATFORM_KEYS)[number]
|
||||
export const SEMI_AUTO_PLATFORM_KEYS = ['huya', 'weibo'] as const
|
||||
export type SemiAutoPlatform = (typeof SEMI_AUTO_PLATFORM_KEYS)[number]
|
||||
|
||||
/**
|
||||
* 半自动履约分类:只用于兑换流程与后台筛选,不参与渠道判定、支付事实或履约完成判定。
|
||||
* 空字符串代表「未分类」。
|
||||
*/
|
||||
export const SEMI_AUTO_CATEGORY_KEYS = ['', 'direct_exchange', 'presale'] as const
|
||||
export type SemiAutoCategory = (typeof SEMI_AUTO_CATEGORY_KEYS)[number]
|
||||
|
||||
/**
|
||||
* 积分换算率(分/积分),**按平台不同**:
|
||||
* 南航 1 积分 = 1 分;乐玩 1 积分 = 1 分;ROCK 1 积分 = 1 元(100 分)。
|
||||
@@ -118,6 +125,7 @@ type ManualSkuRow = {
|
||||
config_channels_json: unknown
|
||||
config_semi_auto_enabled: boolean | null
|
||||
config_semi_auto_platform: string | null
|
||||
config_semi_auto_category: string | null
|
||||
config_semi_auto_config_json: unknown
|
||||
config_douyu_fulfillment_enabled: boolean | null
|
||||
}
|
||||
@@ -358,6 +366,7 @@ export async function listManualSkus(input: Record<string, unknown> = {}) {
|
||||
cfg.channels_json AS config_channels_json,
|
||||
cfg.semi_auto_enabled AS config_semi_auto_enabled,
|
||||
cfg.semi_auto_platform AS config_semi_auto_platform,
|
||||
cfg.semi_auto_category AS config_semi_auto_category,
|
||||
cfg.semi_auto_config_json AS config_semi_auto_config_json,
|
||||
cfg.douyu_fulfillment_enabled AS config_douyu_fulfillment_enabled
|
||||
FROM product_catalog p
|
||||
@@ -567,6 +576,7 @@ export async function saveManualFulfillmentConfig(payload: JsonObject) {
|
||||
channels_json = $9::jsonb,
|
||||
semi_auto_enabled = $10,
|
||||
semi_auto_platform = $11,
|
||||
semi_auto_category = COALESCE($15, semi_auto_category),
|
||||
semi_auto_config_json = $12::jsonb,
|
||||
douyu_fulfillment_enabled = $13,
|
||||
updated_at = $14
|
||||
@@ -587,18 +597,19 @@ export async function saveManualFulfillmentConfig(payload: JsonObject) {
|
||||
JSON.stringify(semiAuto.config),
|
||||
douyuFulfillmentEnabled,
|
||||
now,
|
||||
semiAuto.category,
|
||||
],
|
||||
)
|
||||
: await client.query(
|
||||
`INSERT INTO manual_fulfillment_configs (
|
||||
sku_key, canonical_product_id, platform_key, credit_quantity,
|
||||
cost_mode, enabled, note, channels_json,
|
||||
semi_auto_enabled, semi_auto_platform, semi_auto_config_json,
|
||||
douyu_fulfillment_enabled,
|
||||
semi_auto_enabled, semi_auto_platform, semi_auto_category,
|
||||
semi_auto_config_json, douyu_fulfillment_enabled,
|
||||
created_at, updated_at
|
||||
) VALUES (
|
||||
$1, $2, $3, $4, $5, $6, $7, $8::jsonb,
|
||||
$9, $10, $11::jsonb, $12, $13, $13
|
||||
$9, $10, COALESCE($14, ''), $11::jsonb, $12, $13, $13
|
||||
)
|
||||
RETURNING *`,
|
||||
[
|
||||
@@ -615,6 +626,7 @@ export async function saveManualFulfillmentConfig(payload: JsonObject) {
|
||||
JSON.stringify(semiAuto.config),
|
||||
douyuFulfillmentEnabled,
|
||||
now,
|
||||
semiAuto.category,
|
||||
],
|
||||
)
|
||||
const saved = requiredRow(result.rows[0], '保存人工履约配置失败')
|
||||
@@ -1088,6 +1100,7 @@ export async function getManualFulfillmentConfig(skuKey: string) {
|
||||
channels_json: unknown
|
||||
semi_auto_enabled: boolean
|
||||
semi_auto_platform: string
|
||||
semi_auto_category: string
|
||||
semi_auto_config_json: unknown
|
||||
douyu_fulfillment_enabled: boolean
|
||||
created_at: string
|
||||
@@ -1220,6 +1233,7 @@ function mapManualSku(row: ManualSkuRow, unitPrices: Record<ManualPlatformKey, n
|
||||
enabled: row.config_enabled !== false,
|
||||
semiAutoEnabled: row.config_semi_auto_enabled === true,
|
||||
semiAutoPlatform: String(row.config_semi_auto_platform || ''),
|
||||
semiAutoCategory: String(row.config_semi_auto_category || ''),
|
||||
semiAutoConfig: normalizeStoredSemiAutoConfig(row.config_semi_auto_config_json),
|
||||
douyuFulfillmentEnabled: row.config_douyu_fulfillment_enabled === true,
|
||||
channels: mapConfiguredChannels(channels, unitPrices),
|
||||
@@ -1241,6 +1255,7 @@ function mapManualConfig(
|
||||
channels_json: unknown
|
||||
semi_auto_enabled: boolean
|
||||
semi_auto_platform: string
|
||||
semi_auto_category: string
|
||||
semi_auto_config_json: unknown
|
||||
douyu_fulfillment_enabled: boolean
|
||||
created_at: string
|
||||
@@ -1265,6 +1280,7 @@ function mapManualConfig(
|
||||
enabled: row.enabled,
|
||||
semiAutoEnabled: row.semi_auto_enabled === true,
|
||||
semiAutoPlatform: String(row.semi_auto_platform || ''),
|
||||
semiAutoCategory: String(row.semi_auto_category || ''),
|
||||
semiAutoConfig: normalizeStoredSemiAutoConfig(row.semi_auto_config_json),
|
||||
douyuFulfillmentEnabled: row.douyu_fulfillment_enabled === true,
|
||||
channels: mapConfiguredChannels(channels, unitPrices),
|
||||
@@ -1277,14 +1293,36 @@ function mapManualConfig(
|
||||
function normalizeSemiAutoConfig(payload: JsonObject): {
|
||||
enabled: boolean
|
||||
platform: SemiAutoPlatform | ''
|
||||
/** `null` 表示本次请求没有携带分类,落库时必须沿用旧值。 */
|
||||
category: SemiAutoCategory | null
|
||||
config: Record<string, unknown>
|
||||
} {
|
||||
const enabled = payload.semiAutoEnabled === true || payload.semi_auto_enabled === true
|
||||
const platform = String(payload.semiAutoPlatform ?? payload.semi_auto_platform ?? '')
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
const rawCategoryInput = payload.semiAutoCategory ?? payload.semi_auto_category
|
||||
const categoryProvided = rawCategoryInput !== undefined && rawCategoryInput !== null
|
||||
const rawCategory = String(rawCategoryInput ?? '')
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
const category = (SEMI_AUTO_CATEGORY_KEYS as readonly string[]).includes(rawCategory)
|
||||
? (rawCategory as SemiAutoCategory)
|
||||
: null
|
||||
if (category === null) {
|
||||
throw createHttpError('半自动履约分类无效', {
|
||||
statusCode: 400,
|
||||
errorCode: 'manual_config_semi_auto_category_invalid',
|
||||
})
|
||||
}
|
||||
// 停用半自动不清掉已选分类:下次重新启用时运营不需要重选。
|
||||
if (!enabled) {
|
||||
return { enabled: false, platform: '', config: {} }
|
||||
return {
|
||||
enabled: false,
|
||||
platform: '',
|
||||
category: categoryProvided ? category : null,
|
||||
config: {},
|
||||
}
|
||||
}
|
||||
if (!(SEMI_AUTO_PLATFORM_KEYS as readonly string[]).includes(platform)) {
|
||||
throw createHttpError('半自动履约平台无效', {
|
||||
@@ -1300,6 +1338,7 @@ function normalizeSemiAutoConfig(payload: JsonObject): {
|
||||
return {
|
||||
enabled: true,
|
||||
platform: platform as SemiAutoPlatform,
|
||||
category,
|
||||
config: {
|
||||
pageTitle: String(config.pageTitle || '')
|
||||
.trim()
|
||||
|
||||
@@ -33,6 +33,7 @@ import { randomId } from '../../utils/random.js'
|
||||
import { TASK_STATUS } from '../../domain/task-status.js'
|
||||
import { ensureSemiAutoTasksForOrder } from '../semi-auto/semi-auto-task-service.js'
|
||||
import { ensureSemiAutoTasksForOrderItems } from '../semi-auto/semi-auto-task-service.js'
|
||||
import { convergeSemiAutoTaskState } from '../semi-auto/semi-auto-task-state-service.js'
|
||||
import {
|
||||
defaultSemiAutoConnectorMode,
|
||||
isExternalSemiAutoConnectorConfigured,
|
||||
@@ -505,10 +506,15 @@ export async function createSemiAutoMock(
|
||||
})
|
||||
}
|
||||
|
||||
await query('UPDATE semi_auto_tasks SET connector_mode = $2, updated_at = NOW() WHERE id = $1', [
|
||||
taskId,
|
||||
connectorMode,
|
||||
])
|
||||
await withTransaction((client) =>
|
||||
convergeSemiAutoTaskState(client, taskId, {
|
||||
reason: 'dev_mock_connector_mode_selected',
|
||||
actor: 'system',
|
||||
patch: { connectorMode },
|
||||
// 原入口只切换 Connector 模式,不写任务事件。
|
||||
event: null,
|
||||
}),
|
||||
)
|
||||
|
||||
const connectorConfigured =
|
||||
connectorMode === 'external' ? isExternalSemiAutoConnectorConfigured() : true
|
||||
@@ -878,10 +884,15 @@ export async function createSemiAutoIntegrationMock(
|
||||
})
|
||||
}
|
||||
|
||||
await query('UPDATE semi_auto_tasks SET connector_mode = $2, updated_at = NOW() WHERE id = $1', [
|
||||
Number(row.task_id),
|
||||
connectorMode,
|
||||
])
|
||||
await withTransaction((client) =>
|
||||
convergeSemiAutoTaskState(client, Number(row.task_id), {
|
||||
reason: 'dev_integration_connector_mode_selected',
|
||||
actor: 'system',
|
||||
patch: { connectorMode },
|
||||
// 原入口只切换 Connector 模式,不写任务事件。
|
||||
event: null,
|
||||
}),
|
||||
)
|
||||
const connectorConfigured =
|
||||
connectorMode === 'external' ? isExternalSemiAutoConnectorConfigured() : true
|
||||
return {
|
||||
|
||||
@@ -3,8 +3,6 @@ import test from 'node:test'
|
||||
|
||||
import {
|
||||
confirmMockBinding,
|
||||
consumeMockBrowserTicket,
|
||||
createMockBrowserTicket,
|
||||
createMockLoginSession,
|
||||
exportMockSessionCredential,
|
||||
getMockBinding,
|
||||
@@ -20,7 +18,7 @@ import {
|
||||
|
||||
test.beforeEach(() => resetMockSessions())
|
||||
|
||||
test('Mock Connector 可按轮询自动完成登录、绑定和一次性票据消费', () => {
|
||||
test('Mock Connector 可按轮询自动完成登录与绑定并导出账号 CK', () => {
|
||||
const created = createMockLoginSession({ taskId: 101, orderNo: 'MOCK-SA-1' })
|
||||
assert.equal(created.status, 'waiting_scan')
|
||||
assert.equal(created.hasCredential, false)
|
||||
@@ -49,19 +47,6 @@ test('Mock Connector 可按轮询自动完成登录、绑定和一次性票据
|
||||
|
||||
const confirmed = confirmMockBinding(created.sessionId)
|
||||
assert.equal(confirmed.status, 'confirmed')
|
||||
|
||||
const ticket = createMockBrowserTicket({
|
||||
sessionId: created.sessionId,
|
||||
targetUrl: 'https://www.huya.com/mock',
|
||||
})
|
||||
assert.equal(ticket.targetUrl, 'https://www.huya.com/mock')
|
||||
|
||||
const payload = consumeMockBrowserTicket(ticket.ticket)
|
||||
assert.equal(payload.platform, 'huya')
|
||||
assert.ok(payload.cookies.length >= 1)
|
||||
assert.equal(payload.cookies[0]?.domain, '.huya.com')
|
||||
|
||||
assert.throws(() => consumeMockBrowserTicket(ticket.ticket), /已被消费/)
|
||||
})
|
||||
|
||||
test('Mock Connector 支持控制状态、撤销会话和重置', () => {
|
||||
@@ -71,12 +56,6 @@ test('Mock Connector 支持控制状态、撤销会话和重置', () => {
|
||||
assert.equal(authenticated.status, 'authenticated')
|
||||
assert.equal(authenticated.hasCredential, true)
|
||||
|
||||
const ticket = createMockBrowserTicket({
|
||||
sessionId: created.sessionId,
|
||||
targetUrl: 'https://www.huya.com/no-binding',
|
||||
})
|
||||
assert.equal(consumeMockBrowserTicket(ticket.ticket).targetUrl, 'https://www.huya.com/no-binding')
|
||||
|
||||
const confirmed = setMockBindingStatus(created.sessionId, 'confirmed')
|
||||
assert.equal(confirmed.status, 'confirmed')
|
||||
assert.ok(confirmed.bindGameRole)
|
||||
|
||||
@@ -8,8 +8,6 @@ import crypto from 'node:crypto'
|
||||
|
||||
import type {
|
||||
ConnectorBindingSession,
|
||||
ConnectorBrowserTicket,
|
||||
ConnectorInjectionPayload,
|
||||
ConnectorLoginSession,
|
||||
} from '../semi-auto/huya-connector-client.js'
|
||||
import type { HuyaStoredCredential } from '../semi-auto/huya-native/huya-native-connector.js'
|
||||
@@ -18,18 +16,10 @@ import { createHttpError } from '../../utils/http.js'
|
||||
const LOGIN_QR_TTL_MS = 5 * 60 * 1000
|
||||
const CREDENTIAL_TTL_MS = 24 * 60 * 60 * 1000
|
||||
const BINDING_QR_TTL_MS = 5 * 60 * 1000
|
||||
const BROWSER_TICKET_TTL_MS = 2 * 60 * 1000
|
||||
|
||||
type MockLoginStatus = ConnectorLoginSession['status']
|
||||
type MockBindingStatus = ConnectorBindingSession['status']
|
||||
|
||||
type MockTicket = {
|
||||
ticket: string
|
||||
targetUrl: string
|
||||
expiresAtMs: number
|
||||
consumed: boolean
|
||||
}
|
||||
|
||||
type MockSession = {
|
||||
sessionId: string
|
||||
taskId: number
|
||||
@@ -53,7 +43,6 @@ type MockSession = {
|
||||
bindGameRoleId: string
|
||||
bindGameChannel: string
|
||||
message: string
|
||||
tickets: Map<string, MockTicket>
|
||||
}
|
||||
|
||||
const sessions = new Map<string, MockSession>()
|
||||
@@ -195,7 +184,6 @@ export function createMockLoginSession(input: {
|
||||
bindGameRoleId: '',
|
||||
bindGameChannel: '',
|
||||
message: 'Mock 登录二维码已生成,轮询后会自动模拟扫码成功',
|
||||
tickets: new Map(),
|
||||
}
|
||||
sessions.set(sessionId, session)
|
||||
return loginView(session)
|
||||
@@ -238,7 +226,6 @@ export function sendMockHuyaSmsCode(input: {
|
||||
bindGameRoleId: '',
|
||||
bindGameChannel: '',
|
||||
message: 'Mock 短信验证码已发送,请输入 123456',
|
||||
tickets: new Map(),
|
||||
}
|
||||
sessions.set(sessionId, session)
|
||||
return loginView(session)
|
||||
@@ -375,74 +362,6 @@ export function confirmMockBinding(sessionIdInput: unknown): ConnectorBindingSes
|
||||
return bindingView(session)
|
||||
}
|
||||
|
||||
export function createMockBrowserTicket(input: {
|
||||
sessionId?: unknown
|
||||
targetUrl?: unknown
|
||||
}): ConnectorBrowserTicket {
|
||||
const session = requireSession(input.sessionId)
|
||||
if (session.loginStatus !== 'authenticated' || !session.hasCredential) {
|
||||
throw createHttpError('Mock 登录尚未完成,不能生成浏览器票据', {
|
||||
statusCode: 409,
|
||||
errorCode: 'mock_semi_auto_login_required',
|
||||
})
|
||||
}
|
||||
const ticket = `mock-ticket-${crypto.randomUUID()}`
|
||||
const targetUrl = String(input.targetUrl || 'https://www.huya.com/').trim()
|
||||
const expiresAtMs = Date.now() + BROWSER_TICKET_TTL_MS
|
||||
session.tickets.set(ticket, { ticket, targetUrl, expiresAtMs, consumed: false })
|
||||
return {
|
||||
ticket,
|
||||
expiresAt: new Date(expiresAtMs).toISOString(),
|
||||
targetUrl,
|
||||
}
|
||||
}
|
||||
|
||||
export function consumeMockBrowserTicket(ticketInput: unknown): ConnectorInjectionPayload {
|
||||
const ticket = String(ticketInput || '').trim()
|
||||
for (const session of sessions.values()) {
|
||||
const item = session.tickets.get(ticket)
|
||||
if (!item) continue
|
||||
if (item.consumed) {
|
||||
throw createHttpError('Mock 注入票据已被消费', {
|
||||
statusCode: 410,
|
||||
errorCode: 'mock_semi_auto_ticket_consumed',
|
||||
})
|
||||
}
|
||||
if (item.expiresAtMs <= Date.now()) {
|
||||
throw createHttpError('Mock 注入票据已过期', {
|
||||
statusCode: 410,
|
||||
errorCode: 'mock_semi_auto_ticket_expired',
|
||||
})
|
||||
}
|
||||
item.consumed = true
|
||||
return {
|
||||
platform: 'huya',
|
||||
targetUrl: item.targetUrl,
|
||||
expiresAt: new Date(item.expiresAtMs).toISOString(),
|
||||
cookies: [
|
||||
{
|
||||
name: 'mock_huya_uid',
|
||||
value: session.huyaUid || buildMockUid(session.sessionId),
|
||||
domain: '.huya.com',
|
||||
path: '/',
|
||||
secure: true,
|
||||
},
|
||||
{
|
||||
name: 'mock_huya_session',
|
||||
value: session.sessionId,
|
||||
domain: '.huya.com',
|
||||
path: '/',
|
||||
secure: true,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
throw createHttpError('Mock 注入票据不存在', {
|
||||
statusCode: 404,
|
||||
errorCode: 'mock_semi_auto_ticket_not_found',
|
||||
})
|
||||
}
|
||||
|
||||
export function revokeMockSession(sessionIdInput: unknown) {
|
||||
const sessionId = String(sessionIdInput || '').trim()
|
||||
sessions.delete(sessionId)
|
||||
@@ -518,7 +437,6 @@ export function listMockSessions() {
|
||||
loginStatus: session.loginStatus,
|
||||
bindingStatus: session.bindingStatus,
|
||||
hasCredential: session.hasCredential,
|
||||
ticketCount: session.tickets.size,
|
||||
createdAt: new Date(session.createdAtMs).toISOString(),
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -6,15 +6,6 @@ process.env.SEMI_AUTO_CONNECTOR_API_KEY = 'test-key'
|
||||
|
||||
const connector = await import('./huya-connector-client.js')
|
||||
|
||||
test('浏览器注入票据按 Mock 前缀选择 Connector', () => {
|
||||
assert.equal(connector.inferSemiAutoConnectorModeFromTicket('mock-ticket-0123456789'), 'mock')
|
||||
assert.equal(
|
||||
connector.inferSemiAutoConnectorModeFromTicket('native-ticket-0123456789'),
|
||||
'embedded',
|
||||
)
|
||||
assert.equal(connector.inferSemiAutoConnectorModeFromTicket('real-ticket-0123456789'), 'external')
|
||||
})
|
||||
|
||||
test('创建登录会话按真实 Connector 协议发送蛇形字段', async () => {
|
||||
const originalFetch = globalThis.fetch
|
||||
let requestUrl = ''
|
||||
|
||||
@@ -12,7 +12,6 @@ import {
|
||||
sendMockHuyaSmsCode,
|
||||
} from '../dev-mock/mock-semi-auto-connector.js'
|
||||
import {
|
||||
HUYA_NATIVE_TICKET_PREFIX,
|
||||
huyaNativeConnector,
|
||||
type HuyaRestoreCredentialInput,
|
||||
type HuyaStoredCredential,
|
||||
@@ -139,25 +138,6 @@ export type ConnectorBindingSession = {
|
||||
message: string
|
||||
}
|
||||
|
||||
export type ConnectorBrowserTicket = {
|
||||
ticket: string
|
||||
expiresAt: string
|
||||
targetUrl: string
|
||||
}
|
||||
|
||||
export type ConnectorInjectionPayload = {
|
||||
platform: 'huya' | 'weibo'
|
||||
targetUrl: string
|
||||
expiresAt: string
|
||||
cookies: Array<{
|
||||
name: string
|
||||
value: string
|
||||
domain: string
|
||||
path: string
|
||||
secure: boolean
|
||||
}>
|
||||
}
|
||||
|
||||
type ConnectorRequestOptions = {
|
||||
method?: 'GET' | 'POST' | 'DELETE'
|
||||
body?: unknown
|
||||
@@ -551,21 +531,6 @@ export async function submitHuyaRebind(
|
||||
)
|
||||
}
|
||||
|
||||
export async function createHuyaBrowserTicket(
|
||||
input: {
|
||||
sessionId: string
|
||||
targetUrl?: string
|
||||
},
|
||||
mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(),
|
||||
): Promise<ConnectorBrowserTicket> {
|
||||
if (mode === 'embedded') return huyaNativeConnector.createBrowserTicket(input)
|
||||
return callConnector<ConnectorBrowserTicket>(
|
||||
`/api/internal/huya-semi-auto/sessions/${encodeURIComponent(input.sessionId)}/browser-ticket`,
|
||||
{ method: 'POST', body: { targetUrl: input.targetUrl || '' } },
|
||||
mode,
|
||||
)
|
||||
}
|
||||
|
||||
export async function exportHuyaSessionCredential(
|
||||
sessionId: string,
|
||||
mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(),
|
||||
@@ -592,25 +557,6 @@ export async function restoreHuyaSessionFromCredential(
|
||||
return huyaNativeConnector.restoreSessionFromCredential(input)
|
||||
}
|
||||
|
||||
export function inferSemiAutoConnectorModeFromTicket(ticket: string): SemiAutoConnectorMode {
|
||||
const normalized = ticket.trim()
|
||||
if (normalized.startsWith('mock-ticket-')) return 'mock'
|
||||
if (normalized.startsWith(HUYA_NATIVE_TICKET_PREFIX)) return 'embedded'
|
||||
return 'external'
|
||||
}
|
||||
|
||||
export async function consumeHuyaBrowserTicket(
|
||||
ticket: string,
|
||||
mode: SemiAutoConnectorMode = inferSemiAutoConnectorModeFromTicket(ticket),
|
||||
): Promise<ConnectorInjectionPayload> {
|
||||
if (mode === 'embedded') return huyaNativeConnector.consumeBrowserTicket(ticket)
|
||||
return callConnector<ConnectorInjectionPayload>(
|
||||
`/api/internal/huya-semi-auto/browser-tickets/${encodeURIComponent(ticket)}`,
|
||||
{},
|
||||
mode,
|
||||
)
|
||||
}
|
||||
|
||||
export async function revokeHuyaSession(
|
||||
sessionId: string,
|
||||
mode: SemiAutoConnectorMode = defaultSemiAutoConnectorMode(),
|
||||
|
||||
@@ -15,8 +15,6 @@ import { logWarn } from '../../../utils/logger.js'
|
||||
import { resolveHuyaRebindCooldownResponse } from '../huya-binding-policy.js'
|
||||
import type {
|
||||
ConnectorBindingSession,
|
||||
ConnectorBrowserTicket,
|
||||
ConnectorInjectionPayload,
|
||||
ConnectorLoginSession,
|
||||
HuyaSmsChallenge,
|
||||
HuyaSmsSendResult,
|
||||
@@ -57,9 +55,7 @@ const REBIND_WINDOW_DAYS = 7
|
||||
const DAY_MS = 24 * 60 * 60 * 1000
|
||||
// 提交换绑后给虎牙留的生效时间;期间前端继续轮询,不提前判失败。
|
||||
const REBIND_EFFECT_WINDOW_MS = 60 * 1000
|
||||
const BROWSER_TICKET_TTL_MS = 2 * 60 * 1000
|
||||
const MAX_SESSIONS = 500
|
||||
const NATIVE_TICKET_PREFIX = 'native-ticket-'
|
||||
|
||||
type FetchLike = typeof fetch
|
||||
type NativeLoginStatus = ConnectorLoginSession['status']
|
||||
@@ -108,13 +104,6 @@ type NativeBindState = {
|
||||
message: string
|
||||
}
|
||||
|
||||
type NativeTicket = {
|
||||
ticket: string
|
||||
targetUrl: string
|
||||
cookie: string
|
||||
expiresAtMs: number
|
||||
}
|
||||
|
||||
type NativeSession = {
|
||||
sessionId: string
|
||||
orderNo: string
|
||||
@@ -139,7 +128,6 @@ type NativeSession = {
|
||||
cookie: string
|
||||
message: string
|
||||
binding: NativeBindState
|
||||
tickets: Map<string, NativeTicket>
|
||||
}
|
||||
|
||||
export type HuyaNativeConnectorOptions = {
|
||||
@@ -601,7 +589,6 @@ export class HuyaNativeConnector {
|
||||
cookie: '',
|
||||
message: '等待使用虎牙 App 扫码',
|
||||
binding: defaultBindingState(),
|
||||
tickets: new Map(),
|
||||
}
|
||||
this.sessions.set(sessionId, session)
|
||||
this.prune()
|
||||
@@ -696,7 +683,6 @@ export class HuyaNativeConnector {
|
||||
cookie: identity.cookie,
|
||||
message: '已从账号级 CK 恢复虎牙登录会话',
|
||||
binding: defaultBindingState(),
|
||||
tickets: new Map(),
|
||||
}
|
||||
this.sessions.set(sessionId, session)
|
||||
this.prune()
|
||||
@@ -847,7 +833,6 @@ export class HuyaNativeConnector {
|
||||
cookie: '',
|
||||
message: challenge ? '请完成安全验证后发送验证码' : '验证码已发送,请注意查收',
|
||||
binding: defaultBindingState(),
|
||||
tickets: new Map(),
|
||||
}
|
||||
this.sessions.set(sessionId, session)
|
||||
this.prune()
|
||||
@@ -1388,31 +1373,6 @@ export class HuyaNativeConnector {
|
||||
return this.pollBinding(sessionId)
|
||||
}
|
||||
|
||||
async createBrowserTicket(input: {
|
||||
sessionId: string
|
||||
targetUrl?: string
|
||||
}): Promise<ConnectorBrowserTicket> {
|
||||
return this.withLock(input.sessionId, async () => {
|
||||
const session = this.requireSession(input.sessionId)
|
||||
if (!session.cookie) {
|
||||
throw createHttpError('虎牙登录态不存在或已过期', {
|
||||
statusCode: 404,
|
||||
errorCode: 'huya_native_credential_not_found',
|
||||
})
|
||||
}
|
||||
const ticket = `${NATIVE_TICKET_PREFIX}${crypto.randomBytes(32).toString('base64url')}`
|
||||
const targetUrl = readString(input.targetUrl) || 'https://www.huya.com/'
|
||||
const expiresAtMs = this.now() + BROWSER_TICKET_TTL_MS
|
||||
session.tickets.set(ticket, {
|
||||
ticket,
|
||||
targetUrl,
|
||||
cookie: session.cookie,
|
||||
expiresAtMs,
|
||||
})
|
||||
return { ticket, expiresAt: iso(expiresAtMs), targetUrl }
|
||||
})
|
||||
}
|
||||
|
||||
exportSessionCredential(sessionIdInput: string): HuyaStoredCredential {
|
||||
const session = this.requireAuthenticatedSession(sessionIdInput)
|
||||
return {
|
||||
@@ -1433,40 +1393,6 @@ export class HuyaNativeConnector {
|
||||
}
|
||||
}
|
||||
|
||||
async consumeBrowserTicket(ticketInput: string): Promise<ConnectorInjectionPayload> {
|
||||
this.prune()
|
||||
const ticket = readString(ticketInput)
|
||||
for (const session of this.sessions.values()) {
|
||||
const item = session.tickets.get(ticket)
|
||||
if (!item) continue
|
||||
session.tickets.delete(ticket)
|
||||
if (item.expiresAtMs <= this.now()) {
|
||||
throw createHttpError('浏览器注入票据不存在或已过期', {
|
||||
statusCode: 404,
|
||||
errorCode: 'huya_native_ticket_expired',
|
||||
})
|
||||
}
|
||||
return {
|
||||
platform: 'huya',
|
||||
targetUrl: item.targetUrl,
|
||||
expiresAt: iso(item.expiresAtMs),
|
||||
cookies: cookiePairs(item.cookie)
|
||||
.filter(([name, value]) => name && value)
|
||||
.map(([name, value]) => ({
|
||||
name,
|
||||
value,
|
||||
domain: '.huya.com',
|
||||
path: '/',
|
||||
secure: true,
|
||||
})),
|
||||
}
|
||||
}
|
||||
throw createHttpError('浏览器注入票据不存在或已过期', {
|
||||
statusCode: 404,
|
||||
errorCode: 'huya_native_ticket_not_found',
|
||||
})
|
||||
}
|
||||
|
||||
async revokeSession(sessionIdInput: string): Promise<void> {
|
||||
const sessionId = readString(sessionIdInput)
|
||||
const session = this.sessions.get(sessionId)
|
||||
@@ -1475,7 +1401,6 @@ export class HuyaNativeConnector {
|
||||
session.smsSessionData = ''
|
||||
session.smsPhone = ''
|
||||
session.smsChallenge = null
|
||||
session.tickets.clear()
|
||||
this.sessions.delete(sessionId)
|
||||
await removeFingerprintState(session.stateDir)
|
||||
}
|
||||
@@ -1659,16 +1584,10 @@ export class HuyaNativeConnector {
|
||||
session.smsSessionData = ''
|
||||
session.smsPhone = ''
|
||||
session.smsChallenge = null
|
||||
session.tickets.clear()
|
||||
this.sessions.delete(sessionId)
|
||||
void removeFingerprintState(session.stateDir)
|
||||
}
|
||||
}
|
||||
for (const session of this.sessions.values()) {
|
||||
for (const [ticket, item] of session.tickets) {
|
||||
if (item.expiresAtMs <= now) session.tickets.delete(ticket)
|
||||
}
|
||||
}
|
||||
if (this.sessions.size > MAX_SESSIONS) {
|
||||
const overflow = this.sessions.size - MAX_SESSIONS
|
||||
for (const [sessionId, session] of Array.from(this.sessions.entries()).slice(0, overflow)) {
|
||||
@@ -1676,7 +1595,6 @@ export class HuyaNativeConnector {
|
||||
session.smsSessionData = ''
|
||||
session.smsPhone = ''
|
||||
session.smsChallenge = null
|
||||
session.tickets.clear()
|
||||
this.sessions.delete(sessionId)
|
||||
void removeFingerprintState(session.stateDir)
|
||||
}
|
||||
@@ -1789,4 +1707,3 @@ export class HuyaNativeConnector {
|
||||
}
|
||||
|
||||
export const huyaNativeConnector = new HuyaNativeConnector()
|
||||
export const HUYA_NATIVE_TICKET_PREFIX = NATIVE_TICKET_PREFIX
|
||||
|
||||
@@ -239,11 +239,11 @@ test('已绑定账号和角色时直接使用当前绑定,不再发起换绑',
|
||||
assert.equal(hasExistingHuyaBinding(response), false)
|
||||
})
|
||||
|
||||
test('内置 Connector 完成扫码、CK 兑换和一次性票据且不泄露 CK', async () => {
|
||||
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 now = Date.now()
|
||||
const fetchImpl = (async (urlInput: string | URL | Request, init?: RequestInit) => {
|
||||
const url = String(urlInput)
|
||||
const body = typeof init?.body === 'string' ? init.body : ''
|
||||
@@ -371,23 +371,11 @@ test('内置 Connector 完成扫码、CK 兑换和一次性票据且不泄露 CK
|
||||
'server-issued-cred',
|
||||
)
|
||||
|
||||
const ticket = await connector.createBrowserTicket({
|
||||
sessionId: created.sessionId,
|
||||
targetUrl: 'https://www.huya.com/',
|
||||
})
|
||||
assert.match(ticket.ticket, /^native-ticket-/)
|
||||
assert.equal(ticket.ticket.includes('secret-biztoken'), false)
|
||||
const payload = await connector.consumeBrowserTicket(ticket.ticket)
|
||||
assert.equal(payload.platform, 'huya')
|
||||
// CK 只落在账号级凭证里;导出统一按 .huya.com / 归并,供浏览器注入直接使用。
|
||||
assert.equal(
|
||||
payload.cookies.find((item) => item.name === 'udb_cred')?.value,
|
||||
'server-issued-cred',
|
||||
credential.cookies.every((item) => item.domain === '.huya.com' && item.path === '/'),
|
||||
true,
|
||||
)
|
||||
await assert.rejects(() => connector.consumeBrowserTicket(ticket.ticket), /不存在或已过期/)
|
||||
|
||||
const expiring = await connector.createBrowserTicket({ sessionId: created.sessionId })
|
||||
now += 2 * 60 * 1000 + 1
|
||||
await assert.rejects(() => connector.consumeBrowserTicket(expiring.ticket), /不存在或已过期/)
|
||||
|
||||
await connector.revokeSession(created.sessionId)
|
||||
await assert.rejects(() => connector.getLoginSession(created.sessionId), /不存在或已过期/)
|
||||
@@ -527,7 +515,7 @@ test('内置 Connector 手动发码并完成短信登录后保存账号 CK', asy
|
||||
)
|
||||
})
|
||||
|
||||
test('虎牙进程会话丢失后可从账号级 CK 恢复并生成浏览器注入票据', async () => {
|
||||
test('虎牙进程会话丢失后可从账号级 CK 恢复并要求重新导出 CK', async () => {
|
||||
let fetchCalls = 0
|
||||
const connector = new HuyaNativeConnector({
|
||||
fetchImpl: (async () => {
|
||||
@@ -575,13 +563,10 @@ test('虎牙进程会话丢失后可从账号级 CK 恢复并生成浏览器注
|
||||
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)
|
||||
// 恢复后必须能重新导出同一份 CK(浏览器注入直接使用这份数据,不再签发票据)。
|
||||
const restoredCredential = connector.exportSessionCredential(restored.sessionId)
|
||||
assert.equal(
|
||||
payload.cookies.find((cookie) => cookie.name === 'udb_cred')?.value,
|
||||
restoredCredential.cookies.find((cookie) => cookie.name === 'udb_cred')?.value,
|
||||
'restored-credential',
|
||||
)
|
||||
})
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { query, withTransaction } from '../../db/client.js'
|
||||
import { getFileAssetByObjectKey } from '../../repositories/file-asset-repo.js'
|
||||
import { createHttpError } from '../../utils/http.js'
|
||||
import { SEMI_AUTO_CATEGORY_KEYS } from '../cost-center/manual-fulfillment-config-service.js'
|
||||
import type { AdminSession } from '../admin/admin-auth-service.js'
|
||||
import { safeParseJson } from '../admin/admin-query-utils.js'
|
||||
import {
|
||||
@@ -14,28 +15,20 @@ import {
|
||||
} from '../file-storage/file-storage-service.js'
|
||||
import { publishAdminOrderRealtimeChange } from '../realtime/realtime-event-service.js'
|
||||
import {
|
||||
consumeHuyaBrowserTicket,
|
||||
createHuyaBrowserTicket,
|
||||
revokeHuyaSession,
|
||||
type ConnectorBindingSession,
|
||||
type ConnectorInjectionPayload,
|
||||
type SemiAutoConnectorMode,
|
||||
} from './huya-connector-client.js'
|
||||
import {
|
||||
buildSemiAutoCredentialCookieHeader,
|
||||
loadSemiAutoCredential,
|
||||
selectSemiAutoCredentialCookies,
|
||||
} from './semi-auto-credential-service.js'
|
||||
import {
|
||||
consumeWeiboBrowserTicket,
|
||||
createWeiboBrowserTicket,
|
||||
revokeWeiboSession,
|
||||
} from './weibo-connector-client.js'
|
||||
import { WEIBO_TICKET_PREFIX } from './weibo-native/weibo-native-connector.js'
|
||||
import { revokeWeiboSession } from './weibo-connector-client.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,
|
||||
ensureConnectorSessionForTask,
|
||||
ensureSemiAutoTasksForAdminList,
|
||||
getBindingForTask,
|
||||
@@ -54,12 +47,17 @@ import {
|
||||
updateBindingTask,
|
||||
updateBindingTaskWithClient,
|
||||
type BindingStatus,
|
||||
type ExecutionStatus,
|
||||
type LoginStatus,
|
||||
type SemiAutoPlatform,
|
||||
type TaskRow,
|
||||
} from './semi-auto-task-core.js'
|
||||
import { updateLoginTask } from './semi-auto-customer-service.js'
|
||||
import { ACTIVE_EXECUTION_STATUSES } from './task-state-rules.js'
|
||||
import {
|
||||
convergeSemiAutoTaskState,
|
||||
SEMI_AUTO_COALESCE_NOW,
|
||||
SEMI_AUTO_NOW,
|
||||
} from './semi-auto-task-state-service.js'
|
||||
|
||||
export async function listAdminSemiAutoTasks(input: Record<string, unknown> = {}) {
|
||||
await ensureSemiAutoTasksForAdminList()
|
||||
@@ -67,6 +65,10 @@ export async function listAdminSemiAutoTasks(input: Record<string, unknown> = {}
|
||||
const pageSize = Math.min(100, Math.max(1, Math.trunc(Number(input.pageSize) || 20)))
|
||||
const platform = String(input.platform || '').trim()
|
||||
const status = String(input.status || '').trim()
|
||||
// 分类筛选必须区分「参数缺失」与「显式空串」:
|
||||
// 缺失 = 全部(不筛选),空串 = 未分类(semi_auto_category = '')。
|
||||
const hasCategoryFilter = input.category !== undefined && input.category !== null
|
||||
const category = hasCategoryFilter ? String(input.category).trim() : ''
|
||||
const keyword = String(input.keyword || '').trim()
|
||||
const conditions = ['1 = 1']
|
||||
const params: unknown[] = []
|
||||
@@ -87,6 +89,10 @@ export async function listAdminSemiAutoTasks(input: Record<string, unknown> = {}
|
||||
params.push(status)
|
||||
conditions.push(`task.execution_status = $${params.length}`)
|
||||
}
|
||||
if (hasCategoryFilter && (SEMI_AUTO_CATEGORY_KEYS as readonly string[]).includes(category)) {
|
||||
params.push(category)
|
||||
conditions.push(`task.semi_auto_category = $${params.length}`)
|
||||
}
|
||||
if (keyword) {
|
||||
params.push(`%${keyword.replace(/[\\%_]/g, '\\$&')}%`)
|
||||
const p = `$${params.length}`
|
||||
@@ -285,16 +291,12 @@ export async function claimAdminSemiAutoTask(taskIdInput: unknown, session: Admi
|
||||
})
|
||||
}
|
||||
orderId = Number(task.order_id)
|
||||
await client.query(
|
||||
`UPDATE semi_auto_tasks
|
||||
SET assigned_admin_user_id = $2, updated_at = NOW()
|
||||
WHERE id = $1`,
|
||||
[taskId, adminUserId],
|
||||
)
|
||||
await appendTaskEvent(client, taskId, {
|
||||
eventType: 'task_claimed',
|
||||
actorType: 'admin',
|
||||
await convergeSemiAutoTaskState(client, taskId, {
|
||||
reason: 'task_claimed',
|
||||
actor: 'admin',
|
||||
actorId: String(adminUserId),
|
||||
patch: { assignedAdminUserId: adminUserId },
|
||||
event: { eventType: 'task_claimed' },
|
||||
})
|
||||
})
|
||||
publishSemiAutoTaskRealtimeChange(taskId, orderId)
|
||||
@@ -369,13 +371,16 @@ export async function reconcileSemiAutoTaskStates(limitInput = 100) {
|
||||
}
|
||||
} catch (error) {
|
||||
const detail = error instanceof Error ? error.message : String(error)
|
||||
await query(
|
||||
`UPDATE semi_auto_tasks
|
||||
SET last_error = $2, updated_at = NOW()
|
||||
WHERE id = $1
|
||||
AND execution_status NOT IN ('completed', 'cancelled')`,
|
||||
[candidate.id, detail.slice(0, 1000)],
|
||||
).catch(() => undefined)
|
||||
// 对账失败只补最近错误,不得覆盖人工完成或取消状态。
|
||||
await withTransaction(async (client) => {
|
||||
await convergeSemiAutoTaskState(client, Number(candidate.id), {
|
||||
reason: 'semi_auto_reconcile_failed',
|
||||
actor: 'system',
|
||||
patch: { lastError: detail.slice(0, 1000) },
|
||||
expected: { executionStatus: [...ACTIVE_EXECUTION_STATUSES] },
|
||||
event: null,
|
||||
})
|
||||
}).catch(() => undefined)
|
||||
}
|
||||
}
|
||||
return { checked, updated }
|
||||
@@ -702,38 +707,31 @@ export async function applySemiAutoTaskStateSnapshot(
|
||||
message,
|
||||
}
|
||||
|
||||
await client.query(
|
||||
`UPDATE semi_auto_tasks
|
||||
SET login_status = $2,
|
||||
huya_uid = CASE WHEN $3 <> '' THEN $3 ELSE huya_uid END,
|
||||
platform_nickname = CASE WHEN $4 <> '' THEN $4 ELSE platform_nickname END,
|
||||
authenticated_at = CASE
|
||||
WHEN $2 = 'authenticated' THEN COALESCE(authenticated_at, NOW())
|
||||
ELSE authenticated_at
|
||||
END,
|
||||
last_error = CASE WHEN $2 IN ('failed', 'expired') THEN $5 ELSE last_error END,
|
||||
connector_state_version = $6,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1`,
|
||||
[task.id, loginStatus, uid, nickname, message, stateVersion],
|
||||
)
|
||||
if (
|
||||
loginStatus !== task.login_status ||
|
||||
uid !== task.huya_uid ||
|
||||
nickname !== task.platform_nickname
|
||||
) {
|
||||
await appendTaskEvent(client, task.id, {
|
||||
await convergeSemiAutoTaskState(client, task.id, {
|
||||
reason: 'connector_login_state_synced',
|
||||
actor: 'connector',
|
||||
patch: {
|
||||
loginStatus,
|
||||
// 空值不覆盖已有账号信息(原 CASE WHEN <> '' 语义)。
|
||||
...(uid ? { huyaUid: uid } : {}),
|
||||
...(nickname ? { platformNickname: nickname } : {}),
|
||||
...(loginStatus === 'authenticated' ? { authenticatedAt: SEMI_AUTO_COALESCE_NOW } : {}),
|
||||
...(['failed', 'expired'].includes(loginStatus) ? { lastError: message } : {}),
|
||||
connectorStateVersion: stateVersion,
|
||||
},
|
||||
event: {
|
||||
eventType: 'connector_login_state_synced',
|
||||
actorType: 'connector',
|
||||
fromLoginStatus: task.login_status,
|
||||
toLoginStatus: loginStatus,
|
||||
emit:
|
||||
loginStatus !== task.login_status ||
|
||||
uid !== task.huya_uid ||
|
||||
nickname !== task.platform_nickname,
|
||||
detail: {
|
||||
eventId,
|
||||
source: 'semi_auto_connector',
|
||||
message,
|
||||
},
|
||||
})
|
||||
}
|
||||
},
|
||||
})
|
||||
const bindingResult = await updateBindingTaskWithClient(
|
||||
client,
|
||||
task.id,
|
||||
@@ -822,63 +820,67 @@ export async function createAdminBrowserSession(
|
||||
const fallbackTarget = targets.find((item): item is { url?: string } =>
|
||||
Boolean(item && typeof item === 'object'),
|
||||
)?.url
|
||||
const targetUrl = explicitTarget || String(fallbackTarget || '')
|
||||
const ticket =
|
||||
task.platform === 'weibo'
|
||||
? await createWeiboBrowserTicket(
|
||||
{ sessionId: task.connector_session_id, targetUrl },
|
||||
task.connector_mode,
|
||||
)
|
||||
: await createHuyaBrowserTicket(
|
||||
{
|
||||
sessionId: task.connector_session_id,
|
||||
targetUrl,
|
||||
},
|
||||
task.connector_mode,
|
||||
)
|
||||
const policyTarget = getAccountBindingPolicy(task.platform).defaultTargetUrl
|
||||
const targetUrl = explicitTarget || String(fallbackTarget || '') || policyTarget
|
||||
|
||||
// 直接下发账号级 CK:不再签发一次性票据,也不做额外的 TTL。
|
||||
// 权限边界是后台登录态 + 任务领取人 + 审计日志,与「导出 CK」同一级。
|
||||
// 平台与账号必须双重对齐,避免把其它账号的 CK 写进客服浏览器。
|
||||
const credential = task.credential_id ? await loadSemiAutoCredential(task.credential_id) : null
|
||||
if (credential && credential.platform !== task.platform) {
|
||||
throw createHttpError('账号凭证与任务平台不一致,禁止下发', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_credential_platform_mismatch',
|
||||
})
|
||||
}
|
||||
const taskUid = String(task.huya_uid || '').trim()
|
||||
const credentialUid = String(credential?.platformUid || '').trim()
|
||||
if (taskUid && credentialUid && taskUid !== credentialUid) {
|
||||
throw createHttpError('账号凭证与任务账号不一致,请客户重新登录后再注入', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_credential_account_mismatch',
|
||||
})
|
||||
}
|
||||
const cookies = credential ? selectSemiAutoCredentialCookies(credential.cookies, targetUrl) : []
|
||||
if (cookies.length === 0) {
|
||||
throw createHttpError('账号 CK 不可用,请客户重新登录后再注入浏览器', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_credential_required',
|
||||
})
|
||||
}
|
||||
const payload = {
|
||||
platform: task.platform,
|
||||
targetUrl,
|
||||
cookies: cookies.map((cookie) => ({
|
||||
name: cookie.name,
|
||||
value: cookie.value,
|
||||
domain: cookie.domain,
|
||||
path: cookie.path,
|
||||
secure: cookie.secure,
|
||||
// 平台给出的过期时间要原样带给扩展,不能由扩展统一延成长期有效。
|
||||
expiresAt: cookie.expiresAt,
|
||||
})),
|
||||
}
|
||||
|
||||
await withTransaction(async (client) => {
|
||||
await client.query(
|
||||
`UPDATE semi_auto_tasks
|
||||
SET assigned_admin_user_id = COALESCE(assigned_admin_user_id, $2),
|
||||
execution_status = CASE WHEN execution_status = 'waiting_operator' THEN 'processing' ELSE execution_status END,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1`,
|
||||
[taskId, adminUserId],
|
||||
)
|
||||
await appendTaskEvent(client, taskId, {
|
||||
eventType: 'browser_session_opened',
|
||||
actorType: 'admin',
|
||||
const current = await loadTaskForUpdateWithClient(client, taskId)
|
||||
await convergeSemiAutoTaskState(client, taskId, {
|
||||
reason: 'browser_session_opened',
|
||||
actor: 'admin',
|
||||
actorId: String(adminUserId),
|
||||
detail: { targetUrl },
|
||||
patch: {
|
||||
// 已领取任务保持原领取人(原 COALESCE 语义)。
|
||||
assignedAdminUserId: current.assigned_admin_user_id
|
||||
? Number(current.assigned_admin_user_id)
|
||||
: adminUserId,
|
||||
executionStatus:
|
||||
current.execution_status === 'waiting_operator' ? 'processing' : current.execution_status,
|
||||
},
|
||||
event: { eventType: 'browser_session_opened', detail: { targetUrl } },
|
||||
})
|
||||
})
|
||||
publishSemiAutoTaskRealtimeChange(taskId, task.order_id)
|
||||
return ticket
|
||||
}
|
||||
|
||||
/**
|
||||
* 票据内的 targetUrl 只服务于创建阶段的 Cookie 序列化与审计;
|
||||
* 下发给扩展时清空,指定平台页统一由前端占位页在注入成功后打开,
|
||||
* 这样扩展只写 Cookie,不会再额外打开一个目标页标签。
|
||||
*/
|
||||
export function buildExtensionInjectionPayload(
|
||||
payload: ConnectorInjectionPayload,
|
||||
): ConnectorInjectionPayload {
|
||||
return { ...payload, targetUrl: '' }
|
||||
}
|
||||
|
||||
export async function consumeSemiAutoInjectionTicket(ticketInput: unknown) {
|
||||
const ticket = String(ticketInput || '').trim()
|
||||
if (!ticket) {
|
||||
throw createHttpError('注入票据无效', {
|
||||
statusCode: 400,
|
||||
errorCode: 'semi_auto_injection_ticket_invalid',
|
||||
})
|
||||
}
|
||||
const payload = ticket.startsWith(WEIBO_TICKET_PREFIX)
|
||||
? await consumeWeiboBrowserTicket(ticket)
|
||||
: await consumeHuyaBrowserTicket(ticket)
|
||||
return buildExtensionInjectionPayload(payload)
|
||||
return payload
|
||||
}
|
||||
|
||||
async function resolveCompletionEvidence(
|
||||
@@ -1005,39 +1007,30 @@ export async function completeAdminSemiAutoTask(
|
||||
{ client },
|
||||
)
|
||||
|
||||
const updated = await client.query<{ id: number }>(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET assigned_admin_user_id = COALESCE(assigned_admin_user_id, $2),
|
||||
execution_status = 'completed',
|
||||
completed_quantity = target_quantity,
|
||||
completed_at = NOW(),
|
||||
completion_note = $3,
|
||||
external_order_no = $4,
|
||||
completion_evidence_json = $5::jsonb,
|
||||
last_error = '',
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
RETURNING id
|
||||
`,
|
||||
[taskId, adminUserId, note, externalOrderNo, JSON.stringify({ screenshots })],
|
||||
)
|
||||
if (!updated.rows[0]) {
|
||||
throw createHttpError('半自动履约任务状态更新失败', {
|
||||
statusCode: 500,
|
||||
errorCode: 'semi_auto_task_completion_failed',
|
||||
})
|
||||
}
|
||||
await appendTaskEvent(client, taskId, {
|
||||
eventType: 'task_completed',
|
||||
actorType: 'admin',
|
||||
await convergeSemiAutoTaskState(client, taskId, {
|
||||
reason: 'task_completed',
|
||||
actor: 'admin',
|
||||
actorId: String(adminUserId),
|
||||
fromExecutionStatus: task.execution_status,
|
||||
toExecutionStatus: 'completed',
|
||||
detail: {
|
||||
note,
|
||||
patch: {
|
||||
// 已领取任务保持原领取人(原 COALESCE 语义)。
|
||||
assignedAdminUserId: task.assigned_admin_user_id
|
||||
? Number(task.assigned_admin_user_id)
|
||||
: adminUserId,
|
||||
executionStatus: 'completed',
|
||||
completedQuantity: Number(task.target_quantity || 0),
|
||||
completedAt: SEMI_AUTO_NOW,
|
||||
completionNote: note,
|
||||
externalOrderNo,
|
||||
screenshotCount: screenshots.length,
|
||||
completionEvidence: { screenshots },
|
||||
lastError: '',
|
||||
},
|
||||
event: {
|
||||
eventType: 'task_completed',
|
||||
detail: {
|
||||
note,
|
||||
externalOrderNo,
|
||||
screenshotCount: screenshots.length,
|
||||
},
|
||||
},
|
||||
})
|
||||
return { task, completedNow: true }
|
||||
@@ -1092,23 +1085,12 @@ export async function cancelAdminSemiAutoTask(
|
||||
if (task.execution_status === 'cancelled') {
|
||||
return
|
||||
}
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET execution_status = 'cancelled',
|
||||
last_error = $2,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[taskId, reason],
|
||||
)
|
||||
await appendTaskEvent(client, taskId, {
|
||||
eventType: 'task_cancelled',
|
||||
actorType: 'admin',
|
||||
await convergeSemiAutoTaskState(client, taskId, {
|
||||
reason: reason || 'admin_cancelled_without_reason',
|
||||
actor: 'admin',
|
||||
actorId: String(adminUserId),
|
||||
fromExecutionStatus: task.execution_status,
|
||||
toExecutionStatus: 'cancelled',
|
||||
detail: { reason },
|
||||
patch: { executionStatus: 'cancelled', lastError: reason },
|
||||
event: { eventType: 'task_cancelled' },
|
||||
})
|
||||
})
|
||||
if (connector.sessionId) {
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
/**
|
||||
* 半自动履约分类真实 PostgreSQL 集成测试。
|
||||
*
|
||||
* SEMI_AUTO_TASK_TEST_DATABASE_URL=postgres://... \
|
||||
* npx tsx --test src/services/semi-auto/semi-auto-category.integration.test.ts
|
||||
*
|
||||
* 覆盖:
|
||||
* 1. 分类真源在配置侧,非法值被服务层与数据库双重拒绝;
|
||||
* 2. 任务物化时把分类写成快照;
|
||||
* 3. 配置后续改动不改写历史任务快照;
|
||||
* 4. 后台列表可用分类筛选。
|
||||
*/
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
const TEST_DATABASE_URL = String(process.env.SEMI_AUTO_TASK_TEST_DATABASE_URL || '').trim()
|
||||
const skip = !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false
|
||||
|
||||
async function expectErrorCode(fn: () => Promise<unknown>, errorCode: string) {
|
||||
await assert.rejects(fn, (error: { errorCode?: string }) => {
|
||||
assert.equal(error.errorCode, errorCode)
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
test('半自动履约分类按 SKU 配置并在任务物化时固化为快照', { skip }, async () => {
|
||||
process.env.DATABASE_URL = TEST_DATABASE_URL
|
||||
const { closeDb, query } = await import('../../db/client.js')
|
||||
const { ensureSemiAutoTasksForOrder, listAdminSemiAutoTasks } =
|
||||
await import('./semi-auto-task-service.js')
|
||||
const { getManualFulfillmentConfig, saveManualFulfillmentConfig } =
|
||||
await import('../cost-center/manual-fulfillment-config-service.js')
|
||||
|
||||
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
|
||||
const orderNo = `IT-SEMI-AUTO-CATEGORY-${suffix}`
|
||||
const skuKey = `半自动分类测试-${suffix}`
|
||||
try {
|
||||
const order = await query<{ id: number }>(
|
||||
`
|
||||
INSERT INTO orders (
|
||||
provider, platform, shop_id, shop_name, platform_order_id,
|
||||
order_status, pay_status, total_amount, paid_at, created_at, updated_at
|
||||
) VALUES (
|
||||
'91kaquan', 'kuaishou-91', $1, '半自动分类测试店', $2,
|
||||
'paid', 'paid', 1000, NOW(), NOW(), NOW()
|
||||
) RETURNING id
|
||||
`,
|
||||
[`semi-auto-category-shop-${suffix}`, orderNo],
|
||||
)
|
||||
const orderId = Number(order.rows[0]?.id || 0)
|
||||
assert.ok(orderId > 0)
|
||||
const item = await query<{ id: number }>(
|
||||
`
|
||||
INSERT INTO order_items (
|
||||
order_id, sku_code, sku_name, quantity, spec_json, item_snapshot_json,
|
||||
revenue_amount_fen, revenue_basis, created_at, updated_at
|
||||
) VALUES (
|
||||
$1, $2, $3, 1, $4::jsonb, $4::jsonb,
|
||||
1000, 'order_total', NOW(), NOW()
|
||||
) RETURNING id
|
||||
`,
|
||||
[orderId, `semi-category-${suffix}`, skuKey, JSON.stringify({ skuNick: skuKey })],
|
||||
)
|
||||
const orderItemId = Number(item.rows[0]?.id || 0)
|
||||
const fulfillment = await query<{ id: number }>(
|
||||
'SELECT id FROM fulfillments WHERE order_item_id = $1 LIMIT 1',
|
||||
[orderItemId],
|
||||
)
|
||||
const fulfillmentId = Number(fulfillment.rows[0]?.id || 0)
|
||||
assert.ok(fulfillmentId > 0)
|
||||
|
||||
const config = await query<{ id: number }>(
|
||||
`
|
||||
INSERT INTO manual_fulfillment_configs (
|
||||
sku_key, platform_key, credit_quantity, cost_mode, enabled, note,
|
||||
channels_json, semi_auto_enabled, semi_auto_platform, semi_auto_category,
|
||||
semi_auto_config_json, created_at, updated_at
|
||||
) VALUES (
|
||||
$1, 'fund_cash', 100, 'fixed', TRUE, '集成测试',
|
||||
'[{"platformKey":"fund_cash","creditQuantity":100,"costMode":"fixed","enabled":true}]'::jsonb,
|
||||
TRUE, 'huya', 'direct_exchange', '{}'::jsonb, NOW(), NOW()
|
||||
) RETURNING id
|
||||
`,
|
||||
[skuKey],
|
||||
)
|
||||
const configId = Number(config.rows[0]?.id || 0)
|
||||
assert.ok(configId > 0)
|
||||
|
||||
// 配置读取侧必须把分类原样带出,供后台配置页编辑。
|
||||
const configView = await getManualFulfillmentConfig(skuKey)
|
||||
assert.equal(configView.semiAutoCategory, 'direct_exchange')
|
||||
|
||||
// 非法分类由服务层拒绝,不需要落库。
|
||||
await expectErrorCode(
|
||||
() =>
|
||||
saveManualFulfillmentConfig({
|
||||
skuKey,
|
||||
platformKey: 'fund_cash',
|
||||
creditQuantity: 100,
|
||||
semiAutoEnabled: true,
|
||||
semiAutoPlatform: 'huya',
|
||||
semiAutoCategory: 'activity',
|
||||
}),
|
||||
'manual_config_semi_auto_category_invalid',
|
||||
)
|
||||
// 数据库侧同样有 CHECK 兜底。
|
||||
await assert.rejects(() =>
|
||||
query(`UPDATE manual_fulfillment_configs SET semi_auto_category = 'activity' WHERE id = $1`, [
|
||||
configId,
|
||||
]),
|
||||
)
|
||||
|
||||
await query(
|
||||
`
|
||||
UPDATE fulfillments
|
||||
SET channel = 'manual', status = 'assigned', fulfillment_config_id = $2,
|
||||
source = 'manual_confirm', updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[fulfillmentId, configId],
|
||||
)
|
||||
await ensureSemiAutoTasksForOrder(orderNo)
|
||||
|
||||
const task = await query<{ id: number; semi_auto_category: string }>(
|
||||
'SELECT id, semi_auto_category FROM semi_auto_tasks WHERE order_item_id = $1',
|
||||
[orderItemId],
|
||||
)
|
||||
assert.equal(task.rows[0]?.semi_auto_category, 'direct_exchange')
|
||||
const taskId = Number(task.rows[0]?.id || 0)
|
||||
|
||||
const directList = await listAdminSemiAutoTasks({
|
||||
keyword: orderNo,
|
||||
category: 'direct_exchange',
|
||||
})
|
||||
assert.equal(directList.pagination.total, 1)
|
||||
assert.equal(directList.items[0]?.semiAutoCategory, 'direct_exchange')
|
||||
const presaleList = await listAdminSemiAutoTasks({ keyword: orderNo, category: 'presale' })
|
||||
assert.equal(presaleList.pagination.total, 0)
|
||||
const uncategorizedList = await listAdminSemiAutoTasks({ keyword: orderNo, category: '' })
|
||||
assert.equal(uncategorizedList.pagination.total, 0)
|
||||
|
||||
// 配置改分类后,已有任务快照不能被改写。
|
||||
await query(
|
||||
`UPDATE manual_fulfillment_configs SET semi_auto_category = 'presale', updated_at = NOW() WHERE id = $1`,
|
||||
[configId],
|
||||
)
|
||||
await ensureSemiAutoTasksForOrder(orderNo)
|
||||
const afterConfigChange = await query<{ semi_auto_category: string }>(
|
||||
'SELECT semi_auto_category FROM semi_auto_tasks WHERE id = $1',
|
||||
[taskId],
|
||||
)
|
||||
assert.equal(afterConfigChange.rows[0]?.semi_auto_category, 'direct_exchange')
|
||||
const stillAll = await listAdminSemiAutoTasks({ keyword: orderNo })
|
||||
assert.equal(stillAll.pagination.total, 1)
|
||||
const stillDirect = await listAdminSemiAutoTasks({
|
||||
keyword: orderNo,
|
||||
category: 'direct_exchange',
|
||||
})
|
||||
assert.equal(stillDirect.pagination.total, 1)
|
||||
const nowPresale = await listAdminSemiAutoTasks({ keyword: orderNo, category: 'presale' })
|
||||
assert.equal(nowPresale.pagination.total, 0)
|
||||
} finally {
|
||||
await query(`DELETE FROM orders WHERE platform_order_id = $1`, [orderNo])
|
||||
await query(`DELETE FROM manual_fulfillment_configs WHERE sku_key = $1`, [skuKey])
|
||||
await closeDb()
|
||||
}
|
||||
})
|
||||
@@ -27,6 +27,8 @@ export type SemiAutoCredentialRecord = SemiAutoCredentialPayload & {
|
||||
source: SemiAutoCredentialSource | ''
|
||||
status: 'unknown' | 'valid' | 'invalid' | 'error'
|
||||
updatedAt: string
|
||||
/** 上一次健康检查时间;用于对失效凭证的重试做节流,避免每次请求都真打平台。 */
|
||||
lastCheckedAt: string | null
|
||||
}
|
||||
|
||||
type CredentialRow = {
|
||||
@@ -38,6 +40,7 @@ type CredentialRow = {
|
||||
credential_source: SemiAutoCredentialSource | ''
|
||||
credential_status: 'unknown' | 'valid' | 'invalid' | 'error'
|
||||
credential_updated_at: string
|
||||
last_checked_at: string | null
|
||||
}
|
||||
|
||||
function normalizeCookieList(value: unknown): SemiAutoCredentialCookie[] {
|
||||
@@ -68,6 +71,20 @@ export function buildSemiAutoCredentialCookieHeader(
|
||||
cookies: SemiAutoCredentialCookie[],
|
||||
requestUrlInput: unknown,
|
||||
): string {
|
||||
return selectSemiAutoCredentialCookies(cookies, requestUrlInput)
|
||||
.map((cookie) => `${cookie.name}=${cookie.value}`)
|
||||
.join('; ')
|
||||
}
|
||||
|
||||
/**
|
||||
* 按目标 URL 过滤可下发的 Cookie(RFC 6265 的域/路径/secure/过期规则,长路径优先)。
|
||||
*
|
||||
* 浏览器注入与 `Cookie` 头拼接都只用这一处过滤,避免两套规则漂移。
|
||||
*/
|
||||
export function selectSemiAutoCredentialCookies(
|
||||
cookies: SemiAutoCredentialCookie[],
|
||||
requestUrlInput: unknown,
|
||||
): SemiAutoCredentialCookie[] {
|
||||
const requestUrl = new URL(String(requestUrlInput || '').trim())
|
||||
const hostname = requestUrl.hostname.toLowerCase()
|
||||
const requestPath = requestUrl.pathname || '/'
|
||||
@@ -93,8 +110,6 @@ export function buildSemiAutoCredentialCookieHeader(
|
||||
)
|
||||
})
|
||||
.sort((left, right) => (right.path || '/').length - (left.path || '/').length)
|
||||
.map((cookie) => `${cookie.name}=${cookie.value}`)
|
||||
.join('; ')
|
||||
}
|
||||
|
||||
function decodeCredential(row: CredentialRow): SemiAutoCredentialRecord {
|
||||
@@ -108,6 +123,7 @@ function decodeCredential(row: CredentialRow): SemiAutoCredentialRecord {
|
||||
source: row.credential_source,
|
||||
status: row.credential_status,
|
||||
updatedAt: row.credential_updated_at,
|
||||
lastCheckedAt: row.last_checked_at,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -170,7 +186,7 @@ export async function loadSemiAutoCredential(
|
||||
`
|
||||
SELECT
|
||||
id, platform, platform_uid, platform_nickname, credential_payload_json,
|
||||
credential_source, credential_status, credential_updated_at
|
||||
credential_source, credential_status, credential_updated_at, last_checked_at
|
||||
FROM semi_auto_credentials
|
||||
WHERE id = $1
|
||||
LIMIT 1
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { query, withTransaction } from '../../db/client.js'
|
||||
import { createHttpError } from '../../utils/http.js'
|
||||
import { logWarn } from '../../utils/logger.js'
|
||||
import {
|
||||
confirmHuyaBinding,
|
||||
exportHuyaSessionCredential,
|
||||
@@ -24,9 +25,14 @@ import {
|
||||
startWeiboBinding,
|
||||
} from './weibo-connector-client.js'
|
||||
import { upsertSemiAutoCredentialWithClient } from './semi-auto-credential-service.js'
|
||||
import {
|
||||
convergeSemiAutoTaskState,
|
||||
semiAutoNowPlusSeconds,
|
||||
SEMI_AUTO_COALESCE_NOW,
|
||||
SEMI_AUTO_NOW,
|
||||
} from './semi-auto-task-state-service.js'
|
||||
import { getAccountBindingPolicy } from '../account-binding/platform-policy.js'
|
||||
import {
|
||||
appendTaskEvent,
|
||||
assertCustomerProfileReady,
|
||||
assertHuyaTask,
|
||||
assertWeiboTask,
|
||||
@@ -80,13 +86,11 @@ export async function markCustomerLinkOpened(orderNoInput: unknown, taskIdInput:
|
||||
const task = await loadTaskForOrder(orderNo, taskId)
|
||||
if (!task.customer_link_opened_at) {
|
||||
await withTransaction(async (client) => {
|
||||
await client.query(
|
||||
`UPDATE semi_auto_tasks SET customer_link_opened_at = NOW(), updated_at = NOW() WHERE id = $1`,
|
||||
[taskId],
|
||||
)
|
||||
await appendTaskEvent(client, taskId, {
|
||||
eventType: 'customer_link_opened',
|
||||
actorType: 'customer',
|
||||
await convergeSemiAutoTaskState(client, taskId, {
|
||||
reason: 'customer_link_opened',
|
||||
actor: 'customer',
|
||||
patch: { customerLinkOpenedAt: SEMI_AUTO_NOW },
|
||||
event: { eventType: 'customer_link_opened' },
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -173,21 +177,15 @@ export async function savePublicTaskProfile(
|
||||
errorCode: 'semi_auto_profile_locked',
|
||||
})
|
||||
}
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET customer_game_role_name = $2,
|
||||
customer_game_role_id = $3,
|
||||
customer_game_server_zone = $4,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[current.id, profile.roleName, profile.roleId, profile.serverZone],
|
||||
)
|
||||
await appendTaskEvent(client, current.id, {
|
||||
eventType: 'customer_profile_saved',
|
||||
actorType: 'customer',
|
||||
detail: profile,
|
||||
await convergeSemiAutoTaskState(client, current.id, {
|
||||
reason: 'customer_profile_saved',
|
||||
actor: 'customer',
|
||||
patch: {
|
||||
customerGameRoleName: profile.roleName,
|
||||
customerGameRoleId: profile.roleId,
|
||||
customerGameServerZone: profile.serverZone,
|
||||
},
|
||||
event: { eventType: 'customer_profile_saved', detail: profile },
|
||||
})
|
||||
})
|
||||
publishSemiAutoTaskRealtimeChange(task.id, task.order_id)
|
||||
@@ -246,25 +244,45 @@ export async function updateLoginTask(
|
||||
options: { credentialSource?: 'qr' | 'sms'; method?: 'qr' | 'sms' } = {},
|
||||
) {
|
||||
const mapped = mapLoginUpdate(session)
|
||||
const storedCredential =
|
||||
mapped.status === 'authenticated' && mapped.hasCredential
|
||||
? task.platform === 'weibo'
|
||||
? exportWeiboSessionCredential(session.sessionId, task.connector_mode)
|
||||
: await exportHuyaSessionCredential(session.sessionId, task.connector_mode)
|
||||
: null
|
||||
if (mapped.status === 'authenticated' && !storedCredential) {
|
||||
throw createHttpError('平台登录成功但未能获取账号 CK,请联系客服处理', {
|
||||
statusCode: 502,
|
||||
errorCode: 'semi_auto_credential_export_failed',
|
||||
// 登录成功不等于可履约:账号级 CK 必须真的落库才算「已授权」。
|
||||
// 导出失败或平台未返回 CK 时保留 Connector 会话(下一次轮询还能再试一次导出),
|
||||
// 但登录状态必须落成 `failed` 并写明原因,不能让客户看到「登录成功」而实际没有 CK。
|
||||
let storedCredential: Awaited<ReturnType<typeof exportHuyaSessionCredential>> | null = null
|
||||
let credentialExportError = ''
|
||||
if (mapped.status === 'authenticated') {
|
||||
if (!mapped.hasCredential) {
|
||||
credentialExportError = '平台未返回账号 Cookie'
|
||||
} else {
|
||||
try {
|
||||
storedCredential =
|
||||
task.platform === 'weibo'
|
||||
? await exportWeiboSessionCredential(session.sessionId, task.connector_mode)
|
||||
: await exportHuyaSessionCredential(session.sessionId, task.connector_mode)
|
||||
} catch (error) {
|
||||
credentialExportError =
|
||||
error instanceof Error ? error.message : '平台登录成功但未能导出账号 CK'
|
||||
}
|
||||
}
|
||||
}
|
||||
const exportFailed = mapped.status === 'authenticated' && !storedCredential
|
||||
if (exportFailed && credentialExportError) {
|
||||
logWarn('semi-auto', '账号 CK 导出失败,保留会话等待重试', {
|
||||
taskId: task.id,
|
||||
platform: task.platform,
|
||||
error: credentialExportError,
|
||||
})
|
||||
}
|
||||
const finalLoginStatus = exportFailed ? 'failed' : mapped.status
|
||||
const finalLoginMessage = exportFailed
|
||||
? `登录成功但未能保存账号 CK(${credentialExportError || '未知原因'}),请重新登录`
|
||||
: mapped.message
|
||||
await withTransaction(async (client) => {
|
||||
const current = await loadTaskForUpdateWithClient(client, task.id)
|
||||
if (current.execution_status === 'completed' || current.execution_status === 'cancelled') {
|
||||
return
|
||||
}
|
||||
// 登录成功只代表拿到账号 CK;必须等平台角色绑定事实确认后才进入客服处理。
|
||||
const loginUpdated = { ...current, login_status: mapped.status }
|
||||
const loginUpdated = { ...current, login_status: finalLoginStatus }
|
||||
const nextExecutionStatus = deriveSemiAutoExecutionStatus(
|
||||
loginUpdated,
|
||||
current.binding_status,
|
||||
@@ -277,48 +295,34 @@ export async function updateLoginTask(
|
||||
payload: storedCredential,
|
||||
})
|
||||
: null
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET login_status = $2,
|
||||
credential_id = COALESCE($7, credential_id),
|
||||
huya_uid = CASE WHEN $3 <> '' THEN $3 ELSE huya_uid END,
|
||||
platform_nickname = CASE WHEN $4 <> '' THEN $4 ELSE platform_nickname END,
|
||||
authenticated_at = CASE WHEN $2 = 'authenticated' THEN COALESCE(authenticated_at, NOW()) ELSE authenticated_at END,
|
||||
execution_status = $5,
|
||||
last_error = CASE WHEN $2 IN ('failed', 'expired') THEN $6 ELSE '' END,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[
|
||||
current.id,
|
||||
mapped.status,
|
||||
mapped.uid,
|
||||
mapped.nickname,
|
||||
nextExecutionStatus,
|
||||
mapped.message,
|
||||
credentialId,
|
||||
],
|
||||
)
|
||||
// 轮询会每 2 秒调用一次:状态与执行状态都没变时不写事件,避免时间线被重复项淹没。
|
||||
if (
|
||||
mapped.status !== current.login_status ||
|
||||
nextExecutionStatus !== current.execution_status
|
||||
) {
|
||||
await appendTaskEvent(client, current.id, {
|
||||
await convergeSemiAutoTaskState(client, current.id, {
|
||||
reason: 'login_status_changed',
|
||||
actor: actorType,
|
||||
patch: {
|
||||
loginStatus: finalLoginStatus,
|
||||
...(credentialId ? { credentialId } : {}),
|
||||
// 空值不覆盖已有账号信息(原 CASE WHEN <> '' 语义)。
|
||||
...(mapped.uid ? { huyaUid: mapped.uid } : {}),
|
||||
...(mapped.nickname ? { platformNickname: mapped.nickname } : {}),
|
||||
...(!exportFailed && mapped.status === 'authenticated'
|
||||
? { authenticatedAt: SEMI_AUTO_COALESCE_NOW }
|
||||
: {}),
|
||||
executionStatus: nextExecutionStatus,
|
||||
lastError: ['failed', 'expired'].includes(finalLoginStatus) ? finalLoginMessage : '',
|
||||
},
|
||||
// 轮询会每 2 秒调用一次:状态与执行状态都没变时不写事件,避免时间线被重复项淹没。
|
||||
event: {
|
||||
eventType: 'login_status_changed',
|
||||
actorType,
|
||||
fromLoginStatus: current.login_status,
|
||||
toLoginStatus: mapped.status,
|
||||
fromExecutionStatus: current.execution_status,
|
||||
toExecutionStatus: nextExecutionStatus,
|
||||
emit:
|
||||
finalLoginStatus !== current.login_status ||
|
||||
nextExecutionStatus !== current.execution_status,
|
||||
detail: {
|
||||
hasCredential: mapped.hasCredential,
|
||||
message: mapped.message,
|
||||
message: finalLoginMessage,
|
||||
method: options.method || 'qr',
|
||||
},
|
||||
})
|
||||
}
|
||||
},
|
||||
})
|
||||
})
|
||||
if (mapped.status === 'authenticated' && task.platform === 'weibo') {
|
||||
const resetTask = await syncWeiboBindingSnapshot(task, session.sessionId, actorType)
|
||||
@@ -383,61 +387,54 @@ export async function startPublicLogin(orderNoInput: unknown, taskIdInput: unkno
|
||||
|
||||
const session = await createLoginSessionForTask(task, orderNo)
|
||||
await withTransaction(async (client) => {
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET connector_session_id = $2,
|
||||
login_status = 'qr_pending',
|
||||
binding_status = 'not_started',
|
||||
bind_game_account = '',
|
||||
bind_game_role = '',
|
||||
bind_game_role_id = '',
|
||||
bind_game_role_token = '',
|
||||
platform_game_role_uid = '',
|
||||
bind_game_channel = '',
|
||||
is_bind_account = FALSE,
|
||||
is_bind_role = FALSE,
|
||||
account_change_bind_time = 0,
|
||||
account_change_bind_day = 0,
|
||||
pending_bind_game_account = '',
|
||||
pending_bind_game_role = '',
|
||||
pending_bind_game_role_token = '',
|
||||
pending_platform_game_role_uid = '',
|
||||
pending_bind_game_channel = '',
|
||||
pending_bind_game_change_bind_time = 0,
|
||||
pending_bind_game_change_bind_day = 0,
|
||||
role_identity_source = '',
|
||||
verification_basis = '',
|
||||
binding_flow_state = 'binding_query_required',
|
||||
account_role_state = 'unknown',
|
||||
target_role_match = 'unknown',
|
||||
rebind_block_scope = '',
|
||||
rebind_platform_message = '',
|
||||
rebind_requested = FALSE,
|
||||
bind_confirm_state = 'idle',
|
||||
bind_confirm_message = '',
|
||||
binding_qr_issued_at = NULL,
|
||||
binding_effect_deadline_at = NULL,
|
||||
pending_role_observed_at = NULL,
|
||||
confirmed_role_observed_at = NULL,
|
||||
binding_started_at = NULL,
|
||||
bound_at = NULL,
|
||||
execution_status = 'waiting_customer',
|
||||
auth_started_at = COALESCE(auth_started_at, NOW()),
|
||||
last_error = '',
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[task.id, session.sessionId],
|
||||
)
|
||||
await appendTaskEvent(client, task.id, {
|
||||
eventType: 'login_started',
|
||||
actorType: 'customer',
|
||||
fromLoginStatus: task.login_status,
|
||||
toLoginStatus: 'qr_pending',
|
||||
fromExecutionStatus: task.execution_status,
|
||||
toExecutionStatus: 'waiting_customer',
|
||||
detail: { expiresAt: session.expiresAt },
|
||||
await convergeSemiAutoTaskState(client, task.id, {
|
||||
reason: 'login_started',
|
||||
actor: 'customer',
|
||||
patch: {
|
||||
connectorSessionId: session.sessionId,
|
||||
loginStatus: 'qr_pending',
|
||||
bindingStatus: 'not_started',
|
||||
bindGameAccount: '',
|
||||
bindGameRole: '',
|
||||
bindGameRoleId: '',
|
||||
bindGameRoleToken: '',
|
||||
platformGameRoleUid: '',
|
||||
bindGameChannel: '',
|
||||
isBindAccount: false,
|
||||
isBindRole: false,
|
||||
accountChangeBindTime: 0,
|
||||
accountChangeBindDay: 0,
|
||||
pendingBindGameAccount: '',
|
||||
pendingBindGameRole: '',
|
||||
pendingBindGameRoleToken: '',
|
||||
pendingPlatformGameRoleUid: '',
|
||||
pendingBindGameChannel: '',
|
||||
pendingBindGameChangeBindTime: 0,
|
||||
pendingBindGameChangeBindDay: 0,
|
||||
roleIdentitySource: '',
|
||||
verificationBasis: '',
|
||||
bindingFlowState: 'binding_query_required',
|
||||
accountRoleState: 'unknown',
|
||||
targetRoleMatch: 'unknown',
|
||||
rebindBlockScope: '',
|
||||
rebindPlatformMessage: '',
|
||||
rebindRequested: false,
|
||||
bindConfirmState: 'idle',
|
||||
bindConfirmMessage: '',
|
||||
bindingQrIssuedAt: null,
|
||||
bindingEffectDeadlineAt: null,
|
||||
pendingRoleObservedAt: null,
|
||||
confirmedRoleObservedAt: null,
|
||||
bindingStartedAt: null,
|
||||
boundAt: null,
|
||||
executionStatus: 'waiting_customer',
|
||||
authStartedAt: SEMI_AUTO_COALESCE_NOW,
|
||||
lastError: '',
|
||||
},
|
||||
event: {
|
||||
eventType: 'login_started',
|
||||
detail: { expiresAt: session.expiresAt },
|
||||
},
|
||||
})
|
||||
})
|
||||
const refreshedTask = await loadTask(task.id)
|
||||
@@ -546,25 +543,18 @@ export async function startPublicBinding(
|
||||
await withTransaction(async (client) => {
|
||||
const current = await loadTaskForUpdateWithClient(client, task.id)
|
||||
if (!isHuyaBindingConfirmationInFlight(current)) return
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET bind_confirm_state = 'idle',
|
||||
bind_confirm_message = '',
|
||||
binding_effect_deadline_at = NULL,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[current.id],
|
||||
)
|
||||
await appendTaskEvent(client, current.id, {
|
||||
eventType: 'huya_binding_retry_started',
|
||||
actorType: 'customer',
|
||||
fromBindingStatus: current.binding_status,
|
||||
toBindingStatus: current.binding_status,
|
||||
fromExecutionStatus: current.execution_status,
|
||||
toExecutionStatus: current.execution_status,
|
||||
detail: { previousBindConfirmState: current.bind_confirm_state },
|
||||
await convergeSemiAutoTaskState(client, current.id, {
|
||||
reason: 'huya_binding_retry_started',
|
||||
actor: 'customer',
|
||||
patch: {
|
||||
bindConfirmState: 'idle',
|
||||
bindConfirmMessage: '',
|
||||
bindingEffectDeadlineAt: null,
|
||||
},
|
||||
event: {
|
||||
eventType: 'huya_binding_retry_started',
|
||||
detail: { previousBindConfirmState: current.bind_confirm_state },
|
||||
},
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -642,60 +632,50 @@ export async function resetPublicBinding(orderNoInput: unknown, taskIdInput: unk
|
||||
errorCode: 'semi_auto_profile_locked',
|
||||
})
|
||||
}
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET binding_status = 'not_started',
|
||||
bind_game_account = '',
|
||||
bind_game_role = '',
|
||||
bind_game_role_id = '',
|
||||
bind_game_role_token = '',
|
||||
platform_game_role_uid = '',
|
||||
bind_game_channel = '',
|
||||
is_bind_account = FALSE,
|
||||
is_bind_role = FALSE,
|
||||
account_change_bind_time = 0,
|
||||
account_change_bind_day = 0,
|
||||
pending_bind_game_account = '',
|
||||
pending_bind_game_role = '',
|
||||
pending_bind_game_role_token = '',
|
||||
pending_platform_game_role_uid = '',
|
||||
pending_bind_game_channel = '',
|
||||
pending_bind_game_change_bind_time = 0,
|
||||
pending_bind_game_change_bind_day = 0,
|
||||
role_identity_source = '',
|
||||
verification_basis = '',
|
||||
binding_flow_state = 'binding_query_required',
|
||||
account_role_state = 'unknown',
|
||||
target_role_match = 'unknown',
|
||||
rebind_block_scope = '',
|
||||
rebind_platform_message = '',
|
||||
rebind_requested = FALSE,
|
||||
bind_confirm_state = 'idle',
|
||||
bind_confirm_message = '',
|
||||
binding_qr_issued_at = NULL,
|
||||
binding_effect_deadline_at = NULL,
|
||||
pending_role_observed_at = NULL,
|
||||
confirmed_role_observed_at = NULL,
|
||||
binding_started_at = NULL,
|
||||
bound_at = NULL,
|
||||
execution_status = 'waiting_customer',
|
||||
last_error = '',
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[current.id],
|
||||
)
|
||||
await appendTaskEvent(client, current.id, {
|
||||
eventType: 'binding_reset',
|
||||
actorType: 'customer',
|
||||
fromBindingStatus: current.binding_status,
|
||||
toBindingStatus: 'not_started',
|
||||
fromExecutionStatus: current.execution_status,
|
||||
toExecutionStatus: 'waiting_customer',
|
||||
detail: {
|
||||
reason: 'customer_profile_edit',
|
||||
customerProfileKept: true,
|
||||
await convergeSemiAutoTaskState(client, current.id, {
|
||||
reason: 'customer_profile_edit',
|
||||
actor: 'customer',
|
||||
patch: {
|
||||
bindingStatus: 'not_started',
|
||||
bindGameAccount: '',
|
||||
bindGameRole: '',
|
||||
bindGameRoleId: '',
|
||||
bindGameRoleToken: '',
|
||||
platformGameRoleUid: '',
|
||||
bindGameChannel: '',
|
||||
isBindAccount: false,
|
||||
isBindRole: false,
|
||||
accountChangeBindTime: 0,
|
||||
accountChangeBindDay: 0,
|
||||
pendingBindGameAccount: '',
|
||||
pendingBindGameRole: '',
|
||||
pendingBindGameRoleToken: '',
|
||||
pendingPlatformGameRoleUid: '',
|
||||
pendingBindGameChannel: '',
|
||||
pendingBindGameChangeBindTime: 0,
|
||||
pendingBindGameChangeBindDay: 0,
|
||||
roleIdentitySource: '',
|
||||
verificationBasis: '',
|
||||
bindingFlowState: 'binding_query_required',
|
||||
accountRoleState: 'unknown',
|
||||
targetRoleMatch: 'unknown',
|
||||
rebindBlockScope: '',
|
||||
rebindPlatformMessage: '',
|
||||
rebindRequested: false,
|
||||
bindConfirmState: 'idle',
|
||||
bindConfirmMessage: '',
|
||||
bindingQrIssuedAt: null,
|
||||
bindingEffectDeadlineAt: null,
|
||||
pendingRoleObservedAt: null,
|
||||
confirmedRoleObservedAt: null,
|
||||
bindingStartedAt: null,
|
||||
boundAt: null,
|
||||
executionStatus: 'waiting_customer',
|
||||
lastError: '',
|
||||
},
|
||||
event: {
|
||||
eventType: 'binding_reset',
|
||||
detail: { customerProfileKept: true },
|
||||
},
|
||||
})
|
||||
})
|
||||
@@ -758,28 +738,21 @@ async function markHuyaBindingConfirmationSubmitting(input: {
|
||||
errorCode: 'huya_bind_pending_role_changed',
|
||||
})
|
||||
}
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET bind_confirm_state = 'submitting',
|
||||
bind_confirm_message = '',
|
||||
binding_effect_deadline_at = NOW() + INTERVAL '60 seconds',
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[current.id],
|
||||
)
|
||||
await appendTaskEvent(client, current.id, {
|
||||
eventType: 'huya_binding_confirm_submitted',
|
||||
actorType: input.actorType,
|
||||
fromBindingStatus: current.binding_status,
|
||||
toBindingStatus: current.binding_status,
|
||||
fromExecutionStatus: current.execution_status,
|
||||
toExecutionStatus: current.execution_status,
|
||||
detail: {
|
||||
roleName: input.expectedRoleName,
|
||||
roleToken: input.expectedRoleToken,
|
||||
roleChannel: input.expectedRoleChannel,
|
||||
await convergeSemiAutoTaskState(client, current.id, {
|
||||
reason: 'huya_binding_confirm_submitted',
|
||||
actor: input.actorType,
|
||||
patch: {
|
||||
bindConfirmState: 'submitting',
|
||||
bindConfirmMessage: '',
|
||||
bindingEffectDeadlineAt: semiAutoNowPlusSeconds(60),
|
||||
},
|
||||
event: {
|
||||
eventType: 'huya_binding_confirm_submitted',
|
||||
detail: {
|
||||
roleName: input.expectedRoleName,
|
||||
roleToken: input.expectedRoleToken,
|
||||
roleChannel: input.expectedRoleChannel,
|
||||
},
|
||||
},
|
||||
})
|
||||
return { alreadyInFlight: false }
|
||||
@@ -971,64 +944,57 @@ export async function sendPublicHuyaSmsCode(
|
||||
const previousSessionId = task.connector_session_id
|
||||
try {
|
||||
await withTransaction(async (client) => {
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET connector_session_id = $2,
|
||||
login_status = 'waiting_login',
|
||||
binding_status = 'not_started',
|
||||
execution_status = 'waiting_customer',
|
||||
bind_game_account = '',
|
||||
bind_game_role = '',
|
||||
bind_game_role_id = '',
|
||||
bind_game_role_token = '',
|
||||
platform_game_role_uid = '',
|
||||
bind_game_channel = '',
|
||||
is_bind_account = FALSE,
|
||||
is_bind_role = FALSE,
|
||||
account_change_bind_time = 0,
|
||||
account_change_bind_day = 0,
|
||||
pending_bind_game_account = '',
|
||||
pending_bind_game_role = '',
|
||||
pending_bind_game_role_token = '',
|
||||
pending_platform_game_role_uid = '',
|
||||
pending_bind_game_channel = '',
|
||||
pending_bind_game_change_bind_time = 0,
|
||||
pending_bind_game_change_bind_day = 0,
|
||||
role_identity_source = '',
|
||||
verification_basis = '',
|
||||
binding_flow_state = 'binding_query_required',
|
||||
account_role_state = 'unknown',
|
||||
target_role_match = 'unknown',
|
||||
rebind_block_scope = '',
|
||||
rebind_platform_message = '',
|
||||
rebind_requested = FALSE,
|
||||
bind_confirm_state = 'idle',
|
||||
bind_confirm_message = '',
|
||||
binding_qr_issued_at = NULL,
|
||||
binding_effect_deadline_at = NULL,
|
||||
binding_started_at = NULL,
|
||||
pending_role_observed_at = NULL,
|
||||
confirmed_role_observed_at = NULL,
|
||||
bound_at = NULL,
|
||||
auth_started_at = COALESCE(auth_started_at, NOW()),
|
||||
last_error = '',
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[task.id, session.sessionId],
|
||||
)
|
||||
await appendTaskEvent(client, task.id, {
|
||||
eventType: result.challenge ? 'sms_verification_required' : 'sms_code_sent',
|
||||
actorType: 'customer',
|
||||
fromLoginStatus: task.login_status,
|
||||
toLoginStatus: 'waiting_login',
|
||||
fromExecutionStatus: task.execution_status,
|
||||
toExecutionStatus: 'waiting_customer',
|
||||
detail: {
|
||||
method: 'sms',
|
||||
expiresAt: session.expiresAt,
|
||||
...(result.challenge ? { verificationType: result.challenge.type } : {}),
|
||||
await convergeSemiAutoTaskState(client, task.id, {
|
||||
reason: result.challenge ? 'sms_verification_required' : 'sms_code_sent',
|
||||
actor: 'customer',
|
||||
patch: {
|
||||
connectorSessionId: session.sessionId,
|
||||
loginStatus: 'waiting_login',
|
||||
bindingStatus: 'not_started',
|
||||
executionStatus: 'waiting_customer',
|
||||
bindGameAccount: '',
|
||||
bindGameRole: '',
|
||||
bindGameRoleId: '',
|
||||
bindGameRoleToken: '',
|
||||
platformGameRoleUid: '',
|
||||
bindGameChannel: '',
|
||||
isBindAccount: false,
|
||||
isBindRole: false,
|
||||
accountChangeBindTime: 0,
|
||||
accountChangeBindDay: 0,
|
||||
pendingBindGameAccount: '',
|
||||
pendingBindGameRole: '',
|
||||
pendingBindGameRoleToken: '',
|
||||
pendingPlatformGameRoleUid: '',
|
||||
pendingBindGameChannel: '',
|
||||
pendingBindGameChangeBindTime: 0,
|
||||
pendingBindGameChangeBindDay: 0,
|
||||
roleIdentitySource: '',
|
||||
verificationBasis: '',
|
||||
bindingFlowState: 'binding_query_required',
|
||||
accountRoleState: 'unknown',
|
||||
targetRoleMatch: 'unknown',
|
||||
rebindBlockScope: '',
|
||||
rebindPlatformMessage: '',
|
||||
rebindRequested: false,
|
||||
bindConfirmState: 'idle',
|
||||
bindConfirmMessage: '',
|
||||
bindingQrIssuedAt: null,
|
||||
bindingEffectDeadlineAt: null,
|
||||
bindingStartedAt: null,
|
||||
pendingRoleObservedAt: null,
|
||||
confirmedRoleObservedAt: null,
|
||||
boundAt: null,
|
||||
authStartedAt: SEMI_AUTO_COALESCE_NOW,
|
||||
lastError: '',
|
||||
},
|
||||
event: {
|
||||
eventType: result.challenge ? 'sms_verification_required' : 'sms_code_sent',
|
||||
detail: {
|
||||
method: 'sms',
|
||||
expiresAt: session.expiresAt,
|
||||
...(result.challenge ? { verificationType: result.challenge.type } : {}),
|
||||
},
|
||||
},
|
||||
})
|
||||
})
|
||||
@@ -1093,28 +1059,21 @@ export async function verifyPublicHuyaSmsChallenge(
|
||||
task.connector_mode,
|
||||
)
|
||||
await withTransaction(async (client) => {
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET connector_session_id = $2,
|
||||
login_status = 'waiting_login',
|
||||
execution_status = 'waiting_customer',
|
||||
last_error = '',
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[task.id, result.session.sessionId],
|
||||
)
|
||||
await appendTaskEvent(client, task.id, {
|
||||
eventType: result.challenge ? 'sms_verification_required' : 'sms_code_sent',
|
||||
actorType: 'customer',
|
||||
fromLoginStatus: task.login_status,
|
||||
toLoginStatus: 'waiting_login',
|
||||
fromExecutionStatus: task.execution_status,
|
||||
toExecutionStatus: 'waiting_customer',
|
||||
detail: {
|
||||
method: 'sms',
|
||||
verificationCompleted: !result.challenge,
|
||||
await convergeSemiAutoTaskState(client, task.id, {
|
||||
reason: 'huya_sms_challenge_resolved',
|
||||
actor: 'customer',
|
||||
patch: {
|
||||
connectorSessionId: result.session.sessionId,
|
||||
loginStatus: 'waiting_login',
|
||||
executionStatus: 'waiting_customer',
|
||||
lastError: '',
|
||||
},
|
||||
event: {
|
||||
eventType: result.challenge ? 'sms_verification_required' : 'sms_code_sent',
|
||||
detail: {
|
||||
method: 'sms',
|
||||
verificationCompleted: !result.challenge,
|
||||
},
|
||||
},
|
||||
})
|
||||
})
|
||||
@@ -1249,32 +1208,44 @@ export async function loginPublicWeiboSms(
|
||||
task.connector_mode,
|
||||
)
|
||||
const mapped = mapLoginUpdate(session)
|
||||
const storedCredential =
|
||||
session.status === 'authenticated' && session.hasCredential
|
||||
? exportWeiboSessionCredential(sessionId, task.connector_mode)
|
||||
: null
|
||||
// 与扫码路径一致:导出失败不能把已完成的登录整单丢掉,但也不能声称已授权。
|
||||
let storedCredential: Awaited<ReturnType<typeof exportWeiboSessionCredential>> | null = null
|
||||
let credentialExportError = ''
|
||||
if (session.status === 'authenticated') {
|
||||
if (!session.hasCredential) {
|
||||
credentialExportError = '平台未返回账号 Cookie'
|
||||
} else {
|
||||
try {
|
||||
storedCredential = exportWeiboSessionCredential(sessionId, task.connector_mode)
|
||||
} catch (error) {
|
||||
credentialExportError =
|
||||
error instanceof Error ? error.message : '微博登录成功但未能导出账号 CK'
|
||||
}
|
||||
}
|
||||
}
|
||||
const exportFailed = session.status === 'authenticated' && !storedCredential
|
||||
if (exportFailed && credentialExportError) {
|
||||
logWarn('semi-auto', '微博账号 CK 导出失败,保留会话等待重试', {
|
||||
taskId: task.id,
|
||||
platform: task.platform,
|
||||
error: credentialExportError,
|
||||
})
|
||||
}
|
||||
|
||||
if (session.status !== 'authenticated') {
|
||||
await withTransaction(async (client) => {
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET connector_session_id = $2,
|
||||
login_status = $3,
|
||||
last_error = $4,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[task.id, sessionId, mapped.status, mapped.message],
|
||||
)
|
||||
await appendTaskEvent(client, task.id, {
|
||||
eventType: 'login_status_changed',
|
||||
actorType: 'customer',
|
||||
fromLoginStatus: task.login_status,
|
||||
toLoginStatus: mapped.status,
|
||||
fromExecutionStatus: task.execution_status,
|
||||
toExecutionStatus: task.execution_status,
|
||||
detail: { method: 'sms', message: mapped.message },
|
||||
await convergeSemiAutoTaskState(client, task.id, {
|
||||
reason: 'login_status_changed',
|
||||
actor: 'customer',
|
||||
patch: {
|
||||
connectorSessionId: sessionId,
|
||||
loginStatus: mapped.status,
|
||||
lastError: mapped.message,
|
||||
},
|
||||
event: {
|
||||
eventType: 'login_status_changed',
|
||||
detail: { method: 'sms', message: mapped.message },
|
||||
},
|
||||
})
|
||||
})
|
||||
throw createHttpError(mapped.message || '微博登录失败,请重试', {
|
||||
@@ -1284,6 +1255,10 @@ export async function loginPublicWeiboSms(
|
||||
}
|
||||
|
||||
const nextExecutionStatus: ExecutionStatus = 'waiting_customer'
|
||||
const finalLoginStatus: LoginStatus = exportFailed ? 'failed' : 'authenticated'
|
||||
const finalLoginMessage = exportFailed
|
||||
? `登录成功但未能保存账号 CK(${credentialExportError || '未知原因'}),请重新登录`
|
||||
: ''
|
||||
await withTransaction(async (client) => {
|
||||
const credentialId = storedCredential
|
||||
? await upsertSemiAutoCredentialWithClient(client, {
|
||||
@@ -1292,37 +1267,42 @@ export async function loginPublicWeiboSms(
|
||||
payload: storedCredential,
|
||||
})
|
||||
: null
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET connector_session_id = $2,
|
||||
credential_id = COALESCE($5, credential_id),
|
||||
login_status = 'authenticated',
|
||||
execution_status = $6,
|
||||
huya_uid = CASE WHEN $3 <> '' THEN $3 ELSE huya_uid END,
|
||||
platform_nickname = CASE WHEN $4 <> '' THEN $4 ELSE platform_nickname END,
|
||||
auth_started_at = COALESCE(auth_started_at, NOW()),
|
||||
authenticated_at = COALESCE(authenticated_at, NOW()),
|
||||
last_error = '',
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[task.id, sessionId, mapped.uid, mapped.nickname, credentialId, nextExecutionStatus],
|
||||
)
|
||||
await appendTaskEvent(client, task.id, {
|
||||
eventType: 'login_status_changed',
|
||||
actorType: 'customer',
|
||||
fromLoginStatus: task.login_status,
|
||||
toLoginStatus: 'authenticated',
|
||||
fromExecutionStatus: task.execution_status,
|
||||
toExecutionStatus: nextExecutionStatus,
|
||||
detail: { method: 'sms', hasCredential: mapped.hasCredential, message: mapped.message },
|
||||
await convergeSemiAutoTaskState(client, task.id, {
|
||||
reason: 'login_status_changed',
|
||||
actor: 'customer',
|
||||
patch: {
|
||||
connectorSessionId: sessionId,
|
||||
...(credentialId ? { credentialId } : {}),
|
||||
loginStatus: finalLoginStatus,
|
||||
executionStatus: finalLoginStatus === 'failed' ? 'waiting_customer' : nextExecutionStatus,
|
||||
// 空值不覆盖已有账号信息(原 CASE WHEN <> '' 语义)。
|
||||
...(mapped.uid ? { huyaUid: mapped.uid } : {}),
|
||||
...(mapped.nickname ? { platformNickname: mapped.nickname } : {}),
|
||||
authStartedAt: SEMI_AUTO_COALESCE_NOW,
|
||||
...(exportFailed ? {} : { authenticatedAt: SEMI_AUTO_COALESCE_NOW }),
|
||||
lastError: finalLoginMessage,
|
||||
},
|
||||
event: {
|
||||
eventType: 'login_status_changed',
|
||||
detail: {
|
||||
method: 'sms',
|
||||
hasCredential: mapped.hasCredential,
|
||||
message: finalLoginMessage || mapped.message,
|
||||
},
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
if (previousSessionId && previousSessionId !== sessionId) {
|
||||
await revokeWeiboSession(previousSessionId, task.connector_mode).catch(() => undefined)
|
||||
}
|
||||
if (exportFailed) {
|
||||
// 状态已落成 failed,这里再把原因抛给客户,避免前端按“登录成功”继续往下走。
|
||||
throw createHttpError(finalLoginMessage, {
|
||||
statusCode: 409,
|
||||
errorCode: 'weibo_credential_export_failed',
|
||||
})
|
||||
}
|
||||
const resetTask = await syncWeiboBindingSnapshot(task, sessionId, 'customer')
|
||||
if (resetTask) {
|
||||
throw createHttpError('微博登录状态已失效,请重新登录', {
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { describe, it } from 'node:test'
|
||||
|
||||
import { buildExtensionInjectionPayload } from './semi-auto-task-service.js'
|
||||
|
||||
const payload = {
|
||||
platform: 'weibo' as const,
|
||||
targetUrl: 'https://weibo.com/',
|
||||
expiresAt: '2026-11-17T00:00:00.000Z',
|
||||
cookies: [
|
||||
{
|
||||
name: 'SUB',
|
||||
value: 'weibo-sub',
|
||||
domain: '.weibo.com',
|
||||
path: '/',
|
||||
secure: true,
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
describe('下发给扩展的注入载荷', () => {
|
||||
it('清空 targetUrl,避免扩展额外打开目标页', () => {
|
||||
const result = buildExtensionInjectionPayload(payload)
|
||||
assert.equal(result.targetUrl, '')
|
||||
assert.equal(result.platform, 'weibo')
|
||||
assert.equal(result.expiresAt, payload.expiresAt)
|
||||
assert.deepEqual(result.cookies, payload.cookies)
|
||||
})
|
||||
|
||||
it('不修改票据内的原始载荷(Cookie 序列化仍依赖原 targetUrl)', () => {
|
||||
buildExtensionInjectionPayload(payload)
|
||||
assert.equal(payload.targetUrl, 'https://weibo.com/')
|
||||
})
|
||||
})
|
||||
@@ -21,7 +21,6 @@ import {
|
||||
} from '../file-storage/file-storage-service.js'
|
||||
import {
|
||||
defaultSemiAutoConnectorMode,
|
||||
createHuyaBrowserTicket,
|
||||
createHuyaLoginSession,
|
||||
exportHuyaSessionCredential,
|
||||
getHuyaBinding,
|
||||
@@ -31,16 +30,12 @@ import {
|
||||
restoreHuyaSessionFromCredential,
|
||||
revokeHuyaSession,
|
||||
sendHuyaSmsCode,
|
||||
consumeHuyaBrowserTicket,
|
||||
verifyHuyaSmsChallenge,
|
||||
type ConnectorBindingSession,
|
||||
type ConnectorInjectionPayload,
|
||||
type SemiAutoConnectorMode,
|
||||
type ConnectorLoginSession,
|
||||
} from './huya-connector-client.js'
|
||||
import {
|
||||
consumeWeiboBrowserTicket,
|
||||
createWeiboBrowserTicket,
|
||||
createWeiboLoginSession,
|
||||
exportWeiboSessionCredential,
|
||||
getWeiboBinding,
|
||||
@@ -51,7 +46,6 @@ import {
|
||||
revokeWeiboSession,
|
||||
sendWeiboSmsCode,
|
||||
} from './weibo-connector-client.js'
|
||||
import { WEIBO_TICKET_PREFIX } from './weibo-native/weibo-native-connector.js'
|
||||
import {
|
||||
buildSemiAutoCredentialCookieHeader,
|
||||
loadSemiAutoCredential,
|
||||
@@ -60,6 +54,10 @@ import {
|
||||
type SemiAutoCredentialCookie,
|
||||
} from './semi-auto-credential-service.js'
|
||||
import { querySemiAutoTraces } from './semi-auto-trace.js'
|
||||
import {
|
||||
convergeSemiAutoTaskState,
|
||||
SEMI_AUTO_COALESCE_NOW,
|
||||
} from './semi-auto-task-state-service.js'
|
||||
import { isHuyaRoleToken, isNumericBindingRoleId } from './binding-role-id.js'
|
||||
import { normalizeBindingRoleName, resolveServerZone } from '../account-binding/binding-identity.js'
|
||||
import { getAccountBindingPolicy } from '../account-binding/platform-policy.js'
|
||||
@@ -184,6 +182,7 @@ export type TaskRow = {
|
||||
manual_platform_key: string
|
||||
manual_cost_mode: string
|
||||
manual_credit_quantity: number | string
|
||||
semi_auto_category: string
|
||||
semi_auto_config_json: Record<string, unknown>
|
||||
}
|
||||
|
||||
@@ -355,41 +354,26 @@ export async function refreshHuyaBindingDecisionForTask(
|
||||
current.binding_status,
|
||||
bindingDecision,
|
||||
)
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET binding_flow_state = $2,
|
||||
account_role_state = $3,
|
||||
target_role_match = $4,
|
||||
rebind_block_scope = $5,
|
||||
execution_status = $6,
|
||||
bound_at = CASE WHEN $7 THEN COALESCE(bound_at, NOW()) ELSE NULL END,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[
|
||||
current.id,
|
||||
bindingDecision.flowState,
|
||||
bindingDecision.accountRoleState,
|
||||
bindingDecision.targetRoleMatch,
|
||||
bindingDecision.rebindBlockScope,
|
||||
executionStatus,
|
||||
bindingDecision.flowState === 'confirmed',
|
||||
],
|
||||
)
|
||||
if (
|
||||
const boundConfirmed = bindingDecision.flowState === 'confirmed'
|
||||
const decisionChanged =
|
||||
current.binding_flow_state !== bindingDecision.flowState ||
|
||||
current.execution_status !== executionStatus ||
|
||||
current.account_role_state !== bindingDecision.accountRoleState ||
|
||||
current.target_role_match !== bindingDecision.targetRoleMatch
|
||||
) {
|
||||
await appendTaskEvent(client, current.id, {
|
||||
await convergeSemiAutoTaskState(client, current.id, {
|
||||
reason: 'huya_binding_decision_recomputed',
|
||||
actor: actorType,
|
||||
patch: {
|
||||
bindingFlowState: bindingDecision.flowState,
|
||||
accountRoleState: bindingDecision.accountRoleState,
|
||||
targetRoleMatch: bindingDecision.targetRoleMatch,
|
||||
rebindBlockScope: bindingDecision.rebindBlockScope,
|
||||
executionStatus,
|
||||
boundAt: boundConfirmed ? SEMI_AUTO_COALESCE_NOW : null,
|
||||
},
|
||||
event: {
|
||||
eventType,
|
||||
actorType,
|
||||
fromBindingStatus: current.binding_status,
|
||||
toBindingStatus: current.binding_status,
|
||||
fromExecutionStatus: current.execution_status,
|
||||
toExecutionStatus: executionStatus,
|
||||
emit: decisionChanged,
|
||||
detail: {
|
||||
bindingFlowState: bindingDecision.flowState,
|
||||
primaryAction: bindingDecision.primaryAction,
|
||||
@@ -400,8 +384,8 @@ export async function refreshHuyaBindingDecisionForTask(
|
||||
targetRoleRebindAvailableAt: bindingDecision.targetRoleRebindAvailableAt,
|
||||
message: bindingDecision.message,
|
||||
},
|
||||
})
|
||||
}
|
||||
},
|
||||
})
|
||||
return current
|
||||
})
|
||||
if (!result) return loadTask(taskId)
|
||||
@@ -536,6 +520,7 @@ export function mapTask(task: TaskRow) {
|
||||
loginStatus: task.login_status,
|
||||
bindingStatus: task.binding_status,
|
||||
executionStatus: task.execution_status,
|
||||
semiAutoCategory: task.semi_auto_category || '',
|
||||
connectorMode: task.connector_mode,
|
||||
connectorStateVersion: Number(task.connector_state_version || 0),
|
||||
displayStatus: displayStatus(task, bindingDecision),
|
||||
@@ -834,66 +819,55 @@ export async function resetTaskForCustomerLogin(
|
||||
if (current.execution_status === 'completed' || current.execution_status === 'cancelled') {
|
||||
return
|
||||
}
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET connector_session_id = '',
|
||||
login_status = 'waiting_login',
|
||||
binding_status = 'not_started',
|
||||
execution_status = 'waiting_customer',
|
||||
bind_game_account = '',
|
||||
bind_game_role = '',
|
||||
bind_game_role_id = '',
|
||||
bind_game_role_token = '',
|
||||
platform_game_role_uid = '',
|
||||
bind_game_channel = '',
|
||||
is_bind_account = FALSE,
|
||||
is_bind_role = FALSE,
|
||||
account_change_bind_time = 0,
|
||||
account_change_bind_day = 0,
|
||||
pending_bind_game_account = '',
|
||||
pending_bind_game_role = '',
|
||||
pending_bind_game_role_token = '',
|
||||
pending_platform_game_role_uid = '',
|
||||
pending_bind_game_channel = '',
|
||||
pending_bind_game_change_bind_time = 0,
|
||||
pending_bind_game_change_bind_day = 0,
|
||||
role_identity_source = '',
|
||||
verification_basis = '',
|
||||
binding_flow_state = 'binding_query_required',
|
||||
account_role_state = 'unknown',
|
||||
target_role_match = 'unknown',
|
||||
rebind_block_scope = '',
|
||||
rebind_platform_message = '',
|
||||
rebind_requested = FALSE,
|
||||
bind_confirm_state = 'idle',
|
||||
bind_confirm_message = '',
|
||||
binding_qr_issued_at = NULL,
|
||||
binding_effect_deadline_at = NULL,
|
||||
pending_role_observed_at = NULL,
|
||||
confirmed_role_observed_at = NULL,
|
||||
customer_link_opened_at = NULL,
|
||||
auth_started_at = NULL,
|
||||
authenticated_at = NULL,
|
||||
binding_started_at = NULL,
|
||||
bound_at = NULL,
|
||||
last_error = $2,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[task.id, input.reason],
|
||||
)
|
||||
await appendTaskEvent(client, task.id, {
|
||||
eventType: input.eventType,
|
||||
actorType: input.actorType,
|
||||
await convergeSemiAutoTaskState(client, current.id, {
|
||||
reason: input.reason,
|
||||
actor: input.actorType,
|
||||
...(input.actorId ? { actorId: input.actorId } : {}),
|
||||
fromLoginStatus: current.login_status,
|
||||
toLoginStatus: 'waiting_login',
|
||||
fromBindingStatus: current.binding_status,
|
||||
toBindingStatus: 'not_started',
|
||||
fromExecutionStatus: current.execution_status,
|
||||
toExecutionStatus: 'waiting_customer',
|
||||
detail: { reason: input.reason },
|
||||
patch: {
|
||||
connectorSessionId: '',
|
||||
loginStatus: 'waiting_login',
|
||||
bindingStatus: 'not_started',
|
||||
executionStatus: 'waiting_customer',
|
||||
bindGameAccount: '',
|
||||
bindGameRole: '',
|
||||
bindGameRoleId: '',
|
||||
bindGameRoleToken: '',
|
||||
platformGameRoleUid: '',
|
||||
bindGameChannel: '',
|
||||
isBindAccount: false,
|
||||
isBindRole: false,
|
||||
accountChangeBindTime: 0,
|
||||
accountChangeBindDay: 0,
|
||||
pendingBindGameAccount: '',
|
||||
pendingBindGameRole: '',
|
||||
pendingBindGameRoleToken: '',
|
||||
pendingPlatformGameRoleUid: '',
|
||||
pendingBindGameChannel: '',
|
||||
pendingBindGameChangeBindTime: 0,
|
||||
pendingBindGameChangeBindDay: 0,
|
||||
roleIdentitySource: '',
|
||||
verificationBasis: '',
|
||||
bindingFlowState: 'binding_query_required',
|
||||
accountRoleState: 'unknown',
|
||||
targetRoleMatch: 'unknown',
|
||||
rebindBlockScope: '',
|
||||
rebindPlatformMessage: '',
|
||||
rebindRequested: false,
|
||||
bindConfirmState: 'idle',
|
||||
bindConfirmMessage: '',
|
||||
bindingQrIssuedAt: null,
|
||||
bindingEffectDeadlineAt: null,
|
||||
pendingRoleObservedAt: null,
|
||||
confirmedRoleObservedAt: null,
|
||||
customerLinkOpenedAt: null,
|
||||
authStartedAt: null,
|
||||
authenticatedAt: null,
|
||||
bindingStartedAt: null,
|
||||
boundAt: null,
|
||||
lastError: input.reason,
|
||||
},
|
||||
// reason 已由写入服务写入 detail.reason。
|
||||
event: { eventType: input.eventType },
|
||||
})
|
||||
})
|
||||
publishAdminOrderRealtimeChange(Number(task.order_id))
|
||||
@@ -932,17 +906,22 @@ export async function ensureConnectorSessionForTask(task: TaskRow): Promise<Task
|
||||
}
|
||||
if (!task.credential_id) return task
|
||||
const credential = await loadSemiAutoCredential(task.credential_id)
|
||||
if (
|
||||
!credential ||
|
||||
credential.platform !== task.platform ||
|
||||
credential.status === 'invalid' ||
|
||||
credential.status === 'error' ||
|
||||
credential.cookies.length === 0
|
||||
) {
|
||||
if (!credential || credential.platform !== task.platform || credential.cookies.length === 0) {
|
||||
return task
|
||||
}
|
||||
// 凭证健康状态只是上一次检查的结论,不是永久黑名单:
|
||||
// CK 可能只是当时网络或平台限流误判。但客户页每 2 秒轮询一次,
|
||||
// 所以失效凭证的「重新验证」必须节流,否则会把每一次轮询都变成一次平台请求。
|
||||
if (task.platform === 'huya' && task.connector_mode !== 'embedded') return task
|
||||
if (credential.status === 'invalid' || credential.status === 'error') {
|
||||
// 已经被重置为待登录的任务不再反复验证:客户重新登录会 upsert 同一行并置回 valid。
|
||||
if (task.login_status !== 'authenticated') return task
|
||||
const checkedAtMs = credential.lastCheckedAt ? Date.parse(credential.lastCheckedAt) : NaN
|
||||
const retryWindowMs = 60 * 1000
|
||||
if (Number.isFinite(checkedAtMs) && Date.now() - checkedAtMs < retryWindowMs) return task
|
||||
}
|
||||
try {
|
||||
await assertCredentialMatchesTaskAccount(task, credential.platformUid)
|
||||
const session =
|
||||
task.platform === 'weibo'
|
||||
? await restoreWeiboSessionFromCredential(
|
||||
@@ -963,25 +942,24 @@ export async function ensureConnectorSessionForTask(task: TaskRow): Promise<Task
|
||||
)
|
||||
await markSemiAutoCredentialCheck(task.credential_id, { status: 'valid' })
|
||||
await withTransaction(async (client) => {
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET connector_session_id = $2,
|
||||
login_status = 'authenticated',
|
||||
huya_uid = CASE WHEN $3 <> '' THEN $3 ELSE huya_uid END,
|
||||
platform_nickname = CASE WHEN $4 <> '' THEN $4 ELSE platform_nickname END,
|
||||
last_error = '',
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[task.id, session.sessionId, session.huyaUid, session.nickname],
|
||||
)
|
||||
await appendTaskEvent(client, task.id, {
|
||||
eventType: 'credential_session_restored',
|
||||
actorType: 'connector',
|
||||
detail: {
|
||||
credentialId: task.credential_id,
|
||||
hasCredential: session.hasCredential,
|
||||
const current = await loadTaskForUpdateWithClient(client, task.id)
|
||||
await convergeSemiAutoTaskState(client, current.id, {
|
||||
reason: 'credential_session_restored',
|
||||
actor: 'connector',
|
||||
patch: {
|
||||
connectorSessionId: session.sessionId,
|
||||
loginStatus: 'authenticated',
|
||||
// 空值不覆盖已有账号信息(原 CASE WHEN <> '' 语义)。
|
||||
...(session.huyaUid ? { huyaUid: session.huyaUid } : {}),
|
||||
...(session.nickname ? { platformNickname: session.nickname } : {}),
|
||||
lastError: '',
|
||||
},
|
||||
event: {
|
||||
eventType: 'credential_session_restored',
|
||||
detail: {
|
||||
credentialId: task.credential_id,
|
||||
hasCredential: session.hasCredential,
|
||||
},
|
||||
},
|
||||
})
|
||||
})
|
||||
@@ -1011,19 +989,11 @@ async function restoreHuyaSession(
|
||||
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,
|
||||
platformUid: String(platformUid || '').trim(),
|
||||
nickname,
|
||||
cookies,
|
||||
},
|
||||
@@ -1031,6 +1001,25 @@ async function restoreHuyaSession(
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 账号级 CK 与任务账号必须一致(虎牙、微博共用账号凭证表)。
|
||||
*
|
||||
* 之前只有虎牙恢复路径做了这层比对,微博恢复只校验「Cookie 自身账号 == 凭证账号」,
|
||||
* 任务换过账号时会把旧账号的 CK 恢复进当前任务。这里统一成任务级校验。
|
||||
*/
|
||||
async function assertCredentialMatchesTaskAccount(task: TaskRow, platformUid: string) {
|
||||
const expectedUid = String(task.huya_uid || '').trim()
|
||||
const credentialUid = String(platformUid || '').trim()
|
||||
if (!expectedUid || !credentialUid || expectedUid === credentialUid) return
|
||||
throw createHttpError(
|
||||
`${task.platform === 'weibo' ? '微博' : '虎牙'} CK 与任务账号不一致,请重新登录`,
|
||||
{
|
||||
statusCode: 409,
|
||||
errorCode: `${task.platform}_credential_account_mismatch`,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
type SemiAutoCandidate = {
|
||||
order_id: number
|
||||
platform_order_id: string
|
||||
@@ -1038,6 +1027,7 @@ type SemiAutoCandidate = {
|
||||
fulfillment_id: number
|
||||
manual_fulfillment_config_id: number
|
||||
platform: SemiAutoPlatform
|
||||
semi_auto_category: string
|
||||
quantity: number
|
||||
}
|
||||
|
||||
@@ -1086,25 +1076,19 @@ async function cancelIneligibleSemiAutoTasksWithClient(client: PoolClient, order
|
||||
const orderIds = new Set<number>()
|
||||
for (const task of active.rows) {
|
||||
if (task.config_eligible) continue
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET execution_status = 'cancelled',
|
||||
last_error = '人工履约配置已停用半自动履约或不再满足人工渠道条件',
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[task.id],
|
||||
)
|
||||
await appendTaskEvent(client, task.id, {
|
||||
eventType: 'task_cancelled_config_ineligible',
|
||||
actorType: 'system',
|
||||
fromExecutionStatus: task.execution_status,
|
||||
toExecutionStatus: 'cancelled',
|
||||
detail: {
|
||||
reason: 'manual_semi_auto_config_ineligible',
|
||||
desiredConfigId: task.desired_config_id,
|
||||
desiredPlatform: task.desired_platform,
|
||||
await convergeSemiAutoTaskState(client, Number(task.id), {
|
||||
reason: 'manual_semi_auto_config_ineligible',
|
||||
actor: 'system',
|
||||
patch: {
|
||||
executionStatus: 'cancelled',
|
||||
lastError: '人工履约配置已停用半自动履约或不再满足人工渠道条件',
|
||||
},
|
||||
event: {
|
||||
eventType: 'task_cancelled_config_ineligible',
|
||||
detail: {
|
||||
desiredConfigId: task.desired_config_id,
|
||||
desiredPlatform: task.desired_platform,
|
||||
},
|
||||
},
|
||||
})
|
||||
orderIds.add(Number(task.order_id))
|
||||
@@ -1153,6 +1137,7 @@ async function insertMissingSemiAutoTasksWithClient(
|
||||
f.id AS fulfillment_id,
|
||||
cfg.id AS manual_fulfillment_config_id,
|
||||
cfg.semi_auto_platform AS platform,
|
||||
cfg.semi_auto_category AS semi_auto_category,
|
||||
GREATEST(1, COALESCE(oi.quantity, 1))::int AS quantity
|
||||
FROM orders o
|
||||
JOIN order_items oi ON oi.order_id = o.id
|
||||
@@ -1200,40 +1185,34 @@ async function insertMissingSemiAutoTasksWithClient(
|
||||
task.platform === row.platform,
|
||||
)
|
||||
if (matching) {
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET fulfillment_id = $2,
|
||||
target_quantity = $3,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[matching.id, Number(row.fulfillment_id), Number(row.quantity || 1)],
|
||||
)
|
||||
await convergeSemiAutoTaskState(client, Number(matching.id), {
|
||||
reason: 'task_config_rebound',
|
||||
actor: 'system',
|
||||
patch: {
|
||||
fulfillmentId: Number(row.fulfillment_id),
|
||||
targetQuantity: Number(row.quantity || 1),
|
||||
},
|
||||
// 原入口只同步配置关联与目标数量,不写事件。
|
||||
event: null,
|
||||
})
|
||||
continue
|
||||
}
|
||||
for (const stale of activeTasks.rows) {
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET execution_status = 'cancelled',
|
||||
last_error = '人工履约配置已切换半自动平台,旧任务自动终止',
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[stale.id],
|
||||
)
|
||||
await appendTaskEvent(client, stale.id, {
|
||||
eventType: 'task_cancelled_config_changed',
|
||||
actorType: 'system',
|
||||
fromExecutionStatus: stale.execution_status,
|
||||
toExecutionStatus: 'cancelled',
|
||||
detail: {
|
||||
reason: 'manual_semi_auto_config_changed',
|
||||
fromConfigId: Number(stale.manual_fulfillment_config_id || 0),
|
||||
fromPlatform: stale.platform,
|
||||
toConfigId: Number(row.manual_fulfillment_config_id),
|
||||
toPlatform: row.platform,
|
||||
await convergeSemiAutoTaskState(client, Number(stale.id), {
|
||||
reason: 'manual_semi_auto_config_changed',
|
||||
actor: 'system',
|
||||
patch: {
|
||||
executionStatus: 'cancelled',
|
||||
lastError: '人工履约配置已切换半自动平台,旧任务自动终止',
|
||||
},
|
||||
event: {
|
||||
eventType: 'task_cancelled_config_changed',
|
||||
detail: {
|
||||
fromConfigId: Number(stale.manual_fulfillment_config_id || 0),
|
||||
fromPlatform: stale.platform,
|
||||
toConfigId: Number(row.manual_fulfillment_config_id),
|
||||
toPlatform: row.platform,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1241,8 +1220,8 @@ async function insertMissingSemiAutoTasksWithClient(
|
||||
`
|
||||
INSERT INTO semi_auto_tasks (
|
||||
order_id, order_item_id, fulfillment_id, manual_fulfillment_config_id,
|
||||
platform, connector_mode, target_quantity, created_at, updated_at
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, NOW(), NOW())
|
||||
platform, connector_mode, target_quantity, semi_auto_category, created_at, updated_at
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, NOW(), NOW())
|
||||
ON CONFLICT (order_item_id) WHERE execution_status <> 'cancelled' DO NOTHING
|
||||
RETURNING id
|
||||
`,
|
||||
@@ -1254,6 +1233,7 @@ async function insertMissingSemiAutoTasksWithClient(
|
||||
row.platform,
|
||||
connectorMode,
|
||||
Number(row.quantity || 1),
|
||||
String(row.semi_auto_category || ''),
|
||||
],
|
||||
)
|
||||
const taskId = Number(inserted.rows[0]?.id || 0)
|
||||
@@ -1651,98 +1631,8 @@ export async function updateBindingTaskWithClient(
|
||||
const bindingFlowState =
|
||||
bindingDecision?.flowState || current.binding_flow_state || 'binding_query_required'
|
||||
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
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_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,
|
||||
is_bind_account = CASE WHEN $32 THEN $18 ELSE is_bind_account END,
|
||||
is_bind_role = CASE WHEN $32 THEN $19 ELSE is_bind_role END,
|
||||
account_change_bind_time = CASE WHEN $32 THEN $20 ELSE account_change_bind_time END,
|
||||
account_change_bind_day = CASE WHEN $32 THEN $21 ELSE account_change_bind_day END,
|
||||
pending_bind_game_account = $9,
|
||||
pending_bind_game_role = $10,
|
||||
pending_bind_game_role_token = $11,
|
||||
pending_platform_game_role_uid = $35,
|
||||
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_flow_state = CASE WHEN $34 THEN $22 ELSE binding_flow_state END,
|
||||
account_role_state = CASE WHEN $34 THEN $23 ELSE account_role_state END,
|
||||
target_role_match = CASE WHEN $34 THEN $24 ELSE target_role_match END,
|
||||
rebind_block_scope = CASE WHEN $34 THEN $25 ELSE rebind_block_scope END,
|
||||
rebind_platform_message = $26,
|
||||
rebind_requested = $27,
|
||||
bind_confirm_state = $28,
|
||||
bind_confirm_message = $29,
|
||||
binding_effect_deadline_at = $30,
|
||||
binding_qr_issued_at = CASE
|
||||
WHEN $2 = 'qr_pending' AND $31 THEN COALESCE(binding_qr_issued_at, NOW())
|
||||
WHEN $2 IN ('not_started', 'failed', 'expired') THEN NULL
|
||||
ELSE binding_qr_issued_at
|
||||
END,
|
||||
pending_role_observed_at = CASE
|
||||
WHEN $10 <> '' THEN COALESCE(pending_role_observed_at, NOW())
|
||||
ELSE NULL
|
||||
END,
|
||||
confirmed_role_observed_at = CASE
|
||||
WHEN $33 THEN COALESCE(confirmed_role_observed_at, NOW())
|
||||
ELSE confirmed_role_observed_at
|
||||
END,
|
||||
binding_started_at = CASE
|
||||
WHEN $2 = 'qr_pending' THEN COALESCE(binding_started_at, NOW())
|
||||
ELSE binding_started_at
|
||||
END,
|
||||
bound_at = CASE WHEN $33 THEN COALESCE(bound_at, NOW()) ELSE NULL END,
|
||||
execution_status = $6,
|
||||
last_error = CASE WHEN $2 IN ('failed', 'expired') THEN $7 ELSE '' END,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[
|
||||
current.id,
|
||||
mapped.status,
|
||||
mapped.bindGameAccount,
|
||||
mapped.bindGameRole,
|
||||
mapped.bindGameChannel,
|
||||
executionStatus,
|
||||
mapped.message,
|
||||
mapped.bindGameRoleToken,
|
||||
mapped.pendingBindGameAccount,
|
||||
mapped.pendingBindGameRole,
|
||||
mapped.pendingBindGameRoleToken,
|
||||
mapped.pendingBindGameChannel,
|
||||
mapped.pendingBindGameChangeBindTime,
|
||||
mapped.pendingBindGameChangeBindDay,
|
||||
mapped.roleIdentitySource,
|
||||
mapped.verificationBasis,
|
||||
mapped.platformGameRoleUid,
|
||||
accountFactsObserved ? mapped.isBindAccount : current.is_bind_account,
|
||||
accountFactsObserved ? mapped.isBindRole : current.is_bind_role,
|
||||
accountFactsObserved ? mapped.accountChangeBindTime : current.account_change_bind_time,
|
||||
accountFactsObserved ? mapped.accountChangeBindDay : current.account_change_bind_day,
|
||||
bindingFlowState,
|
||||
bindingDecision?.accountRoleState || current.account_role_state,
|
||||
bindingDecision?.targetRoleMatch || current.target_role_match,
|
||||
bindingDecision?.rebindBlockScope || '',
|
||||
mapped.rebindConfirmMessage,
|
||||
mapped.rebindRequested,
|
||||
mapped.bindConfirmState,
|
||||
mapped.bindConfirmMessage,
|
||||
mapped.bindingEffectDeadlineAt || null,
|
||||
Boolean(mapped.qrImage || mapped.qrExpiresAt),
|
||||
accountFactsObserved,
|
||||
bindingConfirmed,
|
||||
current.platform === 'huya',
|
||||
mapped.pendingPlatformGameRoleUid,
|
||||
],
|
||||
)
|
||||
const hasBindingQr = Boolean(mapped.qrImage || mapped.qrExpiresAt)
|
||||
const isHuyaTask = current.platform === 'huya'
|
||||
const bindingChanged =
|
||||
mapped.status !== current.binding_status ||
|
||||
executionStatus !== current.execution_status ||
|
||||
@@ -1752,14 +1642,67 @@ export async function updateBindingTaskWithClient(
|
||||
(mapped.bindingEffectDeadlineAt || null) !== current.binding_effect_deadline_at ||
|
||||
mapped.rebindUnchanged ||
|
||||
mapped.rebindConfirmState === 'rejected'
|
||||
if (bindingChanged) {
|
||||
await appendTaskEvent(client, current.id, {
|
||||
|
||||
await convergeSemiAutoTaskState(client, current.id, {
|
||||
reason: options.eventType || 'binding_status_changed',
|
||||
actor: actorType,
|
||||
patch: {
|
||||
bindingStatus: mapped.status,
|
||||
// 空值不覆盖已保存的平台事实(原 CASE WHEN <> '' 语义)。
|
||||
bindGameAccount: mapped.bindGameAccount || current.bind_game_account,
|
||||
bindGameRole: mapped.bindGameRole || current.bind_game_role,
|
||||
bindGameRoleToken: mapped.bindGameRoleToken || current.bind_game_role_token,
|
||||
bindGameChannel: mapped.bindGameChannel || current.bind_game_channel,
|
||||
isBindAccount: accountFactsObserved ? mapped.isBindAccount : current.is_bind_account,
|
||||
isBindRole: accountFactsObserved ? mapped.isBindRole : current.is_bind_role,
|
||||
accountChangeBindTime: accountFactsObserved
|
||||
? mapped.accountChangeBindTime
|
||||
: Number(current.account_change_bind_time || 0),
|
||||
accountChangeBindDay: accountFactsObserved
|
||||
? mapped.accountChangeBindDay
|
||||
: Number(current.account_change_bind_day || 0),
|
||||
pendingBindGameAccount: mapped.pendingBindGameAccount,
|
||||
pendingBindGameRole: mapped.pendingBindGameRole,
|
||||
pendingBindGameRoleToken: mapped.pendingBindGameRoleToken,
|
||||
pendingPlatformGameRoleUid: mapped.pendingPlatformGameRoleUid,
|
||||
pendingBindGameChannel: mapped.pendingBindGameChannel,
|
||||
pendingBindGameChangeBindTime: mapped.pendingBindGameChangeBindTime,
|
||||
pendingBindGameChangeBindDay: mapped.pendingBindGameChangeBindDay,
|
||||
roleIdentitySource: mapped.roleIdentitySource || current.role_identity_source,
|
||||
verificationBasis: mapped.verificationBasis || current.verification_basis,
|
||||
platformGameRoleUid: mapped.platformGameRoleUid || current.platform_game_role_uid,
|
||||
// 绑定决策字段只由虎牙决策器写;其它平台保持既有值。
|
||||
...(isHuyaTask
|
||||
? {
|
||||
bindingFlowState,
|
||||
accountRoleState: bindingDecision?.accountRoleState || current.account_role_state,
|
||||
targetRoleMatch: bindingDecision?.targetRoleMatch || current.target_role_match,
|
||||
rebindBlockScope: bindingDecision?.rebindBlockScope || '',
|
||||
}
|
||||
: {}),
|
||||
rebindPlatformMessage: mapped.rebindConfirmMessage,
|
||||
rebindRequested: mapped.rebindRequested,
|
||||
bindConfirmState: mapped.bindConfirmState,
|
||||
bindConfirmMessage: mapped.bindConfirmMessage,
|
||||
bindingEffectDeadlineAt: mapped.bindingEffectDeadlineAt || null,
|
||||
...(mapped.status === 'qr_pending' && hasBindingQr
|
||||
? { bindingQrIssuedAt: SEMI_AUTO_COALESCE_NOW }
|
||||
: {}),
|
||||
...(['not_started', 'failed', 'expired'].includes(mapped.status)
|
||||
? { bindingQrIssuedAt: null }
|
||||
: {}),
|
||||
...(mapped.pendingBindGameRole !== ''
|
||||
? { pendingRoleObservedAt: SEMI_AUTO_COALESCE_NOW }
|
||||
: { pendingRoleObservedAt: null }),
|
||||
...(bindingConfirmed ? { confirmedRoleObservedAt: SEMI_AUTO_COALESCE_NOW } : {}),
|
||||
...(mapped.status === 'qr_pending' ? { bindingStartedAt: SEMI_AUTO_COALESCE_NOW } : {}),
|
||||
boundAt: bindingConfirmed ? SEMI_AUTO_COALESCE_NOW : null,
|
||||
executionStatus,
|
||||
lastError: ['failed', 'expired'].includes(mapped.status) ? mapped.message : '',
|
||||
},
|
||||
event: {
|
||||
eventType: options.eventType || 'binding_status_changed',
|
||||
actorType,
|
||||
fromBindingStatus: current.binding_status,
|
||||
toBindingStatus: mapped.status,
|
||||
fromExecutionStatus: current.execution_status,
|
||||
toExecutionStatus: executionStatus,
|
||||
emit: bindingChanged,
|
||||
detail: {
|
||||
...(options.eventDetail || {}),
|
||||
gameAccount: mapped.bindGameAccount,
|
||||
@@ -1792,8 +1735,8 @@ export async function updateBindingTaskWithClient(
|
||||
changeBindTime: mapped.platformChangeBindTime,
|
||||
message: mapped.message,
|
||||
},
|
||||
})
|
||||
}
|
||||
},
|
||||
})
|
||||
return { current, decision: bindingDecision, executionStatus, mapped }
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,500 @@
|
||||
/**
|
||||
* 半自动任务状态写入的唯一入口。
|
||||
*
|
||||
* 客户操作、Connector 回调和后台操作都只是状态快照输入:它们在调用方事务内先把行锁住,
|
||||
* 再把"要写入的列"交给 `convergeSemiAutoTaskState`,由这里统一
|
||||
* ① 校验乐观守卫(expected);
|
||||
* ② 校验状态转换规则(见 task-state-rules.ts);
|
||||
* ③ 生成**一条** UPDATE(列名来自本文件的白名单,禁止调用方拼接任意 SQL);
|
||||
* ④ 追加 semi_auto_task_events(from/to 状态列由行锁前后的值自动生成,detail.reason 必填)。
|
||||
*
|
||||
* 原有 26 处 `UPDATE semi_auto_tasks` 全部收敛到这里,任何新入口不得再直接拼 UPDATE。
|
||||
*/
|
||||
import type { PoolClient } from 'pg'
|
||||
|
||||
import { createHttpError } from '../../utils/http.js'
|
||||
import {
|
||||
appendTaskEvent,
|
||||
TASK_SELECT,
|
||||
type BindingStatus,
|
||||
type ExecutionStatus,
|
||||
type LoginStatus,
|
||||
type SemiAutoPlatform,
|
||||
type TaskActorType,
|
||||
type TaskEventInput,
|
||||
type TaskRow,
|
||||
} from './semi-auto-task-core.js'
|
||||
import {
|
||||
canTransitionBinding,
|
||||
canTransitionExecution,
|
||||
canTransitionLogin,
|
||||
} from './task-state-rules.js'
|
||||
|
||||
/**
|
||||
* 时间列的取值。
|
||||
*
|
||||
* `null` 表示清空;字符串按 timestamptz 字面量写入;
|
||||
* `SEMI_AUTO_NOW` / `SEMI_AUTO_COALESCE_NOW` / `semiAutoNowPlusSeconds` 生成数据库侧表达式,
|
||||
* 保证 NOW() 仍然是事务时间,而不是 Node 进程时间。
|
||||
*/
|
||||
export type SemiAutoTaskTimeValue =
|
||||
| string
|
||||
| null
|
||||
| { readonly kind: 'now' }
|
||||
| { readonly kind: 'now_plus_seconds'; readonly seconds: number }
|
||||
| { readonly kind: 'coalesce_now' }
|
||||
|
||||
export const SEMI_AUTO_NOW: SemiAutoTaskTimeValue = { kind: 'now' }
|
||||
/** 等价于 `COALESCE(column, NOW())`:已有值保留,空值补当前时间。 */
|
||||
export const SEMI_AUTO_COALESCE_NOW: SemiAutoTaskTimeValue = { kind: 'coalesce_now' }
|
||||
|
||||
export function semiAutoNowPlusSeconds(seconds: number): SemiAutoTaskTimeValue {
|
||||
const normalized = Math.trunc(Number(seconds))
|
||||
if (!Number.isFinite(normalized) || normalized <= 0) {
|
||||
throw createHttpError('半自动任务时间偏移必须为正整数秒', {
|
||||
statusCode: 500,
|
||||
errorCode: 'semi_auto_task_patch_time_invalid',
|
||||
})
|
||||
}
|
||||
return { kind: 'now_plus_seconds', seconds: normalized }
|
||||
}
|
||||
|
||||
/**
|
||||
* 允许写入的列。
|
||||
*
|
||||
* 与 `semi_auto_tasks` 现有 UPDATE 语句用到的列一一对应,不再泛化成 `set = {...row}`。
|
||||
* 新增列必须先登记在这里,否则写入直接报错。
|
||||
*/
|
||||
export type SemiAutoTaskStatePatch = {
|
||||
// 状态三要素
|
||||
loginStatus?: LoginStatus
|
||||
bindingStatus?: BindingStatus
|
||||
executionStatus?: ExecutionStatus
|
||||
// Connector 会话 / 账号凭证 / 分类
|
||||
connectorSessionId?: string
|
||||
credentialId?: number | null
|
||||
huyaUid?: string
|
||||
platformNickname?: string
|
||||
connectorMode?: SemiAutoConnectorModeValue
|
||||
connectorStateVersion?: number
|
||||
semiAutoCategory?: string
|
||||
// 平台绑定事实
|
||||
bindGameAccount?: string
|
||||
bindGameRole?: string
|
||||
bindGameRoleId?: string
|
||||
bindGameRoleToken?: string
|
||||
platformGameRoleUid?: string
|
||||
bindGameChannel?: string
|
||||
isBindAccount?: boolean
|
||||
isBindRole?: boolean
|
||||
accountChangeBindTime?: number
|
||||
accountChangeBindDay?: number
|
||||
pendingBindGameAccount?: string
|
||||
pendingBindGameRole?: string
|
||||
pendingBindGameRoleToken?: string
|
||||
pendingPlatformGameRoleUid?: string
|
||||
pendingBindGameChannel?: string
|
||||
pendingBindGameChangeBindTime?: number
|
||||
pendingBindGameChangeBindDay?: number
|
||||
roleIdentitySource?: string
|
||||
verificationBasis?: string
|
||||
// 绑定决策与确认
|
||||
bindingFlowState?: HuyaBindingFlowStateValue
|
||||
accountRoleState?: HuyaAccountRoleStateValue
|
||||
targetRoleMatch?: HuyaTargetRoleMatchValue
|
||||
rebindBlockScope?: HuyaRebindBlockScopeValue
|
||||
rebindPlatformMessage?: string
|
||||
rebindRequested?: boolean
|
||||
bindConfirmState?: BindConfirmStateValue
|
||||
bindConfirmMessage?: string
|
||||
bindingQrIssuedAt?: SemiAutoTaskTimeValue
|
||||
bindingEffectDeadlineAt?: SemiAutoTaskTimeValue
|
||||
pendingRoleObservedAt?: SemiAutoTaskTimeValue
|
||||
confirmedRoleObservedAt?: SemiAutoTaskTimeValue
|
||||
bindingStartedAt?: SemiAutoTaskTimeValue
|
||||
boundAt?: SemiAutoTaskTimeValue
|
||||
// 客户资料与客户入口
|
||||
customerLinkOpenedAt?: SemiAutoTaskTimeValue
|
||||
customerGameRoleName?: string
|
||||
customerGameRoleId?: string
|
||||
customerGameServerZone?: string
|
||||
// 登录时间
|
||||
authStartedAt?: SemiAutoTaskTimeValue
|
||||
authenticatedAt?: SemiAutoTaskTimeValue
|
||||
// 履约归属、进度与完成
|
||||
assignedAdminUserId?: number | null
|
||||
fulfillmentId?: number | null
|
||||
targetQuantity?: number
|
||||
completedQuantity?: number
|
||||
completedAt?: SemiAutoTaskTimeValue
|
||||
completionNote?: string
|
||||
externalOrderNo?: string
|
||||
completionEvidence?: Record<string, unknown>
|
||||
lastError?: string | null
|
||||
/** 白名单列逃生口;键必须是 snake_case 列名,见 EXTRA_WRITABLE_COLUMNS。 */
|
||||
extra?: Record<string, string | number | boolean | null>
|
||||
}
|
||||
|
||||
type SemiAutoConnectorModeValue = TaskRow['connector_mode']
|
||||
type HuyaBindingFlowStateValue = TaskRow['binding_flow_state']
|
||||
type HuyaAccountRoleStateValue = TaskRow['account_role_state']
|
||||
type HuyaTargetRoleMatchValue = TaskRow['target_role_match']
|
||||
type HuyaRebindBlockScopeValue = TaskRow['rebind_block_scope']
|
||||
type BindConfirmStateValue = TaskRow['bind_confirm_state']
|
||||
|
||||
type PatchColumnMeta = { column: string; kind: 'value' | 'time' | 'json' }
|
||||
|
||||
const PATCH_COLUMN_MAP: Record<string, PatchColumnMeta> = {
|
||||
loginStatus: { column: 'login_status', kind: 'value' },
|
||||
bindingStatus: { column: 'binding_status', kind: 'value' },
|
||||
executionStatus: { column: 'execution_status', kind: 'value' },
|
||||
connectorSessionId: { column: 'connector_session_id', kind: 'value' },
|
||||
credentialId: { column: 'credential_id', kind: 'value' },
|
||||
huyaUid: { column: 'huya_uid', kind: 'value' },
|
||||
platformNickname: { column: 'platform_nickname', kind: 'value' },
|
||||
connectorMode: { column: 'connector_mode', kind: 'value' },
|
||||
connectorStateVersion: { column: 'connector_state_version', kind: 'value' },
|
||||
semiAutoCategory: { column: 'semi_auto_category', kind: 'value' },
|
||||
bindGameAccount: { column: 'bind_game_account', kind: 'value' },
|
||||
bindGameRole: { column: 'bind_game_role', kind: 'value' },
|
||||
bindGameRoleId: { column: 'bind_game_role_id', kind: 'value' },
|
||||
bindGameRoleToken: { column: 'bind_game_role_token', kind: 'value' },
|
||||
platformGameRoleUid: { column: 'platform_game_role_uid', kind: 'value' },
|
||||
bindGameChannel: { column: 'bind_game_channel', kind: 'value' },
|
||||
isBindAccount: { column: 'is_bind_account', kind: 'value' },
|
||||
isBindRole: { column: 'is_bind_role', kind: 'value' },
|
||||
accountChangeBindTime: { column: 'account_change_bind_time', kind: 'value' },
|
||||
accountChangeBindDay: { column: 'account_change_bind_day', kind: 'value' },
|
||||
pendingBindGameAccount: { column: 'pending_bind_game_account', kind: 'value' },
|
||||
pendingBindGameRole: { column: 'pending_bind_game_role', kind: 'value' },
|
||||
pendingBindGameRoleToken: { column: 'pending_bind_game_role_token', kind: 'value' },
|
||||
pendingPlatformGameRoleUid: { column: 'pending_platform_game_role_uid', kind: 'value' },
|
||||
pendingBindGameChannel: { column: 'pending_bind_game_channel', kind: 'value' },
|
||||
pendingBindGameChangeBindTime: { column: 'pending_bind_game_change_bind_time', kind: 'value' },
|
||||
pendingBindGameChangeBindDay: { column: 'pending_bind_game_change_bind_day', kind: 'value' },
|
||||
roleIdentitySource: { column: 'role_identity_source', kind: 'value' },
|
||||
verificationBasis: { column: 'verification_basis', kind: 'value' },
|
||||
bindingFlowState: { column: 'binding_flow_state', kind: 'value' },
|
||||
accountRoleState: { column: 'account_role_state', kind: 'value' },
|
||||
targetRoleMatch: { column: 'target_role_match', kind: 'value' },
|
||||
rebindBlockScope: { column: 'rebind_block_scope', kind: 'value' },
|
||||
rebindPlatformMessage: { column: 'rebind_platform_message', kind: 'value' },
|
||||
rebindRequested: { column: 'rebind_requested', kind: 'value' },
|
||||
bindConfirmState: { column: 'bind_confirm_state', kind: 'value' },
|
||||
bindConfirmMessage: { column: 'bind_confirm_message', kind: 'value' },
|
||||
bindingQrIssuedAt: { column: 'binding_qr_issued_at', kind: 'time' },
|
||||
bindingEffectDeadlineAt: { column: 'binding_effect_deadline_at', kind: 'time' },
|
||||
pendingRoleObservedAt: { column: 'pending_role_observed_at', kind: 'time' },
|
||||
confirmedRoleObservedAt: { column: 'confirmed_role_observed_at', kind: 'time' },
|
||||
bindingStartedAt: { column: 'binding_started_at', kind: 'time' },
|
||||
boundAt: { column: 'bound_at', kind: 'time' },
|
||||
customerLinkOpenedAt: { column: 'customer_link_opened_at', kind: 'time' },
|
||||
customerGameRoleName: { column: 'customer_game_role_name', kind: 'value' },
|
||||
customerGameRoleId: { column: 'customer_game_role_id', kind: 'value' },
|
||||
customerGameServerZone: { column: 'customer_game_server_zone', kind: 'value' },
|
||||
authStartedAt: { column: 'auth_started_at', kind: 'time' },
|
||||
authenticatedAt: { column: 'authenticated_at', kind: 'time' },
|
||||
assignedAdminUserId: { column: 'assigned_admin_user_id', kind: 'value' },
|
||||
fulfillmentId: { column: 'fulfillment_id', kind: 'value' },
|
||||
targetQuantity: { column: 'target_quantity', kind: 'value' },
|
||||
completedQuantity: { column: 'completed_quantity', kind: 'value' },
|
||||
completedAt: { column: 'completed_at', kind: 'time' },
|
||||
completionNote: { column: 'completion_note', kind: 'value' },
|
||||
externalOrderNo: { column: 'external_order_no', kind: 'value' },
|
||||
completionEvidence: { column: 'completion_evidence_json', kind: 'json' },
|
||||
lastError: { column: 'last_error', kind: 'value' },
|
||||
}
|
||||
|
||||
/** `extra` 只允许写这些标量列(时间列必须走上面带类型的字段)。 */
|
||||
const EXTRA_WRITABLE_COLUMNS = new Set([
|
||||
'assigned_admin_user_id',
|
||||
'fulfillment_id',
|
||||
'target_quantity',
|
||||
'completed_quantity',
|
||||
'completion_note',
|
||||
'external_order_no',
|
||||
'connector_state_version',
|
||||
'last_error',
|
||||
])
|
||||
|
||||
export type SemiAutoTaskEventInput = {
|
||||
eventType: string
|
||||
detail?: Record<string, unknown>
|
||||
/** false 表示本次写入不发事件(保留原来不发事件入口的行为)。默认发。 */
|
||||
emit?: boolean
|
||||
}
|
||||
|
||||
export type ConvergeSemiAutoTaskStateInput = {
|
||||
/** 必填,写入事件 detail.reason。 */
|
||||
reason: string
|
||||
actor: TaskActorType
|
||||
actorId?: string
|
||||
patch: SemiAutoTaskStatePatch
|
||||
/** 未传时按 reason 生成事件类型;传 null 表示本次写入不写事件。 */
|
||||
event?: SemiAutoTaskEventInput | null
|
||||
/** 乐观守卫:不满足直接 409。 */
|
||||
expected?: {
|
||||
executionStatus?: ExecutionStatus[]
|
||||
platform?: SemiAutoPlatform[]
|
||||
}
|
||||
/**
|
||||
* 是否回读带 join 投影的完整任务行。
|
||||
*
|
||||
* 默认不回读:写入入口在客户 2 秒轮询等热路径上,`TASK_SELECT` 带 5 个 join,
|
||||
* 每次写入都重读会把热路径成本翻倍。确实需要返回完整行的调用方显式传 `true`。
|
||||
*/
|
||||
reload?: boolean
|
||||
}
|
||||
|
||||
/** 按 reason 推导事件类型:只保留 [a-z0-9_],其它字符折叠为下划线。 */
|
||||
function deriveEventTypeFromReason(reason: string): string {
|
||||
const normalized = reason
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '_')
|
||||
.replace(/^_+|_+$/g, '')
|
||||
.slice(0, 80)
|
||||
return normalized || 'semi_auto_state_converged'
|
||||
}
|
||||
|
||||
/** 行锁只取状态收敛需要的列,避免在轮询热路径上重复做 TASK_SELECT 的 join。 */
|
||||
type SemiAutoTaskLockedRow = {
|
||||
id: number
|
||||
platform: SemiAutoPlatform
|
||||
login_status: LoginStatus
|
||||
binding_status: BindingStatus
|
||||
execution_status: ExecutionStatus
|
||||
}
|
||||
|
||||
async function lockSemiAutoTaskRow(
|
||||
client: PoolClient,
|
||||
taskId: number,
|
||||
): Promise<SemiAutoTaskLockedRow> {
|
||||
const result = await client.query<SemiAutoTaskLockedRow>(
|
||||
`SELECT id, platform, login_status, binding_status, execution_status
|
||||
FROM semi_auto_tasks
|
||||
WHERE id = $1
|
||||
FOR UPDATE`,
|
||||
[taskId],
|
||||
)
|
||||
const row = result.rows[0]
|
||||
if (!row) {
|
||||
throw createHttpError('半自动履约任务不存在', {
|
||||
statusCode: 404,
|
||||
errorCode: 'semi_auto_task_not_found',
|
||||
})
|
||||
}
|
||||
return row
|
||||
}
|
||||
|
||||
function assertExpectedGuard(
|
||||
current: SemiAutoTaskLockedRow,
|
||||
expected: ConvergeSemiAutoTaskStateInput['expected'],
|
||||
): void {
|
||||
if (!expected) return
|
||||
if (expected.platform && expected.platform.length > 0) {
|
||||
if (!expected.platform.includes(current.platform)) {
|
||||
throw createHttpError('半自动任务平台与预期不一致,请刷新后重试', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_task_state_conflict',
|
||||
context: { platform: current.platform, expected: expected.platform },
|
||||
})
|
||||
}
|
||||
}
|
||||
if (expected.executionStatus && expected.executionStatus.length > 0) {
|
||||
if (!expected.executionStatus.includes(current.execution_status)) {
|
||||
throw createHttpError('半自动任务状态已被其它操作改变,请刷新后重试', {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_task_state_conflict',
|
||||
context: { executionStatus: current.execution_status, expected: expected.executionStatus },
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 半自动任务状态唯一写入口。
|
||||
*
|
||||
* 必须在调用方事务内执行:内部先对任务行 `FOR UPDATE`,再校验守卫与转换规则,
|
||||
* 最后只用一条 UPDATE 落库并追加事件。
|
||||
*/
|
||||
export async function convergeSemiAutoTaskState(
|
||||
client: PoolClient,
|
||||
taskId: number,
|
||||
input: ConvergeSemiAutoTaskStateInput,
|
||||
): Promise<TaskRow | null> {
|
||||
const reason = String(input.reason ?? '').trim()
|
||||
if (!reason) {
|
||||
throw createHttpError('半自动任务状态写入必须说明原因', {
|
||||
statusCode: 500,
|
||||
errorCode: 'semi_auto_task_state_reason_required',
|
||||
})
|
||||
}
|
||||
const patch = input.patch || {}
|
||||
|
||||
// ① 行锁:只看任务表本身的轻量 SELECT ... FOR UPDATE,
|
||||
// 后续所有判断与事件 from/to 都以锁定后的行值为准。
|
||||
const current = await lockSemiAutoTaskRow(client, taskId)
|
||||
assertExpectedGuard(current, input.expected)
|
||||
|
||||
// ② 状态转换校验:未出现在 patch 里的状态视为不变。
|
||||
const nextLoginStatus = patch.loginStatus ?? current.login_status
|
||||
const nextBindingStatus = patch.bindingStatus ?? current.binding_status
|
||||
const nextExecutionStatus = patch.executionStatus ?? current.execution_status
|
||||
if (!canTransitionLogin(current.login_status, nextLoginStatus)) {
|
||||
throw createHttpError(`登录状态不允许从 ${current.login_status} 变更为 ${nextLoginStatus}`, {
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_task_transition_invalid',
|
||||
context: { from: current.login_status, to: nextLoginStatus, field: 'login_status' },
|
||||
})
|
||||
}
|
||||
if (!canTransitionBinding(current.binding_status, nextBindingStatus)) {
|
||||
throw createHttpError(
|
||||
`绑定状态不允许从 ${current.binding_status} 变更为 ${nextBindingStatus}`,
|
||||
{
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_task_transition_invalid',
|
||||
context: { from: current.binding_status, to: nextBindingStatus, field: 'binding_status' },
|
||||
},
|
||||
)
|
||||
}
|
||||
if (!canTransitionExecution(current.execution_status, nextExecutionStatus)) {
|
||||
throw createHttpError(
|
||||
`执行状态不允许从 ${current.execution_status} 变更为 ${nextExecutionStatus}`,
|
||||
{
|
||||
statusCode: 409,
|
||||
errorCode: 'semi_auto_task_transition_invalid',
|
||||
context: {
|
||||
from: current.execution_status,
|
||||
to: nextExecutionStatus,
|
||||
field: 'execution_status',
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
// ③ 单条 UPDATE:列名只来自 PATCH_COLUMN_MAP / EXTRA_WRITABLE_COLUMNS。
|
||||
const params: unknown[] = [taskId]
|
||||
const assignments: string[] = []
|
||||
const pushParam = (column: string, value: unknown) => {
|
||||
params.push(value)
|
||||
assignments.push(`${column} = $${params.length}`)
|
||||
}
|
||||
const pushExpression = (column: string, expression: string) => {
|
||||
assignments.push(`${column} = ${expression}`)
|
||||
}
|
||||
const pushTimeValue = (column: string, value: SemiAutoTaskTimeValue) => {
|
||||
if (value === null) {
|
||||
pushParam(column, null)
|
||||
return
|
||||
}
|
||||
if (typeof value === 'string') {
|
||||
// 空串按"清空"处理:timestamptz 不接受空字符串。
|
||||
const text = value.trim()
|
||||
pushParam(column, text || null)
|
||||
return
|
||||
}
|
||||
if (value.kind === 'now') {
|
||||
pushExpression(column, 'NOW()')
|
||||
return
|
||||
}
|
||||
if (value.kind === 'coalesce_now') {
|
||||
pushExpression(column, `COALESCE(${column}, NOW())`)
|
||||
return
|
||||
}
|
||||
const seconds = Math.trunc(Number(value.seconds))
|
||||
if (!Number.isFinite(seconds) || seconds <= 0) {
|
||||
throw createHttpError('半自动任务时间偏移必须为正整数秒', {
|
||||
statusCode: 500,
|
||||
errorCode: 'semi_auto_task_patch_time_invalid',
|
||||
context: { column },
|
||||
})
|
||||
}
|
||||
pushExpression(column, `NOW() + INTERVAL '${seconds} seconds'`)
|
||||
}
|
||||
|
||||
for (const key of Object.keys(patch)) {
|
||||
if (key === 'extra') continue
|
||||
const value = (patch as Record<string, unknown>)[key]
|
||||
if (value === undefined) continue
|
||||
const meta = PATCH_COLUMN_MAP[key]
|
||||
if (!meta) {
|
||||
throw createHttpError('半自动任务状态补丁包含未登记字段', {
|
||||
statusCode: 500,
|
||||
errorCode: 'semi_auto_task_patch_column_not_allowed',
|
||||
context: { field: key },
|
||||
})
|
||||
}
|
||||
if (meta.kind === 'time') {
|
||||
pushTimeValue(meta.column, value as SemiAutoTaskTimeValue)
|
||||
continue
|
||||
}
|
||||
if (meta.kind === 'json') {
|
||||
params.push(JSON.stringify(value ?? {}))
|
||||
assignments.push(`${meta.column} = $${params.length}::jsonb`)
|
||||
continue
|
||||
}
|
||||
pushParam(meta.column, value)
|
||||
}
|
||||
for (const [column, value] of Object.entries(patch.extra || {})) {
|
||||
if (!EXTRA_WRITABLE_COLUMNS.has(column)) {
|
||||
throw createHttpError('半自动任务状态补丁包含未登记列', {
|
||||
statusCode: 500,
|
||||
errorCode: 'semi_auto_task_patch_column_not_allowed',
|
||||
context: { column },
|
||||
})
|
||||
}
|
||||
if (value === undefined) continue
|
||||
pushParam(column, value)
|
||||
}
|
||||
pushExpression('updated_at', 'NOW()')
|
||||
|
||||
await client.query(
|
||||
`
|
||||
UPDATE semi_auto_tasks
|
||||
SET ${assignments.join(',\n ')}
|
||||
WHERE id = $1
|
||||
`,
|
||||
params,
|
||||
)
|
||||
|
||||
// ④ 事件:from*/to* 由行锁前后的值自动生成,detail.reason 必填。
|
||||
const event =
|
||||
input.event === undefined ? { eventType: deriveEventTypeFromReason(reason) } : input.event
|
||||
if (event && event.emit !== false) {
|
||||
// 只写本次真正被 patch 的状态组,其余留 NULL:
|
||||
// 与收敛前的事件行保持一致,时间线不会因为「未变化的状态也照抄一份」而变噪。
|
||||
const touchedLogin = patch.loginStatus !== undefined
|
||||
const touchedBinding = patch.bindingStatus !== undefined
|
||||
const touchedExecution = patch.executionStatus !== undefined
|
||||
const eventInput: TaskEventInput = {
|
||||
eventType: event.eventType,
|
||||
actorType: input.actor,
|
||||
...(input.actorId ? { actorId: input.actorId } : {}),
|
||||
...(touchedLogin
|
||||
? { fromLoginStatus: current.login_status, toLoginStatus: nextLoginStatus }
|
||||
: {}),
|
||||
...(touchedBinding
|
||||
? { fromBindingStatus: current.binding_status, toBindingStatus: nextBindingStatus }
|
||||
: {}),
|
||||
...(touchedExecution
|
||||
? { fromExecutionStatus: current.execution_status, toExecutionStatus: nextExecutionStatus }
|
||||
: {}),
|
||||
detail: { reason, ...(event.detail || {}) },
|
||||
}
|
||||
await appendTaskEvent(client, current.id, eventInput)
|
||||
}
|
||||
|
||||
// ⑤ 默认不回读:热路径上每次写入都做一次带 join 的 `TASK_SELECT` 成本过高。
|
||||
if (input.reload !== true) return null
|
||||
const refreshed = await client.query<TaskRow>(`${TASK_SELECT} WHERE task.id = $1 LIMIT 1`, [
|
||||
current.id,
|
||||
])
|
||||
const row = refreshed.rows[0]
|
||||
if (!row) {
|
||||
throw createHttpError('半自动履约任务不存在', {
|
||||
statusCode: 404,
|
||||
errorCode: 'semi_auto_task_not_found',
|
||||
})
|
||||
}
|
||||
return row
|
||||
}
|
||||
@@ -1090,7 +1090,7 @@ test(
|
||||
)
|
||||
|
||||
test(
|
||||
'虎牙数据库 CK 可在进程会话丢失后恢复并生成浏览器注入票据',
|
||||
'虎牙数据库 CK 可在进程会话丢失后恢复并直接下发浏览器登录态',
|
||||
{ skip: !TEST_DATABASE_URL ? '未设置 SEMI_AUTO_TASK_TEST_DATABASE_URL' : false },
|
||||
async () => {
|
||||
process.env.DATABASE_URL = TEST_DATABASE_URL
|
||||
@@ -1098,8 +1098,7 @@ test(
|
||||
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 { createAdminBrowserSession } = 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}`
|
||||
@@ -1177,7 +1176,7 @@ test(
|
||||
[result.taskId, credentialId, `missing-session-${suffix}`, platformUid],
|
||||
)
|
||||
|
||||
const ticket = await createAdminBrowserSession(result.taskId, 'https://www.huya.com/', {
|
||||
const injection = await createAdminBrowserSession(result.taskId, 'https://www.huya.com/', {
|
||||
userId: adminId,
|
||||
role: 'support',
|
||||
displayName: '集成测试客服',
|
||||
@@ -1201,11 +1200,14 @@ test(
|
||||
assert.notEqual(restoredSessionId, `missing-session-${suffix}`)
|
||||
assert.equal(Number(restored.rows[0]?.credential_session_restored), 1)
|
||||
|
||||
const payload = await consumeSemiAutoInjectionTicket(ticket.ticket)
|
||||
// 直接下发账号级 CK:没有票据、没有 TTL,权限靠后台登录态 + 领取人 + 审计。
|
||||
assert.equal(injection.platform, 'huya')
|
||||
assert.equal(injection.targetUrl, 'https://www.huya.com/')
|
||||
assert.equal(
|
||||
payload.cookies.find((cookie) => cookie.name === 'udb_cred')?.value,
|
||||
injection.cookies.find((cookie) => cookie.name === 'udb_cred')?.value,
|
||||
`restored-${suffix}`,
|
||||
)
|
||||
assert.equal('ticket' in injection, false)
|
||||
} finally {
|
||||
if (restoredSessionId) {
|
||||
await huyaNativeConnector.revokeSession(restoredSessionId).catch(() => undefined)
|
||||
|
||||
@@ -0,0 +1,324 @@
|
||||
/**
|
||||
* 半自动任务状态规则与唯一写入口的纯函数 / 伪 client 单测。
|
||||
*
|
||||
* 这里覆盖三类回归:
|
||||
* ① 转换规则(正向推进、终态保护、既有"倒退"重置路径);
|
||||
* ② 写入收敛服务只发一条 UPDATE,并且事件 from/to 由行锁前后的值生成;
|
||||
* ③ 三个业务服务与 dev-mock 里不再有裸 `UPDATE semi_auto_tasks`。
|
||||
*/
|
||||
import assert from 'node:assert/strict'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import test from 'node:test'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
import {
|
||||
ACTIVE_EXECUTION_STATUSES,
|
||||
canTransitionBinding,
|
||||
canTransitionExecution,
|
||||
canTransitionLogin,
|
||||
isTerminalExecutionStatus,
|
||||
} from './task-state-rules.js'
|
||||
import {
|
||||
convergeSemiAutoTaskState,
|
||||
SEMI_AUTO_COALESCE_NOW,
|
||||
SEMI_AUTO_NOW,
|
||||
semiAutoNowPlusSeconds,
|
||||
} from './semi-auto-task-state-service.js'
|
||||
|
||||
const root = path.dirname(fileURLToPath(import.meta.url))
|
||||
|
||||
function source(file: string) {
|
||||
return readFileSync(path.join(root, file), 'utf8')
|
||||
}
|
||||
|
||||
type RecordedQuery = { sql: string; params: unknown[] }
|
||||
|
||||
/**
|
||||
* 伪 PoolClient:SELECT 返回给定的任务行,其余语句只记录 SQL 与参数。
|
||||
* 足以验证"一条 UPDATE + 一条事件"的写入契约,不需要真实数据库。
|
||||
*/
|
||||
function createFakeClient(row: Record<string, unknown>) {
|
||||
const queries: RecordedQuery[] = []
|
||||
const client = {
|
||||
async query(text: string, params: unknown[] = []) {
|
||||
const sql = String(text)
|
||||
queries.push({ sql, params })
|
||||
if (/^\s*select/i.test(sql)) return { rows: [{ ...row }], rowCount: 1 }
|
||||
return { rows: [], rowCount: 1 }
|
||||
},
|
||||
}
|
||||
return {
|
||||
client: client as unknown as Parameters<typeof convergeSemiAutoTaskState>[0],
|
||||
queries,
|
||||
updates: () => queries.filter((item) => /update\s+semi_auto_tasks/i.test(item.sql)),
|
||||
events: () => queries.filter((item) => /insert\s+into\s+semi_auto_task_events/i.test(item.sql)),
|
||||
}
|
||||
}
|
||||
|
||||
function baseTaskRow(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: 42,
|
||||
order_id: 7,
|
||||
order_item_id: 9,
|
||||
platform: 'huya',
|
||||
platform_order_id: 'IT-SEMI-AUTO-STATE-1',
|
||||
login_status: 'waiting_login',
|
||||
binding_status: 'not_started',
|
||||
execution_status: 'waiting_customer',
|
||||
bind_confirm_state: 'idle',
|
||||
bind_confirm_message: '',
|
||||
connector_session_id: '',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
test('execution 状态允许正向推进,并保留既有倒退重置路径', () => {
|
||||
assert.equal(canTransitionExecution('waiting_customer', 'waiting_operator'), true)
|
||||
assert.equal(canTransitionExecution('waiting_operator', 'processing'), true)
|
||||
assert.equal(canTransitionExecution('processing', 'completed'), true)
|
||||
// 凭证失效/绑定重置会让任务回到 waiting_customer。
|
||||
assert.equal(canTransitionExecution('processing', 'waiting_customer'), true)
|
||||
assert.equal(canTransitionExecution('waiting_operator', 'waiting_customer'), true)
|
||||
// 客服重试后从 failed 重新收敛。
|
||||
assert.equal(canTransitionExecution('failed', 'waiting_operator'), true)
|
||||
// 任意非终态都可以取消或失败。
|
||||
for (const status of ['waiting_customer', 'waiting_operator', 'processing', 'failed'] as const) {
|
||||
assert.equal(canTransitionExecution(status, 'cancelled'), true)
|
||||
assert.equal(canTransitionExecution(status, 'failed'), true)
|
||||
}
|
||||
assert.deepEqual(
|
||||
[...ACTIVE_EXECUTION_STATUSES],
|
||||
['waiting_customer', 'waiting_operator', 'processing', 'failed'],
|
||||
)
|
||||
})
|
||||
|
||||
test('终态 completed/cancelled 不允许再被业务状态改写', () => {
|
||||
assert.equal(isTerminalExecutionStatus('completed'), true)
|
||||
assert.equal(isTerminalExecutionStatus('cancelled'), true)
|
||||
assert.equal(isTerminalExecutionStatus('processing'), false)
|
||||
for (const target of ['waiting_customer', 'waiting_operator', 'processing', 'failed'] as const) {
|
||||
assert.equal(canTransitionExecution('completed', target), false)
|
||||
assert.equal(canTransitionExecution('cancelled', target), false)
|
||||
}
|
||||
assert.equal(canTransitionExecution('cancelled', 'cancelled'), true)
|
||||
assert.equal(canTransitionExecution('completed', 'completed'), true)
|
||||
// 既有行为:人工配置切换半自动平台时会终止该订单项上的历史任务(含已完成任务)。
|
||||
assert.equal(canTransitionExecution('completed', 'cancelled'), true)
|
||||
})
|
||||
|
||||
test('绑定重置(「上一步修改资料」)与登录重置都在规则内被允许', () => {
|
||||
// 客户在 role_ready/scanned/failed/expired 页面返回上一步,必须能回到 not_started。
|
||||
for (const from of [
|
||||
'not_started',
|
||||
'qr_pending',
|
||||
'scanned',
|
||||
'role_ready',
|
||||
'failed',
|
||||
'expired',
|
||||
] as const) {
|
||||
assert.equal(canTransitionBinding(from, 'not_started'), true)
|
||||
}
|
||||
// 平台事实变化可覆盖任意绑定状态(Connector 快照是事实输入)。
|
||||
assert.equal(canTransitionBinding('confirmed', 'not_started'), true)
|
||||
assert.equal(canTransitionBinding('confirmed', 'role_ready'), true)
|
||||
// 登录状态只反映平台事实与入口重置。
|
||||
assert.equal(canTransitionLogin('authenticated', 'waiting_login'), true)
|
||||
assert.equal(canTransitionLogin('failed', 'authenticated'), true)
|
||||
assert.equal(canTransitionLogin('waiting_login', 'qr_pending'), true)
|
||||
})
|
||||
|
||||
test('唯一写入口只发一条 UPDATE,并按行锁前后的值生成事件 from/to', async () => {
|
||||
const fake = createFakeClient(baseTaskRow())
|
||||
const updated = await convergeSemiAutoTaskState(fake.client, 42, {
|
||||
reason: 'customer_profile_bound',
|
||||
actor: 'customer',
|
||||
actorId: '9',
|
||||
patch: { bindingStatus: 'role_ready', executionStatus: 'waiting_operator' },
|
||||
event: { eventType: 'binding_status_changed', detail: { source: 'unit' } },
|
||||
// 默认不回读完整行(热路径省一次 join 查询),需要返回行时必须显式要求。
|
||||
reload: true,
|
||||
})
|
||||
|
||||
assert.equal(updated?.id, 42)
|
||||
assert.equal(fake.updates().length, 1)
|
||||
const update = fake.updates()[0]!
|
||||
assert.match(update.sql, /binding_status = \$\d/)
|
||||
assert.match(update.sql, /execution_status = \$\d/)
|
||||
assert.match(update.sql, /updated_at = NOW\(\)/)
|
||||
assert.deepEqual(update.params, [42, 'role_ready', 'waiting_operator'])
|
||||
|
||||
assert.equal(fake.events().length, 1)
|
||||
const event = fake.events()[0]!
|
||||
assert.equal(event.params[0], 42)
|
||||
assert.equal(event.params[1], 'binding_status_changed')
|
||||
assert.equal(event.params[2], 'customer')
|
||||
assert.equal(event.params[3], '9')
|
||||
// 只写被 patch 的状态组:本次没有改 login,from_login/to_login 必须留 NULL。
|
||||
assert.deepEqual(event.params.slice(4, 10), [
|
||||
null,
|
||||
null,
|
||||
'not_started',
|
||||
'role_ready',
|
||||
'waiting_customer',
|
||||
'waiting_operator',
|
||||
])
|
||||
assert.deepEqual(JSON.parse(String(event.params[10])), {
|
||||
reason: 'customer_profile_bound',
|
||||
source: 'unit',
|
||||
})
|
||||
})
|
||||
|
||||
test('默认不回读带 join 的完整行,避免轮询热路径重复重读', async () => {
|
||||
const fake = createFakeClient(baseTaskRow())
|
||||
const result = await convergeSemiAutoTaskState(fake.client, 42, {
|
||||
reason: 'login_status_changed',
|
||||
actor: 'customer',
|
||||
patch: { loginStatus: 'qr_pending' },
|
||||
event: null,
|
||||
})
|
||||
assert.equal(result, null)
|
||||
assert.equal(fake.queries.filter((item) => /from\s+semi_auto_tasks/i.test(item.sql)).length, 1)
|
||||
})
|
||||
|
||||
test('时间列按数据库表达式写入,避免用进程时间冒充事务时间', async () => {
|
||||
const fake = createFakeClient(baseTaskRow({ auth_started_at: '2026-01-01T00:00:00.000Z' }))
|
||||
await convergeSemiAutoTaskState(fake.client, 42, {
|
||||
reason: 'customer_link_opened',
|
||||
actor: 'customer',
|
||||
patch: {
|
||||
customerLinkOpenedAt: SEMI_AUTO_NOW,
|
||||
authStartedAt: SEMI_AUTO_COALESCE_NOW,
|
||||
bindingEffectDeadlineAt: semiAutoNowPlusSeconds(60),
|
||||
},
|
||||
event: { eventType: 'customer_link_opened' },
|
||||
})
|
||||
const update = fake.updates()[0]!
|
||||
assert.match(update.sql, /customer_link_opened_at = NOW\(\)/)
|
||||
assert.match(update.sql, /auth_started_at = COALESCE\(auth_started_at, NOW\(\)\)/)
|
||||
assert.match(update.sql, /binding_effect_deadline_at = NOW\(\) \+ INTERVAL '60 seconds'/)
|
||||
assert.deepEqual(update.params, [42])
|
||||
})
|
||||
|
||||
test('event 传 null 时保持"原来不发事件"的入口行为', async () => {
|
||||
const fake = createFakeClient(baseTaskRow())
|
||||
await convergeSemiAutoTaskState(fake.client, 42, {
|
||||
reason: 'task_config_rebound',
|
||||
actor: 'system',
|
||||
patch: { fulfillmentId: 1001, targetQuantity: 2 },
|
||||
event: null,
|
||||
})
|
||||
assert.equal(fake.updates().length, 1)
|
||||
assert.equal(fake.events().length, 0)
|
||||
})
|
||||
|
||||
test('event.emit=false 时只写字段不写事件(轮询去噪)', async () => {
|
||||
const fake = createFakeClient(baseTaskRow({ login_status: 'authenticated' }))
|
||||
await convergeSemiAutoTaskState(fake.client, 42, {
|
||||
reason: 'login_status_changed',
|
||||
actor: 'connector',
|
||||
patch: { loginStatus: 'authenticated' },
|
||||
event: { eventType: 'login_status_changed', emit: false },
|
||||
})
|
||||
assert.equal(fake.updates().length, 1)
|
||||
assert.equal(fake.events().length, 0)
|
||||
})
|
||||
|
||||
test('乐观守卫和转换规则不满足时抛 409,且不写库', async () => {
|
||||
const fake = createFakeClient(baseTaskRow({ execution_status: 'completed' }))
|
||||
await assert.rejects(
|
||||
() =>
|
||||
convergeSemiAutoTaskState(fake.client, 42, {
|
||||
reason: 'cursor_write',
|
||||
actor: 'system',
|
||||
patch: { executionStatus: 'waiting_operator' },
|
||||
expected: { executionStatus: ['waiting_customer', 'waiting_operator'] },
|
||||
}),
|
||||
(error: { statusCode?: number; errorCode?: string }) => {
|
||||
assert.equal(error.statusCode, 409)
|
||||
assert.equal(error.errorCode, 'semi_auto_task_state_conflict')
|
||||
return true
|
||||
},
|
||||
)
|
||||
assert.equal(fake.updates().length, 0)
|
||||
|
||||
const terminal = createFakeClient(baseTaskRow({ execution_status: 'completed' }))
|
||||
await assert.rejects(
|
||||
() =>
|
||||
convergeSemiAutoTaskState(terminal.client, 42, {
|
||||
reason: 'illegal_regress',
|
||||
actor: 'system',
|
||||
patch: { executionStatus: 'processing' },
|
||||
}),
|
||||
(error: { statusCode?: number; errorCode?: string }) => {
|
||||
assert.equal(error.statusCode, 409)
|
||||
assert.equal(error.errorCode, 'semi_auto_task_transition_invalid')
|
||||
return true
|
||||
},
|
||||
)
|
||||
assert.equal(terminal.updates().length, 0)
|
||||
|
||||
const platformGuard = createFakeClient(baseTaskRow({ platform: 'weibo' }))
|
||||
await assert.rejects(
|
||||
() =>
|
||||
convergeSemiAutoTaskState(platformGuard.client, 42, {
|
||||
reason: 'huya_only',
|
||||
actor: 'system',
|
||||
patch: { lastError: '' },
|
||||
expected: { platform: ['huya'] },
|
||||
}),
|
||||
(error: { statusCode?: number; errorCode?: string }) => {
|
||||
assert.equal(error.statusCode, 409)
|
||||
assert.equal(error.errorCode, 'semi_auto_task_state_conflict')
|
||||
return true
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
test('未登记列一律拒绝写入', async () => {
|
||||
const fake = createFakeClient(baseTaskRow())
|
||||
await assert.rejects(
|
||||
() =>
|
||||
convergeSemiAutoTaskState(fake.client, 42, {
|
||||
reason: 'raw_column_write',
|
||||
actor: 'system',
|
||||
patch: { extra: { created_at: '2026-01-01T00:00:00.000Z' } },
|
||||
}),
|
||||
(error: { statusCode?: number; errorCode?: string }) => {
|
||||
assert.equal(error.statusCode, 500)
|
||||
assert.equal(error.errorCode, 'semi_auto_task_patch_column_not_allowed')
|
||||
return true
|
||||
},
|
||||
)
|
||||
assert.equal(fake.updates().length, 0)
|
||||
|
||||
const unknownField = createFakeClient(baseTaskRow())
|
||||
await assert.rejects(
|
||||
() =>
|
||||
convergeSemiAutoTaskState(unknownField.client, 42, {
|
||||
reason: 'raw_field_write',
|
||||
actor: 'system',
|
||||
patch: { notARegisteredField: 'x' } as never,
|
||||
}),
|
||||
(error: { errorCode?: string }) => {
|
||||
assert.equal(error.errorCode, 'semi_auto_task_patch_column_not_allowed')
|
||||
return true
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
test('除唯一写入口外,不再有裸 UPDATE semi_auto_tasks', () => {
|
||||
for (const file of [
|
||||
'semi-auto-task-core.ts',
|
||||
'semi-auto-customer-service.ts',
|
||||
'semi-auto-admin-service.ts',
|
||||
]) {
|
||||
assert.doesNotMatch(source(file), /UPDATE semi_auto_tasks/i, file)
|
||||
}
|
||||
assert.doesNotMatch(
|
||||
source('../dev-mock/dev-mock-service.ts'),
|
||||
/UPDATE semi_auto_tasks/i,
|
||||
'dev-mock-service.ts',
|
||||
)
|
||||
assert.match(source('semi-auto-task-state-service.ts'), /UPDATE semi_auto_tasks/)
|
||||
})
|
||||
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* 半自动任务状态转换规则(纯函数,可单测)。
|
||||
*
|
||||
* 规则只从既有写入口的真实行为抽取,不新增、不收紧任何约束:
|
||||
* 既有入口允许的"倒退"或重置路径必须在这里继续允许,并在注释里写明入口名称。
|
||||
* 写入收敛服务 `convergeSemiAutoTaskState` 是唯一调用方。
|
||||
*/
|
||||
import type { BindingStatus, ExecutionStatus, LoginStatus } from './semi-auto-task-core.js'
|
||||
|
||||
export const LOGIN_STATUSES: readonly LoginStatus[] = [
|
||||
'waiting_login',
|
||||
'qr_pending',
|
||||
'scanned',
|
||||
'authenticated',
|
||||
'failed',
|
||||
'expired',
|
||||
]
|
||||
|
||||
export const BINDING_STATUSES: readonly BindingStatus[] = [
|
||||
'not_started',
|
||||
'qr_pending',
|
||||
'scanned',
|
||||
'role_ready',
|
||||
'confirmed',
|
||||
'failed',
|
||||
'expired',
|
||||
]
|
||||
|
||||
export const EXECUTION_STATUSES: readonly ExecutionStatus[] = [
|
||||
'waiting_customer',
|
||||
'waiting_operator',
|
||||
'processing',
|
||||
'completed',
|
||||
'failed',
|
||||
'cancelled',
|
||||
]
|
||||
|
||||
/**
|
||||
* 登录状态只反映平台事实与入口重置,现有入口两两可达:
|
||||
* - `waiting_login → qr_pending`:客户重新发起登录(`startPublicLogin`);
|
||||
* - `qr_pending → scanned → authenticated`:Connector 扫码/短信事实(`updateLoginTask`);
|
||||
* - `authenticated → waiting_login`:CK 失效或客服重发授权(`resetTaskForCustomerLogin`、
|
||||
* `requestAdminSemiAutoCustomerReauth`);
|
||||
* - `authenticated → failed/expired`:凭证失效(`updateLoginTask`、`resetTaskForInvalidCredential`);
|
||||
* - `failed/expired → authenticated`:账号级 CK 恢复会话(`ensureConnectorSessionForTask`);
|
||||
* - 任意 → 任意:外部 Connector 快照(`applySemiAutoTaskStateSnapshot`)按平台事实覆盖。
|
||||
*/
|
||||
const LOGIN_ALLOWED: Record<LoginStatus, readonly LoginStatus[]> = {
|
||||
waiting_login: LOGIN_STATUSES,
|
||||
qr_pending: LOGIN_STATUSES,
|
||||
scanned: LOGIN_STATUSES,
|
||||
authenticated: LOGIN_STATUSES,
|
||||
failed: LOGIN_STATUSES,
|
||||
expired: LOGIN_STATUSES,
|
||||
}
|
||||
|
||||
/**
|
||||
* 绑定状态同样由平台事实驱动,两两可达:
|
||||
* - `qr_pending → scanned → role_ready → confirmed`:客户扫码与确认(`updateBindingTask`);
|
||||
* - `role_ready/failed/expired/scanned → not_started`:客户点「上一步修改资料」
|
||||
* (`resetPublicBinding`),这是显式允许的"倒退"路径,不能被规则拦住;
|
||||
* - `confirmed → not_started`:退出已授权状态时重置(`resetTaskForCustomerLogin`);
|
||||
* - 任意 → 任意:Connector 快照观察到平台绑定事实变化(`applySemiAutoTaskStateSnapshot`)。
|
||||
*/
|
||||
const BINDING_ALLOWED: Record<BindingStatus, readonly BindingStatus[]> = {
|
||||
not_started: BINDING_STATUSES,
|
||||
qr_pending: BINDING_STATUSES,
|
||||
scanned: BINDING_STATUSES,
|
||||
role_ready: BINDING_STATUSES,
|
||||
confirmed: BINDING_STATUSES,
|
||||
failed: BINDING_STATUSES,
|
||||
expired: BINDING_STATUSES,
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行状态与平台无关,只由登录、绑定与人工确认推导(`deriveSemiAutoExecutionStatus`)。
|
||||
*
|
||||
* 正向:`waiting_customer → waiting_operator → processing → completed`。
|
||||
* 同步允许的"倒退":
|
||||
* - `waiting_operator/processing → waiting_customer`:凭证失效、绑定需要客户重新处理
|
||||
* (`resetTaskForCustomerLogin`、`resetPublicBinding`);
|
||||
* - `failed → waiting_customer/waiting_operator/processing`:客服重试后重新收敛;
|
||||
* - 任意非终态 → `cancelled`:后台取消、人工配置停用或切换平台
|
||||
* (`cancelAdminSemiAutoTask`、`cancelIneligibleSemiAutoTasksWithClient`);
|
||||
* - 任意非终态 → `completed`:后台完成履约(`completeAdminSemiAutoTask`);
|
||||
* - 任意非终态 → `failed`:保留既有入口语义。
|
||||
*
|
||||
* 终态 `completed/cancelled` 不允许再被改写,唯一例外是 `completed → cancelled`:
|
||||
* 人工配置切换半自动平台/停用时,`insertMissingSemiAutoTasksWithClient` 会把该订单项
|
||||
* 上所有非取消任务(含已完成任务)收敛为取消并保留为历史,这是既有行为,此处必须继续允许。
|
||||
*/
|
||||
const EXECUTION_TERMINAL_SUCCESSORS: readonly ExecutionStatus[] = ['completed', 'cancelled']
|
||||
|
||||
const EXECUTION_ALLOWED: Record<ExecutionStatus, readonly ExecutionStatus[]> = {
|
||||
waiting_customer: [...EXECUTION_STATUSES],
|
||||
waiting_operator: [...EXECUTION_STATUSES],
|
||||
processing: [...EXECUTION_STATUSES],
|
||||
failed: [...EXECUTION_STATUSES],
|
||||
completed: EXECUTION_TERMINAL_SUCCESSORS,
|
||||
cancelled: ['cancelled'],
|
||||
}
|
||||
|
||||
export function canTransitionLogin(from: LoginStatus, to: LoginStatus): boolean {
|
||||
return (LOGIN_ALLOWED[from] || []).includes(to)
|
||||
}
|
||||
|
||||
export function canTransitionBinding(from: BindingStatus, to: BindingStatus): boolean {
|
||||
return (BINDING_ALLOWED[from] || []).includes(to)
|
||||
}
|
||||
|
||||
export function canTransitionExecution(from: ExecutionStatus, to: ExecutionStatus): boolean {
|
||||
return (EXECUTION_ALLOWED[from] || []).includes(to)
|
||||
}
|
||||
|
||||
/** 终态判断:`completed/cancelled` 不再接受业务状态推进。 */
|
||||
export function isTerminalExecutionStatus(status: ExecutionStatus): boolean {
|
||||
return status === 'completed' || status === 'cancelled'
|
||||
}
|
||||
|
||||
/** 非终态执行状态集合,供写入前乐观守卫使用(最近一次已知的活跃状态)。 */
|
||||
export const ACTIVE_EXECUTION_STATUSES: readonly ExecutionStatus[] = EXECUTION_STATUSES.filter(
|
||||
(status) => !isTerminalExecutionStatus(status),
|
||||
)
|
||||
@@ -1,8 +1,6 @@
|
||||
import { createHttpError } from '../../utils/http.js'
|
||||
import type {
|
||||
ConnectorBindingSession,
|
||||
ConnectorBrowserTicket,
|
||||
ConnectorInjectionPayload,
|
||||
ConnectorLoginSession,
|
||||
SemiAutoConnectorMode,
|
||||
} from './huya-connector-client.js'
|
||||
@@ -120,22 +118,6 @@ export async function startWeiboBinding(
|
||||
return weiboNativeConnector.startBinding(sessionId, options)
|
||||
}
|
||||
|
||||
export async function createWeiboBrowserTicket(
|
||||
input: { sessionId: string; targetUrl?: string },
|
||||
mode: SemiAutoConnectorMode = 'embedded',
|
||||
): Promise<ConnectorBrowserTicket> {
|
||||
assertEmbedded(mode)
|
||||
return weiboNativeConnector.createBrowserTicket(input)
|
||||
}
|
||||
|
||||
export async function consumeWeiboBrowserTicket(
|
||||
ticket: string,
|
||||
mode: SemiAutoConnectorMode = 'embedded',
|
||||
): Promise<ConnectorInjectionPayload> {
|
||||
assertEmbedded(mode)
|
||||
return weiboNativeConnector.consumeBrowserTicket(ticket)
|
||||
}
|
||||
|
||||
export async function revokeWeiboSession(
|
||||
sessionId: string,
|
||||
mode: SemiAutoConnectorMode = 'embedded',
|
||||
|
||||
@@ -15,12 +15,7 @@ import crypto from 'node:crypto'
|
||||
|
||||
import { createHttpError } from '../../../utils/http.js'
|
||||
import { logWarn } from '../../../utils/logger.js'
|
||||
import type {
|
||||
ConnectorBindingSession,
|
||||
ConnectorBrowserTicket,
|
||||
ConnectorInjectionPayload,
|
||||
ConnectorLoginSession,
|
||||
} from '../huya-connector-client.js'
|
||||
import type { ConnectorBindingSession, ConnectorLoginSession } from '../huya-connector-client.js'
|
||||
|
||||
const PASSPORT_BASE = 'https://passport.weibo.com'
|
||||
const WEIBO_BASE = 'https://weibo.com'
|
||||
@@ -43,11 +38,9 @@ const WEIBO_MOBILE_UA =
|
||||
|
||||
const LOGIN_QR_TTL_MS = 5 * 60 * 1000
|
||||
const CREDENTIAL_TTL_MS = 24 * 60 * 60 * 1000
|
||||
const BROWSER_TICKET_TTL_MS = 2 * 60 * 1000
|
||||
const SMS_COOKIE_TTL_MS = 10 * 60 * 1000
|
||||
const COUNTRY_CODE_TTL_MS = 60 * 60 * 1000
|
||||
const MAX_SESSIONS = 200
|
||||
const TICKET_PREFIX = 'weibo-ticket-'
|
||||
const WEIBO_BINDING_QR_TTL_MS = 10 * 60 * 1000
|
||||
const WEIBO_AUTH_ERROR_CODES = new Set([100002, 100004, 400000, 400002])
|
||||
export const WEIBO_YIDUN_CAPTCHA_ID = '7cda0ba2785647ada4d6e946ddb2d465'
|
||||
@@ -123,13 +116,6 @@ type WeiboBindingQrState = {
|
||||
baselineRoleName: string
|
||||
}
|
||||
|
||||
type WeiboTicket = {
|
||||
ticket: string
|
||||
targetUrl: string
|
||||
cookies: WeiboSerializedCookie[]
|
||||
expiresAtMs: number
|
||||
}
|
||||
|
||||
export type WeiboSerializedCookie = {
|
||||
name: string
|
||||
value: string
|
||||
@@ -341,7 +327,6 @@ type WeiboSession = {
|
||||
gameRoleError: WeiboGameRoleError | null
|
||||
bindingQr: WeiboBindingQrState | null
|
||||
lastBindingChannel: 'wx' | 'qq' | ''
|
||||
tickets: Map<string, WeiboTicket>
|
||||
}
|
||||
|
||||
type SmsLoginState = {
|
||||
@@ -499,7 +484,6 @@ export class WeiboNativeConnector {
|
||||
gameRoleError: null,
|
||||
bindingQr: null,
|
||||
lastBindingChannel: '',
|
||||
tickets: new Map(),
|
||||
}
|
||||
this.sessions.set(sessionId, session)
|
||||
return this.loginView(session)
|
||||
@@ -794,7 +778,6 @@ export class WeiboNativeConnector {
|
||||
gameRoleError: null,
|
||||
bindingQr: null,
|
||||
lastBindingChannel: '',
|
||||
tickets: new Map(),
|
||||
}
|
||||
this.smsSessions.delete(stateKey)
|
||||
await this.finishLogin(session, location)
|
||||
@@ -874,67 +857,11 @@ export class WeiboNativeConnector {
|
||||
return this.bindingView(session)
|
||||
}
|
||||
|
||||
async createBrowserTicket(input: {
|
||||
sessionId: string
|
||||
targetUrl?: string
|
||||
}): Promise<ConnectorBrowserTicket> {
|
||||
const session = this.requireSession(input.sessionId)
|
||||
if (!session.cookies.has(WEIBO_BASE, 'SUB')) {
|
||||
throw createHttpError('微博登录态不存在或已过期', {
|
||||
statusCode: 404,
|
||||
errorCode: 'weibo_credential_not_found',
|
||||
})
|
||||
}
|
||||
const ticket = `${TICKET_PREFIX}${crypto.randomBytes(32).toString('base64url')}`
|
||||
const targetUrl = String(input.targetUrl || '').trim() || 'https://weibo.com/'
|
||||
const expiresAtMs = this.now() + BROWSER_TICKET_TTL_MS
|
||||
session.tickets.set(ticket, {
|
||||
ticket,
|
||||
targetUrl,
|
||||
cookies: session.cookies.serialize(targetUrl),
|
||||
expiresAtMs,
|
||||
})
|
||||
return { ticket, expiresAt: iso(expiresAtMs), targetUrl }
|
||||
}
|
||||
|
||||
async consumeBrowserTicket(ticketInput: string): Promise<ConnectorInjectionPayload> {
|
||||
this.prune()
|
||||
const ticket = String(ticketInput || '').trim()
|
||||
if (!ticket) {
|
||||
throw createHttpError('注入票据无效', {
|
||||
statusCode: 400,
|
||||
errorCode: 'weibo_ticket_invalid',
|
||||
})
|
||||
}
|
||||
for (const session of this.sessions.values()) {
|
||||
const item = session.tickets.get(ticket)
|
||||
if (!item) continue
|
||||
session.tickets.delete(ticket)
|
||||
if (item.expiresAtMs <= this.now()) {
|
||||
throw createHttpError('浏览器注入票据不存在或已过期', {
|
||||
statusCode: 404,
|
||||
errorCode: 'weibo_ticket_expired',
|
||||
})
|
||||
}
|
||||
return {
|
||||
platform: 'weibo',
|
||||
targetUrl: item.targetUrl,
|
||||
expiresAt: iso(item.expiresAtMs),
|
||||
cookies: item.cookies,
|
||||
}
|
||||
}
|
||||
throw createHttpError('浏览器注入票据不存在或已过期', {
|
||||
statusCode: 404,
|
||||
errorCode: 'weibo_ticket_not_found',
|
||||
})
|
||||
}
|
||||
|
||||
async revokeSession(sessionIdInput: string): Promise<void> {
|
||||
const sessionId = String(sessionIdInput || '').trim()
|
||||
const session = this.sessions.get(sessionId)
|
||||
if (!session) return
|
||||
session.cookies.clear()
|
||||
session.tickets.clear()
|
||||
this.sessions.delete(sessionId)
|
||||
}
|
||||
|
||||
@@ -1001,7 +928,6 @@ export class WeiboNativeConnector {
|
||||
gameRoleError: null,
|
||||
bindingQr: null,
|
||||
lastBindingChannel: '',
|
||||
tickets: new Map(),
|
||||
}
|
||||
this.sessions.set(session.sessionId, session)
|
||||
return this.loginView(session)
|
||||
@@ -1501,7 +1427,6 @@ export class WeiboNativeConnector {
|
||||
for (const [sessionId, session] of Array.from(this.sessions.entries())) {
|
||||
if (session.expiresAtMs <= nowMs) {
|
||||
session.cookies.clear()
|
||||
session.tickets.clear()
|
||||
this.sessions.delete(sessionId)
|
||||
}
|
||||
}
|
||||
@@ -1509,11 +1434,9 @@ export class WeiboNativeConnector {
|
||||
const overflow = this.sessions.size - MAX_SESSIONS
|
||||
for (const [sessionId, session] of Array.from(this.sessions.entries()).slice(0, overflow)) {
|
||||
session.cookies.clear()
|
||||
session.tickets.clear()
|
||||
this.sessions.delete(sessionId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const weiboNativeConnector = new WeiboNativeConnector()
|
||||
export const WEIBO_TICKET_PREFIX = TICKET_PREFIX
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
import {
|
||||
extractWeiboBindRawUrl,
|
||||
WEIBO_TICKET_PREFIX,
|
||||
WeiboNativeConnector,
|
||||
} from './weibo-native-connector.js'
|
||||
import { selectSemiAutoCredentialCookies } from '../semi-auto-credential-service.js'
|
||||
import { extractWeiboBindRawUrl, WeiboNativeConnector } from './weibo-native-connector.js'
|
||||
|
||||
type CapturedCall = { url: string; init: RequestInit }
|
||||
|
||||
@@ -433,7 +430,7 @@ test('微博短信登录会带上发码响应下发的 Cookie', async () => {
|
||||
assert.match(headers.cookie || '', /SCF=send-cookie/)
|
||||
})
|
||||
|
||||
test('微博短信登录建立会话并可生成一次性注入票据', async () => {
|
||||
test('微博短信登录建立会话并可导出完整账号 CK', async () => {
|
||||
const { fetchImpl, calls } = createFetchMock(defaultHandler)
|
||||
const connector = new WeiboNativeConnector({ fetchImpl })
|
||||
await connector.sendSmsCode({ taskId: 1, mobile: '138 0013 8000' })
|
||||
@@ -472,18 +469,12 @@ test('微博短信登录建立会话并可生成一次性注入票据', async ()
|
||||
'%26openLoginLayer%3D0%26url%3Dhttps%3A%2F%2Fweibo.com%2F&from=weibopro',
|
||||
)
|
||||
|
||||
const ticket = await connector.createBrowserTicket({
|
||||
sessionId,
|
||||
targetUrl: 'https://weibo.com/',
|
||||
})
|
||||
assert.ok(ticket.ticket.startsWith(WEIBO_TICKET_PREFIX))
|
||||
|
||||
const payload = await connector.consumeBrowserTicket(ticket.ticket)
|
||||
assert.equal(payload.platform, 'weibo')
|
||||
assert.equal(payload.targetUrl, 'https://weibo.com/')
|
||||
assert.ok(payload.cookies.some((cookie) => cookie.name === 'SUB' && cookie.value === 'demo-sub'))
|
||||
|
||||
await assert.rejects(() => connector.consumeBrowserTicket(ticket.ticket), /票据不存在或已过期/)
|
||||
const credential = connector.exportSessionCredential(sessionId)
|
||||
assert.equal(credential.platformUid, '123456')
|
||||
assert.ok(
|
||||
credential.cookies.some((cookie) => cookie.name === 'SUB' && cookie.value === 'demo-sub'),
|
||||
)
|
||||
assert.equal(JSON.stringify(credential).includes('demo-sub'), true)
|
||||
})
|
||||
|
||||
test('微博短信登录兼容成功响应省略 act、直接返回 data.location', async () => {
|
||||
@@ -602,15 +593,16 @@ test('微博 CK 可按账号级凭证导出并从序列化 Cookie 恢复会话',
|
||||
),
|
||||
)
|
||||
|
||||
const ticket = await connector.createBrowserTicket({
|
||||
sessionId,
|
||||
targetUrl: 'https://weibo.com/',
|
||||
})
|
||||
const injection = await connector.consumeBrowserTicket(ticket.ticket)
|
||||
// 浏览器注入只下发与目标 URL 匹配的 Cookie(账号级凭证仍保存完整集合)。
|
||||
const injection = selectSemiAutoCredentialCookies(credential.cookies, 'https://weibo.com/')
|
||||
assert.equal(
|
||||
injection.cookies.some((cookie) => cookie.name === 'PASSPORT_ONLY'),
|
||||
injection.some((cookie) => cookie.name === 'PASSPORT_ONLY'),
|
||||
false,
|
||||
)
|
||||
assert.equal(
|
||||
injection.some((cookie) => cookie.name === 'SUB'),
|
||||
true,
|
||||
)
|
||||
|
||||
const restored = await connector.restoreSessionFromCredential({
|
||||
taskId: 2,
|
||||
|
||||
Reference in New Issue
Block a user