重构(半自动履约): 统一虎牙/微博状态写入、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
@@ -0,0 +1,70 @@
# 半自动兑换助手(order_site)
配套 order_site 后台「半自动履约」使用:把所选虎牙/微博账号的登录态写入**操作者本机浏览器**,
兑换动作由人工在平台页面完成。
本扩展由 order_site 维护,取代 live-hub-py 仓库里的 `web/extension/huya-exchange-helper`。
两者协议不同,**不能混用**:旧扩展监听 `huya-exchange-kit` 且只支持虎牙域。
## 它做什么 / 不做什么
- 做:接收后台页面派发的 Cookie 数组 → 按平台写入 `.huya.com` / `.weibo.com` 等域 → 打开目标页 → 回执真实写入结果。
- 不做:不点击、不填表、不提交兑换,不保存登录态,不上报 Cookie。
## 构建
```bash
# 本地开发(只对 localhost:5173 生效)
node build.mjs
# 生产:从部署环境文件读后台域名(读 CADDY_SITE_ADDR)
node build.mjs --env-file /path/to/order-site/.env
# 生产:直接指定域名(支持逗号分隔多个)
ADMIN_ORIGINS="https://你的后台域名" node build.mjs
```
产物在 `dist/`。**生产必须用带后台域名的产物**:manifest 里只有本地开发域,
直接拿仓库目录加载到生产后台域上时内容脚本不会运行,注入会静默失效。
## 安装
1. Chrome/Edge 打开 `chrome://extensions`,开启「开发者模式」;
2. 「加载已解压的扩展程序」选择本目录的 `dist/`;
3. 打开后台半自动履约页,页面能检测到扩展后「注入浏览器」按钮才会真正写 Cookie。
升级/更换后台域名后必须重新构建并重新加载,否则页面会提示「未检测到扩展」或「未收到写入回执」。
## 协议
后台页面派发:
```js
window.dispatchEvent(
new CustomEvent('ORDER_SITE_SEMI_AUTO_INJECT', {
detail: JSON.stringify({
request_id: '<前端生成>',
platform: 'huya' | 'weibo',
target_url: 'https://...',
cookies: [{ name, value, domain, path }],
}),
}),
)
```
扩展回执:
```js
window.addEventListener('huya-exchange-result', (event) => {
const { request_id, ok, written, failed, error } = JSON.parse(event.detail)
})
```
`ok` 只代表 Cookie 写入成功,**不代表兑换成功**。
## 已知边界
- 会先删除本次要写入的**同名** Cookie,其它账号/其它域的 Cookie 保持不动。
- 目标页打不开不影响 Cookie 已写入的事实。
- 写入的 Cookie 统一设置为 180 天过期;CK 真实有效期由平台决定,过期后再注入一次即可。
- 手动点击扩展图标的兜底路径读取页面主世界的 `window.__semiAutoExchangeKit`。
@@ -0,0 +1,218 @@
// 半自动兑换助手 service worker。
//
// 接收后台页面 relay 转发的账号登录材料(Cookie 数组),按平台写入对应域,
// 全部成功且带目标页时打开目标页;兑换动作由人工在平台页完成。
//
// 不保存任何登录态:材料只在内存里流转,写完即弃。
const COOKIE_TTL_SECONDS = 180 * 86400
const PLATFORM_DEFAULT_DOMAIN = {
huya: '.huya.com',
weibo: '.weibo.com',
}
// 允许触发注入的来源站点:直接从 manifest 内容脚本白名单推导,避免两处配置漂移。
const ALLOWED_ORIGINS = (() => {
const manifest = chrome.runtime.getManifest()
const patterns = (manifest.content_scripts || []).flatMap((entry) => entry.matches || [])
const origins = new Set()
for (const pattern of patterns) {
try {
origins.add(new URL(pattern.replace(/\/\*$/, '/')).origin)
} catch (e) {
// 形如 *://*.example.com/* 的通配主机无法解析,忽略
}
}
return origins
})()
function originAllowed(url) {
if (!url) return false
try {
return ALLOWED_ORIGINS.has(new URL(url).origin)
} catch (e) {
return false
}
}
function badge(tabId, text) {
if (!tabId) return
try {
chrome.action.setBadgeText({ tabId, text })
setTimeout(() => {
chrome.action.setBadgeText({ tabId, text: '' })
}, 2500)
} catch (e) {
// 标签页已关闭等场景忽略
}
}
function normalizeDomain(rawDomain, platform) {
const domain = String(rawDomain || '').trim()
if (domain) return domain
return PLATFORM_DEFAULT_DOMAIN[platform] || ''
}
function cookieUrl(domain, path) {
const host = String(domain || '').replace(/^\./, '') || 'localhost'
const cookiePath = String(path || '/').startsWith('/') ? String(path || '/') : '/'
return `https://${host}${cookiePath}`
}
async function injectCookies(kit) {
const platform = String((kit && kit.platform) || '').trim().toLowerCase()
const cookies = Array.isArray(kit && kit.cookies) ? kit.cookies : []
const normalized = cookies
.map((cookie) => {
if (!cookie || typeof cookie !== 'object') return null
const name = String(cookie.name || '').trim()
if (!name) return null
return {
name,
value: cookie.value == null ? '' : String(cookie.value),
domain: normalizeDomain(cookie.domain, platform),
path: String(cookie.path || '/') || '/',
secure: cookie.secure === true,
expiresAt: typeof cookie.expiresAt === 'string' ? cookie.expiresAt : '',
}
})
.filter(Boolean)
if (normalized.length === 0) {
return { ok: false, written: 0, failed: 0, error: '没有可写入的 Cookie,请重新获取兑换材料' }
}
// 只清理与本次登录态同名的旧 Cookie,其余平台 Cookie 保持不动,
// 避免误伤浏览器里已有的其它账号状态。
const wantedNames = new Set(normalized.map((cookie) => cookie.name))
const domainSuffixes = new Set(
normalized.map((cookie) => String(cookie.domain).replace(/^\./, '')).filter(Boolean),
)
for (const suffix of domainSuffixes) {
let existing = []
try {
existing = await chrome.cookies.getAll({ domain: suffix })
} catch (e) {
existing = []
}
for (const cookie of existing) {
if (!wantedNames.has(cookie.name)) continue
try {
await chrome.cookies.remove({
url: cookieUrl(cookie.domain, cookie.path),
name: cookie.name,
})
} catch (e) {
// 单个失败不阻断
}
}
}
const defaultExpiration = Math.floor(Date.now() / 1000) + COOKIE_TTL_SECONDS
let written = 0
const failedNames = []
for (const cookie of normalized) {
// 平台给出的过期时间优先;无效或已过期才退回默认 TTL。
const platformExpiresMs = cookie.expiresAt ? Date.parse(cookie.expiresAt) : NaN
const expirationDate =
Number.isFinite(platformExpiresMs) && platformExpiresMs > Date.now()
? Math.floor(platformExpiresMs / 1000)
: defaultExpiration
try {
await chrome.cookies.set({
url: cookieUrl(cookie.domain, cookie.path),
domain: cookie.domain,
path: cookie.path,
name: cookie.name,
value: cookie.value,
secure: cookie.secure,
expirationDate,
})
written += 1
} catch (e) {
failedNames.push(cookie.name)
}
}
const targetUrl = String((kit && kit.target_url) || '').trim()
// 一个都没写进去时不要打开目标页:否则操作者看到的是未登录或上一个账号
if (written > 0 && targetUrl) {
try {
chrome.tabs.create({ url: targetUrl })
} catch (e) {
// 打不开目标页不影响 Cookie 已写入的事实
}
}
const failed = failedNames.length
return {
ok: written > 0 && failed === 0,
written,
failed,
error: failed
? `有 ${failed} 个 Cookie 写入失败:${failedNames.slice(0, 5).join('、')}`
: written === 0
? '没有可写入的 Cookie,请重新获取兑换材料'
: '',
}
}
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (!msg || msg.type !== 'inject' || !msg.kit) return undefined
const tab = sender && sender.tab
if (!originAllowed(tab && tab.url)) {
// 非后台站点派发的注入请求一律拒绝,页面脚本无法伪造 sender.tab.url
sendResponse({
ok: false,
written: 0,
failed: 0,
error: '来源未授权:仅允许在 order_site 后台管理页面触发注入',
})
return undefined
}
const requestId = typeof msg.kit.request_id === 'string' ? msg.kit.request_id : ''
injectCookies(msg.kit)
.then((result) => {
badge(tab && tab.id, result.ok ? 'OK' : '失败')
sendResponse({ request_id: requestId, ...result })
})
.catch((error) => {
badge(tab && tab.id, '失败')
sendResponse({
request_id: requestId,
ok: false,
written: 0,
failed: 0,
error: String((error && error.message) || error),
})
})
return true // 等 Cookie 真正写完再回执,页面才能显示真实结果
})
// 兜底:后台页面把材料存到 window.__semiAutoExchangeKit,点击扩展图标时读取。
// 该变量由页面主世界写入,必须用 world: 'MAIN' 读取(默认 isolated world 读不到)。
chrome.action.onClicked.addListener(async (tab) => {
if (!tab || !tab.id || !originAllowed(tab.url)) {
badge(tab && tab.id, '非后台页')
return
}
let kit = null
try {
const [result] = await chrome.scripting.executeScript({
target: { tabId: tab.id },
world: 'MAIN',
func: () => window.__semiAutoExchangeKit || null,
})
kit = result ? result.result : null
} catch (e) {
badge(tab.id, '失败')
return
}
if (!kit) {
badge(tab.id, '无任务')
return
}
const result = await injectCookies(kit)
badge(tab.id, result.ok ? 'OK' : '失败')
})
@@ -0,0 +1,95 @@
#!/usr/bin/env node
/**
* 打包半自动兑换助手。
*
* 作用:把 order_site 后台管理域写进 manifest.content_scripts.matches,避免把生产域名
* 硬编码进仓库,也避免扩展在非白名单站点上生效。
*
* 用法:
* node build.mjs # 只带仓库内的开发域,用于本地加载
* ADMIN_ORIGINS="https://order.example.com" node build.mjs
* node build.mjs --env-file /srv/order-site/.env # 从部署环境文件读 CADDY_SITE_ADDR
*
* 产物:dist/(Chrome「加载已解压的扩展程序」选这个目录)
*/
import fs from 'node:fs'
import path from 'node:path'
import process from 'node:process'
import { fileURLToPath } from 'node:url'
const SOURCE_DIR = path.dirname(fileURLToPath(import.meta.url))
const DIST_DIR = path.join(SOURCE_DIR, 'dist')
const COPY_FILES = ['relay.js', 'background.js', 'icon16.png', 'icon48.png', 'icon128.png']
/** 从 `--env-file` 或 `ADMIN_ENV_FILE` 读取部署环境里的后台域名。 */
function readAdminOriginsFromEnvFile() {
const args = process.argv.slice(2)
const flagIndex = args.indexOf('--env-file')
const envPath =
flagIndex >= 0 ? args[flagIndex + 1] : String(process.env.ADMIN_ENV_FILE || '').trim()
if (!envPath) return ''
const raw = fs.readFileSync(path.resolve(envPath), 'utf8')
for (const line of raw.split(/\r?\n/)) {
const trimmed = line.trim()
if (!trimmed || trimmed.startsWith('#')) continue
const match = /^(?:export\s+)?CADDY_SITE_ADDR\s*=\s*(.*)$/.exec(trimmed)
if (!match) continue
return match[1].trim().replace(/^['"]/, '').replace(/['"]$/, '')
}
return ''
}
function parseOrigins(raw) {
return String(raw || '')
.split(',')
.map((item) => item.trim())
.filter(Boolean)
.map((item) => {
let url
try {
url = new URL(item)
} catch (e) {
throw new Error(`ADMIN_ORIGINS 里的地址无法解析:${item}`)
}
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
throw new Error(`ADMIN_ORIGINS 只接受 http/https:${item}`)
}
return `${url.origin}/*`
})
}
function main() {
const manifest = JSON.parse(fs.readFileSync(path.join(SOURCE_DIR, 'manifest.json'), 'utf8'))
const envFileOrigin = readAdminOriginsFromEnvFile()
const combined = [process.env.ADMIN_ORIGINS || '', envFileOrigin].filter(Boolean).join(',')
const extraMatches = parseOrigins(combined)
const contentScripts = (manifest.content_scripts || []).map((entry) => ({
...entry,
matches: [...new Set([...(entry.matches || []), ...extraMatches])],
}))
const output = { ...manifest, content_scripts: contentScripts }
fs.rmSync(DIST_DIR, { recursive: true, force: true })
fs.mkdirSync(DIST_DIR, { recursive: true })
fs.writeFileSync(
path.join(DIST_DIR, 'manifest.json'),
`${JSON.stringify(output, null, 2)}\n`,
'utf8',
)
for (const file of COPY_FILES) {
const from = path.join(SOURCE_DIR, file)
if (!fs.existsSync(from)) continue
fs.copyFileSync(from, path.join(DIST_DIR, file))
}
const matches = contentScripts.flatMap((entry) => entry.matches || [])
console.log(`[build-extension] 已生成 ${path.relative(process.cwd(), DIST_DIR)}`)
console.log(`[build-extension] 生效站点:${matches.join(', ') || '(无)'}`)
if (extraMatches.length === 0) {
console.log(
'[build-extension] 未提供后台域名(ADMIN_ORIGINS 或 --env-file),当前产物只适用于本地开发页',
)
}
}
main()
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 653 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

@@ -0,0 +1,36 @@
{
"manifest_version": 3,
"name": "半自动兑换助手",
"version": "1.0.0",
"description": "配合 order_site 后台使用:把所选虎牙/微博账号的登录态写入本机浏览器,兑换操作仍由人工完成。",
"permissions": ["cookies", "scripting", "activeTab"],
"host_permissions": [
"*://*.huya.com/*",
"*://huya.com/*",
"*://*.weibo.com/*",
"*://weibo.com/*",
"*://*.weibo.cn/*",
"*://*.sina.com.cn/*"
],
"content_scripts": [
{
"matches": [
"http://localhost:5173/*",
"http://127.0.0.1:5173/*"
],
"js": ["relay.js"],
"run_at": "document_start"
}
],
"background": {
"service_worker": "background.js"
},
"action": {
"default_title": "半自动兑换助手"
},
"icons": {
"16": "icon16.png",
"48": "icon48.png",
"128": "icon128.png"
}
}
@@ -0,0 +1,66 @@
// 内容脚本:只在 order_site 后台管理页运行(站点白名单见 manifest.content_scripts.matches)。
//
// 职责:
// ① 打标记,让后台页面知道扩展可用;
// ② 把后台页面派发的登录材料转发给 service worker;
// ③ 把真实写入结果回执给页面(避免"注入失败但界面提示成功")。
//
// 安全边界:页面只能通过固定事件名提交材料;service worker 会二次校验消息来源站点。
// 扩展只写 Cookie 并打开目标页,不做任何兑换/点击动作。
const INJECT_EVENT = 'ORDER_SITE_SEMI_AUTO_INJECT'
const RESULT_EVENT = 'huya-exchange-result'
if (document.documentElement) {
document.documentElement.dataset.huyaExchangeHelper = '1'
document.documentElement.dataset.semiAutoExchangeHelper = '1'
}
function dispatchResult(payload) {
try {
window.dispatchEvent(
new CustomEvent(RESULT_EVENT, { detail: JSON.stringify(payload) }),
)
} catch (e) {
// 页面已卸载等场景忽略
}
}
window.addEventListener(INJECT_EVENT, (event) => {
// 后台页面用页面脚本派发的 CustomEvent,isTrusted 恒为 false,
// 所以这里不能校验 isTrusted;拦截点是 manifest 站点白名单 + service worker 的来源校验。
const detail = event && event.detail
let kit = null
try {
kit = typeof detail === 'string' ? JSON.parse(detail) : detail
} catch (e) {
return
}
if (!kit || !Array.isArray(kit.cookies) || kit.cookies.length === 0) return
const requestId = typeof kit.request_id === 'string' ? kit.request_id : ''
try {
chrome.runtime.sendMessage({ type: 'inject', kit }, (response) => {
const lastError = chrome.runtime.lastError ? chrome.runtime.lastError.message : ''
if (lastError) {
dispatchResult({ request_id: requestId, ok: false, written: 0, failed: 0, error: lastError })
return
}
const result = response || {}
dispatchResult({
request_id: result.request_id || requestId,
ok: result.ok === true,
written: Number(result.written || 0),
failed: Number(result.failed || 0),
error: String(result.error || ''),
})
})
} catch (e) {
dispatchResult({
request_id: requestId,
ok: false,
written: 0,
failed: 0,
error: String((e && e.message) || e),
})
}
})