auth.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. # mautrix-instagram - A Matrix-Instagram puppeting bridge.
  2. # Copyright (C) 2023 Tulir Asokan
  3. #
  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. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU Affero General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU Affero General Public License
  15. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. from __future__ import annotations
  17. import hashlib
  18. import hmac
  19. from mauigpapi.errors import (
  20. IGBad2FACodeError,
  21. IGChallengeError,
  22. IGChallengeWrongCodeError,
  23. IGLoginBadPasswordError,
  24. IGLoginInvalidUserError,
  25. IGLoginTwoFactorRequiredError,
  26. )
  27. from mauigpapi.http import AndroidAPI
  28. from mauigpapi.state import AndroidState
  29. from mauigpapi.types import BaseResponseUser
  30. from mautrix.bridge.commands import HelpSection, command_handler
  31. from .. import user as u
  32. from .typehint import CommandEvent
  33. SECTION_AUTH = HelpSection("Authentication", 10, "")
  34. async def get_login_state(user: u.User, seed: str) -> tuple[AndroidAPI, AndroidState]:
  35. if user.command_status and user.command_status["action"] == "Login":
  36. api: AndroidAPI = user.command_status["api"]
  37. state: AndroidState = user.command_status["state"]
  38. else:
  39. state = AndroidState()
  40. seed = hmac.new(seed.encode("utf-8"), user.mxid.encode("utf-8"), hashlib.sha256).digest()
  41. state.device.generate(seed)
  42. api = AndroidAPI(state, log=user.api_log, proxy_handler=user.proxy_handler)
  43. user.command_status = {
  44. "action": "Login",
  45. "state": state,
  46. "api": api,
  47. }
  48. return api, state
  49. @command_handler(
  50. needs_auth=False,
  51. management_only=True,
  52. help_section=SECTION_AUTH,
  53. help_text="Log in to Instagram",
  54. help_args="<_username_> <_password_>",
  55. )
  56. async def login(evt: CommandEvent) -> None:
  57. if await evt.sender.is_logged_in():
  58. await evt.reply("You're already logged in")
  59. return
  60. elif len(evt.args) < 2:
  61. await evt.reply("**Usage:** `$cmdprefix+sp login <username> <password>`")
  62. return
  63. username = evt.args[0]
  64. password = " ".join(evt.args[1:])
  65. await evt.redact()
  66. api, state = await get_login_state(evt.sender, evt.config["instagram.device_seed"])
  67. try:
  68. resp = await api.login(username, password)
  69. except IGLoginTwoFactorRequiredError as e:
  70. tfa_info = e.body.two_factor_info
  71. msg = "Username and password accepted, but you have two-factor authentication enabled.\n"
  72. if tfa_info.totp_two_factor_on:
  73. msg += "Send the code from your authenticator app here."
  74. if tfa_info.sms_two_factor_on:
  75. msg += f" Alternatively, send `resend-sms` to get an SMS code to •••{tfa_info.obfuscated_phone_number}"
  76. elif tfa_info.sms_two_factor_on:
  77. msg += (
  78. f"Send the code sent to •••{tfa_info.obfuscated_phone_number} here."
  79. " You can also send `resend-sms` if you didn't receive the code."
  80. )
  81. else:
  82. msg += (
  83. "Unfortunately, none of your two-factor authentication methods are currently "
  84. "supported by the bridge."
  85. )
  86. return
  87. evt.sender.command_status = {
  88. **evt.sender.command_status,
  89. "next": enter_login_2fa,
  90. "username": tfa_info.username,
  91. "is_totp": tfa_info.totp_two_factor_on,
  92. "has_sms": tfa_info.sms_two_factor_on,
  93. "2fa_identifier": tfa_info.two_factor_identifier,
  94. }
  95. await evt.reply(msg)
  96. except IGChallengeError:
  97. await evt.reply(
  98. "Login challenges aren't currently supported. "
  99. "Please set up real two-factor authentication."
  100. )
  101. await api.challenge_auto()
  102. evt.sender.command_status = {
  103. **evt.sender.command_status,
  104. "next": enter_login_security_code,
  105. }
  106. await evt.reply(
  107. "Username and password accepted, but Instagram wants to verify it's really"
  108. " you. Please confirm the login and enter the security code here."
  109. )
  110. except IGLoginInvalidUserError:
  111. await evt.reply("Invalid username")
  112. except IGLoginBadPasswordError:
  113. await evt.reply("Incorrect password")
  114. except Exception as e:
  115. evt.log.exception("Failed to log in")
  116. await evt.reply(f"Failed to log in: {e}")
  117. else:
  118. await _post_login(evt, state, resp.logged_in_user)
  119. async def enter_login_2fa(evt: CommandEvent) -> None:
  120. api: AndroidAPI = evt.sender.command_status["api"]
  121. state: AndroidState = evt.sender.command_status["state"]
  122. identifier = evt.sender.command_status["2fa_identifier"]
  123. username = evt.sender.command_status["username"]
  124. is_totp = evt.sender.command_status["is_totp"]
  125. has_sms = evt.sender.command_status["has_sms"]
  126. code = "".join(evt.args).lower()
  127. if has_sms and code == "resend-sms":
  128. try:
  129. resp = await api.send_two_factor_login_sms(username, identifier=identifier)
  130. except Exception as e:
  131. evt.log.exception("Failed to re-request SMS code")
  132. await evt.reply(f"Failed to re-request SMS code: {e}")
  133. else:
  134. await evt.reply(
  135. f"Re-requested SMS code to {resp.two_factor_info.obfuscated_phone_number}"
  136. )
  137. evt.sender.command_status[
  138. "2fa_identifier"
  139. ] = resp.two_factor_info.two_factor_identifier
  140. evt.sender.command_status["is_totp"] = False
  141. return
  142. try:
  143. resp = await api.two_factor_login(
  144. username, code=code, identifier=identifier, is_totp=is_totp
  145. )
  146. except IGBad2FACodeError:
  147. await evt.reply(
  148. "Invalid 2-factor authentication code. Please try again "
  149. "or use `$cmdprefix+sp cancel` to cancel."
  150. )
  151. except IGChallengeError:
  152. await api.challenge_auto(reset=True)
  153. evt.sender.command_status = {
  154. **evt.sender.command_status,
  155. "next": enter_login_security_code,
  156. }
  157. await evt.reply(
  158. "2-factor authentication code accepted, but Instagram wants to verify it's"
  159. " really you. Please confirm the login and enter the security code here."
  160. )
  161. except Exception as e:
  162. evt.log.exception("Failed to log in")
  163. await evt.reply(f"Failed to log in: {e}")
  164. evt.sender.command_status = None
  165. else:
  166. evt.sender.command_status = None
  167. await _post_login(evt, state, resp.logged_in_user)
  168. async def enter_login_security_code(evt: CommandEvent) -> None:
  169. api: AndroidAPI = evt.sender.command_status["api"]
  170. state: AndroidState = evt.sender.command_status["state"]
  171. try:
  172. resp = await api.challenge_send_security_code("".join(evt.args))
  173. except IGChallengeWrongCodeError as e:
  174. await evt.reply(f"Incorrect security code: {e}")
  175. except Exception as e:
  176. evt.log.exception("Failed to log in")
  177. await evt.reply(f"Failed to log in: {e}")
  178. evt.sender.command_status = None
  179. else:
  180. if not resp.logged_in_user:
  181. evt.log.error(
  182. f"Didn't get logged_in_user in challenge response "
  183. f"after entering security code: {resp.serialize()}"
  184. )
  185. await evt.reply("An unknown error occurred. Please check the bridge logs.")
  186. return
  187. evt.sender.command_status = None
  188. await _post_login(evt, state, resp.logged_in_user)
  189. async def _post_login(evt: CommandEvent, state: AndroidState, user: BaseResponseUser) -> None:
  190. evt.sender.state = state
  191. pl = state.device.payload
  192. manufacturer, model = pl["manufacturer"], pl["model"]
  193. await evt.reply(
  194. f"Successfully logged in as {user.full_name} ([@{user.username}]"
  195. f"(https://instagram.com/{user.username}), user ID: {user.pk}).\n\n"
  196. f"The bridge will show up on Instagram as {manufacturer} {model}."
  197. )
  198. await evt.sender.try_connect()
  199. @command_handler(
  200. needs_auth=True,
  201. help_section=SECTION_AUTH,
  202. help_text="Disconnect the bridge from your Instagram account",
  203. )
  204. async def logout(evt: CommandEvent) -> None:
  205. await evt.sender.logout()
  206. await evt.reply("Successfully logged out")