Files
src
.gitignore
package.json
tsconfig.json
Code
5 249
src/bot.ts
import {
Client,
EmbedBuilder,
GatewayIntentBits,
type Attachment,
} from "discord.js";
import { createHash } from "node:crypto";
import * as dotenv from "dotenv";
dotenv.config();
const MAX_FILE_BYTES = 8 * 1024 * 1024;
const COOLDOWN_MS = 30_000;
const DOWNLOAD_TIMEOUT_MS = 15_000;
const cooldowns = new Map<string, number>();
const activeExtensions = new Set([
".app",
".bat",
".cmd",
".com",
".dll",
".dmg",
".exe",
".jar",
".js",
".msi",
".ps1",
".scr",
".sh",
".vbs",
".docm",
".xlsm",
]);
function detectFileSignature(data: Buffer): string {
if (data.length >= 2 && data[0] === 0x4d && data[1] === 0x5a) {
return "Windows executable-style header (MZ)";
}
if (data.length >= 4 && data.subarray(0, 4).equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46]))) {
return "Linux executable header (ELF)";
}
if (data.subarray(0, 4).equals(Buffer.from([0x7f, 0x4d, 0x41, 0x43]))) {
return "Mach-O executable header";
}
if (data.subarray(0, 4).toString("ascii") === "%PDF") {
return "PDF document";
}
if (data.length >= 8 && data.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) {
return "PNG image";
}
if (data.length >= 3 && data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff) {
return "JPEG image";
}
if (data.length >= 4 && data[0] === 0x50 && data[1] === 0x4b && data[2] === 0x03 && data[3] === 0x04) {
return "ZIP archive or ZIP-based document";
}
return "Unrecognized by basic signature checks";
}
async function downloadAttachment(attachment: Attachment): Promise<Buffer> {
if (attachment.size > MAX_FILE_BYTES) {
throw new Error("That file is larger than the 8 MiB inspection limit.");
}
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), DOWNLOAD_TIMEOUT_MS);
try {
const response = await fetch(attachment.url, { signal: controller.signal });
if (!response.ok || !response.body) {
throw new Error(`Could not download the attachment (HTTP ${response.status}).`);
}
const reader = response.body.getReader();
const chunks: Buffer[] = [];
let totalBytes = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
totalBytes += value.byteLength;
if (totalBytes > MAX_FILE_BYTES) {
await reader.cancel();
throw new Error("That file is larger than the 8 MiB inspection limit.");
}
chunks.push(Buffer.from(value));
}
return Buffer.concat(chunks, totalBytes);
} finally {
clearTimeout(timeout);
}
}
async function handleScan(interaction: import("discord.js").ChatInputCommandInteraction): Promise<void> {
const now = Date.now();
for (const [userId, expiresAt] of cooldowns) {
if (expiresAt <= now) cooldowns.delete(userId);
}
const availableAt = cooldowns.get(interaction.user.id);
if (availableAt && availableAt > now) {
await interaction.reply({
content: `Please wait ${Math.ceil((availableAt - now) / 1000)} seconds before inspecting another file.`,
ephemeral: true,
});
return;
}
cooldowns.set(interaction.user.id, now + COOLDOWN_MS);
const attachment = interaction.options.getAttachment("file", true);
await interaction.deferReply({ ephemeral: true });
try {
const data = await downloadAttachment(attachment);
const extension = attachment.name.includes(".")
? `.${attachment.name.split(".").pop()!.toLowerCase()}`
: "None detected";
const extensionWarning = activeExtensions.has(extension)
? "Review carefully: this extension can contain executable or active content."
: "No executable-style extension on the basic review list.";
const embed = new EmbedBuilder()
.setColor(activeExtensions.has(extension) ? 0xe5a50a : 0x3498db)
.setTitle("File triage results")
.addFields(
{ name: "File", value: attachment.name.slice(0, 256) },
{ name: "Size", value: `${data.length.toLocaleString()} bytes`, inline: true },
{ name: "Extension review", value: extensionWarning, inline: true },
{ name: "Detected signature", value: detectFileSignature(data) },
{ name: "SHA-256", value: createHash("sha256").update(data).digest("hex") },
)
.setFooter({ text: "Basic triage only; this is not a malware verdict. The file was not executed or changed." });
await interaction.editReply({ embeds: [embed] });
} catch (error) {
const message = error instanceof Error ? error.message : "An unexpected error occurred.";
await interaction.editReply(`File inspection failed: ${message}`);
}
}
const token = process.env.DISCORD_TOKEN;
if (!token) {
throw new Error("DISCORD_TOKEN is missing. Add it to your .env file.");
}
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.once("ready", (readyClient) => {
console.log(`Logged in as ${readyClient.user.tag}`);
});
client.on("interactionCreate", async (interaction) => {
if (!interaction.isChatInputCommand()) return;
if (interaction.commandName !== "pest" || interaction.options.getSubcommand() !== "scan") return;
try {
await handleScan(interaction);
} catch (error) {
console.error("Slash command failed:", error);
const message = "The file inspection command failed unexpectedly.";
if (interaction.deferred || interaction.replied) {
await interaction.editReply(message).catch(console.error);
} else {
await interaction.reply({ content: message, ephemeral: true }).catch(console.error);
}
}
});
client.login(token).catch((error: unknown) => {
console.error("Discord login failed:", error);
process.exitCode = 1;
});