Files
website/server/test/recoveryCodes.test.js
wtclaude 60ebacff2c
All checks were successful
PR Checks / bot-install (pull_request) Successful in 19s
PR Checks / server-tests (pull_request) Successful in 42s
PR Checks / client-build (pull_request) Successful in 9m24s
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>
2026-07-21 23:38:48 -05:00

96 lines
3.9 KiB
JavaScript

// Point the DB at a closed port BEFORE requiring the model (it builds the pool).
// The .db layer is monkeypatched so no query runs; db.close() releases the pool.
process.env.DB_HOST = '127.0.0.1'
process.env.DB_PORT = '59999'
const { test, after, beforeEach, afterEach } = require('node:test')
const assert = require('node:assert/strict')
const bcrypt = require('bcryptjs')
// Unit-test the recovery-code model. Invariants a regression must not break:
// - generation returns the requested count of human-formatted codes and REPLACES
// any prior set (delete-then-insert), storing only bcrypt hashes;
// - a code verifies regardless of case/dash formatting, and only once (single use);
// - a wrong code never consumes anything.
const model = require('../src/model/recoveryCodes/recoveryCodes.model')
const codesDb = require('../src/model/recoveryCodes/recoveryCodes.db')
const db = require('../src/utils/db')
after(() => db.close())
const orig = {}
beforeEach(() => {
for (const name of ['insertMany', 'listUnusedForUser', 'countUnusedForUser', 'markUsed', 'deleteAllForUser']) {
orig[name] = codesDb[name]
}
})
afterEach(() => {
for (const name of Object.keys(orig)) codesDb[name] = orig[name]
for (const k of Object.keys(orig)) delete orig[k]
})
test('normalize strips separators/whitespace and uppercases', () => {
assert.equal(model.normalize('abcde-fghij'), 'ABCDEFGHIJ')
assert.equal(model.normalize(' ab cd '), 'ABCD')
assert.equal(model.normalize(null), '')
})
test('generateForUser returns the requested count, replaces the old set, and stores only hashes', async () => {
let deleted = null
let inserted = null
codesDb.deleteAllForUser = async (id) => { deleted = id }
codesDb.insertMany = async (id, hashes) => { inserted = { id, hashes }; return hashes.length }
const codes = await model.generateForUser(42, 5)
assert.equal(codes.length, 5)
assert.equal(deleted, 42, 'old codes are cleared first')
assert.equal(inserted.id, 42)
assert.equal(inserted.hashes.length, 5)
// Nothing stored in the clear: every persisted value is a bcrypt hash, and it
// is NOT the code itself.
for (let i = 0; i < 5; i++) {
assert.match(inserted.hashes[i], /^\$2[aby]\$/)
assert.notEqual(inserted.hashes[i], model.normalize(codes[i]))
}
// Each displayed code carries a separator for readability.
assert.ok(codes.every((c) => c.includes('-')))
})
test('consumeForUser accepts a formatted code once, then never again', async () => {
const plainCanonical = 'ABCDE23456'
const hash = await bcrypt.hash(plainCanonical, 10)
const rows = [{ id: 1, code_hash: await bcrypt.hash('OTHER12345', 10) }, { id: 2, code_hash: hash }]
const marked = []
codesDb.listUnusedForUser = async () => rows.filter((r) => !marked.includes(r.id))
codesDb.markUsed = async (id) => { marked.push(id); return 1 }
// Case/format-insensitive: the user may type it lowercase with a dash.
const ok = await model.consumeForUser(7, 'abcde-23456')
assert.equal(ok, true)
assert.deepEqual(marked, [2], 'the matching row was consumed')
// Single use: the same code no longer verifies (its row is now used).
const again = await model.consumeForUser(7, 'abcde-23456')
assert.equal(again, false)
})
test('consumeForUser returns false for a wrong code and consumes nothing', async () => {
const rows = [{ id: 1, code_hash: await bcrypt.hash('REALCODE99', 10) }]
let markedCount = 0
codesDb.listUnusedForUser = async () => rows
codesDb.markUsed = async () => { markedCount++; return 1 }
const ok = await model.consumeForUser(7, 'WRONGCODE0')
assert.equal(ok, false)
assert.equal(markedCount, 0)
})
test('consumeForUser is false for an empty input without touching the DB', async () => {
let listed = false
codesDb.listUnusedForUser = async () => { listed = true; return [] }
const ok = await model.consumeForUser(7, ' ')
assert.equal(ok, false)
assert.equal(listed, false)
})