From 27c8eeb37c186adc1a42a859bc9541c174e082e9 Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 26 Oct 2026 11:55:50 +0100 Subject: [PATCH] Offer secure (HTTPS) and unsecured (HTTP) access side by side, add a QR codes page Optional plain HTTP port next to HTTPS (server.http_port, off by default): - open_sites()/serve() replace web.run_app: one AppRunner, two TCPSites, so the tablet picks https://:8765 or http://:8766 without a restart - http_port requires TLS and must differ from port (validated in config.py) - make http-on / http-off (--http-port N) write or remove the line, restoring the file if the result is invalid; make firewall accepts HTTP_PORT - make url prints both addresses and QR codes QR codes page (make qr, --qr): - self-contained HTML written with mode 600 in $XDG_RUNTIME_DIR and opened as file://, never served: the codes contain the access token - qrencode SVG with crispEdges (no seams between modules), fr/en from LANG - cards for HTTPS, HTTP and the CA certificate, depending on the config Tests: 107 (dual listeners with the local CA, set_http_port, QR page content and file mode). Docs: README fr/en and CLAUDE.md updated. Co-Authored-By: Claude Sonnet 5.5 --- CLAUDE.md | 11 ++- Makefile | 19 +++- README-EN.md | 45 ++++++++- README.md | 45 ++++++++- config.example.toml | 5 + mediadeck/__main__.py | 91 +++++++++++++++--- mediadeck/config.py | 11 +++ mediadeck/qrpage.py | 219 ++++++++++++++++++++++++++++++++++++++++++ mediadeck/server.py | 29 ++++++ mediadeck/tls.py | 24 ++++- tests/test_config.py | 20 ++++ tests/test_qrpage.py | 89 +++++++++++++++++ tests/test_serve.py | 95 ++++++++++++++++++ tests/test_tls.py | 50 +++++++++- 14 files changed, 726 insertions(+), 27 deletions(-) create mode 100644 mediadeck/qrpage.py create mode 100644 tests/test_qrpage.py create mode 100644 tests/test_serve.py diff --git a/CLAUDE.md b/CLAUDE.md index f6555b9..4a5fa92 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -38,7 +38,8 @@ make service-install / status / logs mediadeck/ ├── __main__.py CLI : --config, --check, --url, -v ; lance web.run_app ├── config.py TOML → dataclasses gelées ; validation stricte ; refuse un fichier lisible par group/other -├── server.py aiohttp : /, /static/*, /ws (jeton), /art (jeton) ; diffusion d'état anti-rebond 100 ms + toutes les 10 s +├── server.py aiohttp : /, /static/*, /ws (jeton), /art (jeton) ; diffusion d'état anti-rebond 100 ms + toutes les 10 s ; +│ open_sites()/serve() : port principal (HTTPS si TLS) + port HTTP en clair facultatif (`http_port`) ├── mpris.py MprisManager : découverte via NameOwnerChanged, PropertiesChanged + Seeked ; Player.execute() ├── audio.py AudioManager : `pactl -f json list sinks`, `pactl subscribe` (relancé si mort), set-sink-* ├── input.py VirtualInput : 2 périphériques uinput (clavier + pointeur), touches en liste blanche + TYPING_KEYS (saisie) @@ -47,6 +48,7 @@ mediadeck/ ├── system.py SystemControl : logind (suspend/reboot/poweroff), ScreenSaver.Lock, lancement des lanceurs ├── launchers.py LauncherStore (SQLite), validation, build_argv(), applications .desktop, navigateurs ├── admin.py API REST /api/* des lanceurs (jeton en en-tête Authorization: Bearer) +├── qrpage.py page HTML locale des QR codes (`make qr`) : qrencode -t SVG, images en data: URI, écrite en 600 dans $XDG_RUNTIME_DIR ├── tls.py HTTPS local : CA privée + certificat serveur (CLI openssl), contexte SSL, enable_tls() └── web/ ├── index.html sprite SVG + 4 panneaux (player, audio, remote, system) @@ -121,8 +123,10 @@ La pochette locale (`file://`) n'est jamais transmise : elle est remplacée par - Fenêtre de saisie **non modale** (`dialog.show()`) : le pavé reste utilisable, et un `showModal()` assombrirait les toasts (hors couche supérieure). - **Imports dbus-next par sous-modules** (`dbus_next.signature`, `dbus_next.aio.message_bus`, `dbus_next.constants`) : sinon pyright signale `reportPrivateImportUsage`. - Les proxies dbus-next sont typés `Any`, car leurs méthodes `call_*` / `on_*` sont générées dynamiquement. +- **Page des QR codes = fichier local, jamais une route du serveur** (`make qr`, `--qr`, module `qrpage.py`) : les QR codes contiennent le jeton, une route `/qr` le donnerait à tout le LAN (même limitée à la boucle locale, elle serait fragile derrière un proxy). Page autonome écrite en 600 dans `$XDG_RUNTIME_DIR/mediadeck/access.html` (tmpfs) et ouverte en `file://` : pas de CSP à contourner (` + + +
+

