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: a sign-in with the old password still running during a change, reset or removal gets no session (#118)
Duarte Santos10ebe5e1de17
diff --git a/api/openapi.yaml b/api/openapi.yamlindex e42598f03..45b6f3793 100644--- a/api/openapi.yaml+++ b/api/openapi.yaml@@ -521,9 +521,10 @@ paths: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 getthe 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.+ which names exist. So does a password that was right when its check started but+ was changed, reset or removed before the check finished. 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: truediff --git a/api/server.js b/api/server.jsindex 65d8faa16..70aaf473d 100644--- a/api/server.js+++ b/api/server.js@@ -814,7 +814,9 @@ const policyError = (res, problem) => json(res, 400, { error: POLICY_ERRORS[probconst 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.+// pending pairing codes included; the caller's own is re-issued by the route. Always a new+// record, never an edit of the old one: a check still running against the old one tells the two+// apart by that (see POST /api/login/password).function setPassword(user, h) {user.pw = { h, set: new Date().toISOString() };delete user.pwReset;@@ -847,7 +849,8 @@ async function passkeyStepUp(user, body) {// address before it runs, so that checks sent side by side cannot all start under the same// allowance (see the throttle above). Answers 429 itself and returns null when either is paused.// The caller settles it once: failed() for a wrong password, ok() for a right one, void() when the-// answer says nothing against the password — the queue was full, or the account is disabled.+// answer says nothing against the password — the queue was full, the account is disabled, or the+// password changed while it was being checked.function passwordAttempt(req, res, k) {const addr = 'password|' + limitAddress(req);const wait = ACCOUNT_FAILS.retryAfter(k) || ADDR_FAILS.retryAfter(addr);@@ -886,24 +889,35 @@ const passwordRoutes = {const check = passwordAttempt(req, res, k);if (!check) return;const user = passwordHolder(k);- if (!(await check.verify(pw, user?.pw?.h))) {+ const rec = user?.pw;+ if (!(await check.verify(pw, rec?.h))) {check.failed(user, 'bad-password');return json(res, 401, WRONG);}+ // Right for the password read before the await — which a change, an admin reset or a removal+ // may have replaced since (each puts a new record in user.pw or none; only a rehash edits it+ // in place). A session signed now would carry the account's *new* session version and outlive+ // the "signed out everywhere" that came with it, so the old password gets nothing; it is not+ // counted as a wrong one either.+ const still = () => hasPassword(user) && user.pw === rec && passwordHolder(k) === user;+ if (!still()) {+ check.void();+ return json(res, 401, WRONG);+ }if (user.disabled) {check.void();audit(req, 'auth.password.fail', { ok: false, user, msg: 'account-disabled' });return json(res, 403, { error: 'this account has been disabled', code: 'disabled' });}check.ok();- // A hash made with older parameters is replaced now, while the password is at hand — unless- // the password itself changed while the new hash was being made.- const old = user.pw.h;- if (needsRehash(old)) {+ // A hash made with older parameters is replaced now, while the password is at hand.+ if (needsRehash(rec.h)) {try {const h = await hashPassword(pw);- if (user.pw?.h === old) { user.pw.h = h; saveDb(); }+ if (still()) { rec.h = h; saveDb(); }} catch (e) { if (!(e instanceof BusyError)) throw e; }+ // The same question again: the password may have changed while the new hash was made.+ if (!still()) return json(res, 401, WRONG);}audit(req, 'auth.password.ok', { user });json(res, 200, { user: publicUser(user) }, { 'Set-Cookie': sessionCookie(user) });@@ -981,10 +995,13 @@ const passwordRoutes = {if (!current) return json(res, 403, { error: 'enter your current password', code: 'current-required' });const check = passwordAttempt(req, res, k);if (!check) return;- if (!(await check.verify(current, user.pw.h))) {+ const rec = user.pw;+ if (!(await check.verify(current, rec.h))) {check.failed(user, 'bad-current');return wrongCurrent();}+ // Changed or removed while it was being checked: it is no longer the current password.+ if (user.pw !== rec) { check.void(); return wrongCurrent(); }check.ok();proof = 'password';} else {diff --git a/api/test/server-password.test.js b/api/test/server-password.test.jsindex c77ab50e7..d753451eb 100644--- a/api/test/server-password.test.js+++ b/api/test/server-password.test.js@@ -56,6 +56,14 @@ function softPasskey() {const GOOD = 'correct horse battery staple';let pwHash; // one real hash of GOOD, made once — every user below that "has a password" shares it+let oldHash; // GOOD at N = 2^14, as an instance with older parameters would have stored it++// A hash in password.js's own format at a cost other than today's, so a sign-in rehashes it.+const hashAt = (pw, ln) => new Promise((resolve, reject) => {+ const salt = crypto.randomBytes(16);+ crypto.scrypt(pw.normalize('NFKC'), salt, 32, { N: 2 ** ln, r: 8, p: 1, maxmem: 64 * 1024 * 1024 }, (err, key) => err ? reject(err)+ : resolve(`$scrypt$v=1$ln=${ln},r=8,p=1$${salt.toString('base64')}$${key.toString('base64')}`));+});async function startServer(t, { env = {}, users = [], creds = [], invites = [] } = {}) {pwHash ??= await hashPassword(GOOD);@@ -359,6 +367,54 @@ test('changing a password takes the current one and signs out every other sessioassert.equal((await login(h, 'Ana', next, ip)).status, 200);});+// A sign-in with the old password that is still being checked when the password changes must not+// come back with a session: signed after the change, it would carry the new session version and+// outlive the "signed out everywhere" that the change is. Sign-ins every 20 ms from fresh addresses+// straddle the change; whatever cookie any of them got, none may still work afterwards. Run once+// with a current hash and once with one made at older parameters, whose sign-in rehashes — a+// second await before the cookie is signed.+for (const [label, stored] of [['current', () => pwHash], ['older parameters', () => oldHash]]) {+ test(`sign-ins with the old password still running during a change get no lasting session (${label} hash)`, async t => {+ pwHash ??= await hashPassword(GOOD);+ oldHash ??= await hashAt(GOOD, 14);+ const h = await startServer(t, { users: [user('u1', 'Ana', { pw: { h: stored(), set: new Date().toISOString() } })] });+ const owner = `gymsid=${mintSession('u1')}`;+ const next = 'a much better passphrase';+ const attempts = [];+ let change;+ for (let i = 0; i < 30; i++) {+ attempts.push(login(h, 'Ana', GOOD, `198.51.100.${10 + i}`));+ if (i === 3) change = h.req('POST', '/api/account/password', { body: { next, current: GOOD }, cookie: owner, ip: '203.0.113.200' });+ await new Promise(r => setTimeout(r, 20));+ }+ const done = await change;+ assert.equal(done.status, 200, JSON.stringify(done.body));+ const answers = await Promise.all(attempts);+ for (const r of answers) assert.ok([200, 401, 429].includes(r.status), `status ${r.status}`);+ const cookies = answers.map(r => r.cookie).filter(Boolean);+ const alive = [];+ for (const cookie of cookies) if ((await h.req('GET', '/api/me', { cookie })).status === 200) alive.push(cookie);+ assert.equal(alive.length, 0, `${alive.length} of ${cookies.length} sessions signed with the old password survived the change`);+ assert.equal((await h.req('GET', '/api/me', { cookie: done.cookie })).status, 200, "the owner's own session carries on");+ assert.equal((await login(h, 'Ana', next, '203.0.113.201')).status, 200);+ });+}++test('sign-ins still running when an admin resets the password answer 401, not a server error', async t => {+ const h = await startServer(t, { env: { ADMIN_UIDS: 'adm' }, users: [user('adm', 'Root'), withPassword('u1', 'Ana')] });+ const attempts = Array.from({ length: 5 }, (_, i) => login(h, 'Ana', GOOD, `198.51.100.${60 + i}`));+ await new Promise(r => setTimeout(r, 30));+ const reset = await h.req('POST', '/api/admin/user/password-reset', { body: { id: 'u1' }, cookie: `gymsid=${mintSession('adm')}`, ip: '203.0.113.210' });+ assert.equal(reset.status, 200);+ const answers = await Promise.all(attempts);+ assert.ok(answers.some(r => r.status === 401), `none was still running: ${answers.map(r => r.status)}`);+ for (const r of answers) {+ assert.ok([200, 401].includes(r.status), `status ${r.status}: ${JSON.stringify(r.body)}`);+ if (r.cookie) assert.equal((await h.req('GET', '/api/me', { cookie: r.cookie })).status, 401);+ }+ assert.doesNotMatch(h.log, /TypeError/);+});+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')}`;