| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492 |
- #!/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
- login (default port 18081): /openid/auth, /openid/interaction/<uid>
- (HTML with the cloudron-config JSON), 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 threading
- 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"},
- "u-alice": {"id": "u-alice", "username": "alice", "name": "Alice Example"},
- "u-bob": {"id": "u-bob", "username": "bob", "name": "Bob Böhm"},
- "u-carol": {"id": "u-carol", "username": "carol", "name": "Carol"},
- "u-totp": {"id": "u-totp", "username": "totp", "name": "Totp User"},
- "u-consent": {"id": "u-consent", "username": "consent", "name": "Consent User"},
- },
- "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 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"], "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}],
- "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": ""}
- 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 = """<!DOCTYPE html>
- <html><head><title>Login</title>
- <script id="cloudron-config" type="application/json">
- %s
- </script>
- <script type="module" crossorigin src="/assets/oidc_login.js"></script>
- </head><body><div id="app"></div></body></html>
- """
- 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"]:
- cfg = {"name": "chat", "submitUrl": "/openid/interaction/%s/confirm" % uid}
- else:
- 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, "<!DOCTYPE html><html><body>chat SPA</body></html>",
- "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="", picture="",
- 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="", picture="", active=True)
- for x in STATE["users"].values()])
- parts = p.strip("/").split("/")
- 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()
|