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:
@@ -4,6 +4,7 @@
|
||||
|
||||
const users = require('../../../model/users/users.model')
|
||||
const activity = require('../../../model/activity/activity.model')
|
||||
const userIdentities = require('../../../model/userIdentities/userIdentities.model')
|
||||
const totp = require('../../../utils/totp')
|
||||
|
||||
const log = require('../../../utils/logger')('account')
|
||||
@@ -81,4 +82,32 @@ async function totpDisable(req, res) {
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { getAccount, totpSetup, totpEnable, totpDisable }
|
||||
// ── Linked SSO identities (self-service) ──────────────────────────────────
|
||||
// List the external accounts (Google/Discord/…) linked to the current user.
|
||||
// Linking itself happens via the SSO redirect flow (/auth/sso/:provider/link).
|
||||
async function listIdentities(req, res) {
|
||||
try {
|
||||
const rows = await userIdentities.listForUser(req.user.id)
|
||||
return res.json(rows.map((r) => ({ provider: r.provider, email: r.email, linked_at: r.created_at })))
|
||||
} catch (err) {
|
||||
log.error('listIdentities', err)
|
||||
return res.status(500).json({ message: 'Internal Server Error' })
|
||||
}
|
||||
}
|
||||
|
||||
// Remove a linked SSO identity from the current user's account.
|
||||
async function unlinkIdentity(req, res) {
|
||||
const { provider } = req.params
|
||||
try {
|
||||
const removed = await userIdentities.unlink(req.user.id, provider)
|
||||
if (!removed) return res.status(404).json({ message: 'No linked account for that provider.' })
|
||||
await activity.log({ req, action: 'auth.sso.unlink', detail: { provider } })
|
||||
log.info('sso identity unlinked', { provider, id: req.user.id })
|
||||
return res.json({ unlinked: true })
|
||||
} catch (err) {
|
||||
log.error('unlinkIdentity', err)
|
||||
return res.status(500).json({ message: 'Internal Server Error' })
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { getAccount, totpSetup, totpEnable, totpDisable, listIdentities, unlinkIdentity }
|
||||
|
||||
@@ -8,6 +8,7 @@ const { body, param } = require('express-validator')
|
||||
const ctrl = require('./admin.controller')
|
||||
const account = require('./account.controller')
|
||||
const botActivity = require('./botActivity.controller')
|
||||
const authProviders = require('./authProviders.controller')
|
||||
const { isLoggedIn, requireRole } = require('../../../utils/auth')
|
||||
const noindex = require('../../../middleware/noindex')
|
||||
const validate = require('../../../middleware/validate')
|
||||
@@ -38,6 +39,15 @@ adminRouter.post(
|
||||
account.totpDisable,
|
||||
)
|
||||
|
||||
// Linked SSO identities (self-service — any logged-in role manages their own).
|
||||
adminRouter.get('/account/identities', account.listIdentities)
|
||||
adminRouter.delete(
|
||||
'/account/identities/:provider',
|
||||
param('provider').matches(/^[a-z0-9-]+$/),
|
||||
validate,
|
||||
account.unlinkIdentity,
|
||||
)
|
||||
|
||||
// ── Image uploads (screenshots/gallery) ───────────────────────────────
|
||||
const UPLOAD_DIR =
|
||||
process.env.UPLOAD_DIR || path.join(__dirname, '..', '..', '..', '..', 'uploads')
|
||||
@@ -191,6 +201,49 @@ adminRouter.post(
|
||||
botActivity.unbanIp,
|
||||
)
|
||||
|
||||
// ── Authentication providers / SSO (admin only) ───────────────────────
|
||||
adminRouter.get('/auth/providers', adminOnly, authProviders.list)
|
||||
adminRouter.post(
|
||||
'/auth/providers',
|
||||
adminOnly,
|
||||
body('id').matches(/^[a-z0-9-]+$/),
|
||||
body('kind').isIn(['oidc', 'oauth2']),
|
||||
body('name').isString().trim().notEmpty().isLength({ max: 80 }),
|
||||
body('enabled').optional().isBoolean(),
|
||||
body('clientId').optional({ values: 'falsy' }).isString(),
|
||||
body('secret').optional({ values: 'falsy' }).isString(),
|
||||
body('authorizeUrl').optional({ values: 'falsy' }).isURL({ require_tld: false }),
|
||||
body('tokenUrl').optional({ values: 'falsy' }).isURL({ require_tld: false }),
|
||||
body('userinfoUrl').optional({ values: 'falsy' }).isURL({ require_tld: false }),
|
||||
body('scopes').optional({ values: 'falsy' }).isString().isLength({ max: 500 }),
|
||||
body('priority').optional().isInt(),
|
||||
validate,
|
||||
authProviders.create,
|
||||
)
|
||||
adminRouter.put(
|
||||
'/auth/providers/:id',
|
||||
adminOnly,
|
||||
param('id').matches(/^[a-z0-9-]+$/),
|
||||
body('name').optional().isString().trim().notEmpty().isLength({ max: 80 }),
|
||||
body('enabled').optional().isBoolean(),
|
||||
body('clientId').optional({ values: 'falsy' }).isString(),
|
||||
body('secret').optional({ values: 'falsy' }).isString(),
|
||||
body('authorizeUrl').optional({ values: 'falsy' }).isURL({ require_tld: false }),
|
||||
body('tokenUrl').optional({ values: 'falsy' }).isURL({ require_tld: false }),
|
||||
body('userinfoUrl').optional({ values: 'falsy' }).isURL({ require_tld: false }),
|
||||
body('scopes').optional({ values: 'falsy' }).isString().isLength({ max: 500 }),
|
||||
body('priority').optional().isInt(),
|
||||
validate,
|
||||
authProviders.update,
|
||||
)
|
||||
adminRouter.delete(
|
||||
'/auth/providers/:id',
|
||||
adminOnly,
|
||||
param('id').matches(/^[a-z0-9-]+$/),
|
||||
validate,
|
||||
authProviders.remove,
|
||||
)
|
||||
|
||||
// ── User management (admin only) ──────────────────────────────────────
|
||||
adminRouter.use('/users', adminOnly)
|
||||
adminRouter.get('/users', ctrl.listUsers)
|
||||
|
||||
121
server/src/router/v1/admin/authProviders.controller.js
Normal file
121
server/src/router/v1/admin/authProviders.controller.js
Normal file
@@ -0,0 +1,121 @@
|
||||
// ── Admin: auth provider configuration ─────────────────────────────────────
|
||||
//
|
||||
// CRUD for SSO providers. Built-ins (google, discord) are configured here too but
|
||||
// can only be enabled/disabled and given a client id/secret — their kind, name,
|
||||
// and endpoints are fixed in code and cannot be edited or deleted. Custom
|
||||
// (oidc/oauth2) providers are fully editable.
|
||||
//
|
||||
// SECURITY: the client secret is write-only over this API. It is stored encrypted
|
||||
// and NEVER returned — responses expose only `hasSecret`. A blank `secret` on
|
||||
// update means "leave the existing secret unchanged".
|
||||
|
||||
const authProviders = require('../../../model/authProviders/authProviders.model')
|
||||
const registry = require('../../../auth/providers/registry')
|
||||
const activity = require('../../../model/activity/activity.model')
|
||||
|
||||
const log = require('../../../utils/logger')('admin')
|
||||
|
||||
// Shape a provider row for the admin UI — no secret material, ever.
|
||||
function toSafe(p) {
|
||||
return {
|
||||
id: p.id,
|
||||
kind: p.kind,
|
||||
name: p.name,
|
||||
enabled: Boolean(p.enabled),
|
||||
clientId: p.client_id || '',
|
||||
hasSecret: Boolean(p.client_secret_enc),
|
||||
authorizeUrl: p.authorize_url || '',
|
||||
tokenUrl: p.token_url || '',
|
||||
userinfoUrl: p.userinfo_url || '',
|
||||
scopes: p.scopes || '',
|
||||
priority: p.priority ?? 100,
|
||||
builtin: registry.isBuiltin(p.id),
|
||||
health: p.health || registry.validateConfig(p),
|
||||
}
|
||||
}
|
||||
|
||||
// GET /admin/auth/providers — all providers (built-ins always present) + health.
|
||||
async function list(req, res) {
|
||||
try {
|
||||
const rows = await registry.listConfigured()
|
||||
return res.json(rows.map(toSafe))
|
||||
} catch (err) {
|
||||
log.error('authProviders.list', err)
|
||||
return res.status(500).json({ message: 'Internal Server Error' })
|
||||
}
|
||||
}
|
||||
|
||||
// POST /admin/auth/providers — create a custom (oidc/oauth2) provider.
|
||||
async function create(req, res) {
|
||||
const { id, kind, name, enabled, clientId, secret, authorizeUrl, tokenUrl, userinfoUrl, scopes, priority } = req.body
|
||||
try {
|
||||
if (registry.isBuiltin(id)) {
|
||||
return res.status(400).json({ message: 'Built-in provider — configure it via PUT, not create.' })
|
||||
}
|
||||
if (!['oidc', 'oauth2'].includes(kind)) {
|
||||
return res.status(400).json({ message: 'Custom providers must be of kind oidc or oauth2.' })
|
||||
}
|
||||
if (await authProviders.get(id)) {
|
||||
return res.status(409).json({ message: 'A provider with that id already exists.' })
|
||||
}
|
||||
const saved = await authProviders.save(id, {
|
||||
kind, name, enabled, clientId, secret, authorizeUrl, tokenUrl, userinfoUrl, scopes, priority,
|
||||
})
|
||||
await activity.log({ req, action: 'auth.provider.create', detail: { id } })
|
||||
log.info('auth provider created', { id, kind, by: req.user.username })
|
||||
return res.status(201).json(toSafe(saved))
|
||||
} catch (err) {
|
||||
log.error('authProviders.create', err)
|
||||
return res.status(500).json({ message: 'Internal Server Error' })
|
||||
}
|
||||
}
|
||||
|
||||
// PUT /admin/auth/providers/:id — update a built-in or custom provider.
|
||||
async function update(req, res) {
|
||||
const { id } = req.params
|
||||
const b = req.body
|
||||
try {
|
||||
let fields
|
||||
if (registry.isBuiltin(id)) {
|
||||
// Built-ins: kind/name/priority are fixed; only enable + credentials change.
|
||||
const meta = registry.BUILTINS.find((x) => x.id === id)
|
||||
fields = { kind: meta.kind, name: meta.name, priority: meta.priority, enabled: b.enabled, clientId: b.clientId, secret: b.secret }
|
||||
} else {
|
||||
if (!(await authProviders.get(id))) {
|
||||
return res.status(404).json({ message: 'Provider not found.' })
|
||||
}
|
||||
fields = {
|
||||
name: b.name, enabled: b.enabled, clientId: b.clientId, secret: b.secret,
|
||||
authorizeUrl: b.authorizeUrl, tokenUrl: b.tokenUrl, userinfoUrl: b.userinfoUrl,
|
||||
scopes: b.scopes, priority: b.priority,
|
||||
}
|
||||
}
|
||||
const saved = await authProviders.save(id, fields)
|
||||
await activity.log({ req, action: 'auth.provider.update', detail: { id } })
|
||||
log.info('auth provider updated', { id, by: req.user.username })
|
||||
return res.json(toSafe(saved))
|
||||
} catch (err) {
|
||||
log.error('authProviders.update', err)
|
||||
return res.status(500).json({ message: 'Internal Server Error' })
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE /admin/auth/providers/:id — custom providers only.
|
||||
async function remove(req, res) {
|
||||
const { id } = req.params
|
||||
try {
|
||||
if (registry.isBuiltin(id)) {
|
||||
return res.status(400).json({ message: 'Built-in providers cannot be deleted — disable them instead.' })
|
||||
}
|
||||
const n = await authProviders.remove(id)
|
||||
if (!n) return res.status(404).json({ message: 'Provider not found.' })
|
||||
await activity.log({ req, action: 'auth.provider.delete', detail: { id } })
|
||||
log.info('auth provider deleted', { id, by: req.user.username })
|
||||
return res.json({ deleted: true })
|
||||
} catch (err) {
|
||||
log.error('authProviders.remove', err)
|
||||
return res.status(500).json({ message: 'Internal Server Error' })
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { list, create, update, remove, toSafe }
|
||||
Reference in New Issue
Block a user