d5cf0d8d64f70528654e48363b48d1975863436c
41
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
d5cf0d8d64 |
Música se ordena: pestañas, buscador, y listas de diez con "Mostrar más"
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
La pantalla era una sola columna —radio, después podcasts, después listas— y tres listas de veinte filas es una pantalla por la que se baja buscando lo que ya sabías que querías. Ahora pregunta primero: **Radio | Podcasts | Listas**, una lista a la vez, **diez filas** y un **"Mostrar más"** que dice cuántas esconde. Nada queda fuera de alcance y nada más está en pantalla mientras decidís: el subtítulo también dice qué estás mirando en vez de hablar siempre de listas. El **buscador** busca lo que tengas abierto y en el origen, no en la página: `jazz` le pregunta al directorio de emisoras y `crimen` al de podcasts de Apple —filtrado, como siempre, a español, y pasando por **la misma** función de filtro que una categoría, porque un segundo camino más barato al catálogo es como se pierde una regla—. Con menos de dos letras no se busca ni se pide nada: una letra coincide con todo y sería una petición por tecla para una respuesta inservible. La búsqueda de emisoras **ordena por lo que se buscó**: el directorio coincide con subcadenas en cualquier parte, así que *techno* devolvía "# TOP 100 CLUB CHARTS - DANCE & DJ MIX RADIO" —real, con "techno" entre sus etiquetas— por delante de toda emisora llamada Techno Algo. El nombre pesa antes que la popularidad y a igual peso gana el nombre más corto; los canales de SomaFM y los mixes de Paradise que coinciden van primero, porque no tienen publicidad y su stream ya se sabe que funciona. La búsqueda del directorio va con `is_https=true`, cacheada por consulta. `lib/paging.js` es puro y tiene test porque tiene un borde fácil de equivocar en un componente: una lista que se encoge —una búsqueda nueva, una emisora desmarcada— no puede dejar el tamaño de página pasado del final, que se ve como "Mostrar más" que no hace nada. Verificado contra los directorios reales: `radio?q=jazz` → Sonic Universe (SomaFM) y después Jazz 24; `radio?q=miami` → Miami Beach Radio, 105 Miami; `podcasts?q=crimen` → 20 programas en español (es, es-ar) y `q=entrenamiento en casa` → 3; `?q=j` no busca. `relevance` y `rankStations` se comprobaron por mutación: sacar el orden hace fallar el test que lo mira de punta a punta. |
||
|
|
22654c61fc |
Podcasts: en español solamente, y se acuerdan de dónde ibas
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Música tiene una sección **Podcasts**: programas por categoría —Salud y fitness, Deporte, Comedia, Noticias, Historia, Crímenes reales, Ciencia, Tecnología, Sociedad y cultura, Negocios, Ficción, Educación, Música, Ocio— que suenan mientras entrenás y siguen donde los dejaste. Sin dependencias nuevas y sin clave de API: el directorio de Apple es público. **En español se comprueba, no se supone.** La tienda dice dónde se *vende* un podcast, no en qué idioma está —en el ranking español de comedia hay uno en catalán y en el argentino uno en inglés—, así que se lee el `<language>` del feed de cada programa (los primeros 64 KB, con una petición `Range`: el idioma está en las primeras líneas) y se descarta lo que no sea español. Un feed sin etiqueta se queda: feeds genuinamente españoles la omiten, y tirarlos por una omisión sería sacar podcasts buenos de la lista. La respuesta cuenta cuántos quedaron afuera y por qué (`skipped`), así que una lista corta nunca es un misterio, y abrir un programa en otro idioma se contesta con `spanish:false` en vez de con una lista vacía. Es la otra mitad de la radio y es lo contrario en todo lo que le importa al reproductor: un podcast es un **archivo** —tiene principio, final y un minuto en el que ibas—. Por eso hay un módulo de reglas puras (`lib/podcast-view.js`: dónde retomar, qué cuenta como escuchado, cuál sigue, cuántas posiciones se guardan) y por eso `lib/radio-player.js` pasa a ser `lib/player.js`: **un solo elemento de audio** para las dos cosas, que es lo que impide que una emisora y un episodio suenen a la vez. La barra crece línea de progreso, −15 s, +30 s, siguiente episodio y reloj; la posición se guarda por perfil (con tope de 200, lo más nuevo primero) en pausa, al parar, al terminar y cuando la app se va al fondo, porque con la pantalla bloqueada iOS suspende los temporizadores y un guardado sólo desde el tick perdería lo escuchado con el teléfono guardado. Media Session muestra episodio, programa y progreso en la pantalla bloqueada. Nada se descarga y nada pasa por el servidor: el episodio llega como la URL del `enclosure` y el audio va de quien lo publica al teléfono. Acá no hay lista blanca posible —un feed vive en cualquier host—, así que la puerta es **https, host real y nunca una dirección privada**, comprobada en la URL y en dónde terminó el pedido, con el cuerpo leído a tope y la conexión cortada al llegar: este contenedor vive adentro de una casa. Verificado con datos reales: 20 programas en español por categoría (idiomas es, es-ES, es-mx), un feed de 40 episodios parseado, un feed en inglés contestado como `spanish:false` y la dirección de metadatos rechazada con 400 sin hacer el pedido. Fuera de los podcasts: la página de la API ocultaba `health` y `music` enteras —el generador sólo dibuja las secciones de su tabla de etiquetas—, así que ahora están, con radio y podcasts incluidas. |
||
|
|
a3e13df279 |
La radio no se dibuja para un invitado ni contra un servidor viejo
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Las emisoras las busca el servidor, así que dos situaciones que no son bugs se veían como uno: sin sesión (el modo invitado nunca habla con la api) y una api más vieja que la app —se despliegan por separado, y un deploy que reconstruyó `web` y no el contenedor de la api es una pantalla cuyos pedidos fallan todos. Ahora la sección lo dice y no pide nada en ninguno de los dos casos. Para poder distinguirlos, `radio` entra en `features` (`GET /api/config`), que es exactamente para lo que existe esa lista, y queda documentado en la especificación junto con `features` entero —que hasta ahora no estaba. De paso: la fila y la barra caen al marcador de posición cuando el logo o la portada no cargan, que es el caso de una parte del directorio. |
||
|
|
48cf976635 |
Radio: estaciones en vivo mientras entrenás
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Música tiene una sección **Radio**: estaciones en vivo por género (Workout/Rave, Techno/House, R&B/Soul, Latina, Hip-Hop, Reggae, Chill, Jazz, Rock, Electrónica), sin publicidad primero —SomaFM y Radio Paradise— y detrás el directorio público de radio-browser. Nada de esto suma dependencias: la lista la arma api/radio.js. Tres decisiones que no se ven en la pantalla y son las que hacen que funcione: - **El audio no pasa por el servidor.** La api entrega la lista y después no ve un byte: el teléfono habla con la estación. Sin ancho de banda, sin disco, sin copias. - **La URL del stream viene resuelta en la lista**, porque iOS sólo deja arrancar audio dentro del gesto del toque: cualquier cosa asíncrona entre el dedo y el play() es un botón que no hace nada, sin error en ninguna parte. - **El `<audio>` vive fuera de React** (lib/radio-player.js): un elemento dentro de un componente se desmonta con él, y eso es la música cortándose al cambiar de pantalla — justo lo que no puede pasar en medio de una serie. Barra arriba de la barra de pestañas con pausa (deja la estación donde estaba) y parar; Media Session pone estación, pista y controles en la pantalla bloqueada, y las canciones siguen con el teléfono en el bolsillo. Qué suena lo dicen SomaFM y Radio Paradise y nadie más: en el resto la barra muestra la estación en vez de inventar una pista. api/test/server-radio.test.js guarda las dos puertas (sesión obligatoria, `src`+`id` reconstruidos en vez de confiar en el objeto del cliente); RadioBar.test.jsx y el caso de la fila en Music.test.jsx guardan lo demás. También: radio.js en el COPY del Dockerfile —importar un archivo que no está copiado es un contenedor que arranca en ERR_MODULE_NOT_FOUND—, /api/radio y /api/radio/now (con /api/music/lookup, que faltaba) en la especificación, y docs/RADIO.md. |
||
|
|
f80ade25f6 |
Jev decide y el modelo escribe: el juicio entra en el trabajo del Coach, y juzga la selección
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Recordado como "para mejorar las decisiones en la selección de entrenamiento debe usar Jev y ChatGPT combinado". La combinación estaba a medias por dos razones, y las dos se cierran acá. **El juicio no estaba cuando se escribía el plan.** Viajaba al payload sólo si alguien lo había pedido en Salud hacía menos de seis horas; en la práctica, muchas veces no estaba. Ahora un trabajo del Coach —crear o revisar— **pide su propio juicio** cuando no hay uno fresco (`insightForCoach` en `api/insights.js`), con el mismo cupo que gasta el botón de Salud, así que lo automático no puede costar más que lo manual. Un debrief queda afuera: un veredicto de disposición no habla de una sesión. Y si el proveedor falla, si la instancia no tiene clave o si el cupo se agotó, el trabajo sigue exactamente como antes — el juicio es contexto, nunca una dependencia, y hay tests para los tres casos. **Las preguntas no cubrían la selección.** Jev juzgaba disposición, descarga, limitante y métrica a vigilar; nada sobre *qué cambiar*. Ahora, además de `volume` (hacia dónde va la carga de la semana, cuando hay historia suficiente para tener opinión), recibe **una pregunta por ejercicio estancado**: `keep`, `reduce`, `swap` o `drop`, con la clave del id de la biblioteca y el nombre en la rúbrica — así la respuesta es algo con lo que el plan se puede editar y el modelo lee palabras, no una clave. Los ids de ejercicios pasan a viajar en el estado, y sólo ellos: un id de biblioteca es una fila de un dataset público, no un identificador de persona, y el test de privacidad lo dice ahora en esos términos. Hay una sola forma de producir un juicio: `runInsight` en `api/insights.js`, que usan la ruta de Salud y el trabajo del Coach. Antes esa lógica vivía dentro de la ruta, con sus helpers duplicados en `server.js`; ahora la ruta es una envoltura fina y no hay dos maneras de pedir, cobrar o guardar. En el prompt del escritor quedó dicho con precisión qué es un `swap`: **una propuesta a considerar**, no una decisión a aplicar. Si la evidencia que el propio modelo ve dice que el ejercicio está bien, puede decir por qué y dejarlo; el cambio que envíe tiene que cumplir el esquema y nombrar un id real. Tests: seis del runner y de la regla de cuándo preguntar (contra un gateway de mentira, sin levantar servidor), más los de las preguntas nuevas. API 276 en verde, frontend 1705. |
||
|
|
4ba9e29d1e |
La app avisa cuando la api es más vieja que ella
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Validado desde afuera, y era esto: **el frontend desplegado es el nuevo y la api no**. Los hashes que
sirve producción coinciden byte a byte con mi build de HEAD, y el bundle contiene las novedades
("What arrived last", "one total an hour"); pero `/api/vitals/hours`, `/api/insights` y
`/api/music/lookup` responden **404** donde esta versión responde 401. O sea: el número de cada
tarjeta lo calcula la api — y la api que corre es la de antes de las horas, la que lee el total del
día como si fuera la hora 00 y suma 840 donde el reloj dice 499.
Eso explica el reporte completo sin ninguna otra suposición: las actualizaciones llegan, se guardan,
y la pantalla nueva pide cosas que ese servidor no tiene (de ahí que el detalle por hora y el recibo
no aparezcan nunca) mientras muestra el número que el servidor viejo le manda.
La causa de fondo es de despliegue: `web` se reconstruye desde el código en cada deploy, pero el
código de la api se copia *dentro* de su contenedor, y Dokploy no recrea un servicio que ya está
Running. Un deploy entonces refresca la mitad de la aplicación.
Arreglar eso no puede depender de que alguien se acuerde, así que la app ahora lo pregunta:
`GET /api/config` publica `features` — una lista de capacidades, nunca configuración ni credenciales —
y Salud muestra una línea ámbar cuando esa lista falta o no llega hasta `vitals.hours`. Un servidor
viejo ya no puede parecer una pantalla rota.
Tests: el config contra el servidor real (la lista existe, nombra las rutas nuevas, y esas rutas
contestan 401 y no 404, sin claves adentro), y el aviso en la pantalla para los dos casos — api sin
lista y api al día. Mutation-check: si el aviso deja de dispararse con una api sin lista, falla.
|
||
|
|
90aa802980 |
La segunda opinión: un juicio sobre tus números, con la probabilidad que trae
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Preguntaste si se podía implementar Jev, y con qué API. Resulta que Jev se sirve por OpenCode Zen,
así que una sola cuenta cubre esto y cualquier otra cosa apuntada a ese gateway:
POST https://opencode.ai/zen/v1/systemone Bearer <clave> model: jev-1.13
Y ahí está la razón de que valga la pena: Jev no es un modelo de chat. Le mandás un *estado* y
preguntas tipadas — sí/no (`noul`), opción (`choice`), rúbrica (`score`) — y contesta todas en una
sola petición con el valor **y la probabilidad que le puso**. "62% probable" se puede discutir;
"tomate una semana de descarga" no. Así que no entra por el Coach (que necesita *escribir*) y no se
fuerza dentro de su lista de proveedores: tiene su módulo, sus dos rutas y su tarjeta.
Qué hace. En Salud, arriba de la grilla, una tarjeta con cuatro respuestas: qué tan listo estás para
entrenar fuerte (nivel 1-5, con el número al lado), si la semana pide bajar carga (62% probable), qué
parte del cuerpo parece menos recuperada, y qué métrica de salud merece atención — esa última con la
última lectura de la métrica que nombró, para que "vigilá tu frecuencia en reposo" venga con el 62
que lo motivó. La hoja detrás del ⓘ dice a dónde va y exactamente qué se envía, con el mismo resumen
que devuelve el servidor.
Lo que sale, y lo que no. Se decide en `api/jev.js` y son agregados: una semana de cada métrica por
campo como la escribió el teléfono, series por parte del cuerpo de 4 semanas y de la última, sesiones,
días desde la última, RPE medio, estancamientos *por nombre de ejercicio*, el último pesaje y su
cambio. Ningún identificador: ni perfil, ni nombre, ni títulos de entrenamientos, ni ids de
ejercicios, ni chat — hay un test que lo afirma sobre el JSON, porque es una promesa que hacen los
docs y nada más la miraba. La única excepción es deliberada y está documentada: la nota de
*limitaciones* del cuestionario del Coach, porque "hombro malo" cambia la respuesta. (Los títulos sí
estuvieron un rato ahí: los saqué al escribir ese test, y el test se quedó.)
Un juicio no es una instrucción, y el código lo trata así. Cada respuesta se muestra con su
probabilidad; una pregunta que el modelo no contestó se muestra como no contestada, nunca como un
cero; un nivel que no habíamos ofrecido se marca en vez de disfrazarse de propio; y si los datos
cambiaron desde que se pidió (una sesión registrada, una noche que llegó) la tarjeta lo dice en lugar
de seguir pareciendo actual. Tampoco corre por temporizador: cuesta una petición, así que pasa cuando
alguien aprieta *Preguntar*, con cupo por perfil y por día y un piso de diez minutos aplicados en el
servidor, no en la pantalla.
El Coach, además, lo recibe como `secondOpinion` en su payload **solo si tiene menos de seis horas**,
como evidencia con confianza adjunta para citar en `why`, nunca como una orden ni como un cambio de
plan. Es la mitad que faltaba de "y el Coach escribe con eso".
El lector de respuestas es tolerante a propósito: el contrato de la petición está documentado, la
respuesta no la vimos nunca del servicio real, así que acepta las formas plausibles
(`answers`/`results`, `option`/`answer`/`choice`, `probability` o una distribución sobre los niveles),
normaliza lo que encuentra y devuelve `null` por lo que no puede leer. El cuerpo crudo queda guardado
al lado del parseado (y sale con `?raw=1`): la primera llamada real se puede mirar, y una forma mal
adivinada es un arreglo, no un misterio.
Dos cosas que encontré escribiendo esto y que quedan arregladas: una variable de entorno vacía se
leía como **cero** (`Number('')` pasa un chequeo ingenuo), así que un cupo sin configurar era "cero
peticiones" — un feature que parece configurado y no funciona nunca; y agregar la palabra *Back*
para la espalda redefinió el botón *Atrás* de la app a "Espalda", porque en un objeto literal la
última clave gana y nada lo dice. El catálogo de español tiene ahora un test que falla si una clave
se escribe dos veces, mutación comprobada.
Cobertura: 11 tests del módulo (el estado, las preguntas, cada forma de respuesta, la promesa de
privacidad, el cupo), 5 de las rutas contra un gateway de mentira y el servidor real, 6 del modelo de
vista en el frontend y 5 de render por la tarjeta real. API 259 en verde, frontend 1696, build OK.
|
||
|
|
5c69540f62 |
Salud: reset one measurement, without losing the rest
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
"Podemos reiniciar los números de esas mediciones para yo enviar el de hoy." The whole-file reset
already existed two taps away in the setup sheet, but it is the wrong size for the question: the
four metrics he suspects are not the profile. Throwing away a month of heart rate to start steps
over is not a reset, it is a tax.
So a metric can now be forgotten on its own: the detail sheet has **Reset this measurement**, which
deletes that metric's days (and hours) and nothing else — the other metrics, the workouts and the
ingest key stay. With any Date Range wider than a day the phone re-sends that metric on its next
sync, which is what makes this a reset rather than a loss: Apple Health still has the data, and a
day total replaces the day it names, so the stored past is rewritten rather than duplicated.
The two destructive rows are worded apart on purpose and the confirm names the metric ("¿Reiniciar
Pasos?"), because the neighbouring action in the setup sheet takes every metric there is.
`dropMetric()` is pure and returns how many days it took, and the route answers `metric: null` for
a metric the profile does not have (or a profile with no health file at all) instead of an error —
a screen that says "nothing stored" is more useful than a 404 answering a button press. Tested
from both ends: the helper's purity and arithmetic, the route against a real server (one metric
gone, the others and the workouts intact, the key still working, and a re-sync rebuilding it), and
the sheet's flow through the real confirm. Mutation-checked: pointing the row at the whole-file
delete fails it.
|
||
|
|
aa6ec8ef22 |
Salud: a card opens onto the day, hour by hour, and onto the days before it
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Reported as "le doy a cualquier actividad y solo me presenta los pasos de hoy… debiera presentarme una medida por hora, y no me da el histórico". Two separate things, and only one of them was the app's fault. **The history was the automation's setting.** With Date Range on its default (`Today`) every sync carries today and nothing else, so there is exactly one day in the file to draw. That is why a card looked frozen: not a rendering bug, a range that was never sent. The setup steps now say `Previous 7 Days` and say why. **The hours were thrown away by us.** Even when the phone sends 288 readings a day, the receiver folded every one of them into a single day aggregate, so "8,123 steps today" was all there could ever be — a number you cannot look into. Worse, the recommended setting was Time Grouping `Days`, which sends one point per metric per day: the intraday detail never arrived in the first place. The recommendation is now `Hours`, and the storage keeps the hours. The merge rule for them is the same shape as the day rule, for the same reason: a payload whose datapoints all sit on the hour is HAE's own hour grouping, and the hour *in progress* grows on every run of a five-minute automation, so it is replaced and never unioned — 500 + 900 + 1,340 steps in one hour is a number no watch recorded. The day is then recomputed as the sum of its hours, which is what keeps the card and the detail from ever disagreeing, and which also makes switching an automation from Days to Hours mid-day converge instead of double-count. Raw samples (real timestamps) still union by instant plus numbers, and they now land in their own hour, which is where intraday detail comes from when nothing is grouped. Three things that would have been silent bugs, caught while writing it: - The hour rule is decided from the **whole payload**, never from one timestamp. A five-minute automation produces samples that sit exactly on the hour, and reading one of those as an hour total wipes the hour it belongs to. There is a test with a 09:00:00 and a 09:05:00 sample in one payload, and it fails against the per-point version of the rule. - A day that arrived as a day total keeps its hours beside it, and a day stored before this existed keeps its aggregate when the first hour shows up — recomputing it from hours it does not have would delete 2,000 steps. Both are mutation-checked (removing either guard fails a test). - A payload grouped by hour writes the ledger row anyway, because a later payload with real minutes can describe the same instant and the union path can only see the ledger. Without it the raw-sample route test double-counts a single sample. The hours are the bulky part of this data, so they are kept for a week (the day aggregates still live the full 400 days), pruned when the night's file is written, and fetched one metric and one day at a time — `GET /api/vitals/hours`. A screen listing forty cards downloads none of them; the day view carries only a count per day, which is what tells the sheet whether it is worth asking. The sheet draws the hours, the days before it (tapping one moves the hour list to that day), and every field the watch sent; when the automation groups by Days it says so instead of leaving a gap where a chart should be. Coverage: 6 new tests in `api/test/vitals.test.js` (19 total) and a route test in `api/test/server-vitals.test.js` (5), the hour/history model in `vitals-view.test.js` (31), three render tests through the real sheet, the route documented in `api/openapi.yaml` and `website/api.html`, and `docs/HEALTH.md` with the settings, the new merge row and the two symptoms now in Troubleshooting. |
||
|
|
caed0cbaa0 |
Música: a playlist screen per profile, with Apple's limits stated plainly
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
The idea was "each person types their Apple Music username and their public playlists appear". Apple does not allow that, and it is worth writing down rather than discovering later: there is no API for another person's public playlists — their own developer forums answer that request with "you can't" (threads 692941 and 123894) — and a profile page is rendered by JavaScript with nothing behind it to call. MusicKit offers the catalog and the *signed-in* user's own library, and the second needs an Apple Developer Program membership for a developer token plus a Music-User-Token per person: a private key and a third-party secret in an app that holds none, to fetch something other than what was asked for. What a self-hosted app can do is the share link, which every playlist has: Music → Share → Copy Link. So the Música screen (next to Salud in Home's header, plus a section in Settings) keeps a list of them per profile, in the profile document like the routines — so they sync to the other devices and travel in a backup — and tapping one opens it in Apple Music on the iPhone. The username is a link to the person's public profile. The list is nicer than a column of URLs because the API reads each link's public page for a title, artwork and track count. That is scraping, so it is built to lose: a page that says nothing leaves the card showing the name its owner typed, and nothing on the screen depends on it. `POST /api/music/lookup` is host-allowlisted to Apple's music hosts — https only, checked again on the URL a redirect lands on — because the api container sits on the same network as everything else the owner runs, and a route that fetches whatever it is handed is a request-forgery lever. That boundary has its own tests, including the LAN addresses it must refuse. The parsing lives in api/music.js rather than in both halves: two copies of a parser kept in step by hand is a bomb, and this is the same shape as vitals.js. It is in the Dockerfile's COPY for the same reason vitals.js had to be. |
||
|
|
691e664d3f |
Apple Health (Salud): a per-profile ingest endpoint, and a tab that draws it
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
An iOS automation in Health Auto Export POSTs Apple Health to /api/vitals/ingest, and the new Salud tab (next to Plan) draws whatever arrived: steps, heart rate, sleep, weight, oxygen, workouts and every other metric HAE can export, grouped into cards with a trend, a sparkline and a 7/30/90/365-day range. Nothing on that screen is an input, and the watch's workouts stay out of the history on purpose — they carry no sets and no weights, so folding them into progression, PRs and the recovery model would be inventing data. The interesting part is duplicates. A five-minute automation re-sends overlapping windows: with Date Range "Today", appending would count a day of steps again on every run, and with "Since Last Sync", replacing would throw away everything but the last five minutes. So the endpoint decides per payload instead. Datapoints that sit on midnight are HAE's own day grouping, i.e. a *total*, and a day total replaces the day it names — re-sending the same day all afternoon converges on that day's total. Anything else is a real sample, identified by its instant plus its numbers and stored once, which is right for overlapping and disjoint windows alike. Every sync answers with a receipt (received / duplicates / stored), so a misconfigured automation is visible rather than silent, and day keys come from the date the phone wrote — never the server's clock, or every evening's steps would land on tomorrow. Per profile and private by construction. Each profile mints its own ingest key (Salud → ⚙), which is write-only: it can add to that one profile's health file and cannot read a single number back, so a key leaking out of a phone is a nuisance rather than a disclosure. It is its own credential, so rotating it disconnects a phone without signing anybody out anywhere. The data lives in data/vitals-<uid>.json, outside the synced state document, so a year of heart rate never round-trips through localStorage on every device, and it is bounded on write: 400 days per metric, a 72 h dedupe ledger, the newest 300 workouts. Two traps that only exist in production, both fixed here and both of which would have shipped broken. api/Dockerfile copies the modules server.js imports by name, and vitals.js was not on that list — a container that boots straight into ERR_MODULE_NOT_FOUND. And the web container's nginx capped every /api body at 5 MB, which a health export with Summarize Data off exceeds; that one route now gets the API's own 32 MB while every other path keeps 5 MB, with the shared proxy settings hoisted to server level so the two locations cannot drift apart. Coverage: vitals.js (13 tests — overlapping, disjoint, day-grouped, raw, heart rate, sleep, blood pressure, pruning, timezones), the routes against a real server (4 — isolation between profiles, a key that cannot read, ten re-sends changing nothing), the card model (18) and the screen (4). docs/HEALTH.md has the Health Auto Export settings and the merge table; the five endpoints are in api/openapi.yaml under the health tag, and website/api.html is rebuilt from it. |
||
|
|
87bfd6d4c4 |
Rebrand to KuentaGYM, and start a new profile in pounds and Spanish
The app is now KuentaGYM everywhere a user can see it, and a fresh profile no longer starts on upstream's English/kg defaults. Both are this fork's decisions, so both are pinned by tests rather than left to a find-and-replace. Rename (1,270 references, 149 files) - Visible surfaces: the Login/Home/mobile-onboarding wordmark, the Settings version line, the printed plan, the PWA title + manifest, and the 17 branded strings across all 14 locale packs. - Infrastructure: repo links, the container images and the release endpoints now name git.dploy.lol/dsantillan/kuentagym; .gitea/workflows/docker-publish.yml publishes to this forge's registry instead of gitea.com. - The Android/iOS application id stays ch.duartesantos.opengym on purpose: changing it would make the mobile app a different app that could never update an installed copy. Three things the mechanical pass would have broken, fixed here - The update check asked gitlab.com for upstream's releases and would have installed upstream's APK, putting the old name back on the phone. It now reads this fork's Gitea releases API (the assets shape differs), with the tests rewritten to the payload Gitea actually returns. - Renaming the mobile state/pairing files (opengym-state.json, opengym-remote.json) would lose the on-device copy of a history whose WebView storage may have been evicted, and silently unpair the device. Both are read under their old names and written forward under the new ones. - Renaming the exported plan-file marker (openGym_plan) rejected every plan shared before the rename as "not a plan file". Both markers are accepted. Defaults: pounds and Spanish - DEF.unit = 'lb', DEF.lang = 'es', plus every fallback that independently assumed en/kg (the <html lang> attribute, the Settings pickers, the Store, the MCP, the Coach payload). - Server-generated push copy existed only in English and pt-BR, so a Spanish profile would have been notified in English; Spanish added. - The demo seed states unit: 'kg' — its seeded numbers are kilograms, and inheriting the new default would have introduced an 82.4 lb lifter benching 60. - The module-level language in i18n-core stays English: it is the only language whose strings need no pack, so `t()`, dates, numbers and lists agree before a pack loads. Starting there on 'es' formats a Spanish-shaped UI with English strings. Also - api/package.json's test glob missed push-messages.test.js and verify-error.test.js, which sat beside the modules they cover and never ran. - README, docs/, website/ and the issue templates no longer describe upstream's GitLab/GitHub pipeline, Discord, sponsorship or public demo as if they were this fork's; upstream history and attribution are preserved (NOTICE.md). |
||
|
|
90a1e8956a |
Admin: delete an account, not just disable it (#107)
Disabling locks someone out but deliberately leaves their state file and credential on disk, so 'no data remains' was not reachable from the dashboard — which is what the request asked for. POST /api/admin/user/delete removes the user, their passkeys, their push subscriptions, their presence entry, their training history and any Coach credential of theirs. Two refusals, because nothing in the UI could undo either: an admin cannot delete their own account, and the last remaining admin cannot be removed. The invite code they joined with stays burned — it was used, and freeing it would quietly widen an invite-only instance. In the dashboard it asks twice, naming the account both times, and offers their data as a download first: the training history is theirs. Five tests drive the real server. |
||
|
|
36123c0d19 |
Admin: a stored state written before the entry filter opens the drill-down instead of 500ing it (QA C16 follow-up)
GET /api/admin/user mapped S.routines straight off disk — `r.id` on every entry — so a single
null routine threw, the route answered 500 {"error":"server error"} with a stack trace in the
log, and the sheet never left "Loading…". The Disable button lives inside that sheet, so the
one account an operator opened the dashboard to stop was the one they could not: exactly the
end state C16 described, reached through routines instead of workouts. C16 hardened the sheet
and taught PUT /api/data to drop such entries, but a document v1.3.7 accepted still sits on
disk and answers to nobody.
A `records(list)` helper next to readState now hands every reader the entries of a stored list
and nothing else, and both admin routes go through it: the routine map, the body-weight log,
the workout history (whose `.slice()` threw in its own right when `workouts` was an object
rather than an array) and the user list's workout count, which counted entries the drill-down
then dropped and read `null` for a non-array list. A routine's exercise count counts entries
too, rather than the length of whatever `ex` happens to be. PUT /api/data reuses the helper
for the filter it already had, unchanged in behaviour.
The reminder tick walks the same two lists outside any route: a null entry threw there, was
logged and skipped, and cost that profile every reminder from then on, day after day. It
skips the entry now, not the profile.
Measured on QA slot 32 with each shape planted directly in the slot's data dir
(scripts/opengym-qa/run/r3-admin-null-routine/plant.mjs, shots alongside it):
routines [null, r] before GET /api/admin/user 500, sheet "Loading…", 0 Disable
buttons, 16 stack frames in api.log
after 200, sheet shows Workouts 1 · Weigh-ins 1 · Routines 1,
disable and re-enable both land in the audit log,
0 stack frames, no console or HTTP errors
workouts/routines as before 500, same dead sheet, 12 stack frames
objects, not arrays after 200 with empty lists
bodyweight [null, b] before 200 but "Weigh-ins 2" for one weigh-in (4 for one plus
three junk entries)
after 1, the number of weigh-ins there are
null and shapeless workout entries, a null customEx, absent lists and an ordinary
profile all open, disable and enable, before and after.
api/test/server-admin-state.test.js covers both admin routes against ten stored shapes, and
server-reminder.test.js gains the null-entry case: 188 api tests (was 185). Frontend
untouched — the sheet's own guard from C16 still does the work the server cannot: 1533 vitest
green, 14 locales in sync, 33 demo-only source strings.
|
||
|
|
f94f8ca320 |
API: a request the client got wrong is a 400 (or 413), never a 500 with a stack trace — bad or non-object JSON, an array as the state document, null workout entries, a rest timer without seconds (QA C17, C19, C20, C16)
readBody rejects with a typed HttpError for unparseable text and for a JSON null, string,
number or array; the catch-all answers it with its status and does not log it — three of
these routes are reachable without a session, and a stack trace per malformed body let
anyone fill the container log. String() on a caller-supplied field went through the same
door ({"code":{"toString":1}} is valid JSON) and is replaced by a text() helper.
PUT /api/data refuses an array state (typeof 'object', but _rev on it is dropped by
JSON.stringify, so the file read back as rev 0 while the response claimed rev N+1) and
drops null and non-object entries from workouts/routines instead of refusing them: such an
entry carries nothing worth keeping, while a 400 would strand a client whose own copy is
already malformed in a re-send loop. Every server-side reader of the document (reminder
tick, admin drill-down) dereferences the entries.
POST /api/push/rest-timer validates seconds before clamping — the clamp ran first, turned
any missing or unusable value into a 1-second push and made the documented 400 unreachable.
A body over 5 MiB is a 413 the client actually gets to read: the remainder of the upload is
drained instead of the socket destroyed under it (which sent a reset that a node client hit
before parsing the answer — the QA proxy reported 502 on 3 of 4 attempts, 5 of 5 read the
413 afterwards); past twice the cap the upload is cut off. openapi.yaml documents the
400/413 bodies and the rest-timer 400.
|
||
|
|
826432a3a2 | Signed in, the server's profile is the truth: sign-in and pairing adopt it and ask once about workouts logged while signed out (Add them / Keep profile as is); the app polls the revision every 30 s and on every resume (GET /api/data/rev) and fetches only what moved; offline and unsynced states show a banner, retry on reconnect and confirm with a toast; pagehide flushes a pending change | ||
|
|
477fc07f8b |
Push: reminders owed within 15 minutes still arrive, the subscription heals itself on every boot, rest-timer alerts belong to the device that started the rest
- reminder tick: a due reminder is sent for up to 15 minutes after its time (once per local date) instead of only on the exact minute — a restart across that minute used to lose the day; state files are stat'ed and re-read only when they changed - sendPush prunes 403 (stale VAPID key) like 404/410; optional device targeting - POST /api/push/subscribe is an upsert that keeps created and stores a deviceId; GET /api/push/status says whether the server holds an endpoint - rest timers keyed per user+device; cancel without a device id keeps the old account-wide behaviour - sw.js: payload parsed inside waitUntil (never a silent push), pushsubscriptionchange re-subscribes and registers the new endpoint - lib/push.js: syncPushSubscription() (called once per signed-in boot from App.jsx and when Settings opens) re-registers a lost row, replaces a subscription made against another key, pushSupported() is false off https; deviceId() per browser - Settings: the notifications switch shows what the server holds - tests: server-reminder (window, dedupe, trained day), server-push-status (upsert, status, per-device timers), lib/push.test.js |
||
|
|
5276f9714a | api: /api/data carries a server revision — GET hands it out, a PUT with a stale baseRev answers 409 with the current document instead of overwriting another device's write; clients without baseRev keep overwriting as before | ||
|
|
67a8e68e42 | api: #160 findings 3/7/8/12 — a request target that does not parse answers 400 instead of an unhandled rejection, the reminder tick skips a state it cannot read and PUT /api/data refuses non-array workouts/routines, the push address rule judges every IPv6 spelling and re-checks literals before each send, sign out everywhere voids unredeemed pairing codes | ||
|
|
3dd2092a8d |
Combine routines (ENG-9) phase 3: start-flow wiring + resolver call sites
startFlow / beginWorkout now take string | string[] | null and route through buildCombinedEntries; callers pass [r.id], effectiveRoutineIds(...) or [] as appropriate. Every effectiveRoutine(S,iso) render site that showed one routine now iterates effectiveRoutines / checks effectiveRoutineIds. - sheets.jsx: beginWorkout / beginBackfill write s.active.routineIds + derived name, no routineId / excludeFromProgression; swapTo resolves the slot's routine from its entry rid and carries rid onto the replacement; DayOverride / Calendar use the plural resolver (dayPlan stays scalar — overriding a combined date collapses it, per spec §8); DayAssign writes a one-element list. - active-exercise-swap.js: split-insert carries current.rid like it carries sg. - Workout.jsx: StartChooser id-set exclusion + startFlow(list); add-exercise and progression-settings resolve the routine from the current entry's rid and stamp rid on a freehand add. - TabBar / Home: onStart(effectiveRoutineIds(...)); Home plannedPerWeek counts scheduled days not routines; today card name joins the day's routines. - mobile.js buildReminderNotifications: names all of a combined day's routines, or a count past two. - RoutineEdit delete-cleanup pulls the id from each week list, drops an emptied key. api/server.js effectiveRoutineId reads the first of the list. Tests: sheets.combine.test.jsx (beginWorkout with a routine-id list); mobile.test.js combined-day reminder. Existing suites stay green on the tolerant-reader path. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01JVbWJtoyQU4WgwFR4eAKgy |
||
|
|
e134914026 |
Coach: der Server waermt den Prefix-Cache selbst, und die Tipp-Blase glaubt dem letzten Lauf
Der KV-Prefix-Cache eines lokalen Endpunkts stirbt mit dem Ollama-Prozess; der erste Job danach zahlte still den Kaltstart (~8 min statt ~1). Jetzt pingt der api-Prozess bei Boot und alle 30 Minuten die Review- und Debrief-Prefixe an den kompatiblen Endpunkt — warm kostet der Ping ein Token, kalt macht er die teure Lesung genau einmal, auf niemandes Uhr. Cloud-Provider werden nie gepingt. Und estimateMs nimmt min(Median, letzter Lauf): nach einer Beschleunigung schleppte der Median drei alte 8-Minuten-Laeufe mit. |
||
|
|
4a9e1e3456 |
Merge main (v1.2.11) into coach: Pairing, Notizen, Aufwaerm-Saetze, GitLab-CI
Der Coach-Zweig stand seit v1.2.7. Konflikte: beide Seiten behalten (Server-Imports, Store-Felder, Home-Titel mit naechster Einheit, history.js), das Dockerfile behaelt seine zwei Targets und kopiert die neuen Server-Module mit, compose zeigt auf die GitLab-Registry. pt-BR: die 139 Coach-Strings in die Sie-Form gebracht, Fingerprint nachgezogen. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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> |
||
|
|
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> |
||
|
|
032fe1a348 | fix(push): localize server notifications in pt-BR | ||
|
|
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). |
||
|
|
8d3f667c89 | Merge main into coach: v1.2.6 plus die Backlog-Runde, Locale-Union, CI laeuft jetzt auch auf coach | ||
|
|
9daf637044 | Gastmodus abschaltbar: ALLOW_GUEST=0 nimmt die Tuer ohne Konto raus (#42) | ||
|
|
7be3978476 |
Coach: server plumbing, consent, payload boundary, credential model
First of six. Everything here is transport and boundary: a job can run, its answer can be parsed, and nothing yet judges whether that answer is safe to act on. The validator and the apply path are the next PR, and the seam is explicit — jobs.js carries an answer no further than `unvalidated`, and a test pins that so the next PR has something to replace. Whose account pays, settled first because it decides what the rest may be: instance one account in coach.json, for the single-profile instance profile one account per profile, in its own coach-auth-<uid>.json In instance mode the credential binds to the first profile that spends it and every other profile is refused — no job, not a dismissible warning. A warning moves the decision onto whoever clicks past it and the decision is about somebody's personal subscription. A profile credential is deliberately not a field on state-<uid>.json: that blob syncs and travels in the user's export, and a credential in a backup is the mistake we are avoiding, not repeating. openGym does not interpret any provider's terms; it offers the shape that does not need the interpretation and refuses the shape that does. The privilege drop now fails closed. It only ever engaged when the server ran as root, so adding a USER line to the Dockerfile for unrelated hardening would have silently left the provider runtime on the server's uid. On Linux, no drop means no job, and the admin card says so. ./data is no longer sealed with a blanket 0700. It is a host bind mount and this container is root, so sealing it landed on the host as root-owned and took the owner's own directory hostage — backup scripts, jq, the MCP server in issue #19. The files that hold secrets carry 0600 themselves instead, which is what the directory mode was standing in for; db.json gained an explicit mode rather than inheriting umask once the blanket came off. Bodyweight and per-side, folded in rather than deferred: v1.2.4 made `weight` mean *added* load on a bodyweight exercise, so it is 0 on a good session and every load-shaped signal reads flat. Uncorrected, the Coach would have looked at a working push-up progression and proposed adding weight to a push-up. The payload carries bodyweight/side/repsMax, the session reader carries set count, and the prompts say reps then sets are the progression and per-side targets step in twos. coach-parity.test.js pins the server's three copied reading rules against the frontend's originals over a table of configs — modeOf was never actually pinned, and it is the one that was predicted to drift. No AI dependency lands here: api/ still installs @simplewebauthn/server and web-push and nothing else. Jobs run against the in-repo fixture provider, so CI needs no account, no network and no image build. 33 api tests, 361 frontend tests (169 of them parity), locales in sync. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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.
|
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
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. |
||
|
|
4c2b6344f7 |
Add push notifications: rest-timer alert + workout-day reminder
Web Push (VAPID) backend: keys auto-generated on first run, per-user subscriptions, one new dependency (web-push). The rest timer schedules a server-side push on start/extend and cancels it on skip or on-screen completion, so it only actually fires if the tab got suspended before finishing. A per-minute check sends an optional daily reminder on days with a planned routine that hasn't been logged yet. Opt in per-profile in Settings — requires a signed-in passkey profile. |
||
|
|
3333b4decd |
openGym: Open-Source-Release als Self-Hosting-App
Rebranding GymLog → openGym. Ein-Befehl-Self-Hosting via Docker Compose: web (nginx serviert App + Proxy /api → api, ein Origin für Passkeys), api (Node/WebAuthn), media-Service lädt Übungs-GIFs beim ersten Start automatisch. Passkey-Domain über .env konfigurierbar (RP_ID/ORIGIN/WEB_PORT/RP_NAME), Secure-Cookie nur bei HTTPS (http://localhost funktioniert). MIT-Lizenz, README fürs Self-Hosting, docs/SELF_HOSTING.md, CONTRIBUTING.md. Standalone-Stack Ende-zu-Ende getestet (Passkey-Register/-Login, Daten-Sync, User-Isolation über den Proxy auf http://localhost). |
||
|
|
29f5f64f8e |
GymLog: Gym- & Körpergewicht-Tracker — PWA mit Passkey-Login
Frontend: Static-SPA (Vanilla JS) — Dashboard, Wochenplan mit Per-Tag-Umplanung, geführter Workout-Flow (Körpergewicht-Abfrage, Set-Logging, Rest-Timer, PR-Erkennung, Gewichts-Bestätigung pro Übung), Activity-Heatmap, Kraft- & Gewichts-Charts, Übungs-Bibliothek (1324 Übungen, autoplay GIFs), Swipe-Sheets, PWA/offline. Backend: Node + @simplewebauthn — Passkey-Registrierung/-Login (Face ID), HMAC-Session-Cookies, Per-User-State-Sync mit JSON-File-Storage. Übungsdaten aus hasaneyldrm/exercises-dataset (Medien via scripts/fetch-media.sh). |