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:
2026-07-04 15:54:41 -05:00
parent 0318d6fe9f
commit 7a21cc636c
77 changed files with 4800 additions and 3 deletions

View File

@@ -0,0 +1,31 @@
// In-memory per-guild filter state (word list + allowlist), loaded at startup
// and refreshed on config change — the messageCreate handler runs on every
// message, so it must never hit the DB per message (per the spec's
// performance note).
const filterWords = require('../model/filterWords')
const filterAllowlist = require('../model/filterAllowlist')
const cache = new Map() // guildId -> { words, allowRoles: Set, allowChannels: Set }
async function load(guildId) {
const [words, roles, channels] = await Promise.all([
filterWords.list(guildId),
filterAllowlist.getRoles(guildId),
filterAllowlist.getChannels(guildId),
])
const entry = { words, allowRoles: new Set(roles), allowChannels: new Set(channels) }
cache.set(guildId, entry)
return entry
}
// Lazy-loads on first access per guild (e.g. the first message after boot).
async function getOrLoad(guildId) {
return cache.get(guildId) || load(guildId)
}
// Called by /filter and /filterallow after any mutation.
function refresh(guildId) {
return load(guildId)
}
module.exports = { getOrLoad, refresh }

View File

@@ -0,0 +1,23 @@
// Detects Discord invite links and blocks any that don't resolve to the
// current guild (anti-raid/anti-advertising). An invite that fails to resolve
// (expired/invalid/vanity-only) is treated as foreign too — safer default
// than silently letting an unresolvable link through.
const INVITE_REGEX = /(?:discord\.gg|discord(?:app)?\.com\/invite)\/([a-zA-Z0-9-]+)/gi
async function containsForeignInvite(message) {
const matches = [...message.content.matchAll(INVITE_REGEX)]
if (matches.length === 0) return false
for (const match of matches) {
const code = match[1]
try {
const invite = await message.client.fetchInvite(code)
if (invite.guild?.id !== message.guildId) return true
} catch {
return true
}
}
return false
}
module.exports = { containsForeignInvite }

View File

@@ -0,0 +1,33 @@
// Basic obfuscation-resistant normalization for the word filter: lowercase,
// common leetspeak substitutions, and collapsing 3+ repeated characters
// ("sooooo" -> "so") to one. Deliberately simple per the spec ("start simple,
// leave room to tighten later") — spaced-out letters ("b a d") and more exotic
// unicode lookalikes aren't handled yet.
const SUBS = { 4: 'a', '@': 'a', 3: 'e', 1: 'i', '!': 'i', 0: 'o', $: 's', 5: 's', 7: 't' }
const SUB_CHARS = /[4@31!05$7]/g
function normalize(text) {
return text
.toLowerCase()
.replace(SUB_CHARS, (ch) => SUBS[ch] || ch)
.replace(/(.)\1{2,}/g, '$1')
}
function escapeRegex(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}
// Word-boundary match against already-normalized text. `word` is normalized
// here too, so callers can pass the raw stored value.
function matches(normalizedText, word) {
const pattern = new RegExp(`\\b${escapeRegex(normalize(word))}\\b`, 'i')
return pattern.test(normalizedText)
}
// Returns the first matching filter_words row ({word, severity}) or null.
function findMatch(content, words) {
const normalizedText = normalize(content)
return words.find((w) => matches(normalizedText, w.word)) || null
}
module.exports = { normalize, matches, findMatch }

View File

@@ -0,0 +1,42 @@
// Basic in-memory spam/rate-limit detection. Per-user message-rate tracking is
// the only stateful piece here (mass-mention/mass-emoji are per-message
// counts) — kept in memory rather than the DB since this runs on every
// message and needs to be fast.
const RATE_LIMIT_COUNT = 5
const RATE_LIMIT_WINDOW_MS = 5000
const MENTION_THRESHOLD = 5
const EMOJI_THRESHOLD = 10
const SWEEP_INTERVAL_MS = 5 * 60 * 1000
const history = new Map() // `${guildId}:${userId}` -> timestamps[]
function isRateLimited(guildId, userId) {
const key = `${guildId}:${userId}`
const now = Date.now()
const timestamps = (history.get(key) || []).filter((t) => now - t < RATE_LIMIT_WINDOW_MS)
timestamps.push(now)
history.set(key, timestamps)
return timestamps.length > RATE_LIMIT_COUNT
}
function isMassMention(message) {
return message.mentions.users.size + message.mentions.roles.size > MENTION_THRESHOLD
}
const EMOJI_REGEX = /<a?:\w+:\d+>|\p{Extended_Pictographic}/gu
function isMassEmoji(content) {
const count = (content.match(EMOJI_REGEX) || []).length
return count > EMOJI_THRESHOLD
}
// Periodic cleanup so `history` doesn't grow unbounded over a long-running
// process — drops any key with no recent activity.
setInterval(() => {
const now = Date.now()
for (const [key, timestamps] of history) {
if (timestamps.every((t) => now - t >= RATE_LIMIT_WINDOW_MS)) history.delete(key)
}
}, SWEEP_INTERVAL_MS).unref()
module.exports = { isRateLimited, isMassMention, isMassEmoji }