mock_chat.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. #!/usr/bin/env python3
  2. """Mock Cloudron Chat server + Cloudron OIDC login for the NebOS chat client.
  3. Two plain-HTTP origins on the host, reachable from a QEMU slirp guest as
  4. 10.0.2.2:
  5. chat (default port 18080): /auth/login, /auth/callback, /auth/return,
  6. /auth/logout and the /api/* routes the client uses
  7. login (default port 18081): /openid/auth, /openid/interaction/<uid>
  8. (HTML with the cloudron-config JSON), POST .../login and .../confirm
  9. Accounts (password "test"):
  10. test plain login
  11. totp needs the TOTP code 123456
  12. passkey passkey-only (the client must fall back to the cookie screen)
  13. consent login is followed by a consent interaction (auto-confirmed)
  14. Debug endpoints on the chat port (no auth):
  15. GET /debug/state JSON dump (messages, reads, joins)
  16. POST /debug/inject {"channel","body","user"} message from another user
  17. POST /debug/presence {"user","presence"}
  18. Usage: tools/mock_chat.py [--host 0.0.0.0] [--chat-port 18080]
  19. [--login-port 18081] [--public-host 10.0.2.2] [--messages N]
  20. """
  21. import argparse
  22. import datetime
  23. import json
  24. import secrets
  25. import threading
  26. from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
  27. from urllib.parse import parse_qs, urlparse
  28. LOCK = threading.Lock()
  29. STATE = {
  30. "users": {
  31. "u-test": {"id": "u-test", "username": "test", "name": "Test User"},
  32. "u-alice": {"id": "u-alice", "username": "alice", "name": "Alice Example"},
  33. "u-bob": {"id": "u-bob", "username": "bob", "name": "Bob Böhm"},
  34. "u-carol": {"id": "u-carol", "username": "carol", "name": "Carol"},
  35. "u-totp": {"id": "u-totp", "username": "totp", "name": "Totp User"},
  36. "u-consent": {"id": "u-consent", "username": "consent", "name": "Consent User"},
  37. },
  38. "channels": {}, # id -> {id,name,type,members:set,description}
  39. "messages": {}, # channel id -> [msg]
  40. "reads": {}, # (channel, user) -> last read message id
  41. "presence": {"u-alice": "online", "u-bob": "away", "u-carol": "offline"},
  42. "sessions": {}, # connect.sid -> user id (or None = pre-login)
  43. "interactions": {}, # uid -> {"pre": sid, "user": None, "consent": bool}
  44. "log": [],
  45. }
  46. SEQ = [0]
  47. ARGS = None
  48. def note(line):
  49. STATE["log"].append(line)
  50. if ARGS and ARGS.verbose:
  51. print(line, flush=True)
  52. def now_iso():
  53. SEQ[0] += 1
  54. t = datetime.datetime(2026, 11, 9, 9, 0, 0) + datetime.timedelta(seconds=37 * SEQ[0])
  55. return t.strftime("%Y-%m-%dT%H:%M:%S.") + "%03dZ" % (SEQ[0] % 1000)
  56. def add_channel(cid, name, ctype, members, description=""):
  57. STATE["channels"][cid] = {"id": cid, "name": name, "type": ctype,
  58. "members": set(members), "description": description}
  59. STATE["messages"][cid] = []
  60. def add_message(cid, uid, body, client_id=None, reply_to=None, extra=None):
  61. msgs = STATE["messages"][cid]
  62. m = {"id": "m%05d" % (SEQ[0] + 1), "clientId": client_id, "channelId": cid,
  63. "userId": uid, "authorName": STATE["users"][uid]["name"],
  64. "authorUsername": STATE["users"][uid]["username"], "body": body,
  65. "type": None, "parentId": None, "replyToId": reply_to, "replyTo": None,
  66. "createdAt": now_iso(), "deleted": False, "reactions": [],
  67. "attachments": [], "threadCount": 0, "readBy": [], "pinned": False}
  68. if reply_to:
  69. target = next((x for x in msgs if x["id"] == reply_to), None)
  70. if target:
  71. m["replyTo"] = {"id": target["id"], "authorName": target["authorName"],
  72. "body": target["body"], "deleted": False}
  73. if extra:
  74. m.update(extra)
  75. msgs.append(m)
  76. return m
  77. def seed(n_general):
  78. add_channel("c-general", "general", "public",
  79. ["u-test", "u-alice", "u-bob", "u-carol", "u-totp", "u-consent"],
  80. "Company-wide")
  81. add_channel("c-random", "random", "public", ["u-alice", "u-bob"], "Off topic")
  82. add_channel("c-design", "design", "public", ["u-alice"], "Design talk")
  83. add_channel("c-secret", "secret", "private", ["u-test", "u-alice"])
  84. add_channel("d-alice", None, "dm", ["u-test", "u-alice"])
  85. who = ["u-alice", "u-bob", "u-carol"]
  86. for i in range(n_general):
  87. add_message("c-general", who[i % 3],
  88. "History message %d – “quoted” café \U0001F44D" % (i + 1))
  89. first = STATE["messages"]["c-general"][-1]["id"] if n_general else None
  90. add_message("c-general", "u-bob",
  91. "A longer message that should wrap over several lines in the "
  92. "NebOS chat timeline, because it keeps going and going with "
  93. "plenty of words to test the greedy word wrapper.\nAnd a "
  94. "second paragraph.", reply_to=first,
  95. extra={"attachments": [{"id": "a1", "filename": "notes.txt",
  96. "mime": "text/plain", "size": 12}],
  97. "threadCount": 2,
  98. "reactions": [{"emoji": "\U0001F44D", "count": 3}]})
  99. add_message("c-secret", "u-alice", "Private channel, only us two.")
  100. add_message("d-alice", "u-alice", "Hi Test, this is a direct message!")
  101. # test has read general up to the history; the rest is unread
  102. msgs = STATE["messages"]["c-general"]
  103. if len(msgs) > 1:
  104. STATE["reads"][("c-general", "u-test")] = msgs[-2]["id"]
  105. def unread(cid, uid):
  106. msgs = [m for m in STATE["messages"][cid] if not m["deleted"]]
  107. last = STATE["reads"].get((cid, uid))
  108. if last is None:
  109. return len([m for m in msgs if m["userId"] != uid])
  110. idx = next((i for i, m in enumerate(msgs) if m["id"] == last), -1)
  111. return len([m for m in msgs[idx + 1:] if m["userId"] != uid])
  112. def last_message(cid):
  113. msgs = [m for m in STATE["messages"][cid] if not m["deleted"]]
  114. if not msgs:
  115. return None
  116. m = msgs[-1]
  117. return {"id": m["id"], "body": m["body"][:160], "createdAt": m["createdAt"],
  118. "userId": m["userId"], "authorName": m["authorName"], "authorPicture": ""}
  119. def channel_json(c, uid):
  120. return {"id": c["id"], "name": c["name"], "type": c["type"],
  121. "description": c["description"], "archived": False,
  122. "memberCount": len(c["members"]), "isSelf": False,
  123. "unreadCount": unread(c["id"], uid), "lastMessage": last_message(c["id"])}
  124. def dm_json(c, uid):
  125. other = next((m for m in c["members"] if m != uid), None)
  126. u = STATE["users"].get(other)
  127. return {"id": c["id"], "type": "dm", "isSelf": other is None,
  128. "otherUser": dict(u, active=True) if u else None,
  129. "otherUserId": other, "unreadCount": unread(c["id"], uid),
  130. "lastMessage": last_message(c["id"]),
  131. "presence": STATE["presence"].get(other, "offline")}
  132. class Base(BaseHTTPRequestHandler):
  133. protocol_version = "HTTP/1.1"
  134. server_version = "MockChat/1.0"
  135. def log_message(self, fmt, *a):
  136. note("%s %s" % (self.server.label, fmt % a))
  137. def cookies(self):
  138. out = {}
  139. for part in (self.headers.get("Cookie") or "").split(";"):
  140. if "=" in part:
  141. k, v = part.strip().split("=", 1)
  142. out[k] = v
  143. return out
  144. def body_json(self):
  145. n = int(self.headers.get("Content-Length") or 0)
  146. raw = self.rfile.read(n) if n else b""
  147. if not raw:
  148. return {}
  149. try:
  150. return json.loads(raw.decode())
  151. except ValueError:
  152. return None
  153. def send(self, status, body=b"", ctype="application/json",
  154. headers=None):
  155. if isinstance(body, (dict, list)):
  156. body = json.dumps(body).encode()
  157. elif isinstance(body, str):
  158. body = body.encode()
  159. self.send_response(status)
  160. for k, v in (headers or []):
  161. self.send_header(k, v)
  162. if status not in (204, 304):
  163. self.send_header("Content-Type", ctype)
  164. self.send_header("Content-Length", str(len(body)))
  165. self.end_headers()
  166. if status not in (204, 304):
  167. self.wfile.write(body)
  168. def redirect(self, status, location, headers=None):
  169. self.send(status, "Redirecting to " + location, "text/plain",
  170. [("Location", location)] + (headers or []))
  171. def chat_origin(self):
  172. return "http://%s:%d" % (ARGS.public_host, ARGS.chat_port)
  173. def login_origin(self):
  174. return "http://%s:%d" % (ARGS.public_host, ARGS.login_port)
  175. LOGIN_PAGE = """<!DOCTYPE html>
  176. <html><head><title>Login</title>
  177. <script id="cloudron-config" type="application/json">
  178. %s
  179. </script>
  180. <script type="module" crossorigin src="/assets/oidc_login.js"></script>
  181. </head><body><div id="app"></div></body></html>
  182. """
  183. class LoginHandler(Base):
  184. def do_GET(self):
  185. u = urlparse(self.path)
  186. parts = u.path.strip("/").split("/")
  187. with LOCK:
  188. if u.path == "/openid/auth":
  189. q = parse_qs(u.query)
  190. uid = secrets.token_urlsafe(12)
  191. STATE["interactions"][uid] = {"pre": q.get("state", [""])[0],
  192. "user": None, "consent": False,
  193. "icookie": secrets.token_hex(8)}
  194. it = STATE["interactions"][uid]
  195. return self.redirect(303, "/openid/interaction/" + uid, [
  196. ("Set-Cookie", "_interaction=%s; path=/openid/interaction/%s; "
  197. "expires=Mon, 09 Nov 2026 20:00:00 GMT; samesite=lax; httponly"
  198. % (it["icookie"], uid)),
  199. ("Set-Cookie", "_interaction_resume=%s; path=/openid/auth/%s; "
  200. "httponly" % (it["icookie"], uid))])
  201. if len(parts) == 3 and parts[:2] == ["openid", "interaction"]:
  202. uid = parts[2]
  203. it = STATE["interactions"].get(uid)
  204. if not it or self.cookies().get("_interaction") != it["icookie"]:
  205. return self.send(400, {"message": "interaction cookie missing"})
  206. if it["user"] and it["consent"]:
  207. cfg = {"name": "chat", "submitUrl": "/openid/interaction/%s/confirm" % uid}
  208. else:
  209. cfg = {"iconUrl": "/icon", "name": "chat", "note": "",
  210. "submitUrl": "/openid/interaction/%s/login" % uid,
  211. "passkeyLoginUrl": "/openid/interaction/%s/passkey_login" % uid,
  212. "footer": "&copy; mock", "language": None}
  213. return self.send(200, LOGIN_PAGE % json.dumps(cfg), "text/html")
  214. if len(parts) == 3 and parts[:2] == ["openid", "auth"]:
  215. uid = parts[2]
  216. it = STATE["interactions"].get(uid)
  217. if not it or self.cookies().get("_interaction_resume") != it["icookie"]:
  218. return self.send(400, {"message": "resume cookie missing"})
  219. if not it["user"]:
  220. return self.redirect(303, "/openid/interaction/" + uid)
  221. if it["consent"] and not it.get("confirmed"):
  222. return self.redirect(303, "/openid/interaction/" + uid)
  223. code = secrets.token_hex(8)
  224. STATE["interactions"][uid]["code"] = code
  225. return self.redirect(303, "%s/auth/callback?code=%s&state=%s"
  226. % (self.chat_origin(), code, it["pre"]))
  227. self.send(404, {"message": "not found"})
  228. def do_POST(self):
  229. u = urlparse(self.path)
  230. parts = u.path.strip("/").split("/")
  231. body = self.body_json()
  232. with LOCK:
  233. if len(parts) == 4 and parts[:2] == ["openid", "interaction"]:
  234. uid = parts[2]
  235. it = STATE["interactions"].get(uid)
  236. if not it or self.cookies().get("_interaction") != it["icookie"]:
  237. return self.send(400, {"message": "interaction cookie missing"})
  238. if body is None:
  239. return self.send(400, {"message": "bad JSON"})
  240. if parts[3] == "login":
  241. note("login attempt user=%r totp=%r"
  242. % (body.get("username"), body.get("totpToken")))
  243. user, pw = body.get("username"), body.get("password")
  244. if pw != "test" or user not in ("test", "totp", "passkey", "consent"):
  245. return self.send(401, {"status": "Unauthorized",
  246. "message": "Username and password does not match"})
  247. if user == "passkey":
  248. return self.send(200, {"twoFactorRequired": True,
  249. "totpRequired": False,
  250. "passkeyOptions": {}})
  251. if user == "totp":
  252. tok = body.get("totpToken") or ""
  253. if not tok:
  254. return self.send(200, {"twoFactorRequired": True,
  255. "totpRequired": True,
  256. "passkeyOptions": None})
  257. if tok != "123456":
  258. return self.send(401, {"status": "Unauthorized",
  259. "message": "Invalid totpToken"})
  260. it["user"] = "u-" + user
  261. it["consent"] = user == "consent"
  262. return self.send(200, {"redirectTo": "%s/openid/auth/%s"
  263. % (self.login_origin(), uid)})
  264. if parts[3] == "confirm":
  265. if not it["user"]:
  266. return self.send(400, {"message": "not logged in"})
  267. it["confirmed"] = True
  268. return self.redirect(303, "/openid/auth/" + uid)
  269. self.send(404, {"message": "not found"})
  270. class ChatHandler(Base):
  271. def user(self):
  272. return STATE["sessions"].get(self.cookies().get("connect.sid"))
  273. def do_GET(self):
  274. u = urlparse(self.path)
  275. q = parse_qs(u.query)
  276. p = u.path
  277. with LOCK:
  278. if p == "/auth/login":
  279. sid = "pre-" + secrets.token_hex(8)
  280. STATE["sessions"][sid] = None
  281. return self.redirect(302, "%s/openid/auth?client_id=chat&state=%s"
  282. % (self.login_origin(), sid),
  283. [("Set-Cookie", "connect.sid=%s; Path=/; "
  284. "Expires=Mon, 23 Nov 2026 18:03:29 GMT; HttpOnly; SameSite=Lax" % sid)])
  285. if p == "/auth/callback":
  286. sid = self.cookies().get("connect.sid")
  287. state = q.get("state", [""])[0]
  288. code = q.get("code", [""])[0]
  289. it = next((i for i in STATE["interactions"].values()
  290. if i.get("code") == code), None)
  291. if not sid or sid != state or sid not in STATE["sessions"] or not it:
  292. return self.redirect(302, "/?error=auth_failed")
  293. new = "s%3A" + it["user"] + "." + secrets.token_hex(8)
  294. del STATE["sessions"][sid]
  295. STATE["sessions"][new] = it["user"]
  296. return self.redirect(302, "/auth/return", [
  297. ("Set-Cookie", "connect.sid=%s; Path=/; HttpOnly" % new)])
  298. if p == "/auth/return":
  299. return self.redirect(302, "/")
  300. if p == "/auth/logout":
  301. STATE["sessions"].pop(self.cookies().get("connect.sid"), None)
  302. return self.redirect(302, "/", [
  303. ("Set-Cookie", "connect.sid=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT")])
  304. if p == "/":
  305. return self.send(200, "<!DOCTYPE html><html><body>chat SPA</body></html>",
  306. "text/html")
  307. if p == "/debug/state":
  308. st = {"messages": STATE["messages"],
  309. "reads": {"%s|%s" % k: v for k, v in STATE["reads"].items()},
  310. "channels": {k: dict(v, members=sorted(v["members"]))
  311. for k, v in STATE["channels"].items()},
  312. "sessions": STATE["sessions"], "log": STATE["log"][-200:]}
  313. return self.send(200, st)
  314. if p == "/api/config":
  315. return self.send(200, {"providerName": "Mock", "gifEnabled": False})
  316. uid = self.user()
  317. if not uid:
  318. return self.send(401, {"error": "Unauthorized"})
  319. if p == "/api/me":
  320. return self.send(200, dict(STATE["users"][uid], email="", picture="",
  321. active=True))
  322. if p == "/api/channels":
  323. return self.send(200, [channel_json(c, uid) for c in STATE["channels"].values()
  324. if c["type"] != "dm" and uid in c["members"]])
  325. if p == "/api/channels/public":
  326. return self.send(200, [channel_json(c, uid) for c in
  327. sorted(STATE["channels"].values(),
  328. key=lambda c: c["name"] or "")
  329. if c["type"] == "public" and uid not in c["members"]])
  330. if p == "/api/dms":
  331. return self.send(200, [dm_json(c, uid) for c in STATE["channels"].values()
  332. if c["type"] == "dm" and uid in c["members"]])
  333. if p == "/api/users":
  334. return self.send(200, [dict(x, email="", picture="", active=True)
  335. for x in STATE["users"].values()])
  336. parts = p.strip("/").split("/")
  337. if len(parts) == 4 and parts[:2] == ["api", "channels"] and parts[3] == "messages":
  338. c = STATE["channels"].get(parts[2])
  339. if not c or uid not in c["members"]:
  340. return self.send(403, {"error": "Not a member"})
  341. limit = min(int(q.get("limit", ["50"])[0]), 200)
  342. msgs = STATE["messages"][c["id"]]
  343. ids = [m["id"] for m in msgs]
  344. if "after" in q:
  345. a = q["after"][0]
  346. if a not in ids:
  347. return self.send(404, {"error": "Message not found"})
  348. rows = msgs[ids.index(a) + 1:][:limit]
  349. return self.send(200, list(reversed(rows)))
  350. end = len(msgs)
  351. if "before" in q:
  352. b = q["before"][0]
  353. if b not in ids:
  354. return self.send(404, {"error": "Message not found"})
  355. end = ids.index(b)
  356. rows = msgs[max(0, end - limit):end]
  357. return self.send(200, list(reversed(rows)))
  358. self.send(404, {"error": "Not found"})
  359. def do_POST(self):
  360. u = urlparse(self.path)
  361. p = u.path
  362. body = self.body_json()
  363. with LOCK:
  364. if p == "/debug/inject":
  365. m = add_message(body["channel"], body.get("user", "u-alice"), body["body"])
  366. return self.send(201, m)
  367. if p == "/debug/presence":
  368. STATE["presence"][body["user"]] = body["presence"]
  369. return self.send(200, {})
  370. uid = self.user()
  371. if not uid:
  372. return self.send(401, {"error": "Unauthorized"})
  373. if body is None:
  374. return self.send(400, {"error": "bad JSON"})
  375. parts = p.strip("/").split("/")
  376. if p == "/api/dms":
  377. other = body.get("userId")
  378. if other not in STATE["users"]:
  379. return self.send(400, {"error": "Unknown user"})
  380. for c in STATE["channels"].values():
  381. if c["type"] == "dm" and c["members"] == {uid, other}:
  382. return self.send(200, dm_json(c, uid))
  383. cid = "d-" + secrets.token_hex(4)
  384. add_channel(cid, None, "dm", [uid, other])
  385. return self.send(201, dm_json(STATE["channels"][cid], uid))
  386. if len(parts) == 4 and parts[:2] == ["api", "channels"]:
  387. c = STATE["channels"].get(parts[2])
  388. if not c:
  389. return self.send(404, {"error": "Channel not found"})
  390. if parts[3] == "join":
  391. if c["type"] != "public":
  392. return self.send(403, {"error": "Forbidden"})
  393. c["members"].add(uid)
  394. return self.send(200, channel_json(c, uid))
  395. if uid not in c["members"]:
  396. return self.send(403, {"error": "Not a member"})
  397. if parts[3] == "read":
  398. msgs = STATE["messages"][c["id"]]
  399. if msgs:
  400. STATE["reads"][(c["id"], uid)] = msgs[-1]["id"]
  401. return self.send(200, {"unreadCount": 0})
  402. if parts[3] == "messages":
  403. text = (body.get("body") or "").strip()
  404. if not text:
  405. return self.send(400, {"error": "Message must not be empty"})
  406. cid_ = body.get("clientId")
  407. for m in STATE["messages"][c["id"]]:
  408. if cid_ and m["clientId"] == cid_:
  409. return self.send(201, m)
  410. m = add_message(c["id"], uid, text, client_id=cid_)
  411. STATE["reads"][(c["id"], uid)] = m["id"]
  412. return self.send(201, m)
  413. self.send(404, {"error": "Not found"})
  414. def serve(handler, port, label):
  415. srv = ThreadingHTTPServer((ARGS.host, port), handler)
  416. srv.label = label
  417. srv.daemon_threads = True
  418. threading.Thread(target=srv.serve_forever, daemon=True).start()
  419. return srv
  420. def main():
  421. global ARGS
  422. ap = argparse.ArgumentParser(description=__doc__,
  423. formatter_class=argparse.RawDescriptionHelpFormatter)
  424. ap.add_argument("--host", default="0.0.0.0")
  425. ap.add_argument("--chat-port", type=int, default=18080)
  426. ap.add_argument("--login-port", type=int, default=18081)
  427. ap.add_argument("--public-host", default="10.0.2.2",
  428. help="address the guest uses to reach this host")
  429. ap.add_argument("--messages", type=int, default=120,
  430. help="history messages seeded into #general")
  431. ap.add_argument("-v", "--verbose", action="store_true")
  432. ARGS = ap.parse_args()
  433. seed(ARGS.messages)
  434. serve(ChatHandler, ARGS.chat_port, "chat")
  435. serve(LoginHandler, ARGS.login_port, "login")
  436. print("mock chat on :%d, login on :%d (guest: http://%s:%d)"
  437. % (ARGS.chat_port, ARGS.login_port, ARGS.public_host, ARGS.chat_port),
  438. flush=True)
  439. try:
  440. threading.Event().wait()
  441. except KeyboardInterrupt:
  442. pass
  443. if __name__ == "__main__":
  444. main()