diff --git a/.env.example b/.env.example index ed16451..4842065 100644 --- a/.env.example +++ b/.env.example @@ -160,3 +160,9 @@ RP_NAME=openGym # per provider, or for the Codex provider cached in ./coach-auth — a sibling of ./data, never inside it, # so a live sign-in does not ride along in the documented backup archive. # See docs/AI_COACH.md. +# ── Hevy map regeneration (developers only) ──────────────────────────────── +# Not used by the running app. End users paste their own key in Settings → +# Import from Hevy. Set this only to regenerate frontend/src/lib/hevy-id-map.js: +# +# HEVY_API_KEY= +# node scripts/build-hevy-id-map.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index c8cfa42..8eac556 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -82,6 +82,126 @@ are object keys downstream (`__proto__`, `constructor`) are refused; weight and speed have ceilings; an exercise cannot be added twice to a routine; two changes cannot share an id; a weight for an exercise never lifted is dropped rather than guessed. +## v1.2.14 — 2026-08-30 + +The largest community release so far: twenty merge requests from ten contributors, read and +tried one by one on a staging instance, plus two features of our own and a pass over how the +app feels under a thumb. Nothing changes on the server — a self-hosted instance only needs the +new web bundle; the APK carries the new reminder scheduling. + +### New + +- 📝 **Log a past workout.** History → "Log a past workout": pick date, start time, duration + and a routine (or freestyle), then log it on the normal workout screen — weights, reps, + RIR/RPE, timed sets, everything. A day that already has a workout asks: replace it, add a + second one, or cancel. Backfilled sessions are filed in chronological order, claim no PRs + against later history, and don't touch the weights your next session starts from. +- 📥 **Import straight from Hevy.** Settings → Import from Hevy with a Hevy Pro API key pulls + workouts, routines and weigh-ins directly — no CSV export needed. The key is used for the + one import and never stored; importing again updates the routines it created instead of + duplicating them. (JuliusHaring, !30) +- ⏲️ **Rest per exercise.** Any exercise can carry its own rest time; a superset rests once, + with the longest of the group. The global timer stays the default, and "Off" is overridden + only by an explicit per-exercise rest. Shared plans carry it. (trapy, !34 — issue #10) +- 🧘 **Planned deloads.** A routine can be excluded from automatic progression: its sessions + open on the routine's own targets, stay in history and statistics, and are skipped when the + next regular session computes its prescription — reps and durations included. + (tokyo_underworld, !28) +- 📳 **Timer flash.** Opt-in screen flash when a rest or work timer ends — for loud gyms and + headphones. (mzspicoli, !29) +- 🌍 **Thai and Hungarian.** Full UI translation in both; Hungarian also localizes all 1,326 + exercise names and instructions. That makes 14 languages. (tomzt, !64 · kecskemethy, !68) + +### Active workout + +- ➕ Adding an exercise mid-session now also **moves and swaps** cleanly: move the current + exercise or superset up/down (the rest countdown follows it), or swap it for another — + logged sets stay with the original, the replacement arrives with your usual weights, and a + grouped exercise asks whether the replacement stays in the group. (Space-Hermes, !41, !43) +- 👉 **Swipe between exercises** on the workout card — left/right moves through the session, + buttons and inputs stay untouched. (Space-Hermes, !48) +- 🎯 **Supersets keep the next set centered** on screen, not just in view. (Space-Hermes, !52) +- 📖 **The progression line is now a button**: tap "Linear · +2.5 kg…" mid-workout to open the + exercise's settings; changed rules rebuild the open rows and keep everything you already + logged. (Space-Hermes, !54) + +### Routines and progression + +- ✋ **Reorder by long-press.** Hold a routine row and drag it; superset groups move as one + block. The arrow buttons stay, now group-aware and disabled at the ends. + (Space-Hermes, !45, !47) +- 🔢 **The double-progression rep range is visible**: "Reps from" and "Reps up to" side by + side, per-side exercises stepping in twos — and a progression step of zero can no longer be + saved by accident. (mflova, !69 and !60 follow-up) + +### Stats and the rest + +- 🔍 **The Stats exercise picker is searchable**, and the results stay above the mobile + keyboard. (mflova, !27) +- 🗺️ **The muscle map works from the keyboard** and ranks ties in body order. (Space-Hermes, !46) +- 🔕 **Android reminders follow the calendar**: scheduled per date instead of per weekday, so + a rescheduled day reminds you and a day you already trained stays quiet. (mflova, !66) +- 🤖 **The MCP coach reads what the app shows**: custom exercises resolve in every tool, + warm-ups no longer count as PRs, and progression policies report the value the UI uses. + (TheophileDiot, !38) +- 📚 **A self-hosting HTTPS guide** for valid certificates on a LAN-only address — wildcard + cert via DNS challenge, Caddy in front, no ports opened. (andi242, !67) + +### Feel + +A pass over touch, scroll and tap across the whole app: chip rows keep a slightly diagonal +swipe instead of handing it to the page; sheets decide an axis before following the finger, +snap back cleanly and close on a quick flick; the body-weight slider drags relative to the +knob instead of jumping to it; steppers repeat while held; going back restores your scroll +position; a just-dropped routine row is tappable immediately; the exercise picker's search +stays above the keyboard; set-row inputs, checkboxes and small icon buttons all got bigger +touch targets; and rows everywhere can be driven from a keyboard. + +With thanks to Space-Hermes, mflova, JuliusHaring, trapy, tokyo_underworld, mzspicoli, +TheophileDiot, tomzt, kecskemethy and andi242 — ten contributors in one release. + +## v1.2.13 — 2026-08-30 + +One follow-up that arrived on !60 minutes after v1.2.12 was tagged, and belongs with it. + +- 🔢 **An empty or zero progression step can no longer be saved.** With a progression rule on, + leaving the step field empty or at `0` marks it red, explains why, and holds the save — a step + that cannot progress anything is no longer stored by accident. Nothing else changed; a + self-hosted instance only needs the new web bundle. (mflova, !60) + +## v1.2.12 — 2026-08-30 + +Six small fixes from the community, each read and tried on staging before it went in. All of +them are in the active workout or the exercise settings; nothing changes on the server, so a +self-hosted instance only needs the new web bundle. + +### Active workout + +- ➕ **Adding an exercise mid-session puts it right after the one you are on**, not at the end + of the list, and the flow carries on from there: "next" takes you to the next *unfinished* + exercise and the finish prompt only appears once nothing is left open. Before, a set added + late could leave you looking at a completion prompt with work still pending. + (Space-Hermes, !42) +- ⏱️ **Removing an exercise no longer leaves a timer behind.** A rest countdown that belonged to + the removed exercise stops with it — but a rest you are in the middle of for a *different* + exercise keeps running and simply follows that exercise. (Space-Hermes, !51, narrowed here) +- ⏹️ **Discarding a workout stops a running timed set.** The countdown used to keep going, and + beep, on a session that no longer existed. Cancelling the confirmation leaves it running. + (Space-Hermes, !59) +- 🗺️ **A custom exercise you delete still counts in recovery.** The muscle map and the recovery + view read the snapshot saved with each finished workout, so deleting the exercise afterwards + no longer blanks the muscles it trained. (Space-Hermes, !58) + +### Exercise settings + +- 🔢 **Progression steps below one can be typed.** Entering `0.5` used to snap back to the + default halfway through, because the field rejected the intermediate `0`. A cleared field + still means "use the default". (mflova, !60) +- 📐 **Long values in routine rows no longer squash the title.** The value column is capped + instead of reserving space, so a "3 × 12 @ 102.5 kg" row keeps its exercise name readable on a + narrow phone. (MokshManral, !37) + +With thanks to Space-Hermes, mflova and MokshManral. ## v1.2.11 — 2026-08-25 diff --git a/README.md b/README.md index fffe1fe..252d8cc 100644 --- a/README.md +++ b/README.md @@ -62,17 +62,23 @@ as a home-screen app, passkey sign-in, offline support, sync across your phone a - ⚖️ **Body-weight tracking** — interactive chart with a goal line you set, gains/losses colored by whether they move toward it - 🏋️ **Weekly plan** — a routine per weekday, over a library of **1,324 exercises** (searchable, with animated demos) - 🗓️ **Reschedule any day** — sick, missed a session, or fewer gym days this week? Move a workout to another day without touching your weekly plan -- ▶️ **Guided workouts** — it knows what day it is and starts today's session; asks your body weight first, pre-fills your weights from last time, rest timer, PR detection, per-exercise weight tracking +- 📅 **Your week starts where you say** — Monday or Sunday, in Settings. The weekly plan, the day strip on Home, the calendar and every "this week" total follow it, so the app reads the way the calendar on your wall does +- ▶️ **Guided workouts** — it knows what day it is and starts today's session; asks your body weight first, pre-fills your weights from last time, rest timer, PR detection, per-exercise weight tracking. On a rest day it doesn't just say "rest day" — it names when your next session is and what it is +- 🙈 **Animations are your call** — the exercise demos can be full size, small, or hidden entirely during a workout. Hidden collapses the media rather than leaving a gap, for anyone who finds a looping GIF between sets more distracting than useful - ☀️ **The screen stays awake while you train** — no unlocking the phone and finding your place again between every set. On for as long as a workout is running, released the moment you finish it, and switchable off in Settings - 🔗 **Supersets** — plan them into a routine or pair two exercises *mid-session* with “make superset with previous/next”, then work through the group back-to-back with a single rest at the end of each round. Unpair at any time; a group of one dissolves itself - 🔥 **Warm-up sets** — mark the ramp-up rows as warm-ups and they stay out of the numbers that should not see them: no effect on your estimated 1RM, your progression, or the fatigue map, while still being there in the session where you need them. A weight change cascades down the rows that share their phase, not across the divide - ➖ **Change your mind mid-session** — add an exercise you decided to do, or remove one you didn't, without ending the workout. Removing a member of a superset asks which one - ⏱️ **Timed exercises** — planks, hangs, wall sits and loaded carries are logged by time, not reps, with a work timer that counts the set itself (separate from the rest timer) and logs the time you actually held. They can carry weight too -- 📈 **Progression that follows a rule** — pick one per routine, override it per exercise: linear, **Greyskull LP** (AMRAP top set, double jumps, 10 % resets), double progression through a rep range, or adding time. Your weights are already right when the session opens, and every target says *why* it's that number. Missed reps never advance the load, stalls trigger a deload, and bodyweight exercises progress in reps instead +- ⏲️ **Rest per exercise** — heavy triples and curls don't want the same break: give any exercise its own rest time and it overrides the global timer for that exercise (a superset rests once, taking the longest). Travels with shared plans +- 🧘 **Planned deloads** — flag a routine as excluded from automatic progression: its sessions open with the routine's own target weights, stay in your history and statistics, and never become the baseline your next regular session progresses from +- 📈 **Progression that follows a rule** — pick one per routine, override it per exercise: linear, **Greyskull LP** (AMRAP top set, double jumps, 10 % resets), double progression through a **visible rep range** (both bounds editable, per-side exercises step in twos), or adding time. Your weights are already right when the session opens, and every target says *why* it's that number. Missed reps never advance the load, stalls trigger a deload, and bodyweight exercises progress in reps instead - 💪 **Estimated 1RM** — per exercise, from your best eligible set (it names which one), with its own progress curve and a calculator for sets you haven't done. Won't guess above 12 reps - 🎯 **Effort per set, in your scale** — an optional third column rating how hard a set was, as **RIR** (reps left in the tank) or **RPE** (the same judgement on a 10-point scale). Off by default; each set keeps the scale it was logged with, and nothing else reads the value — your progression and 1RM are unaffected - 💪 **Bodyweight exercises, logged as bodyweight** — push-ups, pull-ups, dips and 300-odd others arrive knowing they carry no load, so there's no weight column and no working-weight prompt: one stepper, log the reps. Add a dip belt and it reads as an addition, and progression goes back to following the weight. Without one, reps climb — and past a ceiling you set, a set is added instead of a rep, up to the point where the honest advice is load or a harder variation - ↔️ **Reps per side** — for lunges, single-arm rows and the rest. You log the total, the app shows the split ("8 per side"), and the target steps in twos so it never lands on a number one side can't have +- 🏋️ **Plate math for barbell work** — barbell, EZ, trap bar and Smith machine carry a bar weight (20 kg / 45 lb and friends, or your own per exercise), and the workout screen tells you what goes on each side: *Bar 20 kg · 30 kg per side*. You still log the total, so your history, progression and 1RM keep meaning exactly what they always did +- 📝 **Log a past workout** — forgot your phone, trained on paper, or switched apps? Add a session after the fact from History: date, start time, duration, routine or freestyle, then the normal workout screen — weights, reps, RIR/RPE, timed sets and all. If that day already has a workout you choose: replace it, keep both, or cancel. Backfilled sessions never claim PRs against workouts that came later - 🎲 **Freestyle sessions** — train without a plan and pick exercises as you go. Each one arrives prefilled from the last time you did it — same sets, same reps and weight by position — so an unplanned session doesn't start by asking you to retype last week - 🏃 **Cardio** — log time + speed, not just weight × reps - 📤 **Share a plan** — send someone your routines and week schedule as a small file (no workouts, no weigh-ins), or print it as a clean PDF. Importing merges, so their plan is never overwritten @@ -80,12 +86,13 @@ as a home-screen app, passkey sign-in, offline support, sync across your phone a - ✨ **Your own exercises** — a name and a body part is enough; they behave like built-in ones everywhere, with an optional description instead of an animation - 🟩 **Activity heatmap** — a GitHub-style year view, shaded by time spent training - 💪 **Muscle map, three ways** — a front-and-back body diagram you can read as **Balance** (where the volume went, over a week, a month or all time — naming the muscles you *haven't* trained), **Fatigue** (what is still recovering, weighted by how close each set was to your maximum, decaying smoothly rather than expiring at a window edge) or **Strength** (how long since you trained each muscle, and behind every one the exercises that built it with their estimated 1RM). It previews what a routine hits while you build it, and shows what you just trained when you finish. Male or female figure, your pick -- 🔔 **Push notifications** — rest-timer alerts even with the app closed, plus an optional reminder on days you have a workout planned but haven't logged one. Opt in per profile; keys are generated on first run, nothing to configure +- 📳 **See the timer end, not just hear it** — an opt-in screen flash when a rest or work timer finishes, for loud gyms and headphones +- 🔔 **Push notifications** — rest-timer alerts even with the app closed, plus an optional reminder on days you have a workout planned but haven't logged one — on the Android app scheduled per calendar date, so a day you already trained or rescheduled stays quiet. Opt in per profile; keys are generated on first run, nothing to configure - 🔑 **Passkeys, not passwords** — Face ID / Touch ID / fingerprint login; each profile keeps its own data, synced across devices. Sign-ins last 90 days by default (configurable), and “sign out everywhere” in Settings ends every session on every device at once - 🛠️ **Admin dashboard** (optional) — for whoever runs the instance: who's training right now, per-user history, disable accounts, invite-only signup, and an **activity log** of sign-ins, failed attempts and admin actions. Off by default, so a fresh instance stays open with no admin - 🎨 **Designed, not assembled** — light/dark themes and 8 accent colors saved to your profile, over a hand-drawn icon set instead of emoji, so it looks the same on every phone -- 🌍 **13 languages** — full UI translation (EN, DE, ES, FR, IT, PT (Portugal), PT (Brazil), PL, TR, RU, ZH, KO, HI); exercise instructions localized in 11 of them and built-in exercise names shown bilingually in PT-BR, all loaded on demand so the app stays fast -- 📥 **Bring your history with you** — import from **FitNotes** (Android and iOS), **Strong** and **Hevy**, or body weight straight out of an **Apple Health** export. Exercise names are matched against the library and anything unrecognised becomes one of your own exercises, so nothing in the file is dropped +- 🌍 **14 languages** — full UI translation (EN, DE, ES, FR, IT, PT (Portugal), PT (Brazil), PL, TR, RU, ZH, KO, HI, TH, HU); exercise instructions localized in 12 of them and built-in exercise names shown bilingually in PT-BR and HU, all loaded on demand so the app stays fast +- 📥 **Bring your history with you** — import from **FitNotes** (Android and iOS), **Strong** and **Hevy** (CSV or directly with a [Hevy Pro API key](https://hevy.com/settings?developer)), or body weight straight out of an **Apple Health** export. Exercise names are matched against the library and anything unrecognised becomes one of your own exercises, so nothing in the file is dropped - 📦 **Yours to keep** — one-tap JSON export/import, guest mode, **no telemetry** - 🤖 **Ask an AI about your training** (optional) — an [MCP server](mcp/README.md) lets a client like Claude Desktop or Cursor read your history in your own words: *"what did I bench last week?"*. Read-only, spawned locally by the client, nothing leaves your box. Not in the Docker build — if you don't use an AI assistant, it isn't there - 🧠 **An AI coach that writes your plan** (optional, off by default) — answer a handful of questions and it designs a week of routines; later it reads what you actually logged and proposes changes, each one with the evidence behind it. You approve every change and can undo it. It runs on **your** server under **your** provider account — Anthropic, OpenAI, Gemini or any OpenAI-compatible endpoint (Ollama on your LAN counts) with a pasted API key on the default image, or the Claude Agent SDK / Codex CLI on a separate build. The phone app can use your instance or its own key. See [docs/AI_COACH.md](docs/AI_COACH.md) @@ -154,6 +161,8 @@ mobile app is the install-and-done flavor. - **api/** — Node with no framework, two dependencies (`@simplewebauthn/server` for passkeys, `web-push` for notifications), storing everything as plain JSON files under `./data` - **web/** — a multi-stage image that builds the frontend and serves it with nginx, proxying `/api` to the backend so it's all on **one origin** (passkeys require this) +The full HTTP API is documented as an OpenAPI spec in [`api/openapi.yaml`](api/openapi.yaml) — browsable at [opengym.duarte-santos.ch/api.html](https://opengym.duarte-santos.ch/api.html). + ## Your data Lives in `./data` on your host: `db.json` (profiles + public passkeys), `state-.json` @@ -201,7 +210,7 @@ Rough, community-driven — ideas and PRs welcome: - [x] Optional AI coach — designs a plan and reviews your training, on your own server and your own provider account ([docs](docs/AI_COACH.md)) - [ ] Percentage / training-max programming (5/3/1-style) on top of the progression engine - [ ] More starter plans (upper/lower, full-body, 5×5) -- [x] Importers from FitNotes / Strong / Hevy (including the RPE they record), and body weight from Apple Health +- [x] Importers from FitNotes / Strong / Hevy (CSV, or Hevy Pro API key — workouts and/or weigh-ins), including the RPE they record, and body weight from Apple Health - [x] Effort per set — RIR or RPE, whichever scale you think in - [ ] Body measurements (waist, arms…) alongside weight - [ ] Per-exercise notes & plate calculator diff --git a/api/openapi.yaml b/api/openapi.yaml new file mode 100644 index 0000000..710c738 --- /dev/null +++ b/api/openapi.yaml @@ -0,0 +1,1398 @@ +# openGym HTTP API — hand-written OpenAPI 3.1 spec. +# Source of truth: api/server.js (a single framework-free Node file). Every route the +# server registers is documented here; if you add a route there, add it here too. +# Browsable version: https://opengym.duarte-santos.ch/api.html +openapi: 3.1.0 + +info: + title: openGym API + version: 1.2.14 + summary: Passkey (WebAuthn) auth + per-user state storage for openGym + description: | + The backend of [openGym](https://opengym.duarte-santos.ch) — a free, open-source + gym & body-weight tracker. One Node file, no framework, JSON-file storage, + HMAC-signed session cookies. + + ### Authentication + Sign-in is **passkey only** (WebAuthn, via `@simplewebauthn/server`). A successful + `register/verify` or `login/verify` sets the session cookie; every authenticated + route then works with that cookie. The paired mobile app has no shared cookie jar, + so it redeems a short pairing code (`/api/pair/redeem`) for the *same* signed token + and sends it as `Authorization: Bearer ` instead. + + ### Sessions + The cookie/bearer value is `.` where the payload is + `::`, signed with a per-instance secret + (HMAC-SHA256). Sessions last `SESSION_DAYS` (default 90). `POST /api/logout/all` + bumps the user's session version, which invalidates every token ever issued for + the account. + + ### CSRF + State-changing browser requests must come from the app's own origin. The server + checks `Sec-Fetch-Site` (falling back to `Origin` vs the configured `ORIGIN`); + a mismatch is refused with `403 {"error":"cross-origin request refused"}` on any + non-GET route. Exempt: the WebAuthn and `pair/redeem` routes (each carries its own + one-shot credential in the body) and any request authenticated with a Bearer token. + + ### Environment-dependent behavior + - `INVITE_ONLY=1` — registration requires a valid invite code (minted by an admin). + - `ALLOW_GUEST=0` — hides the client-side "continue without account" mode; the + server merely reports the flag via `GET /api/config` (guest mode never talks to + this API at all). + - `ADMIN_UIDS=,` — user ids treated as admins (a `"admin": true` flag on + the user record in `db.json` works too). Admins get the `/api/admin/*` routes. + - `AUDIT_LOG` (default on), `AUDIT_MAX` (default 5000 events), `AUDIT_DAYS` + (default 90), `AUDIT_IP` (`off` | `net` | `full`, default off) — shape the audit + log served by `GET /api/admin/audit`. + + ### Conventions + - Every response body is JSON with `Cache-Control: no-store`. + - Errors are always `{"error": ""}`. + - Unknown method+path pairs return `404 {"error":"not found"}`; an unhandled + exception returns `500 {"error":"server error"}`. + - Request bodies are parsed as JSON regardless of Content-Type; max 5 MiB. + - CORS: the request's `Origin` is reflected in `Access-Control-Allow-Origin` + **without** `Allow-Credentials` — cross-origin callers can only ever + authenticate with a Bearer token, never with the cookie. + license: + name: AGPL-3.0-or-later + identifier: AGPL-3.0-or-later + contact: + name: openGym + url: https://gitlab.com/DuarteSantos8/opengym + +servers: + - url: / + description: Same origin as the openGym web app (the normal deployment) + - url: https://opengym.example.com + description: Your self-hosted instance + +tags: + - name: meta + description: Health and public configuration + - name: auth + description: Passkey (WebAuthn) registration and login, sessions + - name: pairing + description: Mobile-app pairing (code from a signed-in browser tab) + - name: data + description: Per-user state sync (the whole app state as one JSON blob) + - name: push + description: Web Push (VAPID) subscriptions, rest-timer and test pushes + - name: activity + description: Live-workout presence heartbeat + - name: admin + description: Admin dashboard — requires an admin session (`ADMIN_UIDS` or `admin:true`) + +security: + - cookieAuth: [] + - bearerAuth: [] + +paths: + /api/health: + get: + tags: [meta] + operationId: getHealth + summary: Health check + description: Always public. Also reports how many user accounts exist. + security: [] + responses: + '200': + description: The server is up. + content: + application/json: + schema: + type: object + properties: + ok: { type: boolean, const: true } + users: + type: integer + description: Number of registered user accounts. + example: { ok: true, users: 7 } + + /api/config: + get: + tags: [meta] + operationId: getConfig + summary: Public instance configuration + description: | + The flags the login screen needs before anyone is signed in. Both reflect + environment variables on the server (`INVITE_ONLY`, `ALLOW_GUEST`). + security: [] + responses: + '200': + description: Instance flags. + content: + application/json: + schema: + type: object + properties: + invite_only: + type: boolean + description: When true, registration requires a valid invite code. + allow_guest: + type: boolean + description: >- + When false, the client hides "continue without account". + Guest mode is purely client-side and never calls this API. + example: { invite_only: true, allow_guest: false } + + /api/me: + get: + tags: [auth] + operationId: getMe + summary: Who am I? + description: Resolves the current session to a user. + responses: + '200': + description: A valid session. + content: + application/json: + schema: + type: object + properties: + user: { $ref: '#/components/schemas/SessionUser' } + '401': { $ref: '#/components/responses/Unauthorized' } + + /api/register/options: + post: + tags: [auth] + operationId: registerOptions + summary: 'Start passkey registration (WebAuthn ceremony, step 1)' + description: | + Returns `PublicKeyCredentialCreationOptions` (from + `@simplewebauthn/server`'s `generateRegistrationOptions`) plus a challenge id + `cid`. The client passes `options` to + `navigator.credentials.create()` (or `@simplewebauthn/browser`'s + `startRegistration`) and sends the result to `/api/register/verify` together + with the `cid`. Challenges are one-shot and expire after 5 minutes. + + CSRF-exempt (the challenge is the credential). No session required. + security: [] + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [name] + properties: + name: + type: string + maxLength: 40 + description: Display name for the new profile (trimmed, max 40 chars). + code: + type: string + description: >- + Invite code — required (and validated) only when the instance + runs with INVITE_ONLY. Compared case-insensitively. + example: { name: "Ada", code: "3F9C21A07B54D688" } + responses: + '200': + description: Ceremony options. + content: + application/json: + schema: + type: object + properties: + cid: + type: string + description: One-shot challenge id, echo it back to /api/register/verify. + options: + $ref: '#/components/schemas/WebAuthnRegistrationOptions' + '400': + description: '`name` missing/empty.' + content: + application/json: + schema: { $ref: '#/components/schemas/Error' } + example: { error: "name required" } + '403': + description: Instance is invite-only and the code is missing, used, or revoked. + content: + application/json: + schema: { $ref: '#/components/schemas/Error' } + example: { error: "a valid invite code is required" } + + /api/register/verify: + post: + tags: [auth] + operationId: registerVerify + summary: 'Finish passkey registration (WebAuthn ceremony, step 2)' + description: | + Verifies the authenticator's attestation response against the stored + challenge (`verifyRegistrationResponse`), creates the user + credential, and + signs the caller in (sets the session cookie). On an invite-only instance the + invite is re-checked and burned here. CSRF-exempt. + security: [] + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [cid, credential] + properties: + cid: + type: string + description: The challenge id from /api/register/options. + credential: + $ref: '#/components/schemas/WebAuthnRegistrationCredential' + responses: + '200': + description: Registered and signed in. The session cookie is set. + headers: + Set-Cookie: + description: >- + Session cookie (`__Host-gymsid` on HTTPS deployments, `gymsid` over + plain http). HttpOnly, SameSite=Lax, Max-Age = SESSION_DAYS. + schema: { type: string } + content: + application/json: + schema: + type: object + properties: + user: { $ref: '#/components/schemas/SessionUser' } + '400': + description: >- + Challenge expired/replayed, or the attestation did not verify (wrong + origin/RP ID, malformed response…). The message is human-readable. + content: + application/json: + schema: { $ref: '#/components/schemas/Error' } + example: { error: "challenge expired — try again" } + '403': + description: Invite-only and the code became invalid since step 1. + content: + application/json: + schema: { $ref: '#/components/schemas/Error' } + example: { error: "invite code is no longer valid — ask for a new one" } + '409': + description: This credential id is already registered. + content: + application/json: + schema: { $ref: '#/components/schemas/Error' } + example: { error: "credential already registered" } + + /api/login/options: + post: + tags: [auth] + operationId: loginOptions + summary: 'Start passkey login (WebAuthn ceremony, step 1)' + description: | + Returns `PublicKeyCredentialRequestOptions` + (`generateAuthenticationOptions` with an empty `allowCredentials` — discoverable + credentials / resident keys are required at registration, so the browser offers + the user their passkeys itself) plus a one-shot challenge id `cid`. + CSRF-exempt. Takes no request body. + security: [] + responses: + '200': + description: Ceremony options. + content: + application/json: + schema: + type: object + properties: + cid: { type: string } + options: + $ref: '#/components/schemas/WebAuthnAuthenticationOptions' + + /api/login/verify: + post: + tags: [auth] + operationId: loginVerify + summary: 'Finish passkey login (WebAuthn ceremony, step 2)' + description: | + Verifies the assertion (`verifyAuthenticationResponse`), updates the signature + counter, and signs the caller in (sets the session cookie). CSRF-exempt. + security: [] + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [cid, credential] + properties: + cid: + type: string + description: The challenge id from /api/login/options. + credential: + $ref: '#/components/schemas/WebAuthnAuthenticationCredential' + responses: + '200': + description: Signed in. The session cookie is set. + headers: + Set-Cookie: + description: Session cookie (see /api/register/verify). + schema: { type: string } + content: + application/json: + schema: + type: object + properties: + user: { $ref: '#/components/schemas/SessionUser' } + '400': + description: Challenge expired/replayed, or the assertion did not verify. + content: + application/json: + schema: { $ref: '#/components/schemas/Error' } + example: { error: "not verified" } + '403': + description: The account has been disabled by an admin. + content: + application/json: + schema: { $ref: '#/components/schemas/Error' } + example: { error: "this account has been disabled" } + '404': + description: The passkey's credential id is unknown to this instance. + content: + application/json: + schema: { $ref: '#/components/schemas/Error' } + example: { error: "unknown passkey — create a profile first" } + '500': + description: Credential exists but its user record is missing (corrupt db). + content: + application/json: + schema: { $ref: '#/components/schemas/Error' } + example: { error: "user missing" } + + /api/logout: + post: + tags: [auth] + operationId: logout + summary: Sign out (this device) + description: >- + Clears the session cookie. Always succeeds — an invalid or missing session is + a no-op. The token itself stays cryptographically valid until it expires; use + /api/logout/all to revoke tokens. + security: [] + responses: + '200': + description: Cookie cleared. + headers: + Set-Cookie: + description: Expires the session cookie(s). + schema: { type: string } + content: + application/json: + schema: { $ref: '#/components/schemas/Ok' } + + /api/logout/all: + post: + tags: [auth] + operationId: logoutAll + summary: Sign out everywhere + description: | + Bumps the account's session version, which invalidates **every** cookie and + Bearer token ever issued for it — on every device, including a copy someone + walked off with. Passkeys are untouched; signing back in works immediately. + Also clears the caller's own cookie. + responses: + '200': + description: All sessions revoked. + headers: + Set-Cookie: + description: Expires the caller's session cookie(s). + schema: { type: string } + content: + application/json: + schema: { $ref: '#/components/schemas/Ok' } + '401': { $ref: '#/components/responses/Unauthorized' } + + /api/pair/create: + post: + tags: [pairing] + operationId: pairCreate + summary: Mint a pairing code for the mobile app + description: | + Called from an already signed-in browser tab (Settings → "Pair the mobile + app"). Returns an 8-character code (alphabet without 0/O/1/I) the phone + redeems within 5 minutes via /api/pair/redeem. One-shot. + responses: + '200': + description: A fresh pairing code. + content: + application/json: + schema: + type: object + properties: + code: + type: string + description: 8 chars from ABCDEFGHJKLMNPQRSTUVWXYZ23456789. + example: { code: "K7WQ2MZP" } + '401': { $ref: '#/components/responses/Unauthorized' } + + /api/pair/redeem: + post: + tags: [pairing] + operationId: pairRedeem + summary: Redeem a pairing code for a Bearer token + description: | + Called from the mobile app with the code shown in the browser. No session + required — the code *is* the credential (one-shot, 5-minute TTL). Returns the + same HMAC-signed session token the cookie would carry; the app sends it as + `Authorization: Bearer ` from then on. CSRF-exempt. + security: [] + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [code] + properties: + code: + type: string + description: The pairing code (case-insensitive). + example: { code: "K7WQ2MZP" } + responses: + '200': + description: Paired. + content: + application/json: + schema: + type: object + properties: + token: + type: string + description: Signed session token, valid for SESSION_DAYS. + user: { $ref: '#/components/schemas/SessionUser' } + '400': + description: >- + Code unknown, already used, expired — or the account behind it is gone or + disabled (deliberately the same message for all of these). + content: + application/json: + schema: { $ref: '#/components/schemas/Error' } + example: { error: "invalid or expired code" } + + /api/data: + get: + tags: [data] + operationId: getData + summary: Pull the account's app state + description: >- + Returns the caller's entire app state as one JSON blob, or `{"state": null}` + if nothing has been synced yet. Sync conflict resolution happens client-side + (last-writer-wins by the client-set `_ts` timestamp). + responses: + '200': + description: The stored state, or null. + content: + application/json: + schema: + type: object + properties: + state: + oneOf: + - $ref: '#/components/schemas/State' + - type: 'null' + '401': { $ref: '#/components/responses/Unauthorized' } + put: + tags: [data] + operationId: putData + summary: Push the account's app state + description: | + Replaces the stored state wholesale (atomic write; there is no merge on the + server). The `active` field — an in-progress workout — is stripped before + saving: a running session belongs to the device running it. Body limit 5 MiB. + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [state] + properties: + state: { $ref: '#/components/schemas/State' } + responses: + '200': + description: Saved. + content: + application/json: + schema: + type: object + properties: + ok: { type: boolean, const: true } + ts: + oneOf: [{ type: number }, { type: 'null' }] + description: Echo of the pushed state's `_ts`, if present. + '400': + description: '`state` missing or not an object.' + content: + application/json: + schema: { $ref: '#/components/schemas/Error' } + example: { error: "state required" } + '401': { $ref: '#/components/responses/Unauthorized' } + + /api/push/public-key: + get: + tags: [push] + operationId: pushPublicKey + summary: VAPID public key + description: >- + The instance's Web-Push application server key (generated once at first boot), + for `PushManager.subscribe({applicationServerKey})`. Public. + security: [] + responses: + '200': + description: The key. + content: + application/json: + schema: + type: object + properties: + key: + type: string + description: base64url-encoded P-256 public key. + + /api/push/subscribe: + post: + tags: [push] + operationId: pushSubscribe + summary: Register a Web-Push subscription + description: | + Stores the browser's `PushSubscription` for this account. Only `endpoint` and + the two protocol keys are kept. The endpoint must be a public `https://` URL — + private/loopback/link-local addresses are refused (here and again at send + time, against DNS rebinding). At most 20 subscriptions per user; the oldest + are dropped first. Re-subscribing an existing endpoint replaces it. + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [subscription] + properties: + subscription: { $ref: '#/components/schemas/PushSubscription' } + responses: + '200': + description: Stored. + content: + application/json: + schema: { $ref: '#/components/schemas/Ok' } + '400': + description: Malformed subscription, or an endpoint that isn't acceptable. + content: + application/json: + schema: { $ref: '#/components/schemas/Error' } + examples: + malformed: { value: { error: "invalid subscription" } } + private: { value: { error: "endpoint must not point at a private address" } } + '401': { $ref: '#/components/responses/Unauthorized' } + + /api/push/unsubscribe: + post: + tags: [push] + operationId: pushUnsubscribe + summary: Remove a Web-Push subscription + description: Removes the caller's subscription with the given endpoint. Idempotent. + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [endpoint] + properties: + endpoint: { type: string, format: uri } + responses: + '200': + description: Removed (or was never there). + content: + application/json: + schema: { $ref: '#/components/schemas/Ok' } + '401': { $ref: '#/components/responses/Unauthorized' } + + /api/push/test: + post: + tags: [push] + operationId: pushTest + summary: Send a test notification + description: >- + Sends a test push to all of the caller's subscriptions (localized with the + `lang` in their synced state). Returns 200 even if delivery to individual + endpoints fails — dead endpoints (404/410) are pruned as a side effect. + responses: + '200': + description: Sends attempted. + content: + application/json: + schema: { $ref: '#/components/schemas/Ok' } + '401': { $ref: '#/components/responses/Unauthorized' } + + /api/push/rest-timer: + post: + tags: [push] + operationId: pushRestTimer + summary: Schedule a server-side rest-timer push + description: | + Schedules one push after `seconds` (clamped to 1–3600; one pending timer per + user, a new call replaces it). The client schedules this on rest start/extend + and cancels on skip or on-screen completion — the push only actually fires + when the tab was backgrounded/suspended and never got to cancel it. + + Note: the documented `400 seconds required` exists in the code but is + unreachable — the clamp turns any missing/invalid value into 1. + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [seconds] + properties: + seconds: + type: number + minimum: 1 + maximum: 3600 + example: { seconds: 90 } + responses: + '200': + description: Timer scheduled. + content: + application/json: + schema: { $ref: '#/components/schemas/Ok' } + '401': { $ref: '#/components/responses/Unauthorized' } + + /api/push/rest-timer/cancel: + post: + tags: [push] + operationId: pushRestTimerCancel + summary: Cancel the pending rest-timer push + description: Cancels the caller's scheduled rest-timer push, if any. Idempotent. + responses: + '200': + description: Cancelled (or nothing was pending). + content: + application/json: + schema: { $ref: '#/components/schemas/Ok' } + '401': { $ref: '#/components/responses/Unauthorized' } + + /api/activity: + post: + tags: [activity] + operationId: postActivity + summary: Live-workout presence heartbeat + description: | + The client pings this every ~20 s while a workout is on screen; the admin + dashboard reads who is training right now. Purely ephemeral, in-memory, never + persisted; entries expire ~70 s after the last ping. `{"active": false}` + drops the caller's entry immediately. + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + active: + type: boolean + description: false ends the presence; true (with the fields below) updates it. + name: + type: string + maxLength: 60 + description: Routine/workout name being trained. + exIdx: { type: integer, description: Current exercise index (0-based). } + exTotal: { type: integer, description: Exercises in the workout. } + setsDone: { type: integer } + setsTotal: { type: integer } + startedAt: + type: number + description: Workout start, ms since epoch (defaults to now). + example: + active: true + name: "Push Day" + exIdx: 2 + exTotal: 5 + setsDone: 7 + setsTotal: 16 + startedAt: 1756500000000 + responses: + '200': + description: Presence updated. + content: + application/json: + schema: { $ref: '#/components/schemas/Ok' } + '401': { $ref: '#/components/responses/Unauthorized' } + + /api/admin/users: + get: + tags: [admin] + operationId: adminUsers + summary: 'Admin: list all users' + description: >- + One row per user with workout counts, last sync, push status and live + presence. Admin only. + responses: + '200': + description: All users. + content: + application/json: + schema: + type: object + properties: + users: + type: array + items: { $ref: '#/components/schemas/AdminUserRow' } + invite_only: { type: boolean } + now: + type: number + description: Server time (ms) — for rendering relative times. + '401': { $ref: '#/components/responses/Unauthorized' } + '403': { $ref: '#/components/responses/Forbidden' } + + /api/admin/user: + get: + tags: [admin] + operationId: adminUser + summary: 'Admin: one user in detail' + description: >- + Drill-down — full workout history (newest first) and body-weight log for one + user. Admin only. + parameters: + - name: id + in: query + required: true + schema: { type: string } + description: The user id. + responses: + '200': + description: The user's detail. + content: + application/json: + schema: { $ref: '#/components/schemas/AdminUserDetail' } + '401': { $ref: '#/components/responses/Unauthorized' } + '403': { $ref: '#/components/responses/Forbidden' } + '404': + description: No user with that id. + content: + application/json: + schema: { $ref: '#/components/schemas/Error' } + example: { error: "no such user" } + + /api/admin/user/disable: + post: + tags: [admin] + operationId: adminUserDisable + summary: 'Admin: disable or re-enable a user' + description: | + Sets the `disabled` flag. A disabled account is locked out everywhere at once + (every existing session stops resolving) and dropped from live presence. + Admins cannot be disabled. Audited. + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [id, disabled] + properties: + id: { type: string, description: The user id. } + disabled: { type: boolean } + responses: + '200': + description: Flag updated. + content: + application/json: + schema: + type: object + properties: + ok: { type: boolean, const: true } + id: { type: string } + disabled: { type: boolean } + '400': + description: Target is an admin. + content: + application/json: + schema: { $ref: '#/components/schemas/Error' } + example: { error: "cannot disable an admin" } + '401': { $ref: '#/components/responses/Unauthorized' } + '403': { $ref: '#/components/responses/Forbidden' } + '404': + description: No user with that id. + content: + application/json: + schema: { $ref: '#/components/schemas/Error' } + example: { error: "no such user" } + + /api/admin/invites: + get: + tags: [admin] + operationId: adminInvites + summary: 'Admin: list invite codes' + description: All invite codes, with the redeeming user's name resolved for display. + responses: + '200': + description: All invites. + content: + application/json: + schema: + type: object + properties: + invites: + type: array + items: { $ref: '#/components/schemas/Invite' } + invite_only: { type: boolean } + '401': { $ref: '#/components/responses/Unauthorized' } + '403': { $ref: '#/components/responses/Forbidden' } + + /api/admin/invites/new: + post: + tags: [admin] + operationId: adminInviteNew + summary: 'Admin: mint an invite code' + description: >- + Creates a fresh single-use invite code (16 hex chars = 64 bits — the code + itself is the thing that isn't worth guessing; rate limiting is the reverse + proxy's job). Audited. + requestBody: + required: false + content: + application/json: + schema: + type: object + properties: + note: + type: string + maxLength: 60 + description: Free-form label ("for Alex"). + responses: + '200': + description: The new invite. + content: + application/json: + schema: + type: object + properties: + invite: { $ref: '#/components/schemas/Invite' } + '401': { $ref: '#/components/responses/Unauthorized' } + '403': { $ref: '#/components/responses/Forbidden' } + + /api/admin/invites/revoke: + post: + tags: [admin] + operationId: adminInviteRevoke + summary: 'Admin: revoke an unused invite code' + description: Deletes an unused code. A code that was already redeemed cannot be revoked. + requestBody: + required: true + content: + application/json: + schema: + type: object + required: [code] + properties: + code: { type: string } + responses: + '200': + description: Revoked. + content: + application/json: + schema: { $ref: '#/components/schemas/Ok' } + '400': + description: The code was already used. + content: + application/json: + schema: { $ref: '#/components/schemas/Error' } + example: { error: "already used — cannot revoke" } + '401': { $ref: '#/components/responses/Unauthorized' } + '403': { $ref: '#/components/responses/Forbidden' } + '404': + description: No such code. + content: + application/json: + schema: { $ref: '#/components/schemas/Error' } + example: { error: "no such code" } + + /api/admin/audit: + get: + tags: [admin] + operationId: adminAudit + summary: 'Admin: read the activity log' + description: | + The audit log (sign-ins, failed attempts, admin actions), newest first, paged + by event id (`before` cursor — offset paging would repeat rows as new events + land). Retention (`AUDIT_MAX` events / `AUDIT_DAYS` days) is applied on read + as well as on the hourly compaction. When `AUDIT_LOG` is off the route still + answers, with `enabled: false` and whatever was logged before. + parameters: + - name: limit + in: query + schema: { type: integer, minimum: 1, maximum: 200, default: 100 } + description: Page size. + - name: before + in: query + schema: { type: integer } + description: Only events with id < before (cursor from `nextBefore`). + - name: cat + in: query + schema: + type: string + enum: [auth, admin, fail] + description: >- + Filter — `fail` keeps only failed events; any other value keeps events + whose name starts with `.` (in practice `auth` or `admin`). + responses: + '200': + description: One page of the log. + content: + application/json: + schema: + type: object + properties: + events: + type: array + items: { $ref: '#/components/schemas/AuditEvent' } + total: + type: integer + description: Rows matching the filter (after retention). + nextBefore: + oneOf: [{ type: integer }, { type: 'null' }] + description: Cursor for the next page; null on the last page. + enabled: + type: boolean + description: Whether audit logging is currently on (AUDIT_LOG). + ip_mode: + type: string + enum: [off, net, full] + description: How much of the caller IP is recorded (AUDIT_IP). + retention: + type: object + properties: + max: { type: integer, description: 'Event cap (0 = none).' } + days: { type: integer, description: 'Age cap in days (0 = none).' } + now: { type: number, description: Server time (ms). } + '401': { $ref: '#/components/responses/Unauthorized' } + '403': { $ref: '#/components/responses/Forbidden' } + + /api/admin/audit/clear: + post: + tags: [admin] + operationId: adminAuditClear + summary: 'Admin: clear the activity log' + description: >- + Deletes the log file. The clear is itself the first event of the fresh log, + and event ids are never reset — a wipe always leaves a visible id gap. + responses: + '200': + description: Cleared. + content: + application/json: + schema: { $ref: '#/components/schemas/Ok' } + '401': { $ref: '#/components/responses/Unauthorized' } + '403': { $ref: '#/components/responses/Forbidden' } + +components: + securitySchemes: + cookieAuth: + type: apiKey + in: cookie + name: gymsid + description: | + HMAC-signed session cookie, set by `register/verify` / `login/verify`. + On HTTPS deployments it is issued as **`__Host-gymsid`** (host-locked, + Secure); the unprefixed `gymsid` is what a plain-http `localhost` instance + uses, and is still accepted for pre-upgrade sessions. HttpOnly + SameSite=Lax; + browser clients never handle the value directly. + bearerAuth: + type: http + scheme: bearer + description: >- + The same signed session token, carried as `Authorization: Bearer ` by + the paired mobile app (obtained from `POST /api/pair/redeem`). Bearer requests + skip the CSRF origin check — a browser never attaches this header on its own. + + responses: + Unauthorized: + description: No session, expired/revoked session, or a disabled account. + content: + application/json: + schema: { $ref: '#/components/schemas/Error' } + example: { error: "not signed in" } + Forbidden: + description: Signed in, but not an admin. The attempt is recorded in the audit log. + content: + application/json: + schema: { $ref: '#/components/schemas/Error' } + example: { error: "forbidden" } + + schemas: + Error: + type: object + required: [error] + properties: + error: + type: string + description: Human-readable message. This is the only error shape the API has. + + Ok: + type: object + properties: + ok: { type: boolean, const: true } + + SessionUser: + type: object + description: The caller's identity, as returned by /api/me and the sign-in routes. + properties: + id: { type: string, description: Stable user id (16 base64url chars). } + name: { type: string } + admin: { type: boolean } + example: { id: "Zk3q9XyPbA2LmN0v", name: "Ada", admin: false } + + # ------------------------------------------------------------------ WebAuthn + # These mirror @simplewebauthn/server v13's JSON shapes (themselves the W3C + # WebAuthn Level 3 JSON serialization). Clients normally never build them by + # hand — @simplewebauthn/browser converts them to/from the navigator.credentials + # calls. Documented loosely on purpose; the library owns the details. + WebAuthnRegistrationOptions: + type: object + description: >- + PublicKeyCredentialCreationOptionsJSON — pass to + `startRegistration()` (@simplewebauthn/browser) or decode for + `navigator.credentials.create()`. Resident keys are required; attestation + is `none`. + properties: + challenge: { type: string, description: base64url } + rp: + type: object + properties: + name: { type: string } + id: { type: string, description: The RP_ID the instance is configured with. } + user: + type: object + properties: + id: { type: string, description: base64url user handle } + name: { type: string } + displayName: { type: string } + pubKeyCredParams: { type: array, items: { type: object } } + authenticatorSelection: + type: object + properties: + residentKey: { type: string, const: required } + userVerification: { type: string, const: preferred } + attestation: { type: string, const: none } + additionalProperties: true + + WebAuthnRegistrationCredential: + type: object + description: >- + RegistrationResponseJSON — the value `startRegistration()` resolves with + (the created credential plus the authenticator's attestation response), + sent back verbatim. + properties: + id: { type: string, description: base64url credential id } + rawId: { type: string } + type: { type: string, const: public-key } + response: + type: object + properties: + clientDataJSON: { type: string, description: base64url } + attestationObject: { type: string, description: base64url } + transports: + type: array + items: { type: string } + description: e.g. ["internal", "hybrid"] — stored for later logins. + additionalProperties: true + additionalProperties: true + + WebAuthnAuthenticationOptions: + type: object + description: >- + PublicKeyCredentialRequestOptionsJSON — pass to `startAuthentication()`. + `allowCredentials` is empty: the browser offers the user's discoverable + passkeys itself. + properties: + challenge: { type: string, description: base64url } + rpId: { type: string } + userVerification: { type: string, const: preferred } + allowCredentials: { type: array, items: { type: object }, description: Always empty. } + additionalProperties: true + + WebAuthnAuthenticationCredential: + type: object + description: >- + AuthenticationResponseJSON — the value `startAuthentication()` resolves + with, sent back verbatim. + properties: + id: { type: string, description: base64url credential id } + rawId: { type: string } + type: { type: string, const: public-key } + response: + type: object + properties: + clientDataJSON: { type: string } + authenticatorData: { type: string } + signature: { type: string } + userHandle: { type: string } + additionalProperties: true + additionalProperties: true + + # ------------------------------------------------------------------ state sync + State: + type: object + description: | + The whole app state as one blob. The server treats it as opaque (it only + strips `active` on save and reads a few fields for reminders and the admin + dashboard) — the schema below is **representative, not enforced**, and grows + with the app. Conflict resolution is client-side via `_ts`. + properties: + _ts: + type: number + description: Client-set last-write timestamp (ms since epoch); drives sync. + unit: { type: string, enum: [kg, lb] } + lang: + type: string + description: UI language code ("en", "de", "pt", …) — also localizes pushes. + theme: { type: string } + accent: { type: string } + workouts: + type: array + description: Completed workouts, chronological. + items: { $ref: '#/components/schemas/Workout' } + routines: + type: array + items: { $ref: '#/components/schemas/Routine' } + week: + type: object + description: 'Weekly plan: weekday (0=Sunday … 6) → routine id.' + additionalProperties: { type: string } + dayPlan: + type: object + description: >- + Per-date overrides: ISO date → routine id, or "rest". Wins over `week`. + additionalProperties: { type: string } + bodyweight: + type: array + items: { $ref: '#/components/schemas/BodyweightEntry' } + customEx: + type: array + description: User-created exercises (id, name, muscles…). + items: { type: object, additionalProperties: true } + exWeights: + type: object + description: 'Per-exercise last/best weight memory: exercise id → {w, d}.' + additionalProperties: { type: object, additionalProperties: true } + reminder: + type: object + description: >- + Daily "workout planned today" push. The server reads this: at `time` + (HH:MM, in `tz`) it sends one push if a routine is planned and nothing + was logged yet. + properties: + 'on': { type: boolean } + time: { type: string, example: "08:00" } + tz: + oneOf: [{ type: string }, { type: 'null' }] + description: IANA zone ("Europe/Zurich"); the user's own clock. + restSec: { type: number, description: Default rest-timer seconds. } + effort: + oneOf: [{ type: string, enum: [none, rir, rpe] }, { type: 'null' }] + equipProfiles: { type: array, items: { type: object, additionalProperties: true } } + settings: + type: object + description: >- + Catch-all note: the remaining top-level keys (sound, keepAwake, gifSize, + targetW, autoBackup, …) are flat settings values like the ones above. + additionalProperties: true + additionalProperties: true + + Workout: + type: object + description: One completed workout (representative shape). + properties: + id: { type: string } + d: { type: string, format: date, description: 'ISO day, e.g. "2026-08-30".' } + start: { type: number, description: ms since epoch } + end: { type: number } + routineId: { type: string } + name: { type: string } + bw: { type: number, description: 'Body weight that day, in `unit`.' } + vol: { type: number, description: Total volume (Σ weight × reps). } + prs: + type: array + items: { type: string } + description: Exercise ids that hit a personal record. + entries: + type: array + items: + type: object + properties: + id: { type: string, description: Exercise id. } + topW: { oneOf: [{ type: number }, { type: 'null' }] } + sets: + type: array + items: + type: object + properties: + w: { type: number, description: Weight. } + r: { type: number, description: Reps. } + done: { type: boolean } + rir: { type: number } + rpe: { type: number } + additionalProperties: true + additionalProperties: true + additionalProperties: true + + Routine: + type: object + description: A workout template (representative shape). + properties: + id: { type: string } + name: { type: string } + emoji: { type: string } + ex: + type: array + description: Exercises with set/rep targets. + items: { type: object, additionalProperties: true } + additionalProperties: true + + BodyweightEntry: + type: object + properties: + d: { type: string, format: date } + w: { type: number, description: Weight in `unit`. } + t: { type: number, description: Timestamp (ms). } + additionalProperties: true + + # ------------------------------------------------------------------ push + PushSubscription: + type: object + description: The browser's PushSubscription.toJSON() — only these fields are stored. + required: [endpoint, keys] + properties: + endpoint: + type: string + format: uri + description: Public https:// push-service URL. + keys: + type: object + required: [p256dh, auth] + properties: + p256dh: { type: string } + auth: { type: string } + + # ------------------------------------------------------------------ admin + AdminUserRow: + type: object + properties: + id: { type: string } + name: { type: string } + created: { oneOf: [{ type: string }, { type: 'null' }], description: ISO timestamp. } + disabled: { type: boolean } + admin: { type: boolean } + invitedBy: + oneOf: [{ type: string }, { type: 'null' }] + description: The invite code this account was created with. + workouts: { type: integer, description: Total logged workouts. } + lastWorkout: + oneOf: [{ type: string }, { type: 'null' }] + description: ISO day of the newest workout. + lastSync: + oneOf: [{ type: number }, { type: 'null' }] + description: The state's `_ts` (ms). + hasPush: { type: boolean, description: Has at least one push subscription. } + live: + oneOf: [{ $ref: '#/components/schemas/Presence' }, { type: 'null' }] + description: Currently training, or null. + + Presence: + type: object + description: Live-workout snapshot (from /api/activity heartbeats). + properties: + name: { type: string } + exIdx: { type: integer } + exTotal: { type: integer } + setsDone: { type: integer } + setsTotal: { type: integer } + startedAt: { type: number } + updatedAt: { type: number } + + AdminUserDetail: + type: object + properties: + user: + type: object + properties: + id: { type: string } + name: { type: string } + created: { oneOf: [{ type: string }, { type: 'null' }] } + disabled: { type: boolean } + admin: { type: boolean } + invitedBy: { oneOf: [{ type: string }, { type: 'null' }] } + unit: { type: string, enum: [kg, lb] } + lastSync: { oneOf: [{ type: number }, { type: 'null' }] } + routines: + type: array + items: + type: object + properties: + id: { type: string } + name: { type: string } + emoji: { type: string } + count: { type: integer, description: Number of exercises. } + bodyweight: + type: array + items: { $ref: '#/components/schemas/BodyweightEntry' } + workouts: + type: array + description: Full history, newest first. + items: { $ref: '#/components/schemas/Workout' } + + Invite: + type: object + properties: + code: { type: string, description: 16 hex chars. } + note: { type: string } + createdBy: { type: string, description: Admin user id. } + created: { type: string, description: ISO timestamp. } + usedBy: + oneOf: [{ type: string }, { type: 'null' }] + description: User id that redeemed the code (absent/null while unused). + usedAt: { type: string } + usedByName: + oneOf: [{ type: string }, { type: 'null' }] + description: Resolved display name (only in GET /api/admin/invites). + additionalProperties: true + + AuditEvent: + type: object + description: One line of the audit log. + required: [id, ts, ev, ok] + properties: + id: + type: integer + description: Monotonic, never reset — a cleared log leaves a visible id gap. + ts: { type: number, description: ms since epoch. } + ev: + type: string + description: | + Event name. Currently one of: + `auth.register.ok|fail|denied`, `auth.login.ok|fail`, `auth.logout`, + `auth.logout.all`, `auth.pair.create|ok|fail`, + `admin.denied`, `admin.user.disable|enable`, + `admin.invite.create|revoke`, `admin.audit.clear`. + ok: { type: boolean, description: false for failed/denied attempts. } + uid: { type: string, description: Acting (or affected) user id. } + name: { type: string, description: Acting user's name (max 40 chars). } + tgt: { type: string, description: Target user id (admin actions). } + tname: { type: string, description: Target user's name. } + msg: + type: string + description: >- + Short detail — a failure reason code, or the invite code involved. + Rejected invite guesses and unknown credential ids are deliberately + never recorded. + ip: + type: string + description: >- + Only when AUDIT_IP is on — the full address (`full`) or just the + network, /24 or /48 (`net`). + example: + id: 421 + ts: 1756500000000 + ev: auth.login.ok + ok: true + uid: Zk3q9XyPbA2LmN0v + name: Ada diff --git a/api/package.json b/api/package.json index 8e7f7d6..75489be 100644 --- a/api/package.json +++ b/api/package.json @@ -1,6 +1,6 @@ { "name": "gym-api", - "version": "1.2.11", + "version": "1.2.14", "private": true, "type": "module", "main": "server.js", diff --git a/docs/API.md b/docs/API.md new file mode 100644 index 0000000..8c24916 --- /dev/null +++ b/docs/API.md @@ -0,0 +1,14 @@ +# HTTP API + +The complete openGym HTTP API — every route of `api/server.js`, with auth, +request/response schemas and the env-dependent behavior — is documented as a +hand-written OpenAPI 3.1 spec: + +- **Spec (source of truth):** [`api/openapi.yaml`](../api/openapi.yaml) +- **Browsable (Swagger UI):** https://opengym.duarte-santos.ch/api.html + +Lint it after changing routes: + +```sh +npx --yes @redocly/cli lint api/openapi.yaml +``` diff --git a/docs/DATA_IMPORTS.md b/docs/DATA_IMPORTS.md index f310df7..95fc1c8 100644 --- a/docs/DATA_IMPORTS.md +++ b/docs/DATA_IMPORTS.md @@ -36,7 +36,24 @@ These apps have been tested to work without adjustments to the column names: | **FitNotes 2 (iOS)** | Export workouts as CSV; also manual/auto iCloud backups | | **Strong** | Settings → Export Data | | **Gravl** | Profile → Export Data | -| **Hevy** | Profile → Settings → Export & Import Data (Workouts or Measurements) | +| **Hevy** | Profile → Settings → Export & Import Data (Workouts or Measurements), **or** Settings → Import from Hevy with a Pro API key | + +### Hevy API (direct) + +If you have **Hevy Pro**, you can skip the CSV and import straight from Hevy: + +1. Open [Hevy → Settings → Developer](https://hevy.com/settings?developer) and create an API key +2. In openGym: **Settings → Import from Hevy** +3. Paste the key (used only for that import — it is not saved) +4. Choose whether to bring **workouts**, **routines**, **weigh-ins**, or any mix, then confirm + +Both the API import and a detected **Hevy CSV** resolve exercises through the same generated +lookup (`frontend/src/lib/hevy-id-map.js`): template id for the API, English title for the CSV. +To regenerate (developers): set `HEVY_API_KEY` in the environment or `.env`, then run +`node scripts/build-hevy-id-map.mjs`. Unmapped lifts become your own exercises. Workout days +that already have data here are left alone; routines are always added as **new** plans +(nothing you already have is overwritten). Localized CSV titles (non-English) still fall back +to name matching. You can also create your own `CSV` file: diff --git a/docs/SELF_HOSTING.md b/docs/SELF_HOSTING.md index 39ee3d5..f67fb30 100644 --- a/docs/SELF_HOSTING.md +++ b/docs/SELF_HOSTING.md @@ -59,6 +59,8 @@ you're poking at the API directly: ## 3. Expose it over HTTPS on your own domain +> Want HTTPS **without** exposing anything to the internet — a valid certificate on a LAN-only address? See [SELF_HOSTING_HTTPS.md](./SELF_HOSTING_HTTPS.md) (wildcard cert via a DNS challenge, Caddy in front). + Put openGym behind something that terminates TLS for a hostname you control, then point it at the `web` container. Pick whichever you already run: diff --git a/docs/SELF_HOSTING_HTTPS.md b/docs/SELF_HOSTING_HTTPS.md new file mode 100644 index 0000000..af646dc --- /dev/null +++ b/docs/SELF_HOSTING_HTTPS.md @@ -0,0 +1,168 @@ +# Selfhosting with HTTPS + +This is a rather complex topic of its own, so it lives apart from the [SELF_HOSTING.md](./SELF_HOSTING.md) which focuses on how to run openGym. +This document takes a more general approach on how to achieve "https at home", it is not necessarily focused on openGym and applies to self hosting in general. + +When self-hosting it is often assumed that one needs to expose their services to the internet, this is not necessarily the case. +We can have https certificates without having to expose our precious hosts to the world. You can still do that if you want to access your applications from the internet without any VPN, but it's not necessary to take the risk. + +Since VPN is a beast of its own we'll only handle the certificates for now and grant https traffic to our local network hosts. + +This guide assumes that you are running a Linux host, everything else is not covered. + +## Components + +Given we have the following setup: +- a little server (e.g. a Raspberry Pi or mini PC) that runs our applications. +- a client (your PC, mobile, tablet, etc.) +- your router (the thing that provides internet access, wifi, etc.) + +```mermaid +graph TD + A@{ shape: cloud, label: "Internet"} + A <--> B[Router] + B <-->C[PC] + B <-->E[Mobile] + B <-->D[homelab] +``` + +### DNS + +In most cases the router also provides DNS for the local network and forwards all requests to the internet provider DNS. +(If you set up your own DNS server on your homelab, you probably know what you're doing.) + +The clients (PC, mobile phone, ...) will ask the local DNS for address translation and if the local DNS can't provide the target address, it will forward the request. +Usually the DNS servers out there translate DNS names to public IP addresses. +Since we do not own a public DNS server, we need a DNS provider that does this for us. +You probably heard of dyndns, duckdns and the like. This is what they do: provide a public DNS for us. + +In order to make the public DNS servers out there resolve the local IP address of our homelab we will set up the DNS provider. +It is strongly advised to check which DNS providers are supported by the tools you choose (we'll get to that later). + +### Let's encrypt! + +Let's encrypt is free to use, they provide certificates for everyone to make the internet safer. Read [here](https://letsencrypt.org/docs/why-all-https/) for more information. +They provide tools to automatically create certificates with a challenge to ensure your request is valid. +Therefore the tool needs to have access to the DNS provider to generate temporary TXT entries on the DNS entry. +If all is checked, the certificate authority of Let's Encrypt signs the certificate and it can be used. + +We will make use of a wildcard certificate, so we can serve all our services with one certificate. + +### proxy + +A proxy is optional but desirable. It acts as sort of a gateway to our service and can be a single entrypoint to multiple services on our homelab. +Let's say we have three services running on our instance. Since a TCP port can be used only once on a host we would have three ports that access our individual services. +It would not be very nice to have to remember all the ports when we address our services, so we let the proxy do it. + +Port 443 (https) can only be used once so we would let our proxy answer to that port. +We configure the proxy to forward requests to our individual services like so: +```mermaid +graph TD + A[proxy] + A <-->B[openGym :8080] + A <-->C[openGym-api :3000] + A <-->D[Nextcloud :8081] +``` +Now we have a nice URL and can forget about the ports. The proxy reads the URL request and forwards it to the target service/host. + +## How?! + +So how does it all come together? + +1. DNS provider translates name to the local IP of homelab (e.g.: `https://opengym.myhomelab.dedyn.io -> http://192.168.0.100:8080`) +1. the proxy listens to the local IP and provides HTTPS +1. Let's encrypt provides certificates with certbot + +### Tools + +- DNS provider: https://desec.io/ free and supports IPv6 and a certbot plugin +- let's encrypt client: certbot, officially supported by LE +- reverse proxy: caddy, lightweight and hackable. + +These are the tools I picked and know to work, your choice may be different and the setup is different as well. +But the main tasks are the same, so you can adapt to your choice. + +Additional info: +- homelab host: 192.168.0.100 + running services: + - opengym on port 8080 + - nextcloud on port 8081 + +1. register with desec.io and choose a name (we take `myhomelab` as example) + 1. create a new A record that points to your service, e.g.: `*.myhomelab.dedyn.io` (Wildcard!) - 192.168.0.100 (the ip of your homelab/mini PC/Raspberry Pi running the proxy) + 2. A wildcard certificate handles all certificates for that given host. e.g.: `opengym.myhomelab.dedyn.io` and `nextcloud.myhomelab.dedyn.io` can share the same certificates. + 3. create an API token for the certbot plugin. It only needs to write records inside your domain — leave `Can create domains` and `Can delete domains` **off**; a leaked token should not be able to take your domain apart. Note the token, it is only displayed once. +2. install certbot on your host + 1. most linux distributions provide the packages for this, e.g. debian: `apt install certbot python3-certbot-dns-desec` check the [docs](https://desec.readthedocs.io/en/latest/integrations/lets-encrypt.html) + 2. create a config file in `/etc/letsencrypt`: `desec.ini` containing `dns_desec_token = YOUR_TOKEN`, and `chmod 600` it + 3. run certbot to register + ```bash + certbot certonly \ + --authenticator dns-desec \ + --dns-desec-credentials /etc/letsencrypt/desec.ini \ + -m YOUR_EMAIL@HOST.TLD \ + --agree-tos \ + --no-eff-email \ + -d "*.myhomelab.dedyn.io" + ``` + 4. certbot also installs a systemd timer that renews the certificate automatically. Caddy only re-reads the files when told to, so add a deploy hook once: `certbot renew --deploy-hook "systemctl reload caddy"` (or drop that line into `/etc/letsencrypt/renewal-hooks/deploy/`). + 5. certbot writes `privkey.pem` readable by root only, while caddy runs as its own user. Either `chgrp caddy /etc/letsencrypt/live /etc/letsencrypt/archive && chmod g+rx` those directories (and `g+r` on the key), or copy the files in the deploy hook — otherwise caddy starts, but every TLS handshake fails. +3. install caddy + 1. most linux distributions provide the packages for this, e.g. debian: `apt install caddy` check the [docs](https://caddyserver.com/docs/install) + 2. create the caddy config, this is an example that should work: + ```jsonc + :443 { + header Content-Type text/html + respond < + caddy +

