#!/usr/bin/env python3 """Sign in to Multica with your exe.dev login, and send its email through exe.dev. Multi-purpose helper for Multica on an exe.dev VM, Python standard library only. SMTP on port 2525, inside the Compose network only: Multica sends its email here. A sign-in code this bridge asked for itself is kept and used (see below); everything else goes, as plain text, to the VM's email gateway (https://exe.dev/docs/send-email). HTTP on port 8090, which nginx serves at /exe-login: exe.dev's proxy tells the VM who is visiting in the X-ExeDev-Email header. The bridge asks Multica for a sign-in code for that address, catches the code on its way out by SMTP, hands it back to Multica, and passes Multica's session cookies to the browser. It uses only Multica's public sign-in API (POST /auth/send-code and /auth/verify-code). Only exe.dev's proxy may reach it: nginx listens on 127.0.0.1, and the proxy strips any X-ExeDev-* header a browser sends. """ import email import email.policy import html import json import os import re import socketserver import threading import time import urllib.error import urllib.parse import urllib.request from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer GATEWAY = "http://169.254.169.254/gateway/email/send" BACKEND = os.environ.get("MULTICA_BACKEND", "http://backend:8080") CODE_SUBJECT = "Your Multica verification code" # Addresses this bridge is signing in right now -> the code once it arrives. pending = {} pending_lock = threading.Lock() def log(*args): print(*args, flush=True) # ---------- SMTP ---------- def parse(raw): msg = email.message_from_bytes(raw, policy=email.policy.default) part = msg.get_body(preferencelist=("plain", "html")) body = part.get_content() if part else "" if part is not None and part.get_content_type() == "text/html": body = re.sub(r']*href="([^"]+)"[^>]*>(.*?)', r"\2: \1", body, flags=re.S) body = html.unescape(re.sub(r"<[^>]+>", "\n", body)) lines = (" ".join(line.split()) for line in body.splitlines()) return str(msg.get("Subject", "Multica")), "\n\n".join(l for l in lines if l) def catch_code(to, subject, body): """Keep a sign-in code the bridge asked for. True if it was one.""" if subject != CODE_SUBJECT: return False with pending_lock: slot = pending.get(to.lower()) if slot is None: return False m = re.search(r"(?")) self.reply("250 OK") elif verb == "DATA": self.reply("354 End with .") data = b"" while (chunk := self.rfile.readline()) not in (b".\r\n", b".\n", b""): data += chunk[1:] if chunk.startswith(b".") else chunk subject, body = parse(data) failed = [] for to in rcpts: if catch_code(to, subject, body): log(f"sign-in code for {to}: kept for exe.dev sign-in") continue status, err = send(to, subject, body) log(f"{subject!r} to {to}: {status} {err}") if status != 200: failed.append(f"{to}: {status} {err}") self.reply("554 " + "; ".join(failed)[:400] if failed else "250 Sent") rcpts = [] elif verb in ("RSET", "NOOP"): rcpts = [] if verb == "RSET" else rcpts self.reply("250 OK") elif verb == "QUIT": self.reply("221 Bye") return else: self.reply("502 Not implemented") class SMTPServer(socketserver.ThreadingTCPServer): allow_reuse_address = True daemon_threads = True # ---------- HTTP: /exe-login ---------- def post(path, payload): req = urllib.request.Request( BACKEND + path, data=json.dumps(payload).encode(), headers={"Content-Type": "application/json"}, ) try: with urllib.request.urlopen(req, timeout=30) as resp: return resp.status, resp.headers.get_all("Set-Cookie") or [], resp.read() except urllib.error.HTTPError as e: return e.code, [], e.read() def sign_in(addr): """Return Multica's Set-Cookie headers for addr, or raise RuntimeError.""" slot = {"event": threading.Event(), "code": None} with pending_lock: if addr in pending: raise RuntimeError("A sign-in for this address is already running. Try again in a moment.") pending[addr] = slot try: deadline = time.time() + 75 while True: status, _, body = post("/auth/send-code", {"email": addr}) if status == 200: break # Multica allows one code per address a minute. if status == 429 and time.time() < deadline: time.sleep(5) continue raise RuntimeError(f"Multica refused to sign you in ({status}): {body.decode(errors='replace')[:200]}") if not slot["event"].wait(20): raise RuntimeError("Multica's sign-in code never reached the bridge. Check SMTP_HOST=bridge in ~/multica/.env.") status, cookies, body = post("/auth/verify-code", {"email": addr, "code": slot["code"]}) if status != 200 or not cookies: raise RuntimeError(f"Multica rejected the sign-in ({status}): {body.decode(errors='replace')[:200]}") return cookies finally: with pending_lock: pending.pop(addr, None) def safe_next(value): value = value or "" if not value.startswith("/") or value.startswith("//") or value.startswith("/\\"): return "" return value CHECK_PAGE = """ Signing in to Multica

