4
0

lynx_relay.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. """LYNX SHARE relay service: Online Sessions P2/P4 WebSocket relay skeleton (rooms of up to 4 peers).
  2. Runs on 127.0.0.1:8082 behind Caddy (relay.lynx-share.com). The relay only forwards frames: it never reads them.
  3. LYNX encrypts every session frame end to end (docs/design/ONLINE_SESSIONS.md §6.4), so the relay sees opaque bytes.
  4. Protocol reference: docs/design/SHARE_API.md ("Relay").
  5. LYNX SHARE (AGPL-3.0-or-later).
  6. """
  7. from __future__ import annotations
  8. import asyncio
  9. import json
  10. import re
  11. import time
  12. from aiohttp import WSMsgType, web
  13. from lynx_common import (VERSION, RateLimiter, bearer, client_key, env_int, env_str, errors_middleware, fail,
  14. json_response, random_id, random_token, setup_logging, token_hash, token_matches)
  15. log = setup_logging("lynx-relay")
  16. MAX_PEERS = env_int("LYNX_RELAY_MAX_PEERS", 4)
  17. MAX_ROOMS = env_int("LYNX_RELAY_MAX_ROOMS", 200)
  18. ROOM_HOURS = env_int("LYNX_RELAY_ROOM_HOURS", 12) # a room lives this long after its last connection
  19. MAX_FRAME = env_int("LYNX_RELAY_MAX_FRAME", 1024 * 1024) # bytes per WebSocket message
  20. PEER_BYTES_PER_SEC = env_int("LYNX_RELAY_PEER_BPS", 4 * 1024 * 1024)
  21. ROOMS_PER_HOUR = env_int("LYNX_RELAY_ROOMS_PER_HOUR", 10)
  22. # Abuse limits (round 190ah): the relay is free and blind, so nobody may fill the server or use it as a tunnel.
  23. # LYNX itself stops a session's audio files at 8 GiB (docs/design/ONLINE_SESSIONS.md §8.4), below the room's limit.
  24. ROOM_BYTES = env_int("LYNX_RELAY_ROOM_BYTES", 12 * 1024 ** 3) # bytes one room may relay in all
  25. CLIENT_BYTES_DAY = env_int("LYNX_RELAY_CLIENT_BYTES_DAY", 32 * 1024 ** 3) # bytes one client may send per 24 h
  26. ROOMS_PER_CLIENT = env_int("LYNX_RELAY_ROOMS_PER_CLIENT", 8) # rooms one client may have open at once
  27. ROOM_MAX_HOURS = env_int("LYNX_RELAY_ROOM_MAX_HOURS", 72) # a room's whole life, even when busy
  28. ROOM_IDLE_HOURS = env_int("LYNX_RELAY_ROOM_IDLE_HOURS", 12) # connected, but no frame for this long
  29. MAX_TEXT = 4096 # bytes per control (text) message
  30. CLOSE_LIMIT = 4001 # WebSocket close code: a limit was reached
  31. CLOSE_SLOW = 4002 # WebSocket close code: the peer reads too slowly
  32. # Round 190oh: what may wait for one peer that reads slowly before it is closed (it reconnects and resumes). Every
  33. # peer has its own outbox, so a slow reader never holds up what its sender sends to the others.
  34. PEER_QUEUE_BYTES = env_int("LYNX_RELAY_PEER_QUEUE", 16 * 1024 * 1024)
  35. CLOSE_REMOVED = 4003 # WebSocket close code: the host removed this peer
  36. MAX_BANS = 64 # removed clients remembered per room
  37. SUBPROTOCOL = "lynx-relay.v1"
  38. # A room token the host chose (LYNX derives it from the invite code, so a guest who has the code can connect without the
  39. # server ever handing the token out). Only its SHA-256 is kept, like every token here.
  40. CHOSEN_TOKEN = re.compile(r"^[A-Za-z0-9_-]{43,128}$")
  41. STARTED = time.time()
  42. room_limiter = RateLimiter(ROOMS_PER_HOUR, 3600)
  43. connect_limiter = RateLimiter(60, 60)
  44. frames_total = 0
  45. bytes_total = 0
  46. limits_hit = 0
  47. class DayBudget:
  48. """Bytes per client key in a 24 h window that starts with the client's first frame. In memory (one process)."""
  49. def __init__(self, limit: int, window: float = 86400.0):
  50. self.limit, self.window = int(limit), float(window)
  51. self.used: dict[str, tuple[float, int]] = {}
  52. def spend(self, key: str, size: int) -> bool:
  53. now = time.monotonic()
  54. start, used = self.used.get(key, (now, 0))
  55. if now - start >= self.window:
  56. start, used = now, 0
  57. used += size
  58. self.used[key] = (start, used)
  59. return used <= self.limit
  60. def sweep(self) -> None:
  61. now = time.monotonic()
  62. for key in [k for k, (start, _) in self.used.items() if now - start >= self.window]:
  63. del self.used[key]
  64. client_budget = DayBudget(CLIENT_BYTES_DAY)
  65. class Room:
  66. def __init__(self, rid: str, token: str, host_token: str, creator: str = ""):
  67. self.id = rid
  68. self.token_hash = token_hash(token)
  69. self.host_hash = token_hash(host_token)
  70. self.peers: dict[int, web.WebSocketResponse] = {}
  71. self.created = time.time()
  72. self.touched = self.created
  73. self.creator = creator # the salted client key (rate limits only; never logged)
  74. self.bytes = 0 # relayed so far
  75. self.last_frame = self.created
  76. self.outboxes: dict[int, Outbox] = {} # round 190oh: one per connected peer
  77. # round 190on: the host can remove a peer (kick). Each connection's salted client key is kept (in memory, never
  78. # logged) so that a removed peer cannot come back into this room from the same address with the old code.
  79. self.peer_keys: dict[int, str] = {}
  80. self.banned: set[str] = set()
  81. self.closing: set[asyncio.Task] = set() # (kicks under way: kept so the tasks are not collected early)
  82. def over_limit(self, now: float) -> str:
  83. """Why this room must close now ("" = it may go on)."""
  84. if self.bytes > ROOM_BYTES:
  85. return "traffic limit"
  86. if now - self.created > ROOM_MAX_HOURS * 3600:
  87. return "open too long"
  88. if self.peers and now - self.last_frame > ROOM_IDLE_HOURS * 3600:
  89. return "idle too long"
  90. return ""
  91. def expires(self) -> float:
  92. return self.touched + ROOM_HOURS * 3600
  93. def free_slot(self) -> int | None:
  94. for n in range(1, MAX_PEERS + 1):
  95. if n not in self.peers:
  96. return n
  97. return None
  98. rooms: dict[str, Room] = {}
  99. class Outbox:
  100. """Round 190oh: what goes to one peer, in order, written by a task of its own. Before this the relay forwarded each
  101. frame with `await peer.send_bytes(...)` inside the sender's read loop, so one peer that read slowly held up
  102. everything its sender sent to everyone else (a 128 KiB/s reader delayed edits to another peer by 4.5 s median,
  103. 12 s at worst). Now `put` never waits; a peer with more than PEER_QUEUE_BYTES waiting is closed (CLOSE_SLOW)."""
  104. def __init__(self, ws: web.WebSocketResponse, limit: int | None = None):
  105. self.ws = ws
  106. self.limit = PEER_QUEUE_BYTES if limit is None else limit
  107. self.queue: asyncio.Queue = asyncio.Queue()
  108. self.waiting = 0 # bytes queued and not yet written
  109. self.closed_slow = False
  110. self.task = asyncio.create_task(self.run())
  111. def put(self, item: bytes | str) -> bool:
  112. """Queues a frame (bytes) or a control message (str); False when the peer is gone or was too slow."""
  113. if self.closed_slow or self.ws.closed:
  114. return False
  115. self.waiting += len(item)
  116. if self.waiting > self.limit:
  117. self.closed_slow = True
  118. log.warning("a peer read too slowly (%d bytes waiting): closed", self.waiting)
  119. asyncio.create_task(self.ws.close(code=CLOSE_SLOW, message=b"too slow"))
  120. return False
  121. self.queue.put_nowait(item)
  122. return True
  123. async def run(self) -> None:
  124. try:
  125. while True:
  126. item = await self.queue.get()
  127. if item is None:
  128. return
  129. self.waiting -= len(item)
  130. if self.ws.closed:
  131. continue
  132. if isinstance(item, str):
  133. await self.ws.send_str(item)
  134. else:
  135. await self.ws.send_bytes(item)
  136. except (ConnectionError, RuntimeError, asyncio.CancelledError):
  137. return
  138. async def finish(self) -> None:
  139. self.queue.put_nowait(None)
  140. self.task.cancel()
  141. try:
  142. await self.task
  143. except asyncio.CancelledError:
  144. pass
  145. def room_token_from(request: web.Request) -> str:
  146. """Native clients send Authorization: Bearer <token>; browsers cannot, so the token may also come as a second
  147. WebSocket subprotocol "token.<token>" (never in the URL, which ends up in logs)."""
  148. tok = bearer(request)
  149. if tok:
  150. return tok
  151. for p in request.headers.get("Sec-WebSocket-Protocol", "").split(","):
  152. p = p.strip()
  153. if p.startswith("token."):
  154. return p[6:]
  155. return ""
  156. async def health(request: web.Request) -> web.Response:
  157. return json_response(200, {
  158. "ok": True, "service": "lynx-relay", "api": VERSION, "uptime": int(time.time() - STARTED),
  159. "rooms": len(rooms), "peers": sum(len(r.peers) for r in rooms.values()), "maxPeers": MAX_PEERS,
  160. "frames": frames_total, "bytes": bytes_total, "limitsHit": limits_hit,
  161. "limits": {"frame": MAX_FRAME, "roomBytes": ROOM_BYTES, "clientBytesDay": CLIENT_BYTES_DAY,
  162. "roomsPerClient": ROOMS_PER_CLIENT, "roomHours": ROOM_MAX_HOURS, "idleHours": ROOM_IDLE_HOURS},
  163. })
  164. async def create_room(request: web.Request) -> web.Response:
  165. creator = client_key(request)
  166. if not room_limiter.allow(creator):
  167. return fail(429, "too many rooms, try again later", {"Retry-After": "600"})
  168. if sum(1 for r in rooms.values() if r.creator == creator) >= ROOMS_PER_CLIENT:
  169. return fail(429, "too many rooms open from this connection, close one first", {"Retry-After": "600"})
  170. if len(rooms) >= MAX_ROOMS:
  171. return fail(503, "relay is full, try again later", {"Retry-After": "300"})
  172. # optional body {"token": "<43..128 url-safe chars>"}: the room token the host chose (SHARE_API.md §3.1)
  173. chosen = ""
  174. if request.can_read_body:
  175. try:
  176. body = await request.json()
  177. except ValueError:
  178. return fail(400, "the body must be JSON")
  179. if not isinstance(body, dict):
  180. return fail(400, "the body must be a JSON object")
  181. chosen = body.get("token") or ""
  182. if chosen and (not isinstance(chosen, str) or not CHOSEN_TOKEN.match(chosen)):
  183. return fail(400, "token: 43 to 128 characters A-Z a-z 0-9 _ -")
  184. # Body reads yield to other creates: reserve capacity only after the last await.
  185. if len(rooms) >= MAX_ROOMS:
  186. return fail(503, "relay is full, try again later", {"Retry-After": "300"})
  187. rid = random_id(7)[:10]
  188. while rid in rooms:
  189. rid = random_id(7)[:10]
  190. token, host_token = chosen or random_token(), random_token()
  191. room = Room(rid, token, host_token, creator)
  192. rooms[rid] = room
  193. log.info("room created %s… (%d rooms)", rid[:4], len(rooms))
  194. base = env_str("LYNX_RELAY_PUBLIC_URL", "wss://relay.lynx-share.com").rstrip("/")
  195. return json_response(201, {"ok": True, "room": rid, "token": "" if chosen else token, "hostToken": host_token,
  196. "maxPeers": MAX_PEERS, "expires": int(room.expires()),
  197. "ws": f"{base}/v1/rooms/{rid}/ws", "subprotocol": SUBPROTOCOL})
  198. async def close_room(request: web.Request) -> web.Response:
  199. room = rooms.get(request.match_info["room"])
  200. if not room:
  201. return fail(404, "no such room")
  202. if not token_matches(bearer(request), room.host_hash):
  203. return fail(401, "missing or wrong host token")
  204. await drop_room(room, "closed by host")
  205. return web.Response(status=204)
  206. async def kick(request: web.Request) -> web.Response:
  207. """Round 190on: the host removes a peer. Body {"peer": n, "ban": true, "token": "<new room token>"}: the peer's
  208. socket is closed with 4003 (its slot is free at once); "ban" (default true) keeps its client address out of this
  209. room; "token" replaces the room token for new connections (the peers already connected stay: the invite code
  210. changed for new joins only). Every field but "peer" is optional; "peer" 0 with a token only changes the token."""
  211. room = rooms.get(request.match_info["room"])
  212. if not room:
  213. return fail(404, "no such room")
  214. if not token_matches(bearer(request), room.host_hash):
  215. return fail(401, "missing or wrong host token")
  216. try:
  217. body = await request.json()
  218. except ValueError:
  219. return fail(400, "the body must be JSON")
  220. if not isinstance(body, dict):
  221. return fail(400, "the body must be a JSON object")
  222. peer = body.get("peer", 0)
  223. if not isinstance(peer, int) or isinstance(peer, bool) or peer < 0 or peer > MAX_PEERS:
  224. return fail(400, f"peer: 0 to {MAX_PEERS}")
  225. ban = body.get("ban", True)
  226. if not isinstance(ban, bool):
  227. return fail(400, "ban: true or false")
  228. new_token = body.get("token") or ""
  229. if new_token and (not isinstance(new_token, str) or not CHOSEN_TOKEN.match(new_token)):
  230. return fail(400, "token: 43 to 128 characters A-Z a-z 0-9 _ -")
  231. # (the body read may have yielded: the room may be gone)
  232. if rooms.get(room.id) is not room:
  233. return fail(404, "no such room")
  234. removed = False
  235. if peer:
  236. key = room.peer_keys.get(peer)
  237. # (never the host's own address: a guest on the host's network would lock the host out of its room)
  238. if ban and key and key != client_key(request) and len(room.banned) < MAX_BANS:
  239. room.banned.add(key)
  240. ws = room.peers.get(peer)
  241. if ws is not None and not ws.closed:
  242. removed = True
  243. # (the close handshake waits for the peer: the host gets its answer at once; the slot is freed when the
  244. # peer's connection ends, at the latest after aiohttp's close timeout)
  245. task = asyncio.create_task(ws.close(code=CLOSE_REMOVED, message=b"removed by host"))
  246. room.closing.add(task)
  247. task.add_done_callback(room.closing.discard)
  248. if new_token:
  249. room.token_hash = token_hash(new_token)
  250. log.info("room %s…: host removed peer %d%s%s", room.id[:4], peer, " (banned)" if ban and peer else "",
  251. ", new token" if new_token else "")
  252. return json_response(200, {"ok": True, "removed": removed, "peers": sorted(room.peers)})
  253. async def drop_room(room: Room, reason: str, code: int = 4000) -> None:
  254. rooms.pop(room.id, None)
  255. for ws in list(room.peers.values()):
  256. await ws.close(code=code, message=reason.encode()[:120])
  257. room.peers.clear()
  258. async def close_for_limit(room: Room, reason: str) -> None:
  259. global limits_hit
  260. limits_hit += 1
  261. log.warning("room %s…: closed, %s (%d bytes relayed)", room.id[:4], reason, room.bytes)
  262. await drop_room(room, reason, CLOSE_LIMIT)
  263. async def send_json(ws: web.WebSocketResponse, msg: dict, room: Room | None = None, slot: int | None = None) -> None:
  264. text = json.dumps(msg, separators=(",", ":"))
  265. box = room.outboxes.get(slot) if room is not None and slot is not None else None
  266. if box is not None and box.ws is ws:
  267. box.put(text) # (in order with the frames already waiting for that peer)
  268. elif not ws.closed:
  269. await ws.send_str(text)
  270. async def broadcast(room: Room, msg: dict, skip: int | None = None) -> None:
  271. for n, ws in list(room.peers.items()):
  272. if n != skip:
  273. await send_json(ws, msg, room, n)
  274. async def connect(request: web.Request) -> web.StreamResponse:
  275. if not connect_limiter.allow(client_key(request)):
  276. return fail(429, "slow down", {"Retry-After": "60"})
  277. room = rooms.get(request.match_info["room"])
  278. if not room:
  279. return fail(404, "no such room")
  280. if not token_matches(room_token_from(request), room.token_hash):
  281. return fail(401, "missing or wrong room token")
  282. if client_key(request) in room.banned: # round 190on: removed by the host
  283. return fail(403, "the host removed you from this session")
  284. slot = room.free_slot()
  285. if slot is None:
  286. return fail(409, f"room is full ({MAX_PEERS} peers)")
  287. ws = web.WebSocketResponse(protocols=(SUBPROTOCOL,), heartbeat=25, max_msg_size=MAX_FRAME)
  288. await ws.prepare(request)
  289. room.peers[slot] = ws
  290. room.outboxes[slot] = box = Outbox(ws)
  291. room.peer_keys[slot] = client_key(request)
  292. room.touched = time.time()
  293. await send_json(ws, {"type": "welcome", "peer": slot, "peers": sorted(room.peers), "maxPeers": MAX_PEERS}, room, slot)
  294. await broadcast(room, {"type": "join", "peer": slot}, skip=slot)
  295. log.info("room %s…: peer %d joined (%d/%d)", room.id[:4], slot, len(room.peers), MAX_PEERS)
  296. global frames_total, bytes_total, limits_hit
  297. sender = client_key(request)
  298. budget, last = float(PEER_BYTES_PER_SEC), time.monotonic()
  299. try:
  300. async for msg in ws:
  301. if msg.type == WSMsgType.BINARY:
  302. data: bytes = msg.data
  303. now = time.monotonic()
  304. budget = min(PEER_BYTES_PER_SEC, budget + (now - last) * PEER_BYTES_PER_SEC)
  305. last = now
  306. budget -= len(data)
  307. if budget < 0: # over the rate: wait instead of dropping (the stream is reliable)
  308. await asyncio.sleep(-budget / PEER_BYTES_PER_SEC)
  309. if len(data) < 1:
  310. continue
  311. # the limits (round 190ah): what one client sends in a day, what one room relays in all
  312. if not client_budget.spend(sender, len(data)):
  313. limits_hit += 1
  314. log.warning("room %s…: peer %d is over the daily traffic limit", room.id[:4], slot)
  315. await ws.close(code=CLOSE_LIMIT, message=b"daily traffic limit")
  316. break
  317. room.bytes += len(data)
  318. room.last_frame = time.time()
  319. bytes_total += len(data)
  320. if room.bytes > ROOM_BYTES:
  321. await close_for_limit(room, "traffic limit")
  322. break
  323. dest = data[0]
  324. frames_total += 1
  325. out = bytes([slot]) + data[1:]
  326. targets = [n for n in room.peers if n != slot] if dest == 0 else [dest]
  327. for n in targets: # (round 190oh: never waits for a slow reader)
  328. target = room.outboxes.get(n)
  329. if target is not None:
  330. target.put(out)
  331. elif msg.type == WSMsgType.TEXT:
  332. if len(msg.data) > MAX_TEXT:
  333. await send_json(ws, {"type": "error", "error": "control message too long"}, room, slot)
  334. continue
  335. try:
  336. ctl = json.loads(msg.data)
  337. except ValueError:
  338. ctl = {}
  339. if ctl.get("type") == "ping":
  340. await send_json(ws, {"type": "pong", "t": ctl.get("t")}, room, slot)
  341. elif ctl.get("type") == "peers":
  342. await send_json(ws, {"type": "peers", "peers": sorted(room.peers)}, room, slot)
  343. else:
  344. await send_json(ws, {"type": "error", "error": "unknown control message"}, room, slot)
  345. elif msg.type == WSMsgType.ERROR:
  346. break
  347. finally:
  348. if room.peers.get(slot) is ws:
  349. del room.peers[slot]
  350. room.peer_keys.pop(slot, None)
  351. if room.outboxes.get(slot) is box:
  352. del room.outboxes[slot]
  353. await box.finish()
  354. room.touched = time.time()
  355. await broadcast(room, {"type": "leave", "peer": slot})
  356. log.info("room %s…: peer %d left (%d/%d)", room.id[:4], slot, len(room.peers), MAX_PEERS)
  357. return ws
  358. async def index(request: web.Request) -> web.Response:
  359. return json_response(200, {"ok": True, "service": "lynx-relay", "api": VERSION,
  360. "docs": "https://github.com/Ka1-S/LYNX-SHARE/blob/main/docs/design/SHARE_API.md"})
  361. async def gc_loop(app: web.Application) -> None:
  362. while True:
  363. await asyncio.sleep(300)
  364. now = time.time()
  365. await sweep(now)
  366. async def sweep(now: float) -> None:
  367. """Forgets empty rooms nobody came back to and closes the ones over a limit (too old, connected but silent)."""
  368. for room in list(rooms.values()):
  369. if not room.peers and now >= room.expires():
  370. rooms.pop(room.id, None)
  371. log.info("room %s… expired", room.id[:4])
  372. elif reason := room.over_limit(now):
  373. await close_for_limit(room, reason)
  374. client_budget.sweep()
  375. async def on_startup(app: web.Application) -> None:
  376. app["gc"] = asyncio.create_task(gc_loop(app))
  377. async def on_shutdown(app: web.Application) -> None:
  378. for room in list(rooms.values()):
  379. await drop_room(room, "relay restarting")
  380. app["gc"].cancel()
  381. def make_app() -> web.Application:
  382. app = web.Application(middlewares=[errors_middleware], client_max_size=16 * 1024)
  383. app.router.add_get("/", index)
  384. app.router.add_get("/health", health)
  385. app.router.add_post("/v1/rooms", create_room)
  386. app.router.add_delete("/v1/rooms/{room}", close_room)
  387. app.router.add_post("/v1/rooms/{room}/kick", kick)
  388. app.router.add_get("/v1/rooms/{room}/ws", connect)
  389. app.on_startup.append(on_startup)
  390. app.on_shutdown.append(on_shutdown)
  391. return app
  392. if __name__ == "__main__":
  393. web.run_app(make_app(), host=env_str("LYNX_RELAY_HOST", "127.0.0.1"), port=env_int("LYNX_RELAY_PORT", 8082),
  394. access_log=None)