Files
dsantillan 22654c61fc
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Podcasts: en español solamente, y se acuerdan de dónde ibas
Música tiene una sección **Podcasts**: programas por categoría —Salud y fitness,
Deporte, Comedia, Noticias, Historia, Crímenes reales, Ciencia, Tecnología,
Sociedad y cultura, Negocios, Ficción, Educación, Música, Ocio— que suenan mientras
entrenás y siguen donde los dejaste. Sin dependencias nuevas y sin clave de API: el
directorio de Apple es público.

**En español se comprueba, no se supone.** La tienda dice dónde se *vende* un
podcast, no en qué idioma está —en el ranking español de comedia hay uno en catalán
y en el argentino uno en inglés—, así que se lee el `<language>` del feed de cada
programa (los primeros 64 KB, con una petición `Range`: el idioma está en las
primeras líneas) y se descarta lo que no sea español. Un feed sin etiqueta se queda:
feeds genuinamente españoles la omiten, y tirarlos por una omisión sería sacar
podcasts buenos de la lista. La respuesta cuenta cuántos quedaron afuera y por qué
(`skipped`), así que una lista corta nunca es un misterio, y abrir un programa en
otro idioma se contesta con `spanish:false` en vez de con una lista vacía.

Es la otra mitad de la radio y es lo contrario en todo lo que le importa al
reproductor: un podcast es un **archivo** —tiene principio, final y un minuto en el
que ibas—. Por eso hay un módulo de reglas puras (`lib/podcast-view.js`: dónde
retomar, qué cuenta como escuchado, cuál sigue, cuántas posiciones se guardan) y
por eso `lib/radio-player.js` pasa a ser `lib/player.js`: **un solo elemento de
audio** para las dos cosas, que es lo que impide que una emisora y un episodio suenen
a la vez. La barra crece línea de progreso, −15 s, +30 s, siguiente episodio y reloj;
la posición se guarda por perfil (con tope de 200, lo más nuevo primero) en pausa, al
parar, al terminar y cuando la app se va al fondo, porque con la pantalla bloqueada
iOS suspende los temporizadores y un guardado sólo desde el tick perdería lo
escuchado con el teléfono guardado. Media Session muestra episodio, programa y
progreso en la pantalla bloqueada.

Nada se descarga y nada pasa por el servidor: el episodio llega como la URL del
`enclosure` y el audio va de quien lo publica al teléfono. Acá no hay lista blanca
posible —un feed vive en cualquier host—, así que la puerta es **https, host real y
nunca una dirección privada**, comprobada en la URL y en dónde terminó el pedido, con
el cuerpo leído a tope y la conexión cortada al llegar: este contenedor vive adentro
de una casa.

Verificado con datos reales: 20 programas en español por categoría (idiomas es, es-ES,
es-mx), un feed de 40 episodios parseado, un feed en inglés contestado como
`spanish:false` y la dirección de metadatos rechazada con 400 sin hacer el pedido.

Fuera de los podcasts: la página de la API ocultaba `health` y `music` enteras —el
generador sólo dibuja las secciones de su tabla de etiquetas—, así que ahora están,
con radio y podcasts incluidas.
2026-09-23 21:11:20 -04:00

189 lines
12 KiB
Markdown

# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## What this is
KuentaGYM is a self-hosted gym & body-weight tracker PWA. Two containers (`api` + `web`) plus a
`./data` folder the user owns — no third-party account, no telemetry. Passkey (WebAuthn) login,
installable as a home-screen app, optional Capacitor shells for standalone Android/iOS builds.
License: AGPL-3.0-or-later.
It is a rebranded fork of [openGym](https://gitlab.com/DuarteSantos8/opengym) by Duarte Santos: the
same code under the same AGPL-3.0-or-later, with this fork's name on it (see NOTICE.md). The fork's
own repository — issues, pull requests, Actions — is the Gitea instance at
<https://git.dploy.lol/dsantillan/kuentagym>, and the live instance runs at <https://gym.dploy.lol>.
## Project layout
```
frontend/ React 19 + Vite app (src/views, src/components, src/store, src/lib). Builds to static files.
android/ + ios/ are the Capacitor shells for the standalone mobile app (docs/MOBILE.md).
api/ backend — server.js (Node, no framework), deps: @simplewebauthn/server, web-push.
web/ multi-stage Dockerfile (builds frontend → nginx) + nginx.conf.template (serves app, proxies /api).
mcp/ optional MCP server — read-only stdio bridge exposing a user's workouts/1RM/muscle
balance to LLM clients (Claude Desktop, Cursor…). Not part of the Docker build; only
runs when an LLM client spawns it.
media/ exercise img/gif, gitignored, fetched at runtime by the `media` compose service.
website/ static marketing site (plain HTML/CSS/JS) — not deployed for this fork; built by hand
when someone wants it (node scripts/build-api-docs.mjs fills in api.html).
docs/ SELF_HOSTING.md, MOBILE.md, AI_COACH.md, HEALTH.md (Apple Health ingest),
RADIO.md (live stations), PODCASTS.md (Spanish-language episodes).
```
## Commands
```bash
# Local stack (api + web + media, prebuilt or built from source)
cp .env.example .env
docker compose up -d --build
# Frontend dev server (hot reload), proxies /api to :3000
cd frontend && npm install && npm run dev
# Frontend tests (training logic: progression, 1RM, session read-back)
cd frontend && npm test # vitest run
cd frontend && npm run test:watch
npx vitest run src/lib/progression.test.js # single file
npx vitest run -t "some test name" # single test by name
# MCP server tests
cd mcp && npm test
# Production build
cd frontend && npm run build
cd frontend && npm run build:mobile # + cap sync, points media at the CDN dataset
```
There is no linter/formatter configured (no ESLint/Prettier config in the repo) and no
TypeScript — match the existing style by hand.
The CI gate is Gitea Actions on `git.dploy.lol`, configured in `.gitea/workflows/`: `test.yml` runs
the `frontend/` suite on Node 22 — the same version as `web/Dockerfile` / `api/Dockerfile`
(`node:22-alpine`) — and `docker-publish.yml` builds and pushes both images to the Gitea registry
on `main` and on a published release. The `mcp/` and `api/` suites are not run by CI, so run them
yourself (`cd mcp && npm test`, `cd api && npm test`). No job packages the Android APK and none
deploys the website. `.gitlab-ci.yml`, `.gitlab/` and `.github/workflows/` are dormant copies of
upstream's pipeline — no host runs them, they are not this fork's gate, and a change that only they
would catch is a change nothing checks here.
## Architecture
### Frontend (`frontend/src`)
- **`store/useStore.js`** — single Zustand store holding the entire client-side app state (`S`),
persisted to `localStorage` (`gym_state_v1`) and debounce-pushed to the server when signed in
(`pushState`, see `lib/api.js`). On the Capacitor mobile build it's also mirrored to a file via
`lib/mobile.js` (`nativeSave`), since WebView storage can be evicted. `store/useUI.js` holds
ephemeral UI state (modals, active sheet, etc.) separately from persisted data.
- **`lib/`** — pure, framework-free helpers, each paired with a same-directory `*.test.js`. This
is where the domain logic lives, most importantly:
- `progression.js` — the progression-rule engine (linear, Greyskull LP, double progression,
time-based). Rules implement a shared policy interface; adding a new one plugs in here.
- `onerm.js` — estimated 1RM from logged sets.
- `finish-workout.js` — reduces a completed session back into state (weights advance, PRs, etc).
- `recovery.js` / `recovery-view.js` — fatigue/muscle-recovery model.
- `workout-model.js`, `supersetFlow.js` — in-session workout state machine, incl. supersets.
- `exercises.js` / `exercises-data.js` — the exercise library (1,324 built-ins + user-defined).
- `vitals-view.js` — the Apple Health metric catalogue and card model (labels, units, which
aggregate a card shows, the hour rows and day history behind a card, workout rows). The server
stores numbers; this decides how they read.
- `music.js` — reading and validating the Apple Music share links a profile keeps. Apple has no
API for somebody else's public playlists, so a playlist here is a link, not an integration.
- `player.js` — the single `<audio>` element and Media Session, for both the radio and the
podcasts, held **outside React** on purpose: an element owned by a component unmounts with it,
which is how a player stops when somebody changes screens. `play()` is called synchronously from
the tap because iOS only allows audio to start inside a gesture, and one element is what keeps a
station and an episode from ever playing at once. See `docs/RADIO.md` and `docs/PODCASTS.md`
before touching any of it.
- `podcast-view.js` — where to resume, what counts as heard, what comes next, and how many
positions to keep. Pure, because "resumed into the last twenty seconds" and "marked heard after
five minutes" are bugs nobody reports — they just stop using the feature.
- `api.js` — the only place that talks to the backend (`fetch` wrapper, session cookie flows).
- CONTRIBUTING.md is explicit: **anything that decides what you lift next, or reads a logged
session back, is a pure helper here with a unit test beside it** — not verifiable by
clicking, and the progression engine has already had two bugs that only a test caught.
- **`views/`** — one file per screen (Home, Workout, Plan, Library, Stats, History, Health,
Settings, Admin, Login, RoutineEdit), routed by `react-router-dom` from `App.jsx`.
- **`components/`** — shared UI (charts, modals, timers); `instr/` holds per-language exercise
instruction text; `locales/` is the i18n string catalogue (`lib/i18n.js` / `i18n-core.js`).
- **The aura and the splash** — `index.html` carries three decorative layers (the "Diamond Weave"
gradient) that blend against the `body` background, so the base colour lives on `body` in
`index.css` and `#app` sits above them at `z-index: 1`. The launch photo is derived from
`assets/splash.jpg` by `frontend/scripts/build-app-icons.mjs` (which also writes every icon).
- Mobile: `@capacitor/*` wraps the same web build into native shells under `frontend/android` and
`frontend/ios` (see `docs/MOBILE.md`); `mobile.js` in `lib/` gates native-only behavior (file
persistence, local notifications, wake lock) behind a `MOBILE` flag.
### API (`api/server.js`)
Single file, no framework, plain `node:http`. Requests are dispatched through a `routes` object
keyed by `'METHOD /path'` (e.g. `routes['GET /api/health']`) matched against `req.method + ' ' +
url.pathname` — add a new endpoint by adding a key here. State is three flat JSON files under
`DATA_DIR` (`db.json`: users/credentials/subscriptions/invites; `state-<uid>.json`: per-user
workout data; `vitals-<uid>.json`: per-user Apple Health, written only by `POST /api/vitals/ingest`
— see `docs/HEALTH.md`), written with a write-temp-then-rename atomic pattern (`atomicWrite`). Auth is
WebAuthn passkeys (`@simplewebauthn/server`) plus a signed session cookie (HMAC'd with a
`DATA_DIR/secret` generated on first boot) — no JWT/session-store dependency. A second, write-only
credential exists for the health ingest (`user.healthKey`, minted by `POST /api/vitals/key`, given
to an iOS automation), deliberately not the session token. Optional pieces
gated by env vars: `ADMIN_UIDS` (admin dashboard), `INVITE_ONLY` (signup needs a code),
`ALLOW_GUEST` (client-only guest mode never hits the server at all), plus a rotating
`data/audit.log` (JSONL) for sign-in/admin events. Web Push (`web-push`, VAPID keys
auto-generated into `data/vapid.json`) drives rest-timer-over and day-reminder notifications.
`vitals.js`, `music.js`, `radio.js` and `podcasts.js` sit beside `server.js` as the modules with real
logic on the API side: HAE parsing, the idempotent merge (the reason a 5-minute automation does not
double a day of steps) and retention in the first; reading what a public Apple Music page says about
itself, behind a host allowlist, in the second; the live-station directory — SomaFM, Radio Paradise
and radio-browser — in the third; and Apple's podcast directory plus a tolerant RSS reader in the
fourth, where the two rules that matter are **Spanish only** (checked in each feed's own
`<language>`, not assumed from the storefront) and **no private address is ever fetched** (a feed can
live anywhere, so there is no allowlist to hide behind: https, a real host, and a check of where the
request ended up as well as where it was pointed). All of them hold the same line about audio:
**nothing is proxied**. The api hands out a resolved stream URL or the publisher's own episode URL,
and the phone talks to the station or the publisher directly. `server.js` owns the
sockets; those files own the parsing, which is why they are testable without a phone or a network.
All of them are listed in the Dockerfile's `COPY` — an import of a file that is not copied there is a
container that boots into ERR_MODULE_NOT_FOUND.
### MCP server (`mcp/src`)
Read-only stdio MCP bridge (`@modelcontextprotocol/sdk`) that lets an LLM client read a single
user's routines/workouts/body-weight/1RM/muscle-balance directly from the same `DATA_DIR` the API
writes to — no network call, no extra container. `state.js` loads/derives the data, `tools.js`
defines the exposed MCP tools (zod-validated schemas), `labels.js` maps internal keys to
human-readable labels, `index.js` wires it together. See `mcp/README.md` for the client-config
side (Claude Desktop / Cursor).
### Passkeys and self-hosting constraints
WebAuthn passkeys are bound to an exact hostname (`RP_ID`) and require HTTPS (localhost excepted)
— this shapes a lot of the API and Settings code (`RP_ID`/`ORIGIN` env vars, guest-mode fallback
when neither is available). Read `docs/SELF_HOSTING.md` before touching auth, session, or
notification code; it documents the exact env-var contract (`RP_ID`, `ORIGIN`, `PORT`,
`WEB_PORT`, `NGINX_PORT`, `BACKEND`, `SESSION_DAYS`, `ADMIN_UIDS`, `INVITE_ONLY`, `ALLOW_GUEST`,
`AUDIT_*`, `VAPID_SUBJECT`) that real deployments depend on.
### Docker / deploy
`docker-compose.yml` has three services: `media` (one-shot exercise-asset downloader, gitignored
output), `api`, `web` (multi-stage build of `frontend/` served by nginx, which also proxies
`/api` → `api` and serves the shared media volume — single origin, required for passkeys).
`web/nginx.conf.template` is rendered from env vars at container start (`NGINX_PORT`, `BACKEND`,
`PORT`), so host/port remapping works against prebuilt images without a rebuild.
Images are built by `.gitea/workflows/docker-publish.yml` and pushed to the Gitea registry as
`git.dploy.lol/dsantillan/kuentagym-api` and `git.dploy.lol/dsantillan/kuentagym-web`. The live
instance at `gym.dploy.lol` is deployed with Dokploy, which runs this compose file and **pulls**
those images — a change that is not committed, built by that workflow and pushed is not on the live
instance.
## Guidelines from CONTRIBUTING.md worth knowing before changing code
- **Dependency-light is a hard constraint, not a preference.** Frontend: React + Router + Zustand
and nothing else. `api/`: two dependencies total. New dependencies are a hard sell either side.
- Don't commit `media/` or `data/` (gitignored).
- Training-logic changes (progression, 1RM, session read-back) need a unit test in `src/lib`
beside the code, not just manual clicking-through.