From 90a1e8956a8945651595a23ae27ac690ff5b45e9 Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Sun, 20 Sep 2026 21:04:56 +0200 Subject: [PATCH] Admin: delete an account, not just disable it (#107) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Disabling locks someone out but deliberately leaves their state file and credential on disk, so 'no data remains' was not reachable from the dashboard — which is what the request asked for. POST /api/admin/user/delete removes the user, their passkeys, their push subscriptions, their presence entry, their training history and any Coach credential of theirs. Two refusals, because nothing in the UI could undo either: an admin cannot delete their own account, and the last remaining admin cannot be removed. The invite code they joined with stays burned — it was used, and freeing it would quietly widen an invite-only instance. In the dashboard it asks twice, naming the account both times, and offers their data as a download first: the training history is theirs. Five tests drive the real server. --- api/server.js | 27 ++++++ api/test/server-admin-delete.test.js | 118 +++++++++++++++++++++++++++ frontend/src/lib/audit.js | 1 + frontend/src/views/Admin.jsx | 33 ++++++++ 4 files changed, 179 insertions(+) create mode 100644 api/test/server-admin-delete.test.js diff --git a/api/server.js b/api/server.js index be84073..b940cd7 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 display diff --git a/api/test/server-admin-delete.test.js b/api/test/server-admin-delete.test.js new file mode 100644 index 0000000..ad9a7f1 --- /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-.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.js index d3d65ac..a2c73f8 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.jsx index 8ca0409..cda0978 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'}
{u.disabled ? 'Enabling lets them sign in and sync again.' : 'Disabling signs them out everywhere and blocks sign-in. Nothing is deleted.'}
+ {/* 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. */} + + +
Deleting removes the account and every trace of its training history from this server.
}

Workout history

{workouts.length ?