auth.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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 AuthorizationFailedError, TimeoutException, UnexpectedResponse
  19. from mautrix.appservice import IntentAPI
  20. from mautrix.bridge.commands import HelpSection, command_handler
  21. from mautrix.types import EventID, ImageInfo, MediaMessageEventContent, MessageType, UserID
  22. from .. import puppet as pu
  23. from ..util import normalize_number
  24. from .typehint import CommandEvent
  25. try:
  26. import PIL as _
  27. import qrcode
  28. except ImportError:
  29. qrcode = None
  30. SECTION_AUTH = HelpSection("Authentication", 10, "")
  31. async def make_qr(
  32. intent: IntentAPI, data: Union[str, bytes], body: str = None
  33. ) -> MediaMessageEventContent:
  34. # TODO always encrypt QR codes?
  35. buffer = io.BytesIO()
  36. image = qrcode.make(data)
  37. size = image.pixel_size
  38. image.save(buffer, "PNG")
  39. qr = buffer.getvalue()
  40. mxc = await intent.upload_media(qr, "image/png", "qr.png", len(qr))
  41. return MediaMessageEventContent(
  42. body=body or data,
  43. url=mxc,
  44. msgtype=MessageType.IMAGE,
  45. info=ImageInfo(mimetype="image/png", size=len(qr), width=size, height=size),
  46. )
  47. @command_handler(
  48. needs_auth=False,
  49. management_only=True,
  50. needs_admin=True,
  51. help_section=SECTION_AUTH,
  52. help_text="Connect to an existing account on signald",
  53. help_args="[mxid] <phone number>",
  54. )
  55. async def connect_existing(evt: CommandEvent) -> EventID:
  56. if len(evt.args) == 0:
  57. return await evt.reply("**Usage:** `$cmdprefix+sp connect-existing [mxid] <phone number>`")
  58. if evt.args[0].startswith("@"):
  59. evt.sender = await evt.bridge.get_user(UserID(evt.args[0]))
  60. evt.args = evt.args[1:]
  61. if await evt.sender.is_logged_in():
  62. return await evt.reply(
  63. "You're already logged in. "
  64. "If you want to relink, log out with `$cmdprefix+sp logout` first."
  65. )
  66. try:
  67. account_id = normalize_number("".join(evt.args))
  68. except Exception:
  69. return await evt.reply("Please enter the phone number in international format (E.164)")
  70. accounts = await evt.bridge.signal.list_accounts()
  71. for account in accounts:
  72. if account.account_id == account_id:
  73. await evt.sender.on_signin(account)
  74. return await evt.reply(
  75. f"Successfully logged in as {pu.Puppet.fmt_phone(evt.sender.username)} "
  76. f"(device #{account.device_id})"
  77. )
  78. return await evt.reply(f"Account with ID {account_id} not found in signald")
  79. @command_handler(
  80. needs_auth=False,
  81. management_only=True,
  82. help_section=SECTION_AUTH,
  83. help_text="Link the bridge as a secondary device",
  84. help_args="[device name]",
  85. )
  86. async def link(evt: CommandEvent) -> None:
  87. if qrcode is None:
  88. await evt.reply("Can't generate QR code: qrcode and/or PIL not installed")
  89. return
  90. if await evt.sender.is_logged_in():
  91. await evt.reply(
  92. "You're already logged in. "
  93. "If you want to relink, log out with `$cmdprefix+sp logout` first."
  94. )
  95. return
  96. # TODO make default device name configurable
  97. device_name = " ".join(evt.args) or "Mautrix-Signal bridge"
  98. sess = await evt.bridge.signal.start_link()
  99. content = await make_qr(evt.az.intent, sess.uri)
  100. event_id = await evt.az.intent.send_message(evt.room_id, content)
  101. try:
  102. account = await evt.bridge.signal.finish_link(
  103. session_id=sess.session_id, overwrite=True, device_name=device_name
  104. )
  105. except TimeoutException:
  106. await evt.reply("Linking timed out, please try again.")
  107. except Exception:
  108. evt.log.exception("Fatal error while waiting for linking to finish")
  109. await evt.reply(
  110. "Fatal error while waiting for linking to finish (see logs for more details)"
  111. )
  112. else:
  113. await evt.sender.on_signin(account)
  114. await evt.reply(
  115. f"Successfully logged in as {pu.Puppet.fmt_phone(evt.sender.username)} "
  116. f"(device #{account.device_id})"
  117. )
  118. finally:
  119. await evt.main_intent.redact(evt.room_id, event_id)
  120. @command_handler(
  121. needs_auth=False,
  122. management_only=True,
  123. help_section=SECTION_AUTH,
  124. is_enabled_for=lambda evt: evt.config["signal.registration_enabled"],
  125. help_text="Sign into Signal as the primary device",
  126. help_args="<phone>",
  127. )
  128. async def register(evt: CommandEvent) -> None:
  129. if len(evt.args) == 0:
  130. await evt.reply("**Usage**: $cmdprefix+sp register [--voice] [--captcha <token>] <phone>")
  131. return
  132. if await evt.sender.is_logged_in():
  133. await evt.reply(
  134. "You're already logged in. "
  135. "If you want to re-register, log out with `$cmdprefix+sp logout` first."
  136. )
  137. return
  138. voice = False
  139. captcha = None
  140. while True:
  141. flag = evt.args[0].lower()
  142. if flag == "--voice" or flag == "-v":
  143. voice = True
  144. evt.args = evt.args[1:]
  145. elif flag == "--captcha" or flag == "-c":
  146. if "=" in evt.args[0]:
  147. captcha = evt.args[0].split("=", 1)[1]
  148. evt.args = evt.args[1:]
  149. else:
  150. captcha = evt.args[1]
  151. evt.args = evt.args[2:]
  152. else:
  153. break
  154. try:
  155. phone = normalize_number(evt.args[0])
  156. except Exception:
  157. await evt.reply("Please enter the phone number in international format (E.164)")
  158. return
  159. username = await evt.bridge.signal.register(phone, voice=voice, captcha=captcha)
  160. evt.sender.command_status = {
  161. "action": "Register",
  162. "room_id": evt.room_id,
  163. "next": enter_register_code,
  164. "username": username,
  165. }
  166. await evt.reply("Register SMS requested, please enter the code here.")
  167. async def enter_register_code(evt: CommandEvent) -> None:
  168. try:
  169. username = evt.sender.command_status["username"]
  170. account = await evt.bridge.signal.verify(username, code=evt.args[0])
  171. except UnexpectedResponse as e:
  172. if e.resp_type == "error":
  173. await evt.reply(e.data)
  174. else:
  175. raise
  176. else:
  177. await evt.sender.on_signin(account)
  178. await evt.reply(
  179. f"Successfully logged in as {pu.Puppet.fmt_phone(evt.sender.username)}."
  180. f"\n\n**N.B.** You must set a Signal profile name with `$cmdprefix+sp "
  181. f"set-profile-name <name>` before you can participate in new groups."
  182. )
  183. @command_handler(
  184. needs_auth=True,
  185. management_only=True,
  186. help_section=SECTION_AUTH,
  187. help_text="Remove all local data about your Signal link",
  188. )
  189. async def logout(evt: CommandEvent) -> None:
  190. if not evt.sender.username:
  191. await evt.reply("You're not logged in")
  192. return
  193. await evt.sender.logout()
  194. await evt.reply("Successfully logged out")
  195. @command_handler(
  196. needs_auth=True,
  197. management_only=True,
  198. help_section=SECTION_AUTH,
  199. help_text="List devices linked to your Signal account",
  200. )
  201. async def list_devices(evt: CommandEvent) -> None:
  202. devices = await evt.bridge.signal.get_linked_devices(evt.sender.username)
  203. await evt.reply(
  204. "\n".join(
  205. f"* #{dev.id}: {dev.name_with_default} (created {dev.created_fmt}, last seen "
  206. f"{dev.last_seen_fmt})"
  207. for dev in devices
  208. )
  209. )
  210. @command_handler(
  211. needs_auth=True,
  212. management_only=True,
  213. help_section=SECTION_AUTH,
  214. help_text="Remove a linked device",
  215. )
  216. async def remove_linked_device(evt: CommandEvent) -> EventID:
  217. if len(evt.args) == 0:
  218. return await evt.reply("**Usage:** `$cmdprefix+sp remove-linked-device <device ID>`")
  219. device_id = int(evt.args[0])
  220. try:
  221. await evt.bridge.signal.remove_linked_device(evt.sender.username, device_id)
  222. except AuthorizationFailedError as e:
  223. return await evt.reply(f"{e} Only the primary device can remove linked devices.")
  224. return await evt.reply("Device removed")