Hard-separate admin.hackrobot.cn (VIP ops) from admin.nomadro.cn forever; add live_ops bus, overlay tags, and deploy helpers. Co-authored-by: Cursor <cursoragent@cursor.com>
299 lines
8.8 KiB
Python
299 lines
8.8 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""Realtime ops: VIP presence + admin broadcast (SSE)."""
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import base64
|
|
import hashlib
|
|
import hmac
|
|
import json
|
|
import os
|
|
import time
|
|
from typing import Annotated, Any
|
|
|
|
import jwt
|
|
from fastapi import APIRouter, Depends, Header, HTTPException, Query, Request
|
|
from fastapi.responses import JSONResponse, StreamingResponse
|
|
from pydantic import BaseModel, Field
|
|
|
|
from ebook_svc.core.rate_limit import rate_limit
|
|
from ebook_svc.services import ops_live
|
|
from ebook_svc.services.store import store
|
|
|
|
try:
|
|
from ebook_svc.config import settings # type: ignore
|
|
except Exception: # pragma: no cover
|
|
from ebook_svc.core.config import settings # type: ignore
|
|
|
|
router = APIRouter(tags=["live-ops"])
|
|
|
|
_SSE_HEADERS = {
|
|
"Cache-Control": "no-cache, no-transform",
|
|
"Connection": "keep-alive",
|
|
"X-Accel-Buffering": "no",
|
|
"Access-Control-Allow-Origin": "*",
|
|
}
|
|
|
|
|
|
def _b64url_decode(raw: str) -> bytes:
|
|
pad = "=" * (-len(raw) % 4)
|
|
return base64.urlsafe_b64decode(raw + pad)
|
|
|
|
|
|
def _b64url_encode(raw: bytes) -> str:
|
|
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
|
|
|
|
|
def _ops_secrets() -> list[str]:
|
|
"""Match nomadvip ops-auth.ts: VIP_OPS_SECRET || POCKETBASE_PASSWORD || default."""
|
|
out: list[str] = []
|
|
for key in ("VIP_OPS_SECRET", "POCKETBASE_PASSWORD"):
|
|
val = (os.environ.get(key) or "").strip()
|
|
if val and val not in out:
|
|
out.append(val)
|
|
for attr in ("vip_ops_secret", "pocketbase_password"):
|
|
val = str(getattr(settings, attr, "") or "").strip()
|
|
if val and val not in out:
|
|
out.append(val)
|
|
if "vip-ops-change-me" not in out:
|
|
out.append("vip-ops-change-me")
|
|
return out
|
|
|
|
|
|
def verify_ops_token(token: str) -> str | None:
|
|
"""Verify VIP 运营台 HMAC token (payload.sig, exp in ms)."""
|
|
parts = str(token or "").split(".")
|
|
if len(parts) != 2:
|
|
return None
|
|
payload, sig = parts
|
|
if not payload or not sig:
|
|
return None
|
|
for secret in _ops_secrets():
|
|
expect = _b64url_encode(
|
|
hmac.new(secret.encode("utf-8"), payload.encode("utf-8"), hashlib.sha256).digest()
|
|
)
|
|
try:
|
|
if len(sig) != len(expect) or not hmac.compare_digest(sig, expect):
|
|
continue
|
|
except Exception:
|
|
continue
|
|
try:
|
|
data = json.loads(_b64url_decode(payload).decode("utf-8"))
|
|
except Exception:
|
|
return None
|
|
user = str(data.get("u") or "").strip()
|
|
exp = data.get("exp")
|
|
if not user or not exp:
|
|
return None
|
|
try:
|
|
if time.time() * 1000 > float(exp):
|
|
return None
|
|
except Exception:
|
|
return None
|
|
return user
|
|
return None
|
|
|
|
|
|
async def require_admin_or_ops(
|
|
authorization: Annotated[str | None, Header()] = None,
|
|
token: str | None = Query(default=None),
|
|
) -> str:
|
|
"""Accept ebook admin JWT or VIP ops HMAC token (admin.hackrobot.cn 运营台)."""
|
|
auth = authorization
|
|
if (not auth or not auth.startswith("Bearer ")) and token:
|
|
auth = f"Bearer {token.strip()}"
|
|
if not auth or not auth.startswith("Bearer "):
|
|
raise HTTPException(401, "未登录管理后台")
|
|
raw = auth.removeprefix("Bearer ").strip()
|
|
try:
|
|
data = jwt.decode(raw, settings.jwt_secret, algorithms=["HS256"])
|
|
if data.get("role") == "admin":
|
|
return str(data.get("sub") or "admin")
|
|
except Exception:
|
|
pass
|
|
ops_user = verify_ops_token(raw)
|
|
if ops_user:
|
|
return ops_user
|
|
raise HTTPException(401, "登录已失效")
|
|
|
|
|
|
class PresenceIn(BaseModel):
|
|
visitorId: str = Field(default="", max_length=80)
|
|
openid: str = Field(default="", max_length=80)
|
|
nick: str = Field(default="", max_length=48)
|
|
email: str = Field(default="", max_length=160)
|
|
page: str = Field(default="/", max_length=160)
|
|
role: str = Field(default="guest", max_length=24)
|
|
|
|
|
|
class BroadcastIn(BaseModel):
|
|
title: str = Field(min_length=1, max_length=80)
|
|
body: str = Field(default="", max_length=400)
|
|
cta: str = Field(default="知道了", max_length=32)
|
|
href: str = Field(default="", max_length=300)
|
|
tone: str = Field(default="amber", max_length=24)
|
|
ttlSec: int = Field(default=60, ge=8, le=600)
|
|
|
|
|
|
def _sse(event: str, data: dict[str, Any]) -> str:
|
|
return f"event: {event}\ndata: {json.dumps(data, ensure_ascii=False)}\n\n"
|
|
|
|
|
|
def _admin_users_online() -> list[dict[str, Any]]:
|
|
rows = store.list_users(limit=200, q="")
|
|
out = []
|
|
for u in rows:
|
|
if not u.get("online"):
|
|
continue
|
|
out.append(
|
|
{
|
|
"openid": u.get("openid"),
|
|
"nickname": u.get("nickname"),
|
|
"notes": u.get("notes"),
|
|
"unlocked_vip": bool(u.get("unlocked_vip")),
|
|
"last_seen_at": u.get("last_seen_at"),
|
|
"status": u.get("status") or "active",
|
|
"source": "miniprogram",
|
|
}
|
|
)
|
|
return out
|
|
|
|
|
|
@router.post("/api/vip/live/presence")
|
|
@router.post("/api/ebook/vip/live/presence")
|
|
async def vip_presence(body: PresenceIn, request: Request):
|
|
rate_limit(request, bucket="vip.live.presence", limit=60, window_sec=60.0)
|
|
ua = (request.headers.get("user-agent") or "")[:180]
|
|
try:
|
|
row = ops_live.touch_presence(
|
|
visitor_id=body.visitorId or body.openid,
|
|
openid=body.openid,
|
|
nick=body.nick,
|
|
email=body.email,
|
|
page=body.page,
|
|
role=body.role,
|
|
ua=ua,
|
|
)
|
|
except ValueError as e:
|
|
raise HTTPException(400, str(e)) from e
|
|
# If looks like wechat openid, also refresh sqlite last_seen for VipUsers
|
|
oid = (body.openid or body.visitorId or "").strip()
|
|
if oid and not oid.startswith("user") and len(oid) >= 16:
|
|
try:
|
|
store.touch_last_seen(oid)
|
|
except Exception:
|
|
pass
|
|
return {"ok": True, "id": row["id"], "ttlSec": int(ops_live.PRESENCE_TTL_SEC)}
|
|
|
|
|
|
@router.get("/api/vip/live/stream")
|
|
@router.get("/api/ebook/vip/live/stream")
|
|
async def vip_live_stream():
|
|
"""Public SSE for vip.hackrobot.cn — receives admin broadcasts."""
|
|
try:
|
|
ops_live.bind_loop()
|
|
except Exception:
|
|
pass
|
|
queue = ops_live.register_listener()
|
|
|
|
async def gen():
|
|
try:
|
|
hello = {"type": "hello", "at": ops_live._now(), "channel": "vip"}
|
|
yield _sse("hello", hello)
|
|
for bc in ops_live.recent_broadcasts(1):
|
|
# only push if fresh (< ttl)
|
|
age = ops_live._now() - float(bc.get("at") or 0)
|
|
if age <= float(bc.get("ttlSec") or 60):
|
|
yield _sse("broadcast", bc)
|
|
while True:
|
|
try:
|
|
payload = await asyncio.wait_for(queue.get(), timeout=18.0)
|
|
except asyncio.TimeoutError:
|
|
yield ": ping\n\n"
|
|
continue
|
|
if not isinstance(payload, dict):
|
|
continue
|
|
if payload.get("type") == "broadcast":
|
|
yield _sse("broadcast", payload)
|
|
# presence ticks ignored on VIP client
|
|
finally:
|
|
ops_live.unregister_listener(queue)
|
|
|
|
return StreamingResponse(gen(), media_type="text/event-stream", headers=_SSE_HEADERS)
|
|
|
|
|
|
@router.get("/api/admin/live/online")
|
|
async def admin_live_online(_: str = Depends(require_admin_or_ops)):
|
|
return {
|
|
"ok": True,
|
|
"webOnline": ops_live.list_online(),
|
|
"appOnline": _admin_users_online(),
|
|
"recentBroadcasts": ops_live.recent_broadcasts(10),
|
|
}
|
|
|
|
|
|
@router.post("/api/admin/live/broadcast")
|
|
async def admin_live_broadcast(
|
|
body: BroadcastIn,
|
|
admin: str = Depends(require_admin_or_ops),
|
|
):
|
|
try:
|
|
msg = ops_live.publish_broadcast(
|
|
title=body.title,
|
|
body=body.body,
|
|
cta=body.cta,
|
|
href=body.href,
|
|
tone=body.tone,
|
|
ttl_sec=body.ttlSec,
|
|
admin=admin,
|
|
)
|
|
except ValueError as e:
|
|
raise HTTPException(400, str(e)) from e
|
|
return {"ok": True, "item": msg}
|
|
|
|
|
|
@router.get("/api/admin/live/stream")
|
|
async def admin_live_stream(
|
|
admin: str = Depends(require_admin_or_ops),
|
|
):
|
|
"""Admin SSE. Prefer Authorization; EventSource may pass ?token=."""
|
|
try:
|
|
ops_live.bind_loop()
|
|
except Exception:
|
|
pass
|
|
queue = ops_live.register_listener()
|
|
|
|
async def gen():
|
|
try:
|
|
snap = ops_live.snapshot(include_users=_admin_users_online())
|
|
snap["admin"] = admin
|
|
yield _sse("tick", snap)
|
|
while True:
|
|
try:
|
|
payload = await asyncio.wait_for(queue.get(), timeout=ops_live.ADMIN_TICK_SEC)
|
|
if isinstance(payload, dict) and payload.get("type") == "broadcast":
|
|
yield _sse("broadcast", payload)
|
|
# always refresh online snapshot on any event
|
|
tick = ops_live.snapshot(include_users=_admin_users_online())
|
|
yield _sse("tick", tick)
|
|
except asyncio.TimeoutError:
|
|
tick = ops_live.snapshot(include_users=_admin_users_online())
|
|
yield _sse("tick", tick)
|
|
finally:
|
|
ops_live.unregister_listener(queue)
|
|
|
|
return StreamingResponse(gen(), media_type="text/event-stream", headers=_SSE_HEADERS)
|
|
|
|
|
|
@router.options("/api/vip/live/{path:path}")
|
|
@router.options("/api/admin/live/{path:path}")
|
|
async def live_cors_options():
|
|
return JSONResponse(
|
|
content={"ok": True},
|
|
headers={
|
|
"Access-Control-Allow-Origin": "*",
|
|
"Access-Control-Allow-Methods": "GET,POST,OPTIONS",
|
|
"Access-Control-Allow-Headers": "Authorization,Content-Type",
|
|
},
|
|
)
|