blob: 1b9d740099305d048263158daca46f58105c122f [file] [log] [blame]
pineafan63fc5e22022-08-04 22:04:10 +01001import fetch from "node-fetch";
Skyler Grey32179982023-03-07 23:59:06 +00002import { writeFileSync } from "fs";
pineafan63fc5e22022-08-04 22:04:10 +01003import generateFileName from "../utils/temp/generateFileName.js";
4import Tesseract from "node-tesseract-ocr";
5import type Discord from "discord.js";
pineafan3a02ea32022-08-11 21:35:04 +01006import client from "../utils/client.js";
TheCodedProfb5e9d552023-01-29 15:43:26 -05007import { createHash } from "crypto";
Skyler Grey32179982023-03-07 23:59:06 +00008import * as nsfwjs from "nsfwjs";
Skyler Grey0a4846c2023-03-08 00:32:01 +00009import ClamScan from "clamscan";
Skyler Grey62da9bf2023-03-08 00:11:00 +000010import * as tf from "@tensorflow/tfjs-node";
pineafan6de4da52023-03-07 20:43:44 +000011import EmojiEmbed from "../utils/generateEmojiEmbed.js";
12import getEmojiByName from "../utils/getEmojiByName.js";
13import { ActionRowBuilder, ButtonBuilder, ButtonStyle } from "discord.js";
Skyler Greyd1157312023-03-08 10:07:38 +000014import config from "../config/main.js";
Skyler Greyea0937b2023-03-09 00:36:38 +000015import gm from "gm";
pineafan813bdf42022-07-24 10:39:10 +010016
Skyler Grey75ea9172022-08-06 10:22:23 +010017interface NSFWSchema {
18 nsfw: boolean;
TheCodedProf5b53a8c2023-02-03 15:40:26 -050019 errored?: boolean;
Skyler Grey75ea9172022-08-06 10:22:23 +010020}
21interface MalwareSchema {
Skyler Grey0d885222023-03-08 21:46:37 +000022 malware: boolean;
TheCodedProf5b53a8c2023-02-03 15:40:26 -050023 errored?: boolean;
Skyler Grey75ea9172022-08-06 10:22:23 +010024}
pineafan813bdf42022-07-24 10:39:10 +010025
Skyler Grey7a966df2023-03-09 12:53:57 +000026const nsfw_model = await nsfwjs.load("file://dist/reflex/nsfwjs/example/nsfw_demo/public/model/", { size: 299 });
Skyler Greyd1157312023-03-08 10:07:38 +000027const clamscanner = await new ClamScan().init({
28 clamdscan: {
Skyler Grey21f52292023-03-10 17:58:30 +000029 socket: "socket" in config.clamav ? (config.clamav.socket as string) : false,
30 host: "host" in config.clamav ? (config.clamav.host as string) : false,
31 port: "port" in config.clamav ? (config.clamav.port as number) : false
Skyler Greyd1157312023-03-08 10:07:38 +000032 }
33});
TheCodedProfd8ef1f32023-03-06 19:15:18 -050034
Skyler Grey74169642023-03-09 11:59:09 +000035export async function testNSFW(url: string): Promise<NSFWSchema> {
36 const [fileStream, hash] = await streamAttachment(url);
Skyler Greyda16adf2023-03-05 10:22:12 +000037 const alreadyHaveCheck = await client.database.scanCache.read(hash);
Skyler Greyea0937b2023-03-09 00:36:38 +000038 if (alreadyHaveCheck && "nsfw" in alreadyHaveCheck!) {
39 return { nsfw: alreadyHaveCheck.nsfw };
40 }
TheCodedProfd8ef1f32023-03-06 19:15:18 -050041
Skyler Greyea0937b2023-03-09 00:36:38 +000042 const converted = (await new Promise((resolve, reject) =>
43 gm(fileStream)
44 .command("convert")
45 .toBuffer("PNG", (err, buf) => {
46 if (err) return reject(err);
47 resolve(buf);
48 })
49 )) as Buffer;
TheCodedProfd8ef1f32023-03-06 19:15:18 -050050
Skyler Grey74169642023-03-09 11:59:09 +000051 const img = tf.node.decodeImage(converted, 3, undefined, false) as tf.Tensor3D;
Skyler Grey0d885222023-03-08 21:46:37 +000052
53 const predictions = (await nsfw_model.classify(img, 1))[0]!;
Skyler Grey74169642023-03-09 11:59:09 +000054 img.dispose();
Skyler Grey0d885222023-03-08 21:46:37 +000055 console.log(2, predictions);
TheCodedProfd8ef1f32023-03-06 19:15:18 -050056
Skyler Greyd1157312023-03-08 10:07:38 +000057 const nsfw = predictions.className === "Hentai" || predictions.className === "Porn";
58 await client.database.scanCache.write(hash, "nsfw", nsfw);
59
60 return { nsfw };
pineafan813bdf42022-07-24 10:39:10 +010061}
62
pineafan02ba0232022-07-24 22:16:15 +010063export async function testMalware(link: string): Promise<MalwareSchema> {
Skyler Grey0a4846c2023-03-08 00:32:01 +000064 const [fileName, hash] = await saveAttachment(link);
Skyler Greyda16adf2023-03-05 10:22:12 +000065 const alreadyHaveCheck = await client.database.scanCache.read(hash);
Skyler Grey0d885222023-03-08 21:46:37 +000066 if (alreadyHaveCheck?.malware !== undefined) return { malware: alreadyHaveCheck.malware };
Skyler Greyd1157312023-03-08 10:07:38 +000067 let malware;
Skyler Grey0a4846c2023-03-08 00:32:01 +000068 try {
Skyler Greyd1157312023-03-08 10:07:38 +000069 malware = (await clamscanner.scanFile(fileName)).isInfected;
Skyler Grey0a4846c2023-03-08 00:32:01 +000070 } catch (e) {
Skyler Grey0d885222023-03-08 21:46:37 +000071 return { malware: true };
Skyler Grey0a4846c2023-03-08 00:32:01 +000072 }
Skyler Greyf4f21c42023-03-08 14:36:29 +000073 await client.database.scanCache.write(hash, "malware", malware);
Skyler Grey0d885222023-03-08 21:46:37 +000074 return { malware };
pineafan3a02ea32022-08-11 21:35:04 +010075}
76
77export async function testLink(link: string): Promise<{ safe: boolean; tags: string[] }> {
Skyler Greyda16adf2023-03-05 10:22:12 +000078 const alreadyHaveCheck = await client.database.scanCache.read(link);
Skyler Grey0d885222023-03-08 21:46:37 +000079 if (alreadyHaveCheck?.bad_link !== undefined)
80 return { safe: alreadyHaveCheck.bad_link, tags: alreadyHaveCheck.tags ?? [] };
81 return { safe: true, tags: [] };
82 // const scanned: { safe?: boolean; tags?: string[] } = {}
83 // await client.database.scanCache.write(link, "bad_link", scanned.safe ?? true, scanned.tags ?? []);
84 // return {
85 // safe: scanned.safe ?? true,
86 // tags: scanned.tags ?? []
87 // };
pineafan813bdf42022-07-24 10:39:10 +010088}
89
Skyler Grey0d885222023-03-08 21:46:37 +000090export async function streamAttachment(link: string): Promise<[Buffer, string]> {
Skyler Greyda16adf2023-03-05 10:22:12 +000091 const image = await (await fetch(link)).arrayBuffer();
Skyler Grey32179982023-03-07 23:59:06 +000092 const enc = new TextDecoder("utf-8");
Skyler Grey0d885222023-03-08 21:46:37 +000093 const buf = Buffer.from(image);
94 return [buf, createHash("sha512").update(enc.decode(image), "base64").digest("base64")];
Skyler Grey32179982023-03-07 23:59:06 +000095}
96
97export async function saveAttachment(link: string): Promise<[string, string]> {
98 const image = await (await fetch(link)).arrayBuffer();
Skyler Greyf4f21c42023-03-08 14:36:29 +000099 const fileName = await generateFileName(link.split("/").pop()!.split(".").pop()!);
TheCodedProf5b53a8c2023-02-03 15:40:26 -0500100 const enc = new TextDecoder("utf-8");
Skyler Grey0d885222023-03-08 21:46:37 +0000101 writeFileSync(fileName, new DataView(image));
Skyler Grey32179982023-03-07 23:59:06 +0000102 return [fileName, createHash("sha512").update(enc.decode(image), "base64").digest("base64")];
pineafan813bdf42022-07-24 10:39:10 +0100103}
104
pineafan813bdf42022-07-24 10:39:10 +0100105const linkTypes = {
Skyler Grey75ea9172022-08-06 10:22:23 +0100106 PHISHING: "Links designed to trick users into clicking on them.",
107 DATING: "Dating sites.",
108 TRACKERS: "Websites that store or track personal information.",
109 ADVERTISEMENTS: "Websites only for ads.",
Skyler Grey11236ba2022-08-08 21:13:33 +0100110 FACEBOOK: "Facebook pages. (Facebook has a number of dangerous trackers. Read more on /privacy)",
Skyler Grey75ea9172022-08-06 10:22:23 +0100111 AMP: "AMP pages. (AMP is a technology that allows websites to be served by Google. Read more on /privacy)",
pineafan813bdf42022-07-24 10:39:10 +0100112 "FACEBOOK TRACKERS": "Websites that include trackers from Facebook.",
Skyler Grey11236ba2022-08-08 21:13:33 +0100113 "IP GRABBERS": "Websites that store your IP address, which shows your approximate location.",
Skyler Grey75ea9172022-08-06 10:22:23 +0100114 PORN: "Websites that include pornography.",
115 GAMBLING: "Gambling sites, often scams.",
Skyler Grey11236ba2022-08-08 21:13:33 +0100116 MALWARE: "Websites which download files designed to break or slow down your device.",
Skyler Grey75ea9172022-08-06 10:22:23 +0100117 PIRACY: "Sites which include illegally downloaded material.",
Skyler Grey11236ba2022-08-08 21:13:33 +0100118 RANSOMWARE: "Websites which download a program that can steal your data and make you pay to get it back.",
Skyler Grey75ea9172022-08-06 10:22:23 +0100119 REDIRECTS: "Sites like bit.ly which could redirect to a malicious site.",
120 SCAMS: "Sites which are designed to trick you into doing something.",
121 TORRENT: "Websites that download torrent files.",
122 HATE: "Websites that spread hate towards groups or individuals.",
123 JUNK: "Websites that are designed to make you waste time."
pineafan63fc5e22022-08-04 22:04:10 +0100124};
pineafan813bdf42022-07-24 10:39:10 +0100125export { linkTypes };
126
pineafan63fc5e22022-08-04 22:04:10 +0100127export async function LinkCheck(message: Discord.Message): Promise<string[]> {
Skyler Grey75ea9172022-08-06 10:22:23 +0100128 const links =
129 message.content.match(
130 /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)/gi
131 ) ?? [];
132 const detections: { tags: string[]; safe: boolean }[] = [];
133 const promises: Promise<void>[] = links.map(async (element) => {
pineafan63fc5e22022-08-04 22:04:10 +0100134 let returned;
pineafan813bdf42022-07-24 10:39:10 +0100135 try {
Skyler Grey11236ba2022-08-08 21:13:33 +0100136 if (element.match(/https?:\/\/[a-zA-Z]+\.?discord(app)?\.(com|net)\/?/)) return; // Also matches discord.net, not enough of a bug
pineafan63fc5e22022-08-04 22:04:10 +0100137 returned = await testLink(element);
138 } catch {
Skyler Grey75ea9172022-08-06 10:22:23 +0100139 detections.push({ tags: [], safe: true });
pineafan63fc5e22022-08-04 22:04:10 +0100140 return;
141 }
Skyler Grey75ea9172022-08-06 10:22:23 +0100142 detections.push({ tags: returned.tags, safe: returned.safe });
pineafan813bdf42022-07-24 10:39:10 +0100143 });
144 await Promise.all(promises);
Skyler Grey75ea9172022-08-06 10:22:23 +0100145 const detectionsTypes = detections
146 .map((element) => {
Skyler Grey11236ba2022-08-08 21:13:33 +0100147 const type = Object.keys(linkTypes).find((type) => element.tags.includes(type));
Skyler Grey75ea9172022-08-06 10:22:23 +0100148 if (type) return type;
149 // if (!element.safe) return "UNSAFE"
150 return undefined;
151 })
152 .filter((element) => element !== undefined);
pineafan63fc5e22022-08-04 22:04:10 +0100153 return detectionsTypes as string[];
pineafan813bdf42022-07-24 10:39:10 +0100154}
155
Skyler Grey74169642023-03-09 11:59:09 +0000156export async function NSFWCheck(url: string): Promise<boolean> {
pineafan813bdf42022-07-24 10:39:10 +0100157 try {
Skyler Grey74169642023-03-09 11:59:09 +0000158 return (await testNSFW(url)).nsfw;
Skyler Grey0d885222023-03-08 21:46:37 +0000159 } catch (e) {
Skyler Greyea0937b2023-03-09 00:36:38 +0000160 console.log(e);
pineafan63fc5e22022-08-04 22:04:10 +0100161 return false;
pineafan813bdf42022-07-24 10:39:10 +0100162 }
163}
164
Skyler Grey11236ba2022-08-08 21:13:33 +0100165export async function SizeCheck(element: { height: number | null; width: number | null }): Promise<boolean> {
pineafan63fc5e22022-08-04 22:04:10 +0100166 if (element.height === null || element.width === null) return true;
167 if (element.height < 20 || element.width < 20) return false;
168 return true;
pineafan813bdf42022-07-24 10:39:10 +0100169}
170
pineafan63fc5e22022-08-04 22:04:10 +0100171export async function MalwareCheck(element: string): Promise<boolean> {
pineafan813bdf42022-07-24 10:39:10 +0100172 try {
Skyler Grey0d885222023-03-08 21:46:37 +0000173 return (await testMalware(element)).malware;
pineafan813bdf42022-07-24 10:39:10 +0100174 } catch {
pineafan63fc5e22022-08-04 22:04:10 +0100175 return true;
pineafan813bdf42022-07-24 10:39:10 +0100176 }
177}
178
pineafan1e462ab2023-03-07 21:34:06 +0000179export function TestString(
180 string: string,
181 soft: string[],
182 strict: string[],
183 enabled?: boolean
184): { word: string; type: string } | null {
pineafan6de4da52023-03-07 20:43:44 +0000185 if (!enabled) return null;
Skyler Grey75ea9172022-08-06 10:22:23 +0100186 for (const word of strict) {
pineafan813bdf42022-07-24 10:39:10 +0100187 if (string.toLowerCase().includes(word)) {
Skyler Grey75ea9172022-08-06 10:22:23 +0100188 return { word: word, type: "strict" };
pineafan813bdf42022-07-24 10:39:10 +0100189 }
190 }
Skyler Grey75ea9172022-08-06 10:22:23 +0100191 for (const word of soft) {
192 for (const word2 of string.match(/[a-z]+/gi) ?? []) {
pineafane23c4ec2022-07-27 21:56:27 +0100193 if (word2 === word) {
pineafan6de4da52023-03-07 20:43:44 +0000194 return { word: word, type: "soft" };
pineafan813bdf42022-07-24 10:39:10 +0100195 }
196 }
197 }
pineafan63fc5e22022-08-04 22:04:10 +0100198 return null;
pineafan813bdf42022-07-24 10:39:10 +0100199}
200
pineafan63fc5e22022-08-04 22:04:10 +0100201export async function TestImage(url: string): Promise<string | null> {
Skyler Grey75ea9172022-08-06 10:22:23 +0100202 const text = await Tesseract.recognize(url, {
203 lang: "eng",
204 oem: 1,
205 psm: 3
206 });
Skyler Greye9c3ef62023-03-09 14:09:00 +0000207 console.log(text);
pineafan813bdf42022-07-24 10:39:10 +0100208 return text;
209}
pineafan6de4da52023-03-07 20:43:44 +0000210
Skyler Grey0d885222023-03-08 21:46:37 +0000211export async function doMemberChecks(member: Discord.GuildMember): Promise<void> {
pineafan6de4da52023-03-07 20:43:44 +0000212 if (member.user.bot) return;
Skyler Grey0d885222023-03-08 21:46:37 +0000213 const guild = member.guild;
pineafan6de4da52023-03-07 20:43:44 +0000214 const guildData = await client.database.guilds.read(guild.id);
215 if (!guildData.logging.staff.channel) return;
pineafan1e462ab2023-03-07 21:34:06 +0000216 const [loose, strict] = [guildData.filters.wordFilter.words.loose, guildData.filters.wordFilter.words.strict];
pineafan6de4da52023-03-07 20:43:44 +0000217 // Does the username contain filtered words
218 const usernameCheck = TestString(member.user.username, loose, strict, guildData.filters.wordFilter.enabled);
219 // Does the nickname contain filtered words
220 const nicknameCheck = TestString(member.nickname ?? "", loose, strict, guildData.filters.wordFilter.enabled);
221 // Does the profile picture contain filtered words
pineafan1e462ab2023-03-07 21:34:06 +0000222 const avatarTextCheck = TestString(
Skyler Greye9c3ef62023-03-09 14:09:00 +0000223 (await TestImage(member.displayAvatarURL({ forceStatic: true }))) ?? "",
pineafan1e462ab2023-03-07 21:34:06 +0000224 loose,
225 strict,
226 guildData.filters.wordFilter.enabled
227 );
pineafan6de4da52023-03-07 20:43:44 +0000228 // Is the profile picture NSFW
Skyler Grey0d885222023-03-08 21:46:37 +0000229 const avatar = member.displayAvatarURL({ extension: "png", size: 1024, forceStatic: true });
Skyler Grey74169642023-03-09 11:59:09 +0000230 const avatarCheck = guildData.filters.images.NSFW && (await NSFWCheck(avatar));
pineafan6de4da52023-03-07 20:43:44 +0000231 // Does the username contain an invite
Skyler Grey14432712023-03-07 23:40:50 +0000232 const inviteCheck = guildData.filters.invite.enabled && /discord\.gg\/[a-zA-Z0-9]+/gi.test(member.user.username);
pineafan6de4da52023-03-07 20:43:44 +0000233 // Does the nickname contain an invite
pineafan1e462ab2023-03-07 21:34:06 +0000234 const nicknameInviteCheck =
Skyler Grey14432712023-03-07 23:40:50 +0000235 guildData.filters.invite.enabled && /discord\.gg\/[a-zA-Z0-9]+/gi.test(member.nickname ?? "");
pineafan1e462ab2023-03-07 21:34:06 +0000236 if (
237 usernameCheck !== null ||
238 nicknameCheck !== null ||
239 avatarCheck ||
240 inviteCheck ||
241 nicknameInviteCheck ||
242 avatarTextCheck !== null
243 ) {
pineafan6de4da52023-03-07 20:43:44 +0000244 const infractions = [];
245 if (usernameCheck !== null) {
246 infractions.push(`Username contains a ${usernameCheck.type}ly filtered word (${usernameCheck.word})`);
pineafan1e462ab2023-03-07 21:34:06 +0000247 }
248 if (nicknameCheck !== null) {
pineafan6de4da52023-03-07 20:43:44 +0000249 infractions.push(`Nickname contains a ${nicknameCheck.type}ly filtered word (${nicknameCheck.word})`);
pineafan1e462ab2023-03-07 21:34:06 +0000250 }
251 if (avatarCheck) {
pineafan6de4da52023-03-07 20:43:44 +0000252 infractions.push("Profile picture is NSFW");
pineafan1e462ab2023-03-07 21:34:06 +0000253 }
254 if (inviteCheck) {
pineafan6de4da52023-03-07 20:43:44 +0000255 infractions.push("Username contains an invite");
pineafan1e462ab2023-03-07 21:34:06 +0000256 }
257 if (nicknameInviteCheck) {
pineafan6de4da52023-03-07 20:43:44 +0000258 infractions.push("Nickname contains an invite");
pineafan1e462ab2023-03-07 21:34:06 +0000259 }
260 if (avatarTextCheck !== null) {
261 infractions.push(
Skyler Greye9c3ef62023-03-09 14:09:00 +0000262 `Profile picture contains a ${avatarTextCheck.type}ly filtered word (${avatarTextCheck.word})`
pineafan1e462ab2023-03-07 21:34:06 +0000263 );
pineafan6de4da52023-03-07 20:43:44 +0000264 }
265 if (infractions.length === 0) return;
266 // This is bad - Warn in the staff notifications channel
267 const filter = getEmojiByName("ICONS.FILTER");
268 const channel = guild.channels.cache.get(guildData.logging.staff.channel) as Discord.TextChannel;
269 const embed = new EmojiEmbed()
270 .setTitle("Member Flagged")
271 .setEmoji("ICONS.FLAGS.RED")
272 .setStatus("Danger")
pineafan1e462ab2023-03-07 21:34:06 +0000273 .setDescription(
274 `**Member:** ${member.user.username} (<@${member.user.id}>)\n\n` +
275 infractions.map((element) => `${filter} ${element}`).join("\n")
276 );
TheCodedProf764e6c22023-03-11 16:07:09 -0500277 const buttons = [
278 new ButtonBuilder()
279 .setCustomId(`mod:warn:${member.user.id}`)
280 .setLabel("Warn")
281 .setStyle(ButtonStyle.Primary),
282 new ButtonBuilder()
283 .setCustomId(`mod:mute:${member.user.id}`)
284 .setLabel("Mute")
285 .setStyle(ButtonStyle.Primary),
TheCodedProf1cfa1ae2023-03-11 16:07:37 -0500286 new ButtonBuilder().setCustomId(`mod:kick:${member.user.id}`).setLabel("Kick").setStyle(ButtonStyle.Danger),
287 new ButtonBuilder().setCustomId(`mod:ban:${member.user.id}`).setLabel("Ban").setStyle(ButtonStyle.Danger)
288 ];
289 if (usernameCheck !== null || nicknameCheck !== null)
290 buttons.concat([
291 new ButtonBuilder()
292 .setCustomId(`mod:nickname:${member.user.id}`)
293 .setLabel("Change Name")
294 .setStyle(ButtonStyle.Primary)
295 ]);
296 if (avatarCheck || avatarTextCheck !== null)
297 buttons.concat([
298 new ButtonBuilder().setURL(member.displayAvatarURL()).setLabel("View Avatar").setStyle(ButtonStyle.Link)
299 ]);
300 const components: ActionRowBuilder<ButtonBuilder>[] = [];
TheCodedProf764e6c22023-03-11 16:07:09 -0500301
302 for (let i = 0; i < buttons.length; i += 5) {
TheCodedProf1cfa1ae2023-03-11 16:07:37 -0500303 components.push(
304 new ActionRowBuilder<ButtonBuilder>().addComponents(
305 buttons.slice(i, Math.min(buttons.length - 1, i + 5))
306 )
307 );
TheCodedProf764e6c22023-03-11 16:07:09 -0500308 }
309
pineafan6de4da52023-03-07 20:43:44 +0000310 await channel.send({
311 embeds: [embed],
TheCodedProf764e6c22023-03-11 16:07:09 -0500312 components: components
pineafan6de4da52023-03-07 20:43:44 +0000313 });
314 }
pineafan1e462ab2023-03-07 21:34:06 +0000315}