Add session abstraction, mobile bearer auth, and pluggable SSO

Refactor authentication into a provider-agnostic session layer and build
two new auth surfaces on top of it, without changing local password/TOTP
behavior. Every flow now issues sessions through
sessionService.createSession(user, authMethod).

Part 1 — Session abstraction (backward-compatible refactor):
- New server/src/auth/: token.js (JWT/cookie primitives), session.service.js
  (create/validate/partial-TOTP/revoke), session.middleware.js
  (attachSession/requireAuth/requireRole). utils/auth.js is now a thin
  compat facade so existing imports are unchanged.

Part 2 — Mobile bearer auth (additive):
- /api/v1/auth/mobile/{login,refresh,logout}: short-lived access JWT +
  long-lived refresh token, stored hashed and rotated on use, in a new
  mobile_refresh_tokens table. Reuses web bot-scoring/backoff; single-request
  TOTP. token.signToken gains a backward-compatible expiresIn option.

Part 3 — Pluggable SSO (Google, Discord, generic OIDC):
- OAuth2Provider base + built-in Google/Discord (fixed endpoints) + generic
  OIDC, a registry with health/validation, PKCE+CSRF transaction state, and
  discovery (GET /auth/providers), start/link/callback routes.
- Link-only policy: SSO signs in only to an already-linked account; external
  identities are never auto-provisioned. Client secrets encrypted at rest
  (AES-256-GCM, utils/secretBox.js). Admin CRUD (/admin/auth/providers) and
  account linking (/admin/account/identities). New auth_providers +
  user_identities tables.

Frontend:
- Login page renders provider buttons from /auth/providers (inline SVG icons,
  graceful with zero providers). New Authentication admin view
  (Local/Google/Discord/Custom). Account page linked-accounts section.

Tests: 83 passing (session, mobile, providers, registry, secretBox, ssoState,
ssoCallback) — all DB-free via fetch mocks + model stubs. README + .env.example
updated.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-03 10:31:29 -05:00
parent 8fa34ca68e
commit 31b31c3a17
46 changed files with 3169 additions and 177 deletions

View File

@@ -0,0 +1,65 @@
// ── Session middleware ─────────────────────────────────────────────────────
//
// Express middleware built on the session service. Three pieces:
//
// attachSession — best-effort: decorate the request with session info if a
// valid token is present, but never reject. For routes that
// behave differently for anon vs authed callers.
// requireAuth — the gate for protected routes. Preserves the exact behavior
// of the old isLoggedIn: re-validate the user against the DB on
// every request so a demoted/deleted user loses access
// immediately, and set req.user to the fresh DB row.
// requireRole — role gate factory, unchanged from the original.
const sessionService = require('./session.service')
const users = require('../model/users/users.model')
const log = require('../utils/logger')('session')
// Best-effort: if the request carries a valid session token, attach the decoded
// session (no DB hit), its auth method, and request metadata. Never rejects —
// anonymous requests simply pass through with req.session undefined.
function attachSession(req, res, next) {
const session = sessionService.validateSession(req)
if (session) {
req.session = session
req.authMethod = session.authMethod
req.sessionMeta = sessionService.sessionMeta(req)
}
return next()
}
// Gate middleware for protected (admin) routes. Re-validates the token against
// the database on every request so a demoted or deleted user loses access
// immediately, instead of keeping their old role (or a working session) until
// the JWT expires. req.user carries the fresh DB row, not the token payload.
async function requireAuth(req, res, next) {
const session = sessionService.validateSession(req)
if (!session) return res.status(401).json({ message: 'Unauthorized' })
try {
const user = await users.getById(session.userId)
if (!user) return res.status(401).json({ message: 'Unauthorized' }) // deleted since token issued
req.user = user
req.session = session
req.authMethod = session.authMethod
return next()
} catch (err) {
log.error('requireAuth', err)
return res.status(500).json({ message: 'Internal Server Error' })
}
}
// Gate middleware factory: allow only the listed roles. Assumes requireAuth ran
// first so req.user is populated. Use for admin-only endpoints (users, site
// mode, settings) so a lower-privilege editor cannot reach them.
function requireRole(...roles) {
return (req, res, next) => {
if (roles.includes(req.user?.role)) return next()
return res.status(403).json({ message: 'Forbidden' })
}
}
module.exports = {
attachSession,
requireAuth,
requireRole,
}