Compare commits

..
263 Commits
Author SHA1 Message Date
Duarte Santos 8104539932 css: drop the minifier claim from the tab-bar fix — it is not true
The tab-bar commit gave two causes for the see-through bar. The first is real
and is what users reported: 72% opacity. The second was invented — that the CSS
minifier collapses a backdrop-filter / -webkit-backdrop-filter pair down to
whichever is written last, so the standard property never shipped and Firefox
got alpha without blur.

It does not. This project builds CSS with esbuild's minifier, which treats the
two as what they are, different property names, and keeps both in either order:
main's stylesheet minifies to five unprefixed and five prefixed, and so does
this branch's. Nothing was ever dropped, and there was no Firefox-only bug.

So the claim comes out of the code comment, out of the CHANGELOG, and out of
the release announcement, where it would have gone to the whole Discord as a
confident technical explanation for something that never happened.

What stays is the part that is true and is the actual fix: 94% opacity, less
blur — which is a genuine win on Android, where a blur behind a fixed element
is recomposited every scroll frame — and the @supports fallback to fully opaque
where backdrop-filter really is unavailable. The prefixed-first ordering stays
too, since that is the right order for a prefixed/standard pair regardless: the
standard name should be the one that wins the cascade. Only the reason given
for it changes.

(The message on 46eaefd still carries the original claim; it is left alone
rather than rewriting a branch mid-review.)
2026-08-25 20:54:14 +02:00
Duarte Santos b28115a8f9 workout: give back the rest a re-checked set used to swallow
The other half of issue #3. "Breaks sometimes not shown after finished set
(first / last)" — the last-set half was the quiet-finish rule, already fixed.
This is the first-set half.

Completing a set only counts as progress when it goes beyond the most sets this
exercise has had done at once, so that unchecking and re-checking finished work
does not replay navigation or reopen sheets. Correct, but it returned before
anything could time a rest: uncheck a set to fix the reps, check it again, and
nothing starts. If the original rest had already run out, you get no break at
all — which is exactly what was reported, and why it reads as "sometimes".

A re-check now fills that gap and only that gap: it starts a rest when none is
running, and never touches one that is still counting down, because a running
timer belongs to the set you finished most recently. Navigation and sheets stay
gated exactly as before.
2026-08-25 20:51:18 +02:00
Duarte Santos 5ff6b7d0a8 history: never seed a session from last time's warm-up rows
Found reviewing this release, and it is this release that makes it bite.

lastEntryFor returns every set that was `done`, warm-ups included, and four
callers then treat position 0 as "your first work set": buildSets seeds the
next session's rows from it, freestyleConfig sizes the config from its length,
and two views print it as "Last time".

Until now that was latent — warm-ups only existed if you pressed "Add warm-up
set", and that button was itself broken in a way that hid this: it handed you a
row at the full working weight, so seeding from it produced the right number by
accident. Fixing the ramp to a real 50% / 75%, and letting a routine plan
warm-ups into every session, turns the latent bug live: work set 1 gets seeded
at half your working weight, then next session at half of that. Your working
weight walks down on its own. A 3x5 also comes back as a 5-set exercise,
because two ramp rows are counted as sets you did.

So lastEntryFor now answers what every caller is actually asking — what you
lifted, not what you warmed up with. Warm-ups were already out of volume,
records and progression; this is the same rule one level up. An entry whose
only completed sets were warm-ups is no longer history at all, and the search
falls through to the session before it.

The regression test covers both seeding paths, planned and freestyle, since
freestyle takes the weight from last time directly and would drift fastest.
2026-08-25 20:49:24 +02:00
Duarte Santos bbf46e2aa2 test: mount the note sheet for real
The note sheet was checked structurally — imports resolve, symbols exist — but
nothing ever rendered it, so a bad hook order or a wrong store path would have
reached a phone before it reached a test. This drives it through the real sheet
stack: both textareas, the pin (disabled while the note is empty, since pinning
nothing means nothing), and a save that has to land in two different places —
today's note on the entry, the standing note on S.exNotes.

The third case is the one that would have bitten: clearing the note has to drop
the pin with it, or a stale pin resurfaces a note that no longer exists.
2026-08-25 20:19:01 +02:00
Duarte Santos 69cefca19e release: v1.2.10
Version bumped in both package.json files, the lockfile's self-reference and
the Android build (versionCode 10 -> 11, so the APK installs over the last
one). Changelog covers everything since v1.2.9 in one entry, per the
project's versioning rule.
2026-08-25 20:02:28 +02:00
Duarte Santos e1c14f7ac0 i18n: translate the new strings into all 12 locales
18 strings from this release, plus the rest-pause explainer that arrived
untranslated with !20. Terminology follows each pack's existing entries
(Wdh. / rip. / powt. / повт., and the "Add warm-up set" wording already there).

pt-BR overrides 8 of them rather than inheriting: the pt-PT versions use
tu-forms and «guillemets» (tuas, podes, treinares, teres), which is exactly
what the locale's own guard test is there to catch. Inheritance fingerprint
re-baselined; the remaining 10 read the same in both variants.
2026-08-25 20:00:19 +02:00
Duarte Santos 6ea7526bff api + docs: say what went wrong when RP_ID or ORIGIN does not match
@simplewebauthn reports a mismatch as "Unexpected RP ID hash", which tells a
self-hoster nothing about their own .env — and this is the most common support
question in #install-help, where charliebelt is currently stuck behind a
Cloudflare Tunnel with values that look right. The error now names both
configured values back and points at the docs. Neither is a secret: one is the
address bar, the other its hostname.

Extracted as api/verify-error.js so it can be tested without booting a server
that opens files and a port, following push-messages.js.

SELF_HOSTING.md gets the diagnosis in order: read what the server logged on
startup (it prints rpID and origin, and `docker compose restart` does not
re-read .env), then the exact shape of each value as a table, then the
reverse-proxy case, then www., then that changing the hostname invalidates
existing passkeys. Plus the thing adam934912 called a blocker: on a LAN
without certificates there is nothing to configure that makes passkeys work.
2026-08-25 20:00:10 +02:00
Duarte Santos 37d6cf895a notes and planned warm-ups
Three kinds of note, because they have three different lifetimes and users
asked for all three:

  · a session note on an exercise — what happened today, stored on the workout
    entry. It carries a PIN, and that is the whole design: only the person
    writing knows whether "shoulder twinged" is a diary line or "go narrower"
    is a message to their next self. A pinned note surfaces again the next time
    that exercise comes up, where the "Last time" line already is; an unpinned
    one stays in that day's history. This is deliberately not a global setting:
    the answer differs per note, so a single switch would need constant
    flipping, while at the moment of writing it is obvious.
  · a standing note on the exercise itself (S.exNotes) — seat height, pin
    position, a form cue. True every session, shown every session. This is
    elchavalico's request, with ten messages of agreement behind it.
  · a whole-session note on the workout, editable from its history entry, where
    it is easier to say how a session went once you can see what you did.

A routine's own `note` (!14) stays where it is: it belongs to the plan, not to
the day or to the movement.

Planned warm-ups: `warmupSets` on an exercise config, stacked by buildSets
using the same ramp as the in-session button, so the session starts with them
already there instead of you adding them by hand every time. Written only when
non-zero, so an existing plan keeps its exact shape and reads back as 0. They
travel with a shared plan, and stay out of volume, records and progression via
the phase flag that already existed.
2026-08-25 20:00:10 +02:00
Duarte Santos 62b69ea88d home + stats: stop asking for a workout that is done, plot bodyweight lifts
Home's week strip already knew today was finished — its dot goes 'done' from
S.workouts — but the row underneath only ever asked `routine`, so a logged day
kept showing the routine name behind a green Start tag and read as still
outstanding (issue #4). It now reports the session instead. Tapping still
starts another one; it just stops urging.

Stats dropped every point whose value was 0, and a bodyweight pull-up has no
weight, so "Exercise progress" read "No data yet" for exercises with a full
history behind them (issue #5). When nothing in an exercise's history was ever
loaded, its progress IS the rep count, so that is what gets plotted, labelled
in reps. Add a weighted set later and it switches back to weight on its own —
which is also the honest reading, because that is when load became the thing
improving. Same fallback in currentOf, or the picker label went blank and the
exercise sorted to the bottom as if it had no history at all.
2026-08-25 19:59:50 +02:00
Duarte Santos 46eaefd2c7 css: make the tab bar opaque, and actually ship backdrop-filter to Firefox
Reported as "the navigation bar is half transparent … the information can be
harder to see as it is mixed with the background". Two separate causes.

The bar was 72% opaque. Even with the blur working that is too little to read
labels against a scrolling page, and nobody needs to read what is behind a
navigation bar. Now 94% in both themes, with the blur down from 24px to 10px:
this is a position:fixed element, so the WebView recomposites the blurred
region on every scroll frame, which is the most expensive thing on an Android
screen. Same blur reduction on the rest timer, which is on screen for a whole
session.

The second cause is worse and was invisible from the source: the CSS minifier
dedupes a `backdrop-filter` / `-webkit-backdrop-filter` pair down to whichever
is written LAST, so the standard property was being dropped from the build
entirely and only the -webkit- one shipped. Firefox understands only the
unprefixed name, so it had no blur at all — just the alpha, which is exactly
the reported symptom. All five pairs now put the prefixed line first, with a
comment so nobody tidies the order back.

Adds an @supports fallback to fully opaque where backdrop-filter is genuinely
unavailable (old Android WebViews, reduce-transparency settings), and drops
.ss-card's padding on narrow screens — a superset pays the page gutter twice
and squeezed the reps field, which socialscientist93 diagnosed exactly.
2026-08-25 19:59:50 +02:00
Duarte Santos 0863aa73fb workout: fix the warm-up weight and the missing rest after a final set
Two session bugs that users reported separately and that both sat in the
"what happens when a set ends" path.

insertWarmupRow read rows[at - 1] to find what to ramp from. For the FIRST
warm-up `at` is 0, so that is rows[-1] — undefined — and the `||` fallback
took the LAST row instead: the heaviest work set. "Add warm-up set" handed
you a warm-up at your full working weight, every time, and you corrected it
by hand. It now ramps from the first work row, each added row closing half
the remaining gap (50% / 75% / 87.5%), rounded DOWN to the exercise's own
loading step — a warm-up a notch light costs nothing, one a notch heavy is a
set you have to strip plates off. The step is passed in by the caller so
history.js keeps no dependency on progression.js, which already imports it.

Rest timers stopped at the end of an exercise: the singleton path called
stopRest() and then skipped startRest(), commented as "final sets finish
quietly". But another exercise follows that set, and you rest before it too —
a two-set exercise timed one rest instead of two (issue #3), and the rest
never carried across the gap. Supersets already had the right rule, so the
condition is now shared as restAfterSet(): rest after every completed set
except the last set of the last exercise, which is where zkssyth landed
independently in Discord.
2026-08-25 19:59:31 +02:00
Duarte Santos a04a5cab52 Merge remote-tracking branch 'mrq/23' into integrate3 2026-08-25 19:29:54 +02:00
Manuel 4a614eb8ca Show calendar year in multi-year chart tooltips 2026-08-25 16:43:06 +00:00
Ameer Khan e737954e37 Import: resolve Hevy exercise names instead of inventing customs
Hevy writes the equipment in parentheses and says "bicep"/"chest fly"
where the catalogue says "biceps"/"fly", so the word-bag matcher landed
one word off. A real 34-session export arrived with 27 custom exercises
covering a third of its sets.

Three separate causes:

- SYN rewrote 'machine' -> 'lever' before 'smith machine' -> 'smith'
  could ever fire, so every Smith-machine name became "smith lever ..."
  and matched nothing in the catalogue. The two rules are order
  dependent; 'smith machine' now runs first.
- The alias table had no entry for Hevy's vocabulary. Added the names
  from a real export, mapped by hand to catalogue ids.
- Hevy exports no category column, so every invented exercise took the
  'upper legs' default and a third of an imported history was
  attributed to the legs in the muscle map. With no category to read,
  the body part now comes off the name instead.

The same export now creates 2 custom exercises instead of 27. The two
that remain, box jump and wall ball, are genuinely not in a 1,324-entry
strength catalogue, and guessing would file them under the wrong lift.

import-match.test.js covers the new aliases, the SYN ordering and the
body-part inference.
2026-08-25 15:36:25 +00:00
Duarte Santos 7d2460c2c2 Merge merge request !20 (intensifiers, pairing, theme, security hardening)
Takes the nine commits as submitted, with three adjustments:

- remote.test.js ran in the node environment while remote.js pulls in
  api.js, which reads navigator.userAgent at module scope — the file failed
  to import. Same @vitest-environment happy-dom pragma the api tests use.
- Drops skills-lock.json. It pins a personal Claude Code skill chain to
  third-party GitHub repos by hash; that is contributor tooling, not a
  project artefact, and this project's GitHub access is gone. CLAUDE.md
  itself is kept — it is an accurate description of the repo.
- Corrects two stale claims in that CLAUDE.md: the website deploys from
  .gitlab-ci.yml, not GitHub Pages, and the CI gate is GitLab, not Gitea
  Actions with a dormant GitHub copy.

pt-BR: 23 of the 44 new pt strings are European (ficheiro, telemóvel,
Definições, «guillemets», tu-forms), so they get Brazilian overrides
rather than being inherited; fingerprint re-baselined.
2026-08-25 14:28:10 +02:00
Duarte Santos 5762096a5f Merge merge request !2 (exercise catalogue and muscle metadata)
Keeps the ExRx-informed primary/secondary metadata for 223 catalogue
entries and the muscle-group UI, with two fixes to the branch:

- muscles.js dropped metadataOf, the muscleSnapshot fallback. A custom
  exercise deleted from the catalogue survives in history only as that
  snapshot, so without it those sessions silently stopped counting toward
  the body map and Stats — loadOfWorkouts returned {} where main returned
  {chest: 1}. Restored and widened to the new primaries/secondaries fields.
- It also replaced the shared isWarmupRow import with a local copy that
  only matches the exact string 'warmup'. phaseForSet normalises 'warm-up',
  'warm_up', casing and whitespace, so warm-up rows written in any other
  spelling would have counted as work here while counting as warm-ups
  everywhere else. Restored the import.

Both are covered by new tests. Locale conflicts resolved additively; the
three new muscle-group strings read the same in pt-BR, so they stay
inherited and the inheritance fingerprint is re-baselined.
2026-08-25 14:22:40 +02:00
Duarte Santos 76973edad1 Merge merge request !16 (pt-BR exercise names and instructions)
Resolves against !13 and !1: the picker and library keep the multi-token
search and the equipment-profile filter, and matchExercise now builds its
haystack from exerciseNameSearchText, so a pt-BR profile finds an exercise
by the name it actually sees as well as by the English one. The 'chosen'
sort takes !16's locale-aware localeCompare. Adds regression tests for
localized search and for cache invalidation on a language switch.
2026-08-25 14:13:03 +02:00
Duarte Santos f37448aece pt-BR: override the equipment-profile strings instead of inheriting them
The new equipment strings landed in pt.js only, so pt-BR inherited European
wording — «guillemets», 'A mostrar', 'Ginásio', 'tens' — and the locale's
own guard test caught it. Adds Brazilian overrides (você, 'Academia',
'Excluir perfil?', curly double quotes) and re-baselines the inheritance
fingerprint: the one newly inherited entry is !14's note placeholder, which
reads the same in both variants ('anilha' is current usage in Brazil too).
2026-08-25 14:10:39 +02:00
Duarte Santos 7f0afae228 Merge remote-tracking branch 'mrq/15' into integrate2 2026-08-25 14:08:36 +02:00
Duarte Santos 6eabeda89b equipment profiles: translate the new strings into all 11 locales
The merge request added 18 user-facing strings and no locale entries, so
every non-English profile would have rendered the equipment card, picker
banner and routine warning in English. Terminology follows each pack's
existing 'Equipment' key (Geräte / Equipo / Attrezzi / Sprzęt / Инвентарь …).

Also replaces the literal \u2019 escape in the Settings footer with the
character itself — the locale key has to match the string as it is written.
2026-08-25 14:06:40 +02:00
Duarte Santos 5a1f1d673f Merge merge request !1 (equipment profiles) 2026-08-25 14:03:32 +02:00
Duarte Santos f5b215f109 import: fix the gravl column aliases so they can actually match
mapHeader normalises the header before comparing ('Weight (kg)' -> 'weight
kg') but matches the alias list raw, so an alias written with parentheses
never matches. Three of the added ones were dead entries whose normalised
twin was already in the table; 'set duration (sec)' had no twin, so gravl's
per-set duration was dropped and its cardio rows skipped entirely.

Also moves that column from "time" to "seconds", which is what it is:
toMinutes() would have read gravl's 22 seconds as 22 minutes.

Adds the gravl sample from the merge request as a regression test.
2026-08-25 14:01:45 +02:00
Duarte Santos 880a9c184e Merge remote-tracking branch 'mrq/21' into integrate2 2026-08-25 14:00:13 +02:00
Duarte Santos 669756a6dd exercise search: cache the normalised haystack per exercise
matchExercise rebuilt an NFD-normalised corpus for all ~1300 catalogue
entries on every keystroke (~8ms desktop, several times that on a phone).
Cache it in a WeakMap keyed by the i18n version so a language switch
rebuilds the translated terms, and custom exercises re-cache on their own
because the store hands out fresh objects on update.
2026-08-25 14:00:13 +02:00
Duarte Santos 1bd69c75ff Merge remote-tracking branch 'mrq/13' into integrate2 2026-08-25 13:59:18 +02:00
Duarte Santos 0d3ddabc96 Merge remote-tracking branch 'mrq/17' into integrate2 2026-08-25 13:58:59 +02:00
Duarte Santos 142b444c8f Merge remote-tracking branch 'mrq/14' into integrate2 2026-08-25 13:58:59 +02:00
Duarte Santos 39577f6f2e Merge remote-tracking branch 'mrq/18' into integrate2 2026-08-25 13:58:59 +02:00
andi242 9c4bc16967 add fields for gravl csv import 2026-08-25 13:21:44 +02:00
andi242 881fe4b2dc add date format parse and tests
parse and test YYYY/MM/DD format
add some different date formats to testing
2026-08-25 12:31:50 +02:00
JoseviandClaude Opus 5 f0c554e86d docs: SECURITY.md al dia con las protecciones nuevas
La afirmacion "CSRF protection is SameSite=Lax and nothing else" y la de que
nginx no pone ninguna cabecera ya no eran ciertas, y el parrafo de las IPs del
activity log describia un stack que se podia falsificar. Se anaden las garantias
del bloque push y se recalculan las referencias a lineas de api/server.js, que
habian quedado desplazadas.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-25 10:01:07 +02:00
JoseviandClaude Opus 5 ec3dc8ba69 web: cabeceras de proxy no falsificables, /api prioritario y cabeceras de seguridad
X-Forwarded-For se ponia con $proxy_add_x_forwarded_for, que APENDE lo que mande
el cliente, y el API lee la primera entrada — asi que cualquiera elegia la IP que
quedaba registrada contra el en el activity log. CF-Connecting-IP no la tocaba
nadie y es la que el API mira primero. Ahora se sobrescribe con $remote_addr y la
de Cloudflare se descarta salvo que pongas CF_CONNECTING_IP=$http_cf_connecting_ip,
que solo es correcto con Cloudflare de verdad delante. .env.example afirmaba que el
stack venia correcto de fabrica; no era cierto.

location /api/ pasa a ^~ para que gane a los location con regex: sin eso una ruta
como /api/algo.json la atraparia el bloque \.(js|css|json|html)$ y se buscaria en
disco en vez de proxearse. Hoy no rompe nada, manana si.

Y cuatro cabeceras de seguridad, repetidas en los dos location con regex porque
add_header dentro de un location reemplaza los heredados en vez de sumarse. Sin
HSTS ni CSP completa a proposito: eso sigue siendo del reverse proxy.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-25 10:01:07 +02:00
JoseviandClaude Opus 5 e326f1b1cb api: cierra SSRF en push, CSRF por subdominio hermano y shadowing de cookie
Cuatro problemas encontrados en una revision de seguridad, los cuatro reproducidos
antes y despues del arreglo.

SSRF + cuelgue del handler. El `endpoint` de una suscripcion push se validaba solo
como "string no vacio", y web-push lo pasa tal cual a https.request: cualquier
usuario registrado alcanzaba cualquier host:puerto que viera el contenedor api,
que comparte red Docker con el resto del stack. Ademas no habia timeout, asi que
un endpoint que aceptaba TCP y se callaba dejaba colgado el handler que hacia
await (>2 min medidos). Ahora el rechazo de direcciones loopback/privadas/
link-local/CGNAT vive en el lookup del propio agente, no en una pasada previa, asi
que no queda ventana de DNS rebinding; y los envios llevan timeout de 10s.

Amplificacion. No habia tope de suscripciones por usuario y sendPush lanzaba un
Promise.all sin limite: una peticion de ~90 bytes producia 200 conexiones TLS
simultaneas al host que eligiera el atacante. Cap de 20 por cuenta y 6 en vuelo.

CSRF. SameSite=Lax deja fuera un origen cross-site pero no un subdominio hermano,
que es el mismo site y es el reparto habitual en self-hosting; y el body se
parseaba como JSON dijera lo que dijera el Content-Type, asi que bastaba un POST
simple sin preflight. Ahora una peticion que cambia estado tiene que ser
Sec-Fetch-Site: same-origin, o traer un Origin igual a ORIGIN donde esa cabecera
no llegue. Exentas las rutas que llevan su credencial en el body y todo lo
autenticado por Bearer, para no romper la app movil.

Fijacion de sesion. Las cookies se reducian con Object.fromEntries, que se queda
con la ultima repetida: un subdominio hermano podia plantar gymsid para el dominio
padre y quedarse con la sesion. En HTTPS la cookie pasa a __Host-gymsid, que el
navegador garantiza host-only; la legacy se sigue aceptando, asi que actualizar no
desloguea a nadie. Un nombre repetido con valores distintos se rechaza entero.

El proxy de Vite reescribe Origin porque el dev server vive en otro puerto.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-25 10:01:07 +02:00
JoseviandClaude Sonnet 5 781e2441ba mobile: modo "conectar a mi servidor" (emparejamiento por codigo, sin passkeys)
La app movil puede ahora sincronizar de verdad contra un servidor openGym
propio en vez de guardar todo solo en el telefono. Como las passkeys no
funcionan desde el WebView de la app (su origen nunca coincide con el
hostname real), el emparejamiento se hace con un codigo de un solo uso
generado desde una sesion ya logueada en el navegador (Ajustes > "Emparejar
la app movil"), canjeado por un bearer token con la misma firma que ya usa
la cookie de sesion.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-25 07:59:12 +02:00
Josevi ec84f6db06 i18n: completa las 10 traducciones que faltaban en todos los idiomas
check-locales.mjs exige el mismo set de claves en las 11 locales; las
cadenas de drop-set/rest-pause (commit 02ea938) y las de tema
"Sistema"/auto-backup solo estaban en es.js, lo que rompia el job
test:frontend en CI y bloqueaba build:apk (dependia de el).
2026-08-24 21:17:47 +02:00
Josevi 7261403d2d settings: opcion de tema "Sistema" que sigue el prefers-color-scheme del OS
Ademas de Oscuro/Claro fijos, ahora se puede elegir que el tema siga la
preferencia del sistema operativo/navegador, con actualizacion en vivo si
esta cambia mientras la app esta abierta (sin necesitar recargar).
2026-08-24 21:04:42 +02:00
Josevi 50194442b6 mobile: opcion de auto-backup local al terminar entreno o editar rutina
En el build movil (Capacitor) los datos solo viven en el dispositivo, sin
backend. Ademas del export/import manual ya existente, se agrega un toggle
en Settings que escribe una copia fechada en la carpeta Documents (visible
en Files/gestor de archivos) tras terminar un entrenamiento o salir del
editor de rutinas, para que una app de sincronizacion externa (o una copia
manual) siempre tenga algo reciente que llevarse.
2026-08-24 20:54:28 +02:00
JoseviandClaude Sonnet 5 02ea938b2c Add planned drop-sets and rest-pause/myo-reps intensifiers
An exercise's set config can now plan a drop-set (N drops, weight
decrement % per drop) or rest-pause (a total rep count split into
descending, roughly-halving bursts) via a new "Intensifier" picker in
the routine editor / exercise config sheet. The guided workout screen
pre-fills the resulting rows already computed and editable, no live
sheet or timer required; a plain set can still grow a drop/burst on
the spot too.

Rest-pause collapses the exercise to exactly two sets (a warm-up at
its own reps, then one rest-pause work set whose own reps ARE the
configured total) rather than repeating the full protocol per set.

Volume, fatigue tonnage, 1RM estimation and progression all continue
to read a set row's own w/r directly, so most of the app needed no
changes; the few that sum across a row's extras (workoutVolume,
setTonnage, applyPrescription's set-growth path) got small, targeted
fixes to avoid double-counting. Full design writeup in
PROJECT_CONTEXT.md.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-24 20:36:25 +02:00
Horus Gonzalez 79206950c4 Add the note placeholder string to the remaining 10 locales
check-locales.mjs requires every locale to carry the same key set —
the previous commit only added the string to es.js. Machine-translated
for de/fr/it/pl/pt/ru/tr/zh/ko/hi; happy to have a native speaker
refine any of these on review.
2026-08-24 11:47:22 -06:00
Horus Gonzalez f52decf633 Add optional per-exercise notes
An exercise instance in a routine only carried sets/reps/weight — a flat
target with no room for loading instructions that vary within a session
(e.g. a pyramid: "bar only, then +1 plate/side each set"). Adds a small
free-text `note` field alongside the existing config flags, shown in the
routine editor, during the active workout, and round-tripped through the
plan share/print/import paths.

No schema migration: it's an optional string on the same object that
already carries `sg`/`bodyweight`/`side`.
2026-08-24 11:40:35 -06:00
wagenheimer 4df4406139 feat(exercises): add multi-token, accent-insensitive and multilingual exercise search 2026-08-24 14:32:00 -03:00
andi242 740b2e7df5 rewrite 2026-08-24 18:30:31 +02:00
andi242 e6261e7b7b reword clunky sentence/hint to editing in demo 2026-08-24 18:27:24 +02:00
andi242 7e1c0ae023 wording 2026-08-24 18:17:08 +02:00
mzspicoli 3e531e72e1 fix: allow passkeys in Chrome on iOS 2026-08-24 18:03:10 +02:00
mzspicoli 032fe1a348 fix(push): localize server notifications in pt-BR 2026-08-24 18:02:35 +02:00
mzspicoli 448c66752f feat(i18n): localize pt-BR exercise names 2026-08-24 18:02:29 +02:00
mzspicoli dc3fafc6ef fix(i18n): correct reviewed pt-BR instructions 2026-08-24 18:02:11 +02:00
mzspicoli 3d3e44c973 feat(i18n): complete Brazilian Portuguese instructions 2026-08-24 18:02:11 +02:00
JoseviandClaude Sonnet 5 41061c1754 Claude Code: Projektdoku (CLAUDE.md) und Skills fuer Tests, A11y, Vite und Changelog installiert
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-24 18:02:04 +02:00
mzspicoli cf7b3496a5 fix(i18n): keep translation tooling portable 2026-08-24 18:01:54 +02:00
mzspicoli ad69235f6e feat(i18n): complete pt-BR core instructions 2026-08-24 18:01:54 +02:00
mzspicoli c667539f10 feat(i18n): translate first pt-BR core batch 2026-08-24 18:01:54 +02:00
mzspicoli 600f7ff0e6 test(i18n): allow pt-BR instruction batches to grow 2026-08-24 18:01:54 +02:00
mzspicoli 052ef7e0ba fix(i18n): document and validate pt-BR instructions 2026-08-24 18:01:54 +02:00
mzspicoli 9b72fb7f1e feat(i18n): start Brazilian Portuguese instructions 2026-08-24 18:01:36 +02:00
mzspicoli 03f8abb46b fix(i18n): address final pt-BR UI review 2026-08-24 18:01:31 +02:00
mzspicoli 4081ddac06 fix(i18n): close pt-BR review gaps 2026-08-24 18:01:31 +02:00
mzspicoli 9f913055d7 fix(i18n): harden Brazilian Portuguese locale 2026-08-24 18:01:31 +02:00
mzspicoli 00ba71d4df feat(i18n): add Brazilian Portuguese UI 2026-08-24 18:01:31 +02:00
andi242 e4995bbe5e wording, line breaks 2026-08-24 18:00:38 +02:00
andi242 7b5ea14d4e update rm 2026-08-24 17:51:53 +02:00
andi242 23632a07ee add doc to describe data imports 2026-08-24 17:06:40 +02:00
Space_Hermes 64ea41a5df fix(stats): remove duplicate muscle exercise list 2026-08-23 22:23:12 +02:00
Aaron Sachs d46b9215a3 feat: persisted equipment profiles (Home/Gym/etc)
Builds on the existing session-only equipment filter (issue #6) by adding a
persisted "what I actually own" profile, so the Library and exercise picker
can default to what's usable at Home vs. at the Gym instead of the full
catalogue every time.

- New equipProfiles / activeEquipId / equipFilterOn on synced state (S)
- lib/equipment.js: ALL_EQUIPMENT catalogue, activeProfile(), exAvailable() —
  body weight is always available regardless of profile
- Settings: create/edit/delete profiles (name + equipment checklist), pick
  the active one, toggle filtering on/off
- Library + exercise picker: filter to the active profile by default, with a
  one-tap "show all equipment" escape hatch per session
- RoutineEdit: flags any saved exercise that needs equipment outside the
  active profile (inline warning icon + a summary banner), so you find out
  before showing up at the wrong location, not mid-workout

Purely additive to synced client state — no server/API changes, no new
dependencies. All 339 previously-passing tests still pass (the 7 failures in
Workout.remove.test.jsx are pre-existing on a clean checkout too — a Node
localStorage/vitest environment issue unrelated to this change).
2026-08-23 16:22:34 -04:00
Space_Hermes c8f4d5bd18 feat: extract exercise catalogue and logging 2026-08-23 22:11:49 +02:00
Duarte Santos f8024d344d website: Download auf v1.2.9, jetzt die aus der CI
Erste APK, die nicht von Hand gebaut wurde. Zertifikats-Fingerprint gegen den
alten 1.2.8-Build und den Keystore geprueft - identisch, Updates installieren
sich also ueber bestehende Installationen.
2026-08-23 22:03:23 +02:00
Duarte Santos cc036406dc website: die Issue-Zahl kam anonym als undefined zurueck
Die GitLab-Projekt-API liefert einem nicht eingeloggten Aufrufer nur star_count
und forks_count - open_issues_count gibt es dort nur mit Session. site.js hat es
trotzdem gelesen und damit "undefined" in die Kachel geschrieben.

Die Zahl steht stattdessen im X-Total-Header des Issues-Endpunkts, und GitLab
fuehrt den in Access-Control-Expose-Headers, der Browser darf ihn also lesen.
Schlaegt der Aufruf fehl, bleibt der Platzhalter stehen statt einer leeren
Kachel.
2026-08-23 21:36:04 +02:00
Duarte Santos 02b02de1b2 CI: PUBLISH_LATEST auch aus per API gestarteten Pipelines
Die Regel pruefte nur auf source == web. Ueber die API gestartet ist die Quelle
"api", der Job lief dann nur zufaellig mit - naemlich ueber die
Default-Branch-Regel, waehrend das Script die Variable trotzdem sah.
2026-08-23 21:31:31 +02:00
Duarte Santos ba7ad8423f CI: latest auch ohne Release veroeffentlichen koennen (PUBLISH_LATEST)
Die docker-compose.yml im Repo zeigt auf :latest, aber latest entsteht nur aus
einem v*-Tag - bis zum ersten GitLab-Release laeuft ein `docker compose pull`
also ins Leere. Das war ein Fehler im Umzug.

Eine von Hand gestartete Pipeline mit PUBLISH_LATEST=1 baut jetzt genau wie ein
Tag: multi-arch, latest, X.Y und X.Y.Z, Version aus frontend/package.json. Der
Weg wird ohnehin gebraucht, sobald ein Basis-Image eine CVE fixt und latest
nachziehen muss, ohne dass sich am Code etwas geaendert hat.
2026-08-23 21:28:28 +02:00
Duarte Santos 24b61c2411 Den signierten APK auf GitLab legen und von README und MOBILE.md verlinken
Bis die Release-Pipeline laeuft, gab es auf GitLab keinen APK zum Laden. Der
aktuelle signierte Build (1.2.8, derselbe, den die Website ausliefert) liegt
jetzt in der Generic Package Registry unter opengym-android/1.2.8/ - genau dem
Pfad, den der build:apk-Job spaeter selbst befuellt. Daneben die .sha256:
sideloaden heisst, dass niemand die Datei fuer dich geprueft hat.

Anonym ladbar, ohne Login - nachgerechnet, die Pruefsumme des heruntergeladenen
Exemplars stimmt mit der lokalen ueberein.
2026-08-23 21:08:54 +02:00
Duarte Santos dc765083fe Buy-Me-a-Coffee-Badge oben, und den toten Sponsor-Verweis ersetzen
Der grosse gelbe Button stand schon unten in der README, aber der Satz darueber
schickte Leute zum "Sponsor button at the top of the page" - das war GitHubs
FUNDING.yml-Knopf, den es auf GitLab nicht gibt. Stattdessen jetzt ein Badge in
der Kopfzeile neben dem Discord-Badge, und der Satz zeigt dorthin.
2026-08-23 20:50:06 +02:00
Duarte Santos 2b3ffad314 Discord ueberall dort verlinken, wo Leute nach Hilfe suchen
Der Server war nur auf der Website verlinkt - im Repo selbst nirgends, obwohl
dort inzwischen das meiste passiert. Jetzt: Badge und eigener Punkt im
Community-Abschnitt der README, erste Zeile der Tabelle in CONTRIBUTING, und ein
Hinweis in der Frage-Vorlage.

Mit der Trennung, die der Sache entspricht: Discord fuer die schnelle Frage,
Issue fuer alles, was der Naechste ueber die Suche finden koennen soll - und
Exploits gehoeren in keines von beiden, sondern in ein vertrauliches Issue.

Statischer Badge, kein Live-Zaehler: das Server-Widget ist aus, shields.io wuerde
sonst "widget disabled" anzeigen.
2026-08-23 20:47:21 +02:00
Duarte Santos d1c2247e82 CI: auf einem Release-Tag ohne Signing-Key abbrechen
Ein Release darf keinen APK ausliefern, den niemand installieren kann. Fehlt auf
einem v*-Tag ANDROID_KEYSTORE_B64, ist an den geschuetzten Variablen etwas kaputt
- dann soll der Job scheitern statt still eine unsignierte Datei zu bauen.
2026-08-23 20:25:12 +02:00
Duarte Santos d2035e0562 CI: Renovate als Dependabot-Ersatz, geplante Pipelines bauen nichts mit
GitLab hat kein Dependabot, also laeuft Renovate als Job - aber nur in einer
*geplanten* Pipeline (monatlich, 1. um 04:00), damit es nie mit einem Push um
Runner-Minuten konkurriert. renovate.json uebernimmt die Politik aus
.github/dependabot.yml eins zu eins: monatlich, pro Oekosystem gruppiert, Majors
einzeln, ungerade Node-Majors raus, android/ und ios/ folgen den @capacitor/*-
Paketen statt eigene Bumps zu bekommen.

Damit die geplante Pipeline nicht nebenbei die Suite laufen laesst und die
edge-Images neu schiebt, haben test, build, apk und pages jetzt eine
"schedule -> never"-Regel.
2026-08-23 20:21:56 +02:00
Duarte Santos f38036fab6 CI: SHA256 zum APK veroeffentlichen, Pages-URL richtigstellen
Ein per Sideload installierter APK ist von niemandem geprueft worden, also soll
die Pruefsumme daneben liegen statt gar nicht zu existieren: das Release haengt
jetzt openGym-<ver>.apk.sha256 mit an.

Pages laeuft unter GitLabs "unique domain" (opengym-bc111a.gitlab.io);
duartesantos8.gitlab.io/opengym/ leitet mit 308 dorthin um.
2026-08-23 20:18:02 +02:00
Duarte Santos b2ee031cf1 CI: buildx den dind-Daemon ueber einen benannten Docker-Kontext geben
"could not create a builder instance with TLS data loaded from environment" -
der docker-container-Treiber liest DOCKER_HOST + DOCKER_CERT_PATH nicht direkt.
`docker context create tls-environment` friert genau diese Umgebung als Kontext
ein, und darauf laesst sich der Builder anlegen.
2026-08-23 20:12:07 +02:00
Duarte Santos 925190109f Umzug nach GitLab: CI/CD fuer Tests, Images, APK, Pages und Releases
gitea.com hat keinen Actions-Runner, also gab es dort seit dem Umzug weder
Container-Images noch einen gebauten APK noch gruene Tests auf Merge Requests.
GitLab kann alles vier, also zieht das Projekt dorthin um.

.gitlab-ci.yml deckt die komplette Kette ab:
- test: Frontend-Suite (346 Tests), Locale-Checks, Fatigue-Probe, MCP-Suite
- build: api- und web-Image nach registry.gitlab.com/duartesantos8/opengym/*,
  auf v*-Tags amd64+arm64 mit latest/X.Y/X.Y.Z, sonst amd64 als edge
- package: signierter APK (zipalign + apksigner) plus Upload in die Generic
  Package Registry; der Key liegt in geschuetzten CI-Variablen und existiert
  damit nur auf main und v*-Tags
- deploy: der Browser-Demo-Build auf GitLab Pages
- release: GitLab-Release mit dem passenden CHANGELOG-Abschnitt und Links auf
  APK und Images

GitHub konnte "Tag gepusht" von "Release veroeffentlicht" unterscheiden und hat
Images nur aus letzterem gebaut (Issue #87). GitLab kann das nicht - dort ist die
Tag-Pipeline das, was das Release anlegt. Die Regel steht deshalb als Kommentar
im CI-File, und v*-Tags sind geschuetzt.

Ausserdem: Issue-/MR-Vorlagen unter .gitlab/, und saemtliche Repo-Links in
README, Docs, App, Dockerfile-Labels, docker-compose und Website zeigen auf
GitLab. site.js liest Sterne und Releases jetzt aus der GitLab-API (andere
Feldnamen, deshalb neue sessionStorage-Keys). SECURITY.md hat wieder einen
privaten Meldeweg: ein vertrauliches Issue.

.github/ und .gitea/ bleiben liegen - Spiegel bzw. fuer den Tag, an dem das
GitHub-Konto zurueckkommt.
2026-08-23 20:10:07 +02:00
Duarte Santos 8b99a644ed Release v1.2.9: Aktivitaetslog im Admin-Dashboard, Demo wieder online
Wer sich anmeldet, wer es vergeblich versucht und was ein Admin aendert, stand
bisher nirgends — der Server hat schlicht nichts protokolliert.

Aktivitaetslog:
- ./data/audit.log, eine JSON-Zeile pro Event, angehaengt statt neu geschrieben.
  Bewusst NICHT in db.json: die Datei wird bei jedem Save komplett neu geschrieben,
  und der Login-Handshake ist unauthentifiziert — ein Log darin haette aus einem
  Muell-Request einen vollen Rewrite gemacht.
- Aufbewahrung ist eine Obergrenze, kein Archiv: AUDIT_MAX (5000) bzw. AUDIT_DAYS (90).
- Per Default an (AUDIT_LOG=0 schaltet es ganz ab). IP-Adressen per Default AUS;
  AUDIT_IP=net speichert nur das Netz, full die ganze Adresse. Nie der User-Agent,
  nie die Passkey-ID eines Fehlversuchs, nie ein abgelehnter Invite-Code.
- Adresse kommt aus CF-Connecting-IP, dann X-Forwarded-For, dann X-Real-IP —
  ein Cloudflare-Tunnel schreibt den Besucher NICHT in XFF, dort steht sonst nur
  der Tunnel selbst und sieht dabei voellig plausibel aus.
- Loeschen wird selbst protokolliert, die Event-IDs zaehlen weiter: die Luecke bleibt sichtbar.
- Neue Karte in views/Admin.jsx (Filter, "Show more"), Aufbereitung in lib/audit.js
  mit 20 Tests. GET /api/admin/audit und POST /api/admin/audit/clear, beide hinter requireAdmin.

Demo:
- Die Live-Demo laeuft wieder, jetzt auf der Projektseite selbst statt auf GitHub Pages:
  opengym.duarte-santos.ch/demo/. Das eingebettete Telefon auf der Startseite geht damit auch
  wieder — es muss derselbe Host sein, X-Frame-Options ist SAMEORIGIN.

Doku: README-Config-Tabelle, .env.example, SELF_HOSTING, SECURITY (inkl. der
api/server.js-Zeilenverweise, die wieder stimmen).
2026-08-23 16:12:35 +02:00
Duarte Santos e709f152c8 website: Download-Seite auf v1.2.8 (APK vom 19.08. mit der Back-Geste ist live) 2026-08-22 15:37:17 +02:00
Duarte Santos c2e41937cb Release v1.2.8: Umzug nach gitea.com, Android-Back-Geste, Medien-Lizenz, Umami
Die Sammelversion fuer alles seit v1.2.7: der Umzug nach gitea.com (Images,
Klon-URL, Anlaufstellen, CI), die Zurueck-Geste auf Android via @capacitor/app,
die richtiggestellte Medien-Lizenz und die Umami-Zaehlung auf der Website (im
Frontend nur, wenn beim Build gesetzt -- selbstgehostet bleibt telemetriefrei).

api/package.json auf 1.2.8 nachgezogen; frontend/package.json und
android/build.gradle standen schon auf 1.2.8.
2026-08-22 15:32:04 +02:00
Duarte Santos 6dfb36c46a Lizenz der Uebungsmedien richtiggestellt: MIT-Metadaten, Bilder (c) Gym visual
"exercise data from hasaneyldrm/exercises-dataset (CC)" stand ueberall -- im
README, in NOTICE.md, auf der Website, in den Settings, im compose-File und im
fetch-Script. Der Upstream lizenziert aber zwei Haelften unterschiedlich: Namen,
Attribute und Anleitungstexte sind MIT, die Bilder und GIFs sind (c) Gym visual
und liegen dort mit einer nicht uebertragbaren Erlaubnis.

- NOTICE.md trennt die beiden Teile, zitiert die MIT-Lizenz im Wortlaut und
  nennt die Gym-visual-Terms
- README/Website/Settings sagen jetzt MIT + (c) Gym visual statt "CC"
- compose und fetch-media.sh drucken die Herkunft beim Download, damit es auch
  sieht, wer die Doku nicht liest

An der Nutzung von openGym aendert das nichts: die Medien lagen nie im Repo, in
der History, im Image oder im APK -- jede Instanz laedt sie beim ersten Start
vom Upstream. An der Weiterverwendung der Medien schon: dafuer braucht es eine
eigene Lizenz von Gym visual.
2026-08-22 15:32:04 +02:00
Duarte Santos c588d219ba website/: den Stand nachgezogen, der seit dem GitHub-Ausfall live ist
Die Seite auf opengym.duarte-santos.ch wurde am Ausfalltag direkt im dist bearbeitet,
die Quelle hier blieb auf dem alten Stand: GitHub-Links, GitHub-API fuer die Zaehler,
Demo-iframe auf die tote Pages-Instanz.

Uebernommen: Hinweisblock zur Sperre auf allen drei Seiten, Links und Zaehler auf
gitea.com (site.js liest jetzt stars_count/open_issues_count und die Releases von
dort), Discord-Abschnitt, Demo-Sektion als "Temporarily offline" mit Verweis auf APK
und Selfhosting, dazu die neuen Styles und der Umami-Tag der Website.

Die Zeitleiste auf about.html fuellt sich, sobald hier Releases stehen - die
Release-API von gitea.com liefert aktuell noch nichts.
2026-08-22 13:56:26 +02:00
Duarte Santos f94fa7c0e3 Umzug nach gitea.com: Images, Klon-URL, Anlaufstellen und CI umgestellt
Das GitHub-Repo ist mit dem gesperrten Account weg, mit ihm die GHCR-Images, die
Pages-Demo und die Discussions. Alles, was jemand zum Selbsthosten anklickt, zeigte
aber weiter dorthin.

- docker-compose zieht jetzt gitea.com/duartesantos/opengym-{api,web}; die
  Dockerfile-Labels (source/url/documentation) ebenso
- README, SECURITY, CONTRIBUTING und docs/SELF_HOSTING zeigen auf gitea.com.
  Discussions gibt es dort nicht: Fragen und Ideen laufen als gelabelte Issues,
  Security-Meldungen ueber eine Issue-Anfrage nach einem privaten Kanal statt
  ueber GitHubs Advisories
- Badges auf die Gitea-Shields umgestellt, die tote Pages-Demo aus dem Kopf
  genommen (die APK bleibt der Weg zum Ausprobieren)
- .gitea/workflows: Tests und Docker-Publish, weiter mit Release- statt
  Tag-Trigger. Kein type=gha-Cache, den gibt es auf den Gitea-Runnern nicht;
  der Push braucht ein Repo-Secret PACKAGES_TOKEN mit write:package
- .gitea/ISSUE_TEMPLATE mit denselben Formularen wie auf GitHub
- .github/* bleibt unangetastet, falls der Account zurueckkommt

Die alten Issue-/PR-Nummern im CHANGELOG bleiben als reiner Text stehen - sie
zeigen auf ein totes Repo und passen nicht auf die Nummerierung hier.
2026-08-22 13:54:26 +02:00
Duarte Santos 4b25a80356 Analytics: Umami auf der Website, im Frontend nur wenn beim Build gesetzt
website/: fester Umami-Tag fuer opengym.duarte-santos.ch (Landing/About/Docs).
frontend/: vite-Plugin injiziert den Tag NUR wenn VITE_UMAMI_SRC und VITE_UMAMI_ID
beim Build gesetzt sind — ein normales 'npm run build' und damit jede
selbstgehostete Instanz bleibt telemetriefrei.

(Die Download-Zeile auf v1.2.7 lag schon uncommitted im Baum und faehrt mit.)
2026-08-20 15:44:59 +02:00
Duarte Santos 19a441d93e Android-Back: @capacitor/app verdrahtet, Zurueck-Geste beendet die App nicht mehr
Capacitor 7 behandelt Zurueck gar nicht selbst, das macht @capacitor/app -- das
Plugin fehlte, also lief jede Zurueck-Geste an der WebView vorbei direkt in
finish(). Die History-Eintraege pro Sheet (#63) haben nur im Browser gewirkt.

Neu: lib/back.js entscheidet Sheet -> Seite -> zweimal Zurueck zum Beenden
(exitApp, weil das Plugin mit registriertem Listener nie mehr selbst beendet),
gesperrte Sheets schlucken Zurueck weiterhin. Version auf 1.2.8/versionCode 9.
2026-08-19 16:30:32 +02:00
Duarte Santos e69673d3cd funding buymeacoffee 2026-08-19 06:42:52 +00:00
Duarte Santos 5de5147c5e funding buymeacoffee 2026-08-19 06:29:49 +00:00
Duarte Santos 9007aeefb6 Release v1.2.7: compose reicht BACKEND/NGINX_PORT/PORT durch, Doku und Website nachgezogen, neue Screenshots 2026-08-18 15:33:02 +02:00
Duarte Santos 71b22b3216 Changelog: Unreleased-Abschnitt fuer die gemergte Backlog-Runde 2026-08-18 12:26:34 +02:00
Duarte Santos 5bf149e60b i18n: Checker fuer Quell-Strings, die in KEINEM Pack stehen (check-locales sieht die nicht) 2026-08-18 12:11:51 +02:00
Duarte Santos c17632ea3d Superset-Flow: High-Water-Marken nach dem Entfernen einer Uebung neu setzen, api.js im Test gemockt 2026-08-18 12:08:15 +02:00
Duarte Santos aac6b185ec Merge remote-tracking branch 'pr/80' 2026-08-18 12:03:38 +02:00
Duarte Santos 3b720b0332 Remove-Exercise: Randfaelle abgedeckt (letzte Uebung, Zweier-Superset, cur unterhalb) 2026-08-18 12:03:31 +02:00
Duarte Santos 8fe980343d Merge remote-tracking branch 'pr/83' 2026-08-18 12:02:22 +02:00
Duarte Santos 8323e06819 Merge remote-tracking branch 'pr/94' 2026-08-18 12:00:52 +02:00
Duarte Santos 55b9dcb864 Warm-up: die vier verbliebenen Roh-Lesungen von .warmup ueber isWarmupRow, mit Regressionstests 2026-08-18 11:57:40 +02:00
Duarte Santos 76a2d3b7a5 Merge remote-tracking branch 'pr/93' 2026-08-18 11:55:28 +02:00
Duarte Santos 09baee49a7 Fatigue: linkedom bleibt (Modals-Test braucht es), Monotonie-Probe laeuft in CI 2026-08-18 11:54:55 +02:00
Duarte Santos 374f6bdadc Merge remote-tracking branch 'pr/55' 2026-08-18 11:53:13 +02:00
Duarte Santos 32c9a2380d Healthchecks: 127.0.0.1 statt localhost, konfigurierter Port statt 80, /api/health statt /api/config 2026-08-18 11:50:53 +02:00
Duarte Santos 9976b7a278 Merge remote-tracking branch 'pr/100' 2026-08-18 11:45:37 +02:00
Duarte Santos d4169690a6 Merge remote-tracking branch 'pr/85' 2026-08-18 11:44:58 +02:00
Duarte Santos 55de70ad23 i18n: neue Keys auf den Quote-Stil der Packs ziehen 2026-08-18 11:44:24 +02:00
Duarte Santos f860edd24a Merge remote-tracking branch 'pr/92' 2026-08-18 11:43:51 +02:00
Duarte Santos 329eed4ce0 CI: Images nur noch aus einem publizierten Release, nicht aus jedem Tag (#87) 2026-08-18 11:39:26 +02:00
Duarte Santos 5d7e13361c Website: Download-Zeile auf die v1.2.6-APK 2026-08-18 11:38:37 +02:00
Duarte Santos 274a0276e0 Release v1.2.6: Changelog-Datum auf den letzten Stand, Android zieht mit 2026-08-18 11:31:53 +02:00
Georgiy Sitnikov 1ba378b632 - Enable Templating feature as per https://hub.docker.com/_/nginx#using-environment-variables-in-nginx-configuration-new-in-119
- Set default Variables
Solution for https://github.com/DuarteSantos8/openGym/issues/99
2026-08-14 12:11:38 +02:00
Georgiy Sitnikov 0e00e1029c Add version metadata and update Dockerfile labels for API and web services 2026-08-14 11:29:23 +02:00
Georgiy Sitnikov 011a3f7790 Add healthcheck to Dockerfiles for API and web services 2026-08-14 11:28:09 +02:00
root 4e842b00e1 feat: resolve warm-up rows by phase 2026-08-12 20:20:34 +02:00
Space Hermes f3ba7de479 feat: add strength exercise view and history snapshots 2026-08-12 20:18:05 +02:00
root 57f04febbe feat(i18n): add strength-view strings to all locales 2026-08-12 20:13:35 +02:00
Space-Hermes 23a5b6c228 fix: smaller same-area items from the review - future-dated clamp, LB_TO_KG export, value-based bodyweight guard 2026-08-12 17:43:20 +02:00
root ed666df237 fix: fatigue round-4 (zero-load strength, history-stable reference, real Stats view tests + committed probe) 2026-08-12 17:25:57 +02:00
root a95104b675 fix: back-button history accounting (explicit pushed-entry counter, locked-sheet popstate) + mouse-drag slider opt-out 2026-08-12 17:25:27 +02:00
root edde72f9cb fix: superset flow round-3 (rest gate for ordinary exercises, high-water progress, top-weight owns advance, Workout coverage) 2026-08-12 17:20:50 +02:00
root 237d1c5cf2 fix: decrement cur when the removed entry sits below it (superset picker case) 2026-08-12 17:20:04 +02:00
root b42d2baa6e fix: make session exercise removal timer-safe 2026-08-11 23:18:45 +02:00
root f32c4d0b73 feat: remove exercise from a session (confirm; superset picker) 2026-08-11 23:01:20 +02:00
Duarte Santos 528cb70a79 Changelog v1.2.6: Session-Supersets, Muscle-Map-Overlay, Medien-Pfade und Import-Aliase 2026-08-11 22:37:31 +02:00
Duarte Santos a7d7f5c24b Fix media paths on routine detail, map the Hevy names that fell through
Two reported bugs, both small:

exercise media (#79): IMG_BASE/GIF_BASE were relative, so on /plan/r/:id --
the app's only two-segment route -- the browser resolved them against the
route and asked for /plan/r/img/..., which nginx's extension block 404s
instead of falling through to index.html. Blank images, nothing in the
console. Absolute defaults; the VITE_* overrides are absolute already, so
the Pages demo and the mobile build are unaffected.

import aliases (#74): Treadmill, Goblet Squat, Cycling and Cable Core
Pallof Press arrived as custom exercises because no word-overlap can reach
the catalogue's names for them. Added those plus the neighbours around
them, and a test file -- matchExercise had none.

Also documents that VITE_IMG_BASE/VITE_GIF_BASE are build-time, which is
why setting them next to docker compose does nothing on a prebuilt image.
2026-08-11 22:35:43 +02:00
Duarte Santos fe585097c8 Merge remote-tracking branch 'pr/64' 2026-08-11 22:30:09 +02:00
Duarte Santos d8c734a2b6 muscle overlay: route the exercise detail tags through smOf too
#67 stopped mutating EXDB and moved the secondary-muscle additions into a
derived smOf() overlay, but ExerciseDetail still read the raw ex.sm. The
four curated row additions (0027, 0293, 0499, 0861) were silently dropped
from the detail sheet's tag row -- "rear deltoids" was the third visible
tag on all four, so the slice(0,3) did not hide it.

Caught on merge, before it shipped.
2026-08-11 22:30:04 +02:00
Duarte Santos 087ce34674 Merge remote-tracking branch 'pr/67' 2026-08-11 22:29:14 +02:00
Duarte Santos 157ca90f3b Merge remote-tracking branch 'pr/60' 2026-08-11 22:29:05 +02:00
root 15c29029c1 neutral superset header text (mirror live) 2026-08-08 10:46:43 +02:00
root 030a609427 translate superset action labels (11 locales) 2026-08-08 10:11:26 +02:00
root 8bbf59c001 remove accidentally committed node_modules symlink 2026-08-08 10:09:49 +02:00
Space_Hermes b29a3f6bb0 feat: create and remove session supersets 2026-08-08 02:24:22 +02:00
root bee9b64b78 progression: guard set growth against an all-warm-up entry (no work seed, no infinite loop) 2026-08-07 17:03:57 +02:00
Duarte Santos 35181af2aa Merge remote-tracking branch 'pr/48' 2026-08-07 16:24:44 +02:00
root 01072ef5e3 warm-up round 3: applyPrescription/readSession never touch warm-up rows; per-phase set numbering; regression tests 2026-08-07 15:19:11 +02:00
root 86ac937d5d warm-up carve-outs (effort ratio, muscle map), cascade/warmup row helpers with tests, dead guard removed, total+work set counts 2026-08-07 15:16:19 +02:00
root 9cc645c755 fix warmup 1RM test equality 2026-08-07 15:15:51 +02:00
root cbb3630423 warm-up sets: excluded from 1RM and progression only (volume semantics kept); tests 2026-08-07 15:15:51 +02:00
root 0109857249 cascade: fixed-weight only, never overwrite done sets 2026-08-07 15:15:51 +02:00
root edb3e42c43 session UX: warm-up phase separation, add/remove warm-up sets, weight cascade to following sets 2026-08-07 15:15:51 +02:00
root 577c86b487 derive secondary additions via smOf overlay - raw dataset never mutated 2026-08-07 13:12:42 +02:00
Duarte Santos 13ed730a0c Changelog v1.2.6: Muscle-Map-Recovery, Rest-Notification, Rear-Delt-Sekundaers 2026-08-07 11:35:04 +02:00
Duarte Santos 7e60ac20f2 Merge remote-tracking branch 'pr/44' 2026-08-07 11:33:51 +02:00
Duarte Santos 06a1e0a709 Merge remote-tracking branch 'pr/49' 2026-08-07 11:33:37 +02:00
Duarte Santos d99f0ef2f1 Merge remote-tracking branch 'pr/51' 2026-08-07 11:33:17 +02:00
root d0075eeddf rest notification: service-worker path for Android, use existing string 2026-08-07 09:10:43 +02:00
root 86f3476f5f fatigue: saturating volume-based model, no window cliff, reachable level bands 2026-08-07 09:02:38 +02:00
Duarte Santos 9daf637044 Gastmodus abschaltbar: ALLOW_GUEST=0 nimmt die Tuer ohne Konto raus (#42) 2026-08-07 08:10:19 +02:00
Duarte Santos b2b3577744 Release v1.2.6: Freestyle-Sessions starten dort, wo du aufgehoert hast 2026-08-07 07:38:56 +02:00
Space-Hermes 84e98425cc feat: prefill freestyle exercises from last workout 2026-08-06 19:54:36 +02:00
Space_Hermes 941d911fa9 feat: enrich common row muscle metadata 2026-08-06 19:46:18 +02:00
root 5b5d65b63e Add local notification on rest timer completion 2026-08-06 19:39:59 +02:00
root 6c91adefcd volWin: plain 90d window filter (upstream-adapted) 2026-08-06 19:17:41 +02:00
root d1cede21d3 fix dropdown label em-dash expression 2026-08-06 19:16:47 +02:00
root 9af028bde3 confirmed UI tweaks: fatigued highlighted (red/amber), strongest gold, strength scale labels, exercise list by current strength, 90d volume on strength rows 2026-08-06 19:16:08 +02:00
Space-Hermes eeee4b461c feat: muscle map Fatigue + Strength (detraining) views
Per-muscle fatigue (72h window, 36h half-life, .25/.5 bands) and retained
strength (14d plateau, 28d half-life, .5 floor) views on the Stats page
behind a Balance | Fatigue | Strength segmented control. Pure recovery.js
module with fatiguedMuscles/detrainedMuscles hooks, owner-approved
backward-compatible absolute-level BodyMap extension, 8 i18n keys across
English fallback + 11 locale packs, mounted interaction tests.
2026-08-06 11:33:21 +02:00
Duarte Santos 551b072c54 MCP: die zweite Einheit an einem Tag ist erreichbar, und ein leeres 1RM sagt warum
Zwei Befunde aus dem Parity-Durchlauf gegen echte Daten. Die Arithmetik stimmte
ueberall (rund 120 Werte gegen eine unabhaengige Nachrechnung, null Abweichung)
— diese beiden nicht.

get_workout nahm `.find(x => x.d === date)`. Wer morgens hebt und abends laeuft,
hat zwei Einheiten am selben Datum, und die zweite war ueber gar keinen Weg
erreichbar: es gab nirgends eine id, und die Frage nach dem Lauf bekam die
Zahlen des Zugtrainings — vollkommen selbstbewusst vorgetragen. list_workouts
liefert jetzt `id`, get_workout nimmt `workout_id` oder `date`, und bei zwei
Treffern am selben Tag antwortet es mit beiden zur Auswahl statt zu raten.

Und `best: null` hatte zwei gegensaetzliche Ursachen in einer Form: nie
trainiert, oder immer ueber der 12-Wiederholungs-Grenze. Eine Wade, die seit
Monaten mit 15ern im Log steht, las sich damit als "keine Aufzeichnungen".
no_estimate_reason unterscheidet die beiden, und formula_note steht jetzt auch
auf diesem Zweig — bisher gab es die Erklaerung nur in der PR-Tabelle.

Drei Regressionstests dazu (36 statt 33), mcp/README zu get_workout nachgezogen.
2026-08-04 17:48:52 +02:00
Duarte Santos e007f76d43 MCP: CI laeuft ueberhaupt erstmal, und der Server ueberlebt seinen Client nicht
Fuer mcp/ gab es keinen CI-Job — weder die 33 Tests noch sonst irgendwas lief je
auf GitHub. Jetzt laeuft beides bei jedem PR, der mcp/ oder frontend/ anfasst.

Dazu der Check, den die Testsuite prinzipiell nicht machen kann: vitest loest
ueber Vite auf, also gehen dort import.meta.glob, ?raw und .jsx anstandslos
durch. Genau so kam ein Vite-only-Import in ein gemeinsames Lib-Modul und liess
33 gruene Tests ueber einem Server stehen, der beim Start starb.
check-node-loadable.mjs laeuft deshalb unter nacktem node — dass es ausserhalb
von vitest laeuft, IST der Test. Gegengeprueft: Bug wieder eingebaut → Exit 1
und history.js/progression.js/tools.js namentlich gemeldet; sauber → Exit 0.

Und der fs.watch-Handle haelt die Event-Loop offen, sobald es eine State-Datei
zu beobachten gibt — der Prozess ueberlebt damit den Client, der ihn gestartet
hat, obwohl die mcp/README genau das Gegenteil verspricht. Ein unref() reicht;
nachgemessen: mit State-Datei vorher Exit 124 (haengt), jetzt Exit 0, und der
Watcher invalidiert den Cache unveraendert weiter.
2026-08-04 16:40:03 +02:00
Duarte Santos e28345dd13 Release v1.2.5: der MCP-Server, und sonst nichts an der App
Letztes publiziertes Release war v1.2.4, also ist das hier v1.2.5 — alles seit
dem Release in EINE Nummer. Inhalt ist genau eine Sache: der optionale
MCP-Server aus PR #19 nebst dem i18n-Kern-Split, der ihn ueberhaupt erst unter
reinem Node ladbar macht.

An der App selbst aendert sich nichts. Wer keinen KI-Client benutzt, merkt von
diesem Release ueberhaupt nichts: nichts wandert in den Docker-Build, die
docker-compose.yml bleibt unberuehrt.

Kein neues APK — der Bundle-Hash bewegt sich zwar (der Modulgraph haengt jetzt
direkt am i18n-Kern), aber verhalten tut sich die App identisch. Die
Download-Zeile auf der Website bleibt deshalb bei v1.2.4.
2026-08-04 16:35:34 +02:00
Duarte Santos ba412cb36d MCP: die Lib bleibt unter reinem Node ladbar, und die Testwerte stimmen wieder
Der MCP-Server ist ein nacktes `node src/index.js` — kein Vite, kein React. PR 19
hatte dafuer den reinen Kern nach i18n-core.js gezogen; v1.2.4 hat danach in
history.js `t` wieder aus i18n.js geholt, und damit import.meta.glob ueber die
Locale-Packs plus useSyncExternalStore in einen Prozess, der beides nicht hat.
Der Server starb beim Import:

  TypeError: (intermediate value).glob is not a function

Die Testsuite konnte das nicht sehen: vitest transformiert import.meta.glob, also
liefen 33 gruene Tests gegen ein Binary, das nie startet. i18n.js re-exportiert
ohnehin genau dieses `t` aus dem Kern — history.js, mobile.js und plan-share.js
holen es jetzt direkt von dort, und mitgeschleppt wird nichts mehr.

Dazu die Werte, die der v1.2.4-Seed verschoben hat: Volumen 18500 → 18412.5
(Handsumme w×r ueber die zwanzig erledigten Saetze), Koerpergewicht 78.6 → 78.4,
Wiegung 78.5/1.5 → 78.3/1.3, Dauer 51 min → 1h 11m — samt der Zusicherung, die
sich das "N min"-Format noch fest verdrahtet hatte. Jeder Wert nachgerechnet,
nicht aus einem roten Lauf abgeschrieben.

Und das FORMULAS aus Punkt 2 des Reviews, das als einziges stehengeblieben war.
2026-08-04 16:30:34 +02:00
Duarte Santos f554b6b004 Merge pull request #19 from Pengboi/feat/mcp-server
MCP: read-only stdio server for LLM apps to query workout history

Ein Node-Prozess, den der LLM-Client selbst startet und der dieselben reinen
Helfer aus frontend/src/lib benutzt wie die Stats-Seite — also stehen dort
dieselben Zahlen. Read-only, kein Container, kein zusaetzliches Auth, nichts
verlaesst die Box. Wer keinen KI-Client benutzt, merkt nichts davon.
2026-08-04 16:30:14 +02:00
Pengboi 09949686c2 MCP: fixes from review (cardio mode, dead code, Stryker drop, docs)
· entryView was passing `e.target || { id: e.id }` to modeOf, which
   doesn't put id on the target when target exists — so a cardio config
   saved as {sets, min, speed} (no mode, no id) fell through to 'reps'
   and the label came back as "0×0". Now uses the same pattern every
   app call site uses (Workout.jsx, Stats.jsx, progression.js):
   modeOf({ ...(e.target || {}), id: e.id }). Same fix applied to the
   setLabel call right below. Added a regression test using a real
   cardio exercise id with a target that has no mode key — would have
   caught the original bug.

 · requireIso/ISO/fmt/friendlyDate/MUSCLES were unused (zod regexes
   cover ISO validation at the SDK layer). Removed, along with the
   misplaced comment that described requireIso but sat above entryView.

 · estimate_1rm's exercise_id schema description referenced
   search_exercises (v1.5) which doesn't exist yet — an LLM reading
   the schema would try to call it. Dropped the reference; the
   Roadmap section in mcp/README.md drops the same mention.

 · resolveUid threw "set OPENGYM_UID to one of: " (empty list) when
   there were zero state files but multiple users in db.json — the
   files array was empty so files.join(', ') rendered nothing. Now
   falls back to the db.json user ids in that branch.

 · Dropped Stryker entirely. The MCP SDK's 93 transitive runtime
   packages are tolerable since mcp/ is opt-in and never enters
   Docker, but a second test toolchain for a 39% mutation score
   wasn't carrying its weight next to the plain vitest suite.
   Removed .stryker.conf.json, the two Stryker devDeps, the
   mutation:test script, the .gitignore entries, and the README
   section. mcp/ now has a single devDep (vitest); 0 vulnerabilities
   (was 2 moderate).

 · CONTRIBUTING.md layout block + a one-line cross-reference in
   README.md's Tech section pointing at mcp/README.md, so people can
   actually find it.

92 frontend + 33 MCP tests pass.
2026-08-02 19:42:36 +01:00
Duarte Santos 7c69e57b4f Website: the download is v1.2.4
The APK on opengym.duarte-santos.ch is the 1.2.4 build (versionCode 5, same
signing key, so it installs over 1.2.3). The meta line said 1.2.3.
2026-08-01 17:09:28 +02:00
Duarte Santos 663e0b3987 Release v1.2.4: the effort stats, and bodyweight training that knows it is
v1.2.3 is published, so this is the next patch and everything since it belongs in
this one version: the Effort card and the readings built on it, the bodyweight and
per-side work from issues #31/#32/#33, and two fixes worth naming.

Versions bumped in frontend, api and the Android module (versionCode 5). CHANGELOG
gets the release heading and a Fixed section, README two feature bullets.
2026-08-01 17:07:17 +02:00
Duarte Santos 5a0345c905 Merge bodyweight: issues #31, #32, #33 2026-08-01 17:06:31 +02:00
Duarte Santos 1e86d6ace2 Config sheet: a stepper is not a list-row accessory
Added weight sat inside a list row next to its label, which is fine for a switch
and wrong for a stepper: the control took the width it needed and left the text
column wrapping one word per line. It now gets the same full-width treatment as
sets and reps, with the explanation underneath, and reuses the "Added (kg)" label
the set table already uses.

Also stops a long value overlapping its own title in a list row — flex:none meant
"Follow the routine (Linear progression)" ran straight through "Rule", since the
title's column was already free to shrink to nothing. The value shrinks and
ellipsises instead. Pre-existing, visible in every settings row with a long value.
2026-08-01 17:00:30 +02:00
Duarte Santos a5e360cde5 Settings can register on an invite-only instance too
The sign-in screen asks for an invite code when the server says it needs one. The
same registration reached from Settings never did: it collected a name, called
passkeyRegister without the second argument, and the server refused it. On an
invite-only instance that path could not succeed at all, with nothing on screen to
explain why.

It now reads /api/config and shows the code field on the same terms, reusing the
sign-in screen's own strings so nothing new needs translating.
2026-08-01 16:52:30 +02:00
Duarte Santos 00b4f543a3 Per side stays on reps work, where reps exist
Switching a per-side exercise to Time carried `side` onto the hold: the config
sheet hides the toggle in that mode but still saved the flag, and the workout
badge then halved a rep count a timed set does not have, reading "0 per side".

Dropped at all three points it could get through — the config sheet no longer
writes it outside reps mode, the badge no longer renders outside it, and the plan
serialiser refuses it on a hold so an older file cannot bring it back.
2026-08-01 16:48:57 +02:00
Duarte Santos 4afffcb248 Per side: log the total, show the split
Feedback on #31: a rep count that sometimes means one side and sometimes both is
the ambiguity, not the fix for it. So the logged number is the total — 16 — the
same as every other set in the app, and the split is derived for planning: "8 per
side" on the exercise, "3 × 16 · 8/side" on the plan line and the printed sheet.

Unilateral targets step in twos. 16 → 18 → 20, in the config stepper, the set-row
stepper and the bodyweight rep progression, because half of an odd total is a rep
one side never gets. Turning the flag on rounds an existing target up to even, and
a saved target is stored even for the same reason. An odd total that arrives some
other way still displays honestly, as 8.5 per side, since that is what it means.

Volume loses its per-side case: both sides are already in the number logged.
2026-08-01 16:47:44 +02:00
Duarte Santos c33ff15d9d Bodyweight work, logged the way it is done
A push-up has no weight to type and the app asked for one anyway, on a quarter of
the catalogue. Issues #31, #32 and #33 are the same gap seen from three sides: the
app assumed progress lived in the load.

Two flags on the exercise config rather than two new modes, because "bodyweight"
and "per side" are equally true of a rep set and a timed hold:

  bodyweight — seeded from the equipment the dataset already records. The weight
               column is gone, the set row is one stepper, and the working-weight
               prompt stops asking about a weight that was never there. A belt
               weight reads as an addition and hands progression back to the
               normal policies, because now there is something to add.
  side       — 8 logged is 8 per side. The total is spelled out where there is
               width for it, and volume counts both sides so a routine that moved
               to single-arm work no longer halves itself on the chart.

Bodyweight progression grows reps, and now sets: a rep ceiling sends the reps back
to the bottom and adds a set instead of climbing forever, stopping at six with the
advice it should have given all along. No ceiling keeps the old behaviour exactly.

Both flags are written to a plan only when they disagree with the catalogue, and
absent reads as false, so every existing plan, workout and backup is read
unchanged.
2026-08-01 16:37:52 +02:00
Duarte Santos 8de55ce0d9 Merge pull request #29 from DuarteSantos8/dependabot/npm_and_yarn/frontend/frontend-120fce7b1d
Bump react-router-dom from 7.18.1 to 7.18.2 in /frontend in the frontend group
2026-08-01 14:49:40 +01:00
Duarte Santos aefb13b544 Merge pull request #30 from DuarteSantos8/dependabot/github_actions/actions-6382876e44
Bump docker/login-action from 4.5.2 to 4.6.0 in the actions group
2026-08-01 14:49:21 +01:00
dependabot[bot] 7354b1ca0c Bump docker/login-action from 4.5.2 to 4.6.0 in the actions group
Bumps the actions group with 1 update: [docker/login-action](https://github.com/docker/login-action).


Updates `docker/login-action` from 4.5.2 to 4.6.0
- [Release notes](https://github.com/docker/login-action/releases)
- [Commits](https://github.com/docker/login-action/compare/v4.5.2...v4.6.0)

---
updated-dependencies:
- dependency-name: docker/login-action
  dependency-version: 4.6.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-01 00:45:03 +00:00
dependabot[bot] f5562febca Bump react-router-dom in /frontend in the frontend group
Bumps the frontend group in /frontend with 1 update: [react-router-dom](https://github.com/remix-run/react-router/tree/HEAD/packages/react-router-dom).


Updates `react-router-dom` from 7.18.1 to 7.18.2
- [Release notes](https://github.com/remix-run/react-router/releases)
- [Changelog](https://github.com/remix-run/react-router/blob/react-router-dom@7.18.2/packages/react-router-dom/CHANGELOG.md)
- [Commits](https://github.com/remix-run/react-router/commits/react-router-dom@7.18.2/packages/react-router-dom)

---
updated-dependencies:
- dependency-name: react-router-dom
  dependency-version: 7.18.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: frontend
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-01 00:44:33 +00:00
Duarte Santos 1f40230727 Dependabot: majors arrive on their own, and Capacitor waits
Grouping by ecosystem cut the noise, which was the point, but it also let a
Capacitor 7 → 8 migration turn up as "the frontend group, 7 updates" — six
routine siblings and one native-platform migration, indistinguishable in the
list. CI would have gone green on it too: the test workflow builds the web app
and never touches the mobile flavour, so the check would have been reassuring
about something it had not looked at.

Minor and patch stay grouped and quiet. Majors get their own PR per ecosystem,
where being alone is the signal.

Capacitor majors are ignored outright for now: Capacitor 8 declares Node >= 22
and the build host runs 20, and frontend/android and frontend/ios are committed,
so the upgrade also means migrating Gradle/AGP and the Podfile. That is a piece
of work to schedule, not a PR to merge. The comment says to drop the ignore once
the build host moves to Node 22.
2026-07-31 20:35:12 +02:00
Duarte Santos de65e1099a Merge pull request #28 from DuarteSantos8/dependabot/github_actions/actions-d8aa18c958 2026-07-31 19:30:56 +01:00
dependabot[bot] be2fb2dd1d Bump the actions group across 1 directory with 10 updates
Bumps the actions group with 10 updates in the / directory:

| Package | From | To |
| --- | --- | --- |
| [actions/checkout](https://github.com/actions/checkout) | `4` | `7` |
| [docker/setup-qemu-action](https://github.com/docker/setup-qemu-action) | `3` | `4` |
| [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action) | `3` | `4` |
| [docker/login-action](https://github.com/docker/login-action) | `3` | `4.5.2` |
| [docker/metadata-action](https://github.com/docker/metadata-action) | `5` | `6` |
| [docker/build-push-action](https://github.com/docker/build-push-action) | `6` | `7` |
| [actions/setup-node](https://github.com/actions/setup-node) | `4` | `7` |
| [actions/configure-pages](https://github.com/actions/configure-pages) | `5` | `6` |
| [actions/upload-pages-artifact](https://github.com/actions/upload-pages-artifact) | `3` | `5` |
| [actions/deploy-pages](https://github.com/actions/deploy-pages) | `4` | `5` |



Updates `actions/checkout` from 4 to 7
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v4...v7)

Updates `docker/setup-qemu-action` from 3 to 4
- [Release notes](https://github.com/docker/setup-qemu-action/releases)
- [Commits](https://github.com/docker/setup-qemu-action/compare/v3...v4)

Updates `docker/setup-buildx-action` from 3 to 4
- [Release notes](https://github.com/docker/setup-buildx-action/releases)
- [Commits](https://github.com/docker/setup-buildx-action/compare/v3...v4)

Updates `docker/login-action` from 3 to 4.5.2
- [Release notes](https://github.com/docker/login-action/releases)
- [Commits](https://github.com/docker/login-action/compare/v3...v4.5.2)

Updates `docker/metadata-action` from 5 to 6
- [Release notes](https://github.com/docker/metadata-action/releases)
- [Commits](https://github.com/docker/metadata-action/compare/v5...v6)

Updates `docker/build-push-action` from 6 to 7
- [Release notes](https://github.com/docker/build-push-action/releases)
- [Commits](https://github.com/docker/build-push-action/compare/v6...v7)

Updates `actions/setup-node` from 4 to 7
- [Release notes](https://github.com/actions/setup-node/releases)
- [Commits](https://github.com/actions/setup-node/compare/v4...v7)

Updates `actions/configure-pages` from 5 to 6
- [Release notes](https://github.com/actions/configure-pages/releases)
- [Commits](https://github.com/actions/configure-pages/compare/v5...v6)

Updates `actions/upload-pages-artifact` from 3 to 5
- [Release notes](https://github.com/actions/upload-pages-artifact/releases)
- [Commits](https://github.com/actions/upload-pages-artifact/compare/v3...v5)

Updates `actions/deploy-pages` from 4 to 5
- [Release notes](https://github.com/actions/deploy-pages/releases)
- [Commits](https://github.com/actions/deploy-pages/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: actions/configure-pages
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: actions/deploy-pages
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: actions/setup-node
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: actions/upload-pages-artifact
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: docker/build-push-action
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: docker/login-action
  dependency-version: 4.5.2
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: docker/metadata-action
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: docker/setup-buildx-action
  dependency-version: '4'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
- dependency-name: docker/setup-qemu-action
  dependency-version: '4'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-31 17:34:50 +00:00
Duarte Santos 611987545a Dependabot: don't chase Node majors that were never LTS
The first run offered node:22-alpine → 25-alpine in both Dockerfiles. Odd
majors are Current, not LTS, and stop getting fixes about six months in — for
an image other people self-host that trades stability for nothing. Even majors
are still proposed, so 22 → 24 will show up as a PR, which is the move actually
worth reviewing.
2026-07-31 19:32:57 +02:00
Duarte Santos accc3c1038 Sessions you can actually end, and invite codes worth guessing at
SECURITY.md documented three weaknesses two hours ago. Documented is better than
hidden; fixed is better than documented.

Sessions were a signed cookie the server trusted for a year, and /api/logout
only cleared it in the browser you clicked it in — a copy left on a shared
machine stayed good until it expired, and the only way to end it was deleting
./data/secret and signing out the entire instance. The cookie payload now
carries the user's session version, and POST /api/logout/all bumps it, which
kills every cookie that account ever had. Settings grows a "Sign out
everywhere" row for it.

Cookies already in the wild have no version field. They read as version 0 and
match a user who has never bumped, so nobody is signed out by this deploy and
db.json needs no migration — sv appears lazily on the first bump. Verified
against a server running the new code with a db.json shaped like the live one.

Session default drops from 365 days to 90, overridable with SESSION_DAYS. The
expiry is baked into each cookie when issued, so lowering it never cuts an
existing session short.

Invite codes go from 32 to 64 bits. The app has no rate limiting by design and
/api/register/options answers whether a code is valid, so the code itself has to
be the part not worth guessing. Existing codes still work — validation is an
exact string compare. Unused old ones are worth revoking and reissuing.

What did not change: no rate limiting, still the reverse proxy's job, still the
first caveat in SECURITY.md. requireUserVerification stays false — raising it
could refuse passkeys that already exist, which is a lockout, not a fix.
2026-07-31 19:32:57 +02:00
Duarte Santos 1574811af0 Wake-lock test: stop assigning to a global Node now owns
The first CI run found this, which is the point of having one. Node 21+ defines
globalThis.navigator itself as a getter with no setter, so `globalThis.navigator
= {...}` throws under ESM strict mode. This box runs Node 20, where the global
does not exist and the assignment is fine — the test has never failed locally
and never would.

Only the first test failed: its afterEach deletes the built-in accessor, so
every later test assigned cleanly against the hole it left. defineProperty works
on both runtimes.

Production images are node:22-alpine (web/Dockerfile, api/Dockerfile), so the
version CI runs is the right one and the test was what needed fixing.
2026-07-31 19:21:03 +02:00
Duarte Santos b45dbca2a6 Demo: rate the sets, so the demo shows the effort stats
The live demo is the shop window, and it was the one place the new Effort card
could not appear — demoSeed fabricated twelve weeks of training with no ratings
at all, so every chart that reads effort rendered empty or absent.

The seed now rates about 82% of finished sets, deterministically as before:
effort tracks position in the session and the block's progression, one deload
week sits well away from failure, the first three weeks are written in RPE as if
imported from another app, and one exercise stays unrated throughout so the
partial-coverage case is visible rather than theoretical. Only reps-mode sets
are rated — a reps-in-reserve number on a cardio set would be nonsense.
2026-07-31 19:12:18 +02:00
Duarte Santos 3a120df205 A security policy, and dependency updates that stay quiet
openGym ships passkeys, a signed session cookie and an admin dashboard, and
people run it on the open internet. Until now someone finding a hole had no
option but a public issue.

SECURITY.md documents the model as it actually is, verified against server.js
rather than described from memory: what the session cookie is and how long it
lasts, that it cannot be revoked individually, that ./data is unencrypted and
its holder can mint a session for any account, that there is no rate limiting,
and what changing RP_ID costs. A self-hoster deciding whether to run this for
other people deserves that list up front.

Dependabot is monthly and grouped one PR per ecosystem — a default setup on a
solo project produces noise that stops being read, which is the opposite of the
point. Android/iOS are left out on purpose: Capacitor pins those to the npm
packages, so bumping them separately breaks the mobile build.

Also: api/ has had two dependencies since notifications landed. CONTRIBUTING
still claimed one.
2026-07-31 19:12:18 +02:00
Duarte Santos 051a37abbf CI: actually run the tests, and hold the locales to one key set
There are 159 unit tests and nothing ran them. Both existing workflows fire on
push to main only, so the two outside pull requests merged so far were reviewed
by eye alone. This runs the suite, the build and a locale check on every pull
request.

The locale check exists because of a bug that shipped last week: a feature added
17 strings to de.js only, and the other ten languages fell back to English
mid-sentence with nothing failing anywhere. The checker compares every locale
against the union of all keys, so a string added to one file flags the other ten
instead of passing unnoticed.
2026-07-31 19:12:18 +02:00
Duarte Santos 8440cf3546 Changelog: the effort stats, under Unreleased
v1.2.3 is published, so this is the start of the next version rather than an
amendment to that one — it stays under Unreleased until there is a release to
fold it into.
2026-07-31 19:00:42 +02:00
Duarte Santos b0d176aba3 Merge branch 'effort-stats': the effort ratings, read back as statistics
Sets have carried an RIR/RPE rating since v1.2.3, but nothing ever read it
back — the number lived in the set label and nowhere else. This is the other
half: a trend per week, the spread across the scale, the share of sets taken
near failure, a hard-sets mode on the muscle map, and the rating riding along
on each exercise's own curve.
2026-07-31 18:49:41 +02:00
Duarte Santos 42ac8c8513 Send questions to Discussions, and put a Sponsor button on the repo
Discussions has been enabled since the start and empty since the start, so
every question arrives as an issue — the tracker is carrying design debates and
"how do I" alongside actual bugs, and the answers end up buried in closed
issues where the next person searching won't find them.

The "New issue" screen now offers Q&A, Ideas and Show-and-tell before the
templates, which is where that traffic gets intercepted; README and CONTRIBUTING
say the same thing in a table.

FUNDING.yml does nothing until the account is enrolled in GitHub Sponsors —
GitHub simply doesn't render the button. Stated plainly next to it: openGym is
AGPL, there is no paid tier and nothing is held back for sponsors. A project
that starts selling access to its maintainer stops being the thing people
starred.
2026-07-31 18:43:15 +02:00
Duarte Santos f232b5ba7e Effort stats: the other ten languages, and drop what nothing calls
The card shipped translated into German only, so every other UI language fell
back to the English source strings mid-sentence — the locale files have been
key-for-key identical until now, and they are again (607 each).

exerciseEffort() had no caller: Stats builds its per-exercise curve from the
points it already has, which are filtered by training mode, so the library
version would have drawn a different set of sessions. Removed with its tests
rather than left as a second answer to the same question.
2026-07-31 16:55:21 +02:00
Duarte Santos caaf61d91e Stats: read the effort back — trend, distribution, hard sets, per exercise
Rating a set only paid off inside the set label until now: Stats never looked at
rir/rpe at all. It reads them now, in four places.

lib/effort.js aggregates everything in RIR and converts back to whichever scale the
profile reads. A history that mixes the two — own logs in RIR, an imported file in
RPE — has to average as one series or every chart draws half the data, and RIR is the
internal unit because its zero is real where RPE's floor of 6 is a convention.

- an Effort card: average and share of sets taken near failure, the week-by-week curve
  with the week's volume in the tooltip, and where the sets land on the scale
- the muscle map gains a hard-sets mode: a muscle can lead on volume and still never
  be trained near failure
- Exercise progress carries effort on the top-set dots and as a curve of its own — the
  same weight with more left in the tank is progress a weight-only line draws flat
- LineChart learns an inverted axis (RIR counts down as it gets harder) and per-point marks

Every number carries how much of the training it speaks for: rating is optional and off
by default, so an unrated set is left out rather than read as failure, and an average
waits for five rated sets before it claims to be one.
2026-07-31 16:17:08 +02:00
Duarte Santos 4c829b6d1f Release v1.2.3: fold in the screen lock, the rest timer and the settings grouping
v1.2.3 was tagged but never published, so everything since v1.2.2 -- the last
published release -- belongs in this one version rather than a new number.

CHANGELOG gets the three new sections, README a feature bullet, SELF_HOSTING a note
that the Wake Lock API wants HTTPS (or localhost) like passkeys do and that iOS
refuses it in Low Power Mode. Website: the APK line said v1.2.2 while the download is
1.2.3, and the feature grid gained the screen-awake card.
2026-07-31 15:35:36 +02:00
Duarte Santos c5e131f81c Rest timer: take 15 seconds off, not only add them
addRest now accepts a negative step, and taking off more than is left finishes the
rest instead of counting into the negative -- which also kept a negative duration out
of the progress bar and out of the server-side push schedule.

Three controls and the clock do not fit one line on a phone: at 360px the bar was
left with about 30px and stopped saying anything. The rest variant stacks -- clock and
bar on top, controls beneath, -15 and +15 together in number-line order, Skip pushed
to the far edge so the button that ends the rest is not next to the one you tap to buy
more time. Scoped to #timer.rest, so the work timer keeps its single row. Back to one
line at >=1000px, and the card is nearly opaque now -- the set rows underneath were
reading through it.
2026-07-31 15:35:27 +02:00
Duarte Santos 248da53dca Keep the screen awake while a workout is running
Locking and unlocking the phone between every set was the worst part of logging on
one. Settings -> During a workout -> Keep screen awake, on by default; the lock is
held only while S.active exists, so it follows the workout rather than the route and
lets go when you finish.

The browser drops the lock whenever the document stops being visible, which is what
happens the moment you glance at a message, so wakelock.js keeps its own 'wanted'
intent and re-acquires on every visibilitychange. It also releases a sentinel that
arrives after a release landed mid-request, and swallows the rejection iOS gives in
Low Power Mode. Where the API is missing the row shows disabled instead of offering
a switch that does nothing.

Settings is regrouped by what each thing affects while the row needed a home:
General (language, units), During a workout (rest timer, keep awake, sounds, effort),
Notifications, Appearance, Data. Nothing removed, no setting changed meaning.
2026-07-31 15:35:18 +02:00
Duarte Santos 42d3659615 Release v1.2.3: effort per set, and the RPE your old app already had
Everything published since v1.2.2 is one number: the RIR column from #21 and
the RIR/RPE scale choice built on top of it, plus the importer reading the
RPE that Hevy and Strong export.

Changelog, README, roadmap and the website all describe the feature as it
actually shipped — a rating that is optional, keeps its scale per set, and
is deliberately not an input to progression or the 1RM estimate.

Android versionCode 4: it has to increase strictly or the APK will not
install over the v1.2.2 build already out there.
2026-07-31 00:16:43 +02:00
Duarte Santos ca917f0320 Merge branch 'effort-metric': effort per set (RIR / RPE)
Adds an optional per-set effort rating on either of the two scales people
actually use, generalising the RIR column from #21 rather than bolting a
second one next to it, and teaches the importer to read the RPE that Hevy
and Strong already export.
2026-07-31 00:14:51 +02:00
Duarte Santos 54fb14be13 Import: bring the RPE other apps already recorded
Hevy and Strong both write an RPE next to every set and the importer was
dropping the column, so a history imported from either arrived flatter than
the file it came from. It is read now, along with an RIR column if a file
happens to have one.

A blank cell stays unrated rather than becoming 0, and a written-out 0 is
only a rating on the RIR scale — RIR 0 is a set taken to failure, while RPE
runs 1-10, so an app writing 0 there means "nothing here" and reading it as
an effort would stamp one on every unrated set in the file. Ratings above
the scale are capped rather than thrown away, junk is ignored, and effort
only rides along on weighted rep sets — a treadmill row has nowhere to show
it. A file carrying both columns is read as RIR, the precedence setLabel
already reads them back with.

The import summary reports how many sets brought a rating, and says where
to switch the column on when the profile is not logging effort yet —
otherwise the ratings arrive invisibly and look like they were lost.

Export needed no change: the backup is the whole state serialised, so both
fields and the setting travel with it. There is a test pinning that now,
along with 11 for the import paths.
2026-07-30 23:59:01 +02:00
Duarte Santos 6905117352 Effort stepper: count up from the bottom of the scale
The first + on an empty cell jumped straight to a "typical working set"
(RIR 2 / RPE 8), skipping 0 and 1 with no way to see why. A stepper that
lands somewhere other than where counting would take you is just puzzling,
so it now starts at the bottom of the scale and walks up in even steps like
every other stepper in the app: RIR from 0, RPE from 6 — the scale is only
meaningful for working sets and anything lighter is a warm-up nobody rates.

Stepping back off the floor clears the cell again, so a mistap is undoable
instead of sticking at 0 — which on the RIR scale claims the set went to
failure. − on a cell that was never filled in still leaves it empty.

The stepping moved out of the view into stepEffort/capEffort in history.js,
where it can be tested: 16 new cases covering the scale walk, the floor and
ceiling, the clear-on-undershoot, half-step rounding, junk settings values,
the showRir overlay every load path performs, and a session's worth of
logging end to end.

A typed value is still only capped, never floored — clamping up would turn
the "1" of "10" into the floor and fight the input.

The help sheet no longer claims the highlighted row is where + starts; it is
where working sets usually land. Reworded in all 11 language packs.
2026-07-30 23:52:57 +02:00
Duarte Santos 0c6c22c04b Effort help: show the two scales as one table, (i) before the control
The sheet explained RIR and RPE in three paragraphs, which is a bad way to
say "these are the same judgement counted from opposite ends" — you had to
hold both sentences in your head to see the correspondence. A conversion
table shows it in one look: RIR and RPE in fixed tabular columns you can
read straight down, the feel in words next to them, and the row a working
set usually lands on highlighted in the accent.

The table is built from the same parts as the app's grouped lists (surface
fill, inset hairlines) instead of a real <table>, so it inherits the card
look and wraps on a narrow phone.

The (i) moves ahead of the segmented control: you reach the explanation on
the way to the choice rather than past it.

The three paragraph strings are replaced by the table's strings in all 11
language packs.
2026-07-30 23:42:21 +02:00
Duarte Santos 4e27461b7e Effort per set: RIR or RPE, whichever scale you think in
The RIR column becomes a three-way setting (Off / RIR / RPE). Both scales
measure the same judgement from opposite ends — RPE 8 is RIR 2 — so they
share one column and one stepper, but keep their own field on the set.

A set is never silently rewritten into the other scale: switching the
setting changes what new sets ask for, and old sets still read back with
the scale they were logged with.

Profiles carrying the old showRir boolean keep their column (effortOf
falls back to it until the new setting is chosen), so a backup or another
device that still has the flag does not lose the column.

The steppers now know the scale: the first + lands on a typical working
set (RIR 2 / RPE 8) instead of the end of the scale, and typed values are
capped at 10 — there is no RPE 12.
2026-07-30 23:35:47 +02:00
Duarte Santos fa978a1bb4 Merge PR #21: optional RIR column on reps-mode sets
octaviodimarco's RIR (reps in reserve) stepper for reps-mode sets, opt-in under
Settings → Units & timer, plus a fixup for the leftover RIR-0 stamp and the
header alignment.
2026-07-30 19:53:21 +02:00
Duarte Santos c08381e558 RIR: an unlogged RIR stays unlogged, and the header lines up
A set that never had an RIR could still end up carrying one: NumberField mapped an
empty field to 0 and the − button clamped to 0, so one stray tap stamped '(RIR 0)' —
went to failure — on the set for good, in history and in backups, with no way back.
An optional field now clears to null (the key is dropped), and stepping down from
empty leaves it empty. A typed 0 still logs a real 0.

The row's three-stepper sizing also has to reach the header, or the labels sit up
to 5px off the columns they name.
2026-07-30 19:53:14 +02:00
Octavio Di Marco c5172d0633 i18n: add RIR strings to all 11 language packs
t('RIR') and the new Settings toggle label had no entries in
src/locales/ — RIR itself is kept as the acronym across languages
(same treatment as 1RM), only the surrounding label text is translated.
2026-07-30 19:20:00 +02:00
Octavio Di Marco c3929b0a70 Remove RIR auto-check; gate the column behind a setting
Two blockers from review:

- NumberField.commit() fires onChange on every keystroke, so typing
  a decimal RIR (e.g. 1.5) committed the auto-check after the first
  character, before the value was finished — and the same auto-check
  turned a stray tap on an empty field's "−" (or clearing it) into a
  permanent "RIR 0", since 0 is indistinguishable from unset once the
  key exists on the set. Logging RIR is back to a plain field with no
  side effect; the checkbox is the only way to mark a set done, same
  as weight and reps.

- The RIR stepper narrowed every reps-mode row's +/- buttons for
  everyone, including the majority not running an RIR-based program.
  It's now behind a `showRir` setting (Settings → Units & timer,
  default off), so the existing row is untouched unless opted in.
2026-07-30 19:20:00 +02:00
Octavio Di Marco eb582e3c7b Auto-check a set when its RIR is logged
Logging RIR is naturally the last thing you do for a set — by the
time you're rating how many reps you had left, you've already
finished it. Editing the RIR field (typing or the +/- stepper) now
checks the set off itself, same beep/vibrate/rest-timer as tapping
the checkbox by hand, so that's one less tap per set.

Weight and reps are unaffected — those are often set before the set
is performed (pre-filled targets), so editing them shouldn't imply
it's done. Guarded by !s.done so re-editing RIR on an already-done
set (e.g. a correction) doesn't re-fire the toggle side effects.
2026-07-28 22:45:28 +02:00
Octavio Di Marco 6714b16e6a Add optional RIR (reps in reserve) to reps-mode sets
Adds a third stepper column, next to weight and reps, for logging RIR
on strength sets — not shown for cardio or timed holds, where it has
no meaning. RIR is purely a logging/display addition: it never
touches the progression engine (linear/Greyskull/double progression
only ever read weight/reps/seconds), and it round-trips through the
existing whole-object backup export/import with no code changes there.

The set object only gains an `rir` key once the user actually logs a
value (buildSets/addSet don't pre-seed it), matching how missing
fields already read as undefined elsewhere in the store — no schema
version or migration needed for existing logged workouts.

Fitting a third stepper next to weight+reps on narrow phones needed
the same treatment as the exercise-config sheet's three-steppers-in-a-row
(.cfgrow): narrower buttons and a smaller value font just for rows
that show RIR, verified by hand at 360-390px with edge-case values
(2-3 digit weight, double-digit reps, decimal RIR together).

"Last time" summaries now append "(RIR n)" when a set has one logged,
covered by new setLabel tests including the rir: 0 case (0 is a valid
RIR and must not be treated as absent).
2026-07-28 17:10:03 +02:00
Pengboi 6aaf2a3eea Comments: trim to the established cadence
The MCP code came in with 5–8 line file headers, JSDoc on every
one-line wrapper, and inline explanations that referenced the PR
itself ("so the MCP server can reuse it") — none of which matches
api/server.js or frontend/src/lib/, where comments are one-line,
fact-shaped and never mention the change that introduced them.

Trimmed across mcp/src/*.js, i18n-core.js, i18n.js, exercises.js,
format.js, mcp/test/tools.test.js, mcp/vitest.config.js and
mcp/README.md. Tool prefaces lost their numbers; duplicate fs.watch
rationale folded into one; the ASCII import diagram in the README
replaced with a paragraph; the cross-references and self-references
removed. Also fixed two real defects: a corrupted Cyrillic word in a
state.js comment and a missing space in a tools.test.js comment.

No code changes; 92 frontend + 32 MCP tests still pass.
2026-07-26 19:47:52 +01:00
Pengboi 4143ab8676 Tests: Stryker mutation testing on the MCP handlers
Adds Stryker 9.6.1 as a devDep and a .stryker.conf.json scoped to the three MCP-only
modules (src/state.js, src/labels.js, src/tools.js). The reused pure lib in
frontend/src/lib/ is deliberately excluded — it has its own 92-test vitest suite, and
mutating it here would just re-test it under a different label.

Two non-obvious config choices, both learned the hard way:
 · inPlace: true. Stryker's default copies the project to a sandbox, but the MCP test
   file imports "../../frontend/src/lib/*.js" — a relative path that breaks the moment
   the source is moved. inPlace mutates files where they live, keeps a backup in
   .stryker-tmp/backup-*/ during the run, and restores on exit. Verified: after the
   run, `git diff` shows no changes and all 92+32 tests still pass.
 · vitest.related: false. The vitest runner's related-files mode uses static import
   analysis to pick which tests to run per mutant; it can't see the cross-directory
   imports and reported "no tests were found". Disabling it means every mutant runs
   the full suite — slower (~54s for 847 mutants) but accurate.

Baseline first run: 39.32% mutation score (333 killed, 330 survived, 184 no-coverage).
Most of the survivors are zod schema string literals (the unit suite bypasses the SDK's
validation by calling handlers directly), and the bulk of the no-coverage debt lives in
state.js — file watching, multi-user resolution and the mtime fallback paths. The HTML
report at mcp/reports/mutation/mutation.html (gitignored, regenerated per run) shows
each survived mutant inline.

Run with `npm run mutation:test` from mcp/.
2026-07-26 19:34:15 +01:00
Pengboi 92914dea43 MCP: read-only stdio server for LLM apps to query workout history
A Model Context Protocol bridge that lets an external LLM application (Claude Desktop,
Cursor, Cline, Continue, …) read a user's openGym profile directly from ./data — no new
container, no extra auth, no third-party service. The LLM client spawns the server
locally as a stdio process (per the official MCP model); reads the same state-<uid>.json
the api server writes; reuses the pure training helpers from frontend/src/lib/*.js so
the numbers it answers with match what the Stats screen shows exactly.

Eight tools in v1, all read-only:
 · list_routines, get_routine — names + exercise counts + per-exercise targets
 · get_week_plan — Mo/We/Fr assignments and today's routine, accounting for any
   date-specific overrides (a "rest" override cancels the day)
 · list_workouts, get_workout — newest-first session summaries + per-set breakdown
 · get_bodyweight — weigh-ins with the goal line and signed deltas vs goal
 · estimate_1rm — Epley/Brzycki/Lombardi formulas, all-time best + trend per exercise,
   or a PR table across all reps-mode exercises
 · muscle_balance — which muscles are trained vs neglected over a week/month/all window

State is read with fs.watch (mtime fallback for platforms where watchers are flaky) so
the server reflects a session the web UI just finished without a restart. No passkey
material, VAPID keys, or session secrets ever cross the boundary — handlers only ever
serialize fields from the state object plus the user's name from db.json.

The MCP server has exactly one runtime dependency beyond the SDK: none. zod is the SDK's
transitive; vitest and Stryker are devDeps only. Tests run against the demo seed fixture
(demoSeed.js) — 32 cases pinning the JSON shape and the most user-facing edge cases
(empty state, missing routine, rest-day override, zero-workout muscle_balance, three
1RM formulas, superset links, timed/cardio set labels).
2026-07-26 19:34:09 +01:00
Pengboi fadeb17b6c i18n: split the pure core out so the lib is Node-loadable
The pure training helpers (history, progression, onerm, muscles, format, exercises) are
deliberately self-contained — that is what lets them ship with their own vitest suites and
got them reused across the React and mobile builds. They were one Vite-only call away from
being loadable from plain Node too: `import.meta.glob` for the lazy locale packs, run at the
top of i18n.js. Anything that imported `t` or `dateLocale` via the chain (i.e. every helper
in src/lib) inherited the dependency.

Splitting the runtime-agnostic state, constants and readers (t, dateLocale, instrFor, getLang,
LANGS, INSTR_LANGS, DATE_LOCALES) into i18n-core.js lets plain Node require them. i18n.js
keeps the Vite-only bits (the async setLang that lazy-loads locale packs via import.meta.glob
and the React subscription hook useLang) and re-exports everything from core, so none of the
23 existing import sites change.

exercises.js had one direct `import.meta.env` access for IMG_BASE/GIF_BASE — guarded with
`?.` so the module resolves without Vite present. format.js and exercises.js import i18n-core
directly; everything else still imports i18n.js.

No public exports changed. 92/92 vitest tests pass; vite build still code-splits the locale
packs the same way.
2026-07-26 19:34:01 +01:00
Duarte Santos ab0c98ba85 Android: versionCode 3 for the v1.2.2 APK
Same versionName — v1.2.2 was never published, so this is still that release — but the code
has to increase strictly or Android refuses to install over the build already out there.
2026-07-25 15:05:12 +02:00
Duarte Santos b15f7d9ec4 Release v1.2.2: docs, changelog and website for everything since v1.2.1
v1.2.2 was tagged but never published, so by the versioning rule everything since the last
published release — v1.2.1 — belongs in this one number: the mobile app, the importer, plan
sharing, the QA fix series, and now timed sets, progression rules and estimated 1RM.

The changelog was missing plan sharing and the fix series entirely; both are written up
here rather than left to the git log.
2026-07-25 15:00:43 +02:00
Duarte Santos 5c846b92d5 i18n: the new strings in all 11 language packs
49 keys per pack, 572 in total. The progression rules explain themselves in prose, so most
of these are full sentences rather than labels — a rule you cannot read is one you will
not trust, in any language.
2026-07-25 14:58:48 +02:00
Duarte Santos c248ca3bae The screens for timed sets, progression and estimated 1RM (#16 #17 #18)
Where the three features surface:

 · Routine editor — a progression rule for the whole routine, and per exercise a
   Reps/Time switch, an optional rule of its own and the step it moves in.
 · Workout — timed sets get a start button and the work-timer bar; every exercise says in
   one line why its target is what it is ("every rep last time — 2.5 kg more", "missed
   reps 3 sessions running — reset to 55 kg"). The weights are already right when the
   session opens rather than being suggested afterwards, which is what the old bump-hint
   button did.
 · Stats — the exercise curve switches between top set and estimated 1RM, and names the
   set the estimate came from. Timed exercises chart the longest hold.
 · Exercise detail — an estimated 1RM from your log plus a calculator for a set you have
   not done yet, so the number is reachable before there is any history.
 · Finish summary — a new best estimated 1RM is reported separately from a weight PR.
   Same weight for more reps is progress, but it is not a heavier lift.

Saving an exercise now replaces its config rather than merging into it, so switching back
from time to reps cannot leave a stale duration behind.
2026-07-25 14:58:42 +02:00
Duarte Santos 8e1d3b96a6 Automatic progression: named rules instead of one hard-coded hint (#17)
The old rule was a single line: all reps done, suggest 2.5 kg more. No rep ranges, no
AMRAP, no idea what to do after a bad session. This replaces it with a small set of
policies — linear, Greyskull LP, double progression, and adding time for timed work —
picked per routine and overridable per exercise.

Every function is pure and derives the next target from the log each time it is needed.
Nothing is written back into a finished workout and no counters are stored, so correcting
a mistyped set immediately produces the right next target.

Reading a session honestly is the whole point. Short reps count as a miss even when the
set was checked off; an unchecked set counts as a miss because it was not performed. A
session that fell apart can never advance the load as though it had succeeded.

Two cases the naive version gets badly wrong, both found against real data:

 · Workouts only started recording their prescription in this version. Judged against
   nothing, every past session scores as a miss — the demo history produced "missed reps
   11 sessions running, deload", and every existing user would have been greeted with the
   same on their first session after updating. Targetless history is judged against the
   exercise's current plan instead, which is what the old hint compared against.

 · Bodyweight work has no load to take off. "Reset your push-ups to 2.5 kg" is not advice,
   so with no external weight the rules progress in reps and leave the load alone.
2026-07-25 14:58:31 +02:00
Duarte Santos ec46c7e20d An exercise can be logged by time instead of reps (#16)
Until now the logging model came from the body part alone: cardio meant duration, and
everything else meant weight × reps. A plank, a hang, a wall sit or a loaded carry could
only be timed by filing it under cardio, which then put it in the wrong charts.

A routine entry can now say so itself — reps, time or cardio. Entries without a mode keep
behaving exactly as before, so every existing plan, workout and shared plan file is read
unchanged and nothing needs migrating.

Timed sets get a work timer that counts the set itself, kept deliberately separate from
the rest timer: the two mean opposite things and must never run together. Finishing early
logs the time actually held, not the target, because crediting a full 45 seconds for a
38-second hold would quietly corrupt the log it exists to keep.

Finished workouts now also store what the session prescribed. Without it, history cannot
say whether a session hit its reps, and a timed session reads back as "0 reps".
2026-07-25 14:58:20 +02:00
Duarte Santos a54bad2641 Estimated 1RM: the calculation, and only from sets that can support it (#18)
Working out how strong a set was meant leaving the app. Epley by default, with Brzycki
and Lombardi available and documented.

Two things it deliberately refuses to do:
 · guess above 12 reps, where the formulas disagree by double digits and the answer says
   more about work capacity than about maximal strength;
 · read `topW`, the working weight you confirm after an exercise — it carries no rep
   count, so it cannot produce an estimate at all.

It also knows nothing about the exercise database. An estimate needs a weight AND reps,
and only reps-mode sets carry both, so cardio and timed sets drop out of every scan on
their own rather than through a type check that would need keeping in sync.
2026-07-25 14:58:10 +02:00
Duarte Santos 0818f1b32b Tests: a runner for the pure helpers
The logic that decides what you lift next has no business being verified by hand in a
browser. Vitest is a dev dependency only — the app itself stays dependency-free.
2026-07-25 14:58:01 +02:00
Duarte Santos 62a0b00fbb i18n: the new strings in all 11 language packs
Twelve keys for the plan-import notice, the mixed-unit warning, the
singular counts, the weigh-in button and the error boundary, anchored
next to the strings they belong with. Drops 'Skip today' and
'{0} routines · {1} exercises', which the code no longer uses, and
retunes the German streak line ('13 Wochen in Folge').

All packs stay at the same key count.
2026-07-24 23:45:43 +02:00
Duarte Santos 827c0f8505 UI fixes found while testing the workout flow
· The rest timer floats above the tab bar, so it covered the set rows
  underneath it — during a rest, the next set was behind the bar. The page
  now gets enough bottom padding while a rest runs to scroll clear of it.
· "Skip today", sitting right under "Save & start workout", reads like
  skipping the session rather than the weigh-in. It says "Start without
  weighing in".
· The calendar legend drew "Planned" in blue while planned days have
  always had a grey dot.
· Body weight showed "− 0" when it hadn't moved since the last weigh-in.
· In a superset both exercises are on screen at once, so their animations
  give way: 180px meant scrolling a full screen between two exercises you
  are meant to alternate.
2026-07-24 23:45:36 +02:00
Duarte Santos 43d5495007 Import from other apps: convert weights per row, not per file
The unit was decided once for the whole file: if any row said lb and none
said kg it converted, otherwise it did nothing. FitNotes writes the unit
next to every set, so a history recorded partly in pounds and partly in
kilos hit the 'otherwise' branch — the file was taken over unconverted
and "185 lb" was logged as 185 kg, while the summary claimed the file
does not say which unit it uses.

Each row now carries its own unit through to the conversion (falling back
to the file's, then to the profile's), and a mixed file says so in the
preview.

Also: the "exercises matched" tile counted matched rows, so three
exercises across five sets read as five. It counts distinct exercises
now, which is what the label says.
2026-07-24 23:45:17 +02:00
Duarte Santos 3d5b00cecd A shared plan file can no longer take the app down
Importing a plan whose exercise ids this build doesn't know — a
hand-edited file, an export from a build with a different dataset — put
those ids straight into a routine. The routine editor skipped them
silently (you could neither see nor delete them), and starting the
routine reached for ex.n on undefined: white screen, no tab bar, no way
back. The running workout is persisted, so it came back on every reload.

Three layers, so this class of bug can't reach the screen again:

  · parsePlan() drops ids that resolve to neither the library nor a
    custom exercise carried in the same file, and the import sheet says
    how many were left out.
  · exOr() renders an unresolvable id as a placeholder, so the routine
    editor shows it (and lets you remove it) instead of hiding it, and
    the workout view survives one.
  · an ErrorBoundary around the routes: it keeps the tab bar alive,
    offers a reload, and can discard a running workout that can't be
    drawn. It is keyed on the route, so switching tabs clears it.

Turning the schedule switch on now really replaces Mon–Sun, as the
switch has always claimed. It only wrote the days the shared plan filled,
so days it left empty kept your own routine and you silently ended up
training a mix of two plans.

Also here, because they sit in the same lines: the tags that carry a unit
or a whole sentence opt out of the capitalise rule ("Best: 85 Kg", "Last
Time You Hit All Reps"), and the workout header's "best" now includes the
working weight you confirmed, so it agrees with the sheet that asked for
it.
2026-07-24 23:45:04 +02:00
Duarte Santos c8a68e37e1 Numbers follow the UI language, volume stays in your own unit
fmtNum was pinned to en-CH, so every user in every one of the twelve
languages got Swiss apostrophes: "7'535 kg". It now uses the same locale
as the dates.

fmtVol turned anything over 10 000 into tonnes regardless of the profile's
unit — "18.8t" is meaningless for a pound profile, and inside one history
list "18.8t" next to "7'535 kg" is two numbers you can't compare. Volume
is now always shown in the unit you train in.

The weight slider's ceiling of 300 was a kg number applied to both units;
in pounds it cut off at 136 kg, below plenty of people's body weight and
well below an everyday squat. It now follows the unit.

Also: a shared exCount() so "1 exercises" reads "1 exercise", and
durPart() so imported workouts (which carry no clock) stop claiming
"0 min".
2026-07-24 23:44:20 +02:00
Duarte Santos 238b435c2b i18n: translate plan-sharing strings into all 11 languages
24 new plan-share/PDF strings added to every locale pack (513 keys each),
anchored on each pack's existing terms (routine/exercise/import/week).
2026-07-24 01:22:09 +02:00
Duarte Santos af9289dcd9 Plan sharing: export/import a plan file + printable PDF
New "Share your plan" action in the Plan header (lib/plan-share.js):
- Export plan file: a small JSON with just your routines, the week schedule and any
  custom exercises they use — a friend imports it into their own openGym. Import
  merges (adds routines with fresh ids, dedupes customs by name+body part, optional
  "use this schedule"), so nothing they already have is overwritten.
- Print / Save as PDF: a clean, one-page-per-plan printout rendered in a hidden
  iframe; break-inside:avoid keeps every exercise (and each routine that fits) whole,
  so an exercise never splits across a page.
2026-07-24 01:12:07 +02:00
Duarte Santos 211fb86480 Icons: full-strength glyphs in the routine icon picker
The pickable routine icons were painted at --label-2 (60%), so the whole picker
looked faded when creating/editing a routine. Bring them to full --label; the
selected cell stays accent-on-accent.
2026-07-23 23:28:47 +02:00
Duarte Santos 6f557399b1 Icons: render at full strength everywhere, drop the muted-grey chrome
Follow-up to the opacity removal: the remaining faded icons were muted by colour,
not opacity. Bring list chevrons (.chev) and row icons (.lrow-c) from --label-3 up
to full --label, and lift the empty-state icon to its caption strength (--label-2).
Semantic colours (accent/orange/yellow/green) are left untouched.
2026-07-23 23:23:43 +02:00
Duarte Santos 17c2324f74 Icons: drop the opacity fade on tab-bar and tile icons
The .3/.32 opacity made those icons look washed-out/see-through. Remove it; the
active/inactive tab distinction still reads via colour (label vs accent) and the
heavier stroke on the active tab.
2026-07-23 23:12:49 +02:00
Duarte Santos 41f17934a9 Icons: redraw abs and pullup so strokes stop crossing through each other
The hollow line icons showed overlapping strokes through their transparency:
- abs drew full-width crease lines through a full-height centre line (a see-through #);
  now a six-pack whose centre seam runs the gap between crease pairs, no crossings.
- pullup's head circle sat on the arm-V apex; lifted it clear so the body no longer
  reads as tangled lines behind a transparent head.
2026-07-23 23:08:50 +02:00
Duarte Santos df91727dcf Website: milestones timeline builds itself from published GitHub releases
No more hand-maintained history on the about page — site.js renders one
timeline entry per published release (title, date, first paragraph of
the notes, link). Static entries remain only as an offline fallback.
2026-07-23 15:58:06 +02:00
Duarte Santos ae399cd1dd Website: fix screenshot aspect ratio, embed the live demo, GitHub button in hero
The screenshot img tags carry width/height attributes; with only a CSS
width the height attribute won (240x2532 — stretched). height:auto fixes
it. New #demo section runs the GitHub-Pages demo in a phone frame right
on the page; nav gets a Demo link and the hero a GitHub star button.
2026-07-23 15:54:25 +02:00
Duarte Santos becd2357ff Project website + one icon everywhere
website/ holds the source of opengym.duarte-santos.ch — landing with live
GitHub stats, docs and the story behind the app; no build step. The
native app icons are now generated (capacitor-assets) from the same
blocky dumbbell as the PWA icon, traced into resources/icon.svg, so the
APK, home-screen PWA, and website favicon all match.
2026-07-23 15:49:21 +02:00
Duarte Santos 768dee50ca Release v1.2.2: history import, standalone mobile app, APK distribution
Consolidates everything since v1.2.1: the FitNotes/Strong/Hevy/Apple
Health importer, the Capacitor-based standalone mobile flavor, and the
store-free distribution story — signed Android APK from
opengym.duarte-santos.ch, docs corrected to match (no store listings;
iOS via self-hosted PWA or Xcode free signing).
2026-07-23 15:36:05 +02:00
Duarte Santos 4888fed0c4 Android: version 1.2.1 in the app manifest 2026-07-23 15:28:06 +02:00
Duarte Santos ee2be743b0 Standalone mobile app: Capacitor shells for iOS and Android
A second flavor of openGym (VITE_MOBILE=1) that runs entirely on the
phone: no account, no server, no sync. State is mirrored into a file in
the app's private storage (survives WebView storage eviction), the
workout-day reminder is a native local notification scheduled on planned
weekdays, and backups export through the OS share sheet. Exercise media
loads from the same CDN as the demo build. npm run build:mobile, then
Android Studio / Xcode — see docs/MOBILE.md. NOTICE.md gains an AGPL §7
app-store exception.
2026-07-23 15:14:36 +02:00
Duarte Santos 389315625c Import history from FitNotes, Strong, Hevy and Apple Health
Losing years of logging is the thing that stops people trying another
tracker, so Settings -> Data -> Import from another app now reads their
exports directly.

All of these ship the same thing in a different dialect: one row per set
with a date, an exercise name and some mix of weight/reps/distance/time.
So the parser builds a column map from the header rather than assuming
positions, and a new app is usually a few header aliases. Verified
against real exports from Strong (1903 sets) and Hevy, both FitNotes
column layouts, and an Apple Health body-mass extract.

Exercise matching is the part that decides whether this is useful.
Parenthetical qualifiers and BB/DB shorthand are normalised, names are
compared as an order-independent bag of words, and a curated table maps
the plain names people actually log onto the dataset's qualified ones -
without it, 'Squat' resolved to 'weighted squat' and 'Leg Press' to
'smith leg press'. Where a name stays genuinely ambiguous it is left
unmatched and becomes a custom exercise rather than guessed at: filing
years of training under the wrong lift is worse than a name the user can
see and fix. Nothing in the file is ever dropped.

A summary sheet shows workouts, sets, matches, misses and any unit
conversion before anything is written, and merging skips days that
already have data, so importing twice - or from two apps - never
duplicates a workout.
2026-07-23 14:50:36 +02:00
Duarte Santos fac45f9af9 Release v1.2.1: muscle map and live demo
Consolidates everything since v1.2.0 into one version: the muscle map
(Stats balance card, routine preview, finish screen, male/female body
diagram), the browser-only GitHub Pages demo, and the fix for the blank
screen when finishing a workout from its last exercise.

api/package.json tracks the release alongside the frontend.
2026-07-23 12:56:52 +02:00
Duarte Santos cd77cfdd84 Muscle map: see which muscles your training actually reaches
A front-and-back body diagram, shaded with the same accent ramp as the
activity heatmap, in three places: Stats gets a Muscle balance card over
a week / 30d / 90d / all-time window, the routine editor previews what a
session hits while you build it, and the finish screen shows what you
just trained. Settings switches between a male and female figure.

The Stats card's real job is the list underneath: the muscles that got
nothing in the period. Load is counted in effective sets — full weight
for an exercise's target muscle, partial for its supporting ones — not
kilograms, since 100 kg of leg press and 12 kg of lateral raise say
nothing about which muscle worked harder. Shading is relative within the
window, so it always reads as a balance rather than an absolute.

The dataset spells muscles inconsistently ('delts', 'deltoids' and
'shoulders' are one muscle); all 50 spellings it uses are normalised onto
the 18 the diagram draws, verified against the full catalogue so nothing
is dropped silently. Custom exercises fall back to their body part.

Geometry is converted from MuscleMap (MIT, see NOTICE.md), which ships
its paths as Swift source rather than .svg. At ~90 kB it is imported
dynamically, so the initial bundle is unchanged.

Also fixes a crash this surfaced but did not cause: finishing a workout
from its last exercise blanked the whole app, because the per-exercise
weight sheet read the running workout without checking it was still
there and finishing clears it while that sheet is on screen.
2026-07-23 12:51:24 +02:00
Duarte Santos e9bf38f39b Publish a browser-only demo to GitHub Pages
Self-hosting is a fair ask once someone knows they want the app, but it's a lot
to ask of someone deciding whether to look at it at all. A demo build (VITE_DEMO=1)
drops the parts that need the backend — passkeys, sync, admin — and boots straight
into guest mode with a seeded example profile, so every screen has real data behind
it: twelve weeks of Push/Pull/Legs with progression and the odd missed session,
twice-weekly weigh-ins trending toward a goal, PRs, and today's session moved onto
the current day so there's always something to press Start on.

The seed generator is imported dynamically and the demo-only UI folds away at build
time, so none of it lands in the bundle self-hosters ship. Exercise media (~140 MB)
isn't committed anywhere, so the demo build points VITE_IMG_BASE / VITE_GIF_BASE at
the upstream dataset on jsDelivr, pinned to a commit; unset, both still resolve to
img/ and gif/ next to the app exactly as before.

Deployed by a Pages workflow on every push to main.
2026-07-23 12:42:40 +02:00
Duarte Santos 3c5bcd5957 Refresh README, self-hosting docs and dependencies for v1.2.0
Screenshots were still from the old design — all five regenerated from a
seeded three-month history.

The feature list had been behind since v1.1.0: push notifications and the
workout-day reminder were never listed, nor were custom exercises, the
equipment filter or the admin dashboard. ADMIN_UIDS and INVITE_ONLY were
documented in .env.example but missing from the README config table, and
docs/SELF_HOSTING.md still claimed there was no admin/invite system by
design — it now explains how to turn one on.

api/package.json version was lagging at 1.1.1; it tracks the release now.
React and @vitejs/plugin-react picked up their patch releases (lockfile
only, no manifest change); api dependencies were already current and both
trees audit clean.
2026-07-23 12:07:10 +02:00
Duarte Santos b28a58930c Release v1.2.0: complete visual redesign
Rebuilt design system (one type scale, neutral surface ramp, hairline
separators), a 77-icon hand-drawn set replacing every emoji in the UI,
grouped routine-icon picker with the old emoji mapped forward, new tab
bar with a raised Start/Resume button, and a reorganised Home.

Chart fixes that came out of it: axis labels, gridlines and the target
line were painted with colour variables the new sheet no longer defines
and fell back to black-on-black; the hover readout is now placed from
its measured size so it can't be clipped at the edges, and it clears
when the pointer leaves the chart.
2026-07-23 11:55:52 +02:00
Duarte Santos fc36476a5f Release v1.1.3: consolidate all work since v1.1.2
v1.1.2 is the last published release; v1.1.3 and v1.1.4 were tagged but
never released. Collapse those two plus the equipment filter and the rest
timer fix into a single v1.1.3 changelog section, grouped into 'Admin
dashboard' and 'Exercises & workout'. Set frontend/package.json to 1.1.3.

Covers #12, the admin dashboard (phases 1+2), #6 and #14.
2026-07-22 14:52:32 +02:00
Duarte Santos fbf125f6a2 Filter exercises by equipment (#6)
Adds an equipment filter row under the body-part chips, in both the
Exercises library and the exercise picker sheet.

The options are derived from the exercises already matching the current
body part and search, ordered most-common-first, so the row stays short
instead of listing all 28 equipment values (many with a single exercise)
and every combination on screen has results behind it. The row hides
itself when there is nothing to choose between.

Changing the body part clears the equipment filter; a search that
narrows the chosen equipment away drops it rather than showing an empty
list. All equipment terms were already localized — only the new 'Any
equipment' label needed adding across the 11 locale packs.

Closes #6
2026-07-22 14:44:27 +02:00
Duarte Santos 33317dac91 Fix rest timer freezing at 0:01 (#14)
The tick callback shadowed the imported i18n helper `t` with the timer
object, so the final tick threw a TypeError on t('Rest over — next set!')
before reaching stopRest(). The interval kept running and re-throwing, the
display stayed on the last value it wrote, and the pending server-side
'rest over' push was never cancelled.

Closes #14
2026-07-22 14:44:15 +02:00
Duarte Santos f3ba05aece Admin dashboard (phase 2): live 'training now' heartbeat + release v1.1.4
Backend: in-memory presence map + POST /api/activity heartbeat (authed);
each /api/admin/users row carries a fresh 'live' snapshot (routine,
exercise x/y, sets done/total, started-at) with a ~70s TTL. Disabling a
user clears their presence immediately.

Frontend: the workout screen pings /api/activity every 20s (signed-in
only) and sends a leave signal on unmount (fetch + sendBeacon). The
dashboard gains a 'Training now' section and live markers, auto-
refreshing every 15s.

Cuts the complete admin-dashboard feature (phases 1+2) as v1.1.4.
2026-07-22 02:06:19 +02:00
Duarte Santos 046217079c Admin dashboard (phase 1): users, disable, invite-gated signup
Adds an operator dashboard for self-hosters, gated on a passkey-
authenticated admin flag (ADMIN_UIDS env) and enforced server-side.

Backend:
- ADMIN_UIDS / INVITE_ONLY env (both off by default, OSS-friendly).
- Invite codes in db.json; /api/register gated when INVITE_ONLY, code
  burned on successful signup.
- disabled users are rejected by readSession — locked out everywhere.
- /api/admin/{users,user,user/disable,invites,invites/new,invites/revoke}
  behind an admin guard; /api/config exposes invite_only to the login UI.
- admin flag surfaced on /api/me, register/verify, login/verify.

Frontend:
- New /admin route + Settings link, shown only to admins: user list with
  workout counts and last-sync, disable/enable, invite generation, and a
  per-user workout-history drill-down.
- Registration sheet shows an invite-code field when the instance is
  invite-only.

Phase 2 (live 'training now' via a heartbeat) is separate.
2026-07-22 01:58:33 +02:00
Duarte Santos dabffdebc0 Minimize the exercise animation during a workout (#12)
Adds a persistent minimize/expand toggle to the workout animation so the
set rows are reachable without scrolling past a full-height GIF. A new
S.gifSize setting ('full' | 'mini') is flipped by the button, saved and
synced like other prefs, and applied across exercises and future
workouts. Tapping the animation still pauses/plays it.

Closes #12
2026-07-22 01:00:50 +02:00
Duarte Santos 785380ab1b Release v1.1.2: consolidate all work since v1.1.1
Collapse the never-released intermediate versions (custom exercises,
localization, comma fix, narrow-phone fix) into a single v1.1.2 release.
Merge their changelog sections under one v1.1.2 heading and set the
package version to 1.1.2. The confusing v1.2.0 and v1.1.3 tags are
removed in favour of a clean v1.1.2.
2026-07-22 00:50:21 +02:00
Duarte Santos 91e0bd73b9 Release v1.1.3: custom exercises + comma decimal separator
Fold the custom-exercises feature (#11) and the comma-decimal fix (#13)
into a single v1.1.3 release. Merge their changelog sections and set the
package version to 1.1.3.
2026-07-22 00:38:24 +02:00
Duarte Santos a4f73e34d1 Custom exercises: optional description + reachable delete
Adds an optional free-text description to custom exercises, shown where
a built-in exercise shows its animation (detail + config sheets) and
included in exercise search.

Deleting was only reachable from the Exercises tab detail sheet, which
you never pass through when tapping an exercise inside a routine. The
routine's config sheet now offers "Edit or delete this exercise", and
its old "Remove exercise" button is relabelled "Remove from routine" so
removing from a routine and deleting for good are no longer confusable.

Refs #11
2026-07-22 00:34:27 +02:00
Duarte Santos 0cefcb3636 Custom exercises: create your own with name + body part
Users can add movements missing from the catalogue (issue #11) from the
exercise picker or the Exercises tab. Custom exercises live in synced
state (S.customEx) and are merged into the exercise index, so routines,
supersets, logging, PRs, stats and history all work unchanged. The
animation stays blank by design. Editable and deletable from the detail
sheet; deleting keeps logged history readable by stamping the name into
past entries. Translated into all 12 UI languages.

Closes #11
2026-07-22 00:26:16 +02:00
Duarte Santos 93bd4e3850 Renumber comma-fix release as v1.1.3 2026-07-22 00:11:26 +02:00
Duarte Santos 30fd3a84a1 Accept comma as decimal separator in numeric inputs
iOS decimal keyboards in many locales only offer a comma; type=number
inputs report an empty value for it, snapping the field to 0. Numeric
fields (weight, speed, etc.) are now text inputs with inputMode=decimal
backed by a shared NumField component that normalizes ',' to '.' and
keeps partial input like "33," alive while typing.

Fixes #13
2026-07-22 00:03:48 +02:00
Duarte Santos c05b0756ec Localization: 12 UI languages + exercise instructions in 10 (#7)
Adds a Language setting (Settings → Appearance) that translates the whole
app: a tiny dependency-free i18n layer (English source strings as keys,
per-language dictionaries in frontend/src/locales/) plus per-language
exercise-instruction packs generated from the upstream dataset
(frontend/src/instr/, via scripts/build-instructions.mjs).

UI: en, de, es, fr, it, pt, pl, tr, ru, zh, ko, hi. Instructions: all of
those except de/pt (not in the upstream dataset — fall back to English).
Body-part/equipment/muscle labels and date formats are localized too;
exercise names stay English (upstream limitation).

Everything is lazy-loaded per language (Vite code-splitting), so the
initial bundle is unchanged; the choice syncs with the profile like the
theme. Closes #7.
2026-07-21 21:45:24 +02:00
Duarte Santos b9f8d18bbd Fix exercise-config sheet overflowing on narrow phones (#10)
The Sets/Reps/Weight stepper row (and its cardio variant) used fixed-width
steppers that added up to ~445px — wider than an iPhone viewport — clipping
the Weight stepper off-screen and letting iOS Safari pan the whole page
sideways. Steppers in the config sheet now flex and shrink to fit, and
html/body clip horizontal overflow as a safety net.
2026-07-21 20:48:14 +02:00
Duarte Santos 42402cae0c Lower weight slider floor to 1kg, add +-1/+-0.5 quick-step buttons
20kg was too high a floor for light dumbbell work. Also added -1/-0.5/
+0.5/+1 chip buttons alongside the existing fine +-0.1 pair, so coarse
adjustments don't need dozens of taps.
2026-07-21 19:08:07 +02:00
Duarte Santos 9da4e5a219 Replace self-extending slider window with a fixed range
The auto-extend fix from the last commit traded one bug for another:
every time the window grew mid-drag, the whole range shifted, so a
value's position on the track would jump around unpredictably (e.g.
60kg sliding from the middle toward the far left just from dragging
to the far end and back). A window that resizes itself during
interaction can't be predictable by construction.

Fixed range (20-300kg) instead — coarser per-pixel precision, but the
thumb's position is now a pure function of value: no drift, no jumps,
ever. The +/- steppers still give exact fine control. Verified with a
repeatable test: a value's slider position is now identical before and
after dragging to both extremes.
2026-07-21 19:02:18 +02:00
Duarte Santos 32fc0071dc Fix weight slider capped at a frozen ±20kg window
WeightInput (used for body weight, goal weight, and per-exercise top
weight) computed its slider's min/max once from the initial value and
never revisited it — starting from a fresh 70kg default capped the
slider at 90kg with no way to drag past it, exactly the reported bug.

Widened the base window (±60) and made it self-extend when dragged or
stepped to either edge, instead of getting stuck there.
2026-07-21 18:57:14 +02:00
Duarte Santos f117101972 Add a remove-set button during a workout
There was + Add set but no way back down — some days you just want
fewer sets than planned. Mirrors Add set (removes the last row),
floored at 1 set per exercise so an entry can't go empty.
2026-07-21 18:49:30 +02:00
Duarte Santos fbc615aa26 Release v1.1.1 2026-07-21 12:48:12 +02:00
Duarte Santos e83d642e1b Remove push delivery latency disclaimer from Settings
Confirmed working reliably after the 10s check-interval + high-urgency
push fixes.
2026-07-21 12:45:57 +02:00
Duarte Santos 95c4b2b279 Add honest delivery-latency disclaimer under push notification settings
Web Push through Apple/Google isn't instant or guaranteed even with
high urgency — set the expectation up front instead of letting people
assume it's unreliable/broken when it lags.
2026-07-21 12:34:32 +02:00
Duarte Santos c5cf31e2ca Tighten reminder timing: 10s check interval + high-urgency push
Reminder loop only checked once a minute, unaligned to the minute
boundary, so it could sit up to 59s on the target time before noticing
- now capped at ~9s. Also mark pushes as urgency:'high', the one lever
we actually have over delivery speed (iOS/Android throttle low-urgency
background push harder under battery saving). Remaining delivery lag
after that is Apple/Google's own push relay scheduling, not something
we control from here.
2026-07-21 12:25:24 +02:00
Duarte Santos 10fa150d09 Flush pending state save immediately when tab backgrounds/closes
Settings changes (like the reminder time) were saved via a 1.5s
debounce; closing or switching away from the tab right after an edit
could kill that pending save before it reached the server, silently
losing the change. Now flushed on visibilitychange instead of relying
on the timer alone.

Also confirmed via a live server-side test (bypassing the client
entirely) that the reminder loop itself fires correctly — trimmed the
verbose per-tick debug log added for that test, kept the one for an
actual match.
2026-07-21 12:00:49 +02:00
Duarte Santos 5a7ce13ca2 Update docs: reminder timezone is now auto-detected per user, not a server env var 2026-07-21 11:47:26 +02:00
Duarte Santos 0ac531acb8 Fix workout reminder using the server's timezone instead of the user's
The reminder compared 'now' against a single TZ env var, so it only
worked correctly for whoever's local time happened to match the
server's. The browser now reports its own IANA timezone (auto-
detected, no picker) and stores it with the reminder; the server
computes each user's local time/date individually via Intl, and the
client re-stamps it on every app load so it follows you when you
travel.
2026-07-21 11:46:45 +02:00
Duarte Santos 7dea9ccfcc Log push send failures instead of swallowing them silently
sendPush caught every webpush.sendNotification error to clean up
expired subscriptions, but never logged anything for other failure
modes — made a delivery problem indistinguishable from 'nothing to
send' when debugging.
2026-07-21 11:42:40 +02:00
302 changed files with 53743 additions and 1151 deletions

No files matched your search

+103 -6
View File
@@ -19,12 +19,109 @@ RP_NAME=openGym
#
# (Point your proxy at the web container's WEB_PORT. See docs/SELF_HOSTING.md.)
# ── Admin dashboard & invite-only signup (optional) ────────────────────────
# Both off by default — a fresh instance has open signup and no admin.
#
# Make yourself an admin: register your own passkey profile first, find your
# user id in ./data/db.json ("users"[].id), then list it here (comma-separated
# for several admins). Admins get an "Admin dashboard" link in Settings to see
# users, disable accounts, generate invite codes and view workout history.
#
# ADMIN_UIDS=youruserid,anotheradmin
#
# Require an invite code to create new profiles (existing accounts keep working;
# generate the codes from the admin dashboard):
#
# INVITE_ONLY=1
#
# Remove the "Continue without account" button, so a profile is the only way in.
# Guest mode keeps everything in the browser and never touches this server, but
# on an instance meant for a known set of people it is still the wrong front
# door. Anyone already inside as a guest is signed out on their next visit; the
# data they made stays in that browser. Defaults to on (guests allowed):
#
# ALLOW_GUEST=0
# ── Activity log (optional) ────────────────────────────────────────────────
# The admin dashboard shows an activity log: who signed in, who tried and
# failed, and every admin action (disabling an account, creating or revoking an
# invite code). It lives in ./data/audit.log, one JSON object per line, so you
# can also just read it with `tail` or `jq`.
#
# It is ON by default. It records strictly less than this instance already
# holds — every profile is in db.json and every workout is in state-<uid>.json,
# both readable by any admin — and a log that ships switched off tells you
# nothing on the day you need it. Turn it off completely with:
#
# AUDIT_LOG=0
#
# Retention is a cap, not an archive. Whichever limit is reached first wins;
# set either to 0 to disable that limit:
#
# AUDIT_MAX=5000 # events kept
# AUDIT_DAYS=90 # days kept
#
# IP addresses are the one thing that is OFF unless you ask, because they are
# the only field here that says where somebody physically is. They are also the
# only way to tell one failed sign-in from twenty. Three settings:
#
# AUDIT_IP=off # default — no addresses at all
# AUDIT_IP=net # network only: 203.0.113.0/24, 2001:db8:1::/48
# AUDIT_IP=full # the whole address
#
# The address is read from CF-Connecting-IP, then the first entry of
# X-Forwarded-For, then X-Real-IP, and finally the connecting socket itself if
# none of those is present.
#
# A forwarded-for header is only worth anything if whatever sits in front
# OVERWRITES it instead of passing a client-supplied one through — otherwise a
# caller simply states the address it would like logged. The web container now
# overwrites X-Forwarded-For and X-Real-IP with the real peer, and DROPS
# CF-Connecting-IP, so the bundled stack records an address nobody can choose.
# (Before, X-Forwarded-For was appended to rather than replaced, and
# CF-Connecting-IP was passed straight through — both were forgeable.)
#
# Cloudflare is first in that list on purpose: a Cloudflare tunnel does not put
# the visitor in X-Forwarded-For at all, so that header would otherwise record
# the tunnel itself and look perfectly plausible. If — and only if — Cloudflare
# is genuinely in front of you, let its header through again:
#
# CF_CONNECTING_IP=$http_cf_connecting_ip
#
# That is safe there because Cloudflare sets the header itself, replacing
# anything the client sent. Anywhere else, leave it unset.
# ── Session length (optional) ──────────────────────────────────────────────
# How long a sign-in lasts, in days. Default 90 — long enough that people who
# train regularly never see a login screen, short enough that a stolen cookie
# doesn't stay good forever. Lower it for an instance on the open internet,
# raise it for a private one. Only affects new sign-ins; cookies already handed
# out keep the lifetime they were issued with. Users can end every session on
# every device themselves with "Sign out everywhere" in Settings.
#
# SESSION_DAYS=90
# ── Fitting into an existing stack (optional) ──────────────────────────────
# The defaults assume openGym is on its own: an API service called `api` on
# port 3000, and nginx listening on 80 inside the web container. If you are
# merging this into a compose file that already has an `api`, or you front the
# web container with your own reverse proxy, move them here. The web image
# renders its nginx config at start-up, so these apply to a prebuilt image and
# need no rebuild. BACKEND and PORT together are what /api is proxied to, so
# they must name a service the web container can reach on your network:
#
# NGINX_PORT=80
# BACKEND=api
# PORT=3000
# ── Notifications (optional) ───────────────────────────────────────────────
# Push works out of the box — VAPID keys are generated on first run and saved
# to ./data/vapid.json. The only thing worth setting yourself:
# Push works out of the box — nothing to set. VAPID keys are generated on first
# run and saved to ./data/vapid.json. Each user's browser reports its own
# timezone automatically, so the workout-day reminder fires at their local
# time regardless of where the server runs or where they're travelling.
#
# TZ=Europe/Zurich
# Push services want a contact address for whoever operates the server, in case
# they need to get in touch about your pushes. Defaults to your ORIGIN, which is
# fine; set a mailto: if you would rather they mailed you:
#
# Sets the container's timezone so the workout-day reminder fires at the time
# you actually pick, not UTC. Find your zone name at
# https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
# VAPID_SUBJECT=mailto:you@example.com
+60
View File
@@ -0,0 +1,60 @@
name: Bug report
description: Something in openGym is broken or not working as expected
labels: ["bug"]
body:
- type: textarea
id: what-happened
attributes:
label: What did you do?
description: Steps to reproduce, as precisely as you can.
placeholder: |
1. Go to '...'
2. Click on '...'
3. See error
validations:
required: true
- type: textarea
id: expected
attributes:
label: What did you expect to happen?
validations:
required: true
- type: textarea
id: actual
attributes:
label: What happened instead?
description: Include error messages, console output, or screenshots if you have them.
validations:
required: true
- type: dropdown
id: setup
attributes:
label: How are you running openGym?
options:
- Self-hosted (docker compose)
- Frontend dev server (npm run dev)
- Other / not sure
validations:
required: true
- type: input
id: environment
attributes:
label: Browser & OS
placeholder: e.g. Safari 17 on iOS 18, Chrome 126 on Android
validations:
required: true
- type: checkboxes
id: passkey
attributes:
label: Is this about login / passkeys?
description: >
Most login issues are an `RP_ID`/`ORIGIN` mismatch — check your `.env` against the
domain you're accessing openGym from before reporting. See the
[self-hosting guide](../../docs/SELF_HOSTING.md).
options:
- label: Yes, this is a login/passkey issue and I've already checked RP_ID/ORIGIN
+14
View File
@@ -0,0 +1,14 @@
# gitea.com has no Discussions, so questions and ideas are issues here — labelled, so they
# are not mistaken for agreed-on work. Blank issues stay off: the forms ask for the two
# things that otherwise cost a round-trip every time (how it is running, and RP_ID/ORIGIN).
blank_issues_enabled: false
contact_links:
- name: Self-hosting guide
url: https://gitea.com/DuarteSantos/openGym/src/branch/main/docs/SELF_HOSTING.md
about: Passkey login failing, reverse proxies, HTTPS, Docker — most login trouble is an RP_ID/ORIGIN mismatch and is answered here.
- name: Contributing guide
url: https://gitea.com/DuarteSantos/openGym/src/branch/main/CONTRIBUTING.md
about: Project layout, dev setup and guidelines before you open a PR.
- name: Changelog
url: https://gitea.com/DuarteSantos/openGym/src/branch/main/CHANGELOG.md
about: What changed in each release, newest first.
+29
View File
@@ -0,0 +1,29 @@
name: Feature request
description: Suggest an idea or improvement for openGym
labels: ["enhancement"]
body:
- type: textarea
id: problem
attributes:
label: What problem does this solve?
description: What are you trying to do that openGym doesn't support today?
validations:
required: true
- type: textarea
id: proposal
attributes:
label: Proposed approach
description: How would you like it to work? Rough ideas are fine.
validations:
required: true
- type: checkboxes
id: deps
attributes:
label: Dependencies
description: >
openGym is intentionally dependency-light — new packages (front or back) are a hard
sell. See [CONTRIBUTING.md](../../CONTRIBUTING.md).
options:
- label: This doesn't require adding a new dependency
+86
View File
@@ -0,0 +1,86 @@
# Publishes the two images to the gitea.com container registry, replacing GHCR.
#
# Images land at gitea.com/duartesantos/opengym-{api,web} and are what
# `docker compose pull` fetches.
#
# As on GitHub, a *published release* is the trigger, never a bare tag push: the
# versioning rule consolidates unreleased tags, and a deleted tag does not delete
# the image tags it already pushed — dependency bots then read the orphan as a
# newer series (that was issue #87 on the old repo).
#
# Needs one repository secret: PACKAGES_TOKEN — a gitea.com token with
# write:package scope (Settings → Applications → Generate New Token). The built-in
# token cannot write packages.
name: Publish Docker images
on:
push:
branches: [main]
release:
types: [published]
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
include:
- image: api
context: ./api
file: ./api/Dockerfile
- image: web
context: .
file: ./web/Dockerfile
steps:
- uses: actions/checkout@v4
- name: Lowercase owner (registry names must be lowercase)
id: repo
run: echo "owner=$(echo '${{ github.repository_owner }}' | tr '[:upper:]' '[:lower:]')" >> "$GITHUB_OUTPUT"
- name: Set version metadata
id: version_meta
run: |
# On a release the ref is refs/tags/vX.Y.Z; on a main push it is a branch ref,
# which would otherwise label the image "refs/heads/main".
case "$GITHUB_REF" in
refs/tags/*) VERSION="${GITHUB_REF#refs/tags/}" ;;
*) VERSION="main-${GITHUB_SHA::7}" ;;
esac
echo "VERSION=$VERSION" >> $GITHUB_OUTPUT
echo "VCS_REF=${GITHUB_SHA}" >> $GITHUB_OUTPUT
echo "BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> $GITHUB_OUTPUT
- uses: docker/setup-qemu-action@v3
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3
with:
registry: gitea.com
username: ${{ github.repository_owner }}
password: ${{ secrets.PACKAGES_TOKEN }}
- uses: docker/metadata-action@v5
id: meta
with:
images: gitea.com/${{ steps.repo.outputs.owner }}/opengym-${{ matrix.image }}
tags: |
type=raw,value=latest,enable={{is_default_branch}}
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
# No cache-from/to: the GHCR copy used type=gha, which is a GitHub-hosted
# service and is not there on gitea.com's runners.
- uses: docker/build-push-action@v6
with:
context: ${{ matrix.context }}
file: ${{ matrix.file }}
platforms: linux/amd64,linux/arm64
build-args: |
VERSION=${{ steps.version_meta.outputs.VERSION }}
VCS_REF=${{ steps.version_meta.outputs.VCS_REF }}
BUILD_DATE=${{ steps.version_meta.outputs.BUILD_DATE }}
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
+38
View File
@@ -0,0 +1,38 @@
# Same suite as .github/workflows/test.yml, run by gitea.com's Actions runners.
# The GitHub copy is kept for the day that account comes back; this one is what
# actually gates contributions today.
name: Tests
on:
pull_request:
paths:
- 'frontend/**'
- 'mcp/**'
- '.gitea/workflows/test.yml'
push:
branches: [main]
paths:
- 'frontend/**'
- 'mcp/**'
- '.gitea/workflows/test.yml'
workflow_dispatch:
concurrency:
group: test-${{ github.ref }}
cancel-in-progress: true
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# node:22-alpine in web/Dockerfile and api/Dockerfile — CI must match production.
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
cache-dependency-path: frontend/package-lock.json
- run: npm ci
working-directory: frontend
- run: npm test
working-directory: frontend
+5
View File
@@ -0,0 +1,5 @@
# Puts a "Sponsor" button on the repo header. The GitHub entry only works once the account is
# enrolled in GitHub Sponsors (github.com/sponsors — identity check, Stripe payout account and
# a tax form); until then the button is simply not shown.
github: DuarteSantos8
buy_me_a_coffee: duartesantos
+11 -2
View File
@@ -1,5 +1,14 @@
blank_issues_enabled: false
contact_links:
- name: Questions & contributing
- name: Question or self-hosting help
url: https://github.com/DuarteSantos8/openGym/discussions/categories/q-a
about: Login/passkey trouble, reverse proxies, Docker, "how do I…" — ask in Q&A, not in an issue.
- name: Idea or feature request to talk through
url: https://github.com/DuarteSantos8/openGym/discussions/categories/ideas
about: Not sure it belongs in the app yet? Float it in Ideas first — issues are for agreed work.
- name: Show your setup
url: https://github.com/DuarteSantos8/openGym/discussions/categories/show-and-tell
about: Running openGym somewhere interesting, or built something on top of it? Show it off.
- name: Contributing guide
url: https://github.com/DuarteSantos8/openGym/blob/main/CONTRIBUTING.md
about: Read the project layout, dev setup, and guidelines before opening an issue.
about: Project layout, dev setup and guidelines before you open a PR.
+102
View File
@@ -0,0 +1,102 @@
# Dependency updates, deliberately quiet.
#
# openGym is dependency-light on purpose: the frontend is React + Router + Zustand, and api/
# has two runtime dependencies. A default Dependabot setup would still open a PR per package
# per week, which on a solo project means the alerts stop being read — the opposite of what
# this is for. So: monthly, everything in an ecosystem grouped into a single PR, and a low
# cap on open PRs. Security advisories are unaffected by any of this; GitHub raises those
# regardless of schedule.
#
# Only manifests that actually exist here are listed. Deliberately NOT covered:
# - gradle (frontend/android) and cocoapods (frontend/ios) — Capacitor generates those shells
# and pins the native versions to the @capacitor/* npm packages. Bumping them independently
# desyncs the two and breaks the mobile build; they follow the npm update instead.
version: 2
updates:
# Frontend app — frontend/package.json
- package-ecosystem: npm
directory: /frontend
schedule:
interval: monthly
open-pull-requests-limit: 3
groups:
# Routine bumps arrive as one PR. Runtime and build tooling move together anyway (a Vite
# bump usually wants its plugin bumped), and splitting them doubles the review without
# splitting the risk.
frontend:
patterns: ['*']
update-types: ['minor', 'patch']
# Majors get their own PR. The first grouped run bundled a Capacitor 7 → 8 migration in
# with six siblings, where it read as housekeeping — and CI would have gone green on it,
# because the test workflow builds the web app and never touches the mobile flavour. A
# major that lands alone is at least obviously a decision.
frontend-major:
patterns: ['*']
update-types: ['major']
ignore:
# Capacitor 8 needs Node >= 22 (its own `engines` field) and the build host is on 20, and
# `frontend/android` + `frontend/ios` are committed, so a major also means migrating the
# native projects — Gradle/AGP, the Podfile. That is a deliberate piece of work, not a
# dependency bump. Drop this ignore once the build host is on Node 22 and you want it.
- dependency-name: '@capacitor/*'
update-types: ['version-update:semver-major']
# Backend — api/package.json (@simplewebauthn/server, web-push)
- package-ecosystem: npm
directory: /api
schedule:
interval: monthly
open-pull-requests-limit: 3
groups:
api:
patterns: ['*']
update-types: ['minor', 'patch']
# Two dependencies, but one of them verifies passkeys — a major there is worth reading on
# its own rather than alongside anything else.
api-major:
patterns: ['*']
update-types: ['major']
# Base images — api/Dockerfile (node:22-alpine)
- package-ecosystem: docker
directory: /api
schedule:
interval: monthly
open-pull-requests-limit: 1
ignore:
# Odd-numbered Node majors are "Current", never LTS — they stop getting fixes in about
# six months. Dependabot's first run offered 22 → 25, which for something other people
# self-host is a stability downgrade for nothing. Even majors (22 → 24 → 26) still get
# proposed, which is the move actually worth reviewing.
- dependency-name: node
versions: ['25.x', '27.x', '29.x', '31.x', '33.x']
# Base images — web/Dockerfile (node:22-alpine build stage + nginx:alpine)
- package-ecosystem: docker
directory: /web
schedule:
interval: monthly
open-pull-requests-limit: 1
ignore:
- dependency-name: node
versions: ['25.x', '27.x', '29.x', '31.x', '33.x']
# Workflow actions — everything under .github/workflows/
- package-ecosystem: github-actions
directory: /
schedule:
interval: monthly
open-pull-requests-limit: 2
groups:
# These are all first-party actions/* and docker/* pinned to a major tag; they update
# in lockstep and none of them is worth a PR of its own.
actions:
patterns: ['*']
update-types: ['minor', 'patch']
# Action majors are usually a runner or Node-version change and usually harmless — but
# these workflows publish the ghcr images and deploy the live demo, so the blast radius
# is real. Separate PR, so a failure has an obvious cause.
actions-major:
patterns: ['*']
update-types: ['major']
+29 -7
View File
@@ -1,9 +1,14 @@
name: Publish Docker images
# Images are published from a *published release*, never from a bare tag push.
# A tag that is later deleted (the versioning rule consolidates unreleased tags)
# would otherwise leave its image tags behind in GHCR forever, and dependency
# bots read those as a newer version. See issue #87.
on:
push:
branches: [main]
tags: ['v*']
release:
types: [published]
workflow_dispatch:
permissions:
@@ -23,22 +28,35 @@ jobs:
context: .
file: ./web/Dockerfile
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Lowercase owner (registry names must be lowercase)
id: repo
run: echo "owner=$(echo '${{ github.repository_owner }}' | tr '[:upper:]' '[:lower:]')" >> "$GITHUB_OUTPUT"
- uses: docker/setup-qemu-action@v3
- uses: docker/setup-buildx-action@v3
- name: Set version metadata
id: version_meta
run: |
# On a release the ref is refs/tags/vX.Y.Z; on a main push it is a branch ref,
# which would otherwise label the image "refs/heads/main".
case "$GITHUB_REF" in
refs/tags/*) VERSION="${GITHUB_REF#refs/tags/}" ;;
*) VERSION="main-${GITHUB_SHA::7}" ;;
esac
echo "VERSION=$VERSION" >> $GITHUB_OUTPUT
echo "VCS_REF=${GITHUB_SHA}" >> $GITHUB_OUTPUT
echo "BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> $GITHUB_OUTPUT
- uses: docker/login-action@v3
- uses: docker/setup-qemu-action@v4
- uses: docker/setup-buildx-action@v4
- uses: docker/login-action@v4.6.0
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- uses: docker/metadata-action@v5
- uses: docker/metadata-action@v6
id: meta
with:
images: ghcr.io/${{ steps.repo.outputs.owner }}/opengym-${{ matrix.image }}
@@ -47,11 +65,15 @@ jobs:
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
- uses: docker/build-push-action@v6
- uses: docker/build-push-action@v7
with:
context: ${{ matrix.context }}
file: ${{ matrix.file }}
platforms: linux/amd64,linux/arm64
build-args: |
VERSION=${{ steps.version_meta.outputs.VERSION }}
VCS_REF=${{ steps.version_meta.outputs.VCS_REF }}
BUILD_DATE=${{ steps.version_meta.outputs.BUILD_DATE }}
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
+65
View File
@@ -0,0 +1,65 @@
# Publishes the browser-only demo to GitHub Pages: https://duartesantos8.github.io/openGym/
#
# DORMANT since 2026-08-19, when the GitHub account was suspended. The demo is now built with the
# same command below and served from the project's own site at https://opengym.duarte-santos.ch/demo/
# (Vite's base is './', so it drops into a subdirectory unchanged). Kept for the day the account
# comes back, exactly like the other workflows in this folder.
#
# Pages serves static files only, so this build has no backend — VITE_DEMO=1 makes the app
# boot straight into guest mode with a seeded example history (see frontend/src/lib/demo.js).
# The exercise images/GIFs (~140 MB) are never committed here; the demo build points at the
# upstream dataset on jsDelivr instead, pinned to a commit so the CDN can cache it forever.
name: Deploy demo to GitHub Pages
on:
push:
branches: [main]
paths:
- 'frontend/**'
- '.github/workflows/pages.yml'
workflow_dispatch:
permissions:
contents: read
pages: write
id-token: write
concurrency:
group: pages
cancel-in-progress: true
env:
DATASET: https://cdn.jsdelivr.net/gh/hasaneyldrm/exercises-dataset@7455efae41b330c265e7cd4b78dfa848e7ce5ebd
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: 22
cache: npm
cache-dependency-path: frontend/package-lock.json
- run: npm ci
working-directory: frontend
- run: npm run build
working-directory: frontend
env:
VITE_DEMO: '1'
VITE_IMG_BASE: ${{ env.DATASET }}/images/
VITE_GIF_BASE: ${{ env.DATASET }}/videos/
- uses: actions/configure-pages@v6
- uses: actions/upload-pages-artifact@v5
with:
path: frontend/dist
deploy:
needs: build
runs-on: ubuntu-latest
environment:
name: github-pages
url: ${{ steps.deploy.outputs.page_url }}
steps:
- id: deploy
uses: actions/deploy-pages@v5
+74
View File
@@ -0,0 +1,74 @@
# Runs on pull requests too — the other two workflows only fire on push to main, so
# contributed changes used to reach main without anything ever having been run.
name: Tests
on:
pull_request:
paths:
- 'frontend/**'
- 'mcp/**'
- '.github/workflows/test.yml'
push:
branches: [main]
paths:
- 'frontend/**'
- 'mcp/**'
- '.github/workflows/test.yml'
workflow_dispatch:
permissions:
contents: read
concurrency:
group: test-${{ github.ref }}
cancel-in-progress: true
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
# node:22-alpine in web/Dockerfile and api/Dockerfile — CI must match production.
- uses: actions/setup-node@v7
with:
node-version: 22
cache: npm
cache-dependency-path: frontend/package-lock.json
- run: npm ci
working-directory: frontend
- run: npm test
working-directory: frontend
# A broken import or bad JSX fails the build long before any test covers it.
- run: npm run build
working-directory: frontend
- run: node scripts/check-locales.mjs
working-directory: frontend
# check-locales compares the packs to each other, so a key missing from ALL of them is
# invisible to it. This walks src/ instead. Report-only for now: there is a known
# backlog of untranslated demo-view strings to clear before it can fail the build.
- run: node scripts/check-source-strings.mjs
working-directory: frontend
# The fatigue model must never read higher after a rest day than before it.
# Property probe over ~108k comparisons; too slow for the unit suite, cheap here.
- run: npm run test:fatigue-probe
working-directory: frontend
mcp:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: 22
cache: npm
cache-dependency-path: mcp/package-lock.json
- run: npm ci
working-directory: mcp
- run: npm test
working-directory: mcp
# The one check the vitest suite structurally cannot make. The MCP server is a bare node
# process, but vitest runs its tests through Vite — import.meta.glob, .jsx imports and
# ?raw all resolve happily there. That is how a Vite-only import reached a shared lib
# module with 33 green tests standing over a server that died on startup.
- run: npm run check:node-loadable
working-directory: mcp
+3
View File
@@ -13,3 +13,6 @@ frontend/dist/
node_modules/
*.log
.DS_Store
node_modules
.claude/
.agents/
+411
View File
@@ -0,0 +1,411 @@
# openGym — GitLab CI/CD
#
# This is the pipeline that actually gates and ships the project. It replaces the
# GitHub Actions workflows (.github/, dormant since the account suspension) and the
# gitea.com ones (.gitea/, kept only so the mirror stays buildable).
#
# What it does, in order:
# test — frontend + MCP suites, on every branch, MR and tag
# build — the two container images → registry.gitlab.com/duartesantos8/opengym/{api,web}
# package — the signed Android APK → job artifact + generic package registry
# deploy — the browser-only demo → GitLab Pages
# release — a GitLab Release with the changelog section and links to APK + images
#
# One deliberate difference from the GitHub copy: GitHub could distinguish a bare tag
# push from a *published* release, and only shipped images from the latter (issue #87 —
# a tag that is later consolidated away must not leave orphan image tags behind).
# GitLab has no such split: the tag pipeline is what creates the Release. So here the
# rule is enforced by hand — **only push a tag when you actually mean to release it.**
# Everything version-tagged (latest images, signed APK, Release) hangs off `v*` tags,
# which are protected, so nobody else can trigger a release either.
stages:
- test
- build
- package
- deploy
- release
- maintenance
variables:
# node:22-alpine in web/Dockerfile and api/Dockerfile — CI must match production.
NODE_IMAGE: "node:22-alpine"
# The demo build has no backend and no local media: the exercise images/GIFs (~140 MB)
# are never committed, so it points at the upstream dataset on jsDelivr, pinned to a
# commit so the CDN can cache it forever.
DATASET: "https://cdn.jsdelivr.net/gh/hasaneyldrm/exercises-dataset@7455efae41b330c265e7cd4b78dfa848e7ce5ebd"
GIT_DEPTH: "50"
# Branch pipeline *or* MR pipeline, never both for the same commit.
workflow:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS
when: never
- if: $CI_COMMIT_TAG
- if: $CI_COMMIT_BRANCH
# ---------------------------------------------------------------------------- test
.node:
image: $NODE_IMAGE
interruptible: true
test:frontend:
extends: .node
stage: test
cache:
key:
files:
- frontend/package-lock.json
paths:
- frontend/.npm
script:
- cd frontend
- npm ci --cache .npm --prefer-offline
- npm test
# A broken import or bad JSX fails the build long before any test covers it.
- npm run build
- node scripts/check-locales.mjs
# check-locales compares the packs to each other, so a key missing from ALL of them is
# invisible to it. This walks src/ instead. Report-only for now: there is a known
# backlog of untranslated demo-view strings to clear before it can fail the build.
- node scripts/check-source-strings.mjs
# The fatigue model must never read higher after a rest day than before it.
# Property probe over ~108k comparisons; too slow for the unit suite, cheap here.
- npm run test:fatigue-probe
rules:
# A scheduled pipeline exists only to run `renovate` (bottom of this file) — it must not
# re-run the suite or republish the edge images once a month for nothing.
- if: $CI_PIPELINE_SOURCE == "schedule"
when: never
- when: on_success
test:mcp:
extends: .node
stage: test
cache:
key:
files:
- mcp/package-lock.json
paths:
- mcp/.npm
script:
- cd mcp
- npm ci --cache .npm --prefer-offline
- npm test
# The one check the vitest suite structurally cannot make. The MCP server is a bare node
# process, but vitest runs its tests through Vite — import.meta.glob, .jsx imports and
# ?raw all resolve happily there. That is how a Vite-only import reached a shared lib
# module with 33 green tests standing over a server that died on startup.
- npm run check:node-loadable
rules:
# A scheduled pipeline exists only to run `renovate` (bottom of this file) — it must not
# re-run the suite or republish the edge images once a month for nothing.
- if: $CI_PIPELINE_SOURCE == "schedule"
when: never
- when: on_success
# --------------------------------------------------------------------------- images
# Images land at registry.gitlab.com/duartesantos8/opengym/{api,web} and are what
# `docker compose pull` fetches.
#
# On a v* tag: linux/amd64 + linux/arm64, tagged X.Y.Z, X.Y and latest.
# On any other branch: amd64 only, tagged `edge` and `main-<sha>`. arm64 is emulated
# through QEMU on the shared runners and costs several times the minutes — a self-hoster
# on a Pi pulls `latest`, which always comes from a release and is always multi-arch.
#
# Third way in: start a pipeline by hand (Build -> Pipelines -> New pipeline, or the API)
# with the variable PUBLISH_LATEST set to anything. That builds exactly like a tag would — multi-arch,
# `latest` and the version out of frontend/package.json — without cutting a release. It is
# there for the rebuild-without-a-code-change case: a base image picking up a CVE fix, where
# the published `latest` needs to move but the app did not change.
build:images:
stage: build
image: docker:28-cli
services:
- docker:28-dind
variables:
DOCKER_HOST: tcp://docker:2376
DOCKER_TLS_CERTDIR: "/certs"
DOCKER_TLS_VERIFY: "1"
DOCKER_CERT_PATH: "/certs/client"
needs: ["test:frontend", "test:mcp"]
parallel:
matrix:
- IMAGE: api
CONTEXT: "./api"
DOCKERFILE: "./api/Dockerfile"
- IMAGE: web
CONTEXT: "."
DOCKERFILE: "./web/Dockerfile"
before_script:
- echo "$CI_REGISTRY_PASSWORD" | docker login -u "$CI_REGISTRY_USER" --password-stdin "$CI_REGISTRY"
# buildx's docker-container driver refuses to read the daemon's TLS material straight
# out of DOCKER_HOST/DOCKER_CERT_PATH ("could not create a builder instance with TLS
# data loaded from environment"). Freezing the same environment into a named context
# and building the builder on top of that is the supported way round it.
- docker context create tls-environment
script:
- |
set -eu
BUILD_DATE="$(date -u +'%Y-%m-%dT%H:%M:%SZ')"
REPO="$CI_REGISTRY_IMAGE/$IMAGE"
if [ -n "${CI_COMMIT_TAG:-}" ] || [ -n "${PUBLISH_LATEST:-}" ]; then
if [ -n "${CI_COMMIT_TAG:-}" ]; then
SEMVER="${CI_COMMIT_TAG#v}"
else
# No tag to read the version off, so take it from the source of truth the APK job
# already uses. `apk add nodejs` would be a 40 MB download for one field.
SEMVER="$(sed -n 's/.*"version": *"\([^"]*\)".*/\1/p' frontend/package.json | head -1)"
[ -n "$SEMVER" ] || { echo "could not read version from frontend/package.json" >&2; exit 1; }
echo "PUBLISH_LATEST: building $SEMVER off $CI_COMMIT_REF_NAME, no release involved"
fi
VERSION="v$SEMVER"
PLATFORMS="linux/amd64,linux/arm64"
TAGS="-t $REPO:$SEMVER -t $REPO:${SEMVER%.*} -t $REPO:latest"
# Only the arm64 leg needs emulation, and only for the api image (web's build
# stage is pinned to $BUILDPLATFORM on purpose — see web/Dockerfile).
docker run --privileged --rm tonistiigi/binfmt --install arm64
else
VERSION="main-$CI_COMMIT_SHORT_SHA"
PLATFORMS="linux/amd64"
TAGS="-t $REPO:edge -t $REPO:$VERSION"
fi
docker buildx create --use --name opengym --driver docker-container tls-environment
# shellcheck disable=SC2086
docker buildx build \
--platform "$PLATFORMS" \
--file "$DOCKERFILE" \
--build-arg "VERSION=$VERSION" \
--build-arg "VCS_REF=$CI_COMMIT_SHA" \
--build-arg "BUILD_DATE=$BUILD_DATE" \
--cache-from "type=registry,ref=$CI_REGISTRY_IMAGE/buildcache:$IMAGE" \
--cache-to "type=registry,ref=$CI_REGISTRY_IMAGE/buildcache:$IMAGE,mode=max" \
--provenance=false \
$TAGS \
--push \
"$CONTEXT"
rules:
# A scheduled pipeline exists only to run `renovate` (bottom of this file) — it must not
# re-run the suite or republish the edge images once a month for nothing.
- if: $CI_PIPELINE_SOURCE == "schedule"
when: never
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/
- if: ($CI_PIPELINE_SOURCE == "web" || $CI_PIPELINE_SOURCE == "api") && $PUBLISH_LATEST
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
when: manual
allow_failure: true
# ------------------------------------------------------------------------------ apk
# The official signed APK. Signing keys live in protected CI variables, so they only
# exist on protected refs (main and v* tags) — a fork's MR builds an unsigned APK and
# cannot get at the key. Sideload-only by design: openGym is on no app store.
#
# Needs three CI/CD variables (Settings → CI/CD → Variables), all *protected*:
# ANDROID_KEYSTORE_B64 file base64 of opengym-release.keystore
# ANDROID_KEYSTORE_PASSWORD masked the keystore password
# ANDROID_KEY_ALIAS plain opengym
# KEEP THAT KEYSTORE: updates must be signed with the same key or Android refuses to
# install them over an existing copy.
build:apk:
stage: package
image: cimg/android:2026.08-node
needs: ["test:frontend"]
variables:
GRADLE_USER_HOME: "$CI_PROJECT_DIR/.gradle"
GRADLE_OPTS: "-Dorg.gradle.daemon=false"
cache:
key: "gradle-$CI_COMMIT_REF_SLUG"
paths:
- .gradle/wrapper
- .gradle/caches
script:
- |
set -eu
cd frontend
npm ci
# VITE_MOBILE build + `cap sync` into android/. The mobile flavor talks to no
# backend at all: no sign-in, no sync, media straight from the CDN.
npm run build:mobile
VER="$(node -p "require('./package.json').version")"
cd android
./gradlew --no-daemon assembleRelease
UNSIGNED=app/build/outputs/apk/release/app-release-unsigned.apk
BT="$(ls -d "$ANDROID_HOME"/build-tools/* | sort -V | tail -1)"
if [ -n "${ANDROID_KEYSTORE_B64:-}" ]; then
base64 -d "$ANDROID_KEYSTORE_B64" > "$CI_PROJECT_DIR/.ks.jks"
"$BT/zipalign" -f -p 4 "$UNSIGNED" aligned.apk
"$BT/apksigner" sign \
--ks "$CI_PROJECT_DIR/.ks.jks" \
--ks-pass "env:ANDROID_KEYSTORE_PASSWORD" \
--ks-key-alias "$ANDROID_KEY_ALIAS" \
--key-pass "env:ANDROID_KEYSTORE_PASSWORD" \
--out "$CI_PROJECT_DIR/openGym-$VER.apk" aligned.apk
rm -f "$CI_PROJECT_DIR/.ks.jks"
"$BT/apksigner" verify --print-certs "$CI_PROJECT_DIR/openGym-$VER.apk"
elif [ -n "${CI_COMMIT_TAG:-}" ]; then
# A release must never quietly ship an APK nobody can install. If the key is missing
# on a tag, something is wrong with the protected variables — say so and stop.
echo "FATAL: $CI_COMMIT_TAG is a release tag but ANDROID_KEYSTORE_B64 is not set." >&2
echo "Set it (protected, file type) under Settings -> CI/CD -> Variables." >&2
exit 1
else
echo "No signing key on this ref — producing an UNSIGNED apk (cannot be installed)."
"$BT/zipalign" -f -p 4 "$UNSIGNED" "$CI_PROJECT_DIR/openGym-$VER-unsigned.apk"
fi
echo "APK_VERSION=$VER" >> "$CI_PROJECT_DIR/apk.env"
# On a release tag the APK also goes into the generic package registry, which is
# what the Release links to (job artifacts expire; packages do not).
- |
set -eu
cd "$CI_PROJECT_DIR"
. ./apk.env
if [ -n "${CI_COMMIT_TAG:-}" ] && [ -f "openGym-$APK_VERSION.apk" ]; then
# Sideloading means nobody's app store checked this file for you, so publish the
# digest next to it rather than leaving people to trust the download.
sha256sum "openGym-$APK_VERSION.apk" > "openGym-$APK_VERSION.apk.sha256"
cat "openGym-$APK_VERSION.apk.sha256"
for f in "openGym-$APK_VERSION.apk" "openGym-$APK_VERSION.apk.sha256"; do
curl --fail --silent --show-error \
--header "JOB-TOKEN: $CI_JOB_TOKEN" \
--upload-file "$f" \
"$CI_API_V4_URL/projects/$CI_PROJECT_ID/packages/generic/opengym-android/$APK_VERSION/$f"
echo "uploaded $f to the generic package registry"
done
fi
artifacts:
name: "openGym-apk-$CI_COMMIT_REF_SLUG"
paths:
- "openGym-*.apk"
- "openGym-*.apk.sha256"
reports:
dotenv: apk.env
expire_in: 30 days
rules:
# A scheduled pipeline exists only to run `renovate` (bottom of this file) — it must not
# re-run the suite or republish the edge images once a month for nothing.
- if: $CI_PIPELINE_SOURCE == "schedule"
when: never
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/
# An APK build is ~8 minutes of shared-runner time; on main and MRs it is one click
# away rather than automatic. Flip `when: manual` off to have every push build one.
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
when: manual
allow_failure: true
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
when: manual
allow_failure: true
# ---------------------------------------------------------------------------- pages
# The browser-only demo: https://opengym-bc111a.gitlab.io/
# (that opaque host is GitLab's "unique domain" for Pages, on by default; the tidier
# https://duartesantos8.gitlab.io/opengym/ 308s to it. Settings → Pages turns it off.)
# Pages serves static files only, so this build has no backend — VITE_DEMO=1 makes the
# app boot straight into guest mode with a seeded example history (frontend/src/lib/demo.js).
# Vite's base is './', so the bundle drops into a subdirectory unchanged.
pages:
extends: .node
stage: deploy
needs: ["test:frontend"]
variables:
VITE_DEMO: "1"
script:
- cd frontend
- npm ci
- VITE_IMG_BASE="$DATASET/images/" VITE_GIF_BASE="$DATASET/videos/" npm run build
- cd ..
- rm -rf public && mv frontend/dist public
artifacts:
paths:
- public
rules:
# A scheduled pipeline exists only to run `renovate` (bottom of this file) — it must not
# re-run the suite or republish the edge images once a month for nothing.
- if: $CI_PIPELINE_SOURCE == "schedule"
when: never
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
changes:
paths:
- "frontend/**/*"
- ".gitlab-ci.yml"
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
when: manual
allow_failure: true
# -------------------------------------------------------------------------- release
release:
stage: release
image: registry.gitlab.com/gitlab-org/release-cli:latest
needs:
- job: build:images
- job: build:apk
artifacts: true
rules:
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/
script:
# The release notes are the matching section of CHANGELOG.md, verbatim — headings
# there are "## v1.2.9 — 2026-08-23", so take everything up to the next "## ".
- |
set -eu
awk -v tag="$CI_COMMIT_TAG" '
$0 ~ "^## " tag "([^0-9.]|$)" { inside = 1; next }
inside && /^## / { exit }
inside { print }
' CHANGELOG.md > release-notes.md
if [ ! -s release-notes.md ]; then
echo "openGym $CI_COMMIT_TAG" > release-notes.md
fi
head -40 release-notes.md
release:
tag_name: $CI_COMMIT_TAG
name: "openGym $CI_COMMIT_TAG"
description: release-notes.md
assets:
links:
- name: "openGym-$APK_VERSION.apk (Android, sideload)"
url: "$CI_API_V4_URL/projects/$CI_PROJECT_ID/packages/generic/opengym-android/$APK_VERSION/openGym-$APK_VERSION.apk"
link_type: package
- name: "openGym-$APK_VERSION.apk.sha256 (checksum)"
url: "$CI_API_V4_URL/projects/$CI_PROJECT_ID/packages/generic/opengym-android/$APK_VERSION/openGym-$APK_VERSION.apk.sha256"
link_type: other
- name: "Container images (api + web)"
url: "$CI_PROJECT_URL/container_registry"
link_type: image
# ---------------------------------------------------------------------- dependencies
# Dependency updates. GitLab has no Dependabot, so Renovate runs as a job — but only on a
# *scheduled* pipeline (Build → Pipeline schedules), so it never fires on a push and never
# competes with a real pipeline for runner minutes. Its policy lives in `renovate.json`
# next to this file, and it is the same policy the GitHub Dependabot config had: monthly,
# grouped per ecosystem, majors on their own, and the native mobile projects left alone.
#
# Needs one CI/CD variable: RENOVATE_TOKEN — a GitLab token with `api` scope, which is what
# lets it read the project and open merge requests.
renovate:
stage: maintenance
image:
name: renovate/renovate:41
entrypoint: [""]
variables:
RENOVATE_PLATFORM: gitlab
RENOVATE_ENDPOINT: "$CI_API_V4_URL"
RENOVATE_AUTODISCOVER: "false"
RENOVATE_REPOSITORIES: "$CI_PROJECT_PATH"
RENOVATE_ONBOARDING: "false"
RENOVATE_REQUIRE_CONFIG: "required"
LOG_LEVEL: info
script:
- renovate
rules:
- if: $CI_PIPELINE_SOURCE == "schedule" && $RENOVATE_TOKEN
# Also runnable by hand from the pipeline page when you want to see what it would do.
- if: $CI_PIPELINE_SOURCE == "web" && $RENOVATE_TOKEN
when: manual
allow_failure: true
+42
View File
@@ -0,0 +1,42 @@
<!-- GitLab has no issue *forms*, only these Markdown templates: the prompts below are the
same ones the GitHub/gitea forms asked for, and they are here because leaving them out
costs a round-trip on nearly every report. Delete the italics as you fill them in. -->
/label ~bug
### What did you do?
*Steps to reproduce, as precisely as you can.*
1.
2.
3.
### What did you expect to happen?
### What happened instead?
*Error messages, console output or screenshots if you have them.*
### How are you running openGym?
*Pick one: self-hosted (docker compose) · frontend dev server (`npm run dev`) · Android APK ·
other / not sure*
### Version & environment
- openGym version or commit:
- Browser & OS: *e.g. Safari 17 on iOS 18, Chrome 126 on Android*
### Is this about login / passkeys?
Most login issues are an `RP_ID`/`ORIGIN` mismatch — check your `.env` against the domain you
reach openGym on before reporting. See the [self-hosting guide](../../docs/SELF_HOSTING.md).
- [ ] Yes, and I have already checked `RP_ID`/`ORIGIN`
- `RP_ID` =
- `ORIGIN` =
- What sits in front of the app (reverse proxy, tunnel, none):
<!-- Security bug? Do not use this template. Open a *confidential* issue instead — tick
"This issue is confidential" before submitting. See SECURITY.md. -->
+16
View File
@@ -0,0 +1,16 @@
/label ~enhancement
### What problem does this solve?
*What are you trying to do that openGym doesn't support today?*
### Proposed approach
*How would you like it to work? Rough ideas are fine.*
### Dependencies
openGym is intentionally dependency-light — new packages, front or back, are a hard sell.
See [CONTRIBUTING.md](../../CONTRIBUTING.md).
- [ ] This doesn't require adding a new dependency
+19
View File
@@ -0,0 +1,19 @@
<!-- GitLab has no Discussions, so questions live in the issue tracker — labelled, so nobody
mistakes a question for agreed-on work. If you'd rather just ask, there is a Discord:
https://discord.gg/e62jY6fwVb — an issue is the better place for anything the next
person should be able to find by searching. -->
/label ~question
### What are you trying to do?
### What have you tried?
### Setup
- openGym version or commit:
- How you run it (docker compose / dev server / APK):
- If it is about login or passkeys — `RP_ID`, `ORIGIN`, and what sits in front of the app:
*Login trouble is an `RP_ID`/`ORIGIN` mismatch far more often than not:*
[docs/SELF_HOSTING.md](../../docs/SELF_HOSTING.md).
@@ -0,0 +1,16 @@
### What this changes
### Why
*Link the issue if there is one: `Closes #123`.*
### Checklist
- [ ] `npm test` passes in `frontend/` (and in `mcp/` if you touched it)
- [ ] `npm run build` succeeds
- [ ] User-facing strings are in every locale pack — `node scripts/check-locales.mjs`
- [ ] No new runtime dependency, or the MR explains why one is unavoidable
- [ ] CHANGELOG.md is left alone — release notes are written at release time
<!-- The pipeline runs the same checks on every MR. An APK build and a container build are
available as manual jobs on the pipeline if your change needs one. -->
+923
View File
@@ -1,5 +1,928 @@
# Changelog
## v1.2.10 — 2026-08-25
The first release since the move to GitLab that is mostly **other people's work**. Nine
contributors, thirteen merge requests: Brazilian Portuguese in full — interface, all 1,324
exercise names and all 7,710 instruction steps — equipment profiles for people who train in more
than one gym, drop-sets and rest-pause, a way to pair the mobile app with your own server, and a
round of security hardening on the API and the reverse proxy.
Alongside that, the bugs you reported in #bugs-and-ideas and on the issue tracker, several of
which turned out to be worse than they looked from the outside.
### Training
- 🔥 **"Add warm-up set" gave you a warm-up at your full working weight.** It looked for the row
to ramp from at the position *before* the first work set — which for the first warm-up is
index −1, so it fell through to the last row instead: your heaviest set. Every warm-up you
added had to be corrected by hand. Warm-ups now ramp toward the work weight, each one closing
half the remaining gap (50% → 75% → 87.5%), rounded down to what you can actually load.
- 🏋️ **Warm-ups can be planned in the routine.** Set how many an exercise gets and the session
starts with them already in place, ramped, instead of you adding them every time. They stay
out of volume, records and progression, and they travel with a shared plan.
- ⏱️ **The rest timer skipped the last set of every exercise.** It was written as "final sets
finish quietly", but another exercise follows that set and you rest before it too — so a
two-set exercise timed one rest instead of two. It now rests after every completed set except
the last one of the session. (issue #3, and zkssyth arrived at the same rule independently)
- 📝 **Notes you can write during a workout**, in three kinds, because they have three different
lifetimes: what happened today, on the exercise; what is always true about the movement (seat
height, pin position); and how the session went as a whole. The per-session note carries a
**pin** — the app cannot know whether "shoulder twinged" is a diary line or "go narrower" is a
message to your next self, but you do, at the moment you write it. Pinned notes come back the
next time that exercise comes up.
- 💥 **Drop-sets and rest-pause / myo-reps**, planned per exercise and extending the set row
itself rather than adding new sets.
### Equipment, and training in more than one gym
- 🎒 **Equipment profiles.** Build a "Home" and a "Gym" list of what you actually own, and the
library, the exercise picker and your routines filter to it — with a warning on any routine
exercise that needs something the active profile does not have. Body-weight exercises are
always available.
### Brazilian Portuguese
- 🇧🇷 **pt-BR is complete**: the interface, every built-in exercise name, and every instruction
step. It is defined as a layer over pt-PT rather than a copy, so a string added to Portuguese
can never silently go missing here — with tests that fingerprint every inherited entry and
refuse European vocabulary (*ficheiro*, *telemóvel*, *ecrã*, «guillemets»).
- 🔔 Server-sent notifications — rest-timer alerts, test pushes, workout-day reminders — follow
the profile's language instead of always arriving in English.
### Fixes
- ✅ **Home kept asking you to do the workout you had just done.** The week strip knew the day was
finished; the row underneath did not, and went on showing the routine behind a green Start tag.
(issue #4)
- 📈 **"Exercise progress" was empty for bodyweight exercises.** Pull-ups and push-ups carry no
weight, and every point without one was dropped, so a full history read as "No data yet". When
nothing in an exercise's history was ever loaded, the reps are the progress — so that is what
is plotted now. Add a weighted set later and it switches back to weight. (issue #5)
- 🫥 **The tab bar was see-through.** At 72% opacity the page read straight through it and the
labels competed with whatever was scrolling behind them — nobody needs to read the content
under a navigation bar. It is 94% now in both themes, and blurs less, which is also faster on
Android, where a blur behind a fixed element is recomposited on every scroll frame. Where
`backdrop-filter` is unavailable at all — old Android WebViews, "reduce transparency" — the
blurred surfaces now go fully opaque instead of leaving just the alpha, which was the worst of
both. (reported by mflova, seconded by seals187)
- 📥 **No Smith-machine exercise could ever match on import.** The `machine → lever` rule ran
before `smith machine → smith`, so the generic one ate the word first. Hevy's vocabulary is
now mapped as well, and exercises it cannot match take their body part from the name instead of
defaulting to "upper legs" — which had been attributing a third of an imported history to the
legs. (diagnosed by rubik_97, fixed by koyosan)
- 🗓️ **Charts show the calendar year** when the data spans more than one, so a point from
November 2025 is not confused with February 2026. (mflova)
- 🔤 **Exercise search matches whole words in any order**, ignores accents, and searches the
translated names too — "bench barbell" finds the barbell bench press, "elevacao" finds
"elevação". The haystack is now built once per exercise instead of on every keystroke.
- 🔑 **Passkeys work in Chrome on iOS**, which was excluded by a user-agent test rather than by
asking the browser what it supports.
- 📱 The reps field in a superset is no longer squeezed on narrow phones, and secondary muscles
are visible while building a plan, not only in the Exercises tab.
### Self-hosting
- 🔐 **Security hardening on the API and the proxy**: SSRF and an unbounded handler in push
delivery, CSRF from a sibling subdomain, session-cookie shadowing, and non-forgeable proxy
headers. Details in SECURITY.md.
- 🧭 **When a passkey fails, the error now says what is misconfigured.** "Unexpected RP ID hash"
told you nothing about your own `.env`; it now names the `RP_ID` and `ORIGIN` the server is
actually running with. `docs/SELF_HOSTING.md` gained a section that works through the usual
causes in order — including that `docker compose restart` does not re-read `.env`, and that on
a LAN without certificates there is nothing you can configure to make passkeys work.
- 📲 **"Connect to my server"** pairs the standalone mobile app to a self-hosted instance with a
one-time code, no passkey ceremony needed inside the app's WebView.
- 💾 **Optional local auto-backup** on the mobile app after finishing a workout or editing a
routine, and a **System** theme option that follows the OS.
With thanks to mzspicoli, Josevi, andi242, Space_Hermes, Horus Gonzalez, wagenheimer, koyosan,
mflova and Aaron Sachs — and to everyone who reported one of the bugs above.
## v1.2.9 — 2026-08-23
If you run openGym for other people, you have had no way to answer "who signed in, and when?" —
the server kept no record of anything. It does now: an **activity log** in the admin dashboard,
covering sign-ins, sign-outs, the attempts that failed, and every admin action. The other half of
this release is that **the live demo is back**, self-hosted this time, after two months offline.
And the project has a working home again: openGym now lives on **GitLab**, where CI builds the
container images and the signed Android APK for every release — the thing that has been missing
since the GitHub account went.
### Activity log
- 🧾 **The admin dashboard has an activity log.** Successful and failed sign-ins, profile
creations and refused signups, sign-outs (including "sign out everywhere"), and every admin
action: disabling or re-enabling an account, creating or revoking an invite code, and clearing
the log itself. Filter it by sign-ins, admin actions or failures, and page back through it.
- 📄 **It is a plain file.** `./data/audit.log`, one JSON object per line — `tail -f` and `jq`
read it directly, which also means it is its own export format. Deliberately *not* part of
`db.json`: that file is rewritten in full on every save, and the sign-in handshake is
unauthenticated, so a log living in there would have turned one junk request into a full
rewrite. Retention is a cap rather than an archive — the last `AUDIT_MAX` events (5,000) or
`AUDIT_DAYS` days (90), whichever runs out first.
- 🔒 **It records less than you might expect, on purpose.** No IP addresses unless you turn them
on (`AUDIT_IP=net` keeps only the network, `full` keeps the address); never the browser's
user-agent; and never the passkey id behind a failed sign-in, because that id is a stable handle
for one device and storing it would let an admin follow an unknown device from one attempt to
the next. A rejected invite code is not stored either — a near-miss guess sitting in a log file
helps nobody.
- 🧹 **Clearing it is itself logged**, and the event ids keep counting, so an erased stretch always
leaves a visible gap.
- ⚙️ **On by default when you update, and one variable turns it off.** It records strictly less
than your instance already holds — every profile is in `db.json`, every workout is in
`state-<uid>.json`, and any admin can already read both — and a log that ships switched off
tells you nothing on the day you need it. `AUDIT_LOG=0` disables it completely; no file is
written. Nothing leaves your server either way: this is a local file, not telemetry.
- Guests still never appear anywhere — guest mode does not talk to the server at all.
### The live demo is back
- ▶️ **<https://opengym.duarte-santos.ch/demo/>** — the in-browser demo, running on the project's
own site instead of GitHub Pages, which went down in August with the suspended account. Same
build as before: no backend, no account, seeded example history, and a reset button in its
settings. The embedded demo on the landing page works again too.
### openGym moved to GitLab
- 🏠 **<https://gitlab.com/DuarteSantos8/opengym>** is the home of the project. Same history,
same tags, same AGPL. gitea.com was the stopgap after the GitHub suspension and stays as a
mirror; it never had a CI runner, which is why releases there had no images.
- 🐳 **Prebuilt images are back.** `docker compose pull` now fetches
`registry.gitlab.com/duartesantos8/opengym/api` and `/web`, built for **amd64 and arm64** on
every release. Pulling is anonymous — the project is public, no login, no token.
- 🤖 **The APK is built by CI now, not by hand.** Every `vX.Y.Z` tag produces a `zipalign`ed,
signed APK, attached to the GitLab release and mirrored onto the download page. The signing
key sits in protected CI variables, so it exists only on `main` and on version tags — a
merge request from a fork builds an unsigned APK and never touches the key.
- ✅ **Every merge request is tested again.** The frontend suite (346 tests), the locale checks,
the fatigue probe and the MCP suite all run on GitLab CI. The GitHub Actions workflows stay
in `.github/` for the day that account comes back.
- 🌐 The in-browser demo also builds to GitLab Pages
(<https://opengym-bc111a.gitlab.io/>, which <https://duartesantos8.gitlab.io/opengym/>
redirects to); <https://opengym.duarte-santos.ch/demo/> remains the copy the landing page
embeds.
- 📄 Security reports have a private channel again: a **confidential issue** on GitLab. See
`SECURITY.md`.
- 🔁 **Dependency updates continue.** GitLab has no Dependabot, so Renovate runs from a monthly
scheduled pipeline with the same deliberately quiet policy the Dependabot config had:
grouped per ecosystem, majors on their own, odd-numbered Node images skipped, and the
generated `android/`/`ios/` projects left to follow their `@capacitor/*` packages. Security
advisories ignore the schedule and land on their own.
### Housekeeping
- The self-hosting docs, `SECURITY.md` and `.env.example` cover the activity log, and the
`api/server.js` line references in `SECURITY.md` are accurate again.
- Every repository link in the README, the docs, the app and the website points at GitLab, and
the website's live star/release numbers come from GitLab's API.
## v1.2.8 — 2026-08-22
A housekeeping release, and two things worth reading even if you skip the rest. openGym has moved
to **gitea.com** — the GitHub account it lived on was suspended, and everything you click to
self-host pointed there. And the exercise media's licence is now stated correctly: the images and
animations are © Gym visual, not CC, which matters if you redistribute them.
### The project moved to gitea.com
- 🏠 **openGym now lives at <https://gitea.com/DuarteSantos/openGym>.** The GitHub account
was suspended on 2026-08-19 and took the repository, the GHCR images, the Pages demo and
Discussions with it. `docker compose` now pulls `gitea.com/duartesantos/opengym-{api,web}`; the
README, `SECURITY.md`, `CONTRIBUTING.md` and the self-hosting docs point at the new home; issue
forms, tests and the image publish run as Gitea Actions. **If you self-host, re-pull:** the old
`ghcr.io` images are gone and will not update again.
- Gitea has no Discussions, so questions and ideas are labelled issues — or the Discord, which
is where most of it happens now: <https://discord.gg/e62jY6fwVb>.
- Old issue and PR numbers in the entries below stay as plain text. They point at a dead repo and
do not match the numbering here.
### The exercise media is © Gym visual — not CC
- ⚖️ **openGym described the exercise dataset as "CC". That was wrong**, and it is now
corrected everywhere it appeared (README, `NOTICE.md`, the website, the in-app credit, the
compose file and `scripts/fetch-media.sh`). Upstream
[hasaneyldrm/exercises-dataset](https://github.com/hasaneyldrm/exercises-dataset) licenses its two
halves differently: the exercise **metadata and instruction text are MIT**, while the **images and
animations are © [Gym visual](https://gymvisual.com/)**, used under that dataset's terms with
permission that is not transferable.
- **Nothing changes for using openGym.** It never shipped that media — not in the repository,
not in its history, not in the images or the APK; your instance downloads it from upstream on
first run, and the media step now prints where it comes from and under what terms.
- **It does change what you may do with the media.** Reusing the images or animations — in
openGym or anywhere else, commercially or not — needs your own licence from Gym visual. See
[NOTICE.md](NOTICE.md).
### Features
- 🇧🇷 **Brazilian Portuguese UI** — Portuguese now has separate Portugal and
Brazil options, with Brazilian terminology, date formatting and localized
instructions for all 1,324 exercises. Built-in exercise titles show the
Brazilian Portuguese name followed by the canonical English name, so both
vocabularies remain recognizable and searchable.
### Fixes
- 🔔 **Server-generated notifications follow Brazilian Portuguese** — rest-timer
alerts, test notifications and workout-day reminders now use the profile's
`pt-BR` language instead of always arriving in English.
- ⬅️ **The back gesture no longer quits the app** (Android). The packaged app never listened for
the system back event at all — Capacitor leaves that to `@capacitor/app`, which was not
installed — so a back swipe went straight past the WebView and finished the activity from
wherever you were. The per-sheet history entries added in [#63] only ever did anything in a
browser tab. Back now dismisses the open sheet, then walks back through the screens you came
from, and only leaves the app after a second press at the root ("Press back again to exit").
A sheet that is locked mid-task still swallows back, as it does in the browser.
### The website counts visits; the app still counts nothing
- 📊 **<https://opengym.duarte-santos.ch> now runs self-hosted, cookieless
[Umami](https://umami.is/)** — page views for the landing, about and docs pages, no cookies,
no third-party service.
- 🔒 **Your instance does not.** The frontend only gets an analytics tag when
`VITE_UMAMI_SRC` *and* `VITE_UMAMI_ID` are set at build time, which they are not in any published
image or in a plain `npm run build`. A self-hosted openGym remains telemetry-free, as advertised.
## v1.2.7 — 2026-08-18
The muscle map answers a third question. Balance showed where the volume went and Fatigue what was
still recovering; Strength now names the exercises behind a muscle and what each one is worth in
estimated 1RM. Fatigue itself got harder to fool — a set counts for more the closer it is to your
maximum, and it can no longer creep upward across a rest week. In a session, supersets finally
behave: pair them as you go, rest once per round, and drop an exercise you have decided against.
### The muscle map, read as strength
- **A per-muscle exercise breakdown** behind the muscle card — estimated 1RM per exercise, decay
bars, and primary/secondary tags, with a best-weight fallback for holds and carries that have no
reps to work from. Contributed by [@Space-Hermes](https://github.com/Space-Hermes) in
[#92](https://github.com/DuarteSantos8/openGym/pull/92),
[#93](https://github.com/DuarteSantos8/openGym/pull/93) and
[#94](https://github.com/DuarteSantos8/openGym/pull/94).
- **Fatigue is now intensity-weighted**, not volume alone: a set counts for more the closer it is
to your estimated maximum. It also reads against a stable historical reference, so fatigue can no
longer *rise* across a rest week, and bodyweight movements no longer register as zero load. A
property probe over 108,000 comparisons runs in CI to keep it that way. Contributed by
[@Space-Hermes](https://github.com/Space-Hermes) in
[#55](https://github.com/DuarteSantos8/openGym/pull/55).
### In a session
- 🔗 **Supersets advance properly.** Completing a set moves to the next member of the group, the
active exercise scrolls into view, and rest starts once the whole round is done rather than after
each set. Contributed by [@Space-Hermes](https://github.com/Space-Hermes) in
[#80](https://github.com/DuarteSantos8/openGym/pull/80).
- ➖ **Remove an exercise from a running session**, with a superset-aware picker and a confirmation.
Contributed by [@Space-Hermes](https://github.com/Space-Hermes) in
[#83](https://github.com/DuarteSantos8/openGym/pull/83).
- ⬅️ **The Android back button closes the open sheet** instead of leaving the screen or the app
([#63]). Each open sheet gets its own history entry, so stacked sheets unwind one at a time.
Contributed by [@Space-Hermes](https://github.com/Space-Hermes) in
[#85](https://github.com/DuarteSantos8/openGym/pull/85).
### Self-hosting
- 🐳 **The API service no longer has to be called `api`** ([#99]). The web image builds its nginx
config at startup from `BACKEND`, `PORT` and `NGINX_PORT`, all defaulted to today's values, so
existing compose files are unaffected. Reported and fixed by
[@GAS85](https://github.com/GAS85) in [#100](https://github.com/DuarteSantos8/openGym/pull/100).
- **…and the shipped `docker-compose.yml` now actually passes those through.** The `web` service
had no environment of its own and published a hardcoded `:80`, so setting `BACKEND` or
`NGINX_PORT` in `.env` did nothing at all on the stock stack — the setting existed, the wiring
did not. Both services now read `PORT` from the same place, so nginx cannot end up proxying to a
port the API is not listening on. Defaults are unchanged, so an existing `.env` behaves exactly
as before.
- 🏷️ **Health checks and OCI image labels** on both images — source, licence, version, revision and
build date, so image tooling can tell what it is holding. Contributed by
[@GAS85](https://github.com/GAS85) in [#98](https://github.com/DuarteSantos8/openGym/pull/98).
- **Images are published from a release, not from any tag** ([#87]). A tag that gets consolidated
away before it becomes a release used to leave its image tags behind in the registry, where
dependency bots read them as newer versions.
### Fixes
- **Imported warm-up sets were counted as work.** The importer marks them with `phase`, but several
places still read the older boolean, so warm-ups from FitNotes/Strong/Hevy history inflated set
counts, progression and the fatigue map.
[#63]: https://github.com/DuarteSantos8/openGym/issues/63
[#87]: https://github.com/DuarteSantos8/openGym/issues/87
[#99]: https://github.com/DuarteSantos8/openGym/issues/99
## v1.2.6 — 2026-08-11
The muscle map learned to answer a second question — not just where the volume went, but what is
still recovering from it. Plus: a freestyle session no longer starts from blanks, the rest timer
can reach you in another app, and a self-hosted instance can insist that everyone using it has an
account.
### The muscle map, read as recovery (#44)
- 🔥 **A `Balance | Fatigue | Strength` switch on the Stats muscle card.** Balance is the map you
already had and is untouched. Fatigue shades each muscle by how much of the recent training it
is still carrying; Strength shades it by how long it has been since you trained it at all, with
the weeks-since count spelled out underneath.
- **Fatigue is volume-sensitive and fades smoothly.** A hard twelve-set chest day starts near the
top and takes about six days to read ready again; a single set barely registers and is gone in
two. It decays continuously on a 36-hour half-life rather than expiring at a window edge, so the
map never flips from "fatigued" to "ready" between one look and the next.
- **Strength holds for two weeks, then decays toward a floor.** A muscle you have not trained in
months reads detrained rather than absent, which is the state that actually tells you something.
- Both views are pure functions over your existing history — no new stored data, no schema change,
nothing sent anywhere.
### The rest timer can reach you in another app (#49)
- ⏰ **A system notification when rest is over**, on top of the beep, for when you have switched to
another tab or app mid-session. Permission is asked the first time a rest starts, and everything
degrades quietly where notifications are unsupported or refused.
- It goes through the service worker where the browser requires that — which is most phones — and
falls back to the direct API elsewhere. No new dependencies; the existing server push path is
untouched.
### Rows now strain the rear delts (#51)
- **Four row variations gained rear-deltoid secondaries** — barbell, dumbbell, inverted and cable
seated rows — so the muscle map spreads their load the way the lift actually does. The overrides
live in a small table that survives a regeneration of the exercise dataset rather than being
edited into the generated data.
### An instance can require an account (#42)
- 🔒 **`ALLOW_GUEST=0` removes the "Continue without account" button.** Guest mode keeps everything
in the browser and never touches the server — no account, no sync, nothing the admin dashboard
can see — so on an instance meant for a known set of people it was a door leading nowhere
useful, and until now there was no way to close it.
- **It also ends guest sessions that already exist.** Guests never authenticate, so there is no
request for the server to start refusing; the switch reaches someone already inside on their
next visit, when the app checks the config and returns them to the login screen. Their data is
not deleted — it stays in that browser, and moves into a real profile if they create one on the
same device.
- **A server it cannot reach is not a server that said no.** The button is only withdrawn on an
explicit `allow_guest: false`; a failed config request, or a server too old to send the flag at
all, leaves guest mode exactly as it was. An instance that is merely offline for a moment does
not lock out everyone who never made an account.
- **Default is on, so nothing changes for existing instances.** Set it alongside `INVITE_ONLY=1`:
invite-only governs who may *create a profile* and says nothing about the guest button, which
never creates one.
### Freestyle sessions start where you left off
- 🏋️ **Adding an exercise to an empty workout now prefills it from the last time you trained
it** — the same number of sets, with each row's reps and weight carried across by position.
Cardio brings its duration and speed, a hold brings its seconds. Until now every row opened on
the config-sheet defaults, so the first thing a freestyle session asked of you was to retype
what you already did last week.
- **The config sheet agrees with the rows it is about to create.** It opens on the last target you
actually trained rather than the generic default, so the set count you confirm is the set count
you get.
- **Planned sessions are untouched.** A routine-driven workout still runs the progression logic and
still applies its prescription; only the freestyle path — which has no prescription to apply —
reads from history instead.
Contributed by [@Space-Hermes](https://github.com/Space-Hermes) in
[#50](https://github.com/DuarteSantos8/openGym/pull/50).
### Pair exercises into a superset mid-session (#64)
- 🔗 **"Make superset with previous / next" on each exercise card.** Two exercises paired in the
session collapse into a single *Superset* card — do them back-to-back, rest once at the end —
with an **Unpair** button in the header. No planning ahead required; pair them when you decide
to, in the workout.
- **Groups are any size.** Pairing the end of one group to the start of another merges them, and
the header wording stays correct past two exercises.
- **Unpairing cleans up after itself.** A group reduced to one exercise is dissolved rather than
left as a superset of one, and the pairing helpers never mutate the running session.
- Session-only by design: pairings drive the workout, and history stores the sets.
Contributed by [@Space-Hermes](https://github.com/Space-Hermes) in
[#64](https://github.com/DuarteSantos8/openGym/pull/64).
### The muscle map stops rewriting the catalogue (#67)
- **The curated secondary-muscle additions are now an overlay, not a mutation.** The four row
exercises that strain the rear delts used to get that written into the shared exercise dataset
at import time, which meant export, print and import saw a catalogue that had been edited
underneath them. They are derived at the read points instead, so the dataset stays pristine.
- The detail sheet's tag row reads through the same overlay, so those muscles still show where
they always did.
Contributed by [@Space-Hermes](https://github.com/Space-Hermes) in
[#67](https://github.com/DuarteSantos8/openGym/pull/67).
### Fixes
- 🖼️ **Exercise images and animations were blank on the routine screen** ([#79]). The media paths
were relative, and `/plan/r/:id` is the app's only two-segment route — so the browser asked for
`/plan/r/img/…` and got a 404 with nothing in the console to say why. Every other screen was
fine, which is what made it look like a one-screen mystery. Reported with the root cause already
found, by [@lemi1000](https://github.com/lemi1000).
- 📥 **Imports mapped more of what other apps export** ([#74]). Treadmill, Goblet Squat, Cycling and
Cable Core Pallof Press arrived as *custom* exercises rather than catalogue ones — no word
overlap could reach the names openGym stores them under. Those and their neighbours are now in
the alias table. Already-imported history stays custom; new imports resolve. Reported by
[@KiloOscarSix](https://github.com/KiloOscarSix).
- **A progression edge case that could loop forever** ([#60]). An entry left with nothing but
warm-up rows seeded the set-growth loop from a warm-up, which could never satisfy its own exit
condition. It leaves the entry alone instead. Contributed by
[@Space-Hermes](https://github.com/Space-Hermes).
- Documented that `VITE_IMG_BASE` / `VITE_GIF_BASE` are build-time values, so setting them next to
`docker compose` does nothing on a prebuilt image.
[#79]: https://github.com/DuarteSantos8/openGym/issues/79
[#74]: https://github.com/DuarteSantos8/openGym/issues/74
[#60]: https://github.com/DuarteSantos8/openGym/pull/60
## v1.2.5 — 2026-08-04
Nothing in the app itself changed. This release adds an optional side door: a small server that
lets an AI assistant you already run — Claude Desktop, Cursor, Cline — answer questions about
your own training, off the same files your instance already writes. If you don't use one, this
release is invisible to you.
### Ask an AI about your training, without the data leaving your box (#19)
- 🤖 **An MCP server (`mcp/`)** — opt-in, read-only, and not part of the Docker build. Your LLM
client spawns it as a local process, it reads `./data` directly, and it exits when the client
disconnects. No new container, no extra auth on the api, no third-party service, nothing over
the network. *"What did I bench last week?", "what's my estimated 1RM on deadlift?", "which
muscles have I been neglecting?"*
- **The answers match the Stats screen because they are the same numbers.** The server calls the
very functions in `frontend/src/lib/` the app already computes with, rather than reimplementing
them. Eight tools: routines, the week plan, workouts, one session in detail, body weight,
estimated 1RM and muscle balance.
- **Read-only on purpose.** Logging a workout from an assistant needs a long-lived token the api
does not have yet, plus a lock against the web UI's read-modify-write. Until both exist, the
server answers questions and does nothing else. It never reads passkey material, VAPID keys or
session state — only the profile it was pointed at.
- `docker-compose.yml` is untouched and nothing new enters the image, so an instance that ignores
this ships exactly what it shipped before. Setup is in [mcp/README.md](mcp/README.md).
### Under the hood
- The pure half of `i18n.js` — the language state, the constants, the readers — moved into
`i18n-core.js`, so the helpers under `frontend/src/lib/` can be loaded by a plain Node process
and not only by Vite. `i18n.js` keeps the Vite-only parts (the locale-pack loader, the React
hook) and re-exports the rest, so nothing that imports it had to change.
- The shared lib modules that only need `t` now take it from the core directly. A Vite-only
import inside a shared module is invisible under vitest, which transforms it, and fatal to the
MCP server, which does not — so the shared half stays clear of the bundler half by
construction rather than by remembering to.
- `npm run check:node-loadable` in `mcp/` walks the server's import graph under a bare `node`,
which is the one thing the test suite cannot do from inside Vite. CI runs it, alongside the
MCP tests — neither had ever run there before.
The MCP server was contributed by [@Pengboi](https://github.com/Pengboi) — the first feature in
openGym written by someone other than me. Thank you.
## v1.2.4 — 2026-08-01
The effort ratings you have been recording since v1.2.3 now answer questions, and bodyweight
training stops being treated as barbell training with the weight left at zero. Plus: creating a
profile from Settings works on an invite-only instance, which it never has.
### The effort ratings, read back as statistics
v1.2.3 let you rate how hard a set was. Nothing then read that rating back — it lived in the set
label and nowhere else. Stats now answers the question the number was recorded for.
- 📊 **An Effort card in Stats** over 30d / 90d / 1Y / all time: average effort, the share of sets
taken close to failure, and — always alongside them — how much of your training was rated at
all. Rating is optional and off by default, so a partly rated history is normal; an average
without its denominator would quietly speak for sets you never rated.
- **Week by week.** The weekly average with that week's set count in the tooltip, because the
pair is the reading: volume up with effort up is fatigue accumulating, volume up with effort
flat is the adaptation you were training for. Weeks resting on a single rated set are dropped
rather than drawn.
- **Where the sets land.** The spread across the scale, not just the middle of it. Half your sets
at failure and half in warm-up territory average out to a healthy-looking number; this is the
chart that shows it.
- 🔥 **Hard-sets mode on the muscle map.** The same body diagram, counting only sets taken near
failure — "where did the stimulus go" rather than "where did the volume go". A muscle can lead
on set count and still never be trained hard.
- **Effort on the exercise curve.** Each session's dot on the top-set chart fills in as less is
left in the tank, so the same weight moved with more in reserve stops reading as a flat line.
Exercises with enough ratings also get an Effort curve of their own.
- **One history, whichever scale you use.** Everything aggregates internally in RIR and converts
back for display, so a history that mixes your own RIR logs with imported RPE averages as one
series instead of two half-empty ones. RIR charts count downward on the axis, so harder sets
sit higher.
- Translated into all 12 UI languages.
### Bodyweight training, logged the way it is done
A push-up has no weight to type, and the app asked for one anyway — every set, on a quarter of
the catalogue. Three reports (#31, #32, #33) turned out to be the same gap: the app assumed
progress lived in the load. It doesn't, for the exercises most people actually start with.
- 💪 **Exercises know they are bodyweight.** Seeded from the equipment the dataset already
records, so push-ups, pull-ups, dips and 300-odd others arrive marked. The weight column is
not shown, the set row is one stepper instead of two, and the "confirm your working weight"
prompt at the end of an exercise stops asking about a weight that was never there. (#32)
- **Added weight when there is any.** A dip belt or a weighted vest is entered once in the
exercise settings and reads as an addition — "+10 × 8", not "10×8" — everywhere it is shown
back. With load on the belt the normal progression rules take over again, because now there
is something to add.
- 📈 **Reps and sets are the progression.** Clean session, one more rep. Set a top of the range
and reaching it adds a set and starts the reps over instead of climbing forever; at six sets
it says what it should have said all along, which is that it is time for weight or a harder
variation. No ceiling set keeps the old behaviour exactly. (#33)
- ↔️ **Reps per side.** For lunges, single-arm rows and every other unilateral movement. You
log what you did — 16, the total — and the app shows the split, "8 per side", so the set in
front of you is unambiguous without the rep count meaning one thing here and another there.
The target steps in twos, 16 → 18 → 20, because half of an odd total is a rep one side never
gets. (#31)
- Both settings travel with a shared plan, and are written to a plan file only when they
disagree with the catalogue — every existing plan, workout and backup is read unchanged and
none of it needs migrating.
- Translated into all 12 UI languages.
### Fixed
- **Creating a profile from Settings on an invite-only instance.** The sign-in screen asks for
the invite code when the server needs one; the same registration reached from Settings never
did, so it was refused with nothing on screen explaining why. It now asks on the same terms.
- **A long value no longer runs through its own label** in a settings row — "Follow the routine
(Linear progression)" overlapped "Rule" rather than shortening itself.
## v1.2.3 — 2026-07-31
How hard a set was, in whichever of the two scales you already think in — and the ratings your
old app recorded come across with the rest of your history. Plus: the phone stops locking itself
mid-workout, the rest timer can hand time back as well as take it, and Settings is grouped by
what each thing actually affects.
### The screen stays on while you train
- ☀️ **Keep screen awake — Settings → *During a workout*, on by default.** Locking, unlocking
and finding your place again between every set was the single most annoying thing about
logging on a phone. The screen now stays lit for as long as a workout is running and lets go
the moment you finish it, so nothing is held while you are not training.
- **It survives a tab switch.** Browsers release the lock whenever the page stops being visible,
which is exactly what happens when you glance at a message. The lock is taken again each time
the app comes back, rather than dying the first time you look away.
- **It follows the workout, not the screen you are on.** Checking Stats mid-session keeps the
screen awake.
- **Where it isn't available, it says so.** iOS grants no wake lock in Low Power Mode, and older
browsers have no Wake Lock API at all — the first is silent, the second shows the row disabled
rather than offering a switch that does nothing. Needs HTTPS, like every other modern browser
capability.
### Rest timer: take 15 seconds off, too
- ⏳ **A −15s button next to +15s.** The timer could only ever be extended or skipped outright;
now it goes both ways. Taking off more than is left finishes the rest rather than counting
into the negative — the same thing Skip does.
- **Rearranged so three controls fit.** The clock and the progress bar take the top row and the
controls sit underneath: −15 and +15 together in number-line order, Skip pushed to the far
edge so the button that ends the rest is not next to the one you tap to buy more time. On a
wide screen it stays on one line. Tap targets are bigger than they were.
- **The bar is nearly opaque.** The set rows underneath were reading through it and making the
clock hard to pick out.
### Settings, grouped by what it affects
- **General** (language, units) · **During a workout** (rest timer, keep screen awake, sounds,
effort per set) · **Notifications** · **Appearance** (theme, body diagram, accent) · **Data**.
- The old grouping mixed axes: "Units & timer" put a display preference next to two workout
behaviours, language sat under Appearance, and *Load starter plan* was buried between the
backup actions and the destructive reset. Data now reads in the order you would use it — fill
the plan, bring history over from another app, restore a backup, export one, wipe everything.
- Nothing was removed and no setting changed its meaning.
### Effort per set: RIR or RPE (#21)
- 🎯 **A third column on a working set, off by default.** Settings → *Effort per set* switches
it between **Off**, **RIR** and **RPE**. It only appears on weighted rep sets: a plank or a
treadmill row has nowhere to put it.
- **Two names for the same judgement.** RIR counts the reps you left in the tank; RPE reads the
same effort off a 10-point scale, so RPE ≈ 10 − RIR. The setting has an (i) that lays the two
scales side by side in a conversion table rather than explaining them in a paragraph.
- **Each set keeps the scale it was logged with.** Switching the setting changes what new sets
ask for and nothing else — history is never silently rewritten, and a set logged as RIR 2
still reads back as RIR 2 years later.
- **An unrated set stays unrated.** Blank and 0 are different things: RIR 0 says the set went to
failure. So `−` on an untouched cell leaves it empty, `+` starts at the bottom of the scale
and walks up in even steps, and stepping back off the bottom clears the cell again — a mistap
is always undoable.
- **Nothing else reads the value.** Progression rules and estimated 1RM are unaffected; the
rating is yours to look at, not an input to the maths.
- Upgrading keeps the column you had: a profile still carrying the old `showRir` flag — from
this device, a sync, or a backup restored later — comes across as RIR.
### Import brings your ratings with it
- 📥 **The RPE Hevy and Strong export is no longer dropped.** An `RPE` column is read into the
set, as is an `RIR` column if a file has one, and the import summary says how many sets
arrived with a rating — plus where to switch the column on if it's off.
- A blank cell stays unrated rather than becoming 0. A written-out `0` counts as a rating on the
RIR scale (a set to failure) but not on RPE, which starts at 1 — apps write 0 there to mean
"nothing here", and reading it as an effort would stamp one on every unrated set in the file.
- Ratings above the scale are capped instead of thrown away, and junk in the column is ignored
without losing the set.
- Backups already carried both fields and the setting, since a backup is the whole state — there
are now tests pinning that, so it can't quietly stop being true.
## v1.2.2 — 2026-07-25
Training that moves on its own: an exercise can now be logged by time instead of reps, the
next weight follows a progression rule you choose rather than a single hard-coded hint, and
every lift carries an estimated 1RM. Plus a standalone mobile app, a shareable plan, and an
importer for your history from other apps.
### Timed sets and a timer for the set itself (#16)
- ⏱️ **Reps or time, per exercise.** Planks, hangs, wall sits, dead hangs and loaded
carries no longer have to be filed under cardio to be timed. Each exercise in a routine
picks its own mode, and a timed set can still carry weight for a weighted plank or a
farmer's walk.
- ▶️ **A work timer, separate from the rest timer.** Start a timed set and it counts the
hold down, beeping and buzzing at zero exactly as the rest timer does, then checks the
set off itself. The two timers can never run at once — they mean opposite things.
- Finishing a hold early logs **the time you actually held**, not the target. A 38-second
hold against a 45-second target is recorded as 38 seconds.
- The mode travels everywhere it should: routine editor, workout, history, exercise
statistics (timed exercises chart their longest hold), the printable plan and the shared
plan file.
- Plans made before this release are read exactly as they always were — nothing to migrate.
### Progression rules you can read (#17)
- 📈 **Pick a rule per routine, override it per exercise.** Linear progression, **Greyskull
LP** (two straight sets plus an AMRAP final set, with double jumps and a 10 % reset),
double progression through a rep range, or adding time for timed work. Or none at all.
- 🧾 **Every target explains itself.** "Every rep last time — 2.5 kg more." "Missed reps
3 sessions running — reset to 55 kg and work back up." The rule is visible before you
train, not after.
- The session opens with the right weights already in the rows, instead of suggesting them
once you are standing at the bar.
- 🚫 **A bad session can't look like a good one.** Short reps count as a miss even when you
checked the set off; a set you never checked counts as a miss because you did not do it.
Nothing advances the load on a session that fell apart.
- Stalls and deloads are worked out from your log every time they are needed. Nothing is
written back into a finished workout and no counters are stored, so fixing a mistyped set
immediately produces the right next target.
- Lower-body lifts step up in larger jumps than upper-body ones by default, and any
exercise can set its own step.
- Bodyweight exercises progress in **reps**, because there is no load to add to a push-up
and no load to take off it either.
### Estimated 1RM (#18)
- 💪 **An estimated one-rep max for every lift**, in the exercise progress card (with its
own curve you can switch to) and in the exercise detail sheet.
- It always names the set it came from — "from 90 kg × 5 on 15 Jul" — because an estimate
off a heavy triple and one off a set of ten are very different claims.
- 🧮 **A calculator** for a set you have not done yet, so the number is reachable before
there is any history.
- Epley by default, and it **refuses to guess above 12 reps**, where the common formulas
disagree by double digits.
- A new best estimate is reported at the end of a workout separately from a weight PR —
same weight for more reps is real progress, but it is not a heavier lift.
### Share a plan
- 📤 **Send someone your plan.** Plan → *Share your plan* writes a small file with your
routines, the week schedule and any custom exercises they use — and nothing else. No
workouts, no weigh-ins, no settings.
- Importing **merges**: shared routines arrive as new ones with fresh ids, custom exercises
are matched by name so they are not duplicated, and your own plan is never overwritten.
Taking the week schedule with it is optional.
- 🖨️ **A printable plan** (Save as PDF) laid out so a single exercise never breaks across
a page.
### Fixes
- A shared plan file naming an exercise this build doesn't have can no longer take the app
down. Unknown ids are dropped on import, anything that slips through renders as a
placeholder you can delete, and an error boundary around the screens means a bad state is
recoverable by switching tabs instead of reloading.
- Importing from another app converts weights **per row**, not per file. FitNotes writes the
unit on each set, so a mixed export used to land 185 lb as 185 kg.
- Numbers follow the UI language instead of a hardcoded locale, which was putting Swiss
apostrophes ("7'535 kg") in front of everyone. Volume stays in your own unit rather than
switching to tonnes, which was wrong for pound profiles.
- Taking over a week schedule from a shared plan now really replaces Monday–Sunday instead
of only the days the shared file happened to fill.
- The body-weight slider's ceiling follows your unit (300 kg / 660 lb).
- "Best: 85 Kg" is capitalised correctly again.
### One codebase, two flavors
openGym is also a standalone mobile app — and it ships as a direct APK download, not
through app stores.
- 📱 **Standalone mobile app.** The same frontend now also builds as a native iPhone /
Android app (Capacitor) — the install-and-done flavor of openGym: no account, no server,
no sync. Everything stays on the phone.
- State is mirrored into a file in the app's private storage on every change, so your
log survives even when the OS evicts WebView storage (iOS does).
- The workout-day reminder becomes a **native notification** scheduled on the weekdays
your plan actually has a routine — no push server involved.
- Backups go out through the OS **share sheet** (Files, AirDrop, mail…).
- Exercise images/animations load from the same CDN as the live demo.
- `npm run build:mobile`, then open `android/` in Android Studio or `ios/` in Xcode —
see **docs/MOBILE.md**. `NOTICE.md` now carries an AGPL §7 app-store exception.
- 🤖 **Android APK, no Play Store.** The official build is a signed, sideloadable APK
(~4.5 MB) from [opengym.duarte-santos.ch](https://opengym.duarte-santos.ch) — deliberately
store-free. docs/MOBILE.md covers building and signing your own.
- 🍎 **iOS reality check.** Apple permits no installs outside the App Store, so there is no
iOS download; the docs explain the free options (self-hosted PWA on the home screen, or
running the native app onto your own iPhone from Xcode).
- 📥 **Import your history from another app.** Settings → Data → *Import from another app*
reads an export from **FitNotes** (both the Android and the FitNotes 2 iOS format),
**Strong** and **Hevy**, and pulls body-weight history out of an **Apple Health** export.
Anything else with a date, an exercise name and weight/reps columns is read too.
- Every row becomes a set, grouped into workouts by date, so your history arrives with
its real dates rather than as one lump. Hevy and Strong also carry session length, so
the activity heatmap fills in properly.
- Exercise names are matched against the 1,324-exercise library — parenthetical
qualifiers like "(Barbell)" and shorthand like BB/DB are normalised, and a curated
table covers the plain names people actually log ("Bench Press", "Squat", "RDL").
Where a name is genuinely ambiguous it is *not* guessed at: it becomes one of your own
exercises instead, because filing years of training under the wrong lift is worse than
an unmatched name you can see and fix.
- A summary shows what will happen — workouts, sets, how many exercises matched, which
ones didn't, and whether weights need converting — before anything is written.
- Importing is idempotent: days you already have data for are left alone, so running it
twice, or importing from two apps, never duplicates a workout.
## v1.2.1 — 2026-07-23
A muscle map across the app, and a live demo you can try without installing anything.
- 💪 **Muscle map.** Three places now show which muscles your training actually reaches, drawn on a
front-and-back body diagram shaded like the activity heatmap — more accent means more work.
- **Stats → Muscle balance** aggregates a week, 30 days, 90 days or everything, lists your
hardest-worked muscles with their set counts, and names the ones that got *nothing* in that
period. That last list is the point of the card: the gaps are what you'd otherwise never notice.
Tap any muscle to read its name and volume.
- **Routine editor** previews what a session hits as you build it, so a hole in the plan shows up
before you train around it for a month.
- **The finish screen** shows what you just trained.
- Load is counted in *effective sets* — a set counts fully for the exercise's target muscle and
partially for its supporting ones — not in kilograms, because 100 kg of leg press and 12 kg of
lateral raise say nothing about which muscle worked harder. Shading is relative within the
period you're looking at, so the map always reads as a balance rather than an absolute.
- Settings → Appearance → **Body diagram** switches between a male and female figure.
- The exercise dataset spells muscles inconsistently ("delts", "deltoids" and "shoulders" are one
muscle); all 50 spellings it uses are normalised onto the 18 the diagram can draw. Custom
exercises, which only carry a body part, fall back to it. The geometry is ~90 kB and loads on
demand, so the initial bundle is unchanged.
- 🐛 **Fixed: finishing a workout from its last exercise could blank the whole app.** The
per-exercise weight sheet read the running workout without checking it was still there, and
finishing clears it while that sheet is still on screen.
- ▶️ **Live demo** at [duartesantos8.github.io/openGym](https://duartesantos8.github.io/openGym/) —
a browser-only build (`VITE_DEMO=1`) published to GitHub Pages on every push to `main`. It boots
into guest mode with a seeded example profile (12 weeks of Push/Pull/Legs, weigh-ins, PRs) so
every screen has something to show, and it never talks to a server. Passkeys, sync and the admin
dashboard stay exclusive to self-hosted instances, which is where the backend lives.
- 🖼️ Builds can point the exercise media elsewhere via `VITE_IMG_BASE` / `VITE_GIF_BASE` — the demo
serves the ~140 MB dataset from a CDN instead of shipping it. The default (`img/` and `gif/` next
to the app) is unchanged.
## v1.2.0 — 2026-07-23
A complete visual redesign. Same app, same data — every screen redrawn.
### A designed interface, not an assembled one
- 🎨 **Rebuilt design system.** One type scale carrying hierarchy through size instead of making
everything bold, a neutral surface ramp instead of saturated blue-greys, hairline separators
instead of outlined boxes, and motion that acknowledges a press rather than animating for
decoration. Light and dark are both first-class, and the eight accent colours now pick their
label colour by measured contrast — the default green in light mode was failing WCAG AA on
every primary button before.
- ✏️ **A hand-drawn icon set** (77 icons, single stroke weight, drawn on one 24×24 grid) replaces
every emoji in the interface. Emoji render differently on each platform, sit on their own
baseline and can't take a theme colour, which is what made the old UI feel stitched together.
Icons inherit the surrounding text colour and optical size.
- 🏋️ **Routine icons.** Picking an icon for a routine now offers a grouped set — strength,
equipment, cardio, recovery — instead of an emoji keyboard. Routines you already made keep
their look: the old emoji are mapped forward automatically, so nothing to migrate and nothing
to redo.
- ▶️ **New tab bar** with a raised Start button that turns into a pulsing orange Resume while a
workout is running.
- 🏠 **Home reads as a plan for today** — week strip, today's session as one tappable row, body
weight, and your streak.
### Charts
- 📈 **Axis labels, gridlines and the target-weight line are visible again** in dark mode. They
were painted with colour variables that no longer existed, which silently fell back to black
on black — and to no stroke at all for the lines.
- 💬 **The hover readout stays on screen.** It used to be positioned with a fixed offset that
assumed one label width, so the first and last point pushed it under the chart's clip; it's now
placed from its measured size and kept inside the frame, dropping below the point when the
point sits high enough that the label would cover the value it reports.
- 🖱️ **It also goes away again** — moving off the chart now clears the readout, crosshair and
marker, which previously stayed until you hovered somewhere else.
## v1.1.3 — 2026-07-22
Admin dashboard for self-hosters (opt-in — off by default), equipment filtering, and
workout-screen fixes.
### Admin dashboard
- 🛠️ **Admin dashboard** (Settings → Admin dashboard) for whoever runs the instance: a users
overview with workout counts and last-active times, plus a per-user drill-down into their full
workout history and body-weight log.
- 🟢 **Live "training now"** — see who's mid-workout in real time, with their current exercise and
set progress, updated by a lightweight heartbeat while a workout is on screen.
- 🚫 **Disable / enable accounts** — a disabled account is signed out and locked out everywhere
until you re-enable it.
- 🔑 **Invite-only signup** (optional) — require an invite code to create a profile; generate and
revoke codes from the dashboard. Existing accounts are unaffected.
- ⚙️ Configured via environment: `ADMIN_UIDS` (comma-separated user ids who are admins) and
`INVITE_ONLY=1`; both default off, so a fresh instance stays open with no admin. See
`.env.example`. Admin access is gated by your passkey and enforced server-side.
### Exercises & workout
- 🏋️ **Filter exercises by equipment** (#6). A second filter row under the body parts lets you
narrow the list to what you actually have — body weight, dumbbell, barbell, cable, band, and so
on — in both the Exercises library and the exercise picker. The options adapt to what you've
already selected and are ordered by how many exercises use them, so every combination on screen
has results behind it and the row stays short. Building a bodyweight-only plan is now two taps
per body part.
- 🔎 **Minimize the exercise animation during a workout** (#12). A ⤡ Minimize / ⤢ Expand button
on the animation shrinks it to a thin strip so the set rows sit right under your thumb — no more
scrolling past a big GIF to tick off a set. Your choice is remembered and applied to every
exercise and future workout until you change it, so you set it once. Tapping the animation still
pauses/plays it as before.
- ⏱️ **Fixed: the rest timer froze at 0:01** (#14) instead of counting down to the end. It also
meant the timer could only be cleared with Skip, and a redundant "rest over" push notification
could still fire.
## v1.1.2 — 2026-07-22
Custom exercises, full localization, and input fixes.
### Custom exercises (#11)
- ✨ **Create your own exercise** from the exercise picker or the Exercises tab: a name and a
body part is all it takes. Your search text is pre-filled as the name, so "no match" flows
straight into "create it".
- 📝 **Optional description** — setup, cues, anything you want to remember. It shows on the
exercise's detail and config sheets (where a built-in exercise would show its animation),
and it's searchable, so you can find your own exercises by their cues too.
- 🏋️ Custom exercises behave like built-in ones everywhere — routines, supersets, workout
logging, weight suggestions, PRs, stats and history. The animation stays blank by design.
- 🏃 Pick the *cardio* body part and it logs time + speed instead of weight × reps, like the
built-in cardio exercises.
- ✏️ Edit (rename, change body part or description) or delete your custom exercises — from
their detail sheet in the Exercises tab, or straight from the exercise inside a routine via
"Edit or delete this exercise". Deleting removes them from your routines; already-logged
workouts keep their sets and still show the exercise name. (The routine sheet's old "Remove
exercise" button is now labelled "Remove from routine", so the two are no longer confusable.)
### Localization (#7)
- 🌍 **12 UI languages**: English, Deutsch, Español, Français, Italiano, Português, Polski,
Türkçe, Русский, 中文, 한국어, हिन्दी. Pick yours under Settings → Appearance → Language;
the choice syncs with your profile like the theme does.
- 📖 **Localized exercise instructions** for 10 of those languages (all except German and
Portuguese, which the upstream dataset doesn't cover yet — those fall back to English),
covering all 1,324 exercises. Body-part filters, equipment and muscle tags are translated
too; exercise *names* stay English (upstream limitation). Custom exercises are translated too.
- 📅 Dates, weekday and month labels follow the selected language.
- ⚡ Zero cost when unused: the app still ships English-only by default. Each UI language is a
~7 kB chunk and each instruction pack ~80–120 kB (gzipped), downloaded only when you switch —
the initial bundle size is unchanged.
- 🛠️ New `scripts/build-instructions.mjs` regenerates the instruction packs from the upstream
dataset; translations live in `frontend/src/locales/` (PRs welcome — it's one flat
English-string → translation map per language).
- Known gaps: push notification texts (sent by the server) and plural forms in some languages
are approximated; happy to take corrections from native speakers.
### Fixes
- ⌨️ Weight and other numeric fields now accept a comma as decimal separator ("33,5") — iOS
decimal keyboards in many locales only offer a comma, which previously reset the field to 0.
Partial input like "33," no longer snaps to 0 while typing. (#13)
- 📱 Fixed the exercise-config sheet (Sets / Reps / Weight, and the cardio variant) overflowing the
screen edge on narrow phones — the Weight stepper was clipped and could make the whole page pan
sideways in iOS Safari. Steppers now shrink to fit the viewport. (#10)
- 🛡️ Added a global horizontal-overflow guard so a single too-wide element can no longer knock the
page layout off-scale.
## v1.1.1 — 2026-07-21
Reliability fixes for the push notifications shipped in v1.1.0, found through live testing:
- 🌍 Workout day reminder now fires by each user's own browser-detected timezone instead of a
single server-wide one — works correctly regardless of where the server runs, and follows you
automatically if you travel.
- 💾 Settings changes (like the reminder time) are flushed to the server immediately when the tab
backgrounds or closes, instead of relying solely on a 1.5s debounce that could get cut short.
- ⏱️ Reminder check tightened from a 60s to a 10s interval, and pushes are now marked
`urgency: 'high'` — cuts avoidable delay on top of it, though delivery time is ultimately up to
Apple/Google's push relay.
- 🪵 Push send failures are now logged instead of silently swallowed.
## v1.1.0 — 2026-07-21
- 🐳 Prebuilt Docker images published to `ghcr.io/duartesantos8/opengym-{api,web}` (amd64 + arm64)
+136
View File
@@ -0,0 +1,136 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## What this is
openGym 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.
## 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), deployed separately by .gitlab-ci.yml.
docs/ SELF_HOSTING.md, MOBILE.md.
```
## 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 `.gitlab-ci.yml` on GitLab, the canonical remote (see README): it runs the
`frontend/` tests on Node 22 — the same version as `web/Dockerfile` / `api/Dockerfile`
(`node:22-alpine`) — and additionally builds and publishes the Docker images, packages the
signed Android APK, and deploys the demo/docs site. The Gitea and GitHub workflow copies
(`.gitea/workflows/`, `.github/workflows/`) are dormant mirrors; neither host runs them.
## 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).
- `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, 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`).
- 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 two flat JSON files under
`DATA_DIR` (`db.json`: users/credentials/subscriptions/invites; `state-<uid>.json`: per-user
workout data), 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. 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.
### 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.
## 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.
+31 -3
View File
@@ -7,10 +7,14 @@ to keep it that way — easy to read, easy to self-host.
```
frontend/ React + 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), one dependency (@simplewebauthn/server).
web/ multi-stage Dockerfile (builds frontend → nginx) + nginx.conf (serves app, proxies /api).
media/ exercise img/gif (gitignored, fetched at runtime).
docs/ self-hosting guide.
mcp/ optional Model Context Protocol server — read-only stdio bridge for LLM apps
(Claude Desktop, Cursor, …) to query a user's workouts/1RM/muscle balance. Not in
the Docker build; only runs when an LLM client spawns it. See mcp/README.md.
```
## Running for development
@@ -20,25 +24,49 @@ cp .env.example .env
docker compose up -d --build # api + web + media on :8080
# frontend hot reload:
cd frontend && npm install && npm run dev
# training logic (progression rules, 1RM, how a session is read back):
cd frontend && npm test
```
## Guidelines
- **Keep it dependency-light.** The frontend uses React + Router + Zustand and nothing else;
new deps (front or back) are a hard sell. `api/` has exactly one dependency — keep it that way.
new deps (front or back) are a hard sell. `api/` has two (`@simplewebauthn/server` for passkeys,
`web-push` for notifications) — keep it near that.
- **Match the style.** Small components, clear names, comments only where the "why" isn't obvious.
State lives in the Zustand store (`src/store`); pure helpers in `src/lib`.
- **Don't commit** the exercise media (`media/`) or `data/` — they're gitignored.
- **Test the flow** you touched — click through the affected screens (and the workout flow) in a
browser before opening a PR.
browser before opening a merge request.
- **Training logic gets a unit test.** Anything deciding what you lift next, or reading a logged
session back, belongs in a pure helper in `src/lib` with tests beside it (`npm test`). These
rules are easy to get subtly wrong and nearly impossible to verify by clicking — the
progression engine grew two real bugs that only a test pinned down.
## Good first issues
- Additional starter plans (upper/lower, full-body, 5×5…)
- More languages for the exercise instructions (the dataset ships several)
- Importers from other trackers (Strong, Hevy CSV → openGym JSON)
- Percentage / training-max programming (5/3/1-style) on top of the progression engine in
`src/lib/progression.js` — the policy interface is already there
- Accessibility passes on the workout and chart screens
## Where to ask what
| You have | Goes to |
| --- | --- |
| A quick question, or you'd rather just chat | [The Discord](https://discord.gg/e62jY6fwVb) |
| A question, or self-hosting that won't behave | [An issue labelled `question`](https://gitlab.com/DuarteSantos8/opengym/-/issues) |
| An idea you're not sure about yet | [An issue labelled `idea`](https://gitlab.com/DuarteSantos8/opengym/-/issues) |
| A reproducible bug | [Issues](https://gitlab.com/DuarteSantos8/opengym/-/issues) |
| A change you've already built | A merge request |
GitLab has no Discussions, so questions and ideas are issues too — just labelled, so nobody
mistakes a question for agreed-on work. An answered question is worth more than the same answer
in a chat log: the next person searching "passkey login fails behind my reverse proxy" finds it.
That is the one thing the Discord can't do, so if an answer there turns out to be worth keeping,
it belongs in an issue afterwards.
## Reporting bugs
Open an issue with: what you did, what you expected, what happened, and your browser/OS. If it's
+118 -6
View File
@@ -3,11 +3,123 @@
openGym — Copyright (C) 2026 Duarte Santos.
openGym's own code is licensed under the **GNU AGPL v3.0** (see [LICENSE](LICENSE)).
## App store exception
As an additional permission under section 7 of the AGPL v3.0, the copyright holder permits
distribution of the openGym mobile application through app store platforms (such as the
Apple App Store and Google Play) whose terms of service would otherwise be incompatible
with the AGPL, provided the corresponding source code remains available under the AGPL at
the project repository. This permission applies to the distribution channel only and does
not otherwise limit the license.
## Body diagram geometry
The muscle outlines the body maps are drawn from (`frontend/src/lib/body-paths.js`) are derived
from [**MuscleMap**](https://github.com/melihcolpan/MuscleMap) by Melih Colpan, used under the
**MIT License** and reproduced below. MuscleMap ships its path data as Swift source rather than
`.svg` files; the paths were converted to a JSON module, its sub-group shapes were dropped, and
nothing else about the artwork was changed.
```
MIT License
Copyright (c) 2026 Melih Colpan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
## Exercise data & media
The exercise names, instructions, images and animations (fetched into `media/` at build time and
indexed in `frontend/src/lib/exercises-data.js`) come from
[**hasaneyldrm/exercises-dataset**](https://github.com/hasaneyldrm/exercises-dataset)
and are **not** covered by openGym's AGPL license — they remain under that dataset's own terms.
This media is not distributed in this repository; it is downloaded from the upstream source on
first run. If you redistribute openGym with the media included, review the upstream license first.
openGym obtains both through
[**hasaneyldrm/exercises-dataset**](https://github.com/hasaneyldrm/exercises-dataset), which
licenses them differently. Neither is covered by openGym's AGPL license.
That dataset is itself a redistribution: the content originates from
[**ExerciseDB v1**](https://exercisedb.dev/) by **AscendAPI**. This is verifiable from openGym's
own data — the stored media filenames embed ExerciseDB's `exerciseId` (openGym's `0001` is
`0001-2gPfomN.jpg`; `2gPfomN` is ExerciseDB's id for "3/4 sit-up"), every metadata field matches,
and the instruction sentences are identical apart from stripped `Step:N ` prefixes. See
[issue #5](https://github.com/hasaneyldrm/exercises-dataset/issues/5) on that dataset.
### Metadata & instruction text
The exercise names, attributes and instructions (English in `frontend/src/lib/exercises-data.js`,
other languages in `frontend/src/instr/`, regenerated via `scripts/build-instructions.mjs`)
originate from ExerciseDB v1 and reach openGym through the dataset above, which distributes them
under the MIT license reproduced below. The translations into languages other than English are
openGym's own derivative work and are covered by openGym's AGPL.
```
MIT License
Copyright (c) 2026 Hasan Emir Yıldırım
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation and data files (the "Software"),
to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
### Images & animations — third-party, not MIT and not AGPL
The exercise thumbnails (180×180) and animations are **not** covered by the MIT license above and
**not** by openGym's AGPL. Their ownership is currently **unresolved**, and openGym states this
plainly rather than guessing:
- The upstream dataset attributes them to **© [Gym visual](https://gymvisual.com/)**, redistributed
there with that rights holder's written permission — a permission granted to *that dataset* and
**not transferable**.
- **ExerciseDB/AscendAPI** describes itself as "the original creator and owner" of this content and
publishes its own [terms](https://exercisedb.io/faq), which permit self-hosting, bundling and
commercial display, while prohibiting redistribution of the raw dataset or media as a standalone
or competing content package.
These two claims contradict each other. A clarification has been requested from AscendAPI; this
notice will be updated once the provenance is settled.
**Until then, treat the media as third-party content licensed to neither openGym nor to you.**
**openGym does not redistribute it.** It is not in this repository, not in its history, and not in
the published container images or the Android APK. A self-hosted instance downloads it from the
upstream source on first `docker compose up`; the mobile and demo builds load it from a CDN at
runtime.
If you want to reuse the media — in openGym or anywhere else, commercially or not — **clear it with
the rights holder first**, and keep any attribution that accompanies it intact.
Brazilian Portuguese exercise instructions under
`scripts/instruction-sources/pt-BR.json` and exercise names under
`scripts/exercise-name-sources/pt-BR.json` are original translations of that
English source produced with OpenAI Codex and Anthropic Claude Code
language-model assistance. They are not copied from a separate Portuguese
dataset. Their review status and translation policy are documented alongside
the source files.
+188
View File
@@ -0,0 +1,188 @@
# PROJECT_CONTEXT.md
Notes for whoever picks this up next. Not a spec — a map of what changed and why, kept next to
the code it describes. See `CLAUDE.md` for the general architecture; this file only covers the
drop-set / rest-pause work.
## What this adds
Two new set "shapes" on top of the existing straight/warm-up model:
- **Drop-set**: a main set followed by one or more weight drops, logged with no real rest.
- **Rest-pause / myo-reps**: an activation set (a normal set near failure) followed by short
bursts of extra reps, each preceded by a brief rest.
Both are **planned on the exercise**, in the same config sheet used by the routine editor and by
"add exercise" mid-workout (`ExConfig` in `sheets.jsx`) — not decided live during the workout.
Planning it stamps every set of that exercise and pre-fills the actual drop/burst rows with
real, already-editable numbers the moment the session starts. A straight (unplanned) set can
still grow a drop/burst live via "+ Drop"/"+ Burst" — that path never went away, it just isn't
the primary one anymore.
## The set row (`frontend/src/lib/workout-model.js`)
There was never a `type` enum on a set row before this — only `phase` (`'work'` / `'warmup'`,
with a legacy `warmup: true` boolean as fallback). This adds a **second, orthogonal**
discriminator, `type`:
```js
phase: 'work' | 'warmup' // existing axis — prep or the real session?
type: 'straight' | 'dropset' | 'restpause' // new axis — what shape is this row? (default 'straight')
```
A drop-set or rest-pause row is still exactly one entry in `entry.sets` — the extra work rides
*inside* that row, the same trick `phase` already uses for warm-ups:
```js
// dropset — main set + extra drops ON TOP of it (extraVolumeOf adds the drops back in for totals)
{ type: 'dropset', w: 100, r: 5, done: true, drops: [{ w: 80, r: 5 }, { w: 64, r: 5 }] }
// restpause — the row's own r IS the total across every burst; clusters are a BREAKDOWN of that
// same total, not extra on top of it (12 → [6, 3, 2, 1], and 6+3+2+1 == 12, always)
{ type: 'restpause', w: 60, r: 12, done: true, clusters: [{ r: 6, restSec: 15 }, { r: 3, restSec: 15 }, { r: 2, restSec: 15 }, { r: 1, restSec: 15 }] }
```
Those two extras genuinely mean different things, which trips people up (it tripped this
implementation up first): a drop-set's `drops` are *additional* work beyond the main set — the
main set stays a real, separate effort. A rest-pause row's `clusters` are the *decomposition* of
its own `r` — there is no separate "first burst is the real one" distinction, `r` already speaks
for the whole thing. Getting this backwards is exactly the bug this file's earlier revision had:
`r` held only the split's biggest chunk, so the row displayed a random-looking fraction of what
was configured instead of the number that was actually typed in.
Pure helpers in `workout-model.js`, mirroring the existing `phaseForSet`/`isWarmupRow` style:
- `setType(set)`, `isDropSet(set)`, `isRestPauseSet(set)` — read the discriminator.
- `dropsOf(set)` / `clustersOf(set)` — the extras array, or `[]` for anything else.
- `extraVolumeOf(set)` — weight×reps across a drop-set's `drops`, on top of the row's own w×r.
**Zero for rest-pause** — see above, its `clusters` never add to this or they'd double-count.
- `addDrop(set, drop)` / `addCluster(set, cluster)` — pure append, stamps `type`.
- `removeDropAt(set, i)` / `removeClusterAt(set, i)` — pure remove by index; clearing the last
one reverts the row to `'straight'`.
- `setDropAt(set, i, patch)` / `setClusterAt(set, i, patch)` — pure in-place edit (the weight/reps
steppers on an already-added drop/burst).
- `nextDropWeight(prevWeight, pct)` — pct% lighter than `prevWeight`, rounded to the nearest .5.
- `nextBurstReps(prevReps)` — roughly half of `prevReps`, floored at 1.
- `splitBurstReps(total)` — splits a rest-pause **total** rep count into a descending,
roughly-halving sequence of bursts that sums back to it (`12 → [6, 3, 2, 1]`). This is what a
planned rest-pause exercise configures directly: you say how many total reps you want out of
the whole rest-pause portion, not how many separate rests.
In `Workout.jsx`, `addBurstRow`/`removeCluster`/`setClusterField` all adjust the row's own `r` by
the same delta as whatever they just did to `clusters`, so the invariant (`r` == sum of every
`clustersOf` entry) survives live edits too, not just the initial plan — including the case of
tapping "+ Burst" cold on a plain straight set, where the set's original reps become the seed a
running total grows from rather than a separately-standing "main" effort. `addDrop`/`removeDrop`
on a drop-set row do **not** do this — a drop-set's main set stays independent on purpose.
## Planning (`ExConfig` in `sheets.jsx`) → `cfg.intensifier`
The exercise config sheet (routine editor and mid-workout "add exercise" both use it) has an
"Intensifier" picker: None / Drop-set / Rest-pause. Selecting one adds `intensifier` to the saved
config:
```js
// drop-set: every configured set becomes a drop-set — N drops, each pct% lighter than the one before
{ intensifier: { type: 'dropset', count: 2, pct: 20 } }
// rest-pause: NOT applied per set. It replaces the exercise's whole set list with exactly two
// rows regardless of the configured "Sets" (which the UI hides once this is selected, since it
// no longer means anything) — a warm-up at the exercise's own "Reps" field, then one rest-pause
// work set. Doing the full activation+bursts protocol several times over isn't how rest-pause is
// actually trained, so this is a structural replacement, not a per-row stamp like drop-set.
{ intensifier: { type: 'restpause', totalReps: 12, restSec: 15 } }
```
`applyIntensifierPlan(sets, cfg)` (`history.js`) applies that. It must run **after**
`applyPrescription`: a drop-set's chain of drops is a percentage of each row's own `w`, so it has
to use the final prescribed weight, not the pre-progression one `buildSets` started from — same
reasoning for where the two rest-pause rows get their weight from. Both call sites chain it last:
```js
applyIntensifierPlan(applyPrescription(buildSets(st, cfg), plan), cfg) // beginWorkout, sheets.jsx
applyIntensifierPlan(freestyle ? sets : applyPrescription(sets, plan), full) // add-exercise, Workout.jsx
```
`buildSets` itself knows nothing about intensifiers — it only builds the plain rows (for
rest-pause, `applyIntensifierPlan` discards all of them but the weight).
**Known open questions, deliberately left alone for now:**
- The progression engine (`readSession`/`nextPrescription`) judges a rest-pause exercise's one
non-warm-up row against `target.reps` — the exercise's plain "Reps" field (what the *warm-up*
row uses), compared against the work row's `r`, which is now the rest-pause *total* and so is
usually well above that goal. In practice this means a rest-pause exercise will almost always
read as "hit the goal" and progress — not obviously wrong, but not a deliberately designed
comparison either.
- `onerm.js`'s `estimate1RM` refuses anything past `REP_CAP` (12 reps) as "work capacity, not
strength" — a rest-pause row's `r` being the total means any rest-pause exercise with a total
over 12 (most of them) never contributes a 1RM estimate or PR. Also not fixed — it falls out
naturally from an existing, deliberate rule, not a new one, but worth knowing it applies here.
## Guided workout UI (`Workout.jsx`)
Every non-warm-up reps-mode row renders its drops/clusters as **editable sub-rows** right under
it (`.subrow`, reusing the same stepper look as the main row, just smaller) — not read-only chips
behind a sheet. A planned exercise arrives with these already filled in; nothing needs pressing
for them to show up. `"+ Drop"`/`"+ Burst"` (hidden on whichever type doesn't apply to that row)
just appends one more entry with the same suggested-next-value math
(`nextDropWeight`/`nextBurstReps`), for a drop/burst beyond what was planned, or for turning an
unplanned straight set into one on the spot.
There is deliberately **no countdown timer** for rest-pause bursts anymore (an earlier version of
this had one, using the work-timer bar) — with the burst rows already pre-filled and editable,
forcing a real-time countdown added friction without adding value; the short rest between bursts
is self-timed.
**Testing gotcha, not a code bug:** `S.active` (the in-progress workout) and each routine's saved
`intensifier` config both live in `localStorage` and are untouched by redeploying the container.
Iterating on this feature while an old workout is still active, or without re-saving an
already-configured exercise, replays stale pre-`totalReps` data. Discard the active workout and
re-save the exercise's config after a schema change like this one.
## Settings (`useStore.js` DEF, `Settings.jsx`)
`S.restPauseSec` (default 15) is the fallback rest used when "+ Burst" is tapped on a set with no
planned rest-pause of its own. It's a real user-editable default now — **Settings → During a
workout → Rest-pause rest** — the same pattern as the existing `S.restSec` (long) rest timer.
A planned exercise's own `intensifier.restSec` always overrides this.
## Why most of the app didn't need to change
1RM estimation (`onerm.js`) and the progression engine (`progression.js`) read a set row's own
`w`/`r`/`sec` directly, never anything nested — so a drop-set's main set, or a rest-pause row's
own total, is automatically the only thing they see; `drops`/`clusters` never had to be taught to
either of them. What *did* need a one-line hook, because they sum across a session rather than
reading one row:
- `workoutVolume` (`history.js`) — adds `extraVolumeOf(s)` on top of `w×r` per row. Drop-set
drops count; rest-pause clusters don't (see above — they're already inside the row's own `r`).
- `setTonnage` (`recovery.js`) — same split: `extraTonnage(...)` prices a drop-set's drops with
the same intensity-weighted formula (`load × reps × min(1, load/1RM)^1.5`) as the main set, and
is a no-op for rest-pause for the same double-counting reason.
- `applyPrescription` (`progression.js`) — when a policy grows the set count (bodyweight double
progression, issue #33), the newly appended row keeps the seed's `type` (that's the exercise's
plan) but never its already-logged `drops`/`clusters` (that's specific work the new row never
actually did).
`muscles.js`'s `loadOf` ("effective sets" for the muscle-balance map) is untouched on purpose: a
drop-set/rest-pause row still counts as one set there, same as today — that model was never
weight-based to begin with.
## Persistence
No backend or schema change was needed. `api/server.js` writes `state-<uid>.json` verbatim with
no set-shape validation beyond "is an object". The MCP server (`mcp/src`) re-imports the same
`workoutVolume`/`onerm.js`/`muscles.js` helpers from `frontend/src/lib` rather than duplicating
them, so its reported volume/1RM figures pick up the fix automatically too.
## i18n
All new strings are translated in `locales/es.js` (the other ten locales fall back to English via
`t()`, which is safe but not localized — nobody's asked for those yet).
## Out of scope for this pass
- Import from other apps (FitNotes/Strong/Hevy) — no equivalent concept there yet.
- Planning which *specific* sets of an exercise get the intensifier — it's all-or-nothing per
exercise (every set), which is what was asked for; a "last set only" option would need a
per-row opt-out on top of this.
+158 -24
View File
@@ -19,9 +19,12 @@ No account on someone else's server, no subscription, no ads. Just `docker compo
![Docker](https://img.shields.io/badge/Docker-compose-2496ED?style=flat-square&logo=docker&logoColor=white)
![No tracking](https://img.shields.io/badge/telemetry-none-f472b6?style=flat-square)
<br>
![GitHub last commit](https://img.shields.io/github/last-commit/DuarteSantos8/openGym?style=flat-square)
[![GitHub stars](https://img.shields.io/github/stars/DuarteSantos8/openGym?style=flat-square)](https://github.com/DuarteSantos8/openGym/stargazers)
[![GitHub issues](https://img.shields.io/github/issues/DuarteSantos8/openGym?style=flat-square)](https://github.com/DuarteSantos8/openGym/issues)
[![Pipeline](https://gitlab.com/DuarteSantos8/opengym/badges/main/pipeline.svg?style=flat-square)](https://gitlab.com/DuarteSantos8/opengym/-/pipelines)
![Last commit](https://img.shields.io/gitlab/last-commit/DuarteSantos8%2Fopengym?style=flat-square)
[![Stars](https://img.shields.io/gitlab/stars/DuarteSantos8%2Fopengym?style=flat-square)](https://gitlab.com/DuarteSantos8/opengym/-/starrers)
[![Issues](https://img.shields.io/gitlab/issues/open/DuarteSantos8%2Fopengym?style=flat-square)](https://gitlab.com/DuarteSantos8/opengym/-/issues)
[![Discord](https://img.shields.io/badge/Discord-join-5865F2?style=flat-square&logo=discord&logoColor=white)](https://discord.gg/e62jY6fwVb)
[![Buy Me A Coffee](https://img.shields.io/badge/Buy%20me%20a%20coffee-support-FFDD00?style=flat-square&logo=buymeacoffee&logoColor=black)](https://buymeacoffee.com/duartesantos)
</div>
@@ -37,6 +40,16 @@ No account on someone else's server, no subscription, no ads. Just `docker compo
</table>
</div>
<div align="center">
### [🌐 opengym.duarte-santos.ch](https://opengym.duarte-santos.ch) · [📦 Source on GitLab](https://gitlab.com/DuarteSantos8/opengym)
Screenshots, docs and the APK download live on the site.<br>
<sub>Want to poke at it first? The <a href="https://opengym.duarte-santos.ch/demo/">in-browser
demo</a> is the real app with example data — no account, nothing to install.</sub>
</div>
## Why
Most workout apps lock your data behind a login on their servers, nag you to upgrade, or
@@ -50,19 +63,39 @@ as a home-screen app, passkey sign-in, offline support, sync across your phone a
- 🏋️ **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
- 🔗 **Supersets** — build them, and log them back-to-back with a rest only after the pair
- ☀️ **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
- 💪 **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
- 🎲 **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
- 🔧 **Filter by equipment** — narrow the library to what you actually own; the options adapt to what you've picked, so every combination on screen has results behind it
- ✨ **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
- 🔑 **Passkeys, not passwords** — Face ID / Touch ID / fingerprint login; each profile keeps its own data, synced across devices
- 🎨 **Themes** — light/dark + 8 accent colors, saved to your profile
- 💪 **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
- 🔑 **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
- 📦 **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
- 📱 **Standalone Android app** — the whole tracker as a sideloadable APK: no account, no server, data on the phone, native workout reminders ([download](https://opengym.duarte-santos.ch))
## Quick start (self-host)
You need [Docker](https://docs.docker.com/get-docker/) with Compose.
```bash
git clone https://github.com/DuarteSantos8/openGym
git clone https://gitlab.com/DuarteSantos8/opengym
cd openGym
cp .env.example .env
docker compose pull # grab prebuilt images (amd64 + arm64) — skip to build from source instead
@@ -70,13 +103,37 @@ docker compose up -d
```
Open **http://localhost:8080**, tap **Create profile**, and you're in. First launch downloads
the exercise media (~140 MB) once. Prefer building the images yourself instead of pulling from
`ghcr.io`? Drop the `pull` step and run `docker compose up -d --build` — you don't need Node or
the exercise media (~140 MB) once.
> **About that media:** it reaches openGym through
> [hasaneyldrm/exercises-dataset](https://github.com/hasaneyldrm/exercises-dataset), which
> redistributes [ExerciseDB v1](https://exercisedb.dev/) — its metadata and instruction text are
> MIT, but the images and animations are third-party content under *neither* that MIT license nor
> openGym's AGPL, and their ownership is currently disputed between Gym visual and ExerciseDB.
> openGym ships none of it: your instance downloads it from upstream. Reusing it yourself,
> commercially or not, means clearing it with the rights holder — see [NOTICE.md](NOTICE.md).
Prefer building the images yourself instead of pulling from
GitLab's registry? Drop the `pull` step and run `docker compose up -d --build` — you don't need Node or
a build step locally either way.
> Want it reachable from your phone over the internet with passkeys? You'll need an HTTPS
> domain — a two-line change in `.env`. See **[docs/SELF_HOSTING.md](docs/SELF_HOSTING.md)**.
## Mobile app (no server at all)
The same codebase also builds a **standalone mobile app** (Capacitor): no account, no sync,
no backend — everything stays on the phone, with native workout-day reminders and share-sheet
backups. Self-hosting gets you multi-device sync and profiles for friends & family; the
mobile app is the install-and-done flavor.
- **Android:** [**download the APK**](https://opengym.duarte-santos.ch) — or straight from
[GitLab's package registry](https://gitlab.com/DuarteSantos8/opengym/-/packages), where every
build sits next to its `.sha256` — and sideload it; openGym is deliberately not on the Play
Store. Or build it yourself: **[docs/MOBILE.md](docs/MOBILE.md)**.
- **iPhone:** Apple doesn't allow installing apps outside the App Store, so there is no iOS
download. Self-host and add it to your home screen from Safari (it's a full PWA), or build
the native app onto your own device from Xcode — see **[docs/MOBILE.md](docs/MOBILE.md)**.
## How it works
```
@@ -93,13 +150,14 @@ a build step locally either way.
```
- **frontend/** — React + Vite (React Router + Zustand), built to static files **inside Docker**
- **api/** — Node with no framework, one dependency (`@simplewebauthn/server`), storing everything as plain JSON files under `./data`
- **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)
## Your data
Lives in `./data` on your host: `db.json` (profiles + public passkeys), `state-<user>.json`
(each user's plan, workouts, body weight, settings), and `secret` (the session-cookie key).
(each user's plan, workouts, body weight, settings), `audit.log` (the admin activity log — sign-ins
and admin actions, no IP addresses unless you ask for them) and `secret` (the session-cookie key).
**Back up `./data` and you've backed up everything.** Passkey private keys never touch the
server — they stay in your phone's secure hardware / your password manager.
@@ -107,39 +165,115 @@ server — they stay in your phone's secure hardware / your password manager.
All via `.env` (see `.env.example`):
| Variable | What it is | Default |
|------------|-----------------------------------|-------------------------|
| `RP_ID` | Hostname passkeys are bound to | `localhost` |
| `ORIGIN` | Full URL the app is served from | `http://localhost:8080` |
| `WEB_PORT` | Host port for the web UI | `8080` |
| `RP_NAME` | Name shown in the passkey prompt | `openGym` |
| Variable | What it is | Default |
|---------------|------------------------------------------------------|-------------------------|
| `RP_ID` | Hostname passkeys are bound to | `localhost` |
| `ORIGIN` | Full URL the app is served from | `http://localhost:8080` |
| `WEB_PORT` | Host port for the web UI | `8080` |
| `NGINX_PORT` | Port the web container listens on, inside the container | `80` |
| `BACKEND` | Name of the API service that `/api` is proxied to — change it if yours isn't called `api` | `api` |
| `PORT` | Port the API listens on; the web container proxies to the same value | `3000` |
| `RP_NAME` | Name shown in the passkey prompt | `openGym` |
| `SESSION_DAYS`| How long a sign-in lasts, in days | `90` |
| `ADMIN_UIDS` | User ids that get the admin dashboard (comma-separated) | *(none)* |
| `INVITE_ONLY` | Require an invite code to create a profile | *(off)* |
| `ALLOW_GUEST` | Offer "Continue without account" — set `0` to require a profile | *(on)* |
| `AUDIT_LOG` | Record sign-ins and admin actions — set `0` to record nothing | *(on)* |
| `AUDIT_MAX` | Events kept in the activity log; `0` for no limit | `5000` |
| `AUDIT_DAYS` | Days kept in the activity log; `0` to keep until `AUDIT_MAX` | `90` |
| `AUDIT_IP` | Record the caller's address: `off`, `net` (network only) or `full` | `off` |
| `VAPID_SUBJECT` | Contact URL sent with push notifications | your `ORIGIN` |
Push notification keys are generated on first run and saved to `./data/vapid.json` — nothing to set.
`DATA_DIR` is pinned to `/data` by `docker-compose.yml` and mapped to `./data` on the host; change the
host side of that volume, not the variable.
## Roadmap
Rough, community-driven — ideas and PRs welcome:
- [x] Standalone mobile app — Android APK to sideload ([download](https://opengym.duarte-santos.ch)); on iOS as a self-hosted PWA (no store listings planned)
- [x] Automatic progression programs (linear, Greyskull LP, double progression) with stalls and deloads
- [x] Estimated 1RM per exercise
- [ ] Percentage / training-max programming (5/3/1-style) on top of the progression engine
- [ ] More starter plans (upper/lower, full-body, 5×5)
- [ ] Importers from Strong / Hevy (CSV → openGym JSON)
- [x] Importers from FitNotes / Strong / Hevy (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
- [ ] More exercise-instruction languages (the dataset ships several)
- [ ] Exercise instructions in German & Portuguese (Portugal); the separately curated Brazilian Portuguese pack is complete
## Tech
React 19 + Vite (React Router, Zustand) · Node (no framework) · nginx · Docker Compose ·
WebAuthn · exercise data from [hasaneyldrm/exercises-dataset](https://github.com/hasaneyldrm/exercises-dataset).
WebAuthn · exercise data from [hasaneyldrm/exercises-dataset](https://github.com/hasaneyldrm/exercises-dataset)
(MIT metadata and instructions; media © Gym visual — see [License](#license)).
No database server, no cloud dependencies — the frontend builds inside Docker, so self-hosting
stays a one-command `docker compose up`.
The training logic — progression rules, 1RM estimation, how a logged session is read back —
lives in pure functions under `frontend/src/lib/` with tests next to them: `npm test` in
`frontend/`. Vitest is a dev dependency; the app itself ships no runtime dependencies beyond
React, the router and Zustand.
The same pure helpers power an optional MCP server (`mcp/`) that lets an LLM client like
Claude Desktop read your data over stdio — see [mcp/README.md](mcp/README.md). Opt-in, not
in the Docker build.
## Community
- **[Discord](https://discord.gg/e62jY6fwVb)** — release announcements, self-hosting help and
the back-and-forth that would be a slow issue thread. Quickest way to get an answer.
- **[Issues](https://gitlab.com/DuarteSantos8/opengym/-/issues)** — bugs, questions, self-hosting
help and ideas. There are no Discussions here, so it all lives in one tracker: label a question
`question` and an idea `idea`, and it gets treated as one rather than as agreed-on work. Use
an issue over the Discord for anything the next person should be able to find by searching.
- **Login trouble?** Most of it is an `RP_ID`/`ORIGIN` mismatch — check
[docs/SELF_HOSTING.md](docs/SELF_HOSTING.md) before opening an issue.
- **Merge requests** — [open one on GitLab](https://gitlab.com/DuarteSantos8/opengym/-/merge_requests); see
[CONTRIBUTING.md](CONTRIBUTING.md).
> **On the GitHub repo:** `github.com/DuarteSantos8/openGym` is offline because the account was
> suspended. **GitLab is the home of the project** — same history, same tags, same releases, and
> the CI that builds the images and the APK runs there. (gitea.com/DuarteSantos/openGym was the
> first stopgap and is now only a mirror.) Old GitHub issue and PR numbers in
> [CHANGELOG.md](CHANGELOG.md) are kept as plain references; they don't map onto GitLab's
> numbering.
## Contributing
Issues and PRs welcome — see [CONTRIBUTING.md](CONTRIBUTING.md). Good first issues: more starter
plans, exercise-data languages, import from other trackers. **A ⭐ helps more people find it.**
openGym is free and stays free: AGPL, no subscription, no paid tier, nothing held back for
sponsors. If it replaced a paid tracker for you and you want to chip in, there's a coffee button
below (and a badge at the top) — a star, a bug report or a merge request is worth just as much.
<!-- GitLab has no Sponsor button the way GitHub's FUNDING.yml gave one, so the link has to
stand on its own here. .github/FUNDING.yml stays put for the day that account returns. -->
<a href="https://buymeacoffee.com/duartesantos" target="_blank">
<img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png"
alt="Buy Me A Coffee"
style="height: 60px !important;width: 217px !important;">
</a>
## License
[GNU AGPL v3.0](LICENSE) — free and open source. You can self-host, use, modify and share it;
if you run a modified version as a network service, you must offer that version's source under
the same license. Nobody can turn openGym into a closed, proprietary product.
**openGym's own code** is [GNU AGPL v3.0](LICENSE) — free and open source. You can self-host,
use, modify and share it; if you run a modified version as a network service, you must offer that
version's source under the same license. Nobody can turn openGym into a closed, proprietary
product.
Exercise images/GIFs are fetched from the upstream dataset and keep their own terms — see [NOTICE.md](NOTICE.md).
**Third-party content is not, and openGym cannot sublicense it.** The exercise metadata and
instruction text originate from [ExerciseDB v1](https://exercisedb.dev/) and reach openGym through
[hasaneyldrm/exercises-dataset](https://github.com/hasaneyldrm/exercises-dataset) under the
**MIT** license. The exercise images and animations are third-party content covered by neither
that license nor the AGPL, and their ownership is **currently unresolved** — the upstream dataset
attributes them to [Gym visual](https://gymvisual.com/) under a non-transferable permission, while
[ExerciseDB/AscendAPI](https://exercisedb.io/faq) claims to be their creator and owner. A
clarification has been requested. openGym does not redistribute them (your instance fetches them
at first run) and does not relicense them. To reuse that media yourself, clear it with the rights
holder first.
Full third-party notices, including the body-diagram geometry: **[NOTICE.md](NOTICE.md)**.
+209
View File
@@ -0,0 +1,209 @@
# Security policy
openGym is a self-hosted app: you run the server, you hold the data. This file says which
versions get fixes, how to report something privately, and — the part most people actually
need — what the app protects you from and what it doesn't.
## Supported versions
Only the **latest release**. Releases are semver tags (`v1.0.0` → `v1.2.3`, see
[CHANGELOG.md](CHANGELOG.md)); there is no LTS or maintenance branch and older tags are never
patched. A fix ships in the next release and in the `latest` images in GitLab's registry.
Updating a self-hosted instance:
```bash
git pull && docker compose pull && docker compose up -d
```
## Reporting a vulnerability
The project lives on GitLab. It has no security-advisory workflow on the free tier, but it does
have **confidential issues**, and that is the private channel: open an issue at
<https://gitlab.com/DuarteSantos8/opengym/-/issues/new> and tick **"This issue is confidential"**
*before* you submit. A confidential issue is readable only by project members — you'll see it,
I'll see it, nobody else will, and it stays that way if it is later closed.
If you'd rather not put the details in GitLab at all, open a confidential issue saying only
*"I need an address for a security report"* — no details, no repro, no version — and you'll get
one back within a couple of days.
> The GitHub repo and its private vulnerability reporting are gone with the suspended account;
> `github.com/DuarteSantos8/openGym/security/advisories/new` no longer resolves.
Please don't put a working exploit in a *non-confidential* issue if it can be used against other
people's instances — and not in the Discord either, which is a public room. Everything else (a crash you can only trigger on your own box, a scanner warning)
is fine as a normal issue.
Useful in a report: the version or commit, whether you're running the prebuilt images or a
source build, your `RP_ID`/`ORIGIN` and what sits in front of the app, steps to reproduce, and
what an attacker gets out of it.
**On response times:** this is a hobby project maintained by one person alongside school. There
is no SLA and no bounty. Expect days rather than hours, and longer during exam periods. If a
week goes by with no reply, comment on the advisory thread — it's more likely to be a missed
notification than a decision. If a report goes unfixed and you want to disclose publicly, say so
in the thread; there's no objection, and no request to sit on it indefinitely.
## In scope
- **`api/server.js`** — forging or replaying a session cookie, bypassing passkey verification,
reading or writing another user's data through `/api/data`, reaching `/api/admin/*` without
being an admin, or creating a profile without a valid code while `INVITE_ONLY=1`.
- **Frontend** — XSS in the React app, or anything that lets a page on another origin read or
change a signed-in user's data.
- **Shipped deployment config** — `docker-compose.yml`, `web/nginx.conf`, the two Dockerfiles:
a default that exposes something a self-hoster wouldn't expect to be exposed.
- **The published images** `registry.gitlab.com/duartesantos8/opengym/api` and `/web`.
## Out of scope
- Anything that already assumes access to the host, to `./data`, or to the Docker socket. The
operator is trusted by design — see the security model below.
- Admins reading their users' workout history. That is the documented purpose of the admin
dashboard, not a leak.
- **Missing rate limiting**, brute force, or "I sent 100k requests and it got slow". The app
has no rate limiting at all and doesn't pretend to; that belongs in the reverse proxy you put
in front of it. Genuine amplification (one small request causing unbounded work) *is* in scope.
- **Missing security headers.** `web/nginx.conf.template` sets `X-Frame-Options: DENY`,
`Content-Security-Policy: frame-ancestors 'none'`, `X-Content-Type-Options: nosniff` and
`Referrer-Policy: same-origin`. It deliberately does **not** set HSTS or a full CSP: TLS is the
reverse proxy's job, and a script/style policy tight enough to be worth having needs testing
against the built app rather than being asserted here. A concrete attack that a header would
have stopped is still worth reporting.
- Instances served over plain `http://` on a LAN IP. Unsupported: passkeys don't work there and
the session cookie isn't marked `Secure`.
- Scanner output with no working exploit, and `npm audit` findings in build-time
devDependencies (Vite, Vitest, Capacitor CLI) that never reach a running instance.
- The GitLab Pages demo build — it has no backend at all, everything stays in that browser.
- Third-party content: the exercise image/GIF dataset and the CDN it's fetched from.
## Security model
Read this before hosting openGym for anyone other than yourself.
### What it does
- **Passkeys only.** No passwords, no email addresses, no reset flow. Registration and login are
verified server-side by `@simplewebauthn/server` against `expectedOrigin: ORIGIN` and
`expectedRPID: RP_ID`, and the authenticator's signature counter is stored and updated on every
login (`api/server.js:561-620`, `api/server.js:622-675`).
- **Sessions are a signed cookie.** It carries `<uid>:<expiry>:<version>` plus an
HMAC-SHA256 tag over it, compared in constant time (`api/server.js:230-243`). The key is 32
random bytes generated on first run and written to `./data/secret` with mode `0600`
(`api/server.js:40-43`). The cookie is `HttpOnly` and `SameSite=Lax`, and gets `Secure` **only
when `ORIGIN` starts with `https:`** (`api/server.js:36`, `api/server.js:316-322`). On an https
instance it is named `__Host-gymsid`: the prefix makes the *browser* enforce that the cookie is
host-only, which is what stops a sibling subdomain from planting a second session cookie on the
shared parent domain and having it shadow the real one. Over plain `http://localhost` the
prefix is not allowed, so the old name `gymsid` stays; both are accepted on the way in, so
upgrading signs nobody out. If one name ever arrives twice with different values, both are
refused rather than guessing which is the real session (`api/server.js:261`).
- **Any user can end every session they have.** `POST /api/logout/all` increments that account's
session version, and every authenticated request checks the version in the cookie against the
one on the user record (`api/server.js:249`, `api/server.js:302-303`), so every cookie ever
issued for the account — on every device, including a copy someone walked off with — stops
verifying at once. Passkeys are untouched; signing back in works immediately.
- **Data is isolated per user by the session's uid.** `GET`/`PUT /api/data` only ever touch
`state-<uid>.json` for the caller (`api/server.js:727-748`); no route lets a normal user name
another user.
- **Disabling an account takes effect immediately.** Every authenticated request and every login
is rejected for a disabled user (`api/server.js:299`, `api/server.js:667`).
- **Push endpoints cannot be aimed at your network.** A subscription's `endpoint` is a URL the
server connects out to and it comes from whoever is signed in, so `/api/push/*` would otherwise
be a request-forgery lever from inside the Docker network. It must be `https:`, and the
connection is refused at socket level if the host resolves to a loopback, private, link-local
(including cloud metadata) or CGNAT address — enforced in the agent's DNS lookup, not in a
prior pass, so there is no rebinding window (`api/server.js:86-119`). Sends have a 10 s timeout
(a stalling endpoint used to hang the request handler indefinitely), run at most 6 at a time,
and each account is capped at 20 subscriptions, so one small request cannot become an unbounded
burst of outbound connections (`api/server.js:84`).
- **There is an activity log.** Sign-ins, sign-outs, failed and refused attempts, and every admin
action are appended to `./data/audit.log`, one JSON object per line, and shown in the admin
dashboard. It is on by default (`AUDIT_LOG=0` disables it) and capped at `AUDIT_MAX` events /
`AUDIT_DAYS` days. Clearing it from the dashboard is itself recorded and the event ids keep
counting, so an erased stretch always leaves a visible gap.
### What it does not do
- **Nothing in `./data` is encrypted.** It holds `db.json` (users, passkey public keys, push
subscriptions, invite codes), one `state-<uid>.json` per user with their complete workout
history and body-weight log, `audit.log`, `secret`, and `vapid.json`. Anyone who can read that folder — you,
whoever holds the backups, whoever gets into the host — can read every user's data, and with
`secret` can mint a valid session cookie for any account. **If you host openGym for other
people, they are trusting you exactly as much as they'd trust any server operator.** With the
activity log on, `./data/audit.log` adds everyone's sign-in times to that — worth remembering
before an archive of `./data` goes somewhere you don't run.
- **Admins can read everything.** A user listed in `ADMIN_UIDS` (or flagged `admin: true` in
`db.json`) gets every user's full history and body weight, can disable accounts, and can create
or revoke invite codes (`api/server.js:825-947`). Off by default — a fresh instance has no admin.
- **Sessions can't be revoked one device at a time.** Revocation is per *account*, not per
session: `POST /api/logout/all` kills all of them at once and there is no device list to pick
from. `POST /api/logout` on its own only clears the cookie in that one browser
(`api/server.js:677-681`) — a copy taken beforehand keeps working. Sessions last **90 days** by
default, settable with `SESSION_DAYS` (`api/server.js:33`); each cookie carries the lifetime it
was issued with, so changing the setting doesn't reach cookies that are already out. Deleting
`./data/secret` and restarting still works as the instance-wide reset, and disabling an account
still locks out one user completely.
- **CSRF protection is `SameSite=Lax` plus an origin check, not tokens.** There are no CSRF
tokens. `SameSite=Lax` alone was not enough: it keeps the cookie off a cross-*site* request but
a sibling subdomain (`gym.example.com` vs anything else under `example.com` — one domain, one
reverse proxy, several apps, i.e. the usual self-hosting layout) is the *same* site and does
get the cookie. So every state-changing request that a browser sent must also be
`Sec-Fetch-Site: same-origin`, or carry an `Origin` equal to `ORIGIN` where that header is
missing (`api/server.js:344`). Requests authenticated with a Bearer token skip the check —
a browser never attaches one by itself, so there is no ambient authority to borrow — as do the
register/login/pair handshakes, which carry their own credential in the body and act on no
existing session (`api/server.js:338`).
- **User verification is preferred, not required.** Both handshakes pass
`requireUserVerification: false` (`api/server.js:575`, `api/server.js:644`), so a passkey
released without a biometric or PIN is still accepted. In practice: unlocked device ≈ account
access.
- **One passkey per profile, and no recovery.** Every successful registration creates a *new*
profile (`api/server.js:600-609`); there is no route to attach a second passkey to an existing
one, and no email or reset path. Lose the passkey and that profile is unreachable — only direct
surgery on `./data` gets it back.
- **Disabling someone isn't a ban.** They can still register a fresh profile with a new passkey
unless `INVITE_ONLY=1` is set. It also makes them near-invisible in the activity log: a disabled
account is refused at the session check, so nothing it does produces an entry except the failed
sign-ins it keeps attempting.
- **HTTPS is required and the app doesn't provide it.** The API container speaks plain HTTP and
nginx listens on `:80` (`web/nginx.conf`); TLS is your reverse proxy's job. Without it,
browsers won't do passkeys at all (except on `http://localhost`) and the session cookie is sent
in the clear.
- **No rate limiting anywhere.** Nothing throttles logins, registrations or writes, and
`POST /api/register/options` still answers whether an invite code is valid
(`api/server.js:544`), so an invite-only instance on the open internet should have a rate limit
in front of it. New invite codes are 16 hex characters — 64 bits (`api/server.js:891`) — which
makes guessing one impractical even unthrottled; codes generated by earlier versions are 8
characters / 32 bits and still work, so revoke and reissue any that are still unused. The only
hard limit
in the app is a 5 MB request body (`api/server.js:34`).
- **The activity log is not an audit archive, and it records less than you might assume.** No IP
address unless you set `AUDIT_IP` (`net` truncates to a /24 or /48; the default is `off`). When it is on, the
address comes from `CF-Connecting-IP`, `X-Forwarded-For`, `X-Real-IP` or, failing all three,
the connecting socket — so it is only as trustworthy as whatever sits in front, which has to
*overwrite* those headers rather than pass a client-supplied one through. The bundled web
container now does: it replaces `X-Forwarded-For`/`X-Real-IP` with the real peer and drops
`CF-Connecting-IP` unless you set `CF_CONNECTING_IP=$http_cf_connecting_ip`, which is correct
only with Cloudflare genuinely in front. Before that it appended to `X-Forwarded-For` and
passed `CF-Connecting-IP` straight through, and the API reads the first entry — so any caller
could choose the address recorded against it. Never the browser's user-agent,
and never the passkey id behind a failed sign-in — that id is a stable
handle for one device, and storing it would let an admin follow an unknown device from attempt
to attempt. So a failed sign-in from a passkey this instance doesn't know is recorded as a time
and nothing else. Retention is a cap, not an archive: old events are dropped, not exported. Any
admin can clear the whole log from the dashboard. And four of the paths that write to it —
the invite check on `POST /api/register/options`, and the expired-challenge and unknown-passkey
branches of the register/login handshakes — are reachable **without a session**, so with no rate
limit in front (see below) anyone can fill the log with noise. It is an append of ~110 bytes per
event to a capped file, never a rewrite of `db.json`, so the cost is a log full of noise rather
than a full disk or a slow server.
- **A few endpoints answer without a session:** `/api/health` (which includes the total user
count), `/api/config` (whether invite-only is on), `/api/push/public-key`, and the
register/login handshakes.
- **Changing `RP_ID` invalidates every existing passkey.** They were bound to the old hostname
and will fail verification against the new one. The data stays on disk but is unreachable until
each user registers again — as a *new* profile. Choose your hostname before anyone registers.
- **Guest mode never reaches the backend.** That data lives unencrypted in the browser's
`localStorage` and is gone when the browser storage is cleared.
+25 -1
View File
@@ -1,8 +1,32 @@
FROM node:22-alpine
ARG VERSION=dev
ARG VCS_REF=dev
ARG BUILD_DATE=unknown
LABEL maintainer="Duarte Santos https://gitlab.com/DuarteSantos8" \
org.opencontainers.image.title="opengym-api" \
org.opencontainers.image.description="Backend for Self-hosted gym & body-weight tracker — plan routines, log workouts (supersets & cardio too), track your weight and progress, passkey login. Your data, your server." \
org.opencontainers.image.source="https://gitlab.com/DuarteSantos8/opengym" \
org.opencontainers.image.url="https://gitlab.com/DuarteSantos8/opengym/container_registry" \
org.opencontainers.image.documentation="https://gitlab.com/DuarteSantos8/opengym#readme" \
org.opencontainers.image.licenses="AGPL-3.0-or-later" \
org.opencontainers.image.version=$VERSION \
org.opencontainers.image.revision=$VCS_REF \
org.opencontainers.image.created=$BUILD_DATE
WORKDIR /app
COPY package.json package-lock.json* ./
RUN npm install --omit=dev && npm cache clean --force
COPY server.js ./
COPY server.js push-messages.js verify-error.js ./
ENV NODE_ENV=production
ENV PORT=3000
EXPOSE 3000
CMD ["node", "server.js"]
HEALTHCHECK --interval=5m \
--timeout=5s \
--retries=3 \
CMD wget --spider -q "http://127.0.0.1:${PORT}/api/health" || exit 1
+3 -2
View File
@@ -1,12 +1,13 @@
{
"name": "gym-api",
"version": "1.1.0",
"version": "1.2.10",
"private": true,
"type": "module",
"main": "server.js",
"license": "AGPL-3.0-or-later",
"scripts": {
"start": "node server.js"
"start": "node server.js",
"test": "node --test"
},
"dependencies": {
"@simplewebauthn/server": "^13.1.1",
+40
View File
@@ -0,0 +1,40 @@
const COPY = {
en: {
restTitle: 'Rest over 💪',
restBody: 'Time for your next set.',
testBody: 'Test notification ✅ — this is what alerts look like.',
dayFallbackTitle: 'Workout planned today',
dayRoutineSuffix: 'today',
dayBody: "It's on your plan — let's go 💪",
},
'pt-BR': {
restTitle: 'Descanso terminado 💪',
restBody: 'Hora da próxima série.',
testBody: 'Notificação de teste ✅ — é assim que os alertas aparecem.',
dayFallbackTitle: 'Treino planejado para hoje',
dayRoutineSuffix: 'hoje',
dayBody: 'Está no seu plano — vamos treinar 💪',
},
};
const copyFor = lang => COPY[lang] || COPY.en;
export function restTimerPush(lang) {
const copy = copyFor(lang);
return { title: copy.restTitle, body: copy.restBody, tag: 'rest-timer' };
}
export function testPush(lang) {
return { title: 'openGym', body: copyFor(lang).testBody, tag: 'test' };
}
export function dayReminderPush(lang, routine) {
const copy = copyFor(lang);
return {
title: routine
? `${routine.emoji || '🏋️'} ${routine.name} ${copy.dayRoutineSuffix}`
: copy.dayFallbackTitle,
body: copy.dayBody,
tag: 'day-reminder',
};
}
+27
View File
@@ -0,0 +1,27 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { dayReminderPush, restTimerPush, testPush } from './push-messages.js';
test('localizes every server-generated notification in pt-BR', () => {
assert.deepEqual(restTimerPush('pt-BR'), {
title: 'Descanso terminado 💪',
body: 'Hora da próxima série.',
tag: 'rest-timer',
});
assert.deepEqual(testPush('pt-BR'), {
title: 'openGym',
body: 'Notificação de teste ✅ — é assim que os alertas aparecem.',
tag: 'test',
});
assert.deepEqual(dayReminderPush('pt-BR', { name: 'Treino A', emoji: '💪' }), {
title: '💪 Treino A hoje',
body: 'Está no seu plano — vamos treinar 💪',
tag: 'day-reminder',
});
});
test('keeps the existing English copy as the fallback', () => {
assert.deepEqual(restTimerPush('fr'), restTimerPush('en'));
assert.equal(dayReminderPush('unknown', null).title, 'Workout planned today');
assert.equal(testPush(undefined).body, 'Test notification ✅ — this is what alerts look like.');
});
+666 -56
View File
@@ -4,18 +4,35 @@ import http from 'node:http';
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import https from 'node:https';
import dns from 'node:dns';
import {
generateRegistrationOptions, verifyRegistrationResponse,
generateAuthenticationOptions, verifyAuthenticationResponse
} from '@simplewebauthn/server';
import webpush from 'web-push';
import { dayReminderPush, restTimerPush, testPush } from './push-messages.js';
import { verifyError } from './verify-error.js';
const PORT = +(process.env.PORT || 3000);
const DATA = process.env.DATA_DIR || '/data';
const RP_ID = process.env.RP_ID || 'localhost';
const ORIGIN = process.env.ORIGIN || 'http://localhost:8080';
const RP_NAME = process.env.RP_NAME || 'openGym';
const SESSION_DAYS = 365;
// Admin dashboard (issue): admins are matched by uid; INVITE_ONLY gates new signups behind a
// code the admin generates. Both default off so a fresh self-hosted instance stays open.
const ADMIN_UIDS = (process.env.ADMIN_UIDS || '').split(',').map(s => s.trim()).filter(Boolean);
const INVITE_ONLY = /^(1|true|yes|on)$/i.test(process.env.INVITE_ONLY || '');
// Guest mode ("Continue without account") keeps everything in the browser and never touches this
// server — but on an instance meant for a known set of people, an entrance nobody can walk back
// out of is still the wrong front door (#42). Default ON, so existing instances are unchanged;
// the polarity is inverted from INVITE_ONLY because the safe default here is the permissive one.
const ALLOW_GUEST = !/^(0|false|no|off)$/i.test(process.env.ALLOW_GUEST || '');
// 90 days keeps someone who trains a few times a week permanently signed in without a stolen
// cookie staying good for a year. Overridable because a family instance and one on the open
// internet don't want the same number. Only affects cookies minted from now on — the expiry is
// baked into each cookie when it's issued, so lowering this never cuts an existing session short.
const SESSION_DAYS = Math.max(1, +(process.env.SESSION_DAYS || 90) || 90);
const MAX_BODY = 5 * 1024 * 1024;
// Secure cookies require HTTPS; over plain http://localhost the flag would drop the cookie
const SECURE = /^https:/i.test(ORIGIN) ? ' Secure;' : '';
@@ -28,9 +45,11 @@ if (!fs.existsSync(secretFile)) fs.writeFileSync(secretFile, crypto.randomBytes(
const SECRET = fs.readFileSync(secretFile, 'utf8').trim();
const dbFile = path.join(DATA, 'db.json');
let db = { users: [], creds: [], subs: [] };
let db = { users: [], creds: [], subs: [], invites: [] };
try { db = JSON.parse(fs.readFileSync(dbFile, 'utf8')); } catch {}
db.subs = db.subs || [];
db.invites = db.invites || [];
const isAdmin = user => !!user && (user.admin === true || ADMIN_UIDS.includes(user.id));
function saveDb() { atomicWrite(dbFile, JSON.stringify(db, null, 2)); }
function atomicWrite(file, content) {
const tmp = file + '.tmp';
@@ -50,31 +69,112 @@ catch { vapid = webpush.generateVAPIDKeys(); fs.writeFileSync(vapidFile, JSON.st
const VAPID_SUBJECT = process.env.VAPID_SUBJECT || (SECURE ? ORIGIN : 'mailto:admin@localhost');
webpush.setVapidDetails(VAPID_SUBJECT, vapid.publicKey, vapid.privateKey);
/* A push subscription's `endpoint` is a URL this server connects out to, chosen by whoever is
signed in — so without a check /api/push/* is a request-forgery lever, and the api container
sits on the same Docker network as the rest of the self-hoster's stack. Three limits below:
1. PUSH_AGENT rejects any connection to a private/loopback/link-local address at the moment
the socket is opened. Validating the URL alone would leave a DNS-rebinding window — the
name is resolved a second time inside web-push — so the check has to live in the lookup
the request itself uses, not in a prior pass.
2. PUSH_TIMEOUT_MS: an endpoint that accepts TCP and then stalls used to hang the request
handler that awaited it, indefinitely. web-push sets no timeout of its own.
3. PUSH_CONCURRENCY: one small request must not turn into an unbounded burst of outbound
connections (with MAX_SUBS_PER_USER below, that is the other half of the same problem). */
const PUSH_TIMEOUT_MS = 10000;
const PUSH_CONCURRENCY = 6;
const MAX_SUBS_PER_USER = 20;
function isPrivateAddr(ip) {
const v = String(ip).toLowerCase();
const m4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(v);
if (m4) {
const a = +m4[1], b = +m4[2];
if (a === 0 || a === 10 || a === 127) return true; // this-network, private, loopback
if (a === 169 && b === 254) return true; // link-local (cloud metadata)
if (a === 172 && b >= 16 && b <= 31) return true; // private
if (a === 192 && b === 168) return true; // private
if (a === 192 && b === 0) return true; // 192.0.0.0/24, 192.0.2.0/24
if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT
if (a >= 224) return true; // multicast + reserved
return false;
}
const m6 = /^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.exec(v);
if (m6) return isPrivateAddr(m6[1]); // IPv4-mapped IPv6
if (v === '::' || v === '::1') return true; // unspecified, loopback
if (/^fe[89ab]/.test(v)) return true; // link-local
if (/^f[cd]/.test(v)) return true; // unique local
return false;
}
// Same shape as dns.lookup, so https.Agent can use it directly.
function guardedLookup(hostname, options, cb) {
dns.lookup(hostname, options, (err, address, family) => {
if (err) return cb(err);
const list = Array.isArray(address) ? address : [{ address, family }];
if (list.some(a => isPrivateAddr(a.address))) {
return cb(Object.assign(new Error('refusing to connect to a private address: ' + hostname), { code: 'EPUSHBLOCKED' }));
}
cb(null, address, family);
});
}
const PUSH_AGENT = new https.Agent({ lookup: guardedLookup, keepAlive: false });
// Cheap pre-check so a bad endpoint is refused at subscribe time with a useful message, rather
// than silently never delivering. PUSH_AGENT is what actually enforces the address rule.
function pushEndpointError(raw) {
let u;
try { u = new URL(String(raw || '')); } catch { return 'endpoint is not a valid URL'; }
if (u.protocol !== 'https:') return 'endpoint must be an https:// URL';
if (u.username || u.password) return 'endpoint must not carry credentials';
// A literal address can be judged right here, which turns the common case into a clear error
// at subscribe time instead of a delivery that quietly never happens. Hostnames are left to
// PUSH_AGENT, which is the check that actually has to hold.
const host = u.hostname.replace(/^\[|\]$/g, '');
if (/^[0-9.]+$/.test(host) || host.includes(':')) {
if (isPrivateAddr(host)) return 'endpoint must not point at a private address';
}
return null;
}
async function sendPush(userId, payload) {
const subs = db.subs.filter(s => s.userId === userId);
if (!subs.length) return;
const body = JSON.stringify(payload);
let dirty = false;
await Promise.all(subs.map(async sub => {
try { await webpush.sendNotification({ endpoint: sub.endpoint, keys: sub.keys }, body); }
catch (e) {
if (e.statusCode === 404 || e.statusCode === 410) {
db.subs = db.subs.filter(s => s.endpoint !== sub.endpoint); dirty = true;
let next = 0;
const worker = async () => {
while (next < subs.length) {
const sub = subs[next++];
// urgency 'high' is the one lever we have over delivery speed — iOS/Android throttle
// low-urgency background push more aggressively under battery-saving modes. TTL is left
// at the library default (long) so a briefly-offline device still gets it once reconnected,
// rather than risking it being dropped for the sake of shaving off latency that TTL doesn't
// actually control anyway.
try {
await webpush.sendNotification({ endpoint: sub.endpoint, keys: sub.keys }, body,
{ urgency: 'high', timeout: PUSH_TIMEOUT_MS, agent: PUSH_AGENT });
} catch (e) {
console.error('push send failed', userId, e.statusCode, e.body || e.message);
if (e.statusCode === 404 || e.statusCode === 410) {
db.subs = db.subs.filter(s => s.endpoint !== sub.endpoint); dirty = true;
}
}
}
}));
};
await Promise.all(Array.from({ length: Math.min(PUSH_CONCURRENCY, subs.length) }, worker));
if (dirty) saveDb();
}
// Rest-timer alerts: client schedules on start/extend, cancels on skip or on-screen completion —
// this only fires when the tab was backgrounded/suspended and never got to cancel it itself.
const restTimers = new Map(); // userId -> Timeout
function scheduleRestTimer(userId, sec) {
function scheduleRestTimer(userId, sec, lang) {
const t = restTimers.get(userId);
if (t) clearTimeout(t);
restTimers.set(userId, setTimeout(() => {
restTimers.delete(userId);
sendPush(userId, { title: 'Rest over 💪', body: 'Time for your next set.', tag: 'rest-timer' });
sendPush(userId, restTimerPush(lang));
}, sec * 1000));
}
function cancelRestTimer(userId) {
@@ -91,32 +191,38 @@ function effectiveRoutineId(S, iso) {
const wd = new Date(iso + 'T12:00:00').getDay();
return S.week?.[wd] || null;
}
const todayISO = () => {
const d = new Date();
return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
};
// Computes "now" in an arbitrary IANA zone (e.g. "Europe/Lisbon") instead of the server's own —
// each user's reminder fires by their own clock, wherever they and their phone actually are.
function userNow(tz) {
try {
const parts = new Intl.DateTimeFormat('en-CA', {
timeZone: tz, hour12: false,
year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit'
}).formatToParts(new Date());
const g = t => parts.find(p => p.type === t)?.value;
return { date: `${g('year')}-${g('month')}-${g('day')}`, hhmm: `${g('hour')}:${g('minute')}` };
} catch { return null; } // unknown/invalid tz string — skip this user rather than guess
}
setInterval(() => {
const now = new Date();
const hhmm = String(now.getHours()).padStart(2, '0') + ':' + String(now.getMinutes()).padStart(2, '0');
const today = todayISO();
for (const user of db.users) {
if (user.lastReminder === today) continue;
if (!db.subs.some(s => s.userId === user.id)) continue;
const S = readState(user.id);
if (!S?.reminder?.on || S.reminder.time !== hhmm) continue;
if ((S.workouts || []).some(w => w.d === today)) continue;
const rid = effectiveRoutineId(S, today);
if (!S?.reminder?.on) continue;
const now = userNow(S.reminder.tz || 'UTC');
if (!now || S.reminder.time !== now.hhmm) continue;
if (user.lastReminder === now.date) continue;
if ((S.workouts || []).some(w => w.d === now.date)) continue;
const rid = effectiveRoutineId(S, now.date);
if (!rid) continue; // rest day — nothing planned
const routine = (S.routines || []).find(r => r.id === rid);
user.lastReminder = today;
console.log('reminder firing', user.id, rid);
user.lastReminder = now.date;
saveDb();
sendPush(user.id, {
title: routine ? `${routine.emoji || '🏋️'} ${routine.name} today` : 'Workout planned today',
body: "It's on your plan — let's go 💪",
tag: 'day-reminder'
});
sendPush(user.id, dayReminderPush(S.lang, routine));
}
}, 60000).unref();
// Checked every 10s (not 60s) — ticks aren't aligned to the top of the minute, so a 60s
// interval could sit on your target minute for up to 59s before noticing. 10s caps that at ~9s.
}, 10000).unref();
/* ---------- sessions (signed cookie) ---------- */
function sign(payload) {
@@ -133,26 +239,127 @@ function verifySig(token) {
} catch { return null; }
return payload;
}
function makeSession(uid) {
// Session payload is `<uid>:<expiry>:<version>`, where the version is the user's `sv` counter.
// Bumping `sv` (POST /api/logout/all) makes every cookie ever handed out for that account stop
// verifying, which is the only revocation there was before short of deleting ./data/secret and
// signing out the whole instance. Cookies minted before `sv` existed have no third field and are
// read as version 0, matching a user who has never bumped — they stay valid until they expire.
const sessionVersion = user => user.sv || 0;
function makeSession(user) {
const exp = Date.now() + SESSION_DAYS * 86400000;
return sign(uid + ':' + exp);
return sign(user.id + ':' + exp + ':' + sessionVersion(user));
}
// With the __Host- prefix the *browser* guarantees the cookie is host-only (no Domain attribute
// is even allowed) — which is what stops a sibling subdomain, e.g. anything-else.example.com
// against gym.example.com, from planting a second session cookie for the shared parent domain
// and having it shadow the real one. The prefix also requires Secure, so it only works on an
// https ORIGIN; over plain http://localhost the old name stays, and localhost has no sibling
// subdomains to worry about. Both names are accepted on the way in, so upgrading an instance
// does not sign anybody out — they move onto the prefixed cookie at their next sign-in.
const COOKIE = SECURE ? '__Host-gymsid' : 'gymsid';
const LEGACY_COOKIE = 'gymsid';
// Every value for a given name, in the order the browser sent them. Not an object: reducing
// duplicates to one entry silently picks a winner, and picking the *last* one handed a shadowing
// cookie the session outright.
function cookieValues(req, name) {
const out = [];
for (const c of (req.headers.cookie || '').split(';')) {
const i = c.indexOf('=');
if (i < 0) continue;
if (c.slice(0, i).trim() === name) out.push(c.slice(i + 1).trim());
}
return out;
}
function cookieToken(req) {
for (const name of (COOKIE === LEGACY_COOKIE ? [COOKIE] : [COOKIE, LEGACY_COOKIE])) {
const vals = cookieValues(req, name);
if (!vals.length) continue;
// Two different values under one name is not something a browser does on its own — it means
// somebody else got to set one. There is no safe way to guess which is the real session, so
// refuse both: a signed-out user signs back in, a shadowing attempt gets nothing.
if (vals.some(v => v !== vals[0])) return null;
return vals[0];
}
return null;
}
function readSession(req) {
const cookies = Object.fromEntries((req.headers.cookie || '').split(';').map(c => {
const i = c.indexOf('='); return i < 0 ? ['', ''] : [c.slice(0, i).trim(), c.slice(i + 1).trim()];
}));
const tok = cookies.gymsid;
// The paired mobile app has no cookie jar shared with the API's origin, so it carries the same
// signed token in an Authorization header instead — same payload, same verification below.
const auth = req.headers.authorization || '';
const tok = cookieToken(req) || (auth.startsWith('Bearer ') ? auth.slice(7).trim() : null);
if (!tok) return null;
const payload = verifySig(tok);
if (!payload) return null;
const [uid, exp] = payload.split(':');
const [uid, exp, ver] = payload.split(':');
if (!uid || +exp < Date.now()) return null;
return db.users.find(u => u.id === uid) || null;
const user = db.users.find(u => u.id === uid) || null;
if (!user) return null;
if (user.disabled) return null; // disabled accounts are locked out everywhere
// Missing third field = pre-versioning cookie = version 0. Anything non-numeric is a malformed
// payload (it still had to pass the HMAC, so this is belt-and-braces) and is refused outright.
const claimed = ver === undefined ? 0 : Number(ver);
if (!Number.isInteger(claimed) || claimed !== sessionVersion(user)) return null;
return user;
}
function sessionCookie(uid) {
return `gymsid=${makeSession(uid)}; Path=/; Max-Age=${SESSION_DAYS * 86400}; HttpOnly;${SECURE} SameSite=Lax`;
// Guard for /api/admin/* — resolves the caller and 401/403s if they aren't an admin.
function requireAdmin(req, res) {
const user = readSession(req);
if (!user) { json(res, 401, { error: 'not signed in' }); return null; }
// Only the 403 is recorded: a 401 is any unauthenticated bot poking /api/admin/*, and
// logging those would bury the events an operator actually wants to see.
if (!isAdmin(user)) { audit(req, 'admin.denied', { ok: false, user }); json(res, 403, { error: 'forbidden' }); return null; }
return user;
}
const expireCookie = name => `${name}=; Path=/; Max-Age=0; HttpOnly;${SECURE} SameSite=Lax`;
function sessionCookie(user) {
const fresh = `${COOKIE}=${makeSession(user)}; Path=/; Max-Age=${SESSION_DAYS * 86400}; HttpOnly;${SECURE} SameSite=Lax`;
// Signing in also retires any pre-upgrade cookie, so nobody is left carrying an unprefixed one
// (or a shadowing copy of it) alongside the new session.
return COOKIE === LEGACY_COOKIE ? [fresh] : [fresh, expireCookie(LEGACY_COOKIE)];
}
const clearCookie = COOKIE === LEGACY_COOKIE
? [expireCookie(LEGACY_COOKIE)]
: [expireCookie(COOKIE), expireCookie(LEGACY_COOKIE)];
/* ---------- CSRF ---------- */
// SameSite=Lax keeps the session cookie off a genuinely cross-*site* request. It does not keep it
// off a *sibling subdomain*: gym.example.com and anything-else.example.com are the same site, and
// that is the ordinary self-hosting layout — one domain, one reverse proxy, several apps. Nothing
// else in a request was being checked either; readBody() JSON.parse's the body whatever the
// Content-Type claims, so a hostile page could reach the state-changing routes with a form-style
// POST that needs no CORS preflight at all.
//
// So a state-changing request that came from a browser has to come from ORIGIN. The exemptions
// below are not holes: each of those routes carries its own credential in the body (a WebAuthn
// challenge id, a one-shot pairing code), none of them acts on the caller's existing session, and
// they have to keep working from the mobile WebView, whose origin is never ORIGIN.
const CSRF_EXEMPT = new Set([
'POST /api/register/options', 'POST /api/register/verify',
'POST /api/login/options', 'POST /api/login/verify',
'POST /api/pair/redeem'
]);
const originsMatch = (a, b) => a.replace(/\/+$/, '') === b.replace(/\/+$/, '');
function csrfOk(req, key) {
if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') return true;
if (CSRF_EXEMPT.has(key)) return true;
// The paired mobile app authenticates with a Bearer token. A browser never attaches one on its
// own, so there is no ambient authority for a hostile page to borrow and no origin to check.
if ((req.headers.authorization || '').startsWith('Bearer ')) return true;
// Sec-Fetch-Site is set by the browser itself and no page can forge it, and it states exactly
// the property wanted here — more precisely than comparing origins can. 'same-origin' is the
// app talking to its own backend; a hostile page reports 'cross-site'; a sibling subdomain,
// the case SameSite=Lax misses entirely, reports 'same-site'. It is also what keeps the Vite
// dev server working, where the page is on another port and its Origin is legitimately not
// ORIGIN. Absent on older Safari and on proxies that strip it, hence the fallback below.
const site = req.headers['sec-fetch-site'];
if (site) return site === 'same-origin' || site === 'none';
const origin = req.headers.origin;
// No Origin header at all means no browser sent this — curl, a script, a monitoring check.
// Browsers put an Origin on every state-changing request and a page cannot suppress it, so the
// forgery this exists to stop always carries one.
if (!origin) return true;
return originsMatch(origin, ORIGIN);
}
const clearCookie = `gymsid=; Path=/; Max-Age=0; HttpOnly;${SECURE} SameSite=Lax`;
/* ---------- challenge store (in-memory, 5 min TTL) ---------- */
const challenges = new Map(); // cid -> {challenge, name?, uid?, exp}
@@ -169,6 +376,21 @@ function takeChallenge(cid) {
}
setInterval(() => { for (const [k, v] of challenges) if (v.exp < Date.now()) challenges.delete(k); }, 60000).unref();
// ---------- device pairing (mobile app "connect to my server", no WebAuthn ceremony) ----------
// A passkey ceremony can't run inside the app's WebView (its origin never matches RP_ID), so the
// app authenticates by redeeming a short code minted from an already signed-in browser tab —
// same 5-min-TTL/one-shot shape as the WebAuthn challenge store above.
const pairings = new Map(); // code -> {uid, exp}
const PAIR_CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // no 0/O/1/I — read off a screen
function makePairCode() {
let code;
do {
code = Array.from(crypto.randomBytes(8)).map(b => PAIR_CODE_ALPHABET[b % PAIR_CODE_ALPHABET.length]).join('');
} while (pairings.has(code));
return code;
}
setInterval(() => { for (const [k, v] of pairings) if (v.exp < Date.now()) pairings.delete(k); }, 60000).unref();
/* ---------- helpers ---------- */
function json(res, code, obj, extraHeaders) {
const body = JSON.stringify(obj);
@@ -192,20 +414,136 @@ function readBody(req) {
}
const b64uToBuf = s => Buffer.from(s, 'base64url');
/* ---------- live presence (in-memory) ---------- */
// Clients heartbeat /api/activity while a workout is on screen; the admin dashboard reads who's
// live. Purely ephemeral — never persisted. Expires shortly after the last ping.
const presence = new Map(); // uid -> { name, exIdx, exTotal, setsDone, setsTotal, startedAt, updatedAt }
const PRESENCE_TTL = 70000; // ~3.5× the 20s client heartbeat
function livePresence(uid) {
const p = presence.get(uid);
if (!p) return null;
if (Date.now() - p.updatedAt > PRESENCE_TTL) { presence.delete(uid); return null; }
return p;
}
setInterval(() => { for (const [k, v] of presence) if (Date.now() - v.updatedAt > PRESENCE_TTL) presence.delete(k); }, 30000).unref();
/* ---------- audit log ---------- */
// Who signed in, who tried and failed, and what an admin changed. One JSON object per line in
// ./data/audit.log, appended and never rewritten in place. It deliberately does not live in
// db.json: that file is rewritten whole on every save, and the login/register handshakes are
// unauthenticated and unthrottled by design (see SECURITY.md), so an audit trail in there would
// turn one bogus request into a full db.json rewrite. A line torn by a crash costs one event and
// is dropped on read.
//
// On by default. It records strictly less than the instance already holds — every account is in
// db.json and every workout is in state-<uid>.json, both readable by any admin — and a security
// feature that ships switched off protects nobody. IP addresses are the exception: off unless you
// ask for them, because they are the one field here that says where somebody physically is.
const AUDIT_ON = !/^(0|false|no|off)$/i.test(process.env.AUDIT_LOG || '');
const AUDIT_MAX = Math.max(0, +(process.env.AUDIT_MAX || 5000) || 0); // 0 = no count cap
const AUDIT_DAYS = Math.max(0, +(process.env.AUDIT_DAYS || 90) || 0); // 0 = no age cap
const AUDIT_IP = /^full$/i.test(process.env.AUDIT_IP || '') ? 'full'
: /^(1|true|yes|on|net)$/i.test(process.env.AUDIT_IP || '') ? 'net' : 'off';
const auditFile = path.join(DATA, 'audit.log');
let auditSeq = 0; // never reset, not even by a clear — a wiped log leaves a visible id gap
let auditCount = 0;
// Which header holds the caller depends on what is in front of the API. CF-Connecting-IP comes
// first because a Cloudflare tunnel does NOT forward the client in X-Forwarded-For — that header
// then only carries the tunnel's own container, which looks like a valid answer and isn't. After
// that, the first entry of X-Forwarded-For is the client and everything behind it is our own hops.
// All three are only as trustworthy as the proxy in front: it has to overwrite them rather than
// pass a client-supplied one through. In 'net' mode only the network survives — enough to tell
// one source from another, not enough to point at a person.
function clientIp(req) {
if (AUDIT_IP === 'off') return null;
const raw = String(req.headers['cf-connecting-ip'] || '').trim()
|| String(req.headers['x-forwarded-for'] || '').split(',')[0].trim()
|| String(req.headers['x-real-ip'] || '').trim()
// Nothing in front at all: the socket peer is the client, and it cannot be forged. Behind
// the bundled web container a header always wins before this is reached.
|| String(req.socket?.remoteAddress || '').replace(/^::ffff:/, '').trim();
const ip = raw.replace(/^\[|\]$/g, '').slice(0, 45);
if (!/^[0-9a-fA-F:.]{3,45}$/.test(ip)) return null; // never store a header verbatim
if (AUDIT_IP === 'full') return ip;
if (/^\d{1,3}(\.\d{1,3}){3}$/.test(ip)) return ip.replace(/\.\d{1,3}$/, '.0/24');
const g = ip.split(':').filter(Boolean).slice(0, 3).join(':');
return g ? g + '::/48' : null;
}
function auditLines() {
let text;
try { text = fs.readFileSync(auditFile, 'utf8'); } catch { return []; }
const rows = [];
for (const line of text.split('\n')) {
if (!line) continue;
try { const r = JSON.parse(line); if (r && r.id && r.ev) rows.push(r); } catch { /* torn line */ }
}
return rows;
}
// Retention is a cap, not an archive: age first, then the newest AUDIT_MAX of what's left.
function auditKeep(rows) {
let out = rows;
if (AUDIT_DAYS) { const cut = Date.now() - AUDIT_DAYS * 86400000; out = out.filter(r => r.ts >= cut); }
if (AUDIT_MAX && out.length > AUDIT_MAX) out = out.slice(out.length - AUDIT_MAX);
return out;
}
function compactAudit() {
const rows = auditLines();
for (const r of rows) if (+r.id > auditSeq) auditSeq = +r.id;
const keep = auditKeep(rows);
auditCount = keep.length;
if (keep.length === rows.length) return;
try { atomicWrite(auditFile, keep.map(r => JSON.stringify(r)).join('\n') + (keep.length ? '\n' : '')); }
catch (e) { console.error('audit compact failed', e.message); }
}
// Never throws: a log that can't be written must not break signing in.
function audit(req, ev, f = {}) {
if (!AUDIT_ON) return;
const rec = { id: ++auditSeq, ts: Date.now(), ev, ok: f.ok !== false };
if (f.user) { rec.uid = f.user.id; rec.name = String(f.user.name || '').slice(0, 40); }
else {
if (f.uid) rec.uid = f.uid;
if (f.name) rec.name = String(f.name).slice(0, 40);
}
if (f.target) { rec.tgt = f.target.id; rec.tname = String(f.target.name || '').slice(0, 40); }
if (f.msg) rec.msg = String(f.msg).slice(0, 120);
const ip = clientIp(req);
if (ip) rec.ip = ip;
try { fs.appendFileSync(auditFile, JSON.stringify(rec) + '\n'); }
catch (e) { return console.error('audit write failed', e.message); }
// Amortized: a 5000-event cap rewrites the file once per ~1250 events.
if (AUDIT_MAX && ++auditCount > AUDIT_MAX * 1.25) compactAudit();
}
if (AUDIT_ON) {
compactAudit(); // prune on boot, seed auditSeq/auditCount
setInterval(compactAudit, 3600000).unref(); // honour AUDIT_DAYS on an idle instance too
}
/* ---------- routes ---------- */
const routes = {
'GET /api/health': async (req, res) => json(res, 200, { ok: true, users: db.users.length }),
// Public config the login screen needs before anyone is signed in.
'GET /api/config': async (req, res) => json(res, 200, { invite_only: INVITE_ONLY, allow_guest: ALLOW_GUEST }),
'GET /api/me': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
json(res, 200, { user: { id: user.id, name: user.name } });
json(res, 200, { user: { id: user.id, name: user.name, admin: isAdmin(user) } });
},
'POST /api/register/options': async (req, res) => {
const body = await readBody(req);
const name = String(body.name || '').trim().slice(0, 40);
if (!name) return json(res, 400, { error: 'name required' });
const code = String(body.code || '').trim().toUpperCase();
if (INVITE_ONLY && !db.invites.some(i => i.code === code && !i.usedBy && !i.revoked)) {
// The rejected code itself is never recorded — a near-miss guess in the log is a liability.
audit(req, 'auth.register.denied', { ok: false, name, msg: 'invite-rejected' });
return json(res, 403, { error: 'a valid invite code is required' });
}
const uid = crypto.randomBytes(12).toString('base64url');
const options = await generateRegistrationOptions({
rpName: RP_NAME, rpID: RP_ID,
@@ -214,14 +552,17 @@ const routes = {
authenticatorSelection: { residentKey: 'required', userVerification: 'preferred' },
excludeCredentials: []
});
const cid = putChallenge({ challenge: options.challenge, name, uid });
const cid = putChallenge({ challenge: options.challenge, name, uid, code });
json(res, 200, { cid, options });
},
'POST /api/register/verify': async (req, res) => {
const body = await readBody(req);
const c = takeChallenge(body.cid);
if (!c || !c.uid) return json(res, 400, { error: 'challenge expired — try again' });
if (!c || !c.uid) {
audit(req, 'auth.register.fail', { ok: false, msg: 'challenge-expired' });
return json(res, 400, { error: 'challenge expired — try again' });
}
let verification;
try {
verification = await verifyRegistrationResponse({
@@ -231,11 +572,31 @@ const routes = {
expectedRPID: RP_ID,
requireUserVerification: false
});
} catch (e) { return json(res, 400, { error: 'verification failed: ' + e.message }); }
if (!verification.verified) return json(res, 400, { error: 'not verified' });
} catch (e) {
// e.message can echo attacker-supplied response fields, so only the reason code is kept.
audit(req, 'auth.register.fail', { ok: false, name: c.name, msg: 'verify-error' });
return json(res, 400, { error: verifyError(e, { rpId: RP_ID, origin: ORIGIN }) });
}
if (!verification.verified) {
audit(req, 'auth.register.fail', { ok: false, name: c.name, msg: 'not-verified' });
return json(res, 400, { error: 'not verified' });
}
const { credential } = verification.registrationInfo;
if (db.creds.find(x => x.id === credential.id)) return json(res, 409, { error: 'credential already registered' });
if (db.creds.find(x => x.id === credential.id)) {
audit(req, 'auth.register.fail', { ok: false, name: c.name, msg: 'credential-exists' });
return json(res, 409, { error: 'credential already registered' });
}
// Re-check the invite at the last moment (it may have been used/revoked since options), then burn it.
let invite = null;
if (INVITE_ONLY) {
invite = db.invites.find(i => i.code === c.code && !i.usedBy && !i.revoked);
if (!invite) {
audit(req, 'auth.register.fail', { ok: false, name: c.name, msg: 'invite-invalid' });
return json(res, 403, { error: 'invite code is no longer valid — ask for a new one' });
}
}
const user = { id: c.uid, name: c.name, created: new Date().toISOString() };
if (invite) { user.invitedBy = invite.code; invite.usedBy = user.id; invite.usedAt = user.created; }
db.users.push(user);
db.creds.push({
id: credential.id, userId: user.id,
@@ -244,7 +605,8 @@ const routes = {
transports: body.credential?.response?.transports || []
});
saveDb();
json(res, 200, { user: { id: user.id, name: user.name } }, { 'Set-Cookie': sessionCookie(user.id) });
audit(req, 'auth.register.ok', { user, msg: invite ? invite.code : null });
json(res, 200, { user: { id: user.id, name: user.name, admin: isAdmin(user) } }, { 'Set-Cookie': sessionCookie(user) });
},
'POST /api/login/options': async (req, res) => {
@@ -258,9 +620,18 @@ const routes = {
'POST /api/login/verify': async (req, res) => {
const body = await readBody(req);
const c = takeChallenge(body.cid);
if (!c) return json(res, 400, { error: 'challenge expired — try again' });
if (!c) {
audit(req, 'auth.login.fail', { ok: false, msg: 'challenge-expired' });
return json(res, 400, { error: 'challenge expired — try again' });
}
const cred = db.creds.find(x => x.id === body.credential?.id);
if (!cred) return json(res, 404, { error: 'unknown passkey — create a profile first' });
if (!cred) {
// No credential id goes in the log: it is a stable handle for one passkey, and recording it
// would let an admin correlate an unknown device across attempts. Nothing here identifies
// the caller beyond the timestamp (and the network, if AUDIT_IP is on).
audit(req, 'auth.login.fail', { ok: false, msg: 'unknown-credential' });
return json(res, 404, { error: 'unknown passkey — create a profile first' });
}
let verification;
try {
verification = await verifyAuthenticationResponse({
@@ -276,16 +647,80 @@ const routes = {
transports: cred.transports
}
});
} catch (e) { return json(res, 400, { error: 'verification failed: ' + e.message }); }
if (!verification.verified) return json(res, 400, { error: 'not verified' });
} catch (e) {
audit(req, 'auth.login.fail', { ok: false, user: db.users.find(u => u.id === cred.userId), uid: cred.userId, msg: 'verify-error' });
return json(res, 400, { error: verifyError(e, { rpId: RP_ID, origin: ORIGIN }) });
}
if (!verification.verified) {
audit(req, 'auth.login.fail', { ok: false, user: db.users.find(u => u.id === cred.userId), uid: cred.userId, msg: 'not-verified' });
return json(res, 400, { error: 'not verified' });
}
cred.counter = verification.authenticationInfo.newCounter;
saveDb();
const user = db.users.find(u => u.id === cred.userId);
if (!user) return json(res, 500, { error: 'user missing' });
json(res, 200, { user: { id: user.id, name: user.name } }, { 'Set-Cookie': sessionCookie(user.id) });
if (!user) {
audit(req, 'auth.login.fail', { ok: false, uid: cred.userId, msg: 'user-missing' });
return json(res, 500, { error: 'user missing' });
}
if (user.disabled) {
audit(req, 'auth.login.fail', { ok: false, user, msg: 'account-disabled' });
return json(res, 403, { error: 'this account has been disabled' });
}
audit(req, 'auth.login.ok', { user });
json(res, 200, { user: { id: user.id, name: user.name, admin: isAdmin(user) } }, { 'Set-Cookie': sessionCookie(user) });
},
'POST /api/logout': async (req, res) => json(res, 200, { ok: true }, { 'Set-Cookie': clearCookie }),
// Reads the session purely so the sign-out can be recorded; the cookie is cleared either way.
// A logout with no valid cookie is a no-op and isn't worth an entry.
'POST /api/logout': async (req, res) => {
const user = readSession(req);
if (user) audit(req, 'auth.logout', { user });
json(res, 200, { ok: true }, { 'Set-Cookie': clearCookie });
},
// "Sign out everywhere" — bumps this user's session version, which invalidates every cookie
// ever issued for the account, on every device, including a copy someone else walked off with.
// The caller's own cookie is cleared here too, so the browser doing it doesn't sit on a token
// it no longer accepts. Passkeys are untouched: signing back in works immediately.
'POST /api/logout/all': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
user.sv = sessionVersion(user) + 1;
saveDb();
audit(req, 'auth.logout.all', { user });
json(res, 200, { ok: true }, { 'Set-Cookie': clearCookie });
},
// Mobile app pairing: called from an already signed-in browser tab (Settings → "Pair the
// mobile app") to mint a short code the phone can redeem below.
'POST /api/pair/create': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
const code = makePairCode();
pairings.set(code, { uid: user.id, exp: Date.now() + 5 * 60000 });
audit(req, 'auth.pair.create', { user });
json(res, 200, { code });
},
// Called from the mobile app itself with the code shown in the browser. No session required —
// the code IS the credential, one-shot and 5-minute-lived like a WebAuthn challenge.
'POST /api/pair/redeem': async (req, res) => {
const body = await readBody(req);
const code = String(body.code || '').trim().toUpperCase();
const p = pairings.get(code);
if (p) pairings.delete(code);
if (!p || p.exp < Date.now()) {
audit(req, 'auth.pair.fail', { ok: false, msg: 'code-invalid' });
return json(res, 400, { error: 'invalid or expired code' });
}
const user = db.users.find(u => u.id === p.uid);
if (!user || user.disabled) {
audit(req, 'auth.pair.fail', { ok: false, uid: p.uid, msg: 'user-unavailable' });
return json(res, 400, { error: 'invalid or expired code' });
}
audit(req, 'auth.pair.ok', { user });
json(res, 200, { token: makeSession(user), user: { id: user.id, name: user.name, admin: isAdmin(user) } });
},
'GET /api/data': async (req, res) => {
const user = readSession(req);
@@ -314,8 +749,21 @@ const routes = {
const body = await readBody(req);
const sub = body.subscription;
if (!sub?.endpoint || !sub?.keys?.p256dh || !sub?.keys?.auth) return json(res, 400, { error: 'invalid subscription' });
const bad = pushEndpointError(sub.endpoint);
if (bad) return json(res, 400, { error: bad });
// Only the two keys the push protocol needs are kept: `sub` is caller-supplied and would
// otherwise put arbitrary fields into db.json, which every admin route reads back out.
const keys = { p256dh: String(sub.keys.p256dh), auth: String(sub.keys.auth) };
db.subs = db.subs.filter(s => s.endpoint !== sub.endpoint);
db.subs.push({ userId: user.id, endpoint: sub.endpoint, keys: sub.keys, created: new Date().toISOString() });
// A browser holds one subscription per device, so this cap is far above real use. Without
// it a single account could pile up endpoints without limit — every one of them a target
// sendPush() would then contact, and a whole rewrite of db.json per addition.
const mine = db.subs.filter(s => s.userId === user.id);
if (mine.length >= MAX_SUBS_PER_USER) {
const drop = new Set(mine.slice(0, mine.length - MAX_SUBS_PER_USER + 1).map(s => s.endpoint));
db.subs = db.subs.filter(s => !drop.has(s.endpoint));
}
db.subs.push({ userId: user.id, endpoint: sub.endpoint, keys, created: new Date().toISOString() });
saveDb();
json(res, 200, { ok: true });
},
@@ -332,7 +780,7 @@ const routes = {
'POST /api/push/test': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
await sendPush(user.id, { title: 'openGym', body: 'Test notification ✅ — this is what alerts look like.', tag: 'test' });
await sendPush(user.id, testPush(readState(user.id)?.lang));
json(res, 200, { ok: true });
},
@@ -342,7 +790,7 @@ const routes = {
const body = await readBody(req);
const sec = Math.max(1, Math.min(3600, Math.round(+body.seconds || 0)));
if (!sec) return json(res, 400, { error: 'seconds required' });
scheduleRestTimer(user.id, sec);
scheduleRestTimer(user.id, sec, readState(user.id)?.lang);
json(res, 200, { ok: true });
},
@@ -351,14 +799,176 @@ const routes = {
if (!user) return json(res, 401, { error: 'not signed in' });
cancelRestTimer(user.id);
json(res, 200, { ok: true });
},
// Live-workout heartbeat: client pings while a workout is on screen; { active:false } drops it.
'POST /api/activity': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
const body = await readBody(req);
if (body.active) {
presence.set(user.id, {
name: String(body.name || '').slice(0, 60),
exIdx: +body.exIdx || 0, exTotal: +body.exTotal || 0,
setsDone: +body.setsDone || 0, setsTotal: +body.setsTotal || 0,
startedAt: +body.startedAt || Date.now(),
updatedAt: Date.now()
});
} else presence.delete(user.id);
json(res, 200, { ok: true });
},
/* ---------- admin dashboard ---------- */
// One row per user, cheap enough for a personal instance (reads each state file once).
'GET /api/admin/users': async (req, res) => {
if (!requireAdmin(req, res)) return;
const users = db.users.map(u => {
const S = readState(u.id) || {};
const workouts = S.workouts || [];
const last = workouts[workouts.length - 1];
return {
id: u.id, name: u.name, created: u.created || null,
disabled: !!u.disabled, admin: isAdmin(u), invitedBy: u.invitedBy || null,
workouts: workouts.length,
lastWorkout: last ? last.d : null,
lastSync: S._ts || null,
hasPush: db.subs.some(s => s.userId === u.id),
live: livePresence(u.id)
};
});
json(res, 200, { users, invite_only: INVITE_ONLY, now: Date.now() });
},
// Drill-down: full workout history + body-weight log for one user.
'GET /api/admin/user': async (req, res) => {
if (!requireAdmin(req, res)) return;
const id = new URL(req.url, 'http://x').searchParams.get('id');
const u = db.users.find(x => x.id === id);
if (!u) return json(res, 404, { error: 'no such user' });
const S = readState(u.id) || {};
json(res, 200, {
user: { id: u.id, name: u.name, created: u.created || null, disabled: !!u.disabled, admin: isAdmin(u), invitedBy: u.invitedBy || null },
unit: S.unit || 'kg',
lastSync: S._ts || null,
routines: (S.routines || []).map(r => ({ id: r.id, name: r.name, emoji: r.emoji, count: (r.ex || []).length })),
bodyweight: S.bodyweight || [],
workouts: (S.workouts || []).slice().reverse() // newest first for display
});
},
'POST /api/admin/user/disable': async (req, res) => {
const admin = requireAdmin(req, res); if (!admin) return;
const body = await readBody(req);
const u = db.users.find(x => x.id === body.id);
if (!u) return json(res, 404, { error: 'no such user' });
if (isAdmin(u)) return json(res, 400, { error: 'cannot disable an admin' });
u.disabled = !!body.disabled;
if (u.disabled) presence.delete(u.id); // drop them off "training now" at once
saveDb();
audit(req, u.disabled ? 'admin.user.disable' : 'admin.user.enable', { user: admin, target: u });
json(res, 200, { ok: true, id: u.id, disabled: u.disabled });
},
'GET /api/admin/invites': async (req, res) => {
if (!requireAdmin(req, res)) return;
// resolve usedBy uid → name for display
const invites = db.invites.map(i => ({
...i, usedByName: i.usedBy ? (db.users.find(u => u.id === i.usedBy) || {}).name || null : null
}));
json(res, 200, { invites, invite_only: INVITE_ONLY });
},
'POST /api/admin/invites/new': async (req, res) => {
const admin = requireAdmin(req, res); if (!admin) return;
const body = await readBody(req);
let code;
// 16 hex chars = 64 bits, up from 8 chars / 32 bits. The app has no rate limiting by design
// (that's the reverse proxy's job) and /api/register/options tells a caller whether a code is
// good, so the code itself has to be the thing that isn't worth guessing. Codes already in
// db.json keep working — validation is an exact string compare, never a length or format check.
do { code = crypto.randomBytes(8).toString('hex').toUpperCase(); } while (db.invites.some(i => i.code === code));
const invite = { code, note: String(body.note || '').slice(0, 60), createdBy: admin.id, created: new Date().toISOString() };
db.invites.push(invite);
saveDb();
audit(req, 'admin.invite.create', { user: admin, msg: code });
json(res, 200, { invite });
},
'POST /api/admin/invites/revoke': async (req, res) => {
const admin = requireAdmin(req, res); if (!admin) return;
const body = await readBody(req);
const inv = db.invites.find(i => i.code === String(body.code || '').toUpperCase());
if (!inv) return json(res, 404, { error: 'no such code' });
if (inv.usedBy) return json(res, 400, { error: 'already used — cannot revoke' });
db.invites = db.invites.filter(i => i.code !== inv.code);
saveDb();
audit(req, 'admin.invite.revoke', { user: admin, msg: inv.code });
json(res, 200, { ok: true });
},
/* ---------- activity log ---------- */
// Newest first, paged by id. Not by offset: the log grows at the front of this view, so an
// offset cursor would repeat a row whenever an event lands between two pages; and not by
// timestamp, because two events can share a millisecond. auditKeep() runs on read as well as
// on the hourly compaction, so nothing past its retention is ever served.
'GET /api/admin/audit': async (req, res) => {
if (!requireAdmin(req, res)) return;
const q = new URL(req.url, 'http://x').searchParams;
const limit = Math.max(1, Math.min(200, +q.get('limit') || 100));
const before = +q.get('before') || Infinity;
const cat = q.get('cat') || '';
let rows = auditKeep(auditLines()).reverse();
if (cat === 'fail') rows = rows.filter(r => !r.ok);
else if (cat) rows = rows.filter(r => String(r.ev).startsWith(cat + '.'));
const page = rows.filter(r => r.id < before).slice(0, limit);
json(res, 200, {
events: page,
total: rows.length,
nextBefore: page.length === limit ? page[page.length - 1].id : null,
enabled: AUDIT_ON, ip_mode: AUDIT_IP,
retention: { max: AUDIT_MAX, days: AUDIT_DAYS },
now: Date.now()
});
},
// Deleting the log is itself logged, and auditSeq is not reset — so a clear always leaves a
// visible gap in the ids and can't be used to quietly erase a trace. There is no export route:
// ./data/audit.log already is the export, in a format jq reads directly.
'POST /api/admin/audit/clear': async (req, res) => {
const admin = requireAdmin(req, res); if (!admin) return;
try { fs.unlinkSync(auditFile); } catch { /* nothing logged yet */ }
auditCount = 0;
audit(req, 'admin.audit.clear', { user: admin });
json(res, 200, { ok: true });
}
};
http.createServer(async (req, res) => {
// Same-origin (the deployed nginx-proxied web app) never triggers CORS, so this only matters
// for the paired mobile app calling in from its own WebView origin. It carries no cookie
// (auth is the Authorization header instead), so Allow-Credentials is deliberately never set —
// reflecting the origin here can't expose the cookie session to anyone.
const origin = req.headers.origin;
if (origin) { res.setHeader('Access-Control-Allow-Origin', origin); res.setHeader('Vary', 'Origin'); }
if (req.method === 'OPTIONS') {
res.writeHead(204, {
'Access-Control-Allow-Methods': 'GET,POST,PUT,DELETE,OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Max-Age': '86400'
});
return res.end();
}
const url = new URL(req.url, 'http://x');
const key = req.method + ' ' + url.pathname;
const handler = routes[key];
if (!handler) return json(res, 404, { error: 'not found' });
if (!csrfOk(req, key)) {
// Logged, not audited: this is reachable without a session, and an audit entry per attempt
// would let anyone fill the log. An operator who has genuinely mis-set ORIGIN needs to see
// the mismatch, and the container log is where they will look.
console.warn('refused cross-origin', key, 'origin=' + req.headers.origin, 'expected=' + ORIGIN);
return json(res, 403, { error: 'cross-origin request refused' });
}
try { await handler(req, res); }
catch (e) {
console.error(key, e);
+12
View File
@@ -0,0 +1,12 @@
// @simplewebauthn reports an RP_ID or origin mismatch as an opaque "Unexpected ..." string, and
// whoever reads it in the browser has no way to connect that to their .env. A misconfigured
// RP_ID/ORIGIN is the single most common self-hosting failure (see docs/SELF_HOSTING.md), so
// name both values back. Neither is a secret: one is the address bar, the other its hostname.
const MISCONFIGURED = /unexpected (rp id|authentication response origin|registration response origin)/i;
export function verifyError(e, { rpId, origin } = {}) {
const msg = String((e && e.message) || 'verification failed');
if (!MISCONFIGURED.test(msg)) return 'verification failed: ' + msg;
return `${msg} — this server is configured with RP_ID=${rpId} and ORIGIN=${origin}, and both `
+ 'must match the address you opened. See docs/SELF_HOSTING.md.';
}
+29
View File
@@ -0,0 +1,29 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { verifyError } from './verify-error.js';
const cfg = { rpId: 'gym.example.com', origin: 'https://gym.example.com' };
test('names the configured values when the RP ID does not match', () => {
const out = verifyError(new Error('Unexpected RP ID hash'), cfg);
assert.match(out, /RP_ID=gym\.example\.com/);
assert.match(out, /ORIGIN=https:\/\/gym\.example\.com/);
assert.match(out, /SELF_HOSTING\.md/);
});
test('does the same for an origin mismatch, on login and on registration', () => {
assert.match(verifyError(new Error('Unexpected authentication response origin'), cfg), /must match the address you opened/);
assert.match(verifyError(new Error('Unexpected registration response origin'), cfg), /must match the address you opened/);
});
test('leaves an unrelated verification failure alone', () => {
assert.equal(
verifyError(new Error('Signature verification failed'), cfg),
'verification failed: Signature verification failed'
);
});
test('does not throw on a missing or empty error', () => {
assert.equal(verifyError(undefined, cfg), 'verification failed: verification failed');
assert.equal(verifyError(new Error(''), cfg), 'verification failed: verification failed');
});
Binary file not shown.

Before

Width:  |  Height:  |  Size: 137 KiB

After

Width:  |  Height:  |  Size: 187 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 204 KiB

After

Width:  |  Height:  |  Size: 320 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 120 KiB

After

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 133 KiB

After

Width:  |  Height:  |  Size: 296 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 225 KiB

After

Width:  |  Height:  |  Size: 246 KiB

+28 -5
View File
@@ -2,7 +2,10 @@ name: opengym
services:
# One-time: download the exercise images + GIFs into ./media (skipped if already there).
# ~140 MB, from github.com/hasaneyldrm/exercises-dataset (CC).
# ~140 MB, from github.com/hasaneyldrm/exercises-dataset. That dataset is MIT for the
# metadata and instruction text, but the images and GIFs are © Gym visual
# (https://gymvisual.com/) and are used under the dataset's terms — openGym neither
# redistributes nor relicenses them. See NOTICE.md.
media:
image: alpine/git
volumes:
@@ -13,6 +16,14 @@ services:
- |
if [ -z "$$(ls -A /out/img 2>/dev/null)" ]; then
echo "↓ Downloading exercise media (~140 MB, one time)…"
echo " Source: github.com/hasaneyldrm/exercises-dataset"
echo " Metadata and instruction text: MIT."
echo " Images and animations: © Gym visual — https://gymvisual.com/"
echo " They are used under that dataset's terms, not openGym's AGPL, and are"
echo " downloaded from upstream — openGym does not redistribute them."
echo " Terms: https://gymvisual.com/content/3-terms-and-conditions-of-use"
echo " Reusing this media yourself, commercially or not, needs your own licence"
echo " from Gym visual. Details in NOTICE.md."
git clone --depth 1 https://github.com/hasaneyldrm/exercises-dataset /tmp/ds
cp /tmp/ds/images/*.jpg /out/img/ && cp /tmp/ds/videos/*.gif /out/gif/
echo "✓ Exercise media ready ($$(ls /out/img | wc -l) images)."
@@ -24,12 +35,14 @@ services:
# Passkey auth + per-user data (Node, no framework).
# image: prebuilt (docker compose pull). build: from source (docker compose up --build).
api:
image: ghcr.io/duartesantos8/opengym-api:latest
image: registry.gitlab.com/duartesantos8/opengym/api:latest
build: ./api
restart: unless-stopped
env_file: .env
environment:
- PORT=3000 # internal port (nginx proxies here) — do not change
# The port the API listens on. web proxies to this same value, so the two
# cannot drift — change it in .env and both follow.
- PORT=${PORT:-3000}
- DATA_DIR=/data
volumes:
- ./data:/data # users, passkeys, per-user state, session secret — BACK THIS UP
@@ -37,7 +50,7 @@ services:
# Builds the React frontend (multi-stage) and serves it, proxying /api → api
# and the exercise media from the shared volume. Single origin for passkeys.
web:
image: ghcr.io/duartesantos8/opengym-web:latest
image: registry.gitlab.com/duartesantos8/opengym/web:latest
build:
context: .
dockerfile: web/Dockerfile
@@ -48,7 +61,17 @@ services:
api:
condition: service_started
ports:
- "${WEB_PORT:-8080}:80"
- "${WEB_PORT:-8080}:${NGINX_PORT:-80}"
# nginx renders its config at start-up from these (web/nginx.conf.template),
# so the API service does not have to be called `api`. Defaults are the old
# hardcoded values, so an existing .env and an existing stack are unaffected.
environment:
- NGINX_PORT=${NGINX_PORT:-80}
- BACKEND=${BACKEND:-api}
- PORT=${PORT:-3000}
# Empty drops the CF-Connecting-IP header, so a direct client cannot forge the address
# the activity log records. Cloudflare users set CF_CONNECTING_IP=$$http_cf_connecting_ip.
- CF_CONNECTING_IP=${CF_CONNECTING_IP:-}
volumes:
- ./media/img:/usr/share/nginx/html/img:ro
- ./media/gif:/usr/share/nginx/html/gif:ro
+73
View File
@@ -0,0 +1,73 @@
# Importing Data
## Plans
Plans/routines can be imported from a plain text json file.
The app supports exporting and an export always contain *every* current routine.
If you don't want to share every plan that you have currently created, you can either:
- edit the exported json with a text editor
or (if you don't feel like editing json files):
- open the [Demo](https://opengym.duarte-santos.ch/demo/#/home)
- import your plans
- make changes
- export a new json file for sharing
If you are using the standalone app on your mobile, you can use the demo for creating plans on your PC and import them.
The demo stores all data in your browser, it is not public or shared in any way.
Writing a json file yourself will be a bit of a complex task since the IDs of the exercises have to match the IDs in the database.
## History
To import your history from other applications, you'll need an export that is in `CSV` format.
The app tries to match the exercise names to link them to the exercises in the database.
> Note: The history is a log of past exercises.
> Because plans change and history does not, it is completely disconnected from routines.
These apps have been tested to work without adjustments:
| App | How to export |
|---|---|
| **FitNotes (Android)** | Settings → Backup/Export → **Spreadsheet Export** |
| **FitNotes 2 (iOS)** | Export workouts as CSV; also manual/auto iCloud backups |
| **Strong** | Settings → Export Data |
| **Hevy** | Profile → Settings → Export & Import Data (Workouts or Measurements) |
You can also create your own `CSV` file:
### Minimal Example
```csv
workout name,exercise,date,weight kg,reps
Leg Day,Squat,2026-08-21,120,5
Leg Day,Squat,2026-08-21,125,4
Leg Day,Leg Press,2026-08-21,200,1
```
These field names are supported:
| Canonical Field | Supported CSV Headers (first match wins) |
|---|---|
| `exercise` | `exercise`, `exercise name`, `exercise title` |
| `date` | `date`, `workout date` |
| `startTime` | `start time` |
| `endTime` | `end time` |
| `workoutName` | `workout name`, `title` |
| `category` | `category`, `body part`, `muscle group` |
| `weightKg` | `weight kg` |
| `weightLb` | `weight lbs`, `weight lb` |
| `weight` | `weight` |
| `weightUnit` | `weight unit`, `unit` |
| `reps` | `reps`, `repetitions` |
| `rpe` | `rpe`, `rpe rating` |
| `rir` | `rir`, `reps in reserve` |
| `distanceKm` | `distance km` |
| `distance` | `distance` |
| `distanceUnit` | `distance unit` |
| `seconds` | `seconds`, `duration seconds` |
| `time` | `time`, `duration` |
| `setType` | `set type` |
| `note` | `comment`, `comments`, `notes`, `note` |
+147
View File
@@ -0,0 +1,147 @@
# Building the mobile app (iOS / Android)
openGym ships in two flavors from the same codebase:
| | **Self-hosted** (this repo's default) | **Mobile app** (`VITE_MOBILE=1`) |
|---|---|---|
| Runs | in any browser, against your own server | natively on iPhone / Android (Capacitor shell) |
| Accounts | passkey sign-in, one profile per person | none — the phone *is* the account |
| Data | synced to your server, readable on desktop | stays on the device (file in the app's private storage) |
| Reminders | Web Push from your server | native local notifications, no server involved |
| Exercise media | served by your server (`img/`, `gif/`) | loaded from the jsDelivr CDN |
The mobile flavor never talks to a backend by default: no sign-in screen, no sync, no
telemetry. State is mirrored from `localStorage` into `opengym-state.json` in the app's
private data directory on every change (iOS is allowed to evict WebView storage under
pressure — the file mirror is the durable copy and is restored on launch). Backups go out
through the OS share sheet instead of a browser download.
### Connecting the app to your own server
On first launch the app asks how you want to use it. Alongside the fully local mode above,
you can instead **connect it to a self-hosted openGym server** — your data then lives there,
synced the same way the browser PWA does, instead of only on the phone. This is a mode of the
same app, not a different build or download.
Passkeys can't be used for this: the app's WebView runs at its own origin, which never
matches the real hostname WebAuthn needs. Instead you *pair* the device from a browser
that's already signed in: Settings → **"Pair the mobile app"** shows a one-time code (valid
5 minutes); enter your server's address and that code in the app (same first-launch screen,
or Settings → **"Connect to my server"** later) to finish. Notes:
- Requires network access every time the app is used — there's no offline file mirror once
connected, same as the browser PWA.
- Use an HTTPS address if at all possible: the connection carries a bearer token instead of
a cookie, and that token would otherwise cross the network in plain text.
- "Sign out everywhere" (Settings → Account, in the browser) revokes a paired app's access
too — it's the same signed session token either way, just delivered over a header instead
of a cookie. See `/api/pair/create` and `/api/pair/redeem` in `api/server.js` for the
exchange itself.
- Settings → "Disconnect" syncs one last time, then drops the device cleanly back to local
mode.
## Prerequisites
- Node 20+
- **Android:** Android Studio (bundles the SDK). Java 21 for Gradle.
- **iOS:** a Mac with Xcode 15+ and CocoaPods (`brew install cocoapods`). A free Apple ID
is enough to run the app on your own iPhone (see below); paid membership is only needed
for App Store distribution, which openGym doesn't do.
## Build & run
```sh
cd frontend
npm install
npm run build:mobile # VITE_MOBILE build + `cap sync` into android/ and ios/
npx cap open android # opens Android Studio → run on emulator or device
npx cap open ios # opens Xcode (Mac only) → set your signing team, then run
```
`npm run build:mobile` bakes the CDN media base into the bundle and copies the web build
into both native projects — re-run it after every web-code change before building natively.
> **Heads-up:** after `build:mobile`, `frontend/dist` contains the *mobile* bundle.
> Run a plain `npm run build` again before deploying `dist` to a server.
## App icons & splash screens
`frontend/resources/icon.svg` is the 1024×1024 source (the app's dumbbell glyph on the
app background). Generate all platform assets from it on a machine with the tooling:
```sh
cd frontend
npx @capacitor/assets generate --iconBackgroundColor '#0c0e12' --splashBackgroundColor '#0c0e12'
```
(If the generator won't take the SVG directly, export it to `resources/icon.png` at
1024×1024 first — any image tool can do it.)
## Distribution — deliberately no app stores
openGym's mobile app is not on the Play Store or App Store, and that's a choice: no store
accounts, no store rules, no yearly fees between you and an open-source app.
### Android — sideload the APK
The official signed APK is in three places, all the same file:
- **[opengym.duarte-santos.ch](https://opengym.duarte-santos.ch)** — the download page.
- **[GitLab's package registry](https://gitlab.com/DuarteSantos8/opengym/-/packages)** — every
build under `opengym-android/<version>/`, with a `.sha256` beside it. Direct link, no login:
`https://gitlab.com/api/v4/projects/85678327/packages/generic/opengym-android/<version>/openGym-<version>.apk`
- **[The GitLab release](https://gitlab.com/DuarteSantos8/opengym/-/releases)** for that version,
which links to the two above.
Android asks you to allow installs from the browser the first time — that's standard for any
app outside the Play Store. Check the `.sha256` if you got the file from anywhere else.
Both come out of CI: the `build:apk` job in [`.gitlab-ci.yml`](../.gitlab-ci.yml) runs
`npm run build:mobile` and `./gradlew assembleRelease`, then `zipalign`s and signs the result
with the release key. The key lives in *protected* CI variables (`ANDROID_KEYSTORE_B64`,
`ANDROID_KEYSTORE_PASSWORD`, `ANDROID_KEY_ALIAS`), so it only exists on `main` and on `v*`
tags — a merge request from a fork can build an APK, but gets an unsigned one and never sees
the key. On a `v*` tag the signed APK is also pushed to the generic package registry, which is
what the release links to.
To build and sign your own:
```sh
cd frontend && npm run build:mobile
cd android && ./gradlew assembleRelease # → app/build/outputs/apk/release/app-release-unsigned.apk
# one-time: create a keystore. KEEP IT — updates must be signed with the same key,
# or Android refuses to install the new version over the old one.
keytool -genkeypair -keystore my.keystore -alias opengym -keyalg RSA -validity 10950
# align + sign (zipalign/apksigner ship with the Android SDK build-tools)
zipalign -f -p 4 app-release-unsigned.apk aligned.apk
apksigner sign --ks my.keystore --ks-key-alias opengym --out openGym.apk aligned.apk
```
### iPhone — what's actually possible
Apple does not allow installing apps outside the App Store, so there is no `.ipa` download
that would simply install. Your free options:
- **Self-host + PWA** (recommended): open your instance in Safari → Share → *Add to Home
Screen*. Full-screen app, no expiry, plus sync and passkeys.
- **Xcode free signing:** open `ios/` in Xcode with a free Apple ID as the team and run it
onto your own iPhone. Apple expires the signature after 7 days; re-run from Xcode to renew.
- **AltStore:** automates that 7-day re-signing over Wi-Fi via a Mac companion app.
### Release notes for maintainers
- Bump `versionName`/`versionCode` in `android/app/build.gradle` per release; keep them in
step with `frontend/package.json`. `versionCode` must strictly increase or updates won't
install over an existing APK. The APK is *named* from `frontend/package.json` (the CI job
reads `version` out of it), so the two drifting apart shows up as a misnamed file.
- Tagging `vX.Y.Z` is what ships everything: images, APK, release notes. Don't push a version
tag you don't mean to release — `v*` tags are protected for that reason.
- **License:** openGym is AGPL-3.0, which by itself sits badly with app-store terms of
service. `NOTICE.md` carries an app-store exception (an additional permission under
AGPL §7) granted by the copyright holder — relevant only if store distribution ever happens.
- The app requests notification permission only when the workout-day reminder is switched
on, and (on Android) declares `SCHEDULE_EXACT_ALARM` so the reminder fires to the minute
where the user allows it.
+173 -21
View File
@@ -8,14 +8,14 @@ This guide takes you from "just cloned it" to "using it from my phone over the i
Requirements: [Docker](https://docs.docker.com/get-docker/) with the Compose plugin.
```bash
git clone https://github.com/DuarteSantos8/gym-app opengym
cd opengym
git clone https://gitlab.com/DuarteSantos8/opengym
cd openGym
cp .env.example .env
docker compose pull # prebuilt images from ghcr.io (amd64 + arm64) — or skip and build from source
docker compose pull # prebuilt images from GitLab (amd64 + arm64) — or skip and build from source
docker compose up -d
```
- First start downloads the exercise images/GIFs (~140 MB) once into `app/img` and `app/gif`.
- First start downloads the exercise images/GIFs (~140 MB) once into `media/img` and `media/gif`.
- Open **http://localhost:8080** and create a profile with a passkey.
- Rather build from source than pull prebuilt images? Skip `docker compose pull` and run
`docker compose up -d --build` instead — no Node needed locally either way.
@@ -42,6 +42,21 @@ passkey prompt won't appear. To use openGym from your phone you need a real HTTP
(You can still open it over LAN in **guest mode**, which stores data only in that browser.)
The standalone mobile app (`docs/MOBILE.md`) sidesteps this entirely for its "connect to my
server" mode: instead of a passkey ceremony (impossible from inside its WebView, which never
runs at your real hostname), it pairs by redeeming a short one-time code — minted from
Settings → "Pair the mobile app" in an already signed-in browser tab — for a bearer token
sent as an `Authorization` header rather than a cookie. Two consequences worth knowing if
you're poking at the API directly:
- `POST /api/pair/create` (needs a session) and `POST /api/pair/redeem` (doesn't) implement
this — see `api/server.js`. The returned token is the exact same signed value a cookie
carries, so "sign out everywhere" invalidates it too.
- The server reflects `Access-Control-Allow-Origin` for any request that sends an `Origin`
header, so the app's own WebView origin can call the API cross-origin. It never sends
`Access-Control-Allow-Credentials`, so this doesn't let a browser read your cookie session
from another origin — only bearer-token requests benefit from it.
## 3. Expose it over HTTPS on your own domain
Put openGym behind something that terminates TLS for a hostname you control, then point it at
@@ -87,11 +102,83 @@ Visit `https://gym.example.com`, create your profile, and add it to your home sc
## 4. Multiple users
Anyone who can reach the URL can create their own profile — each gets isolated data. There's no
admin/invite system by design; if you want it private, keep it behind your VPN, an auth proxy
(Authelia, Cloudflare Access…), or just don't share the URL.
Anyone who can reach the URL can create their own profile — each gets isolated data. That's the
default: open signup, no admin.
## 5. Backups
If you'd rather control who gets in, three optional settings in `.env` turn that around:
```bash
ADMIN_UIDS=youruserid # comma-separated; these users get the admin dashboard
INVITE_ONLY=1 # new profiles need an invite code
ALLOW_GUEST=0 # remove "Continue without account"
```
Register your own passkey profile first, then find your id in `./data/db.json` under `users[].id`
and put it in `ADMIN_UIDS`. You'll get an **Admin dashboard** link in Settings: who's training
right now, each user's workout history and body weight, the ability to disable an account (signed
out and locked out everywhere until you re-enable it), and — with `INVITE_ONLY=1` — generating and
revoking invite codes. Existing accounts keep working when you switch invite-only on. Admin access
is gated by your passkey and enforced server-side, so it needs no separate login.
### The activity log
The dashboard also keeps an **activity log**: sign-ins, sign-outs, failed attempts, refused
signups, and every admin action (disabling an account, creating or revoking an invite code). It
lives in `./data/audit.log` as one JSON object per line, so `tail -f data/audit.log` and `jq`
work on it directly, and the dashboard reads the same file.
It is on by default and keeps the last 5,000 events or 90 days, whichever comes first
(`AUDIT_LOG=0` turns it off entirely; `AUDIT_MAX` and `AUDIT_DAYS` change the caps). **IP
addresses are not recorded** unless you set `AUDIT_IP=net` (network only, e.g. `203.0.113.0/24`)
or `AUDIT_IP=full`. Neither the browser's user-agent nor the passkey id of a failed sign-in is
ever stored: the first is a fingerprint, and the second would let you follow an unknown device
from one attempt to the next.
Two things worth expecting. **Guests never appear** — guest mode never talks to the server, so
there is nothing to log, exactly as there is nothing for the rest of the dashboard to show. And
**a disabled account goes quiet**: a disabled user is refused at the session check, so their only
entries are the failed sign-ins they keep making.
Clearing the log from the dashboard records the clear itself, and the event ids keep counting, so
a gap is always visible.
`INVITE_ONLY=1` and `ALLOW_GUEST=0` answer different questions and are usually set together.
Invite-only controls who may *create a profile*; it says nothing about the **Continue without
account** button, which never creates one. Guest mode keeps everything in that browser and never
talks to the server — there is no account, no sync and nothing for the admin dashboard to show —
so on an instance meant for a known set of people it is a door that leads nowhere useful. With
`ALLOW_GUEST=0` the button is gone, and anyone already using the app as a guest is returned to the
login screen on their next visit. Their data is not deleted: it stays in that browser and comes
back if you ever switch guests on again, or moves into a real profile if they create one on the
same device.
Prefer to keep the whole thing off the open internet? A VPN or an auth proxy (Authelia, Cloudflare
Access…) in front still works, and composes with the above.
## 5. Fitting it into an existing stack
The defaults assume openGym is the only thing here: a service called `api` on port 3000, and nginx
on port 80 inside its container. If you are merging this into a compose file that already has an
`api`, or you put the web container behind your own reverse proxy on a different port, four
settings in `.env` move those without editing any config file:
```bash
WEB_PORT=8080 # host port — what you browse to
NGINX_PORT=80 # port the web container listens on, inside the container
BACKEND=api # name of the API service that /api is proxied to
PORT=3000 # port the API listens on; web proxies to the same value
SESSION_DAYS=90 # how long a sign-in lasts
```
The web image renders its nginx config from these when the container starts, so they take effect
on a **prebuilt image** — no rebuild. `BACKEND` and `PORT` together are what `/api` is proxied to,
so they have to name a service the web container can actually reach on your compose network.
Note the difference from `VITE_IMG_BASE` / `VITE_GIF_BASE` (see Troubleshooting): those are
build-time values baked into the frontend bundle, and setting them next to `docker compose` does
nothing to an image you pulled.
## 6. Backups
Everything is in `./data`:
@@ -99,26 +186,33 @@ Everything is in `./data`:
tar czf opengym-backup-$(date +%F).tar.gz data/
```
That archive contains all profiles, passkeys and workout history. Restore by unpacking it back
into the project folder. (Individual users can also export their own data as JSON from Settings.)
That archive contains all profiles, passkeys and workout history — and, if the activity log is
on, `audit.log` with everyone's sign-in times. Worth knowing before you ship the archive to a
backup service you don't run. Restore by unpacking it back into the project folder. (Individual
users can also export their own data as JSON from Settings.)
## 6. Notifications
## 7. Notifications
openGym can push two kinds of alert to your phone/desktop, even when the app isn't open:
rest-timer-over, and a reminder on days you have a workout planned but haven't logged one yet.
Turn it on per-profile in **Settings → Notifications** (requires a signed-in passkey profile and
HTTPS — see section 3).
No setup needed server-side: VAPID keys are generated on first run and saved to `./data/vapid.json`.
The one thing worth setting is your timezone, so the day reminder fires at the time you actually
picked rather than UTC:
No setup needed server-side, and nothing to configure per timezone: VAPID keys are generated on
first run and saved to `./data/vapid.json`, and each user's browser reports its own timezone
automatically when they turn the reminder on — it fires at their local time, and follows them if
they travel, regardless of what timezone the server itself runs in.
```bash
# .env
TZ=Europe/Zurich
```
**Keep screen awake** (Settings → *During a workout*) has the same transport requirement: the
Wake Lock API is only available over HTTPS or on `http://localhost`, so on a plain-LAN-IP
instance the switch shows as unsupported. Nothing to configure server-side either way, and iOS
refuses the lock while the phone is in Low Power Mode.
## 7. Updating
Push services like a contact address for whoever runs the server, in case they ever need to reach
you about your pushes. openGym sends your `ORIGIN` by default; set `VAPID_SUBJECT=mailto:you@example.com`
in `.env` if you would rather they had an inbox.
## 8. Updating
Running prebuilt images:
@@ -138,15 +232,73 @@ docker compose up -d --build
The app shell is versioned (`?v=N`) so clients pick up changes on next load. Your `./data` and the
downloaded media are untouched.
## Passkeys fail even though `RP_ID` looks right
The most common support question, and the values are usually *nearly* correct. Work through
these in order — the first two account for most of it.
**1. Ask the server what it actually loaded.** It prints both values on startup:
```
docker compose logs api | grep 'gym-api on'
# gym-api on :3000 (rpID=gym.example.com, origin=https://gym.example.com)
```
If that disagrees with your `.env`, the container is still running the old environment.
`docker compose restart` does **not** re-read `.env` — use `docker compose up -d`.
**2. Check the exact shape of each value.** They are not the same kind of string:
| | Correct | Wrong |
|---|---|---|
| `RP_ID` | `gym.example.com` | `https://gym.example.com`, `gym.example.com:8080`, `gym.example.com/` |
| `ORIGIN` | `https://gym.example.com` | `gym.example.com`, `https://gym.example.com/` |
`RP_ID` is a bare hostname: no scheme, no port, no trailing slash. `ORIGIN` is the full origin
*with* the scheme and *without* a trailing slash. Both must match your address bar exactly.
**3. Behind a tunnel or reverse proxy, use the public hostname.** With Cloudflare Tunnel,
Traefik, nginx or Caddy in front, the browser only ever sees the public name — so that is what
both values must be. Not the container name, not the LAN IP, not the internal port:
```env
RP_ID=gym.example.com
ORIGIN=https://gym.example.com
```
The tunnel's own route may point wherever it likes (`http://localhost:8080` is fine). It is the
browser-facing name that has to appear here.
**4. `www.` is a different host.** A passkey registered on `gym.example.com` will not work on
`www.gym.example.com`. Pick one and redirect the other.
**5. Changing the hostname invalidates existing passkeys.** They were bound to the old one, so
everybody registers again — which is why it pays to settle the domain before others join.
> On a LAN without certificates there is nothing to configure that makes passkeys work over
> plain `http://192.168.x.x`: browsers only allow WebAuthn on HTTPS (or `localhost`). Use guest
> mode, the standalone mobile app (`docs/MOBILE.md`), or put a certificate in front of it.
## Troubleshooting
| Symptom | Fix |
|---|---|
| No passkey prompt on my phone | You're on `http://` or an IP, not HTTPS. Set up a domain (section 3). |
| "verification failed" on login | `RP_ID`/`ORIGIN` don't match the URL in the address bar. Make them exact, restart. |
| "verification failed" on login | `RP_ID`/`ORIGIN` don't match the URL in the address bar. See the section above — start with what the server logged on startup. |
| Media didn't download | `docker compose logs media`. Re-run `docker compose up -d`, or run `./scripts/fetch-media.sh`. |
| Port 8080 already used | Set `WEB_PORT=9090` in `.env` (and update `ORIGIN` for local testing). |
| No "Notifications" option in Settings | Requires a signed-in profile and HTTPS (or `localhost`) — guest mode and plain HTTP over LAN can't subscribe. |
| Day reminder fires at the wrong time | Set `TZ=Continent/City` in `.env` and restart (see section 6). Defaults to UTC. |
| Day reminder fires at the wrong time | Toggle it off and on in Settings so it re-detects your browser's timezone (also happens automatically on every app load — see section 7). |
| Want to reset a stuck login | Delete the cookie in your browser; sessions are just signed cookies. |
| `docker compose pull` fails with "denied" / "unauthorized" | The prebuilt images aren't published yet, or need to be, or the GHCR package is still private — build from source instead (`docker compose up -d --build`). |
| Exercise images/GIFs blank when a routine is open | Fixed in current images (issue #79). On an older build, see the note below. |
### `VITE_IMG_BASE` / `VITE_GIF_BASE` are build-time, not run-time
These two are read by Vite when the frontend is **compiled**, so their values are baked into
the shipped JavaScript bundle. Setting them in the `.env` next to `docker compose` has no
effect on an already-built image — the bundle has already made up its mind.
They are only useful if you build the frontend yourself (`docker compose up -d --build`, or a
`npm run build` with the variables exported). If you need to redirect media on a prebuilt
image, do it in your reverse proxy instead.
+101
View File
@@ -0,0 +1,101 @@
# Using Android gitignore template: https://github.com/github/gitignore/blob/HEAD/Android.gitignore
# Built application files
*.apk
*.aar
*.ap_
*.aab
# Files for the ART/Dalvik VM
*.dex
# Java class files
*.class
# Generated files
bin/
gen/
out/
# Uncomment the following line in case you need and you don't have the release build type files in your app
# release/
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Log Files
*.log
# Android Studio Navigation editor temp files
.navigation/
# Android Studio captures folder
captures/
# IntelliJ
*.iml
.idea/workspace.xml
.idea/tasks.xml
.idea/gradle.xml
.idea/assetWizardSettings.xml
.idea/dictionaries
.idea/libraries
# Android Studio 3 in .gitignore file.
.idea/caches
.idea/modules.xml
# Comment next line if keeping position of elements in Navigation Editor is relevant for you
.idea/navEditor.xml
# Keystore files
# Uncomment the following lines if you do not want to check your keystore files in.
#*.jks
#*.keystore
# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild
.cxx/
# Google Services (e.g. APIs or Firebase)
# google-services.json
# Freeline
freeline.py
freeline/
freeline_project_description.json
# fastlane
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
fastlane/test_output
fastlane/readme.md
# Version control
vcs.xml
# lint
lint/intermediates/
lint/generated/
lint/outputs/
lint/tmp/
# lint/reports/
# Android Profiling
*.hprof
# Cordova plugins for Capacitor
capacitor-cordova-android-plugins
# Copied web assets
app/src/main/assets/public
# Generated Config files
app/src/main/assets/capacitor.config.json
app/src/main/assets/capacitor.plugins.json
app/src/main/res/xml/config.xml
+2
View File
@@ -0,0 +1,2 @@
/build/*
!/build/.npmkeep
+54
View File
@@ -0,0 +1,54 @@
apply plugin: 'com.android.application'
android {
namespace "ch.duartesantos.opengym"
compileSdk rootProject.ext.compileSdkVersion
defaultConfig {
applicationId "ch.duartesantos.opengym"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 11
versionName "1.2.10"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
aaptOptions {
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
// Default: https://android.googlesource.com/platform/frameworks/base/+/282e181b58cf72b6ca770dc7ca5f91f135444502/tools/aapt/AaptAssets.cpp#61
ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:!CVS:!thumbs.db:!picasa.ini:!*~'
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
flatDir{
dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs'
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"
implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"
implementation project(':capacitor-android')
testImplementation "junit:junit:$junitVersion"
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
implementation project(':capacitor-cordova-android-plugins')
}
apply from: 'capacitor.build.gradle'
try {
def servicesJSON = file('google-services.json')
if (servicesJSON.text) {
apply plugin: 'com.google.gms.google-services'
}
} catch(Exception e) {
logger.info("google-services.json not found, google-services plugin not applied. Push Notifications won't work")
}
@@ -0,0 +1,22 @@
// DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_21
targetCompatibility JavaVersion.VERSION_21
}
}
apply from: "../capacitor-cordova-android-plugins/cordova.variables.gradle"
dependencies {
implementation project(':capacitor-app')
implementation project(':capacitor-filesystem')
implementation project(':capacitor-local-notifications')
implementation project(':capacitor-share')
}
if (hasProperty('postBuildExtras')) {
postBuildExtras()
}
+21
View File
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
@@ -0,0 +1,26 @@
package com.getcapacitor.myapp;
import static org.junit.Assert.*;
import android.content.Context;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.getcapacitor.app", appContext.getPackageName());
}
}
@@ -0,0 +1,39 @@
<?xml version="1.0" encoding="utf-8" ?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode|navigation"
android:name=".MainActivity"
android:label="@string/title_activity_main"
android:theme="@style/AppTheme.NoActionBarLaunch"
android:launchMode="singleTask"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" />
</provider>
</application>
<!-- Permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- Workout-day reminder: lets the local-notifications plugin fire at the exact minute
on Android 12+. Where it isn't granted, scheduling silently falls back to inexact
alarms — the reminder still arrives, just not to the minute. -->
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
</manifest>
@@ -0,0 +1,5 @@
package ch.duartesantos.opengym;
import com.getcapacitor.BridgeActivity;
public class MainActivity extends BridgeActivity {}
Binary file not shown.

After

Width:  |  Height:  |  Size: 9.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

@@ -0,0 +1,34 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillType="evenOdd"
android:pathData="M32,64C32,64 38.39,52.99 44.13,50.95C51.37,48.37 70.14,49.57 70.14,49.57L108.26,87.69L108,109.01L75.97,107.97L32,64Z"
android:strokeColor="#00000000"
android:strokeWidth="1">
<aapt:attr name="android:fillColor">
<gradient
android:endX="78.5885"
android:endY="90.9159"
android:startX="48.7653"
android:startY="61.0927"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M66.94,46.02L66.94,46.02C72.44,50.07 76,56.61 76,64L32,64C32,56.61 35.56,50.11 40.98,46.06L36.18,41.19C35.45,40.45 35.45,39.3 36.18,38.56C36.91,37.81 38.05,37.81 38.78,38.56L44.25,44.05C47.18,42.57 50.48,41.71 54,41.71C57.48,41.71 60.78,42.57 63.68,44.05L69.11,38.56C69.84,37.81 70.98,37.81 71.71,38.56C72.44,39.3 72.44,40.45 71.71,41.19L66.94,46.02ZM62.94,56.92C64.08,56.92 65,56.01 65,54.88C65,53.76 64.08,52.85 62.94,52.85C61.8,52.85 60.88,53.76 60.88,54.88C60.88,56.01 61.8,56.92 62.94,56.92ZM45.06,56.92C46.2,56.92 47.13,56.01 47.13,54.88C47.13,53.76 46.2,52.85 45.06,52.85C43.92,52.85 43,53.76 43,54.88C43,56.01 43.92,56.92 45.06,56.92Z"
android:strokeColor="#00000000"
android:strokeWidth="1" />
</vector>
@@ -0,0 +1,170 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportHeight="108"
android:viewportWidth="108">
<path
android:fillColor="#26A69A"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeColor="#33FFFFFF"
android:strokeWidth="0.8" />
</vector>
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background>
<inset android:drawable="@mipmap/ic_launcher_background" android:inset="16.7%" />
</background>
<foreground>
<inset android:drawable="@mipmap/ic_launcher_foreground" android:inset="16.7%" />
</foreground>
</adaptive-icon>
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background>
<inset android:drawable="@mipmap/ic_launcher_background" android:inset="16.7%" />
</background>
<foreground>
<inset android:drawable="@mipmap/ic_launcher_foreground" android:inset="16.7%" />
</foreground>
</adaptive-icon>
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 913 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 379 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 333 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 530 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 623 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 608 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 564 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 745 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 839 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Loaded 100 of 302 files, more files were not shown because too many files have changed in this diff. Show more