root.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. """Main bot page"""
  2. # Friendly Telegram (telegram userbot)
  3. # Copyright (C) 2018-2021 The Authors
  4. # This program is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU Affero General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU Affero General Public License for more details.
  12. # You should have received a copy of the GNU Affero General Public License
  13. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. # █ █ ▀ █▄▀ ▄▀█ █▀█ ▀
  15. # █▀█ █ █ █ █▀█ █▀▄ █
  16. # © Copyright 2022
  17. # https://t.me/hikariatama
  18. #
  19. # 🔒 Licensed under the GNU AGPLv3
  20. # 🌐 https://www.gnu.org/licenses/agpl-3.0.html
  21. import asyncio
  22. import collections
  23. import os
  24. import string
  25. import aiohttp_jinja2
  26. import telethon
  27. from aiohttp import web
  28. import atexit
  29. import functools
  30. import logging
  31. import sys
  32. import re
  33. import requests
  34. import time
  35. from .. import utils, main, database, heroku
  36. from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
  37. from telethon.errors.rpcerrorlist import YouBlockedUserError, FloodWaitError
  38. from telethon.tl.functions.contacts import UnblockRequest
  39. DATA_DIR = (
  40. os.path.normpath(os.path.join(utils.get_base_dir(), ".."))
  41. if "OKTETO" not in os.environ and "DOCKER" not in os.environ
  42. else "/data"
  43. )
  44. def restart(*argv):
  45. os.execl(
  46. sys.executable,
  47. sys.executable,
  48. "-m",
  49. os.path.relpath(utils.get_base_dir()),
  50. *argv,
  51. )
  52. class Web:
  53. sign_in_clients = {}
  54. _pending_client = None
  55. _sessions = []
  56. _ratelimit = {}
  57. def __init__(self, **kwargs):
  58. self.api_token = kwargs.pop("api_token")
  59. self.data_root = kwargs.pop("data_root")
  60. self.connection = kwargs.pop("connection")
  61. self.proxy = kwargs.pop("proxy")
  62. super().__init__(**kwargs)
  63. self.app.router.add_get("/", self.root)
  64. self.app.router.add_put("/setApi", self.set_tg_api)
  65. self.app.router.add_post("/sendTgCode", self.send_tg_code)
  66. self.app.router.add_post("/check_session", self.check_session)
  67. self.app.router.add_post("/web_auth", self.web_auth)
  68. self.app.router.add_post("/okteto", self.okteto)
  69. self.app.router.add_post("/tgCode", self.tg_code)
  70. self.app.router.add_post("/finishLogin", self.finish_login)
  71. self.app.router.add_post("/custom_bot", self.custom_bot)
  72. self.api_set = asyncio.Event()
  73. self.clients_set = asyncio.Event()
  74. @aiohttp_jinja2.template("root.jinja2")
  75. async def root(self, request):
  76. return {
  77. "skip_creds": self.api_token is not None,
  78. "tg_done": bool(self.client_data),
  79. "okteto": "OKTETO" in os.environ,
  80. "lavhost": "LAVHOST" in os.environ,
  81. "heroku": "DYNO" in os.environ,
  82. }
  83. async def check_session(self, request):
  84. return web.Response(body=("1" if self._check_session(request) else "0"))
  85. def wait_for_api_token_setup(self):
  86. return self.api_set.wait()
  87. def wait_for_clients_setup(self):
  88. return self.clients_set.wait()
  89. def _check_session(self, request) -> bool:
  90. return (
  91. request.cookies.get("session", None) in self._sessions
  92. if main.hikka.clients
  93. else True
  94. )
  95. async def _check_bot(
  96. self,
  97. client: "TelegramClient", # type: ignore
  98. username: str,
  99. ) -> bool:
  100. async with client.conversation("@BotFather", exclusive=False) as conv:
  101. try:
  102. m = await conv.send_message("/token")
  103. except YouBlockedUserError:
  104. await client(UnblockRequest(id="@BotFather"))
  105. m = await conv.send_message("/token")
  106. r = await conv.get_response()
  107. await m.delete()
  108. await r.delete()
  109. if not hasattr(r, "reply_markup") or not hasattr(r.reply_markup, "rows"):
  110. return False
  111. for row in r.reply_markup.rows:
  112. for button in row.buttons:
  113. if username != button.text.strip("@"):
  114. continue
  115. m = await conv.send_message("/cancel")
  116. r = await conv.get_response()
  117. await m.delete()
  118. await r.delete()
  119. return True
  120. async def custom_bot(self, request):
  121. if not self._check_session(request):
  122. return web.Response(status=401)
  123. text = await request.text()
  124. client = self._pending_client
  125. db = database.Database(client)
  126. await db.init()
  127. text = text.strip("@")
  128. if any(
  129. litera not in (string.ascii_letters + string.digits + "_")
  130. for litera in text
  131. ) or not text.lower().endswith("bot"):
  132. return web.Response(body="OCCUPIED")
  133. try:
  134. await client.get_entity(f"@{text}")
  135. except ValueError:
  136. pass
  137. else:
  138. if not await self._check_bot(client, text):
  139. return web.Response(body="OCCUPIED")
  140. db.set("hikka.inline", "custom_bot", text)
  141. async def set_tg_api(self, request):
  142. if not self._check_session(request):
  143. return web.Response(status=401, body="Authorization required")
  144. text = await request.text()
  145. if len(text) < 36:
  146. return web.Response(
  147. status=400, body="API ID and HASH pair has invalid length"
  148. )
  149. api_id = text[32:]
  150. api_hash = text[:32]
  151. if any(c not in string.hexdigits for c in api_hash) or any(
  152. c not in string.digits for c in api_id
  153. ):
  154. return web.Response(
  155. status=400, body="You specified invalid API ID and/or API HASH"
  156. )
  157. if "DYNO" not in os.environ:
  158. # On Heroku it'll be saved later
  159. with open(
  160. os.path.join(self.data_root or DATA_DIR, "api_token.txt"),
  161. "w",
  162. ) as f:
  163. f.write(api_id + "\n" + api_hash)
  164. self.api_token = collections.namedtuple("api_token", ("ID", "HASH"))(
  165. api_id,
  166. api_hash,
  167. )
  168. self.api_set.set()
  169. return web.Response(body="ok")
  170. async def send_tg_code(self, request):
  171. if not self._check_session(request):
  172. return web.Response(status=401, body="Authorization required")
  173. text = await request.text()
  174. phone = telethon.utils.parse_phone(text)
  175. if not phone:
  176. return web.Response(status=400, body="Invalid phone number")
  177. client = telethon.TelegramClient(
  178. telethon.sessions.MemorySession(),
  179. self.api_token.ID,
  180. self.api_token.HASH,
  181. connection=self.connection,
  182. proxy=self.proxy,
  183. connection_retries=None,
  184. device_model="Hikka",
  185. )
  186. self._pending_client = client
  187. await client.connect()
  188. try:
  189. await client.send_code_request(phone)
  190. except FloodWaitError as e:
  191. return web.Response(
  192. status=429,
  193. body=f"You got FloodWait of {e.seconds}. Please try again later.",
  194. )
  195. return web.Response(body="ok")
  196. async def okteto(self, request):
  197. if main.get_config_key("okteto_uri"):
  198. return web.Response(status=418)
  199. text = await request.text()
  200. main.save_config_key("okteto_uri", text)
  201. return web.Response(body="URI_SAVED")
  202. async def tg_code(self, request):
  203. if not self._check_session(request):
  204. return web.Response(status=401)
  205. text = await request.text()
  206. if len(text) < 6:
  207. return web.Response(status=400)
  208. split = text.split("\n", 2)
  209. if len(split) not in (2, 3):
  210. return web.Response(status=400)
  211. code = split[0]
  212. phone = telethon.utils.parse_phone(split[1])
  213. password = split[2]
  214. if (
  215. (len(code) != 5 and not password)
  216. or any(c not in string.digits for c in code)
  217. or not phone
  218. ):
  219. return web.Response(status=400)
  220. if not password:
  221. try:
  222. await self._pending_client.sign_in(phone, code=code)
  223. except telethon.errors.SessionPasswordNeededError:
  224. return web.Response(
  225. status=401,
  226. body="2FA Password required",
  227. ) # Requires 2FA login
  228. except telethon.errors.PhoneCodeExpiredError:
  229. return web.Response(status=404, body="Code expired")
  230. except telethon.errors.PhoneCodeInvalidError:
  231. return web.Response(status=403, body="Invalid code")
  232. except telethon.errors.FloodWaitError as e:
  233. return web.Response(
  234. status=421,
  235. body=f"You got FloodWait of {e.seconds}. Please try again later.",
  236. )
  237. else:
  238. try:
  239. await self._pending_client.sign_in(phone, password=password)
  240. except telethon.errors.PasswordHashInvalidError:
  241. return web.Response(
  242. status=403,
  243. body="Invalid 2FA password",
  244. ) # Invalid 2FA password
  245. except telethon.errors.FloodWaitError as e:
  246. return web.Response(
  247. status=421,
  248. body=f"You got FloodWait of {e.seconds}. Please try again later.",
  249. )
  250. # At this step we don't want `main.hikka` to "know" about our client
  251. # so it doesn't create bot immediately. That's why we only save its session
  252. # in case user closes web early. It will be handled on restart
  253. # If user finishes login further, client will be passed to main
  254. # To prevent Heroku from restarting too soon, we'll do it after setting bot
  255. if "DYNO" not in os.environ:
  256. await main.hikka.save_client_session(self._pending_client)
  257. return web.Response()
  258. async def finish_login(self, request):
  259. if not self._check_session(request):
  260. return web.Response(status=401)
  261. if not self._pending_client:
  262. return web.Response(status=400)
  263. if "DYNO" in os.environ:
  264. app, config = heroku.get_app()
  265. config["api_id"] = self.api_token.ID
  266. config["api_hash"] = self.api_token.HASH
  267. await main.hikka.save_client_session(
  268. self._pending_client,
  269. heroku_config=config,
  270. heroku_app=app,
  271. )
  272. # We don't care what happens next, bc Heroku will restart anyway
  273. return
  274. first_session = not bool(main.hikka.clients)
  275. # Client is ready to pass in to dispatcher
  276. main.hikka.clients = list(set(main.hikka.clients + [self._pending_client]))
  277. self._pending_client = None
  278. self.clients_set.set()
  279. if not first_session:
  280. atexit.register(functools.partial(restart, *sys.argv[1:]))
  281. handler = logging.getLogger().handlers[0]
  282. handler.setLevel(logging.CRITICAL)
  283. for client in main.hikka.clients:
  284. await client.disconnect()
  285. sys.exit(0)
  286. return web.Response()
  287. async def web_auth(self, request):
  288. if self._check_session(request):
  289. return web.Response(body=request.cookies.get("session", "unauthorized"))
  290. token = utils.rand(8)
  291. markup = InlineKeyboardMarkup()
  292. markup.add(
  293. InlineKeyboardButton(
  294. "🔓 Authorize user",
  295. callback_data=f"authorize_web_{token}",
  296. )
  297. )
  298. ips = request.headers.get("X-FORWARDED-FOR", None) or request.remote
  299. cities = []
  300. for ip in re.findall(r"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}", ips):
  301. if ip not in self._ratelimit:
  302. self._ratelimit[ip] = []
  303. if (
  304. len(
  305. list(
  306. filter(lambda x: time.time() - x < 3 * 60, self._ratelimit[ip])
  307. )
  308. )
  309. >= 3
  310. ):
  311. return web.Response(status=429)
  312. self._ratelimit[ip] = list(
  313. filter(lambda x: time.time() - x < 3 * 60, self._ratelimit[ip])
  314. )
  315. self._ratelimit[ip] += [time.time()]
  316. try:
  317. res = (
  318. await utils.run_sync(
  319. requests.get,
  320. f"https://freegeoip.app/json/{ip}",
  321. )
  322. ).json()
  323. cities += [
  324. f"<i>{utils.get_lang_flag(res['country_code'])} {res['country_name']} {res['region_name']} {res['city']} {res['zip_code']}</i>"
  325. ]
  326. except Exception:
  327. pass
  328. cities = (
  329. ("<b>🏢 Possible cities:</b>\n\n" + "\n".join(cities) + "\n")
  330. if cities
  331. else ""
  332. )
  333. ops = []
  334. for user in self.client_data.values():
  335. try:
  336. bot = user[0].inline.bot
  337. msg = await bot.send_message(
  338. user[1].tg_id,
  339. "🌘🔐 <b>Click button below to confirm web application"
  340. f" ops</b>\n\n<b>Client IP</b>: {ips}\n{cities}\n<i>If you did not"
  341. " request any codes, simply ignore this message</i>",
  342. disable_web_page_preview=True,
  343. reply_markup=markup,
  344. )
  345. ops += [
  346. functools.partial(
  347. bot.delete_message,
  348. chat_id=msg.chat.id,
  349. message_id=msg.message_id,
  350. )
  351. ]
  352. except Exception:
  353. pass
  354. session = f"hikka_{utils.rand(16)}"
  355. if not ops:
  356. # If no auth message was sent, just leave it empty
  357. # probably, request was a bug and user doesn't have
  358. # inline bot or did not authorize any sessions
  359. return web.Response(body=session)
  360. if not await main.hikka.wait_for_web_auth(token):
  361. for op in ops:
  362. await op()
  363. return web.Response(body="TIMEOUT")
  364. for op in ops:
  365. await op()
  366. self._sessions += [session]
  367. return web.Response(body=session)