Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,8 @@ Served by Python's ThreadingHTTPServer. Pages use `{{CSS}}`/`{{JS}}` template su
| `/device-config` or `/device-config.html` | 302 to `/plugins` — the standalone Device Config page is retired; its options live in the **Controller Plugin** section on the Plugins page (the Settings submenu has no separate entry for it) |
| `/configuration.html` or `/configuration` | 302 to `/plugins` (old Device Config URL; the section now lives on /plugins) |
| `/appearance` or `/appearance.html` | 302 to `/config` — the Light Mode toggle now lives in the Configuration page's Appearance section (the Settings submenu has no Appearance entry) |
| `/plugins` or `/plugins.html` | Plugins, in three sections: **Test Plugins** (device plugins and monkeytester-ai), **Build Plugin** (its Configure panel holds the code host) and **Controller Plugin** (the one controller plugin; its Configure panel holds friendly names for the devices it serves, moved from the retired Device Config page). Every section: title + "?" generic intro box, an **Add row** (name, address, optional pairing token; the controller's Add row is only an address and shows only while none is set), its status line, then a **table** of the added plugins — Name, Status, Address (editable; Save address greyed until it differs), Details, Actions (Save address, Configure where a panel exists, Remove). Configure opens the panel inline under the row. Signed-in users |
| `/plugins` or `/plugins.html` | Plugins, in three sections: **Test Plugins** (device plugins and monkeytester-ai), **Build Plugin** (its Configure panel holds the code host) and **Controller Plugin** (the one controller plugin; its Configure panel holds friendly names for the devices it serves, moved from the retired Device Config page). Every section: title + "?" generic intro box, an **Add row** (name, address, optional pairing token; the controller's Add row is only an address and shows only while none is set), its status line, then a **table** of the added plugins — Name, Status, Address (editable; Save address greyed until it differs), Details, Actions (Save address, Configure where a panel exists, Remove). Configure opens the panel inline under the row. When the row's data has `docs: true`, the Details cell ends with a thin rule (`hr.pt-docs-sep`) and a small **Documentation** link (`a.pt-docs`, `target=_blank`, `rel=noopener noreferrer`, `href=/plugins/docs/<key>`); the Details cell is plain HTML re-rendered via `setHtml`, so the address `<input>` is never touched. Signed-in users |
| `/plugins/docs/<name>` | A plugin's documentation page (all three sections; `<name>` = the row key, `controller` for the Mobile Controller unless a plugin has that name). Page route: unauthenticated → 302 `/login`; any signed-in user. `<name>` must match `^[A-Za-z0-9._-]{1,64}$` and be a registered device plugin, monkeytester-ai, build plugin or the controller, else 404 HTML. The viewer resolves base URL + token from its own config (`plugin_docs_target`; never from the request), reads the plugin's `GET /health` `docs` (valid only per `security_utils.plugin_docs_path`: starts with `/`, not `//`, no `\`, scheme, CR/LF, ≤ 256 chars; else 404 "This plugin has no documentation"), then fetches `<base><docs>` with `X-Plugin-Token` (`X-Controller-Token` for the controller), 10 s, no redirects, `text/html` only, ≤ 2 MiB, and serves it with a sandbox CSP (`PLUGIN_DOCS_CSP`), `nosniff`, `Referrer-Policy: no-referrer`, `no-store` (the `harden_handler` defaults skip headers a route already sent). Offline/redirect/non-HTML/oversize/plugin error → 502 HTML "Couldn't load the documentation for <name>: <reason>" with a link back to /plugins. Status data: every `/api/plugins` row and `/api/config/controller` `live` carry `docs: true/false` from the same validation. Tests: `tests/test_plugin_docs.py`; contract text in PLUGIN_API.md / BUILD_PLUGIN_API.md (`GET /docs`) |
| `/models` or `/models.html` | 302 to `/plugins` — the vision provider (Local model or GitHub Copilot) is chosen in the monkeytester-ai plugin's Configure panel there |
| `/copilot` or `/copilot.html` | 302 to `/plugins` — GitHub Copilot is signed in on the monkeytester-ai plugin |
| `/run-status` or `/run-status.html` | Run Status: active and queued runs/tests. Signed-in users |
Expand Down
12 changes: 12 additions & 0 deletions BUILD_PLUGIN_API.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ Same as [PLUGIN_API.md](PLUGIN_API.md):
"viewer_url": "http://192.168.1.10:8089",
"queue": {"running": "br_0123456789abcdef", "waiting": 0},
"capabilities": ["logs", "cancel"],
"docs": "/docs",
"error": null
}
```
Expand All @@ -68,10 +69,21 @@ Same as [PLUGIN_API.md](PLUGIN_API.md):
→ `android`). Build & Test offers only these.
- `recipes`: the file in the app repo that builds each platform.
- `capabilities`: optional parts of this contract the plugin supports (`logs`, `cancel`).
- `docs` (optional): path of the plugin's documentation page, `"/docs"`; present only when
the page can be served (see `GET /docs` below).

MonkeyTester refuses a plugin whose `contract` differs or whose `contract_version` it
does not support.

### `GET /docs` (optional)

The plugin's README as one self-contained HTML page, exactly as in
[PLUGIN_API.md → `GET /docs`](PLUGIN_API.md#get-docs-optional): pairing token required
like every route but `/health`, `text/html; charset=utf-8` under a strict CSP, `404` when
the README can't be read. The viewer's Build Plugin row shows a **Documentation** link
when `/health` reports `docs`; it opens `/plugins/docs/<name>`, which the viewer fetches
with the saved token and serves under a sandbox CSP.

### `GET /config` / `POST /config`

`GET` → `{forge_kind, forge_url, token: {configured, last4, saved_at}, user, viewer_url}`.
Expand Down
33 changes: 33 additions & 0 deletions PLUGIN_API.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,15 +99,48 @@ Readiness. Never blocks on hardware.
"host": {"os": "linux", "hostname": "server"},
"devices": 1,
"capabilities": ["events", "uploads"],
"docs": "/docs",
"error": null
}
```

`capabilities` lists the optional parts of this contract the plugin supports.

`docs` (optional) is the path of the plugin's documentation page, normally `"/docs"`
(see [`GET /docs`](#get-docs-optional)). Advertise it only when the page can actually be
served (a packaged install without its README omits the field); no field means no
documentation, and the viewer shows no link.

MonkeyTester refuses a plugin whose `contract` differs or whose `contract_version`
is not one it supports.

### `GET /docs` (optional)

The plugin's documentation (setup, endpoints, configuration) as one self-contained
HTML page, rendered from the repo's `README.md` by the shared `docs_page.py`. Offered
only when `GET /health` has `"docs": "/docs"`.

- Auth like every other route: only `/health` is open, so with a token configured
`/docs` needs `X-Plugin-Token` (401 otherwise).
- `200`, `Content-Type: text/html; charset=utf-8`, with
`Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,
`X-Content-Type-Options: nosniff`, `Cache-Control: no-store`. No scripts, no
external assets.
- README missing or unreadable: `404` with the usual error body.

Browsers never call it directly. On Settings → Plugins, a row whose plugin reports
`docs` shows a **Documentation** link under its address; it opens the viewer's
`GET /plugins/docs/<name>` in a new tab, and the viewer fetches the page from the
plugin with the plugin's saved token (no redirects followed, `text/html` only, at most
2 MiB) and serves it under a sandbox CSP (`… img-src data: …; sandbox`), so nothing in
it can run on the viewer's origin. The viewer accepts `docs` only as a path: a string
starting with `/` (not `//`), no `\`, no scheme, no CR/LF, at most 256 characters.

The same applies to monkeytester-ai (pairing token as `X-Plugin-Token`), to build
plugins ([BUILD_PLUGIN_API.md](BUILD_PLUGIN_API.md)) and to the Mobile Controller: its
`GET /health` may carry `"docs": "/docs"` and its `GET /docs` takes `X-Controller-Token`
like its other routes; its row's link is `/plugins/docs/controller`.

### `GET /devices`

```json
Expand Down
172 changes: 171 additions & 1 deletion app.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import sys
import threading
import time
import urllib.error
import urllib.request
import uuid
import zipfile
import io
Expand Down Expand Up @@ -287,7 +289,8 @@ def controller_status():
"error": f"API version is {version}, expected {CONTROLLER_API_VERSION}; "
"update whichever is older"}
return {"ok": bool(body.get("ok")), "url": base, "api_version": version,
"appium": body.get("appium"), "adb": body.get("adb")}
"appium": body.get("appium"), "adb": body.get("adb"),
"docs": sec.plugin_docs_path(body.get("docs")) is not None}


