auth.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. # mautrix-signal - A Matrix-Signal puppeting bridge
  2. # Copyright (C) 2020 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 typing import Union
  17. import io
  18. from mausignald.errors import UnexpectedResponse, TimeoutException
  19. from mautrix.client import Client
  20. from mautrix.bridge import custom_puppet as cpu
  21. from mautrix.appservice import IntentAPI
  22. from mautrix.types import MediaMessageEventContent, MessageType, ImageInfo
  23. from mautrix.bridge.commands import HelpSection, command_handler
  24. from .. import puppet as pu
  25. from .typehint import CommandEvent
  26. try:
  27. import qrcode
  28. import PIL as _
  29. except ImportError:
  30. qrcode = None
  31. SECTION_AUTH = HelpSection("Authentication", 10, "")
  32. remove_extra_chars = str.maketrans("", "", " .,-()")
  33. async def make_qr(intent: IntentAPI, data: Union[str, bytes], body: str = None
  34. ) -> MediaMessageEventContent:
  35. # TODO always encrypt QR codes?
  36. buffer = io.BytesIO()
  37. image = qrcode.make(data)
  38. size = image.pixel_size
  39. image.save(buffer, "PNG")
  40. qr = buffer.getvalue()
  41. mxc = await intent.upload_media(qr, "image/png", "qr.png", len(qr))
  42. return MediaMessageEventContent(body=body or data, url=mxc, msgtype=MessageType.IMAGE,
  43. info=ImageInfo(mimetype="image/png", size=len(qr),
  44. width=size, height=size))
  45. @command_handler(needs_auth=False, management_only=True, help_section=SECTION_AUTH,
  46. help_text="Link the bridge as a secondary device", help_args="[device name]")
  47. async def link(evt: CommandEvent) -> None:
  48. if qrcode is None:
  49. await evt.reply("Can't generate QR code: qrcode and/or PIL not installed")
  50. return
  51. # TODO make default device name configurable
  52. device_name = " ".join(evt.args) or "Mautrix-Signal bridge"
  53. sess = await evt.bridge.signal.start_link()
  54. content = await make_qr(evt.az.intent, sess.uri)
  55. event_id = await evt.az.intent.send_message(evt.room_id, content)
  56. try:
  57. account = await evt.bridge.signal.finish_link(session_id=sess.session_id,
  58. device_name=device_name)
  59. except TimeoutException:
  60. await evt.reply("Linking timed out, please try again.")
  61. except Exception:
  62. evt.log.exception("Fatal error while waiting for linking to finish")
  63. await evt.reply("Fatal error while waiting for linking to finish "
  64. "(see logs for more details)")
  65. else:
  66. await evt.sender.on_signin(account)
  67. await evt.reply(f"Successfully logged in as {pu.Puppet.fmt_phone(evt.sender.username)}")
  68. finally:
  69. await evt.main_intent.redact(evt.room_id, event_id)
  70. @command_handler(needs_auth=False, management_only=True, help_section=SECTION_AUTH,
  71. help_text="Sign into Signal as the primary device", help_args="<phone>")
  72. async def register(evt: CommandEvent) -> None:
  73. if len(evt.args) == 0:
  74. await evt.reply("**Usage**: $cmdprefix+sp register [--voice] <phone>")
  75. return
  76. voice = False
  77. captcha = None
  78. while True:
  79. flag = evt.args[0].lower()
  80. if flag == "--voice" or flag == "-v":
  81. voice = True
  82. evt.args = evt.args[1:]
  83. elif flag == "--captcha" or flag == "-c":
  84. if "=" in evt.args[0]:
  85. captcha = evt.args[0].split("=", 1)[1]
  86. evt.args = evt.args[1:]
  87. else:
  88. captcha = evt.args[1]
  89. evt.args = evt.args[2:]
  90. else:
  91. break
  92. phone = evt.args[0].translate(remove_extra_chars)
  93. if not phone.startswith("+") or not phone[1:].isdecimal():
  94. await evt.reply(f"Please enter the phone number in international format (E.164)")
  95. return
  96. username = await evt.bridge.signal.register(phone, voice=voice, captcha=captcha)
  97. evt.sender.command_status = {
  98. "action": "Register",
  99. "room_id": evt.room_id,
  100. "next": enter_register_code,
  101. "username": username,
  102. }
  103. await evt.reply("Register SMS requested, please enter the code here.")
  104. async def enter_register_code(evt: CommandEvent) -> None:
  105. try:
  106. username = evt.sender.command_status["username"]
  107. account = await evt.bridge.signal.verify(username, code=evt.args[0])
  108. except UnexpectedResponse as e:
  109. if e.resp_type == "error":
  110. await evt.reply(e.data)
  111. else:
  112. raise
  113. else:
  114. await evt.sender.on_signin(account)
  115. await evt.reply(f"Successfully logged in as {pu.Puppet.fmt_phone(evt.sender.username)}."
  116. f"\n\n**N.B.** You must set a Signal profile name with `$cmdprefix+sp "
  117. f"set-profile-name <name>` before you can participate in new groups.")
  118. @command_handler(needs_auth=True, management_only=True, help_section=SECTION_AUTH,
  119. help_text="Remove all local data about your Signal link")
  120. async def logout(evt: CommandEvent) -> None:
  121. if not evt.sender.username:
  122. await evt.reply("You're not logged in")
  123. return
  124. await evt.sender.logout()
  125. await evt.reply("Successfully logged out")
  126. @command_handler(needs_auth=True, management_only=True, help_args="<_access token_>",
  127. help_section=SECTION_AUTH, help_text="Replace your Signal account's Matrix puppet"
  128. " with your Matrix account")
  129. async def login_matrix(evt: CommandEvent) -> None:
  130. puppet = await pu.Puppet.get_by_address(evt.sender.address)
  131. _, homeserver = Client.parse_mxid(evt.sender.mxid)
  132. if homeserver != pu.Puppet.hs_domain:
  133. await evt.reply("You can't log in with an account on a different homeserver")
  134. return
  135. try:
  136. await puppet.switch_mxid(" ".join(evt.args), evt.sender.mxid)
  137. await evt.reply("Successfully replaced your Signal account's "
  138. "Matrix puppet with your Matrix account.")
  139. except cpu.OnlyLoginSelf:
  140. await evt.reply("You may only log in with your own Matrix account")
  141. except cpu.InvalidAccessToken:
  142. await evt.reply("Invalid access token")
  143. @command_handler(needs_auth=True, management_only=True, help_section=SECTION_AUTH,
  144. help_text="Revert your Signal account's Matrix puppet to the original")
  145. async def logout_matrix(evt: CommandEvent) -> None:
  146. puppet = await pu.Puppet.get_by_address(evt.sender.address)
  147. if not puppet.is_real_user:
  148. await evt.reply("You're not logged in with your Matrix account")
  149. return
  150. await puppet.switch_mxid(None, None)
  151. await evt.reply("Restored the original puppet for your Signal account")