#!/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"Wi-Fi setup · 10.41.0.1
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.