From b11ae1dfa8f78a9511309bfadc38a86a8b8b85f0 Mon Sep 17 00:00:00 2001 From: Snipzil Date: Tue, 20 Oct 2026 22:13:50 -0400 Subject: [PATCH] feat: add unified Discord bot and dashboard --- .github/scripts/invariants.js | 35 +- README.md | 10 + lib/discordbot.js | 865 ++++++++++++++++++++++++++++++++++ lib/http.js | 7 + lib/modlog.js | 22 +- lib/modpanel.js | 87 +++- lib/panel.js | 56 +++ lib/reports.js | 21 +- lib/roles.js | 3 +- lib/world.js | 25 + package-lock.json | 333 +++++++++++++ package.json | 3 + public/admin.html | 252 ++++++++++ server.js | 3 + 14 files changed, 1708 insertions(+), 14 deletions(-) create mode 100644 lib/discordbot.js create mode 100644 package-lock.json diff --git a/.github/scripts/invariants.js b/.github/scripts/invariants.js index 3ffaea3..bd44d52 100644 --- a/.github/scripts/invariants.js +++ b/.github/scripts/invariants.js @@ -4,7 +4,8 @@ // what the security audit of 2026-10-16 found true of this server, checked on // every push so that it stays true (or is changed on purpose): // -// - it uses no npm packages, so there is no supply chain to break into +// - it has only the one pinned Discord gateway dependency needed by the +// optional staff bot; additions are refused to keep the supply chain small // - the server code starts no other programs and runs no generated code // - the server code names no web address outside .github/allowed-hosts.json // - no private key, certificate key or .env file is committed @@ -22,17 +23,35 @@ const tracked = execFileSync("git", ["ls-files", "-z"], {encoding: "utf8"}).spli const problems = []; const fail = (file, message) => problems.push({file, message}); -// no npm packages +// The server stayed dependency-free until the optional Discord staff bot. Its +// maintained gateway/components implementation is pinned exactly and captured +// in package-lock.json; no other package is permitted without deliberately +// extending this allowlist and its review surface. const pkg = JSON.parse(fs.readFileSync("package.json", "utf8")); +const ALLOWED_DEPENDENCIES = {dependencies: {"discord.js": "14.26.4"}}; for (const field of ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies", "bundledDependencies"]) { - if (pkg[field] && Object.keys(pkg[field]).length) { - fail("package.json", `${field} is not empty. The server has no npm packages on purpose; if one is really needed, change this check in the same pull request and say why.`); + const actual = pkg[field] || {}; + const allowedDependencies = ALLOWED_DEPENDENCIES[field] || {}; + if (JSON.stringify(Object.keys(actual).sort().map(name => [name, actual[name]])) !== JSON.stringify(Object.keys(allowedDependencies).sort().map(name => [name, allowedDependencies[name]]))) { + fail("package.json", `${field} differs from its approved dependency allowlist. Keep dependencies empty except for the pinned Discord staff-bot gateway, or deliberately update this check and explain why.`); } } -for (const lock of ["package-lock.json", "yarn.lock", "pnpm-lock.yaml"]) { - if (tracked.includes(lock)) { - fail(lock, "a lockfile means npm packages; see package.json above."); +for (const lock of ["yarn.lock", "pnpm-lock.yaml"]) { + if (tracked.includes(lock)) fail(lock, "use the reviewed package-lock.json; alternate package-manager lockfiles are not allowed."); +} +if (fs.existsSync("package-lock.json")) { + try { + const lock = JSON.parse(fs.readFileSync("package-lock.json", "utf8")); + if (lock.lockfileVersion !== 3 || lock.packages?.[""]?.dependencies?.["discord.js"] !== "14.26.4") { + fail("package-lock.json", "must be the npm v3 lockfile for the pinned discord.js@14.26.4 dependency."); + } } + catch { + fail("package-lock.json", "is not a readable npm lockfile."); + } +} +else { + fail("package-lock.json", "is required to review the pinned Discord bot dependency."); } // the server's own code: what the game server runs @@ -88,4 +107,4 @@ if (problems.length) { } process.exit(1); } -console.log(`${serverCode.length} server files and ${tracked.length} tracked files checked: no packages, no program starts or generated code, no unlisted hosts, no keys, everything parses`); +console.log(`${serverCode.length} server files and ${tracked.length} tracked files checked: only the pinned Discord bot dependency, no program starts or generated code, no unlisted hosts, no keys, everything parses`); diff --git a/README.md b/README.md index 93f003c..6dcfa75 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,16 @@ Burrow is a private server for AJ Classic. Set `AJ_RECOVERY_MAIL_URL` and `AJ_RECOVERY_MAIL_TOKEN` to an HTTPS mail-relay or transactional-email webhook. Burrow posts `{to, subject, text}` with a Bearer token. Until both are configured, email recovery intentionally does not issue a usable reset link. New web sign-ups are asked for a recovery email; password and 2FA recovery require the one-time link sent there. +## Discord staff bot + +Set `AJ_DISCORD_BOT_TOKEN` and `AJ_DISCORD_GUILD_ID` to enable Burrow's Discord bot. It registers `/burrow status|player|reports|staff|announce`, `/moderate warn|silence|unsilence|kick|ban|unban`, and Discord-server moderation commands `/discord timeout|untimeout|kick|ban|unban|purge`. A Discord user must first link their account through Burrow's existing Discord sign-in and hold active Burrow staff status with 2FA; every command then follows the same role permissions, staff-rank safeguards, actions, and audit log as the moderator panel. Discord-native actions cannot target active linked Burrow staff accounts and also require the bot's Discord role to have the matching server permission. + +`AJ_DISCORD_REPORTS_CHANNEL_ID` optionally posts each new in-game report with a **Mark handled** button. `AJ_DISCORD_STATUS_CHANNEL_ID` optionally maintains a public live-status card. Set `AJ_DISCORD_GAME_LOGS_CHANNEL_ID` for player sign-in/sign-out logs, `AJ_DISCORD_MOD_LOGS_CHANNEL_ID` for the full moderation audit trail (web panel, in-game staff commands, admin actions, and Discord moderation), and `AJ_DISCORD_BOT_LOGS_CHANNEL_ID` for Discord command/button audit events. Game logs deliberately omit IPs, device IDs, auth tokens, and chat text. All bot replies and notifications use Discord Components V2 (containers and text displays), not legacy message content or embeds. + +The owner dashboard's **Discord** tab can start, stop, reconnect, and synchronize the bot; edit notification-channel IDs, the GitHub repository, public status card, security rules, support-ticket settings, and welcome/goodbye notices; and publish the public card immediately. Environment values supply the initial channel configuration. The bot token, guild ID, and GitHub webhook secret deliberately stay in the server environment rather than in the dashboard database. + +For GitHub update cards, set `AJ_GITHUB_REPOSITORY` to `owner/repository`, `AJ_GITHUB_WEBHOOK_SECRET`, and `AJ_DISCORD_UPDATES_CHANNEL_ID`. Then add a GitHub webhook for `https://your-public-burrow-host/discord/github`, choose `application/json`, use the same secret, and subscribe to **Pushes**. Signed pushes appear as polished Components V2 cards with commit summaries and a GitHub compare button; commits that change the Flash client or client assets are labelled **Game update**, while other pushes are **Server update**. + # Security An independent security audit by a Strawberry Jam contributor, who is not part of the Burrow team, found no malware in the Burrow client or server (client v1.2.0, server as of 17 October 2026). Every file in every installer was checked against its source and against the official Electron, NSIS and Adobe Flash releases. The report also lists the weaknesses found, with fixes, and every check can be repeated by anyone. diff --git a/lib/discordbot.js b/lib/discordbot.js new file mode 100644 index 0000000..f053e20 --- /dev/null +++ b/lib/discordbot.js @@ -0,0 +1,865 @@ +"use strict"; + +// Burrow's Discord control surface. It is intentionally a thin client over +// lib/modpanel.js: Discord proves who clicked a command, and the panel then +// proves that their linked Burrow account is still active staff and applies +// its usual permission and rank rules. There is no Discord-only staff list. + +const { + ActionRowBuilder, + ButtonBuilder, + ButtonStyle, + ChannelType, + Client, + GatewayIntentBits, + MessageFlags, + PermissionFlagsBits, + SlashCommandBuilder, +} = require("discord.js"); +const crypto = require("crypto"); +const accounts = require("./accounts.js"); +const config = require("../config.js"); +const modpanel = require("./modpanel.js"); +const modlog = require("./modlog.js"); +const reports = require("./reports.js"); +const world = require("./world.js"); +const {logText} = require("./logtext.js"); + +const COMPONENTS_V2 = MessageFlags.IsComponentsV2; +const EPHEMERAL = MessageFlags.Ephemeral; +const STATUS_MESSAGE_SETTING = "discordBotStatusMessage"; +const STATUS_TITLE_SETTING = "discordBotStatusTitle"; +const STATUS_NOTE_SETTING = "discordBotStatusNote"; +const STATUS_EVERY_MS = 5 * 60000; +const REPORT_BUTTON_PREFIX = "burrow:report:"; +const MAX_GITHUB_WEBHOOK_BYTES = 512 * 1024; +const CONFIG_SETTING_PREFIX = "discordBotConfig:"; +const SECURITY_SETTING = "discordBotSecurity"; +const COMMUNITY_SETTING = "discordBotCommunity"; +const CHANNELS = [ + ["reportsChannelId", "Reports"], + ["statusChannelId", "Public status"], + ["gameLogsChannelId", "In-game activity"], + ["moderationLogsChannelId", "Moderation audit"], + ["botLogsChannelId", "Discord bot audit"], + ["updatesChannelId", "GitHub updates"], +]; +const MANAGED_CONFIG = [...CHANNELS.map(([key]) => key), "githubRepository"]; +let loadedDashboardConfig = false; +let securityConfigLoaded = false; +let securityConfig = null; +let communityConfig = null; +let communityConfigLoaded = false; +const recentMessages = new Map(); +const recentJoins = []; +let lastRaidAlertAt = 0; + +// Text Displays accept markdown. Keep player-provided strings readable while +// ensuring a report cannot ping a Discord role or user. +const safe = (value, max = 1000) => String(value === undefined || value === null ? "" : value) + .replace(/@/g, "@\u200b").replace(/`/g, "'").replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, max); + +const statusSettings = () => ({ + title: safe(accounts.setting(STATUS_TITLE_SETTING) || "Burrow status", 80) || "Burrow status", + note: safe(accounts.setting(STATUS_NOTE_SETTING) || "", 500), +}); + +const setStatusSettings = ({title, note}) => { + const next = { + title: safe(title || "Burrow status", 80) || "Burrow status", + note: safe(note || "", 500), + }; + accounts.setSetting(STATUS_TITLE_SETTING, next.title); + accounts.setSetting(STATUS_NOTE_SETTING, next.note); + return next; +}; + +const securitySettings = () => { + if (securityConfigLoaded) return {...securityConfig}; + const defaults = {enabled: false, blockInvites: true, blockedWords: [], spamLimit: 6, raidJoinLimit: 12}; + try { + const saved = JSON.parse(accounts.setting(SECURITY_SETTING) || "{}"); + const words = Array.isArray(saved.blockedWords) ? saved.blockedWords.map(word => safe(word, 60).toLowerCase()).filter(Boolean).slice(0, 50) : []; + securityConfig = { + enabled: saved.enabled === true, + blockInvites: saved.blockInvites !== false, + blockedWords: [...new Set(words)], + spamLimit: Number.isInteger(saved.spamLimit) && saved.spamLimit >= 2 && saved.spamLimit <= 20 ? saved.spamLimit : defaults.spamLimit, + raidJoinLimit: Number.isInteger(saved.raidJoinLimit) && saved.raidJoinLimit >= 3 && saved.raidJoinLimit <= 100 ? saved.raidJoinLimit : defaults.raidJoinLimit, + }; + } + catch { + securityConfig = defaults; + } + securityConfigLoaded = true; + return {...securityConfig}; +}; + +const updateSecuritySettings = values => { + const words = String(values.blockedWords || "").split(/\r?\n|,/) + .map(word => safe(word, 60).toLowerCase()).filter(Boolean).slice(0, 50); + const spamLimit = Number(values.spamLimit); + const raidJoinLimit = Number(values.raidJoinLimit); + if (!Number.isInteger(spamLimit) || spamLimit < 2 || spamLimit > 20 || !Number.isInteger(raidJoinLimit) || raidJoinLimit < 3 || raidJoinLimit > 100) { + return {error: "Spam limit must be 2 to 20 and raid join limit must be 3 to 100."}; + } + securityConfig = {enabled: values.enabled === true, blockInvites: values.blockInvites === true, + blockedWords: [...new Set(words)], spamLimit, raidJoinLimit}; + securityConfigLoaded = true; + accounts.setSetting(SECURITY_SETTING, JSON.stringify(securityConfig)); + return {ok: "Discord security settings saved. Reconnect the bot to apply message and join monitoring.", security: securitySettings()}; +}; + +const communitySettings = () => { + if (communityConfigLoaded) return {...communityConfig}; + try { + const saved = JSON.parse(accounts.setting(COMMUNITY_SETTING) || "{}"); + communityConfig = {ticketCategoryId: channelId(saved.ticketCategoryId) || "", ticketStaffRoleId: channelId(saved.ticketStaffRoleId) || "", + welcomeChannelId: channelId(saved.welcomeChannelId) || "", welcomeMessage: safe(saved.welcomeMessage || "Welcome {user} to {server}!", 500), + goodbyeChannelId: channelId(saved.goodbyeChannelId) || "", goodbyeMessage: safe(saved.goodbyeMessage || "Goodbye {user}.", 500)}; + } + catch { communityConfig = {ticketCategoryId: "", ticketStaffRoleId: "", welcomeChannelId: "", welcomeMessage: "Welcome {user} to {server}!", goodbyeChannelId: "", goodbyeMessage: "Goodbye {user}."}; } + communityConfigLoaded = true; + return {...communityConfig}; +}; + +const updateCommunitySettings = values => { + const current = communitySettings(); + const next = {...current}; + for (const key of ["ticketCategoryId", "ticketStaffRoleId", "welcomeChannelId", "goodbyeChannelId"]) { + const id = channelId(values[key]); + if (id === null) return {error: "Discord channel, category, and role IDs must contain only 5 to 25 digits."}; + next[key] = id; + } + next.welcomeMessage = safe(values.welcomeMessage || "", 500); + next.goodbyeMessage = safe(values.goodbyeMessage || "", 500); + communityConfig = next; + communityConfigLoaded = true; + accounts.setSetting(COMMUNITY_SETTING, JSON.stringify(next)); + return {ok: "Community and ticket settings saved.", community: communitySettings()}; +}; + +// Non-secret routing settings are owner-controlled in the dashboard. The bot +// token and webhook secret deliberately remain environment-only, so a copied +// database or dashboard session cannot disclose them. +const loadDashboardConfig = () => { + if (loadedDashboardConfig) return; + for (const key of MANAGED_CONFIG) { + const saved = accounts.setting(`${CONFIG_SETTING_PREFIX}${key}`); + if (saved !== null) config.discord[key] = saved; + } + loadedDashboardConfig = true; +}; + +const channelId = value => { + const id = String(value === undefined || value === null ? "" : value).trim(); + return id === "" || /^\d{5,25}$/.test(id) ? id : null; +}; + +const updateDashboardConfig = values => { + loadDashboardConfig(); + const previousStatusChannelId = config.discord.statusChannelId || ""; + const next = {}; + for (const [key] of CHANNELS) { + const id = channelId(values[key]); + if (id === null) return {error: "Discord channel IDs must contain only 5 to 25 digits."}; + next[key] = id; + } + const repository = String(values.githubRepository === undefined || values.githubRepository === null ? "" : values.githubRepository).trim(); + if (repository && !/^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}\/[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$/.test(repository)) { + return {error: "GitHub repository must use the form owner/repository."}; + } + next.githubRepository = repository; + for (const key of MANAGED_CONFIG) { + config.discord[key] = next[key]; + accounts.setSetting(`${CONFIG_SETTING_PREFIX}${key}`, next[key]); + } + if (next.statusChannelId !== previousStatusChannelId) { + accounts.setSetting(STATUS_MESSAGE_SETTING, ""); + } + return {ok: "Discord routing settings saved.", configuration: dashboardStatus()}; +}; + +const duration = seconds => { + if (seconds === -1) return "permanent"; + if (!seconds) return "none"; + const hours = Math.ceil(Number(seconds) / 3600); + return `${hours} hour${hours === 1 ? "" : "s"}`; +}; + +// Components V2 means every visible response—success, refusal, report alert +// and status card—uses a Container and Text Displays. Never add `content` or +// `embeds` to these payloads: Discord ignores them for Components V2. +const card = ({title, sections = [], tone = 0x5865f2, ephemeral = false, components = []}) => ({ + flags: COMPONENTS_V2 | (ephemeral ? EPHEMERAL : 0), + allowedMentions: {parse: []}, + components: [{ + type: 17, // Container + accent_color: tone, + components: [ + {type: 10, content: `## ${safe(title, 160)}`}, // Text Display + ...sections.filter(Boolean).slice(0, 8).flatMap((section, index) => [ + ...(index ? [{type: 14, divider: true, spacing: 1}] : []), // Separator + {type: 10, content: safe(section, 1800)}, + ]), + ...components, + ], + }], +}); + +const success = (title, sections, ephemeral = true) => card({title, sections, tone: 0x57f287, ephemeral}); +const warning = (message, ephemeral = true) => card({title: "Burrow", sections: [message], tone: 0xfee75c, ephemeral}); +const failure = (message, ephemeral = true) => card({title: "Burrow", sections: [message], tone: 0xed4245, ephemeral}); + +const commands = [ + new SlashCommandBuilder().setName("burrow").setDescription("View Burrow server and player information") + .addSubcommand(command => command.setName("status").setDescription("Show the live Burrow server status")) + .addSubcommand(command => command.setName("player").setDescription("Look up a Burrow player") + .addStringOption(option => option.setName("username").setDescription("Burrow username").setRequired(true))) + .addSubcommand(command => command.setName("reports").setDescription("Show open player reports")) + .addSubcommand(command => command.setName("staff").setDescription("Show Burrow staff")) + .addSubcommand(command => command.setName("announce").setDescription("Send an announcement to everyone playing") + .addStringOption(option => option.setName("message").setDescription("Announcement shown in-game").setRequired(true).setMaxLength(300))), + new SlashCommandBuilder().setName("moderate").setDescription("Moderate Burrow through your linked staff account") + .addSubcommand(command => command.setName("warn").setDescription("Warn a player") + .addStringOption(option => option.setName("username").setDescription("Burrow username").setRequired(true)) + .addStringOption(option => option.setName("reason").setDescription("Warning reason, e.g. behavior or custom").setRequired(true)) + .addStringOption(option => option.setName("note").setDescription("Required explanation for a custom warning"))) + .addSubcommand(command => command.setName("silence").setDescription("Stop a player from chatting") + .addStringOption(option => option.setName("username").setDescription("Burrow username").setRequired(true)) + .addIntegerOption(option => option.setName("hours").setDescription("Whole hours; 0 means until lifted").setRequired(true).setMinValue(0).setMaxValue(87600))) + .addSubcommand(command => command.setName("unsilence").setDescription("Let a player chat again") + .addStringOption(option => option.setName("username").setDescription("Burrow username").setRequired(true))) + .addSubcommand(command => command.setName("kick").setDescription("Disconnect an online player") + .addStringOption(option => option.setName("username").setDescription("Burrow username").setRequired(true))) + .addSubcommand(command => command.setName("ban").setDescription("Ban a player") + .addStringOption(option => option.setName("username").setDescription("Burrow username").setRequired(true)) + .addIntegerOption(option => option.setName("hours").setDescription("Whole hours; 0 means permanent").setRequired(true).setMinValue(0).setMaxValue(87600)) + .addStringOption(option => option.setName("reason").setDescription("Why this player is being banned").setRequired(true))) + .addSubcommand(command => command.setName("unban").setDescription("Lift a player's Burrow ban") + .addStringOption(option => option.setName("username").setDescription("Burrow username").setRequired(true))), + new SlashCommandBuilder().setName("discord").setDescription("Moderate this Discord server through Burrow staff permissions") + .addSubcommand(command => command.setName("timeout").setDescription("Temporarily silence a Discord member") + .addUserOption(option => option.setName("member").setDescription("Discord member").setRequired(true)) + .addIntegerOption(option => option.setName("hours").setDescription("Whole hours, up to 28 days").setRequired(true).setMinValue(1).setMaxValue(672)) + .addStringOption(option => option.setName("reason").setDescription("Why this member is being timed out").setMaxLength(300))) + .addSubcommand(command => command.setName("untimeout").setDescription("Remove a Discord member timeout") + .addUserOption(option => option.setName("member").setDescription("Discord member").setRequired(true)) + .addStringOption(option => option.setName("reason").setDescription("Why the timeout is being removed").setMaxLength(300))) + .addSubcommand(command => command.setName("kick").setDescription("Remove a Discord member from this server") + .addUserOption(option => option.setName("member").setDescription("Discord member").setRequired(true)) + .addStringOption(option => option.setName("reason").setDescription("Why this member is being removed").setMaxLength(300))) + .addSubcommand(command => command.setName("ban").setDescription("Ban a Discord member from this server") + .addUserOption(option => option.setName("member").setDescription("Discord member").setRequired(true)) + .addStringOption(option => option.setName("reason").setDescription("Why this member is being banned").setMaxLength(300))) + .addSubcommand(command => command.setName("unban").setDescription("Lift a Discord server ban") + .addStringOption(option => option.setName("user_id").setDescription("Discord user ID").setRequired(true).setMinLength(5).setMaxLength(25)) + .addStringOption(option => option.setName("reason").setDescription("Why the ban is being removed").setMaxLength(300))) + .addSubcommand(command => command.setName("purge").setDescription("Delete recent messages in this channel") + .addIntegerOption(option => option.setName("amount").setDescription("Messages to delete (1 to 100)").setRequired(true).setMinValue(1).setMaxValue(100)) + .addStringOption(option => option.setName("reason").setDescription("Why messages are being removed").setMaxLength(300))), + new SlashCommandBuilder().setName("ticket").setDescription("Open or manage a private support ticket") + .addSubcommand(command => command.setName("open").setDescription("Open a private support ticket") + .addStringOption(option => option.setName("subject").setDescription("What you need help with").setRequired(true).setMaxLength(80))) + .addSubcommand(command => command.setName("close").setDescription("Close this support ticket")), +].map(command => command.toJSON()); + +const actorFor = interaction => modpanel.discordBot.actor(interaction.user.id); + +const reportButton = report => new ActionRowBuilder().addComponents( + new ButtonBuilder().setCustomId(`${REPORT_BUTTON_PREFIX}${report.id}:handled`).setLabel("Mark handled").setStyle(ButtonStyle.Success), +).toJSON(); + +const reportCard = (report, {handled = false, ephemeral = false} = {}) => card({ + title: handled ? `Report #${report.id} handled` : `Report #${report.id}`, + tone: handled ? 0x57f287 : 0xfee75c, + ephemeral, + sections: [ + `**${safe(report.reporter, 40)}** reported **${safe(report.target, 40)}**\n${safe(report.reason, 200)}`, + report.detail ? `**Details**\n${safe(report.detail, 500)}` : "*No additional details.*", + report.room ? `Room: \`${safe(report.room, 100)}\`` : "", + ], + components: handled ? [] : [{type: 14, divider: true, spacing: 1}, reportButton(report)], +}); + +const playerCard = player => success(`Player: ${player.username}`, [ + `**Status**\n${player.online ? `Online${player.room ? ` in ${safe(player.room, 100)}` : ""}` : "Offline"}\nRole: ${player.role || "Player"}`, + `**Moderation**\nBan: ${duration(player.banned)}\nSilence: ${duration(player.silenced)}\nWarnings: ${player.warnings}\nOpen reports: ${player.openReports}`, + player.discord ? `**Discord**\n${safe(player.discord, 80)}` : "", +]); + +const statusCard = status => { + const settings = statusSettings(); + return card({title: settings.title, tone: 0x5865f2, sections: [ + settings.note ? `**Status message**\n${settings.note}` : "", + `**Online**\n${status.players} players in ${status.rooms} room${status.rooms === 1 ? "" : "s"}`, + `**Moderation queue**\n${status.reports} open report${status.reports === 1 ? "" : "s"}`, + `**Server**\nUptime: \nMemory: ${status.memoryMb} MB`, + ]}); +}; + +const staffCard = staff => success("Burrow staff", staff.length + ? [staff.map(member => `**${safe(member.username, 40)}** — ${safe(member.role, 30)}${member.twoStep ? " · 2FA" : ""}`).join("\n")] + : ["No active Burrow staff accounts."]); + +const inConfiguredGuild = interaction => interaction.guildId === config.discord.guildId; + +const replyResult = async (interaction, result, title = "Burrow") => { + if (result.error) { + await interaction.editReply(failure(result.error)); + return; + } + await interaction.editReply(success(title, [result.ok, result.detail].filter(Boolean))); +}; + +const handleBurrow = async interaction => { + const actor = actorFor(interaction); + const subcommand = interaction.options.getSubcommand(); + if (subcommand === "status") { + const result = modpanel.discordBot.status(actor); + await interaction.editReply(result.error ? failure(result.error) : {...statusCard(result), flags: COMPONENTS_V2 | EPHEMERAL}); + return; + } + if (subcommand === "player") { + const result = modpanel.discordBot.player(actor, interaction.options.getString("username", true)); + await interaction.editReply(result.error ? failure(result.error) : {...playerCard(result.player), flags: COMPONENTS_V2 | EPHEMERAL}); + return; + } + if (subcommand === "staff") { + const result = modpanel.discordBot.staff(actor); + await interaction.editReply(result.error ? failure(result.error) : staffCard(result.staff)); + return; + } + if (subcommand === "announce") { + await replyResult(interaction, modpanel.discordBot.announce(actor, interaction.options.getString("message", true)), "In-game announcement"); + return; + } + const result = modpanel.discordBot.reports(actor); + if (result.error) { + await interaction.editReply(failure(result.error)); + return; + } + const shown = result.reports.slice(0, 5); + await interaction.editReply(success("Open reports", [ + `${result.open} open report${result.open === 1 ? "" : "s"}.`, + shown.length ? shown.map(report => `#${report.id} — **${safe(report.target, 40)}** — ${safe(report.reason, 100)}`).join("\n") : "No reports are waiting.", + ])); +}; + +const handleModerate = async interaction => { + const actor = actorFor(interaction); + const subcommand = interaction.options.getSubcommand(); + const username = interaction.options.getString("username", true); + const fields = {action: subcommand}; + if (subcommand === "warn") { + fields.reason = interaction.options.getString("reason", true); + fields.note = interaction.options.getString("note") || ""; + } + if (subcommand === "silence" || subcommand === "ban") { + fields.hours = interaction.options.getInteger("hours", true); + } + if (subcommand === "ban") { + fields.reason = interaction.options.getString("reason", true); + } + await replyResult(interaction, modpanel.discordBot.act(actor, username, fields), `Moderation: ${subcommand}`); +}; + +const nativeDiscordPermission = action => ({ + timeout: "chat.silence", + untimeout: "chat.silence", + kick: "player.kick", + ban: "player.ban", + unban: "player.ban", + purge: "player.kick", +})[action] || ""; + +const handleDiscordModeration = async interaction => { + const actor = actorFor(interaction); + const action = interaction.options.getSubcommand(); + const refused = modpanel.discordBot.authorize(actor, nativeDiscordPermission(action)); + if (refused) { + await interaction.editReply(failure(refused.error)); + return; + } + const reason = safe(interaction.options.getString("reason") || `Burrow staff action by ${actor.username}`, 300); + const user = action === "unban" ? null : interaction.options.getUser("member", true); + if (user && modpanel.discordBot.actor(user.id)) { + await interaction.editReply(failure("Discord-native moderation cannot target an active linked Burrow staff account.")); + return; + } + try { + let detail = ""; + let target = user ? user.username : interaction.options.getString("user_id", true); + if (action === "timeout" || action === "untimeout" || action === "kick") { + const member = await interaction.guild.members.fetch(user.id); + if (action === "timeout") { + const hours = interaction.options.getInteger("hours", true); + await member.timeout(hours * 3600000, reason); + detail = `${hours} hour${hours === 1 ? "" : "s"}`; + } + else if (action === "untimeout") { + await member.timeout(null, reason); + } + else { + await member.kick(reason); + } + } + else if (action === "ban") { + await interaction.guild.members.ban(user.id, {reason, deleteMessageSeconds: 0}); + } + else if (action === "unban") { + if (!/^\d{5,25}$/.test(target)) throw new Error("bad_user_id"); + await interaction.guild.members.unban(target, reason); + } + else if (action === "purge") { + const amount = interaction.options.getInteger("amount", true); + if (!interaction.channel || !interaction.channel.isTextBased() || typeof interaction.channel.bulkDelete !== "function") throw new Error("not_text_channel"); + const deleted = await interaction.channel.bulkDelete(amount, true); + detail = `${deleted.size} message${deleted.size === 1 ? "" : "s"}`; + target = "this channel"; + } + else throw new Error("unknown_action"); + modlog.record(actor.username, `Discord ${action}`, target, detail || reason); + await interaction.editReply(success(`Discord ${action}`, [`${safe(target, 80)} — ${detail || "completed"}.`].concat(reason ? [`Reason: ${reason}`] : []))); + } + catch (err) { + if (err.message === "bad_user_id") { + await interaction.editReply(failure("Enter a valid Discord user ID.")); + return; + } + console.log(`[discord-bot] Discord ${action} failed: ${logText(err.message)}`); + await interaction.editReply(failure("Discord could not complete that action. Check the bot permission and role position.")); + } +}; + +const ticketOwner = channel => (channel && /^burrow-ticket:(\d{5,25})$/.exec(channel.topic || "") || [])[1] || ""; + +const handleTicket = async interaction => { + const action = interaction.options.getSubcommand(); + const settings = communitySettings(); + if (action === "open") { + if (!settings.ticketCategoryId || !settings.ticketStaffRoleId) { + await interaction.editReply(failure("Tickets are not configured. Ask an owner to set the ticket category and staff role in the Discord dashboard.")); + return; + } + const subject = safe(interaction.options.getString("subject", true), 80); + const channel = await interaction.guild.channels.create({ + name: `ticket-${interaction.user.id}`, + type: ChannelType.GuildText, + parent: settings.ticketCategoryId, + topic: `burrow-ticket:${interaction.user.id}`, + permissionOverwrites: [ + {id: interaction.guild.roles.everyone.id, deny: [PermissionFlagsBits.ViewChannel]}, + {id: interaction.user.id, allow: [PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages, PermissionFlagsBits.ReadMessageHistory]}, + {id: settings.ticketStaffRoleId, allow: [PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages, PermissionFlagsBits.ReadMessageHistory]}, + {id: client.user.id, allow: [PermissionFlagsBits.ViewChannel, PermissionFlagsBits.SendMessages, PermissionFlagsBits.ManageChannels, PermissionFlagsBits.ReadMessageHistory]}, + ], + }).catch(() => null); + if (!channel) { + await interaction.editReply(failure("Discord could not open the ticket. Check the category, staff role, and bot channel permissions.")); + return; + } + await channel.send(card({title: "Support ticket", tone: 0x5865f2, sections: [`Opened by **${safe(interaction.user.username, 80)}**\nSubject: ${subject}`, "A staff member will reply here. Use `/ticket close` when this is resolved."]})); + await interaction.editReply(success("Ticket opened", [`Your private ticket: ${channel}`])); + return; + } + const owner = ticketOwner(interaction.channel); + const staff = actorFor(interaction); + if (!owner || (owner !== interaction.user.id && !staff)) { + await interaction.editReply(failure("Only the ticket opener or linked Burrow staff can close this ticket.")); + return; + } + await interaction.channel.setName(`closed-${interaction.channel.name}`.slice(0, 100)).catch(() => {}); + if (owner) await interaction.channel.permissionOverwrites.edit(owner, {ViewChannel: false}).catch(() => {}); + modlog.record(staff ? staff.username : interaction.user.username, "Discord ticket closed", interaction.channel.name); + await interaction.editReply(success("Ticket closed", ["The opener can no longer view this channel. Staff retain it for the support record."])); +}; + +const handleButton = async interaction => { + const match = new RegExp(`^${REPORT_BUTTON_PREFIX.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(\\d+):handled$`).exec(interaction.customId); + if (!match) { + return false; + } + if (!inConfiguredGuild(interaction)) { + await interaction.reply(failure("This control belongs to another Discord server.")).catch(() => {}); + return true; + } + const result = modpanel.discordBot.handleReport(actorFor(interaction), Number(match[1])); + if (result.error) { + await interaction.reply(failure(result.error)).catch(() => {}); + return true; + } + await interaction.update(success(`Report #${Number(match[1])} handled`, [result.ok], false)).catch(() => {}); + return true; +}; + +let client = null; +let statusTimer = null; +let unsubscribeReports = null; +let unsubscribeGameActivity = null; +let unsubscribeModeration = null; +let securityGatewayOn = false; + +const channelFor = async id => { + if (!id || !client || !client.isReady()) return null; + const channel = await client.channels.fetch(id).catch(() => null); + return channel && channel.isTextBased() ? channel : null; +}; + +const postCard = async (channelId, payload, label) => { + const channel = await channelFor(channelId); + if (channel) { + await channel.send(payload).catch(err => console.log(`[discord-bot] ${label} failed: ${logText(err.message)}`)); + } +}; + +const publishStatus = async () => { + const channel = await channelFor(config.discord.statusChannelId); + if (!channel) return {error: "The public status channel is not configured or the Discord bot is not connected."}; + const payload = statusCard({players: 0, rooms: 0, reports: reports.openCount(), uptimeSeconds: Math.floor(process.uptime()), memoryMb: Math.round(process.memoryUsage().rss / 1048576)}); + // The public status card needs no staff actor; it exposes only aggregate + // counts. Store its message id in the server database so restarts edit it. + const saved = accounts.setting(STATUS_MESSAGE_SETTING); + const existing = saved && await channel.messages.fetch(saved).catch(() => null); + if (existing) { + const updated = await existing.edit(payload).then(() => true).catch(err => { + console.log(`[discord-bot] status update failed: ${logText(err.message)}`); + return false; + }); + return updated ? {ok: "The public status card was updated."} : {error: "Discord could not update the public status card."}; + } + const message = await channel.send(payload).catch(err => { + console.log(`[discord-bot] status post failed: ${logText(err.message)}`); + return null; + }); + if (!message) return {error: "Discord could not post the public status card."}; + accounts.setSetting(STATUS_MESSAGE_SETTING, message.id); + return {ok: "The public status card was posted."}; +}; + +const notifyReport = async report => { + await postCard(config.discord.reportsChannelId, reportCard(report), "report notification"); +}; + +const notifyGameActivity = async entry => { + const minutes = Math.max(1, Math.ceil((entry.playedSeconds || 0) / 60)); + const played = entry.type === "logout" ? `\nSession: ${minutes} minute${minutes === 1 ? "" : "s"}` : ""; + await postCard(config.discord.gameLogsChannelId, card({ + title: "In-game player activity", + tone: entry.type === "login" ? 0x57f287 : 0x5865f2, + sections: [`**${safe(entry.username, 40)}** ${entry.type === "login" ? "signed in" : "signed out"}.${played}`], + }), "game activity log"); +}; + +const notifyModeration = async entry => { + await postCard(config.discord.moderationLogsChannelId, card({ + title: "Moderation audit", + tone: 0xfee75c, + sections: [ + `**${safe(entry.by, 50)}** — ${safe(entry.action, 120)}`, + entry.target ? `Player: **${safe(entry.target, 50)}**` : "", + entry.detail ? `Details: ${safe(entry.detail, 500)}` : "", + ], + }), "moderation log"); +}; + +const notifyBot = async (interaction, action) => { + const actor = modpanel.discordBot.actor(interaction.user.id); + await postCard(config.discord.botLogsChannelId, card({ + title: "Discord bot audit", + tone: actor ? 0x5865f2 : 0xed4245, + sections: [ + `Discord user: **${safe(interaction.user.username, 80)}** (\`${safe(interaction.user.id, 30)}\`)`, + `Action: ${safe(action, 160)}`, + actor ? `Linked staff account: **${safe(actor.username, 40)}**` : "No active linked Burrow staff account.", + ], + }), "Discord bot audit log"); +}; + +const securityIncident = async (title, sections, detail = "") => { + await postCard(config.discord.moderationLogsChannelId, card({title, tone: 0xed4245, sections}), "Discord security log"); + modlog.record("discord security", title.toLowerCase(), "", detail); +}; + +const isConfiguredGuild = guild => Boolean(guild && guild.id === config.discord.guildId); + +const inspectDiscordMessage = async message => { + const settings = securitySettings(); + if (!settings.enabled || message.author?.bot || !isConfiguredGuild(message.guild)) return; + const at = Date.now(); + const key = message.author.id; + const times = (recentMessages.get(key) || []).filter(time => time > at - 10000); + times.push(at); + recentMessages.set(key, times); + const text = String(message.content || "").toLowerCase(); + const hasInvite = settings.blockInvites && /(?:discord\.gg|discord(?:app)?\.com\/invite)\//i.test(text); + const word = settings.blockedWords.find(entry => text.includes(entry)); + const reason = times.length > settings.spamLimit ? "message spam" : hasInvite ? "Discord invite" : word ? "blocked word" : ""; + if (!reason) return; + if (message.deletable) await message.delete().catch(() => {}); + await securityIncident("Discord AutoMod", [ + `Member: **${safe(message.author.username, 80)}**`, + `Action: deleted message for ${reason}.`, + ], `${safe(message.author.username, 80)}: ${reason}`); +}; + +const inspectDiscordJoin = async member => { + const settings = securitySettings(); + if (!settings.enabled || !isConfiguredGuild(member.guild)) return; + const at = Date.now(); + recentJoins.push(at); + while (recentJoins.length && recentJoins[0] <= at - 60000) recentJoins.shift(); + if (recentJoins.length < settings.raidJoinLimit || lastRaidAlertAt > at - 60000) return; + lastRaidAlertAt = at; + await securityIncident("Discord anti-raid alert", [ + `${recentJoins.length} members joined in the last minute.`, + "Review recent joins and use the dashboard or Discord moderation controls if action is needed.", + ], `${recentJoins.length} joins in one minute`); +}; + +const communityNotice = async (member, kind) => { + const settings = communitySettings(); + const channelId = kind === "welcome" ? settings.welcomeChannelId : settings.goodbyeChannelId; + const template = kind === "welcome" ? settings.welcomeMessage : settings.goodbyeMessage; + if (!channelId || !isConfiguredGuild(member.guild)) return; + const message = safe(template.replace(/\{user\}/gi, member.user.username).replace(/\{server\}/gi, member.guild.name), 500); + if (message) await postCard(channelId, card({title: kind === "welcome" ? "Welcome" : "Goodbye", tone: kind === "welcome" ? 0x57f287 : 0x5865f2, sections: [message]}), `${kind} notice`); +}; + +const githubUpdatesOn = () => { + loadDashboardConfig(); + return Boolean(config.discord.githubRepository && config.discord.githubWebhookSecret && config.discord.updatesChannelId); +}; + +// Safe to expose to the owner dashboard: it deliberately contains state and +// channel ids only, never the bot token or GitHub webhook secret. +const dashboardStatus = () => { + loadDashboardConfig(); + return { + botTokenConfigured: Boolean(config.discord.botToken), + guildId: config.discord.guildId || "", + connected: Boolean(client && client.isReady()), + commands: ["/burrow status", "/burrow player", "/burrow reports", "/burrow staff", "/burrow announce", "/moderate warn", "/moderate silence", "/moderate unsilence", "/moderate kick", "/moderate ban", "/moderate unban", "/discord timeout", "/discord untimeout", "/discord kick", "/discord ban", "/discord unban", "/discord purge"], + channels: CHANNELS.map(([key, name]) => ({key, name, id: config.discord[key] || "", configured: Boolean(config.discord[key])})), + github: { + repository: config.discord.githubRepository || "", + webhookSecretConfigured: Boolean(config.discord.githubWebhookSecret), + updatesEnabled: githubUpdatesOn(), + endpoint: "/discord/github", + }, + statusCard: statusSettings(), + security: {...securitySettings(), monitoring: securityGatewayOn}, + community: communitySettings(), + modules: [ + {name: "Burrow staff tools", detail: "Player lookup, reports, staff list, in-game announcements, and game moderation", enabled: Boolean(config.discord.botToken && config.discord.guildId)}, + {name: "Discord moderation", detail: "Timeout, kick, ban, unban, and purge; gated by linked Burrow staff permissions", enabled: Boolean(config.discord.botToken && config.discord.guildId)}, + {name: "Activity and audit logs", detail: "In-game activity, reports, moderation, and bot command audit streams", enabled: CHANNELS.some(([key]) => key !== "updatesChannelId" && Boolean(config.discord[key]))}, + {name: "GitHub updates", detail: "Signed commit cards, with client changes marked as game updates", enabled: githubUpdatesOn()}, + {name: "AutoMod and anti-raid", detail: "Blocked words, invite blocking, anti-spam, and join-rate alerts", enabled: securitySettings().enabled}, + {name: "Tickets and member notices", detail: "Private support tickets plus configurable welcome and goodbye cards", enabled: Boolean(communitySettings().ticketCategoryId && communitySettings().ticketStaffRoleId)}, + ], + }; +}; + +const githubBody = req => new Promise((resolve, reject) => { + const chunks = []; + let size = 0; + req.on("data", chunk => { + size += chunk.length; + if (size > MAX_GITHUB_WEBHOOK_BYTES) { + req.destroy(); + reject(new Error("too_large")); + return; + } + chunks.push(chunk); + }); + req.on("end", () => resolve(Buffer.concat(chunks))); + req.on("error", reject); +}); + +const githubSignatureMatches = (body, signature) => { + if (!/^sha256=[0-9a-f]{64}$/i.test(String(signature || ""))) return false; + const expected = `sha256=${crypto.createHmac("sha256", config.discord.githubWebhookSecret).update(body).digest("hex")}`; + return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(String(signature))); +}; + +const changedFiles = commit => [commit.added, commit.modified, commit.removed].flat().filter(file => typeof file === "string"); +const gameChange = payload => (payload.commits || []).some(commit => changedFiles(commit) + .some(file => /^(swf\/|swf-src\/|client-updates\/|public\/(?:badges|music|fonts)\/)/.test(file))); + +const githubUpdateCard = payload => { + const commits = Array.isArray(payload.commits) ? payload.commits.slice(-5) : []; + const isGameUpdate = gameChange(payload); + const compare = config.githubUrl ? `${config.githubUrl.replace(/\/$/, "")}/compare/${safe(payload.before, 40)}...${safe(payload.after, 40)}` : ""; + const branch = String(payload.ref || "").replace(/^refs\/heads\//, "") || "default branch"; + return card({ + title: isGameUpdate ? "Game update" : "Server update", + tone: isGameUpdate ? 0x57f287 : 0x5865f2, + sections: [ + `**${safe(config.discord.githubRepository, 100)}** · ${safe(branch, 100)}\n${commits.length} new commit${commits.length === 1 ? "" : "s"}`, + commits.length ? commits.map(commit => `\`${safe(String(commit.id || "").slice(0, 7), 7)}\` ${safe(String(commit.message || "").split("\n")[0], 180)} — ${safe(commit.author && commit.author.name, 80)}`).join("\n") : "No commit details were supplied.", + ], + components: compare ? [{type: 1, components: [{type: 2, style: 5, label: "View on GitHub", url: compare}]}] : [], + }); +}; + +// GitHub calls this public endpoint. It is intentionally signature-first: +// an untrusted request never reaches Discord or becomes a log entry. +const handleGithubWebhook = async (req, res) => { + const answer = status => { res.writeHead(status, {"Content-Length": 0}); res.end(); }; + if (!githubUpdatesOn()) { + answer(404); + return; + } + if (req.method !== "POST") { + answer(405); + return; + } + let body; + try { + body = await githubBody(req); + } + catch { + answer(413); + return; + } + if (!githubSignatureMatches(body, req.headers["x-hub-signature-256"])) { + answer(401); + return; + } + if (req.headers["x-github-event"] === "ping") { + answer(204); + return; + } + if (req.headers["x-github-event"] !== "push") { + answer(204); + return; + } + let payload; + try { + payload = JSON.parse(body.toString("utf8")); + } + catch { + answer(400); + return; + } + if (payload.repository?.full_name !== config.discord.githubRepository || payload.deleted === true) { + answer(204); + return; + } + const channel = await channelFor(config.discord.updatesChannelId); + if (!channel) { + answer(503); // GitHub retries after the bot finishes reconnecting. + return; + } + const posted = await channel.send(githubUpdateCard(payload)).then(() => true).catch(err => { + console.log(`[discord-bot] GitHub update post failed: ${logText(err.message)}`); + return false; + }); + answer(posted ? 204 : 503); +}; + +const syncCommands = async () => { + if (!client || !client.isReady()) return {error: "The Discord bot is not connected."}; + const guild = await client.guilds.fetch(config.discord.guildId).catch(() => null); + if (!guild) return {error: "The configured Discord server could not be found."}; + const synced = await guild.commands.set(commands).then(() => true).catch(err => { + console.log(`[discord-bot] command registration failed: ${logText(err.message)}`); + return false; + }); + return synced ? {ok: "Discord slash commands are synchronized."} : {error: "Discord could not synchronize slash commands."}; +}; + +const startup = () => { + loadDashboardConfig(); + const security = securitySettings(); + const community = communitySettings(); + if (!config.discord.botToken || !config.discord.guildId) { + return false; + } + if (client) return true; + securityGatewayOn = security.enabled; + const memberEvents = securityGatewayOn || Boolean(community.welcomeChannelId || community.goodbyeChannelId); + client = new Client({intents: securityGatewayOn + ? [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildMembers] + : memberEvents ? [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers] : [GatewayIntentBits.Guilds]}); + client.once("ready", async () => { + console.log(`[discord-bot] signed in as ${logText(client.user.tag)}`); + const synced = await syncCommands(); + console.log(`[discord-bot] ${synced.ok || synced.error}`); + await publishStatus(); + }); + client.on("interactionCreate", async interaction => { + if (interaction.user.bot) return; + if (interaction.isButton()) { + await notifyBot(interaction, `button ${interaction.customId}`).catch(() => {}); + await handleButton(interaction); + return; + } + if (!interaction.isChatInputCommand() || !inConfiguredGuild(interaction)) return; + await notifyBot(interaction, `/${interaction.commandName} ${interaction.options.getSubcommand(false) || ""}`.trim()).catch(() => {}); + await interaction.deferReply({flags: EPHEMERAL}).catch(() => {}); + if (!interaction.deferred) return; + try { + if (interaction.commandName === "burrow") await handleBurrow(interaction); + else if (interaction.commandName === "moderate") await handleModerate(interaction); + else if (interaction.commandName === "discord") await handleDiscordModeration(interaction); + else if (interaction.commandName === "ticket") await handleTicket(interaction); + } + catch (err) { + console.error(`[discord-bot] interaction failed: ${err.stack || err.message}`); + await interaction.editReply(failure("The command could not be completed.")).catch(() => {}); + } + }); + client.on("error", err => console.error(`[discord-bot] client error: ${err.message}`)); + if (securityGatewayOn) { + client.on("messageCreate", message => { inspectDiscordMessage(message).catch(err => console.error(`[discord-bot] AutoMod failed: ${err.message}`)); }); + client.on("guildMemberAdd", member => { inspectDiscordJoin(member).catch(err => console.error(`[discord-bot] anti-raid check failed: ${err.message}`)); }); + } + if (memberEvents) { + client.on("guildMemberAdd", member => { communityNotice(member, "welcome").catch(err => console.error(`[discord-bot] welcome notice failed: ${err.message}`)); }); + client.on("guildMemberRemove", member => { communityNotice(member, "goodbye").catch(err => console.error(`[discord-bot] goodbye notice failed: ${err.message}`)); }); + } + unsubscribeReports = reports.onFile(notifyReport); + unsubscribeGameActivity = world.onGameActivity(notifyGameActivity); + unsubscribeModeration = modlog.onRecord(notifyModeration); + statusTimer = setInterval(() => { publishStatus().catch(err => console.error(`[discord-bot] status failed: ${err.message}`)); }, STATUS_EVERY_MS); + statusTimer.unref(); + client.login(config.discord.botToken).catch(err => console.error(`[discord-bot] login failed: ${err.message}`)); + return true; +}; + +const shutdown = () => { + if (statusTimer) clearInterval(statusTimer); + statusTimer = null; + if (unsubscribeReports) unsubscribeReports(); + unsubscribeReports = null; + if (unsubscribeGameActivity) unsubscribeGameActivity(); + unsubscribeGameActivity = null; + if (unsubscribeModeration) unsubscribeModeration(); + unsubscribeModeration = null; + if (client) client.destroy(); + client = null; + securityGatewayOn = false; + recentMessages.clear(); + recentJoins.length = 0; +}; + +const control = async action => { + if (action === "stop") { + if (!client) return {error: "The Discord bot is already stopped."}; + shutdown(); + return {ok: "Discord bot stopped. Game and panel services remain online."}; + } + if (action === "start") { + return startup() ? {ok: "Discord bot is starting."} : {error: "Set AJ_DISCORD_BOT_TOKEN and AJ_DISCORD_GUILD_ID before starting the bot."}; + } + if (action === "reconnect") { + shutdown(); + return startup() ? {ok: "Discord bot is reconnecting."} : {error: "Set AJ_DISCORD_BOT_TOKEN and AJ_DISCORD_GUILD_ID before reconnecting the bot."}; + } + if (action === "sync") return syncCommands(); + return {error: "Unknown Discord bot control."}; +}; + +module.exports = {startup, shutdown, control, card, COMPONENTS_V2, dashboardStatus, updateDashboardConfig, updateSecuritySettings, updateCommunitySettings, setStatusSettings, publishStatus, handleGithubWebhook}; diff --git a/lib/http.js b/lib/http.js index 7e9ab4f..9e0a5ae 100644 --- a/lib/http.js +++ b/lib/http.js @@ -22,6 +22,7 @@ const defpacks = require("./defpacks.js"); const limits = require("./limits.js"); const manage = require("./manage.js"); const modpanel = require("./modpanel.js"); +const discordBot = require("./discordbot.js"); const badges = require("./badges.js"); const extraMusic = require("./extramusic.js"); const customMusic = require("./custommusic.js"); @@ -758,6 +759,12 @@ const handle = async (req, res) => { from.local = false; } + // GitHub sends signed push events here for optional Discord update cards. + if (url.pathname === "/discord/github") { + await discordBot.handleGithubWebhook(req, res); + return; + } + // One entry point for the owner and staff dashboards. The old addresses // stay as bookmark-friendly redirects; their APIs remain available for // installed tools and are not redirected. diff --git a/lib/modlog.js b/lib/modlog.js index 258428e..847acc2 100644 --- a/lib/modlog.js +++ b/lib/modlog.js @@ -18,13 +18,23 @@ const SCHEMA = ` `; const MAX_DETAIL = 400; const SHOWN = 300; +const listeners = new Set(); const load = () => accounts.database().exec(SCHEMA); const record = (by, action, target = "", detail = "") => { + const entry = {at: Math.floor(Date.now() / 1000), by: String(by), action: String(action), target: String(target), detail: String(detail).slice(0, MAX_DETAIL)}; accounts.database().prepare("INSERT INTO mod_log (at, by, action, target, detail) VALUES (?, ?, ?, ?, ?)") - .run(Math.floor(Date.now() / 1000), by, action, String(target), String(detail).slice(0, MAX_DETAIL)); + .run(entry.at, entry.by, entry.action, entry.target, entry.detail); console.log(`[mod] ${logText(by)}: ${logText(action)}${logText(target ? ` "${target}"` : "")}`); + for (const listener of listeners) { + try { + listener(entry); + } + catch (err) { + console.error(`[modlog] listener failed: ${logText(err.message)}`); + } + } }; const recent = () => accounts.database().prepare("SELECT at, by, action, target, detail FROM mod_log ORDER BY id DESC LIMIT ?").all(SHOWN); @@ -33,4 +43,12 @@ const recent = () => accounts.database().prepare("SELECT at, by, action, target, const about = username => accounts.database().prepare("SELECT at, by, action, target, detail FROM mod_log WHERE target = ? COLLATE NOCASE ORDER BY id DESC LIMIT 100") .all(String(username)); -module.exports = {load, record, recent, about}; +// Optional integrations subscribe here rather than wrapping record(), so an +// unavailable Discord channel can never stop a moderation action or its DB +// audit record from being written. +const onRecord = listener => { + listeners.add(listener); + return () => listeners.delete(listener); +}; + +module.exports = {load, record, recent, about, onRecord}; diff --git a/lib/modpanel.js b/lib/modpanel.js index fd6bb26..4a02259 100644 --- a/lib/modpanel.js +++ b/lib/modpanel.js @@ -1084,4 +1084,89 @@ const moderators = () => accounts.all().filter(account => roles.roleOf(account)) .map(account => ({username: account.username, role: roles.roleOf(account), twoStep: totp.isOn(account), lastSeen: account.lastSeen || null})) .sort((a, b) => a.username.localeCompare(b.username)); -module.exports = {handle, forget, moderators, signedInAs, itemRoutes, reviewRoutes}; +// The Discord bot is deliberately a small adapter over the panel rather than +// its own moderator system. Its actor is a Discord user id that is already +// linked to one Burrow account. From there these methods use the same role, +// rank, permission and action checks as POST /mod/api/act, and log every +// successful change under the staff member's normal Burrow username. +const discordActor = discordId => { + const account = accounts.all().find(candidate => candidate.discordId === String(discordId)); + return mayModerate(account) ? account : null; +}; + +const discordError = (actor, permission) => !actor + ? {error: "Link this Discord account to an active Burrow staff account first."} + : !roles.can(actor, permission) ? {error: "Your Burrow role cannot do that."} : null; + +const discordStatus = actor => { + const error = discordError(actor, "server.view"); + if (error) { + return error; + } + const memory = process.memoryUsage(); + const players = world.players(); + return {ok: true, uptimeSeconds: Math.floor(process.uptime()), players: players.length, + rooms: new Set(players.map(player => player.room).filter(Boolean)).size, + reports: reports.openCount(), memoryMb: Math.round(memory.rss / 1048576)}; +}; + +const discordPlayer = (actor, username) => { + const error = discordError(actor, "player.view"); + if (error) { + return error; + } + const target = accounts.byName(String(username || "").trim()); + return target ? {ok: true, player: playerDetail(target)} : {error: "No such player."}; +}; + +const discordReports = actor => { + const error = discordError(actor, "player.view"); + return error || {ok: true, reports: reports.list(false), open: reports.openCount()}; +}; + +const discordStaff = actor => { + const error = discordError(actor, "staff.list"); + return error || {ok: true, staff: moderators()}; +}; + +const discordAnnounce = (actor, text) => { + const error = discordError(actor, "server.announce"); + if (error) return error; + const message = String(text || "").trim().slice(0, 300); + if (!message) return {error: "The announcement is empty."}; + const reached = world.announce(message); + modlog.record(actor.username, "Discord announcement", "", `${reached} player${reached === 1 ? "" : "s"}`); + return {ok: reached === 1 ? "Shown to 1 player." : `Shown to ${reached} players.`}; +}; + +const discordHandleReport = (actor, id) => { + const error = discordError(actor, "player.warn"); + if (error) { + return error; + } + const handled = reports.markHandled(Number(id)); + if (handled) { + modlog.record(actor.username, "report dealt with", "", `#${Number(id)}`); + } + return handled ? {ok: "Marked as dealt with."} : {error: "No such report waiting."}; +}; + +const discordAct = (actor, username, body) => { + if (!actor) { + return {error: "Link this Discord account to an active Burrow staff account first."}; + } + const target = accounts.byName(String(username || "").trim()); + if (!target) { + return {error: "No such player."}; + } + const result = act(actor, target, body || {}); + if (result.ok) { + modlog.record(actor.username, String(body.action), target.username, result.detail || ""); + } + return result; +}; + +const discordBot = {actor: discordActor, authorize: discordError, status: discordStatus, player: discordPlayer, reports: discordReports, + staff: discordStaff, announce: discordAnnounce, handleReport: discordHandleReport, act: discordAct}; + +module.exports = {handle, forget, moderators, signedInAs, itemRoutes, reviewRoutes, discordBot}; diff --git a/lib/panel.js b/lib/panel.js index cf27532..3d9ce76 100644 --- a/lib/panel.js +++ b/lib/panel.js @@ -9,6 +9,7 @@ const achievements = require("./achievements.js"); const adopt = require("./adopt.js"); const badges = require("./badges.js"); const discordLinks = require("./discord.js"); +const discordBot = require("./discordbot.js"); const bans = require("./bans.js"); const colours = require("./colours.js"); const chatlog = require("./chatlog.js"); @@ -795,6 +796,61 @@ const handle = async (req, res, url, from, web) => { reply(200, overview()); return; + case "GET /admin/api/discord": + reply(200, discordBot.dashboardStatus()); + return; + + case "POST /admin/api/discord/status": { + const statusCard = discordBot.setStatusSettings({title: body.title, note: body.note}); + modlog.record("admin", "Discord public status card changed", "", `title: ${statusCard.title}`); + reply(200, {ok: "Status-card text saved. Use Publish now to update Discord.", statusCard}); + return; + } + + case "POST /admin/api/discord/status/publish": { + const result = await discordBot.publishStatus(); + if (result.ok) { + modlog.record("admin", "Discord public status card published"); + } + reply(result.ok ? 200 : 400, result); + return; + } + + case "POST /admin/api/discord/config": { + const result = discordBot.updateDashboardConfig(body); + if (result.ok) { + modlog.record("admin", "Discord bot routing settings changed"); + } + reply(result.ok ? 200 : 400, result); + return; + } + + case "POST /admin/api/discord/security": { + const result = discordBot.updateSecuritySettings(body); + if (result.ok) { + modlog.record("admin", "Discord security settings changed"); + } + reply(result.ok ? 200 : 400, result); + return; + } + + case "POST /admin/api/discord/community": { + const result = discordBot.updateCommunitySettings(body); + if (result.ok) modlog.record("admin", "Discord community and ticket settings changed"); + reply(result.ok ? 200 : 400, result); + return; + } + + case "POST /admin/api/discord/control": { + const action = String(body.action || ""); + const result = await discordBot.control(action); + if (result.ok) { + modlog.record("admin", `Discord bot ${action}`); + } + reply(result.ok ? 200 : 400, result); + return; + } + // a page of accounts by name (lib/staff.js says in what order), never // all of them: with thousands, sending every one every few seconds // slowed the page and the game alike. diff --git a/lib/reports.js b/lib/reports.js index 62c4d7f..55d5b9d 100644 --- a/lib/reports.js +++ b/lib/reports.js @@ -45,6 +45,7 @@ const MERGE_SECONDS = 10; const perTenMinutes = limits.limiter(10, 600000); const now = () => Math.floor(Date.now() / 1000); const clean = (text, max) => String(text === undefined ? "" : text).replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, " ").trim().slice(0, max); +const listeners = new Set(); const load = () => accounts.database().exec(SCHEMA); @@ -68,9 +69,18 @@ const file = ({reporter, target, reason, detail = "", context = "", room = ""}) if (!perTenMinutes.allow(reporter.toLowerCase()) || openCount() >= MAX_OPEN) { return false; } - db.prepare("INSERT INTO reports (created_at, reporter, target, reason, detail, context, room) VALUES (?, ?, ?, ?, ?, ?, ?)") + const inserted = db.prepare("INSERT INTO reports (created_at, reporter, target, reason, detail, context, room) VALUES (?, ?, ?, ?, ?, ?, ?)") .run(now(), reporter, target, Number.isInteger(reason) ? reason : 0, clean(detail, MAX_DETAIL), clean(context, MAX_CONTEXT), clean(room, 100)); console.log(`[world] ${logText(reporter)} reported "${logText(target)}" (${logText(REASONS[reason] || `reason ${reason}`)})`); + const report = row(db.prepare("SELECT * FROM reports WHERE id = ?").get(Number(inserted.lastInsertRowid))); + for (const listener of listeners) { + try { + listener(report); + } + catch (err) { + console.error(`[reports] listener failed: ${logText(err.message)}`); + } + } return true; }; @@ -95,8 +105,15 @@ const list = (handled = false) => accounts.database() const markHandled = id => accounts.database().prepare("UPDATE reports SET handled_at = ? WHERE id = ? AND handled_at IS NULL").run(now(), id).changes > 0; +// Lets optional integrations (the Discord bot) receive a newly filed report +// without making a report depend on an external service being available. +const onFile = listener => { + listeners.add(listener); + return () => listeners.delete(listener); +}; + // the reports about one player, newest first, for their timeline. const about = username => accounts.database().prepare("SELECT * FROM reports WHERE target = ? COLLATE NOCASE ORDER BY id DESC LIMIT 100") .all(String(username)).map(row); -module.exports = {load, file, list, about, markHandled, openCount, MAX_DETAIL}; +module.exports = {load, file, list, about, markHandled, onFile, openCount, MAX_DETAIL}; diff --git a/lib/roles.js b/lib/roles.js index ac33c27..917c793 100644 --- a/lib/roles.js +++ b/lib/roles.js @@ -16,6 +16,7 @@ const totp = require("./totp.js"); const PERMISSIONS = { "server.view": "see read-only server health in the moderator panel", + "server.announce": "send an announcement to everyone playing", "player.view": "see players, chat, reports, requests, bans and paintings in the moderator panel, and keep notes on players (!note, !notes)", "staff.list": "see which staff are online (!staff)", "player.warn": "warn a player, take a warning back, send them a message and mark a report dealt with (!warn, !unwarn, !warnings, !message)", @@ -38,7 +39,7 @@ const PERMISSIONS = { const HELPER = ["server.view", "player.view", "staff.list", "player.warn", "player.goto", "chat.silence"]; const MODERATOR = [...HELPER, "player.kick", "player.summon", "staff.invisible", "player.ban", "player.names", "address.ban", "items.approve", "items.restrict", "theater.control", "staff.log"]; -const ADMIN = [...MODERATOR, "items.create", "room.effects", "music.upload"]; +const ADMIN = [...MODERATOR, "server.announce", "items.create", "room.effects", "music.upload"]; // a developer makes things, and moderates nobody. const DEVELOPER = ["server.view", "staff.list", "items.create", "room.effects", "theater.control"]; diff --git a/lib/world.js b/lib/world.js index 8c68593..66bc7de 100644 --- a/lib/world.js +++ b/lib/world.js @@ -161,6 +161,26 @@ const THEME_PATH_PREFIX = "theme_"; // lib/http.js looks for this const chatLines = limits.limiter(config.chatLinesPerWindow, config.chatWindowMs); const online = new Map(); // lowercased username -> session const rooms = new Map(); // "path.name#shard" -> room +const gameActivityListeners = new Set(); + +// An intentionally small, privacy-safe activity feed for optional +// integrations. It names only the player and lifecycle event—never IPs, +// device identifiers, game tokens or chat text. +const gameActivity = entry => { + for (const listener of gameActivityListeners) { + try { + listener(entry); + } + catch (err) { + console.error(`[world] activity listener failed: ${logText(err.message)}`); + } + } +}; + +const onGameActivity = listener => { + gameActivityListeners.add(listener); + return () => gameActivityListeners.delete(listener); +}; // worlds (config.shards): a land room's name ends in "#"; dens, // parties and adventures have none and belong to no world. each player has @@ -384,6 +404,7 @@ const login = (session, msg) => { accounts.save(account); online.set(key, session); console.log(`[world] ${logText(account.username)} logged in as sfs user ${logText(session.id)}`); + gameActivity({type: "login", username: account.username, at: Math.floor(Date.now() / 1000)}); session.sendXtJson(-1, {_cmd: "login", status: "1", params: loginParams(session)}); // every custom colour, before anything that might be drawn with one // (XtReplyDemuxer -> PaletteHelper.handleCustomColors in the patched SWF). @@ -1379,6 +1400,8 @@ setInterval(() => { }, 60000).unref(); const leaveWorld = session => { + const username = session.account && session.account.username; + const playedSeconds = session.playStarted ? Math.max(0, Math.round((Date.now() - session.playStarted) / 1000)) : 0; minigames.leave(session); trades.forget(session); leaveRoom(session); @@ -1390,6 +1413,7 @@ const leaveWorld = session => { accounts.release(session.account); accounts.save(session.account); buddies.announce(session.account); + gameActivity({type: "logout", username, at: Math.floor(Date.now() / 1000), playedSeconds}); } }; @@ -2134,4 +2158,5 @@ module.exports = { room: session.room ? session.room.name.replace(/#(\d+)$/, (whole, id) => (worldOf(whole) ? ` (${worldName(Number(id))})` : whole)) : null, address: session.address, })), + onGameActivity, }; diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..c94c79a --- /dev/null +++ b/package-lock.json @@ -0,0 +1,333 @@ +{ + "name": "aj-classic-private-server", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "aj-classic-private-server", + "version": "0.1.0", + "dependencies": { + "discord.js": "14.26.4" + }, + "engines": { + "node": ">=22.5" + } + }, + "node_modules/@discordjs/builders": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.14.1.tgz", + "integrity": "sha512-gSKkhXLqs96TCzk66VZuHHl8z2bQMJFGwrXC0f33ngK+FLNau4hU1PYny3DNJfNdSH+gVMzE85/d5FQ2BpcNwQ==", + "license": "Apache-2.0", + "dependencies": { + "@discordjs/formatters": "^0.6.2", + "@discordjs/util": "^1.2.0", + "@sapphire/shapeshift": "^4.0.0", + "discord-api-types": "^0.38.40", + "fast-deep-equal": "^3.1.3", + "ts-mixer": "^6.0.4", + "tslib": "^2.6.3" + }, + "engines": { + "node": ">=16.11.0" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/collection": { + "version": "1.5.3", + "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-1.5.3.tgz", + "integrity": "sha512-SVb428OMd3WO1paV3rm6tSjM4wC+Kecaa1EUGX7vc6/fddvw/6lg90z4QtCqm21zvVe92vMMDt9+DkIvjXImQQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=16.11.0" + } + }, + "node_modules/@discordjs/formatters": { + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/@discordjs/formatters/-/formatters-0.6.2.tgz", + "integrity": "sha512-y4UPwWhH6vChKRkGdMB4odasUbHOUwy7KL+OVwF86PvT6QVOwElx+TiI1/6kcmcEe+g5YRXJFiXSXUdabqZOvQ==", + "license": "Apache-2.0", + "dependencies": { + "discord-api-types": "^0.38.33" + }, + "engines": { + "node": ">=16.11.0" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/rest": { + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-2.6.3.tgz", + "integrity": "sha512-wvOylxNYJkwKjctS/Mn5GP1w9r3/rzyH+ThD1JlAca6zEdlHs8QWBBUQJpU5Q+W6DoIj/Ljh1IPlZs7hTU+UAg==", + "license": "Apache-2.0", + "dependencies": { + "@discordjs/collection": "^2.1.1", + "@discordjs/util": "^1.2.0", + "@sapphire/async-queue": "^1.5.3", + "@sapphire/snowflake": "^3.5.5", + "@vladfrangu/async_event_emitter": "^2.4.6", + "discord-api-types": "^0.38.50", + "magic-bytes.js": "^1.13.0", + "tslib": "^2.6.3", + "undici": "^6.27.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/rest/node_modules/@discordjs/collection": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.1.1.tgz", + "integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==", + "license": "Apache-2.0", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/rest/node_modules/@sapphire/snowflake": { + "version": "3.5.5", + "resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.5.tgz", + "integrity": "sha512-xzvBr1Q1c4lCe7i6sRnrofxeO1QTP/LKQ6A6qy0iB4x5yfiSfARMEQEghojzTNALDTcv8En04qYNIco9/K9eZQ==", + "license": "MIT", + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/@discordjs/rest/node_modules/undici": { + "version": "6.29.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-6.29.1.tgz", + "integrity": "sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA==", + "license": "MIT", + "engines": { + "node": ">=18.17" + } + }, + "node_modules/@discordjs/util": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@discordjs/util/-/util-1.2.0.tgz", + "integrity": "sha512-3LKP7F2+atl9vJFhaBjn4nOaSWahZ/yWjOvA4e5pnXkt2qyXRCHLxoBQy81GFtLGCq7K9lPm9R517M1U+/90Qg==", + "license": "Apache-2.0", + "dependencies": { + "discord-api-types": "^0.38.33" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/ws": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@discordjs/ws/-/ws-1.2.3.tgz", + "integrity": "sha512-wPlQDxEmlDg5IxhJPuxXr3Vy9AjYq5xCvFWGJyD7w7Np8ZGu+Mc+97LCoEc/+AYCo2IDpKioiH0/c/mj5ZR9Uw==", + "license": "Apache-2.0", + "dependencies": { + "@discordjs/collection": "^2.1.0", + "@discordjs/rest": "^2.5.1", + "@discordjs/util": "^1.1.0", + "@sapphire/async-queue": "^1.5.2", + "@types/ws": "^8.5.10", + "@vladfrangu/async_event_emitter": "^2.2.4", + "discord-api-types": "^0.38.1", + "tslib": "^2.6.2", + "ws": "^8.17.0" + }, + "engines": { + "node": ">=16.11.0" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/ws/node_modules/@discordjs/collection": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-2.1.1.tgz", + "integrity": "sha512-LiSusze9Tc7qF03sLCujF5iZp7K+vRNEDBZ86FT9aQAv3vxMLihUvKvpsCWiQ2DJq1tVckopKm1rxomgNUc9hg==", + "license": "Apache-2.0", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@sapphire/async-queue": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@sapphire/async-queue/-/async-queue-1.5.5.tgz", + "integrity": "sha512-cvGzxbba6sav2zZkH8GPf2oGk9yYoD5qrNWdu9fRehifgnFZJMV+nuy2nON2roRO4yQQ+v7MK/Pktl/HgfsUXg==", + "license": "MIT", + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/@sapphire/shapeshift": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/@sapphire/shapeshift/-/shapeshift-4.0.0.tgz", + "integrity": "sha512-d9dUmWVA7MMiKobL3VpLF8P2aeanRTu6ypG2OIaEv/ZHH/SUQ2iHOVyi5wAPjQ+HmnMuL0whK9ez8I/raWbtIg==", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "lodash": "^4.17.21" + }, + "engines": { + "node": ">=v16" + } + }, + "node_modules/@sapphire/snowflake": { + "version": "3.5.3", + "resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.3.tgz", + "integrity": "sha512-jjmJywLAFoWeBi1W7994zZyiNWPIiqRRNAmSERxyg93xRGzNYvGjlZ0gR6x0F4gPRi2+0O6S71kOZYyr3cxaIQ==", + "license": "MIT", + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/@types/node": { + "version": "26.6.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.5.tgz", + "integrity": "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==", + "license": "MIT", + "dependencies": { + "undici-types": "~8.9.0" + } + }, + "node_modules/@types/ws": { + "version": "8.18.2", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.2.tgz", + "integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@vladfrangu/async_event_emitter": { + "version": "2.4.7", + "resolved": "https://registry.npmjs.org/@vladfrangu/async_event_emitter/-/async_event_emitter-2.4.7.tgz", + "integrity": "sha512-Xfe6rpCTxSxfbswi/W/Pz7zp1WWSNn4A0eW4mLkQUewCrXXtMj31lCg+iQyTkh/CkusZSq9eDflu7tjEDXUY6g==", + "license": "MIT", + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/discord-api-types": { + "version": "0.38.57", + "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.38.57.tgz", + "integrity": "sha512-R1CTSSt4RshqCq23j2Xq2ZscvzB4LzG9OB1CYQdKUGdw8Ti/oF/72EEtK2mNpagG/Vj9NcBT7dw9lKLf+Dacfg==", + "license": "MIT" + }, + "node_modules/discord.js": { + "version": "14.26.4", + "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.26.4.tgz", + "integrity": "sha512-4oBp8tc6Kf8IDBwAHhbsMaAqx1b5fob9SNasZT7V6yyyUydoO5i5fGuX7TmvRtR+q/WgKRnRViRoAWnG7fNyvA==", + "license": "Apache-2.0", + "dependencies": { + "@discordjs/builders": "^1.14.1", + "@discordjs/collection": "1.5.3", + "@discordjs/formatters": "^0.6.2", + "@discordjs/rest": "^2.6.1", + "@discordjs/util": "^1.2.0", + "@discordjs/ws": "^1.2.3", + "@sapphire/snowflake": "3.5.3", + "discord-api-types": "^0.38.40", + "fast-deep-equal": "3.1.3", + "lodash.snakecase": "4.1.1", + "magic-bytes.js": "^1.13.0", + "tslib": "^2.6.3", + "undici": "6.24.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "license": "MIT" + }, + "node_modules/lodash": { + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz", + "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==", + "license": "MIT" + }, + "node_modules/lodash.snakecase": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.snakecase/-/lodash.snakecase-4.1.1.tgz", + "integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==", + "license": "MIT" + }, + "node_modules/magic-bytes.js": { + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/magic-bytes.js/-/magic-bytes.js-1.13.1.tgz", + "integrity": "sha512-x5sn4UX2k5gCWlcfmoFwG4TPie8+dctESyqOBdhB5p6MsgWXdBKGmt9nXPObj/JI50TTL928lc5Yt1WntMn1bw==", + "license": "MIT" + }, + "node_modules/ts-mixer": { + "version": "6.0.4", + "resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.4.tgz", + "integrity": "sha512-ufKpbmrugz5Aou4wcr5Wc1UUFWOLhq+Fm6qa6P0w0K5Qw2yhaUoiWszhCVuNQyNwrlGiscHOmqYoAox1PtvgjA==", + "license": "MIT" + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/undici": { + "version": "6.24.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-6.24.1.tgz", + "integrity": "sha512-sC+b0tB1whOCzbtlx20fx3WgCXwkW627p4EA9uM+/tNNPkSS+eSEld6pAs9nDv7WbY1UUljBMYPtu9BCOrCWKA==", + "license": "MIT", + "engines": { + "node": ">=18.17" + } + }, + "node_modules/undici-types": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", + "license": "MIT" + }, + "node_modules/ws": { + "version": "8.22.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz", + "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/package.json b/package.json index cbe55fa..6cee9d1 100644 --- a/package.json +++ b/package.json @@ -10,5 +10,8 @@ }, "engines": { "node": ">=22.5" + }, + "dependencies": { + "discord.js": "14.26.4" } } diff --git a/public/admin.html b/public/admin.html index 5a7d10b..e24d425 100644 --- a/public/admin.html +++ b/public/admin.html @@ -416,6 +416,7 @@ + @@ -460,6 +461,96 @@ + + @@ -1210,6 +1301,161 @@ $("server-facts").replaceChildren(...facts.flatMap(([name, value]) => [el("dt", name), el("dd", String(value))])); }; + const renderDiscord = data => { + const configured = data.botTokenConfigured && data.guildId; + $("discord-bot-summary").textContent = !configured + ? "The Discord staff bot is off. Set AJ_DISCORD_BOT_TOKEN and AJ_DISCORD_GUILD_ID, then restart the server." + : data.connected ? "The Discord staff bot is connected and ready." : "The Discord staff bot is configured but is not connected. Check the server log and bot permissions."; + const facts = [ + ["Bot token", data.botTokenConfigured ? "Configured" : "Missing"], + ["Guild", data.guildId || "Missing"], + ["Connection", data.connected ? "Connected" : "Not connected"], + ["Commands", (data.commands || []).join(", ") || "None"], + ]; + $("discord-bot-facts").replaceChildren(...facts.flatMap(([name, value]) => [el("dt", name), el("dd", value)])); + $("discord-modules").replaceChildren(...(data.modules || []).map(module => { + const row = el("tr"); + row.append(el("td", module.name), el("td", module.enabled ? "Enabled" : "Off / needs setup"), el("td", module.detail)); + return row; + })); + $("discord-bot-status").textContent = configured + ? "Credentials and webhook secrets are intentionally never shown in this dashboard." + : "Add the missing environment variables to the service that starts Burrow; dashboard settings cannot store bot secrets."; + $("discord-bot-status").classList.toggle("bad", !configured || !data.connected); + const editingStatusCard = ["discord-status-title", "discord-status-note"].includes(document.activeElement && document.activeElement.id); + if (!editingStatusCard) { + $("discord-status-title").value = data.statusCard && data.statusCard.title || "Burrow status"; + $("discord-status-note").value = data.statusCard && data.statusCard.note || ""; + } + const editingRouting = document.activeElement && (document.activeElement.dataset.discordChannel || document.activeElement.id === "discord-github-repository"); + if (!editingRouting) { + $("discord-channel-inputs").replaceChildren(...(data.channels || []).flatMap(channel => { + const label = el("label", channel.name); + label.htmlFor = `discord-channel-${channel.key}`; + const input = el("input"); + input.id = label.htmlFor; + input.dataset.discordChannel = channel.key; + input.inputMode = "numeric"; + input.maxLength = 25; + input.placeholder = "Discord channel ID (optional)"; + input.value = channel.id || ""; + input.setAttribute("aria-label", `${channel.name} Discord channel ID`); + return [label, input]; + })); + $("discord-github-repository").value = data.github && data.github.repository || ""; + } + const github = data.github || {}; + const githubFacts = [ + ["Repository", github.repository || "Missing (AJ_GITHUB_REPOSITORY)"], + ["Webhook secret", github.webhookSecretConfigured ? "Configured" : "Missing"], + ["Update channel", (data.channels || []).some(channel => channel.name === "GitHub updates" && channel.configured) ? "Configured" : "Missing"], + ["Webhook endpoint", github.endpoint || "/discord/github"], + ["Update cards", github.updatesEnabled ? "Enabled" : "Off until all three settings are configured"], + ]; + $("github-update-facts").replaceChildren(...githubFacts.flatMap(([name, value]) => [el("dt", name), el("dd", value)])); + const editingSecurity = ["discord-security-words", "discord-security-spam", "discord-security-raid"].includes(document.activeElement && document.activeElement.id); + if (!editingSecurity) { + const security = data.security || {}; + $("discord-security-enabled").checked = Boolean(security.enabled); + $("discord-security-invites").checked = Boolean(security.blockInvites); + $("discord-security-words").value = (security.blockedWords || []).join("\n"); + $("discord-security-spam").value = String(security.spamLimit || 6); + $("discord-security-raid").value = String(security.raidJoinLimit || 12); + setStatus($("discord-security-status"), security.enabled + ? security.monitoring ? "Security monitoring is active." : "Security is saved. Reconnect the bot after enabling Discord Message Content and Server Members intents." + : "Security monitoring is off.", security.enabled && !security.monitoring); + } + const editingCommunity = ["discord-ticket-category", "discord-ticket-staff-role", "discord-welcome-channel", "discord-welcome-message", "discord-goodbye-channel", "discord-goodbye-message"].includes(document.activeElement && document.activeElement.id); + if (!editingCommunity) { + const community = data.community || {}; + $("discord-ticket-category").value = community.ticketCategoryId || ""; + $("discord-ticket-staff-role").value = community.ticketStaffRoleId || ""; + $("discord-welcome-channel").value = community.welcomeChannelId || ""; + $("discord-welcome-message").value = community.welcomeMessage || ""; + $("discord-goodbye-channel").value = community.goodbyeChannelId || ""; + $("discord-goodbye-message").value = community.goodbyeMessage || ""; + } + }; + + const controlDiscordBot = async action => { + const buttons = ["discord-bot-start", "discord-bot-stop", "discord-bot-reconnect", "discord-bot-sync"].map($); + buttons.forEach(button => { button.disabled = true; }); + const result = await api("discord/control", {action}); + buttons.forEach(button => { button.disabled = false; }); + setStatus($("discord-bot-status"), said(result), !result.ok); + refresh(); + }; + $("discord-bot-start").addEventListener("click", () => controlDiscordBot("start")); + $("discord-bot-stop").addEventListener("click", () => controlDiscordBot("stop")); + $("discord-bot-reconnect").addEventListener("click", () => controlDiscordBot("reconnect")); + $("discord-bot-sync").addEventListener("click", () => controlDiscordBot("sync")); + + $("discord-routing-form").addEventListener("submit", async event => { + event.preventDefault(); + const button = event.submitter; + if (button) button.disabled = true; + const fields = {githubRepository: $("discord-github-repository").value}; + for (const input of $("discord-channel-inputs").querySelectorAll("input[data-discord-channel]")) { + fields[input.dataset.discordChannel] = input.value; + } + const result = await api("discord/config", fields); + if (button) button.disabled = false; + setStatus($("discord-routing-status"), said(result), !result.ok); + if (result.ok) refresh(); + }); + + $("discord-security-form").addEventListener("submit", async event => { + event.preventDefault(); + const button = event.submitter; + if (button) button.disabled = true; + const result = await api("discord/security", { + enabled: $("discord-security-enabled").checked, + blockInvites: $("discord-security-invites").checked, + blockedWords: $("discord-security-words").value, + spamLimit: Number($("discord-security-spam").value), + raidJoinLimit: Number($("discord-security-raid").value), + }); + if (button) button.disabled = false; + setStatus($("discord-security-status"), said(result), !result.ok); + if (result.ok) refresh(); + }); + + $("discord-community-form").addEventListener("submit", async event => { + event.preventDefault(); + const button = event.submitter; + if (button) button.disabled = true; + const result = await api("discord/community", { + ticketCategoryId: $("discord-ticket-category").value, ticketStaffRoleId: $("discord-ticket-staff-role").value, + welcomeChannelId: $("discord-welcome-channel").value, welcomeMessage: $("discord-welcome-message").value, + goodbyeChannelId: $("discord-goodbye-channel").value, goodbyeMessage: $("discord-goodbye-message").value, + }); + if (button) button.disabled = false; + setStatus($("discord-community-status"), said(result), !result.ok); + if (result.ok) refresh(); + }); + + $("discord-status-form").addEventListener("submit", async event => { + event.preventDefault(); + const button = event.submitter; + if (button) button.disabled = true; + const result = await api("discord/status", {title: $("discord-status-title").value, note: $("discord-status-note").value}); + if (button) button.disabled = false; + setStatus($("discord-status-card-result"), said(result), !result.ok); + if (result.ok && result.data.statusCard) { + $("discord-status-title").value = result.data.statusCard.title; + $("discord-status-note").value = result.data.statusCard.note; + } + }); + + $("discord-status-publish").addEventListener("click", async () => { + const button = $("discord-status-publish"); + button.disabled = true; + const result = await api("discord/status/publish", {}); + button.disabled = false; + setStatus($("discord-status-card-result"), said(result), !result.ok); + if (result.ok) refresh(); + }); + const accountState = account => { const tags = []; if (account.online) { @@ -3022,6 +3268,12 @@ quickLockFind(); } } + else if (tab === "discord") { + result = await api("discord"); + if (result.ok) { + renderDiscord(result.data); + } + } else if (tab === "accounts") { const searchBy = $("account-search-by").value; const query = searchBy !== "name" ? "" : $("account-search").value.trim(); diff --git a/server.js b/server.js index 323b950..02f4bc3 100644 --- a/server.js +++ b/server.js @@ -7,6 +7,7 @@ const accounts = require("./lib/accounts.js"); const bans = require("./lib/bans.js"); const devices = require("./lib/devices.js"); const discord = require("./lib/discord.js"); +const discordBot = require("./lib/discordbot.js"); const chatlog = require("./lib/chatlog.js"); const modlog = require("./lib/modlog.js"); const retention = require("./lib/retention.js"); @@ -56,11 +57,13 @@ const main = async () => { panel.load(); await http.start(); await sfs.start(world); + discordBot.startup(); console.log(`[server] ready at ${config.baseUrl}`); }; // stopped on purpose: what is waiting to be written is written first. const stop = code => { + discordBot.shutdown(); stats.flush(); try { accounts.flush();