web: prove an address with the six digits the letter carries
Signing up mailed a link and nothing else, so a visitor who signed up on one
device and read the mail on another had to leave the page the studio was open
on, or give up and stay a guest. The letter now carries six digits as well, and
the verify dialog — the face a fresh signup already lands on — takes them.
Backend, one row is both proofs. `createEmailVerification` mints the token as it
did and a `randomInt(0, 1_000_000)` code padded to six, and returns `{ token,
code }`; `sendVerification` passes both to the mailer, which puts the code first
and the link second. The code's clock is `created_at + CODE_TTL_S` (15 minutes)
and the link keeps the row's own 24-hour `expires_at`: two clocks over one row,
so the code needs no expiry column of its own. That row's `code` is NULL for
anything minted before this commit, a value no typed guess can match, so an
in-flight link from the old mail still works and its owner simply has no code to
type. `db.ts` adds both columns with `PRAGMA table_info` + `ALTER TABLE` rather
than a rebuild, and sets `attempts` to 0.
`verifyEmailCode(userId, code)` answers 'ok' | 'bad' | 'stale' | 'locked', and
the shape of the answer is the point. 'stale' is both "no live code" and "too
old", so the caller learns nothing about which; 'locked' is the spent-attempts
state, which only a fresh letter leaves. The attempt is counted BEFORE the
comparison is trusted, so an interrupted request cannot hand back a guess nobody
paid for; five (MAX_CODE_ATTEMPTS) is the cap, which is what keeps a six-digit
secret from being walked through at a hundred requests a second. The comparison
itself is `timingSafeEqual` behind a length check, the same pair the password
path uses. On success the row is deleted and `email_verified` set, so the same
row spends the link with the code — one proof, one use.
The route is `POST /api/auth/verify-code`, a POST and not a GET like the link
because a code in a query string lands in every proxy log on the way. It reads
`auth`, not `requirePro`: the whole point of it is the account that has not
passed the gate yet. Input must be exactly six digits before anything else
happens, so the counter only ever counts real guesses; a wrong or stale code is
400, a locked one 429 with `retry-after: 900`, and an already-verified caller
gets 200 without touching the row. No limiter of its own: the cap lives with the
secret on the row, and a fresh code costs one of the three resends an hour, so
five guesses per code is the budget either way.
On the web side `api.verifyCode` posts the code, and the dialog's verify face
swaps its resend button for a code box plus a smaller resend beside it: the box
is `inputMode="numeric"`, `autoComplete="one-time-code"`, `maxLength 6`, and
strips non-digits as they are typed, so the number pad comes up on a phone and
nothing can paste a password into it. The submit button is disabled until six
digits are there. The two answers a visitor can actually act on get sentences of
their own (`auth.codeBad`, `auth.codeLocked`); everything else is shown as it
comes. The link path is untouched and still works, and the dialog keeps its
"Tôi đã xác thực xong" escape in no place at all — it verified nothing, so
closing the dialog and asking again covers the same ground.
The comment in `docker/.env.example` now says the letter carries both, since a
deployment without a relay writes both to the api log.
Verified:
backend `npm test` — 180 passed, 0 failed. The new section in security.mjs
drives the route end to end against the source: signup leaves a six-digit
code beside the link, a wrong code verifies nothing and leaves the account
unproven, a five-digit body is refused, a signed-out caller cannot type one,
the mailed code verifies, spending it spends the link, five wrong guesses
lock the code out and the right code then does not help, a resent letter
hands out a fresh code that is not locked out by the old guesses, and a code
aged past its quarter hour is refused.
otp-code-probe.cjs (scratchpad) — 10 PASS, 0 FAIL on http://localhost:8090
against the rebuilt app and api, no page errors: a fresh signup lands on the
verify face with the box ready, a wrong code says so and the account stays a
guest, the mailed code unlocks PRO, and a proven address is not asked again
on the next login.
Regressions, 0 fail: landing-test.cjs 172, pro-gate-test.cjs 27,
award-column-probe.cjs 18, tone-curve-probe.cjs 33. web tsc --noEmit clean.
ponytail: the code rides `created_at` rather than an `expires_at` of its own, so
the link's 24 hours and the code's 15 minutes are one column read twice; the day
the two need to drift apart independently, the column is the thing to split. The
route carries no per-IP limiter, only the per-row cap — a stranger can burn one
account's five guesses, which costs that owner a resend, and a limiter keyed on
the address would be the next thing to add if that turns out to be cheap for an
attacker. The code is not usable from another browser: it verifies the session
that asked for it, which is the behaviour the request asked for and not a gap.
This commit is contained in:
@@ -100,6 +100,25 @@ async function activeSignup(a, email) {
|
||||
await followVerifyLink(email);
|
||||
return res;
|
||||
}
|
||||
// The same letter carries a code, and the suite reaches it the same way — the
|
||||
// database is the only reader of the mail here.
|
||||
function codeFor(email) {
|
||||
const db = new Database(join(DATA_DIR, 'recipescam.db'), { readonly: true });
|
||||
const row = db
|
||||
.prepare('SELECT code FROM email_verifications WHERE user_id = (SELECT id FROM users WHERE email = ?)')
|
||||
.get(email);
|
||||
db.close();
|
||||
return row?.code;
|
||||
}
|
||||
// The code's own clock starts at `created_at`, so an old one is made here
|
||||
// rather than waited for.
|
||||
function ageCode(email, minutes) {
|
||||
const db = new Database(join(DATA_DIR, 'recipescam.db'));
|
||||
db.prepare(
|
||||
'UPDATE email_verifications SET created_at = ? WHERE user_id = (SELECT id FROM users WHERE email = ?)',
|
||||
).run(new Date(Date.now() - minutes * 60_000).toISOString(), email);
|
||||
db.close();
|
||||
}
|
||||
|
||||
// Run the sources, not a possibly stale build: the point of this suite is to
|
||||
// test the code as written.
|
||||
@@ -225,6 +244,49 @@ try {
|
||||
check('a spent link cannot be followed twice', replay.headers.get('location')?.endsWith('/?verified=0'), String(replay.headers.get('location')));
|
||||
check('the allowlisted admin needs no letter', (await admin.req('/auth/me')).body?.user?.verified === true);
|
||||
|
||||
// ---- the code in the same letter ----------------------------------------
|
||||
// The link is not the only way to prove an address any more: the letter also
|
||||
// carries six digits the visitor types into the dialog they signed up on. The
|
||||
// code is the shorter-lived of the two proofs and the one worth guessing, so
|
||||
// the checks below are mostly about what a wrong guess costs.
|
||||
const typed = actor();
|
||||
const typedEmail = `typed${stamp}@test.local`;
|
||||
await typed.signup(typedEmail);
|
||||
const code = codeFor(typedEmail);
|
||||
check('signup leaves a six-digit code beside the link', /^\d{6}$/.test(String(code)), String(code));
|
||||
const wrongCode = code === '000000' ? '111111' : '000000';
|
||||
const type = (a, value) =>
|
||||
a.req('/auth/verify-code', { method: 'POST', headers: jsonHdr, body: JSON.stringify({ code: value }) });
|
||||
check('a wrong code verifies nothing', (await type(typed, wrongCode)).status === 400);
|
||||
check('and leaves the account unproven', (await typed.req('/auth/me')).body?.user?.verified === false);
|
||||
check('a code of the wrong shape is refused', (await type(typed, '12345')).status === 400);
|
||||
check('a signed-out caller cannot type a code', (await type(actor(), code)).status === 401);
|
||||
check('the mailed code verifies the account', (await type(typed, code)).status === 200);
|
||||
check('the account is verified from then on', (await typed.req('/auth/me')).body?.user?.verified === true);
|
||||
check('the code being spent spends the link with it', tokenFor(typedEmail) === undefined, String(tokenFor(typedEmail)));
|
||||
|
||||
const locked = actor();
|
||||
const lockedEmail = `locked${stamp}@test.local`;
|
||||
await locked.signup(lockedEmail);
|
||||
const lockedCode = codeFor(lockedEmail);
|
||||
const otherCode = lockedCode === '000000' ? '111111' : '000000';
|
||||
for (let i = 0; i < 5; i++) await type(locked, otherCode);
|
||||
const afterLock = await type(locked, lockedCode);
|
||||
check('five wrong guesses lock the code out', afterLock.status === 429, `got ${afterLock.status}`);
|
||||
check('and the right code no longer helps', (await locked.req('/auth/me')).body?.user?.verified === false);
|
||||
await locked.req('/auth/resend-verification', { method: 'POST' });
|
||||
const freshCode = codeFor(lockedEmail);
|
||||
check('a resent letter hands out a fresh code', freshCode !== lockedCode && /^\d{6}$/.test(String(freshCode)));
|
||||
check('that fresh code is not locked out by the old guesses', (await type(locked, freshCode)).status === 200);
|
||||
|
||||
const stale = actor();
|
||||
const staleEmail = `stale${stamp}@test.local`;
|
||||
await stale.signup(staleEmail);
|
||||
const staleCode = codeFor(staleEmail);
|
||||
ageCode(staleEmail, 16); // past CODE_TTL_S
|
||||
check('a code older than its quarter hour is refused', (await type(stale, staleCode)).status === 400);
|
||||
check('and leaves the account unproven', (await stale.req('/auth/me')).body?.user?.verified === false);
|
||||
|
||||
// ---- rate limiting ------------------------------------------------------
|
||||
const brute = actor();
|
||||
const bruteEmail = `brute${stamp}@test.local`;
|
||||
|
||||
Reference in New Issue
Block a user