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 stored hash is checked at its own key length and bounded in memory, and a new password lifts the pause on its name (#118)
Duarte Santos20ac2e1e568b
diff --git a/api/password.js b/api/password.jsindex 4a4068a7f..a4937d21a 100644--- a/api/password.js+++ b/api/password.js@@ -34,19 +34,19 @@ const waiting = [];export class BusyError extends Error {}-const rawScrypt = (secret, salt, params) => new Promise((resolve, reject) => crypto.scrypt(secret, salt, KEYLEN,+const rawScrypt = (secret, salt, params, keylen = KEYLEN) => 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) {+async function scrypt(secret, salt, params, keylen) {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);+ return await rawScrypt(secret, salt, params, keylen);} finally {const next = waiting.shift();if (next) next(); else running--;@@ -71,11 +71,12 @@ function parse(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;+ // sign-in allocate more than 256 MiB or spin for minutes.+ if (params.ln < 10 || params.ln > 17 || params.r < 1 || params.r > 16 || params.p < 1 || params.p > 16) return null;+ if (128 * 2 ** params.ln * params.r > 256 * 1024 * 1024) 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;+ if (salt.length < 8 || key.length < 16 || key.length > 128) return null;return { params, salt, key };}@@ -98,10 +99,13 @@ function dummyHash() {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;+ // Derived at the length the stored key has, so a hash made with another key length still verifies.+ const key = await scrypt(normalize(pw), h.salt, h.params, h.key.length);+ return !!real && crypto.timingSafeEqual(key, h.key);}+/** Makes the dummy hash now, so the first sign-in with an unknown name is not the one that pays+ * for it — and takes measurably longer than every later one. */+export const warmUp = () => dummyHash().then(() => {}, () => {});export const needsRehash = stored => {const h = parse(stored);diff --git a/api/server.js b/api/server.jsindex 5e18158ba..bbe1cb69a 100644--- a/api/server.js+++ b/api/server.js@@ -21,7 +21,7 @@ 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+ MIN_LENGTH, MAX_LENGTH, makeResetCode, hashResetCode, resetCodeMatches, RESET_TTL_MS, warmUp} from './password.js';import { createBackoff, createWindow } from './rate-limit.js';@@ -614,8 +614,8 @@ setInterval(() => { for (const [k, v] of presence) if (Date.now() - v.updatedAt// ./data/audit.log, appended and never rewritten in place. It deliberately does not live in// db.json: that file is rewritten whole on every save, and the login/register handshakes are// unauthenticated and only loosely throttled (see the sign-in throttle below and SECURITY.md), so-// an audit trail in there would turn one bogus request into a full db.json rewrite. A line torn by a crash costs one event and-// is dropped on read.+// an audit trail in there would turn one bogus request into a full db.json rewrite. A line torn+// by a crash costs one event and is dropped on read.//// On by default. It records strictly less than the instance already holds — every account is in// db.json and every workout is in state-<uid>.json, both readable by any admin — and a security@@ -833,6 +833,8 @@ function passwordFailed(req, k, user, msg) {if (lock) audit(req, 'auth.password.locked', user ? { ok: false, user } : { ok: false, msg: 'unknown-name' });}+if (PASSWORD_LOGIN) warmUp();+const passwordRoutes = {'POST /api/login/password': async (req, res) => {const body = await readBody(req);@@ -952,6 +954,8 @@ const passwordRoutes = {if (nameTaken(user.name, user.id)) return taken();const first = !hasPassword(user);setPassword(user, h);+ // Whatever pause wrong guesses put on this name was about a password that no longer exists.+ ACCOUNT_FAILS.clear('login|' + k);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.diff --git a/api/test/password.test.js b/api/test/password.test.jsindex ed0dccdd6..3ff2afa09 100644--- a/api/test/password.test.js+++ b/api/test/password.test.js@@ -1,6 +1,7 @@/* Hashing, policy and reset codes for password sign-in (#118), in-process. */import { test } from 'node:test';import assert from 'node:assert/strict';+import crypto from 'node:crypto';import {hashPassword, verifyPassword, needsRehash, passwordProblem, nameKey,makeResetCode, hashResetCode, resetCodeMatches@@ -17,6 +18,17 @@ test('a hash is a versioned scrypt string with its own salt, and only the passwoassert.equal(needsRehash(a.replace('ln=15', 'ln=14')), true);});+test('a hash with other parameters or another key length still verifies, and asks to be redone', async () => {+ const salt = crypto.randomBytes(16);+ const key = crypto.scryptSync('correct horse battery', salt, 64, { N: 2 ** 14, r: 8, p: 1 });+ const stored = `$scrypt$v=1$ln=14,r=8,p=1$${salt.toString('base64')}$${key.toString('base64')}`;+ assert.equal(await verifyPassword('correct horse battery', stored), true);+ assert.equal(await verifyPassword('correct horse batter', stored), false);+ assert.equal(needsRehash(stored), true);+ // …but not one that would take a gigabyte to check.+ assert.equal(await verifyPassword('correct horse battery', stored.replace('ln=14', 'ln=20')), false);+});+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);