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
API: deleting the account asks the owner's proof too
Duarte Santos894f769fcd89
diff --git a/api/openapi.yaml b/api/openapi.yamlindex 0195b17ac..9c732048a 100644--- a/api/openapi.yaml+++ b/api/openapi.yaml@@ -576,20 +576,27 @@ paths:subscriptions, their live presence, their training history file, theiruploaded photos and videos (`DATA_DIR/uploads/<uid>/`) and any Coach credentialstored 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.+ by its owner, and the same proof as setting a password (see OwnerProof): a+ passkey assertion made for this request, or the current password while+ `PASSWORD_LOGIN` is on. The name and the last-admin rule are checked before the+ proof is asked. 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 and the proof it was made with; a refused proof as+ `auth.proof.fail` with `act: account-delete`.requestBody:required: truecontent:application/json:schema:- type: object- required: [name]- properties:- name: { type: string, description: 'The account name, exactly (surrounding spaces are ignored).' }+ allOf:+ - $ref: '#/components/schemas/OwnerProof'+ - type: object+ required: [name]+ properties:+ name: { type: string, description: 'The account name, exactly (surrounding spaces are ignored).' }+ example: { name: "Ada", current: "correct horse battery staple" }responses:'200':description: The account and everything of theirs is gone.@@ -607,12 +614,14 @@ paths:schema: { $ref: '#/components/schemas/Error' }example: { error: "type the account name to confirm", code: "confirm-name" }'401': { $ref: '#/components/responses/Unauthorized' }+ '403': { $ref: '#/components/responses/ProofRefused' }'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" }+ '429': { $ref: '#/components/responses/TooManyRequests' }/api/pair/create:post:diff --git a/api/server.js b/api/server.jsindex 76a8d18fd..3dd0b1298 100644--- a/api/server.js+++ b/api/server.js@@ -958,7 +958,9 @@ const THROTTLED = {// budget: the password that may prove them counts its own failures (passwordAttempt).'POST /api/device-link/options': 'link', 'POST /api/device-link/verify': 'link','POST /api/account/passkeys/options': null, 'POST /api/account/device-link': null,- 'DELETE /api/account/passkeys': null+ 'DELETE /api/account/passkeys': null,+ // Deleting the account: the same, for the password that may prove it.+ 'POST /api/account/delete': null};// Which address the throttle counts against. Unlike clientIp() above, which only labels a log@@ -2143,13 +2145,14 @@ const routes = {},// 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.+ // it too). Everything goes, exactly as when an admin deletes it (removeAccount). Two things+ // stand in front of it: the account's name, typed back by its owner, so a stray request does+ // nothing; and the same proof the other changes to a way in ask (proveOwner), since a session+ // on its own may be a cookie someone walked off with. The proof is asked only once the delete+ // could go ahead, so a refusal the request already decides spends no passkey prompt and no+ // password check. 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' });@@ -2158,11 +2161,16 @@ const routes = {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' });- }+ const lastAdmin = () => isAdmin(user) && db.users.length > 1 && db.users.filter(isAdmin).length <= 1;+ const refuseLastAdmin = () => json(res, 409, { error: 'the last admin cannot leave while other profiles remain', code: 'last-admin' });+ if (lastAdmin()) return refuseLastAdmin();+ const proof = await proveOwner(req, res, user, body, 'account-delete');+ if (!proof) return;+ // Everything above awaited: the session may have ended, and another admin may have left.+ if (readSession(req) !== user) return json(res, 401, { error: 'not signed in' });+ if (lastAdmin()) return refuseLastAdmin();removeAccount(user);- audit(req, 'auth.account.delete', { user });+ audit(req, 'auth.account.delete', { user, msg: proof });json(res, 200, { ok: true }, { 'Set-Cookie': clearCookie });},diff --git a/api/test/server-account-delete.test.js b/api/test/server-account-delete.test.jsindex 7d914ff70..0c47c0324 100644--- a/api/test/server-account-delete.test.js+++ b/api/test/server-account-delete.test.js@@ -1,8 +1,10 @@/* The account's own delete (App Store rule 5.1.1(v)): a signed-in profile removes itself withthe 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';+ and proving it is the owner the way the other changes to a way in do (proveOwner): here with+ the current password, the passkey half is in server-passkeys.test.js. 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, before } from 'node:test';import assert from 'node:assert/strict';import crypto from 'node:crypto';import fs from 'node:fs';@@ -10,6 +12,7 @@ import os from 'node:os';import path from 'node:path';import { spawn } from 'node:child_process';import { fileURLToPath } from 'node:url';+import { hashPassword } from '../password.js';import { boundPort } from './helpers.mjs';const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');@@ -18,15 +21,22 @@ const mintSession = uid => {const payload = `${uid}:${Date.now() + 86400000}:0`;return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');};+const GOOD = 'correct horse battery staple';+let pwHash;+before(async () => { pwHash ??= await hashPassword(GOOD); });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'] } = {}) {+async function startServer(t, { users: which = ['admin', 'user'], env = {} } = {}) {+ pwHash ??= await hashPassword(GOOD);+ const pw = { h: pwHash, set: new Date().toISOString() };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' },+ admin: { id: ADMIN, name: 'Adminna', created: new Date().toISOString(), admin: true, pw },+ admin2: { id: ADMIN2, name: 'Second', created: new Date().toISOString(), admin: true, pw },+ user: { id: USER, name: 'Mallory', created: new Date().toISOString(), invitedBy: 'CODE1', pw },+ // Passkey-only: no password that could prove anything.+ nopw: { id: 'u_nopw', name: 'Keyonly', created: new Date().toISOString() },};fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({users: which.map(k => all[k]),@@ -37,7 +47,7 @@ async function startServer(t, { users: which = ['admin', 'user'] } = {}) {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' },+ env: { ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost', PASSWORD_LOGIN: '1', AUDIT_LOG: '1', ...env },});const h = { api: '', log: '', dataDir };child.stdout.on('data', d => h.log += d);@@ -57,7 +67,7 @@ async function startServer(t, { users: which = ['admin', 'user'] } = {}) {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' });+ const res = await h.del(USER, { name: 'Mallory', current: GOOD });assert.equal(res.status, 200);assert.deepEqual(res.body, { ok: true });assert.match(res.cookie, /gymsid=;.*Max-Age=0/, 'the session cookie is cleared');@@ -81,14 +91,15 @@ test('removes the account and everything attached to it, and ends the session',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 }]) {+ // Checked before the proof: a wrong name costs no password check, even with the right one.+ for (const body of [{}, { name: '' }, { name: 'mallory', current: GOOD }, { name: 'Adminna', current: GOOD }, { 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);+ assert.equal((await h.del(USER, { name: ' Mallory ', current: GOOD })).status, 200);});test('needs a session, and a request from another origin is refused', async t => {@@ -100,9 +111,10 @@ test('needs a session, and a request from another origin is refused', async t =>assert.equal(h.db().users.length, 2);});-test('the last admin cannot leave while other profiles remain', async t => {+test('the last admin cannot leave while other profiles remain, proof or not', async t => {const h = await startServer(t);- const res = await h.del(ADMIN, { name: 'Adminna' });+ assert.equal((await h.del(ADMIN, { name: 'Adminna' })).body.code, 'last-admin', 'refused before any proof is asked');+ const res = await h.del(ADMIN, { name: 'Adminna', current: GOOD });assert.equal(res.status, 409);assert.equal(res.body.code, 'last-admin');assert.equal(h.db().users.length, 2, 'nothing was removed');@@ -110,13 +122,13 @@ test('the last admin cannot leave while other profiles remain', async t => {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.equal((await h.del(ADMIN, { name: 'Adminna', current: GOOD })).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.equal((await h.del(ADMIN, { name: 'Adminna', current: GOOD })).status, 200);assert.deepEqual(h.db().users, []);assert.equal(fs.existsSync(path.join(h.dataDir, `state-${ADMIN}.json`)), false);});@@ -125,8 +137,39 @@ 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' })+ body: JSON.stringify({ name: 'Mallory', current: GOOD })});assert.equal(r.status, 200);assert.deepEqual(h.db().users.map(u => u.id), [ADMIN]);});++test('needs proof that the owner is here: missing or wrong, nothing is removed', async t => {+ const h = await startServer(t, { users: ['admin', 'user', 'nopw'] });+ const none = await h.del(USER, { name: 'Mallory' });+ assert.equal(none.status, 403);+ assert.equal(none.body.code, 'current-required');+ const wrong = await h.del(USER, { name: 'Mallory', current: 'not the password at all' });+ assert.equal(wrong.status, 403);+ assert.equal(wrong.body.code, 'current-wrong');+ // No password, so only a passkey can say it is them; an assertion that does not verify is no proof.+ const keyOnly = await h.del('u_nopw', { name: 'Keyonly', current: GOOD });+ assert.equal(keyOnly.status, 403);+ assert.equal(keyOnly.body.code, 'passkey-required');+ const bogus = await h.del('u_nopw', { name: 'Keyonly', cid: 'nope', credential: { id: 'x', response: {} } });+ assert.equal(bogus.status, 403);+ assert.equal(bogus.body.code, 'passkey');++ assert.equal(h.db().users.length, 3, 'nothing was removed');+ assert.equal(fs.existsSync(path.join(h.dataDir, `state-${USER}.json`)), true);+ const fails = h.audit().filter(r => r.ev === 'auth.proof.fail');+ assert.ok(fails.length >= 2 && fails.every(r => r.act === 'account-delete'), 'logged as a refused proof for the delete');+ assert.ok(!h.audit().some(r => r.ev === 'auth.account.delete'));+});++test('with password sign-in off, a password proves nothing', async t => {+ const h = await startServer(t, { env: { PASSWORD_LOGIN: '' } });+ const res = await h.del(USER, { name: 'Mallory', current: GOOD });+ assert.equal(res.status, 403);+ assert.equal(res.body.code, 'passkey-required');+ assert.equal(h.db().users.length, 2);+});diff --git a/api/test/server-passkeys.test.js b/api/test/server-passkeys.test.jsindex 2c351f486..632f9c192 100644--- a/api/test/server-passkeys.test.js+++ b/api/test/server-passkeys.test.js@@ -778,3 +778,26 @@ test('passkey sign-up and sign-in refusals carry a code the app can translate',assert.equal(off.status, 403);assert.equal(off.body.code, 'disabled');});++// Settings → "Delete my account" asks the same proof (server-account-delete.test.js has the+// password half): a passkey of this profile's own, made for this request, and only once.+test('deleting the account: a passkey of its own proves it, someone else’s does not', async t => {+ const a = softPasskey(), b = softPasskey();+ const h = await startServer(t, { users: [user('u1', 'Ana'), user('u2', 'Bea')], creds: [a.row('u1'), b.row('u2')] });+ const ip = '198.51.100.90';+ const del = (proof, uid = 'u1') => h.req('POST', '/api/account/delete', { body: { name: uid === 'u1' ? 'Ana' : 'Bea', ...proof }, cookie: mintSession(uid), ip });++ const theirs = await del(await h.stepUp(b, ip));+ assert.equal(theirs.status, 403);+ assert.equal(theirs.body.code, 'passkey');+ assert.equal(h.db().users.length, 2, 'nothing was removed');++ const proof = await h.stepUp(a, ip);+ const ok = await del(proof);+ assert.equal(ok.status, 200);+ assert.deepEqual(h.db().users.map(u => u.id), ['u2']);+ assert.deepEqual(h.db().creds.map(c => c.userId), ['u2'], 'its passkeys go with it');+ assert.equal(h.audit().find(r => r.ev === 'auth.account.delete')?.msg, 'passkey');+ // Bea's session, with Ana's spent assertion: no proof for anyone.+ assert.equal((await del(proof, 'u2')).status, 403);+});diff --git a/frontend/src/lib/audit.js b/frontend/src/lib/audit.jsindex b3c3f520c..6c298f678 100644--- a/frontend/src/lib/audit.js+++ b/frontend/src/lib/audit.js@@ -114,7 +114,8 @@ const ACTS = {'password-remove': 'removing the password','passkey-add': 'adding a passkey','passkey-remove': 'removing a passkey',- 'device-link': 'making a one-time code for another device'+ 'device-link': 'making a one-time code for another device',+ 'account-delete': 'deleting their account'}export const auditAct = act => ACTS[act] || (act ? String(act) : '')diff --git a/website/api.html b/website/api.htmlindex 9880f5f9c..8919fbec9 100644--- a/website/api.html+++ b/website/api.html@@ -600,16 +600,14 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon<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/<uid>/</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>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/<uid>/</code>) and any Coach credential stored for them. Not reversible. The body carries the account's name, typed back by its owner, and the same proof as setting a password (see OwnerProof): a passkey assertion made for this request, or the current password while <code>PASSWORD_LOGIN</code> is on. The name and the last-admin rule are checked before the proof is asked. 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 and the proof it was made with; a refused proof as <code>auth.proof.fail</code> with <code>act: account-delete</code>.</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 <token></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">Request body <span class="p-hint">(JSON)</span></p>+<pre><code>{+ "name": "Ada",+ "current": "correct horse battery staple"+}</code></pre><p class="ep-h">Responses</p><div class="ptab"><div class="prow rrow">@@ -624,9 +622,17 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon<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>{"error":"not signed in"}</code></span></span></div>+ <div class="prow rrow">+ <span class="r-code s4">403</span>+ <span class="p-desc">No acceptable proof that the owner is here: <code>passkey-required</code> (no password that counts, because none is set or <code>PASSWORD_LOGIN</code> is off, so a passkey has to confirm), <code>passkey</code> (the assertion did not verify, belongs to another profile, or was made for another challenge, one handed out for another ceremony or one already used), <code>current-required</code> or <code>current-wrong</code>.<span class="r-sig"><code>{"error":"confirm with your passkey first"}</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>{"error":"the last admin cannot leave while other profiles remain"}</code></span></span>+ </div>+ <div class="prow rrow">+ <span class="r-code s4">429</span>+ <span class="p-desc">Paused by the sign-in throttle (see <i>Throttling</i> in the description). The request was not looked at; try again after <code>Retry-After</code> seconds.<span class="r-sig"><code>{"error":"too many attempts, try again later"}</code></span></span></div></div></div>