refactor(douyu): 统一腾讯角色绑定协议与状态判断

This commit is contained in:
yml
2026-11-18 10:59:20 +08:00
parent 9958e4ab7d
commit 8a58f2857d
14 changed files with 1681 additions and 215 deletions
+173 -59
View File
@@ -32,7 +32,7 @@
from __future__ import annotations
from datetime import UTC, datetime
from datetime import UTC, datetime, timedelta
from typing import Any
from ..models import Account
@@ -190,85 +190,199 @@ def bind_payload(account: Account) -> dict[str, str]:
def derive_from_bind_info(info: dict | None) -> str | None:
"""从斗鱼 `bind_info` 的返回推导绑定状态;**推导不出来时返回 None**。
"""从斗鱼腾讯绑定信息推导唯一业务状态。
返回 None 表示「这次查询没能得出可靠结论」—— 调用方应当**保持原值或写
unknown**,绝不要把它当成 `unbound`。"没查到"和"没绑定"必须分开。
最新抓包证明 `bindRole` 与 `bindAct` 不是同一阶段:
判定依据(字段含义见 `core/douyu/activity_client.py:_parse_bind_info`):
- 扫码选中角色后:`bindRole=1, bindAct=0`,此时应为 `pending`;
- 调用 `actBind` 后:`bindAct=1`,此时才是 `bound`;
- 两个标志都是 0:明确未绑定。
- `is_bound_role` 为真 → **bound**(已经绑了角色)
- `is_bound_role` 为假 → **unbound**(接口明确说了没绑)
- 缺失(接口没给 / 解析失败)→ **None**(推不出来,别猜)
⚠️ **只看 `is_bound_role`,不掺 `is_bound_act`。**
这一列问的是「**角色**绑没绑」,而**「活动是否开通/参与」和「是否绑定角色」
是两件独立的事**(用户明确指出的领域事实)。生产实测也印证了:
电竞 opened=False 且 bind=bound → 187 个账号
也就是说这 187 个账号**绑了角色、但手册压根没开通**。
曾经用 `is_bound_act` 做兜底("避免漏掉已绑但没回角色名的"),
那是把"活动维度"当成了"角色维度" —— 一旦有账号 `is_bound_act=True`
而角色未绑,就会报出"角色已绑定"的**错结论**。实测没触发过,
但语义是错的,所以去掉。(当时那些判为 bound 的账号 100% 都有角色名,
证明 `is_bound_role` 本身就够用。)
⚠️ 这里刻意**不产出 pending**:`pending` 描述的是"正在绑定/待确认"这种
**进行中的动作**(例如刚生成过绑定二维码),那是一次查询的**副作用**,
不是查询能观测到的状态。硬用查询结果去推 pending 就是编造。
兼容旧接口:如果响应里完全没有 `is_bound_act`,才回退到
`is_bound_role` 判断。新接口始终会带上 `is_bound_act`。
"""
if not isinstance(info, dict):
return None
def flag(key: str) -> bool | None:
value = info.get(key)
if value is None:
return None
if isinstance(value, bool):
return value
text = str(value).strip().lower()
if text in {"1", "true", "yes", "y"}:
return True
if text in {"0", "false", "no", "n", ""}:
return False
return None
bound_role = flag("is_bound_role")
bound_act = _explicit_flag(info.get("is_bound_act"))
bound_role = _explicit_flag(info.get("is_bound_role"))
role_name = _binding_role_name(info)
if bound_act is True:
return BIND_BOUND
if bound_act is False:
if bound_role is True or bool(role_name):
return BIND_PENDING
return BIND_UNBOUND
# 旧接口没有 is_bound_act,保留原行为。
if bound_role is True:
return BIND_BOUND
if bound_role is False:
return BIND_UNBOUND
# 接口没给结论:保持 unknown,别把"没查到"写成"没绑定"
return None
def is_role_change_cooling(info: dict | None) -> bool:
"""是否处于真实换绑冷却:已有绑定角色且当前不可换绑。"""
def is_confirmed_binding(info: dict | None) -> bool:
"""是否已经完成最终绑定。
新接口以 `bindAct=1` 为准;旧接口缺少该字段时才回退到 `bindRole`。
"""
if not isinstance(info, dict):
return False
role_name = str(info.get("role_name") or info.get("role") or "").strip()
if not role_name or not _truthy_flag(info.get("is_bound_act")):
return False
if str(info.get("api_version") or "") == "esports":
can_change_time = _to_int(info.get("can_change_time"))
if can_change_time is not None:
return can_change_time > int(datetime.now(UTC).timestamp())
bound_act = _explicit_flag(info.get("is_bound_act"))
if bound_act is not None:
return bound_act
return _explicit_flag(info.get("is_bound_role")) is True
def is_bound_act(info: dict | None) -> bool:
"""接口原始 `bindAct` 标志,仅供绑定状态机和候选筛选使用。"""
return isinstance(info, dict) and _explicit_flag(info.get("is_bound_act")) is True
def can_change_role(info: dict | None, *, now: datetime | None = None) -> bool:
"""是否允许换绑。未绑定状态永远不受接口倒计时影响。"""
if not is_confirmed_binding(info):
return True
assert isinstance(info, dict)
moment = now or datetime.now(UTC)
can_change_time = _to_int(info.get("can_change_time"))
if can_change_time is not None and can_change_time > 0:
return can_change_time <= int(moment.timestamp())
wait_time = _to_int(info.get("change_role_wait_time"))
if wait_time is not None and wait_time > 0:
return False
raw_can_change = _explicit_flag(info.get("can_change_role"))
if raw_can_change is not None:
return raw_can_change
return True
def is_role_change_cooling(
info: dict | None,
*,
now: datetime | None = None,
) -> bool:
"""是否处于真实换绑冷却:最终绑定已完成且当前不可换绑。"""
return is_confirmed_binding(info) and not can_change_role(info, now=now)
def role_change_available_at(
info: dict | None,
*,
checked_at: datetime | None = None,
) -> datetime | None:
"""统一的换绑可用时间;未确认绑定或没有冷却时返回 None。"""
if not is_role_change_cooling(info, now=checked_at):
return None
assert isinstance(info, dict)
moment = checked_at or datetime.now(UTC)
can_change_time = _to_int(info.get("can_change_time"))
if can_change_time is not None and can_change_time > 0:
return datetime.fromtimestamp(can_change_time, tz=UTC)
wait_time = _to_int(info.get("change_role_wait_time"))
if wait_time is not None and wait_time > 0:
return moment + timedelta(seconds=wait_time)
return None
def is_pending_binding_role(
info: dict | None,
*,
baseline_role_name: str = "",
baseline_is_bound_act: bool = False,
) -> bool:
"""是否出现了可确认的扫码角色。"""
if not isinstance(info, dict):
return False
snapshot = binding_snapshot(info)
role_name = snapshot["role_name"]
if not role_name:
return False
if snapshot["is_bound_act"]:
return bool(baseline_role_name) and role_name != baseline_role_name
if snapshot["need_bind_act"] or snapshot["need_bind_role"]:
if not baseline_role_name:
return True
return role_name != baseline_role_name or baseline_is_bound_act
if not baseline_role_name:
return True
if info.get("can_change_role") is not None:
return not _truthy_flag(info.get("can_change_role"))
return False
if role_name != baseline_role_name:
return True
return baseline_is_bound_act
def binding_channel(info: dict | None) -> str:
"""统一游戏渠道展示:区服 / 平台。"""
if not isinstance(info, dict):
return ""
return " / ".join(
part
for part in (
str(info.get("area_name") or "").strip(),
str(info.get("plat_name") or "").strip(),
)
if part
)
def binding_snapshot(info: dict | None) -> dict[str, Any]:
"""斗鱼腾讯绑定的唯一业务快照,供执行器、账号刷新和概览复用。"""
data = info if isinstance(info, dict) else {}
role_name = _binding_role_name(data)
bound_status = derive_from_bind_info(data)
phase = {
BIND_BOUND: "confirmed",
BIND_PENDING: "role_ready",
BIND_UNBOUND: "unbound",
}.get(bound_status or "", "unknown")
bound_act = _explicit_flag(data.get("is_bound_act")) is True
return {
"role_name": role_name,
"area_name": str(data.get("area_name") or "").strip(),
"plat_name": str(data.get("plat_name") or "").strip(),
"partition_name": str(data.get("partition_name") or "").strip(),
"game_channel": binding_channel(data),
"nickname": str(data.get("nickname") or "").strip(),
"account_type": str(data.get("account_type") or "").strip(),
"account_avatar": str(data.get("account_avatar") or "").strip(),
"is_bound_account": _truthy_flag(data.get("is_bound_account")),
"is_bound_role": _truthy_flag(data.get("is_bound_role")),
"is_bound_act": bound_act,
"need_bind_act": _truthy_flag(data.get("need_bind_act")),
"need_bind_role": _truthy_flag(data.get("need_bind_role")),
"change_role_wait_time": _to_int(data.get("change_role_wait_time")),
"can_change_time": _to_int(data.get("can_change_time")),
"can_change_role": can_change_role(data),
"is_change_cooling": is_role_change_cooling(data),
"bind_status": bound_status,
"bind_phase": phase,
"bind_confirmed": bound_status == BIND_BOUND,
"bind_ready_for_confirm": bound_status == BIND_PENDING and bool(role_name),
"game_id": str(data.get("game_id") or "").strip(),
"game_name": str(data.get("game_name") or "").strip(),
"tx_act_id": _to_int(data.get("tx_act_id")) or 0,
"bind_info": data,
}
def _binding_role_name(info: dict) -> str:
return str(info.get("role_name") or info.get("role") or "").strip()
def _explicit_flag(value: Any) -> bool | None:
if value is None or value == "":
return None
if isinstance(value, bool):
return value
text = str(value).strip().lower()
if text in {"1", "true", "yes", "y"}:
return True
if text in {"0", "false", "no", "n", ""}:
return False
return None
def _truthy_flag(value: Any) -> bool:
if value is True:
return True
if value is False or value is None:
return False
return str(value).strip().lower() in {"1", "true", "yes", "y"}
return _explicit_flag(value) is True
def _to_int(value: Any) -> int | None:
+10 -19
View File
@@ -9,7 +9,7 @@ from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from datetime import UTC, datetime
from typing import Any
from sqlalchemy.orm import Session
@@ -19,8 +19,9 @@ from core.douyu import DouyuActivityClient
from ..models import Account
from .account_binding import (
SCOPE_ELITE,
derive_from_bind_info,
binding_snapshot,
is_role_change_cooling,
role_change_available_at,
set_bind_status,
)
from .account_lifecycle import on_ck_verdict
@@ -235,30 +236,20 @@ def _apply_bind_state(
*,
checked_at: datetime,
) -> datetime | None:
derived = derive_from_bind_info(bind_info)
snapshot = binding_snapshot(bind_info)
derived = snapshot["bind_status"]
if derived is not None:
set_bind_status(account, SCOPE_ELITE, derived)
role_name = str(bind_info.get("role_name") or bind_info.get("role") or "").strip()
role_name = snapshot["role_name"]
if role_name:
account.game_name = role_name[:128]
area_name = str(bind_info.get("area_name") or "").strip()
plat_name = str(bind_info.get("plat_name") or "").strip()
channel = " · ".join(item for item in (area_name, plat_name) if item)
channel = snapshot["game_channel"]
if channel:
account.game_channel = channel[:128]
account.game_channel = channel.replace(" / ", " · ")[:128]
wait_seconds = _to_int(bind_info.get("change_role_wait_time"))
can_change_time = _to_int(bind_info.get("can_change_time"))
account.change_role_wait_time = wait_seconds
if not is_role_change_cooling(bind_info):
available_at = None
elif can_change_time is not None and can_change_time > 0:
available_at = datetime.fromtimestamp(can_change_time, tz=UTC)
elif wait_seconds is not None and wait_seconds > 0:
available_at = checked_at + timedelta(seconds=wait_seconds)
else:
available_at = account.role_change_available_at
account.change_role_wait_time = snapshot["change_role_wait_time"]
available_at = role_change_available_at(bind_info, checked_at=checked_at)
account.role_change_available_at = available_at
return available_at
@@ -15,6 +15,7 @@ from typing import Any
from core.douyu import DouyuActivityClient
from core.douyu.cookie_utils import cookie_value
from .account_binding import binding_snapshot
from .douyu_goods_service import serialize_goods
ERROR_MAX_LENGTH = 240
@@ -275,6 +276,7 @@ def query_account_overview(
return {
"elite": elite,
"bind": bind,
"bind_snapshot": binding_snapshot(bind),
"gold": gold,
"goods": goods,
"serialized_goods": [serialize_goods(item) for item in goods],
+8 -5
View File
@@ -297,6 +297,7 @@ def _probe_with_client(
)
elite = overview["elite"]
bind = overview["bind"]
bind_snapshot = overview["bind_snapshot"]
gold = overview["gold"]
goods = overview["serialized_goods"]
error_labels = {
@@ -315,13 +316,13 @@ def _probe_with_client(
expire_time = _to_int(elite.get("expire_time"))
user_info = elite.get("user_info") or {}
profile = DouyuActivityClient.profile_from_cookie(str(account.cookie or ""))
bind_role = _text(bind.get("role_name"), max_length=128)
area_name = _text(bind.get("area_name"), max_length=64)
plat_name = _text(bind.get("plat_name"), max_length=64)
bind_role = _text(bind_snapshot["role_name"], max_length=128)
area_name = _text(bind_snapshot["area_name"], max_length=64)
plat_name = _text(bind_snapshot["plat_name"], max_length=64)
bind_channel = " · ".join(item for item in (area_name, plat_name) if item)
bind_account = _text(bind.get("nickname"), max_length=128)
bind_account = _text(bind_snapshot["nickname"], max_length=128)
ck_status = CK_VALID if (elite or bind) else CK_INVALID
ok = bool(bind_role) and not (elite == {} and bind == {})
ok = bool(bind_snapshot["bind_confirmed"]) and not (elite == {} and bind == {})
return {
"found": True,
@@ -340,6 +341,8 @@ def _probe_with_client(
"manual_score": manual_score,
"expire_time": expire_time,
"manual_opened": bool(manual_type is not None and manual_type >= 1),
"bind_status": bind_snapshot["bind_status"],
"bind_phase": bind_snapshot["bind_phase"],
"bind_game_account": bind_account,
"bind_game_role": bind_role,
"bind_game_channel": bind_channel,
+24 -88
View File
@@ -17,7 +17,11 @@ from .account_binding import (
BIND_UNBOUND,
SCOPE_ELITE,
SCOPE_ESPORTS,
binding_snapshot,
is_bound_act,
is_pending_binding_role,
is_role_change_cooling,
role_change_available_at,
set_bind_status,
)
from .business_events import record_bind
@@ -106,45 +110,9 @@ class BindMixin:
aliases.append(alias)
return aliases
@staticmethod
def _role_channel(bind_info: dict) -> str:
return " / ".join(
part
for part in [bind_info.get("area_name"), bind_info.get("plat_name")]
if part
)
@staticmethod
def _is_truthy_flag(value) -> bool:
if value is True:
return True
if value is False or value is None:
return False
text = str(value).strip().lower()
return text in {"1", "true", "yes", "y"}
@classmethod
def _is_bound_act(cls, bind_info: dict | None) -> bool:
if not bind_info:
return False
return cls._is_truthy_flag(bind_info.get("is_bound_act"))
@classmethod
def _can_change_role(cls, bind_info: dict | None) -> bool:
"""综合 can_change_role 与换绑倒计时判断是否允许换绑。"""
if not bind_info:
return True
if str(bind_info.get("api_version") or "") == "esports":
can_change_time = cls._to_int(bind_info.get("can_change_time"))
if can_change_time is not None:
return can_change_time <= int(datetime.now(UTC).timestamp())
wait_time = cls._to_int(bind_info.get("change_role_wait_time"))
if wait_time is not None and wait_time > 0:
return False
if bind_info.get("can_change_role") is not None:
return cls._is_truthy_flag(bind_info.get("can_change_role"))
# 已绑定但接口没给倒计时/开关时,默认允许(避免误杀首次绑定)
return True
return is_bound_act(bind_info)
@classmethod
def _is_change_cooling(cls, bind_info: dict | None) -> bool:
@@ -168,47 +136,14 @@ class BindMixin:
4. need_bind_act / need_bind_role 且角色相对 baseline 有变化,算 pending
5. 无 baseline 且未绑定但有角色,视为待确认残留
"""
if not bind_info:
return False
role_name = str(bind_info.get("role_name") or "").strip()
if not role_name:
return False
is_bound_act = cls._is_bound_act(bind_info)
need_bind_act = cls._is_truthy_flag(bind_info.get("need_bind_act"))
need_bind_role = cls._is_truthy_flag(bind_info.get("need_bind_role"))
role_changed = bool(baseline_role_name) and role_name != baseline_role_name
if is_bound_act:
# 已绑定:仅当相对 baseline 角色发生变化时才视为新扫码结果
return role_changed
if need_bind_act or need_bind_role:
if not baseline_role_name:
return True
return role_changed or baseline_is_bound_act
if not baseline_role_name:
return True
if role_changed:
return True
# 同一角色从已绑定变为未绑定
return baseline_is_bound_act
return is_pending_binding_role(
bind_info,
baseline_role_name=baseline_role_name,
baseline_is_bound_act=baseline_is_bound_act,
)
def _bind_snapshot(self, bind_info: dict | None) -> dict:
info = bind_info or {}
role_name = str(info.get("role_name") or "")
return {
"role_name": role_name,
"area_name": info.get("area_name") or "",
"plat_name": info.get("plat_name") or "",
"nickname": info.get("nickname") or "",
"is_bound_act": self._is_bound_act(info),
"is_bound_role": self._is_truthy_flag(info.get("is_bound_role")),
"is_bound_account": self._is_truthy_flag(info.get("is_bound_account")),
"need_bind_act": self._is_truthy_flag(info.get("need_bind_act")),
"need_bind_role": self._is_truthy_flag(info.get("need_bind_role")),
"change_role_wait_time": self._to_int(info.get("change_role_wait_time")),
"can_change_time": self._to_int(info.get("can_change_time")),
"can_change_role": self._can_change_role(info),
"bind_info": info,
}
return binding_snapshot(bind_info)
def _format_bind_summary(
self, bind_info: dict | None, *, pending: bool | None = None
@@ -241,12 +176,14 @@ class BindMixin:
(`query_game_name` 等)就该这样:它们**没有资格**改变绑定状态。
传值时只能是 `account_binding` 的四个枚举。
"""
role_name = str(bind_info.get("role_name") or "")
snapshot = binding_snapshot(bind_info)
role_name = snapshot["role_name"]
account.game_name = role_name or account.game_name
account.game_channel = self._role_channel(bind_info) or account.game_channel
account.change_role_wait_time = self._to_int(
bind_info.get("change_role_wait_time")
account.game_channel = (
snapshot["game_channel"].replace(" / ", " · ") or account.game_channel
)
account.change_role_wait_time = snapshot["change_role_wait_time"]
account.role_change_available_at = role_change_available_at(bind_info)
if state is not None:
set_bind_status(account, SCOPE_ELITE, state)
account.updated_at = datetime.now(UTC)
@@ -255,15 +192,15 @@ class BindMixin:
self, account: Account, bind_info: dict, state: str | None = None
) -> None:
"""将电竞手册角色状态写入专属字段,避免覆盖精英宝典数据。"""
role_name = str(bind_info.get("role_name") or "")
snapshot = binding_snapshot(bind_info)
role_name = snapshot["role_name"]
account.esports_game_name = role_name or account.esports_game_name
account.esports_game_channel = (
self._role_channel(bind_info) or account.esports_game_channel
snapshot["game_channel"].replace(" / ", " · ")
or account.esports_game_channel
)
account.esports_change_role_wait_time = self._to_int(
bind_info.get("change_role_wait_time")
)
account.esports_can_change_time = self._to_int(bind_info.get("can_change_time"))
account.esports_change_role_wait_time = snapshot["change_role_wait_time"]
account.esports_can_change_time = snapshot["can_change_time"]
if state is not None:
set_bind_status(account, SCOPE_ESPORTS, state)
account.updated_at = datetime.now(UTC)
@@ -278,12 +215,11 @@ class BindMixin:
activity_snapshot = self._bind_snapshot(activity_info)
esports_bound = activity_snapshot["is_bound_act"]
has_selected_role = bool(activity_snapshot["role_name"])
tx_act = activity_info.get("tx_act") or {}
return {
**activity_snapshot,
"is_bound_role": has_selected_role,
"act_alias": act_alias,
"game_id": tx_act.get("gameId") or "",
"game_id": activity_snapshot["game_id"],
"esports_bound": esports_bound,
"has_selected_role": has_selected_role,
"bind_ready_for_confirm": has_selected_role and not esports_bound,
+16 -10
View File
@@ -33,7 +33,7 @@ from sqlalchemy.orm import Session
from core.douyu import DouyuActivityClient
from ..models import Account, DouyuTask
from .account_binding import derive_from_bind_info, set_bind_status
from .account_binding import binding_snapshot, set_bind_status
from .business_events import record_official_exchange
from .douyu_activity_query import (
query_activity_goods,
@@ -367,8 +367,8 @@ class OverviewMixin:
#
# 这三个值以前**从来没人查过** —— 只是 S6 迁移时从旧的垃圾场列
# `bind_status` 能推的推、推不出的留 `unknown`,于是界面上 97% 显示"未知"。
# 实测校准:开发库 4 个账号里 3 个其实**已绑定**(`is_bound_role=True` 且有角色名),
# 全被 unknown 盖住了。
# 实测校准:最终绑定以 `bindAct=1` 为准;只识别到 `bindRole=1`
# 但尚未 actBind 的账号必须保持 pending。
# 和平小店总开关:关着时**完全跳过**它的所有请求。
# 小店目前是关闭状态,不跳过的话每个账号都会产生一条
# "Livelink登录态校验失败"(实测 200 个里失败 195 次,100%),
@@ -394,17 +394,23 @@ class OverviewMixin:
continue
try:
info = self._fetch_bind_info(client, scope, alias)
derived = derive_from_bind_info(info)
snapshot = binding_snapshot(info)
derived = snapshot["bind_status"]
# 把**明细**也带上:运营要看的是"绑的哪个角色、哪个区服、
# 什么时候能换绑",不是一个"已绑定"就完事。
overview["bind"][scope] = {
"derived": derived,
"role_name": str(info.get("role_name") or info.get("role") or ""),
"area_name": str(info.get("area_name") or ""),
"plat_name": str(info.get("plat_name") or ""),
"nickname": str(info.get("nickname") or ""),
"change_role_wait_time": _ts(info.get("change_role_wait_time")),
"can_change_time": _ts(info.get("can_change_time")),
"phase": snapshot["bind_phase"],
"role_name": snapshot["role_name"],
"area_name": snapshot["area_name"],
"plat_name": snapshot["plat_name"],
"nickname": snapshot["nickname"],
"game_id": snapshot["game_id"],
"game_name": snapshot["game_name"],
"is_change_cooling": snapshot["is_change_cooling"],
"can_change_role": snapshot["can_change_role"],
"change_role_wait_time": _ts(snapshot["change_role_wait_time"]),
"can_change_time": _ts(snapshot["can_change_time"]),
}
if derived is not None:
# 唯一写入者;推不出来(None)时**不动原值** —— 宁可留 unknown,
+144
View File
@@ -0,0 +1,144 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const {
parseCookieText,
cookieExpiration,
planCookieWrite,
writeCookies,
} = require('./weibo-cookie-login.user.js');
test('解析 Cookie 请求头、Set-Cookie 属性与重复字段', () => {
const entries = parseCookieText(`
Cookie: SCF=fake-scf; SUB=fake-sub==; SUBP=fake-subp
Path=/
Domain=.weibo.com
WBPSESS=fake-session; HttpOnly; Secure; SameSite=None
SUB=fake-sub-last
`);
const values = new Map(entries);
assert.equal(values.get('SCF'), 'fake-scf');
assert.equal(values.get('SUB'), 'fake-sub-last');
assert.equal(values.get('SUBP'), 'fake-subp');
assert.equal(values.get('WBPSESS'), 'fake-session');
assert.equal(values.has('Path'), false);
assert.equal(values.has('Domain'), false);
assert.equal(values.has('HttpOnly'), false);
});
test('拒绝空输入、无登录字段和非法 Cookie 名称', () => {
assert.throws(() => parseCookieText(''), /请先粘贴/);
assert.throws(() => parseCookieText('foo=bar'), /未找到微博登录 Cookie/);
assert.throws(() => parseCookieText('SUB=x; bad name=x'), /名称格式错误/);
});
test('按微博真实域属性规划 Cookie', () => {
const now = 1_800_000_000;
const sub = planCookieWrite('SUB', 'fake-sub', now);
const session = planCookieWrite('WBPSESS', 'fake-session', now);
const passportToken = planCookieWrite('X-CSRF-TOKEN', 'fake-token', now);
assert.equal(sub.domain, '.weibo.com');
assert.equal(sub.url, 'https://weibo.com/');
assert.equal(sub.httpOnly, true);
assert.equal(sub.sameSite, 'no_restriction');
assert.equal('domain' in session, false);
assert.equal(session.httpOnly, true);
assert.equal(session.expirationDate, now + 86400);
assert.equal(passportToken.url, 'https://passport.weibo.com/');
assert.equal('domain' in passportToken, false);
assert.equal(passportToken.httpOnly, false);
});
test('Cookie 有效期按微博用途区分', () => {
const now = 1_800_000_000;
assert.equal(cookieExpiration('WBPSESS', now), now + 86400);
assert.equal(cookieExpiration('ALF', now), now + 30 * 86400);
assert.equal(cookieExpiration('SUB', now), now + 365 * 86400);
assert.equal(cookieExpiration('XSRF-TOKEN', now), now + 365 * 86400);
});
test('优先使用 GM_cookie 写入完整 Cookie 属性', async () => {
const calls = [];
globalThis.GM_cookie = {
set(details, callback) {
calls.push(details);
callback();
},
};
try {
const result = await writeCookies([
['SUB', 'fake-sub'],
['WBPSESS', 'fake-session'],
]);
assert.deepEqual(result.written, ['SUB', 'WBPSESS']);
assert.deepEqual(result.failures, []);
assert.deepEqual(result.modes, ['GM_cookie']);
assert.equal(calls.length, 2);
assert.equal(calls[0].domain, '.weibo.com');
assert.equal(calls[0].httpOnly, true);
assert.equal('domain' in calls[1], false);
assert.equal(calls[1].httpOnly, true);
} finally {
delete globalThis.GM_cookie;
}
});
test('稳定版拒绝 HttpOnly 时自动降级重试', async () => {
const calls = [];
globalThis.GM_cookie = {
set(details, callback) {
calls.push(details);
callback(details.httpOnly ? 'HttpOnly is not supported' : undefined);
},
};
try {
const result = await writeCookies([['SUB', 'fake-sub']]);
assert.deepEqual(result.written, ['SUB']);
assert.deepEqual(result.failures, []);
assert.equal(calls.length, 2);
assert.equal(calls[0].httpOnly, true);
assert.equal(calls[1].httpOnly, false);
} finally {
delete globalThis.GM_cookie;
}
});
test('兼容脚本猫 GM_cookie 的 (result, error) 回调', async () => {
globalThis.GM_cookie = {
set(details, callback) {
callback(undefined, details.httpOnly ? 'HttpOnly rejected' : undefined);
},
};
try {
const result = await writeCookies([['SUB', 'fake-sub']]);
assert.deepEqual(result.written, ['SUB']);
assert.deepEqual(result.failures, []);
assert.deepEqual(result.modes, ['GM_cookie']);
} finally {
delete globalThis.GM_cookie;
}
});
test('脚本猫 GM_cookie 返回真实错误时不会误判成功', async () => {
globalThis.GM_cookie = {
set(details, callback) {
callback(undefined, new Error('permission denied'));
},
};
try {
await assert.rejects(
writeCookies([['SUB', 'fake-sub']]),
/GM_cookie 与页面 Cookie 均写入失败/,
);
} finally {
delete globalThis.GM_cookie;
}
});
+958
View File
@@ -0,0 +1,958 @@
// ==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();
}
}
})();