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:
@@ -1,150 +1,36 @@
|
||||
const jwt = require('jsonwebtoken')
|
||||
require('dotenv').config()
|
||||
// ── Auth compatibility facade ──────────────────────────────────────────────
|
||||
//
|
||||
// The auth logic now lives in server/src/auth/ (token primitives, the session
|
||||
// service, and session middleware). This module stays as a thin facade so every
|
||||
// existing import site (auth.routes, admin.routes, siteMode, auth.controller)
|
||||
// keeps working with the exact same names and behavior — nothing else in the
|
||||
// codebase needs to change. New code should prefer requiring ../auth/* directly.
|
||||
|
||||
const log = require('./logger')('auth')
|
||||
const users = require('../model/users/users.model')
|
||||
const token = require('../auth/token')
|
||||
const sessionService = require('../auth/session.service')
|
||||
const { requireAuth, requireRole } = require('../auth/session.middleware')
|
||||
|
||||
const JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN || '1d'
|
||||
const COOKIE_NAME = process.env.COOKIE_NAME || 'uomm_token'
|
||||
// Lifetime of the short-lived "password verified, awaiting TOTP" token.
|
||||
const TOTP_CHALLENGE_TTL = process.env.TOTP_CHALLENGE_TTL || '5m'
|
||||
|
||||
// Resolve the signing secret. Without one, jwt.sign/verify can't produce or
|
||||
// validate a usable token, so every login is silently broken. Fail fast in
|
||||
// production rather than booting into that state; in dev fall back to a known
|
||||
// insecure secret so login still works locally (with a loud warning).
|
||||
function resolveJwtSecret() {
|
||||
const secret = process.env.JWT_SECRET
|
||||
if (secret) return secret
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
throw new Error('JWT_SECRET must be set in production')
|
||||
}
|
||||
log.warn('JWT_SECRET is not set — using an insecure development fallback. Set JWT_SECRET in .env before deploying.')
|
||||
return 'dev-insecure-jwt-secret-do-not-use-in-production'
|
||||
}
|
||||
|
||||
const JWT_SECRET = resolveJwtSecret()
|
||||
|
||||
function signToken(user) {
|
||||
const payload = { id: user.id, username: user.username, role: user.role }
|
||||
return jwt.sign(payload, JWT_SECRET, { expiresIn: JWT_EXPIRES_IN })
|
||||
}
|
||||
|
||||
function verifyToken(token) {
|
||||
try {
|
||||
return jwt.verify(token, JWT_SECRET)
|
||||
} catch (err) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// Short-lived token issued after the password step for users with TOTP enabled.
|
||||
// It is NOT a session: it carries stage:'totp' so getUserFromRequest rejects it,
|
||||
// and it is only accepted by verifyTotpChallenge to gate the second factor.
|
||||
function signTotpChallenge(user) {
|
||||
return jwt.sign({ id: user.id, stage: 'totp' }, JWT_SECRET, { expiresIn: TOTP_CHALLENGE_TTL })
|
||||
}
|
||||
|
||||
function verifyTotpChallenge(token) {
|
||||
const decoded = verifyToken(token)
|
||||
if (!decoded || decoded.stage !== 'totp') return null
|
||||
return decoded
|
||||
}
|
||||
|
||||
// Rough max-age (ms) for the cookie, parsed from JWT_EXPIRES_IN (e.g. 1d, 12h, 30m).
|
||||
function cookieMaxAge() {
|
||||
const m = /^(\d+)([dhms])$/.exec(String(JWT_EXPIRES_IN).trim())
|
||||
if (!m) return 24 * 60 * 60 * 1000
|
||||
const n = Number(m[1])
|
||||
const unit = { d: 86400000, h: 3600000, m: 60000, s: 1000 }[m[2]]
|
||||
return n * unit
|
||||
}
|
||||
|
||||
/**
|
||||
* Decide the cookie Secure flag. COOKIE_SECURE=auto (default) uses req.secure,
|
||||
* which is true behind Pangolin (HTTPS, X-Forwarded-Proto) and false over plain
|
||||
* HTTP on the LAN IP — so login works in both. Requires app.set('trust proxy').
|
||||
*/
|
||||
function cookieSecure(req) {
|
||||
const mode = (process.env.COOKIE_SECURE || 'auto').toLowerCase()
|
||||
if (mode === 'true') return true
|
||||
if (mode === 'false') return false
|
||||
return Boolean(req.secure)
|
||||
}
|
||||
|
||||
function cookieOptions(req) {
|
||||
return {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
secure: cookieSecure(req),
|
||||
path: '/',
|
||||
}
|
||||
}
|
||||
|
||||
function setAuthCookie(req, res, token) {
|
||||
res.cookie(COOKIE_NAME, token, { ...cookieOptions(req), maxAge: cookieMaxAge() })
|
||||
}
|
||||
|
||||
function clearAuthCookie(req, res) {
|
||||
res.clearCookie(COOKIE_NAME, cookieOptions(req))
|
||||
}
|
||||
|
||||
// Extract a token from the cookie or an Authorization: Bearer header.
|
||||
function extractToken(req) {
|
||||
if (req.cookies && req.cookies[COOKIE_NAME]) return req.cookies[COOKIE_NAME]
|
||||
const header = req.headers.authorization
|
||||
if (header && header.startsWith('Bearer ')) return header.substring(7)
|
||||
return null
|
||||
}
|
||||
|
||||
// Returns the decoded user or null without rejecting the request. Stage-tagged
|
||||
// tokens (e.g. the TOTP challenge) are explicitly NOT sessions, so an attacker
|
||||
// can't present a half-authenticated challenge token as a full login.
|
||||
// Non-rejecting identity check. Returns the decoded token payload (with `.id`)
|
||||
// or null — same shape callers relied on (siteMode only truthiness-checks it).
|
||||
// Backed by the session service so there is a single validation path.
|
||||
function getUserFromRequest(req) {
|
||||
const token = extractToken(req)
|
||||
if (!token) return null
|
||||
const decoded = verifyToken(token)
|
||||
if (!decoded || decoded.stage) return null
|
||||
return decoded
|
||||
}
|
||||
|
||||
// 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 isLoggedIn(req, res, next) {
|
||||
const decoded = getUserFromRequest(req)
|
||||
if (!decoded) return res.status(401).json({ message: 'Unauthorized' })
|
||||
try {
|
||||
const user = await users.getById(decoded.id)
|
||||
if (!user) return res.status(401).json({ message: 'Unauthorized' }) // deleted since token issued
|
||||
req.user = user
|
||||
return next()
|
||||
} catch (err) {
|
||||
log.error('isLoggedIn', err)
|
||||
return res.status(500).json({ message: 'Internal Server Error' })
|
||||
}
|
||||
}
|
||||
|
||||
// Gate middleware factory: allow only the listed roles. Assumes isLoggedIn 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' })
|
||||
}
|
||||
const session = sessionService.validateSession(req)
|
||||
if (!session) return null
|
||||
// Preserve the historical payload shape (id/username/role) for callers.
|
||||
return { id: session.userId, username: session.username, role: session.role }
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
COOKIE_NAME,
|
||||
signToken,
|
||||
verifyToken,
|
||||
signTotpChallenge,
|
||||
verifyTotpChallenge,
|
||||
setAuthCookie,
|
||||
clearAuthCookie,
|
||||
COOKIE_NAME: token.COOKIE_NAME,
|
||||
// Token primitives (re-exported from auth/token.js).
|
||||
signToken: token.signToken,
|
||||
verifyToken: token.verifyToken,
|
||||
signTotpChallenge: token.signTotpChallenge,
|
||||
verifyTotpChallenge: token.verifyTotpChallenge,
|
||||
setAuthCookie: token.setAuthCookie,
|
||||
clearAuthCookie: token.clearAuthCookie,
|
||||
// Request helpers / middleware.
|
||||
getUserFromRequest,
|
||||
isLoggedIn,
|
||||
isLoggedIn: requireAuth, // old name → new middleware, identical behavior
|
||||
requireRole,
|
||||
}
|
||||
|
||||
55
server/src/utils/secretBox.js
Normal file
55
server/src/utils/secretBox.js
Normal file
@@ -0,0 +1,55 @@
|
||||
// ── Secret-at-rest encryption (AES-256-GCM) ────────────────────────────────
|
||||
//
|
||||
// Used to encrypt OAuth client secrets before they are written to the DB, so a
|
||||
// database read alone does not yield usable provider credentials. Output format
|
||||
// is `iv:tag:ciphertext`, each part base64. GCM provides authenticated
|
||||
// encryption, so tampering is detected on decrypt.
|
||||
//
|
||||
// The key comes from SECRET_ENC_KEY (any string — it is hashed to 32 bytes). In
|
||||
// development, if unset, we derive a key from JWT_SECRET with a loud warning
|
||||
// (mirrors token.resolveJwtSecret) so local dev works; production must set a
|
||||
// dedicated key so rotating JWT_SECRET does not silently orphan stored secrets.
|
||||
|
||||
const crypto = require('crypto')
|
||||
require('dotenv').config()
|
||||
|
||||
const log = require('../utils/logger')('secretbox')
|
||||
|
||||
const ALGO = 'aes-256-gcm'
|
||||
|
||||
function resolveKey() {
|
||||
const explicit = process.env.SECRET_ENC_KEY
|
||||
if (explicit) return crypto.createHash('sha256').update(explicit).digest()
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
throw new Error('SECRET_ENC_KEY must be set in production')
|
||||
}
|
||||
const jwt = process.env.JWT_SECRET || 'dev-insecure-jwt-secret-do-not-use-in-production'
|
||||
log.warn('SECRET_ENC_KEY is not set — deriving an insecure key from JWT_SECRET for development. Set SECRET_ENC_KEY before deploying.')
|
||||
return crypto.createHash('sha256').update(`secretbox:${jwt}`).digest()
|
||||
}
|
||||
|
||||
const KEY = resolveKey()
|
||||
|
||||
// Encrypt a UTF-8 string → "iv:tag:ct" (base64 parts). Returns null for empty input.
|
||||
function encrypt(plaintext) {
|
||||
if (plaintext == null || plaintext === '') return null
|
||||
const iv = crypto.randomBytes(12)
|
||||
const cipher = crypto.createCipheriv(ALGO, KEY, iv)
|
||||
const ct = Buffer.concat([cipher.update(String(plaintext), 'utf8'), cipher.final()])
|
||||
const tag = cipher.getAuthTag()
|
||||
return `${iv.toString('base64')}:${tag.toString('base64')}:${ct.toString('base64')}`
|
||||
}
|
||||
|
||||
// Decrypt a value produced by encrypt(). Returns null for null/blank input;
|
||||
// throws if the payload is malformed or fails authentication (tampered/wrong key).
|
||||
function decrypt(payload) {
|
||||
if (payload == null || payload === '') return null
|
||||
const parts = String(payload).split(':')
|
||||
if (parts.length !== 3) throw new Error('secretBox: malformed ciphertext')
|
||||
const [iv, tag, ct] = parts.map((p) => Buffer.from(p, 'base64'))
|
||||
const decipher = crypto.createDecipheriv(ALGO, KEY, iv)
|
||||
decipher.setAuthTag(tag)
|
||||
return Buffer.concat([decipher.update(ct), decipher.final()]).toString('utf8')
|
||||
}
|
||||
|
||||
module.exports = { encrypt, decrypt }
|
||||
Reference in New Issue
Block a user