迁移 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 中指向不存在文件的失效链接。
219 lines
6.8 KiB
JavaScript
219 lines
6.8 KiB
JavaScript
// 半自动兑换助手 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' : '失败')
|
|
})
|