#!/usr/bin/env python3 """Convivo provisioning portal served in place of comitup-web while the Pi is in HOTSPOT. Wi-Fi picker (comitup D-Bus) plus optional Convivo URL / anon key / station token, which are written to /opt/convivo-printer/.env and applied with docker compose. Only the standard library plus python3-dbus (already required by comitup) is used; dbus is imported lazily so the pure helpers stay unit-testable. """ from __future__ import annotations import html import json import os import re import secrets import subprocess import sys import threading import time import urllib.parse from http.cookies import SimpleCookie from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer ENV_FILE = os.environ.get("PORTAL_ENV_FILE", "/opt/convivo-printer/.env") PORT = int(os.environ.get("PORTAL_PORT", "80")) DRY_RUN = os.environ.get("PORTAL_DRY_RUN", "0") == "1" COMPOSE_FILE = "/opt/convivo-printer/docker-compose.yml" AP_ADDR = "10.41.0.1" MAX_BODY_BYTES = 8192 TOKEN_PREFIX = "cvp_" TOKEN_LENGTH = 68 # The only keys the portal may write; anything else is rejected. ENV_KEY_WHITELIST = ("CONVIVO_URL", "CONVIVO_ANON_KEY", "PRINTER_STATION_TOKEN") DBUS_NAME = "com.github.davesteele.comitup" DBUS_PATH = "/com/github/davesteele/comitup" FAKE_NETWORKS = [ {"ssid": "FakeOffice", "strength": "82", "security": "encrypted"}, {"ssid": "FakeOpen", "strength": "40", "security": "unencrypted"}, ] # --------------------------------------------------------------------------- # Pure helpers (unit-tested, no dbus / no root) # --------------------------------------------------------------------------- def parse_env(text: str) -> dict[str, str]: result: dict[str, str] = {} for line in text.splitlines(): line = line.strip() if not line or line.startswith("#") or "=" not in line: continue key, _, value = line.partition("=") result[key.strip()] = value.strip() return result def update_env(text: str, updates: dict[str, str]) -> str: """Rewrite env text with `updates`; unknown lines are preserved as-is.""" for key in updates: if key not in ENV_KEY_WHITELIST: raise ValueError(f"key not allowed: {key}") value = updates[key] if "=" in value or any(c in value for c in "\r\n"): raise ValueError(f"value for {key} must not contain newlines or '='") lines = text.splitlines() seen: set[str] = set() out: list[str] = [] for line in lines: stripped = line.strip() if stripped and not stripped.startswith("#") and "=" in stripped: key = stripped.partition("=")[0].strip() if key in updates: out.append(f"{key}={updates[key]}") seen.add(key) continue out.append(line) for key in updates: if key not in seen: out.append(f"{key}={updates[key]}") return "\n".join(out) + "\n" def write_env(path: str, text: str) -> None: """Atomically replace `path` with owner-only mode 0600.""" tmp = f"{path}.tmp" fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) with os.fdopen(fd, "w", encoding="utf-8") as fh: fh.write(text) os.chmod(tmp, 0o600) os.replace(tmp, path) def mask_token(token: str) -> str: if not token: return "" return f"{TOKEN_PREFIX}…{token[-4:]}" if len(token) > 8 else f"{TOKEN_PREFIX}…" def _is_private_host(host: str) -> bool: host = host.strip("[]").lower() if host in ("localhost", "localhost.localdomain") or host.endswith(".local"): return True m = re.fullmatch(r"(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})", host) if not m: return False a, b = int(m.group(1)), int(m.group(2)) return a == 10 or (a == 172 and 16 <= b <= 31) or (a == 192 and b == 168) or a == 127 def validate_url(value: str) -> tuple[str | None, str | None]: """Return (error, warning) for a Convivo URL; warning set for plaintext http on a LAN host.""" try: parsed = urllib.parse.urlsplit(value) except ValueError as exc: return f"URL is not valid: {exc}", None host = (parsed.hostname or "").lower() if parsed.scheme == "https" and host: return None, None if parsed.scheme == "http" and host and _is_private_host(host): return None, ("http:// works only on the local network — it sends the station " "token unencrypted; prefer https://.") return "URL must start with https:// (http:// only for a local/LAN address).", None def validate_anon_key(value: str) -> str | None: parts = value.split(".") if len(parts) != 3 or not all(parts): return "Anon key must look like a JWT: three base64url parts separated by dots." if not all(re.fullmatch(r"[A-Za-z0-9_\-]+", p) for p in parts): return "Anon key must look like a JWT: three base64url parts separated by dots." return None def validate_token(value: str) -> str | None: if not value.startswith(TOKEN_PREFIX): return f"Station token must start with {TOKEN_PREFIX}." if len(value) != TOKEN_LENGTH: return f"Station token must be exactly {TOKEN_LENGTH} characters." return None def sort_aps(aps: list[dict]) -> list[dict]: def strength(ap: dict) -> float: try: return float(ap.get("strength", 0)) except (TypeError, ValueError): return 0.0 return sorted(aps, key=strength, reverse=True) def parse_connect(form: dict) -> tuple[str, str, dict[str, str], list[str], list[str]]: """Validate portal form fields. Returns (ssid, password, env-updates, errors, warnings).""" errors: list[str] = [] warnings: list[str] = [] ssid = (form.get("hidden_ssid") if form.get("hidden") else form.get("ssid")) or "" ssid = ssid.strip() if len(ssid.encode("utf-8")) > 32 or any(c in ssid for c in "\r\n"): errors.append("Network name is too long or contains invalid characters.") ssid = "" password = form.get("password") or "" if not ssid and not errors: errors.append("Please choose a Wi-Fi network (or enter a hidden network name).") if any(c in password for c in "\r\n"): errors.append("Password contains invalid characters.") if len(password) > 128: errors.append("Password is too long.") updates: dict[str, str] = {} url = (form.get("convivo_url") or "").strip() if url: err, warn = validate_url(url) if err: errors.append(err) else: if warn: warnings.append(warn) updates["CONVIVO_URL"] = url anon = (form.get("anon_key") or "").strip() if anon: err = validate_anon_key(anon) if err: errors.append(err) else: updates["CONVIVO_ANON_KEY"] = anon token = (form.get("station_token") or "").strip() if token: err = validate_token(token) if err: errors.append(err) else: updates["PRINTER_STATION_TOKEN"] = token return ssid, password, updates, errors, warnings # --------------------------------------------------------------------------- # comitup D-Bus client (verified against comitup/statemgr.py) # --------------------------------------------------------------------------- _dbus_proxy = None _dbus_lock = threading.Lock() def _comitup_proxy(): global _dbus_proxy with _dbus_lock: if _dbus_proxy is None: import dbus # lazy: unit tests never need python3-dbus bus = dbus.SystemBus() _dbus_proxy = bus.get_object(DBUS_NAME, DBUS_PATH) return _dbus_proxy def comitup_access_points() -> list[dict]: """access_points() -> aa{ss}: dicts with ssid, strength (0-100 %), security.""" raw = _comitup_proxy().access_points(dbus_interface=DBUS_NAME) return [ { "ssid": str(ap.get("ssid", "")), "strength": str(ap.get("strength", "")), "security": str(ap.get("security", "")), } for ap in raw ] def comitup_state() -> tuple[str, str]: """state() -> ss: (HOTSPOT|CONNECTING|CONNECTED, connection).""" state, connection = _comitup_proxy().state(dbus_interface=DBUS_NAME) return str(state), str(connection) def comitup_connect(ssid: str, password: str) -> None: """connect(ss, ss): activate/create a NM profile for the SSID and drop the AP.""" _comitup_proxy().connect(ssid, password, dbus_interface=DBUS_NAME) def list_networks() -> list[dict]: if DRY_RUN: return sort_aps(list(FAKE_NETWORKS)) return sort_aps(comitup_access_points()) # --------------------------------------------------------------------------- # HTML rendering (inline CSS only — no internet in hotspot mode) # --------------------------------------------------------------------------- BASE_CSS = """ *{box-sizing:border-box} body{margin:0;font-family:system-ui,-apple-system,'Segoe UI',Roboto,sans-serif; background:#f2f4f7;color:#1c1e21} .wrap{max-width:480px;margin:0 auto;padding:20px 16px 40px} header{display:flex;align-items:center;gap:10px;margin-bottom:16px} header .dot{width:12px;height:12px;border-radius:50%;background:#e8590c} header h1{font-size:19px;margin:0;font-weight:700} header p{margin:0;font-size:12.5px;color:#6b7280} .card{background:#fff;border-radius:14px;padding:16px;margin-bottom:14px; box-shadow:0 1px 3px rgba(0,0,0,.08)} h2{font-size:13px;margin:0 0 12px;text-transform:uppercase;letter-spacing:.04em;color:#6b7280} label{display:block;font-size:13.5px;font-weight:600;margin:12px 0 4px} input,select{width:100%;padding:12px;font-size:16px;border:1px solid #d1d5db; border-radius:10px;background:#fff} input[type=checkbox]{width:auto} .row{display:flex;align-items:center;gap:8px;margin-top:10px;font-size:14px} .row label{margin:0;font-weight:500} button{width:100%;margin-top:18px;padding:14px;font-size:16px;font-weight:700;color:#fff; background:#0b57d0;border:0;border-radius:12px} button:active{transform:scale(.99)} .note{font-size:12.5px;color:#6b7280;margin:6px 0 0} .err{background:#fdecea;border:1px solid #f5c2c0;color:#8a1f11;border-radius:10px; padding:10px 12px;font-size:14px;margin-bottom:12px} .err ul{margin:0;padding-left:18px} .warn{background:#fff8e1;border:1px solid #ffe08a;color:#7a5b00;border-radius:10px; padding:10px 12px;font-size:13.5px;margin-bottom:12px} .warn ul{margin:0;padding-left:18px} .current{font-size:13.5px;color:#374151;margin:0 0 6px;word-break:break-all} details summary{cursor:pointer;font-size:13px;text-transform:uppercase; letter-spacing:.04em;color:#6b7280;font-weight:700} details[open] summary{margin-bottom:10px} .ok{background:#e6f4ea;border:1px solid #b7dfc0;color:#1e4620;border-radius:10px; padding:10px 12px;font-size:14px;margin-bottom:12px} .spin{width:34px;height:34px;margin:0 auto 14px;border:4px solid #d1d5db; border-top-color:#0b57d0;border-radius:50%;animation:s 1s linear infinite} @keyframes s{to{transform:rotate(360deg)}} .center{text-align:center} """ HIDDEN_JS = """ var cb=document.getElementById('hidden-cb'),sel=document.getElementById('ssid'), hid=document.getElementById('hidden-ssid'); function sync(){sel.disabled=cb.checked;hid.style.display=cb.checked?'block':'none'; if(cb.checked)hid.focus();} cb.addEventListener('change',sync);sync(); """ def _e(value: object) -> str: return html.escape(str(value), quote=True) def _network_options(aps: list[dict]) -> str: options = [''] for ap in aps: enc = "encrypted" if ap.get("security") == "encrypted" else "open" options.append( f'' ) return "\n".join(options) def render_page(title: str, body: str) -> bytes: doc = ( "" "" "" f"{_e(title)}" f"
" "

