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
Sync: a server that went back in time is merged into, never taken over what this device confirmed
Duarte Santos65d6c29cb348
diff --git a/api/openapi.yaml b/api/openapi.yamlindex 69fa4c4f6..80cd98fac 100644--- a/api/openapi.yaml+++ b/api/openapi.yaml@@ -1459,6 +1459,12 @@ paths:description: >-The revision this client last read or wrote. Omit or null for anunconditional overwrite.+ baseWid:+ type: string+ description: >-+ The write id (`_wid`) of the document this client last read or wrote. With+ `baseRev`, a write over a different document at the same revision (the data+ directory went back in time and the number was reached again) answers 409.stamped:type: booleandescription: >-@@ -1480,6 +1486,9 @@ paths:rev:type: integerdescription: The revision the write produced.+ wid:+ type: string+ description: The write id (`_wid`) of the stored document.'409':description: >-`baseRev` is not the current revision — another client wrote since this one@@ -1527,6 +1536,7 @@ paths:type: objectproperties:rev: { type: integer }+ wid: { type: string, description: 'The write id (`_wid`) of the stored document; absent before its first write.' }'401': { $ref: '#/components/responses/Unauthorized' }/api/media/{hash}:@@ -3212,6 +3222,15 @@ components:type: integerreadOnly: truedescription: Server-set revision, incremented on every accepted PUT. Ignored when sent by a client.+ _wid:+ type: string+ readOnly: true+ description: Server-set id of this write (16 hex characters), new on every accepted PUT.+ _wids:+ type: array+ readOnly: true+ items: { type: string }+ description: The write ids of the documents this one descends from, oldest first (up to 50).deleted:type: objectdescription: >-diff --git a/api/server.js b/api/server.jsindex 5864e8d8b..f8669a8bd 100644--- a/api/server.js+++ b/api/server.js@@ -128,6 +128,9 @@ function atomicWrite(file, content, mode) {fs.writeFileSync(tmp, content, mode ? { mode } : undefined);fs.renameSync(tmp, file);}+// How many earlier write ids a document keeps (`_wids`, see PUT /api/data): a device that last+// synced more writes ago than this merges on its next pull instead of taking the server's copy.+const WID_KEEP = 50;const stateFile = uid => path.join(DATA, 'state-' + uid.replace(/[^a-zA-Z0-9_-]/g, '') + '.json');// When a profile last fetched its document (GET /api/data). The document's own `_ts` moves only// on a push, so a device that only ever read — a second phone, a profile that trains elsewhere@@ -2055,7 +2058,8 @@ const routes = {'GET /api/data/rev': async (req, res) => {const user = readSession(req);if (!user) return json(res, 401, { error: 'not signed in' });- json(res, 200, { rev: readStateCached(user.id)?._rev || 0 });+ const doc = readStateCached(user.id);+ json(res, 200, { rev: doc?._rev || 0, ...(doc?._wid ? { wid: doc._wid } : {}) });},'PUT /api/data': async (req, res) => {@@ -2095,7 +2099,13 @@ const routes = {// compare-and-write is atomic for this process.const cur = readState(user.id);const curRev = cur?._rev || 0;- if (body.baseRev != null && body.baseRev !== curRev) {+ // `_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+ // a write id (`_wid`) and keeps its ancestors' (`_wids`): a client quoting the id it last saw+ // (`baseWid`) is refused when the stored document is not that one, whatever the numbers say,+ // and a client reading a document can tell whether it descends from its own (useStore pullState).+ if ((body.baseRev != null && body.baseRev !== curRev) ||+ (body.baseRev != null && typeof body.baseWid === 'string' && cur?._wid && body.baseWid !== cur._wid)) {return json(res, 409, { error: 'conflict', rev: curRev, state: cur });}delete body.state.active; // in-progress workouts stay device-local@@ -2117,6 +2127,9 @@ const routes = {try { stampPut(cur, body.state, { overRead: body.baseRev != null && body.baseRev === curRev, stamped: body.stamped === true }); }catch (e) { if (e instanceof RangeError) return json(res, 400, { error: 'invalid state' }); throw e; }body.state._rev = curRev + 1; // server-owned; whatever the client sent is ignored+ body.state._wids = [...(Array.isArray(cur?._wids) ? cur._wids : []), ...(cur?._wid ? [cur._wid] : [])]+ .filter(x => typeof x === 'string').slice(-WID_KEEP);+ body.state._wid = crypto.randomBytes(8).toString('hex');// JSON.parse takes any nesting, JSON.stringify recurses and runs out of stack on a document// nested some thousands deep. No client builds one; it is a bad request, not a server error.let text;@@ -2136,7 +2149,7 @@ const routes = {if (MEDIA_ON) {try { MEDIA.noteState(user.id, body.state); } catch (e) { console.error('media noteState', e); }}- json(res, 200, { ok: true, ts: body.state._ts || null, rev: body.state._rev });+ json(res, 200, { ok: true, ts: body.state._ts || null, rev: body.state._rev, wid: body.state._wid });},'GET /api/push/public-key': async (req, res) => json(res, 200, { key: vapid.publicKey }),diff --git a/api/test/server-data-rev-endpoint.test.js b/api/test/server-data-rev-endpoint.test.jsindex 2fd313cab..46b917d35 100644--- a/api/test/server-data-rev-endpoint.test.js+++ b/api/test/server-data-rev-endpoint.test.js@@ -43,5 +43,7 @@ test('GET /api/data/rev tracks PUT /api/data', async t => {assert.deepEqual(await (await fetch(`${base}/api/data/rev`, { headers: h })).json(), { rev: 0 });const put = await fetch(`${base}/api/data`, { method: 'PUT', headers: h, body: JSON.stringify({ state: { workouts: [], routines: [] }, baseRev: 0 }) });assert.equal(put.status, 200);- assert.deepEqual(await (await fetch(`${base}/api/data/rev`, { headers: h })).json(), { rev: 1 });+ const after = await (await fetch(`${base}/api/data/rev`, { headers: h })).json();+ assert.equal(after.rev, 1);+ assert.match(after.wid, /^[0-9a-f]{16}$/, 'the write id of the stored document');});diff --git a/api/test/server-data-wid.test.js b/api/test/server-data-wid.test.jsnew file mode 100644index 000000000..b2bf89b78--- /dev/null+++ b/api/test/server-data-wid.test.js@@ -0,0 +1,55 @@+/* Every write of /api/data gets a write id (`_wid`) and keeps its ancestors' (`_wids`): after the+ data directory went back in time (a restored backup, a write lost to a power cut) the same `_rev`+ names a different document, and a client quoting the id it last saw (`baseWid`) is refused+ instead of overwriting it. (QA 2026-10-06.) */+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';++// ---- the real server -------------------------------------------------------------------------+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');+}+test('PUT /api/data: write ids, their ancestry, and a stale write id refused at a reused revision', async t => {+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-wid-'));+ fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });+ fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ users: [{ id: 'u1', name: 'One', created: new Date().toISOString() }], creds: [], subs: [], invites: [] }));+ const child = spawn(process.execPath, ['server.js'], { cwd: API, stdio: ['ignore', 'pipe', 'pipe'],+ env: { ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' } });+ let log = '';+ child.stdout.on('data', d => log += d); child.stderr.on('data', d => log += d);+ t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });+ const base = `http://127.0.0.1:${await boundPort(child, () => log)}`;+ const headers = { Cookie: `gymsid=${mintSession('u1')}`, 'Content-Type': 'application/json' };+ const put = async body => { const r = await fetch(`${base}/api/data`, { method: 'PUT', headers, body: JSON.stringify(body) }); return { status: r.status, body: await r.json() }; };+ const file = path.join(dataDir, 'state-u1.json');++ const a = await put({ state: { _ts: 1, workouts: [], routines: [] }, baseRev: 0 });+ assert.equal(a.status, 200);+ const backup = fs.readFileSync(file, 'utf8'); // the nightly backup, at rev 1+ const b = await put({ state: { _ts: 2, workouts: [{ id: 'LegDay', d: '2026-10-01' }], routines: [] }, baseRev: 1, baseWid: a.body.wid });+ assert.equal(b.status, 200);+ assert.notEqual(b.body.wid, a.body.wid);+ assert.deepEqual(JSON.parse(fs.readFileSync(file, 'utf8'))._wids, [a.body.wid]);+ // restored, and another device writes rev 2 again+ fs.writeFileSync(file, backup);+ const other = await put({ state: { _ts: 3, workouts: [{ id: 'B', d: '2026-10-02' }], routines: [] }, baseRev: 1, baseWid: a.body.wid });+ assert.equal(other.status, 200);+ assert.equal(other.body.rev, 2);+ // the first device, at "rev 2" of the lost document, is refused with the current one+ const stale = await put({ state: { _ts: 4, workouts: [], routines: [] }, baseRev: 2, baseWid: b.body.wid });+ assert.equal(stale.status, 409);+ assert.deepEqual(stale.body.state.workouts.map(w => w.id), ['B']);+ // its rev check sees the other write id+ const rev = await (await fetch(`${base}/api/data/rev`, { headers })).json();+ assert.deepEqual(rev, { rev: 2, wid: other.body.wid });+});diff --git a/frontend/src/lib/sync-merge.js b/frontend/src/lib/sync-merge.jsindex 90e345c24..4e4f79301 100644--- a/frontend/src/lib/sync-merge.js+++ b/frontend/src/lib/sync-merge.js@@ -686,6 +686,8 @@ export function mergeStates(a0, b0, { prefer } = {}) {if (resetIds) out.resetIds = resetIdselse delete out.resetIdsdelete out._rev+ delete out._wid+ delete out._widsreturn out}diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.jsindex 6fa6b222b..69ff4188b 100644--- a/frontend/src/store/useStore.js+++ b/frontend/src/store/useStore.js@@ -329,8 +329,10 @@ export const useStore = create((set, get) => {} catch { /* storage refused — the copy in memory still knows */ }}const saveOwed = owed => { try { if (owed) localStorage.setItem(DIRTY_KEY, '1'); else localStorage.removeItem(DIRTY_KEY) } catch { /* as above */ } }- const writeSync = (rev, ts) => {- const base = { rev, ts: ts || 0 }+ // `wid`: the write id of the server's document at that revision (api/server.js PUT /api/data):+ // the same `rev` after the server went back in time names a different document.+ const writeSync = (rev, ts, wid) => {+ const base = { rev, ts: ts || 0, ...(typeof wid === 'string' ? { wid } : {}) }meta.set(get().S, { ...metaOf(), base })saveMarker(base)}@@ -502,8 +504,8 @@ export const useStore = create((set, get) => {const { base } = metaOf()if (!base || owes()) return get().pullState()try {- const { rev } = await api('/api/data/rev')- if (rev !== base.rev) return get().pullState()+ const { rev, wid } = await api('/api/data/rev')+ if (rev !== base.rev || (base.wid && wid && wid !== base.wid)) return get().pullState()confirmed(get().S) // nothing moved on either side} catch (e) {if (isNetworkError(e) || refused(e)) failed(e)@@ -536,7 +538,7 @@ export const useStore = create((set, get) => {if (refillIfComplete(merged)) merged.edited = { ...(merged.edited || {}), queue: Math.max(Date.now(), highestStamp(merged) + 1) }persist(merged, false)if (rev == null) dropSync()- else writeSync(rev, ts)+ else writeSync(rev, ts, remote?._wid)}// The workout running on this device, carried from its copy into the one replacing it — in that// copy's unit: a merge or a pull can bring the other device's switch to lb along, and a session@@ -548,7 +550,7 @@ export const useStore = create((set, get) => {return !a || fu === tu ? a : inUnitOf({ unit: fu, active: a }, to).active}// Take the server's copy as this device's own, timestamp and all (see persist).- const adopt = (next, rev) => { persist(next, false, false); writeSync(rev, next._ts); markOwed(false) }+ const adopt = (next, rev) => { persist(next, false, false); writeSync(rev, next._ts, next._wid); markOwed(false) }const doPush = async (attempt = 0) => {const S = get().S@@ -563,14 +565,14 @@ export const useStore = create((set, get) => {// `stamped`: this client stamps its own changes; the server stamps only for one that does not// (api/sync-stamps.js).const body = { state: S, stamped: true }- if (asReplace != null) body.baseRev = asReplace- else if (!force && base) body.baseRev = base.rev+ if (asReplace != null) { body.baseRev = asReplace.rev; if (asReplace.wid) body.baseWid = asReplace.wid }+ else if (!force && base) { body.baseRev = base.rev; if (base.wid) body.baseWid = base.wid }try {const r = await api('/api/data', { method: 'PUT', body: JSON.stringify(body) })// A server from before revisions answers without one — then there is nothing to hold the// next push to, and the marker must not pretend otherwise.if (r.rev == null) dropSync()- else writeSync(r.rev, S._ts)+ else writeSync(r.rev, S._ts, r.wid)markOwed(false)toldTooLarge = falseconfirmed(S)@@ -656,7 +658,7 @@ export const useStore = create((set, get) => {if (!user || localStorage.getItem('gym_owner') !== user.id) returnlet theirs = nulltry { theirs = JSON.parse(e.newValue) } catch { return }- if (theirs?.rev == null || theirs.rev === metaOf().base?.rev) return+ if (theirs?.rev == null || (theirs.rev === metaOf().base?.rev && theirs.wid === metaOf().base?.wid)) returncheckRev(true)})@@ -928,7 +930,7 @@ export const useStore = create((set, get) => {const merged = Object.assign(clone(DEF), mergeStates(state, S, { prefer: 'a' }))merged.active = carryActive(S, merged)persist(merged, false)- if (rev != null) writeSync(rev, 0)+ if (rev != null) writeSync(rev, 0, state?._wid)else dropSync()await get().pushState()await applyStash()@@ -941,7 +943,7 @@ export const useStore = create((set, get) => {const merged = Object.assign(clone(DEF), mergeStates(S, later, { prefer: 'a' }))merged.active = S.active || nullpersist(merged, false)- if (rev != null) writeSync(rev, 0)+ if (rev != null) writeSync(rev, 0, state?._wid)else dropSync()await get().pushState()}@@ -1147,7 +1149,8 @@ export const useStore = create((set, get) => {if (!mergeWith?.state || !uid) {stampRestore(next, [cur, server], now)next._ts = now- get().replaceState(next, !!uid, { baseRev: read?.rev ?? metaOf().base?.rev ?? null })+ const at = read?.rev != null ? { rev: read.rev, wid: read.state?._wid } : metaOf().base+ get().replaceState(next, !!uid, { baseRev: at?.rev ?? null, baseWid: at?.wid })return}const others = mergeWith.local ? mergeStates(cur, mergeWith.state) : mergeWith.state@@ -1158,14 +1161,14 @@ export const useStore = create((set, get) => {merged._ts = nowmerged.active = next.active || nullpersist(merged, true)- if (mergeWith.rev != null) writeSync(mergeWith.rev, 0)+ if (mergeWith.rev != null) writeSync(mergeWith.rev, 0, mergeWith.state?._wid)},// A replace that is meant to reach the server (backup import, reset) is a deliberate// overwrite, not a change to merge: the push it arms goes without a baseRev — or, given one// (an import), against that revision, so a 409 merges what another device wrote since. It// never takes the reset stamp back (keepReset).- replaceState(S, push = false, { baseRev = null } = {}) {- if (push) { if (baseRev != null) replaceRev = baseRev; else forceNext = true }+ replaceState(S, push = false, { baseRev = null, baseWid } = {}) {+ if (push) { if (baseRev != null) replaceRev = { rev: baseRev, wid: baseWid }; else forceNext = true }persist(keepReset(get().S, clone(S)), push)},@@ -1309,14 +1312,23 @@ export const useStore = create((set, get) => {if (dirty && state) { mergeInto(S, state, rev); pushPending = false; await get().pushState(); return }const restored = restoredStateFor(S, state, false)if (restored) { adopt(restored, rev); confirmed(get().S) }- else if (hasData(S)) { writeSync(rev, 0); await get().pushState() }- else { writeSync(rev, state?._ts || 0); confirmed(get().S) }+ else if (hasData(S)) { writeSync(rev, 0, state?._wid); await get().pushState() }+ else { writeSync(rev, state?._ts || 0, state?._wid); confirmed(get().S) }return}- const serverMoved = rev !== base.rev+ // The document the server holds now, and whether it descends from the one this copy last+ // synced: one it does not (the server's data went back in time — a restored backup, a+ // write lost to a power cut — or an answer that left before this device's own push+ // landed) is never taken as it is. It is merged, and pushed: what this device had+ // confirmed would otherwise vanish here too, and the same revision number can name a+ // different document, which a push would have overwritten without a 409.+ const wid = state?._wid+ const serverMoved = rev !== base.rev || (!!base.wid && !!wid && wid !== base.wid)+ const descends = !base.wid || !wid || wid === base.wid || (Array.isArray(state?._wids) && state._wids.includes(base.wid))const changed = dirty || localChanged(S)if (!serverMoved) { if (changed) await get().pushState(); else confirmed(S); return }if (!state) { writeSync(rev, 0); if (hasData(S)) await get().pushState(); return }+ if (!descends) { mergeInto(S, state, rev); pushPending = false; await get().pushState(); return }if (!changed) { const next = Object.assign(clone(DEF), state); next.active = carryActive(S, next); adopt(next, rev); confirmed(get().S); return }mergeInto(S, state, rev)pushPending = falsediff --git a/frontend/src/store/useStore.rev-rewind.test.jsx b/frontend/src/store/useStore.rev-rewind.test.jsxnew file mode 100644index 000000000..edd775198--- /dev/null+++ b/frontend/src/store/useStore.rev-rewind.test.jsx@@ -0,0 +1,80 @@+// @vitest-environment happy-dom++/* The server's data can go back in time: a restored nightly backup, a write lost to a power cut.+ The revision is a counter, so the same number then names a different document. Every write+ carries a write id and its ancestors' (`_wid`, `_wids`, api/server.js), and a device never takes+ a document that does not descend from the one it last synced: it merges and pushes instead, so+ what it had confirmed comes back rather than vanishing here too (QA 2026-10-06). The server below+ answers like api/server.js. */+import { beforeEach, describe, expect, it, vi } from 'vitest'++vi.mock('../lib/api.js', () => ({ api: vi.fn(), setRemoteAuth: vi.fn() }))+vi.mock('./useUI.js', () => ({ useUI: { getState: () => ({ toast: vi.fn(), stopRest: vi.fn(), abandonWork: vi.fn() }) } }))++import { api } from '../lib/api.js'+import { DEF, useStore } from './useStore.js'++const clone = v => JSON.parse(JSON.stringify(v))+const workout = id => ({ id, d: '2026-10-01', start: 1, entries: [] })+const ids = xs => (xs || []).map(x => x.id).sort()+const USER = { id: 'user-1', name: 'One' }+const fresh = { offline: false, pending: false, auth: false, lastError: null, lastSynced: 0, server: null }+const httpError = (status, data) => Object.assign(new Error('HTTP ' + status), { status, data })+const tick = (ms = 30) => new Promise(r => setTimeout(r, ms))++let doc, n = 0+const write = state => { const wids = [...(doc?._wids || []), ...(doc?._wid ? [doc._wid] : [])]; doc = { ...clone(state), _rev: (doc?._rev || 0) + 1, _wids: wids, _wid: 'w' + (++n) }; return doc }+beforeEach(() => {+ localStorage.clear(); localStorage.setItem('gym_owner', USER.id); api.mockReset(); doc = null; n = 0+ useStore.setState({ S: clone(DEF), user: null, ready: false, sync: { ...fresh }, config: null })+ api.mockImplementation(async (path, o = {}) => {+ const body = o.body ? JSON.parse(o.body) : null+ if (path === '/api/data/rev') return { rev: doc?._rev || 0, wid: doc?._wid }+ if ((o.method || 'GET') === 'GET') return { state: clone(doc), rev: doc?._rev || 0 }+ if (body.baseRev != null && (body.baseRev !== (doc?._rev || 0) || (body.baseWid && doc?._wid && body.baseWid !== doc._wid))) throw httpError(409, { error: 'conflict', rev: doc._rev, state: clone(doc) })+ write(body.state)+ return { ok: true, rev: doc._rev, wid: doc._wid }+ })+})+const signedIn = S => useStore.setState({ S, user: USER, ready: true, sync: { ...fresh } })++describe('the server went back in time', () => {+ it('a workout confirmed at rev 2 is pushed back when the server comes back at rev 1', async () => {+ write({ ...clone(DEF), _ts: 100, workouts: [workout('w1')] })+ const r1 = clone(doc)+ write({ ...clone(DEF), _ts: 200, workouts: [workout('w1'), workout('LegDay')] })+ signedIn({ ...clone(doc), _ts: 200 })+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 2, ts: 200, wid: doc._wid }))+ doc = r1 // host reset: the write of rev 2 never reached the disk+ window.dispatchEvent(new Event('online'))+ await tick()+ expect(ids(useStore.getState().S.workouts)).toEqual(['LegDay', 'w1'])+ expect(ids(doc.workouts)).toEqual(['LegDay', 'w1'])+ })++ it('the same revision number naming another device\'s document is pulled and merged, not overwritten', async () => {+ write({ ...clone(DEF), _ts: 100, workouts: [workout('w1')] })+ const r1 = clone(doc)+ write({ ...clone(DEF), _ts: 200, workouts: [workout('w1'), workout('LegDay')] })+ signedIn({ ...clone(doc), _ts: 200 })+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 2, ts: 200, wid: doc._wid }))+ doc = r1 // restored backup at rev 1+ write({ ...clone(r1), _ts: 300, workouts: [workout('w1'), workout('B_Push')] }) // device B: rev 2 again+ window.dispatchEvent(new Event('online'))+ await tick()+ expect(ids(doc.workouts)).toEqual(['B_Push', 'LegDay', 'w1'])+ expect(ids(useStore.getState().S.workouts)).toEqual(['B_Push', 'LegDay', 'w1'])+ })++ it('an answer that left before this device\'s own push landed is not taken over the newer copy', async () => {+ write({ ...clone(DEF), _ts: 100, workouts: [workout('w1')] })+ const r1 = clone(doc)+ write({ ...clone(DEF), _ts: 200, workouts: [workout('w1'), workout('w2')] }) // this device's push+ signedIn({ ...clone(doc), _ts: 200 })+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 2, ts: 200, wid: doc._wid }))+ const real = api.getMockImplementation()+ api.mockImplementation(async (path, o = {}) => ((o.method || 'GET') === 'GET' && path === '/api/data' ? { state: clone(r1), rev: 1 } : real(path, o)))+ await useStore.getState().pullState()+ expect(ids(useStore.getState().S.workouts)).toEqual(['w1', 'w2'])+ })+})