Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

Audit log: a flood of junk sign-ins or pairing codes can't wipe it

Duarte Santos25ba5a4bf579
diff --git a/api/openapi.yaml b/api/openapi.yaml
index d37bd13fd..87191718e 100644
--- a/api/openapi.yaml
+++ b/api/openapi.yaml
@@ -38,7 +38,8 @@ info:
starts, so checks sent at once get no more tries than checks sent one by one. A
paused caller gets `429 {"error": …, "code": "locked", "retryAfter": <s>}` with a
`Retry-After` header. Passkey sign-up and sign-in and the pairing routes are not
- throttled. The two routes that redeem a one-time device link (tag `passkeys`) share
+ throttled (their failures reach the audit log at most ten a minute per address).
+ The two routes that redeem a one-time device link (tag `passkeys`) share
the per-address budget, and wrong codes pause the address for link redemption only,
after 20, the way wrong reset codes do. Adding or removing a passkey in Settings
(`POST /api/account/passkeys/options`, `DELETE /api/account/passkeys`) and making a
diff --git a/api/server.js b/api/server.js
index e67f93d9b..98e33786a 100644
--- a/api/server.js
+++ b/api/server.js
@@ -803,8 +803,10 @@ if (AUDIT_ON) {
// since none of them exists otherwise — and so are the two that redeem a device link (#95).
// Passkey sign-in, passkey registration and phone pairing stay out of it, as they always were:
// nothing there is worth guessing (an assertion is a signature, an invite code 64 random bits, a
-// pairing code lives five minutes), and behind a proxy that hands the API one address for every
-// visitor a per-address count on them would let one stranger pause everybody's way in. A
+// pairing code 40 bits that live five minutes, one per profile), and behind a proxy that hands the
+// API one address for every visitor a per-address count on them would let one stranger pause
+// everybody's way in. Their failures are still written to the audit log, but only a few per
+// address a minute (auditFail below), so a flood of junk cannot push everything else out of it. A
// device-link code is 60 bits that live ten minutes, no more worth guessing than a pairing code,
// but it is counted the way a reset code is: every wrong one is a guess at a way into somebody's
// profile, and the pause it can start only ever stops link redemption, never a sign-in.
@@ -899,6 +901,20 @@ function strikeAddress(req, kind) {
if (lock) audit(req, 'auth.throttled', { ok: false, msg: kind });
}
+// A failure on a route anyone can call without a session (passkey sign-in and sign-up, pairing)
+// is audited like any other, but only the first few per address and event a minute, and only so
+// many from everybody together. The log keeps the newest AUDIT_MAX rows, so without this a few
+// thousand junk requests (no Origin needed: these routes are CSRF-exempt) pushed every sign-in,
+// admin action and deletion out of it in seconds. Nobody is refused anything here: what is
+// dropped is a row that says the same thing as the ten before it.
+const FAIL_AUDIT = createWindow({ max: 10, windowMs: 60000 });
+const FAIL_AUDIT_ALL = createWindow({ max: 120, windowMs: 60000 });
+setInterval(() => { FAIL_AUDIT.sweep(); FAIL_AUDIT_ALL.sweep(); }, 60000).unref();
+function auditFail(req, ev, f) {
+ if (FAIL_AUDIT.take(ev + '|' + limitAddress(req)) || FAIL_AUDIT_ALL.take(ev)) return;
+ audit(req, ev, f);
+}
+
/* ---------- password sign-in (#118) ---------- */
// Optional, per instance (PASSWORD_LOGIN) and per profile: nobody has a password until they set
// one. Passkeys stay the default and the recommended way in. What a password needs that a
@@ -1833,7 +1849,7 @@ const routes = {
const body = await readBody(req);
const c = takeChallenge(body.cid);
if (!c || c.kind !== 'register' || !c.uid) {
- audit(req, 'auth.register.fail', { ok: false, msg: 'challenge-expired' });
+ auditFail(req, 'auth.register.fail', { ok: false, msg: 'challenge-expired' });
return json(res, 400, { error: 'challenge expired, try again', code: 'challenge-expired' });
}
let verification;
@@ -1847,11 +1863,11 @@ const routes = {
});
} catch (e) {
// e.message can echo attacker-supplied response fields, so only the reason code is kept.
- audit(req, 'auth.register.fail', { ok: false, name: c.name, msg: 'verify-error' });
+ auditFail(req, 'auth.register.fail', { ok: false, name: c.name, msg: 'verify-error' });
return json(res, 400, { error: verifyError(e, { rpId: RP_ID, origin: ORIGIN }) });
}
if (!verification.verified) {
- audit(req, 'auth.register.fail', { ok: false, name: c.name, msg: 'not-verified' });
+ auditFail(req, 'auth.register.fail', { ok: false, name: c.name, msg: 'not-verified' });
return json(res, 400, { error: 'not verified' });
}
const { credential } = verification.registrationInfo;
@@ -1897,7 +1913,7 @@ const routes = {
const body = await readBody(req);
const c = takeChallenge(body.cid);
if (c?.kind !== 'login') {
- audit(req, 'auth.login.fail', { ok: false, msg: 'challenge-expired' });
+ auditFail(req, 'auth.login.fail', { ok: false, msg: 'challenge-expired' });
return json(res, 400, { error: 'challenge expired, try again', code: 'challenge-expired' });
}
const cred = db.creds.find(x => x.id === body.credential?.id);
@@ -1905,7 +1921,7 @@ const routes = {
// No credential id goes in the log: it is a stable handle for one passkey, and recording it
// would let an admin correlate an unknown device across attempts. Nothing here identifies
// the caller beyond the timestamp (and the network, if AUDIT_IP is on).
- audit(req, 'auth.login.fail', { ok: false, msg: 'unknown-credential' });
+ auditFail(req, 'auth.login.fail', { ok: false, msg: 'unknown-credential' });
return json(res, 404, { error: 'unknown passkey, create a profile first', code: 'unknown-credential' });
}
let verification;
@@ -1924,11 +1940,11 @@ const routes = {
}
});
} catch (e) {
- audit(req, 'auth.login.fail', { ok: false, user: db.users.find(u => u.id === cred.userId), uid: cred.userId, msg: 'verify-error' });
+ auditFail(req, 'auth.login.fail', { ok: false, user: db.users.find(u => u.id === cred.userId), uid: cred.userId, msg: 'verify-error' });
return json(res, 400, { error: verifyError(e, { rpId: RP_ID, origin: ORIGIN }) });
}
if (!verification.verified) {
- audit(req, 'auth.login.fail', { ok: false, user: db.users.find(u => u.id === cred.userId), uid: cred.userId, msg: 'not-verified' });
+ auditFail(req, 'auth.login.fail', { ok: false, user: db.users.find(u => u.id === cred.userId), uid: cred.userId, msg: 'not-verified' });
return json(res, 400, { error: 'not verified' });
}
cred.counter = verification.authenticationInfo.newCounter;
@@ -1991,7 +2007,7 @@ const routes = {
const p = pairings.get(code);
if (p) pairings.delete(code);
if (!p || p.exp < Date.now()) {
- audit(req, 'auth.pair.fail', { ok: false, msg: 'code-invalid' });
+ auditFail(req, 'auth.pair.fail', { ok: false, msg: 'code-invalid' });
return json(res, 400, { error: 'invalid or expired code', code: 'pair-invalid' });
}
const user = db.users.find(u => u.id === p.uid);
diff --git a/api/test/server-anon-flood.test.js b/api/test/server-anon-flood.test.js
new file mode 100644
index 000000000..3f246f8ee
--- /dev/null
+++ b/api/test/server-anon-flood.test.js
@@ -0,0 +1,73 @@
+/* The routes anyone can call without a session (pairing, passkey sign-in and sign-up) used to
+ answer a flood of junk with a 400 and an audit row each, never a 429: a few thousand requests
+ pushed every other row out of the AUDIT_MAX-capped log in seconds. And a signed-in session could
+ mint pairing codes without limit, each one kept for five minutes. Real server.js in a child. */
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import crypto from 'node:crypto';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { spawn } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import { boundPort } from './helpers.mjs';
+
+const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
+const SECRET = crypto.randomBytes(32).toString('hex');
+
+function mintSession(uid) {
+ const payload = `${uid}:${Date.now() + 86400000}:0`;
+ return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');
+}
+const cookie = { Cookie: `gymsid=${mintSession('u_test_1')}` };
+
+async function startServer(t) {
+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-flood-'));
+ fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
+ fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({
+ users: [{ id: 'u_test_1', name: 'One', created: new Date().toISOString() }], creds: [], subs: [], invites: []
+ }));
+ 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', AUDIT_LOG: '1' }
+ });
+ const h = { api: '', dataDir, log: '' };
+ child.stdout.on('data', d => h.log += d);
+ child.stderr.on('data', d => h.log += d);
+ t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });
+ h.port = await boundPort(child, () => h.log);
+ h.api = `http://127.0.0.1:${h.port}`;
+ h.post = (p, body, headers = {}) => fetch(`${h.api}${p}`, {
+ method: 'POST', headers: { 'Content-Type': 'application/json', ...headers }, body: JSON.stringify(body || {})
+ });
+ h.audit = () => {
+ let text = '';
+ try { text = fs.readFileSync(path.join(dataDir, 'audit.log'), 'utf8'); } catch { /* none yet */ }
+ return text.split('\n').filter(Boolean).map(l => JSON.parse(l));
+ };
+ return h;
+}
+
+test('wrong pairing codes are all answered, but only a few of them reach the audit log', async t => {
+ const h = await startServer(t);
+ // Not paused: behind a proxy every visitor shares an address, and a 40-bit code that lives five
+ // minutes is not worth guessing (see the sign-in throttle in server.js).
+ for (let i = 0; i < 30; i++) assert.equal((await h.post('/api/pair/redeem', { code: 'WRONG' + i })).status, 400);
+ assert.equal(h.audit().filter(r => r.ev === 'auth.pair.fail').length, 10, 'ten a minute per address, not thirty');
+});
+
+test('junk passkey sign-ins and sign-ups are answered but not each written to the audit log', async t => {
+ const h = await startServer(t);
+ for (let i = 0; i < 25; i++) {
+ assert.equal((await h.post('/api/login/verify', { cid: 'junk' + i, credential: { id: 'x' } })).status, 400);
+ assert.equal((await h.post('/api/register/verify', { cid: 'junk' + i })).status, 400);
+ }
+ // A valid challenge with an unknown passkey is the other cheap miss.
+ for (let i = 0; i < 15; i++) {
+ const { cid } = await (await h.post('/api/login/options')).json();
+ assert.equal((await h.post('/api/login/verify', { cid, credential: { id: 'nobody' + i } })).status, 404);
+ }
+ const rows = h.audit();
+ assert.equal(rows.filter(r => r.ev === 'auth.login.fail').length, 10);
+ assert.equal(rows.filter(r => r.ev === 'auth.register.fail').length, 10);
+});