matrix-puppeteer-line/matrix_puppeteer_line/web/provisioning_api.py

124 lines
4.6 KiB
Python
Raw Normal View History

2021-03-15 01:40:56 -04:00
# matrix-puppeteer-line - A very hacky Matrix-LINE bridge based on running LINE's Chrome extension in Puppeteer
2022-03-28 15:00:36 -04:00
# Copyright (C) 2020-2022 Tulir Asokan, Andrew Ferrazzutti
2020-08-28 09:38:06 -04:00
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
2020-12-29 09:33:33 -05:00
from typing import Awaitable, Dict, Optional
2020-08-28 09:38:06 -04:00
import logging
2020-12-29 09:33:33 -05:00
import asyncio
2020-08-28 09:38:06 -04:00
from aiohttp import web
from mautrix.types import UserID
from mautrix.util.logging import TraceLogger
from .. import user as u
class ProvisioningAPI:
log: TraceLogger = logging.getLogger("mau.web.provisioning")
app: web.Application
def __init__(self, shared_secret: str) -> None:
self.app = web.Application()
self.shared_secret = shared_secret
self.app.router.add_get("/api/whoami", self.status)
2020-12-29 09:33:33 -05:00
self.app.router.add_get("/api/login", self.login)
2020-08-28 09:38:06 -04:00
@property
def _acao_headers(self) -> Dict[str, str]:
return {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Authorization, Content-Type",
2020-12-29 09:33:33 -05:00
"Access-Control-Allow-Methods": "GET",
2020-08-28 09:38:06 -04:00
}
@property
def _headers(self) -> Dict[str, str]:
return {
**self._acao_headers,
"Content-Type": "application/json",
}
async def login_options(self, _: web.Request) -> web.Response:
return web.Response(status=200, headers=self._headers)
2020-12-29 09:33:33 -05:00
@staticmethod
def _get_ws_token(request: web.Request) -> Optional[str]:
if not request.path.endswith("/login"):
return None
try:
auth_parts = request.headers["Sec-WebSocket-Protocol"].split(",")
except KeyError:
return None
for part in auth_parts:
part = part.strip()
2021-06-10 02:51:23 -04:00
if part.startswith("net.miscworks.line.auth-"):
return part[len("net.miscworks.line.auth-"):]
2020-12-29 09:33:33 -05:00
return None
2020-08-28 09:38:06 -04:00
def check_token(self, request: web.Request) -> Awaitable['u.User']:
try:
token = request.headers["Authorization"]
token = token[len("Bearer "):]
except KeyError:
2020-12-29 09:33:33 -05:00
token = self._get_ws_token(request)
if not token:
raise web.HTTPBadRequest(text='{"error": "Missing Authorization header"}',
headers=self._headers)
2020-08-28 09:38:06 -04:00
except IndexError:
2020-12-29 09:33:33 -05:00
raise web.HTTPBadRequest(text='{"error": "Malformed Authorization header"}',
2020-08-28 09:38:06 -04:00
headers=self._headers)
if token != self.shared_secret:
2020-12-29 09:33:33 -05:00
raise web.HTTPForbidden(text='{"error": "Invalid token"}', headers=self._headers)
2020-08-28 09:38:06 -04:00
try:
user_id = request.query["user_id"]
except KeyError:
2020-12-29 09:33:33 -05:00
raise web.HTTPBadRequest(text='{"error": "Missing user_id query param"}',
2020-08-28 09:38:06 -04:00
headers=self._headers)
return u.User.get_by_mxid(UserID(user_id))
async def status(self, request: web.Request) -> web.Response:
user = await self.check_token(request)
data = {
"mxid": user.mxid,
2021-02-10 02:34:19 -05:00
"line": {
2020-12-29 09:33:33 -05:00
"connected": True,
} if await user.is_logged_in() else None,
2020-08-28 09:38:06 -04:00
}
return web.json_response(data, headers=self._acao_headers)
2020-12-29 09:33:33 -05:00
async def login(self, request: web.Request) -> web.WebSocketResponse:
2020-08-28 09:38:06 -04:00
user = await self.check_token(request)
2020-12-29 09:33:33 -05:00
status = await user.client.start()
if status.is_logged_in:
raise web.HTTPConflict(text='{"error": "Already logged in"}', headers=self._headers)
2020-08-28 09:38:06 -04:00
2021-06-10 02:51:23 -04:00
ws = web.WebSocketResponse(protocols=["net.miscworks.line.login"])
2020-12-29 09:33:33 -05:00
await ws.prepare(request)
2020-08-28 09:38:06 -04:00
try:
2020-12-29 09:33:33 -05:00
async for url in user.client.login():
self.log.debug("Sending QR URL %s to websocket", url)
await ws.send_json({"url": url})
2020-08-28 09:38:06 -04:00
except Exception:
2020-12-29 09:33:33 -05:00
await ws.send_json({"success": False})
self.log.exception("Error logging in")
else:
await ws.send_json({"success": True})
asyncio.create_task(user.sync())
await ws.close()
return ws