Files
website/server/src/router/v1/admin/discordBot.controller.js
wtclaude 12d50fd615
All checks were successful
PR Checks / bot-install (pull_request) Successful in 13s
PR Checks / client-build (pull_request) Successful in 22s
PR Checks / server-tests (pull_request) Successful in 11m13s
chore(quality): resolve SonarQube code smells across website
Clears the 124 CODE_SMELL findings from the SonarQube scan (server, client,
and bot). All changes are behaviour-preserving refactors — no route, protocol,
schema, or config changes — verified against the full server (381) and client
(43) test suites plus a clean client build.

By rule:
- S3776 (20, cognitive complexity): extract helpers/handlers so each function
  drops under the threshold — shard model upsert builders, page/wiki update,
  block validation, notification stream mapping (dispatch table), SSO mobile
  login, shard ingest deps, uo-link socket backfill/connect, the bot slash-
  command dispatchers + discord manager, and the Shard/UserDetail/HeroEditor/
  CharacterStats React components.
- S4624 (34, nested template literals): pull inner templates into locals /
  a withQs() helper; rewrite shardEvents.describe() as a formatter table.
- S3358 (35, nested ternaries): lift to if/else vars, lookup maps, small
  components, or guarded JSX expressions.
- S6479 (12, array-index React keys): key by stable content instead of index
  (two in-editor lists left as-is; index matches their by-index edit model).
- S6353 (6): [0-9]/[^0-9] -> \d/\D.  S125 (5): reword state-shape comments that
  parsed as code.  S3800/S3782 (botScore): JSDoc-type PATH_WEIGHTS tuples.
- S6481 (2): memoize Auth/Site context values (and SiteContext brand).
- S4144: dedupe HeroEditor upload handler into useImageUpload().
- S1126 (2), S6035, S5869 (redundant A-Z under /i), S5843 (town-name regex ->
  prefix list): assorted one-liners.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-21 04:35:39 -05:00

98 lines
4.2 KiB
JavaScript

// ── 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}` },
})
return res.status !== 401
} 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 }