Skip to content

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.

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

Boris Kurktchiev67a8e68e42a5
diff --git a/SECURITY.md b/SECURITY.md
index f8d67e41d..4e86fe0f6 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -113,11 +113,13 @@ Read this before hosting openGym for anyone other than yourself.
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
+ (including cloud metadata) or CGNAT address — enforced in the agent's DNS lookup for hostnames,
+ so there is no rebinding window, and for literal IP addresses — which never go through that
+ lookup — by the same address check at subscribe time and again before every send, applied to
+ every textual form of the address (`api/server.js:93-223`). 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`).
+ burst of outbound connections (`api/server.js:108-110`).
- **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 /
diff --git a/api/openapi.yaml b/api/openapi.yaml
index 6b9c29c46..64554ad31 100644
--- a/api/openapi.yaml
+++ b/api/openapi.yaml
@@ -386,7 +386,8 @@ paths:
Bumps the account's session version, which invalidates **every** cookie and
Bearer token ever issued for it — on every device, including a copy someone
walked off with. Passkeys are untouched; signing back in works immediately.
- Also clears the caller's own cookie.
+ Also clears the caller's own cookie. Unredeemed pairing codes for the account
+ are voided too.
responses:
'200':
description: All sessions revoked.
@@ -518,11 +519,15 @@ paths:
oneOf: [{ type: number }, { type: 'null' }]
description: Echo of the pushed state's `_ts`, if present.
'400':
- description: '`state` missing or not an object.'
+ description: >-
+ `state` missing or not an object, or `workouts`/`routines` set to anything
+ other than an array or null.
content:
application/json:
schema: { $ref: '#/components/schemas/Error' }
- example: { error: "state required" }
+ examples:
+ missing: { value: { error: "state required" } }
+ invalid: { value: { error: "invalid state" } }
'401': { $ref: '#/components/responses/Unauthorized' }
/api/push/public-key:
@@ -1135,7 +1140,8 @@ components:
description: |
The whole app state as one blob. The server treats it as opaque (it only
strips `active` on save and reads a few fields for reminders and the admin
- dashboard) — the schema below is **representative, not enforced**, and grows
+ dashboard) — the schema below is **representative, not enforced** (except
+ `workouts` and `routines`, which must be arrays (or null) when present), and grows
with the app. Conflict resolution is client-side via `_ts`.
properties:
_ts:
diff --git a/api/server.js b/api/server.js
index a5b35f193..e8fec8cf6 100644
--- a/api/server.js
+++ b/api/server.js
@@ -6,6 +6,7 @@ import fs from 'node:fs';
import path from 'node:path';
import https from 'node:https';
import dns from 'node:dns';
+import net from 'node:net';
import {
generateRegistrationOptions, verifyRegistrationResponse,
generateAuthenticationOptions, verifyAuthenticationResponse
@@ -96,7 +97,10 @@ webpush.setVapidDetails(VAPID_SUBJECT, vapid.publicKey, vapid.privateKey);
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.
+ the request itself uses, not in a prior pass. A literal IP address never goes through
+ that lookup at all — Node hands it straight to connect() — so literals are judged by
+ pushEndpointError instead: at subscribe, and again in sendPush for an endpoint that got
+ into db.json some other way.
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
@@ -119,14 +123,37 @@ function isPrivateAddr(ip) {
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
+ // IPv6 is judged on its eight groups, never on the text: the same address arrives as
+ // `::ffff:127.0.0.1` from dns.lookup, as `::ffff:7f00:1` from new URL, and in whatever
+ // spelling a caller chose, and a rule keyed to one spelling misses the others.
+ const g = ipv6Groups(v);
+ if (!g) return false;
+ if (g.slice(0, 5).every(x => x === 0) && g[5] === 0xffff) { // IPv4-mapped IPv6
+ return isPrivateAddr(`${g[6] >> 8}.${g[6] & 255}.${g[7] >> 8}.${g[7] & 255}`);
+ }
+ if (g.slice(0, 7).every(x => x === 0) && g[7] <= 1) return true; // unspecified, loopback
+ if ((g[0] & 0xffc0) === 0xfe80) return true; // link-local fe80::/10
+ if ((g[0] & 0xfe00) === 0xfc00) return true; // unique local fc00::/7
return false;
}
+// The eight 16-bit groups of an IPv6 literal in any textual form — compressed, zero-padded,
+// upper-case, with a dotted IPv4 tail — or null when the string is not one.
+function ipv6Groups(v) {
+ if (!net.isIPv6(v)) return null;
+ let s = v.replace(/%.*$/, ''); // zone id
+ const m4 = /:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.exec(s);
+ if (m4) {
+ const [a, b, c, d] = m4[1].split('.').map(Number);
+ s = s.slice(0, -m4[1].length) + ((a << 8) | b).toString(16) + ':' + ((c << 8) | d).toString(16);
+ }
+ const [head, tail = ''] = s.split('::');
+ const groups = head ? head.split(':') : [];
+ const rest = tail ? tail.split(':') : [];
+ if (s.includes('::')) while (groups.length + rest.length < 8) groups.push('0');
+ return groups.concat(rest).map(x => parseInt(x, 16));
+}
+
// Same shape as dns.lookup, so https.Agent can use it directly.
function guardedLookup(hostname, options, cb) {
dns.lookup(hostname, options, (err, address, family) => {
@@ -141,15 +168,16 @@ function guardedLookup(hostname, options, cb) {
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.
+// than silently never delivering. For a hostname PUSH_AGENT is what actually enforces the address
+// rule; for a literal address this is the check, which is why sendPush runs it again.
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.
+ // A literal address is judged right here — and only here: Node hands a literal straight to
+ // connect() without consulting the Agent's lookup. Hostnames are left to PUSH_AGENT, which is
+ // the check that has to hold against rebinding.
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';
@@ -166,6 +194,14 @@ async function sendPush(userId, payload) {
const worker = async () => {
while (next < subs.length) {
const sub = subs[next++];
+ // Re-judged before every send: PUSH_AGENT never sees a literal address, so an endpoint
+ // that is private (however it got into db.json) is dropped here rather than connected to.
+ const bad = pushEndpointError(sub.endpoint);
+ if (bad) {
+ console.error('push endpoint refused', userId, bad);
+ db.subs = db.subs.filter(s => s.endpoint !== sub.endpoint); dirty = true;
+ continue;
+ }
// 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,
@@ -230,19 +266,26 @@ function userNow(tz) {
setInterval(() => {
for (const user of db.users) {
if (!db.subs.some(s => s.userId === user.id)) continue;
- const S = readState(user.id);
- 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);
- console.log('reminder firing', user.id, rid);
- user.lastReminder = now.date;
- saveDb();
- sendPush(user.id, dayReminderPush(S.lang, routine));
+ // One user's state file is one user's problem: a shape this tick cannot read is logged and
+ // skipped, not allowed to take the process — and everyone else's reminders — down with it.
+ // PUT /api/data refuses the obvious shapes, but a file already on disk answers to nobody.
+ try {
+ const S = readState(user.id);
+ 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);
+ console.log('reminder firing', user.id, rid);
+ user.lastReminder = now.date;
+ saveDb();
+ sendPush(user.id, dayReminderPush(S.lang, routine));
+ } catch (e) {
+ console.error('reminder tick', user.id, e);
+ }
}
// 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.
@@ -716,6 +759,8 @@ const routes = {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
user.sv = sessionVersion(user) + 1;
+ // An unredeemed pairing code is a session-in-waiting for this account; it goes too.
+ for (const [k, v] of pairings) if (v.uid === user.id) pairings.delete(k);
saveDb();
audit(req, 'auth.logout.all', { user });
json(res, 200, { ok: true }, { 'Set-Cookie': clearCookie });
@@ -766,6 +811,11 @@ const routes = {
if (!user) return json(res, 401, { error: 'not signed in' });
const body = await readBody(req);
if (!body.state || typeof body.state !== 'object') return json(res, 400, { error: 'state required' });
+ // The reminder tick and the admin routes iterate these two on the server's side, so a truthy
+ // non-array would throw there on every pass for as long as it sat on disk. Absent or null is
+ // fine — every client fills its own defaults.
+ const list = v => v == null || Array.isArray(v);
+ if (!list(body.state.workouts) || !list(body.state.routines)) return json(res, 400, { error: 'invalid state' });
delete body.state.active; // in-progress workouts stay device-local
atomicWrite(stateFile(user.id), JSON.stringify(body.state));
json(res, 200, { ok: true, ts: body.state._ts || null });
@@ -1012,7 +1062,11 @@ http.createServer(async (req, res) => {
});
return res.end();
}
- const url = new URL(req.url, 'http://x');
+ // A target that does not parse (`//`, `//api%2Fhealth`) is a bad request, not a server error —
+ // and the try below only covers the route handler, so it is refused here.
+ let url;
+ try { url = new URL(req.url, 'http://x'); }
+ catch { return json(res, 400, { error: 'bad request' }); }
const key = req.method + ' ' + url.pathname;
const handler = routes[key];
if (!handler) return json(res, 404, { error: 'not found' });
diff --git a/api/test/server-pairing.test.js b/api/test/server-pairing.test.js
new file mode 100644
index 000000000..0507ee044
--- /dev/null
+++ b/api/test/server-pairing.test.js
@@ -0,0 +1,85 @@
+/* "Sign out everywhere" (POST /api/logout/all) has to take the account's outstanding pairing
+ codes with it: a code is a session-in-waiting, and one minted before the sign-out could
+ otherwise be redeemed for a fresh token carrying the new session version. 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, sv = 0) {
+ const payload = `${uid}:${Date.now() + 86400000}:${sv}`;
+ return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');
+}
+const cookie = (uid, sv) => ({ Cookie: `gymsid=${mintSession(uid, sv)}` });
+
+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_test_1', name: 'One', created: new Date().toISOString() },
+ { id: 'u_test_2', name: 'Two', created: new Date().toISOString() }
+];
+
+async function startServer(t) {
+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-pair-'));
+ 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' }
+ });
+ const h = { api: `http://127.0.0.1:${port}`, 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}`);
+ return h;
+}
+
+test('logout/all invalidates the account\'s outstanding pairing codes and nobody else\'s', async t => {
+ const h = await startServer(t);
+ const post = (p, headers, body) => fetch(`${h.api}${p}`, { method: 'POST', headers, body: body && JSON.stringify(body) });
+ const create = async (uid, sv) => {
+ const r = await post('/api/pair/create', cookie(uid, sv));
+ assert.equal(r.status, 200);
+ return (await r.json()).code;
+ };
+ const redeem = code => post('/api/pair/redeem', {}, { code });
+
+ // control: mint and redeem with nothing in between
+ assert.equal((await redeem(await create('u_test_1', 0))).status, 200);
+
+ // a code minted before "sign out everywhere" is refused after it
+ const stale = await create('u_test_1', 0);
+ const other = await create('u_test_2', 0);
+ assert.equal((await post('/api/logout/all', cookie('u_test_1', 0))).status, 200);
+ const r = await redeem(stale);
+ assert.equal(r.status, 400);
+ assert.deepEqual(await r.json(), { error: 'invalid or expired code' });
+
+ // the other account's code is untouched
+ assert.equal((await redeem(other)).status, 200);
+
+ // and a code minted after the sign-out (session version 1 now) redeems for a token of that version
+ const fresh = await redeem(await create('u_test_1', 1));
+ assert.equal(fresh.status, 200);
+ const { token } = await fresh.json();
+ assert.match(token.split('.')[0], /^u_test_1:\d+:1$/);
+});
diff --git a/api/test/server-push-filter.test.js b/api/test/server-push-filter.test.js
new file mode 100644
index 000000000..c212f2172
--- /dev/null
+++ b/api/test/server-push-filter.test.js
@@ -0,0 +1,104 @@
+/* The push endpoint private-address rule, judged on every textual form of an IP literal. new URL
+ canonicalizes `[::ffff:127.0.0.1]` to `[::ffff:7f00:1]`, and Node never consults an Agent's
+ custom lookup for a literal host, so a literal that slips the subscribe-time check is one the
+ send path will actually connect to. Both ends are covered here: subscribe refuses, and a
+ private literal already sitting in db.json is refused at send time without a socket being
+ opened. 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 cookie = { Cookie: `gymsid=${mintSession('u_test_1')}` };
+// Real-shaped keys (65-byte P-256 point, 16-byte auth secret): web-push validates them before it
+// opens a socket, and the send-time test below is only meaningful if the socket would have opened.
+const keys = {
+ p256dh: crypto.generateKeyPairSync('ec', { namedCurve: 'prime256v1' }).publicKey.export({ type: 'spki', format: 'der' }).subarray(-65).toString('base64url'),
+ auth: crypto.randomBytes(16).toString('base64url')
+};
+
+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, subs = []) {
+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-push-'));
+ fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
+ fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({
+ users: [{ id: 'u_test_1', 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' }
+ });
+ const h = { api: `http://127.0.0.1:${port}`, dataDir, 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}`);
+ return h;
+}
+
+test('subscribe refuses every spelling of a private IP literal and accepts public ones', async t => {
+ const h = await startServer(t);
+ const subscribe = endpoint => fetch(`${h.api}/api/push/subscribe`, {
+ method: 'POST', headers: cookie, body: JSON.stringify({ subscription: { endpoint, keys } })
+ });
+ const privateForms = [
+ 'https://[::ffff:127.0.0.1]/x', // mapped loopback, dotted
+ 'https://[::ffff:7f00:1]/x', // mapped loopback, hex (what new URL makes of the above)
+ 'https://[0:0:0:0:0:ffff:7f00:1]/x', // mapped loopback, fully expanded
+ 'https://[::ffff:169.254.169.254]/x', // mapped link-local (cloud metadata)
+ 'https://[::FFFF:C0A8:0101]/x', // mapped 192.168.1.1, upper-case, zero-padded
+ 'https://[::ffff:10.0.0.1]/x', // mapped private
+ 'https://[0:0:0:0:0:0:0:1]/x', // loopback, expanded
+ 'https://[::1]/x', // loopback, compressed
+ 'https://[fe80::1]/x', // link-local
+ 'https://[fd00::1]/x', // unique local
+ 'https://127.0.0.1/x' // plain IPv4 (the case that always worked)
+ ];
+ for (const ep of privateForms) {
+ const r = await subscribe(ep);
+ assert.equal(r.status, 400, ep);
+ assert.deepEqual(await r.json(), { error: 'endpoint must not point at a private address' }, ep);
+ }
+ for (const ep of ['https://[::ffff:8.8.8.8]/x', 'https://[::ffff:808:808]/x', 'https://[2606:4700::1111]/x', 'https://8.8.8.8/x', 'https://push.example/x']) {
+ assert.equal((await subscribe(ep)).status, 200, ep);
+ }
+});
+
+test('a private literal already stored as an endpoint is refused at send time, never connected to, and dropped', async t => {
+ // stands in for whatever else lives on the api container's network
+ const hits = [];
+ const target = net.createServer(s => { hits.push(s.remoteAddress); s.destroy(); });
+ await new Promise(r => target.listen(0, '127.0.0.1', r));
+ t.after(() => target.close());
+ const endpoint = `https://[::ffff:7f00:1]:${target.address().port}/x`;
+ const h = await startServer(t, [{ userId: 'u_test_1', endpoint, keys, created: new Date().toISOString() }]);
+
+ const r = await fetch(`${h.api}/api/push/test`, { method: 'POST', headers: cookie });
+ assert.equal(r.status, 200);
+ assert.deepEqual(hits, [], 'no socket reached the private address');
+ assert.match(h.log, /push endpoint refused u_test_1/);
+ const db = JSON.parse(fs.readFileSync(path.join(h.dataDir, 'db.json'), 'utf8'));
+ assert.equal(db.subs.length, 0, 'the unusable subscription is gone from db.json');
+});
diff --git a/api/test/server-reminder.test.js b/api/test/server-reminder.test.js
new file mode 100644
index 000000000..162dc660a
--- /dev/null
+++ b/api/test/server-reminder.test.js
@@ -0,0 +1,115 @@
+/* Two halves of the same rule — a state whose `workouts` or `routines` is not an array must not
+ be able to take the api down:
+ - PUT /api/data refuses the shape at the door (every real client sends arrays or leaves the
+ field out, so nothing legitimate changes);
+ - a file that got onto disk anyway is logged and skipped by the reminder tick, which runs
+ outside the per-route try/catch, and the users after it still get their reminders.
+ Real server.js in a child. The tick runs every 10 s, so the second
+ test waits on the log rather than on a fixed sleep. */
+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 cookie = { Cookie: `gymsid=${mintSession('u_test_1')}` };
+
+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_test_1', name: 'One', created: new Date().toISOString() },
+ { id: 'u_test_2', name: 'Two', created: new Date().toISOString() }
+];
+
+async function startServer(t, subs = []) {
+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-reminder-'));
+ 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' }
+ });
+ const h = { api: `http://127.0.0.1:${port}`, dataDir, child, 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}`);
+ return h;
+}
+
+test('PUT /api/data refuses a state whose workouts or routines is not an array', async t => {
+ const h = await startServer(t);
+ const put = state => fetch(`${h.api}/api/data`, { method: 'PUT', headers: cookie, body: JSON.stringify({ state }) });
+ const file = path.join(h.dataDir, 'state-u_test_1.json');
+
+ for (const bad of [{ workouts: {} }, { workouts: 'abc' }, { workouts: 7 }, { workouts: true }, { routines: {} }, { routines: 'r1' }, { workouts: [], routines: {} }]) {
+ const r = await put({ _ts: 1, ...bad });
+ assert.equal(r.status, 400, JSON.stringify(bad));
+ assert.deepEqual(await r.json(), { error: 'invalid state' }, JSON.stringify(bad));
+ }
+ assert.equal(fs.existsSync(file), false, 'nothing landed on disk');
+
+ // the shapes real clients send still go through: arrays, the field left out, or null
+ assert.equal((await put({ _ts: 2, workouts: [], routines: [] })).status, 200);
+ assert.equal((await put({ _ts: 3 })).status, 200);
+ assert.equal((await put({ _ts: 4, workouts: null, routines: null })).status, 200);
+ assert.equal(JSON.parse(fs.readFileSync(file, 'utf8'))._ts, 4);
+});
+
+test('a non-array workouts on disk is logged and skipped by the reminder tick; the next user still fires', async t => {
+ const keys = { p256dh: 'p', auth: 'a' };
+ // localhost resolves to a loopback address, which PUSH_AGENT refuses — the send that follows the
+ // reminder fails locally and quietly, with no socket leaving this machine
+ const subs = USERS.map(u => ({ userId: u.id, endpoint: 'https://localhost/x', keys, created: new Date().toISOString() }));
+ const h = await startServer(t, subs);
+
+ const routines = [{ id: 'r1', name: 'Full body', emoji: '💪', ex: [] }];
+ const week = { 0: 'r1', 1: 'r1', 2: 'r1', 3: 'r1', 4: 'r1', 5: 'r1', 6: 'r1' };
+ // hh:mm exactly the way server.js userNow() derives it, so the reminder is "now" in UTC
+ const nowHHMM = () => {
+ const parts = new Intl.DateTimeFormat('en-CA', { timeZone: 'UTC', hour12: false, hour: '2-digit', minute: '2-digit' }).formatToParts(new Date());
+ const g = type => parts.find(p => p.type === type)?.value;
+ return `${g('hour')}:${g('minute')}`;
+ };
+ // The tick re-reads each state file every pass and only acts when the reminder is for the
+ // current minute, so both files are rewritten with "now" until the log shows the tick has done
+ // its work — a minute rolling over mid-wait cannot make it miss.
+ const seed = () => {
+ const reminder = { on: true, time: nowHHMM(), tz: 'UTC' };
+ fs.writeFileSync(path.join(h.dataDir, 'state-u_test_1.json'), JSON.stringify({ reminder, routines, week, workouts: {} }));
+ fs.writeFileSync(path.join(h.dataDir, 'state-u_test_2.json'), JSON.stringify({ reminder, routines, week, workouts: [] }));
+ };
+ const done = () => /reminder tick u_test_1/.test(h.log) && /reminder firing u_test_2 r1/.test(h.log);
+ const deadline = Date.now() + 30000;
+ while (Date.now() < deadline && !done() && h.child.exitCode === null) {
+ seed();
+ await new Promise(r => setTimeout(r, 500));
+ }
+
+ assert.equal(h.child.exitCode, null, `server exited:\n${h.log}`);
+ assert.match(h.log, /reminder tick u_test_1 TypeError/, h.log);
+ assert.match(h.log, /reminder firing u_test_2 r1/, h.log);
+ assert.equal((await fetch(`${h.api}/api/health`)).status, 200);
+ const db = JSON.parse(fs.readFileSync(path.join(h.dataDir, 'db.json'), 'utf8'));
+ assert.ok(db.users.find(u => u.id === 'u_test_2').lastReminder, 'the good user\'s reminder was recorded');
+});
diff --git a/api/test/server-url.test.js b/api/test/server-url.test.js
new file mode 100644
index 000000000..514bfc40a
--- /dev/null
+++ b/api/test/server-url.test.js
@@ -0,0 +1,64 @@
+/* A request target that does not parse as a URL (`//`, `//api%2Fhealth`) must get a 400 from the
+ listener and leave the process running — the parse sits before the per-route try/catch, so a
+ throw there is an unhandled rejection and a dead api container. Raw sockets, because
+ fetch() refuses to send such targets in the first place. 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 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-url-'));
+ fs.writeFileSync(path.join(dataDir, 'secret'), crypto.randomBytes(32).toString('hex'), { mode: 0o600 });
+ fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ 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' }
+ });
+ const h = { api: `http://127.0.0.1:${port}`, port, child, 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}`);
+ return h;
+}
+
+// One request over a bare TCP socket, target written verbatim; resolves with the raw response.
+function rawGet(port, target) {
+ return new Promise((resolve, reject) => {
+ let out = '';
+ const s = net.connect(port, '127.0.0.1', () => s.write(`GET ${target} HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n`));
+ s.on('data', d => out += d);
+ s.on('end', () => resolve(out));
+ s.on('error', reject);
+ });
+}
+
+test('an unparseable request target is a 400, and the server keeps answering afterwards', async t => {
+ const h = await startServer(t);
+ for (const target of ['//', '//api%2Fhealth', '//api%2F/health']) {
+ const res = await rawGet(h.port, target);
+ assert.match(res, /^HTTP\/1\.1 400 /, `${target} ->\n${res || '(no response)'}\n${h.log}`);
+ }
+ // a normal target still parses and still routes
+ assert.match(await rawGet(h.port, '/api/health'), /^HTTP\/1\.1 200 /);
+ assert.equal((await fetch(`${h.api}/api/health`)).status, 200);
+ assert.equal(h.child.exitCode, null, `server exited:\n${h.log}`);
+});