auth.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. # mautrix-instagram - A Matrix-Instagram puppeting bridge.
  2. # Copyright (C) 2022 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. IGChallengeWrongCodeError,
  22. IGCheckpointError,
  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(
  35. user: u.User, username: str, seed: str
  36. ) -> tuple[AndroidAPI, AndroidState]:
  37. if user.command_status and user.command_status["action"] == "Login":
  38. api: AndroidAPI = user.command_status["api"]
  39. state: AndroidState = user.command_status["state"]
  40. else:
  41. state = AndroidState()
  42. seed = hmac.new(seed.encode("utf-8"), username.encode("utf-8"), hashlib.sha256).digest()
  43. state.device.generate(seed)
  44. api = AndroidAPI(state, log=user.api_log)
  45. await api.qe_sync_login_experiments()
  46. user.command_status = {
  47. "action": "Login",
  48. "state": state,
  49. "api": api,
  50. }
  51. return api, state
  52. @command_handler(
  53. needs_auth=False,
  54. management_only=True,
  55. help_section=SECTION_AUTH,
  56. help_text="Log in to Instagram",
  57. help_args="<_username_> <_password_>",
  58. )
  59. async def login(evt: CommandEvent) -> None:
  60. if await evt.sender.is_logged_in():
  61. await evt.reply("You're already logged in")
  62. return
  63. elif len(evt.args) < 2:
  64. await evt.reply("**Usage:** `$cmdprefix+sp login <username> <password>`")
  65. return
  66. username = evt.args[0]
  67. password = " ".join(evt.args[1:])
  68. api, state = await get_login_state(evt.sender, username, evt.config["instagram.device_seed"])
  69. try:
  70. resp = await api.login(username, password)
  71. except IGLoginTwoFactorRequiredError as e:
  72. tfa_info = e.body.two_factor_info
  73. msg = "Username and password accepted, but you have two-factor authentication enabled.\n"
  74. if tfa_info.totp_two_factor_on:
  75. msg += "Send the code from your authenticator app here."
  76. elif tfa_info.sms_two_factor_on:
  77. msg += f"Send the code sent to {tfa_info.obfuscated_phone_number} here."
  78. else:
  79. msg += (
  80. "Unfortunately, none of your two-factor authentication methods are currently "
  81. "supported by the bridge."
  82. )
  83. return
  84. evt.sender.command_status = {
  85. **evt.sender.command_status,
  86. "next": enter_login_2fa,
  87. "username": tfa_info.username,
  88. "is_totp": tfa_info.totp_two_factor_on,
  89. "2fa_identifier": tfa_info.two_factor_identifier,
  90. }
  91. await evt.reply(msg)
  92. except IGCheckpointError:
  93. await api.challenge_auto(reset=True)
  94. evt.sender.command_status = {
  95. **evt.sender.command_status,
  96. "next": enter_login_security_code,
  97. }
  98. await evt.reply(
  99. "Username and password accepted, but Instagram wants to verify it's really"
  100. " you. Please confirm the login and enter the security code here."
  101. )
  102. except IGLoginInvalidUserError:
  103. await evt.reply("Invalid username")
  104. except IGLoginBadPasswordError:
  105. await evt.reply("Incorrect password")
  106. except Exception as e:
  107. evt.log.exception("Failed to log in")
  108. await evt.reply(f"Failed to log in: {e}")
  109. else:
  110. await _post_login(evt, state, resp.logged_in_user)
  111. async def enter_login_2fa(evt: CommandEvent) -> None:
  112. api: AndroidAPI = evt.sender.command_status["api"]
  113. state: AndroidState = evt.sender.command_status["state"]
  114. identifier = evt.sender.command_status["2fa_identifier"]
  115. username = evt.sender.command_status["username"]
  116. is_totp = evt.sender.command_status["is_totp"]
  117. try:
  118. resp = await api.two_factor_login(
  119. username, code="".join(evt.args), identifier=identifier, is_totp=is_totp
  120. )
  121. except IGBad2FACodeError:
  122. await evt.reply(
  123. "Invalid 2-factor authentication code. Please try again "
  124. "or use `$cmdprefix+sp cancel` to cancel."
  125. )
  126. except IGCheckpointError:
  127. await api.challenge_auto(reset=True)
  128. evt.sender.command_status = {
  129. **evt.sender.command_status,
  130. "next": enter_login_security_code,
  131. }
  132. await evt.reply(
  133. "2-factor authentication code accepted, but Instagram wants to verify it's"
  134. " really you. Please confirm the login and enter the security code here."
  135. )
  136. except Exception as e:
  137. evt.log.exception("Failed to log in")
  138. await evt.reply(f"Failed to log in: {e}")
  139. evt.sender.command_status = None
  140. else:
  141. evt.sender.command_status = None
  142. await _post_login(evt, state, resp.logged_in_user)
  143. async def enter_login_security_code(evt: CommandEvent) -> None:
  144. api: AndroidAPI = evt.sender.command_status["api"]
  145. state: AndroidState = evt.sender.command_status["state"]
  146. try:
  147. resp = await api.challenge_send_security_code("".join(evt.args))
  148. except IGChallengeWrongCodeError as e:
  149. await evt.reply(f"Incorrect security code: {e}")
  150. except Exception as e:
  151. evt.log.exception("Failed to log in")
  152. await evt.reply(f"Failed to log in: {e}")
  153. evt.sender.command_status = None
  154. else:
  155. if not resp.logged_in_user:
  156. evt.log.error(
  157. f"Didn't get logged_in_user in challenge response "
  158. f"after entering security code: {resp.serialize()}"
  159. )
  160. await evt.reply("An unknown error occurred. Please check the bridge logs.")
  161. return
  162. evt.sender.command_status = None
  163. await _post_login(evt, state, resp.logged_in_user)
  164. async def _post_login(evt: CommandEvent, state: AndroidState, user: BaseResponseUser) -> None:
  165. evt.sender.state = state
  166. pl = state.device.payload
  167. manufacturer, model = pl["manufacturer"], pl["model"]
  168. await evt.reply(
  169. f"Successfully logged in as {user.full_name} ([@{user.username}]"
  170. f"(https://instagram.com/{user.username}), user ID: {user.pk}).\n\n"
  171. f"The bridge will show up on Instagram as {manufacturer} {model}."
  172. )
  173. await evt.sender.try_connect()
  174. @command_handler(
  175. needs_auth=True,
  176. help_section=SECTION_AUTH,
  177. help_text="Disconnect the bridge from your Instagram account",
  178. )
  179. async def logout(evt: CommandEvent) -> None:
  180. await evt.sender.logout()
  181. await evt.reply("Successfully logged out")