provisioning_api.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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 Awaitable, Dict, TYPE_CHECKING
  17. import logging
  18. import asyncio
  19. import json
  20. from aiohttp import web
  21. from mausignald.types import Address, Account
  22. from mausignald.errors import LinkingTimeout
  23. from mautrix.types import UserID
  24. from mautrix.util.logging import TraceLogger
  25. from .. import user as u
  26. if TYPE_CHECKING:
  27. from ..__main__ import SignalBridge
  28. class ProvisioningAPI:
  29. log: TraceLogger = logging.getLogger("mau.web.provisioning")
  30. app: web.Application
  31. bridge: 'SignalBridge'
  32. def __init__(self, bridge: 'SignalBridge', shared_secret: str) -> None:
  33. self.bridge = bridge
  34. self.app = web.Application()
  35. self.shared_secret = shared_secret
  36. self.app.router.add_get("/api/whoami", self.status)
  37. self.app.router.add_options("/api/link", self.login_options)
  38. self.app.router.add_options("/api/link/wait", self.login_options)
  39. # self.app.router.add_options("/api/register", self.login_options)
  40. # self.app.router.add_options("/api/register/code", self.login_options)
  41. # self.app.router.add_options("/api/logout", self.login_options)
  42. self.app.router.add_post("/api/link", self.link)
  43. self.app.router.add_post("/api/link/wait", self.link_wait)
  44. # self.app.router.add_post("/api/register", self.register)
  45. # self.app.router.add_post("/api/register/code", self.register_code)
  46. # self.app.router.add_post("/api/logout", self.logout)
  47. @property
  48. def _acao_headers(self) -> Dict[str, str]:
  49. return {
  50. "Access-Control-Allow-Origin": "*",
  51. "Access-Control-Allow-Headers": "Authorization, Content-Type",
  52. "Access-Control-Allow-Methods": "POST, OPTIONS",
  53. }
  54. @property
  55. def _headers(self) -> Dict[str, str]:
  56. return {
  57. **self._acao_headers,
  58. "Content-Type": "application/json",
  59. }
  60. async def login_options(self, _: web.Request) -> web.Response:
  61. return web.Response(status=200, headers=self._headers)
  62. def check_token(self, request: web.Request) -> Awaitable['u.User']:
  63. try:
  64. token = request.headers["Authorization"]
  65. token = token[len("Bearer "):]
  66. except KeyError:
  67. raise web.HTTPBadRequest(text='{"error": "Missing Authorization header"}',
  68. headers=self._headers)
  69. except IndexError:
  70. raise web.HTTPBadRequest(text='{"error": "Malformed Authorization header"}',
  71. headers=self._headers)
  72. if token != self.shared_secret:
  73. raise web.HTTPForbidden(text='{"error": "Invalid token"}', headers=self._headers)
  74. try:
  75. user_id = request.query["user_id"]
  76. except KeyError:
  77. raise web.HTTPBadRequest(text='{"error": "Missing user_id query param"}',
  78. headers=self._headers)
  79. return u.User.get_by_mxid(UserID(user_id))
  80. async def status(self, request: web.Request) -> web.Response:
  81. user = await self.check_token(request)
  82. data = {
  83. "permissions": user.permission_level,
  84. "mxid": user.mxid,
  85. "signal": None,
  86. }
  87. if await user.is_logged_in():
  88. profile = await self.bridge.signal.get_profile(username=user.username,
  89. address=Address(number=user.username))
  90. data["signal"] = {
  91. "number": profile.address.number or user.username,
  92. "uuid": str(profile.address.uuid or user.uuid or ""),
  93. "name": profile.name,
  94. }
  95. return web.json_response(data, headers=self._acao_headers)
  96. async def link(self, request: web.Request) -> web.Response:
  97. user = await self.check_token(request)
  98. try:
  99. data = await request.json()
  100. except json.JSONDecodeError:
  101. raise web.HTTPBadRequest(text='{"error": "Malformed JSON"}', headers=self._headers)
  102. device_name = data.get("device_name", "Mautrix-Signal bridge")
  103. uri_future = asyncio.Future()
  104. async def _callback(uri: str) -> None:
  105. uri_future.set_result(uri)
  106. async def _link() -> Account:
  107. account = await self.bridge.signal.link(_callback, device_name=device_name)
  108. await user.on_signin(account)
  109. return account
  110. user.command_status = {
  111. "action": "Link",
  112. "task": self.bridge.loop.create_task(_link()),
  113. }
  114. return web.json_response({"uri": await uri_future}, headers=self._acao_headers)
  115. async def link_wait(self, request: web.Request) -> web.Response:
  116. user = await self.check_token(request)
  117. if not user.command_status or user.command_status["action"] != "Link":
  118. raise web.HTTPBadRequest(text='{"error": "No Signal linking started"}',
  119. headers=self._headers)
  120. try:
  121. account = await user.command_status["task"]
  122. except LinkingTimeout:
  123. raise web.HTTPBadRequest(text='{"error": "Signal linking timed out"}',
  124. headers=self._headers)
  125. return web.json_response({
  126. "number": account.username,
  127. "uuid": account.uuid,
  128. })
  129. # async def logout(self, request: web.Request) -> web.Response:
  130. # user = await self.check_token(request)
  131. # await user.()
  132. # return web.json_response({}, headers=self._acao_headers)