Files
Convivo/apps/printer/portal/portal.py
T
00c89c1b48 feat(printer): badge print queue, Pi worker, captive-portal setup, admin printing view
- migration 20261018170000: pgmq badge_print/badge_print_dlq, print_stations,
  token-gated printer RPCs (claim/complete/fail/heartbeat), admin RPCs,
  welcome_checkin enqueue; badge_print_tests.sql (101 assertions)
- apps/printer: Python worker (Playwright render -> brother_ql via pyusb),
  comitup captive-portal (Wi-Fi + HTTPS endpoint + anon key + token),
  arm64 image build + idempotent Pi setup/install scripts, 77 pytest
- apps/admin: Printing view, station management/DLQ, global printer status
  pill, Print button on Registrations, standalone print renderer entry
  (print.html -> dist-print) with bundled fonts
- docs: printing.md + architecture/schema/rpcs/tests/admin-app updates,
  apps/printer/AGENT.md operating manual
- e2e: printing.spec.ts

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-18 22:25:38 +02:00

586 lines
23 KiB
Python

#!/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 = ['<option value="" disabled selected>Choose a network…</option>']
for ap in aps:
enc = "encrypted" if ap.get("security") == "encrypted" else "open"
options.append(
f'<option value="{_e(ap["ssid"])}">{_e(ap["ssid"])} — {enc}, '
f'signal {_e(ap.get("strength", "?"))}%</option>'
)
return "\n".join(options)
def render_page(title: str, body: str) -> bytes:
doc = (
"<!doctype html><html lang=en><head>"
"<meta charset=utf-8>"
"<meta name=viewport content='width=device-width,initial-scale=1'>"
f"<title>{_e(title)}</title><style>{BASE_CSS}</style></head>"
f"<body><div class=wrap><header><span class=dot></span><div>"
"<h1>Convivo Printer</h1><p>Wi-Fi setup · 10.41.0.1</p></div></header>"
f"{body}</div></body></html>"
)
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('<div class=err><ul>' + "".join(f"<li>{_e(e)}</li>" for e in errors) + "</ul></div>")
if warnings:
parts.append('<div class=warn><ul>' + "".join(f"<li>{_e(w)}</li>" for w in warnings) + "</ul></div>")
if not aps:
parts.append('<div class=warn>No networks found right now — use “hidden network”, '
"or press refresh after a moment.</div>")
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(
"<form method=POST action=/connect>"
f"<input type=hidden name=csrf value=\"{_e(csrf)}\">"
'<div class=card><h2>1 · Wi-Fi network</h2>'
f'<label for=ssid>Network</label><select id=ssid name=ssid>{_network_options(aps)}</select>'
'<div class=row><input type=checkbox id=hidden-cb name=hidden value=1>'
"<label for=hidden-cb>My network is hidden</label></div>"
'<input id=hidden-ssid name=hidden_ssid type=text maxlength=32 style=display:none '
'placeholder="Hidden network name (SSID)" autocomplete=off>'
'<label for=password>Password</label>'
'<input id=password name=password type=password maxlength=128 autocomplete=off '
'placeholder="Leave empty for an open network">'
'<p class=note>The printer keeps any network it already knows and always '
"prefers internet access.</p>"
"</div>"
'<div class=card><h2>2 · Convivo connection (optional)</h2>'
f'<p class=current>Current URL: <strong>{_e(url) or "—"}</strong></p>'
f'<p class=current>Station name: <strong>{_e(station) or "—"}</strong></p>'
f'<p class=current>Station token: <strong>{_e(token_mask) or "not set"}</strong></p>'
+ (f'<div class=warn><ul><li>{_e(url_warn)}</li></ul></div>' if url_warn else "")
+ '<label for=convivo_url>Convivo URL</label>'
'<input id=convivo_url name=convivo_url type=url inputmode=url autocomplete=off '
'placeholder="https://admin.appe.at — empty keeps current">'
'<label for=anon_key>Anon key</label>'
'<input id=anon_key name=anon_key type=text autocomplete=off '
'placeholder="eyJ… JWT — empty keeps current">'
'<label for=station_token>Station token</label>'
'<input id=station_token name=station_token type=password autocomplete=off '
'placeholder="cvp_… — empty keeps current">'
'<p class=note>Blank fields keep the current values; tokens are never shown in full.</p>'
"</div>"
"<button type=submit>Connect</button>"
"</form>"
"<p class=center><a href=/networks.json class=note>Refresh network list</a></p>"
f"<script>{HIDDEN_JS}</script>"
)
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 = (
'<div class="card center">'
'<div class=spin id=spin></div>'
"<h2 style=text-transform:none>Switching networks…</h2>"
f"<p>The printer is leaving this hotspot and joining <strong>{_e(ssid)}</strong>.</p>"
f'<p class=note>Convivo settings: {applied_text}</p>'
'<p class=note>This page will update when the Pi leaves the hotspot.</p>'
"</div>"
'<div class=card id=done style=display:none><div class=ok><strong>Network applied.</strong></div>'
"<p class=note>The open <em>Convivo-Printer</em> hotspot is gone — reconnect your phone "
"to your own Wi-Fi.</p></div>"
'<div class=card><p class=note>In the Convivo admin console the printer pill turns '
"<strong>green</strong> 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.</p></div>"
"<script>var done=false;function poll(){fetch('/status').then(function(r){return r.json()})"
".then(function(j){if(!done&&j.state!=='HOTSPOT'){done=true;"
"document.getElementById('spin').style.display='none';"
"document.getElementById('done').style.display='block';}}).catch(function(){});}"
"setInterval(poll,2000);poll();</script>"
'<meta http-equiv="refresh" content="6">'
)
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()