Files
order_site/apps/extensions/semi-auto-exchange-helper/background.js
T
yml f9e50c499c 修复(半自动注入): 扩展白名单覆盖本机所有端口并显式提示未安装状态
- manifest content_scripts.matches 改为 http://localhost/* 与 http://127.0.0.1/*,
  覆盖本机 Caddy(80/443) 与 Vite(5173) 等所有端口;此前只白名单 5173,
  本地从 http://localhost/ 打开后台时内容脚本不加载,注入既不写 Cookie 也不跳转。
- background 的来源校验从「精确 origin 集合」改为「主机名集合」,
  避免同一后台在不同端口下被判定为未授权来源。
- 版本升到 1.0.1;README 补充本地端口与重新构建/重新加载的说明。
- 后台页在扩展未检测到时展示常驻提示,并在点击注入时说明当前 origin、
  构建与安装步骤,明确「不会写入也不会跳转」,不再静默无反应。
2026-11-30 23:57:32 +08:00

223 lines
7.1 KiB
JavaScript

// 半自动兑换助手 service worker。
//
// 接收后台页面 relay 转发的账号登录材料(Cookie 数组),按平台写入对应域,
// 全部成功且带目标页时打开目标页;兑换动作由人工在平台页完成。
//
// 不保存任何登录态:材料只在内存里流转,写完即弃。
const COOKIE_TTL_SECONDS = 180 * 86400
const PLATFORM_DEFAULT_DOMAIN = {
huya: '.huya.com',
weibo: '.weibo.com',
}
// 允许触发注入的来源:直接从 manifest 内容脚本白名单推导主机,避免两处配置漂移。
// 只比主机不比端口:同一台机器上后台可能跑在 Caddy(80/443)、Vite(5173) 或隧道域名上。
const ALLOWED_HOSTS = (() => {
const manifest = chrome.runtime.getManifest()
const patterns = (manifest.content_scripts || []).flatMap((entry) => entry.matches || [])
const hosts = []
for (const pattern of patterns) {
try {
const { hostname } = new URL(pattern.replace(/\/\*$/, '/'))
if (hostname) hosts.push(hostname.toLowerCase())
} catch (e) {
// 形如 *://*.example.com/* 的通配主机无法解析,忽略
}
}
return hosts
})()
function originAllowed(url) {
if (!url) return false
try {
const { hostname } = new URL(url)
const host = hostname.toLowerCase()
return ALLOWED_HOSTS.some((allowed) => host === allowed || host.endsWith(`.${allowed}`))
} 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' : '失败')
})