Add Discord bot (moderation, filters, scheduling, roles, invites, site integration)
Standalone bot/ service (its own package.json/Dockerfile) managed entirely through a new admin-only Discord Bot panel — token stored encrypted in the DB and pushed to the bot process in-memory, never an env var. Built in phases, each independently verified against a live Discord guild: - Bot skeleton: gateway connection, internal shared-secret API, self-heals on its own restart by pulling config from the site - Moderation core: /ban /kick /mute /warn /warnings + mod-log channel - Word/invite/spam filtering with leetspeak-resistant normalization and a staff role/channel allowlist - Scheduled messages: recurring (cron) and one-off channel posts - Role assignment: button role menus, auto-role on join, temp roles, bulk role ops - Auto-rotating primary invite with an audit log - Site integration: news-publish -> Discord announce webhook, manual /announce, read-only /wiki search Also fixes a pre-existing bug in both DB pools (server + bot): the mariadb driver defaulted to timezone 'local', silently mis-serializing bound Date params by the host's local offset instead of the DB's UTC session. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -3,9 +3,38 @@ const wiki = require('../../../model/wiki/wiki.model')
|
||||
const settings = require('../../../model/settings/settings.model')
|
||||
const users = require('../../../model/users/users.model')
|
||||
const activity = require('../../../model/activity/activity.model')
|
||||
const botInternalClient = require('../../../utils/botInternalClient')
|
||||
|
||||
const log = require('../../../utils/logger')('admin')
|
||||
|
||||
// Public base URL for links back to the site — same fallback pattern as
|
||||
// sso.controller.js's redirect_uri builder.
|
||||
function appBaseUrl(req) {
|
||||
const configured = process.env.APP_BASE_URL
|
||||
if (configured) return configured.replace(/\/+$/, '')
|
||||
return `${req.protocol}://${req.get('host')}`
|
||||
}
|
||||
|
||||
// Fire-and-forget: announce a news post to Discord the moment it actually
|
||||
// transitions from unpublished to published — not on every save or on a
|
||||
// no-op re-publish of an already-live post. Never throws (botInternalClient
|
||||
// itself never rejects); a bot outage must never break publishing a post.
|
||||
function announceIfNewlyPublished(req, post, wasPublished) {
|
||||
if (!post || post.category !== 'news' || !post.published || wasPublished) return
|
||||
const base = appBaseUrl(req)
|
||||
// image_url is stored relative (e.g. "/uploads/xyz.png") — Discord embeds
|
||||
// require an absolute URL.
|
||||
const imageUrl = post.image_url ? new URL(post.image_url, base).toString() : null
|
||||
botInternalClient
|
||||
.announce({
|
||||
title: post.title,
|
||||
excerpt: post.excerpt,
|
||||
url: `${base}/site/news`,
|
||||
imageUrl,
|
||||
})
|
||||
.catch(() => {})
|
||||
}
|
||||
|
||||
// ── Dashboard & site mode ─────────────────────────────────────────────
|
||||
async function dashboard(req, res) {
|
||||
try {
|
||||
@@ -90,6 +119,7 @@ async function createPost(req, res) {
|
||||
author_id: req.user.id,
|
||||
})
|
||||
await activity.log({ req, action: 'post.create', detail: { id: created.id, category: dbCategory } })
|
||||
announceIfNewlyPublished(req, created, false)
|
||||
return res.status(201).json(created)
|
||||
} catch (err) {
|
||||
log.error('createPost', err)
|
||||
@@ -119,6 +149,7 @@ async function updatePost(req, res) {
|
||||
|
||||
const updated = await posts.update(id, fields)
|
||||
await activity.log({ req, action: 'post.update', detail: { id } })
|
||||
announceIfNewlyPublished(req, updated, Boolean(current.published))
|
||||
return res.json(updated)
|
||||
} catch (err) {
|
||||
log.error('updatePost', err)
|
||||
@@ -129,13 +160,15 @@ async function updatePost(req, res) {
|
||||
async function publishPost(req, res) {
|
||||
const id = Number(req.params.id)
|
||||
try {
|
||||
const current = await posts.getById(id)
|
||||
if (!current) return res.status(404).json({ message: 'Not found' })
|
||||
const updated = await posts.setPublished(id, Boolean(req.body.published))
|
||||
if (!updated) return res.status(404).json({ message: 'Not found' })
|
||||
await activity.log({
|
||||
req,
|
||||
action: 'post.publish',
|
||||
detail: { id, published: Boolean(req.body.published) },
|
||||
})
|
||||
announceIfNewlyPublished(req, updated, Boolean(current.published))
|
||||
return res.json(updated)
|
||||
} catch (err) {
|
||||
return res.status(500).json({ message: 'Internal Server Error' })
|
||||
|
||||
@@ -9,6 +9,7 @@ const ctrl = require('./admin.controller')
|
||||
const account = require('./account.controller')
|
||||
const botActivity = require('./botActivity.controller')
|
||||
const authProviders = require('./authProviders.controller')
|
||||
const discordBot = require('./discordBot.controller')
|
||||
const { isLoggedIn, requireRole } = require('../../../utils/auth')
|
||||
const noindex = require('../../../middleware/noindex')
|
||||
const validate = require('../../../middleware/validate')
|
||||
@@ -530,6 +531,39 @@ adminRouter.post(
|
||||
botActivity.unbanIp,
|
||||
)
|
||||
|
||||
// ── Discord bot control (admin only) ──────────────────────────────────
|
||||
// Phase 1: entering/enabling the bot token here — never an env var. The token
|
||||
// is write-only over this API (SECURITY note in discordBot.controller.js).
|
||||
adminRouter.get(
|
||||
'/discord-bot/config',
|
||||
// #swagger.tags = ['Admin · Discord Bot']
|
||||
// #swagger.summary = 'Get Discord bot config + live status (admin only)'
|
||||
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
|
||||
/* #swagger.responses[200] = { description: 'Masked config + live status', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */
|
||||
/* #swagger.responses[401] = { description: 'Not authenticated', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
|
||||
/* #swagger.responses[403] = { description: 'Admin role required', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
|
||||
adminOnly,
|
||||
discordBot.getConfig,
|
||||
)
|
||||
adminRouter.put(
|
||||
'/discord-bot/config',
|
||||
// #swagger.tags = ['Admin · Discord Bot']
|
||||
// #swagger.summary = 'Save Discord bot config (admin only)'
|
||||
// #swagger.description = 'token is write-only — omit/blank it to keep the existing one unchanged.'
|
||||
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
|
||||
/* #swagger.requestBody = { required: true, content: { "application/json": { schema: { type: "object", properties: { guildId: { type: "string" }, token: { type: "string" }, enabled: { type: "boolean" } } } } } } */
|
||||
/* #swagger.responses[200] = { description: 'Updated config + live status', content: { "application/json": { schema: { type: "object", additionalProperties: true } } } } */
|
||||
/* #swagger.responses[400] = { description: 'Validation error, invalid token, or missing token while enabling', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
|
||||
/* #swagger.responses[401] = { description: 'Not authenticated', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
|
||||
/* #swagger.responses[403] = { description: 'Admin role required', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
|
||||
adminOnly,
|
||||
body('guildId').optional({ values: 'falsy' }).isString().trim(),
|
||||
body('token').optional({ values: 'falsy' }).isString().trim(),
|
||||
body('enabled').optional().isBoolean(),
|
||||
validate,
|
||||
discordBot.saveConfig,
|
||||
)
|
||||
|
||||
// ── Authentication providers / SSO (admin only) ───────────────────────
|
||||
adminRouter.get(
|
||||
'/auth/providers',
|
||||
|
||||
98
server/src/router/v1/admin/discordBot.controller.js
Normal file
98
server/src/router/v1/admin/discordBot.controller.js
Normal file
@@ -0,0 +1,98 @@
|
||||
// ── Admin: Discord bot control ─────────────────────────────────────────────
|
||||
//
|
||||
// Phase 1: entering/enabling the bot token here (not an env var) and pushing
|
||||
// it to the bot process over the internal API. SECURITY: the token is
|
||||
// write-only over this API, same convention as auth provider secrets — it is
|
||||
// stored encrypted and NEVER returned; responses expose only `hasToken`. A
|
||||
// blank `token` on save means "leave the existing token unchanged".
|
||||
|
||||
const botConfig = require('../../../model/botConfig/botConfig.model')
|
||||
const botClient = require('../../../utils/botInternalClient')
|
||||
const activity = require('../../../model/activity/activity.model')
|
||||
|
||||
const log = require('../../../utils/logger')('admin')
|
||||
|
||||
const SNOWFLAKE = /^\d{17,20}$/
|
||||
|
||||
// Confirm a bot token is real by asking Discord who it belongs to. Returns
|
||||
// true/false only on a definitive answer; returns true (don't block the save)
|
||||
// if Discord couldn't be reached at all, since a network hiccup shouldn't
|
||||
// stop an admin from saving a token that may well be valid. Guild-membership
|
||||
// validation is deliberately NOT done here — a bot token is valid before the
|
||||
// bot has ever been invited to the guild, so checking guild access here would
|
||||
// reject perfectly good first-time setups with a false negative.
|
||||
async function isValidBotToken(token) {
|
||||
try {
|
||||
const res = await fetch('https://discord.com/api/users/@me', {
|
||||
headers: { Authorization: `Bot ${token}` },
|
||||
})
|
||||
if (res.status === 401) return false
|
||||
return true
|
||||
} catch (err) {
|
||||
log.warn('discord token validation unreachable — not blocking save', { message: err.message })
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// GET /admin/discord-bot/config — masked config + live status (falls back to
|
||||
// the last-known DB-mirrored status if the bot process is unreachable).
|
||||
async function getConfig(req, res) {
|
||||
try {
|
||||
const config = await botConfig.getSafe()
|
||||
const live = await botClient.getStatus()
|
||||
if (live.ok) {
|
||||
config.status = live.data.status
|
||||
config.statusDetail = live.data.statusDetail
|
||||
config.lastConnectedAt = live.data.lastConnectedAt
|
||||
await botConfig.recordStatus(live.data)
|
||||
} else {
|
||||
config.statusDetail = config.statusDetail || `bot unreachable: ${live.error}`
|
||||
}
|
||||
return res.json(config)
|
||||
} catch (err) {
|
||||
log.error('discordBot.getConfig', err)
|
||||
return res.status(500).json({ message: 'Internal Server Error' })
|
||||
}
|
||||
}
|
||||
|
||||
// PUT /admin/discord-bot/config — save + push to the bot process.
|
||||
async function saveConfig(req, res) {
|
||||
const { guildId, token, enabled } = req.body
|
||||
try {
|
||||
if (guildId !== undefined && guildId !== '' && !SNOWFLAKE.test(guildId)) {
|
||||
return res.status(400).json({ message: 'guildId does not look like a valid Discord server ID.' })
|
||||
}
|
||||
|
||||
if (token) {
|
||||
const ok = await isValidBotToken(token)
|
||||
if (!ok) return res.status(400).json({ message: 'That bot token was rejected by Discord — check it and try again.' })
|
||||
}
|
||||
|
||||
const current = await botConfig.getSafe()
|
||||
const willHaveToken = Boolean(token) || current.hasToken
|
||||
if (enabled && !willHaveToken) {
|
||||
return res.status(400).json({ message: 'A bot token is required before enabling.' })
|
||||
}
|
||||
|
||||
const saved = await botConfig.save({ guildId, token, enabled, updatedBy: req.user.id })
|
||||
const withToken = await botConfig.getWithToken()
|
||||
const push = await botClient.pushConfig({ token: withToken.token, guildId: saved.guildId, enabled: saved.enabled })
|
||||
if (push.ok) {
|
||||
await botConfig.recordStatus(push.data)
|
||||
saved.status = push.data.status
|
||||
saved.statusDetail = push.data.statusDetail
|
||||
saved.lastConnectedAt = push.data.lastConnectedAt
|
||||
} else {
|
||||
saved.statusDetail = `bot unreachable: ${push.error}`
|
||||
}
|
||||
|
||||
await activity.log({ req, action: 'discordBot.config.update', detail: { guildId: saved.guildId, enabled: saved.enabled } })
|
||||
log.info('discord bot config updated', { by: req.user.username, enabled: saved.enabled })
|
||||
return res.json(saved)
|
||||
} catch (err) {
|
||||
log.error('discordBot.saveConfig', err)
|
||||
return res.status(500).json({ message: 'Internal Server Error' })
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { getConfig, saveConfig }
|
||||
Reference in New Issue
Block a user