// 半自动兑换助手 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' : '失败') })