#!/usr/bin/env python3 """Mock Cloudron Chat server + Cloudron OIDC login for the NebOS chat client. Two plain-HTTP origins on the host, reachable from a QEMU slirp guest as 10.0.2.2: chat (default port 18080): /auth/login, /auth/callback, /auth/return, /auth/logout and the /api/* routes the client uses, including /api/avatars/ and /api/attachments/ for pictures login (default port 18081): /openid/auth, /openid/interaction/ (login page with cloudron-config JSON, consent page as a bare auto-submit form), POST .../login and .../confirm Accounts (password "test"): test plain login totp needs the TOTP code 123456 passkey passkey-only (the client must fall back to the cookie screen) consent login is followed by a consent interaction (auto-confirmed) Debug endpoints on the chat port (no auth): GET /debug/state JSON dump (messages, reads, joins) POST /debug/inject {"channel","body","user"} message from another user POST /debug/presence {"user","presence"} Usage: tools/mock_chat.py [--host 0.0.0.0] [--chat-port 18080] [--login-port 18081] [--public-host 10.0.2.2] [--messages N] """ import argparse import datetime import json import secrets import struct import threading import zlib from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from urllib.parse import parse_qs, urlparse LOCK = threading.Lock() STATE = { "users": { "u-test": {"id": "u-test", "username": "test", "name": "Test User", "picture": ""}, "u-alice": {"id": "u-alice", "username": "alice", "name": "Alice Example", "picture": "/api/avatars/u-alice"}, "u-bob": {"id": "u-bob", "username": "bob", "name": "Bob Böhm", "picture": "/api/avatars/u-bob"}, "u-carol": {"id": "u-carol", "username": "carol", "name": "Carol", "picture": ""}, "u-totp": {"id": "u-totp", "username": "totp", "name": "Totp User", "picture": ""}, "u-consent": {"id": "u-consent", "username": "consent", "name": "Consent User", "picture": ""}, }, "channels": {}, # id -> {id,name,type,members:set,description} "messages": {}, # channel id -> [msg] "reads": {}, # (channel, user) -> last read message id "presence": {"u-alice": "online", "u-bob": "away", "u-carol": "offline"}, "sessions": {}, # connect.sid -> user id (or None = pre-login) "interactions": {}, # uid -> {"pre": sid, "user": None, "consent": bool} "log": [], } SEQ = [0] ARGS = None def png_chunk(tag, data): return (struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xffffffff)) def png_rgb(w, h, pixel): raw = bytearray() for y in range(h): raw.append(0) for x in range(w): raw.extend(pixel(x, y)) return (b"\x89PNG\r\n\x1a\n" + png_chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)) + png_chunk(b"IDAT", zlib.compress(bytes(raw), 6)) + png_chunk(b"IEND", b"")) AVATAR_PNGS = {} def avatar_png(uid): if uid in AVATAR_PNGS: return AVATAR_PNGS[uid] h = sum(ord(c) for c in uid) colors = [(208, 90, 90), (90, 154, 208), (90, 176, 112), (192, 138, 58), (154, 106, 200), (58, 168, 168)] r, g, b = colors[h % len(colors)] def pixel(x, y): # A coloured disc with a lighter centre, so the screenshot shows a # real avatar rather than the initial fallback. dx, dy = x - 15.5, y - 15.5 if dx * dx + dy * dy > 15.5 * 15.5: return (32, 34, 38) if 8 <= x <= 23 and 12 <= y <= 19: return (245, 245, 245) return (r, g, b) AVATAR_PNGS[uid] = png_rgb(32, 32, pixel) return AVATAR_PNGS[uid] def attachment_png(): def pixel(x, y): if (x // 8 + y // 8) % 2: return (240, 150, 40) return (40, 90, 160) return png_rgb(96, 64, pixel) ATTACHMENT_PNG = attachment_png() def note(line): STATE["log"].append(line) if ARGS and ARGS.verbose: print(line, flush=True) def now_iso(): SEQ[0] += 1 t = datetime.datetime(2026, 11, 9, 9, 0, 0) + datetime.timedelta(seconds=37 * SEQ[0]) return t.strftime("%Y-%m-%dT%H:%M:%S.") + "%03dZ" % (SEQ[0] % 1000) def add_channel(cid, name, ctype, members, description=""): STATE["channels"][cid] = {"id": cid, "name": name, "type": ctype, "members": set(members), "description": description} STATE["messages"][cid] = [] def add_message(cid, uid, body, client_id=None, reply_to=None, extra=None): msgs = STATE["messages"][cid] m = {"id": "m%05d" % (SEQ[0] + 1), "clientId": client_id, "channelId": cid, "userId": uid, "authorName": STATE["users"][uid]["name"], "authorUsername": STATE["users"][uid]["username"], "authorPicture": STATE["users"][uid].get("picture", ""), "body": body, "type": None, "parentId": None, "replyToId": reply_to, "replyTo": None, "createdAt": now_iso(), "deleted": False, "reactions": [], "attachments": [], "threadCount": 0, "readBy": [], "pinned": False} if reply_to: target = next((x for x in msgs if x["id"] == reply_to), None) if target: m["replyTo"] = {"id": target["id"], "authorName": target["authorName"], "body": target["body"], "deleted": False} if extra: m.update(extra) msgs.append(m) return m def seed(n_general): add_channel("c-general", "general", "public", ["u-test", "u-alice", "u-bob", "u-carol", "u-totp", "u-consent"], "Company-wide") add_channel("c-random", "random", "public", ["u-alice", "u-bob"], "Off topic") add_channel("c-design", "design", "public", ["u-alice"], "Design talk") add_channel("c-secret", "secret", "private", ["u-test", "u-alice"]) add_channel("d-alice", None, "dm", ["u-test", "u-alice"]) who = ["u-alice", "u-bob", "u-carol"] for i in range(n_general): add_message("c-general", who[i % 3], "History message %d – “quoted” café \U0001F44D" % (i + 1)) first = STATE["messages"]["c-general"][-1]["id"] if n_general else None add_message("c-general", "u-bob", "A longer message that should wrap over several lines in the " "NebOS chat timeline, because it keeps going and going with " "plenty of words to test the greedy word wrapper.\nAnd a " "second paragraph.", reply_to=first, extra={ "attachments": [ {"id": "a1", "filename": "notes.txt", "mime": "text/plain", "size": 12}, {"id": "a2", "filename": "neb.png", "mime": "image/png", "size": len(ATTACHMENT_PNG), "url": "/api/attachments/a2"}], "threadCount": 2, "reactions": [{"emoji": "\U0001F44D", "count": 3}]}) add_message("c-secret", "u-alice", "Private channel, only us two.") add_message("d-alice", "u-alice", "Hi Test, this is a direct message!") # test has read general up to the history; the rest is unread msgs = STATE["messages"]["c-general"] if len(msgs) > 1: STATE["reads"][("c-general", "u-test")] = msgs[-2]["id"] def unread(cid, uid): msgs = [m for m in STATE["messages"][cid] if not m["deleted"]] last = STATE["reads"].get((cid, uid)) if last is None: return len([m for m in msgs if m["userId"] != uid]) idx = next((i for i, m in enumerate(msgs) if m["id"] == last), -1) return len([m for m in msgs[idx + 1:] if m["userId"] != uid]) def last_message(cid): msgs = [m for m in STATE["messages"][cid] if not m["deleted"]] if not msgs: return None m = msgs[-1] return {"id": m["id"], "body": m["body"][:160], "createdAt": m["createdAt"], "userId": m["userId"], "authorName": m["authorName"], "authorPicture": m.get("authorPicture", "")} def channel_json(c, uid): return {"id": c["id"], "name": c["name"], "type": c["type"], "description": c["description"], "archived": False, "memberCount": len(c["members"]), "isSelf": False, "unreadCount": unread(c["id"], uid), "lastMessage": last_message(c["id"])} def dm_json(c, uid): other = next((m for m in c["members"] if m != uid), None) u = STATE["users"].get(other) return {"id": c["id"], "type": "dm", "isSelf": other is None, "otherUser": dict(u, active=True) if u else None, "otherUserId": other, "unreadCount": unread(c["id"], uid), "lastMessage": last_message(c["id"]), "presence": STATE["presence"].get(other, "offline")} class Base(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" server_version = "MockChat/1.0" def log_message(self, fmt, *a): note("%s %s" % (self.server.label, fmt % a)) def cookies(self): out = {} for part in (self.headers.get("Cookie") or "").split(";"): if "=" in part: k, v = part.strip().split("=", 1) out[k] = v return out def body_json(self): n = int(self.headers.get("Content-Length") or 0) raw = self.rfile.read(n) if n else b"" if not raw: return {} try: return json.loads(raw.decode()) except ValueError: return None def send(self, status, body=b"", ctype="application/json", headers=None): if isinstance(body, (dict, list)): body = json.dumps(body).encode() elif isinstance(body, str): body = body.encode() self.send_response(status) for k, v in (headers or []): self.send_header(k, v) if status not in (204, 304): self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(body))) self.end_headers() if status not in (204, 304): self.wfile.write(body) def redirect(self, status, location, headers=None): self.send(status, "Redirecting to " + location, "text/plain", [("Location", location)] + (headers or [])) def chat_origin(self): return "http://%s:%d" % (ARGS.public_host, ARGS.chat_port) def login_origin(self): return "http://%s:%d" % (ARGS.public_host, ARGS.login_port) LOGIN_PAGE = """ Login
""" # The real Cloudron consent page (dashboard/oidc_interaction_confirm.html) is # a bare auto-submit form, not the login SPA: no cloudron-config JSON. CONSENT_PAGE = """ Authorize chat
""" class LoginHandler(Base): def do_GET(self): u = urlparse(self.path) parts = u.path.strip("/").split("/") with LOCK: if u.path == "/openid/auth": q = parse_qs(u.query) uid = secrets.token_urlsafe(12) STATE["interactions"][uid] = {"pre": q.get("state", [""])[0], "user": None, "consent": False, "icookie": secrets.token_hex(8)} it = STATE["interactions"][uid] return self.redirect(303, "/openid/interaction/" + uid, [ ("Set-Cookie", "_interaction=%s; path=/openid/interaction/%s; " "expires=Mon, 09 Nov 2026 20:00:00 GMT; samesite=lax; httponly" % (it["icookie"], uid)), ("Set-Cookie", "_interaction_resume=%s; path=/openid/auth/%s; " "httponly" % (it["icookie"], uid))]) if len(parts) == 3 and parts[:2] == ["openid", "interaction"]: uid = parts[2] it = STATE["interactions"].get(uid) if not it or self.cookies().get("_interaction") != it["icookie"]: return self.send(400, {"message": "interaction cookie missing"}) if it["user"] and it["consent"]: return self.send(200, CONSENT_PAGE % uid, "text/html") cfg = {"iconUrl": "/icon", "name": "chat", "note": "", "submitUrl": "/openid/interaction/%s/login" % uid, "passkeyLoginUrl": "/openid/interaction/%s/passkey_login" % uid, "footer": "© mock", "language": None} return self.send(200, LOGIN_PAGE % json.dumps(cfg), "text/html") if len(parts) == 3 and parts[:2] == ["openid", "auth"]: uid = parts[2] it = STATE["interactions"].get(uid) if not it or self.cookies().get("_interaction_resume") != it["icookie"]: return self.send(400, {"message": "resume cookie missing"}) if not it["user"]: return self.redirect(303, "/openid/interaction/" + uid) if it["consent"] and not it.get("confirmed"): return self.redirect(303, "/openid/interaction/" + uid) code = secrets.token_hex(8) STATE["interactions"][uid]["code"] = code return self.redirect(303, "%s/auth/callback?code=%s&state=%s" % (self.chat_origin(), code, it["pre"])) self.send(404, {"message": "not found"}) def do_POST(self): u = urlparse(self.path) parts = u.path.strip("/").split("/") body = self.body_json() with LOCK: if len(parts) == 4 and parts[:2] == ["openid", "interaction"]: uid = parts[2] it = STATE["interactions"].get(uid) if not it or self.cookies().get("_interaction") != it["icookie"]: return self.send(400, {"message": "interaction cookie missing"}) if body is None: return self.send(400, {"message": "bad JSON"}) if parts[3] == "login": note("login attempt user=%r totp=%r" % (body.get("username"), body.get("totpToken"))) user, pw = body.get("username"), body.get("password") if pw != "test" or user not in ("test", "totp", "passkey", "consent"): return self.send(401, {"status": "Unauthorized", "message": "Username and password does not match"}) if user == "passkey": return self.send(200, {"twoFactorRequired": True, "totpRequired": False, "passkeyOptions": {}}) if user == "totp": tok = body.get("totpToken") or "" if not tok: return self.send(200, {"twoFactorRequired": True, "totpRequired": True, "passkeyOptions": None}) if tok != "123456": return self.send(401, {"status": "Unauthorized", "message": "Invalid totpToken"}) it["user"] = "u-" + user it["consent"] = user == "consent" return self.send(200, {"redirectTo": "%s/openid/auth/%s" % (self.login_origin(), uid)}) if parts[3] == "confirm": if not it["user"]: return self.send(400, {"message": "not logged in"}) it["confirmed"] = True return self.redirect(303, "/openid/auth/" + uid) self.send(404, {"message": "not found"}) class ChatHandler(Base): def user(self): return STATE["sessions"].get(self.cookies().get("connect.sid")) def do_GET(self): u = urlparse(self.path) q = parse_qs(u.query) p = u.path with LOCK: if p == "/auth/login": sid = "pre-" + secrets.token_hex(8) STATE["sessions"][sid] = None return self.redirect(302, "%s/openid/auth?client_id=chat&state=%s" % (self.login_origin(), sid), [("Set-Cookie", "connect.sid=%s; Path=/; " "Expires=Mon, 23 Nov 2026 18:03:29 GMT; HttpOnly; SameSite=Lax" % sid)]) if p == "/auth/callback": sid = self.cookies().get("connect.sid") state = q.get("state", [""])[0] code = q.get("code", [""])[0] it = next((i for i in STATE["interactions"].values() if i.get("code") == code), None) if not sid or sid != state or sid not in STATE["sessions"] or not it: return self.redirect(302, "/?error=auth_failed") new = "s%3A" + it["user"] + "." + secrets.token_hex(8) del STATE["sessions"][sid] STATE["sessions"][new] = it["user"] return self.redirect(302, "/auth/return", [ ("Set-Cookie", "connect.sid=%s; Path=/; HttpOnly" % new)]) if p == "/auth/return": return self.redirect(302, "/") if p == "/auth/logout": STATE["sessions"].pop(self.cookies().get("connect.sid"), None) return self.redirect(302, "/", [ ("Set-Cookie", "connect.sid=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT")]) if p == "/": return self.send(200, "chat SPA", "text/html") if p == "/debug/state": st = {"messages": STATE["messages"], "reads": {"%s|%s" % k: v for k, v in STATE["reads"].items()}, "channels": {k: dict(v, members=sorted(v["members"])) for k, v in STATE["channels"].items()}, "sessions": STATE["sessions"], "log": STATE["log"][-200:]} return self.send(200, st) if p == "/api/config": return self.send(200, {"providerName": "Mock", "gifEnabled": False}) uid = self.user() if not uid: return self.send(401, {"error": "Unauthorized"}) if p == "/api/me": return self.send(200, dict(STATE["users"][uid], email="", active=True)) if p == "/api/channels": return self.send(200, [channel_json(c, uid) for c in STATE["channels"].values() if c["type"] != "dm" and uid in c["members"]]) if p == "/api/channels/public": return self.send(200, [channel_json(c, uid) for c in sorted(STATE["channels"].values(), key=lambda c: c["name"] or "") if c["type"] == "public" and uid not in c["members"]]) if p == "/api/dms": return self.send(200, [dm_json(c, uid) for c in STATE["channels"].values() if c["type"] == "dm" and uid in c["members"]]) if p == "/api/users": return self.send(200, [dict(x, email="", active=True) for x in STATE["users"].values()]) parts = p.strip("/").split("/") if len(parts) == 3 and parts[:2] == ["api", "avatars"]: if parts[2] in STATE["users"]: return self.send(200, avatar_png(parts[2]), "image/png") if len(parts) == 3 and parts[:2] == ["api", "attachments"]: if parts[2] == "a2": return self.send(200, ATTACHMENT_PNG, "image/png") if len(parts) == 4 and parts[:2] == ["api", "channels"] and parts[3] == "messages": c = STATE["channels"].get(parts[2]) if not c or uid not in c["members"]: return self.send(403, {"error": "Not a member"}) limit = min(int(q.get("limit", ["50"])[0]), 200) msgs = STATE["messages"][c["id"]] ids = [m["id"] for m in msgs] if "after" in q: a = q["after"][0] if a not in ids: return self.send(404, {"error": "Message not found"}) rows = msgs[ids.index(a) + 1:][:limit] return self.send(200, list(reversed(rows))) end = len(msgs) if "before" in q: b = q["before"][0] if b not in ids: return self.send(404, {"error": "Message not found"}) end = ids.index(b) rows = msgs[max(0, end - limit):end] return self.send(200, list(reversed(rows))) self.send(404, {"error": "Not found"}) def do_POST(self): u = urlparse(self.path) p = u.path body = self.body_json() with LOCK: if p == "/debug/inject": m = add_message(body["channel"], body.get("user", "u-alice"), body["body"]) return self.send(201, m) if p == "/debug/presence": STATE["presence"][body["user"]] = body["presence"] return self.send(200, {}) uid = self.user() if not uid: return self.send(401, {"error": "Unauthorized"}) if body is None: return self.send(400, {"error": "bad JSON"}) parts = p.strip("/").split("/") if p == "/api/dms": other = body.get("userId") if other not in STATE["users"]: return self.send(400, {"error": "Unknown user"}) for c in STATE["channels"].values(): if c["type"] == "dm" and c["members"] == {uid, other}: return self.send(200, dm_json(c, uid)) cid = "d-" + secrets.token_hex(4) add_channel(cid, None, "dm", [uid, other]) return self.send(201, dm_json(STATE["channels"][cid], uid)) if len(parts) == 4 and parts[:2] == ["api", "channels"]: c = STATE["channels"].get(parts[2]) if not c: return self.send(404, {"error": "Channel not found"}) if parts[3] == "join": if c["type"] != "public": return self.send(403, {"error": "Forbidden"}) c["members"].add(uid) return self.send(200, channel_json(c, uid)) if uid not in c["members"]: return self.send(403, {"error": "Not a member"}) if parts[3] == "read": msgs = STATE["messages"][c["id"]] if msgs: STATE["reads"][(c["id"], uid)] = msgs[-1]["id"] return self.send(200, {"unreadCount": 0}) if parts[3] == "messages": text = (body.get("body") or "").strip() if not text: return self.send(400, {"error": "Message must not be empty"}) cid_ = body.get("clientId") for m in STATE["messages"][c["id"]]: if cid_ and m["clientId"] == cid_: return self.send(201, m) m = add_message(c["id"], uid, text, client_id=cid_) STATE["reads"][(c["id"], uid)] = m["id"] return self.send(201, m) self.send(404, {"error": "Not found"}) def serve(handler, port, label): srv = ThreadingHTTPServer((ARGS.host, port), handler) srv.label = label srv.daemon_threads = True threading.Thread(target=srv.serve_forever, daemon=True).start() return srv def main(): global ARGS ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--host", default="0.0.0.0") ap.add_argument("--chat-port", type=int, default=18080) ap.add_argument("--login-port", type=int, default=18081) ap.add_argument("--public-host", default="10.0.2.2", help="address the guest uses to reach this host") ap.add_argument("--messages", type=int, default=120, help="history messages seeded into #general") ap.add_argument("-v", "--verbose", action="store_true") ARGS = ap.parse_args() seed(ARGS.messages) serve(ChatHandler, ARGS.chat_port, "chat") serve(LoginHandler, ARGS.login_port, "login") print("mock chat on :%d, login on :%d (guest: http://%s:%d)" % (ARGS.chat_port, ARGS.login_port, ARGS.public_host, ARGS.chat_port), flush=True) try: threading.Event().wait() except KeyboardInterrupt: pass if __name__ == "__main__": main()