_PLUGIN_SELECTED_CACHE = {} # plugin name -> (selected model id, when)
Expand Down Expand Up @@ -710,9 +713,126 @@ def plugins_overview():
out["plugins"].append(row)
out["ai_plugin"] = {"name": pc.AI_PLUGIN_NAME, "url": url, "configured": bool(url),
"token": token_info(key), "managed": managed}
# docs: the plugin's /health advertises a valid GET /docs path, so the
# /plugins row shows its Documentation link (served via /plugins/docs/<name>).
for row in out["plugins"]:
row["docs"] = sec.plugin_docs_path(row.get("docs")) is not None
return out


# ─── Plugin documentation (GET /plugins/docs/<name>) ───
# A plugin whose /health advertises "docs": "/docs" serves its README as an
# HTML page. The browser never talks to a plugin: the viewer fetches the page
# with that plugin's saved token and serves it under a sandbox CSP, so a
# script in the plugin's page can never run on the viewer's origin.
PLUGIN_DOCS_NAME_RE = re.compile(r"^[A-Za-z0-9._-]{1,64}$")
PLUGIN_DOCS_HEALTH_TIMEOUT = 3
PLUGIN_DOCS_TIMEOUT = 10
PLUGIN_DOCS_MAX_BYTES = 2 * 1024 * 1024
PLUGIN_DOCS_CSP = ("default-src 'none'; style-src 'unsafe-inline'; img-src data:; "
"base-uri 'none'; form-action 'none'; frame-ancestors 'none'; sandbox")
PLUGIN_DOCS_ERROR_CSP = ("default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; "
"form-action 'none'; frame-ancestors 'none'")
CONTROLLER_ROW_KEY = "controller" # the Controller Plugin row's key on /plugins


