虎牙人工兑换改用本机浏览器并新增扩展自动注入登录态
移除服务器浏览器方案(容器/Xvfb/noVNC/CDP 会话管理),后端仅下发 兑换材料;新增内置 Chrome/Edge 扩展一键写入 huya.com 登录态, 未安装扩展时回退控制台脚本手动注入,兑换始终由用户手动完成。
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
// 虎牙兑换助手后台:接收后台页面 relay 转发的登录材料,
|
||||
// 覆盖写入 huya.com 同名 Cookie 后打开已登录的兑换页。
|
||||
const HUYA_COOKIE_URL = 'https://www.huya.com/';
|
||||
const TTL_SECONDS = 180 * 86400;
|
||||
|
||||
function badge(tabId, text) {
|
||||
if (!tabId) return;
|
||||
chrome.action.setBadgeText({ tabId, text });
|
||||
setTimeout(() => {
|
||||
chrome.action.setBadgeText({ tabId, text: '' });
|
||||
}, 2500);
|
||||
}
|
||||
|
||||
async function injectKit(kit) {
|
||||
const cookies = Array.isArray(kit && kit.cookies) ? kit.cookies : [];
|
||||
const wanted = new Set(cookies.map(([name]) => String(name)).filter(Boolean));
|
||||
// 只清理与登录态同名的旧 Cookie(覆盖所有域/路径变体),其余 huya Cookie 保持不动,
|
||||
// 行为与控制台脚本方案一致,避免误伤浏览器里已有的其他虎牙状态。
|
||||
const existing = await chrome.cookies.getAll({ domain: 'huya.com' });
|
||||
for (const cookie of existing) {
|
||||
if (!wanted.has(cookie.name)) continue;
|
||||
const url = 'https://' + cookie.domain.replace(/^\./, '') + (cookie.path || '/');
|
||||
try {
|
||||
await chrome.cookies.remove({ url, name: cookie.name });
|
||||
} catch (e) { /* 单个失败不阻断 */ }
|
||||
}
|
||||
const expirationDate = Math.floor(Date.now() / 1000) + TTL_SECONDS;
|
||||
for (const [name, value] of cookies) {
|
||||
if (!name) continue;
|
||||
try {
|
||||
await chrome.cookies.set({
|
||||
url: HUYA_COOKIE_URL,
|
||||
domain: '.huya.com',
|
||||
path: '/',
|
||||
name: String(name),
|
||||
value: value == null ? '' : String(value),
|
||||
secure: true,
|
||||
expirationDate,
|
||||
});
|
||||
} catch (e) { /* 单个失败不阻断 */ }
|
||||
}
|
||||
if (kit && kit.target_url) {
|
||||
chrome.tabs.create({ url: kit.target_url });
|
||||
}
|
||||
}
|
||||
|
||||
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
|
||||
if (msg && msg.type === 'inject' && msg.kit) {
|
||||
injectKit(msg.kit).then(() => badge(sender.tab && sender.tab.id, 'OK'));
|
||||
sendResponse({ ok: true });
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
|
||||
// 兜底:后台页面把材料存到 window.__huyaExchangeKit,点击扩展图标时读取。
|
||||
chrome.action.onClicked.addListener(async (tab) => {
|
||||
if (!tab || !tab.id) return;
|
||||
let payload = null;
|
||||
try {
|
||||
const [result] = await chrome.scripting.executeScript({
|
||||
target: { tabId: tab.id },
|
||||
func: () => window.__huyaExchangeKit || null,
|
||||
});
|
||||
payload = result ? result.result : null;
|
||||
} catch (e) {
|
||||
return; // 无权访问当前页面
|
||||
}
|
||||
if (!payload) {
|
||||
badge(tab.id, '无任务');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await injectKit(JSON.parse(payload));
|
||||
badge(tab.id, 'OK');
|
||||
} catch (e) {
|
||||
badge(tab.id, '失败');
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user