959 lines
31 KiB
JavaScript
959 lines
31 KiB
JavaScript
// ==UserScript==
|
||
// @name 微博 CK 登录助手
|
||
// @namespace live-hub-py/weibo-cookie-login
|
||
// @version 1.0.1
|
||
// @description 在微博网页内导入 CK,覆盖微博域登录 Cookie,并验证当前 UID。
|
||
// @author live-hub-py
|
||
// @license MIT
|
||
// @match https://weibo.com/*
|
||
// @match https://www.weibo.com/*
|
||
// @match https://passport.weibo.com/*
|
||
// @grant GM_cookie
|
||
// @grant GM_registerMenuCommand
|
||
// @grant GM_getValue
|
||
// @grant GM_setValue
|
||
// @grant GM_deleteValue
|
||
// @noframes
|
||
// @run-at document-end
|
||
// ==/UserScript==
|
||
|
||
(() => {
|
||
'use strict';
|
||
|
||
const VERIFY_KEY = 'weiboCkLoginVerifyAt';
|
||
const VERIFY_WINDOW_MS = 2 * 60 * 1000;
|
||
const MAIN_COOKIE_URL = 'https://weibo.com/';
|
||
const PASSPORT_COOKIE_URL = 'https://passport.weibo.com/';
|
||
|
||
const AUTH_COOKIE_NAMES = new Set([
|
||
'SUB',
|
||
'SUBP',
|
||
'SCF',
|
||
'ALF',
|
||
'WBPSESS',
|
||
'XSRF-TOKEN',
|
||
'X-CSRF-TOKEN',
|
||
'ALC',
|
||
'SSOLoginState',
|
||
'SRF',
|
||
'SUHB',
|
||
]);
|
||
const LOGIN_MARKER_NAMES = ['SUB', 'SUBP', 'SCF', 'WBPSESS'];
|
||
const HOST_ONLY_MAIN_COOKIES = new Set(['WBPSESS', 'XSRF-TOKEN']);
|
||
const HOST_ONLY_PASSPORT_COOKIES = new Set(['ALC', 'X-CSRF-TOKEN']);
|
||
const HTTP_ONLY_COOKIES = new Set([
|
||
'SUB',
|
||
'SUBP',
|
||
'SCF',
|
||
'ALF',
|
||
'WBPSESS',
|
||
'ALC',
|
||
'SSOLoginState',
|
||
'SRF',
|
||
'SUHB',
|
||
]);
|
||
const SET_COOKIE_ATTRIBUTES = new Set([
|
||
'domain',
|
||
'path',
|
||
'expires',
|
||
'max-age',
|
||
'secure',
|
||
'httponly',
|
||
'samesite',
|
||
'priority',
|
||
'partitioned',
|
||
]);
|
||
const COOKIE_NAME_RE = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
||
|
||
function parseCookieText(raw) {
|
||
let text = String(raw || '').trim();
|
||
if (!text) throw new Error('请先粘贴微博 Cookie');
|
||
text = text.replace(/^cookie:\s*/i, '').replace(/\r/g, '\n');
|
||
|
||
const pairs = new Map();
|
||
for (const fragment of text.split(/[;\n]+/)) {
|
||
const part = fragment.trim();
|
||
if (!part) continue;
|
||
|
||
const separator = part.indexOf('=');
|
||
if (separator < 0) {
|
||
if (SET_COOKIE_ATTRIBUTES.has(part.toLowerCase())) continue;
|
||
throw new Error(`Cookie 片段格式错误:${part.slice(0, 32)}`);
|
||
}
|
||
|
||
const name = part.slice(0, separator).trim();
|
||
const value = part.slice(separator + 1).trim();
|
||
if (SET_COOKIE_ATTRIBUTES.has(name.toLowerCase())) continue;
|
||
if (!COOKIE_NAME_RE.test(name)) {
|
||
throw new Error(`Cookie 名称格式错误:${name.slice(0, 32)}`);
|
||
}
|
||
if (AUTH_COOKIE_NAMES.has(name) && !value) {
|
||
throw new Error(`Cookie ${name} 的值为空`);
|
||
}
|
||
pairs.set(name, value);
|
||
}
|
||
|
||
if (!pairs.size) throw new Error('没有识别到 Cookie');
|
||
if (!LOGIN_MARKER_NAMES.some((name) => pairs.has(name))) {
|
||
throw new Error('未找到微博登录 Cookie(SUB/SUBP/SCF/WBPSESS)');
|
||
}
|
||
return [...pairs.entries()];
|
||
}
|
||
|
||
function cookieExpiration(name, nowSeconds = Math.floor(Date.now() / 1000)) {
|
||
const days = name === 'WBPSESS' ? 1 : name === 'ALF' ? 30 : 365;
|
||
return nowSeconds + days * 86400;
|
||
}
|
||
|
||
function planCookieWrite(name, value, nowSeconds = Math.floor(Date.now() / 1000)) {
|
||
const details = {
|
||
url: MAIN_COOKIE_URL,
|
||
name,
|
||
value,
|
||
path: '/',
|
||
secure: true,
|
||
sameSite: 'no_restriction',
|
||
httpOnly: HTTP_ONLY_COOKIES.has(name),
|
||
expirationDate: cookieExpiration(name, nowSeconds),
|
||
};
|
||
|
||
if (HOST_ONLY_PASSPORT_COOKIES.has(name)) {
|
||
details.url = PASSPORT_COOKIE_URL;
|
||
} else if (!HOST_ONLY_MAIN_COOKIES.has(name)) {
|
||
details.domain = '.weibo.com';
|
||
}
|
||
return details;
|
||
}
|
||
|
||
function planCookieWrites(entries, nowSeconds = Math.floor(Date.now() / 1000)) {
|
||
return entries.map(([name, value]) => planCookieWrite(name, value, nowSeconds));
|
||
}
|
||
|
||
function gmCookieAvailable() {
|
||
return (
|
||
typeof GM_cookie !== 'undefined' &&
|
||
GM_cookie &&
|
||
typeof GM_cookie.set === 'function'
|
||
);
|
||
}
|
||
|
||
function gmCookieSet(details) {
|
||
return new Promise((resolve, reject) => {
|
||
const timer = setTimeout(() => reject(new Error('Cookie 写入超时')), 5000);
|
||
try {
|
||
GM_cookie.set(details, function (result, callbackError) {
|
||
clearTimeout(timer);
|
||
// Tampermonkey 回调为 (error),脚本猫为 (result, error)。
|
||
const error = arguments.length >= 2 ? callbackError : result;
|
||
if (error) {
|
||
reject(new Error(String(error.message || error)));
|
||
} else {
|
||
resolve();
|
||
}
|
||
});
|
||
} catch (error) {
|
||
clearTimeout(timer);
|
||
reject(error);
|
||
}
|
||
});
|
||
}
|
||
|
||
function gmCookieList(details) {
|
||
return new Promise((resolve, reject) => {
|
||
if (
|
||
typeof GM_cookie === 'undefined' ||
|
||
!GM_cookie ||
|
||
typeof GM_cookie.list !== 'function'
|
||
) {
|
||
reject(new Error('当前油猴版本不支持 GM_cookie.list'));
|
||
return;
|
||
}
|
||
const timer = setTimeout(() => reject(new Error('Cookie 读取超时')), 5000);
|
||
try {
|
||
GM_cookie.list(details, (cookies, error) => {
|
||
clearTimeout(timer);
|
||
if (error) {
|
||
reject(new Error(String(error.message || error)));
|
||
} else {
|
||
resolve(Array.isArray(cookies) ? cookies : []);
|
||
}
|
||
});
|
||
} catch (error) {
|
||
clearTimeout(timer);
|
||
reject(error);
|
||
}
|
||
});
|
||
}
|
||
|
||
function gmCookieDelete(details) {
|
||
return new Promise((resolve, reject) => {
|
||
const timer = setTimeout(() => reject(new Error('Cookie 删除超时')), 5000);
|
||
try {
|
||
GM_cookie.delete(details, function (result, callbackError) {
|
||
clearTimeout(timer);
|
||
// Tampermonkey 回调为 (error),脚本猫为 (result, error)。
|
||
const error = arguments.length >= 2 ? callbackError : result;
|
||
if (error) {
|
||
reject(new Error(String(error.message || error)));
|
||
} else {
|
||
resolve();
|
||
}
|
||
});
|
||
} catch (error) {
|
||
clearTimeout(timer);
|
||
reject(error);
|
||
}
|
||
});
|
||
}
|
||
|
||
function uniqueAttempts(details) {
|
||
const attempts = [details];
|
||
if (details.httpOnly) attempts.push({ ...details, httpOnly: false });
|
||
attempts.push({ ...details, httpOnly: false, sameSite: undefined });
|
||
|
||
const seen = new Set();
|
||
return attempts.filter((attempt) => {
|
||
const clean = Object.fromEntries(
|
||
Object.entries(attempt).filter(([, value]) => value !== undefined),
|
||
);
|
||
const key = JSON.stringify(clean);
|
||
if (seen.has(key)) return false;
|
||
seen.add(key);
|
||
Object.keys(attempt).forEach((name) => {
|
||
if (attempt[name] === undefined) delete attempt[name];
|
||
});
|
||
return true;
|
||
});
|
||
}
|
||
|
||
function setWithTampermonkey(details) {
|
||
return (async () => {
|
||
let lastError = null;
|
||
for (const attempt of uniqueAttempts({ ...details })) {
|
||
try {
|
||
await gmCookieSet(attempt);
|
||
return;
|
||
} catch (error) {
|
||
lastError = error;
|
||
}
|
||
}
|
||
throw lastError || new Error('GM_cookie 写入失败');
|
||
})();
|
||
}
|
||
|
||
function visibleCookieValue(name) {
|
||
for (const fragment of document.cookie.split(';')) {
|
||
const part = fragment.trim();
|
||
const separator = part.indexOf('=');
|
||
if (separator < 0) continue;
|
||
if (part.slice(0, separator).trim() === name) {
|
||
return part.slice(separator + 1);
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function fallbackCookieDomain(details) {
|
||
if (details.domain) return details.domain;
|
||
const hostname = location.hostname.toLowerCase();
|
||
const targetHost = new URL(details.url).hostname;
|
||
if (hostname === targetHost) return '';
|
||
if (targetHost === 'weibo.com' || targetHost.endsWith('.weibo.com')) {
|
||
return '.weibo.com';
|
||
}
|
||
return '';
|
||
}
|
||
|
||
function setWithDocumentCookie(details) {
|
||
const domain = fallbackCookieDomain(details);
|
||
const attributes = [
|
||
`${details.name}=${details.value}`,
|
||
'Path=/',
|
||
'Secure',
|
||
'SameSite=None',
|
||
`Expires=${new Date(details.expirationDate * 1000).toUTCString()}`,
|
||
];
|
||
if (domain) attributes.push(`Domain=${domain}`);
|
||
document.cookie = attributes.join('; ');
|
||
if (visibleCookieValue(details.name) === null) {
|
||
throw new Error('浏览器拒绝了 Cookie 写入');
|
||
}
|
||
}
|
||
|
||
async function writeOneCookie(details) {
|
||
let gmError = null;
|
||
if (gmCookieAvailable()) {
|
||
try {
|
||
await setWithTampermonkey(details);
|
||
return 'GM_cookie';
|
||
} catch (error) {
|
||
gmError = error;
|
||
}
|
||
}
|
||
|
||
try {
|
||
setWithDocumentCookie(details);
|
||
return 'document.cookie';
|
||
} catch (error) {
|
||
if (gmError) {
|
||
throw new Error(`GM_cookie 与页面 Cookie 均写入失败:${error.message}`);
|
||
}
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
async function writeCookies(entries) {
|
||
const plans = planCookieWrites(entries);
|
||
const written = [];
|
||
const failures = [];
|
||
const modes = new Set();
|
||
|
||
for (const details of plans) {
|
||
try {
|
||
const mode = await writeOneCookie(details);
|
||
written.push(details.name);
|
||
modes.add(mode);
|
||
} catch (error) {
|
||
failures.push({ name: details.name, message: error.message });
|
||
}
|
||
}
|
||
|
||
if (!written.length) {
|
||
throw new Error(failures[0]?.message || '没有 Cookie 写入成功');
|
||
}
|
||
return { written, failures, modes: [...modes] };
|
||
}
|
||
|
||
async function clearWeiboCookies() {
|
||
if (!window.confirm('清除微博网页登录 Cookie?这不会删除微博账号。')) return false;
|
||
|
||
let removed = 0;
|
||
if (gmCookieAvailable()) {
|
||
for (const url of [MAIN_COOKIE_URL, PASSPORT_COOKIE_URL]) {
|
||
let cookies = [];
|
||
try {
|
||
cookies = await gmCookieList({ url });
|
||
} catch (error) {
|
||
continue;
|
||
}
|
||
for (const cookie of cookies) {
|
||
if (!AUTH_COOKIE_NAMES.has(cookie.name)) continue;
|
||
const hostname = String(cookie.domain || '').replace(/^\./, '');
|
||
if (!hostname) continue;
|
||
const cookieUrl = new URL(cookie.path || '/', `https://${hostname}/`).href;
|
||
try {
|
||
await gmCookieDelete({ url: cookieUrl, name: cookie.name });
|
||
removed += 1;
|
||
} catch (error) {
|
||
// 单个 Cookie 删除失败时继续清理其余项。
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
if (!removed) {
|
||
const expires = 'Thu, 01 Jan 1970 00:00:00 GMT';
|
||
for (const name of AUTH_COOKIE_NAMES) {
|
||
document.cookie = `${name}=; Path=/; Secure; SameSite=None; Expires=${expires}`;
|
||
document.cookie = `${name}=; Path=/; Domain=.weibo.com; Secure; SameSite=None; Expires=${expires}`;
|
||
}
|
||
}
|
||
|
||
clearVerifyMarker();
|
||
return true;
|
||
}
|
||
|
||
function setVerifyMarker() {
|
||
if (typeof GM_setValue === 'function') {
|
||
GM_setValue(VERIFY_KEY, Date.now());
|
||
}
|
||
}
|
||
|
||
function readVerifyMarker() {
|
||
if (typeof GM_getValue !== 'function') return 0;
|
||
return Number(GM_getValue(VERIFY_KEY, 0)) || 0;
|
||
}
|
||
|
||
function clearVerifyMarker() {
|
||
if (typeof GM_deleteValue === 'function') {
|
||
GM_deleteValue(VERIFY_KEY);
|
||
}
|
||
}
|
||
|
||
async function readCurrentUid() {
|
||
const response = await fetch(
|
||
'https://weibo.com/ajax/statuses/config?type=uid',
|
||
{
|
||
credentials: 'include',
|
||
cache: 'no-store',
|
||
headers: { Accept: 'application/json' },
|
||
},
|
||
);
|
||
if (!response.ok) throw new Error(`微博返回 HTTP ${response.status}`);
|
||
const payload = await response.json();
|
||
const uid = String(payload?.data || '').trim();
|
||
if (payload?.ok === 1 && /^\d+$/.test(uid)) return uid;
|
||
throw new Error('微博未返回登录 UID');
|
||
}
|
||
|
||
function navigateToWeiboHome() {
|
||
const home = new URL(MAIN_COOKIE_URL);
|
||
if (
|
||
location.origin === home.origin &&
|
||
location.pathname === '/' &&
|
||
!location.search
|
||
) {
|
||
location.reload();
|
||
return;
|
||
}
|
||
location.assign(home.href);
|
||
}
|
||
|
||
const ICONS = {
|
||
key: `
|
||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||
<path d="M2.59 17.41A2 2 0 0 0 2 18.83V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.17a2 2 0 0 0 1.42-.59l.81-.81a6.5 6.5 0 1 0-4-4z"/>
|
||
<circle cx="16.5" cy="7.5" r=".5" fill="currentColor"/>
|
||
</svg>`,
|
||
close: `
|
||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||
<path d="M18 6 6 18"/><path d="m6 6 12 12"/>
|
||
</svg>`,
|
||
login: `
|
||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||
<path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"/>
|
||
<path d="m10 17 5-5-5-5"/><path d="M15 12H3"/>
|
||
</svg>`,
|
||
trash: `
|
||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||
<path d="M3 6h18"/><path d="M8 6V4h8v2"/>
|
||
<path d="m19 6-1 14H6L5 6"/><path d="M10 11v5"/><path d="M14 11v5"/>
|
||
</svg>`,
|
||
check: `
|
||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||
<circle cx="12" cy="12" r="9"/><path d="m8 12 2.5 2.5L16 9"/>
|
||
</svg>`,
|
||
alert: `
|
||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||
<circle cx="12" cy="12" r="9"/><path d="M12 8v5"/><path d="M12 16h.01"/>
|
||
</svg>`,
|
||
spinner: `
|
||
<svg class="spin" viewBox="0 0 24 24" aria-hidden="true">
|
||
<path d="M21 12a9 9 0 1 1-6.22-8.56"/>
|
||
</svg>`,
|
||
};
|
||
|
||
function init() {
|
||
const host = document.createElement('div');
|
||
host.id = 'weibo-ck-login-host';
|
||
host.style.cssText =
|
||
'all: initial; position: fixed; inset: 0; z-index: 2147483647; pointer-events: none;';
|
||
(document.documentElement || document.body).appendChild(host);
|
||
|
||
const shadow = host.attachShadow({ mode: 'open' });
|
||
shadow.innerHTML = `
|
||
<style>
|
||
:host {
|
||
color-scheme: light dark;
|
||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||
letter-spacing: 0;
|
||
}
|
||
*, *::before, *::after { box-sizing: border-box; }
|
||
[hidden] { display: none !important; }
|
||
button, textarea { font: inherit; }
|
||
button { letter-spacing: 0; }
|
||
svg {
|
||
width: 18px;
|
||
height: 18px;
|
||
fill: none;
|
||
stroke: currentColor;
|
||
stroke-width: 1.8;
|
||
stroke-linecap: round;
|
||
stroke-linejoin: round;
|
||
flex: 0 0 auto;
|
||
}
|
||
.launcher {
|
||
pointer-events: auto;
|
||
position: fixed;
|
||
right: 24px;
|
||
bottom: 24px;
|
||
width: 48px;
|
||
height: 48px;
|
||
border: 1px solid #cbd5e1;
|
||
border-radius: 50%;
|
||
background: #ffffff;
|
||
color: #0a67d1;
|
||
box-shadow: 0 10px 28px rgba(15, 23, 42, .20);
|
||
display: grid;
|
||
place-items: center;
|
||
cursor: pointer;
|
||
}
|
||
.launcher:hover { background: #eef5ff; border-color: #8bb8ed; }
|
||
.launcher:focus-visible, .icon-button:focus-visible, .button:focus-visible {
|
||
outline: 3px solid rgba(10, 103, 209, .28);
|
||
outline-offset: 2px;
|
||
}
|
||
.launcher svg { width: 22px; height: 22px; }
|
||
.overlay {
|
||
pointer-events: auto;
|
||
position: fixed;
|
||
inset: 0;
|
||
display: grid;
|
||
place-items: center;
|
||
padding: 16px;
|
||
background: rgba(15, 23, 42, .48);
|
||
backdrop-filter: blur(3px);
|
||
}
|
||
.dialog {
|
||
width: min(560px, calc(100vw - 32px));
|
||
max-height: calc(100vh - 32px);
|
||
overflow: auto;
|
||
border: 1px solid #d8dee9;
|
||
border-radius: 8px;
|
||
background: #ffffff;
|
||
color: #172033;
|
||
box-shadow: 0 24px 70px rgba(15, 23, 42, .30);
|
||
}
|
||
.header {
|
||
display: flex;
|
||
align-items: flex-start;
|
||
justify-content: space-between;
|
||
gap: 16px;
|
||
padding: 20px 20px 16px;
|
||
border-bottom: 1px solid #e6ebf2;
|
||
}
|
||
.title-wrap { display: flex; align-items: center; gap: 11px; min-width: 0; }
|
||
.title-icon {
|
||
width: 34px;
|
||
height: 34px;
|
||
border-radius: 8px;
|
||
display: grid;
|
||
place-items: center;
|
||
color: #0a67d1;
|
||
background: #eaf3ff;
|
||
}
|
||
h2 {
|
||
margin: 0;
|
||
font-size: 17px;
|
||
line-height: 1.35;
|
||
font-weight: 650;
|
||
color: #172033;
|
||
}
|
||
.subtitle {
|
||
margin: 3px 0 0;
|
||
color: #64748b;
|
||
font-size: 12px;
|
||
line-height: 1.45;
|
||
}
|
||
.icon-button {
|
||
width: 34px;
|
||
height: 34px;
|
||
border: 1px solid transparent;
|
||
border-radius: 6px;
|
||
background: transparent;
|
||
color: #64748b;
|
||
display: grid;
|
||
place-items: center;
|
||
cursor: pointer;
|
||
flex: 0 0 auto;
|
||
}
|
||
.icon-button:hover { background: #f1f5f9; color: #172033; }
|
||
.body { padding: 18px 20px 20px; }
|
||
label {
|
||
display: block;
|
||
margin-bottom: 8px;
|
||
font-size: 13px;
|
||
font-weight: 600;
|
||
color: #334155;
|
||
}
|
||
textarea {
|
||
display: block;
|
||
width: 100%;
|
||
min-height: 178px;
|
||
resize: vertical;
|
||
border: 1px solid #cbd5e1;
|
||
border-radius: 6px;
|
||
padding: 11px 12px;
|
||
background: #fbfdff;
|
||
color: #172033;
|
||
caret-color: #0a67d1;
|
||
font-family: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
|
||
font-size: 12px;
|
||
line-height: 1.55;
|
||
overflow-wrap: anywhere;
|
||
}
|
||
textarea::placeholder { color: #94a3b8; }
|
||
textarea:focus {
|
||
outline: none;
|
||
border-color: #79aee8;
|
||
box-shadow: 0 0 0 3px rgba(10, 103, 209, .12);
|
||
background: #ffffff;
|
||
}
|
||
.status {
|
||
min-height: 24px;
|
||
margin-top: 10px;
|
||
display: flex;
|
||
align-items: flex-start;
|
||
gap: 7px;
|
||
color: #64748b;
|
||
font-size: 12px;
|
||
line-height: 1.5;
|
||
}
|
||
.status[data-type="success"] { color: #16794b; }
|
||
.status[data-type="error"] { color: #b42318; }
|
||
.status[data-type="working"] { color: #0a67d1; }
|
||
.status svg { width: 16px; height: 16px; margin-top: 1px; }
|
||
.privacy {
|
||
margin: 9px 0 0;
|
||
color: #7b8799;
|
||
font-size: 11px;
|
||
line-height: 1.5;
|
||
}
|
||
.actions {
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: space-between;
|
||
gap: 12px;
|
||
margin-top: 18px;
|
||
}
|
||
.action-group { display: flex; align-items: center; gap: 9px; }
|
||
.button {
|
||
min-height: 38px;
|
||
border: 1px solid transparent;
|
||
border-radius: 6px;
|
||
padding: 0 14px;
|
||
display: inline-flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
gap: 7px;
|
||
font-size: 13px;
|
||
font-weight: 600;
|
||
cursor: pointer;
|
||
white-space: nowrap;
|
||
}
|
||
.button:disabled { cursor: not-allowed; opacity: .55; }
|
||
.button.primary { background: #0a67d1; color: #ffffff; }
|
||
.button.primary:hover:not(:disabled) { background: #0859b4; }
|
||
.button.secondary {
|
||
border-color: #cbd5e1;
|
||
background: #ffffff;
|
||
color: #334155;
|
||
}
|
||
.button.secondary:hover:not(:disabled) { background: #f8fafc; border-color: #94a3b8; }
|
||
.button.danger {
|
||
border-color: transparent;
|
||
background: transparent;
|
||
color: #b42318;
|
||
padding-left: 9px;
|
||
padding-right: 9px;
|
||
}
|
||
.button.danger:hover:not(:disabled) { background: #fff1f0; }
|
||
.spin { animation: spin .8s linear infinite; }
|
||
.toast {
|
||
pointer-events: auto;
|
||
position: fixed;
|
||
top: 22px;
|
||
left: 50%;
|
||
transform: translateX(-50%);
|
||
width: max-content;
|
||
max-width: min(520px, calc(100vw - 32px));
|
||
border: 1px solid #cbd5e1;
|
||
border-radius: 8px;
|
||
padding: 11px 14px;
|
||
background: #ffffff;
|
||
color: #172033;
|
||
box-shadow: 0 12px 35px rgba(15, 23, 42, .22);
|
||
display: flex;
|
||
align-items: flex-start;
|
||
gap: 8px;
|
||
font-size: 13px;
|
||
line-height: 1.45;
|
||
}
|
||
.toast[data-type="success"] { border-color: #a7d8bf; color: #12633d; }
|
||
.toast[data-type="error"] { border-color: #f0b8b3; color: #9f261b; }
|
||
.toast svg { margin-top: 1px; }
|
||
@keyframes spin { to { transform: rotate(360deg); } }
|
||
@media (prefers-color-scheme: dark) {
|
||
.launcher, .dialog, .toast { background: #172033; color: #e8eef7; }
|
||
.launcher { border-color: #475569; color: #78b4ff; }
|
||
.launcher:hover { background: #22304a; border-color: #6d9fe0; }
|
||
.dialog { border-color: #3c4b63; }
|
||
.header { border-bottom-color: #2d3a50; }
|
||
.title-icon { background: #203a5d; color: #78b4ff; }
|
||
h2, label { color: #e8eef7; }
|
||
.subtitle, .status, .privacy { color: #a8b5c8; }
|
||
.icon-button { color: #a8b5c8; }
|
||
.icon-button:hover { background: #22304a; color: #ffffff; }
|
||
textarea { background: #111b2c; border-color: #475569; color: #e8eef7; }
|
||
textarea:focus { background: #0f1928; border-color: #6d9fe0; }
|
||
.button.secondary { background: #172033; border-color: #475569; color: #d8e2f0; }
|
||
.button.secondary:hover:not(:disabled) { background: #22304a; }
|
||
.button.danger:hover:not(:disabled) { background: #3a2025; }
|
||
.toast { border-color: #475569; }
|
||
}
|
||
@media (max-width: 520px) {
|
||
.launcher { right: 16px; bottom: 16px; }
|
||
.overlay { padding: 10px; }
|
||
.dialog { width: calc(100vw - 20px); max-height: calc(100vh - 20px); }
|
||
.header { padding: 17px 16px 14px; }
|
||
.body { padding: 16px; }
|
||
.actions { align-items: stretch; flex-direction: column-reverse; }
|
||
.action-group { display: grid; grid-template-columns: 1fr 1fr; }
|
||
.button.danger { grid-column: 1 / -1; }
|
||
}
|
||
@media (prefers-reduced-motion: reduce) {
|
||
.spin { animation-duration: 1.8s; }
|
||
}
|
||
</style>
|
||
|
||
<button class="launcher" type="button" title="导入微博 CK" aria-label="导入微博 CK"></button>
|
||
|
||
<div class="overlay" hidden>
|
||
<section class="dialog" role="dialog" aria-modal="true" aria-labelledby="weibo-ck-title">
|
||
<header class="header">
|
||
<div class="title-wrap">
|
||
<div class="title-icon" aria-hidden="true">${ICONS.key}</div>
|
||
<div>
|
||
<h2 id="weibo-ck-title">导入微博 CK</h2>
|
||
<p class="subtitle">写入当前浏览器的微博登录态</p>
|
||
</div>
|
||
</div>
|
||
<button class="icon-button close" type="button" title="关闭" aria-label="关闭"></button>
|
||
</header>
|
||
<div class="body">
|
||
<label for="weibo-cookie-input">Cookie</label>
|
||
<textarea id="weibo-cookie-input" spellcheck="false" autocomplete="off"
|
||
placeholder="SCF=...; SUB=...; SUBP=...; ALF=...; WBPSESS=..."></textarea>
|
||
<div class="status" role="status" aria-live="polite"></div>
|
||
<p class="privacy">Cookie 只用于当前浏览器的微博域,不会保存到脚本存储或发送到其他站点。</p>
|
||
<div class="actions">
|
||
<button class="button danger clear" type="button"></button>
|
||
<div class="action-group">
|
||
<button class="button secondary close" type="button">取消</button>
|
||
<button class="button primary import" type="button"></button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
</section>
|
||
</div>
|
||
<div class="toast" role="status" aria-live="polite" hidden></div>
|
||
`;
|
||
|
||
const overlay = shadow.querySelector('.overlay');
|
||
const dialog = shadow.querySelector('.dialog');
|
||
const launcher = shadow.querySelector('.launcher');
|
||
const textarea = shadow.querySelector('textarea');
|
||
const status = shadow.querySelector('.status');
|
||
const importButton = shadow.querySelector('.import');
|
||
const clearButton = shadow.querySelector('.clear');
|
||
const toast = shadow.querySelector('.toast');
|
||
const closeButtons = shadow.querySelectorAll('.close');
|
||
let busy = false;
|
||
let statusTimer = null;
|
||
let toastTimer = null;
|
||
|
||
launcher.innerHTML = ICONS.key;
|
||
clearButton.innerHTML = `${ICONS.trash}<span>清除登录态</span>`;
|
||
importButton.innerHTML = `${ICONS.login}<span>导入并登录</span>`;
|
||
closeButtons.forEach((button) => {
|
||
button.innerHTML = button.classList.contains('icon-button')
|
||
? ICONS.close
|
||
: '取消';
|
||
});
|
||
|
||
function setStatus(message = '', type = 'info', icon = '') {
|
||
clearTimeout(statusTimer);
|
||
status.dataset.type = type;
|
||
status.replaceChildren();
|
||
if (!message) return;
|
||
const iconName = icon || (type === 'error' ? 'alert' : type === 'success' ? 'check' : '');
|
||
if (iconName && ICONS[iconName]) {
|
||
const iconWrap = document.createElement('span');
|
||
iconWrap.innerHTML = ICONS[iconName];
|
||
status.appendChild(iconWrap.firstElementChild);
|
||
}
|
||
const text = document.createElement('span');
|
||
text.textContent = message;
|
||
status.appendChild(text);
|
||
}
|
||
|
||
function showToast(message, type = 'info', duration = 7000) {
|
||
clearTimeout(toastTimer);
|
||
toast.dataset.type = type;
|
||
toast.replaceChildren();
|
||
const iconWrap = document.createElement('span');
|
||
iconWrap.innerHTML = type === 'error' ? ICONS.alert : ICONS.check;
|
||
toast.appendChild(iconWrap.firstElementChild);
|
||
const text = document.createElement('span');
|
||
text.textContent = message;
|
||
toast.appendChild(text);
|
||
toast.hidden = false;
|
||
toastTimer = setTimeout(() => {
|
||
toast.hidden = true;
|
||
}, duration);
|
||
}
|
||
|
||
function openPanel() {
|
||
if (!overlay.hidden) {
|
||
textarea.focus();
|
||
return;
|
||
}
|
||
overlay.hidden = false;
|
||
setStatus('');
|
||
requestAnimationFrame(() => textarea.focus());
|
||
}
|
||
|
||
function closePanel(force = false) {
|
||
if (busy && !force) return;
|
||
overlay.hidden = true;
|
||
textarea.value = '';
|
||
setStatus('');
|
||
}
|
||
|
||
function setBusy(nextBusy) {
|
||
busy = nextBusy;
|
||
importButton.disabled = nextBusy;
|
||
clearButton.disabled = nextBusy;
|
||
textarea.disabled = nextBusy;
|
||
closeButtons.forEach((button) => {
|
||
button.disabled = nextBusy;
|
||
});
|
||
}
|
||
|
||
function validateInput(showEmpty = false) {
|
||
const raw = textarea.value;
|
||
if (!raw.trim()) {
|
||
importButton.disabled = busy;
|
||
if (showEmpty) setStatus('请先粘贴微博 Cookie', 'error');
|
||
else setStatus('');
|
||
return null;
|
||
}
|
||
try {
|
||
const entries = parseCookieText(raw);
|
||
importButton.disabled = busy;
|
||
setStatus(`已识别 ${entries.length} 个 Cookie`, 'info');
|
||
return entries;
|
||
} catch (error) {
|
||
importButton.disabled = true;
|
||
if (showEmpty) setStatus(error.message, 'error');
|
||
else setStatus('');
|
||
return null;
|
||
}
|
||
}
|
||
|
||
async function importAndLogin() {
|
||
if (busy) return;
|
||
let entries = null;
|
||
try {
|
||
entries = parseCookieText(textarea.value);
|
||
} catch (error) {
|
||
setStatus(error.message, 'error');
|
||
return;
|
||
}
|
||
|
||
setBusy(true);
|
||
setStatus(`正在写入 ${entries.length} 个 Cookie...`, 'working', 'spinner');
|
||
try {
|
||
const result = await writeCookies(entries);
|
||
textarea.value = '';
|
||
const mode = result.modes.includes('GM_cookie') ? 'GM_cookie' : '页面 Cookie';
|
||
if (result.failures.length) {
|
||
const names = result.failures.slice(0, 4).map((item) => item.name).join('、');
|
||
setStatus(
|
||
`已写入 ${result.written.length} 个,${result.failures.length} 个失败:${names}`,
|
||
'error',
|
||
);
|
||
} else {
|
||
setStatus(`已通过 ${mode} 写入 ${result.written.length} 个 Cookie`, 'success');
|
||
}
|
||
setVerifyMarker();
|
||
statusTimer = setTimeout(navigateToWeiboHome, 550);
|
||
} catch (error) {
|
||
setStatus(error.message, 'error');
|
||
} finally {
|
||
setBusy(false);
|
||
}
|
||
}
|
||
|
||
async function clearLogin() {
|
||
if (busy) return;
|
||
setBusy(true);
|
||
setStatus('正在清除微博登录 Cookie...', 'working', 'spinner');
|
||
try {
|
||
const removed = await clearWeiboCookies();
|
||
if (removed) {
|
||
setStatus('已清除微博网页登录态', 'success');
|
||
statusTimer = setTimeout(() => location.reload(), 500);
|
||
}
|
||
} catch (error) {
|
||
setStatus(`清除失败:${error.message}`, 'error');
|
||
} finally {
|
||
setBusy(false);
|
||
}
|
||
}
|
||
|
||
let inputTimer = null;
|
||
textarea.addEventListener('input', () => {
|
||
clearTimeout(inputTimer);
|
||
inputTimer = setTimeout(() => validateInput(false), 180);
|
||
});
|
||
textarea.addEventListener('keydown', (event) => {
|
||
event.stopPropagation();
|
||
if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') {
|
||
event.preventDefault();
|
||
importAndLogin();
|
||
}
|
||
if (event.key === 'Escape') closePanel();
|
||
});
|
||
overlay.addEventListener('click', (event) => {
|
||
if (event.target === overlay) closePanel();
|
||
});
|
||
dialog.addEventListener('click', (event) => event.stopPropagation());
|
||
launcher.addEventListener('click', openPanel);
|
||
importButton.addEventListener('click', importAndLogin);
|
||
clearButton.addEventListener('click', clearLogin);
|
||
closeButtons.forEach((button) => button.addEventListener('click', () => closePanel()));
|
||
document.addEventListener('keydown', (event) => {
|
||
if (event.key === 'Escape' && !overlay.hidden) closePanel();
|
||
});
|
||
|
||
if (typeof GM_registerMenuCommand === 'function') {
|
||
GM_registerMenuCommand('导入微博 CK', openPanel);
|
||
GM_registerMenuCommand('清除微博网页登录态', clearLogin);
|
||
}
|
||
|
||
async function verifyPendingLogin() {
|
||
if (location.hostname !== 'weibo.com') return;
|
||
const marker = readVerifyMarker();
|
||
if (!marker) return;
|
||
clearVerifyMarker();
|
||
if (Date.now() - marker > VERIFY_WINDOW_MS) return;
|
||
await new Promise((resolve) => setTimeout(resolve, 450));
|
||
try {
|
||
const uid = await readCurrentUid();
|
||
showToast(`微博登录成功,UID ${uid}`, 'success', 10000);
|
||
} catch (error) {
|
||
showToast(`Cookie 未生效或已过期:${error.message}`, 'error', 12000);
|
||
}
|
||
}
|
||
|
||
verifyPendingLogin();
|
||
}
|
||
|
||
if (typeof module !== 'undefined' && module.exports) {
|
||
module.exports = {
|
||
parseCookieText,
|
||
cookieExpiration,
|
||
planCookieWrite,
|
||
planCookieWrites,
|
||
writeCookies,
|
||
};
|
||
} else if (typeof document !== 'undefined') {
|
||
if (document.readyState === 'loading') {
|
||
document.addEventListener('DOMContentLoaded', init, { once: true });
|
||
} else {
|
||
init();
|
||
}
|
||
}
|
||
})();
|