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 falls back to the last save, so a profile just created survives

Duarte Santosdffbf49fa14e
diff --git a/api/server.js b/api/server.js
index 3356f5d37..b7abc1663 100644
--- a/api/server.js
+++ b/api/server.js
@@ -119,7 +119,7 @@ const dbFile = path.join(DATA, 'db.json');
// 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
+// saveDb keeps of each version it writes (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;
@@ -132,7 +132,7 @@ function loadDb() {
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');
+ console.error('db.json: using db.json.bak, the copy of 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.');
@@ -149,10 +149,15 @@ db.deviceLinks = db.deviceLinks || []; // unused one-time device links, hashed
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.
-// The version being replaced is kept as db.json.bak first: loadDb falls back to it.
+// Once the new version is on disk, a second copy of it goes to db.json.bak, the same durable
+// way: loadDb falls back to it. A copy of the version being replaced, as it used to be, lost
+// whatever the last save wrote (a profile just created) when db.json was later found unreadable.
+// A write cut short leaves the previous db.json.bak whole (temporary file and rename).
function saveDb() {
- try { fs.copyFileSync(dbFile, dbFile + '.bak'); fs.chmodSync(dbFile + '.bak', 0o600); } catch { /* none yet */ }
- atomicWrite(dbFile, JSON.stringify(db, null, 2), 0o600);
+ const text = JSON.stringify(db, null, 2);
+ atomicWrite(dbFile, text, 0o600);
+ try { atomicWrite(dbFile + '.bak', text, 0o600); }
+ catch (e) { console.error('db.json.bak could not be written', e.message); }
}
// Flushed before and after the rename (durable.js): a host reset must not bring back the file
// the client was told had been replaced.
diff --git a/api/test/server-db-unreadable.test.js b/api/test/server-db-unreadable.test.js
index a2efdcb53..a9c9e56d1 100644
--- a/api/test/server-db-unreadable.test.js
+++ b/api/test/server-db-unreadable.test.js
@@ -24,9 +24,9 @@ function dataDir(t) {
fs.writeFileSync(path.join(d, 'db.json'), JSON.stringify({ users: USERS, creds: [], subs: [], invites: [] }));
return d;
}
-function start(t, d) {
+function start(t, d, env = {}) {
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' } });
+ env: { ...process.env, PORT: '0', DATA_DIR: d, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost', ...env } });
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)));
@@ -45,7 +45,7 @@ test('db.json cut short with no previous version: the server refuses to start an
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 => {
+test('db.json cut short after a save: the copy kept with 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)}`;
@@ -60,6 +60,29 @@ test('db.json cut short after a save: the version before it is used, and every a
assert.match(h.log, /using db\.json\.bak/);
});
+// QA retest 2026-10-06: db.json.bak was the version before the last save, so falling back to it
+// lost whatever that save wrote, such as the profile just created.
+test('db.json unreadable after a sign-up: the copy kept is the last save, so the new profile is still there', async t => {
+ const d = dataDir(t);
+ let h = start(t, d, { PASSWORD_LOGIN: '1' });
+ const base = `http://127.0.0.1:${await boundPort(h.child, () => h.log)}`;
+ const r = await fetch(`${base}/api/register/password`, { method: 'POST', headers: { 'Content-Type': 'application/json', Origin: 'http://localhost:8080' },
+ body: JSON.stringify({ name: 'Carla', password: 'correct horse battery 1' }) });
+ assert.equal(r.status, 200, await r.clone().text());
+ const carla = (await r.json()).user?.id;
+ assert.ok(carla);
+ h.child.kill('SIGKILL'); await h.exit;
+ assert.equal(fs.readFileSync(path.join(d, 'db.json.bak'), 'utf8'), fs.readFileSync(path.join(d, 'db.json'), 'utf8'));
+ assert.equal((fs.statSync(path.join(d, 'db.json.bak')).mode & 0o777), 0o600);
+ fs.writeFileSync(path.join(d, 'db.json'), '{"users":[{"id"');
+ h = start(t, d, { PASSWORD_LOGIN: '1' });
+ const base2 = `http://127.0.0.1:${await boundPort(h.child, () => h.log)}`;
+ for (const uid of ['u_a', 'u_b', carla]) {
+ const me = await (await fetch(`${base2}/api/me`, { headers: { Cookie: cookie(uid) } })).json();
+ assert.equal(me.user?.id, uid);
+ }
+});
+
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"');