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
Recovery codes (#584): from an admin, or from the server's own command
Duarte Santosc907bdca37a3
diff --git a/api/Dockerfile b/api/Dockerfileindex 1efcd877c..400023cae 100644--- a/api/Dockerfile+++ b/api/Dockerfile@@ -53,7 +53,7 @@ RUN npm ci --omit=dev --omit=optional && npm cache clean --force# Every module server.js imports from the api root has to be named here: the image carries nothing# else, and one that is missing only shows at boot, as ERR_MODULE_NOT_FOUND.-COPY server.js push-messages.js nudge.js nudge-copy.js verify-error.js password.js rate-limit.js passkeys-store.js device-link.js media.js queue.js sync-stamps.js durable.js ./+COPY server.js push-messages.js nudge.js nudge-copy.js verify-error.js password.js rate-limit.js passkeys-store.js device-link.js media.js queue.js sync-stamps.js durable.js admin-socket.js recover.js ./COPY coach ./coachENV NODE_ENV=productionENV PORT=3000diff --git a/api/admin-socket.js b/api/admin-socket.jsnew file mode 100644index 000000000..eb6742294--- /dev/null+++ b/api/admin-socket.js@@ -0,0 +1,101 @@+/* The server's local admin socket (#584): how `node recover.js <name>` asks the running server for+ * a recovery code.+ *+ * Why a socket and not the file: the server keeps db.json in memory and writes all of it on every+ * change (saveDb). A second process editing db.json while the server runs would be overwritten by+ * the next save, or overwrite one the server just made. So the command never touches the data: it+ * asks the server, which makes the code through the same code path an admin's request takes, in+ * its own memory, and saves and audits it like any other change.+ *+ * Who may ask: whoever can open the socket. It is a Unix socket in a directory only this process's+ * user can enter (0700, checked: ours, not a symlink, nobody else's bits), the socket itself 0600.+ * In the Docker image that is root, which is who `docker compose exec api` runs as; the Coach's+ * jobs run as their own unprivileged user and cannot reach it, any more than they can read /data.+ * Being able to reach it is being able to read db.json anyway. Nothing listens on the network.+ *+ * The path is derived from the data directory, so two instances on one machine do not meet, and+ * recover.js finds it from the same environment the server has (DATA_DIR, or ADMIN_SOCKET_DIR).+ */+import fs from 'node:fs';+import net from 'node:net';+import os from 'node:os';+import path from 'node:path';+import crypto from 'node:crypto';++const MAX_LINE = 4096;++/** The directory the socket lives in: ADMIN_SOCKET_DIR, else a per-user, per-data-dir one in the temp dir. */+export function socketDir(env = process.env) {+ if (env.ADMIN_SOCKET_DIR) return env.ADMIN_SOCKET_DIR;+ const data = path.resolve(env.DATA_DIR || '/data');+ const tag = crypto.createHash('sha256').update(data).digest('hex').slice(0, 10);+ const uid = typeof process.getuid === 'function' ? process.getuid() : 'u';+ return path.join(os.tmpdir(), `opengym-admin-${uid}-${tag}`);+}+export const socketPath = (env = process.env) => path.join(socketDir(env), 'admin.sock');++/** Creates the directory 0700, or checks the one there is ours and private. Throws when it is not. */+export function privateDir(dir) {+ try { fs.mkdirSync(dir, { mode: 0o700 }); } catch (e) { if (e.code !== 'EEXIST') throw e; }+ const st = fs.lstatSync(dir);+ if (!st.isDirectory() || st.isSymbolicLink()) throw new Error(`${dir} is not a directory`);+ if (typeof process.getuid === 'function' && st.uid !== process.getuid()) throw new Error(`${dir} belongs to someone else`);+ if ((st.mode & 0o077) !== 0) throw new Error(`${dir} is open to others (mode ${(st.mode & 0o777).toString(8)})`);+ return dir;+}++/**+ * Listens on the socket. `handle(msg)` answers one request ({ cmd, ... }) with a plain object; each+ * connection carries one JSON line in and one out. Returns the server, or null when there is no+ * safe place for it (logged; the instance runs without the command then).+ */+export function startAdminSocket({ env = process.env, handle, log = console }) {+ if (process.platform === 'win32') return null;+ let file;+ try {+ privateDir(socketDir(env));+ file = socketPath(env);+ // A socket left by the previous process; only ever one of ours, in our private directory.+ try { if (fs.lstatSync(file).isSocket()) fs.unlinkSync(file); } catch { /* none */ }+ } catch (e) {+ log.error('admin socket: not started,', e.message);+ return null;+ }+ const server = net.createServer(conn => {+ let buf = '';+ conn.setTimeout(5000, () => conn.destroy());+ conn.on('error', () => {});+ conn.on('data', async chunk => {+ buf += chunk;+ if (buf.length > MAX_LINE) { conn.end(JSON.stringify({ error: 'request too long' }) + '\n'); return }+ const nl = buf.indexOf('\n');+ if (nl < 0) return;+ let out;+ try { out = await handle(JSON.parse(buf.slice(0, nl))); }+ catch (e) { out = { error: e instanceof SyntaxError ? 'not JSON' : 'server error' }; if (!(e instanceof SyntaxError)) log.error('admin socket:', e); }+ conn.end(JSON.stringify(out) + '\n');+ });+ });+ server.on('error', e => log.error('admin socket:', e.message));+ const old = process.umask(0o177);+ try { server.listen(file, () => { try { fs.chmodSync(file, 0o600); } catch { /* the umask already did */ } }); }+ finally { process.umask(old); }+ server.unref();+ return server;+}++/** One request to the running server: resolves with its answer. For recover.js. */+export function askAdminSocket(msg, { env = process.env, timeoutMs = 10000 } = {}) {+ return new Promise((resolve, reject) => {+ const conn = net.createConnection(socketPath(env));+ let buf = '';+ const timer = setTimeout(() => { conn.destroy(); reject(Object.assign(new Error('no answer'), { code: 'ETIMEDOUT' })) }, timeoutMs);+ conn.on('connect', () => conn.write(JSON.stringify(msg) + '\n'));+ conn.on('data', d => { buf += d });+ conn.on('end', () => {+ clearTimeout(timer);+ try { resolve(JSON.parse(buf)) } catch { reject(new Error('the server sent something unexpected')) }+ });+ conn.on('error', e => { clearTimeout(timer); reject(e) });+ });+}diff --git a/api/device-link.js b/api/device-link.jsindex dc66a769b..7b372b407 100644--- a/api/device-link.js+++ b/api/device-link.js@@ -11,12 +11,19 @@* - one per profile — a new one replaces the one before — good for DEVICE_LINK_TTL_MS, and gone* with the first passkey made with it. An expired one is dropped the next time links are read.*+ * A recovery code (#584) is the same kind of link, made by someone else for a person who has lost+ * every way in: an admin from the dashboard, or the server's own command (recover.js, through the+ * local admin socket). It carries `kind: 'recovery'` and who made it, and lives a day like an+ * admin's password reset code, because it has to reach the person first.+ ** Pure bookkeeping on `db.deviceLinks`; the routes, the throttle and the audit are server.js's. */import crypto from 'node:crypto';// Long enough to walk to the other device, find the camera and sign in; short enough that a code// photographed off a screen is dead by the time anyone could use it.export const DEVICE_LINK_TTL_MS = 10 * 60 * 1000;+// A recovery code is handed over by an admin, by message or in person: a day, like a reset code.+export const RECOVERY_TTL_MS = 24 * 3600 * 1000;const ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';const LENGTH = 12;@@ -33,12 +40,13 @@ function prune(db, now) {db.deviceLinks = (db.deviceLinks || []).filter(l => l && typeof l.h === 'string' && l.exp > now);}-// → { code, link }. The code is returned once and never stored.-export function createDeviceLink(db, userId, now = Date.now(), ttlMs = DEVICE_LINK_TTL_MS) {+// → { code, link }. The code is returned once and never stored. `extra` marks a recovery code:+// { kind: 'recovery', by } (who made it: an admin's id, or 'server').+export function createDeviceLink(db, userId, now = Date.now(), ttlMs = DEVICE_LINK_TTL_MS, extra = {}) {prune(db, now);db.deviceLinks = db.deviceLinks.filter(l => l.userId !== userId);const code = makeLinkCode();- const link = { h: hashLinkCode(code), userId, exp: now + ttlMs, created: now };+ const link = { h: hashLinkCode(code), userId, exp: now + ttlMs, created: now, ...(extra.kind === 'recovery' ? { kind: 'recovery', by: String(extra.by || 'server') } : {}) };db.deviceLinks.push(link);return { code, link };}@@ -66,3 +74,8 @@ export function dropDeviceLinks(db, userId) {db.deviceLinks = (db.deviceLinks || []).filter(l => l.userId !== userId);return db.deviceLinks.length !== before;}++// The live recovery code of a profile, if any (for the admin dashboard: "recovery code until").+export function recoveryLinkOf(db, userId, now = Date.now()) {+ return (db.deviceLinks || []).find(l => l && l.userId === userId && l.kind === 'recovery' && l.exp > now) || null;+}diff --git a/api/openapi.yaml b/api/openapi.yamlindex aee8eb459..e1471517b 100644--- a/api/openapi.yaml+++ b/api/openapi.yaml@@ -1112,6 +1112,67 @@ paths:'429': { $ref: '#/components/responses/TooManyRequests' }'503': { $ref: '#/components/responses/Busy' }+ /api/admin/user/recovery:+ post:+ tags: [admin, passkeys]+ operationId: adminRecoveryCode+ summary: 'Admin: make a one-time recovery code (#584)'+ description: |+ For someone who lost every way in, on any instance (with or without+ `PASSWORD_LOGIN`). Returns a code (12 characters from the pairing alphabet, 60 bits),+ shown once, stored only as a SHA-256, valid for 24 h. The person redeems it like a+ device link (`POST /api/device-link/options` and `/verify`): the device they use gets a+ new passkey for the profile and is signed in. Making it bumps the profile's session+ version (every session, pending pairing code and device link ends); passkeys and the+ password stay. A newer code replaces an older one.++ Any admin may make one for a profile that is not an admin; only the owner for an+ admin; nobody for the owner (403 `owner`: the owner uses the server command+ `node recover.js <name>`), for oneself (400 `self`) or for a disabled profile (400+ `disabled`). Audited as `admin.recovery.create`; a refusal for an admin as+ `admin.denied`.+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ required: [id]+ properties:+ id: { type: string, description: The user id. }+ responses:+ '200':+ description: The code, once.+ content:+ application/json:+ schema:+ type: object+ properties:+ ok: { type: boolean, const: true }+ name: { type: string }+ code: { type: string }+ expires: { type: number, description: Expiry (ms). }+ example: { ok: true, name: "Ada", code: "K7WQ-2MZP-4HXA", expires: 1790000000000 }+ '400':+ description: Oneself, or a disabled profile.+ content:+ application/json:+ schema: { $ref: '#/components/schemas/Error' }+ example: { error: "enable the account first", code: disabled }+ '401': { $ref: '#/components/responses/Unauthorized' }+ '403':+ description: Not an admin; an admin who is not the owner asking for an admin; or the target is the owner.+ content:+ application/json:+ schema: { $ref: '#/components/schemas/Error' }+ example: { error: "the owner recovers with the server command (recover.js)", code: owner }+ '404':+ description: No user with that id.+ content:+ application/json:+ schema: { $ref: '#/components/schemas/Error' }+ example: { error: "no such user" }+/api/admin/user/password-reset:post:tags: [admin, password]@@ -1429,6 +1490,7 @@ paths:options: { $ref: '#/components/schemas/WebAuthnRegistrationOptions' }id: { type: string, description: "The profile's id (also the options' user handle). Names are not unique; this is what tells two profiles apart." }name: { type: string, description: The profile this device is being added to. }+ recovery: { type: boolean, description: 'Present (true) when the code is a recovery code (POST /api/admin/user/recovery, recover.js).' }'400': { $ref: '#/components/responses/LinkInvalid' }'409': { $ref: '#/components/responses/PasskeyLimit' }'429': { $ref: '#/components/responses/TooManyRequests' }@@ -1442,8 +1504,10 @@ paths:Verifies the attestation against the challenge from step 1 (which must have beenmade for this very code), stores the passkey on the code's profile, burns the codeand sets the session cookie; the passkey just made is what signs the device in.- Of two requests racing with one code, one wins. Audited as `auth.link.ok`, and every- refusal as `auth.link.fail`. **Not** CSRF-exempt.+ Of two requests racing with one code, one wins. Audited as `auth.link.ok` (a recovery+ code as `auth.recovery.ok`), and every refusal as `auth.link.fail`. A recovery code+ also works on a profile at the passkey limit: the passkey used longest ago is removed+ to make room. **Not** CSRF-exempt.security: []requestBody:required: true@@ -3833,6 +3897,9 @@ components:resetUntil:oneOf: [{ type: number }, { type: 'null' }]description: PASSWORD_LOGIN instances only. Expiry (ms) of an unused reset code.+ recoveryUntil:+ oneOf: [{ type: number }, { type: 'null' }]+ description: Expiry (ms) of an unused recovery code (POST /api/admin/user/recovery, recover.js).unit: { type: string, enum: [kg, lb] }lastSync: { oneOf: [{ type: number }, { type: 'null' }] }routines:diff --git a/api/recover.js b/api/recover.jsnew file mode 100644index 000000000..dbdb065b9--- /dev/null+++ b/api/recover.js@@ -0,0 +1,51 @@+#!/usr/bin/env node+/* A one-time recovery code for a profile that lost every way in (#584), from the server itself:+ * for the owner, who nobody else can help, and for anyone else when there is no admin to ask.+ *+ * docker compose exec api node recover.js "Their name"+ * docker compose exec api node recover.js --id <profile id> when several share the name+ *+ * The person enters the code on the sign-in screen ("Lost access?" → "I have a code", or "Use a+ * code from your other device"); the device they enter it on gets a new passkey for the profile+ * and is signed in. The code works once, for a day; making it signs the profile out everywhere.+ *+ * This asks the running server (admin-socket.js): the server keeps its data in memory and would+ * overwrite any change made to db.json behind its back. Run it where the server runs, as the same+ * user (in the Docker image, `docker compose exec api` does exactly that).+ */+import { askAdminSocket, socketPath } from './admin-socket.js';++const args = process.argv.slice(2);+let id = null;+const words = [];+for (let i = 0; i < args.length; i++) {+ if (args[i] === '--id') id = args[++i] || null;+ else if (!args[i].startsWith('-')) words.push(args[i]);+}+const name = words.join(' ').trim();++if ((!name && !id) || args.includes('--help') || args.includes('-h')) {+ console.log('usage: node recover.js "<profile name>" | node recover.js --id <profile id>');+ process.exit(name || id ? 0 : 2);+}++try {+ const r = await askAdminSocket({ cmd: 'recover', ...(id ? { id } : { name }) });+ if (r.code) {+ console.log(`Recovery code for "${r.name}" (${r.id}${r.owner ? ', owner' : r.admin ? ', admin' : ''}):\n`);+ console.log(` ${r.code}\n`);+ console.log(`Valid once, until ${new Date(r.expires).toISOString()}. Every session of the profile has been signed out.`);+ console.log('On the sign-in screen: "Lost access?" -> "I have a code". The device gets a new passkey and is signed in.');+ process.exit(0);+ }+ console.error(r.error || 'the server did not make a code');+ for (const m of r.matches || []) console.error(` --id ${m.id} "${m.name}"${m.owner ? ' (owner)' : m.admin ? ' (admin)' : ''}, created ${m.created || 'unknown'}`);+ process.exit(1);+} catch (e) {+ if (e.code === 'ENOENT' || e.code === 'ECONNREFUSED') {+ console.error(`The openGym server is not running here (no ${socketPath()}). Start it first (docker compose up -d), then run this again inside it.`);+ } else {+ console.error('Could not ask the server:', e.message);+ }+ process.exit(1);+}diff --git a/api/server.js b/api/server.jsindex ff6b19f11..35a3a5e28 100644--- a/api/server.js+++ b/api/server.js@@ -30,7 +30,8 @@ import {listPasskeys, addPasskeyRecord, renamePasskeyRecord, removePasskeyRecord, passkeyRemovalRefused, MAX_PASSKEYS,transportsOf,} from './passkeys-store.js';-import { createDeviceLink, findDeviceLink, burnDeviceLink, dropDeviceLinks } from './device-link.js';+import { createDeviceLink, findDeviceLink, burnDeviceLink, dropDeviceLinks, recoveryLinkOf, RECOVERY_TTL_MS } from './device-link.js';+import { startAdminSocket } from './admin-socket.js';import { createMediaStore, mediaLimits, mediaConfig, MediaError, HASH_RE } from './media.js';import { effectiveRoutineId } from './queue.js';import { stampPut } from './sync-stamps.js';@@ -1673,6 +1674,23 @@ const passwordRoutes = {// The last admin may not delete their own profile while anyone else is on the instance: nobody// could run it from the app afterwards. Alone on it, they may go.const lastAdminLeaving = u => isAdmin(u) && db.users.length > 1 && db.users.filter(isAdmin).length <= 1;+// Makes a recovery code for `target` (#584): a device link that lives a day and says who made it+// (`by`: the admin, or null for the server's own command). Making it signs the profile out+// everywhere, as a password reset does: it is asked for when the devices are lost, and a lost phone+// should not stay signed in for the day the code is good. Pairing codes and device links go too.+// Passkeys and the password are left alone; the person removes the lost device's passkey in+// Settings once they are back. Saved and audited here, whoever asked.+function issueRecovery(req, target, by) {+ target.sv = sessionVersion(target) + 1;+ for (const [k, v] of pairings) if (v.uid === target.id) pairings.delete(k);+ dropDeviceLinks(db, target.id);+ presence.delete(target.id);+ const made = createDeviceLink(db, target.id, Date.now(), RECOVERY_TTL_MS, { kind: 'recovery', by: by ? by.id : 'server' });+ saveDb();+ audit(req, by ? 'admin.recovery.create' : 'server.recovery.create', { ...(by ? { user: by } : {}), target, msg: by ? null : 'recover.js' });+ return made;+}+const passkeyState = u => {const passkeys = listPasskeys(db, u.id);// `password`: whether the password can confirm an addition or a removal (proveOwner) — only@@ -1850,10 +1868,12 @@ const passkeyRoutes = {audit(req, 'auth.link.fail', { ok: false, uid: link.userId, msg: 'user-unavailable' });return json(res, 400, LINK_INVALID);}- if (passkeyCount(user) >= MAX_PASSKEYS) return json(res, 409, LIMIT);+ // A recovery code still works on a profile full of passkeys: the oldest unused one makes room+ // (verify below). The lost devices' passkeys are what fill it.+ if (link.kind !== 'recovery' && passkeyCount(user) >= MAX_PASSKEYS) return json(res, 409, LIMIT);const options = await moreOptions(user);const cid = putChallenge({ challenge: options.challenge, uid: user.id, kind: 'link', lh: link.h });- json(res, 200, { cid, options, id: user.id, name: user.name });+ json(res, 200, { cid, options, id: user.id, name: user.name, ...(link.kind === 'recovery' ? { recovery: true } : {}) });},// Step two: the new passkey is stored, the code is burned, and this device is signed in by the@@ -1884,6 +1904,13 @@ const passkeyRoutes = {audit(req, 'auth.link.fail', { ok: false, uid: link.userId, msg: 'link-invalid' });return json(res, 400, LINK_INVALID);}+ const recovery = link.kind === 'recovery';+ // Recovery on a full profile: the passkey used longest ago goes, to make room for this one.+ let dropped = null;+ if (recovery && passkeyCount(user) >= MAX_PASSKEYS) {+ const oldest = listPasskeys(db, user.id).slice().sort((a, b) => String(a.lastUsed || a.created || '').localeCompare(String(b.lastUsed || b.created || '')))[0];+ if (oldest && !removePasskeyRecord(db, user.id, oldest.id, 1).error) dropped = oldest;+ }const added = addPasskeyRecord(db, user.id, cred);if (added.error) {audit(req, 'auth.link.fail', { ok: false, user, msg: added.code });@@ -1892,7 +1919,7 @@ const passkeyRoutes = {added.row.lastUsed = added.row.created;burnDeviceLink(db, link);saveDb();- audit(req, 'auth.link.ok', { user, msg: added.row.name || null });+ audit(req, recovery ? 'auth.recovery.ok' : 'auth.link.ok', { user, msg: [added.row.name, dropped && `replaced ${dropped.name || 'a passkey'}`].filter(Boolean).join(', ') || null });json(res, 200, { user: publicUser(user) }, { 'Set-Cookie': sessionCookie(user) });}};@@ -2671,7 +2698,9 @@ const routes = {id: u.id, name: u.name, created: u.created || null, disabled: !!u.disabled, admin: isAdmin(u), owner: isOwner(u), invitedBy: u.invitedBy || null,// Only on an instance with password sign-in: whether they have one, and until when an// unused reset code is good.- ...(PASSWORD_LOGIN ? { password: hasPassword(u), email: u.email || null, resetUntil: u.pwReset?.exp > Date.now() ? u.pwReset.exp : null } : {})+ ...(PASSWORD_LOGIN ? { password: hasPassword(u), email: u.email || null, resetUntil: u.pwReset?.exp > Date.now() ? u.pwReset.exp : null } : {}),+ // Until when an unused recovery code is good (#584), on every instance.+ recoveryUntil: recoveryLinkOf(db, u.id)?.exp || null},unit: S.unit || 'kg',lastSync: lastSyncOf(u, S),@@ -2683,6 +2712,25 @@ const routes = {});},+ // A recovery code (#584): for someone who lost every way in, on any instance, password sign-in+ // or not. The person enters it on the sign-in screen, and the device they use gets a new passkey+ // for the profile (POST /api/device-link/*, the same redemption a device link has). Who may make+ // one for whom: any admin for a profile that is not an admin; the owner for an admin; nobody here+ // for the owner, who uses the server's own command (recover.js), since no one else may take over+ // the owner's login. Not for oneself, and not for a disabled profile. See issueRecovery.+ 'POST /api/admin/user/recovery': 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 are signed in: add a passkey in Settings instead', code: 'self' });+ if (isOwner(u)) return json(res, 403, { error: 'the owner recovers with the server command (recover.js)', code: 'owner' });+ if (isAdmin(u) && !isOwner(admin)) { audit(req, 'admin.denied', { ok: false, user: admin, target: u, msg: 'recovery' }); return json(res, 403, { error: 'only the owner can make a recovery code for an admin' }); }+ if (u.disabled) return json(res, 400, { error: 'enable the account first', code: 'disabled' });+ const { code, link } = issueRecovery(req, u, admin);+ json(res, 200, { ok: true, name: u.name, code, expires: link.exp });+ },+'POST /api/admin/user/disable': async (req, res) => {const admin = requireAdmin(req, res); if (!admin) return;const body = await readBody(req);@@ -2978,3 +3026,23 @@ server.headersTimeout = 60000;// (the tests spawn the server that way, and so does anyone running two instances on one box) has// no other way to learn it.server.listen(PORT, () => console.log(`gym-api on :${server.address().port} (rpID=${RP_ID}, origin=${ORIGIN})`));++// The server's own command for a locked-out owner or admin (#584, recover.js): asked over a local+// socket only this process's user can open (admin-socket.js explains why not by editing db.json).+// One command: a recovery code for a profile named, or picked by id when several share the name.+const CLI_REQ = { headers: {}, socket: {} };+startAdminSocket({+ handle: async msg => {+ if (!msg || msg.cmd !== 'recover') return { error: 'unknown command' };+ const id = typeof msg.id === 'string' ? msg.id : null;+ const k = nameKey(typeof msg.name === 'string' ? msg.name : '');+ const found = id ? db.users.filter(u => u.id === id) : k ? db.users.filter(u => nameKey(u.name) === k || u.email === k) : [];+ const row = u => ({ id: u.id, name: u.name, created: u.created || null, admin: isAdmin(u), owner: isOwner(u) });+ if (!found.length) return { error: id ? 'no profile with that id' : 'no profile with that name' };+ if (found.length > 1) return { error: 'several profiles have that name: pick one with --id', matches: found.map(row) };+ const u = found[0];+ if (u.disabled) return { error: 'that profile is disabled: enable it in the admin dashboard first' };+ const { code, link } = issueRecovery(CLI_REQ, u, null);+ return { ...row(u), code, expires: link.exp };+ }+});diff --git a/api/test/server-recovery.test.js b/api/test/server-recovery.test.jsnew file mode 100644index 000000000..8da0abb6d--- /dev/null+++ b/api/test/server-recovery.test.js@@ -0,0 +1,178 @@+/* Recovery codes (#584): for someone who lost every way in, on any instance. An admin makes one in+ the dashboard (any admin for a profile that is not an admin, the owner for an admin, nobody for+ the owner), or the server's own command does (recover.js, through the local admin socket, for+ anyone, the owner included). The person redeems it like a device link: the device gets a new+ passkey and is signed in. One-time, a day, hashed at rest, counted like a reset code. */+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, execFile } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { hashLinkCode } from '../device-link.js';+import { MAX_PASSKEYS } from '../passkeys-store.js';+import { boundPort } from './helpers.mjs';+import { softPasskey, ORIGIN } from './soft-passkey.mjs';++const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');+const SECRET = crypto.randomBytes(32).toString('hex');+const mintSession = (uid, sv = 0) => {+ const payload = `${uid}:${Date.now() + 86400000}:${sv}`;+ return 'gymsid=' + payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');+};+const CODE = /^[A-HJ-NP-Z2-9]{4}-[A-HJ-NP-Z2-9]{4}-[A-HJ-NP-Z2-9]{4}$/;++async function startServer(t, { env = {}, users = [], creds = [] } = {}) {+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-rec-'));+ fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });+ fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ users, creds, subs: [], invites: [] }));+ // Password sign-in OFF: recovery has to work without it.+ const childEnv = { ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN, RP_ID: 'localhost', PASSWORD_LOGIN: '', TRUST_PROXY: '1', INVITE_ONLY: '', ADMIN_UIDS: '', AUDIT_LOG: '1', ...env };+ const child = spawn(process.execPath, ['server.js'], { cwd: API, stdio: ['ignore', 'pipe', 'pipe'], env: childEnv });+ const h = { api: '', log: '', dataDir, env: childEnv, child };+ 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.api = `http://127.0.0.1:${await boundPort(child, () => h.log)}`;+ h.req = async (method, p, { body, cookie, ip = '198.51.100.1' } = {}) => {+ const r = await fetch(`${h.api}${p}`, {+ method,+ headers: { 'Content-Type': 'application/json', 'Sec-Fetch-Site': 'same-origin', 'X-Forwarded-For': ip, ...(cookie ? { Cookie: cookie } : {}) },+ body: body === undefined ? undefined : JSON.stringify(body)+ });+ const setCookie = r.headers.getSetCookie().find(c => c.startsWith('gymsid=') && !c.startsWith('gymsid=;'));+ return { status: r.status, body: await r.json(), cookie: setCookie ? setCookie.split(';')[0] : null };+ };+ h.db = () => JSON.parse(fs.readFileSync(path.join(dataDir, 'db.json'), 'utf8'));+ h.audit = () => { try { return fs.readFileSync(path.join(dataDir, 'audit.log'), 'utf8').trim().split('\n').map(l => JSON.parse(l)); } catch { return []; } };+ // The server's own command, run the way `docker compose exec api node recover.js` runs it.+ h.cli = (...args) => new Promise(resolve => execFile(process.execPath, ['recover.js', ...args], { cwd: API, env: childEnv }, (err, stdout, stderr) => resolve({ code: err ? err.code : 0, out: stdout, err: stderr })));+ return h;+}+const user = (id, name, extra = {}) => ({ id, name, created: new Date().toISOString(), ...extra });+const OWNER = user('o1', 'Olga', { admin: true, owner: true });+const ADMIN = user('a1', 'Arne', { admin: true });+const ANA = user('u1', 'Ana');+const BEA = user('u2', 'Bea');++async function redeem(h, code, fresh, ip = '198.51.100.9', name = 'New phone') {+ const opt = await h.req('POST', '/api/device-link/options', { body: { code }, ip });+ if (opt.status !== 200) return { opt };+ const done = await h.req('POST', '/api/device-link/verify', { body: { code, cid: opt.body.cid, credential: fresh.attestation(opt.body.options.challenge), name }, ip });+ return { opt, done };+}++test('an admin makes a recovery code on an instance without password sign-in; it adds a passkey once and signs the device in', async t => {+ const lost = softPasskey(), fresh = softPasskey();+ const h = await startServer(t, { users: [OWNER, ADMIN, ANA], creds: [lost.row('u1')] });+ const made = await h.req('POST', '/api/admin/user/recovery', { body: { id: 'u1' }, cookie: mintSession('a1') });+ assert.equal(made.status, 200);+ assert.match(made.body.code, CODE);+ assert.equal(made.body.name, 'Ana');+ assert.ok(made.body.expires > Date.now() + 23 * 3600000 && made.body.expires <= Date.now() + 24 * 3600000);+ // Kept only as a hash, marked as a recovery code and by whom.+ const raw = fs.readFileSync(path.join(h.dataDir, 'db.json'), 'utf8');+ assert.doesNotMatch(raw, new RegExp(made.body.code.replace(/-/g, '')));+ assert.deepEqual(h.db().deviceLinks.map(l => [l.userId, l.h, l.kind, l.by]), [['u1', hashLinkCode(made.body.code), 'recovery', 'a1']]);+ // Every session of the profile ends.+ assert.equal((await h.req('GET', '/api/me', { cookie: mintSession('u1') })).status, 401);+ assert.ok(h.audit().some(e => e.ev === 'admin.recovery.create' && e.uid === 'a1' && e.tgt === 'u1'));+ // The dashboard says until when it is good.+ const drill = await h.req('GET', '/api/admin/user?id=u1', { cookie: mintSession('a1') });+ assert.equal(drill.body.user.recoveryUntil, made.body.expires);++ const { opt, done } = await redeem(h, made.body.code.toLowerCase().replace(/-/g, ' '), fresh);+ assert.equal(opt.body.recovery, true);+ assert.equal(opt.body.name, 'Ana');+ assert.equal(done.status, 200);+ assert.equal(done.body.user.id, 'u1');+ assert.ok(done.cookie, 'signed in');+ assert.deepEqual(h.db().creds.filter(c => c.userId === 'u1').map(c => c.id).sort(), [lost.id, fresh.id].sort());+ assert.ok(h.audit().some(e => e.ev === 'auth.recovery.ok' && e.uid === 'u1'));+ assert.equal(h.db().deviceLinks.length, 0, 'burned');+ assert.equal((await redeem(h, made.body.code, softPasskey())).opt.body.code, 'link-invalid', 'once only');+ assert.equal((await h.req('GET', '/api/admin/user?id=u1', { cookie: mintSession('a1') })).body.user.recoveryUntil, null);+});++test('who may make one for whom', async t => {+ const h = await startServer(t, { users: [OWNER, ADMIN, user('a2', 'Ada', { admin: true }), ANA, user('u3', 'Cy', { disabled: true })] });+ const ask = (by, id) => h.req('POST', '/api/admin/user/recovery', { body: { id }, cookie: mintSession(by) });+ assert.equal((await ask('u1', 'u3')).status, 403, 'not an admin');+ assert.equal((await ask('a1', 'a2')).status, 403, 'an admin for another admin');+ assert.ok(h.audit().some(e => e.ev === 'admin.denied' && e.uid === 'a1' && e.tgt === 'a2'));+ assert.equal((await ask('a1', 'o1')).body.code, 'owner', 'nobody for the owner here');+ assert.equal((await ask('o1', 'o1')).body.code, 'self');+ assert.equal((await ask('a1', 'a1')).body.code, 'self');+ assert.equal((await ask('a1', 'u3')).body.code, 'disabled');+ assert.equal((await ask('a1', 'nope')).status, 404);+ assert.equal((await ask('o1', 'a2')).status, 200, 'the owner for an admin');+ assert.equal((await ask('a1', 'u1')).status, 200, 'any admin for a plain profile');+});++test('a wrong code says nothing about anyone, and is counted like a reset code', async t => {+ const h = await startServer(t, { users: [OWNER, ANA] });+ await h.req('POST', '/api/admin/user/recovery', { body: { id: 'u1' }, cookie: mintSession('o1') });+ const ip = '198.51.100.77';+ const statuses = [];+ for (let i = 0; i < 22; i++) statuses.push((await h.req('POST', '/api/device-link/options', { body: { code: 'AAAA-AAAA-AAA' + (i % 9 + 2) }, ip })).status);+ assert.deepEqual([...new Set(statuses.slice(0, 20))], [400]);+ assert.equal(statuses.at(-1), 429, 'the address is paused');+ const one = await h.req('POST', '/api/device-link/options', { body: { code: 'BBBB-BBBB-BBBB' }, ip: '198.51.100.78' });+ assert.deepEqual(one.body, { error: 'that code is wrong, used or expired', code: 'link-invalid' });+});++test('a profile full of passkeys still gets back in: the one used longest ago makes room', async t => {+ const keys = Array.from({ length: MAX_PASSKEYS }, () => softPasskey());+ const rows = keys.map((k, i) => k.row('u1', { name: 'Key ' + i, lastUsed: new Date(Date.UTC(2026, 0, 1 + i)).toISOString() }));+ const h = await startServer(t, { users: [OWNER, ANA], creds: rows });+ const { body } = await h.req('POST', '/api/admin/user/recovery', { body: { id: 'u1' }, cookie: mintSession('o1') });+ const fresh = softPasskey();+ const { opt, done } = await redeem(h, body.code, fresh);+ assert.equal(opt.status, 200);+ assert.equal(done.status, 200);+ const ids = h.db().creds.filter(c => c.userId === 'u1').map(c => c.id);+ assert.equal(ids.length, MAX_PASSKEYS);+ assert.ok(ids.includes(fresh.id));+ assert.ok(!ids.includes(keys[0].id), 'Key 0 was the oldest');+ assert.ok(h.audit().some(e => e.ev === 'auth.recovery.ok' && /replaced Key 0/.test(e.msg || '')));+});++test('recover.js asks the running server for the owner’s code, by name or by id', async t => {+ const fresh = softPasskey();+ const h = await startServer(t, { users: [OWNER, ADMIN, ANA, user('u9', 'Ana')] });+ const r = await h.cli('Olga');+ assert.equal(r.code, 0, r.err);+ const code = r.out.match(/[A-HJ-NP-Z2-9]{4}-[A-HJ-NP-Z2-9]{4}-[A-HJ-NP-Z2-9]{4}/)?.[0];+ assert.ok(code, r.out);+ assert.match(r.out, /owner/);+ assert.deepEqual(h.db().deviceLinks.map(l => [l.userId, l.kind, l.by]), [['o1', 'recovery', 'server']]);+ assert.ok(h.audit().some(e => e.ev === 'server.recovery.create' && e.tgt === 'o1'));+ assert.equal((await redeem(h, code, fresh)).done.body.user.id, 'o1');++ const two = await h.cli('ana');+ assert.equal(two.code, 1);+ assert.match(two.err, /--id u1/);+ assert.match(two.err, /--id u9/);+ const byId = await h.cli('--id', 'u9');+ assert.equal(byId.code, 0, byId.err);+ assert.equal(h.db().deviceLinks.find(l => l.userId === 'u9')?.kind, 'recovery');++ assert.equal((await h.cli('Nobody')).code, 1);+ assert.equal((await h.cli()).code, 2);+});++test('the admin socket is private, and recover.js says so when no server runs', async t => {+ const h = await startServer(t, { users: [OWNER] });+ const { socketDir, socketPath } = await import('../admin-socket.js');+ const dir = socketDir(h.env);+ const st = fs.statSync(dir);+ assert.equal(st.mode & 0o777, 0o700);+ assert.equal(fs.statSync(socketPath(h.env)).mode & 0o777, 0o600);+ h.child.kill('SIGKILL');+ await new Promise(r => h.child.once('exit', r));+ const r = await h.cli('Olga');+ assert.equal(r.code, 1);+ assert.match(r.err, /not running|Could not ask/);+});diff --git a/api/test/soft-passkey.mjs b/api/test/soft-passkey.mjsnew file mode 100644index 000000000..e0fb03904--- /dev/null+++ b/api/test/soft-passkey.mjs@@ -0,0 +1,60 @@+/* A software passkey for the api tests: what navigator.credentials.create() and .get() hand back+ * for a P-256 key, serialised the way the app sends them. Shared by the recovery tests; the same+ * as the one in server-passkeys.test.js. */+import crypto from 'node:crypto';++export const ORIGIN = 'http://localhost:8080';+const b64u = b => Buffer.from(b).toString('base64url');+const sha = b => crypto.createHash('sha256').update(b).digest();++const mintSession = (uid, sv = 0) => {+ const payload = `${uid}:${Date.now() + 86400000}:${sv}`;+ return 'gymsid=' + payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');+};++// Just enough CBOR for an attestation object: a map of text keys to text, bytes or an empty map.+const cborHead = (major, n) => n < 24 ? Buffer.from([(major << 5) | n])+ : n < 256 ? Buffer.from([(major << 5) | 24, n]) : Buffer.from([(major << 5) | 25, n >> 8, n & 255]);+const cborText = s => Buffer.concat([cborHead(3, Buffer.byteLength(s)), Buffer.from(s)]);+const cborBytes = b => Buffer.concat([cborHead(2, b.length), b]);++export function softPasskey() {+ const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', { namedCurve: 'P-256' });+ const jwk = publicKey.export({ format: 'jwk' });+ const cose = Buffer.concat([+ Buffer.from([0xa5, 0x01, 0x02, 0x03, 0x26, 0x20, 0x01, 0x21, 0x58, 0x20]), Buffer.from(jwk.x, 'base64url'),+ Buffer.from([0x22, 0x58, 0x20]), Buffer.from(jwk.y, 'base64url')+ ]);+ const raw = crypto.randomBytes(16);+ const id = b64u(raw);+ let counter = 0;+ return {+ id,+ row: (userId, extra = {}) => ({ id, userId, publicKey: cose.toString('base64url'), counter: 0, transports: ['internal'], ...extra }),+ // What navigator.credentials.create() hands back, serialised the way lib/api.js does.+ attestation(challenge, { origin = ORIGIN } = {}) {+ const clientDataJSON = Buffer.from(JSON.stringify({ type: 'webauthn.create', challenge, origin, crossOrigin: false }));+ const len = Buffer.from([raw.length >> 8, raw.length & 255]);+ const authData = Buffer.concat([sha('localhost'), Buffer.from([0x45]), Buffer.alloc(4), Buffer.alloc(16), len, raw, cose]);+ const attestationObject = Buffer.concat([+ Buffer.from([0xa3]), cborText('fmt'), cborText('none'), cborText('attStmt'), Buffer.from([0xa0]),+ cborText('authData'), cborBytes(authData)+ ]);+ return {+ id, rawId: id, type: 'public-key', clientExtensionResults: {}, authenticatorAttachment: 'platform',+ response: { clientDataJSON: b64u(clientDataJSON), attestationObject: b64u(attestationObject), transports: ['internal', 'hybrid'] }+ };+ },+ assertion(challenge) {+ const clientDataJSON = Buffer.from(JSON.stringify({ type: 'webauthn.get', challenge, origin: ORIGIN, crossOrigin: false }));+ const c = Buffer.alloc(4); c.writeUInt32BE(++counter);+ const authData = Buffer.concat([sha('localhost'), Buffer.from([0x05]), c]);+ const signature = crypto.sign('sha256', Buffer.concat([authData, sha(clientDataJSON)]), privateKey);+ return {+ id, rawId: id, type: 'public-key', clientExtensionResults: {}, authenticatorAttachment: 'platform',+ response: { clientDataJSON: b64u(clientDataJSON), authenticatorData: b64u(authData), signature: b64u(signature), userHandle: null }+ };+ }+ };+}+diff --git a/website/api.html b/website/api.htmlindex 2b4371e6e..ebf9fc4d8 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>73 endpoints</span>+ <span>74 endpoints</span><span>AGPL-3.0-or-later</span></p>@@ -1423,7 +1423,7 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon<div class="ptab"><div class="prow rrow"><span class="r-code s2">200</span>- <span class="p-desc">Ceremony options.<span class="r-sig">{ cid: string, options: <a href="#schema-WebAuthnRegistrationOptions">WebAuthnRegistrationOptions</a>, id: string, name: string }</span></span>+ <span class="p-desc">Ceremony options.<span class="r-sig">{ cid: string, options: <a href="#schema-WebAuthnRegistrationOptions">WebAuthnRegistrationOptions</a>, id: string, name: string, recovery: boolean }</span></span></div><div class="prow rrow"><span class="r-code s4">400</span>@@ -1449,7 +1449,7 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon<span class="ep-sum">Redeem a device link (step 2): store the passkey and sign this device in</span></summary><div class="ep-body">-<p>Verifies the attestation against the challenge from step 1 (which must have been made for this very code), stores the passkey on the code's profile, burns the code and sets the session cookie; the passkey just made is what signs the device in. Of two requests racing with one code, one wins. Audited as <code>auth.link.ok</code>, and every refusal as <code>auth.link.fail</code>. <b>Not</b> CSRF-exempt.</p>+<p>Verifies the attestation against the challenge from step 1 (which must have been made for this very code), stores the passkey on the code's profile, burns the code and sets the session cookie; the passkey just made is what signs the device in. Of two requests racing with one code, one wins. Audited as <code>auth.link.ok</code> (a recovery code as <code>auth.recovery.ok</code>), and every refusal as <code>auth.link.fail</code>. A recovery code also works on a profile at the passkey limit: the passkey used longest ago is removed to make room. <b>Not</b> CSRF-exempt.</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>Public: no authentication required.</span></p><p class="ep-h">Request body <span class="p-hint">(JSON)</span></p><div class="ptab">@@ -2564,6 +2564,51 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon<p class="sub">Admin dashboard. Requires an admin session (<code>ADMIN_UIDS</code> or <code>admin:true</code>)</p><div class="eps">+<details class="ep" id="op-adminRecoveryCode">+ <summary>+ <span class="m post">POST</span>+ <span class="ep-path"><code>/api/admin/user/recovery</code><span class="ep-chip admin">admin</span></span>+ <span class="ep-chev" aria-hidden="true"></span>+ <span class="ep-sum">Make a one-time recovery code (#584)</span>+ </summary>+ <div class="ep-body">+<p>For someone who lost every way in, on any instance (with or without <code>PASSWORD_LOGIN</code>). Returns a code (12 characters from the pairing alphabet, 60 bits), shown once, stored only as a SHA-256, valid for 24 h. The person redeems it like a device link (<code>POST /api/device-link/options</code> and <code>/verify</code>): the device they use gets a new passkey for the profile and is signed in. Making it bumps the profile's session version (every session, pending pairing code and device link ends); passkeys and the password stay. A newer code replaces an older one.</p>+<p>Any admin may make one for a profile that is not an admin; only the owner for an admin; nobody for the owner (403 <code>owner</code>: the owner uses the server command <code>node recover.js <name></code>), for oneself (400 <code>self</code>) or for a disabled profile (400 <code>disabled</code>). Audited as <code>admin.recovery.create</code>; a refusal for an admin as <code>admin.denied</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>Admin only: a signed-in session whose user is an admin (<code>ADMIN_UIDS</code> or <code>admin:true</code>), as the session cookie or a Bearer token.</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">id<em class="p-req" title="required">required</em></span>+ <span class="p-type">string</span>+ <span class="p-desc">The user id.</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 code, once.<span class="r-sig">{ ok: always true, name: string, code: string, expires: number }</span></span>+ </div>+ <div class="prow rrow">+ <span class="r-code s4">400</span>+ <span class="p-desc">Oneself, or a disabled profile.<span class="r-sig"><code>{"error":"enable the account first"}</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>{"error":"not signed in"}</code></span></span>+ </div>+ <div class="prow rrow">+ <span class="r-code s4">403</span>+ <span class="p-desc">Not an admin; an admin who is not the owner asking for an admin; or the target is the owner.<span class="r-sig"><code>{"error":"the owner recovers with the server command (recover.js)"}</code></span></span>+ </div>+ <div class="prow rrow">+ <span class="r-code s4">404</span>+ <span class="p-desc">No user with that id.<span class="r-sig"><code>{"error":"no such user"}</code></span></span>+ </div>+ </div>+ </div>+</details>+<details class="ep" id="op-adminPasswordReset"><summary><span class="m post">POST</span>@@ -4517,6 +4562,11 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon<span class="p-type">number | null</span><span class="p-desc">PASSWORD_LOGIN instances only. Expiry (ms) of an unused reset code.</span></div>+ <div class="prow">+ <span class="p-name">user.recoveryUntil</span>+ <span class="p-type">number | null</span>+ <span class="p-desc">Expiry (ms) of an unused recovery code (POST /api/admin/user/recovery, recover.js).</span>+ </div><div class="prow"><span class="p-name">unit</span><span class="p-type">"kg" | "lb"</span>