#!/usr/bin/env python3 """Small HTTP client for STRATO's customer portal. STRATO does not publish a DNS-zone API for ordinary hosted domains. This client implements the minimum path proven by the public certbot-dns-strato project: authenticate, resolve the package that owns one configured DNS zone, read its combined TXT/CNAME form, and replace that form after a narrowly scoped change. Every write re-sends all other form controls unchanged, runs under a process-wide lock and is followed by a fresh read for verification. """ from __future__ import annotations import base64 import hashlib import hmac import os import re import struct import threading import time import urllib.error import urllib.parse import urllib.request from dataclasses import dataclass from html.parser import HTMLParser from http.cookiejar import CookieJar from typing import Callable, Iterable STRATO_URL = "https://www.strato.de/apps/CustomerService" MAX_RESPONSE_BYTES = 5 * 1024 * 1024 USER_AGENT = "Mozilla/5.0 (compatible; strato-dns-mcp/0.3)" SESSION_TTL_SECONDS = 600 RECORD_TYPES = ("CNAME", "TXT") _RECORD_FIELDS = {"prefix", "type", "value", "action_change_txt_records"} _REQUEST_FIELDS = {"sessionID", "cID", "node", "vhost"} _WRITE_LOCK = threading.Lock() class StratoError(RuntimeError): """Short credential-free error suitable for an MCP response.""" class StratoAuthenticationError(StratoError): pass class StratoParseError(StratoError): pass class StratoWriteDisabledError(StratoError): pass @dataclass(frozen=True) class StratoConfig: username: str password: str domain: str package_id: str | None = None totp_secret: str | None = None totp_device: str | None = None timeout_seconds: float = 20.0 write_enabled: bool = False @classmethod def from_env(cls) -> "StratoConfig": values = { "username": os.environ.get("STRATO_USERNAME", "").strip(), "password": os.environ.get("STRATO_PASSWORD", ""), "domain": os.environ.get("STRATO_DOMAIN", "").strip().rstrip("."), } missing = [name.upper() for name, value in values.items() if not value] if missing: raise StratoError( "Missing configuration: " + ", ".join(f"STRATO_{name}" for name in missing) ) domain = values["domain"].encode("idna").decode("ascii").lower() if not re.fullmatch(r"(?=.{1,253}$)[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?", domain): raise StratoError("STRATO_DOMAIN is not a valid DNS zone name") return cls( username=values["username"], password=values["password"], domain=domain, package_id=os.environ.get("STRATO_PACKAGE_ID", "").strip() or None, totp_secret=os.environ.get("STRATO_TOTP_SECRET", "").strip() or None, totp_device=os.environ.get("STRATO_TOTP_DEVICE", "").strip() or None, timeout_seconds=float(os.environ.get("STRATO_TIMEOUT_SECONDS", "20")), write_enabled=os.environ.get("STRATO_WRITE_ENABLED", "false").strip().lower() in {"1", "true", "yes", "on"}, ) @dataclass(frozen=True) class DnsRecord: type: str prefix: str value: str def as_dict(self) -> dict[str, str]: result = {"type": self.type, "prefix": self.prefix, "value": self.value} readable = _unicode_name(self.prefix) if readable != self.prefix: result["prefix_unicode"] = readable return result @dataclass(frozen=True) class DnsForm: records: tuple[DnsRecord, ...] submit_value: str # Every other control of the DNS form (hidden fields, checked radios, selects), # re-sent unchanged so a record change never resets unrelated settings. extra_fields: tuple[tuple[str, str], ...] = () def _unicode_name(name: str) -> str: try: return ".".join( label.encode("ascii").decode("idna") if label.startswith("xn--") else label for label in name.split(".") ) except UnicodeError: return name class _FormParser(HTMLParser): """Extract parallel type/prefix/value fields and all other controls of the form that contains STRATO's DNS submit button.""" def __init__(self) -> None: super().__init__(convert_charrefs=True) self.prefixes: list[str] = [] self.types: list[str] = [] self.values: list[str] = [] self._in_type_select = False self._in_value_textarea = False self._textarea_parts: list[str] = [] self.submit_value: str | None = None # extra controls per