Add moderation dashboard, user history & notes (Phase 6a)

Surface the Discord bot's moderation data on the admin panel: a read-only
staff dashboard over the existing mod_actions log, per-user history, staff
notes, and a new moderator role. No bot changes.

Schema
- users.role ENUM gains 'moderator' (CREATE + idempotent ALTER for existing DBs)
- new server-owned mod_notes table (staff_only/admin_only visibility)

Server
- model/moderation: read mod_actions via the shared pool (documented read-only
  cross of the bot/server ownership boundary), correlate accounts through
  user_identities (provider='discord'), flag automated actions via
  staff_user_id === bot_config.application_id; pure reshaping helpers isolated
  in moderation.pure.js so they unit-test without opening a DB pool
- model/modNotes: list/add with role-gated admin_only visibility
- admin/moderation.controller + routes under /api/v1/admin/moderation/* gated by
  requireRole('admin','moderator'); admin_only note writes require admin
- allow assigning 'moderator' in the user create/update validators

Client
- /admin/moderation overview (window tiles, type-filterable recent feed, user
  lookup) and /user/:discordId history (tabs + notes with add-note)
- RoleGate; AdminLayout filters nav and confines moderators to their section
- moderator badge + action-type/auto badges

Deferred (see plan): 6b bot event capture (joins/leaves/filter/spam), 6c appeals
(needs public accounts), 6d /internal/mod-reverse bot reversal callback.

Verified: 116 server unit tests, client build, DB-backed model smoke, full
HTTP/RBAC e2e, and a browser click-through of the dashboard.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019rao86n5cXpwAyjdBFEshV
This commit is contained in:
2026-07-05 10:16:34 -05:00
parent 20d3fbf594
commit b0c0d1fe9b
19 changed files with 1436 additions and 7 deletions

View File

@@ -0,0 +1,51 @@
// Staff notes on a Discord user (server-owned, see db/schema.sql mod_notes).
// Notes are never user-visible; admin_only notes are filtered out for non-admin
// callers at this layer via includeAdminOnly.
const { query } = require('../../utils/db')
async function listForUser(discordId, { includeAdminOnly = false } = {}) {
const visClause = includeAdminOnly ? '' : "AND n.visibility = 'staff_only'"
return query(
`SELECT n.id, n.discord_user_id, n.author_user_id, n.author_tag,
n.body, n.visibility, n.created_at,
u.username AS author_username
FROM mod_notes n
LEFT JOIN users u ON u.id = n.author_user_id
WHERE n.discord_user_id = ? ${visClause}
ORDER BY n.id DESC`,
[discordId],
)
}
async function insert({ discordUserId, authorUserId = null, authorTag = null, body, visibility = 'staff_only' }) {
const res = await query(
`INSERT INTO mod_notes (discord_user_id, author_user_id, author_tag, body, visibility)
VALUES (?, ?, ?, ?, ?)`,
[discordUserId, authorUserId, authorTag, body, visibility],
)
return res.insertId
}
async function getById(id) {
const rows = await query(
`SELECT n.id, n.discord_user_id, n.author_user_id, n.author_tag,
n.body, n.visibility, n.created_at,
u.username AS author_username
FROM mod_notes n
LEFT JOIN users u ON u.id = n.author_user_id
WHERE n.id = ? LIMIT 1`,
[id],
)
return rows[0] || null
}
async function countForUser(discordId, { includeAdminOnly = false } = {}) {
const visClause = includeAdminOnly ? '' : "AND visibility = 'staff_only'"
const rows = await query(
`SELECT COUNT(*) AS c FROM mod_notes WHERE discord_user_id = ? ${visClause}`,
[discordId],
)
return Number(rows[0].c)
}
module.exports = { listForUser, insert, getById, countForUser }

View File

@@ -0,0 +1,18 @@
const modNotesDb = require('./modNotes.db')
async function listForUser(discordId, { includeAdminOnly = false } = {}) {
return modNotesDb.listForUser(discordId, { includeAdminOnly })
}
async function add({ discordUserId, author, body, visibility = 'staff_only' }) {
const id = await modNotesDb.insert({
discordUserId,
authorUserId: author ? author.id : null,
authorTag: author ? author.username : null,
body,
visibility,
})
return modNotesDb.getById(id)
}
module.exports = { listForUser, add }

View File

@@ -0,0 +1,117 @@
// Read-only access to the bot-owned moderation tables (mod_actions) for the
// admin moderation dashboard (Phase 6). These tables are normally owned by the
// bot process (bot/src/db.js) — see the comment in db/schema.sql — but they live
// in the same physical database, so the site reads them directly through the
// shared pool rather than round-tripping the bot over the internal API. This
// module NEVER writes them; all writes still belong to the bot.
//
// mod_actions is the single source of truth for ban/kick/mute/warn (every warn
// command also mirrors into `warnings`, so counting mod_actions avoids double
// counting). Accounts are correlated to Discord ids via user_identities
// (provider='discord', subject=<snowflake>), the same link the SSO flow writes.
const { query } = require('../../utils/db')
const TYPES = ['ban', 'kick', 'mute', 'warn']
// Per-type counts across three nested windows in a single scan. Boolean
// comparisons yield 1/0 in MariaDB, so SUM(created_at >= cutoff) counts the
// rows inside each window. Returns raw rows: [{ action_type, d1, d7, d30 }].
async function countsByWindow({ cutoff24h, cutoff7d, cutoff30d }) {
return query(
`SELECT action_type,
SUM(created_at >= ?) AS d1,
SUM(created_at >= ?) AS d7,
SUM(created_at >= ?) AS d30
FROM mod_actions
WHERE created_at >= ?
GROUP BY action_type`,
[cutoff24h, cutoff7d, cutoff30d, cutoff30d],
)
}
const ACTION_SELECT = `
SELECT ma.id, ma.guild_id, ma.action_type,
ma.target_user_id, ma.target_tag,
ma.staff_user_id, ma.staff_tag,
ma.reason, ma.duration_seconds, ma.created_at,
ui.user_id AS target_site_user_id,
u.username AS target_site_username
FROM mod_actions ma
LEFT JOIN user_identities ui
ON ui.provider = 'discord' AND ui.subject = ma.target_user_id
LEFT JOIN users u ON u.id = ui.user_id`
// Most-recent-first action feed, optionally filtered by type. limit/offset
// pagination matching the activity-log convention.
async function recentActions({ type = null, limit = 50, offset = 0 } = {}) {
const where = type ? 'WHERE ma.action_type = ?' : ''
const params = type ? [type, limit, offset] : [limit, offset]
return query(`${ACTION_SELECT} ${where} ORDER BY ma.id DESC LIMIT ? OFFSET ?`, params)
}
// Full action history for one Discord user, optionally filtered by type.
async function userActions(discordId, { type = null, limit = 50, offset = 0 } = {}) {
const where = type
? 'WHERE ma.target_user_id = ? AND ma.action_type = ?'
: 'WHERE ma.target_user_id = ?'
const params = type ? [discordId, type, limit, offset] : [discordId, limit, offset]
return query(`${ACTION_SELECT} ${where} ORDER BY ma.id DESC LIMIT ? OFFSET ?`, params)
}
// All-time per-type counts for one user.
async function userCounts(discordId) {
return query(
`SELECT action_type, COUNT(*) AS c FROM mod_actions
WHERE target_user_id = ? GROUP BY action_type`,
[discordId],
)
}
// Latest username snapshot the bot recorded for this Discord id (usernames drift).
async function latestTag(discordId) {
const rows = await query(
'SELECT target_tag FROM mod_actions WHERE target_user_id = ? ORDER BY id DESC LIMIT 1',
[discordId],
)
return rows[0] ? rows[0].target_tag : null
}
// Linked site account for a Discord id, if any (via user_identities).
async function linkedAccount(discordId) {
const rows = await query(
`SELECT u.id, u.username, u.role
FROM user_identities ui
JOIN users u ON u.id = ui.user_id
WHERE ui.provider = 'discord' AND ui.subject = ?
LIMIT 1`,
[discordId],
)
return rows[0] || null
}
// User-lookup: match a Discord id exactly, or a username snapshot (target_tag)
// by prefix, returning the most recently seen distinct targets. Powers the
// dashboard search box (usernames drift, so we search historical snapshots too).
async function searchTargets(term, { limit = 20 } = {}) {
return query(
`SELECT ma.target_user_id, MAX(ma.target_tag) AS target_tag,
COUNT(*) AS action_count, MAX(ma.created_at) AS last_seen
FROM mod_actions ma
WHERE ma.target_user_id = ? OR ma.target_tag LIKE ?
GROUP BY ma.target_user_id
ORDER BY last_seen DESC
LIMIT ?`,
[term, `${term}%`, limit],
)
}
module.exports = {
TYPES,
countsByWindow,
recentActions,
userActions,
userCounts,
latestTag,
linkedAccount,
searchTargets,
}

View File

@@ -0,0 +1,72 @@
// Business logic for the moderation dashboard: reshapes the raw mod_actions
// reads into the shapes the admin UI consumes, and annotates each action with
// whether it was an automated (bot) action. For a Discord bot the application_id
// IS the bot's user id, and the filter/spam pipeline records automated actions
// with staff_user_id = the bot user (see bot/src/discord/messageFilter.js), so
// staff_user_id === bot_config.application_id reliably flags automated actions
// without needing new columns on mod_actions.
const moderationDb = require('./moderation.db')
const botConfigDb = require('../botConfig/botConfig.db')
const { zeroCounts, annotate, reshapeWindows } = require('./moderation.pure')
const DAY_MS = 24 * 60 * 60 * 1000
async function botApplicationId() {
try {
const cfg = await botConfigDb.get()
return cfg ? cfg.application_id : null
} catch {
return null
}
}
// Counts by type across 24h / 7d / 30d windows for the overview tiles.
async function summary() {
const now = Date.now()
const cutoff24h = new Date(now - DAY_MS)
const cutoff7d = new Date(now - 7 * DAY_MS)
const cutoff30d = new Date(now - 30 * DAY_MS)
const rows = await moderationDb.countsByWindow({ cutoff24h, cutoff7d, cutoff30d })
return reshapeWindows(rows)
}
async function recent(opts) {
const appId = await botApplicationId()
return annotate(await moderationDb.recentActions(opts), appId)
}
async function userActions(discordId, opts) {
const appId = await botApplicationId()
return annotate(await moderationDb.userActions(discordId, opts), appId)
}
// Header data for the per-user history page: latest known tag, linked site
// account (if any), and all-time counts per action type.
async function userSummary(discordId) {
const [countRows, tag, linked] = await Promise.all([
moderationDb.userCounts(discordId),
moderationDb.latestTag(discordId),
moderationDb.linkedAccount(discordId),
])
const counts = zeroCounts()
let total = 0
for (const row of countRows) {
const c = Number(row.c) || 0
if (counts[row.action_type] !== undefined) counts[row.action_type] = c
total += c
}
return {
discord_user_id: discordId,
tag,
linked_account: linked,
counts,
total_actions: total,
}
}
async function search(term, opts) {
return moderationDb.searchTargets(term, opts)
}
module.exports = { summary, recent, userActions, userSummary, search }

View File

@@ -0,0 +1,39 @@
// Pure reshaping/annotation helpers for the moderation dashboard, deliberately
// free of any DB (or other side-effecting) imports so they can be unit-tested
// without opening a database pool. moderation.model re-exports these.
function zeroCounts() {
return { ban: 0, kick: 0, mute: 0, warn: 0 }
}
// Tag each action as automated (staff is the bot) and fold the joined
// user_identities columns into a linked_account object. The string coercion
// matters — snowflakes can arrive as number or string from different columns.
function annotate(rows, appId) {
return rows.map((r) => {
const isAutomated = appId != null && String(r.staff_user_id) === String(appId)
return {
...r,
is_automated: isAutomated,
linked_account: r.target_site_user_id
? { id: r.target_site_user_id, username: r.target_site_username }
: null,
}
})
}
// Fold the per-type window rows into the { windows: { '24h', '7d', '30d' } }
// shape the dashboard tiles consume, zero-filling any type with no rows.
function reshapeWindows(rows) {
const windows = { '24h': zeroCounts(), '7d': zeroCounts(), '30d': zeroCounts() }
for (const row of rows) {
const t = row.action_type
if (windows['24h'][t] === undefined) continue
windows['24h'][t] = Number(row.d1) || 0
windows['7d'][t] = Number(row.d7) || 0
windows['30d'][t] = Number(row.d30) || 0
}
return { windows }
}
module.exports = { zeroCounts, annotate, reshapeWindows }