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
Follow-up to #249: the four server tests that arrived since let the server pick its own port too, and the sync-status tests start without a Coach-less config left over from a boot test
Duarte Santosa884eeb31c20
diff --git a/api/test/server-admin-delete.test.js b/api/test/server-admin-delete.test.jsindex ad9a7f1ec..2ce62fcc0 100644--- a/api/test/server-admin-delete.test.js+++ b/api/test/server-admin-delete.test.js@@ -6,12 +6,12 @@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';+import { boundPort } from './helpers.mjs';const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');const SECRET = crypto.randomBytes(32).toString('hex');@@ -21,10 +21,6 @@ const mintSession = uid => {};const ADMIN = 'u_adm_1', ADMIN2 = 'u_adm_2', VICTIM = 'u_vic_1';const as = uid => ({ Cookie: `gymsid=${mintSession(uid)}`, '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, { twoAdmins = false } = {}) {const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-del-'));fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });@@ -40,21 +36,18 @@ async function startServer(t, { twoAdmins = false } = {}) {invites: [{ code: 'CODE1', usedBy: VICTIM, usedAt: new Date().toISOString() }],}));fs.writeFileSync(path.join(dataDir, `state-${VICTIM}.json`), JSON.stringify({ unit: 'kg', workouts: [], _rev: 3 }));- 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' },+ env: { ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' },});- const h = { api: `http://127.0.0.1:${port}`, log: '', dataDir };+ const h = { api: '', 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 carries the port the listener bound, so it is both the address and the+ // readiness signal — see boundPort in helpers.mjs for why the test does not pick one.+ h.port = await boundPort(child, () => h.log);+ h.api = `http://127.0.0.1:${h.port}`;h.del = async (id, uid = ADMIN) => {const r = await fetch(`${h.api}/api/admin/user/delete`, { method: 'POST', headers: { ...as(uid), Origin: 'http://localhost:8080' }, body: JSON.stringify({ id }) });return { status: r.status, body: await r.json() };diff --git a/api/test/server-admin-state.test.js b/api/test/server-admin-state.test.jsindex e4fc49899..39e408ddf 100644--- a/api/test/server-admin-state.test.js+++ b/api/test/server-admin-state.test.js@@ -7,12 +7,12 @@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';+import { boundPort } from './helpers.mjs';const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');const SECRET = crypto.randomBytes(32).toString('hex');@@ -25,10 +25,6 @@ function mintSession(uid) {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 });@@ -38,21 +34,18 @@ async function startServer(t) {{ 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' }+ env: { ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' }});- const h = { api: `http://127.0.0.1:${port}`, log: '', dataDir };+ const h = { api: '', 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 carries the port the listener bound, so it is both the address and the+ // readiness signal — see boundPort in helpers.mjs for why the test does not pick one.+ h.port = await boundPort(child, () => h.log);+ h.api = `http://127.0.0.1:${h.port}`;// 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));diff --git a/api/test/server-bad-input.test.js b/api/test/server-bad-input.test.jsindex a734fe24f..648977922 100644--- a/api/test/server-bad-input.test.js+++ b/api/test/server-bad-input.test.js@@ -4,13 +4,13 @@import { test } from 'node:test';import assert from 'node:assert/strict';import crypto from 'node:crypto';-import net from 'node:net';import http from 'node:http';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';+import { boundPort } from './helpers.mjs';const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');const SECRET = crypto.randomBytes(32).toString('hex');@@ -24,31 +24,24 @@ const UID = 'u_bad_1';const authed = { Cookie: `gymsid=${mintSession(UID)}`, 'Content-Type': 'application/json' };const anon = { '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-bad-'));fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({users: [{ id: UID, name: 'One', 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' }+ env: { ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' }});- const h = { api: `http://127.0.0.1:${port}`, log: '', dataDir };+ const h = { api: '', 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 carries the port the listener bound, so it is both the address and the+ // readiness signal — see boundPort in helpers.mjs for why the test does not pick one.+ h.port = await boundPort(child, () => h.log);+ h.api = `http://127.0.0.1:${h.port}`;// 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;return h;diff --git a/api/test/server-token-refresh.test.js b/api/test/server-token-refresh.test.jsindex 542263b30..94b85f734 100644--- a/api/test/server-token-refresh.test.js+++ b/api/test/server-token-refresh.test.js@@ -6,12 +6,12 @@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';+import { boundPort } from './helpers.mjs';const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');const SECRET = crypto.randomBytes(32).toString('hex');@@ -30,10 +30,6 @@ const verifies = token => {};const bearer = token => ({ Authorization: 'Bearer ' + token });-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)); });-});-const USERS = [{ id: 'u_phone', name: 'Phone', created: new Date().toISOString() },{ id: 'u_bumped', name: 'Bumped', created: new Date().toISOString(), sv: 1 }@@ -43,21 +39,18 @@ async function startServer(t) {const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-renew-'));fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ users: USERS, 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', SESSION_DAYS: String(SESSION_DAYS) }+ env: { ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost', SESSION_DAYS: String(SESSION_DAYS) }});- const h = { api: `http://127.0.0.1:${port}`, log: '' };+ const h = { api: '', log: '' };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 carries the port the listener bound, so it is both the address and the+ // readiness signal — see boundPort in helpers.mjs for why the test does not pick one.+ h.port = await boundPort(child, () => h.log);+ h.api = `http://127.0.0.1:${h.port}`;return h;}diff --git a/frontend/src/store/useStore.sync-status.test.jsx b/frontend/src/store/useStore.sync-status.test.jsxindex f11f7a31b..6024a2059 100644--- a/frontend/src/store/useStore.sync-status.test.jsx+++ b/frontend/src/store/useStore.sync-status.test.jsx@@ -26,16 +26,19 @@ const USER = { id: 'user-1', name: 'One' }const fresh = { offline: false, pending: false, auth: false, lastError: null, lastSynced: 0, server: null }const signedIn = (S, extra = {}) => useStore.setState({ S, user: USER, ready: true, sync: { ...fresh }, ...extra })+// config goes back to null as well: a boot test leaves a pre-sign-in copy behind (no `coach`+// key), and setUser re-asks /api/config for such a copy (#249), which would take the next test's+// queued answer meant for its pull.beforeEach(() => {localStorage.clear()localStorage.setItem('gym_owner', USER.id)api.mockReset(); toast.mockReset()- useStore.setState({ S: clone(DEF), user: null, ready: false, sync: { ...fresh } })+ useStore.setState({ S: clone(DEF), user: null, ready: false, sync: { ...fresh }, config: null })})afterEach(() => {vi.useRealTimers()localStorage.clear()- useStore.setState({ S: clone(DEF), user: null, ready: false, sync: { ...fresh } })+ useStore.setState({ S: clone(DEF), user: null, ready: false, sync: { ...fresh }, config: null })})describe('sync status', () => {