class PluginDocsError(Exception):
"""status 404 (no such plugin / no documentation) or 502 (fetch failed)."""

def __init__(self, status, message):
super().__init__(message)
self.status = status
self.message = message


def plugin_docs_target(name):
"""(base url, request headers) for a /plugins row key, from the viewer's
own config — the same lookups the rows and Configure panels use — or None
for an unknown name. Device plugins, monkeytester-ai and build plugins
send X-Plugin-Token; the Mobile Controller (row key "controller", unless a
plugin is registered under that name) sends X-Controller-Token."""
if not isinstance(name, str) or not PLUGIN_DOCS_NAME_RE.fullmatch(name):
return None
pc = _plugin_client()
cfg = load_config()
if name == pc.AI_PLUGIN_NAME:
url = ai_plugin_url(cfg)
if not url:
return None
key = ai_pairing_token(cfg)
return url.rstrip("/"), ({"X-Plugin-Token": key} if key else {})
try:
devices = pc.load_plugins(cfg)
except pc.PluginError:
devices = {}
if name in devices:
token = auth.plugin_token(name) or devices[name].token or ""
return devices[name].url.rstrip("/"), ({"X-Plugin-Token": token} if token else {})
registry = _builds().registry_plugins()
if name in registry:
token = registry[name].get("token") or builds._saved_token(name)
return registry[name]["url"].rstrip("/"), ({"X-Plugin-Token": token} if token else {})
if name == CONTROLLER_ROW_KEY:
base = _controller_url()
if base:
return base, _controller_headers()
return None


class _NoRedirect(urllib.request.HTTPRedirectHandler):
"""Turn every 3xx into an HTTPError: the docs proxy never follows one."""

def redirect_request(self, req, fp, code, msg, headers, newurl):
return None


def fetch_plugin_docs(name):
"""The plugin's documentation page as bytes. Raises PluginDocsError:
404 for an unknown name or a missing/invalid /health `docs` path, 502
when the plugin is offline, redirects, answers non-HTML, an error or
more than PLUGIN_DOCS_MAX_BYTES."""
target = plugin_docs_target(name)
if not target:
raise PluginDocsError(404, f"There is no plugin named {name!r} on this viewer.")
base, headers = target
opener = urllib.request.build_opener(_NoRedirect)

def open_(path, timeout, accept):
req = urllib.request.Request(sec.check_http_url(base + path),
headers={**headers, "Accept": accept})
return opener.open(req, timeout=timeout) # nosec B310

try:
with open_("/health", PLUGIN_DOCS_HEALTH_TIMEOUT, "application/json") as resp:
health = json.loads(resp.read(256 * 1024).decode() or "{}")
except urllib.error.HTTPError as e:
e.close()
raise PluginDocsError(502, f"GET /health answered HTTP {e.code}") from None
except Exception as e:
raise PluginDocsError(502, f"the plugin is unreachable ({getattr(e, 'reason', e)})") from None
docs = sec.plugin_docs_path(health.get("docs") if isinstance(health, dict) else None)
if not docs:
raise PluginDocsError(404, "This plugin has no documentation.")
try:
with open_(docs, PLUGIN_DOCS_TIMEOUT, "text/html") as resp:
if resp.headers.get_content_type() != "text/html":
raise PluginDocsError(502, "the plugin answered with "
f"{resp.headers.get_content_type()}, not text/html")
body = resp.read(PLUGIN_DOCS_MAX_BYTES + 1)
except PluginDocsError:
raise
except urllib.error.HTTPError as e:
e.close()
if 300 <= e.code < 400:
raise PluginDocsError(502, f"the plugin answered with a redirect (HTTP {e.code})") from None
raise PluginDocsError(502, f"GET {docs} answered HTTP {e.code}") from None
except Exception as e:
raise PluginDocsError(502, f"the plugin is unreachable ({getattr(e, 'reason', e)})") from None
if len(body) > PLUGIN_DOCS_MAX_BYTES:
raise PluginDocsError(502, "the page is larger than 2 MiB")
return body