Convivo Printer

Wi-Fi setup · 10.41.0.1

" f"{body}
" ) return doc.encode("utf-8") def render_form(aps: list[dict], current: dict, errors: list[str], warnings: list[str], csrf: str) -> bytes: parts: list[str] = [] if errors: parts.append('
") if warnings: parts.append('
") if not aps: parts.append('
No networks found right now — use “hidden network”, ' "or press refresh after a moment.
") url = current.get("CONVIVO_URL", "") station = current.get("STATION_NAME", "") token_mask = mask_token(current.get("PRINTER_STATION_TOKEN", "")) _, url_warn = validate_url(url) if url else (None, None) parts.append( "
" f"" '

1 · Wi-Fi network

' f'' '
' "
" '' '' '' '

The printer keeps any network it already knows and always ' "prefers internet access.

" "
" '

2 · Convivo connection (optional)

' f'

Current URL: {_e(url) or "—"}

' f'

Station name: {_e(station) or "—"}

' f'

Station token: {_e(token_mask) or "not set"}

' + (f'
  • {_e(url_warn)}
' if url_warn else "") + '' '' '' '' '' '' '

Blank fields keep the current values; tokens are never shown in full.

' "
" "" "
" "

Refresh network list

" f"" ) return render_page("Convivo Printer — Wi-Fi setup", "".join(parts)) def render_switching(ssid: str, applied: list[str]) -> bytes: applied_text = ( " · ".join(_e(k) for k in applied) if applied else "no changes — current settings kept" ) body = ( '
' '
' "

