auth.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  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. import io
  17. from mausignald.errors import UnexpectedResponse
  18. from mautrix.client import Client
  19. from mautrix.bridge import custom_puppet as cpu
  20. from mautrix.types import MediaMessageEventContent, MessageType, ImageInfo
  21. from mautrix.bridge.commands import HelpSection, command_handler
  22. from .. import puppet as pu
  23. from .typehint import CommandEvent
  24. try:
  25. import qrcode
  26. import PIL as _
  27. except ImportError:
  28. qrcode = None
  29. SECTION_AUTH = HelpSection("Authentication", 10, "")
  30. @command_handler(needs_auth=False, management_only=True, help_section=SECTION_AUTH,
  31. help_text="Link the bridge as a secondary device", help_args="[device name]")
  32. async def link(evt: CommandEvent) -> None:
  33. if qrcode is None:
  34. await evt.reply("Can't generate QR code: qrcode and/or PIL not installed")
  35. return
  36. # TODO make default device name configurable
  37. device_name = " ".join(evt.args) or "Mautrix-Signal bridge"
  38. async def callback(uri: str) -> None:
  39. buffer = io.BytesIO()
  40. image = qrcode.make(uri)
  41. size = image.pixel_size
  42. image.save(buffer, "PNG")
  43. qr = buffer.getvalue()
  44. mxc = await evt.az.intent.upload_media(qr, "image/png", "link-qr.png", len(qr))
  45. content = MediaMessageEventContent(body=uri, url=mxc, msgtype=MessageType.IMAGE,
  46. info=ImageInfo(mimetype="image/png", size=len(qr),
  47. width=size, height=size))
  48. await evt.az.intent.send_message(evt.room_id, content)
  49. account = await evt.bridge.signal.link(callback, device_name=device_name)
  50. await evt.sender.on_signin(account)
  51. await evt.reply(f"Successfully logged in as {pu.Puppet.fmt_phone(evt.sender.username)}")
  52. @command_handler(needs_auth=False, management_only=True, help_section=SECTION_AUTH,
  53. help_text="Sign into Signal as the primary device", help_args="<phone>")
  54. async def register(evt: CommandEvent) -> None:
  55. if len(evt.args) == 0:
  56. await evt.reply("**Usage**: $cmdprefix+sp register <phone>")
  57. return
  58. phone = evt.args[0]
  59. if not phone.startswith("+") or not phone[1:].isdecimal():
  60. await evt.reply(f"Please enter the phone number in international format (E.164)")
  61. return
  62. username = await evt.bridge.signal.register(phone)
  63. evt.sender.command_status = {
  64. "action": "Register",
  65. "room_id": evt.room_id,
  66. "next": enter_register_code,
  67. "username": username,
  68. }
  69. await evt.reply("Register SMS requested, please enter the code here.")
  70. async def enter_register_code(evt: CommandEvent) -> None:
  71. try:
  72. username = evt.sender.command_status["username"]
  73. account = await evt.bridge.signal.verify(username, code=evt.args[0])
  74. except UnexpectedResponse as e:
  75. if e.resp_type == "error":
  76. await evt.reply(e.data)
  77. else:
  78. raise
  79. else:
  80. await evt.sender.on_signin(account)
  81. await evt.reply(f"Successfully logged in as {pu.Puppet.fmt_phone(evt.sender.username)}")
  82. @command_handler(needs_auth=True, management_only=True, help_args="<_access token_>",
  83. help_section=SECTION_AUTH, help_text="Replace your Signal account's Matrix puppet"
  84. " with your Matrix account")
  85. async def login_matrix(evt: CommandEvent) -> None:
  86. puppet = await pu.Puppet.get_by_address(evt.sender.address)
  87. _, homeserver = Client.parse_mxid(evt.sender.mxid)
  88. if homeserver != pu.Puppet.hs_domain:
  89. await evt.reply("You can't log in with an account on a different homeserver")
  90. return
  91. try:
  92. await puppet.switch_mxid(" ".join(evt.args), evt.sender.mxid)
  93. await evt.reply("Successfully replaced your Signal account's "
  94. "Matrix puppet with your Matrix account.")
  95. except cpu.OnlyLoginSelf:
  96. await evt.reply("You may only log in with your own Matrix account")
  97. except cpu.InvalidAccessToken:
  98. await evt.reply("Invalid access token")
  99. @command_handler(needs_auth=True, management_only=True, help_section=SECTION_AUTH,
  100. help_text="Revert your Signal account's Matrix puppet to the original")
  101. async def logout_matrix(evt: CommandEvent) -> None:
  102. puppet = await pu.Puppet.get_by_address(evt.sender.address)
  103. if not puppet.is_real_user:
  104. await evt.reply("You're not logged in with your Matrix account")
  105. return
  106. await puppet.switch_mxid(None, None)
  107. await evt.reply("Restored the original puppet for your Signal account")