feat: initial app prototype

This commit is contained in:
Naomi Carrigan 2025-01-20 18:36:05 -08:00
parent 3abc3e3272
commit d7cd3ffaab
Signed by: naomi
SSH Key Fingerprint: SHA256:rca1iUI2OhAM6n4FIUaFcZcicmri0jgocqKiTTAfrt8
21 changed files with 5187 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
/node_modules/
/prod/

6
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,6 @@
{
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
"eslint.validate": ["typescript"]
}

8
commandJson.ts Normal file
View File

@ -0,0 +1,8 @@
import { log } from "./src/commands/log.js";
import { revoke } from "./src/commands/revoke.js";
const commands = [log.data, revoke.data];
const json = commands.map(c => c.toJSON());
console.log(JSON.stringify(json, null, 2));

5
eslint.config.js Normal file
View File

@ -0,0 +1,5 @@
import NaomisConfig from "@nhcarrigan/eslint-config";
export default [
...NaomisConfig,
];

32
package.json Normal file
View File

@ -0,0 +1,32 @@
{
"name": "social-media-bridge",
"version": "0.0.0",
"description": "",
"main": "prod/index.js",
"type": "module",
"engines": {
"node": "22",
"pnpm": "10"
},
"scripts": {
"build": "tsc",
"lint": "eslint src test --max-warnings 0",
"start": "op run --env-file='./prod.env' -- node prod/index.js"
},
"keywords": [],
"author": "",
"license": "See license in LICENSE.md",
"devDependencies": {
"@nhcarrigan/eslint-config": "5.1.0",
"@nhcarrigan/typescript-config": "4.0.0",
"@types/node": "22.10.7",
"eslint": "9.18.0",
"prisma": "6.2.1",
"typescript": "5.7.3"
},
"dependencies": {
"@prisma/client": "6.2.1",
"discord.js": "14.17.3",
"fastify": "5.2.1"
}
}

4525
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

21
prisma/schema.prisma Normal file
View File

@ -0,0 +1,21 @@
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mongodb"
url = env("MONGO_URI")
}
model Sanctions {
id String @id @default(auto()) @map("_id") @db.ObjectId
date DateTime @default(now())
number Int @unique
uuid String
platform String
action String
reason String
revoked Boolean @default(false)
revokeReason String?
revokeDate DateTime?
}

3
prod.env Normal file
View File

@ -0,0 +1,3 @@
DISCORD_DEBUG_WEBHOOK="op://Environment Variables - Naomi/Mod Logs/webhook"
MONGO_URI="op://Environment Variables - Naomi/Mod Logs/mongo_uri"
DISCORD_TOKEN="op://Environment Variables - Naomi/Mod Logs/discord_token"

114
src/commands/log.ts Normal file
View File

@ -0,0 +1,114 @@
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
src/commands/revoke.ts Normal file
View File

@ -0,0 +1,84 @@
/**
* @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.",
});
}
},
};

39
src/config/icons.ts Normal file
View File

@ -0,0 +1,39 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
/**
* 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>",
};
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>",
suspend: "<i class=\"fa-solid fa-broom\"></i>",
warn: "<i class=\"fa-solid fa-exclamation-triangle\"></i>",
};
export { platformIcons, actionIcons };

107
src/config/landing.ts Normal file
View File

@ -0,0 +1,107 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
/**
* The HTML content to display on the server. Replace `{{ logs }}` with
* the generated moderation log HTML.
*/
export const landingHtml = `
<!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>
<style>
.sanction {
width: 95%;
margin: auto;
margin-bottom: 10px;
border-radius: 50px;
}
.ban, .block {
background-color: #ffcccc;
color: #660000;
}
.kick {
background-color: #ffddcc;
color: #662200;
}
.mute, .suspend {
background-color: #fff1cc;
color: #664b00;
}
.warn {
background-color: #ccccff;
color: #000066;
}
.revoked {
background-color: #ccffdd;
color: #006622;
}
.user {
font-size: 1.25rem;
}
summary {
font-size: 1.5rem;
}
iframe {
background-color: var(--foreground);
width: 95%;
max-width: 1080px;
margin: auto
}
</style>
<body>
<main>
<h1>Moderation Logs</h1>
<section>
<p>This page lists all of our community moderation sanctions.</p>
</section>
<section>
<h2>Links</h2>
<p>
<a href="https://codeberg.org/nhcarrigan/moderation-logs">
<i class="fa-solid fa-code"></i> Source Code
</a>
</p>
<p>
<a href="https://docs.nhcarrigan.com">
<i class="fa-solid fa-book"></i> Documentation
</a>
</p>
<p>
<a href="https://chat.nhcarrigan.com">
<i class="fa-solid fa-circle-info"></i> Support
</a>
</p>
</section>
<section>
<h2>Logs</h2>
{{ logs }}
</section>
<h2>Appeal A Sanction</h2>
<p>See one of your accounts here? Fill out the form below to appeal the sanction!</p>
</main>
</body>
<script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/embed/v2.js"></script>
<script>
hbspt.forms.create({
portalId: "47086586",
formId: "2db4284c-86a1-47d2-a019-c460ef809402"
});
</script>
</html>
`;

48
src/index.ts Normal file
View File

@ -0,0 +1,48 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @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";
const database = new PrismaClient();
const app = {
cacheUpdated: new Date(),
database: database,
discord: new Client({
intents: [ GatewayIntentBits.Guilds ],
}),
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);

14
src/interfaces/app.ts Normal file
View File

@ -0,0 +1,14 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @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
src/interfaces/command.ts Normal file
View File

@ -0,0 +1,15 @@
/**
* @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>;
}

View File

@ -0,0 +1,42 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import { actionIcons, platformIcons } from "../config/icons.js";
import { landingHtml } from "../config/landing.js";
import type { App } from "../interfaces/app.js";
/**
* Generates the HTML for the landing page.
* @param app - The application instance.
* @returns An HTML string.
*/
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
? `<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>
<p class="user">${sanction.uuid}</p>
<p>${sanction.reason}</p>
<p class="user">Revoked:</p>
<p>${sanction.revokeReason ?? "Undocumented."}</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>
<p class="user">${sanction.uuid}</p>
<p>${sanction.reason}</p>
</details>
</div>
`;
});
const html = landingHtml.replace("{{ logs }}", sanctionHtml.join("\n"));
return html;
};

View File

@ -0,0 +1,21 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import { errorHandler } from "../utils/errorHandler.js";
import type { App } from "../interfaces/app.js";
/**
* Updates the cache of sanctions.
* @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);
}
};

30
src/server/serve.ts Normal file
View File

@ -0,0 +1,30 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import fastify from "fastify";
import { generateHtml } from "../modules/generateHtml.js";
import { sendDebugLog } from "../utils/sendDebugLog.js";
import type { App } from "../interfaces/app.js";
/**
* Instantiates the fastify server.
* @param app - The application instance.
*/
export const serve = (app: App): void => {
const server = fastify({
logger: false,
});
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.",
});
});
};

35
src/utils/errorHandler.ts Normal file
View File

@ -0,0 +1,35 @@
/**
* @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
src/utils/sendDebugLog.ts Normal file
View File

@ -0,0 +1,26 @@
/**
* @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",
});
};

10
tsconfig.json Normal file
View File

@ -0,0 +1,10 @@
{
"extends": "@nhcarrigan/typescript-config",
"compilerOptions": {
"rootDir": "./src",
"outDir": "./prod",
"exactOptionalPropertyTypes": false,
"lib": ["ES2024"],
},
"exclude": ["commandJson.ts"]
}