Enforce TOTP second factor on SSO login (#31)

SSO login minted a full session immediately, ignoring the account's
totp_enabled flag — so a 2FA admin with a linked Google/Discord/OIDC
identity could sign in without their authenticator code, silently
downgrading the account to single-factor (the strength of the IdP login).
The local password flow already gates on needsTotp(); SSO did not.

Wire SSO through the same staged-TOTP gate:

- ssoState: createTotpPending/verifyTotpPending + a short-lived httpOnly
  sso_totp cookie. The pending token carries stage:'totp' (session
  validation rejects it) + kind:'sso_totp' (scoped to the SSO endpoint)
  plus the resolved context (userId, provider, authMethod, returnTo).
- sso.controller: finishLogin now stages the challenge and redirects to
  /admin/login?sso_totp=1 instead of creating a session when the account
  has TOTP on. New finishSsoTotp verifies the code (backoff + bot-scoring
  on failure, mirroring loginTotp) and only then mints the session.
- sso.routes: POST /auth/sso/totp behind the same backoff/slow/limiter
  stack and code validation as the local TOTP endpoint.
- client: AdminLogin detects ?sso_totp=1 and completes over fetch via
  api.ssoLoginTotp; the challenge never touches the URL or JS.

Keeps the second factor httpOnly throughout, consistent with the SSO tx
cookie. 12 new tests; full suite 106/106.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019rao86n5cXpwAyjdBFEshV
This commit is contained in:
2026-07-04 22:17:35 -05:00
parent 15cf8ea286
commit 03e62b56ad
8 changed files with 281 additions and 11 deletions

View File

@@ -15,6 +15,7 @@ const activity = require('../src/model/activity/activity.model')
const authProviders = require('../src/model/authProviders/authProviders.model')
const userIdentities = require('../src/model/userIdentities/userIdentities.model')
const registry = require('../src/auth/providers/registry')
const totp = require('../src/utils/totp')
const db = require('../src/utils/db')
after(() => db.close())
@@ -114,3 +115,75 @@ test('bad state (CSRF) → rejected before any provider work', async () => {
assert.equal(res.redirectedTo, '/admin/login?sso_error=bad_state')
assert.equal(res.cookies[token.COOKIE_NAME], undefined)
})
// ── 2FA parity: SSO must not bypass TOTP (issue #31) ────────────────────────
test('linked account with TOTP → staged challenge, NO session, routed to TOTP', async () => {
userIdentities.findByProviderSubject = async () => ({ user_id: 7 })
users.getById = async (id) => ({ id, username: 'alice', role: 'admin', totp_enabled: 1 })
const tx = ssoState.createTx({ provider: 'google', mode: 'login', returnTo: '/admin/posts' })
const res = mockRes()
await ssoCtrl.callback(makeReq(tx), res)
assert.equal(res.cookies[token.COOKIE_NAME], undefined, 'no full session before 2FA')
assert.ok(res.cookies[ssoState.TOTP_COOKIE], 'pending-TOTP cookie staged')
assert.equal(res.redirectedTo, '/admin/login?sso_totp=1')
assert.equal(logged.length, 0, 'login not logged until the second factor passes')
// The staged cookie carries the resolved context and is not a usable session.
const pending = ssoState.verifyTotpPending(res.cookies[ssoState.TOTP_COOKIE])
assert.equal(pending.id, 7)
assert.equal(pending.provider, 'google')
assert.equal(pending.returnTo, '/admin/posts')
})
function makeTotpReq(pendingToken, code) {
return {
cookies: pendingToken ? { [ssoState.TOTP_COOKIE]: pendingToken } : {},
body: { code },
ip: '127.0.0.1', protocol: 'http', get: () => 'localhost', headers: {},
}
}
test('finishSsoTotp: correct code → session issued, pending cookie cleared, login logged', async () => {
users.getRawById = async (id) => ({ id, username: 'alice', role: 'admin', totp_enabled: 1, totp_secret: 'S' })
totp.verifyCode = () => true
const pending = ssoState.createTotpPending({ userId: 7, provider: 'google', authMethod: 'google', returnTo: '/admin/posts' })
const res = mockRes()
await ssoCtrl.finishSsoTotp(makeTotpReq(pending, '123456'), res)
assert.ok(res.cookies[token.COOKIE_NAME], 'session cookie set after 2FA')
assert.ok(res.cleared.includes(ssoState.TOTP_COOKIE), 'pending-TOTP cookie cleared')
assert.equal(res.body.returnTo, '/admin/posts')
assert.equal(res.body.user.id, 7)
assert.equal(logged.at(-1).action, 'auth.sso.login')
assert.equal(logged.at(-1).detail.totp, true)
})
test('finishSsoTotp: wrong code → 401, no session', async () => {
users.getRawById = async (id) => ({ id, username: 'alice', role: 'admin', totp_enabled: 1, totp_secret: 'S' })
totp.verifyCode = () => false
const pending = ssoState.createTotpPending({ userId: 7, provider: 'google', authMethod: 'google' })
const res = mockRes()
await ssoCtrl.finishSsoTotp(makeTotpReq(pending, '000000'), res)
assert.equal(res.statusCode, 401)
assert.match(res.body.message, /Invalid verification code/)
assert.equal(res.cookies[token.COOKIE_NAME], undefined)
})
test('finishSsoTotp: missing/expired pending cookie → 401 expired', async () => {
const res = mockRes()
await ssoCtrl.finishSsoTotp(makeTotpReq(null, '123456'), res)
assert.equal(res.statusCode, 401)
assert.match(res.body.message, /expired/i)
assert.equal(res.cookies[token.COOKIE_NAME], undefined)
})
test('finishSsoTotp: a local /login/totp challenge is not accepted here', async () => {
// A stage:'totp' token without kind:'sso_totp' must be rejected by this endpoint.
const localChallenge = token.signTotpChallenge({ id: 7 })
const res = mockRes()
await ssoCtrl.finishSsoTotp(makeTotpReq(localChallenge, '123456'), res)
assert.equal(res.statusCode, 401)
assert.match(res.body.message, /expired/i)
})

View File

@@ -1,10 +1,18 @@
// Point the DB at a closed port before requiring the auth layer: session.service
// (used by one test below) pulls in the users model → db pool at load, and an idle
// pool would keep this process alive. None of these tests touch the database.
process.env.JWT_SECRET = process.env.JWT_SECRET || 'test-secret'
process.env.DB_HOST = '127.0.0.1'
process.env.DB_PORT = '59999'
const { test } = require('node:test')
const { test, after } = require('node:test')
const assert = require('node:assert/strict')
const crypto = require('crypto')
const ssoState = require('../src/auth/ssoState')
const db = require('../src/utils/db')
after(() => db.close())
test('createTx → verifyTx round-trips the flow payload', () => {
const tx = ssoState.createTx({ provider: 'google', mode: 'login', returnTo: '/admin/posts' })
@@ -36,3 +44,27 @@ test('verifyTx rejects a non-tx token', () => {
const notTx = token.signToken({ id: 1, username: 'a', role: 'admin' })
assert.equal(ssoState.verifyTx(notTx, 'anything'), null)
})
test('createTotpPending → verifyTotpPending round-trips the SSO 2FA context', () => {
const pending = ssoState.createTotpPending({ userId: 7, provider: 'google', authMethod: 'google', returnTo: '/admin/posts' })
const payload = ssoState.verifyTotpPending(pending)
assert.ok(payload)
assert.equal(payload.id, 7)
assert.equal(payload.provider, 'google')
assert.equal(payload.authMethod, 'google')
assert.equal(payload.returnTo, '/admin/posts')
assert.equal(payload.stage, 'totp')
})
test('a pending-TOTP token is NOT accepted as a session (stage + kind reject it)', () => {
const sessionService = require('../src/auth/session.service')
const pending = ssoState.createTotpPending({ userId: 7, provider: 'google', authMethod: 'google' })
assert.equal(sessionService.decodeIdentity(pending), null)
})
test('verifyTotpPending rejects a plain session and a bare TOTP challenge', () => {
const token = require('../src/auth/token')
assert.equal(ssoState.verifyTotpPending(token.signToken({ id: 1, username: 'a', role: 'admin' })), null)
assert.equal(ssoState.verifyTotpPending(token.signTotpChallenge({ id: 1 })), null)
assert.equal(ssoState.verifyTotpPending(null), null)
})