重构(半自动履约): 统一虎牙/微博状态写入、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:
yml
2026-11-30 23:23:07 +08:00
parent 133705e986
commit eaf6296430
48 changed files with 3522 additions and 1482 deletions
@@ -21,6 +21,7 @@ import {
Modal,
Select,
Space,
Tabs,
Tag,
Timeline,
Typography,
@@ -28,6 +29,7 @@ import {
import type { TableColumnsType } from 'antd'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useEffect, useMemo, useRef, useState } from 'react'
import { useSearchParams } from 'react-router'
import ImageUpload from '@/components/files/ImageUpload'
import PageHeader from '@/components/admin/PageHeader'
@@ -37,19 +39,38 @@ import {
cancelAdminSemiAutoTask,
claimAdminSemiAutoTask,
completeAdminSemiAutoTask,
createAdminSemiAutoBrowserSession,
createSemiAutoBrowserSession,
exportAdminSemiAutoCredential,
fetchAdminSemiAutoTask,
fetchAdminSemiAutoTasks,
requestAdminSemiAutoCustomerReauth,
syncAdminSemiAutoTask,
} from '@/services/admin/semi-auto'
import {
SEMI_AUTO_CATEGORY_KEYS,
SEMI_AUTO_CATEGORY_LABELS,
semiAutoCategoryLabel,
} from '@/types/admin/semi-auto'
import type { SemiAutoTask } from '@/types/admin/semi-auto'
import type { UploadedFile } from '@/types/worker-platform'
import { formatAdminDateTime } from '@/utils/admin-time'
import { buildCustomerFulfillmentPath } from '@/utils/customer-fulfillment-link'
import { formatHuyaBindingDecisionMessage } from '@/utils/semi-auto-binding-decision'
import { resolvePostInjectionUrl } from '@/utils/semi-auto-injection'
import {
buildSemiAutoInjectionKit,
dispatchSemiAutoInjection,
isSemiAutoExchangeHelperReady,
matchSemiAutoInjectionResult,
resolvePostInjectionUrl,
SEMI_AUTO_RESULT_EVENT,
} from '@/utils/semi-auto-injection'
import {
buildSemiAutoTaskListParams,
isSemiAutoPlatformTab,
resolveSemiAutoPlatformTab,
SEMI_AUTO_PLATFORM_TABS,
type SemiAutoCategoryFilter,
} from '@/utils/semi-auto-task-filters'
import { canCompleteSemiAutoTask, canInjectSemiAutoBrowser } from '@/utils/semi-auto-task-readiness'
const { Text } = Typography
@@ -118,20 +139,21 @@ type CompleteFormValues = {
costYuan?: number
}
const INJECTION_FOLLOW_UP_TIMEOUT_MS = 30_000
const INJECTION_RESULT_TIMEOUT_MS = 30_000
/** 一次在途注入:只接受 request_id 与它匹配的扩展回执。 */
type PendingInjection = {
requestId: string
taskId: number
platform: SemiAutoTask['platform']
popup: Window | null
timeoutId: number
}
export default function AdminSemiAutoTasksPage() {
const { message, modal } = App.useApp()
const queryClient = useQueryClient()
const [searchParams, setSearchParams] = useSearchParams()
const [keyword, setKeyword] = useState('')
const [platform, setPlatform] = useState('')
const [categoryFilter, setCategoryFilter] = useState<SemiAutoCategoryFilter>('all')
const [status, setStatus] = useState('')
const [page, setPage] = useState(1)
const [pageSize, setPageSize] = useState(20)
@@ -142,15 +164,12 @@ export default function AdminSemiAutoTasksPage() {
const [completeForm] = Form.useForm<CompleteFormValues>()
const pendingInjectionRef = useRef<PendingInjection | null>(null)
// tab 即平台:URL 上没有 tab 或值非法时落到虎牙,刷新/分享链接后仍是同一个列表。
const tab = resolveSemiAutoPlatformTab(searchParams.get('tab'))
const params = useMemo(
() => ({
page,
pageSize,
keyword: keyword.trim() || undefined,
platform: platform || undefined,
status: status || undefined,
}),
[keyword, page, pageSize, platform, status],
() => buildSemiAutoTaskListParams({ tab, categoryFilter, keyword, status, page, pageSize }),
[tab, categoryFilter, keyword, status, page, pageSize],
)
const listQuery = useQuery({
@@ -174,77 +193,39 @@ export default function AdminSemiAutoTasksPage() {
useEffect(() => {
const handleResult = (event: Event) => {
const detail = (event as CustomEvent<string>).detail
if (typeof detail !== 'string') return
let result: { ok?: boolean; written?: number; error?: string }
try {
result = JSON.parse(detail) as { ok?: boolean; written?: number; error?: string }
} catch {
return
}
if (!result || typeof result !== 'object') return
const pending = pendingInjectionRef.current
if (result.ok) {
message.success(`浏览器登录态已注入(${Number(result.written || 0)} 个 Cookie)`)
if (!pending) return
window.clearTimeout(pending.timeoutId)
pendingInjectionRef.current = null
const targetUrl = resolvePostInjectionUrl(pending.platform)
const popup = pending.popup
if (!targetUrl) {
if (popup && !popup.closed) popup.close()
return
}
if (popup && !popup.closed) {
try {
popup.location.href = targetUrl
popup.focus()
return
} catch {
// 占位页已被关闭或无法导航:先关掉残留标签,再用 window.open 兜底。
try {
popup.close()
} catch {
// 关闭失败不影响继续打开目标页。
}
}
}
const opened = window.open(targetUrl, '_blank')
if (opened) {
opened.focus()
return
}
modal.info({
title: '注入成功',
content: (
<span>
浏览器拦截了自动打开的新标签页,请
<a href={targetUrl} target="_blank" rel="noreferrer">
点击这里打开平台页面
</a>
。
</span>
),
})
return
}
message.error(result.error || '浏览器登录态注入失败')
if (!pending) return
// 扩展回执是页面级广播:只消费 request_id 与本次注入匹配的那一条。
const result = matchSemiAutoInjectionResult(
(event as CustomEvent<unknown>).detail,
pending.requestId,
)
if (!result) return
window.clearTimeout(pending.timeoutId)
pendingInjectionRef.current = null
if (pending.popup && !pending.popup.closed) pending.popup.close()
if (result.ok) {
message.success(`已写入 ${result.written} 个 Cookie(扩展已打开平台页面)`)
} else {
message.error(
result.error ||
(result.written > 0
? `只写入 ${result.written} 个 Cookie,${result.failed} 个失败,请重新注入`
: '浏览器登录态写入失败,请确认「半自动兑换助手」可用后重试'),
)
}
void queryClient.invalidateQueries({ queryKey: ['admin-semi-auto-tasks'] })
void queryClient.invalidateQueries({ queryKey: ['admin-semi-auto-task'] })
}
window.addEventListener('huya-exchange-result', handleResult)
return () => window.removeEventListener('huya-exchange-result', handleResult)
}, [message, modal])
window.addEventListener(SEMI_AUTO_RESULT_EVENT, handleResult)
return () => window.removeEventListener(SEMI_AUTO_RESULT_EVENT, handleResult)
}, [message, queryClient])
// 页面卸载时清理未完成的占位页,避免留下空白标签。
// 页面卸载时清掉在途注入的定时器,避免已卸载页面继续弹提示。
useEffect(() => {
return () => {
const pending = pendingInjectionRef.current
if (!pending) return
window.clearTimeout(pending.timeoutId)
if (pending.popup && !pending.popup.closed) pending.popup.close()
pendingInjectionRef.current = null
}
}, [])
@@ -271,69 +252,9 @@ export default function AdminSemiAutoTasksPage() {
const pending = pendingInjectionRef.current
if (!pending) return
window.clearTimeout(pending.timeoutId)
if (pending.popup && !pending.popup.closed) pending.popup.close()
pendingInjectionRef.current = null
}
function openInjectionPlaceholder() {
const popup = window.open('about:blank', '_blank')
if (!popup) return null
try {
popup.document.title = '正在注入浏览器登录态'
popup.document.body.textContent = '正在注入浏览器登录态,完成后将自动打开平台页面…'
} catch {
// 占位内容写入失败不影响后续跳转。
}
return popup
}
const injectionMutation = useMutation({
mutationFn: (task: SemiAutoTask) =>
createAdminSemiAutoBrowserSession(task.id, firstTargetUrl(task)),
onSuccess: (response) => {
const ticket = String(response.data?.ticket || '').trim()
if (!ticket) {
cancelPendingInjection()
message.error('注入票据生成失败')
return
}
window.postMessage({ type: 'ORDER_SITE_SEMI_AUTO_INJECT', ticket }, window.location.origin)
message.info('正在注入浏览器登录态,请稍候')
void refreshAll()
},
onError: (error) => {
cancelPendingInjection()
message.error(error instanceof Error ? error.message : '打开浏览器登录态失败')
},
})
function startInjection(task: SemiAutoTask) {
if (pendingInjectionRef.current) {
message.warning('上一次注入尚未完成,请稍候')
return
}
// 扩展内容脚本会在白名单页面打标记;没有标记时直接提示,避免空等 30 秒。
if (document.documentElement.dataset.huyaExchangeHelper !== '1') {
message.warning('未检测到浏览器扩展,请启用「虎牙兑换助手」后刷新本页')
return
}
const popup = openInjectionPlaceholder()
const timeoutId = window.setTimeout(() => {
const pending = pendingInjectionRef.current
if (!pending) return
pendingInjectionRef.current = null
if (pending.popup && !pending.popup.closed) pending.popup.close()
message.warning('未检测到注入完成,请确认浏览器扩展已启用后重试')
}, INJECTION_FOLLOW_UP_TIMEOUT_MS)
pendingInjectionRef.current = {
taskId: task.id,
platform: task.platform,
popup,
timeoutId,
}
injectionMutation.mutate(task)
}
const credentialExportMutation = useMutation({
mutationFn: (taskId: number) => exportAdminSemiAutoCredential(taskId),
onSuccess: (response) => {
@@ -352,6 +273,64 @@ export default function AdminSemiAutoTasksPage() {
onError: (error) => message.error(error instanceof Error ? error.message : '复制账号 CK 失败'),
})
/**
* 注入流程:取 CK → 组装材料包 → 派发 CustomEvent → 等扩展回执。
* 前端不再签发/消费票据,也不自己开关标签页(写入 Cookie 并打开目标页都是扩展的职责)。
*/
const injectionMutation = useMutation({
mutationFn: (task: SemiAutoTask) =>
createSemiAutoBrowserSession(task.id, resolveInjectionTargetUrl(task)),
onSuccess: (response, task) => {
const session = response.data
const cookieCount = Array.isArray(session?.cookies) ? session.cookies.length : 0
if (!session || cookieCount === 0) {
cancelPendingInjection()
message.error('账号 CK 不可用,请客户重新登录后再注入浏览器')
return
}
cancelPendingInjection()
const kit = buildSemiAutoInjectionKit(session)
const timeoutId = window.setTimeout(() => {
const pending = pendingInjectionRef.current
if (!pending || pending.requestId !== kit.request_id) return
pendingInjectionRef.current = null
message.warning('未收到「半自动兑换助手」回执,请确认扩展已启用后重试')
}, INJECTION_RESULT_TIMEOUT_MS)
pendingInjectionRef.current = { requestId: kit.request_id, taskId: task.id, timeoutId }
if (!dispatchSemiAutoInjection(kit)) {
cancelPendingInjection()
message.error('注入材料派发失败,请刷新页面后重试')
return
}
message.info(`正在向浏览器写入 ${cookieCount} 个 Cookie,请稍候`)
void refreshAll()
},
onError: (error) => {
cancelPendingInjection()
message.error(error instanceof Error ? error.message : '获取浏览器登录态失败')
},
})
function startInjection(task: SemiAutoTask) {
if (pendingInjectionRef.current) {
message.warning('上一次注入尚未完成,请稍候')
return
}
// 扩展内容脚本会在白名单页面打标记;没有标记时直接提示 + 提供复制 CK 兜底,不静默失败。
if (!isSemiAutoExchangeHelperReady(document.documentElement?.dataset)) {
modal.warning({
title: '未检测到「半自动兑换助手」扩展',
content:
'请先在 Chrome / Edge 安装并启用「半自动兑换助手」,然后刷新本页再注入;也可以直接复制账号 CK 手工兑换。',
okText: '复制 CK',
cancelText: '我知道了',
onOk: () => credentialExportMutation.mutateAsync(task.id),
})
return
}
injectionMutation.mutate(task)
}
const reauthMutation = useMutation({
mutationFn: (task: SemiAutoTask) => requestAdminSemiAutoCustomerReauth(task.id),
onSuccess: async (response, task) => {
@@ -408,6 +387,18 @@ export default function AdminSemiAutoTasksPage() {
])
}
function changeTab(nextTab: string) {
if (!isSemiAutoPlatformTab(nextTab) || nextTab === tab) return
setPage(1)
setSearchParams(
(current) => {
current.set('tab', nextTab)
return current
},
{ replace: true },
)
}
async function copyCustomerLink(task: SemiAutoTask, successMessage = '客户授权链接已复制') {
const path = buildCustomerFulfillmentPath(task.orderNo, task.platform)
if (!path) {
@@ -498,6 +489,14 @@ export default function AdminSemiAutoTasksPage() {
</Space>
),
},
{
title: '分类',
dataIndex: 'semiAutoCategory',
width: 100,
render: (value: string) => (
<Tag color={value ? 'blue' : 'default'}>{semiAutoCategoryLabel(value)}</Tag>
),
},
{
title: '客户登录',
key: 'login',
@@ -657,12 +656,8 @@ export default function AdminSemiAutoTasksPage() {
},
]
return (
<section className="page-stack">
<PageHeader
title="半自动履约"
description="人工客服渠道下的平台账号授权、扫码绑定和浏览器辅助履约。"
/>
function renderTaskPanel() {
return (
<Card size="small">
<Space wrap style={{ marginBottom: 16 }}>
<Input.Search
@@ -676,16 +671,17 @@ export default function AdminSemiAutoTasksPage() {
style={{ width: 280 }}
/>
<Select
allowClear
placeholder="全部平台"
value={platform || undefined}
value={categoryFilter}
onChange={(value) => {
setPlatform(value || '')
setCategoryFilter(value)
setPage(1)
}}
options={[
{ value: 'huya', label: '虎牙' },
{ value: 'weibo', label: '微博' },
{ value: 'all', label: '全部分类' },
...SEMI_AUTO_CATEGORY_KEYS.map((key) => ({
value: key,
label: SEMI_AUTO_CATEGORY_LABELS[key],
})),
]}
style={{ width: 130 }}
/>
@@ -716,7 +712,7 @@ export default function AdminSemiAutoTasksPage() {
loading={listQuery.isLoading}
columns={columns}
dataSource={list}
scroll={{ x: 1400 }}
scroll={{ x: 1500 }}
pagination={{
current: pagination?.page || page,
pageSize: pagination?.pageSize || pageSize,
@@ -729,6 +725,25 @@ export default function AdminSemiAutoTasksPage() {
}}
/>
</Card>
)
}
return (
<section className="page-stack">
<PageHeader
title="半自动履约"
description="人工客服渠道下的平台账号授权、扫码绑定和浏览器辅助履约。"
/>
<Tabs
activeKey={tab}
onChange={changeTab}
items={SEMI_AUTO_PLATFORM_TABS.map((platformKey) => ({
key: platformKey,
label: PLATFORM_LABELS[platformKey] || platformKey,
// 只渲染当前 tab:两个平台同时挂在 DOM 上会重复拉一次列表。
children: tab === platformKey ? renderTaskPanel() : null,
}))}
/>
<Drawer
open={Boolean(detailTaskId)}
@@ -747,6 +762,11 @@ export default function AdminSemiAutoTasksPage() {
<Descriptions.Item label="平台">
{PLATFORM_LABELS[detail.task.platform] || detail.task.platform}
</Descriptions.Item>
<Descriptions.Item label="履约分类">
<Tag color={detail.task.semiAutoCategory ? 'blue' : 'default'}>
{semiAutoCategoryLabel(detail.task.semiAutoCategory)}
</Tag>
</Descriptions.Item>
<Descriptions.Item label="Connector">
<Tag color={detail.task.connectorMode === 'mock' ? 'orange' : 'green'}>
{detail.task.connectorMode === 'mock'
@@ -1033,11 +1053,14 @@ export default function AdminSemiAutoTasksPage() {
)
}
function firstTargetUrl(task: SemiAutoTask) {
function resolveInjectionTargetUrl(task: SemiAutoTask) {
// 优先用人工 SKU 里配的 browserTargets,再用平台默认目标页;
// 这个 URL 只是 `target_url`,写入 Cookie 后由扩展负责打开。
const targets = Array.isArray(task.semiAutoConfig?.browserTargets)
? task.semiAutoConfig.browserTargets
: []
return String(targets.find((item) => item?.url)?.url || '')
const configured = String(targets.find((item) => item?.url)?.url || '')
return configured || resolvePostInjectionUrl(task.platform)
}
function taskNeedsCustomerReauth(task: SemiAutoTask) {
@@ -50,6 +50,8 @@ import {
saveAdminManualConfig,
} from '@/services/admin'
import type { ManualPlatformKey, ManualSkuItem } from '@/types/admin'
import { SEMI_AUTO_CATEGORY_KEYS, SEMI_AUTO_CATEGORY_LABELS } from '@/types/admin/semi-auto'
import type { SemiAutoCategory } from '@/types/admin/semi-auto'
import { ADMIN_DEFAULT_PAGE_SIZE, buildAdminTablePagination } from '@/utils/admin-pagination'
import {
formatCreditQuantity,
@@ -68,6 +70,7 @@ type ConfigFormValues = {
note?: string
semiAutoEnabled?: boolean
semiAutoPlatform?: '' | 'huya' | 'weibo'
semiAutoCategory?: SemiAutoCategory
douyuFulfillmentEnabled?: boolean
semiAutoConfig?: {
pageTitle?: string
@@ -153,6 +156,7 @@ export function ManualSkuConfigPanel() {
note: values.note || '',
semiAutoEnabled: values.semiAutoEnabled === true,
semiAutoPlatform: values.semiAutoEnabled ? values.semiAutoPlatform || '' : '',
semiAutoCategory: values.semiAutoEnabled ? values.semiAutoCategory || '' : '',
semiAutoConfig: values.semiAutoConfig || {},
douyuFulfillmentEnabled: values.douyuFulfillmentEnabled === true,
}),
@@ -216,6 +220,7 @@ export function ManualSkuConfigPanel() {
note: item.config?.note || '',
semiAutoEnabled: item.config?.semiAutoEnabled === true,
semiAutoPlatform: item.config?.semiAutoPlatform || '',
semiAutoCategory: item.config?.semiAutoCategory || '',
semiAutoConfig: item.config?.semiAutoConfig || {},
douyuFulfillmentEnabled: item.config?.douyuFulfillmentEnabled === true,
})
@@ -231,6 +236,7 @@ export function ManualSkuConfigPanel() {
note: '',
semiAutoEnabled: false,
semiAutoPlatform: '',
semiAutoCategory: '',
semiAutoConfig: {},
douyuFulfillmentEnabled: false,
})
@@ -682,6 +688,18 @@ export function ManualSkuConfigPanel() {
]}
/>
</Form.Item>
<Form.Item
name="semiAutoCategory"
label="履约分类"
extra="决定任务在「半自动履约」列表里的分类归属,可直接用于筛选与统计。"
>
<Select
options={SEMI_AUTO_CATEGORY_KEYS.map((key) => ({
value: key,
label: SEMI_AUTO_CATEGORY_LABELS[key],
}))}
/>
</Form.Item>
<Row gutter={12}>
<Col span={12}>
<Form.Item name={['semiAutoConfig', 'pageTitle']} label="客户页标题">
@@ -1,4 +1,5 @@
import { apiDelete, apiGet, apiPatch, apiPost } from '@/lib/http'
import type { SemiAutoCategory } from '@/types/admin/semi-auto'
import type {
ChannelMappingDiagnostics,
ChannelProductMapping,
@@ -364,6 +365,8 @@ export function saveAdminManualConfig(payload: {
note?: string
semiAutoEnabled?: boolean
semiAutoPlatform?: '' | 'huya' | 'weibo'
/** 半自动履约分类:''(未分类)/ direct_exchange / presale。 */
semiAutoCategory?: SemiAutoCategory
semiAutoConfig?: Record<string, unknown>
douyuFulfillmentEnabled?: boolean
}) {
@@ -1,5 +1,6 @@
import { apiGet, apiPost } from '@/lib/http'
import type {
SemiAutoBrowserSession,
SemiAutoCredentialExport,
SemiAutoTaskDetail,
SemiAutoTaskHistory,
@@ -40,8 +41,12 @@ export function requestAdminSemiAutoCustomerReauth(taskId: number) {
return apiPost<SemiAutoTaskDetail>(`/api/v1/admin/semi-auto/tasks/${taskId}/reauthorize`, {})
}
export function createAdminSemiAutoBrowserSession(taskId: number, targetUrl?: string) {
return apiPost<{ ticket: string; expiresAt: string; targetUrl: string }>(
/**
* 取账号登录态用于浏览器注入。
* 直接下发 Cookie 数组,不再签发一次性票据,所以没有任何票据或过期时间字段。
*/
export function createSemiAutoBrowserSession(taskId: number, targetUrl?: string) {
return apiPost<SemiAutoBrowserSession>(
`/api/v1/admin/semi-auto/tasks/${taskId}/browser-session`,
{ targetUrl: targetUrl || '' },
)
@@ -1,3 +1,5 @@
import type { SemiAutoCategory } from './semi-auto'
/**
* 履约渠道:唯一真源是 order_items.fulfillment_channel + fulfillment_status。
*/
@@ -432,6 +434,8 @@ export interface ManualFulfillmentConfig {
enabled: boolean
semiAutoEnabled: boolean
semiAutoPlatform: '' | 'huya' | 'weibo'
/** 半自动履约分类:空串 = 未分类;取值与后端 SEMI_AUTO_CATEGORY_KEYS 一致。 */
semiAutoCategory: SemiAutoCategory
douyuFulfillmentEnabled: boolean
semiAutoConfig: {
pageTitle?: string
@@ -8,6 +8,31 @@ import type {
export type SemiAutoPlatform = 'huya' | 'weibo'
/**
* 半自动履约分类。取值与后端 `SEMI_AUTO_CATEGORY_KEYS` 一一对应:
* 空串 = 未分类。前端不得在此之外新造分类口径。
*/
export type SemiAutoCategory = '' | 'direct_exchange' | 'presale'
/** 分类唯一来源:下拉选项、列表列、详情抽屉都读这张映射。 */
export const SEMI_AUTO_CATEGORY_LABELS: Record<SemiAutoCategory, string> = {
'': '未分类',
direct_exchange: '直接兑换',
presale: '预售',
}
/** 分类的全部合法取值,顺序即下拉展示顺序。 */
export const SEMI_AUTO_CATEGORY_KEYS: readonly SemiAutoCategory[] = [
'',
'direct_exchange',
'presale',
]
/** 后端未来新增分类时回落为原始值,避免把未知分类误显示成「未分类」。 */
export function semiAutoCategoryLabel(value: string | null | undefined): string {
const key = String(value ?? '')
return SEMI_AUTO_CATEGORY_LABELS[key as SemiAutoCategory] ?? key
}
export type SemiAutoBindingPolicy = {
bindingKind: 'game_role' | 'account_authorization'
bindingRequired: boolean
@@ -33,6 +58,7 @@ export type SemiAutoTask = {
fulfillmentId: number | null
platform: SemiAutoPlatform
platformLabel: string
semiAutoCategory: SemiAutoCategory
bindingPolicy: SemiAutoBindingPolicy
loginStatus: string
bindingStatus: string
@@ -185,6 +211,26 @@ export type SemiAutoTaskHistory = {
}
}
/**
* 「注入浏览器」下发的账号登录态:后端按目标域筛出的 Cookie,没有票据也没有 TTL。
* 权限边界是后台登录态 + 任务领取人 + 审计日志。
*/
export type SemiAutoBrowserSessionCookie = {
name: string
value: string
domain: string
path: string
secure: boolean
/** 平台给出的过期时间;null 表示会话 Cookie,由扩展按默认 TTL 写入。 */
expiresAt?: string | null
}
export type SemiAutoBrowserSession = {
platform: SemiAutoPlatform
targetUrl: string
cookies: SemiAutoBrowserSessionCookie[]
}
export type SemiAutoCredentialExport = {
credentialId: number
platform: SemiAutoPlatform
+136 -3
View File
@@ -1,8 +1,14 @@
import type { SemiAutoPlatform } from '@/types/admin/semi-auto'
import type {
SemiAutoBrowserSession,
SemiAutoBrowserSessionCookie,
SemiAutoPlatform,
} from '@/types/admin/semi-auto'
/**
* 注入浏览器成功后自动打开的平台页面。
* 只在客户页/后台侧使用;扩展只负责写入 Cookie,指定平台页由前端占位页打开。
* 注入浏览器成功后打开的平台页面。
*
* 前端只把 URL 作为 `target_url` 交给扩展,**不再自己开关标签页**:
* 真正的 Cookie 写入和打开目标页都在「半自动兑换助手」扩展里完成。
*/
export const POST_INJECTION_URLS: Record<SemiAutoPlatform, string> = {
huya: 'https://m-shop.huya.com/points.html?pagecode=heping_baodian_credit_center_page&sourceId=yellowcarlist&pid=1199650619883&anchorUid=1199650619883&roomid=30596253',
@@ -13,3 +19,130 @@ export function resolvePostInjectionUrl(platform: string | null | undefined): st
if (platform === 'huya' || platform === 'weibo') return POST_INJECTION_URLS[platform]
return ''
}
/** 页面派发注入材料的固定事件名,必须与扩展 relay.js 保持一致。 */
export const SEMI_AUTO_INJECT_EVENT = 'ORDER_SITE_SEMI_AUTO_INJECT'
/** 扩展回执事件名,必须与扩展 relay.js 保持一致。 */
export const SEMI_AUTO_RESULT_EVENT = 'huya-exchange-result'
/** 扩展内容脚本写入的页面标记,用来判断扩展是否可用。 */
export const SEMI_AUTO_HELPER_FLAGS = ['huyaExchangeHelper', 'semiAutoExchangeHelper'] as const
/** 派发给扩展的材料包:字段名是扩展协议的一部分,不要改名。 */
export type SemiAutoInjectionKit = {
request_id: string
platform: SemiAutoPlatform
target_url: string
cookies: SemiAutoBrowserSessionCookie[]
}
/** 扩展回执:`ok` 只代表 Cookie 写入成功,不代表兑换成功。 */
export type SemiAutoInjectionResult = {
request_id: string
ok: boolean
written: number
failed: number
error: string
}
/**
* 每次注入生成独立的 request_id。
*
* 扩展回执是页面级广播,多个标签页/多次点击会互相串,
* 只有 request_id 与自己这一条匹配的结果才允许消费。
*/
export function createSemiAutoRequestId(): string {
const cryptoApi = globalThis.crypto
if (cryptoApi && typeof cryptoApi.randomUUID === 'function') {
try {
return cryptoApi.randomUUID()
} catch {
// 非安全上下文(http 内网地址)会抛错,走下面的兜底。
}
}
return `sa-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`
}
/**
* 组装派发给扩展的材料包。
*
* `requestId` 显式传入时原样使用(同一次注入只会有一个 id),
* cookies 直接透传后端返回的数组,前端不裁剪、不补字段。
*/
export function buildSemiAutoInjectionKit(
session: SemiAutoBrowserSession,
requestId: string = createSemiAutoRequestId(),
): SemiAutoInjectionKit {
return {
request_id: requestId,
platform: session.platform,
target_url: String(session.targetUrl || ''),
cookies: session.cookies ?? [],
}
}
/**
* 派发注入材料。
*
* 同时把材料挂到 `window.__semiAutoExchangeKit` 作为兜底:
* 扩展如果没收到事件(例如内容脚本尚未注入),操作者可以手动点扩展图标读取它。
*/
export function dispatchSemiAutoInjection(kit: SemiAutoInjectionKit): boolean {
if (typeof window === 'undefined') return false
;(window as Window & { __semiAutoExchangeKit?: SemiAutoInjectionKit }).__semiAutoExchangeKit = kit
try {
window.dispatchEvent(new CustomEvent(SEMI_AUTO_INJECT_EVENT, { detail: JSON.stringify(kit) }))
return true
} catch {
return false
}
}
/**
* 解析扩展回执。
*
* 回执 detail 是 JSON 字符串(扩展可能回传空串或非法 JSON),解析失败一律丢弃,
* 绝不把「没读到结果」当成成功。
*/
export function parseSemiAutoInjectionResult(detail: unknown): SemiAutoInjectionResult | null {
let payload: unknown = detail
if (typeof detail === 'string') {
try {
payload = JSON.parse(detail) as unknown
} catch {
return null
}
}
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return null
const source = payload as Record<string, unknown>
const requestId = typeof source.request_id === 'string' ? source.request_id.trim() : ''
if (!requestId) return null
return {
request_id: requestId,
ok: source.ok === true,
written: Number.isFinite(Number(source.written)) ? Number(source.written) : 0,
failed: Number.isFinite(Number(source.failed)) ? Number(source.failed) : 0,
error: typeof source.error === 'string' ? source.error : '',
}
}
/** 只接受与自己这一次注入匹配的回执,其余(含其它标签页的结果)一律忽略。 */
export function matchSemiAutoInjectionResult(
detail: unknown,
requestId: string,
): SemiAutoInjectionResult | null {
const expected = String(requestId || '').trim()
if (!expected) return null
const result = parseSemiAutoInjectionResult(detail)
if (!result || result.request_id !== expected) return null
return result
}
/** 扩展是否已在本页打标记(标记由内容脚本写入,未安装/未启用时为 false)。 */
export function isSemiAutoExchangeHelperReady(
dataset: Record<string, string | undefined> | null | undefined,
): boolean {
if (!dataset) return false
return SEMI_AUTO_HELPER_FLAGS.some((flag) => dataset[flag] === '1')
}
@@ -0,0 +1,65 @@
import type { SemiAutoCategory, SemiAutoPlatform } from '@/types/admin/semi-auto'
/**
* 半自动履约页的 tab = 平台。tab key 直接就是 `platform` 参数值,
* 不再额外维护一张映射表(历史上多写一份名单的后果是「tab 点了没反应」)。
*/
export const SEMI_AUTO_PLATFORM_TABS: readonly SemiAutoPlatform[] = ['huya', 'weibo']
/** URL 不带 `?tab=` 或带了非法值时落到虎牙。 */
export const DEFAULT_SEMI_AUTO_PLATFORM_TAB: SemiAutoPlatform = 'huya'
/**
* 分类筛选器的取值。
*
* - `all`:不传 `category` 参数(全部)
* - `''`:显式传空串,后端据此筛「未分类」
* - `direct_exchange` / `presale`:按分类筛
*/
export type SemiAutoCategoryFilter = 'all' | SemiAutoCategory
export function isSemiAutoPlatformTab(value: string | null | undefined): value is SemiAutoPlatform {
return SEMI_AUTO_PLATFORM_TABS.includes(value as SemiAutoPlatform)
}
/** 把 URL 上的 tab 归一成合法平台,非法值回落默认 tab。 */
export function resolveSemiAutoPlatformTab(value: string | null | undefined): SemiAutoPlatform {
return isSemiAutoPlatformTab(value) ? value : DEFAULT_SEMI_AUTO_PLATFORM_TAB
}
/**
* 分类筛选器 → 请求参数。
*
* 「全部」必须返回 undefined(参数不出现),「未分类」必须返回空串
* (axios 会序列化成 `category=`),两者不能混为一谈。
*/
export function resolveSemiAutoCategoryFilter(
filter: SemiAutoCategoryFilter | null | undefined,
): SemiAutoCategory | undefined {
if (filter === 'direct_exchange' || filter === 'presale') return filter
if (filter === '') return ''
return undefined
}
/** 列表查询参数:页面与单测共用同一份组装逻辑。 */
export function buildSemiAutoTaskListParams(input: {
tab: string | null | undefined
categoryFilter: SemiAutoCategoryFilter
keyword?: string
status?: string
page: number
pageSize: number
}): Record<string, unknown> {
const params: Record<string, unknown> = {
page: input.page,
pageSize: input.pageSize,
platform: resolveSemiAutoPlatformTab(input.tab),
}
const keyword = String(input.keyword || '').trim()
if (keyword) params.keyword = keyword
const status = String(input.status || '')
if (status) params.status = status
const category = resolveSemiAutoCategoryFilter(input.categoryFilter)
if (category !== undefined) params.category = category
return params
}
+121 -27
View File
@@ -4,14 +4,32 @@ import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import test from 'node:test'
import { POST_INJECTION_URLS, resolvePostInjectionUrl } from '../src/utils/semi-auto-injection.ts'
import {
POST_INJECTION_URLS,
SEMI_AUTO_INJECT_EVENT,
SEMI_AUTO_RESULT_EVENT,
buildSemiAutoInjectionKit,
createSemiAutoRequestId,
isSemiAutoExchangeHelperReady,
matchSemiAutoInjectionResult,
parseSemiAutoInjectionResult,
resolvePostInjectionUrl,
} from '../src/utils/semi-auto-injection.ts'
const source = readFileSync(
join(dirname(fileURLToPath(import.meta.url)), '../src/pages/admin/AdminSemiAutoTasksPage.tsx'),
'utf8',
)
const root = dirname(fileURLToPath(import.meta.url))
const adminPage = readFileSync(join(root, '../src/pages/admin/AdminSemiAutoTasksPage.tsx'), 'utf8')
const adminService = readFileSync(join(root, '../src/services/admin/semi-auto.ts'), 'utf8')
test('注入完成后打开对应平台页面', () => {
const session = {
platform: 'huya' as const,
targetUrl: 'https://m-shop.huya.com/points.html',
cookies: [
{ name: 'huya_uid', value: '123456', domain: '.huya.com', path: '/', secure: true },
{ name: 'huya_token', value: 'abc.def', domain: '.huya.com', path: '/', secure: true },
],
}
test('注入完成后打开对应平台页面(常量与解析保留)', () => {
assert.equal(resolvePostInjectionUrl('huya'), POST_INJECTION_URLS.huya)
assert.equal(resolvePostInjectionUrl('weibo'), POST_INJECTION_URLS.weibo)
assert.match(POST_INJECTION_URLS.huya, /^https:\/\/m-shop\.huya\.com\/points\.html\?/)
@@ -23,25 +41,101 @@ test('注入完成后打开对应平台页面', () => {
assert.equal(resolvePostInjectionUrl(null), '')
})
test('注入按钮预开新标签页,完成后跳转,失败/超时关闭', () => {
assert.ok(source.includes("window.open('about:blank', '_blank')"))
assert.ok(source.includes('function startInjection('))
assert.ok(source.includes('onClick={() => startInjection(task)}'))
assert.ok(source.includes('onClick={() => startInjection(detail.task)}'))
assert.ok(source.includes('huya-exchange-result'))
assert.ok(source.includes('resolvePostInjectionUrl(pending.platform)'))
assert.ok(source.includes('popup.location.href = targetUrl'))
assert.ok(source.includes('popup.focus()'))
assert.ok(source.includes("const opened = window.open(targetUrl, '_blank')"))
// 占位页无法导航时,先关闭残留标签再走 window.open 兜底,避免留下空白页。
const jumpIndex = source.indexOf('popup.location.href = targetUrl')
const fallbackIndex = source.indexOf("const opened = window.open(targetUrl, '_blank')")
assert.ok(jumpIndex >= 0 && fallbackIndex > jumpIndex)
assert.ok(source.slice(jumpIndex, fallbackIndex).includes('popup.close()'))
assert.ok(source.includes('pending.popup.close()'))
assert.ok(source.includes('INJECTION_FOLLOW_UP_TIMEOUT_MS'))
assert.ok(source.includes('未检测到注入完成'))
assert.ok(source.includes('上一次注入尚未完成'))
assert.ok(source.includes("dataset.huyaExchangeHelper !== '1'"))
assert.ok(source.includes('未检测到浏览器扩展'))
test('材料包字段与扩展协议一致,cookies 原样透传', () => {
const kit = buildSemiAutoInjectionKit(session, 'req-1')
assert.deepEqual(Object.keys(kit).sort(), ['cookies', 'platform', 'request_id', 'target_url'])
assert.equal(kit.request_id, 'req-1')
assert.equal(kit.platform, 'huya')
assert.equal(kit.target_url, session.targetUrl)
// 不裁剪、不补字段:扩展按这个结构直接写 Cookie。
assert.deepEqual(kit.cookies, session.cookies)
assert.equal(kit.cookies[0].name, 'huya_uid')
assert.equal(kit.cookies[0].domain, '.huya.com')
})
test('显式传入的 request_id 原样保留,不会在组装时被换掉', () => {
const first = buildSemiAutoInjectionKit(session, 'stable-id')
const second = buildSemiAutoInjectionKit(session, 'stable-id')
assert.equal(first.request_id, 'stable-id')
assert.deepEqual(first, second)
})
test('自动生成的 request_id 每次不同,且可用于回执匹配', () => {
const ids = new Set(Array.from({ length: 20 }, () => createSemiAutoRequestId()))
assert.equal(ids.size, 20)
for (const id of ids) assert.ok(id.length >= 8)
})
test('回执只接受 request_id 匹配的那一条', () => {
const detail = JSON.stringify({
request_id: 'req-1',
ok: true,
written: 2,
failed: 0,
error: '',
})
const matched = matchSemiAutoInjectionResult(detail, 'req-1')
assert.deepEqual(matched, {
request_id: 'req-1',
ok: true,
written: 2,
failed: 0,
error: '',
})
// 其它标签页/上一次注入的结果必须被丢弃,否则会把失败当成功。
assert.equal(matchSemiAutoInjectionResult(detail, 'req-2'), null)
assert.equal(matchSemiAutoInjectionResult(detail, ''), null)
assert.equal(
matchSemiAutoInjectionResult(
JSON.stringify({ request_id: 'req-1', ok: false, written: 0, failed: 0, error: '未授权' }),
'req-1',
)?.error,
'未授权',
)
})
test('非法或缺失 request_id 的回执一律丢弃,不当成成功', () => {
assert.equal(parseSemiAutoInjectionResult(''), null)
assert.equal(parseSemiAutoInjectionResult('not-json'), null)
assert.equal(parseSemiAutoInjectionResult(null), null)
assert.equal(parseSemiAutoInjectionResult({ ok: true, written: 9 }), null)
assert.equal(parseSemiAutoInjectionResult([{ request_id: 'x', ok: true }]), null)
assert.equal(parseSemiAutoInjectionResult(JSON.stringify({ request_id: ' ' })), null)
// 缺字段时按「没写成」处理,ok 只有严格 true 才算成功。
assert.deepEqual(parseSemiAutoInjectionResult({ request_id: 'x' }), {
request_id: 'x',
ok: false,
written: 0,
failed: 0,
error: '',
})
})
test('扩展可用标记:任一标记为 1 即可用', () => {
assert.equal(isSemiAutoExchangeHelperReady({ huyaExchangeHelper: '1' }), true)
assert.equal(isSemiAutoExchangeHelperReady({ semiAutoExchangeHelper: '1' }), true)
assert.equal(isSemiAutoExchangeHelperReady({ huyaExchangeHelper: '0' }), false)
assert.equal(isSemiAutoExchangeHelperReady({}), false)
assert.equal(isSemiAutoExchangeHelperReady(null), false)
})
test('后台页面改用 CustomEvent 协议,旧 postMessage 与占位页逻辑已删除', () => {
assert.ok(adminPage.includes('dispatchSemiAutoInjection'))
assert.ok(adminPage.includes('buildSemiAutoInjectionKit'))
assert.ok(adminPage.includes('matchSemiAutoInjectionResult'))
assert.ok(adminPage.includes('SEMI_AUTO_RESULT_EVENT'))
assert.ok(adminPage.includes('未检测到「半自动兑换助手」扩展'))
assert.ok(adminPage.includes('已写入 ${result.written} 个 Cookie'))
assert.ok(adminPage.includes('resolveInjectionTargetUrl(task)'))
// 旧协议:postMessage、一次性票据、占位标签页全部不再出现。
assert.ok(!adminPage.includes('window.postMessage'))
assert.ok(!adminPage.includes('about:blank'))
assert.ok(!adminPage.includes('ticket'))
assert.ok(!adminService.includes('ticket'))
assert.ok(!adminService.includes('expiresAt'))
})
test('事件名与扩展 relay.js 保持一致', () => {
assert.equal(SEMI_AUTO_INJECT_EVENT, 'ORDER_SITE_SEMI_AUTO_INJECT')
assert.equal(SEMI_AUTO_RESULT_EVENT, 'huya-exchange-result')
})
@@ -0,0 +1,109 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import test from 'node:test'
import {
DEFAULT_SEMI_AUTO_PLATFORM_TAB,
SEMI_AUTO_PLATFORM_TABS,
buildSemiAutoTaskListParams,
isSemiAutoPlatformTab,
resolveSemiAutoCategoryFilter,
resolveSemiAutoPlatformTab,
} from '../src/utils/semi-auto-task-filters.ts'
const root = dirname(fileURLToPath(import.meta.url))
const adminPage = readFileSync(join(root, '../src/pages/admin/AdminSemiAutoTasksPage.tsx'), 'utf8')
test('tab → platform 参数映射:tab 就是平台', () => {
assert.deepEqual(SEMI_AUTO_PLATFORM_TABS, ['huya', 'weibo'])
assert.equal(
buildSemiAutoTaskListParams({ tab: 'weibo', categoryFilter: 'all', page: 1, pageSize: 20 })
.platform,
'weibo',
)
assert.equal(
buildSemiAutoTaskListParams({ tab: 'huya', categoryFilter: 'all', page: 1, pageSize: 20 })
.platform,
'huya',
)
})
test('非法或缺失 tab 回落到虎牙,且页面不再自己维护平台 Select', () => {
assert.equal(DEFAULT_SEMI_AUTO_PLATFORM_TAB, 'huya')
for (const bad of [null, '', 'nope', 'douyu']) {
assert.equal(resolveSemiAutoPlatformTab(bad), 'huya')
assert.equal(isSemiAutoPlatformTab(bad), false)
}
assert.equal(isSemiAutoPlatformTab('weibo'), true)
assert.ok(adminPage.includes('SEMI_AUTO_PLATFORM_TABS.map'))
assert.ok(adminPage.includes("current.set('tab', nextTab)"))
assert.ok(!adminPage.includes('placeholder="全部平台"'))
})
test('分类参数组装:全部不传、未分类传空串、其余传分类值', () => {
assert.equal(resolveSemiAutoCategoryFilter('all'), undefined)
assert.equal(resolveSemiAutoCategoryFilter(''), '')
assert.equal(resolveSemiAutoCategoryFilter('direct_exchange'), 'direct_exchange')
assert.equal(resolveSemiAutoCategoryFilter('presale'), 'presale')
const all = buildSemiAutoTaskListParams({
tab: 'huya',
categoryFilter: 'all',
page: 1,
pageSize: 20,
})
assert.equal('category' in all, false)
const unclassified = buildSemiAutoTaskListParams({
tab: 'huya',
categoryFilter: '',
page: 1,
pageSize: 20,
})
assert.equal(unclassified.category, '')
const presale = buildSemiAutoTaskListParams({
tab: 'huya',
categoryFilter: 'presale',
page: 2,
pageSize: 50,
})
assert.equal(presale.category, 'presale')
assert.equal(presale.page, 2)
assert.equal(presale.pageSize, 50)
})
test('keyword 与 status 为空时不进参数,避免空串误筛', () => {
const params = buildSemiAutoTaskListParams({
tab: 'weibo',
categoryFilter: 'all',
keyword: ' ',
status: '',
page: 1,
pageSize: 20,
})
assert.equal('keyword' in params, false)
assert.equal('status' in params, false)
const filled = buildSemiAutoTaskListParams({
tab: 'weibo',
categoryFilter: 'direct_exchange',
keyword: ' 虎牙 ',
status: 'processing',
page: 1,
pageSize: 20,
})
assert.equal(filled.keyword, '虎牙')
assert.equal(filled.status, 'processing')
assert.equal(filled.category, 'direct_exchange')
})
test('页面分类筛选与列表列都读同一张映射表', () => {
assert.ok(adminPage.includes('SEMI_AUTO_CATEGORY_LABELS'))
assert.ok(adminPage.includes('semiAutoCategoryLabel'))
assert.ok(adminPage.includes("title: '分类'"))
assert.ok(adminPage.includes("label: '全部分类'"))
assert.ok(adminPage.includes('setCategoryFilter(value)'))
})