mirror of
https://github.com/Komediruzecki/token-circles.git
synced 2026-10-20 09:46:43 +02:00
* feat(auth): TOTP two-factor authentication with recovery codes
Second factor for password and Google sign-in. Login now withholds the
session when the account has a confirmed TOTP credential: the browser
gets a 5-minute signed challenge cookie (fm_2fa) and /api/auth/2fa/verify
trades a valid authenticator or recovery code for the real session.
- RFC 6238 TOTP over WebCrypto (SHA-1/6/30 as authenticator apps expect),
verified against the RFC's reference vectors; constant-time compares;
last-used-step high-water mark so a code is never accepted twice.
- Secrets encrypted at rest (AES-256-GCM under an HKDF key from
JWT_SECRET); decrypt failure fails CLOSED - the challenge remains and
the SHA-256-hashed single-use recovery codes still sign you in.
- Enrollment in Settings: otpauth link + manual key, confirm with a live
code, ten recovery codes shown exactly once. Disable demands a code.
- Rate limits on verify (10/15min/user), auth_logs twofa events, and the
Google callback returns with ?twofa=1 so the SPA opens the code step.
* feat(auth): email-code sign-in (passwordless login)
"Email me a code": POST /api/auth/email-code/request mints a 6-digit
code (stored SHA-256-hashed, mailed via the existing template shell)
and answers the same neutral ok whether or not the address has an
account; /verify trades a live code for a session.
- Single active code per user, single use (atomic claim), 10-minute
TTL, rejection-sampled generation (no modulo bias).
- Layered rate limits mirroring forgot-password: per-IP send flood
guard, 3 sends/hour/address, 10 verify tries/15 min/address.
- A verified code proves inbox control, so it also resolves the
pending email_verified flag.
- 2FA accounts still get the authenticator challenge after the code -
the inbox is one factor, not two. Sessions record provider 'email'
(labelled in the devices list).
- Frontend: shared EmailCodeLogin step wired into LoginScreen and
LoginModal ("Email me a sign-in code"), with its own Turnstile
instance and resend flow.
* feat(2fa): QR enrollment and a full-loop e2e spec
- Enroll now shows a QR code of the otpauth URI, rendered locally with
uqr — the shared secret never leaves the page, so external QR image
services are not an option. White backing keeps it scannable in dark
mode. Manual key entry and the open-directly link stay.
- New Playwright spec drives the whole loop through the real UI with a
dedicated user: enroll (computing codes from the on-screen secret the
way an authenticator app would), wrong-code rejection, TOTP challenge
sign-in, recovery-code sign-in, disable via recovery code.
- tests/db.ts: shared local-D1 helpers (sql / sqlRows) so auth specs can
arrange state the API deliberately refuses to expose.
* fix(2fa): close the review findings on the 2FA lifecycle
Security:
- /2fa/disable now shares the 2fa:<user> attempt bucket with /2fa/verify
(and clears it on success). It accepts the same factors, so it must not
hand an attacker a fresh guessing budget; before this, a stolen session
could brute-force the disable endpoint unmetered.
- Enabling 2FA deletes every OTHER auth session. Sessions that predate
enrollment got in on one factor — including the intruder the user may
be enrolling against. Only the enrolling session survives.
- Account deletion now removes totp_credentials and recovery_codes; the
encrypted secret and code hashes used to outlive the account.
UX / recoverability:
- "Create account" with an existing 2FA-protected email now lands on the
code challenge instead of a silent reload loop (both login surfaces).
- Recovery codes: a Download button joins Copy (clipboard is unavailable
in non-secure contexts and the codes are unrecoverable once revealed),
and Settings warns loudly when 3 or fewer codes remain.
- The challenge's recovery/back controls are real buttons — keyboard and
assistive-tech reachable; they were onClick-only anchors, invisible to
the tab order, gating the only path in after a lost phone.
- Backing out of the challenge strips the ?twofa=1 marker, so a reload
no longer reopens a dead challenge for an expired cookie.
Not addressed here (accepted, low): recovery-code spend before a failed
session write; the two-tab concurrent-setup race (second secret wins).
* fix(email-code): bind verification to the requesting browser; close review findings
The 10^6 code space was defended only by resettable rate-limit windows:
~10 free guesses per code with no captcha on /verify, horizontally
scalable across addresses, plus two denial-of-service handles (fill the
per-address verify bucket to lock an inbox out; fire /request to delete
the code the victim was typing).
Redesign: /request now sets a signed ceremony cookie (fm_logincode, the
fm_2fa construction, TTL = code TTL) naming the one code row that
browser may attempt; /verify accepts nothing without it.
- A third party who triggers codes for someone else's address gets a
cookie for a code they cannot read — no guessing surface, no way to
spend the victim's budget. The per-address verify bucket is gone
(nothing left to lock), the per-IP one stays and clears on success.
- Wrong guesses increment a per-code attempts counter; five misses burn
the code even if the right value is presented later.
- /request no longer deletes previous unused codes (that was the DoS
handle); live codes are capped at three, oldest pruned.
- Anti-enumeration hardened: unknown addresses get the same cookie and
the same code+hash work; the Resend call moved off the response path
(waitUntil + swallow) — it was a 100-400ms timing oracle and its
failures turned into 500-for-registered / 200-for-unknown.
- Account deletion removes login_codes rows.
- UI: the code field focuses itself when the verify step appears, and
the captcha-disabled send button now explains itself (captcha-hint,
LoginScreen's rule).
- New e2e spec drives the real UI loop, rewriting the minted row's hash
to a known value via the local-D1 side door (the mailed code is
unreadable by design); tests/db.ts retries on SQLITE_BUSY so parallel
specs share the database calmly.
Accepted trade-off: entering the code on a different device than the
one that requested it no longer works (the UI never offered that flow).
63 lines
2.4 KiB
TypeScript
63 lines
2.4 KiB
TypeScript
/**
|
|
* Direct access to the local D1 the e2e Worker serves from.
|
|
*
|
|
* `wrangler dev` and `wrangler d1 execute --local` share the same state directory, so specs can
|
|
* arrange fixture state the API deliberately refuses to expose — clearing rate-limit counters,
|
|
* resetting a fixture user's 2FA between runs, planting a login code whose raw value the spec
|
|
* knows. Same mechanism global.setup.ts uses; kept here so auth specs don't each grow a copy.
|
|
*/
|
|
import { execFileSync } from 'node:child_process'
|
|
import { existsSync } from 'node:fs'
|
|
import { resolve } from 'node:path'
|
|
|
|
function wranglerBin(): { wrangler: string; workerDir: string } {
|
|
const workerDir = resolve(process.cwd(), '..', 'worker')
|
|
// eslint-disable-next-line security/detect-non-literal-fs-filename -- derived from cwd, not input
|
|
if (!existsSync(workerDir)) throw new Error(`worker/ not found next to ${process.cwd()}`)
|
|
// The worker's own wrangler, by path — not `npx wrangler`, which resolves off PATH.
|
|
return { wrangler: resolve(workerDir, 'node_modules', '.bin', 'wrangler'), workerDir }
|
|
}
|
|
|
|
const sleepSync = (ms: number) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
|
|
|
|
/**
|
|
* Specs run in parallel and the dev Worker holds the same file, so a concurrent statement can
|
|
* land on SQLITE_BUSY. That's contention, not failure — retry briefly before giving up.
|
|
*/
|
|
function execWithRetry(args: string[]): string {
|
|
const { wrangler, workerDir } = wranglerBin()
|
|
let lastErr: unknown
|
|
for (let attempt = 0; attempt < 10; attempt++) {
|
|
try {
|
|
return execFileSync(wrangler, args, { cwd: workerDir, stdio: 'pipe' }).toString()
|
|
} catch (err) {
|
|
lastErr = err
|
|
const text = String((err as { stderr?: Buffer; stdout?: Buffer }).stderr ?? '').concat(
|
|
String((err as { stdout?: Buffer }).stdout ?? '')
|
|
)
|
|
if (!text.includes('SQLITE_BUSY') && !text.includes('database is locked')) throw err
|
|
sleepSync(250 * (attempt + 1))
|
|
}
|
|
}
|
|
throw lastErr
|
|
}
|
|
|
|
export function sql(command: string): void {
|
|
execWithRetry(['d1', 'execute', 'finance-manager', '--local', '--command', command])
|
|
}
|
|
|
|
/** Run a SELECT and return its rows. */
|
|
export function sqlRows<T>(command: string): T[] {
|
|
const out = execWithRetry([
|
|
'd1',
|
|
'execute',
|
|
'finance-manager',
|
|
'--local',
|
|
'--json',
|
|
'--command',
|
|
command,
|
|
])
|
|
const parsed = JSON.parse(out) as { results: T[] }[]
|
|
return parsed[0]?.results ?? []
|
|
}
|