caddy works.

+ + HTML 200 + } + # define desec configuration + (desec) { + tls /etc/letsencrypt/live/myhomelab.dedyn.io/fullchain.pem /etc/letsencrypt/live/myhomelab.dedyn.io/privkey.pem { + protocols tls1.3 + } + } + # reverse proxy config for opengym + opengym.myhomelab.dedyn.io { + import desec + reverse_proxy http://192.168.0.100:8080 + } + # config for some other service + nextcloud.myhomelab.dedyn.io { + import desec + reverse_proxy http://192.168.0.100:8081 + } + ``` + +And that's about it. Now you should be able to access your opengym instance from your local network via https with working passkeys. +Be sure to update the openGym config accordingly (`RP_ID=opengym.myhomelab.dedyn.io`, `ORIGIN=https://opengym.myhomelab.dedyn.io` — see [SELF_HOSTING.md](./SELF_HOSTING.md#2-understand-the-passkey-requirement-important)). + +**If the name does not resolve on your phone:** many home routers (Fritz!Box, some ISP boxes) have *DNS rebind protection* and silently drop public names that resolve to a private IP. Add `myhomelab.dedyn.io` to the router's rebind exception list, or run your own resolver. + +usable URLs in this example: +- `https://opengym.myhomelab.dedyn.io -> http://192.168.0.100:8080` +- `https://nextcloud.myhomelab.dedyn.io -> http://192.168.0.100:8081` + +Note that the SSL/HTTPS termination is only at the proxy, the service does not have any certificates whatsoever. + + +### Alternatives +- DNS providers: [certbot provider list](https://certbot.eff.org/hosting_providers) so many options... +- Let's encrypt clients: see [here](https://letsencrypt.org/docs/client-options/) +- reverse proxy: nginx proxymanager, easier with web GUI + +## Conclusion + +We created a local-network-only access to our services with HTTPS using Let's encrypt, certbot and caddy. +If something does not work, please check the corresponding documentation: +- [desec](https://desec.readthedocs.io/en/latest/index.html) +- [caddy](https://caddyserver.com/docs/) +- [Let's encrypt](https://letsencrypt.org/docs/) +- [certbot](https://certbot.eff.org/) + +Reaching the services from outside your network (WireGuard plus a dynamic-DNS updater) is out of scope here. + diff --git a/frontend/android/app/build.gradle b/frontend/android/app/build.gradle index 27e2dbf..98868cd 100644 --- a/frontend/android/app/build.gradle +++ b/frontend/android/app/build.gradle @@ -7,8 +7,8 @@ android { applicationId "ch.duartesantos.opengym" minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion - versionCode 12 - versionName "1.2.11" + versionCode 15 + versionName "1.2.14" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" aaptOptions { // Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps. diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 47e7824..b4fd236 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "opengym-frontend", - "version": "1.2.11", + "version": "1.2.14", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "opengym-frontend", - "version": "1.2.11", + "version": "1.2.14", "license": "AGPL-3.0-or-later", "dependencies": { "@aparajita/capacitor-secure-storage": "^7.1.6", diff --git a/frontend/package.json b/frontend/package.json index 73039dd..bfd2ead 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "opengym-frontend", "private": true, - "version": "1.2.11", + "version": "1.2.14", "type": "module", "scripts": { "dev": "vite", diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index f4da1a6..dd5f41c 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -1,5 +1,5 @@ -import { useEffect } from 'react' -import { HashRouter, Routes, Route, Navigate, useNavigate, useLocation } from 'react-router-dom' +import { useEffect, useLayoutEffect, useRef } from 'react' +import { HashRouter, Routes, Route, Navigate, useNavigate, useLocation, useNavigationType } from 'react-router-dom' import { useStore } from './store/useStore.js' import { useUI } from './store/useUI.js' import { bindUI } from './components/ui.jsx' @@ -15,6 +15,7 @@ import ErrorBoundary from './components/ErrorBoundary.jsx' import Modals from './components/Modals.jsx' import Toast from './components/Toast.jsx' import RestTimer from './components/RestTimer.jsx' +import TimerFlash from './components/TimerFlash.jsx' import Login from './views/Login.jsx' import MobileOnboarding from './views/MobileOnboarding.jsx' import Home from './views/Home.jsx' @@ -30,6 +31,9 @@ import CoachChat from './views/CoachChat.jsx' import CoachIntake from './views/CoachIntake.jsx' import CoachSetup from './views/CoachSetup.jsx' +// last known scrollY per route, so back-navigation can put the page where it was +const scrollPositions = new Map() + bindUI(useUI) // lets the shared controls open sheets without importing the store at module scope // theme === 'system' follows the OS/browser preference instead of a fixed choice. @@ -48,6 +52,7 @@ function applyPrefs(theme, accent) { function Shell() { const navigate = useNavigate() const loc = useLocation() + const navType = useNavigationType() const { S, user, ready } = useStore() const isGuest = useStore(s => s.isGuest()) const needsMobileOnboarding = useStore(s => s.needsMobileOnboarding) @@ -66,8 +71,27 @@ function Shell() { }, [S.theme, S.accent]) useEffect(() => { setLang(S.lang || 'en') }, [S.lang]) useEffect(() => { document.documentElement.lang = S.lang || 'en' }, [langV, S.lang]) - // every tab/route change starts at the top of the page - useEffect(() => { window.scrollTo(0, 0) }, [loc.pathname]) + // Forward navigation starts at the top; going back lands where you left off. + // The position is recorded from scroll events rather than read at route + // change, because by then a shorter page may already have clamped it. + const pathRef = useRef(loc.pathname) + useEffect(() => { + const onScroll = () => { + // Modals pins the body while a sheet is open; scrollY is 0 then, not a position. + if (document.body.style.position === 'fixed') return + scrollPositions.set(pathRef.current, window.scrollY) + } + window.addEventListener('scroll', onScroll, { passive: true }) + return () => window.removeEventListener('scroll', onScroll) + }, []) + useLayoutEffect(() => { + pathRef.current = loc.pathname + if (navType !== 'POP') { window.scrollTo(0, 0); return } + const y = scrollPositions.get(loc.pathname) || 0 + // the restored view needs a layout pass before it is tall enough to scroll to y + const frame = window.requestAnimationFrame(() => window.scrollTo(0, y)) + return () => window.cancelAnimationFrame(frame) + }, [loc.pathname, navType]) // bound to the workout, not to the route — checking Stats mid-session keeps the screen on useWakeLock(!!S.active && S.keepAwake !== false) @@ -114,6 +138,7 @@ function Shell() { + ) } diff --git a/frontend/src/admin.css b/frontend/src/admin.css index a1359da..6c54cfe 100644 --- a/frontend/src/admin.css +++ b/frontend/src/admin.css @@ -1,5 +1,7 @@ /* Admin dashboard — operator-facing, English-only. Sits on top of the app's tokens; nothing - here is used outside views/Admin.jsx and views/AdminCoach.jsx. */ + here is used outside views/Admin.jsx and views/AdminCoach.jsx. The page is looked at maybe + twice a year, so every card says what it is for in a sentence and every state is a word, not + a colour to decode. */ .adm-intro{color:var(--label-2);font-size:14px;line-height:1.45;margin:-6px 0 16px} diff --git a/frontend/src/components/BodyMap.jsx b/frontend/src/components/BodyMap.jsx index 022f180..46d3f83 100644 --- a/frontend/src/components/BodyMap.jsx +++ b/frontend/src/components/BodyMap.jsx @@ -27,8 +27,13 @@ function useBodyPaths() { } function View({ view, levels, onMuscle, selected }) { + const activate = (event, slug) => { + if (event.key !== 'Enter' && event.key !== ' ') return + if (event.key === ' ') event.preventDefault() + onMuscle(slug) + } return ( - + {INERT.map(slug => (view.p[slug] || []).map((d, i) => ))} {MUSCLES.map(slug => (view.p[slug] || []).map((d, i) => @@ -37,6 +42,11 @@ function View({ view, levels, onMuscle, selected }) { className={'bm-m l' + (levels[slug] || 0) + (selected === slug ? ' sel' : '')} d={d} onClick={onMuscle ? () => onMuscle(slug) : undefined} + onKeyDown={onMuscle ? event => activate(event, slug) : undefined} + role={onMuscle ? 'button' : undefined} + tabIndex={onMuscle ? 0 : undefined} + aria-label={onMuscle ? t(MUSCLE_NAME[slug]) : undefined} + aria-pressed={onMuscle ? selected === slug : undefined} > {t(MUSCLE_NAME[slug])} ))} @@ -66,7 +76,7 @@ export default function BodyMap({ load = {}, thresholds, body = 'male', onMuscle } export function BodyMapLegend() { - return
+ return
{t('Less')}
{t('More')}
diff --git a/frontend/src/components/BodyMap.test.jsx b/frontend/src/components/BodyMap.test.jsx new file mode 100644 index 0000000..1cc2b43 --- /dev/null +++ b/frontend/src/components/BodyMap.test.jsx @@ -0,0 +1,62 @@ +// @vitest-environment happy-dom +import React, { act } from 'react' +import { createRoot } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import BodyMap, { BodyMapLegend } from './BodyMap.jsx' + +globalThis.IS_REACT_ACT_ENVIRONMENT = true + +let container +let root + +beforeEach(() => { + container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) +}) + +afterEach(() => { + act(() => root.unmount()) + container.remove() +}) + +async function renderMap(props = {}) { + await act(async () => { + root.render() + }) + await vi.waitFor(() => expect(container.querySelectorAll('.bm-v')).toHaveLength(2)) + return container.querySelector('.bm-m[aria-label="Chest"]') +} + +describe('BodyMap interaction semantics', () => { + it('keeps noninteractive maps as images without focusable muscle controls', async () => { + await renderMap() + expect(container.querySelectorAll('svg[role="img"]')).toHaveLength(2) + expect(container.querySelector('[role="button"]')).toBeNull() + }) + + it('exposes interactive muscles as translated pressed buttons inside groups', async () => { + const path = await renderMap({ selected: 'chest', onMuscle: vi.fn() }) + expect(container.querySelectorAll('svg[role="group"]')).toHaveLength(2) + expect(path).toBeTruthy() + expect(path.tabIndex).toBe(0) + expect(path.getAttribute('aria-pressed')).toBe('true') + }) + + it.each(['Enter', ' '])('activates a muscle once with %s', async key => { + const onMuscle = vi.fn() + const path = await renderMap({ onMuscle }) + const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true }) + + act(() => path.dispatchEvent(event)) + + expect(onMuscle).toHaveBeenCalledTimes(1) + expect(onMuscle).toHaveBeenCalledWith('chest') + expect(event.defaultPrevented).toBe(key === ' ') + }) + + it('labels the existing legend direction for assistive technology', () => { + act(() => root.render()) + expect(container.querySelector('.hm-legend').getAttribute('aria-label')).toBe('Less More') + }) +}) diff --git a/frontend/src/components/Heatmap.jsx b/frontend/src/components/Heatmap.jsx index 16f799d..03c6179 100644 --- a/frontend/src/components/Heatmap.jsx +++ b/frontend/src/components/Heatmap.jsx @@ -1,6 +1,7 @@ import { useEffect, useRef } from 'react' import { fmtVol, isoOf, todayISO, MONTHS } from '../lib/format.js' import { t } from '../lib/i18n.js' +import { tappable } from '../lib/use-sheet-keyboard.js' // GitHub-style activity heatmap, shaded by time trained per day. export default function Heatmap({ S, onDay }) { @@ -38,7 +39,7 @@ export default function Heatmap({ S, onDay }) { const cls = 'hm-c l' + level(a) + (key === todayISO() ? ' today' : '') + (day > today ? ' future' : '') cells.push(
onDay(key) : undefined} />) + {...tappable(a ? () => onDay(key) : undefined)} />) } cols.push(
{cells}
) } diff --git a/frontend/src/components/Media.jsx b/frontend/src/components/Media.jsx index cbada4f..61b4602 100644 --- a/frontend/src/components/Media.jsx +++ b/frontend/src/components/Media.jsx @@ -8,17 +8,20 @@ import Icon from './Icon.jsx' // Custom exercises have no media — the animation stays blank by design (issue #11). // `minimizable` (workout view) adds a persistent minimize/expand control so the animation stops // eating the screen; the chosen size is saved to settings and carries across exercises and -// future workouts (issue #12). +// future workouts (issue #12). Settings can also turn workout media off entirely +// (gifSize 'off') — then nothing renders here and the exercise card closes up, exactly like +// a custom exercise without media. Any other/legacy value behaves as 'full'. export default function Media({ ex, id, compact, minimizable }) { const [playing, setPlaying] = useState(true) const gifSize = useStore(s => s.S.gifSize) const update = useStore(s => s.update) if (!ex.gif) return null + if (minimizable && gifSize === 'off') return null const mini = minimizable && gifSize === 'mini' const toggleSize = e => { e.stopPropagation(); update(s => { s.gifSize = mini ? 'full' : 'mini' }) } return (
setPlaying(p => !p)}> - {exerciseNameFor(ex)} + {exerciseNameFor(ex)} {minimizable && (