# -*- coding: utf-8 -*- """Admin security denylist — email / guest / IP bans (PB hub_archives SoT). Entity: hub_archives where entity="security_denylist" entity_id: primary key (usually email lowercase) payload: { email, qq, guestIds[], ips[], reason, active, at } """ from __future__ import annotations import time from typing import Any from nomadro_pb.client import pb_quote ENTITY = "security_denylist" C_ARCHIVES = "hub_archives" # Process cache — refresh every 30s (fail-open on PB outage after seed) _CACHE: dict[str, Any] = {"at": 0.0, "emails": set(), "guests": set(), "ips": set(), "rows": []} _TTL = 30.0 def _now() -> str: return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) def _pb(): from hub_svc.pb_data import get_pb, init_pb init_pb() return get_pb() def _norm_email(email: str) -> str: return (email or "").strip().lower()[:160] def _norm_ip(ip: str) -> str: return (ip or "").strip().split("%")[0][:64] def _seed_from_rows(rows: list[dict[str, Any]]) -> None: emails: set[str] = set() guests: set[str] = set() ips: set[str] = set() active_rows: list[dict[str, Any]] = [] for r in rows: payload = r.get("payload") if isinstance(r.get("payload"), dict) else {} if payload.get("active") is False: continue email = _norm_email(str(payload.get("email") or r.get("entity_id") or "")) if email: emails.add(email) qq = str(payload.get("qq") or "").strip() if qq and "@" not in qq: emails.add(f"{qq}@qq.com") for g in payload.get("guestIds") or []: g = str(g or "").strip() if g: guests.add(g) gid = str(r.get("guest_id") or "").strip() if gid and gid.startswith("guest_"): guests.add(gid) for ip in payload.get("ips") or payload.get("ips_suspected") or []: ip_n = _norm_ip(str(ip)) if ip_n: ips.add(ip_n) active_rows.append(r) _CACHE["emails"] = emails _CACHE["guests"] = guests _CACHE["ips"] = ips _CACHE["rows"] = active_rows _CACHE["at"] = time.monotonic() def refresh_denylist(*, force: bool = False) -> dict[str, Any]: now = time.monotonic() if not force and _CACHE["at"] and (now - float(_CACHE["at"])) < _TTL: return { "emails": set(_CACHE["emails"]), "guests": set(_CACHE["guests"]), "ips": set(_CACHE["ips"]), "count": len(_CACHE["rows"]), } try: rows = _pb().list_all( C_ARCHIVES, filter=f'entity="{ENTITY}"', sort="-created_at", hard_limit=2000, ) _seed_from_rows(rows) except Exception: # Keep last good cache; empty only if never loaded if not _CACHE["at"]: _CACHE["at"] = now return { "emails": set(_CACHE["emails"]), "guests": set(_CACHE["guests"]), "ips": set(_CACHE["ips"]), "count": len(_CACHE["rows"]), } def snapshot() -> dict[str, Any]: return refresh_denylist(force=False) def is_denied( *, email: str = "", guest_id: str = "", ip: str = "", ) -> dict[str, Any] | None: """Return hit detail if denied, else None.""" snap = snapshot() email_n = _norm_email(email) guest_n = (guest_id or "").strip() ip_n = _norm_ip(ip) reasons: list[str] = [] if email_n and email_n in snap["emails"]: reasons.append(f"email:{email_n}") # qq@x without full email — also match local-part@qq.com pattern already seeded if email_n and "@" in email_n: local = email_n.split("@", 1)[0] if local.isdigit() and f"{local}@qq.com" in snap["emails"] and email_n != f"{local}@qq.com": # only exact email match for non-qq aliases pass if guest_n and guest_n in snap["guests"]: reasons.append(f"guest:{guest_n}") if ip_n and ip_n in snap["ips"]: reasons.append(f"ip:{ip_n}") if not reasons: return None return {"denied": True, "reasons": reasons} def assert_not_denied(*, email: str = "", guest_id: str = "", ip: str = "") -> None: hit = is_denied(email=email, guest_id=guest_id, ip=ip) if hit: raise ValueError("账号已被封禁,无法继续操作") def list_denylist(*, limit: int = 200) -> dict[str, Any]: refresh_denylist(force=True) items = [] for r in _CACHE["rows"][: max(1, min(int(limit or 200), 500))]: payload = r.get("payload") if isinstance(r.get("payload"), dict) else {} items.append( { "id": r.get("id"), "email": payload.get("email") or r.get("entity_id") or "", "qq": payload.get("qq") or "", "guestIds": list(payload.get("guestIds") or []), "ips": list(payload.get("ips") or payload.get("ips_suspected") or []), "reason": payload.get("reason") or "", "active": payload.get("active") is not False, "at": payload.get("at") or r.get("created_at") or "", } ) return {"ok": True, "items": items, "total": len(items)} def ban( *, email: str, reason: str = "", guest_ids: list[str] | None = None, ips: list[str] | None = None, qq: str = "", ) -> dict[str, Any]: email_n = _norm_email(email) if not email_n or "@" not in email_n: raise ValueError("invalid email") now = _now() guests = [str(g).strip() for g in (guest_ids or []) if str(g).strip()] ip_list = [_norm_ip(i) for i in (ips or []) if _norm_ip(i)] qq_n = (qq or "").strip() or (email_n.split("@", 1)[0] if email_n.endswith("@qq.com") else "") reason_n = (reason or f"admin ban {email_n}").strip()[:500] payload = { "email": email_n, "qq": qq_n, "guestIds": guests, "ips": ip_list, "ips_suspected": ip_list, "reason": reason_n, "active": True, "at": now, } pb = _pb() existing = pb.first( C_ARCHIVES, filter=f'entity="{ENTITY}" && entity_id={pb_quote(email_n)}', ) if existing: old = existing.get("payload") if isinstance(existing.get("payload"), dict) else {} merged_guests = list({*list(old.get("guestIds") or []), *guests}) merged_ips = list( { *[_norm_ip(x) for x in (old.get("ips") or old.get("ips_suspected") or []) if x], *ip_list, } ) payload["guestIds"] = merged_guests payload["ips"] = merged_ips payload["ips_suspected"] = merged_ips if not payload.get("reason") and old.get("reason"): payload["reason"] = old.get("reason") primary_guest = qq_n or (guests[0] if guests else "") rec = pb.update( C_ARCHIVES, str(existing["id"]), {"action": "ban", "guest_id": primary_guest, "payload": payload}, ) else: primary_guest = qq_n or (guests[0] if guests else "") rec = pb.create( C_ARCHIVES, { "entity": ENTITY, "entity_id": email_n, "action": "ban", "guest_id": primary_guest, "payload": payload, "created_at": now, }, ) # also mark join lead + hide roster guests try: from hub_svc import pb_data lead = pb.first("hub_join_leads", filter=f"email={pb_quote(email_n)}") if lead: old_p = lead.get("payload") if isinstance(lead.get("payload"), dict) else {} pb.update( "hub_join_leads", str(lead["id"]), { "stage": "blocked", "payload": {**old_p, "blocked": True, "blockedReason": reason_n, "blockedAt": now}, "updated_at": now, }, ) gid = str(lead.get("guest_id") or "").strip() if gid and gid not in guests: guests.append(gid) for gid in guests: row = pb_data.get_roster(gid) if row and row.get("id"): pb.update( "hub_roster", str(row["id"]), {"status": "offline", "discoverable": False, "updated_at": now}, ) else: # get_roster returns public shape without id — fetch raw raw = pb.first("hub_roster", filter=f"guest_id={pb_quote(gid)}") if raw: pb.update( "hub_roster", str(raw["id"]), {"status": "offline", "discoverable": False, "updated_at": now}, ) try: pb.upsert( "hub_blocks", filter=f'guest_id="admin_system" && blocked_guest={pb_quote(gid)}', payload={ "guest_id": "admin_system", "blocked_guest": gid, "reason": reason_n, "created_at": now, }, ) except Exception: pass except Exception: pass refresh_denylist(force=True) return {"ok": True, "id": rec.get("id"), "email": email_n, "payload": payload} def unban(*, email: str) -> dict[str, Any]: email_n = _norm_email(email) if not email_n: raise ValueError("invalid email") pb = _pb() existing = pb.first( C_ARCHIVES, filter=f'entity="{ENTITY}" && entity_id={pb_quote(email_n)}', ) if not existing: return {"ok": True, "email": email_n, "active": False, "note": "not_found"} payload = existing.get("payload") if isinstance(existing.get("payload"), dict) else {} payload = dict(payload) payload["active"] = False payload["unbannedAt"] = _now() pb.update(C_ARCHIVES, str(existing["id"]), {"action": "unban", "payload": payload}) refresh_denylist(force=True) return {"ok": True, "email": email_n, "active": False}