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
Admin: delete an account, not just disable it (#107)
Duarte Santos90a1e8956a89
diff --git a/api/server.js b/api/server.jsindex be84073c6..b940cd7a6 100644--- a/api/server.js+++ b/api/server.js@@ -1091,6 +1091,33 @@ const routes = {json(res, 200, { ok: true, id: u.id, disabled: u.disabled });},+ // Disable locks an account out; this removes it. The one destructive action in the app, so the+ // client asks twice and this end refuses the two cases that cannot be undone from the UI+ // afterwards: an admin deleting themselves, and the last admin standing (issue #107).+ // The invite code that let them in stays burned — it was used, and freeing it would quietly+ // widen an invite-only instance. `GET /api/admin/user` is the export: the dashboard offers it+ // before the confirm, so the training history can be kept if anyone wants it.+ 'POST /api/admin/user/delete': async (req, res) => {+ const admin = requireAdmin(req, res); if (!admin) return;+ const body = await readBody(req);+ const u = db.users.find(x => x.id === body.id);+ if (!u) return json(res, 404, { error: 'no such user' });+ if (u.id === admin.id) return json(res, 400, { error: 'you cannot delete your own account' });+ if (isAdmin(u) && db.users.filter(isAdmin).length <= 1) return json(res, 400, { error: 'cannot delete the last admin' });+ const name = u.name;+ db.users = db.users.filter(x => x.id !== u.id);+ db.creds = (db.creds || []).filter(c => c.userId !== u.id);+ db.subs = (db.subs || []).filter(x => x.userId !== u.id);+ presence.delete(u.id);+ // The training history and any Coach credential of theirs, both outside db.json.+ try { fs.unlinkSync(stateFile(u.id)); } catch { /* already gone */ }+ try { coachConfig.clearProfileAuth(u.id); } catch { /* nothing stored */ }+ saveDb();+ // Logged with the name, because the id is about to mean nothing to anyone reading this back.+ audit(req, 'admin.user.delete', { user: admin, msg: name });+ json(res, 200, { ok: true, id: u.id });+ },+'GET /api/admin/invites': async (req, res) => {if (!requireAdmin(req, res)) return;// resolve usedBy uid → name for displaydiff --git a/api/test/server-admin-delete.test.js b/api/test/server-admin-delete.test.jsnew file mode 100644index 000000000..ad9a7f1ec--- /dev/null+++ b/api/test/server-admin-delete.test.js@@ -0,0 +1,118 @@+/* Issue #107: disabling locks an account out but deliberately leaves state-<uid>.json and the+ credential record in place, so "no data remains" was not reachable from the dashboard. Delete+ removes the user, their credentials, their push subscriptions, their training history and any+ Coach credential — and refuses the two cases nothing in the UI could undo afterwards. Real+ server.js in a child, same harness as server-admin-state.test.js. */+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');+const mintSession = uid => {+ const payload = `${uid}:${Date.now() + 86400000}:0`;+ return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');+};+const ADMIN = 'u_adm_1', ADMIN2 = 'u_adm_2', VICTIM = 'u_vic_1';+const as = uid => ({ Cookie: `gymsid=${mintSession(uid)}`, 'Content-Type': 'application/json' });+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, { twoAdmins = false } = {}) {+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-del-'));+ fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });+ const users = [+ { id: ADMIN, name: 'Adminna', created: new Date().toISOString(), admin: true },+ { id: VICTIM, name: 'Mallory', created: new Date().toISOString(), invitedBy: 'CODE1' },+ ];+ if (twoAdmins) users.push({ id: ADMIN2, name: 'Second', created: new Date().toISOString(), admin: true });+ fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({+ users,+ creds: [{ id: 'c-victim', userId: VICTIM, publicKey: 'x' }, { id: 'c-admin', userId: ADMIN, publicKey: 'y' }],+ subs: [{ endpoint: 'https://push/victim', userId: VICTIM }, { endpoint: 'https://push/admin', userId: ADMIN }],+ invites: [{ code: 'CODE1', usedBy: VICTIM, usedAt: new Date().toISOString() }],+ }));+ fs.writeFileSync(path.join(dataDir, `state-${VICTIM}.json`), JSON.stringify({ unit: 'kg', workouts: [], _rev: 3 }));+ 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}`, log: '', dataDir };+ child.stdout.on('data', d => h.log += d);+ child.stderr.on('data', d => h.log += d);+ 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.del = async (id, uid = ADMIN) => {+ const r = await fetch(`${h.api}/api/admin/user/delete`, { method: 'POST', headers: { ...as(uid), Origin: 'http://localhost:8080' }, body: JSON.stringify({ id }) });+ return { status: r.status, body: await r.json() };+ };+ h.db = () => JSON.parse(fs.readFileSync(path.join(h.dataDir, 'db.json'), 'utf8'));+ h.stackFrames = () => h.log.split('\n').filter(l => /^\s+at /.test(l)).length;+ return h;+}++test('removes the account and everything attached to it', async t => {+ const h = await startServer(t);+ assert.ok(fs.existsSync(path.join(h.dataDir, `state-${VICTIM}.json`)));+ const res = await h.del(VICTIM);+ assert.equal(res.status, 200);++ const db = h.db();+ assert.deepEqual(db.users.map(u => u.id), [ADMIN], 'the user is gone');+ assert.deepEqual(db.creds.map(c => c.userId), [ADMIN], 'their passkeys are gone');+ assert.deepEqual(db.subs.map(s => s.userId), [ADMIN], 'their push subscriptions are gone');+ assert.equal(fs.existsSync(path.join(h.dataDir, `state-${VICTIM}.json`)), false, 'their history is gone');+ // The code they joined with stays burned: it was used, and freeing it would quietly widen+ // an invite-only instance.+ assert.equal(db.invites[0].usedBy, VICTIM);+ assert.equal(h.stackFrames(), 0, `no stack traces:\n${h.log}`);+});++test('their session stops working immediately', async t => {+ const h = await startServer(t);+ const before = await fetch(`${h.api}/api/me`, { headers: as(VICTIM) });+ assert.equal(before.status, 200);+ await h.del(VICTIM);+ const after = await fetch(`${h.api}/api/me`, { headers: as(VICTIM) });+ assert.equal(after.status, 401, 'a cookie for a deleted account is worthless');+});++test('refuses the two deletions that cannot be undone', async t => {+ const h = await startServer(t);+ const self = await h.del(ADMIN);+ assert.equal(self.status, 400);+ assert.match(self.body.error, /your own account/);++ const last = await h.del(ADMIN, ADMIN); // ADMIN is also the only admin+ assert.equal(last.status, 400);+ assert.equal(h.db().users.length, 2, 'nothing was removed');+});++test('another admin can be deleted while one remains', async t => {+ const h = await startServer(t, { twoAdmins: true });+ const res = await h.del(ADMIN2);+ assert.equal(res.status, 200);+ assert.deepEqual(h.db().users.map(u => u.id).sort(), [ADMIN, VICTIM].sort());+});++test('says so plainly when the account is not there, and needs an admin', async t => {+ const h = await startServer(t);+ const missing = await h.del('nobody');+ assert.equal(missing.status, 404);+ const asVictim = await h.del(ADMIN, VICTIM);+ assert.equal(asVictim.status, 403, 'an ordinary user cannot delete anyone');+ assert.equal(h.db().users.length, 2);+});diff --git a/frontend/src/lib/audit.js b/frontend/src/lib/audit.jsindex d3d65ac3f..a2c73f86a 100644--- a/frontend/src/lib/audit.js+++ b/frontend/src/lib/audit.js@@ -28,6 +28,7 @@ const LABELS = {'auth.pair.fail': 'Pairing failed','admin.user.disable': 'Disabled an account','admin.user.enable': 'Re-enabled an account',+ 'admin.user.delete': 'Deleted an account','admin.invite.create': 'Created an invite code','admin.invite.revoke': 'Revoked an invite code','admin.audit.clear': 'Cleared the activity log',diff --git a/frontend/src/views/Admin.jsx b/frontend/src/views/Admin.jsxindex 8ca0409c8..cda0978dc 100644--- a/frontend/src/views/Admin.jsx+++ b/frontend/src/views/Admin.jsx@@ -42,6 +42,20 @@ function UserDetail({ id, onChanged, close }) {// left exactly this account un-disableable. setsDone/workoutVolume walk entries and sets, so// an entry that lacks either has nothing to show and is skipped rather than drawn.const workouts = (d.workouts || []).filter(w => w && Array.isArray(w.entries) && w.entries.every(e => e && Array.isArray(e.sets)))+ // Their whole record as the admin API already returns it — the export the delete sheet offers.+ const exportUser = () => {+ const blob = new Blob([JSON.stringify(d, null, 2)], { type: 'application/json' })+ const a = document.createElement('a')+ a.href = URL.createObjectURL(blob)+ a.download = `opengym-${u.name.replace(/[^a-zA-Z0-9_-]+/g, '-').toLowerCase()}-${u.id}.json`+ document.body.appendChild(a); a.click(); a.remove()+ setTimeout(() => URL.revokeObjectURL(a.href), 1000)+ }+ const doDelete = () => {+ api('/api/admin/user/delete', { method: 'POST', body: JSON.stringify({ id: u.id }) })+ .then(() => { toast('Account deleted'); onChanged(); close() })+ .catch(e => toast(e.message))+ }const setDisabled = disabled => {api('/api/admin/user/disable', { method: 'POST', body: JSON.stringify({ id: u.id, disabled }) }).then(() => { toast(disabled ? 'User disabled' : 'User enabled'); onChanged(); close() })@@ -67,6 +81,25 @@ function UserDetail({ id, onChanged, close }) {: confirmSheet({ title: 'Disable ' + u.name + '?', message: 'They are signed out everywhere and can no longer sync or log in until re-enabled. Their data stays.', confirmText: 'Disable', danger: true, onConfirm: () => setDisabled(true) })}>{u.disabled ? 'Enable account' : 'Disable account'}</button><div className="adm-hint">{u.disabled ? 'Enabling lets them sign in and sync again.' : 'Disabling signs them out everywhere and blocks sign-in. Nothing is deleted.'}</div>+ {/* The one destructive action in the app (issue #107), so it asks twice and offers the+ export first — that history is theirs. The second step names the account again, because+ the first sheet can be dismissed by anyone who was not reading. */}+ <button className="btn danger" style={{ margin: '14px 0 4px' }}+ onClick={() => confirmSheet({+ title: 'Delete ' + u.name + '?',+ message: 'Everything goes: their workouts, weigh-ins, routines, passkeys and notifications. This cannot be undone, and the invite code they joined with stays used. Download their data first if they might want it.',+ confirmText: 'Continue',+ danger: true,+ onConfirm: () => confirmSheet({+ title: 'Delete ' + u.name + ' for good?',+ message: 'Last chance — there is no undo and no backup of this on the server.',+ confirmText: 'Delete account',+ danger: true,+ onConfirm: doDelete,+ }),+ })}>Delete account</button>+ <button className="btn" style={{ marginBottom: 4 }} onClick={exportUser}>Download their data</button>+ <div className="adm-hint">Deleting removes the account and every trace of its training history from this server.</div></>}<h4 className="sec">Workout history</h4>{workouts.length ? <div className="list" style={{ gap: 0 }}>