Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
API: optional name-and-password sign-in, and a throttle in front of every sign-in route (#118)
Duarte Santos8a53efdf6727
diff --git a/.env.example b/.env.exampleindex a7a63a993..646afe571 100644--- a/.env.example+++ b/.env.example@@ -42,6 +42,25 @@ RP_NAME=openGym## ALLOW_GUEST=0+# ── Password sign-in (optional, off by default) ────────────────────────────+# Lets people sign in with their profile name and a password next to passkeys:+# for browsers that cannot make a passkey (plain http:// on a LAN address, some+# Firefox setups) and for recovery — an admin can hand out a one-time reset+# code from the dashboard. Nobody has a password until they set one in+# Settings. Passkeys stay the default and the safer choice; read+# docs/SELF_HOSTING.md ("Password sign-in") before turning this on.+#+# PASSWORD_LOGIN=1+#+# Wrong passwords are throttled per name and per address. The address is read+# from X-Forwarded-For / CF-Connecting-IP only when TRUST_PROXY is on; the+# bundled docker-compose.yml turns it on, because there the API is reachable+# only through the web container, which overwrites those headers. Running the+# API some other way, leave it off unless whatever sits in front overwrites+# (never appends to or passes through) those headers:+#+# TRUST_PROXY=1+# ── Activity log (optional) ────────────────────────────────────────────────# The admin dashboard shows an activity log: who signed in, who tried and# failed, and every admin action (disabling an account, creating or revoking andiff --git a/README.md b/README.mdindex ae209c69a..17c354572 100644--- a/README.md+++ b/README.md@@ -200,6 +200,8 @@ All via `.env` (see `.env.example`):| `ADMIN_UIDS` | User ids that get the admin dashboard (comma-separated) | *(none)* || `INVITE_ONLY` | Require an invite code to create a profile | *(off)* || `ALLOW_GUEST` | Offer "Continue without account" — set `0` to require a profile | *(on)* |+| `PASSWORD_LOGIN` | Offer name-and-password sign-in next to passkeys (see `docs/SELF_HOSTING.md`) | *(off)* |+| `TRUST_PROXY` | Let the sign-in throttle read the visitor's address from proxy headers | `1` in `docker-compose.yml`, else *(off)* || `AUDIT_LOG` | Record sign-ins and admin actions — set `0` to record nothing | *(on)* || `AUDIT_MAX` | Events kept in the activity log; `0` for no limit | `5000` || `AUDIT_DAYS` | Days kept in the activity log; `0` to keep until `AUDIT_MAX` | `90` |diff --git a/SECURITY.md b/SECURITY.mdindex 4e86fe0f6..594677c29 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -49,7 +49,10 @@ in the thread; there's no objection, and no request to sit on it indefinitely.- **`api/server.js`** — forging or replaying a session cookie, bypassing passkey verification,reading or writing another user's data through `/api/data`, reaching `/api/admin/*` without- being an admin, or creating a profile without a valid code while `INVITE_ONLY=1`.+ being an admin, or creating a profile without a valid code while `INVITE_ONLY=1`. With+ `PASSWORD_LOGIN=1`: getting a password checked past the sign-in throttle, telling which names+ have a password, setting a password on someone else's profile, or using a reset code twice or+ after it expired (`api/password.js`, `api/rate-limit.js`).- **Frontend** — XSS in the React app, or anything that lets a page on another origin read orchange a signed-in user's data.- **Shipped deployment config** — `docker-compose.yml`, `web/nginx.conf`, the two Dockerfiles:@@ -62,17 +65,20 @@ 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 admindashboard, not a leak.-- **Missing rate limiting**, brute force, or "I sent 100k requests and it got slow". The app- has no rate limiting at all and doesn't pretend to; that belongs in the reverse proxy you put- in front of it. Genuine amplification (one small request causing unbounded work) *is* in scope.+- **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 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 thereverse proxy's job, and a script/style policy tight enough to be worth having needs testingagainst the built app rather than being asserted here. A concrete attack that a header wouldhave stopped is still worth reporting.-- Instances served over plain `http://` on a LAN IP. Unsupported: passkeys don't work there and- the session cookie isn't marked `Secure`.+- Instances served over plain `http://` on a LAN IP. Passkeys don't work there, and with+ password sign-in the password and the session cookie (not marked `Secure`) cross that network+ in the clear. That is the documented trade of running without TLS, not a finding.- Scanner output with no working exploit, and `npm audit` findings in build-timedevDependencies (Vite, Vitest, Capacitor CLI) that never reach a running instance.- The GitLab Pages demo build — it has no backend at all, everything stays in that browser.@@ -84,10 +90,28 @@ Read this before hosting openGym for anyone other than yourself.### What it does-- **Passkeys only.** No passwords, no email addresses, no reset flow. Registration and login are+- **Passkeys by default.** No email addresses, no email reset flow. Registration and login areverified server-side by `@simplewebauthn/server` against `expectedOrigin: ORIGIN` and`expectedRPID: RP_ID`, and the authenticator's signature counter is stored and updated on every- login (`api/server.js:561-620`, `api/server.js:622-675`).+ login.+- **Passwords only if the instance asks for them.** With `PASSWORD_LOGIN=1` a profile may also+ set a password (nobody has one until they do). It is hashed with scrypt (N=2^15, r=8, p=1,+ 16-byte random salt, parameters stored with the hash) and compared in constant time; a name+ with no password is checked against a dummy hash, so answer and timing are the same whether or+ not it exists. At most two hashes run at once with a short queue behind them. A first password+ needs a fresh passkey assertion by that profile, a change needs the current password (or that+ assertion), and either ends every other session of the account. It cannot be removed while it+ is the profile's only way in. Password routes keep the origin check below (no login CSRF).+ 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+ 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`).- **Sessions are a signed cookie.** It carries `<uid>:<expiry>:<version>` plus anHMAC-SHA256 tag over it, compared in constant time (`api/server.js:230-243`). The key is 32random bytes generated on first run and written to `./data/secret` with mode `0600`@@ -161,10 +185,20 @@ Read this before hosting openGym for anyone other than yourself.`requireUserVerification: false` (`api/server.js:575`, `api/server.js:644`), so a passkeyreleased without a biometric or PIN is still accepted. In practice: unlocked device ≈ accountaccess.-- **One passkey per profile, and no recovery.** Every successful registration creates a *new*- profile (`api/server.js:600-609`); there is no route to attach a second passkey to an existing- one, and no email or reset path. Lose the passkey and that profile is unreachable — only direct- surgery on `./data` gets it back.+- **One passkey per profile, and recovery only through an admin.** Every successful+ registration creates a *new* profile; there is no route to attach a second passkey to an+ existing one, and no email path. Lose the passkey and that profile is unreachable — unless the+ instance runs `PASSWORD_LOGIN=1`, where an admin can issue a reset code that sets a password on+ 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.- **Disabling someone isn't a ban.** They can still register a fresh profile with a new passkeyunless `INVITE_ONLY=1` is set. It also makes them near-invisible in the activity log: a disabledaccount is refused at the session check, so nothing it does produces an entry except the failed@@ -173,14 +207,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 sentin the clear.-- **No rate limiting anywhere.** Nothing throttles logins, registrations or writes, and- `POST /api/register/options` still answers whether an invite code is valid- (`api/server.js:544`), so an invite-only instance on the open internet should have a rate limit- in front of it. New invite codes are 16 hex characters — 64 bits (`api/server.js:891`) — which+- **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 — whichmakes 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 only- hard limit- in the app is a 5 MB request body (`api/server.js:34`).+ 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 IPaddress unless you set `AUDIT_IP` (`net` truncates to a /24 or /48; the default is `off`). When it is on, theaddress comes from `CF-Connecting-IP`, `X-Forwarded-For`, `X-Real-IP` or, failing all three,@@ -197,13 +230,17 @@ Read this before hosting openGym for anyone other than yourself.and nothing else. Retention is a cap, not an archive: old events are dropped, not exported. Anyadmin 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 — are reachable **without a session**, so with no rate- limit in front (see below) anyone can fill the log with noise. It is an append of ~110 bytes per+ 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 perevent to a capped file, never a rewrite of `db.json`, so the cost is a log full of noise ratherthan a full disk or a slow server.- **A few endpoints answer without a session:** `/api/health` (which includes the total user- count), `/api/config` (whether invite-only is on), `/api/push/public-key`, and the- register/login handshakes.+ count), `/api/config` (whether invite-only and password sign-in are on), `/api/push/public-key`,+ the register/login handshakes, and with `PASSWORD_LOGIN=1` the password sign-in, password+ registration and reset-code routes. Password registration says when a name is already taken+ by a profile with a password, as any sign-up form with usernames does; on an invite-only+ instance only someone with a valid code gets that far.- **Changing `RP_ID` invalidates every existing passkey.** They were bound to the old hostnameand will fail verification against the new one. The data stays on disk but is unreachable untileach user registers again — as a *new* profile. Choose your hostname before anyone registers.diff --git a/api/openapi.yaml b/api/openapi.yamlindex d627992a7..dc63e4e7a 100644--- a/api/openapi.yaml+++ b/api/openapi.yaml@@ -14,12 +14,28 @@ info:HMAC-signed session cookies.### Authentication- Sign-in is **passkey only** (WebAuthn, via `@simplewebauthn/server`). A successful+ Sign-in is by **passkey** (WebAuthn, via `@simplewebauthn/server`). A successful`register/verify` or `login/verify` sets the session cookie; every authenticatedroute then works with that cookie. The paired mobile app has no shared cookie jar,so it redeems a short pairing code (`/api/pair/redeem`) for the *same* signed tokenand sends it as `Authorization: Bearer <token>` instead.+ An instance started with `PASSWORD_LOGIN=1` also offers **name-and-password+ sign-in** (tag `password`): opt-in per profile, scrypt-hashed, throttled, with an+ admin-issued one-time reset code instead of e-mail. Its routes set exactly the same+ 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 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.+### SessionsThe cookie/bearer value is `<payload>.<hmac>` where the payload is`<uid>:<expiry-ms>:<session-version>`, signed with a per-instance secret@@ -33,6 +49,8 @@ info:a mismatch is refused with `403 {"error":"cross-origin request refused"}` on anynon-GET route. Exempt: the WebAuthn and `pair/redeem` routes (each carries its ownone-shot credential in the body) and any request authenticated with a Bearer token.+ The password routes are **not** exempt: a hostile page knows a valid name and+ password of its own, and could otherwise sign a visitor into it (login CSRF).### Environment-dependent behavior- `INVITE_ONLY=1` — registration requires a valid invite code (minted by an admin).@@ -44,6 +62,10 @@ info:- `AUDIT_LOG` (default on), `AUDIT_MAX` (default 5000 events), `AUDIT_DAYS`(default 90), `AUDIT_IP` (`off` | `net` | `full`, default off) — shape the auditlog served by `GET /api/admin/audit`.+ - `PASSWORD_LOGIN=1` — adds the `password` routes and `password_login: true` in+ `GET /api/config`. Off by default.+ - `TRUST_PROXY=1` — the throttle reads the client address from proxy headers (set by+ the bundled `docker-compose.yml`, where only the web container can reach the API).### Conventions- Every response body is JSON with `Cache-Control: no-store`.@@ -78,6 +100,10 @@ tags:description: Passkey (WebAuthn) registration and login, sessions- name: pairingdescription: Mobile-app pairing (code from a signed-in browser tab)+ - name: password+ description: >-+ Optional name-and-password sign-in (`PASSWORD_LOGIN=1`). Every route here is a 404+ while the flag is off.- name: datadescription: Per-user state sync (the whole app state as one JSON blob)- name: push@@ -138,7 +164,14 @@ paths:description: >-When false, the client hides "continue without account".Guest mode is purely client-side and never calls this API.- example: { invite_only: true, allow_guest: false }+ password_login:+ type: boolean+ const: true+ description: >-+ Present (and true) only when the instance runs with+ PASSWORD_LOGIN=1 — the client then offers name-and-password+ sign-in next to passkeys.+ example: { invite_only: true, allow_guest: false, password_login: true }/api/me:get:@@ -476,6 +509,316 @@ paths:schema: { $ref: '#/components/schemas/Error' }example: { error: "invalid or expired code" }+ /api/login/password:+ post:+ tags: [password]+ operationId: loginPassword+ summary: Sign in with a profile name and password+ description: |+ Only a profile that has set a password can sign in this way. The name is the+ profile's display name, compared trimmed, NFKC-normalised and case-insensitively.+ A wrong password, an unknown name and a name whose profile has no password all get+ the same `401` after the same scrypt work, so neither the answer nor its timing says+ which names exist. Five wrong passwords for a name pause it (see *Throttling*);+ passkey sign-in is never paused by this. Sets the same session cookie as+ `/api/login/verify`. **Not** CSRF-exempt.+ security: []+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ required: [name, password]+ properties:+ name: { type: string }+ password: { type: string, maxLength: 256 }+ example: { name: "Ada", password: "correct horse battery staple" }+ responses:+ '200':+ description: Signed in. The session cookie is set.+ headers:+ Set-Cookie:+ description: Session cookie (see /api/register/verify).+ schema: { type: string }+ content:+ application/json:+ schema:+ type: object+ properties:+ user: { $ref: '#/components/schemas/SessionUser' }+ '400':+ description: Name or password missing.+ content:+ application/json:+ schema: { $ref: '#/components/schemas/Error' }+ example: { error: "name and password required", code: "missing" }+ '401':+ description: Wrong name or password — deliberately one answer for every cause.+ content:+ application/json:+ schema: { $ref: '#/components/schemas/Error' }+ example: { error: "wrong name or password", code: "bad-credentials" }+ '403':+ description: The right password for a disabled account.+ content:+ application/json:+ schema: { $ref: '#/components/schemas/Error' }+ example: { error: "this account has been disabled", code: "disabled" }+ '429': { $ref: '#/components/responses/TooManyRequests' }+ '503': { $ref: '#/components/responses/Busy' }++ /api/register/password:+ post:+ tags: [password]+ operationId: registerPassword+ summary: Create a profile with a name and password+ description: |+ For browsers that cannot make a passkey (plain http on a LAN address, some Firefox+ setups). Creates the profile and signs it in. The same invite rules as passkey+ registration apply: on an invite-only instance the code is checked first, checked+ again after hashing, and burned. The password must be 10–256 characters and not one+ of the passwords guessing scripts try first; no two profiles with a password may+ share a name. **Not** CSRF-exempt.+ security: []+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ required: [name, password]+ properties:+ name: { type: string, maxLength: 40 }+ password: { type: string, minLength: 10, maxLength: 256 }+ code: { type: string, description: Invite code (INVITE_ONLY only). }+ example: { name: "Ada", password: "correct horse battery staple", code: "3F9C21A07B54D688" }+ responses:+ '200':+ description: Registered and signed in. The session cookie is set.+ headers:+ Set-Cookie:+ description: Session cookie (see /api/register/verify).+ schema: { type: string }+ content:+ application/json:+ schema:+ type: object+ properties:+ user: { $ref: '#/components/schemas/SessionUser' }+ '400': { $ref: '#/components/responses/PasswordPolicy' }+ '403':+ description: Invite-only and the code is missing, used or revoked.+ content:+ application/json:+ schema: { $ref: '#/components/schemas/Error' }+ example: { error: "a valid invite code is required", code: "invite" }+ '409': { $ref: '#/components/responses/NameTaken' }+ '429': { $ref: '#/components/responses/TooManyRequests' }+ '503': { $ref: '#/components/responses/Busy' }++ /api/login/password-reset:+ post:+ tags: [password]+ operationId: redeemPasswordReset+ summary: Set a new password with an admin's one-time reset code+ description: |+ 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.+ security: []+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ required: [name, code, next]+ properties:+ name: { type: string }+ code: { type: string, example: "K7WQ-2MZP-4HXA" }+ next: { type: string, minLength: 10, maxLength: 256 }+ responses:+ '200':+ description: Password set and signed in. The session cookie is set.+ headers:+ Set-Cookie:+ description: Session cookie (see /api/register/verify).+ schema: { type: string }+ content:+ application/json:+ schema:+ type: object+ properties:+ user: { $ref: '#/components/schemas/SessionUser' }+ '400':+ description: >-+ `reset-invalid` (wrong, used or expired code — one answer for all),+ `missing`, or a password-policy code.+ content:+ application/json:+ schema: { $ref: '#/components/schemas/Error' }+ example: { error: "that reset code is wrong or has expired", code: "reset-invalid" }+ '403':+ description: The account has been disabled.+ content:+ application/json:+ schema: { $ref: '#/components/schemas/Error' }+ example: { error: "this account has been disabled", code: "disabled" }+ '409': { $ref: '#/components/responses/NameTaken' }+ '429': { $ref: '#/components/responses/TooManyRequests' }+ '503': { $ref: '#/components/responses/Busy' }++ /api/account/password:+ get:+ tags: [password]+ operationId: getAccountPassword+ summary: Whether this profile has a password+ responses:+ '200':+ description: The profile's password state.+ content:+ application/json:+ schema:+ type: object+ properties:+ set: { type: boolean }+ setAt: { oneOf: [{ type: string }, { type: 'null' }], description: ISO timestamp. }+ passkeys: { type: integer, description: 'How many passkeys the profile has; 0 means the password cannot be removed.' }+ name: { type: string, description: The name to sign in with. }+ nameTaken:+ type: boolean+ description: Another profile already signs in with this name, so no password can be set here.+ example: { set: true, setAt: "2026-09-23T10:00:00.000Z", passkeys: 1, name: "Ada", nameTaken: false }+ '401': { $ref: '#/components/responses/Unauthorized' }+ post:+ tags: [password]+ operationId: setAccountPassword+ summary: Set or change this profile's password+ description: |+ Proof first: `current` when the profile has a password, or a passkey assertion made+ for this request (`cid` from `POST /api/login/options`, `credential` signed by one of+ *this* profile's passkeys) — the only way to set a first password, and the way to+ replace a forgotten one. A session alone is never enough. Wrong `current` values+ count toward the same pause as wrong sign-ins. On success the session version is+ bumped, which ends every other session and pending pairing code of the account; the+ caller's own continues on a fresh cookie, or a fresh `token` for a Bearer caller.+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ required: [next]+ properties:+ next: { type: string, minLength: 10, maxLength: 256 }+ current: { type: string }+ cid: { type: string }+ credential: { $ref: '#/components/schemas/WebAuthnAuthenticationCredential' }+ responses:+ '200':+ description: Saved. Other sessions have ended.+ headers:+ Set-Cookie:+ description: A fresh session cookie for this browser (cookie callers).+ schema: { type: string }+ content:+ application/json:+ schema:+ type: object+ properties:+ ok: { type: boolean, const: true }+ token: { type: string, description: 'Bearer callers only — the token to use from now on.' }+ '400': { $ref: '#/components/responses/PasswordPolicy' }+ '401': { $ref: '#/components/responses/Unauthorized' }+ '403':+ description: >-+ No acceptable proof: `current-required`, `current-wrong`, `passkey-required`+ (no password yet, so a passkey has to confirm), or `passkey` (the assertion did+ not verify or belongs to another profile).+ content:+ application/json:+ schema: { $ref: '#/components/schemas/Error' }+ example: { error: "your current password is not right", code: "current-wrong" }+ '409': { $ref: '#/components/responses/NameTaken' }+ '429': { $ref: '#/components/responses/TooManyRequests' }+ '503': { $ref: '#/components/responses/Busy' }+ delete:+ tags: [password]+ operationId: removeAccountPassword+ summary: Remove this profile's password+ description: >-+ Refused while the profile has no passkey: the password would be its last way in.+ Existing sessions are left alone (`POST /api/logout/all` ends them). A profile+ without a password gets 200 as well.+ responses:+ '200':+ description: Removed (or there was none).+ content:+ application/json:+ schema: { $ref: '#/components/schemas/Ok' }+ '401': { $ref: '#/components/responses/Unauthorized' }+ '409':+ description: The password is the profile's only way in.+ content:+ application/json:+ schema: { $ref: '#/components/schemas/Error' }+ example: { error: "the password is the only way into this profile", code: "last-way-in" }+ '429': { $ref: '#/components/responses/TooManyRequests' }++ /api/admin/user/password-reset:+ post:+ tags: [admin, password]+ operationId: adminPasswordReset+ summary: 'Admin: issue a one-time password reset code'+ description: |+ Returns a code (12 characters from the pairing alphabet, 60 bits) that is shown+ once, stored only as a SHA-256, valid for 24 h and good for one+ `POST /api/login/password-reset`. Issuing it removes the profile's current password+ and bumps its session version (every session and pending pairing code ends);+ passkeys keep working. A newer code replaces an older one. Admin accounts are+ refused — an admin sets their own password in Settings. Audited as+ `admin.password.reset`.+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ required: [id]+ properties:+ id: { type: string, description: The user id. }+ responses:+ '200':+ description: The code, once.+ content:+ application/json:+ schema:+ type: object+ properties:+ ok: { type: boolean, const: true }+ name: { type: string, description: The name to redeem it with. }+ code: { type: string }+ expires: { type: number, description: Expiry (ms). }+ example: { ok: true, name: "Ada", code: "K7WQ-2MZP-4HXA", expires: 1790000000000 }+ '400':+ description: The target is an admin.+ content:+ application/json:+ schema: { $ref: '#/components/schemas/Error' }+ example: { error: "an admin sets their own password in Settings" }+ '401': { $ref: '#/components/responses/Unauthorized' }+ '403': { $ref: '#/components/responses/Forbidden' }+ '404':+ description: No user with that id.+ content:+ application/json:+ schema: { $ref: '#/components/schemas/Error' }+ example: { error: "no such user" }+ '409': { $ref: '#/components/responses/NameTaken' }+/api/data:get:tags: [data]@@ -870,6 +1213,7 @@ paths:type: arrayitems: { $ref: '#/components/schemas/AdminUserRow' }invite_only: { type: boolean }+ password_login: { type: boolean, description: Present (true) with PASSWORD_LOGIN=1. }now:type: numberdescription: Server time (ms) — for rendering relative times.@@ -1153,6 +1497,41 @@ components:application/json:schema: { $ref: '#/components/schemas/Error' }example: { error: "forbidden" }+ TooManyRequests:+ description: >-+ Paused by the sign-in throttle (see *Throttling* in the description). The request+ was not looked at; try again after `Retry-After` seconds.+ headers:+ Retry-After:+ description: Seconds until the pause ends.+ schema: { type: integer }+ content:+ application/json:+ schema: { $ref: '#/components/schemas/Error' }+ example: { error: "too many attempts — try again later", code: "locked", retryAfter: 60 }+ Busy:+ description: Every password check slot and the short queue behind them are taken.+ headers:+ Retry-After:+ schema: { type: integer }+ content:+ application/json:+ schema: { $ref: '#/components/schemas/Error' }+ example: { error: "the server is busy — try again in a moment", code: "busy" }+ PasswordPolicy:+ description: >-+ The new password breaks the policy — `too-short` (under 10 characters),+ `too-long` (over 256) or `too-common` — or a field is `missing`.+ content:+ application/json:+ schema: { $ref: '#/components/schemas/Error' }+ example: { error: "this password is too easy to guess", code: "too-common" }+ NameTaken:+ description: Another profile already signs in with this name.+ content:+ application/json:+ schema: { $ref: '#/components/schemas/Error' }+ example: { error: "another profile already signs in with this name", code: "name-taken" }schemas:Error:@@ -1162,6 +1541,14 @@ components:error:type: stringdescription: Human-readable message. This is the only error shape the API has.+ code:+ type: string+ description: >-+ A stable reason on the password and throttle routes, for a client to word in+ its own language (`bad-credentials`, `locked`, `too-short`, …).+ retryAfter:+ type: integer+ description: 429 only — the same number of seconds as the Retry-After header.Ok:type: object@@ -1439,6 +1826,9 @@ components:live:oneOf: [{ $ref: '#/components/schemas/Presence' }, { type: 'null' }]description: Currently training, or null.+ password:+ type: boolean+ description: PASSWORD_LOGIN instances only — the profile has a password.Presence:type: object@@ -1464,6 +1854,10 @@ components:disabled: { type: boolean }admin: { type: boolean }invitedBy: { oneOf: [{ type: string }, { type: 'null' }] }+ password: { type: boolean, description: PASSWORD_LOGIN instances only. }+ resetUntil:+ oneOf: [{ type: number }, { type: 'null' }]+ description: PASSWORD_LOGIN instances only — expiry (ms) of an unused reset code.unit: { type: string, enum: [kg, lb] }lastSync: { oneOf: [{ type: number }, { type: 'null' }] }routines:diff --git a/api/password.js b/api/password.jsnew file mode 100644index 000000000..4a4068a7f--- /dev/null+++ b/api/password.js@@ -0,0 +1,185 @@+/* Password hashing and policy for the optional password sign-in (#118). node:crypto only.+ *+ * A hash is stored as one self-describing string, PHC style:+ *+ * $scrypt$v=1$ln=15,r=8,p=1$<salt, base64>$<key, base64>+ *+ * The parameters travel with every hash, so they can be raised later without a migration:+ * verifyPassword() reads whatever a hash says, and needsRehash() tells the caller to store a+ * fresh one after the next successful sign-in.+ *+ * scrypt at N = 2^15, r = 8, p = 1 is 32 MiB and roughly 50–150 ms of one core per attempt on+ * the kind of machine people self-host on — slow enough that a stolen db.json is expensive to+ * crack, cheap enough for a Raspberry Pi to sign someone in. Because every attempt costs that+ * much, the number running at once is capped (SLOTS) and the queue behind it is short (QUEUE):+ * past that the caller is told to come back rather than the process being walked into its+ * memory limit by a burst of logins. */+import crypto from 'node:crypto';++export const MIN_LENGTH = 10;+// Long passphrases are the point, so the cap is only there to bound the work: scrypt runs its+// input through PBKDF2 first, and a 5 MiB "password" would be hashed in full.+export const MAX_LENGTH = 256;++const PARAMS = { ln: 15, r: 8, p: 1 };+const KEYLEN = 32;+const SALT_BYTES = 16;+// 128 * N * r is 32 MiB at these parameters; node refuses anything at or past `maxmem`.+const maxmem = ({ ln, r, p }) => 128 * 2 ** ln * r * p + 16 * 1024 * 1024;++const SLOTS = 2;+const QUEUE = 32;+let running = 0;+const waiting = [];++export class BusyError extends Error {}++const rawScrypt = (secret, salt, params) => new Promise((resolve, reject) => crypto.scrypt(secret, salt, KEYLEN,+ { N: 2 ** params.ln, r: params.r, p: params.p, maxmem: maxmem(params) },+ (err, key) => (err ? reject(err) : resolve(key))));++// Node's scrypt runs on the libuv pool (four threads by default), which also serves fs and dns+// work for everything else; two slots leave the rest of the server room to breathe.+async function scrypt(secret, salt, params) {+ if (running >= SLOTS) {+ if (waiting.length >= QUEUE) throw new BusyError('password check queue full');+ await new Promise(resolve => waiting.push(resolve));+ } else running++;+ try {+ return await rawScrypt(secret, salt, params);+ } finally {+ const next = waiting.shift();+ if (next) next(); else running--;+ }+}++// NFKC, so the same passphrase typed on two keyboards (a composed "é" on one, "e" plus a+// combining accent on the other) is the same passphrase. Nothing else is changed: no trimming,+// no case folding — every character someone chose is part of the secret.+const normalize = pw => String(pw).normalize('NFKC');+export const passwordLength = pw => [...normalize(pw)].length;++const format = (salt, key) => `$scrypt$v=1$ln=${PARAMS.ln},r=${PARAMS.r},p=${PARAMS.p}$${salt.toString('base64')}$${key.toString('base64')}`;++export async function hashPassword(pw) {+ const salt = crypto.randomBytes(SALT_BYTES);+ return format(salt, await scrypt(normalize(pw), salt, PARAMS));+}++function parse(stored) {+ const m = /^\$scrypt\$v=1\$ln=(\d{1,2}),r=(\d{1,2}),p=(\d{1,2})\$([A-Za-z0-9+/]+=*)\$([A-Za-z0-9+/]+=*)$/.exec(String(stored || ''));+ if (!m) return null;+ const params = { ln: +m[1], r: +m[2], p: +m[3] };+ // Bounds on what a stored string may ask for, so a hand-edited db.json cannot make one+ // sign-in allocate gigabytes.+ if (params.ln < 10 || params.ln > 20 || params.r < 1 || params.r > 16 || params.p < 1 || params.p > 16) return null;+ const salt = Buffer.from(m[4], 'base64');+ const key = Buffer.from(m[5], 'base64');+ if (salt.length < 8 || key.length < 16) return null;+ return { params, salt, key };+}++// A well-formed hash of a random secret nobody knows. Signing in as a name that has no+// password runs the same scrypt against this, so the answer takes as long either way and the+// response time does not say which names exist. Made once, outside the slots, so that a full+// queue cannot leave it a rejected promise for good.+let dummy = null;+function dummyHash() {+ if (!dummy) {+ const salt = crypto.randomBytes(SALT_BYTES);+ dummy = rawScrypt(crypto.randomBytes(24).toString('base64'), salt, PARAMS).then(key => format(salt, key));+ dummy.catch(() => { dummy = null; });+ }+ return dummy;+}++/** true only when `pw` matches `stored`. A missing or malformed `stored` does the same work+ * against the dummy hash and answers false. */+export async function verifyPassword(pw, stored) {+ const real = parse(stored);+ const h = real || parse(await dummyHash());+ const key = await scrypt(normalize(pw), h.salt, h.params);+ const same = key.length === h.key.length && crypto.timingSafeEqual(key, h.key);+ return !!real && same;+}++export const needsRehash = stored => {+ const h = parse(stored);+ return !h || h.params.ln !== PARAMS.ln || h.params.r !== PARAMS.r || h.params.p !== PARAMS.p;+};++// How names compare for password sign-in: the same NFKC as above, then trimmed and case-folded,+// so "Ana", "ana " and "ANA" are one name. The stored display name is never changed.+export const nameKey = name => String(name || '').normalize('NFKC').trim().toLowerCase();++/* ------------------------------------------------------------------ policy ----------------+ Length first, which is what actually matters; then a short list of the passwords every+ guessing script tries first. The list only has to hold entries of MIN_LENGTH or more — the+ rest are already too short — plus the stems people pad with digits and a "!" to get past a+ length rule. A leaked-password database would be better and is deliberately not bundled:+ it is megabytes, and an instance that locks an account after a handful of wrong guesses is+ not where the long tail of that list gets tried. */+const COMMON = new Set([+ '1234567890', '0987654321', '12345678910', '123456789012', '1234567890123', '11111111111',+ '1111111111', '0000000000', '9999999999', '1q2w3e4r5t', '1q2w3e4r5t6y', 'q1w2e3r4t5',+ 'qwertyuiop', 'qwertyuiop[]', 'asdfghjkl;', 'asdfghjkl', 'zxcvbnm,./', '1qaz2wsx3edc',+ 'qazwsxedc123', 'qwerty123456', 'qwertz123456', 'azerty123456', 'password12', 'password123',+ 'password1234', 'password12345', 'passw0rd123', 'iloveyou123', 'abcdefghij', 'abcd123456',+ 'abc1234567', 'a1b2c3d4e5', 'aaaaaaaaaa', 'princess123', 'football123', 'baseball123',+ 'sunshine123', 'superman123', 'welcome123', 'welcome1234', 'letmein123', 'trustno1234',+ 'changeme123', 'administrator', 'opengym123', 'opengym1234', 'qwerty1234567', '123qweasdzxc',+ 'zaq12wsxcde3', '1q2w3e4r5t6y7u', 'q1w2e3r4t5y6', '123123123123', '1234512345',+ '123456123456', 'monkey12345', 'dragon12345', 'master12345', 'shadow12345', 'michael123',+ 'jennifer123', 'computer123', 'starwars123', 'whatever123', 'freedom1234', 'pokemon1234',+ 'liverpool123', 'chelsea1234', 'arsenal1234', 'barcelona123', 'realmadrid123', 'juventus123',+ 'hallo12345', 'passwort123', 'passwort1234', 'motdepasse123', 'contrasena123', 'contraseña123',+ 'senha123456', 'parola12345', 'haslo123456', 'wachtwoord123', 'salasana123', 'gymgymgym1'+]);+const STEMS = new Set([+ 'password', 'passwort', 'passw0rd', 'motdepasse', 'contrasena', 'contraseña', 'senha', 'parola',+ 'haslo', 'wachtwoord', 'salasana', 'qwerty', 'qwertz', 'azerty', 'qwertyuiop', 'asdfgh',+ 'letmein', 'welcome', 'iloveyou', 'admin', 'administrator', 'changeme', 'opengym', 'gym',+ 'workout', 'fitness', 'dragon', 'monkey', 'football', 'baseball', 'sunshine', 'princess',+ 'superman', 'batman', 'master', 'shadow', 'trustno', 'abc', 'abcdef', 'secret', 'login'+]);++/** Why a password may not be used, as a short code the client translates — or null. `name` is+ * the profile name it will sign in with: that name plus a few digits is not a password. */+export function passwordProblem(pw, name) {+ if (typeof pw !== 'string') return 'too-short';+ const len = passwordLength(pw);+ if (len < MIN_LENGTH) return 'too-short';+ if (len > MAX_LENGTH) return 'too-long';+ const low = normalize(pw).toLowerCase();+ if (new Set(low).size <= 2) return 'too-common'; // "aaaaaaaaaa", "abababababab"+ if (COMMON.has(low)) return 'too-common';+ // Letters of any script count as the stem; what a length rule gets padded with does not.+ const stem = low.replace(/^[^\p{L}]+|[^\p{L}]+$/gu, '');+ if (STEMS.has(stem)) return 'too-common'; // "Password123!", "qwerty.2024"+ const n = nameKey(name);+ if (n.length >= 3 && stem === n) return 'too-common'; // "ana.2024.2024"+ return null;+}++/* ----------------------------------------------------------------- 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. */+const ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';+export const RESET_TTL_MS = 24 * 3600000;++export function makeResetCode() {+ const bytes = crypto.randomBytes(12);+ // 256 is a multiple of 32, so the modulo is unbiased.+ const raw = Array.from(bytes, b => ALPHABET[b % ALPHABET.length]).join('');+ return raw.slice(0, 4) + '-' + raw.slice(4, 8) + '-' + raw.slice(8);+}+const cleanCode = code => String(code || '').toUpperCase().replace(/[^A-Z0-9]/g, '');+export const hashResetCode = code => crypto.createHash('sha256').update('opengym-reset:' + cleanCode(code)).digest('hex');+export function resetCodeMatches(code, stored) {+ if (!stored || typeof stored.h !== 'string' || !(stored.exp > Date.now())) return false;+ const a = Buffer.from(hashResetCode(code), 'hex');+ const b = Buffer.from(stored.h, 'hex');+ return a.length === b.length && crypto.timingSafeEqual(a, b);+}diff --git a/api/rate-limit.js b/api/rate-limit.jsnew file mode 100644index 000000000..b243fcb8d--- /dev/null+++ b/api/rate-limit.js@@ -0,0 +1,97 @@+/* In-memory throttling for the routes anyone can call without a session (#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.+ *+ * Two shapes, both small enough to read in one sitting:+ *+ * backoff counts failures per key (an address, an account name). The first `free` cost+ * nothing; every one after that locks the key for `baseMs`, doubling each time up+ * 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.+ *+ * 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.+ *+ * `now` is injectable so the tests can walk the clock instead of sleeping. */++const MINUTE = 60000;++function boundedMap(maxKeys, isLocked) {+ const m = new Map();+ return {+ get: k => m.get(k),+ // Re-inserted on every touch, so iteration order is least recently used first.+ 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);+ }+ m.set(k, v);+ },+ delete: k => m.delete(k),+ entries: () => m.entries(),+ get size() { return m.size; }+ };+}++export function createBackoff({ free = 5, baseMs = MINUTE, maxMs = 60 * MINUTE, forgetMs = 24 * 60 * MINUTE, maxKeys = 10000, now = Date.now } = {}) {+ const locked = e => e.until > now();+ const map = boundedMap(maxKeys, locked);+ const fresh = e => e && now() - Math.max(e.last, e.until) <= forgetMs;+ return {+ /** Seconds the key still has to wait, 0 when it may try. */+ retryAfter(key) {+ const e = map.get(key);+ 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);+ },+ /** A success: the key starts over. */+ clear(key) { map.delete(key); },+ sweep() {+ for (const [k, e] of map.entries()) if (!locked(e) && !fresh(e)) map.delete(k);+ },+ get size() { return map.size; }+ };+}++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);+ return {+ /** Counts this request. Returns 0 when it is within budget, else seconds to wait. */+ take(key) {+ let e = map.get(key);+ if (!e || now() - e.start >= windowMs) e = { start: now(), count: 0 };+ e.count += 1;+ map.set(key, e);+ return e.count > max ? Math.max(1, Math.ceil((e.start + windowMs - now()) / 1000)) : 0;+ },+ sweep() {+ for (const [k, e] of map.entries()) if (now() - e.start >= windowMs) map.delete(k);+ },+ get size() { return map.size; }+ };+}diff --git a/api/server.js b/api/server.jsindex 716c13d49..5e18158ba 100644--- a/api/server.js+++ b/api/server.js@@ -19,6 +19,11 @@ import { startCadence } from './coach/cadence.js';import { startWarmup } from './coach/warmup.js';import { dayReminderPush, restTimerPush, testPush } from './push-messages.js';import { verifyError } from './verify-error.js';+import {+ hashPassword, verifyPassword, needsRehash, passwordProblem, passwordLength, nameKey, BusyError,+ MIN_LENGTH, MAX_LENGTH, makeResetCode, hashResetCode, resetCodeMatches, RESET_TTL_MS+} from './password.js';+import { createBackoff, createWindow } from './rate-limit.js';const PORT = +(process.env.PORT || 3000);const DATA = process.env.DATA_DIR || '/data';@@ -34,6 +39,14 @@ const INVITE_ONLY = /^(1|true|yes|on)$/i.test(process.env.INVITE_ONLY || '');// out of is still the wrong front door (#42). Default ON, so existing instances are unchanged;// the polarity is inverted from INVITE_ONLY because the safe default here is the permissive one.const ALLOW_GUEST = !/^(0|false|no|off)$/i.test(process.env.ALLOW_GUEST || '');+// Name-and-password sign-in next to passkeys (#118). Off by default: it adds a second way into+// every account that opts in, so an instance has to ask for it. While it is off every password+// route answers 404 and the app shows none of it; hashes already stored stay where they are.+const PASSWORD_LOGIN = /^(1|true|yes|on)$/i.test(process.env.PASSWORD_LOGIN || '');+// Whether the address a request came from may be read from the headers a proxy sets. Only the+// sign-in throttle asks (limitAddress below); the bundled compose file sets it, because the API+// is reachable there only through the web container, which overwrites those headers.+const TRUST_PROXY = /^(1|true|yes|on)$/i.test(process.env.TRUST_PROXY || '');// 90 days keeps someone who trains a few times a week permanently signed in without a stolen// cookie staying good for a year. Overridable because a family instance and one on the open// internet don't want the same number. Only affects cookies minted from now on — the expiry is@@ -466,6 +479,10 @@ const clearCookie = COOKIE === LEGACY_COOKIE// below are not holes: each of those routes carries its own credential in the body (a WebAuthn// challenge id, a one-shot pairing code), none of them acts on the caller's existing session, and// they have to keep working from the mobile WebView, whose origin is never ORIGIN.+//+// The password routes are deliberately NOT here. A name and a password are a credential too,+// but one a hostile page can know — its own — so an exempt POST /api/login/password would let+// any site sign a visitor into the attacker's account and collect what they log (login CSRF).const CSRF_EXEMPT = new Set(['POST /api/register/options', 'POST /api/register/verify','POST /api/login/options', 'POST /api/login/verify',@@ -596,8 +613,8 @@ 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 unthrottled by design (see 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+// 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.//// On by default. It records strictly less than the instance already holds — every account is in@@ -686,6 +703,336 @@ if (AUDIT_ON) {setInterval(compactAudit, 3600000).unref(); // honour AUDIT_DAYS on an idle instance too}+/* ---------- sign-in throttle ---------- */+// The routes anyone can reach without a session are counted (rate-limit.js), three ways:+//+// 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.+// 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.+//+// 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.+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 });+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+};++// Which address the throttle counts against. Unlike clientIp() above, which only labels a log+// line, this decides who is refused, so a header is believed only when TRUST_PROXY says the API+// sits behind a proxy that sets it. X-Forwarded-For is read from the right: the last entry is+// the one the trusted proxy added, anything before it is whatever the client claimed. An IPv6+// client is counted by its /64, which is what one household or one VPS is handed — counting the+// full address would give an attacker 2^64 fresh starts.+function limitAddress(req) {+ const sock = String(req.socket?.remoteAddress || '');+ let raw = sock;+ if (TRUST_PROXY) {+ const xff = String(req.headers['x-forwarded-for'] || '').split(',').map(v => v.trim()).filter(Boolean);+ raw = String(req.headers['cf-connecting-ip'] || '').trim() || xff[xff.length - 1]+ || String(req.headers['x-real-ip'] || '').trim() || sock;+ }+ raw = raw.replace(/^\[|\]$/g, '');+ const g = ipv6Groups(raw.toLowerCase());+ if (g) {+ if (g.slice(0, 5).every(x => x === 0) && g[5] === 0xffff) return `${g[6] >> 8}.${g[6] & 255}.${g[7] >> 8}.${g[7] & 255}`;+ return g.slice(0, 4).map(x => x.toString(16)).join(':') + '::/64';+ }+ return /^\d{1,3}(\.\d{1,3}){3}$/.test(raw) ? raw : 'unknown';+}+function tooMany(res, secs) {+ json(res, 429, { error: 'too many attempts — try again later', code: 'locked', retryAfter: secs }, { 'Retry-After': String(secs) });+}+// 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) {+ const lock = ADDR_FAILS.fail(kind + '|' + limitAddress(req));+ if (lock) audit(req, 'auth.throttled', { ok: false, msg: kind });+}++/* ---------- 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+// passkey does not — hashing, a policy, the throttle above, a reset an admin can hand out — lives+// in password.js and rate-limit.js; the routes are here because they share the session, invite+// and audit machinery of the passkey routes.+//+// The name someone signs in with is their profile name, compared the way nameKey() folds it.+// Profile names were never unique, so the rule is narrower than that: no two profiles *with a+// password* may share a name. Setting one is refused while the name is taken that way, which is+// also re-checked after every await, where another request could have taken it meanwhile.+const hasPassword = u => !!(u && u.pw && typeof u.pw.h === 'string');+const passwordHolder = k => db.users.find(u => hasPassword(u) && nameKey(u.name) === k) || null;+const nameTaken = (name, exceptId) => { const u = passwordHolder(nameKey(name)); return !!u && u.id !== exceptId; };+const passkeyCount = u => db.creds.filter(c => c.userId === u.id).length;+const publicUser = u => ({ id: u.id, name: u.name, admin: isAdmin(u) });+const POLICY_ERRORS = {+ 'too-short': `the password needs at least ${MIN_LENGTH} characters`,+ 'too-long': `the password can have at most ${MAX_LENGTH} characters`,+ 'too-common': 'this password is too easy to guess'+};+const policyError = (res, problem) => json(res, 400, { error: POLICY_ERRORS[problem], code: problem });+const WRONG = { error: 'wrong name or password', code: 'bad-credentials' };++// A new password ends every other session of the account, the way "sign out everywhere" does,+// pending pairing codes included; the caller's own is re-issued by the route.+function setPassword(user, h) {+ user.pw = { h, set: new Date().toISOString() };+ delete user.pwReset;+ user.sv = sessionVersion(user) + 1;+ for (const [k, v] of pairings) if (v.uid === user.id) pairings.delete(k);+}++// A passkey assertion made just now by the signed-in account itself — how someone who has no+// password yet proves it is them before setting one. A session alone is not enough for that:+// it may be a cookie someone walked off with, and a password would turn it into a way in that+// outlives "sign out everywhere". Same ceremony as /api/login/verify, and the credential has+// to belong to this account.+async function passkeyStepUp(user, body) {+ const c = takeChallenge(body.cid);+ const cred = c && db.creds.find(x => x.id === body.credential?.id && x.userId === user.id);+ if (!cred) return false;+ try {+ const v = await verifyAuthenticationResponse({+ response: body.credential, expectedChallenge: c.challenge, expectedOrigin: ORIGIN, expectedRPID: RP_ID,+ requireUserVerification: false,+ credential: { id: cred.id, publicKey: b64uToBuf(cred.publicKey), counter: cred.counter, transports: cred.transports }+ });+ if (!v.verified) return false;+ cred.counter = v.authenticationInfo.newCounter;+ return true;+ } 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' });+}++const passwordRoutes = {+ 'POST /api/login/password': async (req, res) => {+ const body = await readBody(req);+ 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 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');+ return json(res, 401, WRONG);+ }+ if (user.disabled) {+ 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);+ // 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;+ if (needsRehash(old)) {+ try {+ const h = await hashPassword(pw);+ if (user.pw?.h === old) { user.pw.h = h; saveDb(); }+ } catch (e) { if (!(e instanceof BusyError)) throw e; }+ }+ audit(req, 'auth.password.ok', { user });+ json(res, 200, { user: publicUser(user) }, { 'Set-Cookie': sessionCookie(user) });+ },++ // For browsers that cannot make a passkey at all: plain http on a LAN address, some Firefox+ // setups. Same invite rules as /api/register/*, checked again and burned after the hash.+ 'POST /api/register/password': async (req, res) => {+ const body = await readBody(req);+ const name = text(body.name).trim().slice(0, 40);+ 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 && !invite()) {+ 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', code: 'invite' });+ }+ const problem = passwordProblem(body.password, name);+ if (problem) return policyError(res, problem);+ const taken = () => json(res, 409, { error: 'another profile already signs in with this name', code: 'name-taken' });+ if (nameTaken(name)) return taken();+ const h = await hashPassword(body.password);+ let inv = null;+ if (INVITE_ONLY) {+ inv = invite();+ if (!inv) {+ audit(req, 'auth.register.fail', { ok: false, name, msg: 'invite-invalid' });+ return json(res, 403, { error: 'invite code is no longer valid — ask for a new one', code: 'invite' });+ }+ }+ if (nameTaken(name)) return taken();+ const created = new Date().toISOString();+ const user = { id: crypto.randomBytes(12).toString('base64url'), name, created, pw: { h, set: created } };+ if (inv) { user.invitedBy = inv.code; inv.usedBy = user.id; inv.usedAt = created; }+ db.users.push(user);+ saveDb();+ audit(req, 'auth.register.ok', { user, msg: inv ? inv.code + ' · password' : 'password' });+ json(res, 200, { user: publicUser(user) }, { 'Set-Cookie': sessionCookie(user) });+ },++ // What Settings shows: whether a password is set, and whether it could be removed.+ 'GET /api/account/password': async (req, res) => {+ const user = readSession(req);+ if (!user) return json(res, 401, { error: 'not signed in' });+ json(res, 200, {+ set: hasPassword(user), setAt: user.pw?.set || null, passkeys: passkeyCount(user),+ name: user.name, nameTaken: nameTaken(user.name, user.id)+ });+ },++ // Set or change. Proof first: the current password when there is one, or a passkey assertion+ // made for this request (which is also how a forgotten password is replaced by its owner).+ 'POST /api/account/password': async (req, res) => {+ const s = sessionOf(req);+ if (!s) return json(res, 401, { error: 'not signed in' });+ const { user } = s;+ const body = await readBody(req);+ const problem = passwordProblem(body.next, user.name);+ if (problem) return policyError(res, problem);+ const taken = () => json(res, 409, { error: 'another profile already signs in with this name', code: 'name-taken' });+ if (nameTaken(user.name, user.id)) return taken();+ const k = nameKey(user.name);+ let proof;+ if (body.credential) {+ if (!(await passkeyStepUp(user, body))) {+ audit(req, 'auth.password.fail', { ok: false, user, msg: 'step-up-failed' });+ return json(res, 403, { error: 'the passkey could not be verified', code: 'passkey' });+ }+ proof = 'passkey';+ } else if (hasPassword(user)) {+ const current = typeof body.current === 'string' ? body.current : '';+ 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' });+ }+ ACCOUNT_FAILS.clear('login|' + k);+ proof = 'password';+ } else {+ return json(res, 403, { error: 'confirm with your passkey first', code: 'passkey-required' });+ }+ const h = await hashPassword(body.next);+ // Everything above awaited: an admin reset, a disable or "sign out everywhere" may have ended+ // this session in the meantime, and a password set now would outlive that.+ if (sessionOf(req)?.user !== user) return json(res, 401, { error: 'not signed in' });+ if (nameTaken(user.name, user.id)) return taken();+ const first = !hasPassword(user);+ setPassword(user, h);+ 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.+ if (s.bearer) return json(res, 200, { ok: true, token: makeSession(user) });+ json(res, 200, { ok: true }, { 'Set-Cookie': sessionCookie(user) });+ },++ // Never the last way in: a profile with no passkey keeps its password, because nothing else+ // could sign it in again. Existing sessions are left alone; "sign out everywhere" ends them.+ 'DELETE /api/account/password': async (req, res) => {+ const user = readSession(req);+ if (!user) return json(res, 401, { error: 'not signed in' });+ if (!hasPassword(user)) return json(res, 200, { ok: true });+ if (!passkeyCount(user)) return json(res, 409, { error: 'the password is the only way into this profile', code: 'last-way-in' });+ delete user.pw;+ saveDb();+ audit(req, 'auth.password.remove', { user });+ json(res, 200, { ok: true });+ },++ // An admin hands out a one-time code; the person redeems it below with a password of their+ // choosing. Issuing it ends the old password and every session of the account at once: a+ // reset is asked for when access is lost or in doubt, and a password someone else may know+ // should not keep working for the day the code is valid. Passkeys are left alone. The code is+ // shown once and stored only as a hash. Admin accounts are refused, as they are by disable —+ // one admin must not be able to take over another's login.+ 'POST /api/admin/user/password-reset': async (req, res) => {+ const admin = requireAdmin(req, res); if (!admin) return;+ const body = await readBody(req);+ const u = db.users.find(x => x.id === body.id);+ if (!u) return json(res, 404, { error: 'no such user' });+ if (isAdmin(u)) return json(res, 400, { error: 'an admin sets their own password in Settings' });+ if (nameTaken(u.name, u.id)) return json(res, 409, { error: 'another profile already signs in with this name', code: 'name-taken' });+ const code = makeResetCode();+ delete u.pw;+ u.pwReset = { h: hashResetCode(code), exp: Date.now() + RESET_TTL_MS, by: admin.id };+ u.sv = sessionVersion(u) + 1;+ for (const [k, v] of pairings) if (v.uid === u.id) pairings.delete(k);+ presence.delete(u.id);+ saveDb();+ audit(req, 'admin.password.reset', { user: admin, target: u });+ json(res, 200, { ok: true, name: u.name, code, expires: u.pwReset.exp });+ },++ 'POST /api/login/password-reset': async (req, res) => {+ const body = await readBody(req);+ 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);+ 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) {+ audit(req, 'auth.password.reset', { ok: false, user, msg: 'account-disabled' });+ return json(res, 403, { error: 'this account has been disabled', code: 'disabled' });+ }+ // The code is good and stays good until a password is actually set with it.+ const problem = passwordProblem(body.next, user.name);+ if (problem) return policyError(res, problem);+ if (nameTaken(user.name, user.id)) return json(res, 409, { error: 'another profile already signs in with this name', code: 'name-taken' });+ const h = await hashPassword(body.next);+ // 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);+ saveDb();+ audit(req, 'auth.password.reset', { user });+ json(res, 200, { user: publicUser(user) }, { 'Set-Cookie': sessionCookie(user) });+ }+};+/* ---------- routes ---------- */const routes = {'GET /api/health': async (req, res) => json(res, 200, { ok: true, users: db.users.length }),@@ -696,7 +1043,7 @@ const routes = {// the app it was before the feature existed.'GET /api/config': async (req, res) => {const coach = coachConfig.publicConfig();- json(res, 200, { invite_only: INVITE_ONLY, allow_guest: ALLOW_GUEST, ...(coach ? { coach } : {}) });+ json(res, 200, { invite_only: INVITE_ONLY, allow_guest: ALLOW_GUEST, ...(PASSWORD_LOGIN ? { password_login: true } : {}), ...(coach ? { coach } : {}) });},// A paired phone's token was minted once, at pairing, and nothing ever renewed it: after@@ -722,6 +1069,7 @@ 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');@@ -893,6 +1241,7 @@ 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);@@ -904,6 +1253,9 @@ const routes = {json(res, 200, { token: makeSession(user), user: { id: user.id, name: user.name, admin: isAdmin(user) } });},+ // Absent entirely while PASSWORD_LOGIN is off, so each of them is a plain 404.+ ...(PASSWORD_LOGIN ? passwordRoutes : {}),+// `rev` is the server's own count of writes to this profile (also stored inside the document as// `_rev`, so every other reader of the file — reminder tick, admin, Coach, MCP — is unaffected).// A client pushes it back as `baseRev`, and a write over a document it never saw is refused.@@ -1070,10 +1422,11 @@ const routes = {lastWorkout: last ? last.d : null,lastSync: S._ts || null,hasPush: db.subs.some(s => s.userId === u.id),- live: livePresence(u.id)+ live: livePresence(u.id),+ ...(PASSWORD_LOGIN ? { password: hasPassword(u) } : {})};});- json(res, 200, { users, invite_only: INVITE_ONLY, now: Date.now() });+ json(res, 200, { users, invite_only: INVITE_ONLY, ...(PASSWORD_LOGIN ? { password_login: true } : {}), now: Date.now() });},// Drill-down: full workout history + body-weight log for one user.@@ -1084,7 +1437,12 @@ const routes = {if (!u) return json(res, 404, { error: 'no such user' });const S = readState(u.id) || {};json(res, 200, {- user: { id: u.id, name: u.name, created: u.created || null, disabled: !!u.disabled, admin: isAdmin(u), invitedBy: u.invitedBy || null },+ user: {+ id: u.id, name: u.name, created: u.created || null, disabled: !!u.disabled, admin: isAdmin(u), invitedBy: u.invitedBy || null,+ // Only on an instance with password sign-in: whether they have one, and until when an+ // unused reset code is good.+ ...(PASSWORD_LOGIN ? { password: hasPassword(u), resetUntil: u.pwReset?.exp > Date.now() ? u.pwReset.exp : null } : {})+ },unit: S.unit || 'kg',lastSync: S._ts || null,routines: records(S.routines).map(r => ({ id: r.id, name: r.name, emoji: r.emoji, count: records(r.ex).length })),@@ -1146,9 +1504,9 @@ 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 app 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+ // 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.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() };@@ -1261,12 +1619,24 @@ 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.+ if (key in THROTTLED) {+ const addr = limitAddress(req);+ const kind = THROTTLED[key];+ const wait = AUTH_BURST.take(addr) || (kind ? ADDR_FAILS.retryAfter(kind + '|' + addr) : 0);+ if (wait) return tooMany(res, wait);+ }try { await handler(req, res); }catch (e) {if (e instanceof HttpError) {if (!res.headersSent) json(res, e.status, { error: e.message });return;}+ // Every scrypt slot and the short queue behind them are taken (password.js).+ if (e instanceof BusyError) {+ if (!res.headersSent) json(res, 503, { error: 'the server is busy — try again in a moment', code: 'busy' }, { 'Retry-After': '2' });+ return;+ }console.error(key, e);if (!res.headersSent) json(res, 500, { error: 'server error' });}diff --git a/api/test/password.test.js b/api/test/password.test.jsnew file mode 100644index 000000000..ed0dccdd6--- /dev/null+++ b/api/test/password.test.js@@ -0,0 +1,58 @@+/* Hashing, policy and reset codes for password sign-in (#118), in-process. */+import { test } from 'node:test';+import assert from 'node:assert/strict';+import {+ hashPassword, verifyPassword, needsRehash, passwordProblem, nameKey,+ makeResetCode, hashResetCode, resetCodeMatches+} from '../password.js';++test('a hash is a versioned scrypt string with its own salt, and only the password verifies', async () => {+ const a = await hashPassword('correct horse battery');+ const b = await hashPassword('correct horse battery');+ assert.match(a, /^\$scrypt\$v=1\$ln=15,r=8,p=1\$[A-Za-z0-9+/]+=*\$[A-Za-z0-9+/]+=*$/);+ assert.notEqual(a, b, 'a fresh salt every time');+ assert.equal(await verifyPassword('correct horse battery', a), true);+ assert.equal(await verifyPassword('correct horse batterY', a), false);+ assert.equal(needsRehash(a), false);+ assert.equal(needsRehash(a.replace('ln=15', 'ln=14')), true);+});++test('the same passphrase typed with a composed or a combining accent is the same', async () => {+ const h = await hashPassword('café au lait, bitte');+ assert.equal(await verifyPassword('café au lait, bitte', h), true);+});++test('no stored hash, or a malformed one, never verifies — and still does the work', async () => {+ for (const stored of [undefined, null, '', 'plaintext', '$scrypt$v=1$ln=40,r=8,p=1$c2FsdHNhbHQ=$a2V5a2V5a2V5a2V5a2V5']) {+ assert.equal(await verifyPassword('anything', stored), false);+ }+});++test('policy: length first, then the passwords every script tries first', () => {+ assert.equal(passwordProblem('short', 'Ana'), 'too-short');+ assert.equal(passwordProblem(12345678901, 'Ana'), 'too-short', 'not a string');+ assert.equal(passwordProblem('x'.repeat(257) + 'yz', 'Ana'), 'too-long');+ assert.equal(passwordProblem('correct horse battery staple '.repeat(9).slice(0, 256), 'Ana'), null, '256 characters are fine');+ for (const pw of ['Password123!', 'qwerty.2024!!', '1234567890', 'aaaaaaaaaaaa', 'abababababab', 'ana.2024.2024', 'OpenGym2026!']) {+ assert.equal(passwordProblem(pw, 'Ana'), 'too-common', pw);+ }+ for (const pw of ['correct horse battery', '日本語のパスワードです', '73920184652', 'Ana likes deadlifts']) {+ assert.equal(passwordProblem(pw, 'Ana'), null, pw);+ }+});++test('names compare folded and trimmed', () => {+ assert.equal(nameKey(' Ana Lu '), 'ana lu');+ assert.equal(nameKey('ANA'), 'ana');+});++test('reset codes: readable, compared on the hash, typed any way, dead after expiry', () => {+ const code = makeResetCode();+ assert.match(code, /^[A-HJ-NP-Z2-9]{4}-[A-HJ-NP-Z2-9]{4}-[A-HJ-NP-Z2-9]{4}$/);+ const stored = { h: hashResetCode(code), exp: Date.now() + 60000 };+ assert.equal(stored.h.includes(code), false);+ assert.equal(resetCodeMatches(code.toLowerCase().replace(/-/g, ' '), stored), true);+ assert.equal(resetCodeMatches(makeResetCode(), stored), false);+ assert.equal(resetCodeMatches(code, { ...stored, exp: Date.now() - 1 }), false);+ assert.equal(resetCodeMatches(code, null), false);+});diff --git a/api/test/rate-limit.test.js b/api/test/rate-limit.test.jsnew file mode 100644index 000000000..dc0195727--- /dev/null+++ b/api/test/rate-limit.test.js@@ -0,0 +1,65 @@+/* The two counters behind the sign-in throttle (#118), on a clock the test walks by hand. */+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { createBackoff, createWindow } from '../rate-limit.js';++const clock = () => { const c = { t: 1e12 }; c.now = () => c.t; return c; };++test('backoff: the free failures cost nothing, then each one doubles the pause up to the cap', () => {+ const c = clock();+ const b = createBackoff({ free: 3, baseMs: 1000, maxMs: 5000, forgetMs: 60000, now: c.now });+ assert.deepEqual([b.fail('k'), b.fail('k'), b.fail('k')], [0, 0, 0]);+ assert.equal(b.retryAfter('k'), 0);+ assert.equal(b.fail('k'), 1);+ assert.equal(b.retryAfter('k'), 1);+ c.t += 1000;+ assert.equal(b.retryAfter('k'), 0);+ assert.equal(b.fail('k'), 2);+ c.t += 2000;+ assert.equal(b.fail('k'), 4);+ c.t += 4000;+ assert.equal(b.fail('k'), 5, 'capped');+ assert.equal(b.retryAfter('other'), 0, 'keys are independent');+});++test('backoff: a success or a quiet spell after the pause starts the count over', () => {+ const c = clock();+ const b = createBackoff({ free: 1, baseMs: 1000, maxMs: 60000, forgetMs: 10000, now: c.now });+ b.fail('k'); assert.equal(b.fail('k'), 1);+ b.clear('k');+ assert.equal(b.fail('k'), 0);+ assert.equal(b.fail('k'), 1);+ c.t += 1000 + 10001; // the pause, then longer than forgetMs without a failure+ assert.equal(b.fail('k'), 0);+});++test('backoff: the map stays bounded, and a locked key is the last to be evicted', () => {+ const c = clock();+ const b = createBackoff({ free: 1, baseMs: 60000, maxMs: 60000, forgetMs: 60000, maxKeys: 3, now: c.now });+ b.fail('locked'); b.fail('locked');+ assert.ok(b.retryAfter('locked') > 0);+ for (const k of ['a', 'b', 'c', 'd']) b.fail(k); // a flood of fresh keys+ assert.equal(b.size, 3);+ assert.ok(b.retryAfter('locked') > 0, 'the lock survived the flood');+});++test('backoff: sweep drops keys that are neither locked nor recent', () => {+ const c = clock();+ const b = createBackoff({ free: 5, forgetMs: 1000, now: c.now });+ b.fail('old'); c.t += 2000; b.fail('new');+ b.sweep();+ assert.equal(b.size, 1);+});++test('window: a fixed budget per key, and how long until it refills', () => {+ const c = clock();+ const w = createWindow({ max: 2, windowMs: 10000, now: c.now });+ assert.deepEqual([w.take('k'), w.take('k')], [0, 0]);+ assert.equal(w.take('k'), 10);+ c.t += 4000;+ assert.equal(w.take('k'), 6);+ c.t += 6000;+ assert.equal(w.take('k'), 0);+ c.t += 10000; w.sweep();+ assert.equal(w.size, 0);+});diff --git a/api/test/server-password.test.js b/api/test/server-password.test.jsnew file mode 100644index 000000000..4c2555864--- /dev/null+++ b/api/test/server-password.test.js@@ -0,0 +1,372 @@+/* Password sign-in next to passkeys (#118): the routes, the throttle in front of them, and the+ rules that make a second way into an account safe to offer. Real server.js in a child, the+ same harness as server-pairing.test.js. Every test talks from its own X-Forwarded-For address+ (TRUST_PROXY=1), so one test's failures never pause another's. */+import { test } from 'node:test';+import assert from 'node:assert/strict';+import crypto from 'node:crypto';+import net from 'node:net';+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 { hashPassword, hashResetCode } from '../password.js';++const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');+const SECRET = crypto.randomBytes(32).toString('hex');+const ORIGIN = 'http://localhost:8080';+const b64u = b => Buffer.from(b).toString('base64url');++const mintSession = (uid, sv = 0) => {+ const payload = `${uid}:${Date.now() + 86400000}:${sv}`;+ return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');+};+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)); });+});++// A passkey in software: a P-256 key whose public half goes into db.json as the COSE key the+// server stores, and whose private half signs assertions the way an authenticator would.+function softPasskey() {+ const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', { namedCurve: 'P-256' });+ const jwk = publicKey.export({ format: 'jwk' });+ const cose = Buffer.concat([+ Buffer.from([0xa5, 0x01, 0x02, 0x03, 0x26, 0x20, 0x01, 0x21, 0x58, 0x20]), Buffer.from(jwk.x, 'base64url'),+ Buffer.from([0x22, 0x58, 0x20]), Buffer.from(jwk.y, 'base64url')+ ]);+ const id = crypto.randomBytes(16).toString('base64url');+ let counter = 0;+ return {+ id,+ row: userId => ({ id, userId, publicKey: cose.toString('base64url'), counter: 0, transports: ['internal'] }),+ assertion(challenge) {+ const clientDataJSON = Buffer.from(JSON.stringify({ type: 'webauthn.get', challenge, origin: ORIGIN, crossOrigin: false }));+ const c = Buffer.alloc(4); c.writeUInt32BE(++counter);+ const authData = Buffer.concat([crypto.createHash('sha256').update('localhost').digest(), Buffer.from([0x05]), c]);+ const signature = crypto.sign('sha256', Buffer.concat([authData, crypto.createHash('sha256').update(clientDataJSON).digest()]), privateKey);+ return {+ id, rawId: id, type: 'public-key', clientExtensionResults: {}, authenticatorAttachment: 'platform',+ response: { clientDataJSON: b64u(clientDataJSON), authenticatorData: b64u(authData), signature: b64u(signature), userHandle: null }+ };+ }+ };+}++const GOOD = 'correct horse battery staple';+let pwHash; // one real hash of GOOD, made once — every user below that "has a password" shares it++async function startServer(t, { env = {}, users = [], creds = [], invites = [] } = {}) {+ pwHash ??= await hashPassword(GOOD);+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-pw-'));+ fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });+ fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ users, 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, RP_ID: 'localhost',+ PASSWORD_LOGIN: '1', TRUST_PROXY: '1', INVITE_ONLY: '', ADMIN_UIDS: '', AUDIT_LOG: '1', ...env+ }+ });+ 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}`);+ // Every request looks like the app talking to its own backend unless a test says otherwise.+ h.req = async (method, p, { body, cookie, ip = '198.51.100.1', headers = {} } = {}) => {+ const r = await fetch(`${h.api}${p}`, {+ method,+ headers: { 'Content-Type': 'application/json', 'Sec-Fetch-Site': 'same-origin', 'X-Forwarded-For': ip, ...(cookie ? { Cookie: cookie } : {}), ...headers },+ body: body === undefined ? undefined : JSON.stringify(body)+ });+ const setCookie = r.headers.getSetCookie().find(c => c.startsWith('gymsid=') && !c.startsWith('gymsid=;'));+ return { status: r.status, body: await r.json(), headers: r.headers, cookie: setCookie ? setCookie.split(';')[0] : null };+ };+ h.db = () => JSON.parse(fs.readFileSync(path.join(dataDir, 'db.json'), 'utf8'));+ h.audit = () => { try { return fs.readFileSync(path.join(dataDir, 'audit.log'), 'utf8').trim().split('\n').map(l => JSON.parse(l)); } catch { return []; } };+ return h;+}+const user = (id, name, extra = {}) => ({ id, name, created: new Date().toISOString(), ...extra });+const withPassword = (id, name, extra = {}) => user(id, name, { pw: { h: pwHash, set: new Date().toISOString() }, ...extra });+const login = (h, name, password, ip) => h.req('POST', '/api/login/password', { body: { name, password }, ip });++test('with PASSWORD_LOGIN off every password route is a 404 and /api/config says nothing', async t => {+ const h = await startServer(t, { env: { PASSWORD_LOGIN: '' }, users: [user('u1', 'Ana')] });+ const cookie = `gymsid=${mintSession('u1')}`;+ for (const [m, p] of [+ ['POST', '/api/login/password'], ['POST', '/api/register/password'], ['POST', '/api/login/password-reset'],+ ['GET', '/api/account/password'], ['POST', '/api/account/password'], ['DELETE', '/api/account/password'],+ ['POST', '/api/admin/user/password-reset']+ ]) {+ const r = await h.req(m, p, { body: m === 'GET' ? undefined : { name: 'Ana', password: GOOD }, cookie });+ assert.equal(r.status, 404, `${m} ${p}`);+ }+ const cfg = await h.req('GET', '/api/config');+ assert.equal('password_login' in cfg.body, false);+});++test('signs in with the right password, case-insensitively by profile name, like a passkey does', async t => {+ const h = await startServer(t, { users: [withPassword('u1', 'Ana Lu')] });+ assert.equal((await h.req('GET', '/api/config')).body.password_login, true);+ const r = await login(h, ' ANA lu ', GOOD, '198.51.100.2');+ assert.equal(r.status, 200);+ assert.deepEqual(r.body.user, { id: 'u1', name: 'Ana Lu', admin: false });+ // Same cookie as a passkey sign-in: HttpOnly, SameSite=Lax, no Secure over plain http.+ assert.ok(r.cookie);+ const raw = r.headers.getSetCookie().find(c => c.startsWith('gymsid='));+ assert.match(raw, /HttpOnly/); assert.match(raw, /SameSite=Lax/); assert.doesNotMatch(raw, /Secure/);+ assert.equal((await h.req('GET', '/api/me', { cookie: r.cookie })).status, 200);+ assert.ok(h.audit().some(e => e.ev === 'auth.password.ok' && e.uid === 'u1'));+});++test('a wrong password and an unknown name get the same answer, after the same work', async t => {+ const h = await startServer(t, { users: [withPassword('u1', 'Ana'), user('u2', 'Bea')] });+ const time = async (name, ip) => {+ const t0 = performance.now();+ const r = await login(h, name, 'not the password at all', ip);+ return { r, ms: performance.now() - t0 };+ };+ const known = [], unknown = [], noPw = [];+ for (let i = 0; i < 3; i++) {+ known.push(await time('Ana', '198.51.100.10'));+ unknown.push(await time('Nobody' + i, '198.51.100.11'));+ noPw.push(await time('Bea', '198.51.100.12')); // exists, but has never set a password+ }+ for (const { r } of [...known, ...unknown, ...noPw]) {+ assert.equal(r.status, 401);+ assert.deepEqual(r.body, { error: 'wrong name or password', code: 'bad-credentials' });+ }+ // Both paths run scrypt; a missing one would answer in well under a tenth of the time.+ const median = xs => xs.map(x => x.ms).sort((a, b) => a - b)[1];+ assert.ok(median(unknown) > median(known) * 0.4, `unknown ${median(unknown)} ms vs known ${median(known)} ms`);+ assert.ok(median(noPw) > median(known) * 0.4, `no password ${median(noPw)} ms vs known ${median(known)} ms`);+ // The log names the account behind a wrong password, and never what was typed as a name.+ const fails = h.audit().filter(e => e.ev === 'auth.password.fail');+ assert.ok(fails.some(e => e.uid === 'u1' && e.msg === 'bad-password'));+ assert.ok(fails.every(e => !String(e.name || '').startsWith('Nobody')));+});++test('five wrong passwords pause the name, whoever sends them, and the pause says how long', async t => {+ const h = await startServer(t, { users: [withPassword('u1', 'Ana')] });+ for (let i = 0; i < 5; i++) assert.equal((await login(h, 'ana', 'wrong password ' + i, `198.51.100.${20 + i}`)).status, 401);+ // The sixth still gets its answer and starts the pause…+ assert.equal((await login(h, 'ana', 'wrong password 6', '198.51.100.30')).status, 401);+ // …after which even the right password, from yet another address, waits.+ const r = await login(h, 'Ana', GOOD, '198.51.100.31');+ assert.equal(r.status, 429);+ assert.equal(r.body.code, 'locked');+ const after = +r.headers.get('retry-after');+ assert.ok(after > 0 && after <= 60, `Retry-After ${after}`);+ assert.equal(r.body.retryAfter, after);+ assert.ok(h.audit().some(e => e.ev === 'auth.password.locked' && e.uid === 'u1'));++ // A name nobody has pauses exactly the same way, so a 429 does not reveal that a name exists.+ for (let i = 0; i < 6; i++) await login(h, 'ghost', 'wrong password ' + i, `198.51.100.${40 + i}`);+ assert.equal((await login(h, 'ghost', GOOD, '198.51.100.50')).status, 429);+});++test('twenty failures from one address pause that address for every name; others are unaffected', async t => {+ const h = await startServer(t, { users: [withPassword('u1', 'Ana')] });+ const ip = '203.0.113.7';+ for (let i = 0; i < 20; i++) assert.equal((await login(h, 'name' + i, 'wrong password', ip)).status, 401);+ assert.equal((await login(h, 'name20', 'wrong password', ip)).status, 401); // this one starts the pause+ const r = await login(h, 'Ana', GOOD, ip);+ assert.equal(r.status, 429);+ assert.ok(+r.headers.get('retry-after') > 0);+ assert.equal((await login(h, 'Ana', GOOD, '203.0.113.8')).status, 200);+ // X-Forwarded-For is read from the right: a client-supplied entry in front changes nothing.+ assert.equal((await login(h, 'Ana', GOOD, `192.0.2.99, ${ip}`)).status, 429);+ 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 => {+ 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' });+ 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);+});++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);+});++test('the password routes keep the origin check: no login CSRF', async t => {+ const h = await startServer(t, { users: [withPassword('u1', 'Ana')] });+ const evil = { 'Sec-Fetch-Site': 'cross-site', Origin: 'https://evil.example' };+ for (const p of ['/api/login/password', '/api/register/password', '/api/login/password-reset']) {+ const r = await h.req('POST', p, { body: { name: 'Ana', password: GOOD }, headers: evil, ip: '198.51.100.70' });+ assert.equal(r.status, 403, p);+ assert.equal(r.body.error, 'cross-origin request refused');+ assert.equal(r.cookie, null);+ }+ // A browser without Sec-Fetch-Site falls back to Origin, which has to be ORIGIN.+ const noMeta = await h.req('POST', '/api/login/password', { body: { name: 'Ana', password: GOOD }, headers: { 'Sec-Fetch-Site': '', Origin: 'http://192.168.1.20:8080' }, ip: '198.51.100.71' });+ assert.equal(noMeta.status, 403);+ const ok = await h.req('POST', '/api/login/password', { body: { name: 'Ana', password: GOOD }, headers: { 'Sec-Fetch-Site': '', Origin: ORIGIN }, ip: '198.51.100.72' });+ assert.equal(ok.status, 200);+});++test('registration with a password: policy, unique names among password holders, and the invite', async t => {+ const h = await startServer(t, {+ env: { INVITE_ONLY: '1' },+ users: [withPassword('u1', 'Ana'), user('u2', 'Bea')],+ invites: [{ code: 'INVITE1', created: new Date().toISOString() }]+ });+ const reg = (body, ip = '198.51.100.80') => h.req('POST', '/api/register/password', { body, ip });+ assert.deepEqual((await reg({ name: 'Cleo', password: GOOD })).body.code, 'invite');+ assert.equal((await reg({ name: 'Cleo', password: GOOD, code: 'WRONG' })).status, 403);+ assert.equal((await reg({ name: 'Cleo', password: 'short', code: 'invite1' })).body.code, 'too-short');+ assert.equal((await reg({ name: 'Cleo', password: 'Password123!', code: 'invite1' })).body.code, 'too-common');+ assert.equal((await reg({ name: 'Cleo', password: 'cleo.2024.2024', code: 'invite1' })).body.code, 'too-common');+ assert.equal((await reg({ name: 'ANA', password: GOOD, code: 'invite1' })).status, 409);+ const r = await reg({ name: 'Cleo', password: GOOD, code: 'invite1' });+ assert.equal(r.status, 200);+ assert.ok(r.cookie);+ const db = h.db();+ const cleo = db.users.find(u => u.name === 'Cleo');+ assert.match(cleo.pw.h, /^\$scrypt\$v=1\$ln=15,r=8,p=1\$/);+ assert.equal(JSON.stringify(db).includes(GOOD), false, 'the password itself is never stored');+ assert.equal(db.invites[0].usedBy, cleo.id);+ // Burned: the same code does not let anyone else in.+ assert.equal((await reg({ name: 'Dora', password: GOOD, code: 'INVITE1' }, '198.51.100.81')).status, 403);+ // A name that only a passkey profile has is free to take; the two never meet at sign-in.+ const h2 = await startServer(t, { users: [user('u2', 'Bea')] });+ assert.equal((await h2.req('POST', '/api/register/password', { body: { name: 'bea', password: GOOD }, ip: '198.51.100.82' })).status, 200);+});++test('setting a first password needs a passkey made for it, not just a session', async t => {+ const key = softPasskey(), other = softPasskey();+ const h = await startServer(t, { users: [user('u1', 'Ana'), user('u2', 'Bea')], creds: [key.row('u1'), other.row('u2')] });+ const cookie = `gymsid=${mintSession('u1')}`;+ const ip = '198.51.100.90';+ const status = await h.req('GET', '/api/account/password', { cookie, ip });+ assert.deepEqual(status.body, { set: false, setAt: null, passkeys: 1, name: 'Ana', nameTaken: false });++ assert.equal((await h.req('POST', '/api/account/password', { body: { next: GOOD }, cookie, ip })).body.code, 'passkey-required');+ assert.equal((await h.req('POST', '/api/account/password', { body: { next: GOOD, current: 'anything at all' }, cookie, ip })).body.code, 'passkey-required');++ const stepUp = async pk => {+ const { cid, options } = (await h.req('POST', '/api/login/options', { body: {}, ip })).body;+ return { cid, credential: pk.assertion(options.challenge) };+ };+ // Somebody else's passkey proves nothing about this account.+ const foreign = await h.req('POST', '/api/account/password', { body: { next: GOOD, ...(await stepUp(other)) }, cookie, ip });+ assert.equal(foreign.status, 403);+ assert.equal(foreign.body.code, 'passkey');+ const r = await h.req('POST', '/api/account/password', { body: { next: GOOD, ...(await stepUp(key)) }, cookie, ip });+ assert.equal(r.status, 200);+ assert.ok(r.cookie, 'this session carries on');+ // The old cookie is gone with the session version it carried.+ assert.equal((await h.req('GET', '/api/me', { cookie, ip })).status, 401);+ assert.equal((await h.req('GET', '/api/me', { cookie: r.cookie, ip })).status, 200);+ assert.equal((await login(h, 'ana', GOOD, '198.51.100.91')).status, 200);+ assert.ok(h.audit().some(e => e.ev === 'auth.password.set' && e.msg === 'passkey'));+});++test('changing a password takes the current one and signs out every other session', async t => {+ const h = await startServer(t, { users: [withPassword('u1', 'Ana')] });+ const ip = '198.51.100.100';+ const a = (await login(h, 'Ana', GOOD, ip)).cookie;+ const b = (await login(h, 'Ana', GOOD, ip)).cookie;+ const next = 'a much better passphrase';+ assert.equal((await h.req('POST', '/api/account/password', { body: { next }, cookie: a, ip })).body.code, 'current-required');+ const wrong = await h.req('POST', '/api/account/password', { body: { next, current: 'not it at all' }, cookie: a, ip });+ assert.equal(wrong.status, 403);+ assert.equal(wrong.body.code, 'current-wrong');+ const r = await h.req('POST', '/api/account/password', { body: { next, current: GOOD }, cookie: a, ip });+ assert.equal(r.status, 200);+ assert.equal(h.db().users[0].sv, 1);+ assert.equal((await h.req('GET', '/api/me', { cookie: b, ip })).status, 401, 'the other session ended');+ assert.equal((await h.req('GET', '/api/me', { cookie: r.cookie, ip })).status, 200, 'this one did not');+ assert.equal((await login(h, 'Ana', GOOD, ip)).status, 401);+ assert.equal((await login(h, 'Ana', next, ip)).status, 200);+});++test('wrong current passwords count toward the same pause as wrong sign-ins', async t => {+ const h = await startServer(t, { users: [withPassword('u1', 'Ana')] });+ const cookie = `gymsid=${mintSession('u1')}`;+ for (let i = 0; i < 6; i++) {+ await h.req('POST', '/api/account/password', { body: { next: 'a much better passphrase', current: 'guess number ' + i }, cookie, ip: `198.51.100.${110 + i}` });+ }+ assert.equal((await login(h, 'Ana', GOOD, '198.51.100.120')).status, 429);+});++test('the last way in is never removed', async t => {+ const key = softPasskey();+ const h = await startServer(t, { users: [withPassword('u1', 'Ana'), withPassword('u2', 'Bea')], creds: [key.row('u2')] });+ const ip = '198.51.100.130';+ const only = await h.req('DELETE', '/api/account/password', { cookie: `gymsid=${mintSession('u1')}`, ip });+ assert.equal(only.status, 409);+ assert.equal(only.body.code, 'last-way-in');+ assert.equal((await login(h, 'Ana', GOOD, ip)).status, 200);+ const both = await h.req('DELETE', '/api/account/password', { cookie: `gymsid=${mintSession('u2')}`, ip });+ assert.equal(both.status, 200);+ assert.equal((await login(h, 'Bea', GOOD, ip)).status, 401);+ assert.equal(h.db().users.find(u => u.id === 'u2').pw, undefined);+});++test('an admin reset: a one-time code that ends the old password, works once, and expires', async t => {+ const h = await startServer(t, {+ env: { ADMIN_UIDS: 'adm' },+ users: [+ user('adm', 'Root'), withPassword('u1', 'Ana'), user('u2', 'Bea', { disabled: true }), withPassword('adm2', 'Other', { admin: true }),+ user('u3', 'Cleo', { pwReset: { h: hashResetCode('AAAA-BBBB-CCCC'), exp: Date.now() - 1000, by: 'adm' } })+ ]+ });+ const ip = '198.51.100.140';+ const admin = `gymsid=${mintSession('adm')}`;+ const session = (await login(h, 'Ana', GOOD, ip)).cookie;++ assert.equal((await h.req('POST', '/api/admin/user/password-reset', { body: { id: 'u1' }, cookie: session, ip })).status, 403);+ assert.equal((await h.req('POST', '/api/admin/user/password-reset', { body: { id: 'adm2' }, cookie: admin, ip })).status, 400);+ const issued = await h.req('POST', '/api/admin/user/password-reset', { body: { id: 'u1' }, cookie: admin, ip });+ assert.equal(issued.status, 200);+ const { code } = issued.body;+ assert.match(code, /^[A-HJ-NP-Z2-9]{4}-[A-HJ-NP-Z2-9]{4}-[A-HJ-NP-Z2-9]{4}$/);+ assert.ok(issued.body.expires > Date.now() + 23 * 3600000);+ const stored = h.db().users.find(u => u.id === 'u1');+ assert.equal(JSON.stringify(stored).includes(code), false, 'only a hash of the code is kept');+ assert.equal(stored.pw, undefined);+ // The old password and the old session are both gone.+ assert.equal((await login(h, 'Ana', GOOD, ip)).status, 401);+ assert.equal((await h.req('GET', '/api/me', { cookie: session, ip })).status, 401);++ const redeem = (body, from = ip) => h.req('POST', '/api/login/password-reset', { body, ip: from });+ assert.equal((await redeem({ name: 'Ana', code: 'ZZZZ-ZZZZ-ZZZZ', next: 'a brand new passphrase' })).body.code, 'reset-invalid');+ // A weak new password is refused without using up the code.+ assert.equal((await redeem({ name: 'Ana', code, next: 'short' })).body.code, 'too-short');+ const r = await redeem({ name: 'ana', code: code.toLowerCase().replace(/-/g, ' '), next: 'a brand new passphrase' });+ assert.equal(r.status, 200);+ assert.ok(r.cookie);+ assert.equal((await h.req('GET', '/api/me', { cookie: r.cookie, ip })).status, 200);+ assert.equal((await redeem({ name: 'Ana', code, next: 'another new passphrase' })).body.code, 'reset-invalid', 'single use');+ assert.equal((await login(h, 'Ana', 'a brand new passphrase', ip)).status, 200);+ // Expired, and a disabled account.+ assert.equal((await redeem({ name: 'Cleo', code: 'AAAA-BBBB-CCCC', next: 'a brand new passphrase' })).body.code, 'reset-invalid');+ const bea = (await h.req('POST', '/api/admin/user/password-reset', { body: { id: 'u2' }, cookie: admin, ip })).body.code;+ assert.equal((await redeem({ name: 'Bea', code: bea, next: 'a brand new passphrase' })).status, 403);++ const evs = h.audit().map(e => e.ev);+ assert.ok(evs.includes('admin.password.reset'));+ assert.ok(h.audit().some(e => e.ev === 'auth.password.reset' && e.ok && e.uid === 'u1'));+ assert.ok(h.audit().some(e => e.ev === 'auth.password.reset' && !e.ok));+});++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');+ assert.equal(r.status, 403);+ assert.equal(r.cookie, null);+});diff --git a/docker-compose.yml b/docker-compose.ymlindex 76690fa9d..28abd5f42 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -51,6 +51,10 @@ services:# cannot drift — change it in .env and both follow.- PORT=${PORT:-3000}- DATA_DIR=/data+ # The API is reachable only through the web container here, and that container overwrites+ # X-Forwarded-For / X-Real-IP with the real peer — so the sign-in throttle may count+ # requests by those headers instead of lumping everyone in as "the web container".+ - TRUST_PROXY=${TRUST_PROXY:-1}volumes:- ./data:/data # users, passkeys, per-user state, session secret — BACK THIS UP# Provider credential cache (Codex). A sibling of ./data on purpose: the documented backupdiff --git a/docs/SELF_HOSTING.md b/docs/SELF_HOSTING.mdindex da401d0ca..ddb5f8743 100644--- a/docs/SELF_HOSTING.md+++ b/docs/SELF_HOSTING.md@@ -40,7 +40,8 @@ So `http://localhost:8080` works on the machine running Docker, but **another dephone) cannot use `http://<your-LAN-ip>:8080`** — that's neither localhost nor HTTPS, so thepasskey prompt won't appear. To use openGym from your phone you need a real HTTPS hostname.-(You can still open it over LAN in **guest mode**, which stores data only in that browser.)+(You can still open it over LAN in **guest mode**, which stores data only in that browser — or+turn on **password sign-in**, see [§4](#password-sign-in-optional).)The standalone mobile app (`docs/MOBILE.md`) sidesteps this entirely for its "connect to myserver" mode: instead of a passkey ceremony (impossible from inside its WebView, which never@@ -174,6 +175,84 @@ oauth2-proxy: `skip_auth_routes`. A proxy that cannot exempt a path (Teleport) hicons inline as `data:` URLs instead — Safari 26 accepts those, older iOS does not, which is whythat is not the default here.+### Password sign-in (optional)++Passkeys are the default and stay the recommended way in. Some people cannot use them: a browser+on a plain `http://` LAN address (passkeys need HTTPS or `localhost`), a Firefox setup that only+offers a hardware key, a passkey on a phone that will not move to the desktop. For them there is+an optional name-and-password sign-in, off unless you ask for it:++```bash+PASSWORD_LOGIN=1+```++What changes when it is on:++- The sign-in screen offers **Sign in with password**, and **Create new profile** can use a+ password instead of a passkey — in browsers without passkey support too. With `INVITE_ONLY=1`+ it asks for the invite code exactly like passkey signup does.+- Settings → Account gets a **Password** row. Nobody has a password until they set one there.+ Setting a first password asks for the profile's passkey; changing it asks for the current+ password (or the passkey, if it was forgotten). Either signs the profile out everywhere else,+ and paired phones have to be paired again.+- People sign in with their **profile name** — case and surrounding spaces do not matter — and the+ password. Two profiles with a password cannot share a name; Settings says so when a name is+ already taken that way.+- A password cannot be removed while it is the profile's only way in (a profile made with a+ password has no passkey).++**Resetting a password.** There is no e-mail. In the admin dashboard open the user and choose+**Reset password**. You get a one-time code such as `K7WQ-2MZP-4HXA` to hand over in person or+by message: it is shown once, works once, is valid for 24 hours and is stored only as a hash.+Issuing it removes their current password and signs them out everywhere at once — their passkeys+keep working. They enter their name, the code and a new password under **Sign in with password →+Have a reset code?**. The same code gets someone back in who lost their only passkey (#219).+Admin accounts cannot be reset from the dashboard, so one admin cannot take over another's login;+an admin sets their own password in Settings. Every step is in the activity log+(`admin.password.reset`, `auth.password.reset`, `auth.password.ok` / `fail` / `locked`).++**On a plain-HTTP LAN**, set `ORIGIN` to exactly the address people type, for example+`ORIGIN=http://192.168.1.20:8080`. Browsers do not send `Sec-Fetch-Site` to plain-http addresses,+so the API compares the request's `Origin` with `ORIGIN` instead and refuses sign-ins (and syncs)+that come from anywhere else. Know what you are trading: without TLS the password and the session+cookie (which cannot be `Secure` over http) cross your network in the clear. For a certificate on+a LAN-only address, see [SELF_HOSTING_HTTPS.md](./SELF_HOSTING_HTTPS.md).++**What a password gives up compared with a passkey:**++- A passkey cannot be phished, reused or guessed — it is bound to your hostname and never leaves+ the device. A password can be all three, which is why passkeys stay the default everywhere.+- `db.json` holds a scrypt hash of each password (N=2^15, r=8, p=1, 16-byte random salt). Someone+ with a copy of `./data` can try guesses offline, slowly; a passkey's public key gives them+ nothing to try.+- Guessing online is throttled. Five wrong passwords for a name pause password sign-in for that+ 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.+- 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.+- 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.++**Which address counts as one visitor.** The throttle needs the visitor's address. With the+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`.++**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+that only has a password cannot sign in.++The mobile app keeps pairing: someone with a password signs in to the website with it and pairs+from Settings → "Pair the mobile app", as with a passkey.+## 5. Fitting it into an existing stackThe defaults assume openGym is the only thing here: a service called `api` on port 3000, and nginx