root.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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, _):
  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. return web.Response(body="OK")
  142. async def set_tg_api(self, request):
  143. if not self._check_session(request):
  144. return web.Response(status=401, body="Authorization required")
  145. text = await request.text()
  146. if len(text) < 36:
  147. return web.Response(
  148. status=400,
  149. body="API ID and HASH pair has invalid length",
  150. )
  151. api_id = text[32:]
  152. api_hash = text[:32]
  153. if any(c not in string.hexdigits for c in api_hash) or any(
  154. c not in string.digits for c in api_id
  155. ):
  156. return web.Response(
  157. status=400,
  158. body="You specified invalid API ID and/or API HASH",
  159. )
  160. if "DYNO" not in os.environ:
  161. # On Heroku it'll be saved later
  162. with open(
  163. os.path.join(self.data_root or DATA_DIR, "api_token.txt"),
  164. "w",
  165. ) as f:
  166. f.write(api_id + "\n" + api_hash)
  167. self.api_token = collections.namedtuple("api_token", ("ID", "HASH"))(
  168. api_id,
  169. api_hash,
  170. )
  171. self.api_set.set()
  172. return web.Response(body="ok")
  173. async def send_tg_code(self, request):
  174. if not self._check_session(request):
  175. return web.Response(status=401, body="Authorization required")
  176. text = await request.text()
  177. phone = telethon.utils.parse_phone(text)
  178. if not phone:
  179. return web.Response(status=400, body="Invalid phone number")
  180. client = telethon.TelegramClient(
  181. telethon.sessions.MemorySession(),
  182. self.api_token.ID,
  183. self.api_token.HASH,
  184. connection=self.connection,
  185. proxy=self.proxy,
  186. connection_retries=None,
  187. device_model="Hikka",
  188. )
  189. self._pending_client = client
  190. await client.connect()
  191. try:
  192. await client.send_code_request(phone)
  193. except FloodWaitError as e:
  194. return web.Response(
  195. status=429,
  196. body=(
  197. f"You got FloodWait of {e.seconds} seconds. Wait the specified"
  198. " amount of time and try again."
  199. ),
  200. )
  201. return web.Response(body="ok")
  202. async def okteto(self, request):
  203. if main.get_config_key("okteto_uri"):
  204. return web.Response(status=418)
  205. text = await request.text()
  206. main.save_config_key("okteto_uri", text)
  207. return web.Response(body="URI_SAVED")
  208. async def tg_code(self, request):
  209. if not self._check_session(request):
  210. return web.Response(status=401)
  211. text = await request.text()
  212. if len(text) < 6:
  213. return web.Response(status=400)
  214. split = text.split("\n", 2)
  215. if len(split) not in (2, 3):
  216. return web.Response(status=400)
  217. code = split[0]
  218. phone = telethon.utils.parse_phone(split[1])
  219. password = split[2]
  220. if (
  221. (len(code) != 5 and not password)
  222. or any(c not in string.digits for c in code)
  223. or not phone
  224. ):
  225. return web.Response(status=400)
  226. if not password:
  227. try:
  228. await self._pending_client.sign_in(phone, code=code)
  229. except telethon.errors.SessionPasswordNeededError:
  230. return web.Response(
  231. status=401,
  232. body="2FA Password required",
  233. ) # Requires 2FA login
  234. except telethon.errors.PhoneCodeExpiredError:
  235. return web.Response(status=404, body="Code expired")
  236. except telethon.errors.PhoneCodeInvalidError:
  237. return web.Response(status=403, body="Invalid code")
  238. except telethon.errors.FloodWaitError as e:
  239. return web.Response(
  240. status=421,
  241. body=(
  242. f"You got FloodWait of {e.seconds} seconds. Wait the specified"
  243. " amount of time and try again."
  244. ),
  245. )
  246. else:
  247. try:
  248. await self._pending_client.sign_in(phone, password=password)
  249. except telethon.errors.PasswordHashInvalidError:
  250. return web.Response(
  251. status=403,
  252. body="Invalid 2FA password",
  253. ) # Invalid 2FA password
  254. except telethon.errors.FloodWaitError as e:
  255. return web.Response(
  256. status=421,
  257. body=(
  258. f"You got FloodWait of {e.seconds} seconds. Wait the specified"
  259. " amount of time and try again."
  260. ),
  261. )
  262. # At this step we don't want `main.hikka` to "know" about our client
  263. # so it doesn't create bot immediately. That's why we only save its session
  264. # in case user closes web early. It will be handled on restart
  265. # If user finishes login further, client will be passed to main
  266. # To prevent Heroku from restarting too soon, we'll do it after setting bot
  267. if "DYNO" not in os.environ:
  268. await main.hikka.save_client_session(self._pending_client)
  269. return web.Response()
  270. async def finish_login(self, request):
  271. if not self._check_session(request):
  272. return web.Response(status=401)
  273. if not self._pending_client:
  274. return web.Response(status=400)
  275. if "DYNO" in os.environ:
  276. app, config = heroku.get_app()
  277. config["api_id"] = self.api_token.ID
  278. config["api_hash"] = self.api_token.HASH
  279. await main.hikka.save_client_session(
  280. self._pending_client,
  281. heroku_config=config,
  282. heroku_app=app,
  283. )
  284. # We don't care what happens next, bc Heroku will restart anyway
  285. return
  286. first_session = not bool(main.hikka.clients)
  287. # Client is ready to pass in to dispatcher
  288. main.hikka.clients = list(set(main.hikka.clients + [self._pending_client]))
  289. self._pending_client = None
  290. self.clients_set.set()
  291. if not first_session:
  292. atexit.register(functools.partial(restart, *sys.argv[1:]))
  293. handler = logging.getLogger().handlers[0]
  294. handler.setLevel(logging.CRITICAL)
  295. for client in main.hikka.clients:
  296. await client.disconnect()
  297. sys.exit(0)
  298. return web.Response()
  299. async def web_auth(self, request):
  300. if self._check_session(request):
  301. return web.Response(body=request.cookies.get("session", "unauthorized"))
  302. token = utils.rand(8)
  303. markup = InlineKeyboardMarkup()
  304. markup.add(
  305. InlineKeyboardButton(
  306. "🔓 Authorize user",
  307. callback_data=f"authorize_web_{token}",
  308. )
  309. )
  310. ips = request.headers.get("X-FORWARDED-FOR", None) or request.remote
  311. cities = []
  312. for ip in re.findall(r"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}", ips):
  313. if ip not in self._ratelimit:
  314. self._ratelimit[ip] = []
  315. if (
  316. len(
  317. list(
  318. filter(lambda x: time.time() - x < 3 * 60, self._ratelimit[ip])
  319. )
  320. )
  321. >= 3
  322. ):
  323. return web.Response(status=429)
  324. self._ratelimit[ip] = list(
  325. filter(lambda x: time.time() - x < 3 * 60, self._ratelimit[ip])
  326. )
  327. self._ratelimit[ip] += [time.time()]
  328. try:
  329. res = (
  330. await utils.run_sync(
  331. requests.get,
  332. f"https://freegeoip.app/json/{ip}",
  333. )
  334. ).json()
  335. cities += [
  336. f"<i>{utils.get_lang_flag(res['country_code'])} {res['country_name']} {res['region_name']} {res['city']} {res['zip_code']}</i>"
  337. ]
  338. except Exception:
  339. pass
  340. cities = (
  341. ("<b>🏢 Possible cities:</b>\n\n" + "\n".join(cities) + "\n")
  342. if cities
  343. else ""
  344. )
  345. ops = []
  346. for user in self.client_data.values():
  347. try:
  348. bot = user[0].inline.bot
  349. msg = await bot.send_message(
  350. user[1].tg_id,
  351. "🌘🔐 <b>Click button below to confirm web application"
  352. f" ops</b>\n\n<b>Client IP</b>: {ips}\n{cities}\n<i>If you did not"
  353. " request any codes, simply ignore this message</i>",
  354. disable_web_page_preview=True,
  355. reply_markup=markup,
  356. )
  357. ops += [
  358. functools.partial(
  359. bot.delete_message,
  360. chat_id=msg.chat.id,
  361. message_id=msg.message_id,
  362. )
  363. ]
  364. except Exception:
  365. pass
  366. session = f"hikka_{utils.rand(16)}"
  367. if not ops:
  368. # If no auth message was sent, just leave it empty
  369. # probably, request was a bug and user doesn't have
  370. # inline bot or did not authorize any sessions
  371. return web.Response(body=session)
  372. if not await main.hikka.wait_for_web_auth(token):
  373. for op in ops:
  374. await op()
  375. return web.Response(body="TIMEOUT")
  376. for op in ops:
  377. await op()
  378. self._sessions += [session]
  379. return web.Response(body=session)