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: POST /api/account/delete, a profile deletes itself

Duarte Santosc2ab01f3b060
diff --git a/api/openapi.yaml b/api/openapi.yaml
index ca178cb63..0195b17ac 100644
--- a/api/openapi.yaml
+++ b/api/openapi.yaml
@@ -565,6 +565,55 @@ paths:
schema: { $ref: '#/components/schemas/Ok' }
'401': { $ref: '#/components/responses/Unauthorized' }
+ /api/account/delete:
+ post:
+ tags: [auth]
+ operationId: accountDelete
+ summary: Delete your own account and everything of yours
+ description: |
+ The signed-in account removes itself for good, with the same clean-up as
+ `/api/admin/user/delete`: the user record, their passkeys, their push
+ subscriptions, their live presence, their training history file, their
+ uploaded photos and videos (`DATA_DIR/uploads/<uid>/`) and any Coach credential
+ stored for them. Not reversible. The body carries the account's name, typed back
+ by its owner, so a request carrying only the session does nothing. The last
+ admin is refused while any other profile remains (the instance would be left
+ with nobody to run it); the only profile on an instance may delete itself.
+ Clears the caller's cookie; every other session and Bearer token of the account
+ stops working with it. Audited as `auth.account.delete`, with the name.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [name]
+ properties:
+ name: { type: string, description: 'The account name, exactly (surrounding spaces are ignored).' }
+ responses:
+ '200':
+ description: The account and everything of theirs is gone.
+ headers:
+ Set-Cookie:
+ description: Expires the caller's session cookie(s).
+ schema: { type: string }
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Ok' }
+ '400':
+ description: '`confirm-name`: the name is missing or is not this account''s.'
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Error' }
+ example: { error: "type the account name to confirm", code: "confirm-name" }
+ '401': { $ref: '#/components/responses/Unauthorized' }
+ '409':
+ description: '`last-admin`: the only admin, with other profiles still on the instance.'
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Error' }
+ example: { error: "the last admin cannot leave while other profiles remain", code: "last-admin" }
+
/api/pair/create:
post:
tags: [pairing]
@@ -3640,7 +3689,7 @@ components:
description: |
Event name. Currently one of:
`auth.register.ok|fail|denied`, `auth.login.ok|fail`, `auth.logout`,
- `auth.logout.all`, `auth.pair.create|ok|fail`,
+ `auth.logout.all`, `auth.account.delete`, `auth.pair.create|ok|fail`,
`admin.denied`, `admin.user.disable|enable`,
`admin.invite.create|revoke`, `admin.audit.clear`.
ok: { type: boolean, description: false for failed/denied attempts. }
diff --git a/api/server.js b/api/server.js
index 938fca7dc..76a8d18fd 100644
--- a/api/server.js
+++ b/api/server.js
@@ -1235,6 +1235,23 @@ async function removeEmail(req, res, user, body) {
json(res, 200, { ok: true, email: null });
}
+// Everything of an account, gone for good: the user record, their passkeys, push subscriptions,
+// device links and live presence, and outside db.json their training history, any Coach
+// credential and their photos and videos. The admin's delete and the account's own both end here.
+function removeAccount(u) {
+ 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);
+ dropDeviceLinks(db, 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 */ }
+ // Their photos and videos — the one place a profile's folder under uploads/ is removed.
+ try { MEDIA.removeUser(u.id); } catch (e) { console.error('media: could not remove uploads of', u.id, e.message); }
+ saveDb();
+}
+
const passwordRoutes = {
'POST /api/login/password': async (req, res) => {
const body = await readBody(req);
@@ -2125,6 +2142,30 @@ const routes = {
json(res, 200, { ok: true }, { 'Set-Cookie': clearCookie });
},
+ // The account's own delete (App Store rule 5.1.1(v): an app you can sign up in lets you leave
+ // it too). Everything goes, exactly as when an admin deletes it (removeAccount). The body names
+ // the account, typed back by its owner: a stray or replayed request with only the session does
+ // nothing. No passkey or password proof on top: whoever holds the session can already wipe the
+ // profile's data with "Reset everything", and this is the one way out that must always work.
+ // The last admin is refused while anyone else is left, since nobody could then run the
+ // instance from the app; alone on it, they may go. The session ends with the account: its
+ // cookie is cleared here, and any other session stops verifying since the user is gone.
+ 'POST /api/account/delete': async (req, res) => {
+ const user = readSession(req);
+ if (!user) return json(res, 401, { error: 'not signed in' });
+ const body = await readBody(req);
+ if (readSession(req) !== user) return json(res, 401, { error: 'not signed in' });
+ if (typeof body.name !== 'string' || body.name.trim() !== user.name) {
+ return json(res, 400, { error: 'type the account name to confirm', code: 'confirm-name' });
+ }
+ if (isAdmin(user) && db.users.length > 1 && db.users.filter(isAdmin).length <= 1) {
+ return json(res, 409, { error: 'the last admin cannot leave while other profiles remain', code: 'last-admin' });
+ }
+ removeAccount(user);
+ audit(req, 'auth.account.delete', { user });
+ json(res, 200, { ok: true }, { 'Set-Cookie': clearCookie });
+ },
+
// Mobile app pairing: called from an already signed-in browser tab (Settings → "Pair the
// mobile app") to mint a short code the phone can redeem below.
'POST /api/pair/create': async (req, res) => {
@@ -2480,17 +2521,7 @@ const routes = {
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);
- dropDeviceLinks(db, 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 */ }
- // Their photos and videos — the one place a profile's folder under uploads/ is removed.
- try { MEDIA.removeUser(u.id); } catch (e) { console.error('media: could not remove uploads of', u.id, e.message); }
- saveDb();
+ removeAccount(u);
// 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 });
diff --git a/api/test/server-account-delete.test.js b/api/test/server-account-delete.test.js
new file mode 100644
index 000000000..7d914ff70
--- /dev/null
+++ b/api/test/server-account-delete.test.js
@@ -0,0 +1,132 @@
+/* The account's own delete (App Store rule 5.1.1(v)): a signed-in profile removes itself with
+ the same clean-up the admin's delete runs (removeAccount in server.js), typing its name back
+ to confirm, and the last admin cannot leave an instance others still use. Real server.js in a
+ child, same harness as server-admin-delete.test.js. */
+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 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', USER = 'u_usr_1';
+const as = uid => ({ Cookie: `gymsid=${mintSession(uid)}`, 'Content-Type': 'application/json', Origin: 'http://localhost:8080' });
+async function startServer(t, { users: which = ['admin', 'user'] } = {}) {
+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-selfdel-'));
+ fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
+ const all = {
+ admin: { id: ADMIN, name: 'Adminna', created: new Date().toISOString(), admin: true },
+ admin2: { id: ADMIN2, name: 'Second', created: new Date().toISOString(), admin: true },
+ user: { id: USER, name: 'Mallory', created: new Date().toISOString(), invitedBy: 'CODE1' },
+ };
+ fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({
+ users: which.map(k => all[k]),
+ creds: [{ id: 'c-user', userId: USER, publicKey: 'x' }, { id: 'c-admin', userId: ADMIN, publicKey: 'y' }],
+ subs: [{ endpoint: 'https://push/user', userId: USER }, { endpoint: 'https://push/admin', userId: ADMIN }],
+ invites: [{ code: 'CODE1', usedBy: USER, usedAt: new Date().toISOString() }],
+ }));
+ for (const uid of [USER, ADMIN]) fs.writeFileSync(path.join(dataDir, `state-${uid}.json`), JSON.stringify({ unit: 'kg', workouts: [], _rev: 3 }));
+ 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' },
+ });
+ const h = { api: '', 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 }); });
+ h.port = await boundPort(child, () => h.log);
+ h.api = `http://127.0.0.1:${h.port}`;
+ h.del = async (uid, body) => {
+ const r = await fetch(`${h.api}/api/account/delete`, { method: 'POST', headers: as(uid), body: JSON.stringify(body) });
+ return { status: r.status, body: await r.json(), cookie: r.headers.get('set-cookie') || '' };
+ };
+ h.db = () => JSON.parse(fs.readFileSync(path.join(h.dataDir, 'db.json'), 'utf8'));
+ h.audit = () => fs.readFileSync(path.join(h.dataDir, 'audit.log'), 'utf8').trim().split('\n').map(l => JSON.parse(l));
+ h.stackFrames = () => h.log.split('\n').filter(l => /^\s+at /.test(l)).length;
+ return h;
+}
+
+test('removes the account and everything attached to it, and ends the session', async t => {
+ const h = await startServer(t);
+ const res = await h.del(USER, { name: 'Mallory' });
+ assert.equal(res.status, 200);
+ assert.deepEqual(res.body, { ok: true });
+ assert.match(res.cookie, /gymsid=;.*Max-Age=0/, 'the session cookie is cleared');
+
+ 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-${USER}.json`)), false, 'their history is gone');
+ assert.equal(fs.existsSync(path.join(h.dataDir, `state-${ADMIN}.json`)), true, 'nobody else’s is touched');
+ assert.equal(db.invites[0].usedBy, USER, 'the code they joined with stays burned');
+
+ const me = await fetch(`${h.api}/api/me`, { headers: as(USER) });
+ assert.equal(me.status, 401, 'a cookie for a deleted account is worthless');
+ const ev = h.audit().find(r => r.ev === 'auth.account.delete');
+ assert.ok(ev, 'audited');
+ assert.equal(ev.uid, USER);
+ assert.equal(ev.name, 'Mallory', 'by name, since the id stops meaning anything');
+ assert.equal(h.stackFrames(), 0, `no stack traces:\n${h.log}`);
+});
+
+test('needs the account name typed back', async t => {
+ const h = await startServer(t);
+ for (const body of [{}, { name: '' }, { name: 'mallory' }, { name: 'Adminna' }, { name: 42 }]) {
+ const res = await h.del(USER, body);
+ assert.equal(res.status, 400, JSON.stringify(body));
+ assert.equal(res.body.code, 'confirm-name');
+ }
+ assert.equal(h.db().users.length, 2, 'nothing was removed');
+ // Spaces around it are a keyboard's, not a different name.
+ assert.equal((await h.del(USER, { name: ' Mallory ' })).status, 200);
+});
+
+test('needs a session, and a request from another origin is refused', async t => {
+ const h = await startServer(t);
+ const anon = await fetch(`${h.api}/api/account/delete`, { method: 'POST', headers: { 'Content-Type': 'application/json', Origin: 'http://localhost:8080' }, body: JSON.stringify({ name: 'Mallory' }) });
+ assert.equal(anon.status, 401);
+ const cross = await fetch(`${h.api}/api/account/delete`, { method: 'POST', headers: { ...as(USER), Origin: 'https://evil.example' }, body: JSON.stringify({ name: 'Mallory' }) });
+ assert.equal(cross.status, 403);
+ assert.equal(h.db().users.length, 2);
+});
+
+test('the last admin cannot leave while other profiles remain', async t => {
+ const h = await startServer(t);
+ const res = await h.del(ADMIN, { name: 'Adminna' });
+ assert.equal(res.status, 409);
+ assert.equal(res.body.code, 'last-admin');
+ assert.equal(h.db().users.length, 2, 'nothing was removed');
+});
+
+test('an admin can leave while another admin remains', async t => {
+ const h = await startServer(t, { users: ['admin', 'admin2', 'user'] });
+ assert.equal((await h.del(ADMIN, { name: 'Adminna' })).status, 200);
+ assert.deepEqual(h.db().users.map(u => u.id).sort(), [ADMIN2, USER].sort());
+});
+
+test('the only profile on the instance can delete itself, admin or not', async t => {
+ const h = await startServer(t, { users: ['admin'] });
+ assert.equal((await h.del(ADMIN, { name: 'Adminna' })).status, 200);
+ assert.deepEqual(h.db().users, []);
+ assert.equal(fs.existsSync(path.join(h.dataDir, `state-${ADMIN}.json`)), false);
+});
+
+test('a paired phone deletes with its Bearer token', async t => {
+ const h = await startServer(t);
+ const r = await fetch(`${h.api}/api/account/delete`, {
+ method: 'POST', headers: { Authorization: `Bearer ${mintSession(USER)}`, 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name: 'Mallory' })
+ });
+ assert.equal(r.status, 200);
+ assert.deepEqual(h.db().users.map(u => u.id), [ADMIN]);
+});
diff --git a/frontend/src/lib/audit.js b/frontend/src/lib/audit.js
index 173fc2231..b3c3f520c 100644
--- a/frontend/src/lib/audit.js
+++ b/frontend/src/lib/audit.js
@@ -21,6 +21,8 @@ const LABELS = {
'auth.register.denied': 'Signup refused',
'auth.logout': 'Signed out',
'auth.logout.all': 'Signed out everywhere',
+ // Settings → "Delete my account": the profile removed itself and everything of theirs.
+ 'auth.account.delete': 'Deleted their own account',
// Device pairing (Settings → "Pair the mobile app"): the code is minted in a signed-in browser
// tab and redeemed by the app, so "ok" is the phone coming online, not a sign-in.
'auth.pair.create': 'Created a pairing code',
diff --git a/website/api.html b/website/api.html
index 1542f96d2..9880f5f9c 100644
--- a/website/api.html
+++ b/website/api.html
@@ -245,7 +245,7 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon
<p class="api-facts">
<span>OpenAPI 3.1.0</span>
<span>openGym v1.4.1</span>
- <span>69 endpoints</span>
+ <span>70 endpoints</span>
<span>AGPL-3.0-or-later</span>
</p>
@@ -591,6 +591,46 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon
</div>
</div>
</details>
+
+<details class="ep" id="op-accountDelete">
+ <summary>
+ <span class="m post">POST</span>
+ <span class="ep-path"><code>/api/account/delete</code></span>
+ <span class="ep-chev" aria-hidden="true"></span>
+ <span class="ep-sum">Delete your own account and everything of yours</span>
+ </summary>
+ <div class="ep-body">
+<p>The signed-in account removes itself for good, with the same clean-up as <code>/api/admin/user/delete</code>: the user record, their passkeys, their push subscriptions, their live presence, their training history file, their uploaded photos and videos (<code>DATA_DIR/uploads/&lt;uid&gt;/</code>) and any Coach credential stored for them. Not reversible. The body carries the account's name, typed back by its owner, so a request carrying only the session does nothing. The last admin is refused while any other profile remains (the instance would be left with nobody to run it); the only profile on an instance may delete itself. Clears the caller's cookie; every other session and Bearer token of the account stops working with it. Audited as <code>auth.account.delete</code>, with the name.</p>
+ <p class="ep-auth"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="4" y="11" width="16" height="10" rx="2.5"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg><span>Requires a session: the cookie set at sign-in, or <code>Authorization: Bearer &lt;token&gt;</code> from mobile-app pairing.</span></p>
+
+<p class="ep-h">Request body <span class="p-hint">(JSON)</span></p><div class="ptab">
+ <div class="prow">
+ <span class="p-name">name<em class="p-req" title="required">required</em></span>
+ <span class="p-type">string</span>
+ <span class="p-desc">The account name, exactly (surrounding spaces are ignored).</span>
+ </div>
+</div>
+ <p class="ep-h">Responses</p>
+ <div class="ptab">
+ <div class="prow rrow">
+ <span class="r-code s2">200</span>
+ <span class="p-desc">The account and everything of theirs is gone.<span class="r-sig"><a href="#schema-Ok">Ok</a> &middot; sets <code>Set-Cookie</code></span></span>
+ </div>
+ <div class="prow rrow">
+ <span class="r-code s4">400</span>
+ <span class="p-desc"><code>confirm-name</code>: the name is missing or is not this account's.<span class="r-sig"><code>{&quot;error&quot;:&quot;type the account name to confirm&quot;}</code></span></span>
+ </div>
+ <div class="prow rrow">
+ <span class="r-code s4">401</span>
+ <span class="p-desc">No session, expired/revoked session, or a disabled account.<span class="r-sig"><code>{&quot;error&quot;:&quot;not signed in&quot;}</code></span></span>
+ </div>
+ <div class="prow rrow">
+ <span class="r-code s4">409</span>
+ <span class="p-desc"><code>last-admin</code>: the only admin, with other profiles still on the instance.<span class="r-sig"><code>{&quot;error&quot;:&quot;the last admin cannot leave while other profiles remain&quot;}</code></span></span>
+ </div>
+ </div>
+ </div>
+</details>
</div>
</section>
@@ -4432,7 +4472,7 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon
<div class="prow">
<span class="p-name">ev<em class="p-req" title="required">required</em></span>
<span class="p-type">string</span>
- <span class="p-desc">Event name. Currently one of: <code>auth.register.ok|fail|denied</code>, <code>auth.login.ok|fail</code>, <code>auth.logout</code>, <code>auth.logout.all</code>, <code>auth.pair.create|ok|fail</code>, <code>admin.denied</code>, <code>admin.user.disable|enable</code>, <code>admin.invite.create|revoke</code>, <code>admin.audit.clear</code>.</span>
+ <span class="p-desc">Event name. Currently one of: <code>auth.register.ok|fail|denied</code>, <code>auth.login.ok|fail</code>, <code>auth.logout</code>, <code>auth.logout.all</code>, <code>auth.account.delete</code>, <code>auth.pair.create|ok|fail</code>, <code>admin.denied</code>, <code>admin.user.disable|enable</code>, <code>admin.invite.create|revoke</code>, <code>admin.audit.clear</code>.</span>
</div>
<div class="prow">
<span class="p-name">ok<em class="p-req" title="required">required</em></span>