From 72452daeb930ead34eaa876631b6fffac836b615 Mon Sep 17 00:00:00 2001 From: blackjackfruit Date: Thu, 26 Nov 2026 09:04:56 -0500 Subject: [PATCH] Serve the README as a documentation page at GET /docs /health advertises "docs": "/docs" while README.md is readable. /docs needs the pairing token like every route but /health and is served as HTML under a strict CSP. docs_page.py is the shared renderer, copied verbatim from the plugin-docs spec. --- README.md | 23 ++++ SECURITY.md | 2 +- build_plugin.py | 37 ++++++ docs_page.py | 250 ++++++++++++++++++++++++++++++++++++++ tests/test_build_local.py | 44 ++++++- tests/test_docs_page.py | 78 ++++++++++++ 6 files changed, 432 insertions(+), 2 deletions(-) create mode 100644 docs_page.py create mode 100644 tests/test_docs_page.py diff --git a/README.md b/README.md index 82c2534..7ab135c 100644 --- a/README.md +++ b/README.md @@ -121,6 +121,29 @@ Exit status `0` with a non-empty file at `MT_OUTPUT` is a successful build; anything else is a build error, reported with the script's last `error:` lines and its log. +## Endpoints + +The full contract is `BUILD_PLUGIN_API.md` in the MonkeyTester repo. Every route +except `GET /health` needs the pairing token when `PLUGIN_TOKEN` is set. + +| Route | Answer | +|---|---| +| `GET /health` | contract, plugin name/version, code host, platforms, `recipes`, capabilities; `"docs": "/docs"` while this README is readable (omitted otherwise) | +| `GET /docs` | this README rendered as a self-contained HTML page (`text/html`, strict CSP, no scripts); 404 JSON if README.md is missing. The viewer shows it through `/plugins/docs/build-local` | +| `GET` / `POST /config` | code host kind + URL + user and viewer URL (the token is never returned) / save them | +| `GET /template?platform=` | example `.monkeytester/build-.sh` | +| `GET /repos//[?branch=]` | check a repo (and branch) | +| `GET /repos///branches` | the repo's branches | +| `GET /repos///cases?ref=` | test cases on a ref | +| `POST /builds` | queue a build; `GET /builds/` its status | +| `GET /builds//log?offset=` | the build log from `offset` | +| `POST /builds//cancel` | stop a queued or running build | + +`/docs` reads `README.md` next to `build_plugin.py` at request time. The +launchd/systemd units run from the checkout and the Nix flake copies every +git-tracked file, so README.md is present in all three; an install without it +just leaves `docs` out of `/health`. + ## Security See [SECURITY.md](SECURITY.md) for the threat model, token setup (launchd diff --git a/SECURITY.md b/SECURITY.md index a4c6e36..f1fd1cb 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -28,7 +28,7 @@ port, bind and auth, and the hardening tiers) lives in the MonkeyTester repo's |---|---| | Access | `PLUGIN_TOKEN` pairing token on every request except `GET /health`, as `X-Plugin-Token` or `Authorization: Bearer`; compared with `hmac.compare_digest`. | | Bind | `PLUGIN_HOST` defaults to `0.0.0.0` (the viewer reaches the Mac over the LAN). **On any non-loopback bind the token is mandatory**: without `PLUGIN_TOKEN` the plugin exits with status 2 and says how to set it. On `127.0.0.1` / `::1` / `localhost` the token is optional. | -| `/health` | Unauthenticated, never contains a secret. Without the token it only answers the contract, plugin name/version, code host kind, platforms, recipes and capabilities (`auth_required: true`); the code host URL/user, viewer URL and queue need the token. | +| `/health` | Unauthenticated, never contains a secret. Without the token it only answers the contract, plugin name/version, code host kind, platforms, recipes and capabilities (`auth_required: true`); the code host URL/user, viewer URL and queue need the token. It may add `"docs": "/docs"` (README.md is readable); `GET /docs` itself needs the token and is served as HTML under `default-src 'none'` with no scripts, raw HTML in the README escaped. | | Code host token | Stored in `config.json` (mode 0600, dir 0700); `GET /config` returns only `{configured, last4, saved_at}`. Given to git per command via `GIT_CONFIG_*` environment — never in argv, the remote URL, `.git/config` or a log. | | Subprocesses | argv lists only, never `shell=True`. Repo `owner/name`, branch/ref, case names, request ids and build refs are validated against allowlist regexes (no leading `-`, no `..`, no control chars). git commands put `--` before positional values; request/log values passed to `submit.py` use `--flag=value` so they can never become another option. | | git transports | `GIT_ALLOW_PROTOCOL=http:https:ssh` and `protocol.allow=never` (plus per-protocol allows) for the fetch **and submodules**: no `ext::` (runs a command), no `file://`/local paths. The clone URL's scheme is checked before any git command runs. | diff --git a/build_plugin.py b/build_plugin.py index 58b07b3..a70969d 100644 --- a/build_plugin.py +++ b/build_plugin.py @@ -7,6 +7,10 @@ `.monkeytester/build-.sh` here (Android and iOS on a Mac, Android only on Linux) and uploads the apps to the viewer with the viewer's submit.py. +GET /docs serves README.md as an HTML page (docs_page.py, needs the pairing +token like every route but /health); /health says "docs": "/docs" while +README.md is readable. + This file: HTTP routing, the pairing token, JSON errors, the config file (code host + token + viewer URL, mode 0600), platform detection. The build queue is runner.py; code host access is sources/. @@ -55,6 +59,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent)) import runner as runner_mod # noqa: E402 +from docs_page import docs_html # noqa: E402 import sources # noqa: E402 from sources import PLATFORMS, RECIPES, SourceError # noqa: E402 @@ -70,6 +75,9 @@ LOOPBACK_NAMES = ("localhost", "localhost.", "ip6-localhost") VIEWER_SERVICE = "monkeytester" # the viewer's GET /health "service" TEMPLATES = Path(__file__).resolve().parent / "templates" +README_PATH = Path(__file__).resolve().parent / "README.md" # GET /docs, read per request +DOCS_CSP = ("default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; " + "form-action 'none'; frame-ancestors 'none'") # owner/repo; neither part may be only dots. REPO_PART_RE = re.compile(r"^(?!\.+$)[A-Za-z0-9_.-]{1,100}$") @@ -320,6 +328,8 @@ def health(self, full=True): "capabilities": list(CAPABILITIES), "error": error, } + if docs_available(): + body["docs"] = "/docs" if not full: body["forge"] = {"kind": src.KIND, "label": src.LABEL} body["auth_required"] = True @@ -441,6 +451,21 @@ def cancel_build(self, ref): return body +def docs_available(): + """True when README.md can be read: /health then advertises GET /docs.""" + path = README_PATH + return path.is_file() and os.access(path, os.R_OK) + + +def docs_page(): + """GET /docs: README.md rendered as a self-contained HTML page (bytes).""" + try: + text = README_PATH.read_text(encoding="utf-8") + except (OSError, UnicodeDecodeError): + raise PluginError("no documentation: README.md is not readable", "not_found") from None + return docs_html(PLUGIN_NAME, text, PLUGIN_VERSION) + + def template_text(platform): if platform not in PLATFORMS: raise PluginError("platform must be one of: " + ", ".join(PLATFORMS)) @@ -478,6 +503,16 @@ def send_text(self, status, data, headers=None): self.end_headers() self.wfile.write(data) + def send_html(self, status, data): + self.send_response(status) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Content-Length", str(len(data))) + self.send_header("Content-Security-Policy", DOCS_CSP) + self.send_header("X-Content-Type-Options", "nosniff") + self.send_header("Cache-Control", "no-store") + self.end_headers() + self.wfile.write(data) + def send_error_json(self, err): payload = {"error": str(err), "code": err.code} if err.forge_status is not None: @@ -545,6 +580,8 @@ def route(self, method, parts, query): return self.send_json(200, public_config(p.config.load())) if method == "POST": return self.send_json(200, p.save_config(self.read_body())) + elif parts == ["docs"] and method == "GET": + return self.send_html(200, docs_page()) elif parts == ["template"] and method == "GET": return self.send_text(200, template_text(query.get("platform") or "")) elif parts == ["builds"] and method == "POST": diff --git a/docs_page.py b/docs_page.py new file mode 100644 index 0000000..6618563 --- /dev/null +++ b/docs_page.py @@ -0,0 +1,250 @@ +"""Render a plugin's README.md as a self-contained HTML documentation page. + +Stdlib only, no external assets. Shared verbatim by every MonkeyTester plugin +(copy this file; keep the copies identical). Raw HTML in the markdown is +escaped, never passed through; link targets are limited to http(s), mailto and +in-page anchors, so the page is safe to serve under a strict CSP: + default-src 'none'; style-src 'unsafe-inline' + + from docs_page import docs_html + body = docs_html("esp32-sensor", readme_text) # -> bytes (UTF-8 HTML) + +Supported markdown: ATX headings, paragraphs, fenced code blocks, indented +code blocks, unordered/ordered lists (nesting by indentation), blockquotes, +GFM pipe tables, horizontal rules, inline code, **bold**, *italic*, links, +. Images render as their alt text. Relative links (other repo +files) render as plain text because they do not resolve on the plugin. +""" +from __future__ import annotations + +import html +import re + +__all__ = ["render_markdown", "docs_html"] + +_FENCE = re.compile(r"^(\s{0,3})(`{3,}|~{3,})\s*([\w+-]*)") +_HEADING = re.compile(r"^\s{0,3}(#{1,6})\s+(.*?)\s*#*\s*$") +_HR = re.compile(r"^\s{0,3}([-*_])(\s*\1){2,}\s*$") +_LIST = re.compile(r"^(\s*)([-*+]|\d{1,9}[.)])\s+(.*)$") +_TABLE_SEP = re.compile(r"^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$") +_SAFE_URL = re.compile(r"^(https?://|mailto:|#)", re.I) + + +def _slug(text: str, used: dict) -> str: + base = re.sub(r"[^\w\s-]", "", text.lower()).strip() + base = re.sub(r"[\s]+", "-", base) or "section" + n = used.get(base, 0) + used[base] = n + 1 + return base if n == 0 else f"{base}-{n}" + + +def _inline(text: str) -> str: + """Escape text and apply inline markdown. Code spans are protected first.""" + codes: list[str] = [] + + def hold_code(m: "re.Match") -> str: + codes.append("" + html.escape(m.group(2).strip(" ")) + "") + return f"\x01{len(codes) - 1}\x01" + + text = re.sub(r"(`+)(.+?)\1", hold_code, text) + out = _inline_plain(text) + return re.sub(r"\x01(\d+)\x01", lambda m: codes[int(m.group(1))], out) + + +def _link(label_html: str, url: str) -> str: + url = url.strip() + if url.startswith("<") and url.endswith(">"): + url = url[1:-1] + url = url.split()[0] if url.split() else "" + if _SAFE_URL.match(url): + return ('" + label_html + "") + return label_html + + +def _inline_plain(text: str) -> str: + # Work on escaped text; markdown punctuation survives html.escape except + # '<' '>' '&' '"' "'", which only matter for autolinks (handled below). + holders: list[str] = [] + + def hold(s: str) -> str: + holders.append(s) + return f"\x00{len(holders) - 1}\x00" + + # Autolinks + text = re.sub(r"<((?:https?://|mailto:)[^\s<>]+)>", + lambda m: hold(_link(html.escape(m.group(1)), m.group(1))), text) + # Images ![alt](url) -> alt text + text = re.sub(r"!\[([^\]]*)\]\(([^)]*)\)", lambda m: hold(html.escape(m.group(1))), text) + # Links [label](url) + text = re.sub(r"\[([^\]]+)\]\(([^)]*)\)", + lambda m: hold(_link(_emph(html.escape(m.group(1))), m.group(2))), text) + text = _emph(html.escape(text, quote=False)) + return re.sub(r"\x00(\d+)\x00", lambda m: holders[int(m.group(1))], text) + + +def _emph(s: str) -> str: + s = re.sub(r"(\*\*|__)(?=\S)(.+?)(?<=\S)\1", r"\2", s) + s = re.sub(r"(?\1", s) + s = re.sub(r"(?\1", s) + return s + + +def _cells(row: str) -> list[str]: + row = row.strip() + if row.startswith("|"): + row = row[1:] + if row.endswith("|") and not row.endswith("\\|"): + row = row[:-1] + return [c.strip().replace("\\|", "|") for c in re.split(r"(? str: + """items: (indent, ordered, text). Builds nested lists by indentation.""" + out: list[str] = [] + stack: list[tuple[int, str]] = [] # (indent, tag) + for indent, ordered, text in items: + tag = "ol" if ordered else "ul" + while stack and (indent < stack[-1][0] or (indent == stack[-1][0] and tag != stack[-1][1])): + out.append(f"") + if not stack or indent > stack[-1][0]: + out.append(f"<{tag}>
  • ") + stack.append((indent, tag)) + else: + out.append("
  • ") + out.append(_inline(text)) + while stack: + out.append(f"
  • ") + return "".join(out) + + +def render_markdown(md: str) -> str: + """Return the HTML body fragment for markdown text.""" + lines = md.replace("\r\n", "\n").replace("\r", "\n").split("\n") + out: list[str] = [] + used_ids: dict = {} + i, n = 0, len(lines) + while i < n: + line = lines[i] + if not line.strip(): + i += 1 + continue + m = _FENCE.match(line) + if m: + fence = m.group(2) + lang = m.group(3) + i += 1 + code: list[str] = [] + while i < n and not lines[i].strip().startswith(fence): + code.append(lines[i]) + i += 1 + i += 1 # closing fence (or EOF) + cls = f' class="language-{html.escape(lang)}"' if lang else "" + out.append(f"
    " + html.escape("\n".join(code)) + "
    ") + continue + m = _HEADING.match(line) + if m: + level = len(m.group(1)) + text = m.group(2) + hid = _slug(re.sub(r"[`*_\[\]()]", "", text), used_ids) + out.append(f'' + _inline(text) + f"") + i += 1 + continue + if _HR.match(line): + out.append("
    ") + i += 1 + continue + if line.startswith(" ") or line.startswith("\t"): + code = [] + while i < n and (lines[i].startswith(" ") or lines[i].startswith("\t") or not lines[i].strip()): + code.append(lines[i][4:] if lines[i].startswith(" ") else lines[i][1:]) + i += 1 + while code and not code[-1].strip(): + code.pop() + out.append("
    " + html.escape("\n".join(code)) + "
    ") + continue + if line.lstrip().startswith(">"): + quote: list[str] = [] + while i < n and lines[i].lstrip().startswith(">"): + quote.append(re.sub(r"^\s*>\s?", "", lines[i])) + i += 1 + out.append("
    " + render_markdown("\n".join(quote)) + "
    ") + continue + if "|" in line and i + 1 < n and _TABLE_SEP.match(lines[i + 1]) and "-" in lines[i + 1]: + head = _cells(line) + i += 2 + rows: list[list[str]] = [] + while i < n and lines[i].strip() and "|" in lines[i]: + rows.append(_cells(lines[i])) + i += 1 + t = [""] + t += ["" for c in head] + t.append("") + for r in rows: + r = (r + [""] * len(head))[:len(head)] + t.append("" + "".join("" for c in r) + "") + t.append("
    " + _inline(c) + "
    " + _inline(c) + "
    ") + out.append("".join(t)) + continue + if _LIST.match(line): + items: list[tuple[int, bool, str]] = [] + while i < n: + lm = _LIST.match(lines[i]) + if lm: + items.append((len(lm.group(1).expandtabs(4)), lm.group(2)[0].isdigit(), lm.group(3))) + i += 1 + elif lines[i].strip() and lines[i].startswith((" ", "\t")) and items: + ind, o, t = items[-1] + items[-1] = (ind, o, t + " " + lines[i].strip()) # continuation line + i += 1 + elif not lines[i].strip() and i + 1 < n and _LIST.match(lines[i + 1]): + i += 1 # loose list: blank line between items + else: + break + out.append(_render_list(items)) + continue + para: list[str] = [] + while i < n and lines[i].strip() and not ( + _FENCE.match(lines[i]) or _HEADING.match(lines[i]) or _HR.match(lines[i]) + or lines[i].lstrip().startswith(">") or _LIST.match(lines[i])): + para.append(lines[i].strip()) + i += 1 + out.append("

    " + _inline(" ".join(para)) + "

    ") + return "\n".join(out) + + +_CSS = """ +:root { color-scheme: light dark; --fg:#1d1d1f; --bg:#ffffff; --muted:#6e6e73; + --code-bg:#f2f2f4; --border:#d9d9de; --link:#0a66c2; } +@media (prefers-color-scheme: dark) { :root { --fg:#e8e8ea; --bg:#151517; + --muted:#9a9aa0; --code-bg:#232327; --border:#38383d; --link:#6cb4ff; } } +html { background: var(--bg); color: var(--fg); } +body { font: 15px/1.6 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; + max-width: 880px; margin: 0 auto; padding: 24px 20px 64px; } +header.docs-head { color: var(--muted); font-size: 13px; border-bottom: 1px solid var(--border); + padding-bottom: 8px; margin-bottom: 16px; } +h1, h2, h3, h4 { line-height: 1.25; margin: 1.6em 0 0.5em; } +h1 { font-size: 1.8em; } h2 { font-size: 1.4em; border-bottom: 1px solid var(--border); padding-bottom: .2em; } +a { color: var(--link); } +code { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-size: .88em; + background: var(--code-bg); padding: .1em .35em; border-radius: 4px; } +pre { background: var(--code-bg); padding: 12px 14px; border-radius: 6px; overflow-x: auto; } +pre code { background: none; padding: 0; font-size: .85em; } +table { border-collapse: collapse; margin: 1em 0; display: block; overflow-x: auto; } +th, td { border: 1px solid var(--border); padding: 6px 10px; text-align: left; vertical-align: top; } +th { background: var(--code-bg); } +blockquote { margin: 1em 0; padding: 0 1em; color: var(--muted); border-left: 3px solid var(--border); } +hr { border: 0; border-top: 1px solid var(--border); margin: 2em 0; } +""" + + +def docs_html(title: str, md: str, version: str | None = None) -> bytes: + """Full UTF-8 HTML page: ' documentation' + the rendered markdown.""" + label = html.escape(title) + (" " + html.escape(version) if version else "") + page = ("<!DOCTYPE html>\n<html lang=\"en\"><head><meta charset=\"utf-8\">" + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">" + f"<title>{html.escape(title)} documentation" + f"
    {label} · plugin documentation
    " + f"
    {render_markdown(md)}
    \n") + return page.encode("utf-8") diff --git a/tests/test_build_local.py b/tests/test_build_local.py index 59797cc..e53279a 100644 --- a/tests/test_build_local.py +++ b/tests/test_build_local.py @@ -363,7 +363,7 @@ def test_every_other_route_needs_the_pairing_token(self): ("GET", f"/repos/{REPO}"), ("GET", f"/repos/{REPO}/branches"), ("GET", f"/repos/{REPO}/cases?ref=master"), ("POST", "/builds"), ("GET", "/builds/br_0123456789abcdef"), ("GET", "/builds/br_0123456789abcdef/log"), - ("POST", "/builds/br_0123456789abcdef/cancel")): + ("POST", "/builds/br_0123456789abcdef/cancel"), ("GET", "/docs")): for headers in ({"X-Plugin-Token": ""}, {"X-Plugin-Token": "wrong"}, {"X-Plugin-Token": "", "Authorization": "Bearer wrong"}): status, body = self.call(method, path, {} if method == "POST" else None, headers=headers) @@ -375,6 +375,48 @@ def test_bearer_header_is_accepted_too(self): self.assertEqual(status, 200) +class DocsTests(PluginCase): + """GET /docs renders README.md; /health advertises it only when readable.""" + + pairing_token = PAIR + + def setUp(self): + super().setUp() + self.start_plugin() + + def test_docs_renders_the_readme(self): + status, raw, headers = self.call("GET", "/docs", raw=True) + self.assertEqual(status, 200) + self.assertEqual(headers["Content-Type"], "text/html; charset=utf-8") + self.assertEqual(headers["Content-Security-Policy"], + "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; " + "form-action 'none'; frame-ancestors 'none'") + self.assertEqual(headers["X-Content-Type-Options"], "nosniff") + self.assertEqual(headers["Cache-Control"], "no-store") + page = raw.decode() + self.assertIn('

    MonkeyTester-Plugin-Build-Local

    ', page) + self.assertIn(f"build-local {build_plugin.PLUGIN_VERSION}", page) + self.assertNotIn("Hello World', out) + self.assertIn('

    ', out) + self.assertIn("text", out) + self.assertIn("bold", out) + + def test_raw_html_is_escaped(self): + out = render_markdown("\n\n") + self.assertNotIn("`:\n\n```sh\necho '' && ls\n```\n") + self.assertIn("a <b>", out) + self.assertIn('
    echo '<x>' && ls
    ', out) + + def test_code_span_not_emphasised(self): + out = render_markdown("`*not*` and `__init__`") + self.assertIn("*not*", out) + self.assertIn("__init__", out) + + def test_bold_around_code_span(self): + out = render_markdown("owns the **`role: sensor`** boards and [`x`](https://a.b)") + self.assertIn("role: sensor", out) + self.assertIn('x', out) + + def test_lists_nested(self): + out = render_markdown("- a\n- b\n - c\n1. one\n") + self.assertTrue(out.startswith("
    • a
    • b
      • c
      ")) + self.assertIn("
      1. one
      ", out) + + def test_table(self): + out = render_markdown("| A | B |\n|---|:-:|\n| `x|y` | 2 |\n| 3 |\n") + self.assertIn("AB", out) + self.assertIn("3", out) + + def test_blockquote_hr(self): + out = render_markdown("> note **this**\n\n---\n") + self.assertIn("

      note this

      ", out) + self.assertIn("
      ", out) + + def test_page(self): + page = docs_html("esp32-sensor", "# Hi", "0.1.0").decode() + self.assertTrue(page.startswith("")) + self.assertIn("esp32-sensor documentation", page) + self.assertIn("esp32-sensor 0.1.0", page) + self.assertNotIn("")[0]) # no external assets + + +if __name__ == "__main__": + unittest.main()