Skip to content

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

Password sign-in: a profile may add an e-mail address and sign in with it instead of its name

Duarte Santos0b7af46c99f3
diff --git a/api/openapi.yaml b/api/openapi.yaml
index e364a32a2..b2061af97 100644
--- a/api/openapi.yaml
+++ b/api/openapi.yaml
@@ -22,15 +22,19 @@ info:
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.
+ admin-issued one-time reset code instead of e-mail. A profile may also add an e-mail
+ address to sign in with instead of its name (`/api/account/email`); no mail is ever
+ sent to it. Its routes set exactly the same cookie. With the flag off (the default)
+ every one of them answers 404.
### Throttling
The `password` routes are counted per client address: at most 60 requests a minute
across them, and wrong answers (a password, a reset code, an invite code on password
- signup) pause the address after 20 for 30 s, doubling up to 15 min. Wrong passwords
- also pause the *name* they were tried against after 5, for 1 min doubling up to 1 h,
- whether or not a profile has that name. A password check counts from the moment it
+ signup, an e-mail address already in use) pause the address after 20 for 30 s,
+ doubling up to 15 min. Wrong passwords also pause the *account* they were tried
+ against after 5, for 1 min doubling up to 1 h — the same pause whether the account
+ was named by its name or its e-mail — and an identifier that names no account is
+ paused the same way, as typed. A password check counts from the moment it
starts, so checks sent at once get no more tries than checks sent one by one. A
paused caller gets `429 {"error": …, "code": "locked", "retryAfter": <s>}` with a
`Retry-After` header. Passkey sign-up and sign-in and the pairing routes are not
@@ -592,15 +596,20 @@ paths:
post:
tags: [password]
operationId: loginPassword
- summary: Sign in with a profile name and password
+ summary: Sign in with a profile name or e-mail and a 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.
+ Only a profile that has set a password can sign in this way. The identifier is the
+ profile's display name or the e-mail address it added (`POST /api/account/email`),
+ compared trimmed, NFKC-normalised and case-insensitively. Send it as `identifier`
+ (what the app sends), `name` (the original field, still accepted) or `email`. In
+ `identifier` and `name`, a value with an `@` is looked up as an e-mail first and
+ then as a name; `email` is looked up only as an e-mail.
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. 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
+ was changed, reset or removed before the check finished. Five wrong passwords for an
+ account pause it, whichever identifier they named it by (see *Throttling*); passkey
+ sign-in is never paused by this. Sets the
same session cookie as `/api/login/verify`. **Not** CSRF-exempt.
security: []
requestBody:
@@ -609,11 +618,17 @@ paths:
application/json:
schema:
type: object
- required: [name, password]
+ required: [password]
+ description: One of `identifier`, `name` or `email`, and the password.
properties:
- name: { type: string }
+ identifier: { type: string, description: A profile name or an e-mail address. }
+ name: { type: string, description: 'The original field: a profile name, or an e-mail address.' }
+ email: { type: string, description: An e-mail address only. }
password: { type: string, maxLength: 256 }
- example: { name: "Ada", password: "correct horse battery staple" }
+ examples:
+ byName: { value: { identifier: "Ada", password: "correct horse battery staple" } }
+ byEmail: { value: { identifier: "[email protected]", password: "correct horse battery staple" } }
+ legacy: { value: { name: "Ada", password: "correct horse battery staple" } }
responses:
'200':
description: Signed in. The session cookie is set.
@@ -659,7 +674,10 @@ paths:
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.
+ share a name. An optional `email` is stored as the profile's sign-in e-mail (see
+ `POST /api/account/email`); one that is in use is refused with `409 email-taken`,
+ which counts against the caller's address like a wrong invite code. **Not**
+ CSRF-exempt.
security: []
requestBody:
required: true
@@ -672,6 +690,7 @@ paths:
name: { type: string, maxLength: 40 }
password: { type: string, minLength: 10, maxLength: 256 }
code: { type: string, description: Invite code (INVITE_ONLY only). }
+ email: { type: string, maxLength: 254, description: Optional sign-in e-mail. }
example: { name: "Ada", password: "correct horse battery staple", code: "3F9C21A07B54D688" }
responses:
'200':
@@ -693,7 +712,14 @@ paths:
application/json:
schema: { $ref: '#/components/schemas/Error' }
example: { error: "a valid invite code is required", code: "invite" }
- '409': { $ref: '#/components/responses/NameTaken' }
+ '409':
+ description: >-
+ `name-taken` (see NameTaken) or `email-taken` — the e-mail is in use by another
+ profile.
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Error' }
+ example: { error: "another profile already uses this e-mail address", code: "email-taken" }
'429': { $ref: '#/components/responses/TooManyRequests' }
'503': { $ref: '#/components/responses/Busy' }
@@ -708,7 +734,8 @@ paths:
A new password that breaks the policy is refused without using up the code. Every
other session of the account ends. Wrong codes count against the caller's address
only (see *Throttling*), never against the name, so they cannot keep a real code
- from working. **Not** CSRF-exempt.
+ from working. The profile is named by its name or its sign-in e-mail, in
+ `identifier`, `name` or `email` as at sign-in. **Not** CSRF-exempt.
security: []
requestBody:
required: true
@@ -716,9 +743,11 @@ paths:
application/json:
schema:
type: object
- required: [name, code, next]
+ required: [code, next]
properties:
- name: { type: string }
+ identifier: { type: string, description: The profile name or its sign-in e-mail. }
+ name: { type: string, description: The original field; an e-mail works here too. }
+ email: { type: string }
code: { type: string, example: "K7WQ-2MZP-4HXA" }
next: { type: string, minLength: 10, maxLength: 256 }
responses:
@@ -772,7 +801,10 @@ paths:
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 }
+ email:
+ oneOf: [{ type: string }, { type: 'null' }]
+ description: The e-mail this profile may sign in with (POST /api/account/email), or null.
+ example: { set: true, setAt: "2026-09-23T10:00:00.000Z", passkeys: 1, name: "Ada", nameTaken: false, email: "[email protected]" }
'401': { $ref: '#/components/responses/Unauthorized' }
post:
tags: [password]
@@ -863,6 +895,94 @@ paths:
'429': { $ref: '#/components/responses/TooManyRequests' }
'503': { $ref: '#/components/responses/Busy' }
+ /api/account/email:
+ post:
+ tags: [password]
+ operationId: setAccountEmail
+ summary: Set, change or remove the e-mail this profile may sign in with
+ description: |
+ An e-mail address to type at `POST /api/login/password` instead of the profile
+ name. No mail is ever sent to it — there is no verification and no reset mail;
+ resets stay the admin's one-time code — so it is only an identifier. Stored
+ trimmed, NFKC-normalised and lower-cased; at most 254 characters; unique across
+ every profile, and never another password-holding profile's name. An empty or null
+ `email` removes it (as `DELETE` does).
+
+ The body carries the same proof as setting a password (see OwnerProof): a session
+ alone is never enough. Saving the address the profile already has answers 200 with
+ no proof asked. An address in use by another profile is refused only after the
+ proof, with `409 email-taken`, and counts against the caller's address and account
+ (20 free, then 30 s doubling to 15 min) — so the answer never costs less than a
+ passkey prompt or a password check, and runs out after a few tries. It says an
+ address is in use somewhere on this instance, never by whom. Audited as
+ `auth.email.set` / `auth.email.change` with the address masked (`a…@e…`).
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ allOf:
+ - $ref: '#/components/schemas/OwnerProof'
+ - type: object
+ properties:
+ email:
+ oneOf: [{ type: string, maxLength: 254 }, { type: 'null' }]
+ example: { email: "[email protected]", current: "correct horse battery staple" }
+ responses:
+ '200':
+ description: Saved (or removed).
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ ok: { type: boolean, const: true }
+ email: { oneOf: [{ type: string }, { type: 'null' }], description: The address as stored. }
+ example: { ok: true, email: "[email protected]" }
+ '400':
+ description: Not an e-mail address.
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Error' }
+ example: { error: "that is not an e-mail address", code: "email-invalid" }
+ '401': { $ref: '#/components/responses/Unauthorized' }
+ '403': { $ref: '#/components/responses/ProofRefused' }
+ '409':
+ description: Another profile already uses this address.
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/Error' }
+ example: { error: "another profile already uses this e-mail address", code: "email-taken" }
+ '429': { $ref: '#/components/responses/TooManyRequests' }
+ '503': { $ref: '#/components/responses/Busy' }
+ delete:
+ tags: [password]
+ operationId: removeAccountEmail
+ summary: Remove the e-mail this profile may sign in with
+ description: >-
+ The profile then signs in by its name only. Takes the same proof as setting one
+ (OwnerProof); a profile without an e-mail gets 200 with none asked. Audited as
+ `auth.email.remove`.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema: { $ref: '#/components/schemas/OwnerProof' }
+ responses:
+ '200':
+ description: Removed (or there was none).
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ ok: { type: boolean, const: true }
+ email: { type: 'null' }
+ '401': { $ref: '#/components/responses/Unauthorized' }
+ '403': { $ref: '#/components/responses/ProofRefused' }
+ '429': { $ref: '#/components/responses/TooManyRequests' }
+ '503': { $ref: '#/components/responses/Busy' }
+
/api/admin/user/password-reset:
post:
tags: [admin, password]
@@ -3241,6 +3361,9 @@ components:
password:
type: boolean
description: PASSWORD_LOGIN instances only — the profile has a password.
+ email:
+ oneOf: [{ type: string }, { type: 'null' }]
+ description: PASSWORD_LOGIN instances only — the e-mail the profile signs in with, if any.
Presence:
type: object
@@ -3267,6 +3390,9 @@ components:
admin: { type: boolean }
invitedBy: { oneOf: [{ type: string }, { type: 'null' }] }
password: { type: boolean, description: PASSWORD_LOGIN instances only. }
+ email:
+ oneOf: [{ type: string }, { type: 'null' }]
+ description: PASSWORD_LOGIN instances only — the sign-in e-mail, if any.
resetUntil:
oneOf: [{ type: number }, { type: 'null' }]
description: PASSWORD_LOGIN instances only — expiry (ms) of an unused reset code.
diff --git a/api/password.js b/api/password.js
index 73de123c1..05a67245c 100644
--- a/api/password.js
+++ b/api/password.js
@@ -116,6 +116,31 @@ export const needsRehash = stored => {
// 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();
+/* ------------------------------------------------------------------ e-mail ----------------
+ An optional second name to sign in with. Nothing is ever sent to it — no verification, no
+ reset mail; an admin's code stays the only reset — so it is only ever compared, the way a name
+ is: the same fold as nameKey() (NFKC, trimmed, lower-cased). Lower-casing the local part is
+ stricter than RFC 5321 allows, and what every mail provider people actually use does anyway;
+ two profiles on one instance told apart only by the case of their address is not a thing
+ worth supporting. The syntax check is deliberately loose — one "@", something before it, a
+ dotted domain after it, no spaces or brackets — because nothing here delivers mail and a
+ stricter rule would only refuse real addresses. 254 is the longest address SMTP can carry. */
+export const EMAIL_MAX = 254;
+const EMAIL_RE = /^[^\s@<>()[\]\\,;:"]{1,64}@(?=.{1,253}$)[^\s@<>()[\]\\,;:"._-][^\s@<>()[\]\\,;:"]*\.[^\s@<>()[\]\\,;:".]{2,}$/u;
+/** The stored form of an address, or null when it is not one. */
+export function normalizeEmail(raw) {
+ if (typeof raw !== 'string') return null;
+ const e = nameKey(raw);
+ if (!e || [...e].length > EMAIL_MAX || !EMAIL_RE.test(e) || e.includes('..')) return null;
+ return e;
+}
+/** What the audit log and the console may say about an address: its first character and its
+ * domain's, nothing that would let someone reading the log write to it. */
+export const maskEmail = e => {
+ const [local = '', domain = ''] = String(e || '').split('@');
+ return (local[0] || '?') + '…@' + (domain[0] || '?') + '…';
+};
+
/* ------------------------------------------------------------------ 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
diff --git a/api/server.js b/api/server.js
index acd93f614..8ec25003d 100644
--- a/api/server.js
+++ b/api/server.js
@@ -22,7 +22,8 @@ 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, warmUp
+ MIN_LENGTH, MAX_LENGTH, makeResetCode, hashResetCode, resetCodeMatches, RESET_TTL_MS, warmUp,
+ normalizeEmail, maskEmail
} from './password.js';
import { createBackoff, createWindow } from './rate-limit.js';
import {
@@ -763,12 +764,15 @@ if (AUDIT_ON) {
// ADDR_FAILS wrong answers per address and per kind (a password or reset code, an invite
// code on password signup, a device-link 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; the count of a name that has a password is
-// never evicted to make room for others. Passkeys are never paused by it.
+// ACCOUNT_FAILS wrong passwords per *account*, 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, an
+// account is not. It is keyed by the account the name or e-mail resolves to
+// (`acct:<id>`), so typing the e-mail after the name was paused meets the same
+// pause; an identifier that resolves to nobody is counted as typed (`id:<fold>`),
+// so a pause looks the same whether an account is there or not. The count of an
+// account with a password is never evicted to make room for others. Passkeys
+// are never paused by it.
//
// A password check is counted against the name and the address the moment it starts, not when
// its answer comes back (passwordAttempt below): scrypt takes a tenth of a second, and counting
@@ -783,7 +787,7 @@ const ADDR_FAILS = createBackoff({ free: 20, baseMs: 30000, maxMs: 15 * 60000, f
const ACCOUNT_FAILS = createBackoff({
free: 5, baseMs: 60000, maxMs: 3600000, forgetMs: 24 * 3600000,
// At most one per profile with a password, so this cannot grow without bound.
- keep: k => !!passwordHolder(k)
+ keep: k => k.startsWith('acct:') && hasPassword(db.users.find(u => u.id === k.slice(5)))
});
setInterval(() => { AUTH_BURST.sweep(); ADDR_FAILS.sweep(); ACCOUNT_FAILS.sweep(); }, 60000).unref();
@@ -793,6 +797,9 @@ const THROTTLED = {
'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,
+ // Setting an e-mail only spends the budget and asks the address's e-mail pause; an address
+ // already in use counts against it (see POST /api/account/email).
+ 'POST /api/account/email': 'email', 'DELETE /api/account/email': null,
// Redeeming a device link (#95). Adding or removing a passkey and making a link only spend the
// budget: the password that may prove them counts its own failures (passwordAttempt).
'POST /api/device-link/options': 'link', 'POST /api/device-link/verify': 'link',
@@ -863,10 +870,58 @@ const hasPassword = u => !!(u && u.pw && typeof u.pw.h === 'string');
const passwordWayIn = u => PASSWORD_LOGIN && hasPassword(u);
const passwordHolder = k => db.users.find(u => hasPassword(u) && nameKey(u.name) === k) || null;
const holdsName = u => hasPassword(u) || !!(u.pwReset && u.pwReset.exp > Date.now());
+// An e-mail is a second name to sign in with (see "e-mail as a sign-in name" below), so a name
+// is also taken by another profile's e-mail — only ever relevant for a name with an "@" in it.
const nameTaken = (name, exceptId) => {
const k = nameKey(name);
- return db.users.some(u => u.id !== exceptId && holdsName(u) && nameKey(u.name) === k);
+ return db.users.some(u => u.id !== exceptId && ((holdsName(u) && nameKey(u.name) === k) || u.email === k));
};
+
+/* ---------- e-mail as a sign-in name ----------
+ Optional, per profile, and only while PASSWORD_LOGIN is on: an address someone may type at the
+ password sign-in instead of their profile name. Nothing is ever sent to it — no verification,
+ no reset mail; resets stay the admin's one-time code — so the address is never proven to be
+ theirs, and it does not need to be: it is only an identifier that points at an account, and the
+ password is still what opens it. Stored as `u.email`, folded by normalizeEmail() (password.js).
+
+ It is unique across every profile, and no profile's address may be another password-holding
+ profile's name (nameTaken above says the same the other way round), so an identifier never
+ points at two accounts. That uniqueness is the one thing an address reveals: setting one that
+ is in use answers 409. The route could be made to hide it — accept the address silently and
+ leave it pointing nowhere — but then someone who typed their own address on a second profile
+ would be told it was saved and find it did not sign in, which is worse. So it answers, and the
+ answer is made expensive instead: only a signed-in owner can ask (session + proveOwner, a
+ passkey prompt or a checked password per try), an address already in use counts against the
+ caller's address and account (20 free, then 30 s doubling to 15 min), and profile creation with
+ an address counts the same way. What that leaves is what the name-taken answer already gives
+ away for names — "some profile here uses this", never which one — at a few tries an hour.
+
+ Sign-in takes it in the same field as the name (loginTarget): an identifier with an "@" is
+ looked up as an address first, then as a name, so a profile name that happens to contain an
+ "@" still signs in. Wrong passwords count against the account the identifier resolves to, so
+ switching between name and address does not reset the pause. The full address is never
+ written to the audit log or the console (maskEmail), is not part of /api/me, the Coach, the
+ MCP bridge or anything shared, and only its owner (GET /api/account/password) and an admin
+ (the user list) ever see it. */
+const emailHolder = e => db.users.find(u => hasPassword(u) && u.email === e) || null;
+const emailTaken = (e, exceptId) => db.users.some(u => u.id !== exceptId && (u.email === e || (holdsName(u) && nameKey(u.name) === e)));
+const EMAIL_ERRORS = {
+ invalid: { error: 'that is not an e-mail address', code: 'email-invalid' },
+ taken: { error: 'another profile already uses this e-mail address', code: 'email-taken' }
+};
+// Who a sign-in body names: `identifier` (what the app sends), `name` (what it sent before, and
+// what older clients still send — an address typed there works too) or `email` (only an address).
+// `key` is what wrong passwords are counted against: the account when there is one, otherwise the
+// identifier as folded, so an unknown one is paused exactly like a known one.
+function loginTarget(body) {
+ const onlyEmail = body.identifier === undefined && body.name === undefined;
+ const k = nameKey(text(body.identifier ?? body.name ?? body.email).slice(0, 300));
+ if (!k) return null;
+ const resolve = () => (k.includes('@') ? emailHolder(k) : null) || (onlyEmail ? null : passwordHolder(k));
+ const user = resolve();
+ return { k, user, resolve, email: k.includes('@'), key: user ? acctKey(user) : 'id:' + k };
+}
+const acctKey = u => 'acct:' + u.id;
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 = {
@@ -911,7 +966,7 @@ async function passkeyStepUp(user, body) {
} catch { return false; }
}
-// One password check against the name `k`, counted as a failure for the name and for the caller's
+// One password check against the account key `k` (loginTarget), counted as a failure for it and for the caller's
// address before it runs, so that checks sent side by side cannot all start under the same
// allowance (see the throttle above). Answers 429 itself and returns null when either is paused.
// The caller settles it once: failed() for a wrong password, ok() for a right one, void() when the
@@ -933,9 +988,9 @@ function passwordAttempt(req, res, k) {
},
// The audit line names the account only when there is one — what someone typed into the
// name field is sometimes their password.
- failed(user, msg) {
- audit(req, 'auth.password.fail', user ? { ok: false, user, msg } : { ok: false, msg: 'unknown-name' });
- if (byName.lock) audit(req, 'auth.password.locked', user ? { ok: false, user } : { ok: false, msg: 'unknown-name' });
+ failed(user, msg, unknown = 'unknown-name') {
+ audit(req, 'auth.password.fail', user ? { ok: false, user, msg } : { ok: false, msg: unknown });
+ if (byName.lock) audit(req, 'auth.password.locked', user ? { ok: false, user } : { ok: false, msg: unknown });
if (byAddr.lock) audit(req, 'auth.throttled', { ok: false, msg: 'password' });
},
// A right password starts the name over; the address keeps whatever else it has run up.
@@ -977,7 +1032,7 @@ async function proveOwner(req, res, user, body, failEv) {
json(res, 403, { error: 'enter your current password', code: 'current-required' });
return null;
}
- const check = passwordAttempt(req, res, nameKey(user.name));
+ const check = passwordAttempt(req, res, acctKey(user));
if (!check) return null;
const rec = user.pw;
if (!(await check.verify(current, rec.h))) {
@@ -992,18 +1047,31 @@ async function proveOwner(req, res, user, body, failEv) {
if (PASSWORD_LOGIN) warmUp();
+// Taking the address away: the profile then signs in by its name only. Asks the same proof as
+// setting one; a profile without an address gets 200 with none asked.
+async function removeEmail(req, res, user, body) {
+ if (!user.email) return json(res, 200, { ok: true, email: null });
+ const proof = await proveOwner(req, res, user, body, 'auth.email.fail');
+ if (!proof) return;
+ if (readSession(req) !== user) return json(res, 401, { error: 'not signed in' });
+ delete user.email;
+ saveDb();
+ audit(req, 'auth.email.remove', { user, msg: proof });
+ json(res, 200, { ok: true, email: null });
+}
+
const passwordRoutes = {
'POST /api/login/password': async (req, res) => {
const body = await readBody(req);
- const k = nameKey(text(body.name).slice(0, 200));
+ const target = loginTarget(body);
const pw = typeof body.password === 'string' ? body.password : '';
- if (!k || !pw) return json(res, 400, { error: 'name and password required', code: 'missing' });
- const check = passwordAttempt(req, res, k);
+ if (!target || !pw) return json(res, 400, { error: 'name and password required', code: 'missing' });
+ const check = passwordAttempt(req, res, target.key);
if (!check) return;
- const user = passwordHolder(k);
+ const { user } = target;
const rec = user?.pw;
if (!(await check.verify(pw, rec?.h))) {
- check.failed(user, 'bad-password');
+ check.failed(user, 'bad-password', target.email ? 'unknown-email' : 'unknown-name');
return json(res, 401, WRONG);
}
// Right for the password read before the await — which a change, an admin reset or a removal
@@ -1011,7 +1079,7 @@ const passwordRoutes = {
// 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;
+ const still = () => hasPassword(user) && user.pw === rec && target.resolve() === user;
if (!still()) {
check.void();
return json(res, 401, WRONG);
@@ -1053,6 +1121,18 @@ const passwordRoutes = {
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();
+ // An e-mail is optional here. One already in use counts against the address, the way it
+ // does in Settings: this route needs no session, so it is the cheaper place to ask.
+ const hasEmail = typeof body.email === 'string' && body.email.trim() !== '';
+ const email = hasEmail ? normalizeEmail(body.email) : null;
+ if (hasEmail && !email) return json(res, 400, EMAIL_ERRORS.invalid);
+ const emailRefused = () => {
+ strikeAddress(req, 'email');
+ audit(req, 'auth.register.fail', { ok: false, name, msg: 'email-taken' });
+ return json(res, 409, EMAIL_ERRORS.taken);
+ };
+ if (email && addressPaused(req, res, 'email')) return;
+ if (email && emailTaken(email)) return emailRefused();
const h = await hashPassword(body.password);
let inv = null;
if (INVITE_ONLY) {
@@ -1063,8 +1143,9 @@ const passwordRoutes = {
}
}
if (nameTaken(name)) return taken();
+ if (email && emailTaken(email)) return emailRefused();
const created = new Date().toISOString();
- const user = { id: crypto.randomBytes(12).toString('base64url'), name, created, pw: { h, set: created } };
+ const user = { id: crypto.randomBytes(12).toString('base64url'), name, created, pw: { h, set: created }, ...(email ? { email } : {}) };
if (inv) { user.invitedBy = inv.code; inv.usedBy = user.id; inv.usedAt = created; }
db.users.push(user);
saveDb();
@@ -1078,7 +1159,9 @@ const passwordRoutes = {
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)
+ name: user.name, nameTaken: nameTaken(user.name, user.id),
+ // Only the owner's own session is ever handed their address.
+ email: user.email || null
});
},
@@ -1093,7 +1176,6 @@ const passwordRoutes = {
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);
const proof = await proveOwner(req, res, user, body, 'auth.password.fail');
if (!proof) return;
const h = await hashPassword(body.next);
@@ -1103,8 +1185,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(k);
+ // Whatever pause wrong guesses put on this account was about a password that no longer exists.
+ ACCOUNT_FAILS.clear(acctKey(user));
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.
@@ -1138,6 +1220,51 @@ const passwordRoutes = {
json(res, 200, { ok: true });
},
+ // Set, change (`email`) or remove (`email` empty or null, or DELETE) the address this profile
+ // may sign in with. The same proof as a password (proveOwner): an address that points at the
+ // account is part of how someone gets in, and a copied session must not choose it. An address
+ // already in use is refused only after the proof, and counts against the caller's address and
+ // account, so asking whether an address is in use costs a passkey prompt or a password check
+ // and runs out after a few tries (see "e-mail as a sign-in name" above).
+ 'POST /api/account/email': 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);
+ if (body.email == null || (typeof body.email === 'string' && body.email.trim() === '')) return removeEmail(req, res, user, body);
+ const email = normalizeEmail(body.email);
+ if (!email) return json(res, 400, EMAIL_ERRORS.invalid);
+ if (email === user.email) return json(res, 200, { ok: true, email });
+ const acct = 'email|' + acctKey(user);
+ const paused = () => {
+ const wait = ADDR_FAILS.retryAfter(acct);
+ if (wait) tooMany(res, wait);
+ return wait > 0 || addressPaused(req, res, 'email');
+ };
+ if (paused()) return;
+ const proof = await proveOwner(req, res, user, body, 'auth.email.fail');
+ if (!proof) return;
+ if (sessionOf(req)?.user !== user) return json(res, 401, { error: 'not signed in' });
+ if (paused()) return;
+ if (emailTaken(email, user.id)) {
+ if (proof === 'passkey') saveDb(); // the confirming passkey's counter and last use
+ strikeAddress(req, 'email');
+ ADDR_FAILS.fail(acct);
+ audit(req, 'auth.email.fail', { ok: false, user, msg: 'email-taken' });
+ return json(res, 409, EMAIL_ERRORS.taken);
+ }
+ const first = !user.email;
+ user.email = email;
+ saveDb();
+ audit(req, first ? 'auth.email.set' : 'auth.email.change', { user, msg: proof + ' · ' + maskEmail(email) });
+ json(res, 200, { ok: true, email });
+ },
+ 'DELETE /api/account/email': async (req, res) => {
+ const user = readSession(req);
+ if (!user) return json(res, 401, { error: 'not signed in' });
+ removeEmail(req, res, user, await readBody(req));
+ },
+
// 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
@@ -1165,14 +1292,15 @@ const passwordRoutes = {
'POST /api/login/password-reset': async (req, res) => {
const body = await readBody(req);
- const k = nameKey(text(body.name).slice(0, 200));
+ // The name or the e-mail, in the same fields sign-in takes them (loginTarget).
+ const k = nameKey(text(body.identifier ?? body.name ?? body.email).slice(0, 300));
const code = text(body.code).slice(0, 64);
if (!k || !code) return json(res, 400, { error: 'name and code required', code: 'missing' });
// Wrong codes count against the address only. A per-name pause would add nothing against a
// 60-bit code that lives a day, and would let anyone who knows the name keep the real code
// refused for that whole day — after the reset has already removed the old password.
if (addressPaused(req, res, 'password')) return;
- const find = () => db.users.find(u => u.pwReset && nameKey(u.name) === k && resetCodeMatches(code, u.pwReset)) || null;
+ const find = () => db.users.find(u => u.pwReset && (nameKey(u.name) === k || u.email === 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' });
const taken = () => json(res, 409, { error: 'another profile already signs in with this name', code: 'name-taken' });
@@ -1194,7 +1322,7 @@ const passwordRoutes = {
if (find() !== user) return invalid();
if (nameTaken(user.name, user.id)) return taken();
setPassword(user, h);
- ACCOUNT_FAILS.clear(k);
+ ACCOUNT_FAILS.clear(acctKey(user));
saveDb();
audit(req, 'auth.password.reset', { user });
json(res, 200, { user: publicUser(user) }, { 'Set-Cookie': sessionCookie(user) });
@@ -2010,7 +2138,9 @@ const routes = {
lastSync: S._ts || null,
hasPush: db.subs.some(s => s.userId === u.id),
live: livePresence(u.id),
- ...(PASSWORD_LOGIN ? { password: hasPassword(u) } : {})
+ // The sign-in e-mail is an admin's to see (to hand out a reset code, to tell two
+ // profiles apart), and only while the instance takes passwords at all.
+ ...(PASSWORD_LOGIN ? { password: hasPassword(u), email: u.email || null } : {})
};
});
json(res, 200, { users, invite_only: INVITE_ONLY, ...(PASSWORD_LOGIN ? { password_login: true } : {}), now: Date.now() });
@@ -2028,7 +2158,7 @@ const routes = {
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 } : {})
+ ...(PASSWORD_LOGIN ? { password: hasPassword(u), email: u.email || null, resetUntil: u.pwReset?.exp > Date.now() ? u.pwReset.exp : null } : {})
},
unit: S.unit || 'kg',
lastSync: S._ts || null,
diff --git a/api/test/server-email.test.js b/api/test/server-email.test.js
new file mode 100644
index 000000000..04efabb33
--- /dev/null
+++ b/api/test/server-email.test.js
@@ -0,0 +1,346 @@
+/* The sign-in e-mail next to the profile name (password sign-in, #118): set, changed and removed
+ only with the owner's proof, unique across profiles, typed at sign-in and at a reset in place of
+ the name — with the same pause behind both — and never written out in full anywhere but the
+ owner's own account row and the admin's user list. Same harness as server-password.test.js. */
+import { test, before } from 'node:test';
+import assert from 'node:assert/strict';
+import crypto from 'node:crypto';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { spawn } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import { hashPassword, hashResetCode, normalizeEmail, maskEmail } from '../password.js';
+import { boundPort } from './helpers.mjs';
+
+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');
+};
+
+// 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
+let oldHash; // GOOD at N = 2^14, as an instance with older parameters would have stored it
+// Made before any test runs: withPassword() reads it while a test's arguments to startServer are
+// still being built, so a test run on its own would otherwise give its user no hash at all.
+before(async () => { pwHash ??= await hashPassword(GOOD); });
+
+// 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);
+ 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 child = spawn(process.execPath, ['server.js'], {
+ cwd: API, stdio: ['ignore', 'pipe', 'pipe'],
+ env: {
+ ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN, RP_ID: 'localhost',
+ PASSWORD_LOGIN: '1', TRUST_PROXY: '1', INVITE_ONLY: '', ADMIN_UIDS: '', AUDIT_LOG: '1', ...env
+ }
+ });
+ const h = { api: '', 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 }); });
+ // The boot line carries the port the listener bound, so it is both the address and the
+ // readiness signal — see boundPort in helpers.mjs for why the test does not pick one.
+ h.api = `http://127.0.0.1:${await boundPort(child, () => 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 signIn = (h, body, ip) => h.req('POST', '/api/login/password', { body, ip });
+const setEmail = (h, cookie, body, ip) => h.req('POST', '/api/account/email', { body, cookie, ip });
+const WRONG = { error: 'wrong name or password', code: 'bad-credentials' };
+// Nothing in the audit log, the process output or db.json's neighbours may carry the address.
+const leaks = (h, needle) => {
+ const audit = (() => { try { return fs.readFileSync(path.join(h.dataDir, 'audit.log'), 'utf8'); } catch { return ''; } })();
+ return audit.toLowerCase().includes(needle) || h.log.toLowerCase().includes(needle);
+};
+
+test('normalizeEmail folds and checks the way sign-in compares; maskEmail keeps two characters', () => {
+ assert.equal(normalizeEmail(' [email protected] '), '[email protected]');
+ assert.equal(normalizeEmail('ada@example.com'), '[email protected]'); // NFKC, like names
+ assert.equal(normalizeEmail('[email protected]'), '[email protected]');
+ for (const bad of ['', 'ada', 'ada@', '@example.com', 'ada@example', '[email protected]', '[email protected]', 'a [email protected]', 'ada@@example.com', 'x'.repeat(250) + '@ex.com', 42, null])
+ assert.equal(normalizeEmail(bad), null, String(bad));
+ assert.equal(normalizeEmail('a@' + 'b'.repeat(245) + '.com'), 'a@' + 'b'.repeat(245) + '.com'); // 251 characters
+ assert.equal(maskEmail('[email protected]'), 'a…@e…');
+});
+
+test('with PASSWORD_LOGIN off the e-mail routes are 404s, sign-in by e-mail too, and admins see no address', async t => {
+ const h = await startServer(t, {
+ env: { PASSWORD_LOGIN: '', ADMIN_UIDS: 'adm' },
+ users: [user('adm', 'Root'), withPassword('u1', 'Ana', { email: '[email protected]' })]
+ });
+ const cookie = `gymsid=${mintSession('u1')}`;
+ assert.equal((await setEmail(h, cookie, { email: '[email protected]', current: GOOD })).status, 404);
+ assert.equal((await h.req('DELETE', '/api/account/email', { body: { current: GOOD }, cookie })).status, 404);
+ assert.equal((await signIn(h, { email: '[email protected]', password: GOOD })).status, 404);
+ const list = await h.req('GET', '/api/admin/users', { cookie: `gymsid=${mintSession('adm')}` });
+ assert.equal(list.status, 200);
+ assert.ok(list.body.users.every(u => !('email' in u)));
+ const one = await h.req('GET', '/api/admin/user?id=u1', { cookie: `gymsid=${mintSession('adm')}` });
+ assert.equal('email' in one.body.user, false);
+ // The stored address stays where it is for when the flag comes back.
+ assert.equal(h.db().users.find(u => u.id === 'u1').email, '[email protected]');
+});
+
+test('signs in by e-mail in any of the three fields, case-insensitively; the name still works', async t => {
+ const h = await startServer(t, { users: [withPassword('u1', 'Ana', { email: '[email protected]' })] });
+ for (const [i, body] of [
+ { identifier: ' [email protected] ', password: GOOD },
+ { name: '[email protected]', password: GOOD }, // an older app sends everything as `name`
+ { email: '[email protected]', password: GOOD },
+ { identifier: 'ana', password: GOOD },
+ { name: 'ANA', password: GOOD }
+ ].entries()) {
+ const r = await signIn(h, body, `198.51.100.${10 + i}`);
+ assert.equal(r.status, 200, JSON.stringify(body));
+ assert.deepEqual(r.body.user, { id: 'u1', name: 'Ana', admin: false });
+ assert.ok(r.cookie);
+ }
+ // `email` means an address and nothing else: the name typed there is not looked up.
+ assert.deepEqual((await signIn(h, { email: 'Ana', password: GOOD }, '198.51.100.20')).body, WRONG);
+ // The session answers carry no address.
+ const me = await h.req('GET', '/api/me', { cookie: (await signIn(h, { identifier: '[email protected]', password: GOOD }, '198.51.100.21')).cookie });
+ assert.equal(JSON.stringify(me.body).includes('example.com'), false);
+});
+
+test('a wrong password, an unknown address and an address without a password get the one answer; nothing logs the address', async t => {
+ const h = await startServer(t, {
+ users: [withPassword('u1', 'Ana', { email: '[email protected]' }), user('u2', 'Bea', { email: '[email protected]' })]
+ });
+ for (const [i, identifier] of ['[email protected]', '[email protected]', '[email protected]'].entries()) {
+ const r = await signIn(h, { identifier, password: 'not the password at all' }, `198.51.100.${30 + i}`);
+ assert.equal(r.status, 401, identifier);
+ assert.deepEqual(r.body, WRONG);
+ }
+ const fails = h.audit().filter(e => e.ev === 'auth.password.fail');
+ assert.ok(fails.some(e => e.uid === 'u1' && e.msg === 'bad-password'));
+ assert.equal(fails.filter(e => e.msg === 'unknown-email').length, 2);
+ assert.equal(leaks(h, 'example.com'), false);
+});
+
+test('a profile name with an "@" in it still signs in by name', async t => {
+ const h = await startServer(t, { users: [withPassword('u1', '[email protected]')] });
+ const r = await signIn(h, { identifier: '[email protected]', password: GOOD }, '198.51.100.40');
+ assert.equal(r.status, 200);
+ assert.equal(r.body.user.id, 'u1');
+});
+
+test('wrong passwords by name and by e-mail count against the one account: switching does not reset the pause', async t => {
+ const h = await startServer(t, { users: [withPassword('u1', 'Ana', { email: '[email protected]' })] });
+ for (let i = 0; i < 3; i++) assert.equal((await signIn(h, { identifier: 'Ana', password: 'wrong ' + i }, `198.51.100.${50 + i}`)).status, 401);
+ for (let i = 0; i < 3; i++) assert.equal((await signIn(h, { identifier: '[email protected]', password: 'wrong ' + i }, `198.51.100.${60 + i}`)).status, 401);
+ // Six wrong in all: the account is paused however it is named, the right password included.
+ for (const body of [{ identifier: 'ana', password: GOOD }, { email: '[email protected]', password: GOOD }, { name: '[email protected]', password: GOOD }]) {
+ const r = await signIn(h, body, '198.51.100.70');
+ assert.equal(r.status, 429, JSON.stringify(body));
+ assert.equal(r.body.code, 'locked');
+ }
+ assert.ok(h.audit().some(e => e.ev === 'auth.password.locked' && e.uid === 'u1'));
+ // An address nobody has is paused the same way on its own, as typed — and pauses nobody else.
+ const h2 = await startServer(t, { users: [withPassword('u1', 'Ana', { email: '[email protected]' })] });
+ for (let i = 0; i < 6; i++) await signIn(h2, { identifier: '[email protected]', password: 'wrong ' + i }, `198.51.100.${80 + i}`);
+ assert.equal((await signIn(h2, { identifier: '[email protected]', password: GOOD }, '198.51.100.90')).status, 429);
+ assert.equal((await signIn(h2, { identifier: '[email protected]', password: GOOD }, '198.51.100.91')).status, 200);
+});
+
+test('a wrong current password given to change the address counts toward the same account pause', async t => {
+ const h = await startServer(t, { users: [withPassword('u1', 'Ana', { email: '[email protected]' })] });
+ const cookie = `gymsid=${mintSession('u1')}`;
+ for (let i = 0; i < 6; i++) {
+ const r = await setEmail(h, cookie, { email: '[email protected]', current: 'wrong ' + i }, `198.51.100.${100 + i}`);
+ assert.equal(r.status, 403);
+ assert.equal(r.body.code, 'current-wrong');
+ }
+ assert.equal((await signIn(h, { identifier: '[email protected]', password: GOOD }, '198.51.100.110')).status, 429);
+});
+
+test('setting, changing and removing the address needs the owner’s proof, never the session alone', async t => {
+ const pk = softPasskey();
+ const h = await startServer(t, {
+ users: [withPassword('u1', 'Ana'), user('u2', 'Bea')],
+ creds: [pk.row('u2')]
+ });
+ const ana = `gymsid=${mintSession('u1')}`;
+ const bea = `gymsid=${mintSession('u2')}`;
+ assert.equal((await h.req('POST', '/api/account/email', { body: { email: '[email protected]' } })).status, 401);
+ let r = await setEmail(h, ana, { email: '[email protected]' }, '198.51.100.120');
+ assert.equal(r.status, 403); assert.equal(r.body.code, 'current-required');
+ r = await setEmail(h, ana, { email: '[email protected]', current: 'not it at all' }, '198.51.100.121');
+ assert.equal(r.status, 403); assert.equal(r.body.code, 'current-wrong');
+ assert.equal(h.db().users.find(u => u.id === 'u1').email, undefined);
+ r = await setEmail(h, ana, { email: ' [email protected] ', current: GOOD }, '198.51.100.122');
+ assert.equal(r.status, 200);
+ assert.deepEqual(r.body, { ok: true, email: '[email protected]' });
+ assert.equal(h.db().users.find(u => u.id === 'u1').email, '[email protected]');
+ // The same address again is no change and asks for nothing.
+ assert.equal((await setEmail(h, ana, { email: '[email protected]' }, '198.51.100.123')).status, 200);
+ // Changing it asks again.
+ assert.equal((await setEmail(h, ana, { email: '[email protected]' }, '198.51.100.124')).status, 403);
+ assert.equal((await setEmail(h, ana, { email: '[email protected]', current: GOOD }, '198.51.100.125')).status, 200);
+ const status = await h.req('GET', '/api/account/password', { cookie: ana });
+ assert.equal(status.body.email, '[email protected]');
+ // Invalid addresses are refused before any proof is asked.
+ r = await setEmail(h, ana, { email: 'not an address', current: GOOD }, '198.51.100.126');
+ assert.equal(r.status, 400); assert.equal(r.body.code, 'email-invalid');
+ r = await setEmail(h, ana, { email: 'a@' + 'b'.repeat(260) + '.com', current: GOOD }, '198.51.100.126');
+ assert.equal(r.body.code, 'email-invalid');
+
+ // Removing: the session alone is refused, by DELETE and by an empty address alike.
+ assert.equal((await h.req('DELETE', '/api/account/email', { body: {}, cookie: ana, ip: '198.51.100.127' })).status, 403);
+ assert.equal((await setEmail(h, ana, { email: '' }, '198.51.100.128')).status, 403);
+ assert.equal(h.db().users.find(u => u.id === 'u1').email, '[email protected]');
+ r = await h.req('DELETE', '/api/account/email', { body: { current: GOOD }, cookie: ana, ip: '198.51.100.129' });
+ assert.deepEqual(r.body, { ok: true, email: null });
+ assert.equal('email' in h.db().users.find(u => u.id === 'u1'), false);
+
+ // A profile with no password confirms with one of its passkeys; without one it is told to.
+ r = await setEmail(h, bea, { email: '[email protected]' }, '198.51.100.130');
+ assert.equal(r.status, 403); assert.equal(r.body.code, 'passkey-required');
+ const opts = await h.req('POST', '/api/login/options', { body: {} });
+ r = await setEmail(h, bea, { email: '[email protected]', cid: opts.body.cid, credential: pk.assertion(opts.body.options.challenge) }, '198.51.100.131');
+ assert.equal(r.status, 200);
+ assert.equal(h.db().users.find(u => u.id === 'u2').email, '[email protected]');
+
+ // The log says what happened and with which proof, with the address masked.
+ const evs = h.audit().filter(e => e.ev.startsWith('auth.email.'));
+ assert.deepEqual(evs.filter(e => e.ok).map(e => [e.ev, e.uid, e.msg]), [
+ ['auth.email.set', 'u1', 'password · a…@e…'],
+ ['auth.email.change', 'u1', 'password · a…@e…'],
+ ['auth.email.remove', 'u1', 'password'],
+ ['auth.email.set', 'u2', 'passkey · b…@e…']
+ ]);
+ assert.equal(leaks(h, 'example.com'), false);
+});
+
+test('an address is unique across profiles, case-insensitively, and never another password holder’s name', async t => {
+ const h = await startServer(t, {
+ users: [withPassword('u1', 'Ana', { email: '[email protected]' }), withPassword('u2', 'Bea'), withPassword('u3', '[email protected]'), user('u4', 'Cy', { email: '[email protected]' })]
+ });
+ const bea = `gymsid=${mintSession('u2')}`;
+ for (const [i, email] of ['[email protected]', '[email protected]', '[email protected]'].entries()) {
+ const r = await setEmail(h, bea, { email, current: GOOD }, `198.51.100.${140 + i}`);
+ assert.equal(r.status, 409, email);
+ assert.deepEqual(r.body, { error: 'another profile already uses this e-mail address', code: 'email-taken' });
+ }
+ assert.equal(h.db().users.find(u => u.id === 'u2').email, undefined);
+ assert.ok(h.audit().some(e => e.ev === 'auth.email.fail' && e.uid === 'u2' && e.msg === 'email-taken'));
+ // The other way round: a profile whose name is someone's address cannot take a password.
+ const h2 = await startServer(t, { users: [withPassword('u1', 'Ana', { email: '[email protected]' }), user('u2', '[email protected]')] });
+ const opts = await h2.req('GET', '/api/account/password', { cookie: `gymsid=${mintSession('u2')}` });
+ assert.equal(opts.body.nameTaken, true);
+ // Signing up with an address in use, or a name that is one, is refused the same way.
+ let r = await h.req('POST', '/api/register/password', { body: { name: 'Dee', password: GOOD, email: '[email protected]' }, ip: '198.51.100.150' });
+ assert.equal(r.status, 409); assert.equal(r.body.code, 'email-taken');
+ r = await h.req('POST', '/api/register/password', { body: { name: '[email protected]', password: GOOD }, ip: '198.51.100.151' });
+ assert.equal(r.status, 409); assert.equal(r.body.code, 'name-taken');
+ r = await h.req('POST', '/api/register/password', { body: { name: 'Dee', password: GOOD, email: 'nope' }, ip: '198.51.100.152' });
+ assert.equal(r.status, 400); assert.equal(r.body.code, 'email-invalid');
+ assert.equal(h.db().users.length, 4);
+ // A free one is stored folded, and signs the new profile in straight away.
+ r = await h.req('POST', '/api/register/password', { body: { name: 'Dee', password: GOOD, email: ' [email protected] ' }, ip: '198.51.100.153' });
+ assert.equal(r.status, 200);
+ assert.equal(h.db().users.find(u => u.name === 'Dee').email, '[email protected]');
+ assert.equal((await signIn(h, { identifier: '[email protected]', password: GOOD }, '198.51.100.154')).status, 200);
+ assert.equal(leaks(h, 'example.com'), false);
+});
+
+test('asking over and over whether an address is in use runs into a pause', async t => {
+ const h = await startServer(t, { users: [withPassword('u1', 'Ana', { email: '[email protected]' }), withPassword('u2', 'Bea')] });
+ const bea = `gymsid=${mintSession('u2')}`;
+ const ip = '203.0.113.60';
+ // Twenty answers are free; the twenty-first starts the pause for the address and the account.
+ for (let i = 0; i < 21; i++) assert.equal((await setEmail(h, bea, { email: '[email protected]', current: GOOD }, ip)).status, 409, 'try ' + i);
+ let r = await setEmail(h, bea, { email: '[email protected]', current: GOOD }, ip);
+ assert.equal(r.status, 429); assert.equal(r.body.code, 'locked');
+ // Another address of the same account is paused too, before any proof is checked.
+ r = await setEmail(h, bea, { email: '[email protected]', current: GOOD }, '203.0.113.61');
+ assert.equal(r.status, 429);
+ // Sign-in is not what was paused.
+ assert.equal((await signIn(h, { identifier: 'bea', password: GOOD }, ip)).status, 200);
+});
+
+test('a reset code is redeemed with the e-mail as well as with the name', async t => {
+ const code = 'K7WQ-2MZP-4HXA';
+ const reset = () => ({ h: hashResetCode(code), exp: Date.now() + 3600000, by: 'adm' });
+ const h = await startServer(t, { users: [user('u1', 'Ana', { email: '[email protected]', pwReset: reset() })] });
+ const r = await h.req('POST', '/api/login/password-reset', { body: { identifier: '[email protected]', code: code.toLowerCase(), next: 'a brand new passphrase' }, ip: '198.51.100.160' });
+ assert.equal(r.status, 200);
+ assert.equal(r.body.user.id, 'u1');
+ assert.equal(h.db().users[0].email, '[email protected]');
+ assert.equal((await signIn(h, { identifier: '[email protected]', password: 'a brand new passphrase' }, '198.51.100.161')).status, 200);
+ const h2 = await startServer(t, { users: [user('u1', 'Ana', { email: '[email protected]', pwReset: reset() })] });
+ assert.equal((await h2.req('POST', '/api/login/password-reset', { body: { name: 'ana', code, next: 'a brand new passphrase' }, ip: '198.51.100.162' })).status, 200);
+});
+
+test('the admin user list and drill-down show the address to admins only', async t => {
+ const h = await startServer(t, {
+ env: { ADMIN_UIDS: 'adm' },
+ users: [user('adm', 'Root'), withPassword('u1', 'Ana', { email: '[email protected]' }), withPassword('u2', 'Bea')]
+ });
+ const adm = `gymsid=${mintSession('adm')}`;
+ const list = await h.req('GET', '/api/admin/users', { cookie: adm });
+ assert.equal(list.body.users.find(u => u.id === 'u1').email, '[email protected]');
+ assert.equal(list.body.users.find(u => u.id === 'u2').email, null);
+ const one = await h.req('GET', '/api/admin/user?id=u1', { cookie: adm });
+ assert.equal(one.body.user.email, '[email protected]');
+ for (const p of ['/api/admin/users', '/api/admin/user?id=u1']) {
+ const r = await h.req('GET', p, { cookie: `gymsid=${mintSession('u2')}` });
+ assert.equal(r.status, 403, p);
+ assert.equal(JSON.stringify(r.body).includes('example.com'), false);
+ }
+});
diff --git a/api/test/server-password.test.js b/api/test/server-password.test.js
index e32d317e0..b08270d9c 100644
--- a/api/test/server-password.test.js
+++ b/api/test/server-password.test.js
@@ -321,7 +321,7 @@ test('setting a first password needs a passkey made for it, not just a session',
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.deepEqual(status.body, { set: false, setAt: null, passkeys: 1, name: 'Ana', nameTaken: false, email: null });
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');
diff --git a/frontend/src/lib/audit.js b/frontend/src/lib/audit.js
index ddb72eadd..5f8432b30 100644
--- a/frontend/src/lib/audit.js
+++ b/frontend/src/lib/audit.js
@@ -34,6 +34,12 @@ const LABELS = {
'auth.password.change': 'Changed their password',
'auth.password.remove': 'Removed their password',
'auth.password.reset': 'Used a reset code',
+ // The e-mail a profile may sign in with instead of its name. `msg` is the proof it was set with
+ // and the address masked to two characters ("password · a…@e…") — never the address itself.
+ 'auth.email.set': 'Added a sign-in e-mail',
+ 'auth.email.change': 'Changed their sign-in e-mail',
+ 'auth.email.remove': 'Removed their sign-in e-mail',
+ 'auth.email.fail': 'Changing the sign-in e-mail failed',
// More than one passkey, and one-time codes for another device (#95). `msg` on an addition or a
// code is the proof it was made with (passkey, password); on a removal or a redemption, the
// passkey's name.
@@ -77,6 +83,8 @@ const REASONS = {
'bad-password': 'wrong password',
'bad-current': 'wrong current password while changing it',
'unknown-name': 'no profile with a password has that name',
+ 'unknown-email': 'no profile with a password has that e-mail',
+ 'email-taken': 'another profile already uses that e-mail',
'step-up-failed': 'the passkey confirming the change was rejected',
'reset-invalid': 'wrong or expired reset code',
'link-invalid': 'wrong, used or expired device code',
@@ -85,6 +93,7 @@ const REASONS = {
'password': 'wrong passwords or reset codes',
'signup': 'wrong invite codes on password signup',
'link': 'wrong one-time device codes',
+ 'email': 'e-mail addresses already in use',
// What a `media.throttled` pause was for.
'upload': 'photo and video uploads',
'sweep': 'clearing unused photos and videos'
diff --git a/frontend/src/lib/audit.test.js b/frontend/src/lib/audit.test.js
index 6d8a3ebf5..e3923e4e4 100644
--- a/frontend/src/lib/audit.test.js
+++ b/frontend/src/lib/audit.test.js
@@ -53,6 +53,7 @@ describe('auditReason', () => {
expect(auditLine({ ev: 'auth.throttled', ok: false, msg: 'signup' }).sub).toMatch(/invite codes/)
expect(auditLine({ ev: 'auth.throttled', ok: false, msg: 'password' }).sub).toMatch(/wrong passwords/)
expect(auditLine({ ev: 'auth.throttled', ok: false, msg: 'link' }).sub).toMatch(/device codes/)
+ expect(auditLine({ ev: 'auth.throttled', ok: false, msg: 'email' }).sub).toMatch(/e-mail addresses/)
})
it('falls back to the raw code and tolerates none at all', () => {
expect(auditReason('brand-new-code')).toBe('brand-new-code')
@@ -77,6 +78,16 @@ describe('auditLine', () => {
expect(auditLine({ ev: 'auth.passkey.fail', ok: false, name: 'Ana', msg: 'credential-exists' }).sub).not.toMatch(/credential-exists/)
})
+ it('reads the sign-in e-mail events, whose line carries only a masked address', () => {
+ // set/change are picked by a ternary the extraction above cannot read, like password set/change.
+ expect(EVENTS).toEqual(expect.arrayContaining(['auth.email.remove', 'auth.email.fail']))
+ expect(SERVER).toContain("first ? 'auth.email.set' : 'auth.email.change'")
+ expect(auditLabel('auth.email.change')).toBe('Changed their sign-in e-mail')
+ expect(auditLine({ ev: 'auth.email.set', ok: true, name: 'Ana', msg: 'passkey · a…@e…' })).toEqual({ title: 'Added a sign-in e-mail', sub: 'Ana · passkey · a…@e…' })
+ expect(auditLine({ ev: 'auth.email.fail', ok: false, name: 'Ana', msg: 'email-taken' }).sub).toBe('Ana · another profile already uses that e-mail')
+ expect(auditLine({ ev: 'auth.password.fail', ok: false, msg: 'unknown-email' }).sub).toBe('unknown caller · no profile with a password has that e-mail')
+ })
+
it('names the person who did it', () => {
expect(auditLine({ ev: 'auth.login.ok', ok: true, uid: 'u1', name: 'Duarte' }))
.toEqual({ title: 'Signed in', sub: 'Duarte' })