feat: move from discord to web forms

This commit is contained in:
2025-01-22 17:02:16 -08:00
parent d7cd3ffaab
commit 2e00e2ed6a
21 changed files with 280 additions and 538 deletions
-114
View File
@@ -1,114 +0,0 @@
import {
ApplicationIntegrationType,
InteractionContextType,
SlashCommandBuilder,
} from "discord.js";
import { errorHandler } from "../utils/errorHandler.js";
import type { Command } from "../interfaces/command.js";
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
export const log: Command = {
data: new SlashCommandBuilder().
setName("log").
setDescription("Log a moderation action.").
setContexts([
InteractionContextType.BotDM,
InteractionContextType.Guild,
InteractionContextType.PrivateChannel,
]).
setIntegrationTypes([ ApplicationIntegrationType.UserInstall ]).
addStringOption((option) => {
return option.
setName("action").
setDescription("The action to log.").
setRequired(true).
addChoices([
{ name: "Ban", value: "ban" },
{ name: "Kick", value: "kick" },
{ name: "Mute", value: "mute" },
{ name: "Warn", value: "warn" },
{ name: "Block", value: "block" },
{ name: "Suspend", value: "suspend" },
]);
}).
addStringOption((option) => {
return option.
setName("platform").
setDescription("The platform to log the action on.").
setRequired(true).
addChoices([
{ name: "Discord", value: "discord" },
{ name: "Twitch", value: "twitch" },
{ name: "Codeberg", value: "codeberg" },
{ name: "Bluesky", value: "bluesky" },
{ name: "Forum", value: "forum" },
{ name: "Reddit", value: "reddit" },
{ name: "IRC", value: "irc" },
{ name: "Slack", value: "slack" },
{ name: "Mastodon", value: "mastodon" },
{ name: "Twitter", value: "twitter" },
{ name: "GitHub", value: "github" },
{ name: "LinkedIn", value: "linkedin" },
{ name: "Peerlist", value: "peerlist" },
{ name: "Signal", value: "signal" },
{ name: "WhatsApp", value: "whatsapp" },
{ name: "Snapchat", value: "snapchat" },
]);
}).
addStringOption((option) => {
return option.
setName("username").
setDescription("Username or UUID of the targeted user.").
setRequired(true);
}).
addStringOption((option) => {
return option.
setName("reason").
setDescription("Reason for the action.").
setRequired(true);
}),
run: async(app, interaction) => {
try {
await interaction.deferReply({ ephemeral: true });
if (interaction.user.id !== "465650873650118659") {
await interaction.editReply({
content:
// eslint-disable-next-line stylistic/max-len -- This is a single string.
"Only Naomi can use this app. Sorry! Feel free to join our Discord? https://chat.nhcarrigan.com",
});
return;
}
const action = interaction.options.getString("action", true);
const platform = interaction.options.getString("platform", true);
const uuid = interaction.options.getString("username", true);
const reason = interaction.options.getString("reason", true);
const number = await app.database.sanctions.count() + 1;
await app.database.sanctions.create({
data: {
action,
number,
platform,
reason,
uuid,
},
});
await interaction.editReply({
content: `Logged ${action} #${String(
number,
)} on ${platform} for user ${uuid}.`,
});
} catch (error) {
await errorHandler("log command", error);
await interaction.editReply({
content:
"An error occurred while processing your command. Please try again.",
});
}
},
};
-84
View File
@@ -1,84 +0,0 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import {
ApplicationIntegrationType,
InteractionContextType,
SlashCommandBuilder,
} from "discord.js";
import { errorHandler } from "../utils/errorHandler.js";
import type { Command } from "../interfaces/command.js";
export const revoke: Command = {
data: new SlashCommandBuilder().
setName("revoke").
setDescription("Revoke a moderation action.").
setContexts([
InteractionContextType.BotDM,
InteractionContextType.Guild,
InteractionContextType.PrivateChannel,
]).
setIntegrationTypes([ ApplicationIntegrationType.UserInstall ]).
addIntegerOption((option) => {
return option.
setName("case").
setDescription("The case number to revoke.").
setRequired(true);
}).
addStringOption((option) => {
return option.
setName("reason").
setDescription("The reason for revoking the case.").
setRequired(true);
}),
run: async(app, interaction) => {
try {
await interaction.deferReply({ ephemeral: true });
if (interaction.user.id !== "465650873650118659") {
await interaction.editReply({
content:
// eslint-disable-next-line stylistic/max-len -- This is a single string.
"Only Naomi can use this app. Sorry! Feel free to join our Discord? https://chat.nhcarrigan.com",
});
return;
}
const number = interaction.options.getInteger("case", true);
const reason = interaction.options.getString("reason", true);
const exists = await app.database.sanctions.findUnique({
where: { number },
});
if (!exists) {
await interaction.editReply({
content: `Case ${String(number)} does not exist.`,
});
return;
}
await app.database.sanctions.update({
data: {
revokeDate: new Date(),
revokeReason: reason,
revoked: true,
},
where: {
number,
},
});
await interaction.editReply({
content: `Revoked action ${String(number)} for ${reason}.`,
});
} catch (error) {
await errorHandler("log command", error);
await interaction.editReply({
content:
"An error occurred while processing your command. Please try again.",
});
}
},
};
+74
View File
@@ -0,0 +1,74 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
const formHtml = `
<!DOCTYPE html>
<html>
<head>
<title>Moderation Logs</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content="This page lists all of our community moderation sanctions." />
<script src="https://cdn.nhcarrigan.com/headers/index.js" async defer></script>
</head>
<body>
<main>
<h1>Log A Sanction</h1>
<section>
<p>This page allows our staff to log an official sanction from one of our platforms.</p>
</section>
<form action="/log" method="post">
<input type="text" name="uuid" placeholder="User UUID" required />
<select name="platform" required>
<option value="forum">Forum</option>
<option value="irc">IRC</option>
<option value="gitea">Code Repositories</option>
<option value="fediverse">Fediverse</option>
</select>
<select name="action" required>
<option value="Ban">Ban</option>
<option value="Kick">Kick</option>
<option value="Mute">Mute</option>
<option value="Warn">Warn</option>
<option value="Suspend">Suspend</option>
</select>
<input type="text" name="reason" placeholder="Reason" required />
<input type="password" name="token" placeholder="Staff Token" required />
<button type="submit">Log Sanction</button>
</form>
</main>
</body>
</html>
`;
const revokeHtml = `
<!DOCTYPE html>
<html>
<head>
<title>Moderation Logs</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content="This page lists all of our community moderation sanctions." />
<script src="https://cdn.nhcarrigan.com/headers/index.js" async defer></script>
</head>
<body>
<main>
<h1>Revoke A Sanction</h1>
<section>
<p>This page allows our staff to indicate a sanction has been successfully appealed.</p>
</section>
<form action="/revoke" method="post">
<input type="number" name="case" placeholder="Sanction Number" required />
<input type="text" name="reason" placeholder="Reason" required />
<input type="password" name="token" placeholder="Staff Token" required />
<button type="submit">Revoke Sanction</button>
</form>
</main>
</body>
</html>
`;
export { formHtml, revokeHtml };
+4 -17
View File
@@ -8,27 +8,14 @@
* Turn a platform name into a font-awesome icon.
*/
const platformIcons: Record<string, string> = {
bluesky: "<i class=\"fa-brands fa-bluesky\"></i>",
codeberg: "<i class=\"fa-solid fa-code\"></i>",
discord: "<i class=\"fa-brands fa-discord\"></i>",
forum: "<i class=\"fa-brands fa-discourse\"></i>",
github: "<i class=\"fa-brands fa-github\"></i>",
irc: "<i class=\"fa-regular fa-comment\"></i>",
linkedin: "<i class=\"fa-brands fa-linkedin\"></i>",
mastodon: "<i class=\"fa-brands fa-mastodon\"></i>",
peerlist: "<i class=\"fa-solid fa-p\"></i>",
reddit: "<i class=\"fa-brands fa-reddit\"></i>",
signal: "<i class=\"fa-brands fa-signal-messenger\"></i>",
slack: "<i class=\"fa-brands fa-slack\"></i>",
snapchat: "<i class=\"fa-brands fa-snapchat\"></i>",
twitch: "<i class=\"fa-brands fa-twitch\"></i>",
twitter: "<i class=\"fa-brands fa-twitter\"></i>",
whatsapp: "<i class=\"fa-brands fa-whatsapp\"></i>",
fediverse: "<i class=\"fa-brands fa-mastodon\"></i>",
forum: "<i class=\"fa-brands fa-discourse\"></i>",
gitea: "<i class=\"fa-solid fa-code\"></i>",
irc: "<i class=\"fa-solid fa-hashtag\"></i>",
};
const actionIcons: Record<string, string> = {
ban: "<i class=\"fa-solid fa-ban\"></i>",
block: "<i class=\"fa-solid fa-ban\"></i>",
kick: "<i class=\"fa-solid fa-shoe-prints\"></i>",
mute: "<i class=\"fa-solid fa-head-side-cough-slash\"></i>",
revoked: "<i class=\"fa-solid fa-undo\"></i>",
+4 -3
View File
@@ -25,17 +25,17 @@ export const landingHtml = `
margin-bottom: 10px;
border-radius: 50px;
}
.ban, .block {
.ban {
background-color: #ffcccc;
color: #660000;
}
.kick {
.kick, .suspend {
background-color: #ffddcc;
color: #662200;
}
.mute, .suspend {
.mute {
background-color: #fff1cc;
color: #664b00;
}
@@ -69,6 +69,7 @@ iframe {
<h1>Moderation Logs</h1>
<section>
<p>This page lists all of our community moderation sanctions.</p>
<p>This log was last updated at {{ timestamp }}.</p>
</section>
<section>
<h2>Links</h2>
+4 -35
View File
@@ -4,45 +4,14 @@
* @author Naomi Carrigan
*/
import { PrismaClient } from "@prisma/client";
import { Client, Events, GatewayIntentBits } from "discord.js";
import { log } from "./commands/log.js";
import { revoke } from "./commands/revoke.js";
import { updateCache } from "./modules/updateCache.js";
import { serve } from "./server/serve.js";
import { sendDebugLog } from "./utils/sendDebugLog.js";
import type { App } from "./interfaces/app.js";
const database = new PrismaClient();
const app = {
const app: App = {
cacheUpdated: new Date(),
database: database,
discord: new Client({
intents: [ GatewayIntentBits.Guilds ],
}),
sanctions: await database.sanctions.findMany(),
sanctions: await database.sanctions.findMany(),
};
app.discord.once(Events.ClientReady, () => {
void sendDebugLog({ content: "Bot is online!" });
setInterval(() => {
void updateCache(app);
}, 1000 * 60 * 60 * 24);
});
app.discord.on(Events.InteractionCreate, (interaction) => {
if (interaction.isChatInputCommand()) {
const target = [ log, revoke ].find((command) => {
return command.data.name === interaction.commandName;
});
if (!target) {
void interaction.reply({
content: `Command ${interaction.commandName} not found.`,
ephemeral: true,
});
return;
}
void target.run(app, interaction);
}
});
await app.discord.login(process.env.DISCORD_TOKEN);
serve(app);
await serve(app);
-2
View File
@@ -4,10 +4,8 @@
* @author Naomi Carrigan
*/
import type { PrismaClient, Sanctions } from "@prisma/client";
import type { Client } from "discord.js";
export interface App {
discord: Client;
database: PrismaClient;
sanctions: Array<Sanctions>;
cacheUpdated: Date;
-15
View File
@@ -1,15 +0,0 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import type { App } from "./app.js";
import type {
ChatInputCommandInteraction,
SlashCommandOptionsOnlyBuilder,
} from "discord.js";
export interface Command {
data: SlashCommandOptionsOnlyBuilder;
run: (app: App, interaction: ChatInputCommandInteraction)=> Promise<void>;
}
+25 -4
View File
@@ -16,27 +16,48 @@ export const generateHtml = (app: App): string => {
const sanctions = app.sanctions.toSorted((a, b) => {
return b.number - a.number;
});
const sanctionHtml = sanctions.map((sanction) => {
return sanction.revoked
&& sanction.revokedBy !== null
&& sanction.revokeDate !== null
&& sanction.revokeReason !== null
? `<div class="sanction revoked">
<details>
<summary>${actionIcons.revoked ?? ""} #${sanction.number.toString()}: ${sanction.action} - REVOKED ${platformIcons[sanction.platform.toLowerCase()] ?? "<i class=\"fa-solid fa-question\"></i>"}</summary>
<summary>${
actionIcons.revoked ?? ""
} #${sanction.number.toString()}: ${sanction.action} - REVOKED ${
platformIcons[sanction.platform.toLowerCase()]
?? "<i class=\"fa-solid fa-question\"></i>"
}</summary>
<p class="user">${sanction.uuid}</p>
<p>${sanction.reason}</p>
<p>Performed by: ${sanction.moderator} on ${sanction.date.toLocaleString("en-GB")}</p>
<p class="user">Revoked:</p>
<p>${sanction.revokeReason ?? "Undocumented."}</p>
<p>${sanction.revokeReason}</p>
<p>Revoked by: ${
sanction.revokedBy
} on ${sanction.revokeDate.toLocaleString("en-GB")}</p>
</details>
</div>
`
: `<div class="sanction ${sanction.action.toLowerCase()}">
<details>
<summary>${actionIcons[sanction.action.toLowerCase()] ?? ""} #${sanction.number.toString()}: ${sanction.action} ${platformIcons[sanction.platform.toLowerCase()] ?? "<i class=\"fa-solid fa-question\"></i>"}</summary>
<summary>${
actionIcons[sanction.action.toLowerCase()] ?? ""
} #${sanction.number.toString()}: ${sanction.action} ${
platformIcons[sanction.platform.toLowerCase()]
?? "<i class=\"fa-solid fa-question\"></i>"
}</summary>
<p class="user">${sanction.uuid}</p>
<p>${sanction.reason}</p>
<p>Performed by: ${sanction.moderator} on ${sanction.date.toLocaleString("en-GB")}</p>
</details>
</div>
`;
});
const html = landingHtml.replace("{{ logs }}", sanctionHtml.join("\n"));
const html = landingHtml.
replace("{{ logs }}", sanctionHtml.join("\n")).
replace("{{ timestamp }}", app.cacheUpdated.toLocaleString("en-GB"));
return html;
};
+3 -8
View File
@@ -3,7 +3,6 @@
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import { errorHandler } from "../utils/errorHandler.js";
import type { App } from "../interfaces/app.js";
/**
@@ -11,11 +10,7 @@ import type { App } from "../interfaces/app.js";
* @param app - The application instance.
*/
export const updateCache = async(app: App): Promise<void> => {
try {
app.cacheUpdated = new Date();
// eslint-disable-next-line require-atomic-updates -- We're allowing this so we can update the cache on an interval.
app.sanctions = await app.database.sanctions.findMany();
} catch (error) {
await errorHandler("update cache module", error);
}
app.cacheUpdated = new Date();
// eslint-disable-next-line require-atomic-updates -- We're allowing this so we can update the cache on an interval.
app.sanctions = await app.database.sanctions.findMany();
};
+134 -6
View File
@@ -3,28 +3,156 @@
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import formParser from "@fastify/formbody";
import fastify from "fastify";
import { formHtml, revokeHtml } from "../config/form.js";
import { generateHtml } from "../modules/generateHtml.js";
import { sendDebugLog } from "../utils/sendDebugLog.js";
import { updateCache } from "../modules/updateCache.js";
import type { App } from "../interfaces/app.js";
/**
* Instantiates the fastify server.
* @param app - The application instance.
*/
export const serve = (app: App): void => {
// eslint-disable-next-line max-lines-per-function -- May refactor?
export const serve = async(app: App): Promise<void> => {
const server = fastify({
logger: false,
});
server.register(formParser);
server.get("/", (_request, response) => {
response.header("Content-Type", "text/html");
response.send(generateHtml(app));
});
server.listen({ port: 12_443 }, () => {
void sendDebugLog({
content: "Server listening on port 12443.",
});
server.get("/log", (_request, response) => {
response.header("Content-Type", "text/html");
response.send(formHtml);
});
server.get("/revoke", (_request, response) => {
response.header("Content-Type", "text/html");
response.send(revokeHtml);
});
server.post<{
// eslint-disable-next-line @typescript-eslint/naming-convention -- Required convention for Fastify.
Body: {
uuid: string;
platform: string;
action: string;
reason: string;
token: string;
};
}>("/log", async(request, response) => {
try {
const { body } = request;
const token = await app.database.tokens.findUnique({
where: {
token: body.token,
},
});
if (!token) {
response.status(401);
response.send("Invalid token.");
return;
}
const number = await app.database.sanctions.count();
await app.database.sanctions.create({
data: {
action: body.action,
moderator: token.username,
number: number + 1,
platform: body.platform,
reason: body.reason,
uuid: body.uuid,
},
});
response.status(200);
response.send(
`Logged #${String(number + 1)} ${body.action} against ${body.uuid} on ${
body.platform
}.`,
);
await updateCache(app).catch(() => {
return null;
});
} catch (error) {
response.status(500);
response.header("Content-Type", "application/json");
response.send(JSON.stringify(error));
}
});
server.post<{
// eslint-disable-next-line @typescript-eslint/naming-convention -- Required convention for Fastify.
Body: {
case: string;
reason: string;
token: string;
};
}>("/revoke", async(request, response) => {
try {
const { body } = request;
const token = await app.database.tokens.findUnique({
where: {
token: body.token,
},
});
if (!token) {
response.status(401);
response.send("Invalid token.");
return;
}
const number = Number.parseInt(body.case, 10);
const sanction = await app.database.sanctions.findUnique({
where: {
number,
},
});
if (!sanction) {
response.status(404);
response.send(`Sanction #${String(number)} not found.`);
return;
}
await app.database.sanctions.update({
data: {
revokeDate: new Date(),
revokeReason: body.reason,
revoked: true,
revokedBy: token.username,
},
where: {
number,
},
});
response.status(200);
response.send(
`Revoked #${String(number)} ${sanction.action} against ${
sanction.uuid
} on ${sanction.platform}.`,
);
await updateCache(app).catch(() => {
return null;
});
} catch (error) {
response.status(500);
response.header("Content-Type", "application/json");
response.send(JSON.stringify(error, null, 2));
}
});
await server.listen({ port: 12_443 });
};
-35
View File
@@ -1,35 +0,0 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import { EmbedBuilder, SnowflakeUtil } from "discord.js";
import { sendDebugLog } from "./sendDebugLog.js";
/**
* Parses an error event (re: from a catch block). If it
* is a proper Error object, extrapolates data. Sends information
* to the debug webhook, and assigns the error a Snowflake ID.
* @param context -- A brief description of the code module that threw the error.
* @param error -- The error payload, typed as unknown to comply with TypeScript's typedef.
* @returns The Snowflake ID assigned to the error.
*/
export const errorHandler = async(
context: string,
error: unknown,
): Promise<string> => {
const id = SnowflakeUtil.generate();
const embed = new EmbedBuilder();
embed.setFooter({ text: `Error ID: ${id.toString()}` });
embed.setTitle(`Error: ${context}`);
if (error instanceof Error) {
embed.setDescription(error.message);
embed.addFields([
{ name: "Stack", value: `\`\`\`\n${String(error.stack).slice(0, 1000)}` },
]);
} else {
embed.setDescription(String(error).slice(0, 2000));
}
await sendDebugLog({ embeds: [ embed ] });
return id.toString();
};
-26
View File
@@ -1,26 +0,0 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import { WebhookClient, type MessageCreateOptions } from "discord.js";
const hook = new WebhookClient({
url: process.env.DISCORD_DEBUG_WEBHOOK ?? "",
});
/**
* Quick wrapper to send a debug message to the webhook.
* Modularised for future expansion if needed.
* @param message -- The message payload, compatible with Discord's API.
*/
export const sendDebugLog = async(
message: MessageCreateOptions,
): Promise<void> => {
await hook.send({
...message,
avatarURL: "https://cdn.nhcarrigan.com/art/logs.png",
username: "Moderation Logs",
});
};