dbadmin.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. from __future__ import annotations
  2. import asyncio
  3. import re
  4. from datetime import UTC, datetime
  5. from secrets import token_hex
  6. from typing import Any
  7. from pymongo import ASCENDING, DESCENDING
  8. from wbb import BOT_PROFILE_ID, control_db, db
  9. admin_usersdb = control_db.admin_users
  10. admin_sessionsdb = control_db.admin_sessions
  11. auditdb = db.admin_audit_logs
  12. managed_chatsdb = db.managed_chats
  13. managed_chat_settingsdb = db.managed_chat_settings
  14. invite_linksdb = db.admin_invite_links
  15. recent_chat_membersdb = db.recent_chat_members
  16. member_identity_changesdb = db.member_identity_changes
  17. _index_lock = asyncio.Lock()
  18. _indexes_ready = False
  19. def utc_now() -> datetime:
  20. return datetime.now(UTC)
  21. async def ensure_admin_indexes() -> None:
  22. global _indexes_ready
  23. if _indexes_ready:
  24. return
  25. async with _index_lock:
  26. if _indexes_ready:
  27. return
  28. await admin_usersdb.create_index([("username", ASCENDING)], unique=True)
  29. await admin_sessionsdb.create_index([("token_hash", ASCENDING)], unique=True)
  30. await admin_sessionsdb.create_index("expires_at", expireAfterSeconds=0)
  31. await auditdb.create_index([("created_at", DESCENDING)])
  32. await auditdb.create_index(
  33. [("chat_id", ASCENDING), ("created_at", DESCENDING)]
  34. )
  35. await managed_chatsdb.create_index(
  36. [("bot_id", ASCENDING), ("chat_id", ASCENDING)], unique=True
  37. )
  38. await managed_chatsdb.create_index([("last_seen_at", DESCENDING)])
  39. await managed_chat_settingsdb.create_index(
  40. [("bot_id", ASCENDING), ("chat_id", ASCENDING)], unique=True
  41. )
  42. await invite_linksdb.create_index(
  43. [("bot_id", ASCENDING), ("chat_id", ASCENDING), ("created_at", DESCENDING)]
  44. )
  45. await recent_chat_membersdb.create_index(
  46. [
  47. ("bot_id", ASCENDING),
  48. ("chat_id", ASCENDING),
  49. ("user_id", ASCENDING),
  50. ],
  51. unique=True,
  52. )
  53. await recent_chat_membersdb.create_index(
  54. [("bot_id", ASCENDING), ("chat_id", ASCENDING), ("last_seen_at", DESCENDING)]
  55. )
  56. await member_identity_changesdb.create_index(
  57. [("bot_id", ASCENDING), ("chat_id", ASCENDING), ("observed_at", DESCENDING)]
  58. )
  59. await member_identity_changesdb.create_index(
  60. [
  61. ("bot_id", ASCENDING),
  62. ("chat_id", ASCENDING),
  63. ("user_id", ASCENDING),
  64. ("observed_at", DESCENDING),
  65. ]
  66. )
  67. _indexes_ready = True
  68. async def ensure_default_admin(
  69. *, username: str, password_hash: str
  70. ) -> dict[str, Any]:
  71. await ensure_admin_indexes()
  72. now = utc_now()
  73. await admin_usersdb.update_one(
  74. {"username": username},
  75. {
  76. "$setOnInsert": {
  77. "username": username,
  78. "password_hash": password_hash,
  79. "must_change_password": True,
  80. "failed_login_count": 0,
  81. "created_at": now,
  82. "updated_at": now,
  83. }
  84. },
  85. upsert=True,
  86. )
  87. return await admin_usersdb.find_one({"username": username})
  88. async def get_admin_user(username: str) -> dict[str, Any] | None:
  89. await ensure_admin_indexes()
  90. return await admin_usersdb.find_one({"username": username})
  91. async def record_login_failure(username: str) -> None:
  92. await ensure_admin_indexes()
  93. await admin_usersdb.update_one(
  94. {"username": username},
  95. {
  96. "$inc": {"failed_login_count": 1},
  97. "$set": {"last_failed_login_at": utc_now(), "updated_at": utc_now()},
  98. },
  99. )
  100. async def record_login_success(username: str) -> None:
  101. await ensure_admin_indexes()
  102. await admin_usersdb.update_one(
  103. {"username": username},
  104. {
  105. "$set": {
  106. "failed_login_count": 0,
  107. "last_login_at": utc_now(),
  108. "updated_at": utc_now(),
  109. }
  110. },
  111. )
  112. async def update_admin_password(username: str, password_hash: str) -> bool:
  113. await ensure_admin_indexes()
  114. result = await admin_usersdb.update_one(
  115. {"username": username},
  116. {
  117. "$set": {
  118. "password_hash": password_hash,
  119. "must_change_password": False,
  120. "password_updated_at": utc_now(),
  121. "updated_at": utc_now(),
  122. }
  123. },
  124. )
  125. if result.modified_count:
  126. await admin_sessionsdb.delete_many({"username": username})
  127. return result.modified_count == 1
  128. async def create_admin_session(
  129. *,
  130. username: str,
  131. token_hash: str,
  132. csrf_token: str,
  133. expires_at: datetime,
  134. remote_address: str,
  135. user_agent: str,
  136. ) -> None:
  137. await ensure_admin_indexes()
  138. now = utc_now()
  139. await admin_sessionsdb.insert_one(
  140. {
  141. "username": username,
  142. "token_hash": token_hash,
  143. "csrf_token": csrf_token,
  144. "remote_address": remote_address[:200],
  145. "user_agent": user_agent[:500],
  146. "created_at": now,
  147. "last_seen_at": now,
  148. "expires_at": expires_at,
  149. }
  150. )
  151. async def get_admin_session(token_hash: str) -> dict[str, Any] | None:
  152. await ensure_admin_indexes()
  153. session = await admin_sessionsdb.find_one(
  154. {"token_hash": token_hash, "expires_at": {"$gt": utc_now()}}
  155. )
  156. if not session:
  157. return None
  158. user = await get_admin_user(session["username"])
  159. if not user:
  160. return None
  161. await admin_sessionsdb.update_one(
  162. {"_id": session["_id"]}, {"$set": {"last_seen_at": utc_now()}}
  163. )
  164. return {**session, "user": user}
  165. async def revoke_admin_session(token_hash: str) -> None:
  166. await ensure_admin_indexes()
  167. await admin_sessionsdb.delete_one({"token_hash": token_hash})
  168. async def revoke_admin_sessions(username: str) -> None:
  169. await ensure_admin_indexes()
  170. await admin_sessionsdb.delete_many({"username": username})
  171. async def upsert_managed_chat(
  172. *,
  173. chat_id: int,
  174. title: str | None,
  175. username: str | None,
  176. chat_type: str,
  177. member_count: int | None = None,
  178. accessible: bool = True,
  179. bot_status: str | None = None,
  180. bot_privileges: list[str] | None = None,
  181. ) -> None:
  182. await ensure_admin_indexes()
  183. now = utc_now()
  184. values: dict[str, Any] = {
  185. "title": title or str(chat_id),
  186. "username": username,
  187. "type": chat_type,
  188. "accessible": accessible,
  189. "last_seen_at": now,
  190. "updated_at": now,
  191. }
  192. if member_count is not None:
  193. values["member_count"] = int(member_count)
  194. if bot_status is not None:
  195. values["bot_status"] = bot_status
  196. if bot_privileges is not None:
  197. values["bot_privileges"] = bot_privileges
  198. await managed_chatsdb.update_one(
  199. {"bot_id": BOT_PROFILE_ID, "chat_id": chat_id},
  200. {
  201. "$set": values,
  202. "$setOnInsert": {"bot_id": BOT_PROFILE_ID, "created_at": now},
  203. },
  204. upsert=True,
  205. )
  206. async def mark_managed_chat_unavailable(chat_id: int, reason: str) -> None:
  207. await ensure_admin_indexes()
  208. await managed_chatsdb.update_one(
  209. {"bot_id": BOT_PROFILE_ID, "chat_id": chat_id},
  210. {
  211. "$set": {
  212. "accessible": False,
  213. "last_error": reason[:500],
  214. "updated_at": utc_now(),
  215. }
  216. },
  217. upsert=True,
  218. )
  219. async def list_managed_chats(
  220. *, query: str = "", page: int = 1, page_size: int = 20
  221. ) -> tuple[list[dict[str, Any]], int]:
  222. await ensure_admin_indexes()
  223. filters: dict[str, Any] = {"bot_id": BOT_PROFILE_ID}
  224. query = query.strip()
  225. if query:
  226. if query.lstrip("-").isdigit():
  227. filters["chat_id"] = int(query)
  228. else:
  229. value = re.escape(query.lstrip("@"))
  230. filters["$or"] = [
  231. {"title": {"$regex": value, "$options": "i"}},
  232. {"username": {"$regex": value, "$options": "i"}},
  233. ]
  234. page = max(1, page)
  235. page_size = max(1, min(page_size, 100))
  236. total = await managed_chatsdb.count_documents(filters)
  237. cursor = (
  238. managed_chatsdb.find(filters)
  239. .sort([("accessible", DESCENDING), ("last_seen_at", DESCENDING)])
  240. .skip((page - 1) * page_size)
  241. .limit(page_size)
  242. )
  243. return [doc async for doc in cursor], total
  244. async def record_audit(
  245. *,
  246. source: str,
  247. actor_id: int | str | None,
  248. actor_name: str,
  249. action: str,
  250. chat_id: int | None = None,
  251. target_id: int | str | None = None,
  252. summary: str = "",
  253. success: bool = True,
  254. error: str = "",
  255. metadata: dict[str, Any] | None = None,
  256. ) -> None:
  257. await ensure_admin_indexes()
  258. await auditdb.insert_one(
  259. {
  260. "source": source,
  261. "actor_id": actor_id,
  262. "actor_name": actor_name,
  263. "action": action,
  264. "chat_id": chat_id,
  265. "target_id": target_id,
  266. "summary": summary[:1000],
  267. "success": bool(success),
  268. "error": error[:1000],
  269. "metadata": metadata or {},
  270. "bot_id": BOT_PROFILE_ID,
  271. "created_at": utc_now(),
  272. }
  273. )
  274. async def list_audit_logs(
  275. *,
  276. chat_id: int | None = None,
  277. action: str | None = None,
  278. page: int = 1,
  279. page_size: int = 20,
  280. ) -> tuple[list[dict[str, Any]], int]:
  281. await ensure_admin_indexes()
  282. filters: dict[str, Any] = {}
  283. if chat_id is not None:
  284. filters["chat_id"] = chat_id
  285. if action:
  286. filters["action"] = action
  287. page = max(1, page)
  288. page_size = max(1, min(page_size, 100))
  289. total = await auditdb.count_documents(filters)
  290. cursor = (
  291. auditdb.find(filters)
  292. .sort("created_at", DESCENDING)
  293. .skip((page - 1) * page_size)
  294. .limit(page_size)
  295. )
  296. return [doc async for doc in cursor], total
  297. async def get_managed_chat_settings(chat_id: int) -> dict[str, Any]:
  298. await ensure_admin_indexes()
  299. doc = await managed_chat_settingsdb.find_one(
  300. {"bot_id": BOT_PROFILE_ID, "chat_id": int(chat_id)}
  301. )
  302. return doc or {
  303. "chat_id": int(chat_id),
  304. "auto_replies": [],
  305. "blacklist_words": [],
  306. "welcome": {"enabled": False, "text": "", "media": None},
  307. "identity_monitor": {"enabled": False, "notify_in_chat": False},
  308. "captcha_enabled": False,
  309. "chatbot_enabled": False,
  310. "antiflood_enabled": True,
  311. }
  312. async def update_managed_chat_settings(
  313. chat_id: int, values: dict[str, Any]
  314. ) -> dict[str, Any]:
  315. await ensure_admin_indexes()
  316. allowed = {
  317. "auto_replies",
  318. "blacklist_words",
  319. "risk_control",
  320. "risk_rules",
  321. "identity_monitor",
  322. "welcome",
  323. "captcha_enabled",
  324. "chatbot_enabled",
  325. "antiflood_enabled",
  326. }
  327. update = {key: value for key, value in values.items() if key in allowed}
  328. now = utc_now()
  329. await managed_chat_settingsdb.update_one(
  330. {"bot_id": BOT_PROFILE_ID, "chat_id": int(chat_id)},
  331. {
  332. "$set": {**update, "updated_at": now},
  333. "$setOnInsert": {
  334. "bot_id": BOT_PROFILE_ID,
  335. "chat_id": int(chat_id),
  336. "created_at": now,
  337. },
  338. },
  339. upsert=True,
  340. )
  341. return await get_managed_chat_settings(chat_id)
  342. async def upsert_recent_chat_member(
  343. *,
  344. chat_id: int,
  345. user_id: int,
  346. username: str | None,
  347. first_name: str | None,
  348. last_name: str | None,
  349. is_bot: bool,
  350. ) -> None:
  351. await ensure_admin_indexes()
  352. now = utc_now()
  353. await recent_chat_membersdb.update_one(
  354. {
  355. "bot_id": BOT_PROFILE_ID,
  356. "chat_id": int(chat_id),
  357. "user_id": int(user_id),
  358. },
  359. {
  360. "$set": {
  361. "username": username,
  362. "first_name": first_name,
  363. "last_name": last_name,
  364. "is_bot": bool(is_bot),
  365. "last_seen_at": now,
  366. },
  367. "$inc": {"message_count": 1},
  368. "$setOnInsert": {
  369. "bot_id": BOT_PROFILE_ID,
  370. "chat_id": int(chat_id),
  371. "user_id": int(user_id),
  372. "created_at": now,
  373. },
  374. },
  375. upsert=True,
  376. )
  377. async def get_recent_chat_member(chat_id: int, user_id: int) -> dict[str, Any] | None:
  378. await ensure_admin_indexes()
  379. return await recent_chat_membersdb.find_one(
  380. {
  381. "bot_id": BOT_PROFILE_ID,
  382. "chat_id": int(chat_id),
  383. "user_id": int(user_id),
  384. }
  385. )
  386. async def record_member_identity_change(
  387. *,
  388. chat_id: int,
  389. user_id: int,
  390. before: dict[str, Any],
  391. after: dict[str, Any],
  392. changed_fields: list[str],
  393. ) -> dict[str, Any]:
  394. await ensure_admin_indexes()
  395. event = {
  396. "change_id": token_hex(10),
  397. "bot_id": BOT_PROFILE_ID,
  398. "chat_id": int(chat_id),
  399. "user_id": int(user_id),
  400. "before": before,
  401. "after": after,
  402. "changed_fields": changed_fields,
  403. "observed_at": utc_now(),
  404. }
  405. await member_identity_changesdb.insert_one(event)
  406. return event
  407. async def list_member_identity_changes(
  408. chat_id: int,
  409. *,
  410. page: int = 1,
  411. page_size: int = 20,
  412. ) -> tuple[list[dict[str, Any]], int]:
  413. await ensure_admin_indexes()
  414. filters = {"bot_id": BOT_PROFILE_ID, "chat_id": int(chat_id)}
  415. page = max(1, int(page))
  416. page_size = max(1, min(int(page_size), 100))
  417. total = await member_identity_changesdb.count_documents(filters)
  418. cursor = (
  419. member_identity_changesdb.find(filters)
  420. .sort("observed_at", DESCENDING)
  421. .skip((page - 1) * page_size)
  422. .limit(page_size)
  423. )
  424. return [item async for item in cursor], total
  425. async def list_recent_chat_members(
  426. chat_id: int,
  427. *,
  428. query: str = "",
  429. limit: int = 30,
  430. ) -> list[dict[str, Any]]:
  431. await ensure_admin_indexes()
  432. filters: dict[str, Any] = {
  433. "bot_id": BOT_PROFILE_ID,
  434. "chat_id": int(chat_id),
  435. "is_bot": {"$ne": True},
  436. }
  437. normalized_query = query.strip().lstrip("@")
  438. if normalized_query:
  439. if normalized_query.isdigit():
  440. filters["user_id"] = int(normalized_query)
  441. else:
  442. pattern = re.escape(normalized_query)
  443. filters["$or"] = [
  444. {"username": {"$regex": pattern, "$options": "i"}},
  445. {"first_name": {"$regex": pattern, "$options": "i"}},
  446. {"last_name": {"$regex": pattern, "$options": "i"}},
  447. ]
  448. cursor = (
  449. recent_chat_membersdb.find(filters)
  450. .sort("last_seen_at", DESCENDING)
  451. .limit(max(1, min(int(limit), 50)))
  452. )
  453. return [item async for item in cursor]
  454. async def store_invite_link(
  455. *, chat_id: int, invite_link: str, name: str, expires_at: datetime | None
  456. ) -> None:
  457. await ensure_admin_indexes()
  458. await invite_linksdb.update_one(
  459. {
  460. "bot_id": BOT_PROFILE_ID,
  461. "chat_id": int(chat_id),
  462. "invite_link": invite_link,
  463. },
  464. {
  465. "$set": {
  466. "name": name,
  467. "expires_at": expires_at,
  468. "revoked": False,
  469. "updated_at": utc_now(),
  470. },
  471. "$setOnInsert": {"bot_id": BOT_PROFILE_ID, "created_at": utc_now()},
  472. },
  473. upsert=True,
  474. )
  475. async def revoke_stored_invite_link(chat_id: int, invite_link: str) -> None:
  476. await ensure_admin_indexes()
  477. await invite_linksdb.update_one(
  478. {
  479. "bot_id": BOT_PROFILE_ID,
  480. "chat_id": int(chat_id),
  481. "invite_link": invite_link,
  482. },
  483. {"$set": {"revoked": True, "revoked_at": utc_now()}},
  484. )
  485. async def list_stored_invite_links(chat_id: int) -> list[dict[str, Any]]:
  486. await ensure_admin_indexes()
  487. cursor = invite_linksdb.find(
  488. {"bot_id": BOT_PROFILE_ID, "chat_id": int(chat_id)}
  489. ).sort(
  490. "created_at", DESCENDING
  491. )
  492. return [doc async for doc in cursor]
  493. async def dashboard_counts() -> dict[str, int]:
  494. await ensure_admin_indexes()
  495. return {
  496. "chats": await managed_chatsdb.count_documents({"accessible": {"$ne": False}}),
  497. "audit_events": await auditdb.count_documents({}),
  498. }