feat(auth): trusted devices, recovery codes, and admin MFA management
Add opt-in "Trust this device" so a browser/app skips the TOTP step (never the password) for 30 days, single-use bcrypt recovery codes as a 2FA-lockout fallback, and admin trusted-device/MFA-reset management — backend, web UI, OpenAPI spec, and tests. - Schema: trusted_devices (sha256 token hash, looked up by unique index) and recovery_codes (bcrypt, single-use). Both additive/idempotent. - Session service: trust-token mint/hash/resolve + cap helpers; new rg_trust httpOnly cookie (survives logout, revoked on untrust/password change/reset/ TOTP disable). JWTs stay stateless — trust is a server-side row, not a claim. - Web + mobile login accept a trusted-device token / recovery code; login/totp gains trustDevice + recoveryCode. Cap of 10/user with NO silent pruning — an over-cap trust returns 409/trustLimitReached and the client prompts to revoke. - Self-service /auth/me/trusted-devices* + recovery-codes*; admin /admin/users/:id/trusted-devices* + /mfa/reset. All actions audit-logged. - Client: "Trust this device" + recovery-code login options, one-time recovery code display, Trusted Devices + Recovery Codes account panels, a TOTP-styled revoke-to-continue cap modal, and admin per-user security controls. - OpenAPI regenerated; 33 new server tests (all suites green). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
63
server/src/model/recoveryCodes/recoveryCodes.db.js
Normal file
63
server/src/model/recoveryCodes/recoveryCodes.db.js
Normal file
@@ -0,0 +1,63 @@
|
||||
const { query } = require('../../utils/db')
|
||||
|
||||
// SQL for the recovery_codes table. Each row is one bcrypt-hashed, single-use
|
||||
// backup code. The raw codes are shown to the user exactly once at generation and
|
||||
// never stored in the clear.
|
||||
|
||||
// Bulk-insert freshly generated code hashes for a user. `hashes` is an array of
|
||||
// bcrypt strings. One multi-row INSERT keeps generation atomic-ish and cheap.
|
||||
async function insertMany(userId, hashes) {
|
||||
if (!hashes || hashes.length === 0) return 0
|
||||
const values = hashes.map(() => '(?, ?)').join(', ')
|
||||
const params = []
|
||||
for (const h of hashes) params.push(userId, h)
|
||||
const res = await query(
|
||||
`INSERT INTO recovery_codes (user_id, code_hash) VALUES ${values}`,
|
||||
params,
|
||||
)
|
||||
return Number(res.affectedRows || 0)
|
||||
}
|
||||
|
||||
// All not-yet-used codes for a user (hashes included — this is the verify path,
|
||||
// server-side only). Ordered by id so verification is deterministic.
|
||||
async function listUnusedForUser(userId) {
|
||||
return query(
|
||||
'SELECT id, code_hash FROM recovery_codes WHERE user_id = ? AND used_at IS NULL ORDER BY id',
|
||||
[userId],
|
||||
)
|
||||
}
|
||||
|
||||
// Count a user's remaining (unused) codes — for the status endpoint (never the
|
||||
// codes themselves).
|
||||
async function countUnusedForUser(userId) {
|
||||
const rows = await query(
|
||||
'SELECT COUNT(*) AS n FROM recovery_codes WHERE user_id = ? AND used_at IS NULL',
|
||||
[userId],
|
||||
)
|
||||
return Number(rows[0]?.n || 0)
|
||||
}
|
||||
|
||||
// Mark one code row used (single-use). Guarded on used_at IS NULL so a race can
|
||||
// only consume it once. Returns rows changed.
|
||||
async function markUsed(id) {
|
||||
const res = await query(
|
||||
'UPDATE recovery_codes SET used_at = NOW() WHERE id = ? AND used_at IS NULL',
|
||||
[id],
|
||||
)
|
||||
return Number(res.affectedRows || 0)
|
||||
}
|
||||
|
||||
// Delete every code for a user. Used both when regenerating (replace the set) and
|
||||
// on TOTP disable / password change/reset. Returns rows removed.
|
||||
async function deleteAllForUser(userId) {
|
||||
const res = await query('DELETE FROM recovery_codes WHERE user_id = ?', [userId])
|
||||
return Number(res.affectedRows || 0)
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
insertMany,
|
||||
listUnusedForUser,
|
||||
countUnusedForUser,
|
||||
markUsed,
|
||||
deleteAllForUser,
|
||||
}
|
||||
86
server/src/model/recoveryCodes/recoveryCodes.model.js
Normal file
86
server/src/model/recoveryCodes/recoveryCodes.model.js
Normal file
@@ -0,0 +1,86 @@
|
||||
// Recovery (backup) code store. Logic layer over recoveryCodes.db, doing the
|
||||
// bcrypt hashing itself — the same pattern as users.model hashing passwords (a
|
||||
// recovery code is a human-typed, lower-entropy fallback credential, so bcrypt,
|
||||
// not sha256; see docs/website/TRUSTED_DEVICES_MFA.md §3). Codes are generated in
|
||||
// batches, shown to the user once, and consumed single-use at login.
|
||||
|
||||
const crypto = require('crypto')
|
||||
const bcrypt = require('bcryptjs')
|
||||
|
||||
const db = require('./recoveryCodes.db')
|
||||
|
||||
const SALT_ROUNDS = 10
|
||||
const CODE_COUNT = Number(process.env.RECOVERY_CODE_COUNT) || 10
|
||||
// 10 chars from a 32-symbol alphabet ≈ 50 bits of entropy per code. Crockford-ish
|
||||
// base32 minus visually ambiguous glyphs (no I, L, O, U) to keep hand-entry clean.
|
||||
const ALPHABET = '23456789ABCDEFGHJKMNPQRSTVWXYZ'
|
||||
const CODE_LEN = 10
|
||||
|
||||
// Canonical form used for hashing + comparison: uppercase, alphanumerics only.
|
||||
// Display adds a dash for readability; input is normalized back to this before
|
||||
// bcrypt.compare so 'abcde-fghij', 'ABCDEFGHIJ', etc. all verify.
|
||||
function normalize(code) {
|
||||
return String(code || '').toUpperCase().replace(/[^0-9A-Z]/g, '')
|
||||
}
|
||||
|
||||
// One random code in canonical form (no separator).
|
||||
function generateCode() {
|
||||
const bytes = crypto.randomBytes(CODE_LEN)
|
||||
let out = ''
|
||||
for (let i = 0; i < CODE_LEN; i++) out += ALPHABET[bytes[i] % ALPHABET.length]
|
||||
return out
|
||||
}
|
||||
|
||||
// Present a canonical code to the user with a mid-string dash (display only).
|
||||
function formatForDisplay(code) {
|
||||
const mid = Math.floor(code.length / 2)
|
||||
return `${code.slice(0, mid)}-${code.slice(mid)}`
|
||||
}
|
||||
|
||||
// Generate a fresh batch, REPLACING any existing codes for the user (regeneration
|
||||
// invalidates the old set). Returns the plaintext codes for one-time display — the
|
||||
// only time they exist outside the user's hands.
|
||||
async function generateForUser(userId, count = CODE_COUNT) {
|
||||
const plain = Array.from({ length: count }, generateCode)
|
||||
const hashes = await Promise.all(plain.map((c) => bcrypt.hash(c, SALT_ROUNDS)))
|
||||
await db.deleteAllForUser(userId)
|
||||
await db.insertMany(userId, hashes)
|
||||
return plain.map(formatForDisplay)
|
||||
}
|
||||
|
||||
// Verify + consume a recovery code (single-use). Normalizes input, bcrypt-compares
|
||||
// against the user's unused codes, and marks the first match used. Returns true iff
|
||||
// a code was consumed. Timing is dominated by bcrypt regardless of match position.
|
||||
async function consumeForUser(userId, rawCode) {
|
||||
const candidate = normalize(rawCode)
|
||||
if (!candidate) return false
|
||||
const rows = await db.listUnusedForUser(userId)
|
||||
for (const row of rows) {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
if (await bcrypt.compare(candidate, row.code_hash)) {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
const changed = await db.markUsed(row.id)
|
||||
return changed > 0 // lost the race to consume this exact code → treat as fail
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Remaining (unused) code count — for the status endpoint. Never returns codes.
|
||||
async function remainingForUser(userId) {
|
||||
return db.countUnusedForUser(userId)
|
||||
}
|
||||
|
||||
// Clear every code for a user (TOTP disable / password change/reset).
|
||||
async function clearForUser(userId) {
|
||||
return db.deleteAllForUser(userId)
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
CODE_COUNT,
|
||||
normalize,
|
||||
generateForUser,
|
||||
consumeForUser,
|
||||
remainingForUser,
|
||||
clearForUser,
|
||||
}
|
||||
103
server/src/model/trustedDevices/trustedDevices.db.js
Normal file
103
server/src/model/trustedDevices/trustedDevices.db.js
Normal file
@@ -0,0 +1,103 @@
|
||||
const { query } = require('../../utils/db')
|
||||
|
||||
// SQL for the trusted_devices table. The opaque trust token lives client-side; the
|
||||
// DB stores only its sha256 hash (token_hash). Mirrors mobileSessions.db — a
|
||||
// trusted device is the MFA analogue of a live session: it lets a login skip the
|
||||
// TOTP step, and is revocable per-row.
|
||||
|
||||
// Insert a new trusted-device row. expiresAt is a JS Date (or ms epoch). last_used_at
|
||||
// is seeded to now (the device was just trusted at a successful login).
|
||||
async function insert({ userId, tokenHash, platform = 'web', deviceName = null, deviceHash = null, userAgent = null, expiresAt }) {
|
||||
const res = await query(
|
||||
`INSERT INTO trusted_devices (user_id, token_hash, platform, device_name, device_hash, user_agent, expires_at, last_used_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, NOW())`,
|
||||
[userId, tokenHash, platform, deviceName, deviceHash, userAgent, new Date(expiresAt)],
|
||||
)
|
||||
return res.insertId
|
||||
}
|
||||
|
||||
// Look up a trusted device by token hash only if it is still usable: not revoked
|
||||
// and not past expiry. Returns the row (incl. user_id) or null. Used by the login
|
||||
// path to decide whether TOTP can be skipped.
|
||||
async function findValidByHash(tokenHash) {
|
||||
const rows = await query(
|
||||
`SELECT * FROM trusted_devices
|
||||
WHERE token_hash = ? AND revoked_at IS NULL AND expires_at > NOW()
|
||||
LIMIT 1`,
|
||||
[tokenHash],
|
||||
)
|
||||
return rows[0] || null
|
||||
}
|
||||
|
||||
// Stamp last_used_at when a device's trust is honored at login. Idempotent.
|
||||
async function touchLastUsed(id) {
|
||||
const res = await query(
|
||||
'UPDATE trusted_devices SET last_used_at = NOW() WHERE id = ?',
|
||||
[id],
|
||||
)
|
||||
return Number(res.affectedRows || 0)
|
||||
}
|
||||
|
||||
// List a user's currently-active (unrevoked, unexpired) trusted devices — newest
|
||||
// first. Never returns the token hash. Powers the self-service "Trusted Devices"
|
||||
// list and the admin per-user view. Works for any user id (self or admin target).
|
||||
async function listActiveForUser(userId) {
|
||||
return query(
|
||||
`SELECT id, platform, device_name, device_hash, user_agent, created_at, last_used_at, expires_at
|
||||
FROM trusted_devices
|
||||
WHERE user_id = ? AND revoked_at IS NULL AND expires_at > NOW()
|
||||
ORDER BY last_used_at DESC, created_at DESC`,
|
||||
[userId],
|
||||
)
|
||||
}
|
||||
|
||||
// Count a user's currently-active trusted devices. Used to enforce the per-user cap
|
||||
// (no silent pruning — the caller refuses an over-cap insert instead).
|
||||
async function countActiveForUser(userId) {
|
||||
const rows = await query(
|
||||
'SELECT COUNT(*) AS n FROM trusted_devices WHERE user_id = ? AND revoked_at IS NULL AND expires_at > NOW()',
|
||||
[userId],
|
||||
)
|
||||
return Number(rows[0]?.n || 0)
|
||||
}
|
||||
|
||||
// Revoke one of a user's trusted devices by row id (ownership-scoped, so both self
|
||||
// and admin-for-target go through the same guarded query). Idempotent; returns
|
||||
// rows changed.
|
||||
async function revokeByIdForUser(id, userId) {
|
||||
const res = await query(
|
||||
'UPDATE trusted_devices SET revoked_at = NOW() WHERE id = ? AND user_id = ? AND revoked_at IS NULL',
|
||||
[id, userId],
|
||||
)
|
||||
return Number(res.affectedRows || 0)
|
||||
}
|
||||
|
||||
// Revoke every active trusted device for a user ("untrust everywhere", and the
|
||||
// invalidation hook on password change/reset / TOTP disable). Returns rows changed.
|
||||
async function revokeAllForUser(userId) {
|
||||
const res = await query(
|
||||
'UPDATE trusted_devices SET revoked_at = NOW() WHERE user_id = ? AND revoked_at IS NULL',
|
||||
[userId],
|
||||
)
|
||||
return Number(res.affectedRows || 0)
|
||||
}
|
||||
|
||||
// Housekeeping: delete rows that are long dead (expired or revoked). Returns rows
|
||||
// removed. Same opportunistic-prune approach as mobile_refresh_tokens.
|
||||
async function pruneExpired() {
|
||||
const res = await query(
|
||||
'DELETE FROM trusted_devices WHERE expires_at < NOW() OR revoked_at IS NOT NULL',
|
||||
)
|
||||
return Number(res.affectedRows || 0)
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
insert,
|
||||
findValidByHash,
|
||||
touchLastUsed,
|
||||
listActiveForUser,
|
||||
countActiveForUser,
|
||||
revokeByIdForUser,
|
||||
revokeAllForUser,
|
||||
pruneExpired,
|
||||
}
|
||||
69
server/src/model/trustedDevices/trustedDevices.model.js
Normal file
69
server/src/model/trustedDevices/trustedDevices.model.js
Normal file
@@ -0,0 +1,69 @@
|
||||
// Trusted-device store. Thin logic layer over trustedDevices.db — mirrors the
|
||||
// mobileSessions model split (.db = SQL, .model = the API the rest of the app
|
||||
// calls). The opaque trust token lives client-side; only its sha256 hash is
|
||||
// persisted (hashing is done by the session service so caller + store agree, the
|
||||
// same seam as mobile refresh tokens).
|
||||
|
||||
const db = require('./trustedDevices.db')
|
||||
|
||||
// Max active trusted devices per user. Enforced by assertUnderCap (no silent
|
||||
// pruning — an over-cap trust attempt is refused so the client can prompt the user
|
||||
// to revoke one first). See docs/website/TRUSTED_DEVICES_MFA.md §5.
|
||||
const MAX_TRUSTED_DEVICES = Number(process.env.MAX_TRUSTED_DEVICES) || 10
|
||||
|
||||
// Persist a newly trusted device (by token hash). Returns the row id.
|
||||
async function store({ userId, tokenHash, platform, deviceName, deviceHash, userAgent, expiresAt }) {
|
||||
return db.insert({ userId, tokenHash, platform, deviceName, deviceHash, userAgent, expiresAt })
|
||||
}
|
||||
|
||||
// Return the stored row for a still-valid (unrevoked, unexpired) trust token, else
|
||||
// null. Used by the login path to decide whether the TOTP step can be skipped.
|
||||
async function findValidByHash(tokenHash) {
|
||||
return db.findValidByHash(tokenHash)
|
||||
}
|
||||
|
||||
// Stamp last_used_at when a device's trust is honored at login.
|
||||
async function touchLastUsed(id) {
|
||||
return db.touchLastUsed(id)
|
||||
}
|
||||
|
||||
// List a user's active trusted devices (self-service list + admin per-user view).
|
||||
async function listActiveForUser(userId) {
|
||||
return db.listActiveForUser(userId)
|
||||
}
|
||||
|
||||
// True if the user is at/over the trusted-device cap. Callers refuse the insert and
|
||||
// signal the client to revoke one first, rather than pruning silently.
|
||||
async function isAtCap(userId) {
|
||||
const n = await db.countActiveForUser(userId)
|
||||
return n >= MAX_TRUSTED_DEVICES
|
||||
}
|
||||
|
||||
// Revoke one of a user's trusted devices by row id (ownership-scoped). Returns rows
|
||||
// changed (0 if it wasn't theirs / already gone — treat idempotently).
|
||||
async function revokeByIdForUser(id, userId) {
|
||||
return db.revokeByIdForUser(id, userId)
|
||||
}
|
||||
|
||||
// Revoke all of a user's trusted devices ("untrust everywhere" + the invalidation
|
||||
// hook on password change/reset / TOTP disable). Returns rows changed.
|
||||
async function revokeAllForUser(userId) {
|
||||
return db.revokeAllForUser(userId)
|
||||
}
|
||||
|
||||
// Drop expired/revoked rows.
|
||||
async function pruneExpired() {
|
||||
return db.pruneExpired()
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
MAX_TRUSTED_DEVICES,
|
||||
store,
|
||||
findValidByHash,
|
||||
touchLastUsed,
|
||||
listActiveForUser,
|
||||
isAtCap,
|
||||
revokeByIdForUser,
|
||||
revokeAllForUser,
|
||||
pruneExpired,
|
||||
}
|
||||
Reference in New Issue
Block a user