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
API: every request but a signed-in upload still has five minutes to send its body
Duarte Santos7dbfa4e2d317
diff --git a/api/server.js b/api/server.jsindex 1f846ec5d..34830cf49 100644--- a/api/server.js+++ b/api/server.js@@ -1492,6 +1492,7 @@ const mediaRoutes = {const user = readSession(req);if (!user) { MEDIA.discard(req); return json(res, 401, { error: 'not signed in' }); }try { mediaThrottle(req, user, MEDIA_BURST); } catch (e) { MEDIA.discard(req); throw e; }+ req.allowSlowBody?.(); // a signed-in upload within its budget may take the half hourconst r = await MEDIA.receive(user.id, req.mediaHash, req);json(res, r.status, r.body);},@@ -2149,7 +2150,29 @@ coachJobs.setProposalHook((uid, pending) => {startCadence({ users: () => db.users, userNow });startWarmup();+// node's requestTimeout is one number for every route, and it is half an hour (below) for the+// sake of one: a video uploaded over a slow uplink. Every other request keeps node's old five+// minutes to finish sending its body — readBody has no timer of its own, and a trickled body on+// any route, the unauthenticated CSRF-exempt POSTs included, would otherwise hold its socket six+// times as long. The upload route lifts it (req.allowSlowBody) only once the session and the+// hourly budget have let the upload in; from there media.js's own idle timer takes over. The+// tests shorten it, as they do REMINDER_TICK_MS.+const BODY_TIMEOUT_MS = Math.max(50, +(process.env.BODY_TIMEOUT_MS || 300000) || 300000);+function bodyDeadline(req) {+ if (req.complete) return;+ // The socket itself, not req: a route that answered without reading the body has finished its+ // response, and node has already closed req (a no-op to destroy again) while the body trickles+ // on. Only 'end' clears it — 'close' also fires at that early answer.+ const socket = req.socket;+ const timer = setTimeout(() => { if (!req.complete) socket.destroy(); }, BODY_TIMEOUT_MS);+ timer.unref();+ const clear = () => clearTimeout(timer);+ req.once('end', clear);+ req.allowSlowBody = clear;+}+const server = http.createServer(async (req, res) => {+ bodyDeadline(req);// Same-origin (the deployed nginx-proxied web app) never triggers CORS, so this only matters// for the paired mobile app calling in from its own WebView origin. It carries no cookie// (auth is the Authorization header instead), so Allow-Credentials is deliberately never set —@@ -2214,7 +2237,8 @@ const server = http.createServer(async (req, res) => {});// Node's default of 300 s for a whole request would answer 408 to a 40 MB video on a ~1 Mbit/s// uplink. Half an hour covers that; a stalled upload is cut much sooner by its own 60 s idle-// timer in media.js, and a client that never finishes its headers still meets headersTimeout.+// timer in media.js, a client that never finishes its headers still meets headersTimeout, and+// every other route's body still has to arrive within five minutes (bodyDeadline above).server.requestTimeout = 30 * 60000;server.headersTimeout = 60000;// The port is read back off the listener rather than echoed from PORT, so the line states thediff --git a/api/test/server-media.test.js b/api/test/server-media.test.jsindex f5f58733f..061a8180a 100644--- a/api/test/server-media.test.js+++ b/api/test/server-media.test.js@@ -8,6 +8,7 @@ import assert from 'node:assert/strict';import crypto from 'node:crypto';import fs from 'node:fs';import http from 'node:http';+import net from 'node:net';import os from 'node:os';import path from 'node:path';import { spawn } from 'node:child_process';@@ -436,6 +437,33 @@ test('boot removes the temp files of uploads the previous process was receiving'assert.deepEqual(fs.readdirSync(tmp), []);});+test('a trickled body is cut after the body deadline on every route but a signed-in upload', async t => {+ const h = await start(t, { BODY_TIMEOUT_MS: '400' });+ // Headers and a tenth of the promised body, then nothing: resolves with how the socket ended.+ const trickle = (line, headers) => new Promise(resolve => {+ const s = net.connect(h.port, '127.0.0.1', () => {+ s.write(`${line} HTTP/1.1\r\nHost: 127.0.0.1\r\n${headers}Content-Length: 100\r\n\r\n` + '{"hashes":');+ });+ const timer = setTimeout(() => { s.destroy(); resolve('still open'); }, 3000);+ s.on('error', () => {});+ s.resume(); // read the early answer, or a paused socket never sees the server's FIN+ s.on('close', () => { clearTimeout(timer); resolve('closed'); });+ });+ const c = `Cookie: gymsid=${mint(U1)}\r\nOrigin: ${ORIGIN}\r\nContent-Type: application/json\r\n`;+ assert.equal(await trickle('POST /api/media/missing', c), 'closed', 'a JSON route reading its body');+ assert.equal(await trickle('POST /api/logout', 'Content-Type: application/json\r\n'), 'closed', 'a route reachable without a session');+ assert.equal(await trickle('PUT /api/media/' + 'd'.repeat(64), `Origin: ${ORIGIN}\r\nContent-Type: image/jpeg\r\n`), 'closed', 'an upload without a session');++ // Signed in and within its budget, an upload may take longer than that.+ const bytes = M.jpeg(20000);+ const { req, response } = rawPut(h, M.sha(bytes), { length: bytes.length });+ req.write(bytes.subarray(0, 5000));+ await sleep(900);+ req.end(bytes.subarray(5000));+ const r = await response;+ assert.equal(r.status, 201, JSON.stringify(r.body));+});+test('server.js gives a slow upload half an hour, not node\'s default five minutes', () => {const src = fs.readFileSync(path.join(API, 'server.js'), 'utf8');const m = /^server\.requestTimeout\s*=\s*([\d_\s*]+);/m.exec(src);