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:
113
server/test/adminTrustedDevices.test.js
Normal file
113
server/test/adminTrustedDevices.test.js
Normal file
@@ -0,0 +1,113 @@
|
||||
// Point the DB at a closed port BEFORE requiring anything that builds the pool.
|
||||
// Every model method the controller touches is stubbed, so the DB is never hit.
|
||||
process.env.DB_HOST = '127.0.0.1'
|
||||
process.env.DB_PORT = '59999'
|
||||
|
||||
const { test, after, afterEach } = require('node:test')
|
||||
const assert = require('node:assert/strict')
|
||||
|
||||
// Unit-test the admin trusted-device + MFA-reset handlers, plus their audit
|
||||
// logging. Invariants:
|
||||
// - a missing target user is a 404 before any mutation;
|
||||
// - revocation is ownership-scoped to the target user id;
|
||||
// - an MFA reset turns TOTP off AND clears both trusted devices and recovery
|
||||
// codes, and every admin action is audit-logged.
|
||||
const ctrl = require('../src/router/v1/admin/admin.controller')
|
||||
const users = require('../src/model/users/users.model')
|
||||
const trustedDevices = require('../src/model/trustedDevices/trustedDevices.model')
|
||||
const recoveryCodes = require('../src/model/recoveryCodes/recoveryCodes.model')
|
||||
const activity = require('../src/model/activity/activity.model')
|
||||
const db = require('../src/utils/db')
|
||||
|
||||
after(() => db.close())
|
||||
|
||||
function mockRes() {
|
||||
return {
|
||||
statusCode: 200,
|
||||
body: null,
|
||||
status(c) { this.statusCode = c; return this },
|
||||
json(b) { this.body = b; return this },
|
||||
}
|
||||
}
|
||||
|
||||
const originals = {
|
||||
getById: users.getById,
|
||||
disableTotp: users.disableTotp,
|
||||
listActiveForUser: trustedDevices.listActiveForUser,
|
||||
revokeByIdForUser: trustedDevices.revokeByIdForUser,
|
||||
revokeAllForUser: trustedDevices.revokeAllForUser,
|
||||
clearForUser: recoveryCodes.clearForUser,
|
||||
log: activity.log,
|
||||
}
|
||||
afterEach(() => { Object.assign(users, { getById: originals.getById, disableTotp: originals.disableTotp }); Object.assign(trustedDevices, { listActiveForUser: originals.listActiveForUser, revokeByIdForUser: originals.revokeByIdForUser, revokeAllForUser: originals.revokeAllForUser }); recoveryCodes.clearForUser = originals.clearForUser; activity.log = originals.log })
|
||||
|
||||
const adminReq = (params = {}) => ({ params, user: { id: 1, role: 'admin' }, ip: '10.0.0.1', headers: {} })
|
||||
|
||||
test('listUserTrustedDevices 404s when the target user does not exist', async () => {
|
||||
users.getById = async () => null
|
||||
const res = mockRes()
|
||||
await ctrl.listUserTrustedDevices(adminReq({ id: '77' }), res)
|
||||
assert.equal(res.statusCode, 404)
|
||||
})
|
||||
|
||||
test('listUserTrustedDevices returns the target user’s devices without token hashes', async () => {
|
||||
users.getById = async (id) => ({ id })
|
||||
trustedDevices.listActiveForUser = async (id) => (id === 77 ? [{ id: 3, platform: 'web', device_name: 'Lap', user_agent: 'UA', created_at: 'c', last_used_at: 'l', expires_at: 'e', token_hash: 'SECRET' }] : [])
|
||||
const res = mockRes()
|
||||
await ctrl.listUserTrustedDevices(adminReq({ id: '77' }), res)
|
||||
assert.equal(res.body.length, 1)
|
||||
assert.equal(res.body[0].id, 3)
|
||||
assert.equal(res.body[0].deviceName, 'Lap')
|
||||
assert.equal(res.body[0].token_hash, undefined, 'never leak the hash')
|
||||
})
|
||||
|
||||
test('revokeUserTrustedDevice is ownership-scoped to the target user and audit-logged', async () => {
|
||||
users.getById = async (id) => ({ id })
|
||||
let scoped = null
|
||||
trustedDevices.revokeByIdForUser = async (deviceId, userId) => { scoped = { deviceId, userId }; return 1 }
|
||||
let logged = null
|
||||
activity.log = async (e) => { logged = e.action }
|
||||
const res = mockRes()
|
||||
await ctrl.revokeUserTrustedDevice(adminReq({ id: '77', deviceId: '3' }), res)
|
||||
assert.deepEqual(scoped, { deviceId: 3, userId: 77 })
|
||||
assert.equal(res.body.revoked, true)
|
||||
assert.equal(logged, 'admin.trusted_device.revoke')
|
||||
})
|
||||
|
||||
test('revokeAllUserTrustedDevices revokes for the target user and logs the count', async () => {
|
||||
users.getById = async (id) => ({ id })
|
||||
trustedDevices.revokeAllForUser = async () => 4
|
||||
let logged = null
|
||||
activity.log = async (e) => { logged = e }
|
||||
const res = mockRes()
|
||||
await ctrl.revokeAllUserTrustedDevices(adminReq({ id: '77' }), res)
|
||||
assert.equal(res.body.revoked, 4)
|
||||
assert.equal(logged.action, 'admin.trusted_device.revoke_all')
|
||||
assert.equal(logged.detail.count, 4)
|
||||
})
|
||||
|
||||
test('resetUserMfa disables TOTP, clears trusted devices AND recovery codes, and logs', async () => {
|
||||
users.getById = async (id) => ({ id })
|
||||
const calls = { disable: null, revoke: null, clear: null, log: null }
|
||||
users.disableTotp = async (id) => { calls.disable = id }
|
||||
trustedDevices.revokeAllForUser = async (id) => { calls.revoke = id; return 2 }
|
||||
recoveryCodes.clearForUser = async (id) => { calls.clear = id }
|
||||
activity.log = async (e) => { calls.log = e.action }
|
||||
const res = mockRes()
|
||||
await ctrl.resetUserMfa(adminReq({ id: '77' }), res)
|
||||
assert.equal(res.body.ok, true)
|
||||
assert.equal(calls.disable, 77)
|
||||
assert.equal(calls.revoke, 77)
|
||||
assert.equal(calls.clear, 77)
|
||||
assert.equal(calls.log, 'admin.user.totp.reset')
|
||||
})
|
||||
|
||||
test('resetUserMfa 404s (and mutates nothing) for a missing user', async () => {
|
||||
users.getById = async () => null
|
||||
let touched = false
|
||||
users.disableTotp = async () => { touched = true }
|
||||
const res = mockRes()
|
||||
await ctrl.resetUserMfa(adminReq({ id: '999' }), res)
|
||||
assert.equal(res.statusCode, 404)
|
||||
assert.equal(touched, false)
|
||||
})
|
||||
@@ -27,6 +27,13 @@ test('/auth/me/account* rejects unauthenticated callers with 401', async () => {
|
||||
['POST', '/api/v1/auth/me/account/totp/setup'],
|
||||
['POST', '/api/v1/auth/me/account/totp/enable', { code: '123456' }],
|
||||
['DELETE', '/api/v1/auth/me/account/identities/google'],
|
||||
// Trusted devices + recovery codes are self-service too — same gate.
|
||||
['GET', '/api/v1/auth/me/trusted-devices'],
|
||||
['POST', '/api/v1/auth/me/trusted-devices', { deviceName: 'X' }],
|
||||
['DELETE', '/api/v1/auth/me/trusted-devices'],
|
||||
['DELETE', '/api/v1/auth/me/trusted-devices/1'],
|
||||
['GET', '/api/v1/auth/me/account/recovery-codes/status'],
|
||||
['POST', '/api/v1/auth/me/account/recovery-codes/generate', { currentPassword: 'x' }],
|
||||
]
|
||||
for (const [method, path, body] of calls) {
|
||||
const res = await fetch(app.url + path, {
|
||||
|
||||
170
server/test/authTrustedDevice.test.js
Normal file
170
server/test/authTrustedDevice.test.js
Normal file
@@ -0,0 +1,170 @@
|
||||
// Point the DB at a closed port BEFORE requiring the controller (its models build
|
||||
// the pool). Every collaborator is monkeypatched, so no query runs.
|
||||
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')
|
||||
|
||||
// Unit-test the trusted-device + recovery-code additions to the web auth flow:
|
||||
// - a TOTP user on a trusted device (bound to THEM) skips the second factor;
|
||||
// - a trust token bound to a DIFFERENT user is ignored (challenge as usual);
|
||||
// - loginTotp accepts a single-use recovery code as an alternative second factor;
|
||||
// - trustDevice sets the trust cookie under the cap, and surfaces a
|
||||
// { trustLimitReached, devices } prompt (session still issued) at the cap.
|
||||
const ctrl = require('../src/router/v1/auth/auth.controller')
|
||||
const users = require('../src/model/users/users.model')
|
||||
const activity = require('../src/model/activity/activity.model')
|
||||
const sessionService = require('../src/auth/session.service')
|
||||
const trustedDevices = require('../src/model/trustedDevices/trustedDevices.model')
|
||||
const recoveryCodes = require('../src/model/recoveryCodes/recoveryCodes.model')
|
||||
const totp = require('../src/utils/totp')
|
||||
const botScore = require('../src/middleware/botScore')
|
||||
const loginProtection = require('../src/middleware/loginProtection')
|
||||
const db = require('../src/utils/db')
|
||||
|
||||
after(() => db.close())
|
||||
|
||||
function mockRes() {
|
||||
return {
|
||||
statusCode: 200,
|
||||
body: null,
|
||||
cookies: {},
|
||||
status(c) { this.statusCode = c; return this },
|
||||
json(b) { this.body = b; return this },
|
||||
cookie(name, val) { this.cookies[name] = val; return this },
|
||||
clearCookie(name) { this.cookies[name] = undefined; return this },
|
||||
}
|
||||
}
|
||||
|
||||
let sessionsCreated
|
||||
const orig = {}
|
||||
beforeEach(() => {
|
||||
sessionsCreated = []
|
||||
for (const [mod, name] of [
|
||||
[users, 'getRawByUsername'], [users, 'validatePassword'], [users, 'recordLogin'], [users, 'getRawById'],
|
||||
[activity, 'log'],
|
||||
[sessionService, 'createSession'], [sessionService, 'createPartialSession'], [sessionService, 'upgradeSessionAfterTotp'],
|
||||
[sessionService, 'resolveTrustedDevice'], [sessionService, 'honorTrustedDevice'],
|
||||
[sessionService, 'trustDeviceCapReached'], [sessionService, 'mintTrustToken'], [sessionService, 'sessionMeta'],
|
||||
[trustedDevices, 'store'], [trustedDevices, 'listActiveForUser'],
|
||||
[recoveryCodes, 'consumeForUser'],
|
||||
[totp, 'verifyCode'],
|
||||
[botScore, 'recordLoginFailure'], [loginProtection, 'recordFailure'], [loginProtection, 'recordSuccess'],
|
||||
]) {
|
||||
orig[name] = orig[name] || { mod, val: mod[name] }
|
||||
}
|
||||
users.recordLogin = async () => {}
|
||||
activity.log = async () => {}
|
||||
botScore.recordLoginFailure = () => {}
|
||||
loginProtection.recordFailure = () => {}
|
||||
loginProtection.recordSuccess = () => {}
|
||||
sessionService.createSession = (user, authMethod) => {
|
||||
sessionsCreated.push({ user, authMethod })
|
||||
return { token: 'session-token' }
|
||||
}
|
||||
sessionService.createPartialSession = () => 'challenge-jwt'
|
||||
sessionService.honorTrustedDevice = async () => true
|
||||
sessionService.sessionMeta = () => ({ deviceHash: 'dh', userAgent: 'UA' })
|
||||
})
|
||||
afterEach(() => {
|
||||
for (const key of Object.keys(orig)) { orig[key].mod[key] = orig[key].val; delete orig[key] }
|
||||
})
|
||||
|
||||
const baseReq = (body = {}) => ({ body, ip: '10.0.0.1', headers: {} })
|
||||
|
||||
// ── login(): trusted-device skips TOTP ────────────────────────────────────
|
||||
test('login: a TOTP user on a device trusted by THEM skips the code and gets a session', async () => {
|
||||
users.getRawByUsername = async () => ({ id: 5, username: 'safe', role: 'admin', status: 'active', totp_enabled: 1 })
|
||||
users.validatePassword = async () => true
|
||||
sessionService.resolveTrustedDevice = async () => ({ id: 11, user_id: 5 })
|
||||
let honored = null
|
||||
sessionService.honorTrustedDevice = async (id) => { honored = id }
|
||||
const res = mockRes()
|
||||
await ctrl.login(baseReq({ username: 'safe', password: 'right' }), res)
|
||||
assert.equal(sessionsCreated.length, 1, 'session issued without a TOTP challenge')
|
||||
assert.equal(sessionsCreated[0].authMethod, 'totp')
|
||||
assert.equal(honored, 11, 'the trusted device was stamped as used')
|
||||
assert.equal(res.body.totpRequired, undefined)
|
||||
})
|
||||
|
||||
test('login: a trust token bound to a DIFFERENT user is ignored (challenge as usual)', async () => {
|
||||
users.getRawByUsername = async () => ({ id: 5, username: 'safe', status: 'active', totp_enabled: 1 })
|
||||
users.validatePassword = async () => true
|
||||
sessionService.resolveTrustedDevice = async () => ({ id: 11, user_id: 999 }) // someone else's device
|
||||
const res = mockRes()
|
||||
await ctrl.login(baseReq({ username: 'safe', password: 'right' }), res)
|
||||
assert.equal(res.body.totpRequired, true)
|
||||
assert.equal(sessionsCreated.length, 0)
|
||||
})
|
||||
|
||||
test('login: a trusted-device lookup error falls back to the TOTP challenge (fail closed)', async () => {
|
||||
users.getRawByUsername = async () => ({ id: 5, username: 'safe', status: 'active', totp_enabled: 1 })
|
||||
users.validatePassword = async () => true
|
||||
sessionService.resolveTrustedDevice = async () => { throw new Error('store down') }
|
||||
const res = mockRes()
|
||||
await ctrl.login(baseReq({ username: 'safe', password: 'right' }), res)
|
||||
assert.equal(res.body.totpRequired, true)
|
||||
assert.equal(sessionsCreated.length, 0)
|
||||
})
|
||||
|
||||
// ── loginTotp(): recovery code as an alternative factor ───────────────────
|
||||
test('loginTotp: a valid recovery code (no TOTP code) issues the session and is consumed', async () => {
|
||||
sessionService.upgradeSessionAfterTotp = () => ({ id: 5 })
|
||||
users.getRawById = async () => ({ id: 5, username: 'safe', role: 'player', totp_enabled: 1, totp_secret: 'S' })
|
||||
totp.verifyCode = () => false
|
||||
let consumed = null
|
||||
recoveryCodes.consumeForUser = async (id, code) => { consumed = { id, code }; return true }
|
||||
const res = mockRes()
|
||||
await ctrl.loginTotp(baseReq({ challenge: 'ok', recoveryCode: 'abcde-12345' }), res)
|
||||
assert.equal(sessionsCreated.length, 1)
|
||||
assert.deepEqual(consumed, { id: 5, code: 'abcde-12345' })
|
||||
assert.equal(res.body.user.id, 5)
|
||||
})
|
||||
|
||||
test('loginTotp: neither a valid code nor a valid recovery code is a 401, no session', async () => {
|
||||
sessionService.upgradeSessionAfterTotp = () => ({ id: 5 })
|
||||
users.getRawById = async () => ({ id: 5, totp_enabled: 1, totp_secret: 'S' })
|
||||
totp.verifyCode = () => false
|
||||
recoveryCodes.consumeForUser = async () => false
|
||||
const res = mockRes()
|
||||
await ctrl.loginTotp(baseReq({ challenge: 'ok', recoveryCode: 'nope' }), res)
|
||||
assert.equal(res.statusCode, 401)
|
||||
assert.equal(sessionsCreated.length, 0)
|
||||
})
|
||||
|
||||
// ── loginTotp(): trustDevice opt-in ───────────────────────────────────────
|
||||
test('loginTotp: trustDevice under the cap sets the trust cookie', async () => {
|
||||
sessionService.upgradeSessionAfterTotp = () => ({ id: 5 })
|
||||
users.getRawById = async () => ({ id: 5, username: 'safe', role: 'admin', totp_enabled: 1, totp_secret: 'S' })
|
||||
totp.verifyCode = () => true
|
||||
sessionService.trustDeviceCapReached = async () => false
|
||||
sessionService.mintTrustToken = () => ({ trustToken: 'TRUST-RAW', trustHash: 'H', deviceHash: null, userAgent: null, expiresAt: new Date() })
|
||||
let stored = null
|
||||
trustedDevices.store = async (row) => { stored = row }
|
||||
const res = mockRes()
|
||||
await ctrl.loginTotp(baseReq({ challenge: 'ok', code: '654321', trustDevice: true, deviceName: 'My Laptop' }), res)
|
||||
assert.equal(sessionsCreated.length, 1)
|
||||
assert.equal(res.cookies.rg_trust, 'TRUST-RAW', 'the trust cookie was set')
|
||||
assert.equal(stored.userId, 5)
|
||||
assert.equal(stored.platform, 'web')
|
||||
assert.equal(stored.deviceName, 'My Laptop')
|
||||
assert.equal(res.body.trustLimitReached, undefined)
|
||||
})
|
||||
|
||||
test('loginTotp: trustDevice at the cap still issues the session but returns the limit prompt', async () => {
|
||||
sessionService.upgradeSessionAfterTotp = () => ({ id: 5 })
|
||||
users.getRawById = async () => ({ id: 5, username: 'safe', role: 'admin', totp_enabled: 1, totp_secret: 'S' })
|
||||
totp.verifyCode = () => true
|
||||
sessionService.trustDeviceCapReached = async () => true
|
||||
trustedDevices.listActiveForUser = async () => [{ id: 1, device_name: 'Old', created_at: 't', last_used_at: 't', expires_at: 't', platform: 'web' }]
|
||||
let stored = false
|
||||
trustedDevices.store = async () => { stored = true }
|
||||
const res = mockRes()
|
||||
await ctrl.loginTotp(baseReq({ challenge: 'ok', code: '654321', trustDevice: true }), res)
|
||||
assert.equal(sessionsCreated.length, 1, 'login still succeeds')
|
||||
assert.equal(res.cookies.rg_trust, undefined, 'no trust cookie at the cap')
|
||||
assert.equal(stored, false, 'no new trust row created')
|
||||
assert.equal(res.body.trustLimitReached, true)
|
||||
assert.equal(res.body.devices.length, 1)
|
||||
})
|
||||
@@ -18,6 +18,8 @@ const ctrl = require('../src/router/v1/auth/passwordReset.controller')
|
||||
const passwordResets = require('../src/model/passwordResets/passwordResets.model')
|
||||
const users = require('../src/model/users/users.model')
|
||||
const mobileSessions = require('../src/model/mobileSessions/mobileSessions.model')
|
||||
const trustedDevices = require('../src/model/trustedDevices/trustedDevices.model')
|
||||
const recoveryCodes = require('../src/model/recoveryCodes/recoveryCodes.model')
|
||||
const activity = require('../src/model/activity/activity.model')
|
||||
const mailer = require('../src/utils/mailer')
|
||||
const db = require('../src/utils/db')
|
||||
@@ -46,7 +48,8 @@ beforeEach(() => {
|
||||
for (const [mod, name] of [
|
||||
[users, 'getActiveByEmail'], [users, 'getById'], [users, 'update'],
|
||||
[passwordResets, 'create'], [passwordResets, 'findValidByToken'], [passwordResets, 'consume'], [passwordResets, 'invalidatePendingForUser'],
|
||||
[mobileSessions, 'revokeAllForUser'], [activity, 'log'], [mailer, 'sendPasswordReset'],
|
||||
[mobileSessions, 'revokeAllForUser'], [trustedDevices, 'revokeAllForUser'], [recoveryCodes, 'clearForUser'],
|
||||
[activity, 'log'], [mailer, 'sendPasswordReset'],
|
||||
]) {
|
||||
orig[name] = { mod, val: mod[name] }
|
||||
}
|
||||
@@ -55,6 +58,8 @@ beforeEach(() => {
|
||||
passwordResets.create = async () => ({ token: 'opaque-token' })
|
||||
passwordResets.invalidatePendingForUser = async () => {}
|
||||
mobileSessions.revokeAllForUser = async () => {}
|
||||
trustedDevices.revokeAllForUser = async () => {}
|
||||
recoveryCodes.clearForUser = async () => {}
|
||||
})
|
||||
afterEach(() => {
|
||||
for (const key of Object.keys(orig)) {
|
||||
|
||||
95
server/test/recoveryCodes.test.js
Normal file
95
server/test/recoveryCodes.test.js
Normal file
@@ -0,0 +1,95 @@
|
||||
// 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)
|
||||
})
|
||||
162
server/test/selfTrustedDevices.test.js
Normal file
162
server/test/selfTrustedDevices.test.js
Normal file
@@ -0,0 +1,162 @@
|
||||
// Point the DB at a closed port BEFORE requiring the controller (its models build
|
||||
// the pool). Every collaborator is monkeypatched, so no query runs.
|
||||
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')
|
||||
|
||||
// Unit-test the self-service trusted-device + recovery-code account handlers.
|
||||
// Invariants:
|
||||
// - enabling TOTP hands back a one-time batch of recovery codes;
|
||||
// - disabling TOTP clears BOTH trusted devices and recovery codes;
|
||||
// - trusting the current device is ownership-scoped and honors the cap (409);
|
||||
// - self-revoke is scoped to the caller's own id;
|
||||
// - regenerating recovery codes is a password step-up (wrong password → 400).
|
||||
const ctrl = require('../src/router/v1/admin/account.controller')
|
||||
const users = require('../src/model/users/users.model')
|
||||
const activity = require('../src/model/activity/activity.model')
|
||||
const sessionService = require('../src/auth/session.service')
|
||||
const trustedDevices = require('../src/model/trustedDevices/trustedDevices.model')
|
||||
const recoveryCodes = require('../src/model/recoveryCodes/recoveryCodes.model')
|
||||
const totp = require('../src/utils/totp')
|
||||
const botScore = require('../src/middleware/botScore')
|
||||
const loginProtection = require('../src/middleware/loginProtection')
|
||||
const db = require('../src/utils/db')
|
||||
|
||||
after(() => db.close())
|
||||
|
||||
function mockRes() {
|
||||
return {
|
||||
statusCode: 200,
|
||||
body: null,
|
||||
cookies: {},
|
||||
status(c) { this.statusCode = c; return this },
|
||||
json(b) { this.body = b; return this },
|
||||
cookie(name, val) { this.cookies[name] = val; return this },
|
||||
clearCookie(name) { this.cookies[name] = undefined; return this },
|
||||
}
|
||||
}
|
||||
|
||||
const orig = {}
|
||||
beforeEach(() => {
|
||||
for (const [mod, name] of [
|
||||
[users, 'getRawById'], [users, 'validatePassword'], [users, 'enableTotp'], [users, 'disableTotp'], [users, 'setTotpSecret'],
|
||||
[activity, 'log'], [totp, 'verifyCode'],
|
||||
[sessionService, 'trustDeviceCapReached'], [sessionService, 'mintTrustToken'], [sessionService, 'sessionMeta'],
|
||||
[trustedDevices, 'store'], [trustedDevices, 'listActiveForUser'], [trustedDevices, 'revokeByIdForUser'], [trustedDevices, 'revokeAllForUser'],
|
||||
[recoveryCodes, 'generateForUser'], [recoveryCodes, 'clearForUser'], [recoveryCodes, 'remainingForUser'],
|
||||
[botScore, 'recordLoginFailure'], [loginProtection, 'recordFailure'],
|
||||
]) {
|
||||
orig[name] = orig[name] || { mod, val: mod[name] }
|
||||
}
|
||||
activity.log = async () => {}
|
||||
botScore.recordLoginFailure = () => {}
|
||||
loginProtection.recordFailure = () => {}
|
||||
sessionService.sessionMeta = () => ({ deviceHash: 'dh', userAgent: 'UA' })
|
||||
})
|
||||
afterEach(() => {
|
||||
for (const key of Object.keys(orig)) { orig[key].mod[key] = orig[key].val; delete orig[key] }
|
||||
})
|
||||
|
||||
const req = (extra = {}) => ({ body: {}, params: {}, ip: '10.0.0.1', headers: {}, user: { id: 5, username: 'u' }, session: { authMethod: 'local' }, ...extra })
|
||||
|
||||
// ── TOTP enable/disable ↔ recovery codes ─────────────────────────────────
|
||||
test('totpEnable returns a one-time batch of recovery codes', async () => {
|
||||
users.getRawById = async () => ({ id: 5, username: 'u', totp_secret: 'S', totp_enabled: 0 })
|
||||
totp.verifyCode = () => true
|
||||
users.enableTotp = async () => {}
|
||||
recoveryCodes.generateForUser = async () => ['aaaa-bbbb', 'cccc-dddd']
|
||||
const res = mockRes()
|
||||
await ctrl.totpEnable({ ...req(), body: { code: '123456' }, user: { id: 5, username: 'u', totp_enabled: 0 } }, res)
|
||||
assert.equal(res.body.totp_enabled, true)
|
||||
assert.deepEqual(res.body.recoveryCodes, ['aaaa-bbbb', 'cccc-dddd'])
|
||||
})
|
||||
|
||||
test('totpDisable clears trusted devices and recovery codes', async () => {
|
||||
users.getRawById = async () => ({ id: 5, totp_enabled: 1, totp_secret: 'S' })
|
||||
totp.verifyCode = () => true
|
||||
users.disableTotp = async () => {}
|
||||
let revokedTrust = false
|
||||
let clearedCodes = false
|
||||
trustedDevices.revokeAllForUser = async () => { revokedTrust = true }
|
||||
recoveryCodes.clearForUser = async () => { clearedCodes = true }
|
||||
const res = mockRes()
|
||||
await ctrl.totpDisable({ ...req(), body: { code: '123456' } }, res)
|
||||
assert.equal(res.body.totp_enabled, false)
|
||||
assert.equal(revokedTrust, true)
|
||||
assert.equal(clearedCodes, true)
|
||||
assert.equal(res.cookies.rg_trust, undefined, 'trust cookie cleared')
|
||||
})
|
||||
|
||||
// ── trust current device ─────────────────────────────────────────────────
|
||||
test('trustThisDevice sets the web trust cookie under the cap', async () => {
|
||||
sessionService.trustDeviceCapReached = async () => false
|
||||
sessionService.mintTrustToken = () => ({ trustToken: 'RAW', trustHash: 'H', deviceHash: null, userAgent: null, expiresAt: new Date() })
|
||||
let stored = null
|
||||
trustedDevices.store = async (row) => { stored = row }
|
||||
const res = mockRes()
|
||||
await ctrl.trustThisDevice(req({ body: { deviceName: 'Desk' } }), res)
|
||||
assert.equal(res.body.trusted, true)
|
||||
assert.equal(res.cookies.rg_trust, 'RAW')
|
||||
assert.equal(stored.userId, 5)
|
||||
assert.equal(stored.platform, 'web')
|
||||
})
|
||||
|
||||
test('trustThisDevice returns 409 with the device list at the cap', async () => {
|
||||
sessionService.trustDeviceCapReached = async () => true
|
||||
trustedDevices.listActiveForUser = async () => [{ id: 1, platform: 'web', device_name: 'A', created_at: 'c', last_used_at: 'l', expires_at: 'e' }]
|
||||
const res = mockRes()
|
||||
await ctrl.trustThisDevice(req(), res)
|
||||
assert.equal(res.statusCode, 409)
|
||||
assert.equal(res.body.error, 'trusted_device_limit')
|
||||
assert.equal(res.body.devices.length, 1)
|
||||
})
|
||||
|
||||
test('trustThisDevice on a mobile (bearer) session returns the token in the body, no cookie', async () => {
|
||||
sessionService.trustDeviceCapReached = async () => false
|
||||
sessionService.mintTrustToken = () => ({ trustToken: 'RAW', trustHash: 'H', deviceHash: null, userAgent: null, expiresAt: new Date() })
|
||||
trustedDevices.store = async () => {}
|
||||
const res = mockRes()
|
||||
await ctrl.trustThisDevice(req({ session: { authMethod: 'mobile' } }), res)
|
||||
assert.equal(res.body.trustToken, 'RAW')
|
||||
assert.equal(res.cookies.rg_trust, undefined, 'native clients get no cookie')
|
||||
})
|
||||
|
||||
// ── self-revoke ownership scoping ─────────────────────────────────────────
|
||||
test('revokeTrustedDevice is scoped to the caller’s own id', async () => {
|
||||
let scoped = null
|
||||
trustedDevices.revokeByIdForUser = async (id, userId) => { scoped = { id, userId }; return 1 }
|
||||
const res = mockRes()
|
||||
await ctrl.revokeTrustedDevice(req({ params: { id: '9' } }), res)
|
||||
assert.deepEqual(scoped, { id: 9, userId: 5 })
|
||||
assert.equal(res.body.revoked, true)
|
||||
})
|
||||
|
||||
// ── recovery-code regeneration is a password step-up ──────────────────────
|
||||
test('generateRecoveryCodes rejects a wrong current password with 400 (no regeneration)', async () => {
|
||||
users.getRawById = async () => ({ id: 5, totp_enabled: 1, password_hash: 'H' })
|
||||
users.validatePassword = async () => false
|
||||
let generated = false
|
||||
recoveryCodes.generateForUser = async () => { generated = true; return [] }
|
||||
const res = mockRes()
|
||||
await ctrl.generateRecoveryCodes(req({ body: { currentPassword: 'wrong' } }), res)
|
||||
assert.equal(res.statusCode, 400)
|
||||
assert.equal(generated, false)
|
||||
})
|
||||
|
||||
test('generateRecoveryCodes returns a fresh set when the password checks out', async () => {
|
||||
users.getRawById = async () => ({ id: 5, totp_enabled: 1, password_hash: 'H' })
|
||||
users.validatePassword = async () => true
|
||||
recoveryCodes.generateForUser = async () => ['new1-new1', 'new2-new2']
|
||||
const res = mockRes()
|
||||
await ctrl.generateRecoveryCodes(req({ body: { currentPassword: 'right' } }), res)
|
||||
assert.deepEqual(res.body.recoveryCodes, ['new1-new1', 'new2-new2'])
|
||||
})
|
||||
|
||||
test('generateRecoveryCodes refuses when two-factor is off', async () => {
|
||||
users.getRawById = async () => ({ id: 5, totp_enabled: 0, password_hash: 'H' })
|
||||
const res = mockRes()
|
||||
await ctrl.generateRecoveryCodes(req({ body: { currentPassword: 'right' } }), res)
|
||||
assert.equal(res.statusCode, 400)
|
||||
})
|
||||
84
server/test/trustedDevices.test.js
Normal file
84
server/test/trustedDevices.test.js
Normal file
@@ -0,0 +1,84 @@
|
||||
// Point the DB at a closed port BEFORE requiring the modules (they build the pool).
|
||||
// The .db / model layers are monkeypatched so no query runs.
|
||||
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 crypto = require('crypto')
|
||||
|
||||
// Unit-test the trusted-device seam: the session-service crypto helpers and the
|
||||
// model's cap check. Invariants:
|
||||
// - a trust token is a high-entropy opaque value hashed deterministically with
|
||||
// sha256 (so the login path can look it up by hash);
|
||||
// - resolveTrustedDevice only returns a device when a token is actually present;
|
||||
// - the per-user cap is a hard boundary (>= MAX is "at cap").
|
||||
const sessionService = require('../src/auth/session.service')
|
||||
const trustedDevices = require('../src/model/trustedDevices/trustedDevices.model')
|
||||
const devicesDb = require('../src/model/trustedDevices/trustedDevices.db')
|
||||
const db = require('../src/utils/db')
|
||||
|
||||
after(() => db.close())
|
||||
|
||||
test('hashTrustToken is deterministic sha256 hex', () => {
|
||||
const h1 = sessionService.hashTrustToken('abc')
|
||||
const h2 = sessionService.hashTrustToken('abc')
|
||||
assert.equal(h1, h2)
|
||||
assert.equal(h1, crypto.createHash('sha256').update('abc').digest('hex'))
|
||||
assert.equal(h1.length, 64)
|
||||
assert.notEqual(sessionService.hashTrustToken('abc'), sessionService.hashTrustToken('abd'))
|
||||
})
|
||||
|
||||
test('mintTrustToken emits an opaque token, its matching hash, and a ~30d expiry', () => {
|
||||
const now = 1_000_000_000_000
|
||||
const out = sessionService.mintTrustToken({ deviceHash: 'dh', userAgent: 'UA' }, now)
|
||||
assert.ok(out.trustToken.length >= 40, 'token carries real entropy')
|
||||
assert.match(out.trustToken, /^[A-Za-z0-9_-]+$/, 'url-safe base64')
|
||||
assert.equal(out.trustHash, sessionService.hashTrustToken(out.trustToken))
|
||||
assert.equal(out.deviceHash, 'dh')
|
||||
assert.equal(out.userAgent, 'UA')
|
||||
const days = (out.expiresAt.getTime() - now) / (24 * 60 * 60 * 1000)
|
||||
assert.equal(Math.round(days), 30)
|
||||
})
|
||||
|
||||
// ── resolveTrustedDevice ─────────────────────────────────────────────────
|
||||
const origFind = trustedDevices.findValidByHash
|
||||
afterEach(() => { trustedDevices.findValidByHash = origFind })
|
||||
|
||||
test('resolveTrustedDevice returns null when the request carries no trust token', async () => {
|
||||
let looked = false
|
||||
trustedDevices.findValidByHash = async () => { looked = true; return { id: 1 } }
|
||||
const row = await sessionService.resolveTrustedDevice({ headers: {} })
|
||||
assert.equal(row, null)
|
||||
assert.equal(looked, false, 'no lookup without a token')
|
||||
})
|
||||
|
||||
test('resolveTrustedDevice looks up by the hash of the presented cookie token', async () => {
|
||||
let seenHash = null
|
||||
trustedDevices.findValidByHash = async (h) => { seenHash = h; return { id: 9, user_id: 3 } }
|
||||
const req = { headers: {}, cookies: { rg_trust: 'opaque-raw' } }
|
||||
const row = await sessionService.resolveTrustedDevice(req)
|
||||
assert.equal(row.id, 9)
|
||||
assert.equal(seenHash, sessionService.hashTrustToken('opaque-raw'))
|
||||
})
|
||||
|
||||
test('resolveTrustedDevice also accepts the X-Trust-Token header (native clients)', async () => {
|
||||
trustedDevices.findValidByHash = async (h) => (h === sessionService.hashTrustToken('hdr-token') ? { id: 5 } : null)
|
||||
const row = await sessionService.resolveTrustedDevice({ headers: { 'x-trust-token': 'hdr-token' } })
|
||||
assert.equal(row.id, 5)
|
||||
})
|
||||
|
||||
// ── cap ──────────────────────────────────────────────────────────────────
|
||||
const origCount = devicesDb.countActiveForUser
|
||||
beforeEach(() => { devicesDb.countActiveForUser = origCount })
|
||||
after(() => { devicesDb.countActiveForUser = origCount })
|
||||
|
||||
test('isAtCap is false below the max and true at/over it', async () => {
|
||||
const max = trustedDevices.MAX_TRUSTED_DEVICES
|
||||
devicesDb.countActiveForUser = async () => max - 1
|
||||
assert.equal(await trustedDevices.isAtCap(1), false)
|
||||
devicesDb.countActiveForUser = async () => max
|
||||
assert.equal(await trustedDevices.isAtCap(1), true)
|
||||
devicesDb.countActiveForUser = async () => max + 3
|
||||
assert.equal(await trustedDevices.isAtCap(1), true)
|
||||
})
|
||||
Reference in New Issue
Block a user