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>
270 lines
11 KiB
JavaScript
270 lines
11 KiB
JavaScript
const express = require('express')
|
|
const path = require('path')
|
|
const fs = require('fs')
|
|
const crypto = require('crypto')
|
|
const multer = require('multer')
|
|
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')
|
|
|
|
const adminRouter = express.Router()
|
|
|
|
// Every admin route requires auth and is kept out of search indexes.
|
|
adminRouter.use(noindex, isLoggedIn)
|
|
|
|
// Admin-only gate. Editors may manage content (posts/wiki), but user
|
|
// management, site mode, and settings are restricted to the admin role.
|
|
const adminOnly = requireRole('admin')
|
|
|
|
// ── Account security (self-service, any logged-in role) ───────────────
|
|
// Not behind adminOnly: an editor manages their own 2FA too.
|
|
adminRouter.get('/account', account.getAccount)
|
|
adminRouter.post('/account/totp/setup', account.totpSetup)
|
|
adminRouter.post(
|
|
'/account/totp/enable',
|
|
body('code').isString().trim().isLength({ min: 6, max: 8 }),
|
|
validate,
|
|
account.totpEnable,
|
|
)
|
|
adminRouter.post(
|
|
'/account/totp/disable',
|
|
body('code').isString().trim().isLength({ min: 6, max: 8 }),
|
|
validate,
|
|
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')
|
|
fs.mkdirSync(UPLOAD_DIR, { recursive: true })
|
|
|
|
// Whitelisted image mimetypes → the extension we store the file under. The
|
|
// stored extension is derived from this map (keyed by the accepted mimetype),
|
|
// never from originalname — so a spoofed `Content-Type: image/png` paired with
|
|
// `originalname: x.html` can never land an executable .html file in /uploads.
|
|
const MIME_EXT = {
|
|
'image/png': '.png',
|
|
'image/jpeg': '.jpg',
|
|
'image/gif': '.gif',
|
|
'image/webp': '.webp',
|
|
'image/avif': '.avif',
|
|
}
|
|
|
|
const storage = multer.diskStorage({
|
|
destination: (req, file, cb) => cb(null, UPLOAD_DIR),
|
|
filename: (req, file, cb) => {
|
|
const ext = MIME_EXT[file.mimetype] || ''
|
|
cb(null, `${Date.now()}-${crypto.randomBytes(8).toString('hex')}${ext}`)
|
|
},
|
|
})
|
|
const upload = multer({
|
|
storage,
|
|
limits: { fileSize: 8 * 1024 * 1024 },
|
|
fileFilter: (req, file, cb) => {
|
|
// Single source of truth: only mimetypes we can map to a safe extension pass.
|
|
if (MIME_EXT[file.mimetype]) cb(null, true)
|
|
else cb(new Error('Only image uploads are allowed'))
|
|
},
|
|
})
|
|
|
|
// ── Dashboard & site mode ─────────────────────────────────────────────
|
|
adminRouter.get('/dashboard', ctrl.dashboard)
|
|
adminRouter.put(
|
|
'/site-mode',
|
|
adminOnly,
|
|
body('mode').isIn(['live', 'maintenance']),
|
|
validate,
|
|
ctrl.setSiteMode,
|
|
)
|
|
|
|
// ── Posts (news / five-on-friday / newsletter / screenshots) ──────────
|
|
adminRouter.get('/posts', ctrl.listPosts)
|
|
adminRouter.post(
|
|
'/posts',
|
|
body('category').isString().notEmpty(),
|
|
body('title').isString().trim().notEmpty().isLength({ max: 200 }),
|
|
validate,
|
|
ctrl.createPost,
|
|
)
|
|
adminRouter.post('/posts/upload', upload.single('image'), ctrl.uploadImage)
|
|
// Generalized upload (rich-text editors). Same multer middleware; returns { url }.
|
|
adminRouter.post('/uploads', upload.single('image'), ctrl.uploadFile)
|
|
adminRouter.get('/posts/:id', param('id').isInt(), validate, ctrl.getPost)
|
|
adminRouter.put('/posts/:id', param('id').isInt(), validate, ctrl.updatePost)
|
|
adminRouter.patch(
|
|
'/posts/:id/publish',
|
|
param('id').isInt(),
|
|
body('published').isBoolean(),
|
|
validate,
|
|
ctrl.publishPost,
|
|
)
|
|
adminRouter.delete('/posts/:id', param('id').isInt(), validate, ctrl.deletePost)
|
|
|
|
// ── Wiki categories (static paths registered before /wiki/:slug) ───────
|
|
adminRouter.get('/wiki/categories', ctrl.listWikiCategories)
|
|
adminRouter.post(
|
|
'/wiki/categories',
|
|
body('slug').matches(/^[a-z0-9-]+$/),
|
|
body('title').isString().trim().notEmpty().isLength({ max: 200 }),
|
|
body('description').optional({ values: 'falsy' }).isString().isLength({ max: 400 }),
|
|
body('sort_order').optional().isInt(),
|
|
validate,
|
|
ctrl.createWikiCategory,
|
|
)
|
|
adminRouter.put(
|
|
'/wiki/categories/:id',
|
|
param('id').isInt(),
|
|
body('slug').optional().matches(/^[a-z0-9-]+$/),
|
|
body('title').optional().isString().trim().notEmpty().isLength({ max: 200 }),
|
|
body('description').optional({ values: 'falsy' }).isString().isLength({ max: 400 }),
|
|
body('sort_order').optional().isInt(),
|
|
validate,
|
|
ctrl.updateWikiCategory,
|
|
)
|
|
adminRouter.delete('/wiki/categories/:id', param('id').isInt(), validate, ctrl.deleteWikiCategory)
|
|
|
|
// ── Wiki tags ──────────────────────────────────────────────────────────
|
|
adminRouter.get('/wiki/tags', ctrl.listWikiTags)
|
|
|
|
// ── Wiki pages ─────────────────────────────────────────────────────────
|
|
adminRouter.get('/wiki', ctrl.listWiki)
|
|
adminRouter.post(
|
|
'/wiki',
|
|
body('slug').matches(/^[a-z0-9-]+$/),
|
|
body('title').isString().trim().notEmpty().isLength({ max: 200 }),
|
|
body('excerpt').optional({ values: 'falsy' }).isString().isLength({ max: 400 }),
|
|
body('category_id').optional({ values: 'null' }).isInt(),
|
|
body('published').optional().isBoolean(),
|
|
body('tags').optional().isArray(),
|
|
validate,
|
|
ctrl.createWiki,
|
|
)
|
|
adminRouter.get('/wiki/:slug', ctrl.getWiki)
|
|
adminRouter.put(
|
|
'/wiki/:slug',
|
|
body('title').optional().isString().trim().notEmpty().isLength({ max: 200 }),
|
|
body('excerpt').optional({ values: 'falsy' }).isString().isLength({ max: 400 }),
|
|
body('category_id').optional({ values: 'null' }).isInt(),
|
|
body('published').optional().isBoolean(),
|
|
body('tags').optional().isArray(),
|
|
body('change_note').optional({ values: 'falsy' }).isString().isLength({ max: 280 }),
|
|
validate,
|
|
ctrl.updateWiki,
|
|
)
|
|
adminRouter.patch(
|
|
'/wiki/:slug/publish',
|
|
body('published').isBoolean(),
|
|
validate,
|
|
ctrl.publishWiki,
|
|
)
|
|
adminRouter.get('/wiki/:slug/revisions', ctrl.listWikiRevisions)
|
|
adminRouter.get('/wiki/:slug/revisions/:id', param('id').isInt(), validate, ctrl.getWikiRevision)
|
|
adminRouter.post(
|
|
'/wiki/:slug/revisions/:id/restore',
|
|
param('id').isInt(),
|
|
validate,
|
|
ctrl.restoreWikiRevision,
|
|
)
|
|
adminRouter.delete('/wiki/:slug', ctrl.deleteWiki)
|
|
|
|
// ── Settings ──────────────────────────────────────────────────────────
|
|
adminRouter.get('/settings', adminOnly, ctrl.getSettings)
|
|
adminRouter.put('/settings', adminOnly, ctrl.updateSettings)
|
|
|
|
// ── Activity log ──────────────────────────────────────────────────────
|
|
adminRouter.get('/activity', ctrl.listActivity)
|
|
|
|
// ── Bot activity (admin only) ─────────────────────────────────────────
|
|
// Read-only view of the botScore middleware's in-memory scoring/ban state and
|
|
// recent events, plus an emergency unban for false positives.
|
|
adminRouter.get('/bot-activity', adminOnly, botActivity.getBotActivity)
|
|
adminRouter.post(
|
|
'/bot-activity/unban',
|
|
adminOnly,
|
|
body('ip').isIP(),
|
|
validate,
|
|
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)
|
|
adminRouter.post(
|
|
'/users',
|
|
body('username').isString().trim().isLength({ min: 3, max: 32 }),
|
|
body('password').isString().isLength({ min: 8, max: 64 }),
|
|
body('role').optional().isIn(['admin', 'editor']),
|
|
validate,
|
|
ctrl.createUser,
|
|
)
|
|
adminRouter.put(
|
|
'/users/:id',
|
|
param('id').isInt(),
|
|
body('username').optional().isString().trim().isLength({ min: 3, max: 32 }),
|
|
body('password').optional().isString().isLength({ min: 8, max: 64 }),
|
|
body('role').optional().isIn(['admin', 'editor']),
|
|
validate,
|
|
ctrl.updateUser,
|
|
)
|
|
adminRouter.delete('/users/:id', param('id').isInt(), validate, ctrl.deleteUser)
|
|
|
|
module.exports = adminRouter
|