Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
Admin: a stored state written before the entry filter opens the drill-down instead of 500ing it (QA C16 follow-up)
Duarte Santos36123c0d1996
diff --git a/api/openapi.yaml b/api/openapi.yamlindex fd2f23db2..b4ad591d6 100644--- a/api/openapi.yaml+++ b/api/openapi.yaml@@ -851,7 +851,8 @@ paths:summary: 'Admin: list all users'description: >-One row per user with workout counts, last sync, push status and live- presence. Admin only.+ presence. `workouts` counts only the entries the drill-down can show.+ Admin only.responses:'200':description: All users.@@ -877,7 +878,10 @@ paths:summary: 'Admin: one user in detail'description: >-Drill-down — full workout history (newest first) and body-weight log for one- user. Admin only.+ user. Admin only. Anything in `routines`, `bodyweight` or `workouts` that is not+ an object is left out, and a list that is not an array reads as empty: PUT+ /api/data drops those entries now, but a state file written before it did still+ has them and this route has to answer for it.parameters:- name: idin: querydiff --git a/api/server.js b/api/server.jsindex 8da9389b0..be84073c6 100644--- a/api/server.js+++ b/api/server.js@@ -81,6 +81,16 @@ const stateFile = uid => path.join(DATA, 'state-' + uid.replace(/[^a-zA-Z0-9_-]/function readState(uid) {try { return JSON.parse(fs.readFileSync(stateFile(uid), 'utf8')); } catch { return null; }}+// An entry is an object a reader can dereference, and `records` is every entry of a stored+// list. PUT /api/data drops the rest on the way in — a null workout, a routine that is a+// number — and refuses a list that is not an array at all, but a file written before it did+// answers to nobody, and the readers below walk those lists (`r.id`, `w.d`, `.slice()`). One+// throw inside an admin route is a 500 for that whole profile: the drill-down never leaves+// "Loading…", the Disable button lives inside it, and the account an operator opened the+// dashboard to stop is exactly the one they then cannot. Answering with the entries that are+// there is the honest reading of such a file — what was dropped carried nothing to show.+const record = x => !!x && typeof x === 'object' && !Array.isArray(x);+const records = v => (Array.isArray(v) ? v.filter(record) : []);/* ---------- push notifications (Web Push / VAPID) ---------- */const vapidFile = path.join(DATA, 'vapid.json');@@ -259,13 +269,14 @@ const deviceIdOf = v => (typeof v === 'string' && /^[A-Za-z0-9_-]{8,64}$/.test(v// "Workout planned today" reminder — one per user per day, at their chosen time.// Duplicated (not imported) from frontend/src/lib/history.js effectiveRoutineId — tiny pure helper, not worth sharing across the two runtimes.+// The `?.` on each entry is this copy's own: it reads whatever is on disk, including a file written before PUT /api/data dropped null entries.// A weekday can hold a routine-id list (combine routines); the reminder only needs the first.function effectiveRoutineId(S, iso) {const ov = S.dayPlan?.[iso];if (ov === 'rest') return null;- if (ov && S.routines?.some(r => r.id === ov)) return ov;+ if (ov && S.routines?.some(r => r?.id === ov)) return ov;const wd = new Date(iso + 'T12:00:00').getDay();- return [].concat(S.week?.[wd] || []).find(id => S.routines?.some(r => r.id === id)) || null;+ return [].concat(S.week?.[wd] || []).find(id => S.routines?.some(r => r?.id === id)) || null;}// 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.@@ -324,10 +335,10 @@ setInterval(() => {const late = minutesLate(S.reminder.time, now);if (!(late >= 0 && late <= REMINDER_WINDOW_MIN)) continue;if (user.lastReminder === now.date) continue;- if ((S.workouts || []).some(w => w.d === 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);+ const routine = (S.routines || []).find(r => r?.id === rid);console.log('reminder firing', user.id, rid);user.lastReminder = now.date;saveDb();@@ -908,12 +919,11 @@ const routes = {// the response claimed the next revision.const list = v => v == null || Array.isArray(v);if (Array.isArray(body.state) || !list(body.state.workouts) || !list(body.state.routines)) return json(res, 400, { error: 'invalid state' });- // The same readers dereference every entry (`w.d`, `w.name`), so a null or non-object entry- // would throw there — and blank the admin's drill-down of this profile. Dropped, not refused:+ // The same readers walk every entry (`w.d`, `w.name`). They skip what is not an entry now+ // (`records` above), but nothing should be storing one. Dropped, not refused:// such an entry carries nothing worth keeping, whereas a 400 would strand a client whose own// copy is already malformed — it keeps re-sending the same document and never syncs again.- const record = x => x && typeof x === 'object' && !Array.isArray(x);- for (const k of ['workouts', 'routines']) if (Array.isArray(body.state[k])) body.state[k] = body.state[k].filter(record);+ for (const k of ['workouts', 'routines']) if (Array.isArray(body.state[k])) body.state[k] = records(body.state[k]);// Conditional write: a `baseRev` that is not the current revision means this client last// read an older document — another device has written since — and the copy it is about to// push would silently drop that write. The current document travels back with the 409, so@@ -1036,7 +1046,7 @@ const routes = {if (!requireAdmin(req, res)) return;const users = db.users.map(u => {const S = readState(u.id) || {};- const workouts = S.workouts || [];+ const workouts = records(S.workouts);const last = workouts[workouts.length - 1];return {id: u.id, name: u.name, created: u.created || null,@@ -1062,9 +1072,9 @@ const routes = {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+ routines: records(S.routines).map(r => ({ id: r.id, name: r.name, emoji: r.emoji, count: records(r.ex).length })),+ bodyweight: records(S.bodyweight),+ workouts: records(S.workouts).reverse() // records() already copied, so this reverse is ours: newest first for display});},diff --git a/api/test/server-admin-state.test.js b/api/test/server-admin-state.test.jsnew file mode 100644index 000000000..e4fc49899--- /dev/null+++ b/api/test/server-admin-state.test.js@@ -0,0 +1,130 @@+/* The admin routes read state files nobody validated. PUT /api/data drops null and shapeless+ entries and refuses a non-array `workouts`/`routines` (QA C16/C19), but a document written+ before it did still sits on disk and answers to nobody — and every one of these routes walks+ those lists and dereferences what it finds. One throw is a 500 for the whole drill-down: the+ sheet never leaves "Loading…", and the Disable button lives inside that sheet, so the account+ an operator opened the dashboard to stop stays un-disableable. Real server.js in a child. */+import { test } from 'node:test';+import assert from 'node:assert/strict';+import crypto from 'node:crypto';+import net from 'node:net';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { spawn } from 'node:child_process';+import { fileURLToPath } from 'node:url';++const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');+const SECRET = crypto.randomBytes(32).toString('hex');++// Same construction as server.js makeSession(): payload `uid:exp:sv`, HMAC-SHA256 over SECRET.+function mintSession(uid) {+ const payload = `${uid}:${Date.now() + 86400000}:0`;+ return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');+}+const ADMIN = 'u_adm_1', VICTIM = 'u_vic_1';+const asAdmin = { Cookie: `gymsid=${mintSession(ADMIN)}`, 'Content-Type': 'application/json' };++const freePort = () => new Promise(r => {+ const s = net.createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); });+});++async function startServer(t) {+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-admin-'));+ fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });+ fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({+ users: [+ { id: ADMIN, name: 'Adminna', created: new Date().toISOString(), admin: true },+ { id: VICTIM, name: 'Mallory', created: new Date().toISOString() }+ ], creds: [], subs: [], invites: []+ }));+ const port = await freePort();+ const child = spawn(process.execPath, ['server.js'], {+ cwd: API, stdio: ['ignore', 'pipe', 'pipe'],+ env: { ...process.env, PORT: String(port), DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' }+ });+ const h = { api: `http://127.0.0.1:${port}`, log: '', dataDir };+ child.stdout.on('data', d => h.log += d);+ child.stderr.on('data', d => h.log += d);+ t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });+ let up = false;+ for (let i = 0; i < 100 && !up; i++) {+ try { up = (await fetch(`${h.api}/api/health`)).ok; } catch { /* not up yet */ }+ if (!up) await new Promise(r => setTimeout(r, 100));+ }+ assert.ok(up, `server never came up:\n${h.log}`);+ // The boot line is fine; anything that looks like a stack frame after this is a defect.+ h.stackFrames = () => h.log.split('\n').filter(l => /^\s+at /.test(l)).length;+ h.plant = S => fs.writeFileSync(path.join(h.dataDir, `state-${VICTIM}.json`), JSON.stringify(S));+ h.get = async p => { const r = await fetch(`${h.api}${p}`, { headers: asAdmin }); return { status: r.status, body: await r.json() }; };+ return h;+}++// One good entry of each kind, so every case below can say what survived as well as what did not.+const okW = { id: 'w1', name: 'Fine', d: '2026-09-18', start: 1, end: 2, entries: [{ id: 'e', sets: [{ w: 10, r: 5, done: true }] }] };+const okR = { id: 'r1', name: 'Full body', emoji: '💪', ex: [{ id: '0001', sets: 3, reps: 10 }] };+const okB = { d: '2026-09-01', w: 80 };++/* The shapes v1.3.7 accepted through PUT /api/data, one per line. `null` is the one the field+ reports came in with; the rest are the same mistake one field over. */+const DOCS = {+ 'a null routine entry': { workouts: [okW], routines: [null, okR], bodyweight: [okB], unit: 'kg' },+ 'shapeless routine entries': { workouts: [okW], routines: [7, 'x', [], okR], bodyweight: [okB], unit: 'kg' },+ 'a null workout entry': { workouts: [null, okW], routines: [okR], bodyweight: [okB], unit: 'kg' },+ 'shapeless workout entries': { workouts: ['x', [], okW], routines: [okR], bodyweight: [okB], unit: 'kg' },+ 'a null body-weight entry': { workouts: [okW], routines: [okR], bodyweight: [null, okB], unit: 'kg' },+ 'shapeless body-weight entries': { workouts: [okW], routines: [okR], bodyweight: ['x', 7, [], okB], unit: 'kg' },+ 'a null customEx entry': { workouts: [okW], routines: [okR], bodyweight: [okB], customEx: [null], unit: 'kg' },+ 'lists that are objects, not arrays': { workouts: { a: 1 }, routines: { a: 1 }, bodyweight: { a: 1 }, unit: 'kg' },+ 'lists that are null': { workouts: null, routines: null, bodyweight: null, unit: 'kg' },+ 'no lists at all': { unit: 'kg' }+};++test('GET /api/admin/user opens a profile whose stored state predates the entry filter', async t => {+ const h = await startServer(t);+ for (const [what, doc] of Object.entries(DOCS)) {+ h.plant(doc);+ const r = await h.get(`/api/admin/user?id=${VICTIM}`);+ assert.equal(r.status, 200, `${what}: ${JSON.stringify(r.body)}`);+ // Every list the sheet counts and walks comes back usable — the drill-down renders it+ // without a guard of its own for anything but the workout entries.+ for (const k of ['routines', 'bodyweight', 'workouts']) {+ assert.ok(Array.isArray(r.body[k]), `${what}: ${k} is an array`);+ assert.equal(r.body[k].some(x => !x || typeof x !== 'object' || Array.isArray(x)), false, `${what}: ${k} holds only entries`);+ }+ }+ // The good entries are still there, and a routine's exercise count is a number in every case.+ h.plant(DOCS['a null routine entry']);+ let r = await h.get(`/api/admin/user?id=${VICTIM}`);+ assert.deepEqual(r.body.routines, [{ id: 'r1', name: 'Full body', emoji: '💪', count: 1 }]);+ assert.deepEqual(r.body.workouts.map(w => w.id), ['w1']);+ assert.deepEqual(r.body.bodyweight, [okB]);+ h.plant({ routines: [{ id: 'r2', name: 'Broken', ex: 'nope' }] });+ r = await h.get(`/api/admin/user?id=${VICTIM}`);+ assert.deepEqual(r.body.routines, [{ id: 'r2', name: 'Broken', count: 0 }]); // an `ex` that is not a list counts as no exercises+ assert.equal(h.stackFrames(), 0, `stack traces in the log:\n${h.log}`);+});++test('the user list and the disable switch survive the same document', async t => {+ const h = await startServer(t);+ for (const [what, doc] of Object.entries(DOCS)) {+ h.plant(doc);+ const r = await h.get('/api/admin/users');+ assert.equal(r.status, 200, what);+ const row = r.body.users.find(u => u.id === VICTIM);+ // "Workouts" is a count of what the drill-down will show, so it is a number, and it does+ // not count entries the sheet drops.+ assert.equal(typeof row.workouts, 'number', `${what}: workouts is a number`);+ assert.equal(row.workouts, Array.isArray(doc.workouts) ? doc.workouts.filter(w => w && typeof w === 'object' && !Array.isArray(w)).length : 0, what);+ }+ // The end state the whole thing is about: the account can be stopped from the dashboard.+ h.plant(DOCS['a null routine entry']);+ const r = await fetch(`${h.api}/api/admin/user/disable`, { method: 'POST', headers: asAdmin, body: JSON.stringify({ id: VICTIM, disabled: true }) });+ assert.equal(r.status, 200);+ assert.equal(JSON.parse(fs.readFileSync(path.join(h.dataDir, 'db.json'), 'utf8')).users.find(u => u.id === VICTIM).disabled, true);+ // …and the audit log still reads back, with that change in it.+ const a = await h.get('/api/admin/audit?limit=10&cat=');+ assert.equal(a.status, 200);+ assert.ok(a.body.events.some(e => e.ev === 'admin.user.disable'), JSON.stringify(a.body.events));+ assert.equal(h.stackFrames(), 0, `stack traces in the log:\n${h.log}`);+});diff --git a/api/test/server-reminder.test.js b/api/test/server-reminder.test.jsindex f3689bc18..51fef782f 100644--- a/api/test/server-reminder.test.js+++ b/api/test/server-reminder.test.js@@ -163,3 +163,22 @@ test('a reminder 20 minutes past is not delivered late, and a day already traineawait wait(1500);assert.equal(firings(h.log), 0, `a trained day must stay silent:\n${h.log}`);});++/* A null entry inside an otherwise fine list is not a shape the tick can refuse at the door:+ PUT /api/data drops those now, but a file written before it did still has them, and the tick+ walks both lists (`w.d`, `r.id`). It threw on the first entry and skipped the user — every+ day, silently, for as long as the file stayed that way. The entries are skipped; the reminder+ is not. */+test('a null entry in workouts or routines does not cost that profile its reminder', async t => {+ const late = hhmmMinusMinutes(2);+ if (!late.sameDay) return t.skip('just after midnight UTC — a same-day window cannot be set up');+ const h = await startServer(t, [sub]);+ fs.writeFileSync(path.join(h.dataDir, 'state-u_test_1.json'), goodState(late.hhmm, {+ workouts: [null, { id: 'w1', d: '2026-01-01' }],+ routines: [null, { id: 'r1', name: 'Full body', emoji: '💪', ex: [] }]+ }));+ const deadline = Date.now() + 30000;+ while (Date.now() < deadline && !firings(h.log)) await wait(300);+ assert.equal(firings(h.log), 1, h.log);+ assert.doesNotMatch(h.log, /reminder tick u_test_1 TypeError/, h.log);+});