mock_chat.py 23 KB

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