Skip to content

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

API: password guesses sent at once are counted before they are checked, and the throttle leaves passkeys and pairing alone again (#118)

Duarte Santos092f6733fbdf
diff --git a/SECURITY.md b/SECURITY.md
index 594677c29..54513f542 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -65,11 +65,12 @@ in the thread; there's no objection, and no request to sit on it indefinitely.
operator is trusted by design — see the security model below.
- Admins reading their users' workout history. That is the documented purpose of the admin
dashboard, not a leak.
-- **Missing rate limiting** on anything but sign-in, or "I sent 100k requests and it got slow".
- The API throttles the routes that work without a session — sign-in, registration, pairing,
- password reset — and nothing else; volume against the rest belongs in the reverse proxy you put
- in front of it. A way past that throttle *is* in scope, and so is genuine amplification (one
- small request causing unbounded work).
+- **Missing rate limiting** on anything but password sign-in, or "I sent 100k requests and it got
+ slow". With `PASSWORD_LOGIN=1` the API throttles its password routes — sign-in, password signup,
+ reset codes, changing a password — and nothing else; volume against the rest, passkey sign-in
+ and pairing included, belongs in the reverse proxy you put in front of it. A way past that
+ throttle *is* in scope, and so is genuine amplification (one small request causing unbounded
+ work).
- **Missing security headers.** `web/nginx.conf.template` sets `X-Frame-Options: DENY`,
`Content-Security-Policy: frame-ancestors 'none'`, `X-Content-Type-Options: nosniff` and
`Referrer-Policy: same-origin`. It deliberately does **not** set HSTS or a full CSP: TLS is the
@@ -105,13 +106,15 @@ Read this before hosting openGym for anyone other than yourself.
An admin can issue a one-time reset code — 60 random bits, stored as a SHA-256, 24 hours, single
use — which also removes the old password and ends every session; admin accounts cannot be
reset that way (`api/password.js`, the password block in `api/server.js`).
-- **Sign-in is throttled.** Every route that works without a session spends a budget of 60
- requests a minute per address; wrong passwords, invite codes and pairing codes pause the
+- **Password sign-in is throttled.** Every password route spends a budget of 60 requests a minute
+ per address; wrong passwords, reset codes and (on password signup) invite codes pause the
address after 20 (30 s, doubling to 15 min); wrong passwords pause the *name* after 5 (1 min,
- doubling to 1 h), existing or not. Passkey failures only spend the budget, so nobody can pause
- everyone's passkey sign-in. The address is the socket peer unless `TRUST_PROXY=1` (set by the
- bundled compose file, where only the web container reaches the API), and IPv6 is counted per
- /64 (`api/rate-limit.js`).
+ doubling to 1 h), existing or not. A password check is counted the moment it starts, so guesses
+ sent all at once get no more checks than guesses sent one by one. Passkey sign-in, passkey
+ signup and pairing are not throttled at all, so nobody can pause them — not even behind a proxy
+ that shows the API one address for every visitor. The address is the socket peer unless
+ `TRUST_PROXY=1` (set by the bundled compose file, where only the web container reaches the
+ API), and IPv6 is counted per /64 (`api/rate-limit.js`).
- **Sessions are a signed cookie.** It carries `<uid>:<expiry>:<version>` plus an
HMAC-SHA256 tag over it, compared in constant time (`api/server.js:230-243`). The key is 32
random bytes generated on first run and written to `./data/secret` with mode `0600`
@@ -192,13 +195,16 @@ Read this before hosting openGym for anyone other than yourself.
it. Without that, only direct surgery on `./data` gets it back.
- **A password is weaker than a passkey, and the throttle is per process.** It can be phished,
reused elsewhere or guessed; a stolen `db.json` allows offline guessing against the scrypt
- hashes. The throttle's counters live in memory: a restart clears them, several API replicas
- would each keep their own, and behind a second proxy that hides the visitor's address every
- visitor shares one per-address count (the per-name pause still holds). Anyone who knows a name
- can keep its *password* sign-in paused — passkeys are never paused — and the activity log shows
- it as `auth.password.locked`. The only password policy is 10–256 characters and a short
- built-in list of the passwords guessing scripts try first; no breached-password database is
- bundled.
+ hashes. The throttle's counters live in memory: a restart clears them, and several API replicas
+ would each keep their own. Behind a second proxy that hides the visitor's address every
+ visitor shares one per-address count, so one client can pause *password* sign-in for everybody
+ for up to 15 minutes at a time (the per-name pause still holds, and passkeys are never
+ paused). Anyone who knows a name can keep its password sign-in paused, which the activity log
+ shows as `auth.password.locked`. Only two password checks run at once, with 32 queued behind
+ them: someone sending from enough addresses can keep that queue full, and every password
+ sign-in then answers `503` until they stop — passkeys are unaffected. The only password
+ policy is 10–256 characters and a short built-in list of the passwords guessing scripts try
+ first; no breached-password database is bundled.
- **Disabling someone isn't a ban.** They can still register a fresh profile with a new passkey
unless `INVITE_ONLY=1` is set. It also makes them near-invisible in the activity log: a disabled
account is refused at the session check, so nothing it does produces an entry except the failed
@@ -207,13 +213,13 @@ Read this before hosting openGym for anyone other than yourself.
nginx listens on `:80` (`web/nginx.conf`); TLS is your reverse proxy's job. Without it,
browsers won't do passkeys at all (except on `http://localhost`) and the session cookie is sent
in the clear.
-- **Rate limiting covers sign-in only.** The throttle above applies to sign-in, registration,
- pairing and password reset; writes and everything else behind a session are not limited. `POST
- /api/register/options` still answers whether an invite code is valid, now at most 20 wrong
- guesses before that address pauses. New invite codes are 16 hex characters — 64 bits — which
- makes guessing one impractical even unthrottled; codes generated by earlier versions are 8
- characters / 32 bits and still work, so revoke and reissue any that are still unused. The other
- hard limit in the app is a 5 MB request body.
+- **Rate limiting covers password sign-in only.** The throttle above applies to the password
+ routes; passkey sign-in and signup, pairing, writes and everything else behind a session are
+ not limited, so an instance on the open internet should have a rate limit in front of it. `POST
+ /api/register/options` still answers whether an invite code is valid, unthrottled. New invite
+ codes are 16 hex characters — 64 bits — which makes guessing one impractical even unthrottled;
+ codes generated by earlier versions are 8 characters / 32 bits and still work, so revoke and
+ reissue any that are still unused. The other hard limit in the app is a 5 MB request body.
- **The activity log is not an audit archive, and it records less than you might assume.** No IP
address unless you set `AUDIT_IP` (`net` truncates to a /24 or /48; the default is `off`). When it is on, the
address comes from `CF-Connecting-IP`, `X-Forwarded-For`, `X-Real-IP` or, failing all three,
@@ -231,8 +237,8 @@ Read this before hosting openGym for anyone other than yourself.
admin can clear the whole log from the dashboard. And four of the paths that write to it —
the invite check on `POST /api/register/options`, and the expired-challenge and unknown-passkey
branches of the register/login handshakes (and, with passwords on, the failed password and
- reset-code attempts) — are reachable **without a session**, so within the sign-in throttle
- anyone can still fill the log with noise. It is an append of ~110 bytes per
+ reset-code attempts, within their throttle) — are reachable **without a session**, so anyone
+ can fill the log with noise. It is an append of ~110 bytes per
event to a capped file, never a rewrite of `db.json`, so the cost is a log full of noise rather
than a full disk or a slow server.
- **A few endpoints answer without a session:** `/api/health` (which includes the total user
diff --git a/api/openapi.yaml b/api/openapi.yaml
index dc63e4e7a..e42598f03 100644
--- a/api/openapi.yaml
+++ b/api/openapi.yaml
@@ -26,12 +26,14 @@ info:
cookie. With the flag off (the default) every one of them answers 404.
### Throttling
- The routes that work without a session are counted per client address: at most 60
- requests a minute across them, and wrong answers (a password, an invite code, a
- pairing code) pause the address after 20 for 30 s, doubling up to 15 min. Wrong
- passwords also pause the *name* they were tried against after 5, for 1 min doubling
- up to 1 h, whether or not a profile has that name. A paused caller gets
- `429 {"error": …, "code": "locked", "retryAfter": <s>}` with a `Retry-After` header.
+ The `password` routes are counted per client address: at most 60 requests a minute
+ across them, and wrong answers (a password, a reset code, an invite code on password
+ signup) pause the address after 20 for 30 s, doubling up to 15 min. Wrong passwords
+ also pause the *name* they were tried against after 5, for 1 min doubling up to 1 h,
+ whether or not a profile has that name. A password check counts from the moment it
+ 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. The passkey and pairing routes are not throttled.
The address is the socket's, or with `TRUST_PROXY=1` the one a trusted proxy put in
`CF-Connecting-IP` / the last `X-Forwarded-For` entry / `X-Real-IP`; IPv6 clients are
counted by /64. Counters live in memory and reset on restart.
@@ -626,8 +628,9 @@ paths:
Redeems the code from `POST /api/admin/user/password-reset` (valid 24 h, single
use, stored only as a hash; dashes, spaces and case do not matter) and signs in.
A new password that breaks the policy is refused without using up the code. Every
- other session of the account ends. Wrong codes are paused per name like wrong
- passwords, in a separate count. **Not** CSRF-exempt.
+ other session of the account ends. Wrong codes count against the caller's address
+ only (see *Throttling*), never against the name, so they cannot keep a real code
+ from working. **Not** CSRF-exempt.
security: []
requestBody:
required: true
diff --git a/api/password.js b/api/password.js
index a4937d21a..73de123c1 100644
--- a/api/password.js
+++ b/api/password.js
@@ -167,9 +167,10 @@ export function passwordProblem(pw, name) {
/* ----------------------------------------------------------------- reset codes -------------
What an admin hands someone who can no longer get in. 12 characters from the pairing-code
- alphabet (no 0/O/1/I) is 60 bits: it is read off a screen and typed once, and the account
- lockout sits in front of it like it does in front of a password. Stored only as a SHA-256 —
- the code is random, so a slow hash would add nothing but a second way to exhaust the server. */
+ alphabet (no 0/O/1/I) is 60 bits: it is read off a screen and typed once, and it lives a day,
+ so the per-address throttle is all that needs to stand in front of it — a per-name pause would
+ only let a stranger keep the real code refused. Stored only as a SHA-256 — the code is random,
+ so a slow hash would add nothing but a second way to exhaust the server. */
const ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
export const RESET_TTL_MS = 24 * 3600000;
diff --git a/api/rate-limit.js b/api/rate-limit.js
index b243fcb8d..a402eb845 100644
--- a/api/rate-limit.js
+++ b/api/rate-limit.js
@@ -1,9 +1,10 @@
-/* In-memory throttling for the routes anyone can call without a session (#118).
+/* In-memory throttling for the password routes (#118).
*
- * Until password sign-in there was nothing here worth guessing: a passkey assertion cannot be
- * brute-forced, invite codes are 64 random bits and pairing codes live five minutes. A password
- * is the first secret a person chooses, so the API now has to say no after enough wrong answers
- * instead of leaving that to whatever proxy the self-hoster did or did not put in front.
+ * Until password sign-in there was nothing worth guessing: a passkey assertion cannot be
+ * brute-forced, invite codes are 64 random bits and pairing codes live five minutes — which is
+ * why the passkey and pairing routes are still not counted here. A password is the first secret
+ * a person chooses, so the API now has to say no after enough wrong answers instead of leaving
+ * that to whatever proxy the self-hoster did or did not put in front.
*
* Two shapes, both small enough to read in one sitting:
*
@@ -12,19 +13,28 @@
* to `maxMs`. A key forgets after `forgetMs` without a failure, or when the caller
* reports a success. This is what stands between an attacker and a password.
* window counts every request per key in a fixed window — a plain budget, so one address
- * cannot make the server mint challenges or run scrypt as fast as it can send.
+ * cannot make the server run scrypt as fast as it can send.
+ *
+ * A failure can be counted before its answer is known (backoff.attempt), and taken back once
+ * it turns out not to be one. A password check takes a tenth of a second; counted only when it
+ * came back, a burst sent all at once was checked in full before the first failure landed.
*
* Both live in a Map that never grows past `maxKeys`: a key that is not locked and has gone
- * quiet is swept every minute, and when the Map is full anyway the oldest unlocked key makes
- * room first. Evicting a *locked* key would hand an attacker a way to reset their own lockout
- * by flooding fresh keys, so those go last. Everything is lost on a restart, which is the
- * accepted cost of not having a store — a restart is loud, and the lockouts are minutes long.
+ * quiet is swept every minute, and when the Map is full anyway the key with the least to lose
+ * makes room — for a backoff, the unlocked one with the fewest failures. Evicting a *locked*
+ * key, or one halfway to its lock, would hand an attacker a way to reset a count by flooding
+ * fresh keys that cost one failure each, so those go last, and a key the caller marks with
+ * `keep` never goes at all. Everything is lost on a restart, which is the accepted cost of not
+ * having a store — a restart is loud, and the lockouts are minutes long.
*
* `now` is injectable so the tests can walk the clock instead of sleeping. */
const MINUTE = 60000;
-function boundedMap(maxKeys, isLocked) {
+// `rank(entry)` says what a key has to lose: the lowest is evicted first, the least recently used
+// among equals. 0 is as low as it goes, so the scan stops at the first. `keep(key)` is never
+// evicted; it is asked only of a key that would otherwise be the one, because it may be slow.
+function boundedMap(maxKeys, rank, keep = () => false) {
const m = new Map();
return {
get: k => m.get(k),
@@ -32,9 +42,13 @@ function boundedMap(maxKeys, isLocked) {
set(k, v) {
m.delete(k);
if (m.size >= maxKeys) {
- let victim = null;
- for (const [key, e] of m) { if (!isLocked(e)) { victim = key; break; } }
- m.delete(victim ?? m.keys().next().value);
+ let victim, best = Infinity;
+ for (const [key, e] of m) {
+ const r = rank(e);
+ if (r < best && !keep(key)) { best = r; victim = key; if (r <= 0) break; }
+ }
+ // Nothing but kept keys: the Map grows past maxKeys by those, which the caller bounds.
+ if (victim !== undefined) m.delete(victim);
}
m.set(k, v);
},
@@ -44,10 +58,26 @@ function boundedMap(maxKeys, isLocked) {
};
}
-export function createBackoff({ free = 5, baseMs = MINUTE, maxMs = 60 * MINUTE, forgetMs = 24 * 60 * MINUTE, maxKeys = 10000, now = Date.now } = {}) {
+export function createBackoff({ free = 5, baseMs = MINUTE, maxMs = 60 * MINUTE, forgetMs = 24 * 60 * MINUTE, maxKeys = 10000, keep = () => false, now = Date.now } = {}) {
const locked = e => e.until > now();
- const map = boundedMap(maxKeys, locked);
+ // Unlocked keys by their count, then locked ones: a flood of keys with one failure each only
+ // ever pushes out its own kind.
+ const map = boundedMap(maxKeys, e => (locked(e) ? 1e9 : 0) + Math.max(0, e.n - 1), keep);
const fresh = e => e && now() - Math.max(e.last, e.until) <= forgetMs;
+ function bump(key) {
+ const prev = map.get(key);
+ const e = fresh(prev) ? prev : { n: 0, until: 0, last: 0 };
+ const wasUntil = e.until;
+ e.n += 1;
+ e.last = now();
+ let lock = 0;
+ if (e.n > free) {
+ lock = Math.min(maxMs, baseMs * 2 ** Math.min(30, e.n - free - 1));
+ e.until = e.last + lock;
+ }
+ map.set(key, e);
+ return { e, wasUntil, lock: Math.ceil(lock / 1000) };
+ }
return {
/** Seconds the key still has to wait, 0 when it may try. */
retryAfter(key) {
@@ -55,18 +85,27 @@ export function createBackoff({ free = 5, baseMs = MINUTE, maxMs = 60 * MINUTE,
return e && locked(e) ? Math.ceil((e.until - now()) / 1000) : 0;
},
/** One more failure. Returns the lock in seconds this failure caused, 0 for none. */
- fail(key) {
- const prev = map.get(key);
- const e = fresh(prev) ? prev : { n: 0, until: 0, last: 0 };
- e.n += 1;
- e.last = now();
- let lock = 0;
- if (e.n > free) {
- lock = Math.min(maxMs, baseMs * 2 ** Math.min(30, e.n - free - 1));
- e.until = e.last + lock;
- }
- map.set(key, e);
- return Math.ceil(lock / 1000);
+ fail: key => bump(key).lock,
+ /** An attempt whose answer is not known yet, counted as a failure from the moment it starts,
+ * so that attempts running side by side are all counted before any of them is answered.
+ * Returns the lock in seconds it started (0 for none) and `undo()`, which takes the attempt
+ * back once it turns out not to have been a failure after all. */
+ attempt(key) {
+ const { e, wasUntil, lock } = bump(key);
+ let open = true;
+ return {
+ lock,
+ undo() {
+ if (!open) return;
+ open = false;
+ // Cleared, forgotten or evicted since: nothing of this attempt is left to take back.
+ if (map.get(key) !== e) return;
+ e.n -= 1;
+ // The pause this attempt started goes with it, unless the failures left still earn one.
+ if (lock && e.n <= free) e.until = wasUntil;
+ if (e.n <= 0 && !locked(e)) map.delete(key);
+ }
+ };
},
/** A success: the key starts over. */
clear(key) { map.delete(key); },
@@ -79,7 +118,7 @@ export function createBackoff({ free = 5, baseMs = MINUTE, maxMs = 60 * MINUTE,
export function createWindow({ max = 60, windowMs = MINUTE, maxKeys = 10000, now = Date.now } = {}) {
const over = e => e.count > max && now() - e.start < windowMs;
- const map = boundedMap(maxKeys, over);
+ const map = boundedMap(maxKeys, e => (over(e) ? 1 : 0));
return {
/** Counts this request. Returns 0 when it is within budget, else seconds to wait. */
take(key) {
diff --git a/api/server.js b/api/server.js
index bbe1cb69a..65d8faa16 100644
--- a/api/server.js
+++ b/api/server.js
@@ -613,9 +613,9 @@ setInterval(() => { for (const [k, v] of presence) if (Date.now() - v.updatedAt
// Who signed in, who tried and failed, and what an admin changed. One JSON object per line in
// ./data/audit.log, appended and never rewritten in place. It deliberately does not live in
// db.json: that file is rewritten whole on every save, and the login/register handshakes are
-// unauthenticated and only loosely throttled (see the sign-in throttle below and SECURITY.md), so
-// an audit trail in there would turn one bogus request into a full db.json rewrite. A line torn
-// by a crash costs one event and is dropped on read.
+// unauthenticated and unthrottled by design (see SECURITY.md; only the optional password routes
+// are throttled, below), so an audit trail in there would turn one bogus request into a full
+// db.json rewrite. A line torn by a crash costs one event and is dropped on read.
//
// On by default. It records strictly less than the instance already holds — every account is in
// db.json and every workout is in state-<uid>.json, both readable by any admin — and a security
@@ -704,34 +704,46 @@ if (AUDIT_ON) {
}
/* ---------- sign-in throttle ---------- */
-// The routes anyone can reach without a session are counted (rate-limit.js), three ways:
+// The password routes are counted (rate-limit.js), and only those — so only on an instance with
+// PASSWORD_LOGIN on, since none of them exists otherwise. 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. Three counts:
//
-// AUTH_BURST every request to a throttled route, 60 a minute per address. Enough for a
-// household behind one proxy; not enough to have the server mint challenges or
-// run scrypt as fast as one client can ask.
-// ADDR_FAILS wrong answers per address and per kind (a password, an invite code, a pairing
-// code): 20 free, then a pause of 30 s that doubles up to 15 min.
+// AUTH_BURST every request to a password route, 60 a minute per address. Enough for a
+// household behind one proxy; not enough to run scrypt as fast as one client
+// can ask.
+// ADDR_FAILS wrong answers per address and per kind (a password or reset code, an invite
+// code on password signup): 20 free, then a pause of 30 s that doubles up to
+// 15 min.
// ACCOUNT_FAILS wrong passwords per *name*, whoever sends them: 5 free, then 1 min doubling
// up to 1 h, forgotten after a day without one or on the next success. This is
// the one that protects a password — an address is cheap to change, a name is
// not. It is keyed by the name as typed, existing or not, so a lockout never
-// says whether an account is there. Passkeys are never paused by it.
+// says whether an account is there; the count of a name that has a password is
+// never evicted to make room for others. Passkeys are never paused by it.
+//
+// A password check is counted against the name and the address the moment it starts, not when
+// its answer comes back (passwordAttempt below): scrypt takes a tenth of a second, and counting
+// afterwards let a burst sent at once be checked in full under a single allowance.
//
// Behind a proxy every request can come from the same address (the bundled web container passes
// the real one on; a second proxy in front of it may not). Then the per-address counts act for
-// the whole instance, which is why passkey failures only ever count against the burst budget: a
-// stranger's junk must not be able to pause everybody's passkey sign-in.
+// the whole instance: one client can pause *password* sign-in for everybody for a while, and the
+// per-name pause is what still protects each password.
const AUTH_BURST = createWindow({ max: 60, windowMs: 60000 });
const ADDR_FAILS = createBackoff({ free: 20, baseMs: 30000, maxMs: 15 * 60000, forgetMs: 3600000 });
-const ACCOUNT_FAILS = createBackoff({ free: 5, baseMs: 60000, maxMs: 3600000, forgetMs: 24 * 3600000 });
+const ACCOUNT_FAILS = createBackoff({
+ free: 5, baseMs: 60000, maxMs: 3600000, forgetMs: 24 * 3600000,
+ // At most one per profile with a password, so this cannot grow without bound.
+ keep: k => !!passwordHolder(k)
+});
setInterval(() => { AUTH_BURST.sweep(); ADDR_FAILS.sweep(); ACCOUNT_FAILS.sweep(); }, 60000).unref();
// Route -> the kind of failure it can count. Every route listed here also spends the burst
// budget; `null` spends only that.
const THROTTLED = {
- 'POST /api/register/options': 'signup', 'POST /api/register/verify': 'signup',
- 'POST /api/login/options': null, 'POST /api/login/verify': null,
- 'POST /api/pair/redeem': 'pair',
'POST /api/login/password': 'password', 'POST /api/login/password-reset': 'password',
'POST /api/register/password': 'signup',
'POST /api/account/password': 'password', 'DELETE /api/account/password': null
@@ -762,6 +774,14 @@ function limitAddress(req) {
function tooMany(res, secs) {
json(res, 429, { error: 'too many attempts — try again later', code: 'locked', retryAfter: secs }, { 'Retry-After': String(secs) });
}
+// Whether the caller's address is paused for `kind`, answering 429 when it is. A route asks this
+// again right before the check it guards, with no await in between: the dispatcher asked before
+// the body was read, and requests sent at once all pass that one together.
+function addressPaused(req, res, kind) {
+ const wait = ADDR_FAILS.retryAfter(kind + '|' + limitAddress(req));
+ if (wait) tooMany(res, wait);
+ return wait > 0;
+}
// One wrong answer against the caller's address. The pause it starts, if any, is recorded once
// — not every refused request after it, which anyone could use to fill the log.
function strikeAddress(req, kind) {
@@ -823,14 +843,36 @@ async function passkeyStepUp(user, body) {
} catch { return false; }
}
-// One wrong password against a name: counted for the name and for the address. The audit line
-// names the account only when there is one — what someone typed into the name field is
-// sometimes their password.
-function passwordFailed(req, k, user, msg) {
- const lock = ACCOUNT_FAILS.fail('login|' + k);
- strikeAddress(req, 'password');
- audit(req, 'auth.password.fail', user ? { ok: false, user, msg } : { ok: false, msg: 'unknown-name' });
- if (lock) audit(req, 'auth.password.locked', user ? { ok: false, user } : { ok: false, msg: 'unknown-name' });
+// One password check against the name `k`, counted as a failure for the name and for the caller's
+// address before it runs, so that checks sent side by side cannot all start under the same
+// allowance (see the throttle above). Answers 429 itself and returns null when either is paused.
+// The caller settles it once: failed() for a wrong password, ok() for a right one, void() when the
+// answer says nothing against the password — the queue was full, or the account is disabled.
+function passwordAttempt(req, res, k) {
+ const addr = 'password|' + limitAddress(req);
+ const wait = ACCOUNT_FAILS.retryAfter(k) || ADDR_FAILS.retryAfter(addr);
+ if (wait) { tooMany(res, wait); return null; }
+ const byName = ACCOUNT_FAILS.attempt(k);
+ const byAddr = ADDR_FAILS.attempt(addr);
+ const settle = () => { byName.undo(); byAddr.undo(); };
+ return {
+ // Every slot and the queue behind them taken (BusyError) is not a wrong password.
+ async verify(pw, stored) {
+ // Longer than any password that can be set: wrong, without hashing a megabyte to find out.
+ try { return passwordLength(pw) <= MAX_LENGTH && await verifyPassword(pw, stored); }
+ catch (e) { settle(); throw e; }
+ },
+ // The audit line names the account only when there is one — what someone typed into the
+ // name field is sometimes their password.
+ failed(user, msg) {
+ audit(req, 'auth.password.fail', user ? { ok: false, user, msg } : { ok: false, msg: 'unknown-name' });
+ if (byName.lock) audit(req, 'auth.password.locked', user ? { ok: false, user } : { ok: false, msg: 'unknown-name' });
+ if (byAddr.lock) audit(req, 'auth.throttled', { ok: false, msg: 'password' });
+ },
+ // A right password starts the name over; the address keeps whatever else it has run up.
+ ok() { ACCOUNT_FAILS.clear(k); byAddr.undo(); },
+ void: settle
+ };
}
if (PASSWORD_LOGIN) warmUp();
@@ -841,20 +883,19 @@ const passwordRoutes = {
const k = nameKey(text(body.name).slice(0, 200));
const pw = typeof body.password === 'string' ? body.password : '';
if (!k || !pw) return json(res, 400, { error: 'name and password required', code: 'missing' });
- const wait = ACCOUNT_FAILS.retryAfter('login|' + k);
- if (wait) return tooMany(res, wait);
+ const check = passwordAttempt(req, res, k);
+ if (!check) return;
const user = passwordHolder(k);
- // Longer than any password that can be set: wrong, without hashing a megabyte to find out.
- const ok = passwordLength(pw) <= MAX_LENGTH && await verifyPassword(pw, user?.pw?.h);
- if (!ok) {
- passwordFailed(req, k, user, 'bad-password');
+ if (!(await check.verify(pw, user?.pw?.h))) {
+ check.failed(user, 'bad-password');
return json(res, 401, WRONG);
}
if (user.disabled) {
+ check.void();
audit(req, 'auth.password.fail', { ok: false, user, msg: 'account-disabled' });
return json(res, 403, { error: 'this account has been disabled', code: 'disabled' });
}
- ACCOUNT_FAILS.clear('login|' + k);
+ check.ok();
// A hash made with older parameters is replaced now, while the password is at hand — unless
// the password itself changed while the new hash was being made.
const old = user.pw.h;
@@ -876,6 +917,7 @@ const passwordRoutes = {
if (!name) return json(res, 400, { error: 'name required', code: 'missing' });
const code = text(body.code).trim().toUpperCase();
const invite = () => db.invites.find(i => i.code === code && !i.usedBy && !i.revoked);
+ if (INVITE_ONLY && addressPaused(req, res, 'signup')) return;
if (INVITE_ONLY && !invite()) {
audit(req, 'auth.register.denied', { ok: false, name, msg: 'invite-rejected' });
strikeAddress(req, 'signup');
@@ -935,14 +977,15 @@ const passwordRoutes = {
proof = 'passkey';
} else if (hasPassword(user)) {
const current = typeof body.current === 'string' ? body.current : '';
+ const wrongCurrent = () => json(res, 403, { error: 'your current password is not right', code: 'current-wrong' });
if (!current) return json(res, 403, { error: 'enter your current password', code: 'current-required' });
- const wait = ACCOUNT_FAILS.retryAfter('login|' + k);
- if (wait) return tooMany(res, wait);
- if (!(passwordLength(current) <= MAX_LENGTH && await verifyPassword(current, user.pw.h))) {
- passwordFailed(req, k, user, 'bad-current');
- return json(res, 403, { error: 'your current password is not right', code: 'current-wrong' });
+ const check = passwordAttempt(req, res, k);
+ if (!check) return;
+ if (!(await check.verify(current, user.pw.h))) {
+ check.failed(user, 'bad-current');
+ return wrongCurrent();
}
- ACCOUNT_FAILS.clear('login|' + k);
+ check.ok();
proof = 'password';
} else {
return json(res, 403, { error: 'confirm with your passkey first', code: 'passkey-required' });
@@ -955,7 +998,7 @@ const passwordRoutes = {
const first = !hasPassword(user);
setPassword(user, h);
// Whatever pause wrong guesses put on this name was about a password that no longer exists.
- ACCOUNT_FAILS.clear('login|' + k);
+ ACCOUNT_FAILS.clear(k);
saveDb();
audit(req, first ? 'auth.password.set' : 'auth.password.change', { user, msg: proof });
// This session carries on under the new version: a new cookie, or a new token for a phone.
@@ -1005,16 +1048,16 @@ const passwordRoutes = {
const k = nameKey(text(body.name).slice(0, 200));
const code = text(body.code).slice(0, 64);
if (!k || !code) return json(res, 400, { error: 'name and code required', code: 'missing' });
- const wait = ACCOUNT_FAILS.retryAfter('reset|' + k);
- if (wait) return tooMany(res, wait);
+ // Wrong codes count against the address only. A per-name pause would add nothing against a
+ // 60-bit code that lives a day, and would let anyone who knows the name keep the real code
+ // refused for that whole day — after the reset has already removed the old password.
+ if (addressPaused(req, res, 'password')) return;
const find = () => db.users.find(u => u.pwReset && nameKey(u.name) === k && resetCodeMatches(code, u.pwReset)) || null;
const user = find();
const invalid = () => json(res, 400, { error: 'that reset code is wrong or has expired', code: 'reset-invalid' });
if (!user) {
- const lock = ACCOUNT_FAILS.fail('reset|' + k);
strikeAddress(req, 'password');
audit(req, 'auth.password.reset', { ok: false, msg: 'reset-invalid' });
- if (lock) audit(req, 'auth.password.locked', { ok: false, msg: 'reset' });
return invalid();
}
if (user.disabled) {
@@ -1029,8 +1072,7 @@ const passwordRoutes = {
// Single use: a second request that raced this one through the hash finds the code gone.
if (find() !== user) return invalid();
setPassword(user, h);
- ACCOUNT_FAILS.clear('reset|' + k);
- ACCOUNT_FAILS.clear('login|' + k);
+ ACCOUNT_FAILS.clear(k);
saveDb();
audit(req, 'auth.password.reset', { user });
json(res, 200, { user: publicUser(user) }, { 'Set-Cookie': sessionCookie(user) });
@@ -1073,7 +1115,6 @@ const routes = {
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' });
- strikeAddress(req, 'signup');
return json(res, 403, { error: 'a valid invite code is required' });
}
const uid = crypto.randomBytes(12).toString('base64url');
@@ -1245,7 +1286,6 @@ const routes = {
if (p) pairings.delete(code);
if (!p || p.exp < Date.now()) {
audit(req, 'auth.pair.fail', { ok: false, msg: 'code-invalid' });
- strikeAddress(req, 'pair');
return json(res, 400, { error: 'invalid or expired code' });
}
const user = db.users.find(u => u.id === p.uid);
@@ -1508,10 +1548,10 @@ const routes = {
const admin = requireAdmin(req, res); if (!admin) return;
const body = await readBody(req);
let code;
- // 16 hex chars = 64 bits, up from 8 chars / 32 bits. The sign-in throttle only slows guessing
- // down, and /api/register/options tells a caller whether a code is 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.
+ // 16 hex chars = 64 bits, up from 8 chars / 32 bits. Passkey signup has no rate limiting by
+ // design (that's the reverse proxy's job) and /api/register/options tells a caller whether a
+ // code is 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: text(body.note).slice(0, 60), createdBy: admin.id, created: new Date().toISOString() };
db.invites.push(invite);
@@ -1623,7 +1663,8 @@ http.createServer(async (req, res) => {
console.warn('refused cross-origin', key, 'origin=' + req.headers.origin, 'expected=' + ORIGIN);
return json(res, 403, { error: 'cross-origin request refused' });
}
- // After the origin check, so a forged request spends nobody's budget.
+ // After the origin check, so a forged request spends nobody's budget. The password routes only
+ // (see the sign-in throttle above).
if (key in THROTTLED) {
const addr = limitAddress(req);
const kind = THROTTLED[key];
diff --git a/api/test/rate-limit.test.js b/api/test/rate-limit.test.js
index dc0195727..359b54edc 100644
--- a/api/test/rate-limit.test.js
+++ b/api/test/rate-limit.test.js
@@ -63,3 +63,86 @@ test('window: a fixed budget per key, and how long until it refills', () => {
c.t += 10000; w.sweep();
assert.equal(w.size, 0);
});
+
+test('backoff: attempts counted before their answer — a burst started at once is refused after the allowance', () => {
+ const c = clock();
+ const b = createBackoff({ free: 5, baseMs: 60000, maxMs: 3600000, now: c.now });
+ // Twenty checks started side by side, none answered yet: the way a caller uses it is to ask
+ // retryAfter() and, if free, start an attempt — with no await in between.
+ const started = [];
+ let refused = 0;
+ for (let i = 0; i < 20; i++) {
+ if (b.retryAfter('ana')) { refused++; continue; }
+ started.push(b.attempt('ana'));
+ }
+ assert.equal(started.length, 6, 'five free and the one that starts the pause');
+ assert.equal(refused, 14);
+ assert.equal(started[5].lock, 60);
+ assert.deepEqual(started.slice(0, 5).map(a => a.lock), [0, 0, 0, 0, 0]);
+});
+
+test('backoff: undo takes an attempt back, and the pause it started with it — once', () => {
+ const c = clock();
+ const b = createBackoff({ free: 2, baseMs: 60000, maxMs: 3600000, now: c.now });
+ b.fail('k'); b.fail('k');
+ const a = b.attempt('k');
+ assert.equal(a.lock, 60);
+ assert.ok(b.retryAfter('k') > 0);
+ a.undo();
+ assert.equal(b.retryAfter('k'), 0, 'the pause went with the attempt');
+ a.undo(); // a second undo takes nothing more back
+ assert.equal(b.fail('k'), 60, 'still two failures on record: the next one pauses');
+
+ // An attempt on a key that was cleared meanwhile has nothing left to take back.
+ const x = b.attempt('x');
+ b.clear('x');
+ b.fail('x');
+ x.undo();
+ assert.equal(b.fail('x'), 0);
+ assert.equal(b.fail('x'), 60, 'the two failures after the clear both still count');
+
+ // An attempt that turned out right leaves no trace of itself.
+ const y = b.attempt('y');
+ y.undo();
+ assert.equal(b.size, 2);
+});
+
+test('backoff: undo never lifts a pause the failures left still earn, or one it did not start', () => {
+ const c = clock();
+ const b = createBackoff({ free: 1, baseMs: 60000, maxMs: 3600000, now: c.now });
+ b.fail('k');
+ const a = b.attempt('k'); // the second failure: pauses
+ assert.equal(a.lock, 60);
+ assert.equal(b.fail('k'), 120); // a third, counted meanwhile
+ a.undo(); // two left: still more than the one free
+ assert.equal(b.retryAfter('k'), 120);
+
+ const d = createBackoff({ free: 1, baseMs: 60000, maxMs: 3600000, now: c.now });
+ const first = d.attempt('k'); // free, started no pause
+ assert.equal(d.fail('k'), 60);
+ first.undo();
+ assert.equal(d.retryAfter('k'), 60, 'only the attempt that started a pause takes it back');
+});
+
+test('backoff: a flood of fresh keys pushes out its own kind, not a count halfway to its pause', () => {
+ const c = clock();
+ const b = createBackoff({ free: 5, baseMs: 60000, maxMs: 3600000, maxKeys: 100, now: c.now });
+ for (let i = 0; i < 5; i++) b.fail('ana'); // one short of the pause
+ for (let i = 0; i < 10000; i++) b.fail('junk' + i); // one failure each
+ assert.equal(b.size, 100);
+ assert.equal(b.fail('ana'), 60, 'the five earlier failures are still on record');
+});
+
+test('backoff: a key marked keep is never evicted, even when everything else has more to lose', () => {
+ const c = clock();
+ const b = createBackoff({ free: 5, maxKeys: 3, keep: k => k === 'ana', now: c.now });
+ b.fail('ana');
+ for (let i = 0; i < 50; i++) { b.fail('junk' + i); b.fail('junk' + i); b.fail('junk' + i); }
+ assert.equal(b.size, 3);
+ for (let i = 0; i < 4; i++) assert.equal(b.fail('ana'), 0);
+ assert.equal(b.fail('ana'), 60, 'the first failure was kept through the flood');
+ // Only kept keys left: the Map grows by those instead of dropping one.
+ const k = createBackoff({ maxKeys: 2, keep: () => true, now: c.now });
+ for (const key of ['a', 'b', 'c']) k.fail(key);
+ assert.equal(k.size, 3);
+});
diff --git a/api/test/server-password.test.js b/api/test/server-password.test.js
index 4c2555864..c77ab50e7 100644
--- a/api/test/server-password.test.js
+++ b/api/test/server-password.test.js
@@ -6,6 +6,7 @@ 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';
@@ -186,20 +187,84 @@ test('twenty failures from one address pause that address for every name; others
assert.ok(h.audit().some(e => e.ev === 'auth.throttled' && e.msg === 'password'));
});
-test('the burst budget answers 429 with Retry-After on the passkey and pairing routes too', async t => {
+// scrypt takes a tenth of a second, so guesses sent at once are all in flight before the first
+// is answered. Each is counted the moment it starts: the allowance is what gets checked, the rest
+// wait — however many arrive together.
+test('guesses sent all at once are checked only up to the pause, per name and per address', async t => {
+ const h = await startServer(t, { users: [withPassword('u1', 'Ana')] });
+ const byName = await Promise.all(Array.from({ length: 20 }, (_, i) => login(h, 'Ana', 'wrong password ' + i, `198.51.100.${160 + i}`)));
+ const statuses = byName.map(r => r.status);
+ assert.equal(statuses.filter(s => s === 401).length, 6, `five free and the one that starts the pause: ${statuses}`);
+ assert.equal(statuses.filter(s => s === 429).length, 14);
+ assert.equal((await login(h, 'Ana', GOOD, '198.51.100.199')).status, 429, 'the name is paused');
+
+ const ip = '203.0.113.90';
+ const byAddr = await Promise.all(Array.from({ length: 30 }, (_, i) => login(h, 'someone' + i, 'wrong password', ip)));
+ const a = byAddr.map(r => r.status);
+ assert.equal(a.filter(s => s === 401).length, 21, `twenty free and the one that starts the pause: ${a}`);
+ assert.equal(a.filter(s => s === 429).length, 9);
+ assert.equal(h.audit().filter(e => e.ev === 'auth.password.locked').length, 1, 'the pause is logged once');
+});
+
+test('the owner signing in while guesses are in flight is not counted against the name', async t => {
+ const h = await startServer(t, { users: [withPassword('u1', 'Ana')] });
+ // Five wrong and the right one, side by side: whichever of them is sixth starts the pause but is
+ // still checked, and the right one clears the name when it lands.
+ const all = await Promise.all([
+ ...Array.from({ length: 5 }, (_, i) => login(h, 'Ana', 'wrong password ' + i, `198.51.100.${210 + i}`)),
+ login(h, 'Ana', GOOD, '198.51.100.215')
+ ]);
+ assert.deepEqual(all.map(r => r.status), [401, 401, 401, 401, 401, 200]);
+ // Five wrong from here on are free again, and only the sixth pauses.
+ for (let i = 0; i < 6; i++) assert.equal((await login(h, 'Ana', 'wrong again ' + i, `198.51.100.${220 + i}`)).status, 401);
+ assert.equal((await login(h, 'Ana', GOOD, '198.51.100.230')).status, 429);
+});
+
+test('the burst budget answers 429 with Retry-After on the password routes', async t => {
const h = await startServer(t);
let last;
- for (let i = 0; i < 61; i++) last = await h.req('POST', '/api/login/options', { body: {}, ip: '203.0.113.60' });
+ for (let i = 0; i < 61; i++) last = await h.req('POST', '/api/login/password', { body: {}, ip: '203.0.113.60' });
assert.equal(last.status, 429);
assert.ok(+last.headers.get('retry-after') > 0);
- assert.equal((await h.req('POST', '/api/pair/redeem', { body: { code: 'NOPE' }, ip: '203.0.113.60' })).status, 429);
- assert.equal((await h.req('POST', '/api/login/options', { body: {}, ip: '203.0.113.61' })).status, 200);
+ assert.equal((await h.req('POST', '/api/login/password-reset', { body: {}, ip: '203.0.113.60' })).status, 429);
+ assert.equal((await h.req('POST', '/api/login/password', { body: {}, ip: '203.0.113.61' })).status, 400);
});
test('without TRUST_PROXY a forwarded address is ignored: the socket is who is counted', async t => {
const h = await startServer(t, { env: { TRUST_PROXY: '' } });
- for (let i = 0; i < 61; i++) await h.req('POST', '/api/login/options', { body: {}, ip: `203.0.113.${i + 100}` });
- assert.equal((await h.req('POST', '/api/login/options', { body: {}, ip: '192.0.2.1' })).status, 429);
+ for (let i = 0; i < 61; i++) await h.req('POST', '/api/login/password', { body: {}, ip: `203.0.113.${i + 100}` });
+ assert.equal((await h.req('POST', '/api/login/password', { body: {}, ip: '192.0.2.1' })).status, 429);
+});
+
+// Behind a proxy that hides the visitor, every request comes from one address. Whatever one client
+// sends from there must not pause anybody's passkey sign-in, passkey signup or phone pairing —
+// which were never throttled, and are not now.
+test('a flood from a shared address leaves passkey sign-in, registration and pairing working', async t => {
+ const key = softPasskey();
+ const h = await startServer(t, {
+ env: { TRUST_PROXY: '', INVITE_ONLY: '1' },
+ users: [withPassword('u1', 'Ana')], creds: [key.row('u1')],
+ invites: [{ code: 'GOODCODE', created: new Date().toISOString() }]
+ });
+ for (let i = 0; i < 100; i++) await h.req('POST', '/api/login/options', { body: {} });
+ for (let i = 0; i < 30; i++) assert.equal((await h.req('POST', '/api/register/options', { body: { name: 'X', code: 'JUNK' + i } })).status, 403);
+ for (let i = 0; i < 30; i++) assert.equal((await h.req('POST', '/api/pair/redeem', { body: { code: 'JUNK' + i } })).status, 400);
+ await Promise.all(Array.from({ length: 25 }, (_, i) => login(h, 'name' + i, 'wrong password')));
+ // Password sign-in is what the shared address pauses — for everybody behind it, as documented.
+ assert.equal((await login(h, 'Ana', GOOD)).status, 429);
+
+ const { cid, options } = (await h.req('POST', '/api/login/options', { body: {} })).body;
+ const signedIn = await h.req('POST', '/api/login/verify', { body: { cid, credential: key.assertion(options.challenge) } });
+ assert.equal(signedIn.status, 200, 'passkey sign-in');
+ assert.ok(signedIn.cookie);
+ assert.equal((await h.req('POST', '/api/register/options', { body: { name: 'Cleo', code: 'goodcode' } })).status, 200, 'passkey signup');
+ const { code } = (await h.req('POST', '/api/pair/create', { cookie: signedIn.cookie })).body;
+ assert.equal((await h.req('POST', '/api/pair/redeem', { body: { code } })).status, 200, 'pairing');
+ assert.equal(h.audit().some(e => e.ev === 'auth.throttled' && e.msg !== 'password'), false);
+
+ // With PASSWORD_LOGIN off nothing at all is counted.
+ const off = await startServer(t, { env: { TRUST_PROXY: '', PASSWORD_LOGIN: '' } });
+ for (let i = 0; i < 100; i++) assert.equal((await off.req('POST', '/api/login/options', { body: {} })).status, 200);
});
test('the password routes keep the origin check: no login CSRF', async t => {
@@ -364,6 +429,43 @@ test('an admin reset: a one-time code that ends the old password, works once, an
assert.ok(h.audit().some(e => e.ev === 'auth.password.reset' && !e.ok));
});
+// A 60-bit code that lives a day needs no per-name pause, and one would let anyone who knows the
+// name keep the real code refused for that whole day. Wrong codes count against the address only.
+test('wrong reset codes for a name do not lock out its real code, and do not touch the password count', async t => {
+ const h = await startServer(t, {
+ // No activity log: ten thousand lines of it below would only slow the test down.
+ env: { ADMIN_UIDS: 'adm', AUDIT_LOG: '0' },
+ users: [user('adm', 'Root'), withPassword('u1', 'Ana'), withPassword('u2', 'Bea')]
+ });
+ const { code } = (await h.req('POST', '/api/admin/user/password-reset', { body: { id: 'u2' }, cookie: `gymsid=${mintSession('adm')}`, ip: '198.51.100.245' })).body;
+ for (let i = 0; i < 12; i++) {
+ const r = await h.req('POST', '/api/login/password-reset', { body: { name: 'Bea', code: 'ZZZZ-ZZZZ-ZZZ' + i, next: 'whatever passphrase' }, ip: `198.51.100.${100 + i}` });
+ assert.equal(r.body.code, 'reset-invalid');
+ }
+ assert.equal((await h.req('POST', '/api/login/password-reset', { body: { name: 'Bea', code, next: 'a brand new passphrase' }, ip: '198.51.100.246' })).status, 200);
+
+ // The cheap flood of the probe: five wrong passwords for Ana, then ten thousand junk codes for
+ // names nobody has, twenty per IPv6 /64 so no address is paused. Ana's count is still there.
+ for (let i = 0; i < 5; i++) assert.equal((await login(h, 'Ana', 'wrong password ' + i, `198.51.100.${150 + i}`)).status, 401);
+ // Kept-alive connections: a fresh one per request would make this the slowest test in the file.
+ const agent = new http.Agent({ keepAlive: true, maxSockets: 50 });
+ t.after(() => agent.destroy());
+ const junk = i => new Promise((resolve, reject) => {
+ const r = http.request(`${h.api}/api/login/password-reset`, {
+ method: 'POST', agent,
+ headers: { 'Content-Type': 'application/json', 'Sec-Fetch-Site': 'same-origin', 'X-Forwarded-For': `2001:db8:${(i / 20 | 0).toString(16)}::1` }
+ }, res => { res.resume(); res.on('end', () => resolve(res.statusCode)); });
+ r.on('error', reject);
+ r.end(JSON.stringify({ name: 'junk' + i, code: 'ZZZZ-ZZZZ-ZZZZ', next: 'whatever passphrase' }));
+ });
+ for (let i = 0; i < 10000; i += 200) {
+ const batch = await Promise.all(Array.from({ length: 200 }, (_, j) => junk(i + j)));
+ assert.ok(batch.every(status => status === 400), 'no junk request was paused');
+ }
+ assert.equal((await login(h, 'Ana', 'wrong password 5', '198.51.100.160')).status, 401);
+ assert.equal((await login(h, 'Ana', GOOD, '198.51.100.161')).status, 429, 'the sixth wrong password paused the name');
+});
+
test('a disabled account is refused even with the right password', async t => {
const h = await startServer(t, { users: [withPassword('u1', 'Ana', { disabled: true })] });
const r = await login(h, 'Ana', GOOD, '198.51.100.150');
diff --git a/docs/SELF_HOSTING.md b/docs/SELF_HOSTING.md
index ddb5f8743..5428cb24c 100644
--- a/docs/SELF_HOSTING.md
+++ b/docs/SELF_HOSTING.md
@@ -229,10 +229,13 @@ a LAN-only address, see [SELF_HOSTING_HTTPS.md](./SELF_HOSTING_HTTPS.md).
name for a minute, doubling up to an hour, whoever sends them — names that do not exist pause
the same way, so a pause reveals nothing. Twenty wrong answers from one address pause that
address for 30 seconds, doubling up to 15 minutes, and every address gets 60 requests a minute
- to the sign-in routes. Passkeys are never paused. The counters live in memory, so a restart
- clears them.
+ to the password routes. Guesses sent all at once count the same as guesses sent one by one.
+ Passkey sign-in, passkey signup and phone pairing are not throttled at all, so they are never
+ paused. The counters live in memory, so a restart clears them.
- The flip side: anyone who knows a name can keep that name's *password* sign-in paused. The
- activity log shows it (`auth.password.locked`), and passkeys still work.
+ activity log shows it (`auth.password.locked`), and passkeys still work. A reset code is not
+ paused per name — it is 60 random bits and lives a day — so nobody can keep a real code from
+ working by sending wrong ones.
- Passwords need 10 to 256 characters and may not be one of a short built-in list of the
passwords guessing scripts try first (`Password123!`, `qwerty…`, the profile's own name with
digits). A long passphrase is the point.
@@ -241,10 +244,12 @@ a LAN-only address, see [SELF_HOSTING_HTTPS.md](./SELF_HOSTING_HTTPS.md).
bundled `docker-compose.yml` it reads the one the web container passes on: the compose file sets
`TRUST_PROXY=1` for the api, because the API is reachable only through that container, which
overwrites `X-Forwarded-For`. If you put another reverse proxy in front of the web container, every
-visitor may arrive as that proxy — then the per-address limits apply to everyone together, and the
-per-name pause is what protects the passwords. Behind Cloudflare, `CF_CONNECTING_IP` (see the
-activity log above) passes the real visitor on. Running the API without the web container, leave
-`TRUST_PROXY` off unless whatever is in front overwrites (not appends to) `X-Forwarded-For`.
+visitor may arrive as that proxy — then the per-address limits apply to everyone together: one
+client sending wrong passwords can pause password sign-in for everybody for up to 15 minutes at a
+time (passkeys keep working), and the per-name pause is what protects the passwords. Behind
+Cloudflare, `CF_CONNECTING_IP` (see the activity log above) passes the real visitor on. Running
+the API without the web container, leave `TRUST_PROXY` off unless whatever is in front overwrites
+(not appends to) `X-Forwarded-For`.
**Switching it off again** hides all of it and makes every password route answer 404. The stored
hashes stay in `db.json` and work again if you switch it back on — but while it is off, a profile