Files
website/server/src/router/v1/auth/sso.controller.js
Claude f8bcc7f6a3 Player accounts backend: schema, registration, self-service, SSO provision
- Widen users.role enum to include 'player'; make password_hash nullable;
  add email/email_verified/status/last_login_ip; pin username _ci collation.
- POST /auth/register (honeypot + registerLimiter + botScore, reserved-name
  blocklist, duplicate->409, auto-login). player_registration setting gates it.
- SSO auto-provision in finishLogin (setting-gated); return/portal-aware SSO
  redirects for the player portal; status refusal on login + requireAuth.
- New /player self-service group (account, change username/password, TOTP,
  identities), reusing account.controller; accountChangeLimiter.
- Admin: 'player' role + status/email on user create/update, role/status audit,
  player_registration enum validation, derived public registration flags.
- usernamePolicy module (reserved, sanitize, derive, dedup) + unit tests;
  extend SSO callback tests. 133 server tests green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019rao86n5cXpwAyjdBFEshV
2026-07-06 01:36:51 -05:00

334 lines
16 KiB
JavaScript

// ── SSO (OAuth2 / OIDC) controller ─────────────────────────────────────────
//
// Drives the redirect flow for built-in (Google, Discord) and custom providers:
// GET /auth/providers → public discovery (enabled + valid providers)
// GET /auth/sso/:provider/start → begin login (redirect to the IdP)
// GET /auth/sso/:provider/link → begin account linking (requireAuth)
// GET /auth/sso/:provider/callback → exchange code, then log in OR link
//
// LINK-ONLY policy: a login succeeds only if the external identity is already
// linked to an internal account. Unknown identities are refused, never
// auto-provisioned. Every successful login goes through sessionService, so the
// resulting session is identical to a local login (same cookie, logging, RBAC).
const users = require('../../../model/users/users.model')
const activity = require('../../../model/activity/activity.model')
const authProviders = require('../../../model/authProviders/authProviders.model')
const userIdentities = require('../../../model/userIdentities/userIdentities.model')
const settings = require('../../../model/settings/settings.model')
const registry = require('../../../auth/providers/registry')
const sessionService = require('../../../auth/session.service')
const ssoState = require('../../../auth/ssoState')
const token = require('../../../auth/token')
const totp = require('../../../utils/totp')
const usernamePolicy = require('../../../auth/usernamePolicy')
const botScore = require('../../../middleware/botScore')
const loginProtection = require('../../../middleware/loginProtection')
const { needsTotp } = require('./auth.controller')
const log = require('../../../utils/logger')('sso')
const PROVIDER_ID_RE = /^[a-z0-9-]+$/
// How many username suffixes to try before giving up on auto-provision.
const PROVISION_MAX_TRIES = 25
// Which front-end area a flow belongs to, derived from its returnTo. Players
// drive SSO from /account*, staff from /admin*; defaults to admin. This is what
// makes error/TOTP/success redirects land the caller back in their own portal.
function portalFor(returnTo) {
return typeof returnTo === 'string' && /^\/account(?:[/?]|$)/.test(returnTo) ? 'account' : 'admin'
}
const loginPath = (portal) => (portal === 'account' ? '/account/login' : '/admin/login')
const accountPath = (portal) => (portal === 'account' ? '/account' : '/admin/account')
const homePath = (portal) => (portal === 'account' ? '/account' : '/admin')
// Redirect targets (front-end routes). Errors surface as a query param the login
// / account pages can render. Portal-aware so a player flow stays in /account*.
const loginError = (code, portal = 'admin') => `${loginPath(portal)}?sso_error=${code}`
const accountError = (code, portal = 'admin') => `${accountPath(portal)}?link_error=${code}`
// Only allow returning to an internal /admin or /account path (prevents open
// redirect). Both areas are first-party SPA routes.
function sanitizeReturn(returnTo) {
if (
typeof returnTo === 'string' &&
/^\/(admin|account)(?:[/?]|$)/.test(returnTo) &&
!returnTo.startsWith('//')
) {
return returnTo
}
return null
}
// Public base URL used to build the OAuth redirect_uri. Prefer APP_BASE_URL;
// fall back to the request's own origin with a warning if it is unset.
function appBaseUrl(req) {
const configured = process.env.APP_BASE_URL
if (configured) return configured.replace(/\/+$/, '')
const derived = `${req.protocol}://${req.get('host')}`
log.warn('APP_BASE_URL not set — deriving redirect_uri from the request', { derived })
return derived
}
function redirectUriFor(req, providerId) {
return `${appBaseUrl(req)}/api/v1/auth/sso/${providerId}/callback`
}
// httpOnly cookie carrying the signed tx (nonce + PKCE verifier + mode). Reuse the
// app's standard cookie options (httpOnly, sameSite=lax, secure=auto) + a TTL.
function txCookieOptions(req) {
return { ...token.cookieOptions(req), maxAge: 10 * 60 * 1000 }
}
// httpOnly cookie carrying the staged pending-TOTP token for the second-factor
// step. Same standard options; TTL matches the token so a stale cookie can't
// outlive the challenge it holds.
function totpCookieOptions(req) {
return { ...token.cookieOptions(req), maxAge: 5 * 60 * 1000 }
}
// GET /auth/providers — public discovery. Never touches secrets.
async function listProviders(req, res) {
try {
return res.json(await registry.listEnabledValid())
} catch (err) {
log.error('listProviders', err)
return res.status(500).json({ message: 'Internal Server Error' })
}
}
// Shared start for both login and link. `mode` ∈ 'login' | 'link'. For link,
// requireAuth has already run so req.user is the account to attach the identity to.
async function beginFlow(req, res, mode) {
const providerId = req.params.provider
const returnTo = sanitizeReturn(req.query.returnTo)
const portal = portalFor(returnTo)
const failUrl = mode === 'link' ? accountError('error', portal) : loginError('error', portal)
try {
if (!PROVIDER_ID_RE.test(providerId)) return res.redirect(failUrl)
const row = await authProviders.getWithSecret(providerId)
if (!row || !row.enabled || !registry.validateConfig(row).valid) {
log.warn('sso start: provider unavailable', { provider: providerId, mode })
return res.redirect(
mode === 'link' ? accountError('unavailable', portal) : loginError('unavailable', portal),
)
}
const provider = registry.instantiate(row)
const tx = ssoState.createTx({
provider: providerId,
mode,
linkUserId: mode === 'link' ? req.user.id : undefined,
returnTo: returnTo || undefined,
})
res.cookie(ssoState.TX_COOKIE, tx.txToken, txCookieOptions(req))
const url = provider.getAuthorizationUrl(tx.nonce, {
redirectUri: redirectUriFor(req, providerId),
codeChallenge: tx.codeChallenge,
})
return res.redirect(url)
} catch (err) {
log.error('sso start', err)
return res.redirect(failUrl)
}
}
const start = (req, res) => beginFlow(req, res, 'login')
const linkStart = (req, res) => beginFlow(req, res, 'link')
// GET /auth/sso/:provider/callback
async function callback(req, res) {
const providerId = req.params.provider
const txToken = req.cookies && req.cookies[ssoState.TX_COOKIE]
const { code, state, error: oauthError } = req.query
// The tx cookie is single-use — clear it no matter the outcome.
res.clearCookie(ssoState.TX_COOKIE, token.cookieOptions(req))
if (oauthError) {
log.warn('sso callback: provider returned error', { provider: providerId, error: String(oauthError).slice(0, 60) })
return res.redirect(loginError('denied'))
}
const tx = ssoState.verifyTx(txToken, state)
if (!tx || tx.provider !== providerId || !code) {
log.warn('sso callback: bad state', { provider: providerId })
return res.redirect(loginError('bad_state'))
}
// tx is verified — steer failures back to the portal (and page) the flow began in.
const portal = portalFor(tx.returnTo)
const failFor = (code) => (tx.mode === 'link' ? accountError(code, portal) : loginError(code, portal))
try {
const row = await authProviders.getWithSecret(providerId)
if (!row || !row.enabled || !registry.validateConfig(row).valid) {
return res.redirect(failFor('unavailable'))
}
const provider = registry.instantiate(row)
const profile = await provider.handleCallback({
code,
redirectUri: redirectUriFor(req, providerId),
codeVerifier: tx.verifier,
})
if (tx.mode === 'link') return finishLink(req, res, providerId, tx, profile)
return finishLogin(req, res, providerId, row.kind, tx, profile)
} catch (err) {
log.error('sso callback', err)
return res.redirect(failFor('error'))
}
}
// Auto-provision a `player` from an SSO profile when no identity is linked yet
// and registration allows SSO sign-up. Derives a unique username (reserved-name
// safe) with a bounded retry against the UNIQUE index, captures the provider
// email, links the identity, and audit-logs the provision. Returns the new user,
// or null if a unique username couldn't be found.
async function provisionSsoPlayer(req, providerId, profile) {
const base = usernamePolicy.deriveUsernameBase(profile)
for (let attempt = 0; attempt < PROVISION_MAX_TRIES; attempt++) {
const candidate = usernamePolicy.candidateUsername(base, attempt)
try {
const user = await users.createUser({
username: candidate,
role: 'player',
email: profile.email || null,
// The built-in providers only return an email the IdP has verified, so
// treat a supplied address as verified (skips the eventual re-verify).
emailVerified: Boolean(profile.email),
})
await userIdentities.link({
userId: user.id,
provider: providerId,
subject: profile.subject,
email: profile.email,
})
await activity.log({ req, userId: user.id, action: 'auth.sso.provision', detail: { provider: providerId } })
log.info('sso player provisioned', { provider: providerId, id: user.id, username: user.username })
return user
} catch (err) {
// Username collided with a concurrent/existing account — try the next
// suffix. Any other error is real; propagate it.
if (users.isDuplicateUsername(err)) continue
throw err
}
}
log.error('sso provision: exhausted username candidates', { provider: providerId, base })
return null
}
// SSO login. Normally link-only: a login succeeds only if the external identity
// is already linked. The one setting-gated relaxation is auto-provisioning a
// player when player_registration ∈ {sso, both} (see provisionSsoPlayer).
async function finishLogin(req, res, providerId, kind, tx, profile) {
const portal = portalFor(tx.returnTo)
let user
const identity = await userIdentities.findByProviderSubject(providerId, profile.subject)
if (identity) {
user = await users.getById(identity.user_id)
if (!user) return res.redirect(loginError('not_linked', portal))
} else {
// Unknown identity: auto-provision only if registration opts into SSO sign-up.
const mode = await settings.getRegistrationMode()
if (mode !== 'sso' && mode !== 'both') {
log.warn('sso login refused: no linked account', { provider: providerId })
return res.redirect(loginError('not_linked', portal))
}
user = await provisionSsoPlayer(req, providerId, profile)
if (!user) return res.redirect(loginError('error', portal))
}
// Status gate (parity with local login): a disabled/banned account can't
// complete SSO login either.
if (user.status && user.status !== 'active') {
log.warn('sso login refused: inactive account', { provider: providerId, id: user.id, status: user.status })
return res.redirect(loginError('disabled', portal))
}
const authMethod = sessionService.AUTH_METHODS.includes(kind) ? kind : 'sso'
// 2FA parity with the local login (auth.controller): if the account has TOTP
// enabled, an SSO sign-in must NOT bypass the second factor. Stage a signed,
// httpOnly challenge and route the browser through the TOTP form instead of
// minting a session here. See issue #31.
if (needsTotp(user)) {
const pending = ssoState.createTotpPending({
userId: user.id,
provider: providerId,
authMethod,
returnTo: sanitizeReturn(tx.returnTo) || undefined,
})
res.cookie(ssoState.TOTP_COOKIE, pending, totpCookieOptions(req))
log.info('sso login: awaiting TOTP', { provider: providerId, id: user.id, ip: req.ip })
return res.redirect(`${loginPath(portal)}?sso_totp=1`)
}
const { token: sessionToken } = sessionService.createSession(user, authMethod)
token.setAuthCookie(req, res, sessionToken)
await users.recordLogin(user.id, req.ip)
await activity.log({ req, userId: user.id, action: 'auth.sso.login', detail: { provider: providerId } })
log.info('sso login success', { provider: providerId, id: user.id, ip: req.ip })
return res.redirect(sanitizeReturn(tx.returnTo) || homePath(portal))
}
// POST /auth/sso/totp — second factor for an SSO login whose account has TOTP on.
// Reads the staged pending-TOTP cookie, verifies the authenticator code, then
// mints the full session. Mirrors auth.controller.loginTotp: a wrong code is a
// failed attempt (backoff + bot score), and the response is JSON (the login page
// completes this step over fetch and then navigates to returnTo).
async function finishSsoTotp(req, res) {
const pending = ssoState.verifyTotpPending(req.cookies && req.cookies[ssoState.TOTP_COOKIE])
if (!pending) {
return res.status(401).json({ message: 'Your verification session expired. Please sign in again.' })
}
try {
const user = await users.getRawById(pending.id)
if (!user || !user.totp_enabled || !totp.verifyCode(user.totp_secret, req.body.code)) {
botScore.recordLoginFailure(req.ip)
loginProtection.recordFailure(req.ip)
log.warn('sso TOTP verify failed', { id: pending.id, ip: req.ip })
return res.status(401).json({ message: 'Invalid verification code.' })
}
// Correct second factor, but the account is disabled/banned since the flow
// started — refuse and clear the staged cookie.
if (user.status && user.status !== 'active') {
res.clearCookie(ssoState.TOTP_COOKIE, token.cookieOptions(req))
log.warn('sso TOTP refused: inactive account', { id: user.id, status: user.status })
return res.status(403).json({ message: 'This account is not active. Contact an administrator.' })
}
// Second factor satisfied — clear the staged cookie and issue the real session.
res.clearCookie(ssoState.TOTP_COOKIE, token.cookieOptions(req))
loginProtection.recordSuccess(req.ip)
const authMethod = sessionService.AUTH_METHODS.includes(pending.authMethod) ? pending.authMethod : 'sso'
const { token: sessionToken } = sessionService.createSession(user, authMethod)
token.setAuthCookie(req, res, sessionToken)
await users.recordLogin(user.id, req.ip)
await activity.log({ req, userId: user.id, action: 'auth.sso.login', detail: { provider: pending.provider, totp: true } })
log.info('sso login success (2fa)', { provider: pending.provider, id: user.id, ip: req.ip })
return res.json({
user: { id: user.id, username: user.username, role: user.role },
returnTo: sanitizeReturn(pending.returnTo) || homePath(portalFor(pending.returnTo)),
})
} catch (err) {
log.error('sso totp error', err)
return res.status(500).json({ message: 'Internal Server Error' })
}
}
// Attach the external identity to the account that initiated linking (tx.linkUserId
// was captured behind requireAuth at /link start, so the signed tx authorizes it).
async function finishLink(req, res, providerId, tx, profile) {
const portal = portalFor(tx.returnTo)
const userId = tx.linkUserId
if (!userId) return res.redirect(loginError('error', portal))
const existing = await userIdentities.findByProviderSubject(providerId, profile.subject)
if (existing && existing.user_id !== userId) {
return res.redirect(accountError('in_use', portal)) // external identity belongs to another account
}
if (!existing) {
await userIdentities.link({ userId, provider: providerId, subject: profile.subject, email: profile.email })
await activity.log({ req, userId, action: 'auth.sso.link', detail: { provider: providerId } })
log.info('sso account linked', { provider: providerId, userId })
}
return res.redirect(`${accountPath(portal)}?linked=${providerId}`)
}
module.exports = { listProviders, start, linkStart, callback, beginFlow, finishLogin, finishSsoTotp, finishLink }