Files
website/server/src/router/v1/admin/admin.routes.js
Claude d38c98ad9e Harden admin login: RBAC-safe controls, 2FA, bot-scoring, rate limits (#9)
Adds a layered set of protections around the admin login and the app edge.

Trust proxy (server/src/utils/trustProxy.js)
- Configurable via TRUST_PROXY; pin to the newt agent ("ptero") LAN IP so
  X-Forwarded-For is trusted ONLY from that peer. A blanket "true" is
  rejected (coerced to 1) to prevent XFF spoofing that would dodge every
  IP-based control. DEBUG_TRUST_PROXY logs peer/XFF/req.ip to re-verify the
  proxy IP without a redeploy. Documents the Omada static-reservation
  assumption.

Login throttling (server/src/middleware/loginProtection.js, rateLimit.js)
- express-slow-down progressive delay + the existing hard rate cap + a
  separate per-IP exponential backoff that persists across the rate window.
  All failures return one generic message (no user/pass disclosure).

Honeypot (login form + auth.controller)
- Hidden, plausibly-named field ("company"); a filled value fails
  generically and is scored as an unambiguous bot.

Optional per-user TOTP 2FA (speakeasy/qrcode)
- totp_secret/totp_enabled columns (+ idempotent migration). Self-service
  Account page: enroll via QR, confirm a code to enable, code-gated disable.
- Login is two-step for enrolled users: after the password, a short-lived
  signed challenge (stage:'totp', not a session) is required before the
  real session is issued.

Bot / scanner scoring + IP ban (server/src/middleware/botScore.js)
- Weighted CMS-scanner paths (this app uses none). Junk paths 404 FIRST,
  unconditionally — independent of score/ban state, so a scanner rotating
  through fresh Cloudflare IPs gets no free pass. /wp-admin/install.php is
  the top-weighted near-1-hit ban (worst offender in prod logs). Per-IP
  score with quiet-period decay temp-bans an IP from ALL routes once past a
  (deliberately low) threshold, to protect /admin from credential stuffing.
  Failed logins and honeypot hits feed the same score.
- Periodic sweep evicts stale, unbanned, quiet entries so the in-memory
  store can't grow unbounded; the interval is unref'd and cleared on
  graceful shutdown.

Tests: node --test suite (40) covering trust-proxy parsing + live req.ip
(incl. pinned-IP), rate limiter + exponential backoff, honeypot rejection,
TOTP verify (enabled/disabled) + challenge-isn't-a-session, bot-score
threshold/decay/ban + junk-404-independence + install.php + store sweep.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-02 23:22:35 -05:00

204 lines
7.9 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 { 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,
)
// ── 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)
// ── 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