Merge fix/api-admin: QA round 2026-09-19 (dev team)
This commit is contained in:
commit
6a86f54e4c
7 files changed
+379
-36
No files matched your search
+17
-7
@@ -50,7 +50,11 @@ info:
|
||||
- Errors are always `{"error": "<human-readable message>"}`.
|
||||
- Unknown method+path pairs return `404 {"error":"not found"}`; an unhandled
|
||||
exception returns `500 {"error":"server error"}`.
|
||||
- Request bodies are parsed as JSON regardless of Content-Type; max 5 MiB.
|
||||
- Request bodies are parsed as JSON regardless of Content-Type. A body that does
|
||||
not parse, or parses to anything but an object (`null`, a string, an array), is
|
||||
`400 {"error":"invalid json"}` on every route that reads one; an empty body counts
|
||||
as `{}`. A body over 5 MiB is `413 {"error":"body too large"}`; the rest of the
|
||||
upload is discarded so the answer reaches the client.
|
||||
- CORS: the request's `Origin` is reflected in `Access-Control-Allow-Origin`
|
||||
**without** `Allow-Credentials` — cross-origin callers can only ever
|
||||
authenticate with a Bearer token, never with the cookie.
|
||||
@@ -556,8 +560,10 @@ paths:
|
||||
- type: 'null'
|
||||
'400':
|
||||
description: >-
|
||||
`state` missing or not an object, or `workouts`/`routines` set to anything
|
||||
other than an array or null.
|
||||
`state` missing or not an object, `state` an array, or `workouts`/`routines`
|
||||
set to anything other than an array or null. Entries inside those two arrays
|
||||
that are not objects (`null`, numbers, nested arrays) are dropped before the
|
||||
write rather than refused, so a client with a damaged copy still syncs.
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: '#/components/schemas/Error' }
|
||||
@@ -725,7 +731,8 @@ paths:
|
||||
operationId: pushRestTimer
|
||||
summary: Schedule a server-side rest-timer push
|
||||
description: |
|
||||
Schedules one push after `seconds` (clamped to 1–3600). One pending timer per
|
||||
Schedules one push after `seconds` (a number or numeric string ≥ 1, clamped to
|
||||
3600). One pending timer per
|
||||
device — `deviceId`, the same token the subscription was registered with; a
|
||||
new call from the same device replaces it, and the push goes only to that
|
||||
device's subscriptions. Without a `deviceId` there is one timer per account
|
||||
@@ -733,9 +740,6 @@ paths:
|
||||
on rest start/extend and cancels on skip or on-screen completion — the push
|
||||
only actually fires when the tab was backgrounded/suspended and never got to
|
||||
cancel it. Timers live in memory: an API restart drops them.
|
||||
|
||||
Note: the documented `400 seconds required` exists in the code but is
|
||||
unreachable — the clamp turns any missing/invalid value into 1.
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
@@ -759,6 +763,12 @@ paths:
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: '#/components/schemas/Ok' }
|
||||
'400':
|
||||
description: '`seconds` missing, not numeric, or below 1. Nothing is scheduled.'
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: '#/components/schemas/Error' }
|
||||
example: { error: "seconds required" }
|
||||
'401': { $ref: '#/components/responses/Unauthorized' }
|
||||
|
||||
/api/push/rest-timer/cancel:
|
||||
|
||||
+63
-14
@@ -513,21 +513,53 @@ function json(res, code, obj, extraHeaders) {
|
||||
res.writeHead(code, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', ...(extraHeaders || {}) });
|
||||
res.end(body);
|
||||
}
|
||||
// A request the caller got wrong. The catch-all at the bottom answers it with this status and
|
||||
// message and does not log it: three of the routes below are reachable without a session, and a
|
||||
// stack trace per malformed body would let anyone fill the container log with noise that looks
|
||||
// like a crash. Anything else that escapes a handler is still a real 500 and still logged.
|
||||
class HttpError extends Error {
|
||||
constructor(status, message) { super(message); this.status = status; }
|
||||
}
|
||||
function readBody(req) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let size = 0; const chunks = [];
|
||||
let size = 0, over = false; const chunks = [];
|
||||
req.on('data', d => {
|
||||
size += d.length;
|
||||
if (size > MAX_BODY) { reject(new Error('body too large')); req.destroy(); return; }
|
||||
if (over) {
|
||||
// The 413 is already on its way. The rest of the upload is read and thrown away rather
|
||||
// than the socket destroyed under it: closing with unread bytes on the wire makes the
|
||||
// kernel send a reset, and a client (node's own http client included) that hits the
|
||||
// reset before it has parsed the answer reports a dropped connection instead of the
|
||||
// 413. A client that keeps streaming past twice the cap is not a mistaken one, and is
|
||||
// cut off.
|
||||
if (size > 2 * MAX_BODY) req.destroy();
|
||||
return;
|
||||
}
|
||||
if (size > MAX_BODY) {
|
||||
over = true; chunks.length = 0;
|
||||
reject(new HttpError(413, 'body too large'));
|
||||
return;
|
||||
}
|
||||
chunks.push(d);
|
||||
});
|
||||
req.on('end', () => {
|
||||
try { resolve(chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {}); }
|
||||
catch { reject(new Error('bad json')); }
|
||||
if (over) return;
|
||||
if (!chunks.length) return resolve({});
|
||||
let body;
|
||||
try { body = JSON.parse(Buffer.concat(chunks).toString('utf8')); }
|
||||
catch { return reject(new HttpError(400, 'invalid json')); }
|
||||
// Every handler reads fields off the result, so a JSON `null`, string, number or array is
|
||||
// as much a client mistake as unparseable text — refused once here rather than dereferenced
|
||||
// (and turned into a TypeError) in each route.
|
||||
if (!body || typeof body !== 'object' || Array.isArray(body)) return reject(new HttpError(400, 'invalid json'));
|
||||
resolve(body);
|
||||
});
|
||||
req.on('error', reject);
|
||||
});
|
||||
}
|
||||
// A caller-supplied field that is meant to be text. String() alone is not safe on a parsed body:
|
||||
// `{"code":{"toString":1}}` is valid JSON and String() throws on it.
|
||||
const text = v => (typeof v === 'string' ? v : typeof v === 'number' ? String(v) : '');
|
||||
const b64uToBuf = s => Buffer.from(s, 'base64url');
|
||||
|
||||
/* ---------- live presence (in-memory) ---------- */
|
||||
@@ -658,9 +690,9 @@ const routes = {
|
||||
|
||||
'POST /api/register/options': async (req, res) => {
|
||||
const body = await readBody(req);
|
||||
const name = String(body.name || '').trim().slice(0, 40);
|
||||
const name = text(body.name).trim().slice(0, 40);
|
||||
if (!name) return json(res, 400, { error: 'name required' });
|
||||
const code = String(body.code || '').trim().toUpperCase();
|
||||
const code = text(body.code).trim().toUpperCase();
|
||||
if (INVITE_ONLY && !db.invites.some(i => i.code === code && !i.usedBy && !i.revoked)) {
|
||||
// The rejected code itself is never recorded — a near-miss guess in the log is a liability.
|
||||
audit(req, 'auth.register.denied', { ok: false, name, msg: 'invite-rejected' });
|
||||
@@ -830,7 +862,7 @@ const routes = {
|
||||
// the code IS the credential, one-shot and 5-minute-lived like a WebAuthn challenge.
|
||||
'POST /api/pair/redeem': async (req, res) => {
|
||||
const body = await readBody(req);
|
||||
const code = String(body.code || '').trim().toUpperCase();
|
||||
const code = text(body.code).trim().toUpperCase();
|
||||
const p = pairings.get(code);
|
||||
if (p) pairings.delete(code);
|
||||
if (!p || p.exp < Date.now()) {
|
||||
@@ -871,9 +903,17 @@ const routes = {
|
||||
if (!body.state || typeof body.state !== 'object') return json(res, 400, { error: 'state required' });
|
||||
// The reminder tick and the admin routes iterate these two on the server's side, so a truthy
|
||||
// non-array would throw there on every pass for as long as it sat on disk. Absent or null is
|
||||
// fine — every client fills its own defaults.
|
||||
// fine — every client fills its own defaults. An array is `typeof 'object'` but no document:
|
||||
// `_rev` set on it is dropped by JSON.stringify, so the file would read back as rev 0 while
|
||||
// the response claimed the next revision.
|
||||
const list = v => v == null || Array.isArray(v);
|
||||
if (!list(body.state.workouts) || !list(body.state.routines)) return json(res, 400, { error: 'invalid state' });
|
||||
if (Array.isArray(body.state) || !list(body.state.workouts) || !list(body.state.routines)) return json(res, 400, { error: 'invalid state' });
|
||||
// The same readers dereference every entry (`w.d`, `w.name`), so a null or non-object entry
|
||||
// would throw there — and blank the admin's drill-down of this profile. Dropped, not refused:
|
||||
// such an entry carries nothing worth keeping, whereas a 400 would strand a client whose own
|
||||
// copy is already malformed — it keeps re-sending the same document and never syncs again.
|
||||
const record = x => x && typeof x === 'object' && !Array.isArray(x);
|
||||
for (const k of ['workouts', 'routines']) if (Array.isArray(body.state[k])) body.state[k] = body.state[k].filter(record);
|
||||
// Conditional write: a `baseRev` that is not the current revision means this client last
|
||||
// read an older document — another device has written since — and the copy it is about to
|
||||
// push would silently drop that write. The current document travels back with the 409, so
|
||||
@@ -954,8 +994,13 @@ const routes = {
|
||||
const user = readSession(req);
|
||||
if (!user) return json(res, 401, { error: 'not signed in' });
|
||||
const body = await readBody(req);
|
||||
const sec = Math.max(1, Math.min(3600, Math.round(+body.seconds || 0)));
|
||||
if (!sec) return json(res, 400, { error: 'seconds required' });
|
||||
// Validated before it is clamped: the clamp used to run first, which turned a missing or
|
||||
// unusable value into a 1-second push and made the 400 below unreachable. `Number()` only
|
||||
// on a number or a string — on an object it can throw.
|
||||
const raw = body.seconds;
|
||||
const n = typeof raw === 'number' || typeof raw === 'string' ? Number(raw) : NaN;
|
||||
if (!(n >= 1)) return json(res, 400, { error: 'seconds required' });
|
||||
const sec = Math.min(3600, Math.round(n));
|
||||
scheduleRestTimer(user.id, deviceIdOf(body.deviceId), sec, readState(user.id)?.lang);
|
||||
json(res, 200, { ok: true });
|
||||
},
|
||||
@@ -975,7 +1020,7 @@ const routes = {
|
||||
const body = await readBody(req);
|
||||
if (body.active) {
|
||||
presence.set(user.id, {
|
||||
name: String(body.name || '').slice(0, 60),
|
||||
name: text(body.name).slice(0, 60),
|
||||
exIdx: +body.exIdx || 0, exTotal: +body.exTotal || 0,
|
||||
setsDone: +body.setsDone || 0, setsTotal: +body.setsTotal || 0,
|
||||
startedAt: +body.startedAt || Date.now(),
|
||||
@@ -1054,7 +1099,7 @@ const routes = {
|
||||
// good, so the code itself has to be the thing that isn't worth guessing. Codes already in
|
||||
// db.json keep working — validation is an exact string compare, never a length or format check.
|
||||
do { code = crypto.randomBytes(8).toString('hex').toUpperCase(); } while (db.invites.some(i => i.code === code));
|
||||
const invite = { code, note: String(body.note || '').slice(0, 60), createdBy: admin.id, created: new Date().toISOString() };
|
||||
const invite = { code, note: text(body.note).slice(0, 60), createdBy: admin.id, created: new Date().toISOString() };
|
||||
db.invites.push(invite);
|
||||
saveDb();
|
||||
audit(req, 'admin.invite.create', { user: admin, msg: code });
|
||||
@@ -1064,7 +1109,7 @@ const routes = {
|
||||
'POST /api/admin/invites/revoke': async (req, res) => {
|
||||
const admin = requireAdmin(req, res); if (!admin) return;
|
||||
const body = await readBody(req);
|
||||
const inv = db.invites.find(i => i.code === String(body.code || '').toUpperCase());
|
||||
const inv = db.invites.find(i => i.code === text(body.code).toUpperCase());
|
||||
if (!inv) return json(res, 404, { error: 'no such code' });
|
||||
if (inv.usedBy) return json(res, 400, { error: 'already used — cannot revoke' });
|
||||
db.invites = db.invites.filter(i => i.code !== inv.code);
|
||||
@@ -1166,6 +1211,10 @@ http.createServer(async (req, res) => {
|
||||
}
|
||||
try { await handler(req, res); }
|
||||
catch (e) {
|
||||
if (e instanceof HttpError) {
|
||||
if (!res.headersSent) json(res, e.status, { error: e.message });
|
||||
return;
|
||||
}
|
||||
console.error(key, e);
|
||||
if (!res.headersSent) json(res, 500, { error: 'server error' });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
/* A client's mistake is a 400 (or a 413), never a 500 with a stack trace in the log: unparseable
|
||||
or non-object JSON bodies, a state document that is an array, null entries inside it, and a
|
||||
rest-timer request without a usable `seconds` (QA C17, C19, C20). Real server.js in a child. */
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import crypto from 'node:crypto';
|
||||
import net from 'node:net';
|
||||
import http from 'node:http';
|
||||
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');
|
||||
|
||||
// Same construction as server.js makeSession(): payload `uid:exp:sv`, HMAC-SHA256 over SECRET.
|
||||
function mintSession(uid, sv = 0) {
|
||||
const payload = `${uid}:${Date.now() + 86400000}:${sv}`;
|
||||
return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');
|
||||
}
|
||||
const UID = 'u_bad_1';
|
||||
const authed = { Cookie: `gymsid=${mintSession(UID)}`, 'Content-Type': 'application/json' };
|
||||
const anon = { '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) {
|
||||
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-bad-'));
|
||||
fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
|
||||
fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({
|
||||
users: [{ id: UID, name: 'One', created: new Date().toISOString() }], creds: [], subs: [], invites: []
|
||||
}));
|
||||
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}`);
|
||||
// The boot line is fine; anything that looks like a stack frame after this is a defect.
|
||||
h.stackFrames = () => h.log.split('\n').filter(l => /^\s+at /.test(l)).length;
|
||||
return h;
|
||||
}
|
||||
|
||||
const send = (h, method, p, headers, body) => fetch(`${h.api}${p}`, { method, headers, body });
|
||||
const status = async (h, method, p, headers, body) => {
|
||||
const r = await send(h, method, p, headers, body);
|
||||
return { status: r.status, body: await r.json() };
|
||||
};
|
||||
|
||||
test('malformed and non-object JSON bodies are a 400 with no stack trace, on every route', async t => {
|
||||
const h = await startServer(t);
|
||||
const bad = ['not json', '{bad', 'null', '"str"', '42', '[]'];
|
||||
const routes = [
|
||||
['POST', '/api/register/options', anon],
|
||||
['POST', '/api/register/verify', anon],
|
||||
['POST', '/api/pair/redeem', anon],
|
||||
['PUT', '/api/data', authed],
|
||||
['POST', '/api/push/rest-timer', authed]
|
||||
];
|
||||
for (const [method, p, headers] of routes) {
|
||||
for (const b of bad) {
|
||||
const r = await status(h, method, p, headers, b);
|
||||
assert.equal(r.status, 400, `${method} ${p} with body ${b}`);
|
||||
assert.equal(r.body.error, 'invalid json', `${method} ${p} with body ${b}`);
|
||||
}
|
||||
}
|
||||
// A field whose toString is not callable is valid JSON; String() on it used to throw.
|
||||
let r = await status(h, 'POST', '/api/register/options', anon, JSON.stringify({ name: 'x', code: { toString: 1 } }));
|
||||
assert.notEqual(r.status, 500);
|
||||
r = await status(h, 'POST', '/api/pair/redeem', anon, JSON.stringify({ code: { toString: 1 } }));
|
||||
assert.equal(r.status, 400);
|
||||
r = await status(h, 'POST', '/api/register/options', anon, JSON.stringify({ name: { toString: 1 } }));
|
||||
assert.equal(r.status, 400);
|
||||
assert.equal(r.body.error, 'name required');
|
||||
// An empty body is still "no fields", as the routes that send none rely on.
|
||||
r = await status(h, 'POST', '/api/logout', { Cookie: authed.Cookie });
|
||||
assert.equal(r.status, 200);
|
||||
// Well-formed controls keep their own answers.
|
||||
r = await status(h, 'POST', '/api/register/options', anon, '{}');
|
||||
assert.deepEqual(r, { status: 400, body: { error: 'name required' } });
|
||||
r = await status(h, 'PUT', '/api/data', authed, JSON.stringify({ state: { workouts: [], routines: [] }, baseRev: 0 }));
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal(h.stackFrames(), 0, `stack traces in the log:\n${h.log}`);
|
||||
assert.doesNotMatch(h.log, /bad json|TypeError/);
|
||||
});
|
||||
|
||||
// node's own http client, writing the whole body in one go on a keep-alive socket: the client
|
||||
// the QA proxy (and any node-side caller) is, and the one that used to report a reset instead
|
||||
// of the 413 when the server closed the socket under the still-running upload.
|
||||
const rawPut = (h, agent, body) => new Promise((resolve, reject) => {
|
||||
const rq = http.request(`${h.api}/api/data`, { method: 'PUT', headers: authed, agent }, res => {
|
||||
let data = ''; res.on('data', d => data += d); res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) }));
|
||||
});
|
||||
rq.on('error', reject);
|
||||
rq.end(body);
|
||||
});
|
||||
|
||||
test('a body over the 5 MiB cap is a 413 that every client gets to read, and nothing is written', async t => {
|
||||
const h = await startServer(t);
|
||||
const big = JSON.stringify({ state: { workouts: [], routines: [], pad: 'x'.repeat(6 * 1024 * 1024) }, baseRev: 0 });
|
||||
let r = await status(h, 'PUT', '/api/data', authed, big);
|
||||
assert.equal(r.status, 413);
|
||||
assert.equal(r.body.error, 'body too large');
|
||||
assert.equal(fs.existsSync(path.join(h.dataDir, `state-${UID}.json`)), false, 'nothing was written');
|
||||
const agent = new http.Agent({ keepAlive: true, maxSockets: 1 });
|
||||
t.after(() => agent.destroy());
|
||||
for (let i = 0; i < 3; i++) {
|
||||
r = await rawPut(h, agent, big);
|
||||
assert.equal(r.status, 413, `node client, attempt ${i + 1}`);
|
||||
}
|
||||
// The same keep-alive socket, and the server as a whole, are still fine afterwards.
|
||||
r = await rawPut(h, agent, JSON.stringify({ state: { workouts: [], routines: [] }, baseRev: 0 }));
|
||||
assert.equal(r.status, 200);
|
||||
// Past twice the cap the upload is cut off rather than drained: the 413 may or may not
|
||||
// arrive, but the process must not be left reading, and must still serve.
|
||||
const huge = 'x'.repeat(11 * 1024 * 1024);
|
||||
await rawPut(h, new http.Agent(), huge).catch(() => {});
|
||||
r = await status(h, 'GET', '/api/health', {});
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal(h.stackFrames(), 0, `stack traces in the log:\n${h.log}`);
|
||||
});
|
||||
|
||||
test('PUT /api/data: an array is not a document, and null entries never reach the disk', async t => {
|
||||
const h = await startServer(t);
|
||||
const put = body => status(h, 'PUT', '/api/data', authed, JSON.stringify(body));
|
||||
const onDisk = () => JSON.parse(fs.readFileSync(path.join(h.dataDir, `state-${UID}.json`), 'utf8'));
|
||||
|
||||
let r = await put({ state: { _ts: 100, workouts: [{ id: 'w1', d: '2026-09-01' }], routines: [], unit: 'kg' }, baseRev: 0 });
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal(r.body.rev, 1);
|
||||
|
||||
// An array passes `typeof === 'object'`; it used to be written as `[]`, losing the document
|
||||
// and, since `_rev` cannot live on an array, resetting the revision to 0 while the response
|
||||
// claimed rev 2.
|
||||
r = await put({ state: [], baseRev: 1 });
|
||||
assert.equal(r.status, 400);
|
||||
assert.equal(r.body.error, 'invalid state');
|
||||
assert.equal(onDisk()._rev, 1);
|
||||
assert.deepEqual(onDisk().workouts.map(w => w.id), ['w1']);
|
||||
r = await status(h, 'GET', '/api/data/rev', authed);
|
||||
assert.deepEqual(r.body, { rev: 1 });
|
||||
|
||||
// Null and other non-object entries are dropped: every server-side reader of the document
|
||||
// (reminder tick, admin drill-down) dereferences the entries, and a 400 would strand a client
|
||||
// whose own copy is already malformed.
|
||||
r = await put({ state: { workouts: [null, { id: 'w2', d: '2026-09-02' }, 7, 'x', [], { id: 'w3', d: '2026-09-03' }], routines: [null, { id: 'r1', name: 'A', ex: [] }] }, baseRev: 1 });
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal(r.body.rev, 2);
|
||||
assert.deepEqual(onDisk().workouts.map(w => w.id), ['w2', 'w3']);
|
||||
assert.deepEqual(onDisk().routines.map(x => x.id), ['r1']);
|
||||
// Absent lists stay absent — every client fills its own defaults.
|
||||
r = await put({ state: { unit: 'kg' }, baseRev: 2 });
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal('workouts' in onDisk(), false);
|
||||
assert.equal(h.stackFrames(), 0, `stack traces in the log:\n${h.log}`);
|
||||
});
|
||||
|
||||
test('POST /api/push/rest-timer: a missing or invalid `seconds` is a 400, never a 1-second timer', async t => {
|
||||
const h = await startServer(t);
|
||||
const post = b => status(h, 'POST', '/api/push/rest-timer', authed, b);
|
||||
for (const b of ['{}', '{"seconds":"abc"}', '{"seconds":0}', '{"seconds":-5}', '{"seconds":null}', '{"seconds":0.4}', '{"seconds":{"valueOf":1}}', '{"seconds":[90]}']) {
|
||||
const r = await post(b);
|
||||
assert.deepEqual(r, { status: 400, body: { error: 'seconds required' } }, `body ${b}`);
|
||||
}
|
||||
for (const b of ['{"seconds":90}', '{"seconds":"90"}', '{"seconds":1}', '{"seconds":99999}']) {
|
||||
const r = await post(b);
|
||||
assert.deepEqual(r, { status: 200, body: { ok: true } }, `body ${b}`);
|
||||
}
|
||||
assert.equal(h.stackFrames(), 0, `stack traces in the log:\n${h.log}`);
|
||||
});
|
||||
@@ -21,6 +21,11 @@ const LABELS = {
|
||||
'auth.register.denied': 'Signup refused',
|
||||
'auth.logout': 'Signed out',
|
||||
'auth.logout.all': 'Signed out everywhere',
|
||||
// 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',
|
||||
'auth.pair.ok': 'Paired a phone',
|
||||
'auth.pair.fail': 'Pairing failed',
|
||||
'admin.user.disable': 'Disabled an account',
|
||||
'admin.user.enable': 'Re-enabled an account',
|
||||
'admin.invite.create': 'Created an invite code',
|
||||
@@ -41,7 +46,9 @@ const REASONS = {
|
||||
'account-disabled': 'the account is disabled',
|
||||
'credential-exists': 'that passkey already belongs to a profile',
|
||||
'invite-invalid': 'the invite code was used or revoked in the meantime',
|
||||
'invite-rejected': 'wrong or already-used invite code'
|
||||
'invite-rejected': 'wrong or already-used invite code',
|
||||
'code-invalid': 'wrong or expired pairing code',
|
||||
'user-unavailable': 'the profile behind the pairing code is disabled or gone'
|
||||
}
|
||||
export const auditReason = msg => REASONS[msg] || (msg ? String(msg) : '')
|
||||
|
||||
|
||||
@@ -1,19 +1,15 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { auditCat, auditLabel, auditReason, auditLine, fmtWhen } from './audit.js'
|
||||
|
||||
// Every event name and reason code the server can emit (api/server.js, the audit block).
|
||||
// Every event name and reason code the server can emit, read off api/server.js itself rather
|
||||
// than kept as a second list here: the hand-kept copy silently missed the three pairing events
|
||||
// for several releases, and the dashboard printed 'auth.pair.create' at the operator (QA C18).
|
||||
// If a new one is added there without a label here, the first test fails rather than the
|
||||
// dashboard quietly printing a dotted identifier at a person.
|
||||
const EVENTS = [
|
||||
'auth.login.ok', 'auth.login.fail', 'auth.register.ok', 'auth.register.fail',
|
||||
'auth.register.denied', 'auth.logout', 'auth.logout.all',
|
||||
'admin.user.disable', 'admin.user.enable', 'admin.invite.create',
|
||||
'admin.invite.revoke', 'admin.audit.clear', 'admin.denied'
|
||||
]
|
||||
const REASONS = [
|
||||
'challenge-expired', 'unknown-credential', 'verify-error', 'not-verified',
|
||||
'user-missing', 'account-disabled', 'credential-exists', 'invite-invalid', 'invite-rejected'
|
||||
]
|
||||
const SERVER = readFileSync(new URL('../../../api/server.js', import.meta.url), 'utf8')
|
||||
const EVENTS = [...new Set([...SERVER.matchAll(/audit\(req, '([a-z.]+)'/g)].map(m => m[1]))]
|
||||
const REASONS = [...new Set([...SERVER.matchAll(/msg: '([a-z-]+)'/g)].map(m => m[1]))]
|
||||
|
||||
describe('auditLabel', () => {
|
||||
it('has a sentence for every event the server emits', () => {
|
||||
@@ -58,6 +54,14 @@ describe('auditReason', () => {
|
||||
})
|
||||
|
||||
describe('auditLine', () => {
|
||||
it('reads the server lists off api/server.js, pairing events included', () => {
|
||||
// Guards the extraction itself: an empty match would make the two loops above vacuous.
|
||||
expect(EVENTS).toEqual(expect.arrayContaining(['auth.login.ok', 'auth.pair.create', 'auth.pair.ok', 'auth.pair.fail', 'admin.audit.clear']))
|
||||
expect(REASONS).toEqual(expect.arrayContaining(['challenge-expired', 'code-invalid', 'user-unavailable']))
|
||||
expect(auditLine({ ev: 'auth.pair.fail', ok: false, msg: 'code-invalid' })).toEqual({ title: 'Pairing failed', sub: 'unknown caller · wrong or expired pairing code' })
|
||||
expect(auditLine({ ev: 'auth.pair.ok', ok: true, name: 'Verifier' })).toEqual({ title: 'Paired a phone', sub: 'Verifier' })
|
||||
})
|
||||
|
||||
it('names the person who did it', () => {
|
||||
expect(auditLine({ ev: 'auth.login.ok', ok: true, uid: 'u1', name: 'Duarte' }))
|
||||
.toEqual({ title: 'Signed in', sub: 'Duarte' })
|
||||
|
||||
@@ -36,6 +36,12 @@ function UserDetail({ id, onChanged, close }) {
|
||||
useEffect(() => { api('/api/admin/user?id=' + encodeURIComponent(id)).then(setD).catch(e => toast(e.message)) }, [id])
|
||||
if (!d) return <div className="muted small">Loading…</div>
|
||||
const u = d.user
|
||||
// The document comes straight off the user's state file. PUT /api/data drops null and
|
||||
// shapeless entries now, but a file written before it did still answers with them, and this
|
||||
// sheet renders outside the route's ErrorBoundary: one throw here blanked the whole app and
|
||||
// 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)))
|
||||
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() })
|
||||
@@ -50,7 +56,7 @@ function UserDetail({ id, onChanged, close }) {
|
||||
<span className="adm-pill">joined {u.created ? fmtDate(u.created.slice(0, 10)) : '—'}</span>
|
||||
</div>
|
||||
<div className="tiles" style={{ textAlign: 'left' }}>
|
||||
<div className="tile"><div className="l">Workouts</div><div className="v" style={{ fontSize: '1.1rem' }}>{d.workouts.length}</div></div>
|
||||
<div className="tile"><div className="l">Workouts</div><div className="v" style={{ fontSize: '1.1rem' }}>{workouts.length}</div></div>
|
||||
<div className="tile"><div className="l">Weigh-ins</div><div className="v" style={{ fontSize: '1.1rem' }}>{d.bodyweight.length}</div></div>
|
||||
<div className="tile"><div className="l">Routines</div><div className="v" style={{ fontSize: '1.1rem' }}>{d.routines.length}</div></div>
|
||||
<div className="tile"><div className="l">Last sync</div><div className="v" style={{ fontSize: '.95rem' }}>{rel(d.lastSync)}</div></div>
|
||||
@@ -63,8 +69,8 @@ function UserDetail({ id, onChanged, close }) {
|
||||
<div className="adm-hint">{u.disabled ? 'Enabling lets them sign in and sync again.' : 'Disabling signs them out everywhere and blocks sign-in. Nothing is deleted.'}</div>
|
||||
</>}
|
||||
<h4 className="sec">Workout history</h4>
|
||||
{d.workouts.length ? <div className="list" style={{ gap: 0 }}>
|
||||
{d.workouts.slice(0, 60).map(w => <div key={w.id} className="row between" style={{ padding: '9px 2px', borderBottom: '1px solid var(--sep)' }}>
|
||||
{workouts.length ? <div className="list" style={{ gap: 0 }}>
|
||||
{workouts.slice(0, 60).map(w => <div key={w.id} className="row between" style={{ padding: '9px 2px', borderBottom: '1px solid var(--sep)' }}>
|
||||
<div><div className="small" style={{ fontWeight: 600 }}>{w.name}</div>
|
||||
<div className="dim" style={{ fontSize: '.72rem' }}>{fmtDate(w.d, true)} · {fmtDur((w.end || w.start) - w.start)} · {setsDone(w)} sets{w.prs?.length ? ' · ' + w.prs.length + ' PR' : ''}</div></div>
|
||||
<span className="small muted">{fmtVol(w.vol ?? workoutVolume(w), d.unit)}</span>
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
// @vitest-environment happy-dom
|
||||
// The admin drill-down (QA C16): a profile whose stored workouts hold a null or otherwise
|
||||
// shapeless entry must still open, because the sheet host sits outside the route's
|
||||
// ErrorBoundary — a throw here blanked the whole app and left the account un-disableable.
|
||||
import React, { act } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import Admin from './Admin.jsx'
|
||||
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
|
||||
const mocks = vi.hoisted(() => ({ answers: {}, sheets: [] }))
|
||||
vi.mock('../lib/api.js', () => ({
|
||||
api: path => {
|
||||
const key = path.split('?')[0]
|
||||
return key in mocks.answers ? Promise.resolve(mocks.answers[key]) : Promise.reject(new Error('not found'))
|
||||
}
|
||||
}))
|
||||
vi.mock('../store/useStore.js', () => {
|
||||
const snap = () => ({ user: { id: 'adm', name: 'Admin', admin: true }, S: {} })
|
||||
const useStore = selector => selector ? selector(snap()) : snap()
|
||||
useStore.getState = snap
|
||||
return { useStore }
|
||||
})
|
||||
vi.mock('../store/useUI.js', () => {
|
||||
const snap = () => ({ toast: () => {}, openSheet: render => mocks.sheets.push(render) })
|
||||
const useUI = selector => selector ? selector(snap()) : snap()
|
||||
useUI.getState = snap
|
||||
return { useUI }
|
||||
})
|
||||
vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
|
||||
vi.mock('../sheets.jsx', () => ({ confirmSheet: vi.fn() }))
|
||||
vi.mock('./AdminCoach.jsx', () => ({ default: () => null }))
|
||||
|
||||
const mounted = []
|
||||
function render(el) {
|
||||
const host = document.createElement('div')
|
||||
document.body.appendChild(host)
|
||||
const root = createRoot(host)
|
||||
mounted.push(root)
|
||||
act(() => root.render(el))
|
||||
return host
|
||||
}
|
||||
const settle = () => act(() => new Promise(r => setTimeout(r, 0)))
|
||||
|
||||
const good = { id: 'w1', name: 'Push day', d: '2026-09-10', start: 1000, end: 61000, entries: [{ sets: [{ done: true }, { done: false }] }] }
|
||||
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = ''
|
||||
mocks.sheets.length = 0
|
||||
mocks.answers = {
|
||||
'/api/admin/users': { users: [{ id: 'u1', name: 'Mallory', workouts: 2, lastSync: null, disabled: false }], invite_only: false },
|
||||
'/api/admin/invites': { invites: [] },
|
||||
'/api/admin/audit': { rows: [] },
|
||||
'/api/admin/user': {
|
||||
user: { id: 'u1', name: 'Mallory', created: '2026-09-01T00:00:00Z', disabled: false, admin: false },
|
||||
unit: 'kg', lastSync: null, routines: [], bodyweight: [],
|
||||
// What GET /api/admin/user hands over for a document written before PUT /api/data dropped
|
||||
// such entries: a null, and a bare object without entries, next to a real session.
|
||||
workouts: [null, good, {}]
|
||||
}
|
||||
}
|
||||
})
|
||||
afterEach(() => { act(() => { mounted.splice(0).forEach(root => root.unmount()) }) })
|
||||
|
||||
describe('Admin user drill-down', () => {
|
||||
it('opens a profile with malformed workout entries and still offers "Disable account"', async () => {
|
||||
const page = render(<Admin />)
|
||||
await settle()
|
||||
const row = [...page.querySelectorAll('.item')].find(el => el.textContent.includes('Mallory'))
|
||||
expect(row).toBeTruthy()
|
||||
act(() => row.click())
|
||||
expect(mocks.sheets.length).toBe(1)
|
||||
const sheet = render(mocks.sheets[0](() => {}))
|
||||
await settle()
|
||||
const buttons = [...sheet.querySelectorAll('button')].map(b => b.textContent)
|
||||
expect(buttons).toContain('Disable account')
|
||||
// The one real session is listed; the two shapeless entries are skipped, not drawn as blanks.
|
||||
const rows = [...sheet.querySelectorAll('.list > div')]
|
||||
expect(rows.length).toBe(1)
|
||||
expect(rows[0].textContent).toContain('Push day')
|
||||
expect(rows[0].textContent).toContain('1 sets')
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user