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:
@@ -73,3 +73,12 @@ SMTP_PASS=
|
||||
CONTACT_TO=UOMysticmoon@gmail.com
|
||||
|
||||
CLIENT_ORIGIN=http://localhost:5173
|
||||
|
||||
# Discord bot — internal API (server <-> bot/). BOT_INTERNAL_KEY MUST be
|
||||
# byte-for-byte identical to the same variable in bot/.env.example — it is the
|
||||
# only auth on both sides' /internal/* routes, so a mismatch silently breaks
|
||||
# every server<->bot call with 401s. The Discord bot TOKEN itself is not an env
|
||||
# var — it's entered in the admin panel (Discord Bot page) and stored
|
||||
# encrypted in the DB (see the bot_config table / SECRET_ENC_KEY above).
|
||||
BOT_INTERNAL_URL=http://localhost:4100
|
||||
BOT_INTERNAL_KEY=dev-only-change-me-bot-key
|
||||
|
||||
@@ -176,6 +176,179 @@ CREATE TABLE IF NOT EXISTS mobile_refresh_tokens (
|
||||
INDEX idx_mrt_expires (expires_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
-- Discord bot control (Phase 1). Singleton row (id = 1) holding the bot's
|
||||
-- config — the token is encrypted at rest (bot_token_enc) the same way OAuth
|
||||
-- client secrets are, and is only ever decrypted server-side to push to the
|
||||
-- bot process over the internal API; it is never returned to the admin UI
|
||||
-- and the bot process never reads this table directly. `status`/`status_detail`
|
||||
-- /`last_connected_at` are last-known-state mirrors of what the bot reported,
|
||||
-- shown in the admin panel between polls.
|
||||
CREATE TABLE IF NOT EXISTS bot_config (
|
||||
id INT PRIMARY KEY DEFAULT 1,
|
||||
guild_id VARCHAR(32) NULL,
|
||||
bot_token_enc TEXT NULL,
|
||||
application_id VARCHAR(32) NULL,
|
||||
enabled TINYINT(1) NOT NULL DEFAULT 0,
|
||||
status VARCHAR(20) NOT NULL DEFAULT 'disconnected',
|
||||
status_detail VARCHAR(500) NULL,
|
||||
last_connected_at DATETIME NULL,
|
||||
updated_by INT NULL,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
CONSTRAINT fk_bot_config_user FOREIGN KEY (updated_by) REFERENCES users(id) ON DELETE SET NULL,
|
||||
CONSTRAINT chk_bot_config_singleton CHECK (id = 1)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
-- Discord bot moderation core (Phase 2). These tables are owned by the bot
|
||||
-- process (its own DB pool, bot/src/db.js) — the main server never reads or
|
||||
-- writes them. They live in the same physical database as everything else
|
||||
-- (per the spec's "shared instance, clearly prefixed where needed" option)
|
||||
-- purely because there's no separate migration tooling to stand up a second
|
||||
-- database for a single-guild v1 bot.
|
||||
|
||||
-- Per-guild key/value config the bot needs at runtime (currently just the
|
||||
-- mod-log channel; filters/schedules/role-menu config lands here in later
|
||||
-- phases). Set via the `/modlog set` slash command, not the admin panel —
|
||||
-- unlike bot_config (identity/connection secrets), this is routine Discord
|
||||
-- server administration staff already do inside Discord.
|
||||
CREATE TABLE IF NOT EXISTS guild_config (
|
||||
guild_id VARCHAR(32) NOT NULL,
|
||||
`key` VARCHAR(64) NOT NULL,
|
||||
value VARCHAR(500) NULL,
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (guild_id, `key`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
-- Audit trail + mod-log source of truth for ban/kick/mute/warn actions.
|
||||
-- duration_seconds is only set for timed mutes; NULL for permanent
|
||||
-- ban/kick/warn actions.
|
||||
CREATE TABLE IF NOT EXISTS mod_actions (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
guild_id VARCHAR(32) NOT NULL,
|
||||
action_type ENUM('ban','kick','mute','warn') NOT NULL,
|
||||
target_user_id VARCHAR(32) NOT NULL,
|
||||
target_tag VARCHAR(120) NULL,
|
||||
staff_user_id VARCHAR(32) NOT NULL,
|
||||
staff_tag VARCHAR(120) NULL,
|
||||
reason VARCHAR(500) NULL,
|
||||
duration_seconds INT NULL,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
INDEX idx_mod_actions_target (guild_id, target_user_id, created_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
-- Standing warnings, separate from mod_actions so /warnings can list active
|
||||
-- warnings per user. expires_at is unused in Phase 2 (no decay/escalation
|
||||
-- yet — deferred, see mute/warn command comments) but the column is cheap to
|
||||
-- add now rather than migrate in later.
|
||||
CREATE TABLE IF NOT EXISTS warnings (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
guild_id VARCHAR(32) NOT NULL,
|
||||
target_user_id VARCHAR(32) NOT NULL,
|
||||
target_tag VARCHAR(120) NULL,
|
||||
staff_user_id VARCHAR(32) NOT NULL,
|
||||
staff_tag VARCHAR(120) NULL,
|
||||
reason VARCHAR(500) NULL,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
expires_at DATETIME NULL,
|
||||
INDEX idx_warnings_target (guild_id, target_user_id, created_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
-- Banned-word list (Phase 3). `word` is stored as the admin typed it; matching
|
||||
-- normalizes both sides at runtime (case, leetspeak, repeated chars — see
|
||||
-- bot/src/filter/normalize.js), so the stored value doesn't need every
|
||||
-- obfuscated variant. severity drives the auto-action: delete-only, delete +
|
||||
-- warn, or delete + mute (see messageFilter.js). The role/channel allowlist
|
||||
-- that bypasses filtering entirely lives in guild_config (keys
|
||||
-- filter_allow_roles / filter_allow_channels, CSV of snowflake ids) rather
|
||||
-- than a separate table — it's a short, rarely-changed list.
|
||||
CREATE TABLE IF NOT EXISTS filter_words (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
guild_id VARCHAR(32) NOT NULL,
|
||||
word VARCHAR(200) NOT NULL,
|
||||
severity ENUM('delete','warn','mute') NOT NULL DEFAULT 'delete',
|
||||
added_by VARCHAR(32) NULL,
|
||||
added_by_tag VARCHAR(120) NULL,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE KEY uq_filter_words_guild_word (guild_id, word)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
-- Scheduled/recurring messages (Phase 4). A row is EITHER recurring
|
||||
-- (cron_expression set, run_at NULL — reposts on the node-cron schedule
|
||||
-- forever until disabled/removed) OR one-off (run_at set, cron_expression
|
||||
-- NULL — posted once, then sent_at is stamped so the scheduler's due-message
|
||||
-- sweep never reposts it). content is plain text for now — the original spec
|
||||
-- allows richer embed JSON here, deferred since authoring embed JSON through a
|
||||
-- single slash-command string option isn't practical without a modal/admin UI.
|
||||
CREATE TABLE IF NOT EXISTS scheduled_messages (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
guild_id VARCHAR(32) NOT NULL,
|
||||
channel_id VARCHAR(32) NOT NULL,
|
||||
content VARCHAR(2000) NOT NULL,
|
||||
cron_expression VARCHAR(100) NULL,
|
||||
run_at DATETIME NULL,
|
||||
enabled TINYINT(1) NOT NULL DEFAULT 1,
|
||||
sent_at DATETIME NULL,
|
||||
created_by VARCHAR(32) NULL,
|
||||
created_by_tag VARCHAR(120) NULL,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT chk_schedule_kind CHECK (
|
||||
(cron_expression IS NOT NULL AND run_at IS NULL) OR
|
||||
(cron_expression IS NULL AND run_at IS NOT NULL)
|
||||
),
|
||||
INDEX idx_scheduled_due (run_at, sent_at, enabled)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
-- Self-assignable role menus (Phase 5). Button-based, not reaction-based —
|
||||
-- avoids needing the messageReactionAdd/Remove events and their own intent.
|
||||
-- `mapping` is a JSON array of {roleId, label}, validated against at click
|
||||
-- time (see bot/src/discord/roleMenuHandler.js) so a stale/foreign button
|
||||
-- customId can't toggle an untracked role. Auto-role-on-join is simpler and
|
||||
-- reuses guild_config (key auto_role_id) rather than a table of its own.
|
||||
CREATE TABLE IF NOT EXISTS role_menus (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
guild_id VARCHAR(32) NOT NULL,
|
||||
channel_id VARCHAR(32) NOT NULL,
|
||||
message_id VARCHAR(32) NOT NULL,
|
||||
mapping TEXT NOT NULL,
|
||||
created_by VARCHAR(32) NULL,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE KEY uq_role_menus_message (message_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
-- Timed role assignments (temp-mute-equivalent roles, timed event roles).
|
||||
-- Swept once a minute (bot/src/roles/tempRoleSweeper.js) — expired rows have
|
||||
-- their Discord role removed and the row deleted. UNIQUE(guild,user,role) so
|
||||
-- re-granting the same temp role just refreshes its expiry via ON DUPLICATE
|
||||
-- KEY UPDATE rather than stacking duplicate rows.
|
||||
CREATE TABLE IF NOT EXISTS temp_roles (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
guild_id VARCHAR(32) NOT NULL,
|
||||
user_id VARCHAR(32) NOT NULL,
|
||||
role_id VARCHAR(32) NOT NULL,
|
||||
expires_at DATETIME NOT NULL,
|
||||
created_by VARCHAR(32) NULL,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE KEY uq_temp_roles_user_role (guild_id, user_id, role_id),
|
||||
INDEX idx_temp_roles_expires (expires_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
-- Audit trail for the auto-rotating primary invite (Phase 6). triggered_by
|
||||
-- NULL means the weekly scheduled rotation did it, not a staff member — see
|
||||
-- bot/src/invites/inviteRotator.js, shared by both /invite rotate and the
|
||||
-- cron job so both paths log identically. The channel invites are created in
|
||||
-- is configured separately in guild_config (key invite_channel_id).
|
||||
CREATE TABLE IF NOT EXISTS invite_log (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
guild_id VARCHAR(32) NOT NULL,
|
||||
channel_id VARCHAR(32) NOT NULL,
|
||||
invite_code VARCHAR(20) NOT NULL,
|
||||
triggered_by VARCHAR(32) NULL,
|
||||
triggered_by_tag VARCHAR(120) NULL,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
revoked_at DATETIME NULL,
|
||||
INDEX idx_invite_log_guild (guild_id, created_at)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||
|
||||
-- Migrations for databases created before the wiki upgrade. Each statement uses
|
||||
-- IF NOT EXISTS so re-running on every boot is a harmless no-op. New installs get
|
||||
-- these columns from the CREATE TABLE above; existing installs get them here.
|
||||
|
||||
20
server/src/middleware/requireInternalKey.js
Normal file
20
server/src/middleware/requireInternalKey.js
Normal file
@@ -0,0 +1,20 @@
|
||||
// Gate for server-side /internal/* routes. The only caller is the bot process,
|
||||
// on its own boot, over the private compose network — never expose this route
|
||||
// through the public reverse proxy. Timing-safe compare so response time can't
|
||||
// be used to brute-force the shared secret one byte at a time. Same pattern as
|
||||
// bot/src/internal/requireInternalKey.js on the other side of this call.
|
||||
const crypto = require('crypto')
|
||||
|
||||
function requireInternalKey(req, res, next) {
|
||||
const expected = process.env.BOT_INTERNAL_KEY || ''
|
||||
const provided = req.get('X-Internal-Key') || ''
|
||||
|
||||
const a = Buffer.from(expected)
|
||||
const b = Buffer.from(provided)
|
||||
const match = expected.length > 0 && a.length === b.length && crypto.timingSafeEqual(a, b)
|
||||
|
||||
if (!match) return res.status(401).json({ message: 'Unauthorized' })
|
||||
return next()
|
||||
}
|
||||
|
||||
module.exports = requireInternalKey
|
||||
28
server/src/model/botConfig/botConfig.db.js
Normal file
28
server/src/model/botConfig/botConfig.db.js
Normal file
@@ -0,0 +1,28 @@
|
||||
const { query } = require('../../utils/db')
|
||||
|
||||
const COLS =
|
||||
'id, guild_id, bot_token_enc, application_id, enabled, status, status_detail, last_connected_at, updated_by, created_at, updated_at'
|
||||
|
||||
// Singleton row (id = 1). Returns null until the admin saves it for the first time.
|
||||
async function get() {
|
||||
const rows = await query(`SELECT ${COLS} FROM bot_config WHERE id = 1 LIMIT 1`)
|
||||
return rows[0] || null
|
||||
}
|
||||
|
||||
// Upsert the singleton row. `fields` are column values already prepared by the
|
||||
// model (token pre-encrypted). Only the provided columns are written/updated.
|
||||
async function upsert(fields) {
|
||||
const cols = Object.keys(fields)
|
||||
const vals = cols.map((c) => fields[c])
|
||||
const insertCols = ['id', ...cols].map((c) => `\`${c}\``).join(', ')
|
||||
const placeholders = ['1', ...cols.map(() => '?')].join(', ')
|
||||
const updates = cols.map((c) => `\`${c}\` = VALUES(\`${c}\`)`).join(', ')
|
||||
await query(
|
||||
`INSERT INTO bot_config (${insertCols}) VALUES (${placeholders})
|
||||
ON DUPLICATE KEY UPDATE ${updates}`,
|
||||
vals,
|
||||
)
|
||||
return get()
|
||||
}
|
||||
|
||||
module.exports = { get, upsert }
|
||||
73
server/src/model/botConfig/botConfig.model.js
Normal file
73
server/src/model/botConfig/botConfig.model.js
Normal file
@@ -0,0 +1,73 @@
|
||||
// Discord bot config store (Phase 1). Mirrors the authProviders model split:
|
||||
// the DB layer only ever sees ciphertext, and only getWithToken() (used
|
||||
// internally to push config to the bot process / to the bot-config internal
|
||||
// endpoint) decrypts it. The admin-facing getSafe() never includes the token.
|
||||
|
||||
const db = require('./botConfig.db')
|
||||
const secretBox = require('../../utils/secretBox')
|
||||
|
||||
function toSafe(row) {
|
||||
if (!row) {
|
||||
return {
|
||||
guildId: null,
|
||||
applicationId: null,
|
||||
enabled: false,
|
||||
hasToken: false,
|
||||
status: 'disconnected',
|
||||
statusDetail: null,
|
||||
lastConnectedAt: null,
|
||||
}
|
||||
}
|
||||
return {
|
||||
guildId: row.guild_id || null,
|
||||
applicationId: row.application_id || null,
|
||||
enabled: Boolean(row.enabled),
|
||||
hasToken: Boolean(row.bot_token_enc),
|
||||
status: row.status || 'disconnected',
|
||||
statusDetail: row.status_detail || null,
|
||||
lastConnectedAt: row.last_connected_at || null,
|
||||
}
|
||||
}
|
||||
|
||||
async function getSafe() {
|
||||
return toSafe(await db.get())
|
||||
}
|
||||
|
||||
// Decrypted token included — server-side only (pushing config to the bot, or
|
||||
// serving the shared-secret-gated /internal/bot-config route).
|
||||
async function getWithToken() {
|
||||
const row = await db.get()
|
||||
if (!row) return null
|
||||
return { ...toSafe(row), token: row.bot_token_enc ? secretBox.decrypt(row.bot_token_enc) : null }
|
||||
}
|
||||
|
||||
// Save admin-supplied config. `token` undefined or '' means "leave the
|
||||
// existing token unchanged" (same convention as authProviders.save).
|
||||
async function save({ guildId, applicationId, token, enabled, updatedBy }) {
|
||||
const fields = {}
|
||||
if (guildId !== undefined) fields.guild_id = guildId
|
||||
if (applicationId !== undefined) fields.application_id = applicationId
|
||||
if (token) fields.bot_token_enc = secretBox.encrypt(token)
|
||||
if (enabled !== undefined) fields.enabled = enabled ? 1 : 0
|
||||
if (updatedBy !== undefined) fields.updated_by = updatedBy
|
||||
const row = await db.upsert(fields)
|
||||
return toSafe(row)
|
||||
}
|
||||
|
||||
// Mirror the bot's last-reported status into the DB so the admin panel has
|
||||
// something to show even if the bot is briefly unreachable.
|
||||
async function recordStatus({ status, statusDetail, lastConnectedAt }) {
|
||||
const fields = {}
|
||||
if (status !== undefined) fields.status = status
|
||||
if (statusDetail !== undefined) fields.status_detail = statusDetail
|
||||
// lastConnectedAt arrives over HTTP as a JSON-serialized ISO string (e.g.
|
||||
// "2026-07-04T18:49:51.429Z") — MariaDB's DATETIME parser rejects the "T"/
|
||||
// "Z"/milliseconds in that format. Convert to a real Date so the mariadb
|
||||
// driver formats it correctly on the wire.
|
||||
if (lastConnectedAt !== undefined) fields.last_connected_at = lastConnectedAt ? new Date(lastConnectedAt) : null
|
||||
if (Object.keys(fields).length === 0) return getSafe()
|
||||
const row = await db.upsert(fields)
|
||||
return toSafe(row)
|
||||
}
|
||||
|
||||
module.exports = { getSafe, getWithToken, save, recordStatus }
|
||||
@@ -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 }
|
||||
19
server/src/router/v1/internal/internal.controller.js
Normal file
19
server/src/router/v1/internal/internal.controller.js
Normal file
@@ -0,0 +1,19 @@
|
||||
const botConfig = require('../../../model/botConfig/botConfig.model')
|
||||
const log = require('../../../utils/logger')('internal')
|
||||
|
||||
// GET /internal/bot-config — called by the bot process on its own boot so a
|
||||
// restart self-reconnects without any admin-panel interaction. Returns the
|
||||
// DECRYPTED token — this route must never be reachable outside the private
|
||||
// compose network (see requireInternalKey + deployment notes).
|
||||
async function getBotConfig(req, res) {
|
||||
try {
|
||||
const config = await botConfig.getWithToken()
|
||||
if (!config) return res.json({ enabled: false, token: null, guildId: null })
|
||||
return res.json({ enabled: config.enabled, token: config.token, guildId: config.guildId })
|
||||
} catch (err) {
|
||||
log.error('internal.getBotConfig', err)
|
||||
return res.status(500).json({ message: 'Internal Server Error' })
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { getBotConfig }
|
||||
18
server/src/router/v1/internal/internal.routes.js
Normal file
18
server/src/router/v1/internal/internal.routes.js
Normal file
@@ -0,0 +1,18 @@
|
||||
const express = require('express')
|
||||
|
||||
const requireInternalKey = require('../../../middleware/requireInternalKey')
|
||||
const ctrl = require('./internal.controller')
|
||||
|
||||
const router = express.Router()
|
||||
|
||||
// Shared-secret gated, not session-gated — the caller is the bot process, not
|
||||
// a logged-in browser. Mounted before any auth/session middleware in v1.router.
|
||||
router.use(requireInternalKey)
|
||||
|
||||
router.get(
|
||||
'/bot-config',
|
||||
// #swagger.ignore = true
|
||||
ctrl.getBotConfig,
|
||||
)
|
||||
|
||||
module.exports = router
|
||||
@@ -5,9 +5,13 @@ const v1Router = express.Router()
|
||||
const authRouter = require('./auth/auth.routes')
|
||||
const publicRouter = require('./public/public.routes')
|
||||
const adminRouter = require('./admin/admin.routes')
|
||||
const internalRouter = require('./internal/internal.routes')
|
||||
|
||||
v1Router.use('/auth', authRouter)
|
||||
v1Router.use('/public', publicRouter)
|
||||
v1Router.use('/admin', adminRouter)
|
||||
// Shared-secret gated (not session-gated) — server<->bot only, never exposed
|
||||
// through the public reverse proxy. See server/src/middleware/requireInternalKey.js.
|
||||
v1Router.use('/internal', internalRouter)
|
||||
|
||||
module.exports = v1Router
|
||||
|
||||
55
server/src/utils/botInternalClient.js
Normal file
55
server/src/utils/botInternalClient.js
Normal file
@@ -0,0 +1,55 @@
|
||||
// Tiny fetch wrapper for calling the bot process's /internal/* API (shared
|
||||
// secret, same pattern as requireInternalKey on both sides). Used by the
|
||||
// Discord Bot admin controller to push config after a save and to poll live
|
||||
// status for the admin panel. Never throws — callers get { ok: false, error }
|
||||
// on any failure (bot unreachable, timeout, non-2xx) so an admin save/poll
|
||||
// never 500s just because the bot container is down or restarting.
|
||||
const log = require('./logger')('bot-internal-client')
|
||||
|
||||
const BASE_URL = process.env.BOT_INTERNAL_URL || 'http://localhost:4100'
|
||||
const KEY = process.env.BOT_INTERNAL_KEY || ''
|
||||
const TIMEOUT_MS = 4000
|
||||
|
||||
async function call(path, { method = 'GET', body } = {}) {
|
||||
const controller = new AbortController()
|
||||
const timeout = setTimeout(() => controller.abort(), TIMEOUT_MS)
|
||||
try {
|
||||
const res = await fetch(`${BASE_URL}${path}`, {
|
||||
method,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Internal-Key': KEY,
|
||||
},
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
signal: controller.signal,
|
||||
})
|
||||
if (!res.ok) {
|
||||
return { ok: false, error: `bot responded ${res.status}` }
|
||||
}
|
||||
return { ok: true, data: await res.json() }
|
||||
} catch (err) {
|
||||
log.warn('bot internal call failed', { path, message: err.message })
|
||||
return { ok: false, error: err.message }
|
||||
} finally {
|
||||
clearTimeout(timeout)
|
||||
}
|
||||
}
|
||||
|
||||
// Push a config change (start/stop the bot's Discord client).
|
||||
function pushConfig({ token, guildId, enabled }) {
|
||||
return call('/internal/config', { method: 'POST', body: { token, guildId, enabled } })
|
||||
}
|
||||
|
||||
// Live connection status, for the admin panel.
|
||||
function getStatus() {
|
||||
return call('/internal/status')
|
||||
}
|
||||
|
||||
// Site -> bot: a news post was published, post it to the configured #news
|
||||
// channel. Fire-and-forget from the caller's perspective — never throws, so
|
||||
// a bot outage never breaks publishing a post.
|
||||
function announce({ title, excerpt, url, imageUrl }) {
|
||||
return call('/internal/announce', { method: 'POST', body: { title, excerpt, url, imageUrl } })
|
||||
}
|
||||
|
||||
module.exports = { pushConfig, getStatus, announce }
|
||||
@@ -16,6 +16,13 @@ const pool = mariadb.createPool({
|
||||
insertIdAsNumber: true,
|
||||
bigIntAsNumber: true,
|
||||
decimalAsNumber: true,
|
||||
// The driver defaults to 'local' — silently serializing bound JS Date
|
||||
// params using the HOST MACHINE's local offset instead of the DB session's
|
||||
// timezone (discovered via the Discord bot's temp_roles.expires_at coming
|
||||
// back hours off in dev). 'auto' negotiates the actual session timezone so
|
||||
// Date round-trips correctly regardless of host TZ — affects any write of
|
||||
// a JS Date param, e.g. botConfig.model.js's last_connected_at.
|
||||
timezone: 'auto',
|
||||
})
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user