Compare commits

...

No commits in common. "aad026ae5a40b71df8ac5efa111ce70962eefa33" and "2e00e2ed6ab12f4647796a0308e449880c0c2774" have entirely different histories.

17 changed files with 4931 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": {
"@fastify/formbody": "8.0.2",
"@prisma/client": "6.2.1",
"fastify": "5.2.1"
}
}

4362
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

29
prisma/schema.prisma Normal file
View File

@ -0,0 +1,29 @@
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
moderator String
reason String
revoked Boolean @default(false)
revokedBy String?
revokeReason String?
revokeDate DateTime?
}
model Tokens {
id String @id @default(auto()) @map("_id") @db.ObjectId
username String @unique
token String @unique
}

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"

74
src/config/form.ts Normal file
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 };

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

@ -0,0 +1,26 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
/**
* Turn a platform name into a font-awesome icon.
*/
const platformIcons: Record<string, string> = {
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>",
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 };

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

@ -0,0 +1,108 @@
/**
* @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 {
background-color: #ffcccc;
color: #660000;
}
.kick, .suspend {
background-color: #ffddcc;
color: #662200;
}
.mute {
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>
<p>This log was last updated at {{ timestamp }}.</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>
`;

17
src/index.ts Normal file
View File

@ -0,0 +1,17 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import { PrismaClient } from "@prisma/client";
import { serve } from "./server/serve.js";
import type { App } from "./interfaces/app.js";
const database = new PrismaClient();
const app: App = {
cacheUpdated: new Date(),
database: database,
sanctions: await database.sanctions.findMany(),
};
await serve(app);

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

@ -0,0 +1,12 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import type { PrismaClient, Sanctions } from "@prisma/client";
export interface App {
database: PrismaClient;
sanctions: Array<Sanctions>;
cacheUpdated: Date;
}

View File

@ -0,0 +1,63 @@
/**
* @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
&& 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>
<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}</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>
<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")).
replace("{{ timestamp }}", app.cacheUpdated.toLocaleString("en-GB"));
return html;
};

View File

@ -0,0 +1,16 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
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> => {
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();
};

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

@ -0,0 +1,158 @@
/**
* @copyright nhcarrigan
* @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 { updateCache } from "../modules/updateCache.js";
import type { App } from "../interfaces/app.js";
/**
* Instantiates the fastify server.
* @param app - The application instance.
*/
// 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.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 });
};

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"]
}