AI_NOT_CONFIGURED = ("no monkeytester-ai plugin configured — set its address first "
"in Settings → Device Plugins (its Configure panel)")

Expand Down Expand Up @@ -2862,6 +2982,10 @@ def do_GET(self):
self.end_headers()
elif path == "/plugins" or path == "/plugins.html":
self.serve_page("plugins.html")
elif path.startswith("/plugins/docs/"):
# A plugin's documentation page, fetched from the plugin by the
# viewer (the /plugins rows' Documentation link opens it).
self.serve_plugin_docs(path[len("/plugins/docs/"):])
elif path == "/models" or path == "/models.html":
# The model picker now lives inside the Device Plugins panel:
# clicking the AI plugin row configures it there. Old bookmarks
Expand Down Expand Up @@ -3244,6 +3368,52 @@ def serve_page(self, filename):
else:
self.send_error(404)

def serve_plugin_docs(self, name):
"""GET /plugins/docs/<name>: the plugin's GET /docs page, proxied with
its saved token and served under a sandbox CSP (PLUGIN_DOCS_CSP), so
nothing in it can run on the viewer's origin. Unknown name or no
documentation → 404 page; fetch failure → 502 page."""
try:
body = fetch_plugin_docs(name)
except PluginDocsError as e:
self.send_plugin_docs_error(name, e.status, e.message)
return
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.send_header("Content-Security-Policy", PLUGIN_DOCS_CSP)
self.send_header("X-Content-Type-Options", "nosniff")
self.send_header("Referrer-Policy", "no-referrer")
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body)

def send_plugin_docs_error(self, name, status, message):
"""Small self-contained HTML page for a docs failure, everything escaped."""
import html as _html
shown = name if PLUGIN_DOCS_NAME_RE.fullmatch(name or "") else "this plugin"
if status == 404:
title = "No documentation"
text = message
else:
title = "Documentation unavailable"
text = f"Couldn't load the documentation for {shown}: {message}"
page = ("<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\">"
f"<title>{_html.escape(title)}</title><style>body{{font-family:sans-serif;"
"max-width:640px;margin:40px auto;padding:0 16px;line-height:1.5}</style>"
f"</head><body><h1>{_html.escape(title)}</h1><p>{_html.escape(text)}</p>"
"<p><a href=\"/plugins\">Back to Plugins</a></p></body></html>").encode()
self.send_response(status)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(page)))
# Its own CSP without `sandbox`: the page is the viewer's own (no
# plugin bytes), and its Back link must keep the session cookie.
self.send_header("Content-Security-Policy", PLUGIN_DOCS_ERROR_CSP)
self.send_header("Referrer-Policy", "no-referrer")
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(page)

def serve_font(self, name):
"""GET /fonts/<name>.woff2 — one of the woff2 files in fonts/.

Expand Down
3 changes: 3 additions & 0 deletions build_plugin_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,9 @@ def health_entry(client, timeout=3):
viewer_url=str(body.get("viewer_url") or ""),
queue={"running": queue.get("running"), "waiting": queue.get("waiting")} if queue else None,
capabilities=[str(c) for c in body.get("capabilities") or [] if isinstance(c, str)])
if isinstance(body.get("docs"), str):
# Optional GET /docs path, raw; the viewer validates it (docs: true/false).
entry["docs"] = body["docs"]
if not entry["ok"]:
entry["error"] = str(body.get("error") or "plugin reports not ok")
return entry
Expand Down
4 changes: 4 additions & 0 deletions mt-tests/scripts/plugin_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -717,6 +717,10 @@ def check(client):
config=None)
if body is not None:
entry["capabilities"] = body.get("capabilities") or []
# The optional /health `docs` path, raw: the viewer validates it
# and passes only a docs true/false on to the browser.
if isinstance(body.get("docs"), str):
entry["docs"] = body["docs"]
try:
entry["devices"] = client.devices(timeout=timeout)
except PluginError:
Expand Down
Loading
Loading