Switching networks…

" f"

The printer is leaving this hotspot and joining {_e(ssid)}.

" f'

Convivo settings: {applied_text}

' '

This page will update when the Pi leaves the hotspot.

' "
" '" '

In the Convivo admin console the printer pill turns ' "green as soon as the station is online. If it stays grey for more " "than a minute, the Wi-Fi credentials or the Convivo URL/token may be wrong — power " "the printer off and on again to get the hotspot back.

" "" '' ) return render_page("Switching networks…", body) # --------------------------------------------------------------------------- # HTTP server # --------------------------------------------------------------------------- class PortalHandler(BaseHTTPRequestHandler): server_version = "ConvivoPortal/1.0" protocol_version = "HTTP/1.1" def log_message(self, fmt, *args): # keep stdout quiet on the Pi pass # -- helpers ------------------------------------------------------------ def _cookies(self) -> SimpleCookie: cookie = SimpleCookie() raw = self.headers.get("Cookie") if raw: cookie.load(raw) return cookie def _respond(self, code: int, body: bytes, content_type: str, extra_headers: list[tuple[str, str]] | None = None) -> None: self.send_response(code) self.send_header("Content-Type", content_type) self.send_header("Content-Length", str(len(body))) self.send_header("Cache-Control", "no-store") for key, value in extra_headers or []: self.send_header(key, value) self.end_headers() self.wfile.write(body) def _redirect_to_portal(self) -> None: # Captive-portal probes (captive.apple.com, connectivity-check, …) land here. self._respond(302, b"", "text/plain; charset=utf-8", [("Location", f"http://{AP_ADDR}/")]) # -- routes ------------------------------------------------------------- def do_GET(self) -> None: # noqa: N802 path = urllib.parse.urlsplit(self.path).path if path == "/": try: aps = list_networks() except Exception: aps = [] try: with open(ENV_FILE, encoding="utf-8") as fh: current = parse_env(fh.read()) except OSError: current = {} csrf = secrets.token_hex(16) body = render_form(aps, current, [], [], csrf) self._respond(200, body, "text/html; charset=utf-8", [("Set-Cookie", f"portal_csrf={csrf}; Path=/; Max-Age=3600")]) elif path == "/networks.json": try: aps = list_networks() except Exception as exc: self._respond(503, json.dumps({"error": str(exc)}).encode(), "application/json") return self._respond(200, json.dumps({"networks": aps}).encode(), "application/json") elif path == "/status": try: state, connection = ("HOTSPOT", "") if DRY_RUN else comitup_state() except Exception: state, connection = "UNKNOWN", "" self._respond(200, json.dumps({"state": state, "connection": connection}).encode(), "application/json") else: self._redirect_to_portal() def do_POST(self) -> None: # noqa: N802 path = urllib.parse.urlsplit(self.path).path if path != "/connect": self.close_connection = True # the body is not read self._respond(405, b"", "text/plain; charset=utf-8") return try: length = int(self.headers.get("Content-Length") or 0) except ValueError: length = -1 if length < 0 or length > MAX_BODY_BYTES: # The unread body would corrupt a kept-alive connection. self.close_connection = True self._respond(431, b"", "text/plain; charset=utf-8") return body = self.rfile.read(length).decode("utf-8", "replace") form = {k: v for k, v in urllib.parse.parse_qsl(body, keep_blank_values=True)} cookie = self._cookies().get("portal_csrf") expected = cookie.value if cookie else "" def show_form(errors: list[str], warnings: list[str]) -> None: try: aps = list_networks() except Exception: aps = [] try: with open(ENV_FILE, encoding="utf-8") as fh: current = parse_env(fh.read()) except OSError: current = {} csrf = secrets.token_hex(16) body_bytes = render_form(aps, current, errors, warnings, csrf) self._respond(400, body_bytes, "text/html; charset=utf-8", [("Set-Cookie", f"portal_csrf={csrf}; Path=/; Max-Age=3600")]) if not expected or not secrets.compare_digest(form.get("csrf", ""), expected): show_form(["The form expired — please try again."], []) return ssid, password, updates, errors, warnings = parse_connect(form) if errors: show_form(errors, warnings) return if updates: try: with open(ENV_FILE, encoding="utf-8") as fh: old = fh.read() except OSError: old = "" try: write_env(ENV_FILE, update_env(old, updates)) except ValueError as exc: show_form([str(exc)], warnings) return if ssid: if DRY_RUN: sys.stderr.write(f"[dry-run] would comitup connect to {ssid!r}\n") else: worker = threading.Thread( target=self._connect_worker, args=(ssid, password, bool(updates)), daemon=True, ) worker.start() body_bytes = render_switching(ssid or "(no network change)", sorted(updates)) self._respond(200, body_bytes, "text/html; charset=utf-8") def _connect_worker(self, ssid: str, password: str, env_changed: bool) -> None: # Let the HTTP response flush before the AP disappears / docker bounces. time.sleep(1.0) if env_changed: try: subprocess.run( ["docker", "compose", "-f", COMPOSE_FILE, "up", "-d", "--force-recreate"], check=False, timeout=180, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, ) except Exception as exc: sys.stderr.write(f"portal: docker compose failed: {exc}\n") time.sleep(0.5) try: comitup_connect(ssid, password) except Exception as exc: sys.stderr.write(f"portal: comitup connect failed: {exc}\n") def main() -> None: server = ThreadingHTTPServer(("0.0.0.0", PORT), PortalHandler) sys.stderr.write(f"convivo portal listening on :{PORT} (env={ENV_FILE}, dry_run={DRY_RUN})\n") try: server.serve_forever() except KeyboardInterrupt: pass if __name__ == "__main__": main()