$title

+

$intro

+
+$cards +
+

$warning

+
+ + +""") + +CARD = Template("""
+

$title

+ QR code +

$address

+

$hint

+
""") + + +@dataclass(frozen=True) +class QrCard: + """Un code à afficher : `url` est encodée dans le QR code, `address` (sans jeton) est affichée.""" + + kind: str # "https", "http" ou "ca" + address: str + url: str + + +def detect_language() -> str: + locale = os.environ.get("LC_ALL") or os.environ.get("LC_MESSAGES") or os.environ.get("LANG") or "" + return "fr" if locale.lower().startswith("fr") else "en" + + +def qr_svg(url: str) -> bytes: + """QR code au format SVG (qrencode).""" + qrencode = shutil.which("qrencode") + if qrencode is None: + raise ConfigError("qrencode not found (apt install qrencode)") + try: + result = subprocess.run([qrencode, "-t", "SVG", "-m", "2", "-o", "-", url], check=True, capture_output=True) + except subprocess.CalledProcessError as exc: + raise ConfigError(f"qrencode failed: {exc.stderr.decode(errors='replace').strip()}") from exc + # Sans anti-aliasing : sinon de fines lignes claires apparaissent entre les modules une fois l'image mise à l'échelle + return result.stdout.replace(b" str: + """HTML autonome (images en data: URI, aucune ressource externe).""" + text = MESSAGES[lang or detect_language()] + items = [] + for card in cards: + title, hint = text[card.kind] + items.append( + CARD.substitute( + title=html.escape(title), + image=base64.b64encode(qr_svg(card.url)).decode("ascii"), + address=html.escape(card.address), + hint=html.escape(hint), + ) + ) + return PAGE.substitute( + lang=lang or detect_language(), + title=html.escape(str(text["title"])), + intro=html.escape(str(text["intro"])), + warning=html.escape(str(text["warning"])), + cards="\n".join(items), + ) + + +def page_path() -> Path: + runtime = os.environ.get("XDG_RUNTIME_DIR") + directory = Path(runtime) / "mediadeck" if runtime else Path(tempfile.mkdtemp(prefix="mediadeck-")) + directory.mkdir(mode=0o700, parents=True, exist_ok=True) + return directory / PAGE_NAME + + +def write_page(cards: list[QrCard], lang: str | None = None) -> Path: + """Écrit la page (mode 600 dès la création : elle contient le jeton) et renvoie son chemin.""" + content = build_page(cards, lang) + path = page_path() + descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(descriptor, "w", encoding="utf-8") as handle: + handle.write(content) + path.chmod(0o600) # le fichier existait peut-être déjà avec un autre mode + return path diff --git a/mediadeck/server.py b/mediadeck/server.py index 5686824..3b0554e 100644 --- a/mediadeck/server.py +++ b/mediadeck/server.py @@ -7,6 +7,8 @@ import hmac import json import logging import mimetypes +import signal +import ssl from pathlib import Path from typing import Any from urllib.parse import unquote, urlparse @@ -269,6 +271,33 @@ class MediaDeckServer: await self._broadcast() +async def open_sites(app: web.Application, config: Config, ssl_context: ssl.SSLContext | None) -> web.AppRunner: + """Ouvre le port principal (HTTPS si un contexte TLS est fourni) et, si demandé, le port HTTP en clair.""" + runner = web.AppRunner(app) + await runner.setup() + try: + await web.TCPSite(runner, config.host, config.port, ssl_context=ssl_context).start() + if config.http_port: + await web.TCPSite(runner, config.host, config.http_port).start() + except BaseException: + await runner.cleanup() + raise + return runner + + +async def serve(app: web.Application, config: Config, ssl_context: ssl.SSLContext | None) -> None: + """Sert l'application jusqu'à SIGINT / SIGTERM, puis arrête proprement (on_shutdown).""" + runner = await open_sites(app, config, ssl_context) + stop = asyncio.Event() + loop = asyncio.get_running_loop() + for signum in (signal.SIGINT, signal.SIGTERM): + loop.add_signal_handler(signum, stop.set) + try: + await stop.wait() + finally: + await runner.cleanup() + + @web.middleware async def security_headers(request: web.Request, handler: Any) -> web.StreamResponse: response: web.StreamResponse = await handler(request) diff --git a/mediadeck/tls.py b/mediadeck/tls.py index 0e150be..8fa1ac7 100644 --- a/mediadeck/tls.py +++ b/mediadeck/tls.py @@ -16,7 +16,7 @@ import tempfile from collections.abc import Iterable from pathlib import Path -from .config import CONFIG_DIR, Config, ConfigError +from .config import CONFIG_DIR, Config, ConfigError, load_config TLS_DIR = CONFIG_DIR / "tls" CA_KEY = "ca.key" @@ -166,6 +166,28 @@ def enable_tls(config_path: Path, cert: Path, key: Path, ca: Path) -> bool: return True +def set_http_port(config_path: Path, port: int) -> None: + """Écrit (port > 0) ou retire (0) `http_port` dans [server] ; restaure le fichier si le résultat est invalide.""" + original = config_path.read_text() + if port: + line = f"http_port = {port}" + existing = r"(?m)^([ \t]*)http_port[ \t]*=.*$" + if re.search(existing, original): + updated = re.sub(existing, lambda match: match.group(1) + line, original, count=1) + else: + updated, count = re.subn(r"(?m)^port\s*=.*$", lambda match: f"{match.group(0)}\n{line}", original, count=1) + if count == 0: + raise ConfigError(f"no 'port' line found in {config_path}: add '{line}' under [server] manually") + else: + updated = re.sub(r"(?m)^[ \t]*http_port[ \t]*=.*\n?", "", original) + config_path.write_text(updated) + try: + load_config(config_path) + except ConfigError: + config_path.write_text(original) + raise + + def build_ssl_context(config: Config) -> ssl.SSLContext | None: """Contexte TLS serveur, ou None si HTTPS n'est pas configuré.""" if config.tls_cert is None or config.tls_key is None: diff --git a/tests/test_config.py b/tests/test_config.py index 9c641b8..c77c3c6 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -64,6 +64,26 @@ class ParseConfigTest(unittest.TestCase): with self.subTest(server=server), self.assertRaises(ConfigError): parse_config({"server": {"token": TOKEN, **server}}) + def test_http_port_is_off_by_default(self) -> None: + self.assertEqual(parse_config({"server": {"token": TOKEN}}).http_port, 0) + + def test_http_port_next_to_tls(self) -> None: + server = {"token": TOKEN, "tls_cert": "/c.pem", "tls_key": "/k.key", "http_port": 8766} + self.assertEqual(parse_config({"server": server}).http_port, 8766) + + def test_http_port_is_validated(self) -> None: + tls = {"tls_cert": "/c.pem", "tls_key": "/k.key"} + for server in ( + {"http_port": 8766}, # sans TLS, `port` sert déjà du HTTP en clair + {**tls, "http_port": 8765}, # même port que le HTTPS + {**tls, "http_port": 70000}, + {**tls, "http_port": -1}, + {**tls, "http_port": "8766"}, + {**tls, "http_port": True}, + ): + with self.subTest(server=server), self.assertRaises(ConfigError): + parse_config({"server": {"token": TOKEN, **server}}) + def test_max_volume_bounds(self) -> None: with self.assertRaises(ConfigError): parse_config({"server": {"token": TOKEN}, "audio": {"max_volume": 3}}) diff --git a/tests/test_qrpage.py b/tests/test_qrpage.py new file mode 100644 index 0000000..297e228 --- /dev/null +++ b/tests/test_qrpage.py @@ -0,0 +1,89 @@ +"""Tests de la page des QR codes : contenu, absence du jeton en clair, droits du fichier, choix des codes.""" + +import base64 +import re +import shutil +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +from mediadeck.__main__ import access_cards +from mediadeck.config import parse_config +from mediadeck.qrpage import QrCard, build_page, qr_svg, write_page + +TOKEN = "secret-token-" + "x" * 20 +LAN_IP = "192.168.1.104" +TLS = {"tls_cert": "/c.pem", "tls_key": "/k.key", "tls_ca": "/ca.crt"} + + +def cards_for(**server: object) -> list[QrCard]: + return access_cards(parse_config({"server": {"token": TOKEN, "advertise_host": LAN_IP, **server}})) + + +class AccessCardsTest(unittest.TestCase): + def test_plain_http_only_by_default(self) -> None: + cards = cards_for() + self.assertEqual([card.kind for card in cards], ["http"]) + self.assertEqual(cards[0].url, f"http://{LAN_IP}:8765/?token={TOKEN}") + + def test_https_only_with_tls(self) -> None: + cards = cards_for(**TLS) + self.assertEqual([card.kind for card in cards], ["https", "ca"]) + self.assertEqual(cards[0].url, f"https://{LAN_IP}:8765/?token={TOKEN}") + self.assertEqual(cards[1].url, f"https://{LAN_IP}:8765/ca.crt") + + def test_both_modes_fetch_the_ca_over_http(self) -> None: + cards = cards_for(**TLS, http_port=8766) + self.assertEqual([card.kind for card in cards], ["https", "http", "ca"]) + self.assertEqual(cards[1].url, f"http://{LAN_IP}:8766/?token={TOKEN}") + self.assertEqual(cards[2].url, f"http://{LAN_IP}:8766/ca.crt") + + def test_displayed_address_never_holds_the_token(self) -> None: + for card in cards_for(**TLS, http_port=8766): + self.assertNotIn(TOKEN, card.address) + + +@unittest.skipUnless(shutil.which("qrencode"), "qrencode is required") +class QrPageTest(unittest.TestCase): + def setUp(self) -> None: + self.cards = cards_for(**TLS, http_port=8766) + + def test_page_is_self_contained_and_keeps_the_token_out_of_the_text(self) -> None: + page = build_page(self.cards, "en") + self.assertEqual(page.count('class="card"'), 3) + self.assertNotIn(TOKEN, page) + # Aucune ressource externe : seules les images en data: URI + self.assertNotRegex(page, r"(src|href)=\"(?!data:)") + self.assertIn("Unsecured (HTTP)", page) + self.assertIn(f"http://{LAN_IP}:8766", page) + + def test_each_qr_code_encodes_its_url(self) -> None: + page = build_page(self.cards, "en") + images = re.findall(r"base64,([A-Za-z0-9+/=]+)\"", page) + self.assertEqual([base64.b64decode(image) for image in images], [qr_svg(card.url) for card in self.cards]) + + def test_qr_svg_has_no_anti_aliasing_seams(self) -> None: + self.assertIn(b'shape-rendering="crispEdges"', qr_svg("http://x")) + + def test_language_and_escaping(self) -> None: + card = QrCard("http", "http://