feat: read-only Wodify athlete client
A CLI that answers "what classes ran", "who was there" and "what was the workout" with a single HTTP POST each -- no browser at query time. Wodify's athlete app is an OutSystems Reactive SPA. Driving it with a headless browser works but is slow and, for an LLM agent, expensive: a full page render to read a few lines back out of the DOM. Its data actions are plain JSON endpoints, so this talks to them directly. wodify list date 2026-07-25 time, coach, booked/max, title, duration, ID wodify list workout <id> attendee names + that class's workout Two phases. `prime` attaches over CDP to a browser that is already logged in and captures the session cookies, the CSRF token, and each action's apiVersion and body shape. Everything after that is stdlib HTTP -- the query path has no third-party dependencies at all. Three things genuinely require the browser, which is why priming exists: - the session bearer nr1W_Theme_UI is HttpOnly, so it cannot be exported by hand - X-CSRFToken is not in cookies, localStorage, or any JS global - apiVersion is per-action, not global Read-only is enforced in code, not by the credential (Wodify issues no read-only token): an explicit allowlist plus a write-marker guard applied even to allowlisted paths, so a careless registry edit fails closed. Tests assert that real mutating endpoint names are refused. Responses are cached in SQLite, keyed by the local date they were fetched on, so a repeat query the same day touches no network. All fetching funnels through service.py so a call site cannot forget the cache. Staleness is explicit rather than silent: responses carry hasModuleVersionChanged/hasApiVersionChanged, and the client raises VersionStale/SessionExpired instead of returning a plausible empty result. That matters because every bug found while building this produced confident wrong output rather than an error -- see CLAUDE.md for the field-name traps. History squashed before first publication: earlier commits embedded real gym members' names in test fixtures. Fixtures now use fictional names. 122 tests, no network required. Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
commit
5a61890011
31 files changed
+3576
No files matched your search
@@ -0,0 +1,230 @@
|
||||
"""Capture session credentials and per-action metadata from a logged-in browser.
|
||||
|
||||
Run rarely: once after login, and again when Wodify redeploys (the query path
|
||||
raises :class:`~wodify.client.VersionStaleError` when that happens).
|
||||
|
||||
What has to be sniffed rather than read, and why:
|
||||
|
||||
* ``nr1W_Theme_UI`` is HttpOnly -- page JS cannot see it, so it is read at
|
||||
browser scope over CDP.
|
||||
* ``X-CSRFToken`` is not in cookies, localStorage, or any JS global. It appears
|
||||
only on outbound requests.
|
||||
* ``apiVersion`` is **per-action**, so each endpoint's value must be observed
|
||||
from a real call to that endpoint.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import datetime as _dt
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from . import actions, cdp, client, config
|
||||
|
||||
#: Screens to walk so the interesting data actions actually fire. Ordered:
|
||||
#: Home first (it is the reliable entry point and populates client vars).
|
||||
WALK = (
|
||||
("/WodifyClient/Home", 12),
|
||||
("/WodifyClient/Scheduler", 10),
|
||||
)
|
||||
|
||||
#: In-app click walk: Schedule -> a date -> a class -> Go to workout.
|
||||
#:
|
||||
#: This is required, not a nicety. ``GetAllWorkoutData`` (the workout content)
|
||||
#: fires *only* on the properly-reached workout screen -- a direct load of
|
||||
#: /WodifyClient/Exercise never issues it, and OutSystems serves a cached copy if
|
||||
#: the date has not changed. Walking to a class on a specific date forces a real
|
||||
#: request, which is what exposes the apiVersion and body shape.
|
||||
#:
|
||||
#: Clicks are text-matched and confined to navigation. Nothing here touches
|
||||
#: Reserve, Cancel, waitlist, or results controls.
|
||||
WORKOUT_WALK_JS = r"""
|
||||
(async () => {
|
||||
const log = [];
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
const clickText = (txt) => {
|
||||
const els = [...document.querySelectorAll('*')].filter(
|
||||
e => e.childElementCount === 0 && e.textContent.trim() === txt);
|
||||
if (!els.length) return false;
|
||||
els[els.length - 1].click();
|
||||
return true;
|
||||
};
|
||||
const clickAria = frag => {
|
||||
const el = [...document.querySelectorAll('[aria-label]')]
|
||||
.find(e => (e.getAttribute('aria-label') || '').includes(frag));
|
||||
if (!el) return false;
|
||||
el.click();
|
||||
return true;
|
||||
};
|
||||
|
||||
log.push('schedule=' + clickText('Schedule'));
|
||||
await sleep(3500);
|
||||
if (__DATE_LABEL__) { log.push('date=' + clickAria(__DATE_LABEL__)); await sleep(3500); }
|
||||
|
||||
const classes = [...document.querySelectorAll('*')]
|
||||
.filter(e => e.childElementCount === 0 && /^[A-Za-z][^,]*:\s*\d{1,2}:\d{2}/.test(e.textContent.trim()))
|
||||
.map(e => e.textContent.trim())
|
||||
.filter((v, i, a) => a.indexOf(v) === i);
|
||||
log.push('classes=' + classes.length);
|
||||
if (!classes.length) return JSON.stringify({log, ok: false, why: 'no classes on that date'});
|
||||
|
||||
log.push('class=' + clickText(classes[0]));
|
||||
await sleep(4000);
|
||||
const hasLink = document.body.innerText.includes('Go to workout');
|
||||
log.push('hasGoToWorkout=' + hasLink);
|
||||
if (!hasLink) return JSON.stringify({log, ok: false, why: 'no workout posted for that class'});
|
||||
|
||||
log.push('goto=' + clickText('Go to workout'));
|
||||
await sleep(5000);
|
||||
return JSON.stringify({log, ok: document.body.innerText.includes('WARM-UP')});
|
||||
})()
|
||||
"""
|
||||
|
||||
#: Paths we want metadata for, indexed for quick lookup.
|
||||
WANTED_PATHS = {a.path for a in actions.ACTIONS.values()}
|
||||
|
||||
|
||||
def _observe(event: dict[str, Any], found: dict[str, dict[str, Any]],
|
||||
csrf: list[str]) -> None:
|
||||
"""Record versionInfo/viewName/input shape for any wanted read action."""
|
||||
if event.get("method") != "Network.requestWillBeSent":
|
||||
return
|
||||
req = (event.get("params") or {}).get("request") or {}
|
||||
url = req.get("url") or ""
|
||||
if "/screenservices/" not in url:
|
||||
return
|
||||
|
||||
for name, value in (req.get("headers") or {}).items():
|
||||
if name.lower() == "x-csrftoken" and value and not csrf:
|
||||
csrf.append(value)
|
||||
|
||||
path = url.split("/screenservices/", 1)[1]
|
||||
if path not in WANTED_PATHS or path in found:
|
||||
return
|
||||
|
||||
body = req.get("postData")
|
||||
if not body:
|
||||
return
|
||||
try:
|
||||
parsed = json.loads(body)
|
||||
except json.JSONDecodeError:
|
||||
return
|
||||
|
||||
version = parsed.get("versionInfo") or {}
|
||||
if not version.get("apiVersion"):
|
||||
return
|
||||
|
||||
# Never store a mutating path, even if Wodify reuses a name we allowlisted.
|
||||
actions.assert_read_only(path)
|
||||
|
||||
# Store the whole body minus versionInfo. Screen data actions carry their
|
||||
# parameters in `screenData.variables` -- the entire screen state, including
|
||||
# ClientVariables -- rather than `inputParameters`, so the body *is* the
|
||||
# contract and cannot be reconstructed field by field.
|
||||
body_template = {k: v for k, v in parsed.items() if k != "versionInfo"}
|
||||
|
||||
found[path] = {
|
||||
"api_version": version["apiVersion"],
|
||||
"module_version": version.get("moduleVersion"),
|
||||
"view_name": parsed.get("viewName"),
|
||||
"body_template": body_template,
|
||||
"body_keys": sorted(body_template),
|
||||
}
|
||||
|
||||
|
||||
def _date_label(date: str | None) -> str:
|
||||
"""JS string literal for the aria-label fragment of a schedule date button.
|
||||
|
||||
Wodify labels them like "Friday, July 24, 2026", so match on "July 24".
|
||||
"""
|
||||
if not date:
|
||||
return "null"
|
||||
try:
|
||||
parsed = _dt.date.fromisoformat(date)
|
||||
except ValueError:
|
||||
return "null"
|
||||
return json.dumps(parsed.strftime("%B ") + str(parsed.day))
|
||||
|
||||
|
||||
async def _run(walk=WALK, workout_date: str | None = None) -> dict[str, Any]:
|
||||
session = await cdp.CDPSession.connect()
|
||||
walk_log: Any = None
|
||||
try:
|
||||
cookie = await session.session_cookies()
|
||||
await session.open_page()
|
||||
|
||||
found: dict[str, dict[str, Any]] = {}
|
||||
csrf: list[str] = []
|
||||
|
||||
for path, wait in walk:
|
||||
await session.navigate(config.origin() + path)
|
||||
await session.drain(wait, lambda ev: _observe(ev, found, csrf))
|
||||
|
||||
# Walk to a real workout screen so GetAllWorkoutData (and the class
|
||||
# detail actions) actually fire.
|
||||
script = WORKOUT_WALK_JS.replace("__DATE_LABEL__", _date_label(workout_date))
|
||||
walk_task = asyncio.create_task(session.evaluate(script, await_promise=True))
|
||||
await session.drain(26, lambda ev: _observe(ev, found, csrf))
|
||||
try:
|
||||
walk_log = await asyncio.wait_for(walk_task, timeout=10)
|
||||
except (asyncio.TimeoutError, Exception): # noqa: BLE001 - best effort
|
||||
walk_log = None
|
||||
|
||||
module_version = await session.evaluate(
|
||||
"fetch('/WodifyClient/moduleservices/moduleversioninfo')"
|
||||
".then(r => r.json()).then(j => j.versionToken)",
|
||||
await_promise=True,
|
||||
)
|
||||
finally:
|
||||
await session.close()
|
||||
|
||||
if not csrf:
|
||||
raise RuntimeError(
|
||||
"no X-CSRFToken observed. The browser is logged in but made no data "
|
||||
"action calls -- try again, or widen the walk in prime.WALK."
|
||||
)
|
||||
if not module_version:
|
||||
module_version = next(
|
||||
(m["module_version"] for m in found.values() if m.get("module_version")), None
|
||||
)
|
||||
if not module_version:
|
||||
raise RuntimeError("could not determine moduleVersion")
|
||||
|
||||
return {
|
||||
"host": config.host(),
|
||||
"primed_at": _dt.datetime.now(_dt.timezone.utc).isoformat(timespec="seconds"),
|
||||
"cookie": cookie,
|
||||
"csrf": csrf[0],
|
||||
"module_version": module_version,
|
||||
"actions": found,
|
||||
"walk_log": walk_log,
|
||||
}
|
||||
|
||||
|
||||
def prime(workout_date: str | None = None) -> dict[str, Any]:
|
||||
"""Capture and persist session state. Returns a non-secret summary.
|
||||
|
||||
``workout_date`` should be a day that actually has a posted WOD -- the
|
||||
workout action cannot be captured from a day with nothing published.
|
||||
"""
|
||||
payload = asyncio.run(_run(workout_date=workout_date))
|
||||
walk_log = payload.pop("walk_log", None)
|
||||
path = client.save_cache(payload)
|
||||
|
||||
captured = sorted(payload["actions"])
|
||||
missing = sorted(
|
||||
a.key for a in actions.ACTIONS.values() if a.path not in payload["actions"]
|
||||
)
|
||||
return {
|
||||
"cache": str(path),
|
||||
"host": payload["host"],
|
||||
"cookie_chars": len(payload["cookie"]),
|
||||
"csrf_chars": len(payload["csrf"]),
|
||||
"module_version": payload["module_version"],
|
||||
"actions_captured": [
|
||||
k for k, a in sorted(actions.ACTIONS.items()) if a.path in payload["actions"]
|
||||
],
|
||||
"actions_missing": missing,
|
||||
"raw_paths_captured": len(captured),
|
||||
"walk": walk_log,
|
||||
}
|
||||
Reference in new issue
Block a user