Files
order_site/apps/backend/src/services/semi-auto/semi-auto-credential-service.ts
T
yml eaf6296430 重构(半自动履约): 统一虎牙/微博状态写入、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 中指向不存在文件的失效链接。
2026-11-30 23:23:07 +08:00

227 lines
7.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { PoolClient } from 'pg'
import { query } from '../../db/client.js'
export type SemiAutoCredentialCookie = {
name: string
value: string
domain: string
path: string
secure: boolean
httpOnly: boolean
hostOnly?: boolean
expiresAt: string | null
}
export type SemiAutoCredentialPayload = {
platformUid: string
nickname: string
cookies: SemiAutoCredentialCookie[]
}
export type SemiAutoCredentialSource = 'qr' | 'sms' | 'web' | 'app' | 'import'
export type SemiAutoCredentialRecord = SemiAutoCredentialPayload & {
id: number
platform: 'huya' | 'weibo'
source: SemiAutoCredentialSource | ''
status: 'unknown' | 'valid' | 'invalid' | 'error'
updatedAt: string
/** 上一次健康检查时间;用于对失效凭证的重试做节流,避免每次请求都真打平台。 */
lastCheckedAt: string | null
}
type CredentialRow = {
id: number
platform: 'huya' | 'weibo'
platform_uid: string
platform_nickname: string
credential_payload_json: string
credential_source: SemiAutoCredentialSource | ''
credential_status: 'unknown' | 'valid' | 'invalid' | 'error'
credential_updated_at: string
last_checked_at: string | null
}
function normalizeCookieList(value: unknown): SemiAutoCredentialCookie[] {
if (!Array.isArray(value)) return []
return value
.filter((item): item is Record<string, unknown> =>
Boolean(item && typeof item === 'object' && !Array.isArray(item)),
)
.map((item) => {
const domain = String(item.domain || '')
.trim()
.toLowerCase()
return {
name: String(item.name || '').trim(),
value: String(item.value || ''),
domain,
path: String(item.path || '/').trim() || '/',
secure: item.secure === true,
httpOnly: item.httpOnly === true,
hostOnly: typeof item.hostOnly === 'boolean' ? item.hostOnly : !domain.startsWith('.'),
expiresAt: item.expiresAt ? String(item.expiresAt) : null,
}
})
.filter((item) => item.name && item.domain)
}
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 || '/'
const nowMs = Date.now()
return cookies
.filter((cookie) => {
if (cookie.secure && requestUrl.protocol !== 'https:') return false
if (cookie.expiresAt) {
const expiresAtMs = Date.parse(cookie.expiresAt)
if (Number.isFinite(expiresAtMs) && expiresAtMs <= nowMs) return false
}
const cookieDomain = cookie.domain.trim().toLowerCase().replace(/^\./, '')
if (!cookieDomain) return false
const hostOnly = cookie.hostOnly ?? !cookie.domain.startsWith('.')
const domainMatches = hostOnly
? hostname === cookieDomain
: hostname === cookieDomain || hostname.endsWith(`.${cookieDomain}`)
if (!domainMatches) return false
const cookiePath = cookie.path || '/'
return (
requestPath === cookiePath ||
requestPath.startsWith(cookiePath.endsWith('/') ? cookiePath : `${cookiePath}/`)
)
})
.sort((left, right) => (right.path || '/').length - (left.path || '/').length)
}
function decodeCredential(row: CredentialRow): SemiAutoCredentialRecord {
const parsed = JSON.parse(row.credential_payload_json) as Record<string, unknown>
return {
id: Number(row.id),
platform: row.platform,
platformUid: row.platform_uid,
nickname: row.platform_nickname,
cookies: normalizeCookieList(parsed.cookies),
source: row.credential_source,
status: row.credential_status,
updatedAt: row.credential_updated_at,
lastCheckedAt: row.last_checked_at,
}
}
export async function upsertSemiAutoCredentialWithClient(
client: Pick<PoolClient, 'query'>,
input: {
platform: 'huya' | 'weibo'
source: SemiAutoCredentialSource
payload: SemiAutoCredentialPayload
},
): Promise<number> {
const platformUid = String(input.payload.platformUid || '').trim()
if (!platformUid) {
throw new Error('平台账号 UID 为空,无法保存半自动履约凭证')
}
const cookies = normalizeCookieList(input.payload.cookies)
if (cookies.length === 0) {
throw new Error('平台 Cookie 为空,无法保存半自动履约凭证')
}
const payloadJson = JSON.stringify({ cookies })
const result = await client.query<{ id: number }>(
`
INSERT INTO semi_auto_credentials (
platform, platform_uid, platform_nickname, credential_payload_json,
credential_source, credential_status, credential_updated_at,
last_checked_at, last_check_error, created_at, updated_at
) VALUES (
$1, $2, $3, $4, $5, 'valid', NOW(), NOW(), '', NOW(), NOW()
)
ON CONFLICT (platform, platform_uid) DO UPDATE
SET platform_nickname = EXCLUDED.platform_nickname,
credential_payload_json = EXCLUDED.credential_payload_json,
credential_source = EXCLUDED.credential_source,
credential_status = 'valid',
credential_updated_at = NOW(),
last_checked_at = NOW(),
last_check_error = '',
updated_at = NOW()
RETURNING id
`,
[
input.platform,
platformUid,
String(input.payload.nickname || '')
.trim()
.slice(0, 120),
payloadJson,
input.source,
],
)
return Number(result.rows[0]?.id || 0)
}
export async function loadSemiAutoCredential(
credentialIdInput: unknown,
): Promise<SemiAutoCredentialRecord | null> {
const credentialId = Number(credentialIdInput || 0)
if (!Number.isInteger(credentialId) || credentialId <= 0) return null
const result = await query<CredentialRow>(
`
SELECT
id, platform, platform_uid, platform_nickname, credential_payload_json,
credential_source, credential_status, credential_updated_at, last_checked_at
FROM semi_auto_credentials
WHERE id = $1
LIMIT 1
`,
[credentialId],
)
const row = result.rows[0]
return row ? decodeCredential(row) : null
}
export async function markSemiAutoCredentialCheck(
credentialIdInput: unknown,
input: {
status: 'valid' | 'invalid' | 'error'
error?: string
},
): Promise<void> {
const credentialId = Number(credentialIdInput || 0)
if (!Number.isInteger(credentialId) || credentialId <= 0) return
await query(
`
UPDATE semi_auto_credentials
SET credential_status = $2,
last_checked_at = NOW(),
last_check_error = $3,
updated_at = NOW()
WHERE id = $1
`,
[
credentialId,
input.status,
String(input.error || '')
.trim()
.slice(0, 1000),
],
)
}