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: a client that hangs up mid-body is not a server error

Boris 'B' Kurktchiev565ea91c51f1
diff --git a/api/server.js b/api/server.js
index f3018f7b7..53542a28d 100644
--- a/api/server.js
+++ b/api/server.js
@@ -571,7 +571,10 @@ function readBody(req) {
if (!body || typeof body !== 'object' || Array.isArray(body)) return reject(new HttpError(400, 'invalid json'));
resolve(body);
});
- req.on('error', reject);
+ // A browser hanging up mid-body — which is what pagehide does to an in-flight sync — is not
+ // the caller getting a request wrong, it is nobody being left to answer. Marked so the
+ // catch-all at the bottom says one line instead of a stack trace and a 500 into a dead socket.
+ req.on('error', e => reject(Object.assign(e, { clientGone: true })));
});
}
// A caller-supplied field that is meant to be text. String() alone is not safe on a parsed body:
@@ -1254,6 +1257,7 @@ http.createServer(async (req, res) => {
}
try { await handler(req, res); }
catch (e) {
+ if (e?.clientGone) { console.warn(key, 'client went away mid-body:', e.message); return; }
if (e instanceof HttpError) {
if (!res.headersSent) json(res, e.status, { error: e.message });
return;
diff --git a/api/test/server-body-errors.test.js b/api/test/server-body-errors.test.js
new file mode 100644
index 000000000..414c69c97
--- /dev/null
+++ b/api/test/server-body-errors.test.js
@@ -0,0 +1,92 @@
+/* A browser hanging up mid-body — which is what pagehide does to an in-flight sync — is not a
+ server error, and it used to print a four-line stack per request. It is one warning line now.
+
+ The other two ways a body fails to arrive, unparseable JSON and a body over the cap, are
+ covered by server-bad-input.test.js. Raw sockets here, because an abort has to be a real
+ hang-up: a client that stops writing is not the same as one that goes away. 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');
+
+function mintSession(uid) {
+ const payload = `${uid}:${Date.now() + 86400000}:0`;
+ return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('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) {
+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-bodyerr-'));
+ fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
+ fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({
+ users: [{ id: 'u_body_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}`, port, dataDir, log: '', exited: null };
+ child.stdout.on('data', d => h.log += d);
+ child.stderr.on('data', d => h.log += d);
+ child.on('exit', (code, signal) => { h.exited = { code, signal }; });
+ 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}`);
+ h.cookie = `gymsid=${mintSession('u_body_1')}`;
+ return h;
+}
+
+/* One request over a socket we drive ourselves. `write` is called with the socket once the
+ headers are out, so a test can trickle, flood or hang up as it likes; the promise settles with
+ whatever came back (or 'reset' / 'closed' if nothing did). No Origin header: no browser sent
+ this, which is what csrfOk already allows. */
+function raw(h, requestLine, headers, write) {
+ return new Promise(resolve => {
+ let got = '';
+ const s = net.connect(h.port, '127.0.0.1', () => {
+ s.write(`${requestLine} HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: keep-alive\r\n${headers}\r\n`);
+ write(s, () => resolve(got || 'closed'));
+ });
+ s.on('data', d => {
+ got += d;
+ if (got.includes('\r\n\r\n')) { s.destroy(); resolve(got); }
+ });
+ s.on('error', e => resolve(got || 'reset:' + e.code));
+ s.on('close', () => resolve(got || 'closed'));
+ });
+}
+const stackLines = log => log.split('\n').filter(l => /^\s+at /.test(l));
+
+test('a client that hangs up mid-body costs one log line and no stack', async t => {
+ const h = await startServer(t);
+ const aborts = 5;
+ for (let i = 0; i < aborts; i++) {
+ await raw(h, 'PUT /api/data',
+ `Cookie: ${h.cookie}\r\nContent-Type: application/json\r\nContent-Length: 5000\r\n`,
+ (s, done) => { s.write('{"state":{'); setTimeout(() => { s.destroy(); done(); }, 60); });
+ }
+ await new Promise(r => setTimeout(r, 300));
+
+ assert.equal(h.exited, null);
+ assert.deepEqual(stackLines(h.log), [], `nothing to trace:\n${h.log}`);
+ assert.equal((h.log.match(/client went away mid-body/g) || []).length, aborts, `one line each:\n${h.log}`);
+ assert.equal(fs.existsSync(path.join(h.dataDir, 'state-u_body_1.json')), false, 'and nothing was written');
+ assert.equal((await fetch(`${h.api}/api/health`)).status, 200);
+});