Signing you in to Multica as {who}…

""" ERROR_PAGE = """ Sign-in failed

Couldn't sign you in to Multica

{msg}

Try again

""" SIGNED_OUT_PAGE = """ Signed out of Multica

Signed out of Multica

Sign in again as {who}

""" class HTTPHandler(BaseHTTPRequestHandler): server_version = "multica-bridge" def log_message(self, fmt, *args): log("http:", fmt % args) def page(self, status, body, headers=()): data = body.encode() self.send_response(status) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Cache-Control", "no-store") for k, v in headers: self.send_header(k, v) self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) def do_GET(self): url = urllib.parse.urlsplit(self.path) query = urllib.parse.parse_qs(url.query) nxt = safe_next(query.get("next", [""])[0]) addr = (self.headers.get("X-ExeDev-Email") or "").strip().lower() if not addr: return self.page(403, ERROR_PAGE.format(msg="No exe.dev login on this request. Open the VM's https://VMNAME.exe.xyz/ address.")) # After signing in, Multica's own /login page sends people on to # `next`, their workspace, or onboarding. done = "/login" + ("?next=" + urllib.parse.quote(nxt, safe="/") if nxt else "") if url.path in ("/exe-login", "/exe-login/"): go = "/exe-login/go" + ("?next=" + urllib.parse.quote(nxt, safe="/") if nxt else "") # nginx sets exe_signed_out when someone logs out of Multica, so # logging out doesn't sign them straight back in. cookie = self.headers.get("Cookie") or "" who = re.search(r"(?:^|;)\s*exe_who=([^;]*)", cookie) if who and who.group(1) != addr: # A Multica session for a different exe.dev user: replace it. self.send_response(302) self.send_header("Location", go) self.send_header("Cache-Control", "no-store") self.send_header("Content-Length", "0") self.end_headers() return if re.search(r"(^|;)\s*exe_signed_out=1", cookie): return self.page(200, SIGNED_OUT_PAGE.format(who=html.escape(addr), go_html=html.escape(go))) # The session cookie is SameSite=Strict, so a visit from a link # elsewhere doesn't show it. Check from the page first. return self.page(200, CHECK_PAGE.format( who=html.escape(addr), done=json.dumps(done), go=json.dumps(go), go_html=html.escape(go))) if url.path == "/exe-login/go": try: cookies = sign_in(addr) except RuntimeError as e: log(f"sign-in for {addr} failed: {e}") return self.page(502, ERROR_PAGE.format(msg=html.escape(str(e)))) log(f"signed in {addr}") self.send_response(302) for c in cookies: self.send_header("Set-Cookie", c) self.send_header("Set-Cookie", "exe_signed_out=; Path=/; Max-Age=0; Secure; HttpOnly; SameSite=Lax") # Remember whose exe.dev login this Multica session belongs to, so # nginx can sign the browser in again when the exe.dev user changes. if re.fullmatch(r"[a-z0-9@._+-]+", addr): self.send_header("Set-Cookie", f"exe_who={addr}; Path=/; Max-Age=2592000; Secure; HttpOnly; SameSite=Lax") self.send_header("Location", done) self.send_header("Cache-Control", "no-store") self.send_header("Content-Length", "0") self.end_headers() return self.page(404, ERROR_PAGE.format(msg="Not found.")) if __name__ == "__main__": threading.Thread(target=SMTPServer(("0.0.0.0", 2525), SMTPHandler).serve_forever, daemon=True).start() log("multica bridge: SMTP on :2525, exe.dev sign-in on :8090") ThreadingHTTPServer(("0.0.0.0", 8090), HTTPHandler).serve_forever()