| 1 | """Optional hosted publishing for rendered HTML artifacts.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import http.client |
| 6 | import json |
| 7 | import urllib.request |
| 8 | from collections.abc import Mapping |
| 9 | from typing import Any, Callable |
| 10 | from urllib.error import HTTPError, URLError |
| 11 | from urllib.parse import urlsplit |
| 12 | from urllib.request import Request |
| 13 | |
| 14 | |
| 15 | DEFAULT_ENDPOINT = "https://api.ht-ml.app/v1/sites" |
| 16 | _MAX_RESPONSE_BYTES = 1024 * 1024 # 1 MiB |
| 17 | _MAX_ERROR_BYTES = 64 * 1024 # 64 KiB |
| 18 | _DEFAULT_URLOPEN = urllib.request.urlopen |
| 19 | urlopen = _DEFAULT_URLOPEN |
| 20 | |
| 21 | |
| 22 | class HtmlPublishError(RuntimeError): |
| 23 | """Raised when the hosted HTML publish endpoint rejects the artifact.""" |
| 24 | |
| 25 | |
| 26 | class HtmlPublishBatchResult(dict[str, dict[str, Any]]): |
| 27 | """Successful document publishes plus an optional later failure.""" |
| 28 | |
| 29 | def __init__(self) -> None: |
| 30 | super().__init__() |
| 31 | self.error: HtmlPublishError | None = None |
| 32 | |
| 33 | |
| 34 | class _NoRedirectHandler(urllib.request.HTTPRedirectHandler): |
| 35 | """Refuse all 3xx redirects so POST payloads and passwords cannot be forwarded or downgraded.""" |
| 36 | |
| 37 | def redirect_request(self, req, fp, code, msg, headers, newurl): |
| 38 | raise HTTPError( |
| 39 | req.full_url, |
| 40 | code, |
| 41 | "publish endpoint redirects are not allowed", |
| 42 | headers, |
| 43 | fp, |
| 44 | ) |
| 45 | |
| 46 | |
| 47 | def _build_publish_opener() -> urllib.request.OpenerDirector: |
| 48 | """Build an HTTPS-only OpenerDirector without file/ftp/data/http or redirect following.""" |
| 49 | https_proxies = { |
| 50 | scheme: target |
| 51 | for scheme, target in urllib.request.getproxies().items() |
| 52 | if scheme.lower() == "https" |
| 53 | } |
| 54 | opener = urllib.request.OpenerDirector() |
| 55 | handlers: list[urllib.request.BaseHandler] = [ |
| 56 | urllib.request.ProxyHandler(https_proxies), |
| 57 | urllib.request.UnknownHandler(), |
| 58 | urllib.request.HTTPDefaultErrorHandler(), |
| 59 | _NoRedirectHandler(), |
| 60 | urllib.request.HTTPErrorProcessor(), |
| 61 | ] |
| 62 | if hasattr(http.client, "HTTPSConnection"): |
| 63 | handlers.append(urllib.request.HTTPSHandler()) |
| 64 | for handler in handlers: |
| 65 | opener.add_handler(handler) |
| 66 | return opener |
| 67 | |
| 68 | |
| 69 | _PUBLISH_OPENER = _build_publish_opener() |
| 70 | |
| 71 | |
| 72 | def _validate_https_url(url: str, *, label: str) -> str: |
| 73 | if not isinstance(url, str) or not url or url != url.strip(): |
| 74 | raise HtmlPublishError(f"{label} must be a valid https:// URL") |
| 75 | if any(ord(ch) < 0x20 or ord(ch) == 0x7F or ch.isspace() for ch in url): |
| 76 | raise HtmlPublishError(f"{label} contains invalid characters") |
| 77 | try: |
| 78 | parts = urlsplit(url) |
| 79 | hostname = parts.hostname |
| 80 | _ = parts.port |
| 81 | except ValueError as exc: |
| 82 | raise HtmlPublishError(f"{label} is not a valid URL") from exc |
| 83 | if parts.scheme.lower() != "https": |
| 84 | raise HtmlPublishError(f"{label} must use https://") |
| 85 | if not hostname: |
| 86 | raise HtmlPublishError(f"{label} must include a hostname") |
| 87 | if "\\" in hostname or "\\" in parts.netloc: |
| 88 | raise HtmlPublishError(f"{label} contains invalid characters") |
| 89 | if parts.username is not None or parts.password is not None or "@" in parts.netloc: |
| 90 | raise HtmlPublishError(f"{label} must not contain credentials") |
| 91 | return url |
| 92 | |
| 93 | |
| 94 | def _read_bounded(stream: Any, max_bytes: int, *, truncate: bool = False) -> bytes: |
| 95 | """Read at most ``max_bytes`` from ``stream``, tolerating zero-arg test stubs.""" |
| 96 | try: |
| 97 | data = stream.read(max_bytes + 1) |
| 98 | except TypeError: |
| 99 | data = stream.read() |
| 100 | if not isinstance(data, (bytes, bytearray)): |
| 101 | raise HtmlPublishError("publish endpoint returned invalid response stream") |
| 102 | raw = bytes(data) |
| 103 | if len(raw) > max_bytes: |
| 104 | if truncate: |
| 105 | return raw[:max_bytes] |
| 106 | raise HtmlPublishError(f"publish endpoint response exceeded {max_bytes} bytes") |
| 107 | return raw |
| 108 | |
| 109 | |
| 110 | def _resolve_open_fn(opener: Callable[..., Any] | None) -> Callable[..., Any]: |
| 111 | if opener is not None: |
| 112 | return opener |
| 113 | if urlopen is not _DEFAULT_URLOPEN: |
| 114 | return urlopen |
| 115 | if urllib.request.urlopen is not _DEFAULT_URLOPEN: |
| 116 | return urllib.request.urlopen |
| 117 | return _PUBLISH_OPENER.open |
| 118 | |
| 119 | |
| 120 | def publish_html( |
| 121 | html_content: str, |
| 122 | *, |
| 123 | password: str | None = None, |
| 124 | endpoint: str = DEFAULT_ENDPOINT, |
| 125 | opener: Callable[..., Any] | None = None, |
| 126 | timeout: int = 30, |
| 127 | ) -> dict[str, Any]: |
| 128 | """Publish a single HTML document and return the provider response.""" |
| 129 | if not html_content.strip(): |
| 130 | raise HtmlPublishError("HTML content is empty") |
| 131 | validated_endpoint = _validate_https_url(endpoint, label="publish endpoint") |
| 132 | |
| 133 | payload: dict[str, str] = {"html_content": html_content} |
| 134 | if password is not None: |
| 135 | payload["password"] = password |
| 136 | |
| 137 | request = Request( |
| 138 | validated_endpoint, |
| 139 | data=json.dumps(payload).encode("utf-8"), |
| 140 | headers={"Content-Type": "application/json", "Accept": "application/json"}, |
| 141 | method="POST", |
| 142 | ) |
| 143 | open_fn = _resolve_open_fn(opener) |
| 144 | try: |
| 145 | with open_fn(request, timeout=timeout) as response: |
| 146 | raw_body = _read_bounded(response, _MAX_RESPONSE_BYTES) |
| 147 | body = raw_body.decode("utf-8") |
| 148 | except HTTPError as exc: |
| 149 | try: |
| 150 | if 300 <= exc.code < 400: |
| 151 | reason = str(exc.reason or "publish endpoint redirects are not allowed") |
| 152 | raise HtmlPublishError(f"{exc.code}: {reason}") from exc |
| 153 | detail = "" |
| 154 | if exc.fp is not None: |
| 155 | try: |
| 156 | detail = _read_bounded(exc, _MAX_ERROR_BYTES, truncate=True).decode( |
| 157 | "utf-8", errors="replace" |
| 158 | ) |
| 159 | except (HtmlPublishError, http.client.HTTPException, OSError): |
| 160 | detail = "" |
| 161 | raise HtmlPublishError( |
| 162 | _error_message(exc.code, detail or str(exc.reason or "")) |
| 163 | ) from exc |
| 164 | finally: |
| 165 | try: |
| 166 | exc.close() |
| 167 | except Exception: |
| 168 | pass |
| 169 | except URLError as exc: |
| 170 | raise HtmlPublishError(str(exc.reason)) from exc |
| 171 | except (http.client.HTTPException, UnicodeDecodeError, OSError) as exc: |
| 172 | raise HtmlPublishError(str(exc)) from exc |
| 173 | |
| 174 | try: |
| 175 | result = json.loads(body) |
| 176 | except json.JSONDecodeError as exc: |
| 177 | raise HtmlPublishError("publish endpoint returned non-JSON response") from exc |
| 178 | if not isinstance(result, dict): |
| 179 | raise HtmlPublishError("publish endpoint returned unexpected JSON response") |
| 180 | |
| 181 | url = result.get("url") |
| 182 | if not isinstance(url, str): |
| 183 | raise HtmlPublishError("publish endpoint response did not include a valid url") |
| 184 | try: |
| 185 | _validate_https_url(url, label="publish endpoint response url") |
| 186 | except HtmlPublishError as exc: |
| 187 | raise HtmlPublishError("publish endpoint response did not include a valid url") from exc |
| 188 | return result |
| 189 | |
| 190 | |
| 191 | def publish_html_documents( |
| 192 | documents: Mapping[str, str], |
| 193 | *, |
| 194 | password: str | None = None, |
| 195 | endpoint: str = DEFAULT_ENDPOINT, |
| 196 | opener: Callable[..., Any] | None = None, |
| 197 | timeout: int = 30, |
| 198 | ) -> HtmlPublishBatchResult: |
| 199 | """Publish a named set of documents, preserving caller order in results.""" |
| 200 | results = HtmlPublishBatchResult() |
| 201 | for name, content in documents.items(): |
| 202 | try: |
| 203 | results[name] = publish_html( |
| 204 | content, |
| 205 | password=password, |
| 206 | endpoint=endpoint, |
| 207 | opener=opener, |
| 208 | timeout=timeout, |
| 209 | ) |
| 210 | except HtmlPublishError as exc: |
| 211 | results.error = exc |
| 212 | break |
| 213 | return results |
| 214 | |
| 215 | |
| 216 | def _error_message(status: int, detail: str) -> str: |
| 217 | try: |
| 218 | payload = json.loads(detail) |
| 219 | except json.JSONDecodeError: |
| 220 | payload = {} |
| 221 | message = payload.get("message") if isinstance(payload, dict) else None |
| 222 | if message: |
| 223 | return f"{status}: {message}" |
| 224 | return f"{status}: {detail.strip() or 'publish failed'}" |
| 225 |