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: an unreadable db.json or state file no longer starts the instance or the profile over

Duarte Santosd5d99c6e0363
diff --git a/api/server.js b/api/server.js
index 6d7535dae..3356f5d37 100644
--- a/api/server.js
+++ b/api/server.js
@@ -115,15 +115,45 @@ if (!fs.existsSync(secretFile)) fs.writeFileSync(secretFile, crypto.randomBytes(
const SECRET = fs.readFileSync(secretFile, 'utf8').trim();
const dbFile = path.join(DATA, 'db.json');
-let db = { users: [], creds: [], subs: [], invites: [] };
-try { db = JSON.parse(fs.readFileSync(dbFile, 'utf8')); } catch {}
+// Every account, passkey and invite. Only a missing file starts empty: an unreadable one (a write
+// cut short by a power loss, a damaged restore) used to boot with no users at all, and the first
+// save then replaced it — every profile locked out, every training history orphaned, and with
+// FIRST_USER_ADMIN the first visitor made admin. Now the damaged file is kept aside and the copy
+// saveDb keeps of the previous version (db.json.bak) is used; with neither readable the server
+// refuses to start, saying why, rather than start as a new instance.
+function loadDb() {
+ let raw;
+ try { raw = fs.readFileSync(dbFile, 'utf8'); }
+ catch (e) { if (e.code === 'ENOENT') return { users: [], creds: [], subs: [], invites: [] }; throw e; }
+ const parse = text => { const v = JSON.parse(text); if (!v || typeof v !== 'object' || Array.isArray(v)) throw new Error('not an object'); return v; };
+ try { return parse(raw); } catch (err) {
+ const aside = `${dbFile}.unreadable-${Date.now()}`;
+ try { fs.copyFileSync(dbFile, aside); } catch { /* the original stays where it is anyway */ }
+ console.error(`db.json cannot be read (${err.message}); kept a copy as ${path.basename(aside)}`);
+ try {
+ const bak = parse(fs.readFileSync(dbFile + '.bak', 'utf8'));
+ console.error('db.json: using db.json.bak, the version before the last save');
+ return bak;
+ } catch {
+ console.error('db.json: no readable db.json.bak either. Refusing to start: restore db.json from a backup.');
+ process.exit(1);
+ }
+ }
+}
+let db = loadDb();
+db.users = db.users || [];
+db.creds = db.creds || [];
db.subs = db.subs || [];
db.invites = db.invites || [];
db.deviceLinks = db.deviceLinks || []; // unused one-time device links, hashed (device-link.js)
const isAdmin = user => !!user && (user.admin === true || ADMIN_UIDS.includes(user.id));
// 0600: db.json holds passkey credential material. It used to be covered by a blanket 0700 on
// the whole directory; now that the directory stays traversable, the file carries its own mode.
-function saveDb() { atomicWrite(dbFile, JSON.stringify(db, null, 2), 0o600); }
+// The version being replaced is kept as db.json.bak first: loadDb falls back to it.
+function saveDb() {
+ try { fs.copyFileSync(dbFile, dbFile + '.bak'); fs.chmodSync(dbFile + '.bak', 0o600); } catch { /* none yet */ }
+ atomicWrite(dbFile, JSON.stringify(db, null, 2), 0o600);
+}
// Flushed before and after the rename (durable.js): a host reset must not bring back the file
// the client was told had been replaced.
function atomicWrite(file, content, mode) { durableWrite(file, content, mode); }
@@ -146,6 +176,16 @@ const lastSyncOf = (u, S) => Math.max(S?._ts || 0, u?.lastPull || 0) || null;
function readState(uid) {
try { return JSON.parse(fs.readFileSync(stateFile(uid), 'utf8')); } catch { return null; }
}
+// GET and PUT /api/data tell a profile with no state yet from one whose file cannot be read: the
+// second answers 503 instead of an empty profile, which a device would adopt, or a write would
+// replace, losing what a restore could still bring back.
+const UNREADABLE = Symbol('unreadable');
+function readStateStrict(uid) {
+ let raw;
+ try { raw = fs.readFileSync(stateFile(uid), 'utf8'); }
+ catch (e) { return e.code === 'ENOENT' ? null : UNREADABLE; }
+ try { return JSON.parse(raw); } catch { return UNREADABLE; }
+}
// 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
@@ -2044,7 +2084,8 @@ const routes = {
'GET /api/data': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
- const state = readState(user.id);
+ const state = readStateStrict(user.id);
+ if (state === UNREADABLE) { console.error('state file unreadable for', user.id); return json(res, 503, { error: 'state unreadable' }); }
notePull(user);
json(res, 200, { state, rev: state?._rev || 0 });
},
@@ -2096,7 +2137,8 @@ const routes = {
// before revisions, or a deliberate replace such as a backup import) overwrites, as before.
// readState and atomicWrite are synchronous with nothing awaited between them, so the
// compare-and-write is atomic for this process.
- const cur = readState(user.id);
+ const cur = readStateStrict(user.id);
+ if (cur === UNREADABLE) { console.error('state file unreadable for', user.id); return json(res, 503, { error: 'state unreadable' }); }
const curRev = cur?._rev || 0;
// `_rev` is a counter, so after the data directory went back in time (a restored backup, a
// write lost to a power cut) the same number names a different document. Every write also gets
diff --git a/api/test/server-db-unreadable.test.js b/api/test/server-db-unreadable.test.js
new file mode 100644
index 000000000..a2efdcb53
--- /dev/null
+++ b/api/test/server-db-unreadable.test.js
@@ -0,0 +1,73 @@
+/* An unreadable db.json (a write cut short by a power loss, a damaged restore) booted with zero
+ users and the first save replaced it: every profile locked out, every history orphaned, the
+ first visitor admin under FIRST_USER_ADMIN. And an unreadable state file read as "no state yet",
+ which a device adopted and a write replaced. (QA 2026-10-06.) Real server.js in a child. */
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import crypto from 'node:crypto';
+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');
+const cookie = uid => { const p = `${uid}:${Date.now() + 86400000}:0`; return `gymsid=${p}.${crypto.createHmac('sha256', SECRET).update(p).digest('base64url')}`; };
+const USERS = [{ id: 'u_a', name: 'Anna', created: new Date().toISOString() }, { id: 'u_b', name: 'Bruno', created: new Date().toISOString() }];
+
+function dataDir(t) {
+ const d = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-dbx-'));
+ t.after(() => fs.rmSync(d, { recursive: true, force: true }));
+ fs.writeFileSync(path.join(d, 'secret'), SECRET, { mode: 0o600 });
+ fs.writeFileSync(path.join(d, 'db.json'), JSON.stringify({ users: USERS, creds: [], subs: [], invites: [] }));
+ return d;
+}
+function start(t, d) {
+ const child = spawn(process.execPath, ['server.js'], { cwd: API, stdio: ['ignore', 'pipe', 'pipe'],
+ env: { ...process.env, PORT: '0', DATA_DIR: d, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' } });
+ const h = { log: '', child };
+ child.stdout.on('data', x => h.log += x); child.stderr.on('data', x => h.log += x);
+ h.exit = new Promise(r => child.on('exit', code => r(code)));
+ t.after(() => child.kill('SIGKILL'));
+ return h;
+}
+
+test('db.json cut short with no previous version: the server refuses to start and keeps the file', async t => {
+ const d = dataDir(t);
+ const full = fs.readFileSync(path.join(d, 'db.json'), 'utf8');
+ fs.writeFileSync(path.join(d, 'db.json'), full.slice(0, full.length >> 1));
+ const h = start(t, d);
+ assert.equal(await h.exit, 1);
+ assert.match(h.log, /Refusing to start/);
+ assert.equal(fs.readFileSync(path.join(d, 'db.json'), 'utf8'), full.slice(0, full.length >> 1));
+ assert.ok(fs.readdirSync(d).some(f => f.startsWith('db.json.unreadable-')));
+});
+
+test('db.json cut short after a save: the version before it is used, and every account is still there', async t => {
+ const d = dataDir(t);
+ let h = start(t, d);
+ const base = `http://127.0.0.1:${await boundPort(h.child, () => h.log)}`;
+ await fetch(`${base}/api/data`, { headers: { Cookie: cookie('u_a') } }); // a pull note saves db.json
+ assert.ok(fs.existsSync(path.join(d, 'db.json.bak')));
+ h.child.kill('SIGKILL'); await h.exit;
+ fs.writeFileSync(path.join(d, 'db.json'), '');
+ h = start(t, d);
+ const base2 = `http://127.0.0.1:${await boundPort(h.child, () => h.log)}`;
+ const me = await (await fetch(`${base2}/api/me`, { headers: { Cookie: cookie('u_b') } })).json();
+ assert.equal(me.user?.id, 'u_b');
+ assert.match(h.log, /using db\.json\.bak/);
+});
+
+test('an unreadable state file is a 503 on GET and PUT, and is not replaced', async t => {
+ const d = dataDir(t);
+ fs.writeFileSync(path.join(d, 'state-u_a.json'), '{"_rev":7,"workouts":[{"id":"w1"');
+ const h = start(t, d);
+ const base = `http://127.0.0.1:${await boundPort(h.child, () => h.log)}`;
+ const headers = { Cookie: cookie('u_a'), 'Content-Type': 'application/json' };
+ assert.equal((await fetch(`${base}/api/data`, { headers })).status, 503);
+ const put = await fetch(`${base}/api/data`, { method: 'PUT', headers, body: JSON.stringify({ state: { workouts: [], routines: [] } }) });
+ assert.equal(put.status, 503);
+ assert.equal(fs.readFileSync(path.join(d, 'state-u_a.json'), 'utf8'), '{"_rev":7,"workouts":[{"id":"w1"');
+});
diff --git a/api/test/server-state-read-cost.test.js b/api/test/server-state-read-cost.test.js
index 9701fa227..39d94e70f 100644
--- a/api/test/server-state-read-cost.test.js
+++ b/api/test/server-state-read-cost.test.js
@@ -175,6 +175,7 @@ test('the three hot-path state reads all go through readStateCached', () => {
}
// GET /api/data hands out the document itself and PUT compares against it — both want the real
// thing, uncached.
- assert.match(handler('GET /api/data'), /readState\(user\.id\)/);
- assert.match(handler('PUT /api/data'), /readState\(user\.id\)/);
+ // (readStateStrict: a file that cannot be read is a 503, not an empty profile.)
+ assert.match(handler('GET /api/data'), /readStateStrict\(user\.id\)/);
+ assert.match(handler('PUT /api/data'), /readStateStrict\(user\.id\)/);
});