external_risk_rules.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. from __future__ import annotations
  2. import hashlib
  3. import re
  4. import unicodedata
  5. from datetime import UTC, datetime
  6. from secrets import token_hex
  7. from typing import Any
  8. from urllib.parse import urlsplit
  9. from aiohttp import ClientSession, ClientTimeout
  10. from pymongo import ASCENDING
  11. from wbb import BOT_PROFILE_ID, db, log
  12. SOURCES = {
  13. "yt_spam_domains": {
  14. "name": "YT-Spam-Lists 域名",
  15. "url": "https://raw.githubusercontent.com/ThioJoe/YT-Spam-Lists/main/SpamDomainsList.txt",
  16. "repository": "https://github.com/ThioJoe/YT-Spam-Lists",
  17. "license": "MIT",
  18. "kind": "domain",
  19. "max_bytes": 1_000_000,
  20. },
  21. "phishing_domains": {
  22. "name": "Phishing.Database 活跃域名",
  23. "url": "https://raw.githubusercontent.com/Phishing-Database/Phishing.Database/master/phishing-domains-ACTIVE.txt",
  24. "repository": "https://github.com/Phishing-Database/Phishing.Database",
  25. "license": "MIT",
  26. "kind": "domain",
  27. "max_bytes": 20_000_000,
  28. },
  29. "zapper_phrases": {
  30. "name": "zapper-TGAB 短语候选",
  31. "url": "https://raw.githubusercontent.com/RGB-Outl4w/zapper-TGAB/master/spam_phrases.txt",
  32. "repository": "https://github.com/RGB-Outl4w/zapper-TGAB",
  33. "license": "MIT",
  34. "kind": "phrase",
  35. "max_bytes": 100_000,
  36. },
  37. }
  38. snapshotsdb = db.external_risk_snapshots
  39. entriesdb = db.external_risk_entries
  40. statesdb = db.external_risk_sources
  41. policiesdb = db.external_risk_chat_policies
  42. eventsdb = db.external_risk_events
  43. DOMAIN_RE = re.compile(r"^(?:[a-z0-9-]{1,63}\.)+[a-z0-9-]{2,63}$")
  44. LINK_RE = re.compile(r"(?:(?:https?://|www\.)[^\s<>]+)", re.IGNORECASE)
  45. _indexes_ready = False
  46. async def ensure_indexes() -> None:
  47. global _indexes_ready
  48. if _indexes_ready:
  49. return
  50. await snapshotsdb.create_index([("snapshot_id", ASCENDING)], unique=True)
  51. await snapshotsdb.create_index([("bot_id", ASCENDING), ("source_id", ASCENDING), ("created_at", -1)])
  52. await entriesdb.create_index([("snapshot_id", ASCENDING), ("value", ASCENDING)], unique=True)
  53. await statesdb.create_index([("bot_id", ASCENDING), ("source_id", ASCENDING)], unique=True)
  54. await policiesdb.create_index([("bot_id", ASCENDING), ("chat_id", ASCENDING)], unique=True)
  55. await eventsdb.create_index([("bot_id", ASCENDING), ("chat_id", ASCENDING), ("created_at", -1)])
  56. _indexes_ready = True
  57. def normalize_domain(raw: str) -> str | None:
  58. value = raw.strip().lower().lstrip("*.").rstrip(".")
  59. if value.startswith(("http://", "https://")):
  60. value = urlsplit(value).hostname or ""
  61. value = value.split("/")[0].split(":")[0]
  62. try:
  63. value = value.encode("idna").decode("ascii")
  64. except UnicodeError:
  65. return None
  66. if not DOMAIN_RE.fullmatch(value) or ".." in value:
  67. return None
  68. return value
  69. def parse_entries(source_id: str, content: bytes) -> list[str]:
  70. source = SOURCES[source_id]
  71. values: set[str] = set()
  72. for line in content.decode("utf-8-sig", errors="replace").splitlines():
  73. line = line.strip()
  74. if not line or line.startswith(("#", "//")):
  75. continue
  76. if source["kind"] == "domain":
  77. domain = normalize_domain(line)
  78. if domain:
  79. values.add(domain)
  80. else:
  81. phrase = unicodedata.normalize("NFKC", line).casefold().strip()
  82. if 5 <= len(phrase) <= 120:
  83. values.add(phrase)
  84. return sorted(values)
  85. async def stage_snapshot(source_id: str) -> dict[str, Any]:
  86. await ensure_indexes()
  87. if source_id not in SOURCES:
  88. raise ValueError("未知外部规则来源。")
  89. source = SOURCES[source_id]
  90. async with ClientSession(timeout=ClientTimeout(total=60)) as session:
  91. async with session.get(source["url"], allow_redirects=False) as response:
  92. response.raise_for_status()
  93. chunks: list[bytes] = []
  94. size = 0
  95. async for chunk in response.content.iter_chunked(65536):
  96. chunks.append(chunk)
  97. size += len(chunk)
  98. if size > int(source["max_bytes"]):
  99. raise ValueError("外部规则文件超过大小限制。")
  100. content = b"".join(chunks)
  101. if len(content) > int(source["max_bytes"]):
  102. raise ValueError("外部规则文件超过大小限制。")
  103. values = parse_entries(source_id, content)
  104. if not values:
  105. raise ValueError("外部规则文件没有可导入的条目。")
  106. digest = hashlib.sha256(content).hexdigest()
  107. existing = await snapshotsdb.find_one(
  108. {"bot_id": BOT_PROFILE_ID, "source_id": source_id, "sha256": digest}
  109. )
  110. if existing and existing.get("status") in {"pending", "published"}:
  111. return existing
  112. snapshot_id = token_hex(12)
  113. now = datetime.now(UTC)
  114. snapshot = {
  115. "snapshot_id": snapshot_id, "bot_id": BOT_PROFILE_ID,
  116. "source_id": source_id, "source_url": source["url"],
  117. "repository": source["repository"], "license": source["license"],
  118. "kind": source["kind"], "sha256": digest, "entry_count": len(values),
  119. "status": "pending", "created_at": now,
  120. }
  121. await snapshotsdb.insert_one(snapshot)
  122. try:
  123. for offset in range(0, len(values), 1000):
  124. await entriesdb.insert_many(
  125. [{"snapshot_id": snapshot_id, "value": value} for value in values[offset:offset + 1000]]
  126. )
  127. except Exception:
  128. await snapshotsdb.update_one(
  129. {"snapshot_id": snapshot_id}, {"$set": {"status": "failed"}}
  130. )
  131. raise
  132. return snapshot
  133. async def list_snapshots(source_id: str | None = None) -> list[dict[str, Any]]:
  134. await ensure_indexes()
  135. query: dict[str, Any] = {"bot_id": BOT_PROFILE_ID}
  136. if source_id:
  137. query["source_id"] = source_id
  138. return [item async for item in snapshotsdb.find(query).sort("created_at", -1).limit(100)]
  139. async def list_active_sources() -> list[dict[str, Any]]:
  140. await ensure_indexes()
  141. return [item async for item in statesdb.find({"bot_id": BOT_PROFILE_ID})]
  142. async def list_snapshot_entries(
  143. snapshot_id: str, *, page: int = 1, page_size: int = 50, query: str = ""
  144. ) -> tuple[list[dict[str, Any]], int]:
  145. await ensure_indexes()
  146. snapshot = await snapshotsdb.find_one({"snapshot_id": snapshot_id, "bot_id": BOT_PROFILE_ID})
  147. if not snapshot:
  148. raise ValueError("规则快照不存在。")
  149. filters: dict[str, Any] = {"snapshot_id": snapshot_id}
  150. if query.strip():
  151. filters["value"] = {"$regex": re.escape(query.strip()[:100]), "$options": "i"}
  152. page = max(1, int(page))
  153. page_size = max(1, min(100, int(page_size)))
  154. total = await entriesdb.count_documents(filters)
  155. cursor = entriesdb.find(filters).sort("value", ASCENDING).skip((page - 1) * page_size).limit(page_size)
  156. return [item async for item in cursor], total
  157. async def publish_snapshot(snapshot_id: str) -> dict[str, Any]:
  158. await ensure_indexes()
  159. snapshot = await snapshotsdb.find_one({"snapshot_id": snapshot_id, "bot_id": BOT_PROFILE_ID})
  160. if not snapshot or snapshot["status"] not in {"pending", "published"}:
  161. raise ValueError("快照不存在或不可发布。")
  162. await statesdb.update_one(
  163. {"bot_id": BOT_PROFILE_ID, "source_id": snapshot["source_id"]},
  164. {"$set": {"active_snapshot_id": snapshot_id, "updated_at": datetime.now(UTC)}},
  165. upsert=True,
  166. )
  167. await snapshotsdb.update_one(
  168. {"snapshot_id": snapshot_id}, {"$set": {"status": "published", "published_at": datetime.now(UTC)}}
  169. )
  170. return snapshot
  171. async def get_policy(chat_id: int) -> dict[str, Any]:
  172. await ensure_indexes()
  173. stored = await policiesdb.find_one({"bot_id": BOT_PROFILE_ID, "chat_id": int(chat_id)})
  174. return {"chat_id": int(chat_id), "mode": (stored or {}).get("mode", "observe")}
  175. async def set_policy(chat_id: int, mode: str) -> dict[str, Any]:
  176. if mode not in {"off", "observe", "delete"}:
  177. raise ValueError("风控模式只能是关闭、观察或删消息。")
  178. await ensure_indexes()
  179. await policiesdb.update_one(
  180. {"bot_id": BOT_PROFILE_ID, "chat_id": int(chat_id)},
  181. {"$set": {"mode": mode, "updated_at": datetime.now(UTC)}}, upsert=True,
  182. )
  183. return {"chat_id": int(chat_id), "mode": mode}
  184. def _message_domains(message: Any) -> set[str]:
  185. text = str(getattr(message, "text", None) or getattr(message, "caption", None) or "")
  186. links = LINK_RE.findall(text)
  187. for entity in list(getattr(message, "entities", None) or []) + list(getattr(message, "caption_entities", None) or []):
  188. if getattr(entity, "url", None):
  189. links.append(str(entity.url))
  190. result: set[str] = set()
  191. for link in links:
  192. domain = normalize_domain(link.rstrip(".,!?;:)]}"))
  193. if domain:
  194. labels = domain.split(".")
  195. result.update(".".join(labels[index:]) for index in range(len(labels) - 1))
  196. return result
  197. async def detect_external(message: Any) -> list[dict[str, Any]]:
  198. await ensure_indexes()
  199. active = [item async for item in statesdb.find({"bot_id": BOT_PROFILE_ID, "active_snapshot_id": {"$exists": True}})]
  200. if not active:
  201. return []
  202. domains = _message_domains(message)
  203. text = unicodedata.normalize(
  204. "NFKC", str(getattr(message, "text", None) or getattr(message, "caption", None) or "")
  205. ).casefold()
  206. matches: list[dict[str, Any]] = []
  207. for state in active:
  208. snapshot = await snapshotsdb.find_one({"snapshot_id": state["active_snapshot_id"]})
  209. if not snapshot:
  210. continue
  211. if snapshot["kind"] == "domain" and domains:
  212. entry = await entriesdb.find_one(
  213. {"snapshot_id": snapshot["snapshot_id"], "value": {"$in": list(domains)}}
  214. )
  215. if entry:
  216. matches.append({"source_id": snapshot["source_id"], "snapshot_id": snapshot["snapshot_id"], "value": entry["value"]})
  217. elif snapshot["kind"] == "phrase" and text:
  218. entries = [item async for item in entriesdb.find({"snapshot_id": snapshot["snapshot_id"]})]
  219. hit = next((item for item in entries if item["value"] in text), None)
  220. if hit:
  221. matches.append({"source_id": snapshot["source_id"], "snapshot_id": snapshot["snapshot_id"], "value": hit["value"]})
  222. return matches
  223. async def enforce_external(message: Any, *, already_deleted: bool = False) -> None:
  224. chat_id = int(message.chat.id)
  225. policy = await get_policy(chat_id)
  226. if policy["mode"] == "off" or getattr(getattr(message, "from_user", None), "is_bot", False):
  227. return
  228. matches = await detect_external(message)
  229. if not matches:
  230. return
  231. deleted = False
  232. if policy["mode"] == "delete" and not already_deleted:
  233. from wbb.services.blacklist_enforcement import _bot_capabilities, _is_privileged_member
  234. user = getattr(message, "from_user", None)
  235. if user and not await _is_privileged_member(chat_id, int(user.id)):
  236. capabilities = await _bot_capabilities(chat_id)
  237. if capabilities["delete"] is True:
  238. try:
  239. await message.delete()
  240. deleted = True
  241. except Exception as exc:
  242. log.error(f"外部风控删除消息失败 chat_id={chat_id}: {exc}")
  243. await eventsdb.insert_one({
  244. "bot_id": BOT_PROFILE_ID, "chat_id": chat_id,
  245. "message_id": int(message.id),
  246. "user_id": int(message.from_user.id) if getattr(message, "from_user", None) else None,
  247. "matches": matches, "mode": policy["mode"], "deleted": deleted,
  248. "created_at": datetime.now(UTC),
  249. })